@zinn-dev/cli 0.37.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lib.test.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import type { OpenPolicy } from "@zinn-dev/core";
2
2
 
3
3
  import { expect, test } from "bun:test";
4
- import { ReadOnlyDatabaseError, UnmarkedDatabaseError } from "@zinn-dev/core";
4
+ import { ReadOnlyDatabaseError, TextEditMatchError, UnmarkedDatabaseError } from "@zinn-dev/core";
5
5
 
6
- import { failureMessage } from "./lib";
6
+ import { failureMessage, UsageError, validatePositionals } from "./lib";
7
7
 
8
8
  const FALLBACK = "Something went wrong";
9
9
  const POLICY: OpenPolicy = {
@@ -58,3 +58,29 @@ test("an unmarked database opened for reading refuses changes without pointing a
58
58
 
59
59
  expect(failureMessage(error, FALLBACK)).toBe(error.message);
60
60
  });
61
+
62
+ test("a text edit that matches several places points at --all, and one that matches none does not", () => {
63
+ const several = new TextEditMatchError(3, "ZINN-1's description");
64
+ const none = new TextEditMatchError(0, "ZINN-1's description");
65
+
66
+ expect(failureMessage(several, FALLBACK)).toBe(
67
+ `${several.message} Use --all to replace every match.`,
68
+ );
69
+ expect(failureMessage(none, FALLBACK)).toBe(none.message);
70
+ });
71
+
72
+ test("validatePositionals names the first missing word, or the first word past the most it takes", () => {
73
+ const words = ["<project-key>", "<column-name>"];
74
+
75
+ expect(() => validatePositionals(["SHOP", "Later"], words)).not.toThrow();
76
+ expect(() => validatePositionals(["SHOP"], words)).toThrow(UsageError);
77
+ expect(() => validatePositionals(["SHOP"], words)).toThrow("<column-name>");
78
+ expect(() => validatePositionals([], words)).toThrow("<project-key>");
79
+ expect(() => validatePositionals(["SHOP", "Needs", "Review", "Now"], words)).toThrow('"Review"');
80
+
81
+ // ? Written as in the usage lines: [...] marks an optional word and a trailing ... a word that repeats.
82
+ expect(() => validatePositionals([], ["[<project-key>]"])).not.toThrow();
83
+ expect(() => validatePositionals(["SHOP", "extra"], ["[<project-key>]"])).toThrow('"extra"');
84
+ expect(() => validatePositionals(["A-1", "A-2", "A-3"], ["<task-key>..."])).not.toThrow();
85
+ expect(() => validatePositionals(["A-1"], ["<task-key>...", "<target-column>"])).toThrow("<target-column>");
86
+ });
package/src/lib.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import type { parseArgs } from "node:util";
2
2
 
3
- import { assertWritable, ReadOnlyDatabaseError, UnmarkedDatabaseError } from "@zinn-dev/core";
3
+ import {
4
+ assertWritable,
5
+ ReadOnlyDatabaseError,
6
+ TextEditMatchError,
7
+ UnmarkedDatabaseError,
8
+ } from "@zinn-dev/core";
4
9
 
5
10
  type ParsedTokens = NonNullable<ReturnType<typeof parseArgs>["tokens"]>;
6
11
  type OutputMode = "text" | "json";
@@ -42,26 +47,40 @@ export function output<T>(data: T, transformToString: (data: T) => string) {
42
47
  }
43
48
 
44
49
  /** Asks before a change that cannot be undone, unless --yes already confirmed it. */
45
- export function confirmAction(message: string, isPreconfirmed: boolean) {
50
+ export function confirmAction(message: string, isPreconfirmed: boolean, jsonRefusal?: string) {
46
51
  // Throws on a read-only database, to avoid asking for confirmation to an already refused action
47
52
  assertWritable();
48
53
 
49
- return askConfirmation(message, isPreconfirmed);
54
+ return askConfirmation(message, isPreconfirmed, jsonRefusal);
50
55
  }
51
56
 
52
57
  /** Like confirmAction, without opening the database, for commands that bypass the open policy. */
53
- export function askConfirmation(message: string, isPreconfirmed: boolean) {
58
+ export function askConfirmation(
59
+ message: string,
60
+ isPreconfirmed: boolean,
61
+ jsonRefusal = "Commands that ask for confirmation need --yes when used with --json",
62
+ ) {
54
63
  if (isPreconfirmed) {
55
64
  return true;
56
65
  }
57
66
 
58
67
  if (outputMode === "json") {
59
- quit("Commands that ask for confirmation need --yes when used with --json");
68
+ quit(jsonRefusal);
69
+ }
70
+
71
+ // Refuses rather than treating an unanswered prompt as declined, so scripts do not see a false success
72
+ if (!canPrompt()) {
73
+ quit("Commands that ask for confirmation need --yes when not running in a terminal");
60
74
  }
61
75
 
62
76
  return confirm(message);
63
77
  }
64
78
 
79
+ /** Whether someone can answer a prompt: stdin and stdout are both terminals, like how gh decides it. */
80
+ export function canPrompt() {
81
+ return process.stdin.isTTY === true && process.stdout.isTTY === true;
82
+ }
83
+
65
84
  /** The message to report for a failed command, or fallback when the error has none. */
66
85
  export function failureMessage(error: any, fallback: string) {
67
86
  const isOlderReadOnly = error instanceof ReadOnlyDatabaseError && error.reason === "older";
@@ -73,6 +92,10 @@ export function failureMessage(error: any, fallback: string) {
73
92
  return `${error.message}. Add --allow-legacy-read to read it anyway.`;
74
93
  }
75
94
 
95
+ if (error instanceof TextEditMatchError && error.matchCount > 1) {
96
+ return `${error.message} Use --all to replace every match.`;
97
+ }
98
+
76
99
  if (error?.message === "no such table: task_search") {
77
100
  return `${error.message}. Run \`zinn reindex\` to rebuild the search index.`;
78
101
  }
@@ -80,23 +103,37 @@ export function failureMessage(error: any, fallback: string) {
80
103
  return error?.message ?? fallback;
81
104
  }
82
105
 
83
- export function quit(reason: string): never {
106
+ /** Prints the reason as an error, followed by help when given, and exits with code 1. */
107
+ export function quit(reason: string, help?: string): never {
84
108
  if (outputMode === "json") {
85
- console.error(JSON.stringify({ error: { message: reason } }, null, 2));
109
+ const error = help == null ? { message: reason } : { message: reason, help };
110
+ console.error(JSON.stringify({ error }, null, 2));
86
111
  } else {
87
- console.error(reason);
112
+ console.error(help == null ? reason : `${reason}\n\n${help}`);
88
113
  }
89
114
 
90
115
  process.exit(1);
91
116
  }
92
117
 
93
- export function validatePositionalCount(
94
- positionals: Array<string>,
95
- expected: number,
96
- message: string,
97
- ) {
98
- if (positionals.length !== expected) {
99
- quit(message);
118
+ /** A command was given the wrong words. The router prints the message with the command's usage lines. */
119
+ export class UsageError extends Error {}
120
+
121
+ /**
122
+ * Checks a command's words against its usage line, with the words written the same way:
123
+ * `<task-key>` is required, `[<project-key>]` is optional and `<task-key>...` repeats.
124
+ * Optional words go last.
125
+ */
126
+ export function validatePositionals(positionals: Array<string>, words: Array<string>) {
127
+ const requiredWords = words.filter((word) => !word.startsWith("["));
128
+ const missingWord = requiredWords[positionals.length];
129
+ if (missingWord !== undefined) {
130
+ throw new UsageError(`Missing argument ${missingWord}`);
131
+ }
132
+
133
+ const hasRepeatingWord = words.some((word) => word.endsWith("..."));
134
+ const extraWord = positionals[words.length];
135
+ if (!hasRepeatingWord && extraWord !== undefined) {
136
+ throw new UsageError(`Unexpected argument "${extraWord}"`);
100
137
  }
101
138
  }
102
139
 
@@ -0,0 +1,112 @@
1
+ import type { Activity } from "@zinn-dev/core";
2
+
3
+ import { expect, test } from "bun:test";
4
+ import { abbreviateActivityIds, formatActivityList } from "./activity-presentation";
5
+
6
+ test("activity abbreviations are shortest unique canonical prefixes across all supplied IDs", () => {
7
+ const first = "019abcdf-1234-7000-8000-123456abcde1";
8
+ const second = "019abcdf-1234-7000-8000-123456abcde2";
9
+ const earlier = "019abcdf-0234-7000-8000-123456abcde1";
10
+ const separate = "019abcda-1234-7000-8000-123456abcde1";
11
+ const prefixes = abbreviateActivityIds([second, separate, first, earlier]);
12
+ expect(prefixes.get(first)).toBe(first);
13
+ expect(prefixes.get(second)).toBe(second);
14
+ expect(prefixes.get(earlier)).toBe("019abcdf-0");
15
+ expect(prefixes.get(separate)).toBe("019abcda");
16
+ expect(abbreviateActivityIds([first]).get(first)).toBe("019abcdf");
17
+ });
18
+
19
+ test("activity text keeps full task identities when a long reused key needs disambiguation", () => {
20
+ const event: Activity = {
21
+ id: "019abcdf-1234-7000-8000-123456abcde1", created_at: 1,
22
+ actor_name: "Test", actor_email: null, actor_kind: "human",
23
+ entity_type: "task", entity_id: "019abcdf-1234-7000-8000-123456abcde2",
24
+ action: "archive", changes: null,
25
+ };
26
+ const text = formatActivityList([{ event, displayId: "019abcdf", removedTasks: [],
27
+ navigation: { name: `${"A".repeat(100)}-1`, status: "deleted", distinguishesTaskId: true } }]);
28
+ expect(text).toContain(event.entity_id);
29
+ expect(text).toContain("deleted");
30
+ expect(text).toContain("archive");
31
+ });
32
+
33
+ test("activity details keep explicit empty containers distinct from null changes", () => {
34
+ const event: Activity = {
35
+ id: "019abcdf-1234-7000-8000-123456abcde1", created_at: 1,
36
+ actor_name: "Test", actor_email: null, actor_kind: "human",
37
+ entity_type: "task", entity_id: "019abcdf-1234-7000-8000-123456abcde2",
38
+ action: "create", changes: { labels: [], column: {} },
39
+ };
40
+ const entry = { event, displayId: event.id, removedTasks: [],
41
+ navigation: { name: "APP-1", status: "current" as const } };
42
+ const text = formatActivityList([entry], { showsDetails: true });
43
+ expect(text).toContain("labels:\n[]");
44
+ expect(text).toContain("column:\n{}");
45
+ expect(formatActivityList([{ ...entry, event: { ...event, changes: null } }], { showsDetails: true }))
46
+ .toContain("Changes:\nnull");
47
+ });
48
+
49
+ test("task rows for a shared key mark only deleted tasks and keep every task ID", () => {
50
+ const event: Activity = {
51
+ id: "019abcdf-1234-7000-8000-123456abcde1", created_at: 1,
52
+ actor_name: "Test", actor_email: null, actor_kind: "human",
53
+ entity_type: "task", entity_id: "current-task", action: "edit", changes: null,
54
+ };
55
+ const identities = [
56
+ { id: "current-task", status: "current" as const },
57
+ { id: "archived-task", status: "archived" as const },
58
+ { id: "first-deleted-task", status: "deleted" as const },
59
+ { id: "second-deleted-task", status: "deleted" as const },
60
+ ];
61
+ for (const identity of identities) {
62
+ const entry = {
63
+ event: { ...event, entity_id: identity.id }, displayId: event.id, removedTasks: [],
64
+ navigation: { name: "APP-1", status: identity.status, distinguishesTaskId: true },
65
+ };
66
+ const text = formatActivityList([entry]);
67
+ expect(text.split("\n")[0]!.split(" · ")[0]!.includes("deleted")).toBe(identity.status === "deleted");
68
+ expect(text).toContain(identity.id);
69
+ }
70
+ });
71
+
72
+ test("project deletion keeps its project and removed-task identities visible", () => {
73
+ const event: Activity = {
74
+ id: "019abcdf-1234-7000-8000-123456abcde1", created_at: 1,
75
+ actor_name: "Test", actor_email: null, actor_kind: "human",
76
+ entity_type: "project", entity_id: "old-project", action: "delete",
77
+ changes: { key: "APP", tasks: [{ id: "old-task", key: "APP-1", title: "Old task" }] },
78
+ };
79
+ const text = formatActivityList([{
80
+ event, displayId: event.id,
81
+ navigation: { name: "APP", status: "deleted" },
82
+ removedTasks: [{ id: "old-task", key: "APP-1", title: "Old task", status: "deleted" }],
83
+ }]);
84
+ expect(text.split("\n")[0]!.split(" · ")[0]).toContain("deleted");
85
+ expect(text).toContain("APP-1");
86
+ expect(text).toContain("old-task");
87
+ });
88
+
89
+ test("long entity identities do not pad neighboring activity descriptions", () => {
90
+ const event: Activity = {
91
+ id: "019abcdf-1234-7000-8000-123456abcde1", created_at: 1,
92
+ actor_name: "Test", actor_email: null, actor_kind: "human",
93
+ entity_type: "task", entity_id: "task-id", action: "archive", changes: null,
94
+ };
95
+ const short = { event, displayId: "019abcdf", removedTasks: [],
96
+ navigation: { name: "APP-1", status: "archived" as const } };
97
+ const longKey = "PB137E58A84AC41B5A704693239312DF2";
98
+ const outlier = { ...short, displayId: "019abcda",
99
+ event: { ...event, id: "019abcda-1234-7000-8000-123456abcde1", entity_type: "project" as const,
100
+ action: "delete" as const, changes: { key: longKey, name: "Active ordering tail" } },
101
+ navigation: { name: longKey, status: "deleted" as const } };
102
+ const alone = formatActivityList([short]);
103
+ const together = formatActivityList([short, outlier]);
104
+ expect(together.split("\n")[0]).toBe(alone);
105
+ expect(alone).toContain("APP-1 · archived");
106
+ expect(alone).not.toContain("[archived]");
107
+ expect(together).toContain(`Full project key: ${longKey}`);
108
+ const contentColumn = alone.indexOf("APP-1");
109
+ expect(together.split("\n").find((line) => line.includes("Full project key:"))!.indexOf("Full project key:"))
110
+ .toBe(contentColumn);
111
+ expect(together.split("\n")[1]).not.toContain(longKey);
112
+ });