@networkbase/cli 2.0.4 → 2.1.1
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/bin/nb.mjs +6 -1
- package/lib/args.mjs +37 -17
- package/lib/commands/account.mjs +15 -4
- package/lib/commands/browse.mjs +24 -2
- package/lib/commands/extras.mjs +1 -1
- package/lib/commands/files.mjs +73 -5
- package/lib/commands/inbox.mjs +33 -1
- package/lib/commands/link.mjs +33 -1
- package/lib/commands/misc.mjs +72 -13
- package/lib/commands/table.mjs +37 -10
- package/lib/commands/tasks.mjs +164 -22
- package/lib/commands/undo.mjs +1 -1
- package/lib/commands/work.mjs +55 -18
- package/lib/config.mjs +1 -1
- package/lib/context.mjs +7 -0
- package/lib/dates.mjs +47 -0
- package/lib/error-fixes.mjs +60 -0
- package/lib/mcp/tools.mjs +40 -21
- package/lib/print/notices.mjs +6 -0
- package/lib/print/out.mjs +4 -2
- package/lib/print/style.mjs +2 -0
- package/lib/sync/queue.mjs +1 -1
- package/package.json +1 -1
package/bin/nb.mjs
CHANGED
|
@@ -21,6 +21,8 @@ const restoreCursor = () => { if (process.stderr.isTTY) process.stderr.write("\x
|
|
|
21
21
|
process.on("exit", restoreCursor);
|
|
22
22
|
for (const signal of /** @type {const} */ (["SIGINT", "SIGTERM"])) process.on(signal, () => { restoreCursor(); process.exit(EXIT.cancelled); });
|
|
23
23
|
|
|
24
|
+
/** The command being run, so a usage error can point at its help (C5). @type {string | null} */
|
|
25
|
+
let commandName = null;
|
|
24
26
|
try {
|
|
25
27
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
26
28
|
const { VERSION } = await import("../lib/context.mjs");
|
|
@@ -28,6 +30,7 @@ try {
|
|
|
28
30
|
process.exit(EXIT.ok);
|
|
29
31
|
}
|
|
30
32
|
const { spec, rest, alias } = resolveCommand(argv);
|
|
33
|
+
commandName = spec?.name ?? null;
|
|
31
34
|
if (!spec) {
|
|
32
35
|
if (argv.includes("--json")) {
|
|
33
36
|
const { helpData } = await import("../lib/args.mjs");
|
|
@@ -45,7 +48,7 @@ try {
|
|
|
45
48
|
const ctx = createContext({ flags: spec.name === "prompt" ? { ...flags, quiet: true } : flags, positionals });
|
|
46
49
|
if (alias) {
|
|
47
50
|
const { remindOnce } = await import("../lib/print/remind.mjs");
|
|
48
|
-
remindOnce(ctx, `alias:${alias.from}`, `nb ${alias.from} is now nb ${alias.to} (the old name works until 3.0)`);
|
|
51
|
+
remindOnce(ctx, `alias:${alias.from}`, alias.shortcut ? `nb ${alias.from} is short for nb ${alias.to}` : `nb ${alias.from} is now nb ${alias.to} (the old name works until 3.0)`);
|
|
49
52
|
}
|
|
50
53
|
// login is what signs you in, so it can't look a workspace up first; an agent's workspace is picked on the approval page.
|
|
51
54
|
if (spec.name !== "login") await ctx.resolveWorkspace();
|
|
@@ -67,6 +70,8 @@ try {
|
|
|
67
70
|
await (await import("../lib/print/notices.mjs")).afterCommand(ctx);
|
|
68
71
|
} catch (error) {
|
|
69
72
|
const cliError = toCliError(error);
|
|
73
|
+
// A usage error's next step is the command's own help (C5).
|
|
74
|
+
if (!cliError.hint && cliError.exitCode === EXIT.usage && commandName) cliError.hint = `See nb ${commandName} --help`;
|
|
70
75
|
early.error(cliError);
|
|
71
76
|
if (cliError.code === "INTERNAL" && process.env.NB_DEBUG === "1" && error instanceof Error) process.stderr.write(`${error.stack}\n`);
|
|
72
77
|
process.exitCode = cliError.exitCode;
|
package/lib/args.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// flags and commands are errors with a "did you mean", never silently ignored (finding 81).
|
|
3
3
|
import { parseArgs } from "node:util";
|
|
4
4
|
|
|
5
|
-
import { ALIASES, COMMANDS, GLOBAL_FLAGS, REMOVED } from "./commands/table.mjs";
|
|
5
|
+
import { ALIASES, COMMANDS, GLOBAL_FLAGS, REMOVED, SHORTCUTS } from "./commands/table.mjs";
|
|
6
6
|
import { CliError, usage } from "./errors.mjs";
|
|
7
7
|
|
|
8
8
|
/** @typedef {import("./commands/table.mjs").CommandSpec} CommandSpec */
|
|
@@ -33,23 +33,30 @@ const TASK_REF = /^(#?\d+|T-\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-
|
|
|
33
33
|
/**
|
|
34
34
|
* Finds the command in argv. `nb task 4` is a shortcut for `nb task view 4`.
|
|
35
35
|
* @param {string[]} argv
|
|
36
|
-
* @returns {{ spec: CommandSpec | null, rest: string[], alias: { from: string, to: string } | null }}
|
|
36
|
+
* @returns {{ spec: CommandSpec | null, rest: string[], alias: { from: string, to: string, shortcut?: boolean } | null }}
|
|
37
37
|
*/
|
|
38
38
|
export function resolveCommand(argv) {
|
|
39
|
+
// Help groups these under "Classes", so nb class … is nb assignment … (C16 #10).
|
|
40
|
+
if (argv[0] === "class") argv = ["assignment", ...argv.slice(1)];
|
|
39
41
|
/** @type {string[]} */
|
|
40
42
|
const words = [];
|
|
41
43
|
for (const token of argv) {
|
|
42
44
|
if (token.startsWith("-")) break;
|
|
43
45
|
words.push(token);
|
|
44
46
|
}
|
|
47
|
+
// `nb` on its own (also `nb --plain`, `nb -w x`) is the home screen (C1); `nb --help` and `nb --json` stay the help.
|
|
48
|
+
if (words.length === 0 && !argv.some((a) => a === "--help" || a === "-h" || a === "--json")) return { spec: /** @type {CommandSpec} */ (COMMANDS.find((c) => c.name === "home")), rest: argv, alias: null };
|
|
45
49
|
if (words.length === 0) return { spec: null, rest: argv, alias: null };
|
|
46
50
|
for (let n = Math.min(3, words.length); n >= 1; n--) {
|
|
47
51
|
const name = words.slice(0, n).join(" ");
|
|
48
52
|
if (name in REMOVED) throw new CliError("USAGE", /** @type {Record<string, string>} */ (REMOVED)[name]);
|
|
49
|
-
const
|
|
53
|
+
const short = /** @type {Record<string, string>} */ (SHORTCUTS);
|
|
54
|
+
const target = short[short[name] ?? ""] ?? short[name] ?? /** @type {Record<string, string>} */ (ALIASES)[name] ?? name;
|
|
50
55
|
const spec = COMMANDS.find((c) => c.name === target);
|
|
51
|
-
if (spec) return { spec, rest: argv.slice(n), alias: target !== name ? { from: name, to: target } : null };
|
|
56
|
+
if (spec) return { spec, rest: argv.slice(n), alias: target !== name ? { from: name, to: target, ...(short[name] ? { shortcut: true } : {}) } : null };
|
|
52
57
|
}
|
|
58
|
+
// `nb comment "looks good"` comments on the current task (C8).
|
|
59
|
+
if (words[0] === "comment" && words[1]) return { spec: /** @type {CommandSpec} */ (COMMANDS.find((c) => c.name === "comment add")), rest: argv.slice(1), alias: null };
|
|
53
60
|
if (words[0] === "task" && words[1] && TASK_REF.test(words[1])) {
|
|
54
61
|
return { spec: /** @type {CommandSpec} */ (COMMANDS.find((c) => c.name === "task view")), rest: argv.slice(1), alias: null };
|
|
55
62
|
}
|
|
@@ -115,24 +122,37 @@ const wrap = (text, width) => text.split(" ").reduce((/** @type {string[]} */ ou
|
|
|
115
122
|
}, []);
|
|
116
123
|
|
|
117
124
|
/** Overview help: every command by group, summaries wrapped to the terminal. @param {number} [columns] */
|
|
125
|
+
/** The commands most people use, shown first in nb help (C1). */
|
|
126
|
+
const MOST_USED = ["init", "status", "pull", "push", "next", "task list", "task start", "task done", "task create", "inbox"];
|
|
127
|
+
|
|
128
|
+
/** A short help page (C1): the 10 most-used commands, then the rest by area, names only. */
|
|
118
129
|
export function overviewHelp(columns = 80) {
|
|
130
|
+
const width = columns || 80;
|
|
131
|
+
const top = MOST_USED.map((name) => /** @type {CommandSpec} */ (COMMANDS.find((c) => c.name === name)));
|
|
132
|
+
const w = Math.max(...top.map((c) => c.name.length));
|
|
133
|
+
const lines = ["NetworkBase CLI", "", "Usage", " nb <command> [flags]", "", "Most used"];
|
|
134
|
+
for (const c of top) {
|
|
135
|
+
const [first = "", ...rest] = wrap(c.summary, Math.max(16, width - w - 4));
|
|
136
|
+
lines.push(` ${c.name.padEnd(w)} ${first}`, ...rest.map((l) => ` ${" ".repeat(w)} ${l}`));
|
|
137
|
+
}
|
|
138
|
+
lines.push("", "More");
|
|
119
139
|
const groups = new Map();
|
|
120
140
|
for (const c of COMMANDS) {
|
|
121
|
-
if (c.hidden) continue;
|
|
141
|
+
if (c.hidden || MOST_USED.includes(c.name)) continue;
|
|
122
142
|
if (!groups.has(c.group)) groups.set(c.group, []);
|
|
123
|
-
groups.get(c.group).push(c);
|
|
143
|
+
groups.get(c.group).push(c.name);
|
|
124
144
|
}
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
lines.push("");
|
|
145
|
+
for (const [group, names] of groups) {
|
|
146
|
+
// Wrapped between names, never inside one ("inbox / open").
|
|
147
|
+
const rows = names.reduce((/** @type {string[]} */ out, /** @type {string} */ name) => {
|
|
148
|
+
const last = out.at(-1);
|
|
149
|
+
if (last !== undefined && last.length + name.length + 2 <= Math.max(16, width - 5)) out[out.length - 1] = `${last}, ${name}`;
|
|
150
|
+
else out.push(name);
|
|
151
|
+
return out;
|
|
152
|
+
}, []);
|
|
153
|
+
lines.push(` ${group}`, ...rows.map((r, i) => ` ${r}${i < rows.length - 1 ? "," : ""}`));
|
|
134
154
|
}
|
|
135
|
-
lines.push(...wrap("Every command takes --json, --quiet, --plain and --help.",
|
|
155
|
+
lines.push("", ...wrap("nb help <command> explains one. Every command takes --json, --quiet, --plain and --help.", width), "Docs: https://networkbase.in/docs/cli");
|
|
136
156
|
return lines.join("\n");
|
|
137
157
|
}
|
|
138
158
|
|
|
@@ -141,6 +161,6 @@ export function helpData() {
|
|
|
141
161
|
return {
|
|
142
162
|
commands: COMMANDS.filter((c) => !c.hidden).map((c) => ({ name: c.name, summary: c.summary, usage: c.usage, flags: Object.fromEntries(Object.entries(c.flags ?? {}).filter(([, f]) => !f.hidden)), examples: c.examples ?? [], exitCodes: c.exit ?? [0, 1] })),
|
|
143
163
|
globalFlags: GLOBAL_FLAGS,
|
|
144
|
-
aliases: ALIASES,
|
|
164
|
+
aliases: { ...ALIASES, ...SHORTCUTS },
|
|
145
165
|
};
|
|
146
166
|
}
|
package/lib/commands/account.mjs
CHANGED
|
@@ -15,6 +15,14 @@ import { openInBrowser } from "./misc.mjs";
|
|
|
15
15
|
const TOKEN_SHAPE = /^nb_(dev|pat|agt)_[A-Za-z0-9_-]{16,}$/;
|
|
16
16
|
const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
|
|
17
17
|
|
|
18
|
+
/** @param {Context} ctx @param {string} token */
|
|
19
|
+
/**
|
|
20
|
+
* This computer's own sign-in, sent with a new sign-in so the server closes it (C6): one entry per computer.
|
|
21
|
+
* Only a saved device token; never an agent's, an environment token, or a personal token.
|
|
22
|
+
* @param {Context} ctx
|
|
23
|
+
*/
|
|
24
|
+
const renewing = (ctx) => (!ctx.flags.agent && ctx.profile.profile?.source === "file" && String(ctx.profile.token ?? "").startsWith("nb_dev_") ? { renew: String(ctx.profile.token) } : {});
|
|
25
|
+
|
|
18
26
|
/** @param {Context} ctx @param {string} token */
|
|
19
27
|
async function whoIs(ctx, token) {
|
|
20
28
|
const api = createApi({ origin: ctx.profile.origin, token, version: ctx.version });
|
|
@@ -44,7 +52,8 @@ export function connectedLines(ctx, access) {
|
|
|
44
52
|
/** @param {Context} ctx @param {string} token @param {string} method */
|
|
45
53
|
async function finish(ctx, token, method) {
|
|
46
54
|
const me = await whoIs(ctx, token);
|
|
47
|
-
|
|
55
|
+
// The end date is kept so nb can warn 7 days before (C6).
|
|
56
|
+
saveProfile(ctx.profile.name, { origin: ctx.profile.origin, token, user: { id: me.user.id, username: me.user.username, email: me.user.email }, ...(me.credential?.expiresAt ? { expiresAt: me.credential.expiresAt } : {}) }, ctx.env);
|
|
48
57
|
ctx.out.result("nb.login/1", { method, origin: ctx.profile.origin, profile: ctx.profile.name, user: me.user, scopes: me.credential.scopes, access: me.access ?? null }, (d) =>
|
|
49
58
|
d.access ? connectedLines(ctx, d.access) : `${ctx.out.c.success(ctx.out.sym.done)} Signed in as ${safe(d.user.username ? `@${d.user.username}` : d.user.email ?? d.user.id)} on ${new URL(d.origin).host}${d.profile !== "default" ? ` (profile ${d.profile})` : ""}`);
|
|
50
59
|
}
|
|
@@ -121,7 +130,7 @@ export async function deviceLogin(ctx, agentName = /** @type {string | null} */
|
|
|
121
130
|
try {
|
|
122
131
|
while (Date.now() < until) {
|
|
123
132
|
await new Promise((resolve) => setTimeout(resolve, interval * 1000));
|
|
124
|
-
const res = /** @type {any} */ (await api.post("/api/v1/device/token", { deviceCode: start.deviceCode }, { auth: false }).catch((/** @type {unknown} */ error) => {
|
|
133
|
+
const res = /** @type {any} */ (await api.post("/api/v1/device/token", { deviceCode: start.deviceCode, ...renewing(ctx) }, { auth: false }).catch((/** @type {unknown} */ error) => {
|
|
125
134
|
if (error instanceof CliError && error.status === 403) throw new CliError("CANCELLED", "Sign-in was denied in the browser");
|
|
126
135
|
if (error instanceof CliError && error.status === 410) throw new CliError("TIMEOUT", "The sign-in code expired before it was approved", { hint: "Run nb login --device again" });
|
|
127
136
|
throw error;
|
|
@@ -205,7 +214,7 @@ function browserLogin(ctx) {
|
|
|
205
214
|
if (!code || url.searchParams.get("state") !== state) return reply(400, "Not this sign-in", "This window doesn't match the sign-in your terminal started.");
|
|
206
215
|
try {
|
|
207
216
|
const api = createApi({ origin, token: null, version: ctx.version });
|
|
208
|
-
const exchanged = /** @type {any} */ (await api.post("/api/v1/extension/auth-code", { code, state, codeVerifier: verifier }, { auth: false }));
|
|
217
|
+
const exchanged = /** @type {any} */ (await api.post("/api/v1/extension/auth-code", { code, state, codeVerifier: verifier, ...renewing(ctx) }, { auth: false }));
|
|
209
218
|
reply(200, "Signed in", "Your terminal is signed in. You can close this window.");
|
|
210
219
|
done(null, exchanged.token);
|
|
211
220
|
} catch (error) {
|
|
@@ -283,9 +292,11 @@ export async function whoami(ctx) {
|
|
|
283
292
|
ctx.out.result("nb.whoami/1", data, (d) => [
|
|
284
293
|
`${ctx.out.c.brand(ctx.out.sym.brand)} ${safe(d.user.username ? `@${d.user.username}` : d.user.email ?? d.user.id)}${d.user.fullName ? ` · ${safe(d.user.fullName)}` : ""}`,
|
|
285
294
|
` server ${new URL(d.origin).host}${d.profile !== "default" ? ` (profile ${d.profile})` : ""}`,
|
|
286
|
-
` token ${d.credential.type ? `${d.credential.type === "agent" ? "agent" : d.credential.type === "pat" ? "personal access" : "device"} · ` : ""}${d.tokenSource === "env" ? "from NETWORKBASE_TOKEN" : `kept in ${storageWords(d.storage)}`} · ${d.access ? (d.access.allWorkspaces ? "all your workspaces" : `only ${safe(d.access.workspaceTitle ?? "one workspace")}`) : d.credential.workspaceId ? "one workspace only" : `${d.credential.scopes.length} permissions`}`,
|
|
295
|
+
` token ${d.credential.type ? `${d.credential.type === "agent" ? "agent" : d.credential.type === "pat" ? "personal access" : "device"} · ` : ""}${d.tokenSource === "env" ? "from NETWORKBASE_TOKEN" : `kept in ${storageWords(d.storage)}`} · ${d.access ? (d.access.allWorkspaces ? "all your workspaces" : `only ${safe(d.access.workspaceTitle ?? "one workspace")}`) : d.credential.workspaceId ? "one workspace only" : d.credential.type === "device" ? "all your workspaces" : `${d.credential.scopes.length} permissions`}`,
|
|
287
296
|
// An agent's access in the approval page's words (report A4, A10 "nb whoami and Settings show the same sentence").
|
|
288
297
|
...(d.access ? [` access ${safe(d.access.sentence)}`] : []),
|
|
298
|
+
// Your own sign-in in a sentence too (report C16 #7).
|
|
299
|
+
...(!d.access && d.credential.type === "device" ? [` access Your own sign-in: does what you can, in all your workspaces${d.credential.expiresAt ? `, until ${new Date(d.credential.expiresAt).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" })}` : ""}.`] : []),
|
|
289
300
|
` files up to ${Math.round(d.limits.largestFileBytes / 1024 / 1024)} MB each`,
|
|
290
301
|
...(ctx.flags.verbose ? [` can ${d.credential.scopes.join(", ")}`] : []),
|
|
291
302
|
]);
|
package/lib/commands/browse.mjs
CHANGED
|
@@ -9,6 +9,11 @@ import { formatDate, resolveTask, taskRef } from "./tasks.mjs";
|
|
|
9
9
|
|
|
10
10
|
/** @param {Context} ctx */
|
|
11
11
|
export async function workspaceView(ctx) {
|
|
12
|
+
// `nb workspace view deepscope-ai` names it directly, like -w (found live in M4a: the name was ignored).
|
|
13
|
+
if (ctx.positionals[0]) {
|
|
14
|
+
ctx.flags.workspace = ctx.positionals[0];
|
|
15
|
+
await ctx.resolveWorkspace();
|
|
16
|
+
}
|
|
12
17
|
const w = /** @type {any} */ (await ctx.api.get(`/api/v1/workspaces/${encodeURIComponent(ctx.requireWorkspace())}`));
|
|
13
18
|
const { c } = ctx.out;
|
|
14
19
|
ctx.out.result("nb.workspace.view/1", w, (d) => [
|
|
@@ -98,8 +103,25 @@ export async function fileHistory(ctx) {
|
|
|
98
103
|
if (!p) throw usage("nb file history <path>");
|
|
99
104
|
const node = await nodeOf(ctx, p);
|
|
100
105
|
const res = /** @type {any} */ (await ctx.api.get("/api/v1/extension/file-history", { query: { projectId: ctx.requireWorkspace(), nodeId: node.nodeId ?? node.id } }));
|
|
101
|
-
|
|
102
|
-
|
|
106
|
+
const { c } = ctx.out;
|
|
107
|
+
// Which version is active and what each was based on (C3), so "going back" reads plainly.
|
|
108
|
+
ctx.out.result("nb.file.history/1", { path: remote(p), activeVersion: res.activeVersion ?? null, versions: res.versions }, (d) => [
|
|
109
|
+
...d.versions.map((/** @type {any} */ v) => `${v.version === d.activeVersion ? c.brand(ctx.out.sym.cursor) : " "} v${v.version} ${c.muted(String(v.uploadedAt).slice(0, 16).replace("T", " "))} ${v.uploadedByUsername ? `@${safe(v.uploadedByUsername)}` : safe(v.uploadedByName ?? "someone")}${v.via ? c.muted(` via ${v.via === "agent" ? safe(v.agentName ?? "an agent") : "CLI"}`) : ""}${v.basedOnVersion && v.basedOnVersion !== v.version - 1 ? c.muted(` based on v${v.basedOnVersion}`) : ""}${v.version === d.activeVersion ? ` ${c.success("active")}` : ""}${v.comment ? ` ${safe(v.comment)}` : ""}`),
|
|
110
|
+
...(d.versions.length > 1 ? ["", c.muted(` Go back: nb file use ${safe(d.path.slice(1))} v<n>`)] : []),
|
|
111
|
+
]);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** `nb file use <file> v1` (C3): the app's "Use this version"; the next save is based on it. @param {Context} ctx */
|
|
115
|
+
export async function fileUse(ctx) {
|
|
116
|
+
const [p, raw] = ctx.positionals;
|
|
117
|
+
const version = Number(String(raw ?? "").replace(/^v/i, ""));
|
|
118
|
+
if (!p || !Number.isInteger(version) || version < 1) throw usage("nb file use <path> v<n>", "See the versions: nb file history <path>");
|
|
119
|
+
const node = await nodeOf(ctx, p);
|
|
120
|
+
const res = /** @type {any} */ (await ctx.api.post("/api/v1/extension/file-history", { projectId: ctx.requireWorkspace(), nodeId: node.nodeId ?? node.id, version }));
|
|
121
|
+
ctx.out.result("nb.file.use/1", { path: remote(p), activeVersion: res.activeVersion, previousVersion: res.previousVersion }, (d) => [
|
|
122
|
+
d.previousVersion === d.activeVersion ? `v${d.activeVersion} of ${safe(d.path)} was already active` : `${ctx.out.c.success(ctx.out.sym.done)} v${d.activeVersion} of ${safe(d.path)} is active (was v${d.previousVersion}); the next save is based on it`,
|
|
123
|
+
ctx.out.c.muted(` nb pull gets it here · nb undo puts v${d.previousVersion} back`),
|
|
124
|
+
]);
|
|
103
125
|
}
|
|
104
126
|
|
|
105
127
|
/** @param {Context} ctx @param {"move" | "rename" | "trash"} kind */
|
package/lib/commands/extras.mjs
CHANGED
|
@@ -49,7 +49,7 @@ export async function filesFromLastCommit(cwd) {
|
|
|
49
49
|
|
|
50
50
|
// ───────────────────────────────── saved filters (finding 148)
|
|
51
51
|
|
|
52
|
-
const FILTER_KEYS = ["mine", "all", "status", "limit"];
|
|
52
|
+
const FILTER_KEYS = ["mine", "all", "status", "limit", "due", "to", "sprint", "priority", "sort"];
|
|
53
53
|
|
|
54
54
|
/** `--save <name>` stores the list flags; `@name` brings them back. @param {Context} ctx */
|
|
55
55
|
export function applySavedFilter(ctx) {
|
package/lib/commands/files.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { enqueue, QUEUE_TTL_MS, readQueue, writeQueue } from "../sync/queue.mjs"
|
|
|
12
12
|
import { acquireLock, pruneBaseCopies, readState, saveBaseCopy, writeState } from "../sync/state.mjs";
|
|
13
13
|
import { conflictCopyPath, downloadTo, fetchManifest, renameRetry, safeJoin, uploadFiles } from "../sync/transfer.mjs";
|
|
14
14
|
import { confirm } from "../tui/ask.mjs";
|
|
15
|
-
import { resolveTask } from "./tasks.mjs";
|
|
15
|
+
import { branchTask, resolveTask } from "./tasks.mjs";
|
|
16
16
|
|
|
17
17
|
/** @typedef {import("../context.mjs").Context} Context */
|
|
18
18
|
/** @typedef {import("../sync/plan.mjs").PlanItem} PlanItem */
|
|
@@ -76,15 +76,20 @@ export function recordBase(state, p, f) {
|
|
|
76
76
|
|
|
77
77
|
/** @param {Context} ctx */
|
|
78
78
|
export async function status(ctx) {
|
|
79
|
+
// The day's counts ride along (C2 "a home screen in nb status"); offline or refused, status still works.
|
|
80
|
+
const todayP = ctx.api.get("/api/v1/home").then((/** @type {any} */ h) => ({ dueThisWeek: h.tasks.dueThisWeek, overdue: h.tasks.overdue, unread: h.unread }), () => null);
|
|
79
81
|
const { root, project, items, skipped, offline, manifest } = await buildPlan(ctx);
|
|
82
|
+
const today = await todayP;
|
|
80
83
|
const changed = items.filter((i) => i.state !== "unchanged");
|
|
81
84
|
const conflicts = changed.filter((i) => i.state === "conflict");
|
|
82
85
|
const data = {
|
|
83
86
|
workspace: { id: project.workspaceId, slug: project.slug, title: project.title },
|
|
84
|
-
|
|
87
|
+
// The current task (C8): the started one, or the one the nb/<n>- git branch names.
|
|
88
|
+
startedTask: project.startedTask ?? ((n) => (n ? { number: Number(n), title: "(from the git branch)" } : null))(branchTask(root)),
|
|
85
89
|
offline,
|
|
86
90
|
readOnly: !manifest.canWrite,
|
|
87
91
|
queued: readQueue(root).length,
|
|
92
|
+
today,
|
|
88
93
|
files: changed.map((i) => ({ path: i.path, state: i.state, action: i.action, ...(i.note ? { note: i.note } : {}), ...(i.remote ? { remoteVersion: i.remote.version } : {}) })),
|
|
89
94
|
skipped,
|
|
90
95
|
};
|
|
@@ -92,8 +97,21 @@ export async function status(ctx) {
|
|
|
92
97
|
ctx.out.result("nb.status/1", data, (d) => {
|
|
93
98
|
const task = d.startedTask ? ` · #${d.startedTask.number ?? ""} ${safe(d.startedTask.title ?? "")}` : "";
|
|
94
99
|
const head = `${c.brand(sym.brand)} ${safe(project.slug ?? project.workspaceId)}${task}${d.readOnly ? ` · ${c.warning("read only")}` : ""}${d.offline ? ` · ${c.warning("offline: server side not checked")}` : ""}`;
|
|
95
|
-
const queued = d.queued ? [` ${c.warning(`${d.queued} push(es) queued while offline: nb
|
|
100
|
+
const queued = d.queued ? [` ${c.warning(`${d.queued} push(es) queued while offline: nb queue`)}`] : [];
|
|
101
|
+
const t = d.today;
|
|
102
|
+
const here = d.files.filter((f) => f.action === "push" || f.state === "conflict").length;
|
|
103
|
+
const day = t ? [t.dueThisWeek && `${t.dueThisWeek} due this week`, t.overdue && c.warning(`${t.overdue} overdue`), t.unread && `${t.unread} unread`, here && `${here} ${here === 1 ? "file" : "files"} changed here`].filter(Boolean) : [];
|
|
104
|
+
if (day.length) queued.unshift(` ${day.join(" · ")}`);
|
|
96
105
|
if (!d.files.length) return [head, ...queued, ` ${c.muted(`Up to date · ${root}`)}`, ...skippedLines(d.skipped)];
|
|
106
|
+
// A freshly linked folder: hundreds of server files are one line, not a table (C16 #5).
|
|
107
|
+
const waiting = d.files.filter((f) => f.state === "remote-added");
|
|
108
|
+
if (waiting.length > 20) {
|
|
109
|
+
const rest = d.files.filter((f) => f.state !== "remote-added");
|
|
110
|
+
const line = ` ${waiting.length} files on the server · ${c.muted("nb pull to get them")}`;
|
|
111
|
+
if (!rest.length) return [head, ...queued, line, ...skippedLines(d.skipped)];
|
|
112
|
+
d = { ...d, files: rest };
|
|
113
|
+
queued.push(line);
|
|
114
|
+
}
|
|
97
115
|
const color = (/** @type {string} */ s) => (s === "conflict" ? c.danger : s === "modified" || s === "added" ? c.accent : s.startsWith("remote") ? c.info : c.muted);
|
|
98
116
|
const counts = Object.entries(d.files.reduce((/** @type {Record<string, number>} */ acc, f) => ({ ...acc, [f.state]: (acc[f.state] ?? 0) + 1 }), {})).map(([s, n]) => `${n} ${s}`).join(" · ");
|
|
99
117
|
const rows = ctx.out.table([
|
|
@@ -236,7 +254,7 @@ export async function push(ctx) {
|
|
|
236
254
|
const queueOffline = () => {
|
|
237
255
|
if (ctx.flags["dry-run"]) return new CliError("OFFLINE", "Can't reach the server", { hint: "Try again when you're online" });
|
|
238
256
|
const flags = Object.fromEntries(["task", "as", "message", "keep-both", "folder", "all"].filter((k) => ctx.flags[k] !== undefined).map((k) => [k, ctx.flags[k]]));
|
|
239
|
-
const n = enqueue(root, { id: keyBase, op: "push", paths: only, flags, queuedAt: new Date().toISOString() });
|
|
257
|
+
const n = enqueue(root, { id: keyBase, op: "push", paths: only, flags, queuedAt: new Date().toISOString(), reason: "the server couldn't be reached" });
|
|
240
258
|
return new CliError("OFFLINE", `Offline: queued this push${n > 1 ? ` (${n} waiting)` : ""}`, { hint: "It sends with your next nb sync; your files are unchanged" });
|
|
241
259
|
};
|
|
242
260
|
const release = ctx.flags["dry-run"] ? () => {} : await acquireLock(root, "nb push");
|
|
@@ -244,6 +262,17 @@ export async function push(ctx) {
|
|
|
244
262
|
const plan = await buildPlan(ctx, { only });
|
|
245
263
|
if (plan.offline) throw queueOffline();
|
|
246
264
|
const { project, state } = plan;
|
|
265
|
+
// A file you named that can't go up is an error that says why, never "Nothing changed" (C16 #2).
|
|
266
|
+
const named = new Set(only.map((p) => p.split(path.sep).join("/").replace(/^\/+/, "")));
|
|
267
|
+
const refused = plan.skipped.find((s) => named.has(s.path.replace(/^\/+/, "")));
|
|
268
|
+
if (refused) {
|
|
269
|
+
const limit = plan.manifest.largestFileBytes;
|
|
270
|
+
const bytes = (() => { try { return fs.statSync(path.join(root, refused.path)).size; } catch { return 0; } })();
|
|
271
|
+
const mb = (/** @type {number} */ n) => Math.ceil(n / 1024 / 1024);
|
|
272
|
+
throw /^over the/.test(refused.reason) && limit
|
|
273
|
+
? new CliError("PLAN_LIMIT_FILE_SIZE", `${safe(refused.path)} is ${mb(bytes)} MB; files can be up to ${mb(limit)} MB`, { hint: "Make it smaller, or share it as a link" })
|
|
274
|
+
: new CliError("USAGE", `${safe(refused.path)} can't be pushed: ${refused.reason}`);
|
|
275
|
+
}
|
|
247
276
|
if (!plan.manifest.canWrite) throw new CliError("READ_ONLY", "You can read this workspace but not change it", { hint: "Ask an owner for member access" });
|
|
248
277
|
// With no paths, only files NetworkBase already tracks; new files are pushed by naming them (A1.6, §17.4).
|
|
249
278
|
let items = plan.items.filter((i) => i.action === "push" && (only.length || i.base));
|
|
@@ -285,7 +314,10 @@ export async function push(ctx) {
|
|
|
285
314
|
}
|
|
286
315
|
}
|
|
287
316
|
moves = moves.filter((m) => state.files[m.path]);
|
|
288
|
-
|
|
317
|
+
// The started task gets the files unless told otherwise (C16 #1, C8): nb task start promises it.
|
|
318
|
+
// The current task (C8): --task, the started one, or the nb/<n>- git branch; --no-task opts out.
|
|
319
|
+
const taskRef = ctx.flags.task ?? (ctx.flags["no-task"] ? null : ctx.project?.startedTask?.id ?? branchTask(root));
|
|
320
|
+
const task = taskRef ? await resolveTask(ctx, String(taskRef)) : null;
|
|
289
321
|
const uploaded = items.length
|
|
290
322
|
? await uploadFiles(ctx.api, {
|
|
291
323
|
workspaceId: project.workspaceId,
|
|
@@ -398,6 +430,42 @@ export async function sync(ctx) {
|
|
|
398
430
|
return push(ctx2);
|
|
399
431
|
}
|
|
400
432
|
|
|
433
|
+
// ───────────────────────────────── queue (C6)
|
|
434
|
+
|
|
435
|
+
/** What's waiting to send, since when and why (C6). @param {Context} ctx */
|
|
436
|
+
export async function queue(ctx) {
|
|
437
|
+
const { root } = ctx.requireRoot();
|
|
438
|
+
const entries = readQueue(root).map((e, i) => ({ n: i + 1, id: e.id, paths: e.paths, task: e.flags?.task ?? null, queuedAt: e.queuedAt, reason: e.reason ?? "the server couldn't be reached", dropsAt: new Date(Date.parse(e.queuedAt) + QUEUE_TTL_MS).toISOString() }));
|
|
439
|
+
const { c } = ctx.out;
|
|
440
|
+
ctx.out.result("nb.queue/1", { entries }, (d) => (d.entries.length ? [
|
|
441
|
+
`${d.entries.length} ${d.entries.length === 1 ? "push is" : "pushes are"} waiting to send`,
|
|
442
|
+
...d.entries.map((e) => ` ${e.n}. ${e.paths.length ? e.paths.map((p) => safe(p)).slice(0, 3).join(", ") + (e.paths.length > 3 ? ` and ${e.paths.length - 3} more` : "") : "every changed file"}${e.task ? ` · task ${safe(String(e.task))}` : ""} ${c.muted(`queued ${e.queuedAt.slice(0, 16).replace("T", " ")}: ${e.reason}`)}`),
|
|
443
|
+
c.muted(" nb queue retry sends them · nb queue drop <n> forgets one (your files stay as they are)"),
|
|
444
|
+
] : "Nothing waiting: every push has gone up"));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Send the queue now (C6). @param {Context} ctx */
|
|
448
|
+
export async function queueRetry(ctx) {
|
|
449
|
+
const { root } = ctx.requireRoot();
|
|
450
|
+
const before = readQueue(root).length;
|
|
451
|
+
await replayQueue(ctx);
|
|
452
|
+
ctx.out.result("nb.queue.retry/1", { sent: before }, (d) => (d.sent ? `${ctx.out.c.success(ctx.out.sym.done)} Sent ${d.sent} queued ${d.sent === 1 ? "push" : "pushes"}` : "Nothing waiting"));
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Forget queued pushes; the files themselves don't change (C6). @param {Context} ctx */
|
|
456
|
+
export async function queueDrop(ctx) {
|
|
457
|
+
const { root } = ctx.requireRoot();
|
|
458
|
+
const entries = readQueue(root);
|
|
459
|
+
if (!ctx.flags.all && !ctx.positionals.length) throw usage("Which ones?", "nb queue drop 1, or nb queue drop --all");
|
|
460
|
+
const drop = ctx.flags.all ? entries : ctx.positionals.map((r) => {
|
|
461
|
+
const hit = /^\d+$/.test(r) ? entries[Number(r) - 1] : entries.find((e) => e.id.startsWith(r));
|
|
462
|
+
if (!hit) throw new CliError("NOT_FOUND", `Nothing queued as ${r}`, { hint: "nb queue" });
|
|
463
|
+
return hit;
|
|
464
|
+
});
|
|
465
|
+
writeQueue(root, entries.filter((e) => !drop.includes(e)));
|
|
466
|
+
ctx.out.result("nb.queue.drop/1", { dropped: drop.length }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Dropped ${d.dropped} queued ${d.dropped === 1 ? "push" : "pushes"}; your files are unchanged (nb status shows them)`);
|
|
467
|
+
}
|
|
468
|
+
|
|
401
469
|
/**
|
|
402
470
|
* Sends pushes queued while offline, oldest first. A conflict stops the queue there (later pushes may depend on
|
|
403
471
|
* it); still offline keeps it; expired entries are dropped with a note (A12.4).
|
package/lib/commands/inbox.mjs
CHANGED
|
@@ -22,7 +22,7 @@ export async function inbox(ctx) {
|
|
|
22
22
|
ctx.out.result("nb.inbox/1", { unread: p.unreadCount, items }, (d) => d.items.length ? [
|
|
23
23
|
`${d.unread} unread`,
|
|
24
24
|
...d.items.map((i, n) => `${i.readAt ? " " : c.brand(sym.brand)} ${String(n + 1).padStart(2)} ${c.muted(formatDate(i.activityAt ?? i.createdAt))} ${safe(i.title)}${i.body ? c.muted(` · ${safe(String(i.body)).replace(/\n/g, " ").slice(0, 80)}`) : ""}`),
|
|
25
|
-
c.muted(" nb inbox
|
|
25
|
+
c.muted(" nb inbox reply <n> \"text\" · nb inbox approve <n> · nb inbox read <n> · nb inbox open <n>"),
|
|
26
26
|
] : "Nothing in your inbox", { page: true });
|
|
27
27
|
}
|
|
28
28
|
|
|
@@ -45,6 +45,38 @@ export async function inboxRead(ctx) {
|
|
|
45
45
|
ctx.out.result("nb.inbox.read/1", { read: res.read }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Marked ${d.read} read`);
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
+
/** The task an inbox item is about; replying and approving work on those (C4). @param {any} item @param {string} ref */
|
|
49
|
+
function taskOf(item, ref) {
|
|
50
|
+
const refs = item.entityRefs ?? {};
|
|
51
|
+
if (!refs.taskId) throw new CliError("NOT_A_TASK", "That item isn't about a task, so there's nothing to reply to here", { hint: `nb inbox open ${ref}` });
|
|
52
|
+
return /** @type {{ taskId: string, projectId?: string, commentId?: string }} */ (refs);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** `nb inbox reply 3 "done"` (C4): a comment on the item's task, as a reply when the item is a comment. @param {Context} ctx */
|
|
56
|
+
export async function inboxReply(ctx) {
|
|
57
|
+
const [ref, ...words] = ctx.positionals;
|
|
58
|
+
const text = String(ctx.flags.message ?? words.join(" ")).trim();
|
|
59
|
+
if (!ref || !text) throw usage('nb inbox reply <n> "your reply"');
|
|
60
|
+
const [item] = await pick({ ...ctx, positionals: [ref] });
|
|
61
|
+
const refs = taskOf(item, ref);
|
|
62
|
+
await ctx.api.post("/api/v1/extension/comments", { kind: "task", ...(refs.projectId ? { projectId: refs.projectId } : {}), taskId: refs.taskId, text, ...(refs.commentId ? { replyTo: refs.commentId } : {}) });
|
|
63
|
+
await ctx.api.post("/api/v1/inbox/read", { ids: [item.id] });
|
|
64
|
+
ctx.out.result("nb.inbox.reply/1", { item: item.id, taskId: refs.taskId }, () => `${ctx.out.c.success(ctx.out.sym.done)} Replied on ${safe(item.title)}`);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** `nb inbox approve 3` (C4): approve the task waiting for your review. @param {Context} ctx */
|
|
68
|
+
export async function inboxApprove(ctx) {
|
|
69
|
+
const ref = ctx.positionals[0];
|
|
70
|
+
if (!ref) throw usage("nb inbox approve <n>");
|
|
71
|
+
const [item] = await pick(ctx);
|
|
72
|
+
const refs = taskOf(item, ref);
|
|
73
|
+
const { task } = /** @type {any} */ (await ctx.api.get("/api/v1/extension/task-detail", { query: { taskId: refs.taskId, brief: "1" } }));
|
|
74
|
+
if (task.reviewStatus !== "pending") throw new CliError("NOTHING_TO_APPROVE", `#${task.taskNumber} isn't waiting for review`, { hint: `nb inbox open ${ref}` });
|
|
75
|
+
await ctx.api.patch("/api/v1/extension/task-update", { kind: "approve", projectId: task.projectId, taskId: task.id, expectedUpdatedAt: new Date(task.updatedAt).toISOString() });
|
|
76
|
+
await ctx.api.post("/api/v1/inbox/read", { ids: [item.id] });
|
|
77
|
+
ctx.out.result("nb.inbox.approve/1", { number: task.taskNumber }, (d) => `${ctx.out.c.success(ctx.out.sym.done)} Approved #${d.number}`);
|
|
78
|
+
}
|
|
79
|
+
|
|
48
80
|
/** @param {Context} ctx */
|
|
49
81
|
export async function inboxOpen(ctx) {
|
|
50
82
|
const [item] = await pick(ctx);
|
package/lib/commands/link.mjs
CHANGED
|
@@ -29,7 +29,10 @@ export async function init(ctx) {
|
|
|
29
29
|
}
|
|
30
30
|
if (!chosen) {
|
|
31
31
|
if (!workspaces.length) throw new CliError("WORKSPACE_NOT_FOUND", "You have no workspaces yet", { hint: "Create one at networkbase.in first" });
|
|
32
|
-
|
|
32
|
+
// The workspace named like this folder (or its repository) comes first (C1).
|
|
33
|
+
const matches = folderMatches(workspaces, here);
|
|
34
|
+
const ordered = [...matches, ...workspaces.filter((/** @type {any} */ w) => !matches.includes(w))];
|
|
35
|
+
const slug = await ask(ctx, { key: "workspace", header: "Workspace", question: "Which workspace should this folder link to?", options: ordered.slice(0, 9).map((/** @type {any} */ w, /** @type {number} */ i) => ({ value: w.slug, label: safe(w.title), description: i === 0 && matches.length ? `${w.slug} · matches this folder` : w.slug, recommended: i === 0 })) });
|
|
33
36
|
chosen = workspaces.find((/** @type {any} */ w) => w.slug === slug);
|
|
34
37
|
}
|
|
35
38
|
const remoteRoot = ctx.flags.path ? `/${String(ctx.flags.path).replace(/^\/+|\/+$/g, "")}` : "/";
|
|
@@ -46,6 +49,35 @@ export async function init(ctx) {
|
|
|
46
49
|
ctx.out.c.muted(`Next: nb pull to get the files, or edit and nb push <files>${ctx.flags.task ? "" : " (nb task start <n> to work on a task)"}`));
|
|
47
50
|
}
|
|
48
51
|
|
|
52
|
+
const plain = (/** @type {unknown} */ s) => String(s ?? "").toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
53
|
+
|
|
54
|
+
/** The folder's name and its git repository's name: what a person most likely called the workspace. @param {string} cwd */
|
|
55
|
+
function folderNames(cwd) {
|
|
56
|
+
const names = new Set([plain(path.basename(cwd))]);
|
|
57
|
+
for (let dir = cwd; ; dir = path.dirname(dir)) {
|
|
58
|
+
const config = path.join(dir, ".git", "config");
|
|
59
|
+
if (fs.existsSync(config)) {
|
|
60
|
+
const url = /\[remote "origin"\][^[]*?url\s*=\s*(\S+)/.exec(fs.readFileSync(config, "utf8"))?.[1];
|
|
61
|
+
if (url) names.add(plain(path.basename(url).replace(/\.git$/, "")));
|
|
62
|
+
if (dir !== cwd) names.add(plain(path.basename(dir)));
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
if (path.dirname(dir) === dir) break;
|
|
66
|
+
}
|
|
67
|
+
names.delete("");
|
|
68
|
+
return [...names];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Workspaces whose slug or title matches this folder or its repository, best first (C1).
|
|
73
|
+
* @template {{ slug: string, title: string }} W @param {W[]} workspaces @param {string} cwd @returns {W[]}
|
|
74
|
+
*/
|
|
75
|
+
export function folderMatches(workspaces, cwd) {
|
|
76
|
+
const names = folderNames(cwd);
|
|
77
|
+
const score = (/** @type {W} */ w) => Math.max(0, ...[plain(w.slug), plain(w.title)].flatMap((label) => names.map((n) => (label === n ? 3 : label && (label.includes(n) || n.includes(label)) && Math.min(label.length, n.length) >= 3 ? 2 : 0))));
|
|
78
|
+
return workspaces.map((w, i) => ({ w, s: score(w), i })).filter((x) => x.s > 0).sort((a, b) => b.s - a.s || a.i - b.i).map((x) => x.w);
|
|
79
|
+
}
|
|
80
|
+
|
|
49
81
|
/**
|
|
50
82
|
* 1.x left a mirror folder and maybe a background process (A1.20). The mirror moves aside (never deleted);
|
|
51
83
|
* the old auto-push process is stopped.
|
package/lib/commands/misc.mjs
CHANGED
|
@@ -12,6 +12,34 @@ import { safe } from "../print/style.mjs";
|
|
|
12
12
|
|
|
13
13
|
/** @typedef {import("../context.mjs").Context} Context */
|
|
14
14
|
|
|
15
|
+
/** `nb` on its own (report C1): signed out → sign in; not linked → the matching workspace; linked → nb status. @param {Context} ctx */
|
|
16
|
+
export async function home(ctx) {
|
|
17
|
+
const { c } = ctx.out;
|
|
18
|
+
if (!ctx.profile.token) {
|
|
19
|
+
ctx.out.result("nb.home/1", { state: "signed-out" }, () => [
|
|
20
|
+
`${c.brand("NetworkBase")} ${c.muted(ctx.version)}`, "", "You're not signed in.", "",
|
|
21
|
+
` nb login ${c.muted("Sign in (one click in your browser)")}`,
|
|
22
|
+
` nb help ${c.muted("What the CLI can do")}`,
|
|
23
|
+
]);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (!ctx.project) {
|
|
27
|
+
const { folderMatches } = await import("./link.mjs");
|
|
28
|
+
const { workspaces } = /** @type {any} */ (await ctx.api.get("/api/v1/extension/workspaces"));
|
|
29
|
+
const matches = folderMatches(workspaces, ctx.cwd).slice(0, 3).map((/** @type {any} */ w) => ({ slug: w.slug, title: w.title }));
|
|
30
|
+
ctx.out.result("nb.home/1", { state: "not-linked", matches, workspaces: workspaces.length }, (d) => [
|
|
31
|
+
"This folder isn't linked to a workspace.",
|
|
32
|
+
...(d.matches.length
|
|
33
|
+
? ["", `Best match${d.matches.length > 1 ? "es" : ""}:`, ...d.matches.map((/** @type {any} */ m) => ` nb init ${safe(m.slug)} ${c.muted(safe(m.title))}`)]
|
|
34
|
+
: ["", ` nb init ${c.muted(d.workspaces ? "Choose one of your workspaces" : "Create a workspace at networkbase.in first")}`]),
|
|
35
|
+
` nb help ${c.muted("What the CLI can do")}`,
|
|
36
|
+
]);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const { status } = await import("./files.mjs");
|
|
40
|
+
return status(ctx);
|
|
41
|
+
}
|
|
42
|
+
|
|
15
43
|
/** @param {Context} ctx */
|
|
16
44
|
export async function help(ctx) {
|
|
17
45
|
const name = ctx.positionals.join(" ");
|
|
@@ -136,15 +164,40 @@ export async function feedback(ctx) {
|
|
|
136
164
|
|
|
137
165
|
/** One short line for your shell prompt: the linked workspace and started task. No network; empty outside a link. @param {Context} ctx */
|
|
138
166
|
export async function prompt(ctx) {
|
|
139
|
-
if (!ctx.project) return;
|
|
140
|
-
const
|
|
141
|
-
ctx.
|
|
167
|
+
if (!ctx.project || !ctx.root) return;
|
|
168
|
+
const { branchTask } = await import("./tasks.mjs");
|
|
169
|
+
const number = ctx.project.startedTask?.number ?? branchTask(ctx.root);
|
|
170
|
+
// "2 changed": tracked files whose size or time moved since the last sync, by stat only (it runs on every prompt).
|
|
171
|
+
// ponytail: new untracked files aren't counted, and past 3,000 tracked files the count is left out.
|
|
172
|
+
let changed = 0;
|
|
173
|
+
try {
|
|
174
|
+
const { readState } = await import("../sync/state.mjs");
|
|
175
|
+
const { toRelative } = await import("../sync/local.mjs");
|
|
176
|
+
const entries = Object.entries(readState(ctx.root, ctx.project.workspaceId).files);
|
|
177
|
+
if (entries.length <= 3000) {
|
|
178
|
+
for (const [remotePath, base] of entries) {
|
|
179
|
+
const rel = toRelative(ctx.project.remoteRoot ?? "/", remotePath);
|
|
180
|
+
if (rel === null) continue;
|
|
181
|
+
try {
|
|
182
|
+
const st = fs.statSync(path.join(ctx.root, ...rel.split("/")));
|
|
183
|
+
if (st.size !== base.size || Math.trunc(st.mtimeMs) !== Math.trunc(base.mtimeMs)) changed++;
|
|
184
|
+
} catch {
|
|
185
|
+
changed++;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
} catch {
|
|
190
|
+
// No sync yet: nothing to count.
|
|
191
|
+
}
|
|
192
|
+
const parts = [number ? `#${number}` : safe(ctx.project.slug ?? "nb"), changed ? `${changed} changed` : null].filter(Boolean);
|
|
193
|
+
// A trailing space, so `PS1='$(nb prompt)'$PS1` reads well and adds nothing outside linked folders.
|
|
194
|
+
ctx.out.raw(`[${parts.join(" · ")}] `);
|
|
142
195
|
}
|
|
143
196
|
|
|
144
|
-
const RC = /** @type {Record<string, { file: (home: string) => string, line: string }>} */ ({
|
|
145
|
-
zsh: { file: (h) => path.join(h, ".zshrc"), line: "command -v nb >/dev/null && source <(nb completion zsh)" },
|
|
146
|
-
bash: { file: (h) => path.join(h, ".bashrc"), line: "command -v nb >/dev/null && source <(nb completion bash)" },
|
|
147
|
-
fish: { file: (h) => path.join(h, ".config", "fish", "conf.d", "nb.fish"), line: "type -q nb; and nb completion fish | source" },
|
|
197
|
+
const RC = /** @type {Record<string, { file: (home: string) => string, line: string, prompt: string }>} */ ({
|
|
198
|
+
zsh: { file: (h) => path.join(h, ".zshrc"), line: "command -v nb >/dev/null && source <(nb completion zsh)", prompt: "setopt PROMPT_SUBST; PROMPT='$(nb prompt 2>/dev/null)'$PROMPT" },
|
|
199
|
+
bash: { file: (h) => path.join(h, ".bashrc"), line: "command -v nb >/dev/null && source <(nb completion bash)", prompt: "PS1='$(nb prompt 2>/dev/null)'$PS1" },
|
|
200
|
+
fish: { file: (h) => path.join(h, ".config", "fish", "conf.d", "nb.fish"), line: "type -q nb; and nb completion fish | source", prompt: "functions -q _nb_prompt_was; or functions -c fish_prompt _nb_prompt_was; function fish_prompt; nb prompt 2>/dev/null; _nb_prompt_was; end" },
|
|
148
201
|
});
|
|
149
202
|
|
|
150
203
|
/** Adds completions to your shell's startup file, after a yes (A6.6). @param {Context} ctx */
|
|
@@ -158,14 +211,20 @@ export async function setupShell(ctx) {
|
|
|
158
211
|
if (/[\\/]_npx[\\/]/.test(process.argv[1] ?? "")) ctx.out.warn("nb isn't installed, so completions won't find it: npm i -g @networkbase/cli");
|
|
159
212
|
const file = rc.file(os.homedir());
|
|
160
213
|
const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
|
|
161
|
-
if (current.includes("nb completion")) return ctx.out.result("nb.setup.shell/1", { shell, file, added: false }, () => `Completions are already set up in ${file}`);
|
|
162
214
|
const { confirm } = await import("../tui/ask.mjs");
|
|
163
|
-
|
|
215
|
+
/** @type {string[]} */
|
|
216
|
+
const lines = [];
|
|
217
|
+
if (!current.includes("nb completion")) {
|
|
218
|
+
if (!(await confirm(ctx, { key: "shell", question: `Add nb completions to ${file}?`, preview: rc.line, yesLabel: "Add", defaultYes: true }))) return 130;
|
|
219
|
+
lines.push(rc.line);
|
|
220
|
+
}
|
|
221
|
+
// The current task in the prompt, [#4 · 2 changed] (C8): a separate yes, since it changes how the prompt looks.
|
|
222
|
+
if (!current.includes("nb prompt") && (await confirm(ctx, { key: "prompt", question: `Show the current task in your prompt too, like [#4 · 2 changed]?`, preview: rc.prompt, yesLabel: "Add", defaultYes: true }).catch(() => false))) lines.push(rc.prompt);
|
|
223
|
+
if (!lines.length) return ctx.out.result("nb.setup.shell/1", { shell, file, added: false }, () => `Already set up in ${file}`);
|
|
164
224
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
165
|
-
fs.appendFileSync(file, `${current && !current.endsWith("\n") ? "\n" : ""}# NetworkBase CLI\n${
|
|
166
|
-
ctx.out.result("nb.setup.shell/1", { shell, file, added: true }, () => [
|
|
167
|
-
`${ctx.out.c.success(ctx.out.sym.done)} Added completions to ${file}; open a new terminal to use them`,
|
|
168
|
-
ctx.out.c.muted(` Workspace in your prompt too: ${shell === "fish" ? "add (nb prompt) to fish_prompt" : "PS1='$(nb prompt) '$PS1"}`),
|
|
225
|
+
fs.appendFileSync(file, `${current && !current.endsWith("\n") ? "\n" : ""}# NetworkBase CLI\n${lines.join("\n")}\n`);
|
|
226
|
+
ctx.out.result("nb.setup.shell/1", { shell, file, added: true, prompt: lines.includes(rc.prompt) }, (d) => [
|
|
227
|
+
`${ctx.out.c.success(ctx.out.sym.done)} Added ${lines.includes(rc.line) ? "completions" : ""}${lines.length === 2 ? " and " : ""}${d.prompt ? "the task in your prompt" : ""} to ${file}; open a new terminal to use ${lines.length === 2 ? "them" : "it"}`,
|
|
169
228
|
]);
|
|
170
229
|
}
|
|
171
230
|
|