@zinn-dev/cli 0.36.1 → 0.38.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.
@@ -1,34 +1,59 @@
1
1
  import type { RouteDef } from "../types";
2
- import type { PresentedTask } from "../presentation/task-presentation";
2
+ import type {
3
+ PresentedColumn,
4
+ PresentedColumnTaskCount,
5
+ } from "../presentation/column-presentation";
3
6
 
4
7
  import { parseArgs } from "node:util";
5
8
 
6
- import { column, project, task } from "@zinn-dev/core";
9
+ import { column, project } from "@zinn-dev/core";
7
10
  import {
8
11
  confirmAction,
12
+ failureMessage,
9
13
  output,
10
14
  quit,
11
- validatePositionalCount,
15
+ UsageError,
16
+ validatePositionals,
12
17
  validateUniqueOptions,
13
18
  } from "../lib";
14
- import { formatTaskList, presentTask } from "../presentation/task-presentation";
19
+ import { resolveTextEdit, textEditHelp, textEditOptions, textEditUsage } from "../text-edit";
20
+ import { formatColumnList } from "../presentation/column-presentation";
15
21
  import { formatDescriptionPreview } from "../presentation/description-presentation";
22
+ import { formatCellSeparator, formatRows } from "../presentation/row-layout";
23
+ import { formatSection } from "../presentation/section";
16
24
  import { currentActor } from "../actor";
17
25
 
18
26
  type PresentedProject = { key: string; name: string; description: string | null };
19
- type PresentedProjectView = PresentedProject & { tasks: Array<PresentedTask> };
27
+ type PresentedProjectView = PresentedProject & {
28
+ columns: Array<PresentedColumnTaskCount>;
29
+ archivedTaskCount: number;
30
+ };
31
+ type ProjectRowOptions = { showsDescriptionPreview?: boolean };
20
32
 
21
33
  function presentProject(projectMatch: PresentedProject): PresentedProject {
22
34
  return { key: projectMatch.key, name: projectMatch.name, description: projectMatch.description };
23
35
  }
24
36
 
25
- function formatProject(presented: PresentedProject, keyWidth = presented.key.length) {
26
- const descriptionPreview = formatDescriptionPreview(presented.description);
27
- const description = descriptionPreview.length > 0 ? ` | ${descriptionPreview}` : "";
28
- return `${presented.key.padEnd(keyWidth)} | ${presented.name}${description}`;
37
+ function formatProject(presented: PresentedProject, options: ProjectRowOptions = {}) {
38
+ return formatProjectList([presented], options);
29
39
  }
30
40
 
31
- type PresentedColumn = { project: string; name: string };
41
+ function formatProjectList(
42
+ presentedProjects: Array<PresentedProject>,
43
+ { showsDescriptionPreview = true }: ProjectRowOptions = {},
44
+ ) {
45
+ return formatRows(
46
+ presentedProjects.map((presented) => {
47
+ const descriptionPreview = showsDescriptionPreview
48
+ ? formatDescriptionPreview(presented.description)
49
+ : "";
50
+ const description =
51
+ descriptionPreview.length > 0 ? `${formatCellSeparator()}${descriptionPreview}` : "";
52
+
53
+ return [{ text: presented.key }, { text: `${presented.name}${description}` }];
54
+ }),
55
+ );
56
+ }
32
57
 
33
58
  function presentColumn(columnMatch: { project_id: string; name: string }): PresentedColumn {
34
59
  const columnProject = project.getById(columnMatch.project_id)!;
@@ -37,7 +62,7 @@ function presentColumn(columnMatch: { project_id: string; name: string }): Prese
37
62
  }
38
63
 
39
64
  function formatColumn(presented: PresentedColumn) {
40
- return `${presented.project} | ${presented.name}`;
65
+ return formatColumnList([presented], { showsProject: true });
41
66
  }
42
67
 
43
68
  export const projectRouter = {
@@ -51,15 +76,10 @@ export const projectRouter = {
51
76
  tokens: true,
52
77
  });
53
78
 
54
- const projectKey = positionals[0];
55
-
56
- if (projectKey == null) {
57
- quit("Project key must be specified");
58
- }
59
-
60
- validatePositionalCount(positionals, 1, "Only one project key can be specified");
61
-
62
79
  validateUniqueOptions(tokens);
80
+ validatePositionals(positionals, ["<project-key>"]);
81
+
82
+ const projectKey = positionals[0]!;
63
83
 
64
84
  try {
65
85
  const createdProject = project.create(
@@ -68,7 +88,7 @@ export const projectRouter = {
68
88
  );
69
89
  output(presentProject(createdProject), formatProject);
70
90
  } catch (err: any) {
71
- quit(err?.message ?? "Something went wrong");
91
+ quit(failureMessage(err, "Something went wrong"));
72
92
  }
73
93
  },
74
94
  help: `Usage: zinn project create <project-key> [--name <text>] [--description <text>]
@@ -77,23 +97,19 @@ Create a project with the default columns.
77
97
  Project keys are stored in uppercase.
78
98
 
79
99
  An omitted name defaults to the uppercase project key.
80
- Names cannot be blank.
100
+ Names are trimmed and cannot be blank or contain line breaks or control characters.
81
101
  Descriptions may contain multiple lines. If omitted, they are saved as null.
82
102
 
83
103
  Example: zinn project create MDR --name "Macrodata Refinement"`,
84
104
  },
85
105
  list: {
86
- run: () => {
87
- const projects = project.getAll();
106
+ run: (args: Array<string>) => {
107
+ const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
108
+ validatePositionals(positionals, []);
88
109
 
89
- output(projects.map(presentProject), (presentedProjects) => {
90
- const longestKeyLength = presentedProjects.reduce(
91
- (prev, current) => Math.max(prev, current.key.length),
92
- 0,
93
- );
110
+ const projects = project.getAll();
94
111
 
95
- return presentedProjects.map((p) => formatProject(p, longestKeyLength)).join("\n");
96
- });
112
+ output(projects.map(presentProject), formatProjectList);
97
113
  },
98
114
  help: `Usage: zinn project list
99
115
 
@@ -103,35 +119,47 @@ Example: zinn project list`,
103
119
  },
104
120
  view: {
105
121
  run: (args: Array<string>) => {
106
- const projectKey = args[0];
107
-
108
- if (projectKey == null) {
109
- quit("Project key must be specified");
110
- }
111
-
112
- validatePositionalCount(args, 1, "Only one project key can be specified");
122
+ const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
123
+ validatePositionals(positionals, ["<project-key>"]);
113
124
 
125
+ const projectKey = positionals[0]!;
114
126
  const projectMatch = project.getByKey(projectKey);
115
127
 
116
128
  if (projectMatch == null) {
117
129
  quit(`Project with key "${project.standardizeKey(projectKey)}" does not exist!`);
118
130
  }
119
131
 
132
+ const taskCounts = column.getTaskCountsByProjectKey(projectMatch.key);
120
133
  const presentedProject: PresentedProjectView = {
121
134
  ...presentProject(projectMatch),
122
- tasks: task.getAll({ projectKey, archive: "active" }).map(presentTask),
135
+ columns: taskCounts.columns.map((columnCount) => ({
136
+ name: columnCount.column.name,
137
+ taskCount: columnCount.taskCount,
138
+ })),
139
+ archivedTaskCount: taskCounts.archivedTaskCount,
123
140
  };
124
141
 
125
142
  output(presentedProject, (viewedProject) => {
126
- const projectHeader = formatProject(viewedProject);
127
- const taskList = formatTaskList(viewedProject.tasks);
143
+ // The full description follows as its own section, so the row leaves out the preview.
144
+ const sections = [formatProject(viewedProject, { showsDescriptionPreview: false })];
145
+
146
+ if (viewedProject.description != null) {
147
+ sections.push(formatSection("Description", viewedProject.description));
148
+ }
149
+
150
+ const columnTaskCounts = formatColumnList(viewedProject.columns, {
151
+ showsTaskCounts: true,
152
+ archivedTaskCount: viewedProject.archivedTaskCount,
153
+ });
154
+ sections.push(formatSection("Columns", columnTaskCounts));
128
155
 
129
- return taskList.length === 0 ? projectHeader : `${projectHeader}\n\n${taskList}`;
156
+ return sections.join("\n\n");
130
157
  });
131
158
  },
132
159
  help: `Usage: zinn project view <project-key>
133
160
 
134
- Show a project and its active tasks in board order.
161
+ Show a project with its description and the number of tasks in each column.
162
+ The description prints in full, keeping its line breaks. Archived tasks are counted as one total.
135
163
 
136
164
  Example: zinn project view MDR`,
137
165
  },
@@ -139,53 +167,52 @@ Example: zinn project view MDR`,
139
167
  run: (args) => {
140
168
  const { values, positionals, tokens } = parseArgs({
141
169
  args,
142
- options: { name: { type: "string" }, description: { type: "string" } },
170
+ options: { name: { type: "string" }, description: { type: "string" }, ...textEditOptions },
143
171
  allowPositionals: true,
144
172
  strict: true,
145
173
  tokens: true,
146
174
  });
147
175
 
148
- const projectKey = positionals[0];
149
-
150
- if (projectKey == null) {
151
- quit("Project key must be specified");
152
- }
153
-
154
- validatePositionalCount(positionals, 1, "Only one project key can be specified");
155
-
156
176
  validateUniqueOptions(tokens);
177
+ validatePositionals(positionals, ["<project-key>"]);
157
178
 
158
- if (values.name === undefined && values.description === undefined) {
179
+ const projectKey = positionals[0]!;
180
+ const description = resolveTextEdit(values.description, values, "--description");
181
+
182
+ if (values.name === undefined && description === undefined) {
159
183
  quit("Provide an edit flag: --name or --description");
160
184
  }
161
185
 
162
186
  const editedProject = project.edit(
163
- { projectKey, name: values.name, description: values.description },
187
+ { projectKey, name: values.name, description },
164
188
  currentActor(),
165
189
  );
166
190
  output(presentProject(editedProject), formatProject);
167
191
  },
168
- help: `Usage: zinn project edit <project-key> [--name <text>] [--description <text>]
192
+ help: `Usage: zinn project edit <project-key> [--name <text>] [--description <text> ${textEditUsage}]
169
193
 
170
194
  Change the supplied project fields. At least one edit flag is required.
171
195
  Use --description "" to clear the description.
172
- Omitted fields are preserved. Unchanged values leave the timestamp unchanged.
173
196
 
174
- Example: zinn project edit MDR --name "Macrodata Refinement"`,
197
+ ${textEditHelp("--description")}
198
+
199
+ Examples:
200
+ zinn project edit MDR --name "Macrodata Refinement"
201
+ zinn project edit MDR --description "database" --replacing "board" --all`,
175
202
  },
176
203
  delete: {
177
204
  run: (args: Array<string>) => {
178
- const { values, positionals } = parseArgs({
205
+ const { values, positionals, tokens } = parseArgs({
179
206
  args,
180
207
  options: { yes: { type: "boolean" } },
181
208
  allowPositionals: true,
182
209
  strict: true,
210
+ tokens: true,
183
211
  });
184
- const projectKey = positionals[0];
212
+ validateUniqueOptions(tokens);
213
+ validatePositionals(positionals, ["<project-key>"]);
185
214
 
186
- if (projectKey == null) {
187
- quit("You need to specificy which project to delete");
188
- }
215
+ const projectKey = positionals[0]!;
189
216
 
190
217
  try {
191
218
  const projectMatch = project.getByKey(projectKey);
@@ -206,7 +233,7 @@ Example: zinn project edit MDR --name "Macrodata Refinement"`,
206
233
  output(presentProject(projectMatch), (p) => `Deletion cancelled for ${formatProject(p)}`);
207
234
  }
208
235
  } catch (err: any) {
209
- quit(err?.message ?? "Something went wrong");
236
+ quit(failureMessage(err, "Something went wrong"));
210
237
  }
211
238
  },
212
239
  help: `Usage: zinn project delete <project-key> [--yes]
@@ -219,42 +246,45 @@ Example: zinn project delete MDR`,
219
246
  column: {
220
247
  create: {
221
248
  run: (args: Array<string>) => {
222
- const projectKey = args[0];
223
- const columnName = args[1];
249
+ const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
250
+ validatePositionals(positionals, ["<project-key>", "<column-name>"]);
224
251
 
225
- if (projectKey == null || columnName == null) {
226
- quit("Both the project name and the column name must be defined");
227
- }
252
+ const projectKey = positionals[0]!;
253
+ const columnName = positionals[1]!;
228
254
 
229
255
  try {
230
256
  const createdColumn = column.create({ projectKey, name: columnName }, currentActor());
231
257
  output(presentColumn(createdColumn), formatColumn);
232
258
  } catch (err: any) {
233
- quit(err?.message ?? "Something went wrong");
259
+ quit(failureMessage(err, "Something went wrong"));
234
260
  }
235
261
  },
236
262
  help: `Usage: zinn project column create <project-key> <column-name>
237
263
 
238
264
  Add a column at the end of a project's board.
239
- Names are trimmed, must contain printable text on a single line, and must be unique within the project regardless of casing.
265
+ Names are trimmed, cannot be blank or contain line breaks or control characters, and must be unique within the project regardless of casing.
240
266
 
241
267
  Example: zinn project column create MDR "Boardlog"`,
242
268
  },
243
269
  list: {
244
270
  run: (args: Array<string>) => {
245
- const projectKey = args[0];
246
- if (projectKey == null) {
247
- quit("Project key needs to be specified to list columns");
248
- }
249
-
250
- // TODO: attach per-column task count
251
- // TODO: terminal formatting
252
- const columns = column.getAllByProjectKey(projectKey).map((c) => ({ name: c.name }));
253
- output(columns, (presentedColumns) => presentedColumns.map((c) => c.name).join("\n"));
271
+ const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
272
+ validatePositionals(positionals, ["<project-key>"]);
273
+
274
+ const taskCounts = column.getTaskCountsByProjectKey(positionals[0]!);
275
+ const columns = taskCounts.columns.map((columnCount) => ({
276
+ name: columnCount.column.name,
277
+ taskCount: columnCount.taskCount,
278
+ }));
279
+ output(columns, (presentedColumns) =>
280
+ formatColumnList(presentedColumns, {
281
+ showsTaskCounts: true,
282
+ }),
283
+ );
254
284
  },
255
285
  help: `Usage: zinn project column list <project-key>
256
286
 
257
- List a project's columns in board order.
287
+ List a project's columns in board order with their unarchived task counts.
258
288
 
259
289
  Example: zinn project column list MDR`,
260
290
  },
@@ -268,12 +298,8 @@ Example: zinn project column list MDR`,
268
298
  tokens: true,
269
299
  });
270
300
 
271
- validatePositionalCount(
272
- positionals,
273
- 2,
274
- "Both the project key and the column name must be specified",
275
- );
276
301
  validateUniqueOptions(tokens);
302
+ validatePositionals(positionals, ["<project-key>", "<column-name>"]);
277
303
 
278
304
  if (values.name === undefined) {
279
305
  quit("Provide an edit flag: --name");
@@ -302,31 +328,30 @@ Example: zinn project column edit MDR "In Progress" --name "Refining"`,
302
328
  },
303
329
  order: {
304
330
  run: (args: Array<string>) => {
305
- const [projectKey, columnName, direction, targetColumnName, ...extraArgs] = args;
306
-
307
- if (projectKey == null || columnName == null) {
308
- quit("Both the project key and the column name must be specified");
309
- }
310
-
311
- if (direction == null) {
312
- quit("Order direction must be specified");
313
- }
314
-
331
+ const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
332
+ /**
333
+ * The words every direction needs. Only whether they are there is checked here,
334
+ * since the direction decides whether a target column follows.
335
+ */
336
+ const leadingWords = [
337
+ "<project-key>",
338
+ "<column-name>",
339
+ "{first|previous|next|last|before|after}",
340
+ ];
341
+ validatePositionals(positionals.slice(0, leadingWords.length), leadingWords);
342
+
343
+ const projectKey = positionals[0]!;
344
+ const columnName = positionals[1]!;
345
+ const direction = positionals[2]!;
315
346
  let orderedColumn: ReturnType<typeof column.order>;
316
347
 
317
348
  switch (direction) {
318
349
  case "before":
319
350
  case "after": {
320
- if (targetColumnName == null) {
321
- quit(`Target column must be specified for "${direction}"`);
322
- }
323
-
324
- if (extraArgs.length > 0) {
325
- quit("Only one target column can be specified");
326
- }
351
+ validatePositionals(positionals, [...leadingWords, "<target-column-name>"]);
327
352
 
328
353
  orderedColumn = column.order(
329
- { projectKey, columnName, direction, targetColumnName },
354
+ { projectKey, columnName, direction, targetColumnName: positionals[3]! },
330
355
  currentActor(),
331
356
  );
332
357
  break;
@@ -335,15 +360,13 @@ Example: zinn project column edit MDR "In Progress" --name "Refining"`,
335
360
  case "previous":
336
361
  case "next":
337
362
  case "last": {
338
- if (targetColumnName != null) {
339
- quit(`Order direction "${direction}" does not accept a target column`);
340
- }
363
+ validatePositionals(positionals, leadingWords);
341
364
 
342
365
  orderedColumn = column.order({ projectKey, columnName, direction }, currentActor());
343
366
  break;
344
367
  }
345
368
  default:
346
- quit(`Unknown order direction "${direction}"`);
369
+ throw new UsageError(`Unknown order direction "${direction}"`);
347
370
  }
348
371
 
349
372
  // TODO: maybe also print the new full column state?
@@ -0,0 +1,27 @@
1
+ import type { Command } from "../types";
2
+
3
+ import { parseArgs } from "node:util";
4
+ import { reindex } from "@zinn-dev/core";
5
+
6
+ import { reportLockWait } from "../database";
7
+ import { output, validatePositionals } from "../lib";
8
+
9
+ export const reindexCommand = {
10
+ run: (args) => {
11
+ const { positionals } = parseArgs({ args, strict: true, allowPositionals: true });
12
+ validatePositionals(positionals, []);
13
+
14
+ const result = reindex.run({ onWait: reportLockWait });
15
+
16
+ output(result, (r) => {
17
+ const noun = r.taskCount === 1 ? "task" : "tasks";
18
+ return `Rebuilt the search index from ${r.taskCount} ${noun}`;
19
+ });
20
+ },
21
+ help: `Usage: zinn reindex
22
+
23
+ Rebuild the search index that \`zinn task search\` uses from the tasks and their comments, archived tasks included.
24
+
25
+ Only the index changes, completely or not at all, so no backup is saved.
26
+ Fails, leaving the database as it is, when there is no database yet or when this Zinn cannot change it, such as a database with a newer schema version.`,
27
+ } satisfies Command;
@@ -2,14 +2,16 @@ import type { TaskRelationType, TaskWithKey } from "@zinn-dev/core";
2
2
  import type { RouteDef } from "../types";
3
3
 
4
4
  import { parseArgs } from "node:util";
5
- import { relation, relationCreateSchema, task } from "@zinn-dev/core";
6
- import { output, quit, validatePositionalCount, validateUniqueOptions } from "../lib";
5
+ import { column, relation, relationCreateSchema, task } from "@zinn-dev/core";
6
+ import { output, quit, validatePositionals, validateUniqueOptions } from "../lib";
7
7
  import { currentActor } from "../actor";
8
+ import { formatCellSeparator, formatRows } from "../presentation/row-layout";
9
+ import { columnNameCell } from "../presentation/column-presentation";
8
10
 
9
11
  type PresentedRelation = {
10
12
  type: TaskRelationType;
11
13
  direction: "outgoing" | "incoming" | null;
12
- task: { key: string; title: string; status: "Active" | "Archived" };
14
+ task: { key: string; column: string; title: string; status: "Active" | "Archived" };
13
15
  };
14
16
 
15
17
  export function presentRelations(taskMatch: TaskWithKey): Array<PresentedRelation> {
@@ -30,6 +32,7 @@ export function presentRelations(taskMatch: TaskWithKey): Array<PresentedRelatio
30
32
  direction,
31
33
  task: {
32
34
  key: other.key,
35
+ column: column.getById(other.column_id)!.name,
33
36
  title: other.title,
34
37
  status: other.archived_at == null ? "Active" : "Archived",
35
38
  },
@@ -38,8 +41,8 @@ export function presentRelations(taskMatch: TaskWithKey): Array<PresentedRelatio
38
41
  }
39
42
 
40
43
  export function formatRelations(relations: Array<PresentedRelation>) {
41
- return relations
42
- .map((entry) => {
44
+ return formatRows(
45
+ relations.map((entry) => {
43
46
  const isOutgoing = entry.direction === "outgoing";
44
47
 
45
48
  let label: string;
@@ -62,10 +65,15 @@ export function formatRelations(relations: Array<PresentedRelation>) {
62
65
  }
63
66
  }
64
67
 
65
- const archived = entry.task.status === "Archived" ? " | Archived" : "";
66
- return `${label} | ${entry.task.key} | ${entry.task.title}${archived}`;
67
- })
68
- .join("\n");
68
+ const archived = entry.task.status === "Archived" ? `${formatCellSeparator()}Archived` : "";
69
+ return [
70
+ { text: label },
71
+ { text: entry.task.key },
72
+ columnNameCell(entry.task.column),
73
+ { text: `${entry.task.title}${archived}` },
74
+ ];
75
+ }),
76
+ );
69
77
  }
70
78
 
71
79
  type PresentedRelationChange = { type: TaskRelationType; source: string; target: string };
@@ -79,9 +87,8 @@ function parseRelationArgs(args: string[]) {
79
87
  tokens: true,
80
88
  });
81
89
 
82
- validatePositionalCount(positionals, 2, "Exactly two task keys are required: source, target");
83
-
84
90
  validateUniqueOptions(tokens);
91
+ validatePositionals(positionals, ["<source-task-key>", "<target-task-key>"]);
85
92
 
86
93
  const typeResult = relationCreateSchema.shape.relation_type.safeParse(values.type);
87
94
 
@@ -143,12 +150,12 @@ Example: zinn task relation create APP-1 APP-2 --type dependency`,
143
150
  list: {
144
151
  run: (args) => {
145
152
  const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
146
- validatePositionalCount(positionals, 1, "Provide exactly one task key");
153
+ validatePositionals(positionals, ["<task-key>"]);
147
154
  output(presentRelations(task.getByKey(positionals[0]!)), formatRelations);
148
155
  },
149
156
  help: `Usage: zinn task relation list <task-key>
150
157
 
151
- Show incoming and outgoing relations with connected task keys and titles.
158
+ Show incoming and outgoing relations with connected task keys, columns and titles.
152
159
  Archived connected tasks are included and marked Archived.
153
160
  An empty list prints nothing.
154
161
 
@@ -0,0 +1,44 @@
1
+ import { expect, spyOn, test } from "bun:test";
2
+ import { backup, RestoreRefusedError, getStorage } from "@zinn-dev/core";
3
+
4
+ import { restoreCommand } from "./restore-router";
5
+
6
+ test("restore keeps the general hint for damaged search index internals and rethrows the error", () => {
7
+ const failure = Object.assign(new Error("vtable constructor failed: task_search"), {
8
+ code: "SQLITE_ERROR",
9
+ });
10
+ const restore = spyOn(backup, "restore").mockImplementation(() => {
11
+ throw failure;
12
+ });
13
+ const stderr = spyOn(console, "error").mockImplementation(() => {});
14
+
15
+ try {
16
+ expect(() => restoreCommand.run(["backup.sqlite", "--yes"])).toThrow(failure);
17
+ expect(stderr.mock.calls).toEqual([
18
+ [
19
+ `The database is unchanged. Backups taken before each restore attempt are kept in ${getStorage().backupDirectory}.`,
20
+ ],
21
+ ]);
22
+ } finally {
23
+ restore.mockRestore();
24
+ stderr.mockRestore();
25
+ }
26
+ });
27
+
28
+ test("a refused damaged backup does not get the damaged live database hint", () => {
29
+ const failure = new RestoreRefusedError("The backup is damaged, so nothing was restored", {
30
+ cause: Object.assign(new Error("database disk image is malformed"), { code: "SQLITE_CORRUPT" }),
31
+ });
32
+ const restore = spyOn(backup, "restore").mockImplementation(() => {
33
+ throw failure;
34
+ });
35
+ const stderr = spyOn(console, "error").mockImplementation(() => {});
36
+
37
+ try {
38
+ expect(() => restoreCommand.run(["backup.sqlite", "--yes"])).toThrow(failure);
39
+ expect(stderr.mock.calls).toEqual([]);
40
+ } finally {
41
+ restore.mockRestore();
42
+ stderr.mockRestore();
43
+ }
44
+ });
@@ -0,0 +1,90 @@
1
+ import type { Command } from "../types";
2
+
3
+ import { parseArgs } from "node:util";
4
+ import { resolve } from "node:path";
5
+ import { backup, RestoreRefusedError, getStorage } from "@zinn-dev/core";
6
+
7
+ import { reportLockWait } from "../database";
8
+ import { askConfirmation, output, validatePositionals, validateUniqueOptions } from "../lib";
9
+ import packageJson from "../../package.json";
10
+
11
+ const build = { client: "cli", version: packageJson.version };
12
+
13
+ export const restoreCommand = {
14
+ run: (args) => {
15
+ const { positionals, values, tokens } = parseArgs({
16
+ args,
17
+ strict: true,
18
+ allowPositionals: true,
19
+ tokens: true,
20
+ options: { yes: { type: "boolean" } },
21
+ });
22
+ validateUniqueOptions(tokens);
23
+ validatePositionals(positionals, ["<path>"]);
24
+
25
+ const path = resolve(positionals[0]!);
26
+ const { databasePath, backupDirectory } = getStorage();
27
+ const isPreconfirmed = values.yes === true;
28
+
29
+ // A backup that would be refused is refused before the prompt.
30
+ if (!isPreconfirmed) {
31
+ backup.check({ ...build, path });
32
+ }
33
+
34
+ const isConfirmed = askConfirmation(
35
+ `Replace the database at ${databasePath} with the backup ${path}? Its current board is saved to ${backupDirectory} first.`,
36
+ isPreconfirmed,
37
+ );
38
+
39
+ if (!isConfirmed) {
40
+ output(null, () => `Restore cancelled. The database at ${databasePath} is unchanged`);
41
+ return;
42
+ }
43
+
44
+ try {
45
+ const result = backup.restore({ ...build, path, onWait: reportLockWait });
46
+
47
+ output(result, (r) => {
48
+ const restored = `Restored the board from ${path} at schema version ${r.restoredVersion}.`;
49
+ return r.backupPath == null
50
+ ? `${restored} There was no board to save`
51
+ : `${restored} The board it replaced was saved to ${r.backupPath}`;
52
+ });
53
+ } catch (error) {
54
+ // A refusal attempted nothing, so only a failed restore points at the backups.
55
+ if (!(error instanceof RestoreRefusedError)) {
56
+ const isDamagedDatabase =
57
+ error instanceof Error &&
58
+ "code" in error &&
59
+ typeof error.code === "string" &&
60
+ error.code.startsWith("SQLITE_CORRUPT");
61
+
62
+ if (isDamagedDatabase) {
63
+ console.error(
64
+ `The database at ${databasePath} is damaged. Nothing was changed. To restore it:\n` +
65
+ `1. Close every program that has the database open.\n` +
66
+ `2. Move ${databasePath}, ${databasePath}-wal and ${databasePath}-shm out of the data folder, keeping any that exist together. Keep these files; do not delete them.\n` +
67
+ `3. Run the same zinn restore command again to create the database from the backup.`,
68
+ );
69
+ } else {
70
+ console.error(
71
+ `The database is unchanged. Backups taken before each restore attempt are kept in ${backupDirectory}.`,
72
+ );
73
+ }
74
+ }
75
+
76
+ throw error;
77
+ }
78
+ },
79
+ help: `Usage: zinn restore <path> [--yes]
80
+
81
+ Replace the board with the one in a backup file, such as one saved by \`zinn backup\` or by an upgrade, after confirmation.
82
+
83
+ The current board is saved first, in the same place as \`zinn backup\`, and the restore is applied completely or not at all.
84
+ A backup with an older schema version is restored at that version. Zinn then upgrades it like any older database: by itself, except for ~/.zinn run from a source checkout, which needs \`zinn migrate\`.
85
+ Restoring onto a missing database creates it.
86
+ Fails, leaving the database as it is, when the backup has a newer schema version than this Zinn or none at all, is damaged, or is not a Zinn database.
87
+ Use --yes to skip the confirmation prompt, for example in scripts or with --json.
88
+
89
+ Example: zinn restore ~/.zinn/backups/2026-10-06T12-30-05Z-cli-0.40.0-1a2b3c4d.sqlite`,
90
+ } satisfies Command;