From f23cc9f9470f92fc321d0686b1bf4229a5086c74 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:50:24 -0800 Subject: [PATCH 1/5] Move release maintenance workflows to Azure Pipelines --- .github/workflows/create-cherry-pick-pr.yml | 239 -------------- .github/workflows/new-release-branch.yaml | 147 --------- .github/workflows/set-version.yaml | 166 ---------- .github/workflows/sync-branch.yaml | 155 --------- tools/pipelines/release-maintenance.yml | 339 ++++++++++++++++++++ tools/scripts/release-maintenance.mjs | 231 +++++++++++++ 6 files changed, 570 insertions(+), 707 deletions(-) delete mode 100644 .github/workflows/create-cherry-pick-pr.yml delete mode 100644 .github/workflows/new-release-branch.yaml delete mode 100644 .github/workflows/set-version.yaml delete mode 100644 .github/workflows/sync-branch.yaml create mode 100644 tools/pipelines/release-maintenance.yml create mode 100644 tools/scripts/release-maintenance.mjs diff --git a/.github/workflows/create-cherry-pick-pr.yml b/.github/workflows/create-cherry-pick-pr.yml deleted file mode 100644 index a0dd69e68bb5d..0000000000000 --- a/.github/workflows/create-cherry-pick-pr.yml +++ /dev/null @@ -1,239 +0,0 @@ -name: Create cherry pick PR - -on: - workflow_dispatch: - inputs: - pr: - description: PR number to cherry-pick - required: true - type: number - target_branch: - description: Target branch to cherry-pick to - required: true - type: string - - # Inputs provided by the bot - distinct_id: - description: '(bot) A distinct ID' - required: false - default: '' - source_issue: - description: '(bot) The issue that triggered this workflow' - required: false - default: '' - requesting_user: - description: '(bot) The user who requested this workflow' - required: false - default: '' - status_comment: - description: '(bot) The comment to update with the status of this workflow' - required: false - default: '' - -run-name: ${{ github.workflow }}${{ inputs.distinct_id && format(' (bot run {0})', inputs.distinct_id) || '' }} - -permissions: - contents: read - id-token: write - -# Ensure scripts are run with pipefail. See: -# https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#exit-codes-and-error-action-preference -defaults: - run: - shell: bash - -jobs: - open-pr: - runs-on: ubuntu-latest - environment: - name: azure - deployment: false - if: github.repository == 'microsoft/TypeScript' - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - filter: blob:none # https://github.blog/2020-12-21-get-up-to-speed-with-partial-clone-and-shallow-clone/ - fetch-depth: 0 # Default is 1; need to set to 0 to get the benefits of blob:none. - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 24 - - uses: ./.github/actions/setup-go - - name: Check out target branch - env: - TARGET_BRANCH: ${{ inputs.target_branch }} - run: git switch --detach "origin/$TARGET_BRANCH" - - run: npm ci - - uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0 - if: ${{ !cancelled() }} - with: - client-id: ${{ vars.AZURE_CLIENT_ID }} - tenant-id: ${{ vars.AZURE_TENANT_ID }} - subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} - - name: Create GitHub App token - if: ${{ !cancelled() }} - id: app-token - uses: microsoft/create-github-app-token-via-key-vault@5ba0d436e9c3cac52feff4d1f2f66f9698ce4a2d # v1 - with: - client-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_CLIENT_ID }} - key-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID }} - owner: microsoft - repositories: TypeScript - permission-contents: write - permission-issues: write - permission-pull-requests: write - - name: Configure git for GitHub App token - shell: bash - env: - GITHUB_APP_TOKEN: ${{ steps.app-token.outputs.token }} - run: | - set -euo pipefail - basic_auth="$(node -e 'process.stdout.write(Buffer.from("x-access-token:" + process.env.GITHUB_APP_TOKEN).toString("base64"))')" - echo "::add-mask::$basic_auth" - git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${basic_auth}" - - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - id: open-pr - env: - PR: ${{ inputs.pr }} - TARGET_BRANCH: ${{ inputs.target_branch }} - DISTINCT_ID: ${{ inputs.distinct_id }} - SOURCE_ISSUE: ${{ inputs.source_issue }} - REQUESTING_USER: ${{ inputs.requesting_user }} - STATUS_COMMENT: ${{ inputs.status_comment }} - with: - retries: 3 - github-token: ${{ steps.app-token.outputs.token }} - result-encoding: string - script: | - const { - PR, - TARGET_BRANCH, - DISTINCT_ID, - SOURCE_ISSUE, - REQUESTING_USER, - STATUS_COMMENT, - } = process.env; - - const pr = await github.rest.pulls.get({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: +PR, - }); - - if (!pr.data.merged || !pr.data.merge_commit_sha) { - throw new Error(`PR #${PR} has not been merged`); - } - - const pickBranch = `cherry-pick/${PR}/${TARGET_BRANCH}`; - - const title = `🤖 Pick PR #${PR} (${pr.data.title.substring(0, 35)}${pr.data.title.length > 35 ? "..." : ""}) into ${TARGET_BRANCH}`; - - await exec.exec("git", ["config", "user.email", "290192711+typescript-automation[bot]@users.noreply.github.com"]); - await exec.exec("git", ["config", "user.name", "typescript-automation[bot]"]); - await exec.exec("git", ["switch", "-c", pickBranch]); - - let updatedBaselinesMessage = ""; - try { - await exec.exec("git", ["cherry-pick", "-m", "1", pr.data.merge_commit_sha]); - } catch (e) { - console.log(e); - - // The cherry-pick failed. If all conflicts are compiler baselines, - // try to run the tests and accept the new baselines. - - const conflictsOutput = await exec.getExecOutput("git", ["diff", "--name-only", "--diff-filter=U"]); - const conflictedFiles = conflictsOutput.stdout.trim().split("\n").filter(Boolean); - const baselineDirs = ["tsc/testdata/baselines", "tests/baselines"]; - if (!conflictedFiles.length || conflictedFiles.some(file => !baselineDirs.some(dir => file.startsWith(`${dir}/`)))) { - throw new Error(`Cherry-pick has non-baseline conflicts:\n${conflictedFiles.join("\n")}`); - } - - await exec.exec("git", ["add", "--all", "--", ...conflictedFiles]); - await exec.exec("git", ["-c", "core.editor=true", "cherry-pick", "--continue"]); - - try { - await exec.exec("npx", ["hereby", "test"]); - } catch { - // Expected to fail. - } - - await exec.exec("npx", ["hereby", "baseline-accept"]); - await exec.exec("npx", ["hereby", "test"]); - const existingBaselineDirs = baselineDirs.filter(dir => conflictedFiles.some(file => file.startsWith(`${dir}/`))); - await exec.exec("git", ["add", "--all", "--", ...existingBaselineDirs]); - const staged = await exec.getExecOutput("git", ["diff", "--cached", "--quiet"], { ignoreReturnCode: true }); - if (staged.exitCode !== 0) { - await exec.exec("git", ["commit", "-m", "Update baselines"]); - } - - updatedBaselinesMessage = " This involved updating baselines; please check the diff."; - } - - await exec.exec("git", ["push", "--force-with-lease", "--set-upstream", "origin", pickBranch]); - - const existingPulls = await github.rest.pulls.list({ - owner: context.repo.owner, - repo: context.repo.repo, - head: `${context.repo.owner}:${pickBranch}`, - }); - - let commentBody; - - if (existingPulls.data.length === 0) { - console.log(`No existing PRs found for ${pickBranch}`); - - const body = `This cherry-pick was triggered by a request on #${PR}.\n\nPlease review the diff and merge if no changes are unexpected.${updatedBaselinesMessage}`; - - const newPr = await github.rest.pulls.create({ - owner: context.repo.owner, - repo: context.repo.repo, - base: TARGET_BRANCH, - head: pickBranch, - title, - body, - }); - - await github.rest.issues.addAssignees({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: newPr.data.number, - assignees: ["DanielRosenwasser"], - }); - - const reviewers = ["DanielRosenwasser", REQUESTING_USER].filter(Boolean); - await github.rest.pulls.requestReviewers({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: newPr.data.number, - reviewers, - }); - - commentBody = `I've created #${newPr.data.number} for you.${updatedBaselinesMessage}`; - } - else { - const existing = existingPulls.data[0]; - console.log(`Found existing PR #${existing.number} for ${pickBranch}`); - - await github.rest.pulls.update({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: existing.number, - title, - }); - - commentBody = `I've updated #${existing.number} for you.${updatedBaselinesMessage}`; - } - - return commentBody; - - - uses: microsoft/typescript-bot-test-triggerer/.github/actions/post-workflow-result@08bcbbf253fd6bc533dd8b9ab47a58582be57fbe # master - if: ${{ !cancelled() && inputs.distinct_id }} - with: - success_comment: ${{ steps.open-pr.outputs.result }} - failure_comment: 'I was unable to cherry-pick this PR.' - github_token: ${{ steps.app-token.outputs.token }} - distinct_id: ${{ inputs.distinct_id }} - source_issue: ${{ inputs.source_issue }} - requesting_user: ${{ inputs.requesting_user }} - status_comment: ${{ inputs.status_comment }} diff --git a/.github/workflows/new-release-branch.yaml b/.github/workflows/new-release-branch.yaml deleted file mode 100644 index 7fa9e2b3b81ff..0000000000000 --- a/.github/workflows/new-release-branch.yaml +++ /dev/null @@ -1,147 +0,0 @@ -name: New release branch - -on: - workflow_dispatch: - inputs: - branch_name: - description: Release branch name to create - required: true - type: string - package_version: - description: Release package version - required: true - type: string - core_major_minor: - description: Release core major.minor version - required: true - type: string - - # Inputs provided by the bot - distinct_id: - description: '(bot) A distinct ID' - required: false - default: '' - source_issue: - description: '(bot) The issue that triggered this workflow' - required: false - default: '' - requesting_user: - description: '(bot) The user who requested this workflow' - required: false - default: '' - status_comment: - description: '(bot) The comment to update with the status of this workflow' - required: false - default: '' - -run-name: ${{ github.workflow }}${{ inputs.distinct_id && format(' (bot run {0})', inputs.distinct_id) || '' }} - -permissions: - contents: read - id-token: write - -defaults: - run: - shell: bash - -jobs: - create: - if: github.repository == 'microsoft/TypeScript' - runs-on: ubuntu-latest - environment: - name: azure - deployment: false - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: main - filter: blob:none - fetch-depth: 0 - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 24 - - uses: ./.github/actions/setup-go - - name: Configure release branch - env: - BRANCH_NAME: ${{ inputs.branch_name }} - PACKAGE_VERSION: ${{ inputs.package_version }} - CORE_MAJOR_MINOR: ${{ inputs.core_major_minor }} - run: | - set -euo pipefail - if ! [[ "$BRANCH_NAME" =~ ^(release-.+|ts[0-9]+-release)$ ]]; then - echo "Release branch name must start with 'release-' or match 'ts-release'." >&2 - exit 1 - fi - if git show-ref --verify --quiet "refs/remotes/origin/$BRANCH_NAME"; then - echo "Branch $BRANCH_NAME already exists." >&2 - exit 1 - fi - - git switch -c "$BRANCH_NAME" - node tools/scripts/configure-release.mjs "$PACKAGE_VERSION" "$CORE_MAJOR_MINOR" - - mapfile -t changedFiles < <(git diff --name-only) - expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") - if [ "${changedFiles[*]}" != "${expectedFiles[*]}" ]; then - echo "Unexpected files in release configuration: ${changedFiles[*]}" >&2 - exit 1 - fi - - run: npm ci - - run: npx hereby validate --all - - name: Commit release configuration - env: - PACKAGE_VERSION: ${{ inputs.package_version }} - run: | - set -euo pipefail - mapfile -t changedFiles < <(git diff --name-only) - expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") - if [ "${changedFiles[*]}" != "${expectedFiles[*]}" ]; then - echo "Validation produced unexpected changes: ${changedFiles[*]}" >&2 - exit 1 - fi - git add Herebyfile.mjs tsc/internal/core/version.go - git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" - git config user.name "typescript-automation[bot]" - git config core.hooksPath /dev/null - git commit -m "Bump version to $PACKAGE_VERSION" - - uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0 - if: ${{ !cancelled() }} - with: - client-id: ${{ vars.AZURE_CLIENT_ID }} - tenant-id: ${{ vars.AZURE_TENANT_ID }} - subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} - - name: Create GitHub App token - if: ${{ !cancelled() }} - id: app-token - uses: microsoft/create-github-app-token-via-key-vault@5ba0d436e9c3cac52feff4d1f2f66f9698ce4a2d # v1 - with: - client-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_CLIENT_ID }} - key-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID }} - owner: microsoft - repositories: TypeScript - permission-contents: write - permission-issues: write - - name: Configure git for GitHub App token - env: - GITHUB_APP_TOKEN: ${{ steps.app-token.outputs.token }} - run: | - set -euo pipefail - basic_auth="$(node -e 'process.stdout.write(Buffer.from("x-access-token:" + process.env.GITHUB_APP_TOKEN).toString("base64"))')" - echo "::add-mask::$basic_auth" - git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${basic_auth}" - - env: - BRANCH_NAME: ${{ inputs.branch_name }} - run: git push --set-upstream origin "$BRANCH_NAME" - - - uses: microsoft/typescript-bot-test-triggerer/.github/actions/post-workflow-result@08bcbbf253fd6bc533dd8b9ab47a58582be57fbe # master - if: ${{ !cancelled() && inputs.distinct_id }} - with: - success_comment: "I've created ${{ inputs.branch_name }} with version ${{ inputs.package_version }} for you." - failure_comment: 'I was unable to create the new release branch.' - github_token: ${{ steps.app-token.outputs.token }} - distinct_id: ${{ inputs.distinct_id }} - source_issue: ${{ inputs.source_issue }} - requesting_user: ${{ inputs.requesting_user }} - status_comment: ${{ inputs.status_comment }} diff --git a/.github/workflows/set-version.yaml b/.github/workflows/set-version.yaml deleted file mode 100644 index dbf2e235b3e60..0000000000000 --- a/.github/workflows/set-version.yaml +++ /dev/null @@ -1,166 +0,0 @@ -name: Set branch version - -on: - workflow_dispatch: - inputs: - branch_name: - description: Release branch to update - required: true - type: string - package_version: - description: Release package version - required: true - type: string - core_major_minor: - description: Release core major.minor version - required: true - type: string - - # Inputs provided by the bot - distinct_id: - description: '(bot) A distinct ID' - required: false - default: '' - source_issue: - description: '(bot) The issue that triggered this workflow' - required: false - default: '' - requesting_user: - description: '(bot) The user who requested this workflow' - required: false - default: '' - status_comment: - description: '(bot) The comment to update with the status of this workflow' - required: false - default: '' - -run-name: ${{ github.workflow }}${{ inputs.distinct_id && format(' (bot run {0})', inputs.distinct_id) || '' }} - -permissions: - contents: read - id-token: write - -defaults: - run: - shell: bash - -jobs: - update: - if: github.repository == 'microsoft/TypeScript' - runs-on: ubuntu-latest - environment: - name: azure - deployment: false - - steps: - - name: Validate release branch name - env: - BRANCH_NAME: ${{ inputs.branch_name }} - run: | - set -euo pipefail - if ! [[ "$BRANCH_NAME" =~ ^(release-.+|ts[0-9]+-release)$ ]]; then - echo "Release branch name must start with 'release-' or match 'ts-release'." >&2 - exit 1 - fi - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ inputs.branch_name }} - filter: blob:none - fetch-depth: 0 - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 24 - - uses: ./.github/actions/setup-go - - run: npm ci - - name: Load release automation from main - run: | - set -euo pipefail - git fetch origin main - git show origin/main:tools/scripts/configure-release.mjs > "$RUNNER_TEMP/configure-release.mjs" - - name: Configure release version - id: configure - env: - PACKAGE_VERSION: ${{ inputs.package_version }} - CORE_MAJOR_MINOR: ${{ inputs.core_major_minor }} - run: | - set -euo pipefail - node "$RUNNER_TEMP/configure-release.mjs" "$PACKAGE_VERSION" "$CORE_MAJOR_MINOR" - - mapfile -t changedFiles < <(git diff --name-only) - if [ "${#changedFiles[@]}" -eq 0 ]; then - echo "Version is already $PACKAGE_VERSION." - echo "changed=false" >> "$GITHUB_OUTPUT" - exit 0 - fi - - expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") - for changedFile in "${changedFiles[@]}"; do - if [[ ! " ${expectedFiles[*]} " =~ " $changedFile " ]]; then - echo "Unexpected file in release configuration: $changedFile" >&2 - exit 1 - fi - done - echo "changed=true" >> "$GITHUB_OUTPUT" - - if: steps.configure.outputs.changed == 'true' - run: npx hereby validate --all - - name: Commit release configuration - if: steps.configure.outputs.changed == 'true' - env: - PACKAGE_VERSION: ${{ inputs.package_version }} - run: | - set -euo pipefail - mapfile -t changedFiles < <(git diff --name-only) - expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") - for changedFile in "${changedFiles[@]}"; do - if [[ ! " ${expectedFiles[*]} " =~ " $changedFile " ]]; then - echo "Validation produced unexpected change: $changedFile" >&2 - exit 1 - fi - done - git add Herebyfile.mjs tsc/internal/core/version.go - git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" - git config user.name "typescript-automation[bot]" - git config core.hooksPath /dev/null - git commit -m "Bump version to $PACKAGE_VERSION" - - uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0 - if: ${{ !cancelled() }} - with: - client-id: ${{ vars.AZURE_CLIENT_ID }} - tenant-id: ${{ vars.AZURE_TENANT_ID }} - subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} - - name: Create GitHub App token - if: ${{ !cancelled() }} - id: app-token - uses: microsoft/create-github-app-token-via-key-vault@5ba0d436e9c3cac52feff4d1f2f66f9698ce4a2d # v1 - with: - client-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_CLIENT_ID }} - key-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID }} - owner: microsoft - repositories: TypeScript - permission-contents: write - permission-issues: write - - name: Configure git for GitHub App token - if: steps.configure.outputs.changed == 'true' - env: - GITHUB_APP_TOKEN: ${{ steps.app-token.outputs.token }} - run: | - set -euo pipefail - basic_auth="$(node -e 'process.stdout.write(Buffer.from("x-access-token:" + process.env.GITHUB_APP_TOKEN).toString("base64"))')" - echo "::add-mask::$basic_auth" - git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${basic_auth}" - - if: steps.configure.outputs.changed == 'true' - env: - BRANCH_NAME: ${{ inputs.branch_name }} - run: git push origin "HEAD:$BRANCH_NAME" - - - uses: microsoft/typescript-bot-test-triggerer/.github/actions/post-workflow-result@08bcbbf253fd6bc533dd8b9ab47a58582be57fbe # master - if: ${{ !cancelled() && inputs.distinct_id }} - with: - success_comment: "I've set the version of ${{ inputs.branch_name }} to ${{ inputs.package_version }} for you." - failure_comment: 'I was unable to set the version.' - github_token: ${{ steps.app-token.outputs.token }} - distinct_id: ${{ inputs.distinct_id }} - source_issue: ${{ inputs.source_issue }} - requesting_user: ${{ inputs.requesting_user }} - status_comment: ${{ inputs.status_comment }} diff --git a/.github/workflows/sync-branch.yaml b/.github/workflows/sync-branch.yaml deleted file mode 100644 index ec726a91f227e..0000000000000 --- a/.github/workflows/sync-branch.yaml +++ /dev/null @@ -1,155 +0,0 @@ -name: Sync release branch with main - -on: - workflow_dispatch: - inputs: - branch_name: - description: Release branch to update - required: true - type: string - - # Inputs provided by the bot - distinct_id: - description: '(bot) A distinct ID' - required: false - default: '' - source_issue: - description: '(bot) The issue that triggered this workflow' - required: false - default: '' - requesting_user: - description: '(bot) The user who requested this workflow' - required: false - default: '' - status_comment: - description: '(bot) The comment to update with the status of this workflow' - required: false - default: '' - -run-name: ${{ github.workflow }}${{ inputs.distinct_id && format(' (bot run {0})', inputs.distinct_id) || '' }} - -permissions: - contents: read - id-token: write - -defaults: - run: - shell: bash - -jobs: - sync: - if: github.repository == 'microsoft/TypeScript' - runs-on: ubuntu-latest - environment: - name: azure - deployment: false - - steps: - - name: Validate release branch name - env: - BRANCH_NAME: ${{ inputs.branch_name }} - run: | - set -euo pipefail - if ! [[ "$BRANCH_NAME" =~ ^(release-.+|ts[0-9]+-release)$ ]]; then - echo "Release branch name must start with 'release-' or match 'ts-release'." >&2 - exit 1 - fi - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ inputs.branch_name }} - filter: blob:none - fetch-depth: 0 - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 24 - - uses: ./.github/actions/setup-go - - name: Merge main - env: - BRANCH_NAME: ${{ inputs.branch_name }} - run: | - set -euo pipefail - releaseVersion="$(node -e ' - const source = require("node:fs").readFileSync("tsc/internal/core/version.go", "utf8"); - const match = source.match(/var version = "([^"]+)"/); - if (!match) throw new Error("Unable to read the release version"); - process.stdout.write(match[1]); - ')" - git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" - git config user.name "typescript-automation[bot]" - git config core.hooksPath /dev/null - git fetch origin main - git show origin/main:tools/scripts/configure-release.mjs > "$RUNNER_TEMP/configure-release.mjs" - - if ! git merge origin/main --no-ff --no-commit; then - mapfile -t conflictedFiles < <(git diff --name-only --diff-filter=U) - allowedConflicts=("Herebyfile.mjs" "tsc/internal/core/version.go") - for conflictedFile in "${conflictedFiles[@]}"; do - if [[ ! " ${allowedConflicts[*]} " =~ " $conflictedFile " ]]; then - echo "Merge conflict requires manual resolution: $conflictedFile" >&2 - exit 1 - fi - done - if [ "${#conflictedFiles[@]}" -eq 0 ]; then - echo "Merge failed without reporting conflicted files." >&2 - exit 1 - fi - git checkout --theirs -- "${conflictedFiles[@]}" - fi - - node "$RUNNER_TEMP/configure-release.mjs" "$releaseVersion" - git add Herebyfile.mjs tsc/internal/core/version.go - if git rev-parse --verify --quiet MERGE_HEAD >/dev/null; then - git commit --no-edit - elif ! git diff --cached --quiet; then - git commit -m "Restore release configuration after syncing main" - fi - - run: npm ci - - run: npx hereby validate --all - - name: Verify clean merge - run: | - set -euo pipefail - if ! git diff --quiet || ! git diff --cached --quiet; then - echo "Validation modified the worktree; refusing to push the merge." >&2 - git status --short - exit 1 - fi - - uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0 - if: ${{ !cancelled() }} - with: - client-id: ${{ vars.AZURE_CLIENT_ID }} - tenant-id: ${{ vars.AZURE_TENANT_ID }} - subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} - - name: Create GitHub App token - if: ${{ !cancelled() }} - id: app-token - uses: microsoft/create-github-app-token-via-key-vault@5ba0d436e9c3cac52feff4d1f2f66f9698ce4a2d # v1 - with: - client-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_CLIENT_ID }} - key-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID }} - owner: microsoft - repositories: TypeScript - permission-contents: write - permission-issues: write - - name: Configure git for GitHub App token - env: - GITHUB_APP_TOKEN: ${{ steps.app-token.outputs.token }} - run: | - set -euo pipefail - basic_auth="$(node -e 'process.stdout.write(Buffer.from("x-access-token:" + process.env.GITHUB_APP_TOKEN).toString("base64"))')" - echo "::add-mask::$basic_auth" - git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${basic_auth}" - - env: - BRANCH_NAME: ${{ inputs.branch_name }} - run: git push origin "HEAD:$BRANCH_NAME" - - - uses: microsoft/typescript-bot-test-triggerer/.github/actions/post-workflow-result@08bcbbf253fd6bc533dd8b9ab47a58582be57fbe # master - if: ${{ !cancelled() && inputs.distinct_id }} - with: - success_comment: "I've pulled main into ${{ inputs.branch_name }} for you." - failure_comment: 'I was unable to merge main into ${{ inputs.branch_name }}.' - github_token: ${{ steps.app-token.outputs.token }} - distinct_id: ${{ inputs.distinct_id }} - source_issue: ${{ inputs.source_issue }} - requesting_user: ${{ inputs.requesting_user }} - status_comment: ${{ inputs.status_comment }} diff --git a/tools/pipelines/release-maintenance.yml b/tools/pipelines/release-maintenance.yml new file mode 100644 index 0000000000000..33bfae485ff18 --- /dev/null +++ b/tools/pipelines/release-maintenance.yml @@ -0,0 +1,339 @@ +trigger: none +pr: none + +parameters: + - name: operation + type: string + values: + - cherry-pick + - new-release-branch + - set-version + - sync-branch + - name: pr + type: string + default: '' + - name: target_branch + type: string + default: '' + - name: branch_name + type: string + default: '' + - name: package_version + type: string + default: '' + - name: core_major_minor + type: string + default: '' + - name: distinct_id + type: string + default: '' + - name: source_issue + type: string + default: '' + - name: requesting_user + type: string + default: '' + - name: status_comment + type: string + default: '' + +name: $(Date:yyyyMMdd)$(Rev:.r) ${{ parameters.operation }} + +variables: + - name: TYPESCRIPT_AUTOMATION_GITHUB_APP_CLIENT_ID + value: Iv23li4GolzJSEp1mzHI + - name: TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID + value: https://jststeam-passwords.vault.azure.net/keys/typescript-automation + +jobs: + - ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/main') }}: + - job: ReleaseMaintenance + displayName: ${{ parameters.operation }} + timeoutInMinutes: 180 + pool: + name: TypeScript-1ES-Large + demands: + - ImageOverride -equals azure-linux-3 + + steps: + - checkout: self + fetchDepth: 0 + fetchFilter: blob:none + fetchTags: false + + - bash: git fetch --no-tags origin "+refs/heads/*:refs/remotes/origin/*" + displayName: Fetch branches + + - bash: | + set -euo pipefail + if [[ "$OPERATION" == cherry-pick ]]; then + if ! [[ "$PR" =~ ^[1-9][0-9]*$ ]]; then + echo "pr must be a PR number." >&2 + exit 1 + fi + if [[ -z "$TARGET_BRANCH" ]]; then + echo "target_branch is required." >&2 + exit 1 + fi + else + if ! [[ "$BRANCH_NAME" =~ ^(release-.+|ts[0-9]+-release)$ ]]; then + echo "Release branch name must start with 'release-' or match 'ts-release'." >&2 + exit 1 + fi + if [[ "$OPERATION" != sync-branch && ( -z "$PACKAGE_VERSION" || -z "$CORE_MAJOR_MINOR" ) ]]; then + echo "package_version and core_major_minor are required." >&2 + exit 1 + fi + fi + cp tools/scripts/configure-release.mjs tools/scripts/release-maintenance.mjs "$AGENT_TEMPDIRECTORY/" + displayName: Validate inputs + env: + OPERATION: ${{ parameters.operation }} + PR: ${{ parameters.pr }} + TARGET_BRANCH: ${{ parameters.target_branch }} + BRANCH_NAME: ${{ parameters.branch_name }} + PACKAGE_VERSION: ${{ parameters.package_version }} + CORE_MAJOR_MINOR: ${{ parameters.core_major_minor }} + + - task: UseNode@1 + displayName: Use Node 24.x + inputs: + version: 24.x + + - template: /tools/pipelines/steps/setup-go.yml@self + + - ${{ if eq(parameters.operation, 'cherry-pick') }}: + - bash: | + set -euo pipefail + git switch --detach "origin/$TARGET_BRANCH" + displayName: Check out target branch + env: + TARGET_BRANCH: ${{ parameters.target_branch }} + + - bash: npm ci + displayName: npm ci + + - ${{ if eq(parameters.operation, 'new-release-branch') }}: + - bash: | + set -euo pipefail + if git show-ref --verify --quiet "refs/remotes/origin/$BRANCH_NAME"; then + echo "Branch $BRANCH_NAME already exists." >&2 + exit 1 + fi + + git switch -c "$BRANCH_NAME" + node "$AGENT_TEMPDIRECTORY/configure-release.mjs" "$PACKAGE_VERSION" "$CORE_MAJOR_MINOR" + + mapfile -t changedFiles < <(git diff --name-only) + expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") + if [ "${changedFiles[*]}" != "${expectedFiles[*]}" ]; then + echo "Unexpected files in release configuration: ${changedFiles[*]}" >&2 + exit 1 + fi + displayName: Configure release branch + env: + BRANCH_NAME: ${{ parameters.branch_name }} + PACKAGE_VERSION: ${{ parameters.package_version }} + CORE_MAJOR_MINOR: ${{ parameters.core_major_minor }} + + - bash: npm ci + displayName: npm ci + + - bash: npx hereby validate --all + displayName: hereby validate --all + + - bash: | + set -euo pipefail + mapfile -t changedFiles < <(git diff --name-only) + expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") + if [ "${changedFiles[*]}" != "${expectedFiles[*]}" ]; then + echo "Validation produced unexpected changes: ${changedFiles[*]}" >&2 + exit 1 + fi + git add Herebyfile.mjs tsc/internal/core/version.go + git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" + git config user.name "typescript-automation[bot]" + git config core.hooksPath /dev/null + git commit -m "Bump version to $PACKAGE_VERSION" + displayName: Commit release configuration + env: + PACKAGE_VERSION: ${{ parameters.package_version }} + + - ${{ if eq(parameters.operation, 'set-version') }}: + - bash: | + set -euo pipefail + git switch --detach "origin/$BRANCH_NAME" + displayName: Check out release branch + env: + BRANCH_NAME: ${{ parameters.branch_name }} + + - bash: npm ci + displayName: npm ci + + - bash: | + set -euo pipefail + node "$AGENT_TEMPDIRECTORY/configure-release.mjs" "$PACKAGE_VERSION" "$CORE_MAJOR_MINOR" + + mapfile -t changedFiles < <(git diff --name-only) + if [ "${#changedFiles[@]}" -eq 0 ]; then + echo "Version is already $PACKAGE_VERSION." + echo "##vso[task.setvariable variable=ReleaseConfigChanged]false" + exit 0 + fi + + expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") + for changedFile in "${changedFiles[@]}"; do + if [[ ! " ${expectedFiles[*]} " =~ " $changedFile " ]]; then + echo "Unexpected file in release configuration: $changedFile" >&2 + exit 1 + fi + done + echo "##vso[task.setvariable variable=ReleaseConfigChanged]true" + displayName: Configure release version + env: + PACKAGE_VERSION: ${{ parameters.package_version }} + CORE_MAJOR_MINOR: ${{ parameters.core_major_minor }} + + - bash: npx hereby validate --all + displayName: hereby validate --all + condition: and(succeeded(), eq(variables['ReleaseConfigChanged'], 'true')) + + - bash: | + set -euo pipefail + mapfile -t changedFiles < <(git diff --name-only) + expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") + for changedFile in "${changedFiles[@]}"; do + if [[ ! " ${expectedFiles[*]} " =~ " $changedFile " ]]; then + echo "Validation produced unexpected change: $changedFile" >&2 + exit 1 + fi + done + git add Herebyfile.mjs tsc/internal/core/version.go + git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" + git config user.name "typescript-automation[bot]" + git config core.hooksPath /dev/null + git commit -m "Bump version to $PACKAGE_VERSION" + displayName: Commit release configuration + condition: and(succeeded(), eq(variables['ReleaseConfigChanged'], 'true')) + env: + PACKAGE_VERSION: ${{ parameters.package_version }} + + - ${{ if eq(parameters.operation, 'sync-branch') }}: + - bash: | + set -euo pipefail + git switch --detach "origin/$BRANCH_NAME" + + releaseVersion="$(node -e ' + const source = require("node:fs").readFileSync("tsc/internal/core/version.go", "utf8"); + const match = source.match(/var version = "([^"]+)"/); + if (!match) throw new Error("Unable to read the release version"); + process.stdout.write(match[1]); + ')" + git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" + git config user.name "typescript-automation[bot]" + git config core.hooksPath /dev/null + + if ! git merge origin/main --no-ff --no-commit; then + mapfile -t conflictedFiles < <(git diff --name-only --diff-filter=U) + allowedConflicts=("Herebyfile.mjs" "tsc/internal/core/version.go") + for conflictedFile in "${conflictedFiles[@]}"; do + if [[ ! " ${allowedConflicts[*]} " =~ " $conflictedFile " ]]; then + echo "Merge conflict requires manual resolution: $conflictedFile" >&2 + exit 1 + fi + done + if [ "${#conflictedFiles[@]}" -eq 0 ]; then + echo "Merge failed without reporting conflicted files." >&2 + exit 1 + fi + git checkout --theirs -- "${conflictedFiles[@]}" + fi + + node "$AGENT_TEMPDIRECTORY/configure-release.mjs" "$releaseVersion" + git add Herebyfile.mjs tsc/internal/core/version.go + if git rev-parse --verify --quiet MERGE_HEAD >/dev/null; then + git commit --no-edit + elif ! git diff --cached --quiet; then + git commit -m "Restore release configuration after syncing main" + fi + displayName: Merge main + env: + BRANCH_NAME: ${{ parameters.branch_name }} + + - bash: npm ci + displayName: npm ci + + - bash: npx hereby validate --all + displayName: hereby validate --all + + - bash: | + set -euo pipefail + if ! git diff --quiet || ! git diff --cached --quiet; then + echo "Validation modified the worktree; refusing to push the merge." >&2 + git status --short + exit 1 + fi + displayName: Verify clean merge + + - template: /tools/pipelines/steps/create-github-app-token.yml@self + parameters: + azureSubscription: typescript-automation-signing + repositories: TypeScript + ${{ if eq(parameters.operation, 'cherry-pick') }}: + permissions: contents:write,issues:write,pull_requests:write + ${{ else }}: + permissions: contents:write,issues:write + condition: not(canceled()) + insertSteps: + - bash: | + set -euo pipefail + basic_auth="$(node -e 'process.stdout.write(Buffer.from("x-access-token:" + process.env.GH_TOKEN).toString("base64"))')" + echo "##vso[task.setsecret]$basic_auth" + git remote set-url origin https://github.com/microsoft/TypeScript.git + git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${basic_auth}" + displayName: Configure git for GitHub App token + env: + GH_TOKEN: $(GH_TOKEN) + + - ${{ if eq(parameters.operation, 'cherry-pick') }}: + - bash: node "$AGENT_TEMPDIRECTORY/release-maintenance.mjs" cherry-pick + displayName: Create cherry-pick PR + env: + GH_TOKEN: $(GH_TOKEN) + PR: ${{ parameters.pr }} + TARGET_BRANCH: ${{ parameters.target_branch }} + REQUESTING_USER: ${{ parameters.requesting_user }} + + - ${{ if eq(parameters.operation, 'new-release-branch') }}: + - bash: git push --set-upstream origin "$BRANCH_NAME" + displayName: Push release branch + env: + BRANCH_NAME: ${{ parameters.branch_name }} + + - ${{ if eq(parameters.operation, 'set-version') }}: + - bash: git push origin "HEAD:refs/heads/$BRANCH_NAME" + displayName: Push release branch + condition: and(succeeded(), eq(variables['ReleaseConfigChanged'], 'true')) + env: + BRANCH_NAME: ${{ parameters.branch_name }} + + - ${{ if eq(parameters.operation, 'sync-branch') }}: + - bash: git push origin "HEAD:refs/heads/$BRANCH_NAME" + displayName: Push release branch + env: + BRANCH_NAME: ${{ parameters.branch_name }} + + - ${{ if ne(parameters.distinct_id, '') }}: + - bash: node "$AGENT_TEMPDIRECTORY/release-maintenance.mjs" post-result + displayName: Post result + condition: not(canceled()) + env: + GH_TOKEN: $(GH_TOKEN) + OPERATION: ${{ parameters.operation }} + BRANCH_NAME: ${{ parameters.branch_name }} + PACKAGE_VERSION: ${{ parameters.package_version }} + CHERRY_PICK_RESULT: $(CherryPickResult) + DISTINCT_ID: ${{ parameters.distinct_id }} + SOURCE_ISSUE: ${{ parameters.source_issue }} + REQUESTING_USER: ${{ parameters.requesting_user }} + STATUS_COMMENT: ${{ parameters.status_comment }} diff --git a/tools/scripts/release-maintenance.mjs b/tools/scripts/release-maintenance.mjs new file mode 100644 index 0000000000000..d393a015f45a1 --- /dev/null +++ b/tools/scripts/release-maintenance.mjs @@ -0,0 +1,231 @@ +import { execFileSync } from "node:child_process"; + +const owner = "microsoft"; +const repo = "TypeScript"; +const botEmail = "290192711+typescript-automation[bot]@users.noreply.github.com"; +const botName = "typescript-automation[bot]"; + +const [command] = process.argv.slice(2); +switch (command) { + case "cherry-pick": + await cherryPick(); + break; + case "post-result": + await postResult(); + break; + default: + throw new Error("Usage: node release-maintenance.mjs "); +} + +async function cherryPick() { + const pr = mustGetEnv("PR"); + const targetBranch = mustGetEnv("TARGET_BRANCH"); + const requestingUser = process.env.REQUESTING_USER; + + const pull = await github("GET", `/repos/${owner}/${repo}/pulls/${+pr}`); + if (!pull.merged || !pull.merge_commit_sha) { + throw new Error(`PR #${pr} has not been merged`); + } + + const pickBranch = `cherry-pick/${pr}/${targetBranch}`; + const title = `🤖 Pick PR #${pr} (${pull.title.substring(0, 35)}${pull.title.length > 35 ? "..." : ""}) into ${targetBranch}`; + + run("git", "config", "user.email", botEmail); + run("git", "config", "user.name", botName); + run("git", "switch", "-c", pickBranch); + + let updatedBaselinesMessage = ""; + try { + run("git", "cherry-pick", "-m", "1", pull.merge_commit_sha); + } + catch (e) { + console.log(e); + + // The cherry-pick failed. If all conflicts are compiler baselines, + // try to run the tests and accept the new baselines. + + const conflictedFiles = output("git", "diff", "--name-only", "--diff-filter=U").split("\n").filter(Boolean); + const baselineDirs = ["tsc/testdata/baselines", "tests/baselines"]; + if (!conflictedFiles.length || conflictedFiles.some(file => !baselineDirs.some(dir => file.startsWith(`${dir}/`)))) { + throw new Error(`Cherry-pick has non-baseline conflicts:\n${conflictedFiles.join("\n")}`); + } + + run("git", "add", "--all", "--", ...conflictedFiles); + run("git", "-c", "core.editor=true", "cherry-pick", "--continue"); + + try { + run("npx", "hereby", "test"); + } + catch { + // Expected to fail. + } + + run("npx", "hereby", "baseline-accept"); + run("npx", "hereby", "test"); + const existingBaselineDirs = baselineDirs.filter(dir => conflictedFiles.some(file => file.startsWith(`${dir}/`))); + run("git", "add", "--all", "--", ...existingBaselineDirs); + try { + run("git", "diff", "--cached", "--quiet"); + } + catch { + run("git", "commit", "-m", "Update baselines"); + } + + updatedBaselinesMessage = " This involved updating baselines; please check the diff."; + } + + run("git", "push", "--force-with-lease", "--set-upstream", "origin", pickBranch); + + const existingPulls = await github("GET", `/repos/${owner}/${repo}/pulls?head=${encodeURIComponent(`${owner}:${pickBranch}`)}`); + + let commentBody; + if (existingPulls.length === 0) { + console.log(`No existing PRs found for ${pickBranch}`); + + const body = `This cherry-pick was triggered by a request on #${pr}.\n\nPlease review the diff and merge if no changes are unexpected.${updatedBaselinesMessage}`; + const newPr = await github("POST", `/repos/${owner}/${repo}/pulls`, { + base: targetBranch, + head: pickBranch, + title, + body, + }); + + await github("POST", `/repos/${owner}/${repo}/issues/${newPr.number}/assignees`, { + assignees: ["DanielRosenwasser"], + }); + + const reviewers = ["DanielRosenwasser", requestingUser].filter(Boolean); + await github("POST", `/repos/${owner}/${repo}/pulls/${newPr.number}/requested_reviewers`, { reviewers }); + + commentBody = `I've created #${newPr.number} for you.${updatedBaselinesMessage}`; + } + else { + const existing = existingPulls[0]; + console.log(`Found existing PR #${existing.number} for ${pickBranch}`); + + await github("PATCH", `/repos/${owner}/${repo}/pulls/${existing.number}`, { title }); + + commentBody = `I've updated #${existing.number} for you.${updatedBaselinesMessage}`; + } + + console.log(`##vso[task.setvariable variable=CherryPickResult]${commentBody}`); +} + +async function postResult() { + const operation = mustGetEnv("OPERATION"); + const branchName = process.env.BRANCH_NAME; + const packageVersion = process.env.PACKAGE_VERSION; + const distinctId = mustGetEnv("DISTINCT_ID"); + const sourceIssue = +mustGetEnv("SOURCE_ISSUE"); + const requestingUser = mustGetEnv("REQUESTING_USER"); + const statusComment = +mustGetEnv("STATUS_COMMENT"); + const jobStatus = mustGetEnv("AGENT_JOBSTATUS"); + + const success = jobStatus === "Succeeded" || jobStatus === "SucceededWithIssues"; + + /** @type {Record} */ + const comments = { + "cherry-pick": [process.env.CHERRY_PICK_RESULT, "I was unable to cherry-pick this PR."], + "new-release-branch": [`I've created ${branchName} with version ${packageVersion} for you.`, "I was unable to create the new release branch."], + "set-version": [`I've set the version of ${branchName} to ${packageVersion} for you.`, "I was unable to set the version."], + "sync-branch": [`I've pulled main into ${branchName} for you.`, `I was unable to merge main into ${branchName}.`], + }; + const [successComment, failureComment] = comments[operation]; + + let commentBody = `Hey, @${requestingUser}! `; + commentBody += success ? successComment : failureComment; + if (!success) { + const logsUrl = `${mustGetEnv("SYSTEM_COLLECTIONURI")}${mustGetEnv("SYSTEM_TEAMPROJECT")}/_build/results?buildId=${mustGetEnv("BUILD_BUILDID")}`; + commentBody += `\n\nCheck the logs at: ${logsUrl}`; + } + + const resultsComment = await github("POST", `/repos/${owner}/${repo}/issues/${sourceIssue}/comments`, { body: commentBody }); + + const emoji = success ? "✅" : "❌"; + const toReplace = ``; + let posted = false; + for (let i = 0; i < 5; i++) { + const oldComment = (await github("GET", `/repos/${owner}/${repo}/issues/comments/${statusComment}`)).body; + if (!oldComment?.includes(toReplace)) { + posted = true; + break; + } + + const newComment = oldComment.replace(toReplace, `[${emoji} Results](${resultsComment.html_url})`); + await github("PATCH", `/repos/${owner}/${repo}/issues/comments/${statusComment}`, { body: newComment }); + + // Repeat; someone may have edited the comment at the same time. + await new Promise(resolve => setTimeout(resolve, 1000)); + } + + if (!posted) { + throw new Error("Failed to update status comment"); + } +} + +/** + * @param {string} method + * @param {string} path + * @param {unknown} [body] + * @returns {Promise} + */ +async function github(method, path, body) { + const token = mustGetEnv("GH_TOKEN"); + for (let attempt = 0;; attempt++) { + let response; + try { + response = await fetch(`https://api.github.com${path}`, { + method, + headers: { + "Accept": "application/vnd.github+json", + "Authorization": `Bearer ${token}`, + "X-GitHub-Api-Version": "2022-11-28", + ...(body === undefined ? {} : { "Content-Type": "application/json" }), + }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + } + catch (e) { + if (attempt < 3) { + await new Promise(resolve => setTimeout(resolve, 2 ** attempt * 1000)); + continue; + } + throw e; + } + if (response.status >= 500 && attempt < 3) { + await new Promise(resolve => setTimeout(resolve, 2 ** attempt * 1000)); + continue; + } + if (!response.ok) { + throw new Error(`${method} ${path} failed: ${response.status} ${response.statusText}: ${await response.text()}`); + } + return response.status === 204 ? undefined : response.json(); + } +} + +/** + * @param {string} name + */ +function mustGetEnv(name) { + const value = process.env[name]; + if (!value) { + throw new Error(`${name} must be set`); + } + return value; +} + +/** + * @param {string} file + * @param {string[]} args + */ +function run(file, ...args) { + execFileSync(file, args, { stdio: "inherit" }); +} + +/** + * @param {string} file + * @param {string[]} args + */ +function output(file, ...args) { + return execFileSync(file, args, { encoding: "utf8" }).trim(); +} From a2a197e46a10146554b6f53525749b3344ff5422 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:10:42 -0800 Subject: [PATCH 2/5] Move release maintenance logic into the script --- tools/pipelines/release-maintenance.yml | 274 +++--------------------- tools/scripts/release-maintenance.mjs | 246 ++++++++++++++++++++- 2 files changed, 267 insertions(+), 253 deletions(-) diff --git a/tools/pipelines/release-maintenance.yml b/tools/pipelines/release-maintenance.yml index 33bfae485ff18..a671058d4b6af 100644 --- a/tools/pipelines/release-maintenance.yml +++ b/tools/pipelines/release-maintenance.yml @@ -44,6 +44,26 @@ variables: value: Iv23li4GolzJSEp1mzHI - name: TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID value: https://jststeam-passwords.vault.azure.net/keys/typescript-automation + - name: OPERATION + value: ${{ parameters.operation }} + - name: PR + value: ${{ parameters.pr }} + - name: TARGET_BRANCH + value: ${{ parameters.target_branch }} + - name: BRANCH_NAME + value: ${{ parameters.branch_name }} + - name: PACKAGE_VERSION + value: ${{ parameters.package_version }} + - name: CORE_MAJOR_MINOR + value: ${{ parameters.core_major_minor }} + - name: DISTINCT_ID + value: ${{ parameters.distinct_id }} + - name: SOURCE_ISSUE + value: ${{ parameters.source_issue }} + - name: REQUESTING_USER + value: ${{ parameters.requesting_user }} + - name: STATUS_COMMENT + value: ${{ parameters.status_comment }} jobs: - ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/main') }}: @@ -61,40 +81,6 @@ jobs: fetchFilter: blob:none fetchTags: false - - bash: git fetch --no-tags origin "+refs/heads/*:refs/remotes/origin/*" - displayName: Fetch branches - - - bash: | - set -euo pipefail - if [[ "$OPERATION" == cherry-pick ]]; then - if ! [[ "$PR" =~ ^[1-9][0-9]*$ ]]; then - echo "pr must be a PR number." >&2 - exit 1 - fi - if [[ -z "$TARGET_BRANCH" ]]; then - echo "target_branch is required." >&2 - exit 1 - fi - else - if ! [[ "$BRANCH_NAME" =~ ^(release-.+|ts[0-9]+-release)$ ]]; then - echo "Release branch name must start with 'release-' or match 'ts-release'." >&2 - exit 1 - fi - if [[ "$OPERATION" != sync-branch && ( -z "$PACKAGE_VERSION" || -z "$CORE_MAJOR_MINOR" ) ]]; then - echo "package_version and core_major_minor are required." >&2 - exit 1 - fi - fi - cp tools/scripts/configure-release.mjs tools/scripts/release-maintenance.mjs "$AGENT_TEMPDIRECTORY/" - displayName: Validate inputs - env: - OPERATION: ${{ parameters.operation }} - PR: ${{ parameters.pr }} - TARGET_BRANCH: ${{ parameters.target_branch }} - BRANCH_NAME: ${{ parameters.branch_name }} - PACKAGE_VERSION: ${{ parameters.package_version }} - CORE_MAJOR_MINOR: ${{ parameters.core_major_minor }} - - task: UseNode@1 displayName: Use Node 24.x inputs: @@ -102,178 +88,23 @@ jobs: - template: /tools/pipelines/steps/setup-go.yml@self - - ${{ if eq(parameters.operation, 'cherry-pick') }}: - - bash: | - set -euo pipefail - git switch --detach "origin/$TARGET_BRANCH" - displayName: Check out target branch - env: - TARGET_BRANCH: ${{ parameters.target_branch }} - - - bash: npm ci - displayName: npm ci - - - ${{ if eq(parameters.operation, 'new-release-branch') }}: - - bash: | - set -euo pipefail - if git show-ref --verify --quiet "refs/remotes/origin/$BRANCH_NAME"; then - echo "Branch $BRANCH_NAME already exists." >&2 - exit 1 - fi - - git switch -c "$BRANCH_NAME" - node "$AGENT_TEMPDIRECTORY/configure-release.mjs" "$PACKAGE_VERSION" "$CORE_MAJOR_MINOR" + - bash: node tools/scripts/release-maintenance.mjs prepare + displayName: Prepare ${{ parameters.operation }} - mapfile -t changedFiles < <(git diff --name-only) - expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") - if [ "${changedFiles[*]}" != "${expectedFiles[*]}" ]; then - echo "Unexpected files in release configuration: ${changedFiles[*]}" >&2 - exit 1 - fi - displayName: Configure release branch - env: - BRANCH_NAME: ${{ parameters.branch_name }} - PACKAGE_VERSION: ${{ parameters.package_version }} - CORE_MAJOR_MINOR: ${{ parameters.core_major_minor }} - - - bash: npm ci - displayName: npm ci - - - bash: npx hereby validate --all - displayName: hereby validate --all - - - bash: | - set -euo pipefail - mapfile -t changedFiles < <(git diff --name-only) - expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") - if [ "${changedFiles[*]}" != "${expectedFiles[*]}" ]; then - echo "Validation produced unexpected changes: ${changedFiles[*]}" >&2 - exit 1 - fi - git add Herebyfile.mjs tsc/internal/core/version.go - git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" - git config user.name "typescript-automation[bot]" - git config core.hooksPath /dev/null - git commit -m "Bump version to $PACKAGE_VERSION" - displayName: Commit release configuration - env: - PACKAGE_VERSION: ${{ parameters.package_version }} - - - ${{ if eq(parameters.operation, 'set-version') }}: - - bash: | - set -euo pipefail - git switch --detach "origin/$BRANCH_NAME" - displayName: Check out release branch - env: - BRANCH_NAME: ${{ parameters.branch_name }} - - - bash: npm ci - displayName: npm ci - - - bash: | - set -euo pipefail - node "$AGENT_TEMPDIRECTORY/configure-release.mjs" "$PACKAGE_VERSION" "$CORE_MAJOR_MINOR" - - mapfile -t changedFiles < <(git diff --name-only) - if [ "${#changedFiles[@]}" -eq 0 ]; then - echo "Version is already $PACKAGE_VERSION." - echo "##vso[task.setvariable variable=ReleaseConfigChanged]false" - exit 0 - fi - - expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") - for changedFile in "${changedFiles[@]}"; do - if [[ ! " ${expectedFiles[*]} " =~ " $changedFile " ]]; then - echo "Unexpected file in release configuration: $changedFile" >&2 - exit 1 - fi - done - echo "##vso[task.setvariable variable=ReleaseConfigChanged]true" - displayName: Configure release version - env: - PACKAGE_VERSION: ${{ parameters.package_version }} - CORE_MAJOR_MINOR: ${{ parameters.core_major_minor }} + - bash: npm ci + displayName: npm ci + - ${{ if ne(parameters.operation, 'cherry-pick') }}: - bash: npx hereby validate --all displayName: hereby validate --all condition: and(succeeded(), eq(variables['ReleaseConfigChanged'], 'true')) - - bash: | - set -euo pipefail - mapfile -t changedFiles < <(git diff --name-only) - expectedFiles=("Herebyfile.mjs" "tsc/internal/core/version.go") - for changedFile in "${changedFiles[@]}"; do - if [[ ! " ${expectedFiles[*]} " =~ " $changedFile " ]]; then - echo "Validation produced unexpected change: $changedFile" >&2 - exit 1 - fi - done - git add Herebyfile.mjs tsc/internal/core/version.go - git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" - git config user.name "typescript-automation[bot]" - git config core.hooksPath /dev/null - git commit -m "Bump version to $PACKAGE_VERSION" - displayName: Commit release configuration + - bash: node "$AGENT_TEMPDIRECTORY/release-maintenance.mjs" commit + ${{ if eq(parameters.operation, 'sync-branch') }}: + displayName: Verify clean merge + ${{ else }}: + displayName: Commit release configuration condition: and(succeeded(), eq(variables['ReleaseConfigChanged'], 'true')) - env: - PACKAGE_VERSION: ${{ parameters.package_version }} - - - ${{ if eq(parameters.operation, 'sync-branch') }}: - - bash: | - set -euo pipefail - git switch --detach "origin/$BRANCH_NAME" - - releaseVersion="$(node -e ' - const source = require("node:fs").readFileSync("tsc/internal/core/version.go", "utf8"); - const match = source.match(/var version = "([^"]+)"/); - if (!match) throw new Error("Unable to read the release version"); - process.stdout.write(match[1]); - ')" - git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" - git config user.name "typescript-automation[bot]" - git config core.hooksPath /dev/null - - if ! git merge origin/main --no-ff --no-commit; then - mapfile -t conflictedFiles < <(git diff --name-only --diff-filter=U) - allowedConflicts=("Herebyfile.mjs" "tsc/internal/core/version.go") - for conflictedFile in "${conflictedFiles[@]}"; do - if [[ ! " ${allowedConflicts[*]} " =~ " $conflictedFile " ]]; then - echo "Merge conflict requires manual resolution: $conflictedFile" >&2 - exit 1 - fi - done - if [ "${#conflictedFiles[@]}" -eq 0 ]; then - echo "Merge failed without reporting conflicted files." >&2 - exit 1 - fi - git checkout --theirs -- "${conflictedFiles[@]}" - fi - - node "$AGENT_TEMPDIRECTORY/configure-release.mjs" "$releaseVersion" - git add Herebyfile.mjs tsc/internal/core/version.go - if git rev-parse --verify --quiet MERGE_HEAD >/dev/null; then - git commit --no-edit - elif ! git diff --cached --quiet; then - git commit -m "Restore release configuration after syncing main" - fi - displayName: Merge main - env: - BRANCH_NAME: ${{ parameters.branch_name }} - - - bash: npm ci - displayName: npm ci - - - bash: npx hereby validate --all - displayName: hereby validate --all - - - bash: | - set -euo pipefail - if ! git diff --quiet || ! git diff --cached --quiet; then - echo "Validation modified the worktree; refusing to push the merge." >&2 - git status --short - exit 1 - fi - displayName: Verify clean merge - template: /tools/pipelines/steps/create-github-app-token.yml@self parameters: @@ -285,55 +116,14 @@ jobs: permissions: contents:write,issues:write condition: not(canceled()) insertSteps: - - bash: | - set -euo pipefail - basic_auth="$(node -e 'process.stdout.write(Buffer.from("x-access-token:" + process.env.GH_TOKEN).toString("base64"))')" - echo "##vso[task.setsecret]$basic_auth" - git remote set-url origin https://github.com/microsoft/TypeScript.git - git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${basic_auth}" - displayName: Configure git for GitHub App token + - bash: node "$AGENT_TEMPDIRECTORY/release-maintenance.mjs" publish + displayName: Publish ${{ parameters.operation }} env: GH_TOKEN: $(GH_TOKEN) - - ${{ if eq(parameters.operation, 'cherry-pick') }}: - - bash: node "$AGENT_TEMPDIRECTORY/release-maintenance.mjs" cherry-pick - displayName: Create cherry-pick PR - env: - GH_TOKEN: $(GH_TOKEN) - PR: ${{ parameters.pr }} - TARGET_BRANCH: ${{ parameters.target_branch }} - REQUESTING_USER: ${{ parameters.requesting_user }} - - - ${{ if eq(parameters.operation, 'new-release-branch') }}: - - bash: git push --set-upstream origin "$BRANCH_NAME" - displayName: Push release branch - env: - BRANCH_NAME: ${{ parameters.branch_name }} - - - ${{ if eq(parameters.operation, 'set-version') }}: - - bash: git push origin "HEAD:refs/heads/$BRANCH_NAME" - displayName: Push release branch - condition: and(succeeded(), eq(variables['ReleaseConfigChanged'], 'true')) - env: - BRANCH_NAME: ${{ parameters.branch_name }} - - - ${{ if eq(parameters.operation, 'sync-branch') }}: - - bash: git push origin "HEAD:refs/heads/$BRANCH_NAME" - displayName: Push release branch - env: - BRANCH_NAME: ${{ parameters.branch_name }} - - ${{ if ne(parameters.distinct_id, '') }}: - bash: node "$AGENT_TEMPDIRECTORY/release-maintenance.mjs" post-result displayName: Post result condition: not(canceled()) env: GH_TOKEN: $(GH_TOKEN) - OPERATION: ${{ parameters.operation }} - BRANCH_NAME: ${{ parameters.branch_name }} - PACKAGE_VERSION: ${{ parameters.package_version }} - CHERRY_PICK_RESULT: $(CherryPickResult) - DISTINCT_ID: ${{ parameters.distinct_id }} - SOURCE_ISSUE: ${{ parameters.source_issue }} - REQUESTING_USER: ${{ parameters.requesting_user }} - STATUS_COMMENT: ${{ parameters.status_comment }} diff --git a/tools/scripts/release-maintenance.mjs b/tools/scripts/release-maintenance.mjs index d393a015f45a1..28049d6ae843c 100644 --- a/tools/scripts/release-maintenance.mjs +++ b/tools/scripts/release-maintenance.mjs @@ -1,20 +1,228 @@ import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; const owner = "microsoft"; const repo = "TypeScript"; const botEmail = "290192711+typescript-automation[bot]@users.noreply.github.com"; const botName = "typescript-automation[bot]"; +const releaseConfigFiles = ["Herebyfile.mjs", "tsc/internal/core/version.go"]; +const releaseBranchPattern = /^(release-.+|ts[0-9]+-release)$/; const [command] = process.argv.slice(2); switch (command) { - case "cherry-pick": - await cherryPick(); + case "prepare": + prepare(); + break; + case "commit": + commit(); + break; + case "publish": + await publish(); break; case "post-result": await postResult(); break; default: - throw new Error("Usage: node release-maintenance.mjs "); + throw new Error("Usage: node release-maintenance.mjs "); +} + +function prepare() { + const operation = mustGetEnv("OPERATION"); + validateInputs(operation); + + // Later steps run from a release branch checkout, so keep main's copies of the scripts. + const tempDir = mustGetEnv("AGENT_TEMPDIRECTORY"); + for (const file of ["configure-release.mjs", "release-maintenance.mjs"]) { + fs.copyFileSync(path.join(import.meta.dirname, file), path.join(tempDir, file)); + } + + run("git", "fetch", "--no-tags", "origin", "+refs/heads/*:refs/remotes/origin/*"); + run("git", "config", "user.email", botEmail); + run("git", "config", "user.name", botName); + + switch (operation) { + case "cherry-pick": + run("git", "switch", "--detach", `origin/${mustGetEnv("TARGET_BRANCH")}`); + return; + case "new-release-branch": + prepareNewReleaseBranch(); + break; + case "set-version": + prepareSetVersion(); + break; + case "sync-branch": + prepareSyncBranch(); + break; + } +} + +/** + * @param {string} operation + */ +function validateInputs(operation) { + if (operation === "cherry-pick") { + if (!/^[1-9][0-9]*$/.test(process.env.PR ?? "")) { + throw new Error("pr must be a PR number."); + } + mustGetEnv("TARGET_BRANCH"); + return; + } + + if (!["new-release-branch", "set-version", "sync-branch"].includes(operation)) { + throw new Error(`Unknown operation: ${operation}`); + } + if (!releaseBranchPattern.test(process.env.BRANCH_NAME ?? "")) { + throw new Error("Release branch name must start with 'release-' or match 'ts-release'."); + } + if (operation !== "sync-branch") { + mustGetEnv("PACKAGE_VERSION"); + mustGetEnv("CORE_MAJOR_MINOR"); + } +} + +function prepareNewReleaseBranch() { + const branchName = mustGetEnv("BRANCH_NAME"); + if (tryRun("git", "show-ref", "--verify", "--quiet", `refs/remotes/origin/${branchName}`)) { + throw new Error(`Branch ${branchName} already exists.`); + } + + run("git", "config", "core.hooksPath", "/dev/null"); + run("git", "switch", "-c", branchName); + configureRelease(mustGetEnv("PACKAGE_VERSION"), mustGetEnv("CORE_MAJOR_MINOR")); + checkChangedFiles("Unexpected files in release configuration", { exact: true }); + setReleaseConfigChanged(true); +} + +function prepareSetVersion() { + run("git", "config", "core.hooksPath", "/dev/null"); + switchToReleaseBranch(); + const packageVersion = mustGetEnv("PACKAGE_VERSION"); + configureRelease(packageVersion, mustGetEnv("CORE_MAJOR_MINOR")); + + if (changedFiles().length === 0) { + console.log(`Version is already ${packageVersion}.`); + setReleaseConfigChanged(false); + return; + } + checkChangedFiles("Unexpected files in release configuration", { exact: false }); + setReleaseConfigChanged(true); +} + +function prepareSyncBranch() { + run("git", "config", "core.hooksPath", "/dev/null"); + switchToReleaseBranch(); + + const versionSource = fs.readFileSync("tsc/internal/core/version.go", "utf8"); + const releaseVersion = /var version = "([^"]+)"/.exec(versionSource)?.[1]; + if (!releaseVersion) { + throw new Error("Unable to read the release version"); + } + + if (!tryRun("git", "merge", "origin/main", "--no-ff", "--no-commit")) { + const conflictedFiles = lines(output("git", "diff", "--name-only", "--diff-filter=U")); + if (conflictedFiles.length === 0) { + throw new Error("Merge failed without reporting conflicted files."); + } + const unexpected = conflictedFiles.filter(file => !releaseConfigFiles.includes(file)); + if (unexpected.length) { + throw new Error(`Merge conflict requires manual resolution:\n${unexpected.join("\n")}`); + } + run("git", "checkout", "--theirs", "--", ...conflictedFiles); + } + + configureRelease(releaseVersion); + run("git", "add", ...releaseConfigFiles); + if (tryRun("git", "rev-parse", "--verify", "--quiet", "MERGE_HEAD")) { + run("git", "commit", "--no-edit"); + } + else if (!tryRun("git", "diff", "--cached", "--quiet")) { + run("git", "commit", "-m", "Restore release configuration after syncing main"); + } + setReleaseConfigChanged(true); +} + +function commit() { + const operation = mustGetEnv("OPERATION"); + if (operation === "sync-branch") { + if (changedFiles().length || !tryRun("git", "diff", "--cached", "--quiet")) { + run("git", "status", "--short"); + throw new Error("Validation modified the worktree; refusing to push the merge."); + } + return; + } + + checkChangedFiles("Validation produced unexpected changes", { exact: operation === "new-release-branch" }); + run("git", "add", ...releaseConfigFiles); + run("git", "commit", "-m", `Bump version to ${mustGetEnv("PACKAGE_VERSION")}`); +} + +async function publish() { + const token = mustGetEnv("GH_TOKEN"); + const basicAuth = Buffer.from(`x-access-token:${token}`).toString("base64"); + console.log(`##vso[task.setsecret]${basicAuth}`); + run("git", "remote", "set-url", "origin", `https://github.com/${owner}/${repo}.git`); + run("git", "config", "--local", "http.https://github.com/.extraheader", `AUTHORIZATION: basic ${basicAuth}`); + + const operation = mustGetEnv("OPERATION"); + const branchName = process.env.BRANCH_NAME; + switch (operation) { + case "cherry-pick": + await cherryPick(); + break; + case "new-release-branch": + run("git", "push", "--set-upstream", "origin", mustGetEnv("BRANCH_NAME")); + break; + case "set-version": + if (process.env.RELEASECONFIGCHANGED !== "true") { + console.log("Version unchanged; nothing to push."); + break; + } + run("git", "push", "origin", `HEAD:refs/heads/${branchName}`); + break; + case "sync-branch": + run("git", "push", "origin", `HEAD:refs/heads/${branchName}`); + break; + } +} + +function switchToReleaseBranch() { + const branchName = mustGetEnv("BRANCH_NAME"); + run("git", "switch", "-C", branchName, `origin/${branchName}`); +} + +/** + * @param {string} version + * @param {string} [expectedMajorMinor] + */ +function configureRelease(version, expectedMajorMinor) { + const script = path.join(mustGetEnv("AGENT_TEMPDIRECTORY"), "configure-release.mjs"); + run("node", script, version, ...(expectedMajorMinor ? [expectedMajorMinor] : [])); +} + +function changedFiles() { + return lines(output("git", "diff", "--name-only")); +} + +/** + * @param {string} message + * @param {{ exact: boolean }} options + */ +function checkChangedFiles(message, { exact }) { + const changed = changedFiles(); + const ok = exact + ? changed.length === releaseConfigFiles.length && releaseConfigFiles.every(file => changed.includes(file)) + : changed.every(file => releaseConfigFiles.includes(file)); + if (!ok) { + throw new Error(`${message}: ${changed.join(" ")}`); + } +} + +/** + * @param {boolean} value + */ +function setReleaseConfigChanged(value) { + console.log(`##vso[task.setvariable variable=ReleaseConfigChanged]${value}`); } async function cherryPick() { @@ -30,8 +238,6 @@ async function cherryPick() { const pickBranch = `cherry-pick/${pr}/${targetBranch}`; const title = `🤖 Pick PR #${pr} (${pull.title.substring(0, 35)}${pull.title.length > 35 ? "..." : ""}) into ${targetBranch}`; - run("git", "config", "user.email", botEmail); - run("git", "config", "user.name", botName); run("git", "switch", "-c", pickBranch); let updatedBaselinesMessage = ""; @@ -44,7 +250,7 @@ async function cherryPick() { // The cherry-pick failed. If all conflicts are compiler baselines, // try to run the tests and accept the new baselines. - const conflictedFiles = output("git", "diff", "--name-only", "--diff-filter=U").split("\n").filter(Boolean); + const conflictedFiles = lines(output("git", "diff", "--name-only", "--diff-filter=U")); const baselineDirs = ["tsc/testdata/baselines", "tests/baselines"]; if (!conflictedFiles.length || conflictedFiles.some(file => !baselineDirs.some(dir => file.startsWith(`${dir}/`)))) { throw new Error(`Cherry-pick has non-baseline conflicts:\n${conflictedFiles.join("\n")}`); @@ -64,10 +270,7 @@ async function cherryPick() { run("npx", "hereby", "test"); const existingBaselineDirs = baselineDirs.filter(dir => conflictedFiles.some(file => file.startsWith(`${dir}/`))); run("git", "add", "--all", "--", ...existingBaselineDirs); - try { - run("git", "diff", "--cached", "--quiet"); - } - catch { + if (!tryRun("git", "diff", "--cached", "--quiet")) { run("git", "commit", "-m", "Update baselines"); } @@ -125,7 +328,7 @@ async function postResult() { /** @type {Record} */ const comments = { - "cherry-pick": [process.env.CHERRY_PICK_RESULT, "I was unable to cherry-pick this PR."], + "cherry-pick": [process.env.CHERRYPICKRESULT, "I was unable to cherry-pick this PR."], "new-release-branch": [`I've created ${branchName} with version ${packageVersion} for you.`, "I was unable to create the new release branch."], "set-version": [`I've set the version of ${branchName} to ${packageVersion} for you.`, "I was unable to set the version."], "sync-branch": [`I've pulled main into ${branchName} for you.`, `I was unable to merge main into ${branchName}.`], @@ -229,3 +432,24 @@ function run(file, ...args) { function output(file, ...args) { return execFileSync(file, args, { encoding: "utf8" }).trim(); } + +/** + * @param {string} file + * @param {string[]} args + */ +function tryRun(file, ...args) { + try { + execFileSync(file, args, { stdio: "inherit" }); + return true; + } + catch { + return false; + } +} + +/** + * @param {string} text + */ +function lines(text) { + return text.split("\n").filter(Boolean); +} From e655de0bbd0aa6c27377e16c1c87fc3af5295022 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:32:52 -0800 Subject: [PATCH 3/5] Restructure release maintenance script around operations --- tools/scripts/release-maintenance.mjs | 252 +++++++++++++------------- 1 file changed, 127 insertions(+), 125 deletions(-) diff --git a/tools/scripts/release-maintenance.mjs b/tools/scripts/release-maintenance.mjs index 28049d6ae843c..fb4076e145689 100644 --- a/tools/scripts/release-maintenance.mjs +++ b/tools/scripts/release-maintenance.mjs @@ -7,7 +7,86 @@ const repo = "TypeScript"; const botEmail = "290192711+typescript-automation[bot]@users.noreply.github.com"; const botName = "typescript-automation[bot]"; const releaseConfigFiles = ["Herebyfile.mjs", "tsc/internal/core/version.go"]; -const releaseBranchPattern = /^(release-.+|ts[0-9]+-release)$/; + +/** + * @typedef {object} Operation + * @property {() => void} validate + * @property {() => boolean} prepare Returns whether the release configuration changed. + * @property {() => void} commit + * @property {() => Promise} publish + * @property {() => string | undefined} successMessage + * @property {() => string} failureMessage + */ + +/** @type {Record} */ +const operations = { + "cherry-pick": { + validate() { + if (!/^[1-9][0-9]*$/.test(process.env.PR ?? "")) { + throw new Error("pr must be a PR number."); + } + mustGetEnv("TARGET_BRANCH"); + }, + prepare() { + run("git", "switch", "--detach", `origin/${mustGetEnv("TARGET_BRANCH")}`); + return false; + }, + commit() {}, + publish: cherryPick, + successMessage: () => process.env.CHERRYPICKRESULT, + failureMessage: () => "I was unable to cherry-pick this PR.", + }, + "new-release-branch": { + validate: () => validateReleaseInputs({ requireVersion: true }), + prepare() { + const branchName = mustGetEnv("BRANCH_NAME"); + if (tryRun("git", "show-ref", "--verify", "--quiet", `refs/remotes/origin/${branchName}`)) { + throw new Error(`Branch ${branchName} already exists.`); + } + run("git", "switch", "-c", branchName); + configureRelease(mustGetEnv("PACKAGE_VERSION"), mustGetEnv("CORE_MAJOR_MINOR")); + checkChangedFiles("Unexpected files in release configuration", { exact: true }); + return true; + }, + commit: () => commitVersionBump({ exact: true }), + publish: pushReleaseBranch, + successMessage: () => `I've created ${process.env.BRANCH_NAME} with version ${process.env.PACKAGE_VERSION} for you.`, + failureMessage: () => "I was unable to create the new release branch.", + }, + "set-version": { + validate: () => validateReleaseInputs({ requireVersion: true }), + prepare() { + switchToReleaseBranch(); + const packageVersion = mustGetEnv("PACKAGE_VERSION"); + configureRelease(packageVersion, mustGetEnv("CORE_MAJOR_MINOR")); + if (changedFiles().length === 0) { + console.log(`Version is already ${packageVersion}.`); + return false; + } + checkChangedFiles("Unexpected files in release configuration", { exact: false }); + return true; + }, + commit: () => commitVersionBump({ exact: false }), + publish: pushReleaseBranch, + successMessage: () => `I've set the version of ${process.env.BRANCH_NAME} to ${process.env.PACKAGE_VERSION} for you.`, + failureMessage: () => "I was unable to set the version.", + }, + "sync-branch": { + validate: () => validateReleaseInputs({ requireVersion: false }), + prepare: mergeMain, + commit() { + if (changedFiles().length || hasStagedChanges()) { + run("git", "status", "--short"); + throw new Error("Validation modified the worktree; refusing to push the merge."); + } + }, + publish: pushReleaseBranch, + successMessage: () => `I've pulled main into ${process.env.BRANCH_NAME} for you.`, + failureMessage: () => `I was unable to merge main into ${process.env.BRANCH_NAME}.`, + }, +}; + +const operation = getOperation(); const [command] = process.argv.slice(2); switch (command) { @@ -15,7 +94,7 @@ switch (command) { prepare(); break; case "commit": - commit(); + operation.commit(); break; case "publish": await publish(); @@ -27,9 +106,16 @@ switch (command) { throw new Error("Usage: node release-maintenance.mjs "); } +function getOperation() { + const name = mustGetEnv("OPERATION"); + if (!Object.hasOwn(operations, name)) { + throw new Error(`Unknown operation: ${name}`); + } + return operations[name]; +} + function prepare() { - const operation = mustGetEnv("OPERATION"); - validateInputs(operation); + operation.validate(); // Later steps run from a release branch checkout, so keep main's copies of the scripts. const tempDir = mustGetEnv("AGENT_TEMPDIRECTORY"); @@ -40,77 +126,40 @@ function prepare() { run("git", "fetch", "--no-tags", "origin", "+refs/heads/*:refs/remotes/origin/*"); run("git", "config", "user.email", botEmail); run("git", "config", "user.name", botName); + run("git", "config", "core.hooksPath", "/dev/null"); - switch (operation) { - case "cherry-pick": - run("git", "switch", "--detach", `origin/${mustGetEnv("TARGET_BRANCH")}`); - return; - case "new-release-branch": - prepareNewReleaseBranch(); - break; - case "set-version": - prepareSetVersion(); - break; - case "sync-branch": - prepareSyncBranch(); - break; - } + const changed = operation.prepare(); + console.log(`##vso[task.setvariable variable=ReleaseConfigChanged]${changed}`); +} + +async function publish() { + const basicAuth = Buffer.from(`x-access-token:${mustGetEnv("GH_TOKEN")}`).toString("base64"); + console.log(`##vso[task.setsecret]${basicAuth}`); + run("git", "remote", "set-url", "origin", `https://github.com/${owner}/${repo}.git`); + run("git", "config", "--local", "http.https://github.com/.extraheader", `AUTHORIZATION: basic ${basicAuth}`); + + await operation.publish(); } /** - * @param {string} operation + * @param {{ requireVersion: boolean }} options */ -function validateInputs(operation) { - if (operation === "cherry-pick") { - if (!/^[1-9][0-9]*$/.test(process.env.PR ?? "")) { - throw new Error("pr must be a PR number."); - } - mustGetEnv("TARGET_BRANCH"); - return; - } - - if (!["new-release-branch", "set-version", "sync-branch"].includes(operation)) { - throw new Error(`Unknown operation: ${operation}`); - } - if (!releaseBranchPattern.test(process.env.BRANCH_NAME ?? "")) { +function validateReleaseInputs({ requireVersion }) { + if (!/^(release-.+|ts[0-9]+-release)$/.test(process.env.BRANCH_NAME ?? "")) { throw new Error("Release branch name must start with 'release-' or match 'ts-release'."); } - if (operation !== "sync-branch") { + if (requireVersion) { mustGetEnv("PACKAGE_VERSION"); mustGetEnv("CORE_MAJOR_MINOR"); } } -function prepareNewReleaseBranch() { +function switchToReleaseBranch() { const branchName = mustGetEnv("BRANCH_NAME"); - if (tryRun("git", "show-ref", "--verify", "--quiet", `refs/remotes/origin/${branchName}`)) { - throw new Error(`Branch ${branchName} already exists.`); - } - - run("git", "config", "core.hooksPath", "/dev/null"); - run("git", "switch", "-c", branchName); - configureRelease(mustGetEnv("PACKAGE_VERSION"), mustGetEnv("CORE_MAJOR_MINOR")); - checkChangedFiles("Unexpected files in release configuration", { exact: true }); - setReleaseConfigChanged(true); -} - -function prepareSetVersion() { - run("git", "config", "core.hooksPath", "/dev/null"); - switchToReleaseBranch(); - const packageVersion = mustGetEnv("PACKAGE_VERSION"); - configureRelease(packageVersion, mustGetEnv("CORE_MAJOR_MINOR")); - - if (changedFiles().length === 0) { - console.log(`Version is already ${packageVersion}.`); - setReleaseConfigChanged(false); - return; - } - checkChangedFiles("Unexpected files in release configuration", { exact: false }); - setReleaseConfigChanged(true); + run("git", "switch", "-C", branchName, `origin/${branchName}`); } -function prepareSyncBranch() { - run("git", "config", "core.hooksPath", "/dev/null"); +function mergeMain() { switchToReleaseBranch(); const versionSource = fs.readFileSync("tsc/internal/core/version.go", "utf8"); @@ -136,59 +185,27 @@ function prepareSyncBranch() { if (tryRun("git", "rev-parse", "--verify", "--quiet", "MERGE_HEAD")) { run("git", "commit", "--no-edit"); } - else if (!tryRun("git", "diff", "--cached", "--quiet")) { + else if (hasStagedChanges()) { run("git", "commit", "-m", "Restore release configuration after syncing main"); } - setReleaseConfigChanged(true); + return true; } -function commit() { - const operation = mustGetEnv("OPERATION"); - if (operation === "sync-branch") { - if (changedFiles().length || !tryRun("git", "diff", "--cached", "--quiet")) { - run("git", "status", "--short"); - throw new Error("Validation modified the worktree; refusing to push the merge."); - } - return; - } - - checkChangedFiles("Validation produced unexpected changes", { exact: operation === "new-release-branch" }); +/** + * @param {{ exact: boolean }} options + */ +function commitVersionBump({ exact }) { + checkChangedFiles("Validation produced unexpected changes", { exact }); run("git", "add", ...releaseConfigFiles); run("git", "commit", "-m", `Bump version to ${mustGetEnv("PACKAGE_VERSION")}`); } -async function publish() { - const token = mustGetEnv("GH_TOKEN"); - const basicAuth = Buffer.from(`x-access-token:${token}`).toString("base64"); - console.log(`##vso[task.setsecret]${basicAuth}`); - run("git", "remote", "set-url", "origin", `https://github.com/${owner}/${repo}.git`); - run("git", "config", "--local", "http.https://github.com/.extraheader", `AUTHORIZATION: basic ${basicAuth}`); - - const operation = mustGetEnv("OPERATION"); - const branchName = process.env.BRANCH_NAME; - switch (operation) { - case "cherry-pick": - await cherryPick(); - break; - case "new-release-branch": - run("git", "push", "--set-upstream", "origin", mustGetEnv("BRANCH_NAME")); - break; - case "set-version": - if (process.env.RELEASECONFIGCHANGED !== "true") { - console.log("Version unchanged; nothing to push."); - break; - } - run("git", "push", "origin", `HEAD:refs/heads/${branchName}`); - break; - case "sync-branch": - run("git", "push", "origin", `HEAD:refs/heads/${branchName}`); - break; +async function pushReleaseBranch() { + if (process.env.RELEASECONFIGCHANGED !== "true") { + console.log("Release configuration unchanged; nothing to push."); + return; } -} - -function switchToReleaseBranch() { - const branchName = mustGetEnv("BRANCH_NAME"); - run("git", "switch", "-C", branchName, `origin/${branchName}`); + run("git", "push", "origin", `HEAD:refs/heads/${mustGetEnv("BRANCH_NAME")}`); } /** @@ -204,6 +221,10 @@ function changedFiles() { return lines(output("git", "diff", "--name-only")); } +function hasStagedChanges() { + return !tryRun("git", "diff", "--cached", "--quiet"); +} + /** * @param {string} message * @param {{ exact: boolean }} options @@ -218,13 +239,6 @@ function checkChangedFiles(message, { exact }) { } } -/** - * @param {boolean} value - */ -function setReleaseConfigChanged(value) { - console.log(`##vso[task.setvariable variable=ReleaseConfigChanged]${value}`); -} - async function cherryPick() { const pr = mustGetEnv("PR"); const targetBranch = mustGetEnv("TARGET_BRANCH"); @@ -270,7 +284,7 @@ async function cherryPick() { run("npx", "hereby", "test"); const existingBaselineDirs = baselineDirs.filter(dir => conflictedFiles.some(file => file.startsWith(`${dir}/`))); run("git", "add", "--all", "--", ...existingBaselineDirs); - if (!tryRun("git", "diff", "--cached", "--quiet")) { + if (hasStagedChanges()) { run("git", "commit", "-m", "Update baselines"); } @@ -315,9 +329,6 @@ async function cherryPick() { } async function postResult() { - const operation = mustGetEnv("OPERATION"); - const branchName = process.env.BRANCH_NAME; - const packageVersion = process.env.PACKAGE_VERSION; const distinctId = mustGetEnv("DISTINCT_ID"); const sourceIssue = +mustGetEnv("SOURCE_ISSUE"); const requestingUser = mustGetEnv("REQUESTING_USER"); @@ -326,17 +337,8 @@ async function postResult() { const success = jobStatus === "Succeeded" || jobStatus === "SucceededWithIssues"; - /** @type {Record} */ - const comments = { - "cherry-pick": [process.env.CHERRYPICKRESULT, "I was unable to cherry-pick this PR."], - "new-release-branch": [`I've created ${branchName} with version ${packageVersion} for you.`, "I was unable to create the new release branch."], - "set-version": [`I've set the version of ${branchName} to ${packageVersion} for you.`, "I was unable to set the version."], - "sync-branch": [`I've pulled main into ${branchName} for you.`, `I was unable to merge main into ${branchName}.`], - }; - const [successComment, failureComment] = comments[operation]; - let commentBody = `Hey, @${requestingUser}! `; - commentBody += success ? successComment : failureComment; + commentBody += success ? operation.successMessage() : operation.failureMessage(); if (!success) { const logsUrl = `${mustGetEnv("SYSTEM_COLLECTIONURI")}${mustGetEnv("SYSTEM_TEAMPROJECT")}/_build/results?buildId=${mustGetEnv("BUILD_BUILDID")}`; commentBody += `\n\nCheck the logs at: ${logsUrl}`; From 91f020d3ab6652ff6fa31ea2857f62a2835cd9e8 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:51:20 -0800 Subject: [PATCH 4/5] Copy release scripts before any step that can fail --- tools/pipelines/release-maintenance.yml | 6 +++++- tools/scripts/release-maintenance.mjs | 6 ------ 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/tools/pipelines/release-maintenance.yml b/tools/pipelines/release-maintenance.yml index a671058d4b6af..e5631351171dd 100644 --- a/tools/pipelines/release-maintenance.yml +++ b/tools/pipelines/release-maintenance.yml @@ -81,6 +81,10 @@ jobs: fetchFilter: blob:none fetchTags: false + # Later steps run from a release branch checkout, so keep main's copies of the scripts. + - bash: cp tools/scripts/configure-release.mjs tools/scripts/release-maintenance.mjs "$AGENT_TEMPDIRECTORY/" + displayName: Copy release scripts + - task: UseNode@1 displayName: Use Node 24.x inputs: @@ -88,7 +92,7 @@ jobs: - template: /tools/pipelines/steps/setup-go.yml@self - - bash: node tools/scripts/release-maintenance.mjs prepare + - bash: node "$AGENT_TEMPDIRECTORY/release-maintenance.mjs" prepare displayName: Prepare ${{ parameters.operation }} - bash: npm ci diff --git a/tools/scripts/release-maintenance.mjs b/tools/scripts/release-maintenance.mjs index fb4076e145689..df2652c886e38 100644 --- a/tools/scripts/release-maintenance.mjs +++ b/tools/scripts/release-maintenance.mjs @@ -117,12 +117,6 @@ function getOperation() { function prepare() { operation.validate(); - // Later steps run from a release branch checkout, so keep main's copies of the scripts. - const tempDir = mustGetEnv("AGENT_TEMPDIRECTORY"); - for (const file of ["configure-release.mjs", "release-maintenance.mjs"]) { - fs.copyFileSync(path.join(import.meta.dirname, file), path.join(tempDir, file)); - } - run("git", "fetch", "--no-tags", "origin", "+refs/heads/*:refs/remotes/origin/*"); run("git", "config", "user.email", botEmail); run("git", "config", "user.name", botName); From 865a19a6be394038a99bfd07d2648c1b5db458f3 Mon Sep 17 00:00:00 2001 From: Jake Bailey <5341706+jakebailey@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:56:57 -0800 Subject: [PATCH 5/5] Move vscode-typescript bump workflow to Azure Pipelines --- .github/workflows/bump-vscode-typescript.yml | 186 ------------------- tools/pipelines/bump-vscode-typescript.yml | 159 ++++++++++++++++ 2 files changed, 159 insertions(+), 186 deletions(-) delete mode 100644 .github/workflows/bump-vscode-typescript.yml create mode 100644 tools/pipelines/bump-vscode-typescript.yml diff --git a/.github/workflows/bump-vscode-typescript.yml b/.github/workflows/bump-vscode-typescript.yml deleted file mode 100644 index 4343a1b1f623d..0000000000000 --- a/.github/workflows/bump-vscode-typescript.yml +++ /dev/null @@ -1,186 +0,0 @@ -name: Bump vscode-typescript - -on: - workflow_dispatch: - inputs: - bump: - description: Version component to bump - required: true - type: choice - options: - - patch - - minor - - major - -run-name: Bump vscode-typescript (${{ inputs.bump }}) - -permissions: - contents: read - -defaults: - run: - shell: bash - -jobs: - prepare: - if: github.repository == 'microsoft/TypeScript' - runs-on: ubuntu-latest - outputs: - source-sha: ${{ steps.source.outputs.sha }} - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: main - filter: blob:none - fetch-depth: 0 - persist-credentials: false - - - name: Record source commit - id: source - run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: 'lts/*' - - - run: npm ci - - - name: Update extension version - env: - BUMP: ${{ inputs.bump }} - run: | - set -euo pipefail - currentVersion="$(jq -r '.version' packages/vscode-typescript/package.json)" - if [ "$currentVersion" = "0.0.0" ] && [ "$BUMP" != "major" ]; then - echo "The first extension release must use a major bump from 0.0.0 to 1.0.0." >&2 - exit 1 - fi - - npm version "$BUMP" \ - --workspace packages/vscode-typescript \ - --no-git-tag-version \ - --package-lock-only - - packageVersion="$(jq -r '.version' packages/vscode-typescript/package.json)" - lockVersion="$(jq -r '.packages["packages/vscode-typescript"].version' package-lock.json)" - if [ "$packageVersion" != "$lockVersion" ]; then - echo "package.json version $packageVersion does not match package-lock.json version $lockVersion." >&2 - exit 1 - fi - - - run: npm test -w packages/vscode-typescript - - - name: Package extension - run: npx hereby vscode-typescript:pack --forRelease --vscodeTypescriptRelease - - - name: Create version bump patch - run: git diff --binary -- packages/vscode-typescript/package.json package-lock.json > vscode-typescript-bump.patch - - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: vscode-typescript-bump - path: vscode-typescript-bump.patch - if-no-files-found: error - - create-pr: - needs: prepare - if: github.repository == 'microsoft/TypeScript' - runs-on: ubuntu-latest - permissions: - contents: read - id-token: write - environment: - name: azure - deployment: false - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ needs.prepare.outputs.source-sha }} - filter: blob:none - fetch-depth: 0 - persist-credentials: false - - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - name: vscode-typescript-bump - path: ${{ runner.temp }} - - - name: Apply version bump - run: | - set -euo pipefail - git apply --index "$RUNNER_TEMP/vscode-typescript-bump.patch" - - mapfile -t changedFiles < <(git diff --cached --name-only) - expectedFiles=("package-lock.json" "packages/vscode-typescript/package.json") - if [ "${changedFiles[*]}" != "${expectedFiles[*]}" ]; then - echo "Unexpected files in version bump: ${changedFiles[*]}" >&2 - exit 1 - fi - - - uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0 - with: - client-id: ${{ vars.AZURE_CLIENT_ID }} - tenant-id: ${{ vars.AZURE_TENANT_ID }} - subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} - - - name: Create GitHub App token - id: app-token - uses: microsoft/create-github-app-token-via-key-vault@5ba0d436e9c3cac52feff4d1f2f66f9698ce4a2d # v1 - with: - client-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_CLIENT_ID }} - key-id: ${{ vars.TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID }} - owner: microsoft - repositories: TypeScript - permission-contents: write - permission-pull-requests: write - - - name: Commit, push, and open pull request - env: - SOURCE_SHA: ${{ needs.prepare.outputs.source-sha }} - GITHUB_APP_TOKEN: ${{ steps.app-token.outputs.token }} - GH_TOKEN: ${{ steps.app-token.outputs.token }} - run: | - set -euo pipefail - EXTENSION_VERSION="$(jq -r '.version' packages/vscode-typescript/package.json)" - branch="vscode-typescript-release/v$EXTENSION_VERSION" - git switch -c "$branch" - git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" - git config user.name "typescript-automation[bot]" - git config core.hooksPath /dev/null - git commit -m "Bump vscode-typescript to $EXTENSION_VERSION" - - basic_auth="$(node -e 'process.stdout.write(Buffer.from("x-access-token:" + process.env.GITHUB_APP_TOKEN).toString("base64"))')" - echo "::add-mask::$basic_auth" - git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${basic_auth}" - - if git ls-remote --exit-code --heads origin "$branch" >/dev/null; then - git fetch origin "refs/heads/$branch:refs/remotes/origin/$branch" - existingCommit="$(git rev-parse "origin/$branch")" - existingParent="$(git rev-parse "origin/$branch^")" - if [ "$existingParent" != "$SOURCE_SHA" ] || ! git diff --quiet HEAD "$existingCommit"; then - echo "Existing branch $branch does not match this release bump." >&2 - exit 1 - fi - else - git push --set-upstream origin "$branch" - fi - - existingPr="$(gh pr list \ - --repo microsoft/TypeScript \ - --base main \ - --head "$branch" \ - --state open \ - --json url \ - --jq '.[0].url // empty')" - if [ -n "$existingPr" ]; then - echo "Pull request already exists: $existingPr" - else - gh pr create \ - --repo microsoft/TypeScript \ - --base main \ - --head "$branch" \ - --title "Bump vscode-typescript to $EXTENSION_VERSION" \ - --body "Updates the vscode-typescript extension to $EXTENSION_VERSION." - fi diff --git a/tools/pipelines/bump-vscode-typescript.yml b/tools/pipelines/bump-vscode-typescript.yml new file mode 100644 index 0000000000000..beb7845c0cf30 --- /dev/null +++ b/tools/pipelines/bump-vscode-typescript.yml @@ -0,0 +1,159 @@ +trigger: none +pr: none + +parameters: + - name: bump + displayName: Version component to bump + type: string + values: + - patch + - minor + - major + +name: $(Date:yyyyMMdd)$(Rev:.r) ${{ parameters.bump }} + +variables: + - name: TYPESCRIPT_AUTOMATION_GITHUB_APP_CLIENT_ID + value: Iv23li4GolzJSEp1mzHI + - name: TYPESCRIPT_AUTOMATION_GITHUB_APP_KEY_ID + value: https://jststeam-passwords.vault.azure.net/keys/typescript-automation + +jobs: + - ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/main') }}: + - job: Prepare + displayName: Prepare version bump + pool: + vmImage: ubuntu-latest + + steps: + - checkout: self + fetchDepth: 1 + fetchTags: false + + - task: UseNode@1 + displayName: Use Node 24.x + inputs: + version: 24.x + + - bash: npm ci + displayName: npm ci + + - bash: | + set -euo pipefail + currentVersion="$(jq -r '.version' packages/vscode-typescript/package.json)" + if [ "$currentVersion" = "0.0.0" ] && [ "$BUMP" != "major" ]; then + echo "The first extension release must use a major bump from 0.0.0 to 1.0.0." >&2 + exit 1 + fi + + npm version "$BUMP" \ + --workspace packages/vscode-typescript \ + --no-git-tag-version \ + --package-lock-only + + packageVersion="$(jq -r '.version' packages/vscode-typescript/package.json)" + lockVersion="$(jq -r '.packages["packages/vscode-typescript"].version' package-lock.json)" + if [ "$packageVersion" != "$lockVersion" ]; then + echo "package.json version $packageVersion does not match package-lock.json version $lockVersion." >&2 + exit 1 + fi + displayName: Update extension version + env: + BUMP: ${{ parameters.bump }} + + - bash: npm test -w packages/vscode-typescript + displayName: Test extension + + - bash: npx hereby vscode-typescript:pack --forRelease --vscodeTypescriptRelease + displayName: Package extension + + - bash: git diff --binary -- packages/vscode-typescript/package.json package-lock.json > "$BUILD_ARTIFACTSTAGINGDIRECTORY/vscode-typescript-bump.patch" + displayName: Create version bump patch + + - publish: $(Build.ArtifactStagingDirectory)/vscode-typescript-bump.patch + artifact: vscode-typescript-bump + displayName: Publish version bump patch + + # This job holds the GitHub token, so it applies the patch without running repository code. + - job: CreatePullRequest + displayName: Create pull request + dependsOn: Prepare + pool: + vmImage: ubuntu-latest + + steps: + - checkout: self + fetchDepth: 0 + fetchFilter: blob:none + fetchTags: false + + - download: current + artifact: vscode-typescript-bump + displayName: Download version bump patch + + - bash: | + set -euo pipefail + git apply --index "$PIPELINE_WORKSPACE/vscode-typescript-bump/vscode-typescript-bump.patch" + + mapfile -t changedFiles < <(git diff --cached --name-only) + expectedFiles=("package-lock.json" "packages/vscode-typescript/package.json") + if [ "${changedFiles[*]}" != "${expectedFiles[*]}" ]; then + echo "Unexpected files in version bump: ${changedFiles[*]}" >&2 + exit 1 + fi + displayName: Apply version bump + + - template: /tools/pipelines/steps/create-github-app-token.yml@self + parameters: + azureSubscription: typescript-automation-signing + repositories: TypeScript + permissions: contents:write,pull_requests:write + insertSteps: + - bash: | + set -euo pipefail + EXTENSION_VERSION="$(jq -r '.version' packages/vscode-typescript/package.json)" + branch="vscode-typescript-release/v$EXTENSION_VERSION" + git switch -c "$branch" + git config user.email "290192711+typescript-automation[bot]@users.noreply.github.com" + git config user.name "typescript-automation[bot]" + git config core.hooksPath /dev/null + git commit -m "Bump vscode-typescript to $EXTENSION_VERSION" + + basic_auth="$(node -e 'process.stdout.write(Buffer.from("x-access-token:" + process.env.GH_TOKEN).toString("base64"))')" + echo "##vso[task.setsecret]$basic_auth" + git remote set-url origin https://github.com/microsoft/TypeScript.git + git config --local http.https://github.com/.extraheader "AUTHORIZATION: basic ${basic_auth}" + + if git ls-remote --exit-code --heads origin "$branch" >/dev/null; then + git fetch origin "refs/heads/$branch:refs/remotes/origin/$branch" + existingCommit="$(git rev-parse "origin/$branch")" + existingParent="$(git rev-parse "origin/$branch^")" + if [ "$existingParent" != "$SOURCE_SHA" ] || ! git diff --quiet HEAD "$existingCommit"; then + echo "Existing branch $branch does not match this release bump." >&2 + exit 1 + fi + else + git push --set-upstream origin "$branch" + fi + + existingPr="$(gh pr list \ + --repo microsoft/TypeScript \ + --base main \ + --head "$branch" \ + --state open \ + --json url \ + --jq '.[0].url // empty')" + if [ -n "$existingPr" ]; then + echo "Pull request already exists: $existingPr" + else + gh pr create \ + --repo microsoft/TypeScript \ + --base main \ + --head "$branch" \ + --title "Bump vscode-typescript to $EXTENSION_VERSION" \ + --body "Updates the vscode-typescript extension to $EXTENSION_VERSION." + fi + displayName: Commit, push, and open pull request + env: + GH_TOKEN: $(GH_TOKEN) + SOURCE_SHA: $(Build.SourceVersion)