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
2 changes: 1 addition & 1 deletion .github/scripts/download-release-artifacts.mts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(version)) {
throw new Error('Invalid release version.')
}
const packages = version.includes('-') ? ['socket'] : ['socket', 'socketsecurity-cli', 'socketsecurity-cli-with-sentry']
const releases = [{ name: process.env['ROOT_ARTIFACT'] ?? 'npm-release-tarballs', receipt: required('ROOT_RECEIPT'), files: packages.map(pkg => `${pkg}-${version}.tgz`) }]
const releases = [{ name: process.env['ROOT_ARTIFACT'] ?? 'npm-release-tarballs', receipt: required('ROOT_RECEIPT'), files: process.env['ROOT_ARTIFACT'] === 'release-bump' ? ['release.patch'] : packages.map(pkg => `${pkg}-${version}.tgz`) }]
if (process.env['NATIVE_RECEIPTS'] !== undefined) {
const receipts = JSON.parse(process.env['NATIVE_RECEIPTS'])
const targets = version.includes('-') ? ['darwin-arm64', 'linux-arm64', 'linux-x64', 'win32-arm64', 'win32-x64'] : []
Expand Down
32 changes: 24 additions & 8 deletions .github/workflows/publish-npm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ name: Publish to npm registry
# CHANGELOG's `## [Unreleased]` section as they land.
# 2. Dispatch with mode=release-pr. The `prepare` job runs
# scripts/release/prepare.mts to pick the next versions and rewrite
# package.json + CHANGELOG.md. With dry-run=true (the default) it only
# the manifest, stable changelog, and screenshots for a new native version. With dry-run=true (the default) it only
# prints the versions. With dry-run=false the `release-pr` job commits the
# release files via the release App onto `npm-publish-v<X.Y.Z>` and opens a
# `chore(release)` PR naming the prepared versions into this branch.
Expand Down Expand Up @@ -673,8 +673,7 @@ jobs:
echo "Approve each staged package with: pnpm run approve:npm <stage-id>"
# Prepare the next version and changelog. This job runs the installed
# toolchain without write credentials and changes only package.json and
# CHANGELOG.md.
# toolchain without write credentials, including native screenshot generation.
prepare:
name: Prepare the release version
if: ${{ inputs.mode == 'release-pr' }}
Expand All @@ -684,7 +683,7 @@ jobs:
contents: read

outputs:
patch: ${{ steps.patch.outputs.patch }}
patch-receipt: ${{ steps.patch.outputs.artifact-id }}:${{ steps.patch.outputs.artifact-digest }}
version: ${{ steps.bump.outputs.version }}
paired-version: ${{ steps.bump.outputs.paired-version }}

Expand All @@ -706,11 +705,19 @@ jobs:
- name: Export the bump as a patch
if: ${{ inputs.dry-run == false }}
id: patch
run: |
echo "patch=$(git diff --binary HEAD -- CHANGELOG.md package.json | base64 -w0)" >> "$GITHUB_OUTPUT"
mkdir -p "$RUNNER_TEMP/release-bump"
git diff --binary HEAD -- CHANGELOG.md package.json test/snapshots/termless > "$RUNNER_TEMP/release-bump/release.patch"
git diff --stat HEAD
- name: Upload the prepared release patch
if: ${{ inputs.dry-run == false }}
id: patch
uses: ./.github/actions/repo/upload-artifact
with:
name: release-bump-${{ github.run_attempt }}
path: ${{ runner.temp }}/release-bump

# Commit the bump via the release App and open the release PR. This job
# installs nothing, so no third-party code shares a job with the App token.
release-pr:
Expand All @@ -721,6 +728,7 @@ jobs:

permissions:
contents: read
actions: read

steps:
# The bump commit's parent is github.sha, so a shallow checkout of it is
Expand All @@ -736,8 +744,16 @@ jobs:

- name: Apply the bump
env:
PATCH_B64: ${{ needs.prepare.outputs.patch }}
run: printf '%s' "$PATCH_B64" | base64 -d | git apply
ROOT_ARTIFACT: release-bump
ROOT_RECEIPT: ${{ needs.prepare.outputs.patch-receipt }}
VERSION: ${{ needs.prepare.outputs.version }}
GH_TOKEN: ${{ github.token }}
DIST_DIRECTORY: ${{ runner.temp }}/release-bump
run: |
node .github/scripts/download-release-artifacts.mts
git apply --index --include=package.json --include=CHANGELOG.md --include='test/snapshots/termless/*.svg' "$DIST_DIRECTORY/release.patch"
# Release bumps may only edit existing regular files.
test -z "$(git diff --cached --summary HEAD)"
- name: Mint release App token
id: release-app
Expand Down
11 changes: 10 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ packageExtensions:
dependencies:
"@protobuf-ts/runtime": "^2.11.1"
overrides:
# The Actions glob walker calls Minimatch.matchOne, which v11 removed.
"@actions/glob@0.7.0>minimatch": "10.2.6"
"@humanfs/node": "0.16.8"
"@octokit/graphql": "$@octokit/graphql"
"@octokit/request-error": "$@octokit/request-error"
Expand Down
18 changes: 15 additions & 3 deletions scripts/ci/upload-artifact.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,21 @@ function artifactHttpsUrl(value) {
}
}

export async function readReleaseTarballs(directory, single = false) {
export async function readReleaseTarballs(
directory,
single = false,
releasePatch = false,
) {
try {
if (!(await lstat(directory)).isDirectory()) {
throw new Error('invalid directory')
}
const names = (await readdir(directory)).sort()
if (
if (releasePatch) {
if (names.length !== 1 || names[0] !== 'release.patch') {
throw new Error('invalid release patch')
}
} else if (
(single
? names.length !== 1
: names.length !== 3 &&
Expand Down Expand Up @@ -165,7 +173,11 @@ export async function uploadReleaseArtifact(config, dependencies = {}) {
const ids = readArtifactBackendIds(token)
const baseUrl = artifactHttpsUrl(env.ACTIONS_RESULTS_URL)
const expiresAt = artifactExpiration(env.GITHUB_RETENTION_DAYS)
const names = await readReleaseTarballs(directory, name.startsWith('native-'))
const names = await readReleaseTarballs(
directory,
name.startsWith('native-'),
/^release-bump-[1-9]\d*$/u.test(name),
)
const scratch = await mkdtemp(
path.join(env.RUNNER_TEMP ?? os.tmpdir(), 'release-artifact-'),
)
Expand Down
33 changes: 7 additions & 26 deletions scripts/release/github-api.mts
Original file line number Diff line number Diff line change
Expand Up @@ -168,32 +168,13 @@ export async function commitViaGithubApi(
): Promise<string> {
const cfg = { __proto__: null, ...config } as CommitViaGithubApiConfig
const gitPath = `/repos/${cfg.repo}/git`
const tree: Array<{
mode: string
path: string
sha: string
type: string
}> = []
for (let i = 0, { length } = cfg.files; i < length; i += 1) {
const file = cfg.files[i]!
// eslint-disable-next-line no-await-in-loop
const blob = await githubRequest<{ sha: string }>({
apiUrl: cfg.apiUrl,
body: {
content: Buffer.from(file.content, 'utf8').toString('base64'),
encoding: 'base64',
},
method: 'POST',
path: `${gitPath}/blobs`,
token: cfg.token,
})
tree.push({
mode: '100644',
path: file.path,
sha: blob!.sha,
type: 'blob',
})
}
// The tree API creates UTF-8 blobs inline, including the native SVGs.
const tree = cfg.files.map(({ content, path }) => ({
content,
mode: '100644',
path,
type: 'blob',
}))
const newTree = await githubRequest<{ sha: string }>({
apiUrl: cfg.apiUrl,
body: { base_tree: cfg.baseTreeSha, tree },
Expand Down
35 changes: 30 additions & 5 deletions scripts/release/open-release-pr.mts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ import {
requireReleaseLane,
resolveReleaseEnv,
} from './release-branch.mts'
import {
nativeReleaseVersionChanged,
readReleasePolicy,
} from '../../src/sea/version.mts'
import { isMainModule } from '../lib/is-main-module.mts'
import { runMain } from '../lib/run-main.mts'

Expand All @@ -38,8 +42,7 @@ const rootPath = path.join(
'..',
)

// The only files a bump may change. Anything else in the diff means the
// derivation job wrote something it should not have.
// Required metadata files for each lane. Native bumps also carry rendered SVGs.
export function bumpFiles(lane: ReleaseLane): string[] {
return lane === 'v2-rc' ? ['package.json'] : ['CHANGELOG.md', 'package.json']
}
Expand All @@ -64,9 +67,24 @@ export async function git(args: readonly string[]): Promise<string> {
export function assertBumpOnly(
changedFiles: readonly string[],
lane: ReleaseLane,
nativeVersionChanged = false,
): void {
const expected = bumpFiles(lane)
const sorted = [...changedFiles].sort()
const snapshotPath =
/^test\/snapshots\/termless\/[\w.-]+\.native\.[\w.-]+\.svg$/u
const sorted = changedFiles
.filter(file => !nativeVersionChanged || !snapshotPath.test(file))
.sort()
if (
nativeVersionChanged &&
!changedFiles.includes(
'test/snapshots/termless/cli.native.socket-version.svg',
)
) {
throw new Error(
'[open-release-pr] The native version changed without its version screenshot.',
)
}
if (
sorted.length !== expected.length ||
sorted.some((file, i) => file !== expected[i])
Expand All @@ -92,7 +110,6 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
const changed = (await git(['diff', '--name-only', 'HEAD']))
.split('\n')
.filter(Boolean)
assertBumpOnly(changed, lane)
const manifest = JSON.parse(
readFileSync(path.join(rootPath, 'package.json'), 'utf8'),
) as { version?: string; socketCliPrereleaseVersion?: string }
Expand Down Expand Up @@ -122,7 +139,15 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
const env = resolveReleaseEnv()
const parentSha = (await git(['rev-parse', 'HEAD'])).trim()
const baseTreeSha = (await git(['rev-parse', 'HEAD^{tree}'])).trim()
const files = bumpFiles(lane).map(relPath => ({
const previous = JSON.parse(await git(['show', 'HEAD:package.json']))
const policy = readReleasePolicy(rootPath)
const nativeVersionChanged = nativeReleaseVersionChanged(
previous,
manifest,
policy,
)
assertBumpOnly(changed, lane, nativeVersionChanged)
const files = changed.map(relPath => ({
content: readFileSync(path.join(rootPath, relPath), 'utf8'),
path: relPath,
}))
Expand Down
27 changes: 26 additions & 1 deletion scripts/release/prepare.mts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* node scripts/release/prepare.mts [--dry-run] [--release-as major|minor|patch]
*/

import { execFileSync } from 'node:child_process'
import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import process from 'node:process'
Expand All @@ -34,7 +35,10 @@ import {
parseConventionalCommits,
releaseVersionsForLine,
} from './version.mts'
import { readReleasePolicy } from '../../src/sea/version.mts'
import {
nativeReleaseVersionChanged,
readReleasePolicy,
} from '../../src/sea/version.mts'
import { isMainModule } from '../lib/is-main-module.mts'
import { runMain } from '../lib/run-main.mts'

Expand Down Expand Up @@ -153,9 +157,18 @@ export function prepareStableChangelog(opts: {
})
}

export function refreshReleaseSnapshots(root: string): void {
execFileSync(
process.execPath,
['scripts/test/native.mts', '--build', '.native.test.mts', '--update'],
{ cwd: root, stdio: 'inherit' },
)
}

async function main(
argv = process.argv.slice(2),
root = rootPath,
refreshSnapshots = refreshReleaseSnapshots,
): Promise<void> {
const { dryRun, releaseAs } = parseArgs(argv)
const laneValue = process.env['SOCKET_CLI_RELEASE_LANE']
Expand Down Expand Up @@ -327,6 +340,12 @@ async function main(
log(`paired native prerelease ${pairedVersion}.`)
}

const nextManifest: PackageJsonShape = JSON.parse(rawManifest)
const nativeVersionChanged = nativeReleaseVersionChanged(
manifest.parsed,
nextManifest,
releasePolicy,
)
const outputs = {
version: derived.version,
...(pairedVersion ? { 'paired-version': pairedVersion } : {}),
Expand All @@ -336,6 +355,9 @@ async function main(
if (promoted) {
process.stdout.write(`${promoted.section}\n`)
}
if (nativeVersionChanged) {
log('Would build the native CLI and refresh its terminal snapshots.')
}
emitOutputs(outputs)
return
}
Expand All @@ -344,6 +366,9 @@ async function main(
if (promoted) {
writeFileSync(changelogPath, promoted.changelog)
}
if (nativeVersionChanged) {
refreshSnapshots(root)
}
log(
`wrote ${derived.version} to package.json${promoted ? ' and CHANGELOG.md' : ''}.`,
)
Expand Down
29 changes: 29 additions & 0 deletions src/sea/version.mts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,35 @@ export function seaVersionForManifestVersion(
return `${policy.versionHint}-${policy.identifier}.0`
}

/** Release preparation and the App writer must agree on which binary changed. */
export function nativeReleaseVersionChanged(
before: {
version?: string | undefined
socketCliPrereleaseVersion?: unknown
},
after: { version?: string | undefined; socketCliPrereleaseVersion?: unknown },
policy: ReleasePolicy,
): boolean {
if (policy.mode !== 'prerelease-only') {
return false
}
if (!before.version || !after.version) {
throw new Error('Expected a version in both release manifests.')
}
return (
seaVersionForManifestVersion(
before.version,
policy,
before.socketCliPrereleaseVersion,
) !==
seaVersionForManifestVersion(
after.version,
policy,
after.socketCliPrereleaseVersion,
)
)
}

export function releasePolicyPath(root = REPOSITORY_ROOT): string {
const candidates = [
path.join(root, '.config/release.json'),
Expand Down
Loading
Loading