Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 0 additions & 64 deletions .github/workflows/publish-packages.yml

This file was deleted.

163 changes: 163 additions & 0 deletions build/azure-pipelines/changesets.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Opens or updates the "Version Packages" PR while changesets are pending.
// Once that PR is merged, tags the new versions and creates GitHub releases.

import { execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

const pipelinePath = "build/azure-pipelines/changesets.yml";

function requiredEnv(name) {
const value = process.env[name];
if (!value) throw new Error(`${name} is required.`);
return value;
}

const repository = requiredEnv("GITHUB_REPOSITORY");
const token = requiredEnv("GH_TOKEN");
const botName = "typescript-automation[bot]";
const botEmail = "290192711+typescript-automation[bot]@users.noreply.github.com";
const env = {
...process.env,
GITHUB_TOKEN: token,
GIT_AUTHOR_NAME: botName,
GIT_AUTHOR_EMAIL: botEmail,
GIT_COMMITTER_NAME: botName,
GIT_COMMITTER_EMAIL: botEmail,
};

function run(command, args, input, extraEnv) {
console.log(`> ${command} ${args.join(" ")}`);
return execFileSync(command, args, { env: { ...env, ...extraEnv }, input, encoding: "utf8", stdio: ["pipe", "pipe", "inherit"], maxBuffer: 64 * 1024 * 1024 });
}

function changesetOutput(args) {
const outputPath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "changesets-")), "output");
process.stdout.write(run("pnpm", ["changeset", ...args], undefined, { CHANGESETS_OUTPUT: outputPath }));
return fs.existsSync(outputPath) ? fs.readFileSync(outputPath, "utf8") : "";
}

function githubApi(apiPath, method = "GET", body) {
const args = ["api", "--method", method, `repos/${repository}/${apiPath}`];
if (body) args.push("--input", "-");
return JSON.parse(run("gh", args, body && JSON.stringify(body)));
}

const basicAuth = Buffer.from(`x-access-token:${token}`).toString("base64");
console.log(`##vso[task.setsecret]${basicAuth}`);
function push(args) {
run("git", ["push", `https://github.com/${repository}.git`, ...args], undefined, {
GIT_CONFIG_COUNT: "1",
GIT_CONFIG_KEY_0: "http.https://github.com/.extraheader",
GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basicAuth}`,
});
}

// Returns the `## <version>` section of a package's CHANGELOG.md.
// Changesets writes these headings and indents changeset text under
// list items, so a line starting with `#` or `##` always ends a section.
function getChangelogEntry(packageDir, version) {
const changelogPath = path.join(packageDir, "CHANGELOG.md");
if (!fs.existsSync(changelogPath)) return "";

const lines = fs.readFileSync(changelogPath, "utf8").split(/\r?\n/);
const start = lines.findIndex(line => line.trim() === `## ${version}`);
if (start === -1) return "";
const end = lines.findIndex((line, i) => i > start && /^##? /.test(line));
return lines.slice(start + 1, end === -1 ? undefined : end).join("\n").trim();
}

function listPackages() {
return JSON.parse(run("pnpm", ["list", "--recursive", "--depth", "-1", "--json"]));
}

function hasRelease(tag) {
try {
githubApi(`releases/tags/${tag}`);
return true;
}
catch (error) {
if (/"status":\s*"404"/.test(error.stdout ?? "")) return false;
throw error;
}
}

// Tags new package versions, then creates a release for every public
// package whose current version tag has none. Checking all packages lets
// a rerun finish releases for tags pushed by a run that failed partway.
function tagReleases() {
const tags = changesetOutput(["git-tag"]).split("\n").filter(Boolean).map(line => JSON.parse(line));
if (tags.length > 0) push(tags.map(({ tag }) => `refs/tags/${tag}`));

const remoteTags = new Set(
run("git", ["ls-remote", "--tags", `https://github.com/${repository}.git`])
.split("\n")
.map(line => line.split("\t")[1]?.replace(/^refs\/tags\//, ""))
.filter(Boolean),
);
for (const pkg of listPackages()) {
if (pkg.private) continue;
const tag = `${pkg.name}@${pkg.version}`;
if (!remoteTags.has(tag) || hasRelease(tag)) continue;

const body = getChangelogEntry(pkg.path, pkg.version);
if (!body) throw new Error(`No CHANGELOG.md entry found for ${tag}.`);
const release = githubApi("releases", "POST", {
tag_name: tag,
name: tag,
body,
prerelease: pkg.version.includes("-"),
});
console.log(`Created ${release.html_url}`);
}
}

function versionPackages(baseBranch, plan) {
const versionBranch = `changeset-release/${baseBranch}`;
const title = "Version Packages";

run("git", ["switch", "--force-create", versionBranch]);
process.stdout.write(run("pnpm", ["changeset", "version"]));
run("git", ["add", "--all"]);
run("git", ["-c", "core.hooksPath=/dev/null", "commit", "--message", title]);
push(["--force", `HEAD:refs/heads/${versionBranch}`]);

const packageDirs = new Map(listPackages().map(pkg => [pkg.name, pkg.path]));
const lines = [
`This PR was opened by the Changesets pipeline (\`${pipelinePath}\`). When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to ${baseBranch}, this PR will be updated.`,
"",
"# Releases",
"",
];
for (const { name, newVersion, type } of plan.releases) {
if (type === "none") continue;
lines.push(`## ${name}@${newVersion}`, "");
const entry = getChangelogEntry(packageDirs.get(name), newVersion);
if (entry) lines.push(entry, "");
}
const body = lines.join("\n");

const [owner] = repository.split("/");
const query = new URLSearchParams({ state: "open", base: baseBranch, head: `${owner}:${versionBranch}` });
const [existing] = githubApi(`pulls?${query}`);
const pr = existing
? githubApi(`pulls/${existing.number}`, "PATCH", { title, body })
: githubApi("pulls", "POST", { base: baseBranch, head: versionBranch, title, body });
console.log(`${existing ? "Updated" : "Created"} ${pr.html_url}`);
}

const { baseBranch } = JSON.parse(fs.readFileSync(".changeset/config.json", "utf8"));
// `changeset status` compares the working tree against a local base branch.
run("git", ["switch", "--force-create", baseBranch]);
const plan = JSON.parse(changesetOutput(["status"]));

if (plan.changesets.length === 0) {
tagReleases();
}
else if (plan.changesets.every(changeset => changeset.releases.length === 0)) {
console.log("All pending changesets are empty; not creating a version PR.");
}
else {
versionPackages(baseBranch, plan);
}
48 changes: 48 additions & 0 deletions build/azure-pipelines/changesets.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
trigger:
batch: true
branches:
include:
- v2
pr: none

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/v2') }}:
- job: Changesets
displayName: Version or tag packages
pool:
vmImage: ubuntu-latest
steps:
# The changelog generator reads the commit that added each changeset.
- checkout: self
fetchDepth: 0
fetchFilter: blob:none
fetchTags: false

- task: UseNode@1
displayName: Use Node 24.x
inputs:
version: 24.x

- bash: |
set -euo pipefail
npm install --global "$(jq -r '.packageManager' package.json)"
pnpm install --frozen-lockfile
displayName: Install dependencies

- template: /build/azure-pipelines/steps/create-github-app-token.yml@self
parameters:
azureSubscription: typescript-automation-signing
repositories: TypeScript-Website
permissions: contents:write,pull_requests:write
insertSteps:
- bash: node build/azure-pipelines/changesets.mjs
displayName: Version or tag packages
env:
GH_TOKEN: $(GH_TOKEN)
GITHUB_REPOSITORY: microsoft/TypeScript-Website
Loading
Loading