@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.
@@ -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