@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.
@@ -2,15 +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
8
  import { formatCellSeparator, formatRows } from "../presentation/row-layout";
9
+ import { columnNameCell } from "../presentation/column-presentation";
9
10
 
10
11
  type PresentedRelation = {
11
12
  type: TaskRelationType;
12
13
  direction: "outgoing" | "incoming" | null;
13
- task: { key: string; title: string; status: "Active" | "Archived" };
14
+ task: { key: string; column: string; title: string; status: "Active" | "Archived" };
14
15
  };
15
16
 
16
17
  export function presentRelations(taskMatch: TaskWithKey): Array<PresentedRelation> {
@@ -31,6 +32,7 @@ export function presentRelations(taskMatch: TaskWithKey): Array<PresentedRelatio
31
32
  direction,
32
33
  task: {
33
34
  key: other.key,
35
+ column: column.getById(other.column_id)!.name,
34
36
  title: other.title,
35
37
  status: other.archived_at == null ? "Active" : "Archived",
36
38
  },
@@ -67,6 +69,7 @@ export function formatRelations(relations: Array<PresentedRelation>) {
67
69
  return [
68
70
  { text: label },
69
71
  { text: entry.task.key },
72
+ columnNameCell(entry.task.column),
70
73
  { text: `${entry.task.title}${archived}` },
71
74
  ];
72
75
  }),
@@ -84,9 +87,8 @@ function parseRelationArgs(args: string[]) {
84
87
  tokens: true,
85
88
  });
86
89
 
87
- validatePositionalCount(positionals, 2, "Exactly two task keys are required: source, target");
88
-
89
90
  validateUniqueOptions(tokens);
91
+ validatePositionals(positionals, ["<source-task-key>", "<target-task-key>"]);
90
92
 
91
93
  const typeResult = relationCreateSchema.shape.relation_type.safeParse(values.type);
92
94
 
@@ -148,12 +150,12 @@ Example: zinn task relation create APP-1 APP-2 --type dependency`,
148
150
  list: {
149
151
  run: (args) => {
150
152
  const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
151
- validatePositionalCount(positionals, 1, "Provide exactly one task key");
153
+ validatePositionals(positionals, ["<task-key>"]);
152
154
  output(presentRelations(task.getByKey(positionals[0]!)), formatRelations);
153
155
  },
154
156
  help: `Usage: zinn task relation list <task-key>
155
157
 
156
- Show incoming and outgoing relations with connected task keys and titles.
158
+ Show incoming and outgoing relations with connected task keys, columns and titles.
157
159
  Archived connected tasks are included and marked Archived.
158
160
  An empty list prints nothing.
159
161
 
@@ -5,7 +5,7 @@ import { resolve } from "node:path";
5
5
  import { backup, RestoreRefusedError, getStorage } from "@zinn-dev/core";
6
6
 
7
7
  import { reportLockWait } from "../database";
8
- import { askConfirmation, output, validatePositionalCount, validateUniqueOptions } from "../lib";
8
+ import { askConfirmation, output, validatePositionals, validateUniqueOptions } from "../lib";
9
9
  import packageJson from "../../package.json";
10
10
 
11
11
  const build = { client: "cli", version: packageJson.version };
@@ -20,7 +20,7 @@ export const restoreCommand = {
20
20
  options: { yes: { type: "boolean" } },
21
21
  });
22
22
  validateUniqueOptions(tokens);
23
- validatePositionalCount(positionals, 1, "Specify the backup file to restore");
23
+ validatePositionals(positionals, ["<path>"]);
24
24
 
25
25
  const path = resolve(positionals[0]!);
26
26
  const { databasePath, backupDirectory } = getStorage();
@@ -95,6 +95,24 @@ test("a help request never runs a command even when its help is empty", () => {
95
95
  }
96
96
  });
97
97
 
98
+ test("a help flag anywhere before -- prints help for the words before it and runs nothing", () => {
99
+ const run = mock(() => {});
100
+ const info = spyOn(console, "info").mockImplementation(() => {});
101
+ const router = createRouter({ foo: { bar: { run, help: "bar help" } } });
102
+
103
+ try {
104
+ router.route(["foo", "bar", "--help", "--name", "x"]);
105
+ router.route(["foo", "bar", "x", "-h"]);
106
+ expect(run).not.toHaveBeenCalled();
107
+ expect(info.mock.calls).toEqual([["bar help"], ["bar help"]]);
108
+
109
+ router.route(["foo", "--help", "bar"]);
110
+ expect(info.mock.calls.at(-1)![0]).toContain("Usage: zinn foo <command>");
111
+ } finally {
112
+ info.mockRestore();
113
+ }
114
+ });
115
+
98
116
  test("--allow-legacy-read before a -- is taken out of the arguments and allows legacy reads", () => {
99
117
  const run = mock(() => {});
100
118
  const router = createRouter({ foo: { run, help: "" } });
@@ -1,5 +1,7 @@
1
1
  import type { Command, ParsedRoute, RouteDef } from "../types";
2
2
 
3
+ import { parseArgs } from "node:util";
4
+
3
5
  import {
4
6
  failureMessage,
5
7
  isAllowLegacyReadFlag,
@@ -8,12 +10,35 @@ import {
8
10
  quit,
9
11
  setLegacyReadAllowed,
10
12
  setOutputMode,
13
+ UsageError,
14
+ validateUniqueOptions,
11
15
  } from "../lib";
12
16
 
13
17
  function getIsRunnable(obj: any): obj is Command {
14
18
  return Object.hasOwn(obj, "run");
15
19
  }
16
20
 
21
+ function isRouterFlag(arg: string) {
22
+ return isJsonFlag(arg) || isAllowLegacyReadFlag(arg);
23
+ }
24
+
25
+ // --json and --allow-legacy-read can each be given once, like a command's own flags.
26
+ function validateRouterFlags(routableArgs: Array<string>) {
27
+ const { tokens } = parseArgs({
28
+ args: routableArgs.filter(isRouterFlag),
29
+ options: { json: { type: "boolean" }, "allow-legacy-read": { type: "boolean" } },
30
+ strict: true,
31
+ tokens: true,
32
+ });
33
+
34
+ validateUniqueOptions(tokens);
35
+ }
36
+
37
+ /** The usage lines that open a command's help, up to its first blank line. */
38
+ function getUsage(help: string) {
39
+ return help.split("\n\n")[0]!;
40
+ }
41
+
17
42
  function toCommand(args: Array<string>) {
18
43
  return args.join(" ");
19
44
  }
@@ -47,6 +72,28 @@ function formatCommands(parsedRoutes: Array<ParsedRoute>, prefix: string) {
47
72
  .join("\n");
48
73
  }
49
74
 
75
+ function getRootHelp(parsedRoutes: Array<ParsedRoute>) {
76
+ // TODO: maybe "brand" text that is exported and used here for title and desc
77
+ return `ZINN - A kanban workflow in the terminal
78
+
79
+ Usage: zinn <command>
80
+
81
+ Options:
82
+ -h, --help Show help
83
+ -v, --version Show version
84
+ --json Print command output as JSON
85
+ --allow-legacy-read Read a database without a schema version, best effort and read-only
86
+
87
+ Commands:
88
+ ${formatCommands(parsedRoutes, "")}
89
+
90
+ Run zinn <namespace> --help or zinn <command> --help for more information.
91
+ --help shows help for the command words before it and runs nothing. The rest of the line is ignored.
92
+ -- ends the options: everything after it is considered a plain word, even if it starts with a dash (e.g. 'zinn project column create SHOP -- -later').
93
+ Flags after it are not read.
94
+ Running zinn without a command shows this help.`;
95
+ }
96
+
50
97
  function getNamespaceHelp(parsedRoutes: Array<ParsedRoute>, namespace: string) {
51
98
  const commands = formatCommands(parsedRoutes, `${namespace} `);
52
99
 
@@ -57,6 +104,48 @@ function getNamespaceHelp(parsedRoutes: Array<ParsedRoute>, namespace: string) {
57
104
  return `Usage: zinn ${namespace} <command>\n\nCommands:\n${commands}`;
58
105
  }
59
106
 
107
+ // The longest leading run of words that names a namespace, or the root namespace "" when none does.
108
+ function findNearestNamespace(parsedRoutes: Array<ParsedRoute>, words: Array<string>) {
109
+ for (let endIndex = words.length; endIndex > 0; endIndex--) {
110
+ const namespace = toCommand(words.slice(0, endIndex));
111
+ const help = getNamespaceHelp(parsedRoutes, namespace);
112
+
113
+ if (help != null) {
114
+ return { namespace, wordCount: endIndex, help };
115
+ }
116
+ }
117
+
118
+ return { namespace: "", wordCount: 0, help: getRootHelp(parsedRoutes) };
119
+ }
120
+
121
+ // Prints help for a namespace when asked, or exits with an error for a missing or unknown command in it.
122
+ function routeToNamespace(
123
+ parsedRoutes: Array<ParsedRoute>,
124
+ words: Array<string>,
125
+ isHelpRequest: boolean,
126
+ ) {
127
+ const { namespace, wordCount, help } = findNearestNamespace(parsedRoutes, words);
128
+ const unknownWord = words[wordCount];
129
+ const commandName = namespace === "" ? "zinn" : `zinn ${namespace}`;
130
+
131
+ if (unknownWord == null && isHelpRequest) {
132
+ console.info(help);
133
+ return;
134
+ }
135
+
136
+ if (unknownWord == null) {
137
+ quit(`Missing a command for "${commandName}"`, help);
138
+ }
139
+
140
+ const reason = `Unrecognized command "${unknownWord}" for "${commandName}"`;
141
+
142
+ if (isHelpRequest) {
143
+ quit(reason, help);
144
+ }
145
+
146
+ quit(`${reason}. Run \`${commandName} --help\` for a list of available commands`);
147
+ }
148
+
60
149
  export function parseRoutes(routesDef: RouteDef, prefix?: string) {
61
150
  const routeDefinitions: Array<ParsedRoute> = [];
62
151
  if (process.env.DEBUG) {
@@ -84,9 +173,7 @@ function route(parsedRoutes: Array<ParsedRoute>, rawArgs: Array<string>) {
84
173
  const separatorIndex = rawArgs.indexOf("--");
85
174
  const routableArgs = separatorIndex === -1 ? rawArgs : rawArgs.slice(0, separatorIndex);
86
175
  const passthroughArgs = separatorIndex === -1 ? [] : rawArgs.slice(separatorIndex);
87
- const filteredRoutableArgs = routableArgs.filter(
88
- (arg) => !isJsonFlag(arg) && !isAllowLegacyReadFlag(arg),
89
- );
176
+ const filteredRoutableArgs = routableArgs.filter((arg) => !isRouterFlag(arg));
90
177
 
91
178
  if (routableArgs.some(isJsonFlag)) {
92
179
  setOutputMode("json");
@@ -96,17 +183,12 @@ function route(parsedRoutes: Array<ParsedRoute>, rawArgs: Array<string>) {
96
183
  setLegacyReadAllowed(true);
97
184
  }
98
185
 
99
- const args = [...filteredRoutableArgs, ...passthroughArgs];
100
- const isHelpRequest = isHelpFlag(filteredRoutableArgs.at(-1) ?? "");
101
-
102
- if (isHelpRequest && args.length > 1) {
103
- const namespace = toCommand(filteredRoutableArgs.slice(0, -1));
104
- const namespaceHelp = getNamespaceHelp(parsedRoutes, namespace);
105
- if (namespaceHelp != null) {
106
- console.info(namespaceHelp);
107
- return;
108
- }
109
- }
186
+ // A help flag asks for help with the command words before it, so nothing after it is read.
187
+ const helpFlagIndex = filteredRoutableArgs.findIndex(isHelpFlag);
188
+ const isHelpRequest = helpFlagIndex !== -1;
189
+ const args = isHelpRequest
190
+ ? filteredRoutableArgs.slice(0, helpFlagIndex)
191
+ : [...filteredRoutableArgs, ...passthroughArgs];
110
192
 
111
193
  let match: ParsedRoute | null = null;
112
194
  let nestingLevel = 0;
@@ -127,22 +209,26 @@ function route(parsedRoutes: Array<ParsedRoute>, rawArgs: Array<string>) {
127
209
  }
128
210
 
129
211
  if (match == null) {
130
- quit(
131
- `Unrecognized command "${toCommand(args)}". Please run \`zinn --help\` for a list of available commands`,
132
- );
212
+ routeToNamespace(parsedRoutes, args, isHelpRequest);
213
+ return;
133
214
  }
134
215
 
135
- const commandArgs = args.slice(nestingLevel);
136
- const isCommandHelpRequest = commandArgs.length === 1 && isHelpFlag(commandArgs[0]!);
137
-
138
- if (isCommandHelpRequest) {
216
+ if (isHelpRequest) {
139
217
  console.info(match.help);
140
218
  return;
141
219
  }
142
220
 
221
+ validateRouterFlags(routableArgs);
222
+
223
+ const commandArgs = args.slice(nestingLevel);
224
+
143
225
  try {
144
226
  match.run(commandArgs);
145
227
  } catch (err: any) {
228
+ if (err instanceof UsageError) {
229
+ quit(err.message, getUsage(match.help));
230
+ }
231
+
146
232
  quit(
147
233
  failureMessage(
148
234
  err,
@@ -157,6 +243,6 @@ export function createRouter(routesDef: RouteDef) {
157
243
 
158
244
  return {
159
245
  route: (args: Array<string>) => route(parsedRoutes, args),
160
- commands: formatCommands(parsedRoutes, ""),
246
+ help: getRootHelp(parsedRoutes),
161
247
  };
162
248
  }
@@ -5,12 +5,14 @@ import { backupCommand } from "./backup-router";
5
5
  import { restoreCommand } from "./restore-router";
6
6
  import { migrateCommand } from "./migrate-router";
7
7
  import { reindexCommand } from "./reindex-router";
8
+ import { activityRouter } from "./activity-router";
8
9
 
9
10
  // TODO: lazy load?
10
11
  export const routes = {
11
12
  project: projectRouter,
12
13
  task: taskRouter,
13
14
  label: labelRouter,
15
+ activity: activityRouter,
14
16
  backup: backupCommand,
15
17
  restore: restoreCommand,
16
18
  migrate: migrateCommand,