### Unmatched File Pattern Example Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md Shows how to handle 'Unmatched File Pattern' errors. The first example will error if no .exe files are found in dist/. The second example recovers by only issuing a warning. ```yaml - uses: softprops/action-gh-release@v3 with: files: dist/*.exe fail_on_unmatched_files: true # Error if dist/ contains no .exe files # Recovery: - uses: softprops/action-gh-release@v3 with: files: dist/*.exe fail_on_unmatched_files: false # Warn only ``` -------------------------------- ### Install Dependencies Source: https://github.com/softprops/action-gh-release/blob/master/CONTRIBUTING.md Run this command at the root of the repository to install dependencies and bootstrap your environment with a modern version of npm. ```bash npm i ``` -------------------------------- ### Configuration Precedence Example Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Demonstrates how explicit inputs override environment variables and defaults. The 'repository' input is used here, ignoring the GITHUB_REPOSITORY environment variable. ```yaml - uses: softprops/action-gh-release@v3 with: repository: org/repo # Uses this, not env var or default env: GITHUB_REPOSITORY: other/repo # Ignored ``` -------------------------------- ### Async Iteration with Pagination Example Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/workflows-and-patterns.md This example shows how to use the `paginate.iterator` method from the GitHub API to fetch releases page by page. The `allReleases` method returns an async iterable, allowing the caller to control pagination and break early. ```typescript // In GitHubReleaser allReleases(params) { const updatedParams = { per_page: 100, ...params }; return this.github.paginate.iterator( this.github.rest.repos.listReleases.endpoint.merge(updatedParams) ); } // Usage for await (const page of releaser.allReleases({ owner, repo })) { console.log(`Page with ${page.data.length} releases`); } ``` -------------------------------- ### Cross-Platform Build and Release Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/README.md This example demonstrates releasing assets from a matrix build across different platforms. The action handles concurrent releases to the same tag by consolidating drafts and merging assets. ```yaml on: push: tags: ['v*'] strategy: matrix: platform: [ubuntu, windows, macos] steps: - uses: actions/checkout@v4 - run: build.sh - uses: softprops/action-gh-release@v3 with: files: dist/* ``` -------------------------------- ### Minimal GitHub Release Action Usage Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/entry-point.md This TypeScript code demonstrates the minimal setup required to use the GitHub Release action. It includes parsing configuration from environment variables, initializing the GitHub API client, creating or updating a release, uploading assets, finalizing the release, and setting outputs. Ensure necessary environment variables and dependencies are available. ```typescript import { setFailed, setOutput } from '@actions/core'; import { getOctokit } from '@actions/github'; import { GitHubReleaser, release, upload, finalizeRelease, listReleaseAssets } from './github'; import { parseConfig, paths, unmatchedPatterns, uploadUrl } from './util'; import { env } from 'process'; async function run() { try { const config = parseConfig(env); // Validate if (!config.input_tag_name && !isTag(config.github_ref) && !config.input_draft) { throw new Error(`⚠️ GitHub Releases requires a tag`); } // Initialize const gh = getOctokit(config.github_token); const releaser = new GitHubReleaser(gh); // Create/update release const releaseResult = await release(config, releaser); let rel = releaseResult.release; // Upload assets if (config.input_files?.length > 0) { const files = paths(config.input_files, config.input_working_directory); const uploadedIds = new Set(); for (const file of files) { const uploaded = await upload(config, releaser, uploadUrl(rel.upload_url), file, rel.assets); if (uploaded?.id) uploadedIds.add(uploaded.id); } // Finalize rel = await finalizeRelease(config, releaser, rel, releaseResult.created); // Output assets const assets = (await listReleaseAssets(config, releaser, rel)) .filter(a => uploadedIds.has(a.id)) .map(({ uploader, ...rest }) => rest); setOutput('assets', assets); } setOutput('url', rel.html_url); setOutput('id', rel.id.toString()); setOutput('upload_url', rel.upload_url); } catch (error: any) { setFailed(error.message); } } run(); ``` -------------------------------- ### Immutable Release Upload Example Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md Illustrates the correct pattern for uploading assets to immutable releases, especially when using prerelease workflows. Assets are uploaded while the release is a draft, and then the draft is published. ```yaml # Correct pattern for immutable releases + prerelease - uses: softprops/action-gh-release@v3 with: prerelease: true draft: true # Upload assets while draft files: dist/* # Later: publish the draft (in separate workflow) - uses: softprops/action-gh-release@v3 with: tag_name: v1.0.0 draft: false # Publish ``` -------------------------------- ### Sequential Upload Alternative Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/workflows-and-patterns.md This diagram shows the sequential upload process where each file is uploaded using await before the next one starts, resulting in a slower but deterministic order. ```mermaid graph TD Start_Loop_Files[For each file:] --> await_upload[await upload(file) → Complete before next] await_upload --> Result[Result: Slower but deterministic order] ``` -------------------------------- ### Get Release Body from Configuration Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md Helper function to retrieve the release body content. It prioritizes content from configuration, falling back to an inline value if not found. ```typescript import { releaseBody } from './util'; const body = releaseBody(config); // File → fallback to inline ``` -------------------------------- ### Parse Configuration Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/README.md Parses environment variables to get configuration settings for the GitHub release action. Use this to access repository, tag, and file inputs. ```typescript const config = parseConfig(process.env); console.log(`Repository: ${config.github_repository}`); console.log(`Tag: ${config.input_tag_name}`); console.log(`Files: ${config.input_files?.join(', ')}`); ``` -------------------------------- ### Logging Informational Messages Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md Shows examples of informational messages logged using `console.log()`, such as the progress of creating a release, uploading assets, or retry attempts. These messages provide visibility into the action's execution flow. ```text 👩‍🏭 Creating new GitHub release for tag v1.0.0... ⬆️ Uploading app.exe... ✅ Uploaded app.exe ``` -------------------------------- ### No Tag Error Example Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md Demonstrates how to configure the action to avoid 'No Tag Error' by either providing a tag name, setting draft to true, or triggering the workflow only on tag pushes. ```yaml # BAD — will error unless draft is true on: push steps: - uses: softprops/action-gh-release@v3 # GOOD — only runs on tag push on: push: tags: - 'v*' steps: - uses: softprops/action-gh-release@v3 # GOOD — explicitly set draft steps: - uses: softprops/action-gh-release@v3 with: draft: true ``` -------------------------------- ### Upload Single Release Asset Source: https://github.com/softprops/action-gh-release/blob/master/README.md Upload a single file named `Release.txt` as a release asset. The `files` input accepts a glob expression. This example demonstrates a basic file upload. ```yaml name: Main on: push jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Build run: echo ${{ github.sha }} > Release.txt - name: Test run: cat Release.txt - name: Release uses: softprops/action-gh-release@v3 if: github.ref_type == 'tag' with: files: Release.txt ``` -------------------------------- ### Logging Non-Fatal Warnings Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md Illustrates examples of non-fatal errors that are logged as warnings using `console.warn()`. These include issues like unmatched file patterns or read failures, where the action can continue with degraded functionality. ```text 🤔 Pattern 'missing/*.zip' does not match any files. ⚠️ Failed to read body_path "...CHANGELOG.txt" (ENOENT). Falling back to 'body' input. ``` -------------------------------- ### Get Asset Metadata Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md Helper function to retrieve metadata for a given asset file. This includes the file name, MIME type, and size. ```typescript import { asset } from './github'; const meta = asset('/path/to/file.exe'); // { name: 'file.exe', mime: 'application/x-msdownload', size: 5242880 } ``` -------------------------------- ### Get GitHub Release Asset Metadata Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-github.md Analyzes a file to determine its upload name, MIME type, and size. This is useful for preparing assets before uploading. ```typescript const asset = (path: string): ReleaseAsset ``` ```typescript const metadata = asset('/path/to/app.exe'); // { name: 'app.exe', mime: 'application/x-msdownload', size: 5242880 } ``` -------------------------------- ### Main Entry Point Function Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/entry-point.md The `run()` function is the primary asynchronous entry point for the GitHub Action. It orchestrates the entire release workflow. ```typescript async function run() ``` -------------------------------- ### Get Release by Tag Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-github.md Retrieve a specific release using its tag name. This method is useful for checking if a release already exists or fetching its details. ```typescript const result = await releaser.getReleaseByTag({ owner: 'owner', repo: 'repo', tag: 'v1.0.0' }); console.log(result.data.id); ``` -------------------------------- ### Configuration with File Uploads Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md Configure the action to upload specified files to the release. Supports glob patterns for selecting files. ```yaml - uses: softprops/action-gh-release@v3 with: files: | dist/*.exe build/*.tar.gz ``` -------------------------------- ### Prerelease with Auto-Generated Notes Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Create a prerelease and enable automatic generation of release notes based on previous tags. Ensure the `previous_tag` is correctly set. ```yaml - uses: softprops/action-gh-release@v3 with: prerelease: true generate_release_notes: true previous_tag: v1.0.0 ``` -------------------------------- ### Escape Literal Brackets in Filenames Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md Literal '[' or ']' characters in filenames must be escaped when using glob patterns. This example shows how to match a filename containing literal brackets. ```glob dist/app-\[1.0.0\].exe # Matches literal filename "app-[1.0.0].exe" ``` -------------------------------- ### Generate Release Notes from File Source: https://github.com/softprops/action-gh-release/blob/master/README.md Use this snippet to load release notes from a file generated during your build process. Ensure the file path is correctly specified. ```yaml name: Main on: push jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Generate Changelog run: echo "# Good things have arrived" > ${{ github.workspace }}-CHANGELOG.txt - name: Release uses: softprops/action-gh-release@v3 if: github.ref_type == 'tag' with: body_path: ${{ github.workspace }}-CHANGELOG.txt repository: my_gh_org/my_gh_repo # note you'll typically need to create a personal access token # with permissions to create releases in the other repo. # A non-empty explicit token overrides GITHUB_TOKEN. # Omit the input to use github.token; passing "" treats the token as unset. token: ${{ secrets.CUSTOM_GITHUB_TOKEN }} ``` -------------------------------- ### isTag() Helper Function Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md Checks if a given reference string conforms to the Git tag format by verifying if it starts with 'refs/tags/'. This is used to validate the Git context for tag-related operations. ```typescript const isTag = (ref: string): boolean> ``` -------------------------------- ### Set Release Notes with Body Input Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Use the `body` input to provide plain text or markdown for the release notes. This is a fallback if `body_path` fails. ```yaml - uses: softprops/action-gh-release@v3 with: body: | ## Changes - Fixed critical bug #123 - Added new feature X ``` -------------------------------- ### Draft Prerelease Configuration Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md Configure the action to create a draft prerelease and upload specified files. Useful for testing releases before publishing. ```yaml - uses: softprops/action-gh-release@v3 with: prerelease: true draft: true files: dist/* ``` -------------------------------- ### Set Release Notes with Body Path Input Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Use the `body_path` input to specify a file containing the release notes. This is attempted before the `body` input. ```yaml - uses: softprops/action-gh-release@v3 with: body_path: ${{ github.workspace }}-CHANGELOG.txt ``` -------------------------------- ### Concurrent Asset Upload Workflow Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/workflows-and-patterns.md This diagram illustrates the process of uploading assets concurrently using Promise.all(), detailing the steps from resolving file patterns to handling partial or full failures. ```mermaid graph TD Start_Loop_Files[For each file pattern:] --> Resolve_glob[Resolve glob → File list] Resolve_glob --> Start_Loop_Files2[For each file:] Start_Loop_Files2 --> Create_upload_task[Create upload task (async, unstarted)] Create_upload_task --> Promise_all[Promise.all(tasks) ← All start concurrently] Promise_all --> Task1[Task 1: Upload file1 (may have conflicts)] Promise_all --> Task2[Task 2: Upload file2 (may have conflicts)] Promise_all --> Task3[Task 3: Upload file3 (may have conflicts)] Promise_all --> Ellipsis[... (up to OS file handle limits)] Promise_all --> Wait_for_all_tasks[Wait for all tasks] Wait_for_all_tasks -->|Successful: Collect asset IDs| Collect_asset_ids[Collect asset IDs] Wait_for_all_tasks -->|Partial failure: Some assets uploaded, some failed| Partial_failure[Some assets uploaded, some failed] Wait_for_all_tasks -->|Full failure: All assets failed| Full_failure[All assets failed] Collect_asset_ids --> Continue_even_if_failed[Continue (even if some failed)] Partial_failure --> Continue_even_if_failed Full_failure --> Continue_even_if_failed Continue_even_if_failed --> Finalize_release[→ Finalize release with available assets] Finalize_release --> Output_uploaded_assets[→ Output assets that were uploaded] ``` -------------------------------- ### Module Graph Visualization Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/README.md Illustrates the module dependencies and relationships within the action-gh-release project. Shows the entry point, core modules, and external SDKs. ```text main.ts (Entry point) ├── github.ts (Release operations) │ └── Types: Release, ReleaseAsset, ReleaseResult, Releaser ├── util.ts (Config & utilities) │ └── Types: Config └── @actions/core, @actions/github (GitHub Actions SDK) ``` -------------------------------- ### Limit Releases to Pushes to Tags Source: https://github.com/softprops/action-gh-release/blob/master/README.md Use the `step.if` field to gate releases to pushes on git tags. This example uses `github.ref_type == 'tag'` to ensure the action only runs when a tag is pushed. ```yaml name: Main on: push jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Release uses: softprops/action-gh-release@v3 if: github.ref_type == 'tag' ``` -------------------------------- ### Run Tests Source: https://github.com/softprops/action-gh-release/blob/master/CONTRIBUTING.md Execute all tests in the `__tests__` directory using this command. ```bash npm t ``` -------------------------------- ### Draft Prerelease with Later Publication Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/README.md Create a draft prerelease first, then publish it in a subsequent step. Set `prerelease` and `draft` to true for the initial creation, and omit `draft` in the second step to publish. ```yaml # Step 1: Create draft prerelease with assets - uses: softprops/action-gh-release@v3 with: tag_name: v1.0.0 prerelease: true draft: true files: dist/* # Step 2: Later, publish the draft - uses: softprops/action-gh-release@v3 with: tag_name: v1.0.0 # Omit draft to publish ``` -------------------------------- ### YAML Configuration for Immutable Release Uploads Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md This configuration demonstrates a strategy for handling immutable releases by first creating a draft release with assets, and then publishing it in a subsequent step. This avoids issues with uploading assets after a release has been published. ```yaml - uses: softprops/action-gh-release@v3 with: prerelease: true draft: true # Upload while draft files: dist/* # Publish in separate step/workflow - uses: softprops/action-gh-release@v3 with: tag_name: v1.0.0 draft: false ``` -------------------------------- ### Run Local Verification Set Source: https://github.com/softprops/action-gh-release/blob/master/RELEASE.md Execute this set of npm scripts to ensure code formatting, type checking, build, and tests pass before committing the release. ```bash npm run fmtcheck ``` ```bash npm run typecheck ``` ```bash npm run build ``` ```bash npm test ``` -------------------------------- ### Initialize GitHubReleaser Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-github.md Instantiate the GitHubReleaser class by passing an Octokit GitHub instance. This is the first step before performing any release operations. ```typescript import { getOctokit } from '@actions/github'; import { GitHubReleaser } from './github'; const gh = getOctokit(token); const releaser = new GitHubReleaser(gh); ``` -------------------------------- ### Minimal Configuration for action-gh-release Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md The most basic configuration to use the action for the current repository and tag. ```yaml - uses: softprops/action-gh-release@v3 ``` -------------------------------- ### upload() Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md Upload a single file as a release asset. ```APIDOC ## upload() ### Description Upload a single file as a release asset. ### Method ```typescript upload(config: Config, releaser: Releaser, uploadUrl: string, filePath: string, currentAssets: Asset[]) ``` ### Parameters - **config** (Config) - The action configuration object. - **releaser** (Releaser) - The releaser object. - **uploadUrl** (string) - The URL to upload the asset to. - **filePath** (string) - The path to the file to upload. - **currentAssets** (Asset[]) - An array of existing assets. ### Returns - **Asset** - Asset metadata or throws an error. ### Example ```typescript import { upload } from './github'; const asset = await upload(config, releaser, uploadUrl, filePath, currentAssets); // Returns asset metadata or throws ``` ``` -------------------------------- ### Format Code Source: https://github.com/softprops/action-gh-release/blob/master/CONTRIBUTING.md Apply consistent code styling across the project by running this command. It helps maintain a uniform code style. ```bash npm run fmt ``` -------------------------------- ### Upload Multiple Release Assets Source: https://github.com/softprops/action-gh-release/blob/master/README.md Upload multiple files, `Release.txt` and `LICENSE`, as release assets. The `files` input supports a multi-line string for listing multiple files. ```yaml name: Main on: push jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v6 - name: Build run: echo ${{ github.sha }} > Release.txt - name: Test run: cat Release.txt - name: Release uses: softprops/action-gh-release@v3 if: github.ref_type == 'tag' with: files: | Release.txt LICENSE ``` -------------------------------- ### Platform Support Note Source: https://github.com/softprops/action-gh-release/blob/master/README.md Important note regarding the action's platform compatibility and previous Docker implementation. ```APIDOC ## Platform Support Note **⚠️ Note:** This action was previously implemented as a Docker container, limiting its use to GitHub Actions Linux virtual environments only. With recent releases, we now support cross platform usage. You'll need to remove the `docker://` prefix in these versions ``` -------------------------------- ### release() Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md Create or update a release. This is the main entry point for release operations. ```APIDOC ## release() ### Description Create or update a release. Main entry point for release operations. ### Method ```typescript release(config: Config, releaser: Releaser) ``` ### Parameters - **config** (Config) - The action configuration object. - **releaser** (Releaser) - The releaser object. ### Returns - **ReleaseResult** - An object containing the release information and a boolean indicating if it was newly created. ### Example ```typescript import { release } from './github'; const result = await release(config, releaser); // result.release — Release object // result.created — true if newly created, false if updated ``` ``` -------------------------------- ### GitHub API Client Initialization Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/entry-point.md Initializes the Octokit client with throttle and retry configurations for robust API interaction. A `GitHubReleaser` instance is created using this client. ```typescript const gh = getOctokit(config.github_token, { throttle: { onRateLimit: (retryAfter, options) => { ... }, onAbuseLimit: (retryAfter, options) => { ... }, }, }); const releaser = new GitHubReleaser(gh); ``` -------------------------------- ### Accessing Release Asset Download URL Source: https://github.com/softprops/action-gh-release/blob/master/README.md Demonstrates how to access the download URL of the first asset from the action's output. This is useful for referencing uploaded files in subsequent steps. ```yaml ${{ fromJSON(steps..outputs.assets)[0].browser_download_url }} ``` -------------------------------- ### Debug File Existence Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md Before running the release action, use this command to verify that the files you expect to be released actually exist in the specified directory. This is useful for debugging 'Pattern does not match any files' errors. ```bash # Or debug pattern before release: - run: ls -la dist/ ``` -------------------------------- ### Asset Upload with Conflict Resolution Workflow Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/workflows-and-patterns.md Handles uploading a single file to a release, including comprehensive error handling and conflict resolution for asset names and race conditions. ```mermaid graph TD Start_upload_single_file[ Start (upload single file) ] Start_upload_single_file --> Get_file_metadata[ Get file metadata (name, MIME type, size) ] Get_file_metadata --> Check_for_existing_asset[ Check for existing asset ] Check_for_existing_asset --> Not_found[ Not found: → Upload ] Check_for_existing_asset --> Found_overwrite_true[ Found & overwrite=true: Delete existing → Upload ] Check_for_existing_asset --> Found_overwrite_false[ Found & overwrite=false: Skip with warning → End ] Not_found --> Upload_Phase[ [Upload Phase] ├─ Prepare asset endpoint URL ├─ Stream file to GitHub API ├─ Handle upload response (201 = success, else error) └─ On 201: Continue to label restoration ] Found_overwrite_true --> Upload_Phase Upload_Phase --> Label_Restoration[ [Label Restoration] ├─ Check if GitHub normalized filename ├─ If normalized: Update asset label to original filename ├─ On label update fail: Retry with asset refresh └─ On success: Return asset metadata ] Label_Restoration --> Return_asset_metadata_or_null[ Return asset metadata or null ] Return_asset_metadata_or_null --> End [Error Handling] ├─ Immutable release error: Throw with helpful message ├─ Race condition (422 already_exists): Delete conflicting asset & retry upload ├─ Asset update 404: Refresh and retry label update └─ Other errors: Throw subgraph Error Handling Immutable_release_error[ Immutable release error: Throw with helpful message ] Race_condition_422_already_exists[ Race condition (422 already_exists): Delete conflicting asset & retry upload ] Asset_update_404[ Asset update 404: Refresh and retry label update ] Other_errors[ Other errors: Throw ] end Upload_Phase --> Error_Handling Label_Restoration --> Error_Handling Error_Handling --> Return_asset_metadata_or_null ``` -------------------------------- ### Use GITHUB_REPOSITORY Environment Variable (Deprecated) Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Provides a fallback for the target repository if the 'repository' input is not provided. This method is deprecated; use the 'repository' input instead. ```yaml steps: - uses: softprops/action-gh-release@v3 env: GITHUB_REPOSITORY: owner/repo # Not recommended; use input instead ``` -------------------------------- ### List GitHub Release Assets Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-github.md Lists all assets for a given release with automatic pagination. Useful for retrieving all files associated with a release. ```typescript async listReleaseAssets(params: { owner: string; repo: string; release_id: number; }): Promise> ``` ```typescript const assets = await releaser.listReleaseAssets({ owner: 'owner', repo: 'repo', release_id: 12345 }); assets.forEach(asset => console.log(asset.name)); ``` -------------------------------- ### listReleaseAssets() Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-github.md Lists all assets for a release with automatic pagination (100 items per page). ```APIDOC ## listReleaseAssets() ### Description Lists all assets for a release with automatic pagination (100 items per page). ### Method GET ### Endpoint `/repos/{owner}/{repo}/releases/{release_id}/assets` (Assumed, based on common GitHub API patterns) ### Parameters #### Path Parameters - **owner** (string) - Required - Repository owner - **repo** (string) - Required - Repository name - **release_id** (number) - Required - Release ID ### Response #### Success Response (200) - **Array of asset objects** - Array of asset objects with id, name, label, and additional properties ### Response Example ```typescript const assets = await releaser.listReleaseAssets({ owner: 'owner', repo: 'repo', release_id: 12345 }); assets.forEach(asset => console.log(asset.name)); ``` ``` -------------------------------- ### List Action Outputs for Debugging Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md A debugging command to list all available outputs from the action. This helps in verifying that the action has completed successfully and its outputs are as expected. ```yaml - uses: softprops/action-gh-release@v3 id: release - run: | echo "URL: ${{ steps.release.outputs.url }}" echo "ID: ${{ steps.release.outputs.id }}" echo "Assets: ${{ steps.release.outputs.assets }}" ``` -------------------------------- ### expandHomePattern() Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-util.md Expands the `~` prefix in file paths to the user's home directory. ```APIDOC ## expandHomePattern() ### Description Expands `~` prefix in file paths to the user's home directory. ### Method Not applicable (function signature provided) ### Parameters #### Path Parameters - **pattern** (string) - Required - Path with optional `~` prefix - **homeDirectory** (string) - Optional - Home directory path ### Returns `string` — Path with `~` expanded to home directory ### Behavior - `~` alone → returns homeDirectory - `~/...` → `homeDirectory/...` - `~\...` (Windows) → `homeDirectory\...` - Other paths → returned unchanged ### Example ```typescript expandHomePattern('~/projects/repo'); // '/home/user/projects/repo' expandHomePattern('~\projects\repo'); // 'C:\Users\user\projects\repo' expandHomePattern('/var/lib'); // '/var/lib' ``` ``` -------------------------------- ### Parse Configuration from Environment Variables Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-util.md Parses environment variables into a Config object, mapping GitHub Actions inputs to the Config interface. Use this to initialize the tool's configuration based on the execution environment. ```typescript export const parseConfig = (env: Env): Config ``` ```typescript import { parseConfig } from './util'; import { env } from 'process'; const config = parseConfig(env); console.log(`Repository: ${config.github_repository}`); console.log(`Tag: ${config.input_tag_name}`); ``` -------------------------------- ### upload() Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-github.md Uploads a file as a release asset with automatic retry logic, asset name restoration, and race condition handling. ```APIDOC ## upload() ### Description Uploads a file as a release asset with automatic retry logic, asset name restoration, and race condition handling. ### Method POST (inferred from upload context) ### Endpoint `/repos/:owner/:repo/releases/:release_id/assets?name=:name` (inferred from context) ### Parameters #### Path Parameters - **config** (Config) - Required - Release configuration - **releaser** (Releaser) - Required - Release API wrapper - **url** (string) - Required - Release upload URL (template URL from release object) - **path** (string) - Required - File path to upload - **currentAssets** (Array) - Required - List of existing release assets ### Request Example ```typescript const uploaded = await upload( config, releaser, release.upload_url, '/path/to/app.exe', release.assets ); console.log(`Uploaded: ${uploaded.name}, size: ${uploaded.size}`); ``` ### Response #### Success Response (200) - **asset metadata object** (any) - Uploaded asset metadata object with id, name, label ### Response Example ```json { "id": 12345678, "name": "app.exe", "label": null, "size": 102400, "upload_url": "https://uploads.github.com/..." } ``` **Throws:** Error if upload fails or asset with same name exists and overwrite is disabled **Handles:** - Asset name restoration for GitHub-normalized filenames - Automatic retry with exponential backoff for transient failures - Race condition detection (422 already_exists error) - Immutable release detection with helpful error message - Asset label restoration via updateReleaseAsset ``` -------------------------------- ### Cross-Repository Release Configuration Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md Configure the action to create a release in a different repository. Requires a custom token with appropriate permissions. ```yaml - uses: softprops/action-gh-release@v3 with: repository: other/repo token: ${{ secrets.CUSTOM_TOKEN }} ``` -------------------------------- ### Configure Release Action to Fail on Unmatched Files Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md Use this configuration to make the release action fail if the specified glob pattern does not match any files. This helps catch errors early if your distribution files are not generated as expected. ```yaml # Check pattern: - uses: softprops/action-gh-release@v3 with: files: dist/*.exe fail_on_unmatched_files: true ``` -------------------------------- ### Environment Variables Source: https://github.com/softprops/action-gh-release/blob/master/README.md Information on environment variables that can be used as fallbacks for action inputs. ```APIDOC ## Environment Variables The following `step.env` keys are allowed as a fallback but deprecated in favor of using inputs: ### `GITHUB_TOKEN` - **Description**: GITHUB_TOKEN as provided by `secrets` ### `GITHUB_REPOSITORY` - **Description**: Name of a target repository in `/` format. defaults to the current repository ``` -------------------------------- ### parseConfig() Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md Parse GitHub Actions inputs into a configuration object. ```APIDOC ## parseConfig() ### Description Parse GitHub Actions inputs into configuration object. ### Method ```typescript parseConfig(env: NodeJS.ProcessEnv) ``` ### Parameters - **env** (NodeJS.ProcessEnv) - The environment variables object. ### Returns - **Config** - The parsed configuration object. ### Example ```typescript import { parseConfig } from './util'; const config = parseConfig(process.env); // Parses all INPUT_* env vars and GitHub context ``` ``` -------------------------------- ### Specify Files for Asset Upload (Newline Delimited) Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Use the `files` input with newline-delimited glob patterns to specify assets for upload. Patterns are relative to the workspace. ```yaml - uses: softprops/action-gh-release@v3 with: files: | dist/app-${{ runner.os }}-*.tar.gz build/*.exe checksums/SHA256SUM ``` -------------------------------- ### Create Release as a Draft Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Use `draft: true` to create or keep a release in draft state, preventing it from being published immediately. Omit the `draft` input to publish the release. ```yaml - uses: softprops/action-gh-release@v3 with: draft: true # Publish draft later: - uses: softprops/action-gh-release@v3 with: tag_name: v1.0.0 # Omit draft input to publish ``` -------------------------------- ### Configuration and Validation Stage Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/entry-point.md Parses configuration from environment variables and validates the presence of a tag. Throws an error if a tag is missing and the release is not in draft mode. ```typescript const config = parseConfig(env); if (!config.input_tag_name && !isTag(config.github_ref) && !config.input_draft) { throw new Error(`⚠️ GitHub Releases requires a tag`); } ``` -------------------------------- ### Specify Files for Asset Upload with Glob Brace Patterns Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Use glob brace patterns within the `files` input to specify multiple related asset files for upload. ```yaml - uses: softprops/action-gh-release@v3 with: files: dist/{windows,linux,macos}/app-*.zip ``` -------------------------------- ### Set Upload URL Output Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/entry-point.md Sets the 'upload_url' output for the action, providing the GitHub API URL for uploading additional assets. ```typescript setOutput('upload_url', rel.upload_url); ``` -------------------------------- ### Specify Target Repository Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Use the 'repository' input to target a specific repository for release creation. This is useful for creating releases in a different repository than the one running the workflow. Ensure the token has appropriate permissions for the target repository. ```yaml - uses: softprops/action-gh-release@v3 with: repository: myorg/myrepo token: ${{ secrets.CUSTOM_TOKEN }} ``` -------------------------------- ### Create or Update a Release Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/quick-reference.md Use this function as the main entry point for release operations. It creates or updates a release and returns the release object and a boolean indicating if it was newly created. ```typescript import { release } from './github'; const result = await release(config, releaser); // result.release — Release object // result.created — true if newly created, false if updated ``` -------------------------------- ### List Release Assets with Retries Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-github.md Lists assets for a release. Includes automatic retries for robustness. Use when you need to retrieve all associated files for a specific GitHub release. ```typescript export const listReleaseAssets = async ( config: Config, releaser: Releaser, release: Release, maxRetries: number = 3 ): Promise> ``` ```typescript const assets = await listReleaseAssets(config, releaser, release); assets.forEach(asset => console.log(`${asset.name}: ${asset.id}`)); ``` -------------------------------- ### Use GITHUB_TOKEN Environment Variable (Deprecated) Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Provides a fallback for the GitHub API token if the 'token' input is not provided. This method is deprecated; use the 'token' input instead. ```yaml steps: - uses: softprops/action-gh-release@v3 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Not recommended; use input instead ``` -------------------------------- ### YAML Configuration for Token Permissions Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md This YAML snippet shows how to configure the action with a Personal Access Token (PAT) that has sufficient permissions, particularly when targeting an older commit. It highlights the need for `contents: write` permission and using a PAT instead of the default `github.token`. ```yaml - uses: softprops/action-gh-release@v3 with: target_commitish: abc123 # Creating tag on old commit token: ${{ secrets.PAT_WITH_CONTENTS }} # Use PAT instead of github.token ``` -------------------------------- ### Upload Release Assets Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Use this snippet to upload multiple files as assets to a GitHub release. Specify the files using a glob pattern. ```yaml - uses: softprops/action-gh-release@v3 with: files: | dist/app-linux-*.tar.gz dist/app-windows-*.exe dist/app-macos-*.dmg ``` -------------------------------- ### Create a New GitHub Release Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-github.md Create a new release for a repository. Supports options for generating release notes, setting as draft or prerelease, and specifying commitish. ```typescript const release = await releaser.createRelease({ owner: 'owner', repo: 'repo', tag_name: 'v1.0.0', name: 'Version 1.0.0', body: 'Initial release', draft: false, prerelease: false }); ``` -------------------------------- ### Loosen Glob Pattern for Release Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/errors.md If your initial glob pattern is too specific, use a broader pattern like `dist/**/*` to include all files recursively within the `dist` directory. This can resolve 'Pattern does not match any files' errors. ```yaml # Or loosen pattern: - uses: softprops/action-gh-release@v3 with: files: dist/**/* ``` -------------------------------- ### allReleases() Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-github.md Iterates through all releases in a repository with automatic pagination. ```APIDOC ## allReleases() ### Description Iterates through all releases in a repository with automatic pagination (100 per page). ### Method GET ### Endpoint /repos/{owner}/{repo}/releases ### Parameters #### Path Parameters - **owner** (string) - yes - Repository owner - **repo** (string) - yes - Repository name ### Response #### Success Response (200) - **data** (Release[]) - Async iterator yielding pages of releases #### Response Example ```typescript for await (const page of releaser.allReleases({ owner: 'owner', repo: 'repo' })) { console.log(`Page with ${page.data.length} releases`); page.data.forEach(release => console.log(release.tag_name)); } ``` ``` -------------------------------- ### Batch Asset Upload with Promise.all or Sequential Execution Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/workflows-and-patterns.md Handles uploading multiple files, either concurrently using Promise.all for performance or sequentially if order preservation is required. It filters out undefined results from failed uploads. ```typescript const uploadFile = async (path: string) => { const json = await upload(config, releaser, uploadUrl(rel.upload_url), path, currentAssets); return json ? (json.id as number) : undefined; }; let results: (number | undefined)[]; if (!config.input_preserve_order) { results = await Promise.all(files.map(uploadFile)); } else { results = []; for (const path of files) { results.push(await uploadFile(path)); } } uploadedAssetIds = new Set(results.filter((id): id is number => id !== undefined)); ``` -------------------------------- ### Release Creation or Update Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/entry-point.md Handles the creation of a new release or updating an existing one based on the provided tag. It manages race conditions and deduplicates draft releases. ```typescript const releaseResult = await release(config, releaser); let rel = releaseResult.release; const releaseWasCreated = releaseResult.created; ``` -------------------------------- ### Mark Release as Pre-release Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/configuration.md Set `prerelease: true` to mark the release as a pre-release. If `draft` is not specified, the release is created as a draft first and then published after asset upload. ```yaml - uses: softprops/action-gh-release@v3 with: prerelease: true body: "This is a beta release" ``` -------------------------------- ### Iterate All GitHub Releases Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/api-reference-github.md Iterates through all releases in a repository with automatic pagination. Yields pages of releases, with 100 releases per page. ```typescript allReleases(params: { owner: string; repo: string }): AsyncIterable<{ data: Release[] }> ``` ```typescript for await (const page of releaser.allReleases({ owner: 'owner', repo: 'repo' })) { console.log(`Page with ${page.data.length} releases`); page.data.forEach(release => console.log(release.tag_name)); } ``` -------------------------------- ### Create Annotated Git Tag Source: https://github.com/softprops/action-gh-release/blob/master/RELEASE.md Use this command to create an annotated tag for a release commit. Replace v3.0.0 with the actual version number. ```bash git tag -a v3.0.0 -m "v3.0.0" ``` -------------------------------- ### Generate Release Notes with Previous Tag Comparison Source: https://github.com/softprops/action-gh-release/blob/master/README.md This configuration utilizes GitHub's built-in release notes generation, allowing explicit pinning of the comparison base with `previous_tag`. This is useful for specific release series. ```yaml - name: Release uses: softprops/action-gh-release@v3 with: tag_name: stage-2026-03-15 target_commitish: ${{ github.sha }} previous_tag: prod-2026-03-01 generate_release_notes: true ``` -------------------------------- ### Asset Operation Parameters Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/types.md Standard parameter pattern for asset-specific operations, including owner, repository, and asset ID. ```typescript { owner: string; repo: string; asset_id: number } ``` -------------------------------- ### Push Commit and Tag to Origin Source: https://github.com/softprops/action-gh-release/blob/master/RELEASE.md After creating the release commit and tag, push them to the remote repository. This ensures the changes are available on the server. ```bash git push origin master && git push origin v3.0.0 ``` -------------------------------- ### Set Release URL Output Source: https://github.com/softprops/action-gh-release/blob/master/_autodocs/entry-point.md Sets the 'url' output for the action, providing the GitHub.com HTML URL to the release page. ```typescript setOutput('url', rel.html_url); ```