### Install Dependencies Source: https://github.com/github/vscode-github-actions/blob/main/CONTRIBUTING.md Installs project dependencies. This is a one-time setup step required before running and testing code locally. ```bash npm i ``` -------------------------------- ### Setup Local Development Environment with npm Workspaces Source: https://github.com/github/vscode-github-actions/blob/main/docs/development.md Clones the repository, bootstraps dependencies, and installs/builds packages using npm workspaces for linked package development. Assumes npm version supports workspaces. ```shell mkdir ~/vscode cd ~/vscode gh repo clone github/vscode-github-actions cd vscode-github-actions script/bootstrap cd ~/vscode npm i npm run build -ws ``` -------------------------------- ### Troubleshooting npm Workspaces Error Source: https://github.com/github/vscode-github-actions/blob/main/docs/development.md Resolves the 'This command does not support workspaces' error by upgrading to the latest version of npm. This can be done globally using npm or via package managers like Homebrew. ```shell npm install npm@latest -g # or brew upgrade node ``` -------------------------------- ### Configuration Access and Settings (TypeScript) Source: https://context7.com/github/vscode-github-actions/llms.txt Demonstrates how to access and retrieve configuration settings for the GitHub Actions extension using VS Code's workspace configuration API. It shows examples of getting pinned workflows, auto-refresh settings, the Git remote name, and whether to use GitHub Enterprise mode. These settings control various aspects of the extension's behavior. ```typescript // Access configuration settings import { workspace } from "vscode"; const config = workspace.getConfiguration("github-actions"); // Get pinned workflows const pinnedWorkflows = config.get("workflows.pinned.workflows", []); console.log(`Pinned workflows: ${pinnedWorkflows.join(", ")}`); // Get refresh settings const refreshEnabled = config.get("workflows.pinned.refresh.enabled", false); const refreshInterval = config.get("workflows.pinned.refresh.interval", 30); console.log(`Auto-refresh: ${refreshEnabled} (every ${refreshInterval}s)`); // Get remote name const remoteName = config.get("remote-name", "origin"); console.log(`Git remote name: ${remoteName}`); // Check enterprise mode const useEnterprise = config.get("use-enterprise", false); console.log(`GitHub Enterprise mode: ${useEnterprise}`); ``` -------------------------------- ### Updating Package Locks After Local Changes Source: https://github.com/github/vscode-github-actions/blob/main/docs/development.md Updates individual package-lock.json files within each package directory after making changes, ensuring correct dependency locking when not using workspaces for publishing. This script should be run from the root development directory. ```shell /workspaces/update-package-locks.sh ``` -------------------------------- ### Manage GitHub Workflow Runs with TypeScript Source: https://context7.com/github/vscode-github-actions/llms.txt Provides examples for managing GitHub workflow runs, including fetching run details, canceling active runs, rerunning completed runs, listing runs with filters, and downloading logs. Requires repository context and a valid run ID. ```typescript import { getGitHubContextForRepo } from "./git/repository"; // Manage workflow runs const repoContext = await getGitHubContextForRepo("octocat", "hello-world"); if (repoContext) { const runId = 123456789; // Get workflow run details const runResponse = await repoContext.client.actions.getWorkflowRun({ owner: repoContext.owner, repo: repoContext.name, run_id: runId }); const run = runResponse.data; console.log(`Workflow Run: ${run.name}`); console.log(` ID: ${run.id}`); console.log(` Status: ${run.status}`); console.log(` Conclusion: ${run.conclusion || "N/A"}`); console.log(` Branch: ${run.head_branch}`); console.log(` Commit: ${run.head_sha}`); console.log(` Actor: ${run.actor?.login}`); console.log(` Created: ${run.created_at}`); console.log(` Updated: ${run.updated_at}`); console.log(` URL: ${run.html_url}`); // Cancel a running workflow if (run.status === "in_progress" || run.status === "queued") { try { await repoContext.client.actions.cancelWorkflowRun({ owner: repoContext.owner, repo: repoContext.name, run_id: runId }); console.log("Workflow run cancelled successfully"); } catch (error) { console.error(`Failed to cancel workflow: ${error.message}`); } } // Rerun a workflow if (run.status === "completed") { try { await repoContext.client.actions.reRunWorkflow({ owner: repoContext.owner, repo: repoContext.name, run_id: runId }); console.log("Workflow rerun triggered successfully"); } catch (error) { console.error(`Failed to rerun workflow: ${error.message}`); } } // List workflow runs with filters const recentRuns = await repoContext.client.actions.listWorkflowRunsForRepo({ owner: repoContext.owner, repo: repoContext.name, branch: "main", status: "completed", per_page: 20 }); console.log(`Found ${recentRuns.data.total_count} completed runs on main branch`); // Download workflow run logs const logsResponse = await repoContext.client.actions.downloadWorkflowRunLogs({ owner: repoContext.owner, repo: repoContext.name, run_id: runId }); console.log(`Download logs from: ${logsResponse.url}`); } ``` -------------------------------- ### Package and Run Web Extension Source: https://github.com/github/vscode-github-actions/blob/main/CONTRIBUTING.md Commands for packaging the extension and running its web version. 'npm run package' creates a packaged version of the extension. 'Run Web Extension in VS Code' is a development task to run the web version. ```bash npm run package ``` -------------------------------- ### Run and Watch Tests Source: https://github.com/github/vscode-github-actions/blob/main/CONTRIBUTING.md Executes the project's test suite. 'npm test' runs tests once, while 'npm run test-watch' runs tests and watches for file changes to re-run them. ```bash npm test ``` ```bash npm run test-watch ``` -------------------------------- ### Build Extension Source: https://github.com/github/vscode-github-actions/blob/main/CONTRIBUTING.md Builds the extension. Use 'npm run build' for a one-time build or 'npm run watch' to automatically rebuild on file saves. ```bash npm run build ``` ```bash npm run watch ``` -------------------------------- ### GitHub API Client Factory (TypeScript) Source: https://context7.com/github/vscode-github-actions/llms.txt Provides a factory function 'getClient' to create an authenticated Octokit client for interacting with the GitHub API. It requires an access token obtained from a GitHub session. This client can be used to list repositories, workflows, and other repository-specific data. Depends on './api/api' and './auth/auth'. ```typescript import { getClient } from "./api/api"; import { getSession } from "./auth/auth"; // Create authenticated Octokit client const session = await getSession(); if (session) { const client = getClient(session.accessToken); // Use client for GitHub API calls const repos = await client.repos.listForAuthenticatedUser({ per_page: 10, sort: "updated" }); console.log(`Found ${repos.data.length} repositories`); // List workflows for a repository const workflows = await client.actions.listRepoWorkflows({ owner: "octocat", repo: "hello-world" }); console.log(`Workflows: ${workflows.data.workflows.map(w => w.name).join(", ")}`); } ``` -------------------------------- ### Fetch Workflow Job and Step Logs (TypeScript) Source: https://context7.com/github/vscode-github-actions/llms.txt Fetches and displays job and step logs for a given GitHub Actions workflow run. It retrieves all jobs for a run, logs job details, and downloads logs for completed jobs, displaying them in VS Code. Requires './git/repository' and 'vscode' API. ```typescript import { getGitHubContextForRepo } from "./git/repository"; import * as vscode from "vscode"; // Fetch workflow run jobs const repoContext = await getGitHubContextForRepo("octocat", "hello-world"); if (repoContext) { const runId = 123456789; // Get all jobs for a workflow run const jobsResponse = await repoContext.client.actions.listJobsForWorkflowRun({ owner: repoContext.owner, repo: repoContext.name, run_id: runId }); console.log(`Found ${jobsResponse.data.jobs.length} jobs`); for (const job of jobsResponse.data.jobs) { console.log(`Job: ${job.name}`); console.log(` Status: ${job.status}`); console.log(` Conclusion: ${job.conclusion || "N/A"}`); console.log(` Started: ${job.started_at}`); console.log(` Duration: ${job.completed_at ? (new Date(job.completed_at).getTime() - new Date(job.started_at).getTime()) / 1000 + "s" : "in progress"}`); // List steps console.log(` Steps:`); job.steps?.forEach(step => { console.log(` - ${step.name}: ${step.status} (${step.conclusion || "running"})`); }); // Download job logs if (job.status === "completed") { try { const logsResponse = await repoContext.client.actions.downloadJobLogsForWorkflowRun({ owner: repoContext.owner, repo: repoContext.name, job_id: job.id }); console.log(` Log URL: ${logsResponse.url}`); // Logs are displayed in VS Code using custom URI scheme // Example: workflow-step-log://github/octocat/hello-world/runs/123456789/jobs/987654321 const logUri = vscode.Uri.parse( `workflow-step-log://github/${repoContext.owner}/${repoContext.name}/runs/${runId}/jobs/${job.id}` ); const document = await vscode.workspace.openTextDocument(logUri); await vscode.window.showTextDocument(document); } catch (error) { console.error(`Failed to download logs: ${error.message}`); } } } } ``` -------------------------------- ### Secret Encryption and Management Source: https://context7.com/github/vscode-github-actions/llms.txt This section details the process of encrypting secrets using a repository's public key and managing them via the API. It covers creating, listing, and deleting repository secrets. ```APIDOC ## GitHub Actions Secret Management ### Description Provides functionality to securely manage GitHub Actions secrets for a repository, including encryption, creation, retrieval, and deletion. ### Method - GET (for public key and listing secrets) - POST (for creating secrets) - PUT (for updating secrets) - DELETE (for deleting secrets) ### Endpoint - `GET /repos/{owner}/{repo}/actions/secrets/public-key` (Get public key) - `POST /repos/{owner}/{repo}/actions/secrets` (Create or update secret) - `GET /repos/{owner}/{repo}/actions/secrets` (List secrets) - `DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}` (Delete secret) ### Parameters #### Path Parameters - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. - **secret_name** (string) - Required - The name of the secret. #### Query Parameters None for specific operations, but listing might support pagination. #### Request Body ##### For Creating/Updating Secrets: - **encrypted_value** (string) - Required - The Base64 encoded and encrypted value of the secret. - **key_id** (string) - Required - The ID of the public key used for encryption. ### Request Example ```typescript // Get repository public key const publicKeyResponse = await repoContext.client.actions.getRepoPublicKey({...}); const publicKey = publicKeyResponse.data.key; const keyId = publicKeyResponse.data.key_id; // Encrypt secret value const encryptedValue = await encodeSecret(publicKey, "super-secret-value-123"); // Create or update secret await repoContext.client.actions.createOrUpdateRepoSecret({ owner: repoContext.owner, repo: repoContext.name, secret_name: "API_TOKEN", encrypted_value: encryptedValue, key_id: keyId }); // List secrets await repoContext.client.actions.listRepoSecrets({...}); // Delete secret await repoContext.client.actions.deleteRepoSecret({...}); ``` ### Response #### Success Response (200 or 201) - **For Public Key**: `{"key": "...", "key_id": "...", "url": "..."}` - **For Create/Update**: Confirmation of creation/update. - **For List**: A JSON object containing a list of secrets. - **For Delete**: Typically a 204 No Content response. #### Response Example (List Secrets) ```json { "secrets": [ { "name": "API_TOKEN", "created_at": "2023-01-01T12:00:00Z", "updated_at": "2023-01-01T12:05:00Z", "visibility": "all" } ], "total_count": 1 } ``` ``` -------------------------------- ### Manage GitHub Repository Variables with TypeScript Source: https://context7.com/github/vscode-github-actions/llms.txt Demonstrates how to manage repository variables using the GitHub Actions API. It covers listing, creating, updating, and deleting variables. Requires authentication and access to repository context. ```typescript import { getGitHubContextForRepo } from "./git/repository"; // Manage repository variables const repoContext = await getGitHubContextForRepo("octocat", "hello-world"); if (repoContext) { // List all variables const variables = await repoContext.client.actions.listRepoVariables({ owner: repoContext.owner, repo: repoContext.name }); console.log("Repository variables:"); variables.data.variables.forEach(variable => { console.log(` - ${variable.name}: ${variable.value}`); console.log(` Created: ${variable.created_at}`); console.log(` Updated: ${variable.updated_at}`); }); // Create a new variable try { await repoContext.client.actions.createRepoVariable({ owner: repoContext.owner, repo: repoContext.name, name: "DEPLOYMENT_REGION", value: "us-west-2" }); console.log("Variable created successfully"); } catch (error) { console.error(`Failed to create variable: ${error.message}`); } // Update existing variable await repoContext.client.actions.updateRepoVariable({ owner: repoContext.owner, repo: repoContext.name, name: "DEPLOYMENT_REGION", value: "eu-west-1" }); console.log("Variable updated successfully"); // Delete a variable await repoContext.client.actions.deleteRepoVariable({ owner: repoContext.owner, repo: repoContext.name, name: "DEPLOYMENT_REGION" }); console.log("Variable deleted successfully"); } ``` -------------------------------- ### Trigger Workflow Dispatch Source: https://context7.com/github/vscode-github-actions/llms.txt This section covers triggering GitHub Actions workflows, specifically the `workflow_dispatch` and `repository_dispatch` events. It shows how to programmatically initiate workflows with specified inputs or payloads. ```APIDOC ## Trigger GitHub Actions Workflow ### Description Allows programmatic triggering of GitHub Actions workflows, including `workflow_dispatch` with custom inputs and `repository_dispatch` with a client payload. ### Method POST ### Endpoint - `POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches` (for `workflow_dispatch`) - `POST /repos/{owner}/{repo}/dispatches` (for `repository_dispatch`) ### Parameters #### Path Parameters - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. - **workflow_id** (string) - Required - The ID of the workflow to trigger (e.g., `.github/workflows/deploy.yml`). #### Query Parameters None #### Request Body ##### For `workflow_dispatch`: - **ref** (string) - Required - The Git reference (e.g., `refs/heads/main`) for the workflow. - **inputs** (object) - Optional - Key-value pairs for workflow inputs. ##### For `repository_dispatch`: - **event_type** (string) - Required - A custom event type string. - **client_payload** (object) - Optional - JSON payload to send with the event. ### Request Example ```typescript // Trigger workflow_dispatch await repoContext.client.actions.createWorkflowDispatch({ owner: repoContext.owner, repo: repoContext.name, workflow_id: workflowPath, ref: "refs/heads/main", inputs: { environment: "production", version: "v1.2.3" } }); // Trigger repository_dispatch await repoContext.client.repos.createDispatchEvent({ owner: repoContext.owner, repo: repoContext.name, event_type: "deploy", client_payload: { environment: "staging", ref: "main" } }); ``` ### Response #### Success Response (200 or 204) - Typically returns an empty response or a confirmation of event creation. #### Response Example (No specific JSON response body documented for success, typically indicates success via status code) ```json { "message": "Successfully triggered workflow dispatch." } ``` ``` -------------------------------- ### Lint and Format Code Source: https://github.com/github/vscode-github-actions/blob/main/CONTRIBUTING.md Manages code quality and formatting. 'npm run lint' checks for code style issues, 'npm run lint-fix' attempts to automatically fix them. 'npm run format-check' checks formatting with Prettier, and 'npm run format' automatically formats the code. ```bash npm run lint ``` ```bash npm run lint-fix ``` ```bash npm run format-check ``` ```bash npm run format ``` -------------------------------- ### Extension Activation and Deactivation (TypeScript) Source: https://context7.com/github/vscode-github-actions/llms.txt Handles the activation and deactivation lifecycle of the VS Code extension. It sets various context keys based on authentication and GitHub API status, initializes core components like resources, configuration, stores, and tree views, registers commands, and initializes the language server. The deactivate function is responsible for cleaning up the language server. ```typescript import * as vscode from "vscode"; import { activate, deactivate } from "./extension"; // Extension activation function // Called when extension is activated export async function activate(context: vscode.ExtensionContext) { // Check authentication status const hasSession = !!(await getSession()); const canReachAPI = hasSession && (await canReachGitHubAPI()); const ghContext = hasSession && (await getGitHubContext()); const hasGitHubRepos = ghContext && ghContext.repos.length > 0; // Set context keys for conditional UI await vscode.commands.executeCommand("setContext", "github-actions.signed-in", hasSession); await vscode.commands.executeCommand("setContext", "github-actions.internet-access", canReachAPI); await vscode.commands.executeCommand("setContext", "github-actions.has-repos", hasGitHubRepos); // Initialize components initResources(context); initConfiguration(context); const store = new RunStore(); await initPinnedWorkflows(store); await initTreeViews(context, store); // Register commands registerOpenWorkflowRun(context); registerTriggerWorkflowRun(context); registerReRunWorkflowRun(context); registerCancelWorkflowRun(context); registerAddSecret(context); registerPinWorkflow(context); // Initialize language server for authoring features await initLanguageServer(context); console.log("GitHub Actions extension activated"); } // Extension deactivation export function deactivate(): Thenable | undefined { return deactivateLanguageServer(); } ``` -------------------------------- ### Initialize Pinned Workflows Status Bar (TypeScript) Source: https://context7.com/github/vscode-github-actions/llms.txt Initializes the pinned workflows feature, which displays workflow status in the VS Code status bar. It requires a RunStore instance and is configured via VS Code settings. Enabled workflows appear with status icons and can be clicked to view the latest run. Auto-refresh can be enabled. ```typescript import { initPinnedWorkflows } from "./pinnedWorkflows/pinnedWorkflows"; import { RunStore } from "./store/store"; import * as vscode from "vscode"; // Initialize pinned workflows with a run store const store = new RunStore(); await initPinnedWorkflows(store); // Configure pinned workflows in VS Code settings // settings.json: // { // "github-actions.workflows.pinned.workflows": [ // ".github/workflows/ci.yml", // ".github/workflows/deploy.yml" // ], // "github-actions.workflows.pinned.refresh.enabled": true, // "github-actions.workflows.pinned.refresh.interval": 30 // } // Pinned workflows automatically appear in status bar // They show: // - Workflow name // - Current status icon (success, failure, in progress, etc.) // - Clickable to open most recent workflow run // - Auto-refresh every 30 seconds (if enabled) // - Red background for failed workflows console.log("Pinned workflows initialized and monitoring status"); ``` -------------------------------- ### GitHub Authentication (TypeScript) Source: https://context7.com/github/vscode-github-actions/llms.txt Handles user authentication with GitHub using getSession and newSession functions. It supports retrieving existing sessions, forcing re-authentication with a custom prompt, and performing silent authentication checks. Requires access to the './auth/auth' module. ```typescript import { getSession, newSession } from "./auth/auth"; // Get existing session or prompt user to sign in const session = await getSession(); if (session) { console.log(`Authenticated as: ${session.account.label}`); console.log(`Access token: ${session.accessToken}`); } // Force new session with custom prompt try { const newSessionForce = await newSession("Re-authentication required for this operation"); console.log(`New session created for: ${newSessionForce.account.label}`); } catch (error) { console.error("Authentication failed:", error.message); } // Skip prompt for silent authentication check const silentSession = await getSession(true); if (!silentSession) { console.log("No active session and user was not prompted"); } ``` -------------------------------- ### Workflow File Parsing Source: https://context7.com/github/vscode-github-actions/llms.txt This section details how to parse GitHub Actions workflow files from a given URI. It demonstrates extracting information about workflow events, jobs, and specific event inputs like workflow_dispatch. ```APIDOC ## Workflow File Parsing API ### Description Parses a GitHub Actions workflow file from a given URI and extracts details about its events, jobs, and inputs. ### Method GET (Implied by parsing function) ### Endpoint `/github/vscode-github-actions/workflow/workflow.parseWorkflowFile` ### Parameters #### Path Parameters - **workflowUri** (vscode.Uri) - Required - The URI of the workflow file to parse. #### Query Parameters None #### Request Body None ### Request Example ```typescript import { parseWorkflowFile } from "./workflow/workflow"; import * as vscode from "vscode"; const workflowUri = vscode.Uri.file("/path/to/repo/.github/workflows/ci.yml"); const workflow = await parseWorkflowFile(workflowUri); ``` ### Response #### Success Response (200) - **workflow** (object | null) - An object containing workflow details if parsing is successful, otherwise null. - **events** (object) - Details about the events that trigger the workflow. - **jobs** (object) - Details about the jobs defined in the workflow. #### Response Example ```json { "events": { "workflow_dispatch": { "inputs": { "environment": { "description": "Deployment environment", "required": true } } }, "repository_dispatch": { "types": ["deploy"] } }, "jobs": { "build": { /* ... job details ... */ }, "test": { /* ... job details ... */ } } } ``` ``` -------------------------------- ### Parse GitHub Actions Workflow File Source: https://context7.com/github/vscode-github-actions/llms.txt Parses a GitHub Actions workflow YAML file from a given URI. It extracts information about the workflow, including the events it listens to (like `workflow_dispatch` and `repository_dispatch`) and any associated inputs or types. Dependencies include the `workflow` module for parsing and `vscode.Uri` for handling file paths. ```typescript import { parseWorkflowFile, getWorkflowUri } from "./workflow/workflow"; import { getGitHubContextForRepo } from "./git/repository"; import * as vscode from "vscode"; // Parse workflow file from URI const workflowUri = vscode.Uri.file("/path/to/repo/.github/workflows/ci.yml"); const workflow = await parseWorkflowFile(workflowUri); if (workflow) { console.log(`Workflow parsed successfully`); console.log(`Events: ${Object.keys(workflow.events).join(", ")}`); console.log(`Jobs: ${Object.keys(workflow.jobs).join(", ")}`); // Check for workflow_dispatch event if (workflow.events.workflow_dispatch) { console.log("Workflow supports manual triggering"); const inputs = workflow.events.workflow_dispatch.inputs; if (inputs) { console.log("Required inputs:"); Object.entries(inputs).forEach(([name, input]) => { console.log(` - ${name}: ${input.description} (required: ${input.required})`); }); } } // Check for repository_dispatch event if (workflow.events.repository_dispatch?.types) { console.log(`Repository dispatch types: ${workflow.events.repository_dispatch.types.join(", ")}`); } } // Get workflow URI from repository context const repoContext = await getGitHubContextForRepo("octocat", "hello-world"); if (repoContext) { const workflowPath = ".github/workflows/ci.yml"; const uri = getWorkflowUri(repoContext, workflowPath); console.log(`Workflow URI: ${uri.toString()}`); } ``` -------------------------------- ### Manage GitHub Repository Secrets Source: https://context7.com/github/vscode-github-actions/llms.txt Encrypts and manages repository secrets using the GitHub API. It retrieves the repository's public key, encrypts a secret value using `libsodium`, and then creates or updates the secret. The function also includes operations to list and delete secrets. Dependencies include the `secrets/index` module for encryption and `git/repository` for context. ```typescript import { encodeSecret } from "./secrets/index"; import { getGitHubContextForRepo } from "./git/repository"; // Encrypt and add repository secret const repoContext = await getGitHubContextForRepo("octocat", "hello-world"); if (repoContext) { // Get repository public key for encryption const publicKeyResponse = await repoContext.client.actions.getRepoPublicKey({ owner: repoContext.owner, repo: repoContext.name }); const publicKey = publicKeyResponse.data.key; const keyId = publicKeyResponse.data.key_id; // Encrypt secret value using libsodium const secretName = "API_TOKEN"; const secretValue = "super-secret-value-123"; const encryptedValue = await encodeSecret(publicKey, secretValue); // Create or update secret try { await repoContext.client.actions.createOrUpdateRepoSecret({ owner: repoContext.owner, repo: repoContext.name, secret_name: secretName, encrypted_value: encryptedValue, key_id: keyId }); console.log(`Secret ${secretName} created successfully`); } catch (error) { console.error(`Failed to create secret: ${error.message}`); } // List all repository secrets const secrets = await repoContext.client.actions.listRepoSecrets({ owner: repoContext.owner, repo: repoContext.name }); console.log("Repository secrets:"); secrets.data.secrets.forEach(secret => { console.log(` - ${secret.name} (updated: ${secret.updated_at})`); }); // Delete a secret await repoContext.client.actions.deleteRepoSecret({ owner: repoContext.owner, repo: repoContext.name, secret_name: secretName }); console.log(`Secret ${secretName} deleted`); } ``` -------------------------------- ### Repository Context Resolution (TypeScript) Source: https://context7.com/github/vscode-github-actions/llms.txt Resolves GitHub repository context within the VS Code environment. Functions like 'getGitHubContext' and 'getGitHubContextForRepo' retrieve repository details, including owner, name, default branch, and permissions. It also provides the current branch and an authenticated Octokit client for API operations. Relies on './git/repository'. ```typescript import { getGitHubContext, getGitHubContextForRepo, getCurrentBranch } from "./git/repository"; // Get all GitHub repositories in workspace const gitHubContext = await getGitHubContext(); if (gitHubContext) { console.log(`Authenticated as: ${gitHubContext.username}`); console.log(`Found ${gitHubContext.repos.length} repositories`); for (const repo of gitHubContext.repos) { console.log(`Repository: ${repo.owner}/${repo.name}`); console.log(`Default branch: ${repo.defaultBranch}`); console.log(`Permission level: ${repo.permissionLevel}`); console.log(`Organization owned: ${repo.organizationOwned}`); const currentBranch = getCurrentBranch(repo.repositoryState); console.log(`Current branch: ${currentBranch || "detached HEAD"}`); } } // Get specific repository context const repoContext = await getGitHubContextForRepo("octocat", "hello-world"); if (repoContext) { // Use repository context for API calls const runs = await repoContext.client.actions.listWorkflowRunsForRepo({ owner: repoContext.owner, repo: repoContext.name, per_page: 5 }); console.log(`Recent workflow runs:`); runs.data.workflow_runs.forEach(run => { console.log(`- ${run.name}: ${run.status} (${run.conclusion || "in progress"})`); }); } ``` -------------------------------- ### Store and Poll Workflow Runs (TypeScript) Source: https://context7.com/github/vscode-github-actions/llms.txt Manages GitHub Actions workflow runs by storing their data and polling for updates. It fetches runs, adds them to a store, and polls active runs for status changes. Dependencies include './store/store' and './git/repository'. Outputs log messages to the console and can retrieve stored runs. ```typescript import { RunStore } from "./store/store"; import { getGitHubContextForRepo } from "./git/repository"; // Create run store const store = new RunStore(); // Subscribe to run updates store.event(({ run }) => { console.log(`Run updated: ${run.run.id} - ${run.run.status} (${run.run.conclusion || "in progress"})`); console.log(` Workflow: ${run.run.name}`); console.log(` Branch: ${run.run.head_branch}`); console.log(` Commit: ${run.run.head_sha.substring(0, 7)}`); console.log(` Updated: ${run.run.updated_at}`); }); // Fetch and add runs to store const repoContext = await getGitHubContextForRepo("octocat", "hello-world"); if (repoContext) { const runsResponse = await repoContext.client.actions.listWorkflowRunsForRepo({ owner: repoContext.owner, repo: repoContext.name, per_page: 10 }); // Add runs to store runsResponse.data.workflow_runs.forEach(runData => { const run = store.addRun(repoContext, runData); console.log(`Added run ${run.run.id} to store`); }); // Poll active runs for updates const activeRuns = runsResponse.data.workflow_runs.filter( run => run.status === "in_progress" || run.status === "queued" ); activeRuns.forEach(run => { // Poll every 10 seconds, up to 20 attempts store.pollRun(run.id, repoContext, 10000, 20); console.log(`Started polling for run ${run.id}`); }); // Retrieve run from store const runId = runsResponse.data.workflow_runs[0].id; const storedRun = store.getRun(runId); if (storedRun) { console.log(`Retrieved run ${storedRun.run.id} from store`); } } ``` -------------------------------- ### Trigger GitHub Actions Dispatch Events Source: https://context7.com/github/vscode-github-actions/llms.txt Triggers GitHub Actions workflows using `workflow_dispatch` or `repository_dispatch` events. It requires repository context and a valid workflow path. For `workflow_dispatch`, it can include specific inputs. For `repository_dispatch`, it takes an event type and client payload. Error handling is included for API calls. ```typescript import { getGitHubContextForRepo } from "./git/repository"; import { parseWorkflowFile, getWorkflowUri } from "./workflow/workflow"; // Trigger workflow_dispatch event const repoContext = await getGitHubContextForRepo("octocat", "hello-world"); if (repoContext) { const workflowPath = ".github/workflows/deploy.yml"; const workflowUri = getWorkflowUri(repoContext, workflowPath); const workflow = await parseWorkflowFile(workflowUri); if (workflow?.events.workflow_dispatch) { try { await repoContext.client.actions.createWorkflowDispatch({ owner: repoContext.owner, repo: repoContext.name, workflow_id: workflowPath, ref: "refs/heads/main", inputs: { environment: "production", version: "v1.2.3" } }); console.log("Workflow dispatch event created successfully"); } catch (error) { console.error(`Failed to trigger workflow: ${error.message}`); } } } // Trigger repository_dispatch event if (repoContext) { try { await repoContext.client.repos.createDispatchEvent({ owner: repoContext.owner, repo: repoContext.name, event_type: "deploy", client_payload: { environment: "staging", ref: "main" } }); console.log("Repository dispatch event created successfully"); } catch (error) { console.error(`Failed to create dispatch event: ${error.message}`); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.