@operad-io/bot 0.1.1 → 0.3.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/README.md +1 -1
- package/bot.schema.json +40 -2
- package/package.json +6 -4
- package/src/bot.ts +588 -70
- package/src/chat-watch.ts +101 -0
- package/src/create.ts +230 -0
- package/src/follow-up.ts +313 -0
- package/src/index.ts +544 -29
- package/src/login.ts +226 -0
- package/src/mcp-proposals.ts +2 -2
- package/src/proposals.ts +392 -79
- package/src/schedule.ts +1184 -0
- package/src/setup-dev.ts +282 -0
- package/src/setup-git.ts +323 -0
- package/src/setup.ts +113 -0
- package/src/tidy.ts +1021 -0
package/src/setup-dev.ts
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Setup Dev (ADR 0030 D15): turns on `dev` for one repository through a
|
|
3
|
+
* proposal. The prepared prompt has a bot's agent read the repository and
|
|
4
|
+
* propose a `.operad/dev.json` (the prompt is the `dev` plugin's guide, read
|
|
5
|
+
* through `./setup.ts`); approving the proposal turns the plugins on,
|
|
6
|
+
* writes the file and asks `dev` to register the repository.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
13
|
+
import {
|
|
14
|
+
isMissingFile,
|
|
15
|
+
isRecord,
|
|
16
|
+
messageOf,
|
|
17
|
+
readConfig,
|
|
18
|
+
setPluginEnabled,
|
|
19
|
+
type CommandContext,
|
|
20
|
+
type ObjectStore,
|
|
21
|
+
} from "@operad-io/engine";
|
|
22
|
+
import { findGit, writeFileAtomic } from "@operad-io/engine/platform";
|
|
23
|
+
import { BotError, readBots } from "./bot.ts";
|
|
24
|
+
import { setupDevPrompt } from "./setup.ts";
|
|
25
|
+
|
|
26
|
+
/** The plugins `dev` needs, with the package each is enabled from. */
|
|
27
|
+
export const SETUP_DEV_PLUGINS: Readonly<Record<string, string>> = {
|
|
28
|
+
dev: "@operad-io/dev",
|
|
29
|
+
shell: "@operad-io/shell",
|
|
30
|
+
pool: "@operad-io/pool",
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** The directory under the home where a request to register a repository is left for `dev`. */
|
|
34
|
+
export const DEV_REGISTER_DIRECTORY = "dev-register";
|
|
35
|
+
|
|
36
|
+
/** What a `dev` proposal stores. */
|
|
37
|
+
export interface DevChange {
|
|
38
|
+
/** The repository's directory, resolved. */
|
|
39
|
+
readonly repo: string;
|
|
40
|
+
/** The `dev.json` text to write. */
|
|
41
|
+
readonly json: string;
|
|
42
|
+
/** The file's present text; null when there is none. */
|
|
43
|
+
readonly before: string | null;
|
|
44
|
+
/** The plugins that are off now and would be turned on. */
|
|
45
|
+
readonly plugins: readonly string[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const USAGE = "usage: operad bot setup-dev <bot> <repository directory> [< dev.json]";
|
|
49
|
+
|
|
50
|
+
/** The line a bot chat starts with, so a sentence is enough to start Setup Dev. */
|
|
51
|
+
export const SETUP_DEV_INSTRUCTION =
|
|
52
|
+
"To set up dev for a repository (Setup Dev), call the operad `command` tool with plugin `bot`, verb `setup-dev`, my bot and the repository's directory and no input: it answers with the steps. Nothing is turned on until I approve the proposal in Pending.";
|
|
53
|
+
|
|
54
|
+
function git(directory: string, args: readonly string[]): string | undefined {
|
|
55
|
+
const program = findGit();
|
|
56
|
+
if (program === undefined) return undefined;
|
|
57
|
+
try {
|
|
58
|
+
return execFileSync(program, ["-C", directory, ...args], {
|
|
59
|
+
encoding: "utf8",
|
|
60
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
61
|
+
}).trim();
|
|
62
|
+
} catch {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// The top of the work tree `directory` is in; undefined when there is no git
|
|
68
|
+
// program or git says, in English, that the folder is in no work tree. Any other
|
|
69
|
+
// refusal (dubious ownership, an unreadable .git, nothing printed) is an error
|
|
70
|
+
// carrying git's message: the folder may be a repository.
|
|
71
|
+
function toplevelOf(directory: string): string | undefined {
|
|
72
|
+
const program = findGit();
|
|
73
|
+
if (program === undefined) return undefined;
|
|
74
|
+
const result = spawnSync(program, ["-C", directory, "rev-parse", "--show-toplevel"], {
|
|
75
|
+
encoding: "utf8",
|
|
76
|
+
env: { ...process.env, LC_ALL: "C", LANGUAGE: "" },
|
|
77
|
+
});
|
|
78
|
+
const top = (result.stdout ?? "").trim();
|
|
79
|
+
if (result.status === 0 && top.length > 0) return top;
|
|
80
|
+
const reason = (result.stderr ?? "").trim();
|
|
81
|
+
if (result.status !== 0 && /not a git repository|this operation must be run in a work tree/i.test(reason)) {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
throw new BotError(`setup-dev: git cannot tell what "${directory}" is: ${reason.length > 0 ? reason : "it printed nothing"}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function rootOf(path: string): string {
|
|
88
|
+
if (!existsSync(path) || !statSync(path).isDirectory()) {
|
|
89
|
+
throw new BotError(`setup-dev: there is no directory "${path}"`);
|
|
90
|
+
}
|
|
91
|
+
const real = realpathSync(path);
|
|
92
|
+
// A folder needs git only to create a task: without the program, or in no
|
|
93
|
+
// repository, it is set up as it is. A subfolder of a repository is refused.
|
|
94
|
+
const top = toplevelOf(real);
|
|
95
|
+
if (top !== undefined && realpathSync(top) !== real) {
|
|
96
|
+
throw new BotError(`setup-dev: "${path}" is inside the git repository at "${top}"; use "${top}" instead`);
|
|
97
|
+
}
|
|
98
|
+
return real;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function registeredPaths(store: ObjectStore): Promise<string[]> {
|
|
102
|
+
const found: string[] = [];
|
|
103
|
+
let cursor: string | undefined;
|
|
104
|
+
do {
|
|
105
|
+
const page = await store.list("repo", { ...(cursor === undefined ? {} : { cursor }) });
|
|
106
|
+
for (const object of page.objects) {
|
|
107
|
+
if (typeof object.data.path === "string" && object.data.removed !== true) found.push(object.data.path);
|
|
108
|
+
}
|
|
109
|
+
cursor = page.next;
|
|
110
|
+
} while (cursor !== undefined);
|
|
111
|
+
return found;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function pluginsOff(home: string): Promise<string[]> {
|
|
115
|
+
const enabled: string[] = [];
|
|
116
|
+
try {
|
|
117
|
+
for (const entry of (await readConfig(home)).plugins) {
|
|
118
|
+
if (entry.enabled && entry.name !== undefined) enabled.push(entry.name);
|
|
119
|
+
}
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (!isMissingFile(error)) throw error;
|
|
122
|
+
}
|
|
123
|
+
return Object.keys(SETUP_DEV_PLUGINS).filter((name) => !enabled.includes(name));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Proposes Setup Dev for a repository; nothing is turned on or written. */
|
|
127
|
+
export async function proposeDev(
|
|
128
|
+
store: ObjectStore,
|
|
129
|
+
home: string,
|
|
130
|
+
bot: string,
|
|
131
|
+
repoPath: string,
|
|
132
|
+
jsonText: string,
|
|
133
|
+
cwd: string,
|
|
134
|
+
makeProposal: (change: DevChange) => Promise<string>,
|
|
135
|
+
): Promise<string> {
|
|
136
|
+
if (readBots(home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
|
|
137
|
+
const repo = rootOf(isAbsolute(repoPath) ? repoPath : resolve(cwd, repoPath));
|
|
138
|
+
let parsed: unknown;
|
|
139
|
+
try {
|
|
140
|
+
parsed = JSON.parse(jsonText);
|
|
141
|
+
} catch (error) {
|
|
142
|
+
throw new BotError(`setup-dev: the dev.json text is not JSON: ${messageOf(error)}`);
|
|
143
|
+
}
|
|
144
|
+
if (!isRecord(parsed)) throw new BotError("setup-dev: the dev.json text must be a JSON object");
|
|
145
|
+
// A repository with no remote works on its local main branch: the file names none.
|
|
146
|
+
if ((git(repo, ["remote"]) ?? "").length === 0) delete parsed.remote;
|
|
147
|
+
// Without a repository the work is done in the folder itself, whatever the text says.
|
|
148
|
+
if (toplevelOf(repo) === undefined) {
|
|
149
|
+
parsed.workIn = "branch";
|
|
150
|
+
delete parsed.concurrency;
|
|
151
|
+
}
|
|
152
|
+
if ((await registeredPaths(store)).some((path) => resolve(path) === repo)) {
|
|
153
|
+
throw new BotError(`setup-dev: "${repo}" is already registered`);
|
|
154
|
+
}
|
|
155
|
+
const file = join(repo, ".operad", "dev.json");
|
|
156
|
+
let before: string | null = null;
|
|
157
|
+
try {
|
|
158
|
+
before = readFileSync(file, "utf8");
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (!isMissingFile(error)) throw error;
|
|
161
|
+
}
|
|
162
|
+
return makeProposal({
|
|
163
|
+
repo,
|
|
164
|
+
json: `${JSON.stringify(parsed, null, 2)}\n`,
|
|
165
|
+
before,
|
|
166
|
+
plugins: await pluginsOff(home),
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Turns the plugins on, writes `dev.json` and leaves the request `dev` registers the repository from. */
|
|
171
|
+
export async function applyDev(home: string, change: DevChange): Promise<void> {
|
|
172
|
+
const directory = join(change.repo, ".operad");
|
|
173
|
+
mkdirSync(directory, { recursive: true });
|
|
174
|
+
await writeFileAtomic(join(directory, "dev.json"), change.json);
|
|
175
|
+
const requests = join(home, DEV_REGISTER_DIRECTORY);
|
|
176
|
+
mkdirSync(requests, { recursive: true });
|
|
177
|
+
writeFileSync(join(requests, `${randomUUID()}.json`), `${JSON.stringify({ path: change.repo })}\n`);
|
|
178
|
+
// Last, because a change of config.json reloads serve and dev then finds the request.
|
|
179
|
+
for (const name of await pluginsOff(home)) {
|
|
180
|
+
await setPluginEnabled(home, name, true, { optional: SETUP_DEV_PLUGINS });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The review of a `dev` proposal. */
|
|
185
|
+
export function devReview(bot: string, change: DevChange): string {
|
|
186
|
+
const out = [
|
|
187
|
+
`## Setup Dev for ${change.repo}`,
|
|
188
|
+
"",
|
|
189
|
+
`Proposed by bot ${bot}. Approve turns on ${
|
|
190
|
+
change.plugins.length === 0 ? "nothing (dev is already on)" : change.plugins.join(", ")
|
|
191
|
+
}, writes \`.operad/dev.json\` and registers the repository. Reject changes nothing.`,
|
|
192
|
+
];
|
|
193
|
+
if (change.before !== null) {
|
|
194
|
+
out.push("", "### dev.json now", "", "```json", change.before.trimEnd(), "```");
|
|
195
|
+
}
|
|
196
|
+
out.push("", change.before === null ? "### dev.json" : "### dev.json after", "", "```json", change.json.trimEnd(), "```");
|
|
197
|
+
return out.join("\n");
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Reads a stored change; undefined when it is not one. */
|
|
201
|
+
export function devChangeOf(value: unknown): DevChange | undefined {
|
|
202
|
+
if (
|
|
203
|
+
!isRecord(value) ||
|
|
204
|
+
typeof value.repo !== "string" ||
|
|
205
|
+
typeof value.json !== "string" ||
|
|
206
|
+
!(value.before === null || typeof value.before === "string") ||
|
|
207
|
+
!Array.isArray(value.plugins)
|
|
208
|
+
) {
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
return {
|
|
212
|
+
repo: value.repo,
|
|
213
|
+
json: value.json,
|
|
214
|
+
before: value.before,
|
|
215
|
+
plugins: value.plugins.filter((item): item is string => typeof item === "string"),
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** The stream a command reads, and what a test may stand in for. */
|
|
220
|
+
export interface PipedInput {
|
|
221
|
+
/** Defaults to the process's standard input. */
|
|
222
|
+
readonly stream?: (AsyncIterable<Uint8Array | string> & { readonly destroy?: () => void }) | undefined;
|
|
223
|
+
/** Settles when a stream that has delivered nothing is given up on; defaults to a timer. */
|
|
224
|
+
readonly giveUp?: Promise<void> | undefined;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const FIRST_BYTES_MS = 2000;
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* The text piped to a command that was given none. A terminal, and a pipe that
|
|
231
|
+
* delivers nothing before the deadline, are no input; once data starts the
|
|
232
|
+
* read goes on to the end.
|
|
233
|
+
*/
|
|
234
|
+
export async function readPiped(input: string | undefined, options: PipedInput = {}): Promise<string> {
|
|
235
|
+
if (input !== undefined) return input;
|
|
236
|
+
const stream = options.stream ?? process.stdin;
|
|
237
|
+
if (options.stream === undefined && process.stdin.isTTY === true) return "";
|
|
238
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
239
|
+
const giveUp =
|
|
240
|
+
options.giveUp ??
|
|
241
|
+
new Promise<void>((done) => {
|
|
242
|
+
timer = setTimeout(done, FIRST_BYTES_MS);
|
|
243
|
+
});
|
|
244
|
+
const iterator = stream[Symbol.asyncIterator]();
|
|
245
|
+
try {
|
|
246
|
+
const first = await Promise.race([iterator.next(), giveUp.then(() => undefined)]);
|
|
247
|
+
if (first === undefined) {
|
|
248
|
+
try {
|
|
249
|
+
stream.destroy?.();
|
|
250
|
+
} catch {
|
|
251
|
+
// The stream already ended.
|
|
252
|
+
}
|
|
253
|
+
return "";
|
|
254
|
+
}
|
|
255
|
+
const chunks: Buffer[] = [];
|
|
256
|
+
let step = first;
|
|
257
|
+
while (!step.done) {
|
|
258
|
+
chunks.push(typeof step.value === "string" ? Buffer.from(step.value, "utf8") : Buffer.from(step.value));
|
|
259
|
+
step = await iterator.next();
|
|
260
|
+
}
|
|
261
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
262
|
+
} finally {
|
|
263
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** `bot setup-dev <bot> <directory>`: with `dev.json` on stdin it proposes, without it answers the steps. */
|
|
268
|
+
export async function runSetupDevCommand(
|
|
269
|
+
ctx: CommandContext,
|
|
270
|
+
argv: readonly string[],
|
|
271
|
+
propose: (bot: string, change: DevChange) => Promise<string>,
|
|
272
|
+
piped: PipedInput = {},
|
|
273
|
+
): Promise<string> {
|
|
274
|
+
const bot = argv[0];
|
|
275
|
+
const repo = argv[1];
|
|
276
|
+
if (bot === undefined || repo === undefined || argv.length > 2) throw new BotError(USAGE);
|
|
277
|
+
if (readBots(ctx.home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
|
|
278
|
+
const text = (await readPiped(ctx.input, piped)).trim();
|
|
279
|
+
const resolved = isAbsolute(repo) ? repo : resolve(ctx.cwd, repo);
|
|
280
|
+
if (text.length === 0) return setupDevPrompt(ctx.setup, bot, resolved);
|
|
281
|
+
return proposeDev(ctx.store, ctx.home, bot, repo, text, ctx.cwd, (change) => propose(bot, change));
|
|
282
|
+
}
|
package/src/setup-git.ts
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "Set up git here" (ADR 0039 D8): the bot's side. A task needs git, and a
|
|
3
|
+
* folder may have none; at the first task the bot's agent calls the agent-only
|
|
4
|
+
* verb `setup-git` and a pending item titled "Set up git here" (在这里设置 git)
|
|
5
|
+
* shows the `.gitignore`, the files the first commit would hold and the name and
|
|
6
|
+
* email the commit is made with. Nothing is written into the folder, and git is
|
|
7
|
+
* not run in it, until the person approves; approval leaves a request that
|
|
8
|
+
* `dev` carries out (`dev/src/setup-git.ts`).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
12
|
+
import { mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { hostname, userInfo } from "node:os";
|
|
14
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_GITIGNORE,
|
|
17
|
+
DEV_GIT_GUIDE,
|
|
18
|
+
existingGitignore,
|
|
19
|
+
firstCommitList,
|
|
20
|
+
gitStateOf,
|
|
21
|
+
type FirstCommitList,
|
|
22
|
+
} from "@operad-io/dev";
|
|
23
|
+
import { isRecord, messageOf, type CommandContext } from "@operad-io/engine";
|
|
24
|
+
import type { GitFinderHost } from "@operad-io/engine/platform";
|
|
25
|
+
import { BotError, readBots } from "./bot.ts";
|
|
26
|
+
import { readPiped, type PipedInput } from "./setup-dev.ts";
|
|
27
|
+
import { renderGuide } from "./setup.ts";
|
|
28
|
+
|
|
29
|
+
/** The directory under the home where requests for `dev` are left (the one Setup Dev uses). */
|
|
30
|
+
const REQUESTS_DIRECTORY = "dev-register";
|
|
31
|
+
|
|
32
|
+
/** The title of the pending item, in English and in Chinese. */
|
|
33
|
+
export const SETUP_GIT_TITLE = "Set up git here";
|
|
34
|
+
export const SETUP_GIT_TITLE_ZH = "在这里设置 git";
|
|
35
|
+
|
|
36
|
+
/** The paths a review lists before it says how many more there are. */
|
|
37
|
+
const REVIEW_PATHS = 200;
|
|
38
|
+
|
|
39
|
+
/** The name and email a commit is made with. */
|
|
40
|
+
export interface GitIdentityFields {
|
|
41
|
+
readonly name: string;
|
|
42
|
+
readonly email: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** What a "Set up git here" proposal stores. */
|
|
46
|
+
export interface GitChange {
|
|
47
|
+
/** The folder, resolved. */
|
|
48
|
+
readonly repo: string;
|
|
49
|
+
/** The `.gitignore` text that is written and committed. */
|
|
50
|
+
readonly gitignore: string;
|
|
51
|
+
/** The folder's own `.gitignore` text now; null when it has none. */
|
|
52
|
+
readonly before: string | null;
|
|
53
|
+
/** The files the first commit holds, exactly; approval commits these and nothing else. */
|
|
54
|
+
readonly files: readonly string[];
|
|
55
|
+
/** Folders that are repositories of their own; they are not committed. */
|
|
56
|
+
readonly nested: readonly string[];
|
|
57
|
+
/** The sentence that asks to check the `.gitignore` first, when the folder is large. */
|
|
58
|
+
readonly note: string | null;
|
|
59
|
+
/** The name and email to store in the repository; null when git already has an identity. */
|
|
60
|
+
readonly identity: GitIdentityFields | null;
|
|
61
|
+
/** True when the folder has no repository yet; false when it has one without a commit. */
|
|
62
|
+
readonly init: boolean;
|
|
63
|
+
/** The language of the pending item's title. */
|
|
64
|
+
readonly language: "en" | "zh";
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const USAGE =
|
|
68
|
+
'usage: operad bot setup-git <bot> <folder> [< {"gitignore": "...", "identity": {"name": "...", "email": "..."}}]';
|
|
69
|
+
|
|
70
|
+
/** The line a bot chat starts with: when the agent proposes the git setup, and that git is never asked about before. */
|
|
71
|
+
export const SETUP_GIT_INSTRUCTION =
|
|
72
|
+
"When I want a task in a folder and operad answers that git is not installed or not set up there, call the operad `command` tool with plugin `bot`, verb `setup-git`, my bot and the folder, with no input: it answers with the steps. Never ask me about git before that; chatting and changing files need none. Nothing is installed or written until I approve it in Pending.";
|
|
73
|
+
|
|
74
|
+
/** The language of the title: Chinese when the computer's locale is. */
|
|
75
|
+
export function titleLanguage(env: NodeJS.ProcessEnv = process.env): "en" | "zh" {
|
|
76
|
+
const locale = env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? "";
|
|
77
|
+
return /^zh/i.test(locale) ? "zh" : "en";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The title of the pending item. */
|
|
81
|
+
export function gitTitle(language: "en" | "zh"): string {
|
|
82
|
+
return language === "zh" ? SETUP_GIT_TITLE_ZH : SETUP_GIT_TITLE;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** What the computer account says about the person, to prefill the commit's name and email. */
|
|
86
|
+
export interface AccountHost {
|
|
87
|
+
readonly username: () => string;
|
|
88
|
+
readonly hostname: () => string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const realAccount: AccountHost = { username: () => userInfo().username, hostname: () => hostname() };
|
|
92
|
+
|
|
93
|
+
/** The name and email prefilled from the computer account; the person confirms them in the chat. */
|
|
94
|
+
export function accountIdentity(host: AccountHost = realAccount): GitIdentityFields {
|
|
95
|
+
const name = host.username();
|
|
96
|
+
return { name, email: `${name}@${host.hostname()}` };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function parseInput(text: string): { gitignore: string | undefined; identity: GitIdentityFields | undefined } {
|
|
100
|
+
let parsed: unknown;
|
|
101
|
+
try {
|
|
102
|
+
parsed = JSON.parse(text);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
throw new BotError(`setup-git: the input is not JSON: ${messageOf(error)}`);
|
|
105
|
+
}
|
|
106
|
+
if (!isRecord(parsed)) throw new BotError("setup-git: the input must be a JSON object");
|
|
107
|
+
const gitignore = parsed.gitignore;
|
|
108
|
+
if (gitignore !== undefined && typeof gitignore !== "string") {
|
|
109
|
+
throw new BotError("setup-git: gitignore must be text");
|
|
110
|
+
}
|
|
111
|
+
let identity: GitIdentityFields | undefined;
|
|
112
|
+
if (parsed.identity !== undefined) {
|
|
113
|
+
const given = parsed.identity;
|
|
114
|
+
if (!isRecord(given) || typeof given.name !== "string" || typeof given.email !== "string") {
|
|
115
|
+
throw new BotError("setup-git: identity must have a name and an email, both text");
|
|
116
|
+
}
|
|
117
|
+
const name = given.name.trim();
|
|
118
|
+
const email = given.email.trim();
|
|
119
|
+
if (name === "" || !/^[^\s@]+@[^\s@]+$/.test(email)) {
|
|
120
|
+
throw new BotError("setup-git: identity needs a name and an email address such as name@example.com");
|
|
121
|
+
}
|
|
122
|
+
identity = { name, email };
|
|
123
|
+
}
|
|
124
|
+
return { gitignore, identity };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// The folder's own text with the default lines it does not have yet added after it.
|
|
128
|
+
function withDefaults(existing: string): string {
|
|
129
|
+
const have = new Set(existing.split("\n").map((line) => line.trim()));
|
|
130
|
+
const added = DEFAULT_GITIGNORE.split("\n").filter(
|
|
131
|
+
(line) => line.trim() !== "" && !line.startsWith("#") && !have.has(line.trim()),
|
|
132
|
+
);
|
|
133
|
+
if (added.length === 0) return existing;
|
|
134
|
+
return `${existing.endsWith("\n") || existing === "" ? existing : `${existing}\n`}${added.join("\n")}\n`;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function folderOf(path: string): string {
|
|
138
|
+
if (statSync(path, { throwIfNoEntry: false })?.isDirectory() !== true) {
|
|
139
|
+
throw new BotError(`setup-git: there is no directory "${path}"`);
|
|
140
|
+
}
|
|
141
|
+
return realpathSync(path);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** What a test may stand in for. */
|
|
145
|
+
export interface ProposeGitOptions {
|
|
146
|
+
readonly env?: NodeJS.ProcessEnv;
|
|
147
|
+
readonly account?: AccountHost;
|
|
148
|
+
/** The home folder that is refused; the default is the computer account's. */
|
|
149
|
+
readonly homeFolder?: string;
|
|
150
|
+
/** The machine the git program is looked up on; a test injects one without git. */
|
|
151
|
+
readonly finder?: GitFinderHost;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Makes the proposal for a folder; nothing is written into it. */
|
|
155
|
+
export function proposeGit(
|
|
156
|
+
home: string,
|
|
157
|
+
bot: string,
|
|
158
|
+
folderPath: string,
|
|
159
|
+
inputText: string,
|
|
160
|
+
cwd: string,
|
|
161
|
+
options: ProposeGitOptions = {},
|
|
162
|
+
): GitChange {
|
|
163
|
+
if (readBots(home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
|
|
164
|
+
const folder = folderOf(isAbsolute(folderPath) ? folderPath : resolve(cwd, folderPath));
|
|
165
|
+
const input = parseInput(inputText);
|
|
166
|
+
const state = gitStateOf(folder, {
|
|
167
|
+
...(options.env === undefined ? {} : { env: options.env }),
|
|
168
|
+
...(options.finder === undefined ? {} : { finder: options.finder }),
|
|
169
|
+
});
|
|
170
|
+
switch (state.state) {
|
|
171
|
+
case "no program":
|
|
172
|
+
throw new BotError(
|
|
173
|
+
"setup-git: git is not installed on this machine. Follow the steps for installing git (each command is a pending item the person approves), then call setup-git again.",
|
|
174
|
+
);
|
|
175
|
+
case "subfolder":
|
|
176
|
+
throw new BotError(
|
|
177
|
+
`setup-git: "${folder}" is inside the git repository at "${state.root}"; set up nothing here and use "${state.root}" instead`,
|
|
178
|
+
);
|
|
179
|
+
case "ready":
|
|
180
|
+
throw new BotError(`setup-git: "${folder}" already has git and a first commit; there is nothing to set up`);
|
|
181
|
+
default:
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
const own = existingGitignore(folder);
|
|
185
|
+
const text = input.gitignore ?? (own === undefined ? DEFAULT_GITIGNORE : withDefaults(own));
|
|
186
|
+
let list: FirstCommitList;
|
|
187
|
+
try {
|
|
188
|
+
list = firstCommitList(folder, text, {
|
|
189
|
+
...(options.homeFolder === undefined ? {} : { home: options.homeFolder }),
|
|
190
|
+
...(options.env === undefined ? {} : { env: options.env }),
|
|
191
|
+
});
|
|
192
|
+
} catch (error) {
|
|
193
|
+
throw new BotError(`setup-git: ${messageOf(error)}`);
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
repo: folder,
|
|
197
|
+
gitignore: text,
|
|
198
|
+
before: list.existingGitignore ?? null,
|
|
199
|
+
files: list.files,
|
|
200
|
+
nested: list.nested,
|
|
201
|
+
note: list.note ?? null,
|
|
202
|
+
identity: state.identity.set ? null : (input.identity ?? accountIdentity(options.account)),
|
|
203
|
+
init: state.state === "no repository",
|
|
204
|
+
language: titleLanguage(options.env),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The review of a "Set up git here" proposal. */
|
|
209
|
+
export function gitReview(bot: string, change: GitChange): string {
|
|
210
|
+
const out = [
|
|
211
|
+
`## ${gitTitle(change.language)}: ${change.repo}`,
|
|
212
|
+
"",
|
|
213
|
+
`Proposed by bot ${bot}. Approve ${
|
|
214
|
+
change.init ? "starts git in this folder and " : ""
|
|
215
|
+
}makes the first commit of the files below; the folder then works in a branch with no remote. Nothing is pushed. Reject changes nothing.`,
|
|
216
|
+
];
|
|
217
|
+
if (change.note !== null) out.push("", `**${change.note}**`);
|
|
218
|
+
out.push(
|
|
219
|
+
"",
|
|
220
|
+
change.before === null ? "### .gitignore (new)" : "### .gitignore (yours, with additions)",
|
|
221
|
+
"",
|
|
222
|
+
"```",
|
|
223
|
+
change.gitignore.trimEnd(),
|
|
224
|
+
"```",
|
|
225
|
+
"",
|
|
226
|
+
`### Files in the first commit (${change.files.length})`,
|
|
227
|
+
"",
|
|
228
|
+
"```",
|
|
229
|
+
...change.files.slice(0, REVIEW_PATHS),
|
|
230
|
+
);
|
|
231
|
+
if (change.files.length > REVIEW_PATHS) out.push(`... and ${change.files.length - REVIEW_PATHS} more`);
|
|
232
|
+
out.push("```");
|
|
233
|
+
if (change.nested.length > 0) {
|
|
234
|
+
out.push("", "### Folders that are repositories of their own (not committed)", "", ...change.nested.map((path) => `- ${path}`));
|
|
235
|
+
}
|
|
236
|
+
if (change.identity === null) {
|
|
237
|
+
out.push("", "### Name and email", "", "Git already has them on this computer; they are used.");
|
|
238
|
+
} else {
|
|
239
|
+
out.push(
|
|
240
|
+
"",
|
|
241
|
+
"### Name and email for the commit",
|
|
242
|
+
"",
|
|
243
|
+
`- name: ${change.identity.name}`,
|
|
244
|
+
`- email: ${change.identity.email}`,
|
|
245
|
+
"",
|
|
246
|
+
"Stored in this folder's git settings only. Prefilled from the computer account; the bot asks you to confirm or change them.",
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
return out.join("\n");
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** The pending item's prompt. */
|
|
253
|
+
export function gitPrompt(bot: string, change: GitChange | undefined): string {
|
|
254
|
+
if (change === undefined) return `${SETUP_GIT_TITLE} (proposed by bot ${bot}) is waiting for your review`;
|
|
255
|
+
return `${gitTitle(change.language)}: ${change.repo} (proposed by bot ${bot}) is waiting for your review`;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Approval: leaves the request `dev` sets git up from. */
|
|
259
|
+
export function applyGit(home: string, change: GitChange): void {
|
|
260
|
+
const requests = join(home, REQUESTS_DIRECTORY);
|
|
261
|
+
mkdirSync(requests, { recursive: true });
|
|
262
|
+
const body = {
|
|
263
|
+
kind: "setup-git",
|
|
264
|
+
path: change.repo,
|
|
265
|
+
gitignore: change.gitignore,
|
|
266
|
+
paths: change.files,
|
|
267
|
+
...(change.identity === null ? {} : { identity: change.identity }),
|
|
268
|
+
};
|
|
269
|
+
writeFileSync(join(requests, `${randomUUID()}.json`), `${JSON.stringify(body)}\n`);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Reads a stored change; undefined when it is not one. */
|
|
273
|
+
export function gitChangeOf(value: unknown): GitChange | undefined {
|
|
274
|
+
if (
|
|
275
|
+
!isRecord(value) ||
|
|
276
|
+
typeof value.repo !== "string" ||
|
|
277
|
+
typeof value.gitignore !== "string" ||
|
|
278
|
+
!(value.before === null || typeof value.before === "string") ||
|
|
279
|
+
!Array.isArray(value.files) ||
|
|
280
|
+
!Array.isArray(value.nested) ||
|
|
281
|
+
!(value.note === null || typeof value.note === "string") ||
|
|
282
|
+
typeof value.init !== "boolean"
|
|
283
|
+
) {
|
|
284
|
+
return undefined;
|
|
285
|
+
}
|
|
286
|
+
const identity =
|
|
287
|
+
isRecord(value.identity) && typeof value.identity.name === "string" && typeof value.identity.email === "string"
|
|
288
|
+
? { name: value.identity.name, email: value.identity.email }
|
|
289
|
+
: null;
|
|
290
|
+
const strings = (items: readonly unknown[]): string[] => items.filter((item): item is string => typeof item === "string");
|
|
291
|
+
return {
|
|
292
|
+
repo: value.repo,
|
|
293
|
+
gitignore: value.gitignore,
|
|
294
|
+
before: value.before,
|
|
295
|
+
files: strings(value.files),
|
|
296
|
+
nested: strings(value.nested),
|
|
297
|
+
note: value.note,
|
|
298
|
+
identity,
|
|
299
|
+
init: value.init,
|
|
300
|
+
language: value.language === "zh" ? "zh" : "en",
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** The steps the agent follows for a folder: the guide with the bot and the folder filled in. */
|
|
305
|
+
export function setupGitSteps(bot: string, folder: string): string {
|
|
306
|
+
return renderGuide(readFileSync(DEV_GIT_GUIDE, "utf8"), bot, folder);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** `bot setup-git <bot> <folder>`: with no input the steps, with the `.gitignore` and identity on stdin the proposal. */
|
|
310
|
+
export async function runSetupGitCommand(
|
|
311
|
+
ctx: CommandContext,
|
|
312
|
+
argv: readonly string[],
|
|
313
|
+
propose: (bot: string, change: GitChange) => Promise<string>,
|
|
314
|
+
piped: PipedInput = {},
|
|
315
|
+
): Promise<string> {
|
|
316
|
+
const bot = argv[0];
|
|
317
|
+
const folder = argv[1];
|
|
318
|
+
if (bot === undefined || folder === undefined || argv.length > 2) throw new BotError(USAGE);
|
|
319
|
+
if (readBots(ctx.home)[bot] === undefined) throw new BotError(`there is no bot "${bot}"`);
|
|
320
|
+
const text = (await readPiped(ctx.input, piped)).trim();
|
|
321
|
+
if (text.length === 0) return setupGitSteps(bot, isAbsolute(folder) ? folder : resolve(ctx.cwd, folder));
|
|
322
|
+
return propose(bot, proposeGit(ctx.home, bot, folder, text, ctx.cwd));
|
|
323
|
+
}
|