@able-autonomy/able 0.2.3 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/able.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // `able sync` keeps a host's follow-up issues and week records up to date (sync.ts).
5
5
  // `able config --json` prints the host's resolved `able.config.ts` (config.ts).
6
6
  // `able init` brings a project to Able on this machine (src/init.ts); a work in progress.
7
+ // `able release` (and `able bump`) releases the host's packages (src/release/).
7
8
 
8
9
  import { createSign } from 'node:crypto'
9
10
  import { mkdirSync } from 'node:fs'
@@ -92,6 +93,8 @@ async function installationToken(repo: string) {
92
93
 
93
94
  // The bloat diagnostic's names before `able audit bloat`, still accepted until #27: rewritten to it before anything runs.
94
95
  if (process.argv[2] === 'bloat' || process.argv[2] === 'agents') process.argv.splice(2, 1, 'audit', 'bloat')
96
+ // `able bump` is `able release bump`.
97
+ if (process.argv[2] === 'bump') process.argv.splice(2, 1, 'release', 'bump')
95
98
  const [command, ...args] = process.argv.slice(2)
96
99
  if (command === 'sync') {
97
100
  await import('./sync.ts')
@@ -135,6 +138,7 @@ const modules: Record<string, string> = {
135
138
  commit: './src/commit.ts',
136
139
  init: './src/init.ts',
137
140
  push: './src/push.ts',
141
+ release: './src/release/index.ts',
138
142
  ws: './src/workspaces/index.ts',
139
143
  }
140
144
  if (command && modules[command]) {
@@ -155,7 +159,7 @@ if (delegate) {
155
159
  }
156
160
  if (command !== 'gh') {
157
161
  console.error(
158
- "usage: able gh <gh arguments> run gh as Able's GitHub App\n able sync [--dry-run] file follow-ups and write ended weeks' records\n able config [--json] print the host's able.config.ts\n able init [--list|--remove] sets this project up on this machine (WIP)\n able commit \"<message>\" [<path>…] a pathspec commit after the touched folders' checks\n able push pushes this branch with its tags\n able upgrade makes bunx run the latest published able\n able -v prints this able's version\n able ws <new|ls|current|refresh|merge|preview|rm|start|stop|status|take|build|attach> workspaces\n able audit bloat <status|scan|load|blocks|checks|classify|propose|report|show|pick|history|apply|compare> the bloat diagnostic: where each agent-file rule belongs",
162
+ "usage: able gh <gh arguments> run gh as Able's GitHub App\n able sync [--dry-run] file follow-ups and write ended weeks' records\n able config [--json] print the host's able.config.ts\n able init [--list|--remove] sets this project up on this machine (WIP)\n able commit \"<message>\" [<path>…] a pathspec commit after the touched folders' checks\n able push pushes this branch with its tags\n able release <bump|status> releases packages: checks, versions, one commit, tags, push, publish (able bump)\n able upgrade makes bunx run the latest published able\n able -v prints this able's version\n able ws <new|ls|current|refresh|merge|preview|rm|start|stop|status|take|build|attach> workspaces\n able audit bloat <status|scan|load|blocks|checks|classify|propose|report|show|pick|history|apply|compare> the bloat diagnostic: where each agent-file rule belongs",
159
163
  )
160
164
  process.exit(command ? 1 : 0)
161
165
  }
package/config.ts CHANGED
@@ -43,10 +43,33 @@ export interface WorkspacesConfig {
43
43
  resources?: Record<string, { take: Command; auto?: boolean; holder?: Command }>
44
44
  }
45
45
 
46
+ /** Where a package's version lives. Default: its `package.json`. `held`: it never moves; a release tags what
47
+ * `package.json` says. `xcode` and `gradle`: the native project file, from the package's folder, with the version
48
+ * also written into the package's `package.json` when it has one. */
49
+ export type VersionSource = 'held' | { xcode: string; bundleId: string } | { gradle: string }
50
+
51
+ /** One package of the host, keyed in `packages` by its path from the root. Its last path segment names it: in tags
52
+ * (`<segment>@v<version>`) and on the command line, so no two packages share one. */
53
+ export interface PackageConfig {
54
+ /** Run in order in the package's folder (a `cwd` is from there). `commit`: for every commit or merge touching the
55
+ * package, kept fast. `release`: after those, at `able release bump` only (builds, tests). */
56
+ checks?: { commit?: Command[]; release?: Command[] }
57
+ version?: VersionSource
58
+ /** Written once the version moves, from the package's folder: a path is another `package.json` whose version is set
59
+ * too; `{ file, pattern }` writes the version where the pattern matches, `{v}` standing for it (`'**Version: {v}**'`). */
60
+ alsoWrite?: (string | { file: string; pattern: string })[]
61
+ /** Published once tagged and pushed, with `bun publish` on the terminal, so npm's 2FA can ask. */
62
+ publish?: 'npm'
63
+ /** `false`: checked only, never offered by `able release bump` and never tagged. */
64
+ release?: false
65
+ }
66
+
46
67
  export interface AbleConfig {
47
- /** `commit`: per folder from the root (`.` for the root itself), run in order for the folders a commit or a merge
48
- * touches; kept fast. `merge`: run from the root after those, at `able ws merge` only (the cross-package checks).
49
- * Any failure stops it. Release checks (builds, tests) come with the Release module (98). */
68
+ /** Every package checked or released, by path from the root (`.` for the root itself). */
69
+ packages?: Record<string, PackageConfig>
70
+ /** `merge`: run from the root after the commit checks, at `able ws merge` only (the cross-package checks); any
71
+ * failure stops it. `commit`: the old shape of the packages' commit checks, per folder, read only when `packages`
72
+ * is absent. It is going away: move it into `packages`. */
50
73
  checks?: { commit?: Record<string, Command[]>; merge?: Command[] }
51
74
  /** `trailers`: lines such as `Co-Authored-By: …`, added to every commit Able makes with `able commit` and
52
75
  * `able ws new --brief` (and so `able sync`'s); a message that already ends with one is not given it twice. */
@@ -70,6 +93,7 @@ export const trailerArgs = (config: AbleConfig) => (config.commit?.trailers ?? [
70
93
  // types, so a mistyped key fails here rather than being ignored.
71
94
  type Shape = { [key: string]: Shape | true }
72
95
  const shape: Shape = {
96
+ packages: { '*': { checks: { commit: true, release: true }, version: true, alsoWrite: true, publish: true, release: true } },
73
97
  checks: { commit: true, merge: true },
74
98
  commit: { trailers: true },
75
99
  workspaces: {
@@ -116,5 +140,14 @@ export async function loadConfig(root: string): Promise<AbleConfig> {
116
140
  const missing = (['trunk', 'journal'] as const).filter((key) => typeof config?.[key] !== 'string' || !config[key])
117
141
  if (missing.length) fail(`${path} is missing ${missing.join(', ')}`)
118
142
  if (config?.knowledge !== undefined && (typeof config.knowledge !== 'string' || !config.knowledge)) fail(`${path}: knowledge must be a folder name`)
143
+ if (config?.packages && config.checks?.commit) fail(`${path}: checks.commit and packages are both set; move checks.commit into packages`)
144
+ const released = Object.entries(config?.packages ?? {}).filter(([, c]) => c.release !== false)
145
+ if (released.some(([p]) => segmentOf(p) === '.')) fail(`${path}: the root package (.) can't be released, its tag would have no name; give it release: false`)
146
+ const segments = released.map(([p]) => segmentOf(p))
147
+ const twice = [...new Set(segments.filter((s, i) => segments.indexOf(s) !== i))]
148
+ if (twice.length) fail(`${path}: two packages end in ${twice.join(', ')}; tags and short names use the last path segment, so each must be unique`)
119
149
  return config as AbleConfig
120
150
  }
151
+
152
+ /** A package's short name, the last segment of its path: what its tags carry and the command line accepts. */
153
+ export const segmentOf = (path: string) => path.split('/').filter(Boolean).pop() ?? path
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@able-autonomy/able",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "Able's command line and the config types a host's able.config.ts uses",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,5 +20,8 @@
20
20
  ],
21
21
  "publishConfig": {
22
22
  "access": "public"
23
+ },
24
+ "dependencies": {
25
+ "@clack/prompts": "^0.11.0"
23
26
  }
24
27
  }
@@ -0,0 +1,53 @@
1
+ // Commit checks come from `packages`, or from the old top-level `checks.commit` while hosts switch: the same checks run
2
+ // either way, at `able commit` and at `able ws merge`.
3
+
4
+ import { expect, test } from 'bun:test'
5
+ import { commit, git, host, run, write } from './workspaces/fixture.ts'
6
+
7
+ const shapes = {
8
+ packages: `packages: { app: { checks: { commit: ['echo checked-app'], release: ['echo released-app'] } }, docs: { checks: { commit: ['echo checked-docs'] }, release: false } }`,
9
+ old: `checks: { commit: { app: ['echo checked-app'], docs: ['echo checked-docs'] } }`,
10
+ }
11
+
12
+ function hostWith(shape: string) {
13
+ const h = host()
14
+ commit(h.main, 'able.config.ts', `export default { trunk: 'main', journal: 'journal', workspaces: { dir: '../ws', ports: { step: 100, max: 9 } }, ${shape} }\n`, 'config')
15
+ git(h.main, 'push', '--quiet', 'origin', 'main')
16
+ return h
17
+ }
18
+
19
+ for (const [name, shape] of Object.entries(shapes)) {
20
+ test(`able commit runs the touched package's commit checks (${name})`, () => {
21
+ const h = hostWith(shape)
22
+ write(h.main, 'app/a.txt', 'a\n')
23
+ const r = run(h.main, 'commit', 'add a', 'app/a.txt', '--yes')
24
+ expect(r.code).toBe(0)
25
+ expect(r.out).toContain('✓ echo checked-app')
26
+ expect(r.out).not.toContain('checked-docs')
27
+ expect(r.out).not.toContain('released-app')
28
+ })
29
+
30
+ test(`able ws merge runs the branch's packages' commit checks (${name})`, () => {
31
+ const h = hostWith(shape)
32
+ run(h.main, 'ws', 'new', 'one', '--no-brief')
33
+ commit(h.ws('one'), 'docs/d.md', 'd\n')
34
+ const r = run(h.ws('one'), 'ws', 'merge', '--yes', '--keep-open')
35
+ expect(r.code).toBe(0)
36
+ expect(r.out).toContain('✓ echo checked-docs')
37
+ expect(r.out).not.toContain('checked-app')
38
+ })
39
+ }
40
+
41
+ test('a config with two packages ending in the same segment is refused', () => {
42
+ const h = hostWith(`packages: { 'apps/ios': {}, 'native/ios': {} }`)
43
+ const r = run(h.main, 'config', '--json')
44
+ expect(r.code).not.toBe(0)
45
+ expect(r.out).toContain('two packages end in ios')
46
+ })
47
+
48
+ test('packages and the old checks.commit together are refused', () => {
49
+ const h = hostWith(`packages: { app: {} }, checks: { commit: { app: ['true'] } }`)
50
+ const r = run(h.main, 'config', '--json')
51
+ expect(r.code).not.toBe(0)
52
+ expect(r.out).toContain('checks.commit and packages are both set')
53
+ })
package/src/checks.ts CHANGED
@@ -1,16 +1,20 @@
1
1
  // A host's commit checks, per folder (decisions 73, 93, 97): only the folders a change touches run theirs, in their own folder.
2
2
 
3
- import type { AbleConfig } from '../config.ts'
3
+ import type { AbleConfig, Command } from '../config.ts'
4
4
  import { runCommand, type Place } from './run.ts'
5
5
  import { bold } from './ui.ts'
6
6
 
7
- /** The folder a path belongs to: the longest `checks.commit` key it sits in, else `.` when the root has checks. */
7
+ /** The commit checks per folder: from `packages`, else from the old top-level `checks.commit`. */
8
+ const commitChecks = (config: AbleConfig): Record<string, Command[]> =>
9
+ config.packages ? Object.fromEntries(Object.entries(config.packages).map(([path, pkg]) => [path, pkg.checks?.commit ?? []])) : (config.checks?.commit ?? {})
10
+
11
+ /** The folder a path belongs to: the longest package path it sits in, else `.` when the root has checks. */
8
12
  export const folderOf = (path: string, folders: string[]) =>
9
13
  folders.filter((f) => f !== '.' && (path === f || path.startsWith(`${f}/`))).sort((a, b) => b.length - a.length)[0] ?? (folders.includes('.') ? '.' : undefined)
10
14
 
11
15
  /** Runs the commit checks of every folder the paths touch; false at the first failure. */
12
16
  export function runChecks(config: AbleConfig, paths: string[], at: Place): boolean {
13
- const checks = config.checks?.commit ?? {}
17
+ const checks = commitChecks(config)
14
18
  const folders = [...new Set(paths.map((p) => folderOf(p, Object.keys(checks))).filter((f): f is string => Boolean(f)))].sort()
15
19
  for (const folder of folders) {
16
20
  console.log(`\n ${bold(folder)}`)
package/src/commit.ts CHANGED
@@ -11,7 +11,7 @@ import { existsSync } from 'node:fs'
11
11
  import { join, relative, resolve } from 'node:path'
12
12
  import { loadConfig, trailerArgs } from '../config.ts'
13
13
  import { runChecks } from './checks.ts'
14
- import { failOnMerge, git, gitLoud } from './git.ts'
14
+ import { changedPaths, failOnMerge, git, gitLoud } from './git.ts'
15
15
  import { status, working } from './status.ts'
16
16
  import { bold, cancel, confirm, dim, fail, green } from './ui.ts'
17
17
  import { current, refuseInPreview } from './workspaces/state.ts'
@@ -26,19 +26,7 @@ const root = at.path
26
26
  failOnMerge(root)
27
27
 
28
28
  const scope = named.length ? named.map((p) => relative(root, resolve(p))) : [relative(root, process.cwd()) || '.']
29
- // `-z`: one NUL-ended entry per path, unquoted; a rename or copy is followed by its old path, which goes in too.
30
- const changed = () => {
31
- const entries = git(root, 'status', '--porcelain', '-z', '--untracked-files=all', '--', ...scope)
32
- .split('\0')
33
- .filter(Boolean)
34
- const paths: string[] = []
35
- for (let i = 0; i < entries.length; i++) {
36
- const entry = entries[i] ?? ''
37
- paths.push(entry.slice(3))
38
- if (/[RC]/.test(entry.slice(0, 2))) paths.push(entries[++i] ?? '')
39
- }
40
- return paths
41
- }
29
+ const changed = () => changedPaths(root, scope)
42
30
 
43
31
  const step = working('commit')
44
32
  step('reading what changed')
package/src/git.ts CHANGED
@@ -28,6 +28,21 @@ export const lines = (cwd: string, ...args: string[]) =>
28
28
  /** The number of commits in a range, e.g. `HEAD..origin/main`. */
29
29
  export const count = (cwd: string, ...range: string[]) => Number(git(cwd, 'rev-list', '--count', ...range) || '0')
30
30
 
31
+ /** Every uncommitted path under the pathspecs, untracked files one by one; a rename or copy gives its old path too.
32
+ * `-z`: one NUL-ended entry per path, unquoted, the old path of a rename or copy in the entry after it. */
33
+ export function changedPaths(cwd: string, scope: string[]) {
34
+ const entries = git(cwd, 'status', '--porcelain', '-z', '--untracked-files=all', '--', ...scope)
35
+ .split('\0')
36
+ .filter(Boolean)
37
+ const paths: string[] = []
38
+ for (let i = 0; i < entries.length; i++) {
39
+ const entry = entries[i] ?? ''
40
+ paths.push(entry.slice(3))
41
+ if (/[RC]/.test(entry.slice(0, 2))) paths.push(entries[++i] ?? '')
42
+ }
43
+ return paths
44
+ }
45
+
31
46
  export const dirtyCount = (cwd: string) => lines(cwd, 'status', '--porcelain').length
32
47
 
33
48
  /** Commits reachable from HEAD and from no remote ref: what exists only here. */
@@ -0,0 +1,211 @@
1
+ // able release bump (alias able bump): releases the host's packages, as `packages` in able.config.ts describes them.
2
+ //
3
+ // able release bump pick packages, release them
4
+ // able release bump ios web the same, without the picker (a path or its last segment)
5
+ // able release bump --dry-run runs every check and prints what a release would write; writes nothing
6
+ // able release bump --yes no questions: the preselected packages, --level (patch), no note
7
+ // --level=patch|minor|major the level; asked when not given, unless --yes
8
+ //
9
+ // It runs in the main checkout, on the trunk, when local and origin match after a fetch, so what it releases is what
10
+ // origin has. The picker preselects every package with uncommitted files or commits since its last tag. For the
11
+ // selected ones the commit checks, then the release checks, run first; only when all pass does any version move.
12
+ // Then one commit holds the new versions and each selected package's uncommitted files, one annotated tag per package
13
+ // marks it, the commit and tags are pushed together, and only then is a `publish: 'npm'` package published: npm never
14
+ // holds a version origin lacks.
15
+
16
+ import * as p from '@clack/prompts'
17
+ import { existsSync, writeFileSync } from 'node:fs'
18
+ import { join, relative } from 'node:path'
19
+ import { loadConfig } from '../../config.ts'
20
+ import { changedPaths, count, failOnMerge, git, gitQuiet, gitLoud, lines, unpushedOnTrunk } from '../git.ts'
21
+ import { folderOf } from '../checks.ts'
22
+ import { status } from '../status.ts'
23
+ import { bold, cancel, dim, fail, green, yellow } from '../ui.ts'
24
+ import { current, refuseInPreview } from '../workspaces/state.ts'
25
+ import { commitsSinceTag, dirtyIn, releasable, tagExists, tagOf, type Pkg } from './packages.ts'
26
+ import { heading, step } from './steps.ts'
27
+ import { LEVELS, plan, shown, type Level, type Plan } from './versions.ts'
28
+
29
+ const argv = process.argv.slice(4)
30
+ // A flag this does not know is refused, never ignored: a mistyped dry-run flag would start a real release.
31
+ const FLAGS = ['--dry-run', '--dry', '--yes']
32
+ const unknownFlag = argv.find((a) => a.startsWith('-') && !FLAGS.includes(a) && !a.startsWith('--level='))
33
+ if (unknownFlag) fail(`unknown flag ${unknownFlag}; one of ${FLAGS.join(', ')}, --level=patch|minor|major`)
34
+ const dryRun = argv.includes('--dry-run') || argv.includes('--dry')
35
+ const yes = argv.includes('--yes')
36
+ const levelArg = argv.find((a) => a.startsWith('--level='))?.slice('--level='.length)
37
+ if (levelArg !== undefined && !LEVELS.includes(levelArg as Level)) fail(`--level=${levelArg}: one of ${LEVELS.join(', ')}`)
38
+ const named = argv.filter((a) => !a.startsWith('-'))
39
+
40
+ const at = await current()
41
+ refuseInPreview(at, 'able release bump')
42
+ const root = at.path
43
+ const config = await loadConfig(root)
44
+ const trunk = config.trunk
45
+
46
+ // A dry run carries on past what would stop a release, saying so, so it can be tried anywhere.
47
+ const refuse = (msg: string) => (dryRun ? console.log(yellow(` a release would stop here: ${msg}`)) : fail(msg))
48
+
49
+ console.log(`\n ${bold(`Release${dryRun ? ' (dry run)' : ''}`)} ${dim(`${at.branch} · ${root}`)}`)
50
+ if (at.isWorkspace) refuse(`this is the workspace ${at.slug}; release from the main checkout, after able ws merge`)
51
+ if (at.branch !== trunk) refuse(`on ${at.branch || 'no branch'}; a release is made on ${trunk}`)
52
+ failOnMerge(root)
53
+ if (!gitQuiet(root, 'fetch', '--quiet', 'origin', trunk)) refuse(`couldn't reach origin/${trunk}; a release pushes`)
54
+ else {
55
+ const unpushed = unpushedOnTrunk(root, trunk)
56
+ const unpulled = count(root, `refs/heads/${trunk}..origin/${trunk}`)
57
+ if (unpushed.length || unpulled)
58
+ refuse(
59
+ [
60
+ `local ${trunk} doesn't match origin/${trunk}; push or pull until they match`,
61
+ unpushed.length && ` ${unpushed.length} unpushed:\n${unpushed.map((l) => ` ${l}`).join('\n')}`,
62
+ unpulled && ` ${unpulled} on origin/${trunk} not pulled`,
63
+ ]
64
+ .filter(Boolean)
65
+ .join('\n'),
66
+ )
67
+ }
68
+
69
+ // ── Which packages ────────────────────────────────────────────────────────────
70
+
71
+ const candidates = releasable(config, root)
72
+ if (!candidates.length) fail('no releasable packages: describe them in packages in able.config.ts')
73
+ // Asked once per package: the picker's hints and its preselection both use it.
74
+ const changes = new Map(candidates.map((pkg) => [pkg, { dirty: dirtyIn(root, pkg), since: commitsSinceTag(root, pkg) }]))
75
+ const changed = candidates.filter((pkg) => changes.get(pkg)?.dirty || changes.get(pkg)?.since)
76
+
77
+ const unknown = named.filter((n) => !candidates.some((pkg) => pkg.path === n || pkg.name === n))
78
+ if (unknown.length) fail(`not a releasable package: ${unknown.join(', ')}; one of ${candidates.map((pkg) => pkg.path).join(', ')}`)
79
+
80
+ const ask = async <T>(question: Promise<T | symbol>): Promise<T> => {
81
+ status({ state: 'blocked', kind: 'question' })
82
+ const answer = await question
83
+ status({ state: 'working' })
84
+ return p.isCancel(answer) ? cancel('aborted; nothing written') : answer
85
+ }
86
+
87
+ let selected: Pkg[]
88
+ if (named.length) selected = candidates.filter((pkg) => named.includes(pkg.path) || named.includes(pkg.name))
89
+ else if (yes) selected = changed
90
+ else {
91
+ const hint = (pkg: Pkg) => {
92
+ const { dirty = 0, since = 0 } = changes.get(pkg) ?? {}
93
+ return [dirty && `${dirty} uncommitted`, since && `${since} commit(s) since its last tag`].filter(Boolean).join(' · ') || 'unchanged'
94
+ }
95
+ const picked = await ask(
96
+ p.multiselect({
97
+ message: 'Which packages to release?',
98
+ options: candidates.map((pkg) => ({ value: pkg.path, label: pkg.path, hint: hint(pkg) })),
99
+ initialValues: changed.map((pkg) => pkg.path),
100
+ required: false,
101
+ }),
102
+ )
103
+ selected = candidates.filter((pkg) => picked.includes(pkg.path))
104
+ }
105
+ if (!selected.length) fail(yes ? 'nothing changed since the last tags' : 'nothing selected')
106
+
107
+ const level: Level =
108
+ (levelArg as Level | undefined) ?? (yes ? 'patch' : await ask(p.select({ message: 'Version bump', options: LEVELS.map((l) => ({ value: l, label: l })), initialValue: 'patch' as Level })))
109
+ const note = yes ? '' : ((await ask(p.text({ message: 'Release note (optional)', placeholder: '' }))) ?? '').trim()
110
+
111
+ // ── What it would write ───────────────────────────────────────────────────────
112
+
113
+ interface Release {
114
+ pkg: Pkg
115
+ plan: Plan
116
+ /** Undefined for a held package whose tag already exists. */
117
+ tag?: string
118
+ }
119
+
120
+ const planAll = (): Release[] =>
121
+ selected.map((pkg) => {
122
+ let pl: Plan
123
+ try {
124
+ pl = plan(pkg.config, pkg.dir, level)
125
+ } catch (e) {
126
+ return fail(`${pkg.path}: ${(e as Error).message}; nothing was written`)
127
+ }
128
+ const tag = tagOf(pkg, pl.next.version)
129
+ if (!tagExists(root, tag)) return { pkg, plan: pl, tag }
130
+ if (pkg.config.version === 'held') return { pkg, plan: pl }
131
+ return fail(`${pkg.path}: the tag ${tag} already exists; nothing was written`)
132
+ })
133
+
134
+ let releases = planAll()
135
+ heading(`${releases.length} package(s), ${level}`)
136
+ for (const { pkg, plan: pl, tag } of releases)
137
+ console.log(` ${pkg.path.padEnd(12)} ${pkg.config.version === 'held' ? `${shown(pl.current)} held${tag ? '' : `, ${dim('already tagged')}`}` : `${shown(pl.current)} → ${shown(pl.next)}`}`)
138
+
139
+ const tags = () => releases.flatMap((r) => (r.tag ? [r.tag] : []))
140
+ if (!tags().length) {
141
+ const dirty = selected.filter((pkg) => dirtyIn(root, pkg))
142
+ console.log(`\n nothing to release: every selected package's tag exists${dirty.length ? dim(`; uncommitted in ${dirty.map((pkg) => pkg.path).join(', ')}: able commit`) : ''}\n`)
143
+ status({ state: 'done', msg: 'release: nothing to release' })
144
+ process.exit(0)
145
+ }
146
+
147
+ // ── Every check before any version moves ──────────────────────────────────────
148
+
149
+ for (const pkg of selected) {
150
+ const checks = [...(pkg.config.checks?.commit ?? []).map((c) => ['commit', c] as const), ...(pkg.config.checks?.release ?? []).map((c) => ['release', c] as const)]
151
+ if (!checks.length) continue
152
+ heading(pkg.path)
153
+ for (const [kind, c] of checks) if (!step(c, at, pkg.dir, kind)) fail(`${pkg.path}: a ${kind} check failed; nothing was written`)
154
+ }
155
+ // The checks may have formatted files, so the plans are made again from what is on disk now.
156
+ releases = planAll()
157
+
158
+ const message = `release: ${tags().join(', ')}${note ? ` — ${note}` : ''}`
159
+ const writes = releases.flatMap((r) => r.plan.writes)
160
+ const lockfile = existsSync(join(root, 'bun.lock'))
161
+ const publishing = releases.filter((r) => r.pkg.config.publish === 'npm' && r.tag)
162
+
163
+ if (dryRun) {
164
+ heading('would')
165
+ for (const w of writes) console.log(` write ${relative(root, w.path)}`)
166
+ if (lockfile) console.log(' run bun install --lockfile-only')
167
+ console.log(` commit "${message}"`)
168
+ console.log(` tag ${tags().join(' ')}`)
169
+ console.log(` push the commit and tags to origin/${at.branch}`)
170
+ for (const r of publishing) console.log(` publish ${r.pkg.path} ${r.plan.next.version} to npm`)
171
+ console.log(`\n ${green('✓')} dry run: ${releases.length} package(s) checked, nothing written\n`)
172
+ status({ state: 'done', msg: `release: dry run of ${tags().join(', ')}` })
173
+ process.exit(0)
174
+ }
175
+
176
+ // ── Write, commit, tag, push, publish ─────────────────────────────────────────
177
+
178
+ for (const w of writes) writeFileSync(w.path, w.text)
179
+ if (lockfile && !step('bun install --lockfile-only', at, root, 'lockfile')) fail('bun install --lockfile-only failed; the versions are written, not committed')
180
+
181
+ // Only what is released goes in: a held package with its tag already made carries no files, and a nested package's
182
+ // files stay out of its parent's commit.
183
+ const tagged = releases.filter((r) => r.tag)
184
+ const paths = [...new Set([...tagged.flatMap((r) => r.pkg.spec), ...writes.map((w) => relative(root, w.path)), ...(lockfile ? ['bun.lock'] : [])])]
185
+ if (!gitLoud(root, 'add', '--all', '--', ...paths)) fail('git add failed; the versions are written, not committed')
186
+ // A held package may have nothing to commit: its tag then goes on HEAD as it is.
187
+ const staged = lines(root, 'diff', '--cached', '--name-only', '--', ...paths).length > 0
188
+ if (staged && !gitLoud(root, 'commit', '--quiet', '-m', message, '--', ...paths)) fail('git commit failed; the versions are written, not committed')
189
+ for (const tag of tags()) if (!gitLoud(root, 'tag', '-a', tag, '-m', message)) fail(`git tag ${tag} failed`)
190
+
191
+ // Atomic: the commit and every tag land on origin together, or none of them does; npm waits for it.
192
+ heading(`pushing to origin/${at.branch}`)
193
+ const refs = tags().map((t) => `refs/tags/${t}`)
194
+ if (!gitLoud(root, 'push', '--quiet', '--atomic', 'origin', `HEAD:refs/heads/${at.branch}`, ...refs))
195
+ fail(`push failed; committed and tagged here, nothing published. Push with: git push --atomic origin ${at.branch} ${tags().join(' ')}, then publish`)
196
+
197
+ // On the real terminal, uncaptured: npm's 2FA asks for a code or a browser round-trip.
198
+ for (const r of publishing) {
199
+ heading(`${r.pkg.path}: bun publish ${r.plan.next.version}`)
200
+ status({ state: 'blocked', kind: 'auth', msg: `release: publishing ${r.pkg.path}` })
201
+ const published = Bun.spawnSync(['bun', 'publish', '--access', 'public'], { cwd: r.pkg.dir, stdio: ['inherit', 'inherit', 'inherit'] }).exitCode === 0
202
+ if (!published) fail(`${r.pkg.path}: publish failed; committed, tagged and pushed. Publish with: cd ${r.pkg.path} && bun publish --access public`)
203
+ }
204
+
205
+ console.log(`\n ${green('✓')} ${staged ? git(root, 'log', '--oneline', '-1') : `tagged HEAD: ${tags().join(', ')}`}`)
206
+ // Files outside every package carry no version, so no release ever sweeps them.
207
+ const everyPackage = Object.keys(config.packages ?? {})
208
+ const unowned = changedPaths(root, []).filter((f) => folderOf(f, everyPackage) === undefined)
209
+ if (unowned.length) console.log(`\n ${yellow('not in any package — able commit')}\n${unowned.map((f) => dim(` ${f}`)).join('\n')}`)
210
+ console.log(`\n pushed to origin/${at.branch}${publishing.length ? ', then published' : ''}\n`)
211
+ status({ state: 'done', msg: `release: ${tags().join(', ')}` })
@@ -0,0 +1,5 @@
1
+ # Web
2
+
3
+ **Version: 0.3.1**
4
+
5
+ Install web@0.3.1 (**Version: 0.3.1**).
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "web",
3
+ "version": "0.3.1",
4
+ "private": true
5
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "name": "sub",
3
+ "version": "0.3.1"
4
+ }
@@ -0,0 +1,9 @@
1
+ android {
2
+ namespace = "com.example.app"
3
+ defaultConfig {
4
+ applicationId = "com.example.app"
5
+ minSdk = 26
6
+ versionCode = 41
7
+ versionName = "1.4.2"
8
+ }
9
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "name": "shared",
3
+ "version": "2.0.0"
4
+ }
@@ -0,0 +1,46 @@
1
+ // !$*UTF8*$!
2
+ {
3
+ objects = {
4
+ /* Begin XCBuildConfiguration section */
5
+ A1 /* Release */ = {
6
+ isa = XCBuildConfiguration;
7
+ buildSettings = {
8
+ CURRENT_PROJECT_VERSION = 41;
9
+ MARKETING_VERSION = 1.4.2;
10
+ PRODUCT_BUNDLE_IDENTIFIER = com.example.app;
11
+ PRODUCT_NAME = App;
12
+ };
13
+ name = Release;
14
+ };
15
+ A2 /* Dev */ = {
16
+ isa = XCBuildConfiguration;
17
+ buildSettings = {
18
+ CURRENT_PROJECT_VERSION = 41;
19
+ MARKETING_VERSION = 0.0.6;
20
+ PRODUCT_BUNDLE_IDENTIFIER = com.example.app.dev;
21
+ PRODUCT_NAME = "App Dev";
22
+ };
23
+ name = Dev;
24
+ };
25
+ A3 /* Staging */ = {
26
+ isa = XCBuildConfiguration;
27
+ buildSettings = {
28
+ CURRENT_PROJECT_VERSION = 41;
29
+ MARKETING_VERSION = 1.3.18;
30
+ PRODUCT_BUNDLE_IDENTIFIER = "com.example.app.staging";
31
+ PRODUCT_NAME = "App Staging";
32
+ };
33
+ name = Staging;
34
+ };
35
+ A4 /* Tests */ = {
36
+ isa = XCBuildConfiguration;
37
+ buildSettings = {
38
+ CURRENT_PROJECT_VERSION = 7;
39
+ MARKETING_VERSION = 9.9.9;
40
+ PRODUCT_BUNDLE_IDENTIFIER = com.example.appTests;
41
+ };
42
+ name = Release;
43
+ };
44
+ /* End XCBuildConfiguration section */
45
+ };
46
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "ios",
3
+ "version": "1.4.2",
4
+ "private": true
5
+ }
@@ -0,0 +1,19 @@
1
+ // able release: the Release module (knowledge/product/modules/release.md).
2
+ //
3
+ // able release bump [<package>…] [--dry-run] [--yes] [--level=…] releases packages (alias: able bump)
4
+ // able release status [--json] every releasable package's version and tag
5
+
6
+ const sub = process.argv[3] ?? ''
7
+ const commands: Record<string, () => Promise<unknown>> = {
8
+ bump: () => import('./bump.ts'),
9
+ status: () => import('./status.ts'),
10
+ }
11
+
12
+ const command = commands[sub]
13
+ if (command) await command()
14
+ else {
15
+ console.error(`usage: able release ${Object.keys(commands).join(' | ')}`)
16
+ process.exit(sub ? 1 : 0)
17
+ }
18
+
19
+ export {}
@@ -0,0 +1,42 @@
1
+ // The host's releasable packages, from `packages` in `able.config.ts`, and what git says about each: its last tag,
2
+ // the commits since it and its uncommitted files.
3
+
4
+ import { join } from 'node:path'
5
+ import { segmentOf, type AbleConfig, type PackageConfig } from '../../config.ts'
6
+ import { count, lines } from '../git.ts'
7
+
8
+ export interface Pkg {
9
+ /** From the root, as keyed in `packages`. */
10
+ path: string
11
+ /** The last segment: what tags carry and the command line accepts. */
12
+ name: string
13
+ dir: string
14
+ config: PackageConfig
15
+ /** Its git pathspec: its folder without the packages nested in it, which are released on their own. */
16
+ spec: string[]
17
+ }
18
+
19
+ /** Every package `able release bump` offers, by path: all but the `release: false` ones. */
20
+ export function releasable(config: AbleConfig, root: string): Pkg[] {
21
+ const all = Object.keys(config.packages ?? {})
22
+ const nested = (path: string) => all.filter((o) => o !== path && (path === '.' || o.startsWith(`${path}/`)))
23
+ return Object.entries(config.packages ?? {})
24
+ .filter(([, c]) => c.release !== false)
25
+ .map(([path, c]) => ({ path, name: segmentOf(path), dir: join(root, path), config: c, spec: [path, ...nested(path).map((o) => `:(exclude)${o}`)] }))
26
+ .sort((a, b) => a.path.localeCompare(b.path))
27
+ }
28
+
29
+ export const tagOf = (pkg: Pkg, version: string) => `${pkg.name}@v${version}`
30
+
31
+ export const tagExists = (root: string, tag: string) => lines(root, 'tag', '--list', tag).length > 0
32
+
33
+ /** The package's newest release tag. */
34
+ export const lastTag = (root: string, pkg: Pkg): string | undefined => lines(root, 'tag', '--list', `${pkg.name}@v*`, '--sort=-v:refname')[0]
35
+
36
+ /** Uncommitted files in the package, untracked ones one by one; a rename counts once. */
37
+ export const dirtyIn = (root: string, pkg: Pkg) => lines(root, 'status', '--porcelain', '--untracked-files=all', '--', ...pkg.spec).length
38
+
39
+ /** `tag`: the last tag when already known, `null` for none. */
40
+ export function commitsSinceTag(root: string, pkg: Pkg, tag: string | null = lastTag(root, pkg) ?? null) {
41
+ return count(root, tag ? `${tag}..HEAD` : 'HEAD', '--', ...pkg.spec)
42
+ }
@@ -0,0 +1,164 @@
1
+ // able release bump and status in a scratch host: a bare origin and a main checkout with three packages.
2
+
3
+ import { expect, test } from 'bun:test'
4
+ import { readFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { commit, git, host, run, write } from '../workspaces/fixture.ts'
7
+
8
+ const pkgJson = (name: string, version: string) => `${JSON.stringify({ name, version }, null, 2)}\n`
9
+ const versionOf = (root: string, path: string) => JSON.parse(readFileSync(join(root, path, 'package.json'), 'utf8')).version
10
+
11
+ /** A host releasing `app` (checked) and `lib/core`, with `docs` checked only; `extra` joins `packages` as given. */
12
+ function releaseHost(extra = '') {
13
+ const h = host()
14
+ write(h.main, 'app/package.json', pkgJson('app', '0.1.0'))
15
+ write(h.main, 'lib/core/package.json', pkgJson('core', '1.0.0'))
16
+ write(h.main, 'docs/index.md', '# docs\n')
17
+ git(h.main, 'add', '-A')
18
+ commit(
19
+ h.main,
20
+ 'able.config.ts',
21
+ `export default { trunk: 'main', journal: 'journal', workspaces: { dir: '../ws', ports: { step: 100, max: 9 } }, packages: {
22
+ app: { checks: { commit: ['echo app-commit'], release: ['echo app-release'] } },
23
+ 'lib/core': {},
24
+ docs: { release: false },
25
+ ${extra}
26
+ } }\n`,
27
+ 'start packages',
28
+ )
29
+ git(h.main, 'tag', '-a', 'app@v0.1.0', '-m', 'app')
30
+ git(h.main, 'tag', '-a', 'core@v1.0.0', '-m', 'core')
31
+ git(h.main, 'push', '--quiet', '--atomic', 'origin', 'main', 'app@v0.1.0', 'core@v1.0.0')
32
+ return h
33
+ }
34
+
35
+ const change = (h: ReturnType<typeof host>, path: string) => {
36
+ commit(h.main, path, `${Math.random()}\n`)
37
+ git(h.main, 'push', '--quiet', 'origin', 'main')
38
+ }
39
+
40
+ test('--yes releases what changed since its tag: checks, one commit, a tag, pushed together', () => {
41
+ const h = releaseHost()
42
+ change(h, 'app/src.ts')
43
+ write(h.main, 'app/wip.ts', 'uncommitted\n')
44
+ write(h.main, 'loose.txt', 'outside\n')
45
+ const r = run(h.main, 'release', 'bump', '--yes')
46
+ expect(r.code).toBe(0)
47
+ expect(r.out.indexOf('app-commit')).toBeLessThan(r.out.indexOf('app-release'))
48
+ expect(versionOf(h.main, 'app')).toBe('0.1.1')
49
+ expect(versionOf(h.main, 'lib/core')).toBe('1.0.0')
50
+ expect(git(h.main, 'log', '-1', '--format=%s', 'origin/main')).toBe('release: app@v0.1.1')
51
+ expect(git(h.main, 'show', '--name-only', '--format=', 'HEAD').split('\n').sort()).toEqual(['app/package.json', 'app/wip.ts'])
52
+ expect(git(h.main, 'ls-remote', '--tags', 'origin')).toContain('refs/tags/app@v0.1.1')
53
+ expect(r.out).toContain('not in any package — able commit')
54
+ expect(r.out).toContain('loose.txt')
55
+ })
56
+
57
+ test('named packages skip the picker, by path or last segment, at the level given', () => {
58
+ const h = releaseHost()
59
+ const r = run(h.main, 'bump', 'core', '--yes', '--level=minor')
60
+ expect(r.code).toBe(0)
61
+ expect(versionOf(h.main, 'lib/core')).toBe('1.1.0')
62
+ expect(git(h.main, 'log', '-1', '--format=%s')).toBe('release: core@v1.1.0')
63
+ })
64
+
65
+ test('--dry-run runs the checks and prints the release, writing nothing', () => {
66
+ const h = releaseHost()
67
+ change(h, 'app/src.ts')
68
+ const head = git(h.main, 'rev-parse', 'HEAD')
69
+ const r = run(h.main, 'release', 'bump', '--dry-run', '--yes')
70
+ expect(r.code).toBe(0)
71
+ expect(r.out).toContain('app-release')
72
+ expect(r.out).toContain('0.1.0 → 0.1.1')
73
+ expect(r.out).toContain('commit "release: app@v0.1.1"')
74
+ expect(r.out).toContain('tag app@v0.1.1')
75
+ expect(versionOf(h.main, 'app')).toBe('0.1.0')
76
+ expect(git(h.main, 'rev-parse', 'HEAD')).toBe(head)
77
+ expect(git(h.main, 'tag', '--list', 'app@v0.1.1')).toBe('')
78
+ })
79
+
80
+ test('a failing check writes nothing', () => {
81
+ const h = releaseHost(`broken: { checks: { release: ['echo broke-here && exit 3'] } },`)
82
+ write(h.main, 'broken/package.json', pkgJson('broken', '0.0.1'))
83
+ git(h.main, 'add', '-A')
84
+ git(h.main, 'commit', '--quiet', '-m', 'broken')
85
+ git(h.main, 'push', '--quiet', 'origin', 'main')
86
+ const r = run(h.main, 'release', 'bump', 'broken', 'app', '--yes')
87
+ expect(r.code).not.toBe(0)
88
+ expect(r.out).toContain('broke-here')
89
+ expect(r.out).toContain('nothing was written')
90
+ expect(versionOf(h.main, 'app')).toBe('0.1.0')
91
+ expect(git(h.main, 'status', '--porcelain')).toBe('')
92
+ })
93
+
94
+ test('it refuses in a workspace, off the trunk and with unpushed commits; an unknown flag is refused', () => {
95
+ const h = releaseHost()
96
+ run(h.main, 'ws', 'new', 'one', '--no-brief')
97
+ expect(run(h.ws('one'), 'release', 'bump', 'app', '--yes').out).toContain('this is the workspace one')
98
+ commit(h.main, 'app/x.ts', 'x\n', 'not pushed')
99
+ const unpushed = run(h.main, 'release', 'bump', 'app', '--yes')
100
+ expect(unpushed.code).not.toBe(0)
101
+ expect(unpushed.out).toContain("local main doesn't match origin/main")
102
+ const flag = run(h.main, 'release', 'bump', '--dryrun')
103
+ expect(flag.code).not.toBe(0)
104
+ expect(flag.out).toContain('unknown flag --dryrun')
105
+ expect(versionOf(h.main, 'app')).toBe('0.1.0')
106
+ })
107
+
108
+ test('a held package is tagged at its version once, then has nothing to release', () => {
109
+ const h = releaseHost(`shared: { version: 'held' },`)
110
+ write(h.main, 'shared/package.json', pkgJson('shared', '2.0.0'))
111
+ git(h.main, 'add', '-A')
112
+ git(h.main, 'commit', '--quiet', '-m', 'shared')
113
+ git(h.main, 'push', '--quiet', 'origin', 'main')
114
+ const first = run(h.main, 'release', 'bump', 'shared', '--yes', '--level=major')
115
+ expect(first.code).toBe(0)
116
+ expect(versionOf(h.main, 'shared')).toBe('2.0.0')
117
+ expect(git(h.main, 'ls-remote', '--tags', 'origin')).toContain('refs/tags/shared@v2.0.0')
118
+ expect(git(h.main, 'log', '-1', '--format=%s')).toBe('shared')
119
+ const again = run(h.main, 'release', 'bump', 'shared', '--yes')
120
+ expect(again.code).toBe(0)
121
+ expect(again.out).toContain('nothing to release')
122
+ })
123
+
124
+ test('release status --json lists the releasable packages', () => {
125
+ const h = releaseHost()
126
+ change(h, 'app/src.ts')
127
+ write(h.main, 'lib/core/wip.ts', 'w\n')
128
+ const r = run(h.main, 'release', 'status', '--json')
129
+ expect(r.code).toBe(0)
130
+ expect(JSON.parse(r.out)).toEqual({
131
+ format: 'able.release-status@1',
132
+ packages: [
133
+ { path: 'app', version: '0.1.0', lastTag: 'app@v0.1.0', commitsSinceTag: 1, dirty: 0 },
134
+ { path: 'lib/core', version: '1.0.0', lastTag: 'core@v1.0.0', commitsSinceTag: 0, dirty: 1 },
135
+ ],
136
+ })
137
+ })
138
+
139
+ test("a nested package's files stay out of its parent's release, and so does a held package already tagged", () => {
140
+ const h = releaseHost(`lib: {}, shared: { version: 'held' },`)
141
+ write(h.main, 'lib/package.json', pkgJson('lib', '0.5.0'))
142
+ write(h.main, 'shared/package.json', pkgJson('shared', '2.0.0'))
143
+ git(h.main, 'add', '-A')
144
+ git(h.main, 'commit', '--quiet', '-m', 'lib and shared')
145
+ git(h.main, 'tag', '-a', 'lib@v0.5.0', '-m', 'lib')
146
+ git(h.main, 'tag', '-a', 'shared@v2.0.0', '-m', 'shared')
147
+ git(h.main, 'push', '--quiet', '--atomic', 'origin', 'main', 'lib@v0.5.0', 'shared@v2.0.0')
148
+ write(h.main, 'lib/core/wip.ts', 'core work\n')
149
+ write(h.main, 'shared/wip.ts', 'shared work\n')
150
+ const status = JSON.parse(run(h.main, 'release', 'status', '--json').out).packages
151
+ expect(status.find((p: { path: string }) => p.path === 'lib').dirty).toBe(0)
152
+ const r = run(h.main, 'release', 'bump', 'lib', 'shared', '--yes')
153
+ expect(r.code).toBe(0)
154
+ expect(git(h.main, 'show', '--name-only', '--format=', 'HEAD')).toBe('lib/package.json')
155
+ expect(git(h.main, 'status', '--porcelain')).toContain('lib/core/')
156
+ expect(git(h.main, 'status', '--porcelain')).toContain('shared/')
157
+ })
158
+
159
+ test('a releasable root package is refused', () => {
160
+ const h = releaseHost(`'.': {},`)
161
+ const r = run(h.main, 'release', 'status')
162
+ expect(r.code).not.toBe(0)
163
+ expect(r.out).toContain("the root package (.) can't be released")
164
+ })
@@ -0,0 +1,37 @@
1
+ // able release status [--json]: every releasable package's version, last tag, commits since it and uncommitted files.
2
+ // Read-only, in any checkout. `--json` prints one `able.release-status@1` object, for a host's own release dashboard:
3
+ //
4
+ // { format: 'able.release-status@1', packages: [{ path, version, build?, lastTag?, commitsSinceTag, dirty }] }
5
+ //
6
+ // `dirty` is the number of uncommitted files in the package, untracked ones included.
7
+
8
+ import { hostRoot, loadConfig } from '../../config.ts'
9
+ import { bold, dim, fail } from '../ui.ts'
10
+ import { commitsSinceTag, dirtyIn, lastTag, releasable } from './packages.ts'
11
+ import { readVersion, shown } from './versions.ts'
12
+
13
+ const root = hostRoot()
14
+ const config = await loadConfig(root)
15
+ const packages = releasable(config, root).map((pkg) => {
16
+ let read
17
+ try {
18
+ read = readVersion(pkg.config, pkg.dir)
19
+ } catch (e) {
20
+ return fail(`${pkg.path}: ${(e as Error).message}`)
21
+ }
22
+ const { version, build } = read
23
+ const tag = lastTag(root, pkg)
24
+ return { path: pkg.path, version, ...(build !== undefined && { build }), ...(tag && { lastTag: tag }), commitsSinceTag: commitsSinceTag(root, pkg, tag ?? null), dirty: dirtyIn(root, pkg) }
25
+ })
26
+
27
+ if (process.argv.includes('--json')) console.log(JSON.stringify({ format: 'able.release-status@1', packages }))
28
+ else {
29
+ console.log(`\n ${bold(`${packages.length} package(s)`)}`)
30
+ for (const p of packages)
31
+ console.log(
32
+ ` ${p.path.padEnd(12)} ${shown(p).padEnd(14)} ${dim(
33
+ [p.lastTag ?? 'never tagged', p.commitsSinceTag && `${p.commitsSinceTag} commit(s) since`, p.dirty && `${p.dirty} uncommitted`].filter(Boolean).join(' · '),
34
+ )}`,
35
+ )
36
+ console.log()
37
+ }
@@ -0,0 +1,20 @@
1
+ // The step reporter (decision 48): one line per command, its whole output shown when it fails, through `runCommand`.
2
+ // The terminal's stdin is passed through, but the output is captured, so a prompt shows only once the step ends: a
3
+ // step that must talk to the operator (npm's 2FA) runs on the real terminal instead, as the publish does. It lives
4
+ // with Release, its only user, and moves to core when a second module needs it.
5
+
6
+ import type { Command } from '../../config.ts'
7
+ import { runCommand, type Place } from '../run.ts'
8
+ import { working } from '../status.ts'
9
+ import { bold } from '../ui.ts'
10
+
11
+ const report = working('release')
12
+
13
+ /** Runs one command in `base` (a `cwd` is from there); true when it succeeds. */
14
+ export function step(c: Command, at: Place, base: string, label: string): boolean {
15
+ report(`${label}: ${typeof c === 'string' ? c : c.run}`)
16
+ return runCommand(c, at, { base, label, stdin: 'inherit', tail: Infinity })
17
+ }
18
+
19
+ /** A heading for a group of steps. */
20
+ export const heading = (text: string) => console.log(`\n ${bold(text)}`)
@@ -0,0 +1,101 @@
1
+ // The five ways a release moves a version, each against fixture files: package.json, Xcode, Gradle, held, alsoWrite.
2
+
3
+ import { describe, expect, test } from 'bun:test'
4
+ import { join } from 'node:path'
5
+ import { plan, raise, readXcode } from './versions.ts'
6
+
7
+ const fixtures = join(import.meta.dir, 'fixtures')
8
+ const textOf = (p: ReturnType<typeof plan>, path: string) => p.writes.find((w) => w.path === join(fixtures, path))?.text ?? ''
9
+
10
+ test('raise moves the level and zeroes what is below it', () => {
11
+ expect(raise('1.4.2', 'patch')).toBe('1.4.3')
12
+ expect(raise('1.4.2', 'minor')).toBe('1.5.0')
13
+ expect(raise('1.4.2', 'major')).toBe('2.0.0')
14
+ })
15
+
16
+ describe('1. default: package.json', () => {
17
+ test('its version is raised by the level, and it is the only write', () => {
18
+ const p = plan({}, join(fixtures, 'default'), 'minor')
19
+ expect(p.current).toEqual({ version: '0.3.1' })
20
+ expect(p.next).toEqual({ version: '0.4.0' })
21
+ expect(p.writes.map((w) => w.path)).toEqual([join(fixtures, 'default/package.json')])
22
+ expect(JSON.parse(textOf(p, 'default/package.json'))).toEqual({ name: 'web', version: '0.4.0', private: true })
23
+ })
24
+ })
25
+
26
+ describe('2. Xcode', () => {
27
+ const xcode = { xcode: 'App.xcodeproj/project.pbxproj', bundleId: 'com.example.app' }
28
+ const p = plan({ version: xcode }, join(fixtures, 'xcode'), 'patch')
29
+ const pbx = textOf(p, 'xcode/App.xcodeproj/project.pbxproj')
30
+
31
+ test('the current version and build come from the bare bundle id', () => {
32
+ expect(p.current).toEqual({ version: '1.4.2', build: 41 })
33
+ expect(p.next).toEqual({ version: '1.4.3', build: 42 })
34
+ })
35
+
36
+ test('every channel of the bundle id gets the version and the build, other targets nothing', () => {
37
+ expect(pbx.match(/MARKETING_VERSION = 1\.4\.3;/g)).toHaveLength(3)
38
+ expect(pbx.match(/CURRENT_PROJECT_VERSION = 42;/g)).toHaveLength(3)
39
+ expect(pbx).not.toContain('0.0.6')
40
+ expect(pbx).not.toContain('1.3.18')
41
+ expect(pbx).toContain('MARKETING_VERSION = 9.9.9;')
42
+ expect(pbx).toContain('CURRENT_PROJECT_VERSION = 7;')
43
+ expect(readXcode(pbx, 'com.example.app.staging')).toEqual({ version: '1.4.3', build: 42 })
44
+ })
45
+
46
+ test('the package.json beside it gets the version', () => {
47
+ expect(JSON.parse(textOf(p, 'xcode/package.json')).version).toBe('1.4.3')
48
+ })
49
+
50
+ test('a bundle id with no build settings is refused', () => {
51
+ expect(() => plan({ version: { ...xcode, bundleId: 'com.example.other' } }, join(fixtures, 'xcode'), 'patch')).toThrow('com.example.other')
52
+ })
53
+ })
54
+
55
+ describe('3. Gradle', () => {
56
+ test('versionName is raised by the level and versionCode goes up by 1; no package.json, none written', () => {
57
+ const p = plan({ version: { gradle: 'app/build.gradle.kts' } }, join(fixtures, 'gradle'), 'major')
58
+ expect(p.current).toEqual({ version: '1.4.2', build: 41 })
59
+ expect(p.next).toEqual({ version: '2.0.0', build: 42 })
60
+ expect(p.writes).toHaveLength(1)
61
+ const text = textOf(p, 'gradle/app/build.gradle.kts')
62
+ expect(text).toContain('versionName = "2.0.0"')
63
+ expect(text).toContain('versionCode = 42')
64
+ expect(text).toContain('minSdk = 26')
65
+ })
66
+ })
67
+
68
+ describe('4. held', () => {
69
+ test('the version does not move and nothing is written', () => {
70
+ const p = plan({ version: 'held' }, join(fixtures, 'held'), 'major')
71
+ expect(p.current).toEqual({ version: '2.0.0' })
72
+ expect(p.next).toEqual(p.current)
73
+ expect(p.writes).toEqual([])
74
+ })
75
+ })
76
+
77
+ describe('5. alsoWrite', () => {
78
+ test('a path sets another package.json; a pattern writes the version wherever it matches', () => {
79
+ const p = plan({ alsoWrite: ['sub/package.json', { file: 'README.md', pattern: '**Version: {v}**' }] }, join(fixtures, 'default'), 'patch')
80
+ expect(JSON.parse(textOf(p, 'default/sub/package.json'))).toEqual({ name: 'sub', version: '0.3.2' })
81
+ expect(textOf(p, 'default/README.md')).toBe('# Web\n\n**Version: 0.3.2**\n\nInstall web@0.3.1 (**Version: 0.3.2**).\n')
82
+ })
83
+
84
+ test('two patterns on one file both land', () => {
85
+ const p = plan(
86
+ {
87
+ alsoWrite: [
88
+ { file: 'README.md', pattern: '**Version: {v}**' },
89
+ { file: 'README.md', pattern: 'web@{v}' },
90
+ ],
91
+ },
92
+ join(fixtures, 'default'),
93
+ 'patch',
94
+ )
95
+ expect(textOf(p, 'default/README.md')).toBe('# Web\n\n**Version: 0.3.2**\n\nInstall web@0.3.2 (**Version: 0.3.2**).\n')
96
+ })
97
+
98
+ test('a pattern that matches nothing is refused', () => {
99
+ expect(() => plan({ alsoWrite: [{ file: 'README.md', pattern: 'v{v} released' }] }, join(fixtures, 'default'), 'patch')).toThrow('no match for v{v} released')
100
+ })
101
+ })
@@ -0,0 +1,136 @@
1
+ // Where a package's version lives and how a release moves it: `package.json` (the default), an Xcode project, a Gradle
2
+ // file, or held. Reading and planning only: `plan` returns every file's new text, written by the caller once every
3
+ // check has passed, so a dry run and the tests see exactly what a release would write.
4
+
5
+ import { existsSync, readFileSync } from 'node:fs'
6
+ import { join, resolve } from 'node:path'
7
+ import type { PackageConfig } from '../../config.ts'
8
+
9
+ export type Level = 'patch' | 'minor' | 'major'
10
+ export const LEVELS: Level[] = ['patch', 'minor', 'major']
11
+
12
+ /** A version and, for a native app, its build number. */
13
+ export interface Version {
14
+ version: string
15
+ build?: number
16
+ }
17
+
18
+ /** A file's path and its new text. */
19
+ export interface Write {
20
+ path: string
21
+ text: string
22
+ }
23
+
24
+ /** What a release does to one package: its version now and next, and the files that change. `next` equals `current` when held. */
25
+ export interface Plan {
26
+ current: Version
27
+ next: Version
28
+ writes: Write[]
29
+ }
30
+
31
+ export function raise(version: string, level: Level) {
32
+ const [major = 0, minor = 0, patch = 0] = version.split('.').map((n) => Number.parseInt(n, 10) || 0)
33
+ if (level === 'major') return `${major + 1}.0.0`
34
+ if (level === 'minor') return `${major}.${minor + 1}.0`
35
+ return `${major}.${minor}.${patch + 1}`
36
+ }
37
+
38
+ const read = (path: string) => (existsSync(path) ? readFileSync(path, 'utf8') : fail(`${path} not found`))
39
+ const fail = (message: string): never => {
40
+ throw new Error(message)
41
+ }
42
+ const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
43
+
44
+ /** A version as `{v}` matches it in an `alsoWrite` pattern. */
45
+ const VERSION = String.raw`\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?`
46
+
47
+ // ── package.json ──────────────────────────────────────────────────────────────
48
+
49
+ const readPackage = (path: string): string => {
50
+ const version = JSON.parse(read(path)).version
51
+ return typeof version === 'string' ? version : fail(`${path} has no version`)
52
+ }
53
+
54
+ // ── Xcode ─────────────────────────────────────────────────────────────────────
55
+
56
+ const BLOCKS = /buildSettings = \{[^{}]*\}/gs
57
+ const idIn = (block: string) => block.match(/PRODUCT_BUNDLE_IDENTIFIER = "?([^";]+)"?;/)?.[1]
58
+
59
+ /** The version and build of the bare bundle id's build settings. */
60
+ export function readXcode(text: string, bundleId: string): Version {
61
+ for (const [block] of text.matchAll(BLOCKS)) {
62
+ if (idIn(block) !== bundleId) continue
63
+ const version = block.match(/MARKETING_VERSION = "?([^";]+)"?;/)?.[1]
64
+ const build = block.match(/CURRENT_PROJECT_VERSION = "?(\d+)"?;/)?.[1]
65
+ if (version && build) return { version, build: Number(build) }
66
+ }
67
+ return fail(`no build settings with PRODUCT_BUNDLE_IDENTIFIER = ${bundleId} and both MARKETING_VERSION and CURRENT_PROJECT_VERSION`)
68
+ }
69
+
70
+ /** Sets the version and build in every build settings block of the bundle id or one of its `<bundleId>.<suffix>`
71
+ * channels (`.dev`, `.staging`), so no channel is left frozen at an old version. Other targets are left alone. */
72
+ function writeXcode(text: string, bundleId: string, next: Version) {
73
+ const ours = (id?: string) => id === bundleId || Boolean(id?.startsWith(`${bundleId}.`))
74
+ return text.replace(BLOCKS, (block) =>
75
+ ours(idIn(block))
76
+ ? block.replace(/MARKETING_VERSION = [^;]+;/, `MARKETING_VERSION = ${next.version};`).replace(/CURRENT_PROJECT_VERSION = [^;]+;/, `CURRENT_PROJECT_VERSION = ${next.build};`)
77
+ : block,
78
+ )
79
+ }
80
+
81
+ // ── Gradle ────────────────────────────────────────────────────────────────────
82
+
83
+ // Kotlin script (`versionName = "1.2.3"`) and Groovy (`versionName "1.2.3"`) alike.
84
+ const NAME = /(versionName\s*=?\s*)"([^"]+)"/
85
+ const CODE = /(versionCode\s*=?\s*)(\d+)/
86
+
87
+ function readGradle(text: string): Version {
88
+ const version = text.match(NAME)?.[2]
89
+ const build = text.match(CODE)?.[2]
90
+ return version && build ? { version, build: Number(build) } : fail('no versionName and versionCode')
91
+ }
92
+
93
+ const writeGradle = (text: string, next: Version) => text.replace(NAME, `$1"${next.version}"`).replace(CODE, `$1${next.build}`)
94
+
95
+ // ── alsoWrite ─────────────────────────────────────────────────────────────────
96
+
97
+ /** Writes the version where the pattern matches, its text taken literally and `{v}` standing for a version. */
98
+ function writePattern(text: string, pattern: string, version: string) {
99
+ const [before, after = ''] = pattern.split('{v}')
100
+ const re = new RegExp(`(${escape(before ?? '')})${VERSION}(${escape(after)})`, 'g')
101
+ return re.test(text) ? text.replace(re, `$1${version}$2`) : fail(`no match for ${pattern}`)
102
+ }
103
+
104
+ /** A version as the CLI prints it: `1.4.2`, or `1.4.2 (41)` with a build. */
105
+ export const shown = (v: Version) => `${v.version}${v.build === undefined ? '' : ` (${v.build})`}`
106
+
107
+ // ── A package ─────────────────────────────────────────────────────────────────
108
+
109
+ /** The package's version now, from its version source. */
110
+ export function readVersion(pkg: PackageConfig, dir: string): Version {
111
+ const v = pkg.version
112
+ if (v === undefined || v === 'held') return { version: readPackage(join(dir, 'package.json')) }
113
+ if ('xcode' in v) return readXcode(read(resolve(dir, v.xcode)), v.bundleId)
114
+ return readGradle(read(resolve(dir, v.gradle)))
115
+ }
116
+
117
+ /** The release of one package at a level: its next version and every file it writes. Throws naming what is missing. */
118
+ export function plan(pkg: PackageConfig, dir: string, level: Level): Plan {
119
+ const v = pkg.version
120
+ const current = readVersion(pkg, dir)
121
+ if (v === 'held') return { current, next: current, writes: [] }
122
+ const next: Version = { version: raise(current.version, level), ...(current.build !== undefined && { build: current.build + 1 }) }
123
+ // Each file's text so far, so two entries on one file (a README with two patterns) both land.
124
+ const files = new Map<string, string>()
125
+ const edit = (path: string, change: (text: string) => string) => files.set(path, change(files.get(path) ?? read(path)))
126
+ const setVersion = (text: string) => `${JSON.stringify({ ...JSON.parse(text), version: next.version }, null, 2)}\n`
127
+ const pkgJson = join(dir, 'package.json')
128
+ if (v === undefined || existsSync(pkgJson)) edit(pkgJson, setVersion)
129
+ if (v && 'xcode' in v) edit(resolve(dir, v.xcode), (t) => writeXcode(t, v.bundleId, next))
130
+ if (v && 'gradle' in v) edit(resolve(dir, v.gradle), (t) => writeGradle(t, next))
131
+ for (const entry of pkg.alsoWrite ?? [])
132
+ if (typeof entry === 'string') edit(resolve(dir, entry), setVersion)
133
+ else edit(resolve(dir, entry.file), (t) => writePattern(t, entry.pattern, next.version))
134
+ const writes = [...files].map(([path, text]) => ({ path, text }))
135
+ return { current, next, writes }
136
+ }
package/src/run.ts CHANGED
@@ -22,20 +22,22 @@ export function shellFor(at: Place, run: string, cwd = '.', base = at.path) {
22
22
  }
23
23
 
24
24
  /** Runs one command; reported, its output is shown only when it fails. */
25
- export function runCommand(c: Command, at: Place, { base = at.path, quiet = false } = {}): boolean {
25
+ /** `label` goes before the command on its line; `stdin: 'inherit'` passes the terminal's input through; `tail`: how many
26
+ * lines of a failure's output are shown. */
27
+ export function runCommand(c: Command, at: Place, { base = at.path, quiet = false, label = '', stdin = 'ignore' as 'ignore' | 'inherit', tail = 30 } = {}): boolean {
26
28
  const { run, cwd } = typeof c === 'string' ? { run: c } : c
27
29
  const sh = shellFor(at, run, cwd, base)
28
- const r = Bun.spawnSync(sh.argv, { cwd: sh.cwd, env: sh.env, stdout: 'pipe', stderr: 'pipe' })
30
+ const r = Bun.spawnSync(sh.argv, { cwd: sh.cwd, env: sh.env, stdin, stdout: 'pipe', stderr: 'pipe' })
29
31
  if (quiet) return r.exitCode === 0
30
32
  const where = sh.cwd === at.path ? '' : dim(` (${sh.cwd.slice(at.path.length + 1) || '.'})`)
31
- console.log(` ${r.exitCode === 0 ? '✓' : red('✗')} ${run}${where}`)
33
+ console.log(` ${r.exitCode === 0 ? '✓' : red('✗')} ${label ? `${dim(label)} ` : ''}${run}${where}`)
32
34
  if (r.exitCode !== 0)
33
35
  console.log(
34
36
  dim(
35
37
  `${r.stdout}${r.stderr}`
36
38
  .trim()
37
39
  .split('\n')
38
- .slice(-30)
40
+ .slice(-tail)
39
41
  .map((l) => ` │ ${l}`)
40
42
  .join('\n'),
41
43
  ),