@networkbase/cli 1.0.3 → 2.0.0-next.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/README.md +60 -37
- package/bin/nb.mjs +69 -5350
- package/lib/api.mjs +163 -0
- package/lib/args.mjs +140 -0
- package/lib/commands/account.mjs +293 -0
- package/lib/commands/agent.mjs +169 -0
- package/lib/commands/ask.mjs +84 -0
- package/lib/commands/assignments.mjs +199 -0
- package/lib/commands/browse.mjs +140 -0
- package/lib/commands/docs.mjs +178 -0
- package/lib/commands/extras.mjs +114 -0
- package/lib/commands/files.mjs +425 -0
- package/lib/commands/inbox.mjs +98 -0
- package/lib/commands/link.mjs +85 -0
- package/lib/commands/mcp.mjs +149 -0
- package/lib/commands/misc.mjs +263 -0
- package/lib/commands/resolve.mjs +95 -0
- package/lib/commands/table.mjs +225 -0
- package/lib/commands/tasks.mjs +362 -0
- package/lib/commands/undo.mjs +52 -0
- package/lib/commands/watch.mjs +113 -0
- package/lib/commands/work.mjs +190 -0
- package/lib/config.mjs +203 -0
- package/lib/context.mjs +72 -0
- package/lib/errors.mjs +72 -0
- package/lib/keychain.mjs +59 -0
- package/lib/mcp/tools.mjs +336 -0
- package/lib/print/notices.mjs +48 -0
- package/lib/print/out.mjs +151 -0
- package/lib/print/remind.mjs +25 -0
- package/lib/print/style.mjs +110 -0
- package/lib/sync/diff.mjs +41 -0
- package/lib/sync/ignore.mjs +86 -0
- package/lib/sync/local.mjs +68 -0
- package/lib/sync/plan.mjs +94 -0
- package/lib/sync/queue.mjs +31 -0
- package/lib/sync/state.mjs +136 -0
- package/lib/sync/transfer.mjs +172 -0
- package/lib/tui/ask.mjs +124 -0
- package/lib/undo-log.mjs +34 -0
- package/package.json +13 -11
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// Docs (the README), workspaces, search and reading remote files (report §17.4, §18.2 "change the workspace README", §21 flow C).
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import crypto from "node:crypto";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
|
|
8
|
+
import { readUserConfig } from "../config.mjs";
|
|
9
|
+
import { CliError, EXIT, usage } from "../errors.mjs";
|
|
10
|
+
import { safe } from "../print/style.mjs";
|
|
11
|
+
import { unifiedDiff } from "../sync/diff.mjs";
|
|
12
|
+
import { fetchManifest } from "../sync/transfer.mjs";
|
|
13
|
+
import { confirm } from "../tui/ask.mjs";
|
|
14
|
+
import { resolveTask } from "./tasks.mjs";
|
|
15
|
+
|
|
16
|
+
/** @typedef {import("../context.mjs").Context} Context */
|
|
17
|
+
|
|
18
|
+
/** @param {Context} ctx @param {string} slug */
|
|
19
|
+
async function readDoc(ctx, slug) {
|
|
20
|
+
const workspaceId = ctx.requireWorkspace();
|
|
21
|
+
return /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/docs/${encodeURIComponent(slug)}`).catch((error) => {
|
|
22
|
+
if (error instanceof CliError && error.status === 404) throw new CliError("DOC_NOT_FOUND", `No doc called ${slug} here`, { hint: "See nb doc list" });
|
|
23
|
+
throw error;
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @param {Context} ctx */
|
|
28
|
+
export async function list(ctx) {
|
|
29
|
+
const workspaceId = ctx.requireWorkspace();
|
|
30
|
+
const { docs } = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/docs`));
|
|
31
|
+
ctx.out.result("nb.doc.list/1", { docs }, (d) => (d.docs.length ? d.docs.map((/** @type {any} */ doc) => ` ${safe(doc.slug).padEnd(20)} ${ctx.out.c.muted(safe(doc.filename ?? ""))}`) : "No docs yet"));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param {Context} ctx */
|
|
35
|
+
export async function view(ctx) {
|
|
36
|
+
const doc = await readDoc(ctx, ctx.positionals[0] ?? "readme");
|
|
37
|
+
if (ctx.out.json) return ctx.out.result("nb.doc.view/1", doc, () => null);
|
|
38
|
+
if (ctx.flags.raw || !process.stdout.isTTY) {
|
|
39
|
+
ctx.out.raw(doc.content);
|
|
40
|
+
if (!String(doc.content).endsWith("\n")) ctx.out.raw("\n");
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
ctx.out.result("nb.doc.view/1", doc, (d) => safe(d.content), { page: true });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The editor for doc edits: setting, then VISUAL / EDITOR, then a sensible default. @param {Context} ctx */
|
|
47
|
+
function editorCommand(ctx) {
|
|
48
|
+
return ctx.env.NB_EDITOR || readUserConfig(ctx.env).editor || ctx.env.VISUAL || ctx.env.EDITOR || (process.platform === "win32" ? "notepad" : "vi");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Edits a doc in your editor and saves it as a new version of its file, based on the version you opened:
|
|
53
|
+
* a teammate's newer save is a conflict, not an overwrite (A1.8). Needs doc:write for tokens (D16).
|
|
54
|
+
* @param {Context} ctx
|
|
55
|
+
*/
|
|
56
|
+
export async function edit(ctx) {
|
|
57
|
+
const slug = ctx.positionals[0] ?? "readme";
|
|
58
|
+
const doc = await readDoc(ctx, slug);
|
|
59
|
+
if (!doc.file) throw new CliError("NOT_SUPPORTED", `${slug} isn't backed by a file, so it's edited in the app`, { hint: `nb open` });
|
|
60
|
+
if (!doc.canEdit) throw new CliError("FORBIDDEN", `You can read ${slug} but not edit it`);
|
|
61
|
+
if (!ctx.out.interactive) throw new CliError("NEEDS_INPUT", "nb doc edit opens your editor, so it needs a terminal", { hint: `Agents: change ${doc.file.path} and nb push it` });
|
|
62
|
+
// The file name comes from the server, so only plain characters reach the editor's command line.
|
|
63
|
+
const name = path.posix.basename(doc.file.path).replace(/[^A-Za-z0-9._-]/g, "_").replace(/^\.+/, "") || "doc.md";
|
|
64
|
+
const tmp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "nb-doc-")), name);
|
|
65
|
+
fs.writeFileSync(tmp, doc.content);
|
|
66
|
+
const [cmd, ...args] = editorCommand(ctx).split(" ");
|
|
67
|
+
// Windows editors are often .cmd files, which need the shell; the path is quoted for it.
|
|
68
|
+
const win = process.platform === "win32";
|
|
69
|
+
const run = spawnSync(/** @type {string} */ (cmd), [...args, win ? `"${tmp}"` : tmp], { stdio: "inherit", shell: win });
|
|
70
|
+
if (run.status !== 0) throw new CliError("EDITOR_FAILED", `The editor exited with ${run.status ?? run.signal}`);
|
|
71
|
+
const next = fs.readFileSync(tmp, "utf8");
|
|
72
|
+
fs.rmSync(path.dirname(tmp), { recursive: true, force: true });
|
|
73
|
+
return saveDoc(ctx, slug, doc, next);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Replaces a doc's Markdown without an editor (scripts and agents): from --file, stdin (--file -), or the
|
|
78
|
+
* MCP tool's content. Same diff preview, yes and conflict rules as nb doc edit.
|
|
79
|
+
* @param {Context} ctx
|
|
80
|
+
*/
|
|
81
|
+
export async function set(ctx) {
|
|
82
|
+
const slug = ctx.positionals[0] ?? "readme";
|
|
83
|
+
const from = ctx.flags.file;
|
|
84
|
+
const next = typeof ctx.flags.content === "string" ? ctx.flags.content : from === "-" ? fs.readFileSync(0, "utf8") : from ? fs.readFileSync(path.resolve(ctx.cwd, from), "utf8") : null;
|
|
85
|
+
if (next === null) throw usage("nb doc set <slug> --file <path>, or --file - to read stdin");
|
|
86
|
+
const doc = await readDoc(ctx, slug);
|
|
87
|
+
if (!doc.file) throw new CliError("NOT_SUPPORTED", `${slug} isn't backed by a file, so it's edited in the app`, { hint: "nb open" });
|
|
88
|
+
if (!doc.canEdit) throw new CliError("FORBIDDEN", `You can read ${slug} but not edit it`);
|
|
89
|
+
return saveDoc(ctx, slug, doc, next);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** @param {Context} ctx @param {string} slug @param {any} doc @param {string} next */
|
|
93
|
+
async function saveDoc(ctx, slug, doc, next) {
|
|
94
|
+
if (next === doc.content) {
|
|
95
|
+
ctx.out.result("nb.doc.edit/1", { slug, changed: false }, () => "No changes");
|
|
96
|
+
return EXIT.ok;
|
|
97
|
+
}
|
|
98
|
+
const preview = unifiedDiff(doc.content, next)?.lines.slice(0, 30).map((l) => `${l.kind === "@" ? "" : l.kind}${l.text}`).join("\n");
|
|
99
|
+
if (!(await confirm(ctx, { key: "save", question: `Save ${doc.file.path} as v${doc.file.version + 1}?`, ...(preview ? { preview } : {}), yesLabel: "Save", defaultYes: true }))) return EXIT.cancelled;
|
|
100
|
+
const bytes = Buffer.from(next, "utf8");
|
|
101
|
+
const res = /** @type {any} */ (await ctx.api.post("/api/v1/files/place", {
|
|
102
|
+
projectId: ctx.requireWorkspace(),
|
|
103
|
+
...(ctx.flags.message ? { message: ctx.flags.message } : {}),
|
|
104
|
+
files: [{ path: doc.file.path, versionOf: doc.file.nodeId, baseVersion: doc.file.version, contentHash: crypto.createHash("sha256").update(bytes).digest("hex"), size: bytes.length, mimeType: "text/markdown", contentBase64: bytes.toString("base64") }],
|
|
105
|
+
}).catch((error) => {
|
|
106
|
+
if (error instanceof CliError && error.code === "VERSION_CONFLICT") throw new CliError("VERSION_CONFLICT", `Someone saved ${doc.file.path} while you were editing`, { hint: "Read the doc again and redo your change on their version", details: error.details });
|
|
107
|
+
throw error;
|
|
108
|
+
}));
|
|
109
|
+
const saved = res.files[0];
|
|
110
|
+
ctx.out.result("nb.doc.edit/1", { slug, changed: true, path: saved.path, version: saved.version }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Saved ${safe(d.path)} as v${d.version}`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** @param {Context} ctx */
|
|
114
|
+
export async function workspaceList(ctx) {
|
|
115
|
+
const { workspaces } = /** @type {any} */ (await ctx.api.get("/api/v1/extension/workspaces"));
|
|
116
|
+
const linked = ctx.project?.workspaceId;
|
|
117
|
+
ctx.out.result("nb.workspace.list/1", { workspaces: workspaces.map((/** @type {any} */ w) => ({ id: w.id, slug: w.slug, title: w.title, role: w.role ?? null })) }, (d) =>
|
|
118
|
+
d.workspaces.length ? ctx.out.table([{ title: "", value: (w) => (w.id === linked ? ctx.out.c.brand(ctx.out.sym.brand) : " ") }, { title: "Workspace", value: (w) => safe(w.title), flex: true }, { title: "Slug", value: (w) => safe(w.slug) }, { title: "Role", value: (w) => w.role ?? "" }], d.workspaces) : "No workspaces yet");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** @param {Context} ctx */
|
|
122
|
+
export async function search(ctx) {
|
|
123
|
+
const q = ctx.positionals.join(" ").trim();
|
|
124
|
+
if (!q) throw usage('nb search "<text>"');
|
|
125
|
+
const res = /** @type {any} */ (await ctx.api.get("/api/v1/extension/search", { query: { projectId: ctx.requireWorkspace(), q, kind: "file" } }));
|
|
126
|
+
ctx.out.result("nb.search/1", { query: q, files: res.files.map((/** @type {any} */ f) => ({ path: f.path, version: f.currentVersion })) }, (/** @type {any} */ d) => (d.files.length ? d.files.map((/** @type {any} */ f) => ` ${safe(f.path)} ${ctx.out.c.muted(`v${f.version}`)}`) : `Nothing named like "${safe(q)}"`));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ───────────────────────────────── file list / view
|
|
130
|
+
|
|
131
|
+
/** @param {Context} ctx */
|
|
132
|
+
export async function fileList(ctx) {
|
|
133
|
+
const workspaceId = ctx.requireWorkspace();
|
|
134
|
+
if (ctx.flags.task) {
|
|
135
|
+
const task = await resolveTask(ctx, String(ctx.flags.task));
|
|
136
|
+
const files = /** @type {any[]} */ (task.files ?? []).map((f) => ({ path: f.path ?? f.name, as: f.role === "deliverable" ? "final" : f.role === "working" ? "draft" : f.role ?? "draft", version: f.currentVersion ?? null, size: f.size ?? null }));
|
|
137
|
+
return ctx.out.result("nb.file.list/1", { task: { id: task.id, number: task.taskNumber }, files }, (d) => (d.files.length ? ctx.out.table([{ title: "Path", value: (f) => safe(f.path), flex: true, path: true }, { title: "Role", value: (f) => f.as }, { title: "Version", value: (f) => (f.version ? `v${f.version}` : ""), align: "right" }], d.files) : "No files on this task"));
|
|
138
|
+
}
|
|
139
|
+
const { files } = await fetchManifest(ctx.api, workspaceId);
|
|
140
|
+
const folder = ctx.positionals[0] ? `/${ctx.positionals[0].replace(/^\/+|\/+$/g, "")}/` : "/";
|
|
141
|
+
const list = [...files.values()].filter((f) => f.path.startsWith(folder)).sort((a, b) => a.path.localeCompare(b.path));
|
|
142
|
+
ctx.out.result("nb.file.list/1", { files: list.map((f) => ({ path: f.path, version: f.version, size: f.size })) }, (d) =>
|
|
143
|
+
d.files.length ? ctx.out.table([{ title: "Path", value: (f) => safe(f.path), flex: true, path: true }, { title: "Version", value: (f) => `v${f.version}`, align: "right" }, { title: "Size", value: (f) => formatBytes(f.size), align: "right" }], d.files) : "No files");
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** @param {number} bytes */
|
|
147
|
+
export const formatBytes = (bytes) => (bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`);
|
|
148
|
+
|
|
149
|
+
/** Prints a file; raw bytes when piped, control characters made visible on a terminal (A3.11). @param {Context} ctx */
|
|
150
|
+
export async function fileView(ctx) {
|
|
151
|
+
const workspaceId = ctx.requireWorkspace();
|
|
152
|
+
const p = ctx.positionals[0];
|
|
153
|
+
if (!p) throw usage("nb file view <path>");
|
|
154
|
+
const remotePath = p.startsWith("/") ? p : `/${p}`;
|
|
155
|
+
const response = await ctx.api.download("/api/v1/extension/file", { projectId: workspaceId, path: remotePath, transfer: "raw" }).catch(async () => null);
|
|
156
|
+
/** @type {Buffer} */
|
|
157
|
+
let bytes;
|
|
158
|
+
if (response) bytes = Buffer.from(await response.arrayBuffer());
|
|
159
|
+
else {
|
|
160
|
+
const inline = /** @type {any} */ (await ctx.api.get("/api/v1/extension/file", { query: { projectId: workspaceId, path: remotePath, transfer: "inline" } }));
|
|
161
|
+
bytes = Buffer.from(inline.content ?? "", inline.encoding === "base64" ? "base64" : "utf8");
|
|
162
|
+
}
|
|
163
|
+
if (ctx.out.json) return ctx.out.result("nb.file.view/1", { path: remotePath, size: bytes.length, contentBase64: bytes.toString("base64") }, () => null);
|
|
164
|
+
if (process.stdout.isTTY) {
|
|
165
|
+
ctx.out.raw(bytes.toString("utf8").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, (ch) => (ch < " " ? `^${String.fromCharCode(ch.charCodeAt(0) + 64)}` : `\\x${ch.charCodeAt(0).toString(16)}`)));
|
|
166
|
+
} else ctx.out.raw(bytes);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Members matching a name (the server returns at most 10). @param {Context} ctx */
|
|
170
|
+
export async function memberList(ctx) {
|
|
171
|
+
const workspaceId = ctx.requireWorkspace();
|
|
172
|
+
const q = ctx.positionals.join(" ");
|
|
173
|
+
const { members } = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/members`, { query: q ? { q } : {} }));
|
|
174
|
+
ctx.out.result("nb.member.list/1", { query: q || null, members: members.map((/** @type {any} */ m) => ({ username: m.username, name: m.fullName, role: m.role })) }, (d) =>
|
|
175
|
+
d.members.length
|
|
176
|
+
? [...ctx.out.table([{ title: "Member", value: (m) => (m.username ? `@${safe(m.username)}` : ""), flex: true }, { title: "Name", value: (m) => safe(m.name ?? "") }, { title: "Role", value: (m) => m.role }], d.members), ...(d.members.length >= 10 ? [ctx.out.c.muted(" First 10 shown: add a name to narrow it")] : [])]
|
|
177
|
+
: `No members match "${safe(q)}"`);
|
|
178
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Phase 6 extras (report findings 146, 148, 149): git branches and commit trailers, saved task filters, and many
|
|
2
|
+
// tasks from one Markdown file. git runs with execFile (no shell); nothing here installs hooks (D6).
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
import { readUserConfig, writeUserConfig } from "../config.mjs";
|
|
8
|
+
import { CliError, EXIT, usage } from "../errors.mjs";
|
|
9
|
+
import { safe } from "../print/style.mjs";
|
|
10
|
+
import { confirm } from "../tui/ask.mjs";
|
|
11
|
+
|
|
12
|
+
/** @typedef {import("../context.mjs").Context} Context */
|
|
13
|
+
|
|
14
|
+
/** @param {string} cwd @param {string[]} args @returns {Promise<string>} */
|
|
15
|
+
export const git = (cwd, args) => new Promise((resolve, reject) => execFile("git", args, { cwd, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => (error ? reject(new CliError("GIT_FAILED", `git ${args[0]}: ${String(stderr || error.message).trim()}`)) : resolve(String(stdout)))));
|
|
16
|
+
|
|
17
|
+
/** `nb/4-fix-login` (finding 146). @param {number | string} number @param {string} title */
|
|
18
|
+
export const branchName = (number, title) => `nb/${number}-${String(title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "task"}`;
|
|
19
|
+
|
|
20
|
+
/** Switches to the task's branch, creating it the first time. @param {string} cwd @param {string} name */
|
|
21
|
+
export async function switchToBranch(cwd, name) {
|
|
22
|
+
const exists = await git(cwd, ["rev-parse", "--verify", "--quiet", `refs/heads/${name}`]).then(() => true, () => false);
|
|
23
|
+
await git(cwd, exists ? ["switch", name] : ["switch", "-c", name]);
|
|
24
|
+
return exists ? "switched" : "created";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** `NetworkBase-Task: 4` in a commit message (finding 146). @param {string} message */
|
|
28
|
+
export const taskTrailer = (message) => /^NetworkBase-Task:\s*#?(\d+)\s*$/im.exec(message)?.[1] ?? null;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* `nb push --from-git`: the files the last commit changed, its subject as the message, and its NetworkBase-Task
|
|
32
|
+
* trailer as the task. Returns paths relative to `cwd`. @param {string} cwd
|
|
33
|
+
*/
|
|
34
|
+
export async function filesFromLastCommit(cwd) {
|
|
35
|
+
// This folder's place in the repository, from git itself ("" at the top, else "sub/dir/"). Comparing absolute
|
|
36
|
+
// paths broke on Windows, where git prints C:/Users/runneradmin/… and Node C:\Users\RUNNER~1\….
|
|
37
|
+
const prefix = (await git(cwd, ["rev-parse", "--show-prefix"])).trim();
|
|
38
|
+
const names = (await git(cwd, ["diff-tree", "--no-commit-id", "--name-only", "--diff-filter=ACMR", "-r", "HEAD"])).split("\n").filter(Boolean);
|
|
39
|
+
const message = await git(cwd, ["log", "-1", "--format=%B"]);
|
|
40
|
+
return {
|
|
41
|
+
paths: names.filter((n) => n.startsWith(prefix)).map((n) => n.slice(prefix.length))
|
|
42
|
+
// git never lists ".." or absolute names; checked anyway so nothing outside this folder is ever pushed.
|
|
43
|
+
.filter((n) => n && !n.startsWith("/") && !n.split("/").includes(".."))
|
|
44
|
+
.map((n) => n.split("/").join(path.sep)).filter((p) => fs.existsSync(path.join(cwd, p))),
|
|
45
|
+
subject: message.split("\n")[0]?.trim() ?? "",
|
|
46
|
+
task: taskTrailer(message),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ───────────────────────────────── saved filters (finding 148)
|
|
51
|
+
|
|
52
|
+
const FILTER_KEYS = ["mine", "all", "status", "limit"];
|
|
53
|
+
|
|
54
|
+
/** `--save <name>` stores the list flags; `@name` brings them back. @param {Context} ctx */
|
|
55
|
+
export function applySavedFilter(ctx) {
|
|
56
|
+
const at = ctx.positionals.find((p) => p.startsWith("@"));
|
|
57
|
+
const config = readUserConfig(ctx.env);
|
|
58
|
+
/** @type {Record<string, Record<string, unknown>>} */
|
|
59
|
+
const filters = config.filters ?? {};
|
|
60
|
+
if (at) {
|
|
61
|
+
const saved = filters[at.slice(1)];
|
|
62
|
+
if (!saved) throw usage(`No saved filter ${at}`, Object.keys(filters).length ? `Saved: ${Object.keys(filters).map((f) => `@${f}`).join(", ")}` : "Save one: nb task list --status todo --save todo");
|
|
63
|
+
for (const [k, v] of Object.entries(saved)) if (ctx.flags[k] === undefined) ctx.flags[k] = v;
|
|
64
|
+
}
|
|
65
|
+
if (ctx.flags.save) {
|
|
66
|
+
const name = String(ctx.flags.save).replace(/^@/, "");
|
|
67
|
+
if (!/^[\w-]{1,40}$/.test(name)) throw usage("A filter name is letters, numbers, - and _");
|
|
68
|
+
writeUserConfig({ ...config, filters: { ...filters, [name]: Object.fromEntries(FILTER_KEYS.filter((k) => ctx.flags[k] !== undefined).map((k) => [k, ctx.flags[k]])) } }, ctx.env);
|
|
69
|
+
ctx.out.note(ctx.out.c.muted(`Saved as @${name}: nb task list @${name}`));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ───────────────────────────────── tasks from Markdown (finding 149)
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* One task per `#`/`##` heading; the text under it is the description and `- [ ]` lines are its subtasks.
|
|
77
|
+
* @param {string} text @returns {Array<{ title: string, description: string, subtasks: string[] }>}
|
|
78
|
+
*/
|
|
79
|
+
export function parseTasksMarkdown(text) {
|
|
80
|
+
/** @type {Array<{ title: string, description: string[], subtasks: string[] }>} */
|
|
81
|
+
const tasks = [];
|
|
82
|
+
for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
|
|
83
|
+
const heading = /^#{1,3}\s+(.+?)\s*#*$/.exec(line);
|
|
84
|
+
if (heading) { tasks.push({ title: String(heading[1]).trim(), description: [], subtasks: [] }); continue; }
|
|
85
|
+
const current = tasks.at(-1);
|
|
86
|
+
if (!current) continue;
|
|
87
|
+
const box = /^\s*[-*]\s+\[[ xX]\]\s+(.+)$/.exec(line);
|
|
88
|
+
if (box) current.subtasks.push(String(box[1]).trim());
|
|
89
|
+
else current.description.push(line);
|
|
90
|
+
}
|
|
91
|
+
return tasks.filter((t) => t.title).map((t) => ({ title: t.title.slice(0, 200), description: t.description.join("\n").trim(), subtasks: t.subtasks }));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** `nb task create --from tasks.md`: one preview, one yes, then each task (finding 149). @param {Context} ctx @param {string} file */
|
|
95
|
+
export async function createFromMarkdown(ctx, file) {
|
|
96
|
+
const abs = path.resolve(ctx.cwd, file);
|
|
97
|
+
if (!fs.existsSync(abs)) throw usage(`No file ${file}`);
|
|
98
|
+
const tasks = parseTasksMarkdown(fs.readFileSync(abs, "utf8"));
|
|
99
|
+
if (!tasks.length) throw usage(`${file} has no headings`, "Write one task per heading (# Title), with - [ ] lines for subtasks");
|
|
100
|
+
if (tasks.length > 50) throw usage(`${file} has ${tasks.length} tasks; 50 at a time`);
|
|
101
|
+
const preview = tasks.map((t) => `${t.title}${t.subtasks.length ? ` (${t.subtasks.length} subtasks)` : ""}`).join("\n");
|
|
102
|
+
if (!(await confirm(ctx, { key: "create", question: `Create ${tasks.length} task${tasks.length === 1 ? "" : "s"}?`, preview, yesLabel: "Create", defaultYes: true }))) return EXIT.cancelled;
|
|
103
|
+
const projectId = ctx.requireWorkspace();
|
|
104
|
+
/** @type {Array<{ number: number, title: string }>} */
|
|
105
|
+
const made = [];
|
|
106
|
+
for (const t of tasks) {
|
|
107
|
+
const res = /** @type {any} */ (await ctx.api.post("/api/v1/extension/create-task", { projectId, title: t.title, ...(t.description ? { description: t.description.slice(0, 10000) } : {}) }));
|
|
108
|
+
const task = res.task ?? res;
|
|
109
|
+
for (const sub of t.subtasks) await ctx.api.post("/api/v1/extension/task-subtask", { projectId, taskId: task.id, title: sub.slice(0, 200) });
|
|
110
|
+
made.push({ number: task.taskNumber, title: task.title ?? t.title });
|
|
111
|
+
}
|
|
112
|
+
ctx.out.result("nb.task.create.many/1", { tasks: made }, (d) => [`${ctx.out.c.success(ctx.out.sym.done)} Created ${d.tasks.length} tasks`, ...d.tasks.map((t) => ` #${t.number} ${safe(t.title)}`)]);
|
|
113
|
+
return EXIT.ok;
|
|
114
|
+
}
|