@able-autonomy/able 0.2.2 → 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
@@ -32,6 +32,9 @@ export interface WorkspacesConfig {
32
32
  /** Where a checkout's app answers, printed by `able ws preview` and in `able ws ls --json`:
33
33
  * `http://<slug>.localhost:<port + offset><path>`. */
34
34
  url?: { port: number; path?: string }
35
+ /** The app, run in the foreground in the preview by `able ws preview` once it is built (`--no-serve` skips it);
36
+ * Ctrl-C stops it. A dev server that runs until stopped, such as `just dev`. */
37
+ serve?: Command
35
38
  services?: Record<string, Service>
36
39
  /** Shared resources with one holder at a time on a machine (the tunnel, the devices): `able ws take` runs `take` and
37
40
  * records the holder. An `auto` one is taken by `able ws start` and goes back to its earlier holder at `able ws stop`.
@@ -40,10 +43,33 @@ export interface WorkspacesConfig {
40
43
  resources?: Record<string, { take: Command; auto?: boolean; holder?: Command }>
41
44
  }
42
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
+
43
67
  export interface AbleConfig {
44
- /** `commit`: per folder from the root (`.` for the root itself), run in order for the folders a commit or a merge
45
- * touches; kept fast. `merge`: run from the root after those, at `able ws merge` only (the cross-package checks).
46
- * 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`. */
47
73
  checks?: { commit?: Record<string, Command[]>; merge?: Command[] }
48
74
  /** `trailers`: lines such as `Co-Authored-By: …`, added to every commit Able makes with `able commit` and
49
75
  * `able ws new --brief` (and so `able sync`'s); a message that already ends with one is not given it twice. */
@@ -67,6 +93,7 @@ export const trailerArgs = (config: AbleConfig) => (config.commit?.trailers ?? [
67
93
  // types, so a mistyped key fails here rather than being ignored.
68
94
  type Shape = { [key: string]: Shape | true }
69
95
  const shape: Shape = {
96
+ packages: { '*': { checks: { commit: true, release: true }, version: true, alsoWrite: true, publish: true, release: true } },
70
97
  checks: { commit: true, merge: true },
71
98
  commit: { trailers: true },
72
99
  workspaces: {
@@ -77,6 +104,7 @@ const shape: Shape = {
77
104
  onRemove: true,
78
105
  onPreview: true,
79
106
  url: { port: true, path: true },
107
+ serve: true,
80
108
  services: { '*': { start: true, stop: true, ready: true, needs: true, cwd: true } },
81
109
  resources: { '*': { take: true, auto: true, holder: true } },
82
110
  },
@@ -112,5 +140,14 @@ export async function loadConfig(root: string): Promise<AbleConfig> {
112
140
  const missing = (['trunk', 'journal'] as const).filter((key) => typeof config?.[key] !== 'string' || !config[key])
113
141
  if (missing.length) fail(`${path} is missing ${missing.join(', ')}`)
114
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`)
115
149
  return config as AbleConfig
116
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.2",
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
+ }