@able-autonomy/able 0.0.20 → 0.2.0
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 +9 -2
- package/config.ts +11 -0
- package/package.json +1 -1
- package/src/bloat/apply.test.ts +81 -0
- package/src/bloat/apply.ts +49 -0
- package/src/{agents → bloat}/blocks.ts +2 -2
- package/src/{agents → bloat}/checks.ts +2 -2
- package/src/bloat/compare.ts +63 -0
- package/src/{agents → bloat}/findings.ts +11 -7
- package/src/{agents → bloat}/grid.ts +4 -4
- package/src/bloat/index.ts +258 -0
- package/src/{agents → bloat}/load.ts +2 -2
- package/src/{agents → bloat}/picker.ts +3 -3
- package/src/bloat/report.ts +286 -0
- package/src/{agents → bloat}/scan.ts +2 -2
- package/src/bloat/show.ts +79 -0
- package/src/bloat/steps.ts +32 -0
- package/src/{agents → bloat}/types.ts +48 -3
- package/src/commit.ts +2 -1
- package/src/git.ts +43 -2
- package/src/push.ts +2 -1
- package/src/ui.ts +3 -0
- package/src/workspaces/agent.ts +8 -2
- package/src/workspaces/fixture.ts +49 -0
- package/src/workspaces/index.ts +3 -1
- package/src/workspaces/ls.ts +56 -11
- package/src/workspaces/merge.ts +29 -13
- package/src/workspaces/new.ts +17 -15
- package/src/workspaces/overlap.test.ts +53 -0
- package/src/workspaces/overlap.ts +86 -0
- package/src/workspaces/preview.test.ts +81 -0
- package/src/workspaces/preview.ts +162 -0
- package/src/workspaces/refresh.ts +26 -24
- package/src/workspaces/rm.ts +6 -1
- package/src/workspaces/services.ts +2 -2
- package/src/workspaces/state.ts +56 -9
- package/src/workspaces/trunk.test.ts +88 -0
- package/sync.ts +5 -2
- package/src/agents/index.ts +0 -198
- package/src/agents/report.ts +0 -211
- package/src/agents/show.ts +0 -73
- package/src/agents/steps.ts +0 -32
- /package/src/{agents → bloat}/kinds.ts +0 -0
|
@@ -0,0 +1,162 @@
|
|
|
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.
|
|
4
|
+
//
|
|
5
|
+
// 1. fetch, then chain `git merge-tree --write-tree` over `origin/<trunk>` and each workspace's committed tip,
|
|
6
|
+
// `git commit-tree` each step; a workspace that conflicts is left out, and named with whom it conflicts
|
|
7
|
+
// 2. in `all`: stop its services, check the commit out (detached), run `onCreate` when a lockfile changed since the
|
|
8
|
+
// last build (or on the first), then `onPreview` (Able's resets its Postgres), put back any tracked file the
|
|
9
|
+
// hooks rewrote, record the build, then start its services
|
|
10
|
+
//
|
|
11
|
+
// `all` has its own entry in `.able/workspaces.json` (`kind: 'preview'`, its offset, its last build), so its ports,
|
|
12
|
+
// database and host are its own. It is created on first use. Edits in it stop the rebuild: each changed file is
|
|
13
|
+
// named with the workspace that changes it, where the edit belongs.
|
|
14
|
+
|
|
15
|
+
import { existsSync, mkdirSync } from 'node:fs'
|
|
16
|
+
import { dirname, relative, resolve } from 'node:path'
|
|
17
|
+
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'
|
|
20
|
+
import { status, working } from '../status.ts'
|
|
21
|
+
import { bold, dim, fail, green, red, yellow } from '../ui.ts'
|
|
22
|
+
import { mergeTree, requireMergeTree, scratchObjects } from './overlap.ts'
|
|
23
|
+
import { start, stop } from './services.ts'
|
|
24
|
+
import { copyFiles, current, freeOffset, openWorkspaces, PREVIEW, readState, workspaces, writeState, type Build } from './state.ts'
|
|
25
|
+
|
|
26
|
+
const LOCKFILES = /(^|\/)(bun\.lockb?|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|uv\.lock|poetry\.lock|Cargo\.lock|Gemfile\.lock|go\.sum)$/
|
|
27
|
+
|
|
28
|
+
const named = process.argv.slice(4).filter((a) => !a.startsWith('-'))
|
|
29
|
+
const main = mainRoot()
|
|
30
|
+
if (resolve((await current()).path) !== resolve(main)) fail('able ws preview runs in the main checkout')
|
|
31
|
+
const config = await loadConfig(main)
|
|
32
|
+
const { trunk } = config
|
|
33
|
+
const wsc = config.workspaces ?? fail('able.config.ts has no workspaces')
|
|
34
|
+
requireMergeTree()
|
|
35
|
+
|
|
36
|
+
const began = Date.now()
|
|
37
|
+
const step = working('preview')
|
|
38
|
+
step(`fetching origin/${trunk}`)
|
|
39
|
+
fetchTrunk(main, trunk)
|
|
40
|
+
const base = `origin/${trunk}`
|
|
41
|
+
const baseCommit = git(main, 'rev-parse', '--verify', '--quiet', `${base}^{commit}`) || fail(`no ${base}; push ${trunk} to origin first`)
|
|
42
|
+
|
|
43
|
+
const state = await readState(main)
|
|
44
|
+
const open = await openWorkspaces(main, state)
|
|
45
|
+
const unknown = named.filter((n) => !open.some((w) => w.slug === n))
|
|
46
|
+
if (unknown.length) fail(`no open workspace ${unknown.map((n) => `'${n}'`).join(', ')}; see able ws ls`)
|
|
47
|
+
const chosen = named.length ? open.filter((w) => named.includes(w.slug)) : open
|
|
48
|
+
|
|
49
|
+
const path = resolve(main, wsc.dir, PREVIEW)
|
|
50
|
+
const exists = (await workspaces(main, state)).some((w) => w.kind === 'preview' && existsSync(w.path))
|
|
51
|
+
|
|
52
|
+
// Edits in the preview belong in a workspace: name it for each file, and stop.
|
|
53
|
+
if (exists) {
|
|
54
|
+
const edited = lines(path, 'status', '--porcelain', '--untracked-files=all').map((l) => l.slice(3))
|
|
55
|
+
if (edited.length) {
|
|
56
|
+
const changes = Object.fromEntries(open.map((w) => [w.slug, new Set(lines(main, 'diff', '--name-only', `${base}...${w.branch}`))]))
|
|
57
|
+
const owner = (f: string) =>
|
|
58
|
+
open
|
|
59
|
+
.filter((w) => changes[w.slug]?.has(f))
|
|
60
|
+
.map((w) => w.slug)
|
|
61
|
+
.join(', ') || 'no workspace'
|
|
62
|
+
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
|
|
64
|
+
.map((f) => ` ${f.padEnd(40)} ${dim(owner(f))}`)
|
|
65
|
+
.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
|
+
)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ── The combined commit ─────────────────────────────────────────────────────────────────────────
|
|
71
|
+
|
|
72
|
+
step('combining')
|
|
73
|
+
let head = baseCommit
|
|
74
|
+
const included: Build['included'] = []
|
|
75
|
+
const left: Build['left'] = []
|
|
76
|
+
const scratch = scratchObjects(main)
|
|
77
|
+
try {
|
|
78
|
+
for (const w of chosen) {
|
|
79
|
+
const tip = git(main, 'rev-parse', w.branch)
|
|
80
|
+
const { tree, conflicts } = mergeTree(main, head, tip)
|
|
81
|
+
if (!conflicts.length) {
|
|
82
|
+
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 })
|
|
84
|
+
continue
|
|
85
|
+
}
|
|
86
|
+
// With whom: origin/<trunk>, then each workspace already in; failing both, the combination of them.
|
|
87
|
+
const against = [{ slug: base, tip: baseCommit }, ...included].filter((o) => mergeTree(main, o.tip, tip, scratch).conflicts.length).map((o) => o.slug)
|
|
88
|
+
left.push({ slug: w.slug, tip, with: against.length ? against : included.map((i) => i.slug) })
|
|
89
|
+
}
|
|
90
|
+
} finally {
|
|
91
|
+
scratch.done()
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ── The checkout ────────────────────────────────────────────────────────────────────────────────
|
|
95
|
+
|
|
96
|
+
const entry = state.workspaces[PREVIEW]
|
|
97
|
+
const portOffset = entry?.portOffset ?? freeOffset(state, wsc.ports)
|
|
98
|
+
const at: Place = { slug: PREVIEW, path, portOffset, main }
|
|
99
|
+
if (!exists) {
|
|
100
|
+
step('adding the preview checkout')
|
|
101
|
+
gitQuiet(main, 'worktree', 'prune')
|
|
102
|
+
if (existsSync(path)) fail(`${path} exists and is not the preview; remove it first`)
|
|
103
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
104
|
+
const added = Bun.spawnSync(['git', '-C', main, 'worktree', 'add', '--detach', path, head], { stdout: 'pipe', stderr: 'pipe' })
|
|
105
|
+
if (added.exitCode !== 0) fail(`worktree add failed: ${added.stderr.toString().trim()}`)
|
|
106
|
+
copyFiles(main, path, wsc.copy)
|
|
107
|
+
state.workspaces[PREVIEW] = { portOffset, createdAt: new Date().toISOString(), kind: 'preview', path }
|
|
108
|
+
await writeState(main, state)
|
|
109
|
+
} else {
|
|
110
|
+
step('stopping its services')
|
|
111
|
+
await stop([], at)
|
|
112
|
+
if (!gitLoud(path, 'checkout', '--quiet', '--detach', head)) fail('could not check the combined commit out in the preview')
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const previous = entry?.build?.commit
|
|
116
|
+
const installs = !exists || !previous || lines(main, 'diff', '--name-only', previous, head).some((f) => LOCKFILES.test(f))
|
|
117
|
+
const failed = new Set<string>()
|
|
118
|
+
if (installs && wsc.onCreate?.length) {
|
|
119
|
+
step('onCreate (a lockfile changed)')
|
|
120
|
+
for (const c of wsc.onCreate) if (!runCommand(c, at)) failed.add('onCreate')
|
|
121
|
+
}
|
|
122
|
+
if (wsc.onPreview?.length) {
|
|
123
|
+
step('onPreview')
|
|
124
|
+
for (const c of wsc.onPreview) if (!runCommand(c, at)) failed.add('onPreview')
|
|
125
|
+
}
|
|
126
|
+
// 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.
|
|
128
|
+
const rewritten = lines(path, 'diff', '--name-only', 'HEAD')
|
|
129
|
+
if (rewritten.length) gitQuiet(path, 'checkout', '--quiet', 'HEAD', '--', '.')
|
|
130
|
+
|
|
131
|
+
// Recorded before the services start, so a service that fails to come up still leaves the record of what is checked
|
|
132
|
+
// out. Re-read: stopping services moves resource holders in the same file.
|
|
133
|
+
const after = await readState(main)
|
|
134
|
+
const build: Build = { at: new Date().toISOString(), commit: head, base: baseCommit, included, left }
|
|
135
|
+
// Written above on the first build, or there from an earlier one.
|
|
136
|
+
after.workspaces[PREVIEW] = { ...after.workspaces[PREVIEW]!, build }
|
|
137
|
+
await writeState(main, after)
|
|
138
|
+
|
|
139
|
+
const services = Object.keys(wsc.services ?? {})
|
|
140
|
+
if (services.length && !failed.size) {
|
|
141
|
+
step('starting its services')
|
|
142
|
+
await start([], at)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ── What went in ────────────────────────────────────────────────────────────────────────────────
|
|
146
|
+
|
|
147
|
+
const short = (c: string) => c.slice(0, 7)
|
|
148
|
+
const width = Math.max(12, ...chosen.map((w) => w.slug.length + 2))
|
|
149
|
+
console.log(
|
|
150
|
+
`\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
|
+
)
|
|
152
|
+
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))}`)
|
|
154
|
+
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
|
+
if (!chosen.length) console.log(dim(` no open workspaces: the preview is ${base} alone`))
|
|
156
|
+
if (wsc.url) console.log(`\n ${'url'.padEnd(width)} ${urlOf(wsc.url, PREVIEW, portOffset)}`)
|
|
157
|
+
console.log(` ${'port offset'.padEnd(width)} ${portOffset}`)
|
|
158
|
+
if (rewritten.length) console.log(dim(`\n put back what the hooks changed in tracked files: ${rewritten.join(', ')}`))
|
|
159
|
+
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`))
|
|
161
|
+
console.log()
|
|
162
|
+
status({ state: 'done', msg: `preview: ${included.length} workspace(s) in${left.length ? `, ${left.length} left out` : ''}` })
|
|
@@ -1,37 +1,39 @@
|
|
|
1
1
|
// able ws refresh: catches this workspace up with the trunk, from inside it (decision 81).
|
|
2
2
|
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
3
|
+
// The trunk is `origin/<trunk>`, after a fetch: only what origin holds reaches a workspace. Commits on the main
|
|
4
|
+
// checkout's `local <trunk>` that aren't pushed are left out and named, so they never leave the machine inside this
|
|
5
|
+
// workspace's merge. Refuses on uncommitted files.
|
|
6
6
|
|
|
7
|
-
import { count, dirtyCount, fetchTrunk, git,
|
|
7
|
+
import { carriedFromLocal, count, dirtyCount, fetchTrunk, git, mergeOrFail, unpushedOnTrunk, warnLeftOut } from '../git.ts'
|
|
8
8
|
import { status, working } from '../status.ts'
|
|
9
|
-
import { bold, dim, fail, green
|
|
9
|
+
import { bold, dim, fail, green } from '../ui.ts'
|
|
10
10
|
import { inWorkspace } from './state.ts'
|
|
11
11
|
|
|
12
|
-
const { ws, config } = await inWorkspace()
|
|
12
|
+
const { ws, config } = await inWorkspace('able ws refresh')
|
|
13
13
|
const { trunk } = config
|
|
14
14
|
const dirty = dirtyCount(ws.path)
|
|
15
15
|
if (dirty) fail(`${dirty} uncommitted file(s); commit them first, so the merge stays separable from your work`)
|
|
16
16
|
|
|
17
17
|
const step = working(`refresh ${ws.slug}`)
|
|
18
|
-
step(`fetching
|
|
18
|
+
step(`fetching origin/${trunk}`)
|
|
19
19
|
fetchTrunk(ws.path, trunk)
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
const remote = git(ws.path, 'rev-parse', '--verify', '--quiet', `origin/${trunk}`) ? `origin/${trunk}` : ''
|
|
23
|
-
const sources = !local ? [remote] : !remote || contains(local, remote) ? [local] : contains(remote, local) ? [remote] : [remote, local]
|
|
20
|
+
const remote = `origin/${trunk}`
|
|
21
|
+
if (!git(ws.path, 'rev-parse', '--verify', '--quiet', remote)) fail(`no ${remote}; push ${trunk} to origin first`)
|
|
24
22
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
23
|
+
const behind = count(ws.path, `HEAD..${remote}`)
|
|
24
|
+
if (behind) {
|
|
25
|
+
console.log(` ${bold(remote)}: ${behind} commit(s)`)
|
|
26
|
+
step(`merging ${remote}`)
|
|
27
|
+
mergeOrFail(ws.path, remote, ws.branch, 'resolve them here and commit the merge, or abort it with git merge --abort')
|
|
28
|
+
} else console.log(dim(` ${remote}: already merged`))
|
|
29
|
+
|
|
30
|
+
const left = unpushedOnTrunk(ws.path, trunk, 'HEAD')
|
|
31
|
+
warnLeftOut(left, `on local ${trunk} not included: they aren't on ${remote}, and only what origin holds reaches a workspace`, 'push them from the main checkout (able push), then refresh again')
|
|
32
|
+
// Taken in before the trunk rule: already in the branch, and `able ws merge` refuses them until origin has them.
|
|
33
|
+
warnLeftOut(
|
|
34
|
+
carriedFromLocal(ws.path, trunk),
|
|
35
|
+
`from local ${trunk} already in ${ws.branch}, not on ${remote}: able ws merge refuses them`,
|
|
36
|
+
'push them from the main checkout (able push) before merging',
|
|
37
|
+
)
|
|
38
|
+
console.log(`\n${green('✓')} ${bold(ws.branch)} holds ${remote}\n`)
|
|
39
|
+
status({ state: 'done', msg: `refresh: ${ws.branch} holds ${remote}${left.length ? `; ${left.length} unpushed on local ${trunk} left out` : ''}` })
|
package/src/workspaces/rm.ts
CHANGED
|
@@ -23,7 +23,8 @@ const ws = (await workspaces(main)).find((w) => w.slug === slug) ?? fail(`no wor
|
|
|
23
23
|
|
|
24
24
|
if (!args.includes('--force') && existsSync(ws.path)) {
|
|
25
25
|
const dirty = dirtyCount(ws.path)
|
|
26
|
-
|
|
26
|
+
// A checkout without a branch (the preview) holds builds of other checkouts' work: only uncommitted edits are its own.
|
|
27
|
+
const ahead = ws.branch ? unpushedCount(ws.path) : 0
|
|
27
28
|
const blockers = [dirty && `${dirty} uncommitted file(s)`, ahead && `${ahead} unpushed commit(s)`].filter(Boolean)
|
|
28
29
|
if (blockers.length) fail(`${red('refusing to remove')} ${bold(slug)}: this work exists nowhere else: ${blockers.join(', ')}\n ${dim('push it, or --force to discard')}`)
|
|
29
30
|
}
|
|
@@ -44,6 +45,10 @@ delete state.workspaces[slug]
|
|
|
44
45
|
await writeState(main, state)
|
|
45
46
|
console.log(`\n${green('✓')} removed ${bold(slug)}`)
|
|
46
47
|
|
|
48
|
+
if (!ws.branch) {
|
|
49
|
+
console.log()
|
|
50
|
+
process.exit(0)
|
|
51
|
+
}
|
|
47
52
|
fetchTrunk(main, config.trunk)
|
|
48
53
|
if (git(main, 'branch', '--merged', `origin/${config.trunk}`, '--list', ws.branch)) {
|
|
49
54
|
gitQuiet(main, 'branch', '-D', ws.branch)
|
|
@@ -55,8 +55,8 @@ async function ready(s: Service, at: Place, timeoutMs = 120_000): Promise<boolea
|
|
|
55
55
|
return false
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
export async function start(names: string[]) {
|
|
59
|
-
const at = await current()
|
|
58
|
+
export async function start(names: string[], place?: Place) {
|
|
59
|
+
const at = place ?? (await current())
|
|
60
60
|
const config = await loadConfig(at.path)
|
|
61
61
|
const services = config.workspaces?.services ?? fail('able.config.ts has no workspaces.services')
|
|
62
62
|
// Without `ports`, every checkout uses the same ports: only one runs services at a time (88, 94).
|
package/src/workspaces/state.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
// Which workspaces exist comes from git (decision 92): every worktree on `feat/<slug>`. What git can't know, a
|
|
2
2
|
// workspace's port offset and creation date and who holds each shared resource, is in `.able/workspaces.json` in the
|
|
3
3
|
// main checkout.
|
|
4
|
+
//
|
|
5
|
+
// One more checkout is registered there: the combined preview, slug `all` (preview.ts), a detached worktree with
|
|
6
|
+
// `kind: 'preview'`, its own offset and its last build. It is a checkout of its own, never the main one, and never a
|
|
7
|
+
// workspace anything is merged from.
|
|
4
8
|
|
|
5
|
-
import { existsSync } from 'node:fs'
|
|
9
|
+
import { copyFileSync, existsSync, mkdirSync } from 'node:fs'
|
|
6
10
|
import { dirname, join, resolve } from 'node:path'
|
|
7
11
|
import { loadConfig, type AbleConfig } from '../../config.ts'
|
|
8
12
|
import { failOnMerge, git } from '../git.ts'
|
|
@@ -10,6 +14,9 @@ import type { Place } from '../run.ts'
|
|
|
10
14
|
import { fail } from '../ui.ts'
|
|
11
15
|
|
|
12
16
|
export const branchOf = (slug: string) => `feat/${slug}`
|
|
17
|
+
|
|
18
|
+
/** The combined preview's slug, reserved: no workspace can take it. */
|
|
19
|
+
export const PREVIEW = 'all'
|
|
13
20
|
const slugOf = (ref: string) => ref.match(/^refs\/heads\/feat\/(.+)$/)?.[1]
|
|
14
21
|
|
|
15
22
|
export interface Workspace {
|
|
@@ -18,10 +25,17 @@ export interface Workspace {
|
|
|
18
25
|
path: string
|
|
19
26
|
portOffset: number
|
|
20
27
|
createdAt?: string
|
|
28
|
+
/** Set only on the combined preview. */
|
|
29
|
+
kind?: 'preview'
|
|
21
30
|
}
|
|
22
31
|
|
|
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[] }[] }
|
|
34
|
+
|
|
35
|
+
type Entry = { portOffset: number; createdAt: string; kind?: 'preview'; path?: string; build?: Build }
|
|
36
|
+
|
|
23
37
|
/** What git can't know: each workspace's offset and creation date, and each shared resource's holders, the current one last (89, 95). */
|
|
24
|
-
export type State = { workspaces: Record<string,
|
|
38
|
+
export type State = { workspaces: Record<string, Entry>; holders?: Record<string, string[]> }
|
|
25
39
|
|
|
26
40
|
const statePath = (main: string) => join(main, '.able', 'workspaces.json')
|
|
27
41
|
|
|
@@ -41,28 +55,56 @@ export async function running(checkout: string): Promise<Record<string, { pid: n
|
|
|
41
55
|
return Object.fromEntries(Object.entries(saved as Record<string, { pid: number; startedAt: string }>).filter(([, s]) => alive(s.pid)))
|
|
42
56
|
}
|
|
43
57
|
|
|
44
|
-
/**
|
|
58
|
+
/** Copies the host's `copy` files, gitignored ones a worktree can't inherit, from the main checkout into a new one. */
|
|
59
|
+
export function copyFiles(main: string, path: string, rels: string[] = []) {
|
|
60
|
+
for (const rel of rels) {
|
|
61
|
+
if (!existsSync(join(main, rel))) continue
|
|
62
|
+
mkdirSync(dirname(join(path, rel)), { recursive: true })
|
|
63
|
+
copyFileSync(join(main, rel), join(path, rel))
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The first port offset no checkout holds; 0 for every checkout when the host gives no `ports`. */
|
|
68
|
+
export function freeOffset(state: State, ports?: { step: number; max: number }) {
|
|
69
|
+
if (!ports) return 0
|
|
70
|
+
const taken = new Set(Object.values(state.workspaces).map((w) => w.portOffset))
|
|
71
|
+
return Array.from({ length: ports.max }, (_, i) => (i + 1) * ports.step).find((o) => !taken.has(o)) ?? fail('no free port offset; remove a workspace first')
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Every workspace git knows, with what the state file adds, and the preview: from its entry, even when its folder
|
|
75
|
+
* is gone (it still holds its offset, and `ws rm all` clears it). */
|
|
45
76
|
export async function workspaces(main: string, state?: State): Promise<Workspace[]> {
|
|
46
77
|
const saved = (state ?? (await readState(main))).workspaces
|
|
78
|
+
const preview = saved[PREVIEW]?.kind === 'preview' ? saved[PREVIEW] : undefined
|
|
79
|
+
const previewAt = preview?.path ? resolve(preview.path) : undefined
|
|
47
80
|
// `-z`: fields end in NUL, records in an empty field, so paths with spaces or newlines survive.
|
|
48
|
-
|
|
81
|
+
const listed = git(main, 'worktree', 'list', '--porcelain', '-z')
|
|
49
82
|
.split('\0\0')
|
|
50
|
-
.flatMap((record) => {
|
|
83
|
+
.flatMap((record): Workspace[] => {
|
|
51
84
|
const fields = record.split('\0')
|
|
52
85
|
const path = fields.find((f) => f.startsWith('worktree '))?.slice('worktree '.length)
|
|
53
86
|
const slug = slugOf(fields.find((f) => f.startsWith('branch '))?.slice('branch '.length) ?? '')
|
|
54
|
-
if (!path || !slug) return []
|
|
87
|
+
if (!path || !slug || resolve(path) === previewAt) return []
|
|
55
88
|
return [{ slug, branch: branchOf(slug), path, portOffset: saved[slug]?.portOffset ?? 0, createdAt: saved[slug]?.createdAt }]
|
|
56
89
|
})
|
|
90
|
+
return preview && previewAt ? [...listed, { slug: PREVIEW, branch: '', path: previewAt, portOffset: preview.portOffset, createdAt: preview.createdAt, kind: 'preview' }] : listed
|
|
57
91
|
}
|
|
58
92
|
|
|
93
|
+
/** Oldest first, the preview last: the order checkouts are listed and merged in. */
|
|
94
|
+
export const byAge = (a: Workspace, b: Workspace) => Number(Boolean(a.kind)) - Number(Boolean(b.kind)) || (a.createdAt ?? '').localeCompare(b.createdAt ?? '')
|
|
95
|
+
|
|
96
|
+
/** The open workspaces of a list, oldest first, without the preview: the ones work is merged from. */
|
|
97
|
+
export const openOf = (list: Workspace[]) => list.filter((w) => !w.kind && existsSync(w.path)).sort(byAge)
|
|
98
|
+
|
|
99
|
+
export const openWorkspaces = async (main: string, state?: State) => openOf(await workspaces(main, state))
|
|
100
|
+
|
|
59
101
|
/** The main checkout, at offset 0, and every workspace. */
|
|
60
102
|
export const checkouts = async (main: string, state?: State): Promise<Place[]> => [
|
|
61
103
|
{ slug: 'main', path: main, portOffset: 0, main },
|
|
62
104
|
...(await workspaces(main, state)).map((w) => ({ slug: w.slug, path: w.path, portOffset: w.portOffset, main })),
|
|
63
105
|
]
|
|
64
106
|
|
|
65
|
-
/** The checkout the command runs in. The main checkout is `main`, at offset 0, and not a workspace
|
|
107
|
+
/** The checkout the command runs in. The main checkout is `main`, at offset 0, and not a workspace; the preview answers as `all`. */
|
|
66
108
|
export async function current(cwd = process.cwd()) {
|
|
67
109
|
const [common = '.git', root = cwd, branch = ''] = git(cwd, 'rev-parse', '--git-common-dir', '--show-toplevel', '--abbrev-ref', 'HEAD').split('\n')
|
|
68
110
|
const main = dirname(resolve(cwd, common))
|
|
@@ -70,9 +112,14 @@ export async function current(cwd = process.cwd()) {
|
|
|
70
112
|
return ws ? { ...ws, main, isWorkspace: true } : { slug: 'main', branch, path: root, portOffset: 0, main, isWorkspace: false }
|
|
71
113
|
}
|
|
72
114
|
|
|
73
|
-
/**
|
|
74
|
-
export
|
|
115
|
+
/** Fails in the preview: it is rebuilt by `able ws preview`, never committed to, pushed or merged from. */
|
|
116
|
+
export const refuseInPreview = (at: { kind?: string }, what: string) =>
|
|
117
|
+
at.kind === 'preview' && fail(`${what} doesn't run in the preview: it is read-only, rebuilt by able ws preview; make the change in its workspace`)
|
|
118
|
+
|
|
119
|
+
/** The workspace a command runs in, with its config; fails in the main checkout, the preview, or during a merge. */
|
|
120
|
+
export async function inWorkspace(what: string): Promise<{ ws: Awaited<ReturnType<typeof current>>; config: AbleConfig }> {
|
|
75
121
|
const ws = await current()
|
|
122
|
+
refuseInPreview(ws, what)
|
|
76
123
|
if (!ws.isWorkspace) fail('not inside a workspace')
|
|
77
124
|
failOnMerge(ws.path)
|
|
78
125
|
return { ws, config: await loadConfig(ws.path) }
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// The trunk rule: every command means `origin/<trunk>`, and commits only on `local <trunk>` never leave inside a merge.
|
|
2
|
+
|
|
3
|
+
import { expect, test } from 'bun:test'
|
|
4
|
+
import { commit, git, host, run } from './fixture.ts'
|
|
5
|
+
|
|
6
|
+
test('ws new warns about unpushed commits on local main, and cuts from origin/main', () => {
|
|
7
|
+
const h = host()
|
|
8
|
+
commit(h.main, 'local.txt', 'mine\n', 'local only')
|
|
9
|
+
const r = run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
10
|
+
expect(r.code).toBe(0)
|
|
11
|
+
expect(r.out).toContain('1 commit(s) on local main not in the new workspace')
|
|
12
|
+
expect(r.out).toContain('local only')
|
|
13
|
+
expect(git(h.ws('one'), 'log', '--format=%s')).not.toContain('local only')
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
test('ws refresh merges origin/main only, and names what it left out', () => {
|
|
17
|
+
const h = host()
|
|
18
|
+
run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
19
|
+
commit(h.main, 'pushed.txt', 'p\n', 'pushed')
|
|
20
|
+
git(h.main, 'push', '--quiet', 'origin', 'main')
|
|
21
|
+
commit(h.main, 'local.txt', 'mine\n', 'local only')
|
|
22
|
+
const r = run(h.ws('one'), 'ws', 'refresh')
|
|
23
|
+
expect(r.code).toBe(0)
|
|
24
|
+
expect(r.out).toContain('1 commit(s) on local main not included')
|
|
25
|
+
const log = git(h.ws('one'), 'log', '--format=%s')
|
|
26
|
+
expect(log).toContain('pushed')
|
|
27
|
+
expect(log).not.toContain('local only')
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
test('ws merge never carries a commit that is only on local main', () => {
|
|
31
|
+
const h = host()
|
|
32
|
+
run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
33
|
+
commit(h.ws('one'), 'work.txt', 'w\n', 'work')
|
|
34
|
+
commit(h.main, 'local.txt', 'mine\n', 'local only')
|
|
35
|
+
|
|
36
|
+
// A plain merge: origin/main gets the work, never the local commit.
|
|
37
|
+
expect(run(h.ws('one'), 'ws', 'merge', '--yes', '--keep-open').code).toBe(0)
|
|
38
|
+
const onOrigin = git(h.main, 'log', '--format=%s', 'origin/main')
|
|
39
|
+
expect(onOrigin).toContain('work')
|
|
40
|
+
expect(onOrigin).not.toContain('local only')
|
|
41
|
+
|
|
42
|
+
// A branch that took local main in (as the old refresh did) is refused, naming the commit.
|
|
43
|
+
git(h.ws('one'), 'merge', '--quiet', '--no-edit', 'main')
|
|
44
|
+
commit(h.ws('one'), 'more.txt', 'm\n', 'more')
|
|
45
|
+
const r = run(h.ws('one'), 'ws', 'merge', '--yes', '--keep-open')
|
|
46
|
+
expect(r.code).not.toBe(0)
|
|
47
|
+
expect(r.out).toContain('holds 1 commit(s) from local main')
|
|
48
|
+
expect(r.out).toContain('local only')
|
|
49
|
+
expect(git(h.main, 'log', '--format=%s', 'origin/main')).not.toContain('more')
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
test('an unreachable origin is reported: a read carries on, a push fails', () => {
|
|
53
|
+
const h = host()
|
|
54
|
+
run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
55
|
+
commit(h.ws('one'), 'work.txt', 'w\n', 'work')
|
|
56
|
+
git(h.main, 'remote', 'set-url', 'origin', `${h.dir}/gone.git`)
|
|
57
|
+
|
|
58
|
+
const refresh = run(h.ws('one'), 'ws', 'refresh')
|
|
59
|
+
expect(refresh.code).toBe(0)
|
|
60
|
+
expect(refresh.out).toMatch(/couldn't reach origin; using origin\/main as of \S/)
|
|
61
|
+
|
|
62
|
+
const merge = run(h.ws('one'), 'ws', 'merge', '--yes', '--keep-open')
|
|
63
|
+
expect(merge.code).not.toBe(0)
|
|
64
|
+
expect(merge.out).toContain("couldn't reach origin")
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
test("ws merge doesn't blame local main for the branch's own commits, even when local main was moved onto them", () => {
|
|
68
|
+
const h = host()
|
|
69
|
+
run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
70
|
+
commit(h.ws('one'), 'work.txt', 'w\n', 'work')
|
|
71
|
+
git(h.main, 'merge', '--quiet', '--ff-only', 'feat/one')
|
|
72
|
+
const r = run(h.ws('one'), 'ws', 'merge', '--yes', '--keep-open')
|
|
73
|
+
expect(r.out).not.toContain('from local main')
|
|
74
|
+
expect(r.code).toBe(0)
|
|
75
|
+
expect(git(h.main, 'log', '--format=%s', 'origin/main')).toContain('work')
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
test('ws refresh names local main commits the branch already holds apart from those it left out', () => {
|
|
79
|
+
const h = host()
|
|
80
|
+
run(h.main, 'ws', 'new', 'one', '--no-brief')
|
|
81
|
+
commit(h.ws('one'), 'work.txt', 'w\n', 'work')
|
|
82
|
+
commit(h.main, 'local.txt', 'mine\n', 'local only')
|
|
83
|
+
git(h.ws('one'), 'merge', '--quiet', '--no-edit', 'main')
|
|
84
|
+
const r = run(h.ws('one'), 'ws', 'refresh')
|
|
85
|
+
expect(r.code).toBe(0)
|
|
86
|
+
expect(r.out).not.toContain('not included')
|
|
87
|
+
expect(r.out).toContain('1 commit(s) from local main already in feat/one')
|
|
88
|
+
})
|
package/sync.ts
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
import { existsSync } from 'node:fs'
|
|
16
16
|
import { dirname, join, relative, resolve } from 'node:path'
|
|
17
17
|
import { hostRoot, loadConfig } from './config.ts'
|
|
18
|
+
import { fetchTrunk, needOrigin } from './src/git.ts'
|
|
18
19
|
import { status, working } from './src/status.ts'
|
|
19
20
|
import { fail as failWith } from './src/ui.ts'
|
|
20
21
|
|
|
@@ -41,8 +42,9 @@ if (resolve(root, git('rev-parse', '--git-dir')) !== resolve(root, git('rev-pars
|
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
const step = working('sync')
|
|
44
|
-
step(`fetching
|
|
45
|
-
|
|
45
|
+
step(`fetching origin/${trunk}`)
|
|
46
|
+
// Offline it still reads and reports; it fails only once it has records to push.
|
|
47
|
+
const fetched = fetchTrunk(root, trunk)
|
|
46
48
|
const behind = Number(git('rev-list', '--count', `HEAD..origin/${trunk}`) || '0')
|
|
47
49
|
if (behind) fail(`this checkout is ${behind} commit(s) behind origin/${trunk}; pull first, or the records merged since are missed. Nothing done.`)
|
|
48
50
|
|
|
@@ -287,6 +289,7 @@ if (reasons.length) {
|
|
|
287
289
|
status({ state: 'done', msg: `${summary}, left uncommitted` })
|
|
288
290
|
process.exit(0)
|
|
289
291
|
}
|
|
292
|
+
needOrigin(fetched, trunk)
|
|
290
293
|
const names = due.map(weekName).join(', ')
|
|
291
294
|
const able = [process.execPath, join(import.meta.dir, 'able.ts')]
|
|
292
295
|
step('publishing the week records')
|