- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/src/drafts.ts?version=287&format=json
172 linesFirst import 94% · pinch 3% · rename 3%Last change pinch in version 280, 4 versions changed it
You're reading version 287. The newest is 318, and no version since then changed this file.
1// abso switch, land and draft-sync: named drafts (#10, #22).
2//
3// Each agent has its own unpublished draft in each space (shared, or a named
4// draft). Switching parks the draft on the server in the space it leaves and
5// brings back what was parked in the space it moves to, so nothing needs
6// publishing first. `switch -c <name>` instead takes the current unpublished
7// changes into a new named draft.
9import { readFileSync } from "node:fs";
10import { bool, type Parsed, str, UsageError } from "./args.ts";
11import {
12 applyAnswer,
13 changedFilesText,
14 collisionsHeading,
15 collisionText,
16 type Env,
17 EXIT,
18 mergedLinesText,
19 type Output,
20 open,
21 plural,
22 pullAnswer,
23 pullWritten,
24 recordedFirst,
25 recordFolder,
26} from "./commands.ts";
27import { isLocalOnly } from "./core.ts";
28import { absolute } from "./folder.ts";
29import { refusedText } from "./safety.ts";
31/** The name that means shared, not a named draft. */
32const SHARED = "shared";
34function draftName(raw: string): string {
35 if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(raw))
36 throw new UsageError(`draft names are letters, digits, dot, dash and underscore (got ${JSON.stringify(raw)})`);
37 return raw;
38}
40export async function runSwitch(args: Parsed, env: Env): Promise<Output> {
41 if (args.positionals.length !== 1)
42 throw new UsageError(
43 "switch takes one name: abso switch <draft>, abso switch -c <new draft>, or abso switch shared",
44 );
45 const raw = args.positionals[0]!;
46 const carry = bool(args, "carry");
47 const name = raw === SHARED ? null : draftName(raw);
48 if (carry && name === null)
49 throw new UsageError("-c starts a new named draft; shared already exists (use: abso switch shared)");
50 const { root, api } = open(env);
51 // Folder-only edits must be on the server first, or the new view would overwrite them instead of parking them.
52 const recorded = await recordFolder(root, api);
53 // What the folder held before, for each file the switch or the sync touches, so only the net change is reported.
54 const before = new Map<string, string | null>();
55 const note = (files: Readonly<Record<string, unknown>>): void => {
56 for (const rel of Object.keys(files)) if (!before.has(rel)) before.set(rel, onDisk(root, rel));
57 };
58 const answer = await api.switchDraft(name, carry);
59 note(answer.files);
60 const switched = await applyAnswer(root, api, answer);
61 // The switch brings back the space as it was when parked; sync straight away so the folder shows it as it is now (#22).
62 const syncAnswer = await pullAnswer(root, api);
63 note(syncAnswer.files);
64 const synced = await applyAnswer(root, api, syncAnswer);
65 pullWritten(root);
66 const touched = new Set([...switched.written, ...switched.deleted, ...synced.written, ...synced.deleted]);
67 const written: string[] = [];
68 const deleted: string[] = [];
69 for (const rel of [...touched].sort()) {
70 const now = onDisk(root, rel);
71 if (now === before.get(rel)) continue;
72 (now === null ? deleted : written).push(rel);
73 }
74 const where = answer.draft === null ? "shared" : `draft ${answer.draft}`;
75 const kept = [...new Set([...switched.kept, ...synced.kept])];
76 const dropped = [...new Set([...switched.dropped, ...synced.dropped])];
77 const collisions = [...switched.collisions, ...synced.collisions];
78 const lines = [
79 ...recordedFirst(recorded),
80 carry
81 ? `Started ${where}, carrying your unpushed changes into it.`
82 : `Switched to ${where}. Your unpushed changes where you were are parked there, and come back when you switch back.`,
83 `It is at version ${synced.version}. ${written.length + deleted.length === 0 ? "No files changed in this folder." : `${plural(written.length, "file")} updated, ${deleted.length} deleted:`}`,
84 ...changedFilesText("switch", written, deleted, [], bool(args, "verbose")),
85 ...refusedText([...switched.refused, ...synced.refused]),
86 ...mergedLinesText([...switched.merged, ...synced.merged]),
87 ...(kept.length > 0 ? [`Left alone because they changed while switching (run abso pull): ${kept.join(", ")}`] : []),
88 ...(dropped.length > 0 ? [`Dropped from your draft, kept on disk (these stay local): ${dropped.join(", ")}`] : []),
89 ...(collisions.length > 0 ? [collisionsHeading(collisions), ...collisions.map(collisionText)] : []),
90 ...(answer.draft !== null
91 ? ['Push into this draft with abso push; land it in shared with abso land -m "why".']
92 : []),
93 ];
94 return {
95 text: lines.join("\n"),
96 json: {
97 draft: answer.draft,
98 version: synced.version,
99 carried: carry,
100 recorded: recorded.sent,
101 written,
102 deleted,
103 kept,
104 dropped,
105 collisions,
106 },
107 };
108}
110/** A file's bytes as text, or null when there is no file. */
111function onDisk(root: string, rel: string): string | null {
112 try {
113 return readFileSync(absolute(root, rel), "latin1");
114 } catch {
115 return null;
116 }
117}
119export async function runLand(args: Parsed, env: Env): Promise<Output> {
120 const message = str(args, "message");
121 if (!message) throw new UsageError('say why with -m "<message>"');
122 const { root, api } = open(env);
123 const recorded = await recordFolder(root, api);
124 const answer = await api.land(message);
125 const pre = recordedFirst(recorded);
126 if (answer.ok) {
127 const what =
128 answer.changes === 0
129 ? `Nothing to land: the draft has nothing shared doesn't. Shared is at version ${answer.version}.`
130 : `Landed in shared as version ${answer.version}.`;
131 return {
132 text: [...pre, what].join("\n"),
133 json: { version: answer.version, changes: answer.changes ?? null, recorded: recorded.sent },
134 };
135 }
136 const collisions = (answer.collisions ?? []).filter((c) => !isLocalOnly(c.file));
137 return {
138 exit: EXIT.refused,
139 text: [
140 ...pre,
141 `Not landed: ${plural(collisions.length, "collision")} with work that landed in shared since the draft's base.`,
142 ...collisions.map(collisionText),
143 "Run abso draft-pull to move the draft onto shared, settle those lines in the draft, push, then land again.",
144 ].join("\n"),
145 json: { collisions, recorded: recorded.sent },
146 };
147}
149export async function runDraftSync(_args: Parsed, env: Env): Promise<Output> {
150 const { root, api } = open(env);
151 const moved = await api.draftSync();
152 // Bring the moved draft's new view into this folder straight away.
153 const recorded = await recordFolder(root, api);
154 const applied = await applyAnswer(root, api, await pullAnswer(root, api));
155 pullWritten(root);
156 const lines = [
157 `Moved draft ${moved.draft} onto shared version ${moved.sharedBase} (the draft is at version ${moved.version}).`,
158 ...recordedFirst(recorded),
159 applied.written.length + applied.deleted.length === 0
160 ? "No files changed in this folder."
161 : `${plural(applied.written.length, "file")} updated, ${applied.deleted.length} deleted.`,
162 ...refusedText(applied.refused),
163 ...mergedLinesText(applied.merged),
164 ...(applied.collisions.length > 0
165 ? [
166 `${plural(applied.collisions.length, "collision")} to settle in the draft before it lands:`,
167 ...applied.collisions.map(collisionText),
168 ]
169 : []),
170 ];
171 return { text: lines.join("\n"), json: { ...applied, ...moved } };
172}