@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.
@@ -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
  ),
@@ -6,7 +6,9 @@
6
6
  // able ws refresh merges the trunk into this workspace
7
7
  // able ws merge ["message"] [--yes] [--keep-open] merges this workspace into the trunk as `Merge feat/<slug>`
8
8
  // able ws rm <slug> [--force] stops and removes a workspace, deleting its branch once merged
9
- // able ws preview [<slug>…] rebuilds `all`: origin's trunk plus the open workspaces' committed work
9
+ // able ws preview [<slug>…] [--no-serve] rebuilds `all` from origin's trunk and the open workspaces' work as it
10
+ // stands, then serves it until Ctrl-C
11
+ // able ws preview rm stops and throws the preview away; the next `able ws preview` builds it afresh
10
12
  // able ws start | stop [<service>…] the workspace's services, in dependency order
11
13
  // able ws status the services running in this checkout
12
14
  // able ws take <resource> moves a shared resource to this checkout
@@ -22,7 +24,8 @@ const commands: Record<string, () => Promise<unknown>> = {
22
24
  rm: () => import('./rm.ts'),
23
25
  refresh: () => import('./refresh.ts'),
24
26
  merge: () => import('./merge.ts'),
25
- preview: () => import('./preview.ts'),
27
+ // `preview rm` is `rm all --force`: the preview holds nothing of its own to lose.
28
+ preview: () => (args[0] === 'rm' ? (process.argv.splice(3, 2, 'rm', 'all', '--force'), import('./rm.ts')) : import('./preview.ts')),
26
29
  take: () => import('./take.ts'),
27
30
  current: async () => console.log(JSON.stringify(await (await import('./state.ts')).current(), null, args.includes('--json') ? undefined : 2)),
28
31
  start: async () => (await import('./services.ts')).start(names),
@@ -1,4 +1,4 @@
1
- // The preview slot: `all`, rebuilt from origin/main and the open workspaces' committed tips, never answering as main.
1
+ // The preview slot: `all`, rebuilt from origin/main and the open workspaces' work as it stands, never answering as main.
2
2
 
3
3
  import { expect, test } from 'bun:test'
4
4
  import { existsSync, readFileSync } from 'node:fs'
@@ -12,17 +12,21 @@ test('ws preview combines the open workspaces, leaves out and names a conflictin
12
12
  commit(h.ws('two'), 'two.txt', 'from two\n')
13
13
  commit(h.ws('one'), 'README.md', 'one\nTWO by one\nthree\n')
14
14
  commit(h.ws('three'), 'README.md', 'one\nTWO by three\nthree\n')
15
- write(h.ws('two'), 'uncommitted.txt', 'never in the preview\n')
15
+ write(h.ws('two'), 'uncommitted.txt', 'in the preview, uncommitted\n')
16
+ const twoBefore = { head: git(h.ws('two'), 'rev-parse', 'HEAD'), status: git(h.ws('two'), 'status', '--porcelain') }
16
17
 
17
18
  const r = run(h.main, 'ws', 'preview')
18
19
  expect(r.code).toBe(0)
19
20
  expect(r.out).toMatch(/\+ one/)
20
- expect(r.out).toMatch(/\+ two/)
21
+ expect(r.out).toMatch(/\+ two .* \+ 1 uncommitted/)
21
22
  expect(r.out).toMatch(/− three .* left out: conflicts with one/)
22
23
  const all = h.ws('all')
23
24
  expect(readFileSync(join(all, 'one.txt'), 'utf8')).toBe('from one\n')
24
25
  expect(readFileSync(join(all, 'two.txt'), 'utf8')).toBe('from two\n')
25
- expect(existsSync(join(all, 'uncommitted.txt'))).toBe(false)
26
+ expect(readFileSync(join(all, 'uncommitted.txt'), 'utf8')).toBe('in the preview, uncommitted\n')
27
+ // The workspace is as it was: same HEAD, the file still untracked, nothing staged.
28
+ expect(git(h.ws('two'), 'rev-parse', 'HEAD')).toBe(twoBefore.head)
29
+ expect(git(h.ws('two'), 'status', '--porcelain')).toBe(twoBefore.status)
26
30
  // Detached, and no branch or ref of its own.
27
31
  expect(git(all, 'rev-parse', '--abbrev-ref', 'HEAD')).toBe('HEAD')
28
32
  expect(git(h.main, 'for-each-ref', '--format=%(refname)')).not.toContain('all')
@@ -55,9 +59,9 @@ test('ws preview combines the open workspaces, leaves out and names a conflictin
55
59
  expect(stopped.out).toMatch(/two\.txt\s+two/)
56
60
  expect(stopped.out).toMatch(/stray\.txt\s+no workspace/)
57
61
 
58
- // Reserved, and removable like any checkout.
62
+ // Reserved, and thrown away by `ws preview rm`.
59
63
  expect(run(h.main, 'ws', 'new', 'all', '--no-brief').out).toContain('reserved')
60
- expect(run(h.main, 'ws', 'rm', 'all', '--force').code).toBe(0)
64
+ expect(run(h.main, 'ws', 'preview', 'rm').code).toBe(0)
61
65
  expect(existsSync(all)).toBe(false)
62
66
  })
63
67
 
@@ -79,3 +83,19 @@ test("a hook that rewrites a tracked file doesn't stop the next rebuild, and a p
79
83
  expect(run(h.main, 'ws', 'rm', 'all').code).toBe(0)
80
84
  expect((JSON.parse(run(h.main, 'ws', 'ls', '--json').out) as { slug: string }[]).map((w) => w.slug)).toEqual(['one'])
81
85
  })
86
+
87
+ test('ws preview serves the rebuilt preview in the foreground with its own slug and offset, and says when it adds nothing', () => {
88
+ const h = host()
89
+ expect(run(h.main, 'ws', 'new', 'one', '--no-brief').code).toBe(0)
90
+ write(
91
+ h.main,
92
+ 'able.config.ts',
93
+ `export default { trunk: 'main', journal: 'journal', workspaces: { dir: '../ws', ports: { step: 100, max: 9 }, serve: 'echo "served $ABLE_WS_SLUG at $ABLE_WS_PORT_OFFSET"' } }\n`,
94
+ )
95
+
96
+ const served = run(h.main, 'ws', 'preview')
97
+ expect(served.code).toBe(0)
98
+ expect(served.out).toMatch(/served all at [1-9]\d*/)
99
+ expect(served.out).toContain(`every workspace's work is on origin/main already`)
100
+ expect(run(h.main, 'ws', 'preview', '--no-serve').out).not.toContain('served all')
101
+ })