@able-autonomy/able 0.2.2 → 0.2.3

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/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`.
@@ -77,6 +80,7 @@ const shape: Shape = {
77
80
  onRemove: true,
78
81
  onPreview: true,
79
82
  url: { port: true, path: true },
83
+ serve: true,
80
84
  services: { '*': { start: true, stop: true, ready: true, needs: true, cwd: true } },
81
85
  resources: { '*': { take: true, auto: true, holder: true } },
82
86
  },
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.3",
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",
@@ -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
+ })
@@ -1,31 +1,36 @@
1
- // able ws preview [<slug>…]: the combined preview, from the main checkout. One checkout, slug `all`, in
2
- // `workspaces.dir`, rebuilt on request as `origin/<trunk>` plus the open workspaces' committed work: every open one,
3
- // oldest first, or the ones named. Combination is a view, not a branch: nothing in it is merged anywhere.
1
+ // able ws preview [<slug>…] [--no-serve]: the combined preview, from the main checkout. One checkout, slug `all`, in
2
+ // `workspaces.dir`, rebuilt on request as `origin/<trunk>` plus the open workspaces' work as it stands, uncommitted
3
+ // files included: every open one, oldest first, or the ones named. Combination is a view, not a branch: nothing in it
4
+ // is merged anywhere, and no workspace's index, files or history are touched. `able ws preview rm` throws it away.
4
5
  //
5
- // 1. fetch, then chain `git merge-tree --write-tree` over `origin/<trunk>` and each workspace's committed tip,
6
+ // 1. fetch; snapshot each workspace with uncommitted work as a commit on its HEAD that no ref points to (built in a
7
+ // copy of its index); chain `git merge-tree --write-tree` over `origin/<trunk>` and each tip or snapshot,
6
8
  // `git commit-tree` each step; a workspace that conflicts is left out, and named with whom it conflicts
7
9
  // 2. in `all`: stop its services, check the commit out (detached), run `onCreate` when a lockfile changed since the
8
10
  // last build (or on the first), then `onPreview` (Able's resets its Postgres), put back any tracked file the
9
11
  // hooks rewrote, record the build, then start its services
12
+ // 3. run `serve` in the foreground until Ctrl-C, when the config has one
10
13
  //
11
14
  // `all` has its own entry in `.able/workspaces.json` (`kind: 'preview'`, its offset, its last build), so its ports,
12
15
  // database and host are its own. It is created on first use. Edits in it stop the rebuild: each changed file is
13
16
  // named with the workspace that changes it, where the edit belongs.
14
17
 
15
- import { existsSync, mkdirSync } from 'node:fs'
16
- import { dirname, relative, resolve } from 'node:path'
18
+ import { copyFileSync, existsSync, mkdirSync, rmSync } from 'node:fs'
19
+ import { tmpdir } from 'node:os'
20
+ import { dirname, join, relative, resolve } from 'node:path'
17
21
  import { loadConfig, urlOf } from '../../config.ts'
18
- import { fetchTrunk, git, gitLoud, gitQuiet, lines, mainRoot } from '../git.ts'
19
- import { runCommand, type Place } from '../run.ts'
22
+ import { dirtyCount, fetchTrunk, git, gitLoud, gitQuiet, lines, mainRoot } from '../git.ts'
23
+ import { runCommand, shellFor, type Place } from '../run.ts'
20
24
  import { status, working } from '../status.ts'
21
25
  import { bold, dim, fail, green, red, yellow } from '../ui.ts'
22
26
  import { mergeTree, requireMergeTree, scratchObjects } from './overlap.ts'
23
- import { start, stop } from './services.ts'
27
+ import { portOpen, start, stop } from './services.ts'
24
28
  import { copyFiles, current, freeOffset, openWorkspaces, PREVIEW, readState, workspaces, writeState, type Build } from './state.ts'
25
29
 
26
30
  const LOCKFILES = /(^|\/)(bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|uv\.lock|poetry\.lock|Cargo\.lock|Gemfile\.lock|go\.sum)$/
27
31
 
28
32
  const named = process.argv.slice(4).filter((a) => !a.startsWith('-'))
33
+ const noServe = process.argv.includes('--no-serve')
29
34
  const main = mainRoot()
30
35
  if (resolve((await current()).path) !== resolve(main)) fail('able ws preview runs in the main checkout')
31
36
  const config = await loadConfig(main)
@@ -48,6 +53,13 @@ const chosen = named.length ? open.filter((w) => named.includes(w.slug)) : open
48
53
 
49
54
  const path = resolve(main, wsc.dir, PREVIEW)
50
55
  const exists = (await workspaces(main, state)).some((w) => w.kind === 'preview' && existsSync(w.path))
56
+ const entry = state.workspaces[PREVIEW]
57
+ const portOffset = entry?.portOffset ?? freeOffset(state, wsc.ports)
58
+ const serve = noServe ? undefined : wsc.serve
59
+
60
+ // Served already (another terminal), or the port held by something else: say so before rebuilding under it.
61
+ const port = wsc.url && wsc.url.port + portOffset
62
+ if (serve && port && (await portOpen(port))) fail(`port ${port} is taken: the preview is served already (stop it with Ctrl-C there), or something else holds it (lsof -iTCP:${port} -sTCP:LISTEN)`)
51
63
 
52
64
  // Edits in the preview belong in a workspace: name it for each file, and stop.
53
65
  if (exists) {
@@ -60,7 +72,7 @@ if (exists) {
60
72
  .map((w) => w.slug)
61
73
  .join(', ') || 'no workspace'
62
74
  fail(
63
- `${edited.length} uncommitted file(s) in the preview; it is rebuilt from committed work only, so make each change in its workspace:\n${edited
75
+ `${edited.length} uncommitted file(s) in the preview; it is rebuilt from the workspaces, so make each change in its workspace:\n${edited
64
76
  .map((f) => ` ${f.padEnd(40)} ${dim(owner(f))}`)
65
77
  .join('\n')}\n ${dim(`then discard them (git -C ${relative(process.cwd(), path)} checkout -- . && git -C ${relative(process.cwd(), path)} clean -fd) and rebuild`)}`,
66
78
  )
@@ -69,6 +81,24 @@ if (exists) {
69
81
 
70
82
  // ── The combined commit ─────────────────────────────────────────────────────────────────────────
71
83
 
84
+ /** A workspace's tree as it stands, untracked files included and gitignored ones not, as a commit on its HEAD that no
85
+ * ref points to. Built in a copy of its index, so its own index, files and history are untouched; '' when clean. */
86
+ function snapshot(at: string, slug: string) {
87
+ if (!existsSync(at) || !dirtyCount(at)) return ''
88
+ const index = resolve(at, git(at, 'rev-parse', '--git-path', 'index'))
89
+ const temp = join(tmpdir(), `able-preview-${process.pid}-${slug}.index`)
90
+ try {
91
+ if (existsSync(index)) copyFileSync(index, temp)
92
+ const env = { ...process.env, GIT_INDEX_FILE: temp }
93
+ const added = Bun.spawnSync(['git', '-C', at, 'add', '-A'], { env, stdout: 'pipe', stderr: 'pipe' })
94
+ if (added.exitCode !== 0) fail(`could not snapshot ${slug}'s uncommitted work: ${added.stderr.toString().trim()}`)
95
+ const tree = Bun.spawnSync(['git', '-C', at, 'write-tree'], { env, stdout: 'pipe', stderr: 'pipe' }).stdout.toString().trim()
96
+ return git(at, 'commit-tree', tree, '-p', 'HEAD', '-m', `Preview: ${slug}'s uncommitted work`) || fail(`could not snapshot ${slug}'s uncommitted work`)
97
+ } finally {
98
+ rmSync(temp, { force: true })
99
+ }
100
+ }
101
+
72
102
  step('combining')
73
103
  let head = baseCommit
74
104
  const included: Build['included'] = []
@@ -76,11 +106,12 @@ const left: Build['left'] = []
76
106
  const scratch = scratchObjects(main)
77
107
  try {
78
108
  for (const w of chosen) {
79
- const tip = git(main, 'rev-parse', w.branch)
109
+ const uncommitted = existsSync(w.path) ? dirtyCount(w.path) : 0
110
+ const tip = snapshot(w.path, w.slug) || git(main, 'rev-parse', w.branch)
80
111
  const { tree, conflicts } = mergeTree(main, head, tip)
81
112
  if (!conflicts.length) {
82
113
  head = git(main, 'commit-tree', tree, '-p', head, '-p', tip, '-m', `Preview: ${w.branch} at ${tip.slice(0, 7)}`) || fail(`git commit-tree failed for ${w.slug}`)
83
- included.push({ slug: w.slug, tip })
114
+ included.push({ slug: w.slug, tip, ...(uncommitted && { uncommitted }) })
84
115
  continue
85
116
  }
86
117
  // With whom: origin/<trunk>, then each workspace already in; failing both, the combination of them.
@@ -93,8 +124,6 @@ try {
93
124
 
94
125
  // ── The checkout ────────────────────────────────────────────────────────────────────────────────
95
126
 
96
- const entry = state.workspaces[PREVIEW]
97
- const portOffset = entry?.portOffset ?? freeOffset(state, wsc.ports)
98
127
  const at: Place = { slug: PREVIEW, path, portOffset, main }
99
128
  if (!exists) {
100
129
  step('adding the preview checkout')
@@ -124,7 +153,7 @@ if (wsc.onPreview?.length) {
124
153
  for (const c of wsc.onPreview) if (!runCommand(c, at)) failed.add('onPreview')
125
154
  }
126
155
  // The hooks may rewrite tracked files (an install updating a lockfile the combined tree disagrees with). The preview
127
- // holds committed work only, so put them back, or the next rebuild would refuse over edits nobody made.
156
+ // holds the workspaces' work only, so put them back, or the next rebuild would refuse over edits nobody made.
128
157
  const rewritten = lines(path, 'diff', '--name-only', 'HEAD')
129
158
  if (rewritten.length) gitQuiet(path, 'checkout', '--quiet', 'HEAD', '--', '.')
130
159
 
@@ -150,13 +179,34 @@ console.log(
150
179
  `\n${green('✓')} ${bold(PREVIEW)} ${dim(relative(process.cwd(), path))} ${dim(`built in ${((Date.now() - began) / 1000).toFixed(1)}s, ${new Date(build.at).toLocaleTimeString('en-GB')}`)}\n`,
151
180
  )
152
181
  console.log(` ${'from'.padEnd(width)} ${base} ${dim(short(baseCommit))}`)
153
- for (const i of included) console.log(` ${green('+')} ${i.slug.padEnd(width - 2)} ${dim(short(i.tip))}`)
182
+ for (const i of included)
183
+ console.log(` ${green('+')} ${i.slug.padEnd(width - 2)} ${dim(i.uncommitted ? `${short(git(main, 'rev-parse', `${i.tip}^`))} + ${i.uncommitted} uncommitted` : short(i.tip))}`)
184
+ // A workspace merged with --keep-open and untouched since adds nothing: say so, or the preview looks broken.
185
+ if (included.length && !left.length && included.every((i) => gitQuiet(main, 'merge-base', '--is-ancestor', i.tip, baseCommit)))
186
+ console.log(dim(` every workspace's work is on ${base} already: the preview is ${base} alone`))
154
187
  for (const l of left) console.log(` ${red('−')} ${l.slug.padEnd(width - 2)} ${dim(short(l.tip))} ${red('left out')}: conflicts with ${l.with.join(', ')}`)
155
188
  if (!chosen.length) console.log(dim(` no open workspaces: the preview is ${base} alone`))
156
189
  if (wsc.url) console.log(`\n ${'url'.padEnd(width)} ${urlOf(wsc.url, PREVIEW, portOffset)}`)
157
190
  console.log(` ${'port offset'.padEnd(width)} ${portOffset}`)
158
191
  if (rewritten.length) console.log(dim(`\n put back what the hooks changed in tracked files: ${rewritten.join(', ')}`))
159
192
  if (failed.size) console.log(yellow(`\n ${[...failed].join(' and ')} failed; see above, then run it again`))
160
- else if (!services.length) console.log(dim(`\n able.config.ts names no services: start the app in ${relative(process.cwd(), path)} yourself`))
193
+ else if (!services.length && !serve)
194
+ console.log(
195
+ dim(`\n not served: ${wsc.serve ? 'able ws preview without --no-serve serves it' : `start the app in ${relative(process.cwd(), path)} yourself, or give able.config.ts a workspaces.serve`}`),
196
+ )
161
197
  console.log()
162
198
  status({ state: 'done', msg: `preview: ${included.length} workspace(s) in${left.length ? `, ${left.length} left out` : ''}` })
199
+
200
+ // ── Served ──────────────────────────────────────────────────────────────────────────────────────
201
+
202
+ if (serve && !failed.size) {
203
+ const { run, cwd } = typeof serve === 'string' ? { run: serve } : serve
204
+ const sh = shellFor(at, run, cwd)
205
+ console.log(dim(` serving: ${run} (Ctrl-C stops it; able ws preview rm throws the preview away)\n`))
206
+ // Ctrl-C reaches the whole foreground group: the app stops itself, and this waits for it rather than leaving it.
207
+ process.on('SIGINT', () => {})
208
+ const child = Bun.spawn(sh.argv, { cwd: sh.cwd, env: sh.env, stdio: ['inherit', 'inherit', 'inherit'] })
209
+ const code = await child.exited
210
+ console.log(dim(`\n preview stopped; able ws preview serves it again, able ws preview rm throws it away\n`))
211
+ process.exit(code === 130 ? 0 : code)
212
+ }
@@ -10,7 +10,7 @@ import { dirtyCount, fetchTrunk, git, gitQuiet, mainRoot, unpushedCount } from '
10
10
  import { runCommand } from '../run.ts'
11
11
  import { bold, dim, fail, green, red, yellow } from '../ui.ts'
12
12
  import { leave } from './resources.ts'
13
- import { stop } from './services.ts'
13
+ import { portOpen, stop } from './services.ts'
14
14
  import { readState, workspaces, writeState } from './state.ts'
15
15
 
16
16
  const args = process.argv.slice(4)
@@ -20,6 +20,8 @@ if (!slug) fail('usage: able ws rm <slug> [--force]')
20
20
  const main = mainRoot()
21
21
  const config = await loadConfig(main)
22
22
  const ws = (await workspaces(main)).find((w) => w.slug === slug) ?? fail(`no workspace '${slug}'; see able ws ls`)
23
+ const url = config.workspaces?.url
24
+ if (ws.kind === 'preview' && url && (await portOpen(url.port + ws.portOffset))) fail(`the preview is being served on port ${url.port + ws.portOffset}; stop it there (Ctrl-C) first`)
23
25
 
24
26
  if (!args.includes('--force') && existsSync(ws.path)) {
25
27
  const dirty = dirtyCount(ws.path)
@@ -37,7 +37,8 @@ export function ordered(services: Record<string, Service>, names: string[]): [st
37
37
  return out
38
38
  }
39
39
 
40
- const portOpen = (port: number) =>
40
+ /** Whether something answers on this port on this machine. */
41
+ export const portOpen = (port: number) =>
41
42
  new Promise<boolean>((done) => {
42
43
  const socket = connect({ port, host: '127.0.0.1' }, () => (socket.destroy(), done(true)))
43
44
  socket.on('error', () => done(false))
@@ -30,7 +30,7 @@ export interface Workspace {
30
30
  }
31
31
 
32
32
  /** The preview's last build: what went in, and what was left out with whom it conflicts. */
33
- export type Build = { at: string; commit: string; base: string; included: { slug: string; tip: string }[]; left: { slug: string; tip: string; with: string[] }[] }
33
+ export type Build = { at: string; commit: string; base: string; included: { slug: string; tip: string; uncommitted?: number }[]; left: { slug: string; tip: string; with: string[] }[] }
34
34
 
35
35
  type Entry = { portOffset: number; createdAt: string; kind?: 'preview'; path?: string; build?: Build }
36
36