@flowscripter/flowscripter-io-cli 2.0.11 → 3.0.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.
Files changed (49) hide show
  1. package/README.md +70 -34
  2. package/bun.lock +59 -58
  3. package/functional_tests/features/commands.feature +76 -7
  4. package/functional_tests/features/steps/executable.py +6 -0
  5. package/functional_tests/features/steps/io_commands.py +5 -0
  6. package/package.json +12 -11
  7. package/src/cli.ts +19 -9
  8. package/src/commands/copy.ts +6 -62
  9. package/src/commands/delete.ts +28 -29
  10. package/src/commands/get-properties.ts +30 -34
  11. package/src/commands/hash.ts +102 -68
  12. package/src/commands/list.ts +76 -57
  13. package/src/commands/move.ts +6 -62
  14. package/src/commands/set-properties.ts +92 -37
  15. package/src/commands/transferCommand.ts +121 -0
  16. package/src/util/interruptSignals.ts +70 -0
  17. package/src/util/location/createLocationOption.ts +59 -0
  18. package/src/util/location/describeTarget.ts +6 -0
  19. package/src/util/location/targetKey.ts +9 -0
  20. package/src/util/location/toStructuredLocation.ts +8 -0
  21. package/src/util/payloadKindOption.ts +20 -0
  22. package/src/{pluginsDir.ts → util/pluginsDir.ts} +1 -1
  23. package/src/util/providerRegistry.ts +23 -0
  24. package/src/util/requireOperation.ts +19 -0
  25. package/src/util/zodToComplexOption.ts +93 -0
  26. package/tests/commands/copy.test.ts +80 -0
  27. package/tests/commands/delete.test.ts +44 -0
  28. package/tests/commands/get-properties.test.ts +52 -0
  29. package/tests/commands/hash.test.ts +76 -0
  30. package/tests/commands/list.test.ts +78 -0
  31. package/tests/commands/move.test.ts +45 -0
  32. package/tests/commands/set-properties.test.ts +68 -0
  33. package/tests/commands/transferCommand.test.ts +63 -0
  34. package/tests/fixtures/pluginStore.ts +39 -0
  35. package/tests/{testContext.ts → fixtures/testContext.ts} +17 -1
  36. package/tests/{byteScale_test.ts → util/byteScale.test.ts} +1 -1
  37. package/tests/util/interruptSignals.test.ts +80 -0
  38. package/tests/util/location/createLocationOption.test.ts +73 -0
  39. package/tests/util/location/describeTarget.test.ts +12 -0
  40. package/tests/util/location/targetKey.test.ts +15 -0
  41. package/tests/util/location/toStructuredLocation.test.ts +14 -0
  42. package/tests/util/payloadKindOption.test.ts +19 -0
  43. package/tests/util/providerRegistry.test.ts +39 -0
  44. package/tests/util/requireOperation.test.ts +25 -0
  45. package/tests/util/zodToComplexOption.test.ts +116 -0
  46. package/src/filesystemProvider.ts +0 -40
  47. package/tests/commands_test.ts +0 -186
  48. /package/src/{byteScale.ts → util/byteScale.ts} +0 -0
  49. /package/tests/{cli_test.ts → cli.test.ts} +0 -0
@@ -0,0 +1,44 @@
1
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { Icon } from "@flowscripter/dynamic-cli-framework";
6
+ import type { ProviderRegistry } from "@flowscripter/pluggable-io-framework";
7
+ import { fileLocation, installFilesystemPlugin } from "../fixtures/pluginStore.ts";
8
+ import { createStubContext } from "../fixtures/testContext.ts";
9
+ import { createDeleteCommand } from "../../src/commands/delete.ts";
10
+
11
+ let registry: ProviderRegistry;
12
+ let cleanup: () => Promise<void>;
13
+ let root: string;
14
+
15
+ beforeAll(async () => {
16
+ ({ registry, cleanup } = await installFilesystemPlugin());
17
+ });
18
+
19
+ afterAll(async () => {
20
+ await cleanup();
21
+ });
22
+
23
+ beforeEach(async () => {
24
+ root = await mkdtemp(join(tmpdir(), "flowscripter-io-cli-test-"));
25
+ });
26
+
27
+ afterEach(async () => {
28
+ await rm(root, { recursive: true, force: true });
29
+ });
30
+
31
+ describe("delete", () => {
32
+ test("removes a file, with a spinner", async () => {
33
+ await writeFile(join(root, "a.txt"), "hello");
34
+ const { context, icons, spinnerMessages } = createStubContext();
35
+
36
+ await createDeleteCommand(registry).execute(context, {
37
+ location: fileLocation(root, { filename: "a.txt" }),
38
+ });
39
+
40
+ await expect(stat(join(root, "a.txt"))).rejects.toThrow();
41
+ expect(spinnerMessages).toEqual([`Deleting ${join(root, "a.txt")}...`]);
42
+ expect(icons).toEqual([Icon.SUCCESS]);
43
+ });
44
+ });
@@ -0,0 +1,52 @@
1
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { ProviderRegistry } from "@flowscripter/pluggable-io-framework";
6
+ import { fileLocation, installFilesystemPlugin } from "../fixtures/pluginStore.ts";
7
+ import { createStubContext } from "../fixtures/testContext.ts";
8
+ import { createGetPropertiesCommand } from "../../src/commands/get-properties.ts";
9
+
10
+ let registry: ProviderRegistry;
11
+ let cleanup: () => Promise<void>;
12
+ let root: string;
13
+
14
+ beforeAll(async () => {
15
+ ({ registry, cleanup } = await installFilesystemPlugin());
16
+ });
17
+
18
+ afterAll(async () => {
19
+ await cleanup();
20
+ });
21
+
22
+ beforeEach(async () => {
23
+ root = await mkdtemp(join(tmpdir(), "flowscripter-io-cli-test-"));
24
+ });
25
+
26
+ afterEach(async () => {
27
+ await rm(root, { recursive: true, force: true });
28
+ });
29
+
30
+ describe("get-properties", () => {
31
+ test("prints properties as pretty-printed JSON", async () => {
32
+ await writeFile(join(root, "a.txt"), "hello");
33
+ const { lines, context } = createStubContext();
34
+
35
+ await createGetPropertiesCommand(registry).execute(context, {
36
+ location: fileLocation(root, { filename: "a.txt" }),
37
+ });
38
+
39
+ expect(JSON.parse(lines[0]!).size).toBe(5);
40
+ expect(lines[0]).toContain("\n");
41
+ });
42
+
43
+ test("rejects a pattern location", async () => {
44
+ const { context } = createStubContext();
45
+
46
+ await expect(
47
+ createGetPropertiesCommand(registry).execute(context, {
48
+ location: fileLocation(root, { pattern: "*" }),
49
+ }),
50
+ ).rejects.toThrow("get-properties does not accept a pattern location");
51
+ });
52
+ });
@@ -0,0 +1,76 @@
1
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { ProviderRegistry } from "@flowscripter/pluggable-io-framework";
6
+ import { fileLocation, installFilesystemPlugin } from "../fixtures/pluginStore.ts";
7
+ import { createStubContext } from "../fixtures/testContext.ts";
8
+ import { createHashCommand } from "../../src/commands/hash.ts";
9
+
10
+ let registry: ProviderRegistry;
11
+ let cleanup: () => Promise<void>;
12
+ let root: string;
13
+
14
+ beforeAll(async () => {
15
+ ({ registry, cleanup } = await installFilesystemPlugin());
16
+ });
17
+
18
+ afterAll(async () => {
19
+ await cleanup();
20
+ });
21
+
22
+ beforeEach(async () => {
23
+ root = await mkdtemp(join(tmpdir(), "flowscripter-io-cli-test-"));
24
+ });
25
+
26
+ afterEach(async () => {
27
+ await rm(root, { recursive: true, force: true });
28
+ });
29
+
30
+ describe("hash", () => {
31
+ test("algorithm option has a curated set of allowable values", () => {
32
+ const algorithmOption = createHashCommand(registry).options.find(
33
+ (option) => option.name === "algorithm",
34
+ ) as { allowableValues?: readonly unknown[] } | undefined;
35
+ expect(algorithmOption?.allowableValues).toEqual(["sha1", "sha256", "sha384", "sha512", "md5"]);
36
+ });
37
+
38
+ test("hashes a file with the default algorithm using the native hasher", async () => {
39
+ await writeFile(join(root, "a.txt"), "hello");
40
+ const { lines, context, progressUpdates } = createStubContext();
41
+
42
+ await createHashCommand(registry).execute(context, {
43
+ location: fileLocation(root, { filename: "a.txt" }),
44
+ algorithm: "sha256",
45
+ });
46
+
47
+ const expected = new Bun.CryptoHasher("sha256").update("hello").digest("hex");
48
+ expect(lines[0]).toBe(`${expected} ${join(root, "a.txt")}\n`);
49
+ expect(progressUpdates.at(-1)).toBe(5);
50
+ });
51
+
52
+ test("hashes a file with a non-sha256 algorithm via the Bun.CryptoHasher fallback", async () => {
53
+ await writeFile(join(root, "a.txt"), "hello");
54
+ const { lines, context } = createStubContext();
55
+
56
+ await createHashCommand(registry).execute(context, {
57
+ location: fileLocation(root, { filename: "a.txt" }),
58
+ algorithm: "sha1",
59
+ "payload-kind": "js",
60
+ });
61
+
62
+ const expected = new Bun.CryptoHasher("sha1").update("hello").digest("hex");
63
+ expect(lines[0]).toBe(`${expected} ${join(root, "a.txt")}\n`);
64
+ });
65
+
66
+ test("rejects a location that is not a single entry", async () => {
67
+ const { context } = createStubContext();
68
+
69
+ await expect(
70
+ createHashCommand(registry).execute(context, {
71
+ location: fileLocation(root),
72
+ algorithm: "sha256",
73
+ }),
74
+ ).rejects.toThrow("hash needs a single entry location");
75
+ });
76
+ });
@@ -0,0 +1,78 @@
1
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { ProviderRegistry } from "@flowscripter/pluggable-io-framework";
6
+ import { fileLocation, installFilesystemPlugin } from "../fixtures/pluginStore.ts";
7
+ import { createStubContext } from "../fixtures/testContext.ts";
8
+ import { createListCommand } from "../../src/commands/list.ts";
9
+
10
+ let registry: ProviderRegistry;
11
+ let cleanup: () => Promise<void>;
12
+ let root: string;
13
+
14
+ beforeAll(async () => {
15
+ ({ registry, cleanup } = await installFilesystemPlugin());
16
+ });
17
+
18
+ afterAll(async () => {
19
+ await cleanup();
20
+ });
21
+
22
+ beforeEach(async () => {
23
+ root = await mkdtemp(join(tmpdir(), "flowscripter-io-cli-test-"));
24
+ });
25
+
26
+ afterEach(async () => {
27
+ await rm(root, { recursive: true, force: true });
28
+ });
29
+
30
+ describe("list", () => {
31
+ test("prints one JSON line per item in a folder", async () => {
32
+ await writeFile(join(root, "a.txt"), "hello");
33
+ const { lines, context } = createStubContext();
34
+
35
+ await createListCommand(registry).execute(context, { location: fileLocation(root) });
36
+
37
+ expect(lines.length).toBe(1);
38
+ expect(JSON.parse(lines[0]!).path).toBe("a.txt");
39
+ });
40
+
41
+ test("filters by a pattern location or by --regex", async () => {
42
+ await writeFile(join(root, "a.txt"), "hello");
43
+ await writeFile(join(root, "b.log"), "hello");
44
+ const pattern = createStubContext();
45
+ const regex = createStubContext();
46
+
47
+ await createListCommand(registry).execute(pattern.context, {
48
+ location: fileLocation(root, { pattern: "*.txt" }),
49
+ });
50
+ await createListCommand(registry).execute(regex.context, {
51
+ location: fileLocation(root),
52
+ regex: "\\.log$",
53
+ });
54
+
55
+ expect(pattern.lines.map((line) => JSON.parse(line).path)).toEqual(["a.txt"]);
56
+ expect(regex.lines.map((line) => JSON.parse(line).path)).toEqual(["b.log"]);
57
+ });
58
+
59
+ test("rejects an entry location and a pattern combined with --regex", async () => {
60
+ const { context } = createStubContext();
61
+ const list = createListCommand(registry);
62
+
63
+ await expect(
64
+ list.execute(context, { location: fileLocation(root, { filename: "a.txt" }) }),
65
+ ).rejects.toThrow("list needs a folder or pattern location");
66
+ await expect(
67
+ list.execute(context, { location: fileLocation(root, { pattern: "*" }), regex: "a" }),
68
+ ).rejects.toThrow("either a pattern location or --regex");
69
+ });
70
+
71
+ test("declares the location option for the installed protocols", () => {
72
+ const list = createListCommand(registry);
73
+ const location = list.options.find((option) => option.name === "location") as unknown as {
74
+ properties: { name: string; allowableValues?: readonly unknown[] }[];
75
+ };
76
+ expect(location.properties[0]?.allowableValues).toEqual(["file"]);
77
+ });
78
+ });
@@ -0,0 +1,45 @@
1
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { Icon } from "@flowscripter/dynamic-cli-framework";
6
+ import type { ProviderRegistry } from "@flowscripter/pluggable-io-framework";
7
+ import { fileLocation, installFilesystemPlugin } from "../fixtures/pluginStore.ts";
8
+ import { createStubContext } from "../fixtures/testContext.ts";
9
+ import { createMoveCommand } from "../../src/commands/move.ts";
10
+
11
+ let registry: ProviderRegistry;
12
+ let cleanup: () => Promise<void>;
13
+ let root: string;
14
+
15
+ beforeAll(async () => {
16
+ ({ registry, cleanup } = await installFilesystemPlugin());
17
+ });
18
+
19
+ afterAll(async () => {
20
+ await cleanup();
21
+ });
22
+
23
+ beforeEach(async () => {
24
+ root = await mkdtemp(join(tmpdir(), "flowscripter-io-cli-test-"));
25
+ });
26
+
27
+ afterEach(async () => {
28
+ await rm(root, { recursive: true, force: true });
29
+ });
30
+
31
+ describe("move", () => {
32
+ test("moves a file", async () => {
33
+ await writeFile(join(root, "a.txt"), "hello");
34
+ const { context, icons } = createStubContext();
35
+
36
+ await createMoveCommand(registry).execute(context, {
37
+ source: fileLocation(root, { filename: "a.txt" }),
38
+ dest: fileLocation(root, { filename: "b.txt" }),
39
+ });
40
+
41
+ expect(await readFile(join(root, "b.txt"), "utf8")).toBe("hello");
42
+ await expect(stat(join(root, "a.txt"))).rejects.toThrow();
43
+ expect(icons).toEqual([Icon.SUCCESS, undefined]);
44
+ });
45
+ });
@@ -0,0 +1,68 @@
1
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { Icon } from "@flowscripter/dynamic-cli-framework";
6
+ import type { ProviderRegistry } from "@flowscripter/pluggable-io-framework";
7
+ import { fileLocation, installFilesystemPlugin } from "../fixtures/pluginStore.ts";
8
+ import { createStubContext } from "../fixtures/testContext.ts";
9
+ import { createSetPropertiesCommand } from "../../src/commands/set-properties.ts";
10
+
11
+ let registry: ProviderRegistry;
12
+ let cleanup: () => Promise<void>;
13
+ let root: string;
14
+
15
+ beforeAll(async () => {
16
+ ({ registry, cleanup } = await installFilesystemPlugin());
17
+ });
18
+
19
+ afterAll(async () => {
20
+ await cleanup();
21
+ });
22
+
23
+ beforeEach(async () => {
24
+ root = await mkdtemp(join(tmpdir(), "flowscripter-io-cli-test-"));
25
+ });
26
+
27
+ afterEach(async () => {
28
+ await rm(root, { recursive: true, force: true });
29
+ });
30
+
31
+ describe("set-properties", () => {
32
+ test("applies the protocol's properties and last-modified, with a spinner", async () => {
33
+ await writeFile(join(root, "a.txt"), "hello");
34
+ const { context, icons, spinnerMessages } = createStubContext();
35
+
36
+ await createSetPropertiesCommand(registry).execute(context, {
37
+ location: fileLocation(root, { filename: "a.txt" }),
38
+ "last-modified": "2020-01-02T03:04:05.000Z",
39
+ properties: { file: { mode: 0o600 } },
40
+ });
41
+
42
+ const stats = await stat(join(root, "a.txt"));
43
+ if (process.platform !== "win32") {
44
+ expect(stats.mode & 0o777).toBe(0o600);
45
+ }
46
+ expect(stats.mtime.toISOString()).toBe("2020-01-02T03:04:05.000Z");
47
+ expect(spinnerMessages).toEqual([`Setting properties for ${join(root, "a.txt")}...`]);
48
+ expect(icons).toEqual([Icon.SUCCESS]);
49
+ });
50
+
51
+ test("declares one --properties group per protocol with settable properties", () => {
52
+ const command = createSetPropertiesCommand(registry);
53
+ const properties = command.options.find(
54
+ (option) => option.name === "properties",
55
+ ) as unknown as {
56
+ properties: { name: string; properties: { name: string }[] }[];
57
+ };
58
+ expect(properties.properties.map((group) => group.name)).toEqual(["file"]);
59
+ expect(properties.properties[0]?.properties.map((property) => property.name)).toEqual(["mode"]);
60
+ });
61
+
62
+ test("validates --last-modified", () => {
63
+ const command = createSetPropertiesCommand(registry);
64
+ const lastModified = command.options.find((option) => option.name === "last-modified");
65
+ expect(lastModified?.validate?.("not a date")).toBe("must be an ISO 8601 date");
66
+ expect(lastModified?.validate?.("2020-01-02")).toBeUndefined();
67
+ });
68
+ });
@@ -0,0 +1,63 @@
1
+ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
2
+ import { mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { Icon, PRINTER_SERVICE_ID, type PrinterService } from "@flowscripter/dynamic-cli-framework";
6
+ import type { ProviderRegistry } from "@flowscripter/pluggable-io-framework";
7
+ import { fileLocation, installFilesystemPlugin } from "../fixtures/pluginStore.ts";
8
+ import { createStubContext } from "../fixtures/testContext.ts";
9
+ import { createTransferCommand } from "../../src/commands/transferCommand.ts";
10
+
11
+ let registry: ProviderRegistry;
12
+ let cleanup: () => Promise<void>;
13
+ let root: string;
14
+
15
+ beforeAll(async () => {
16
+ ({ registry, cleanup } = await installFilesystemPlugin());
17
+ });
18
+
19
+ afterAll(async () => {
20
+ await cleanup();
21
+ });
22
+
23
+ beforeEach(async () => {
24
+ root = await mkdtemp(join(tmpdir(), "flowscripter-io-cli-test-"));
25
+ });
26
+
27
+ afterEach(async () => {
28
+ await rm(root, { recursive: true, force: true });
29
+ });
30
+
31
+ describe("createTransferCommand", () => {
32
+ test("declares source, dest and payload-kind options", () => {
33
+ const command = createTransferCommand(registry, "move");
34
+ expect(command.name).toBe("move");
35
+ expect(command.description).toStartWith("Move a file");
36
+ expect(command.options.map((option) => option.name)).toEqual([
37
+ "source",
38
+ "dest",
39
+ "payload-kind",
40
+ ]);
41
+ });
42
+
43
+ test("reports a transfer stopped by the first Ctrl-C", async () => {
44
+ await writeFile(join(root, "a.txt"), "hello");
45
+ await mkdir(join(root, "out"));
46
+ const { context, lines, icons } = createStubContext();
47
+ const printerService = context.getServiceById(PRINTER_SERVICE_ID) as PrinterService;
48
+ printerService.showSpinner = async () => {
49
+ process.emit("SIGINT");
50
+ };
51
+
52
+ await createTransferCommand(registry, "copy").execute(context, {
53
+ source: fileLocation(root, { pattern: "*.txt" }),
54
+ dest: fileLocation(join(root, "out")),
55
+ });
56
+
57
+ expect(lines[0]).toBe(
58
+ `Copy of *.txt in ${root} to ${join(root, "out")} stopped after 0 bytes\n`,
59
+ );
60
+ expect(icons[0]).toBe(Icon.ALERT);
61
+ await expect(stat(join(root, "out", "a.txt"))).rejects.toThrow();
62
+ });
63
+ });
@@ -0,0 +1,39 @@
1
+ import { mkdir, mkdtemp, rm, symlink } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import type { Values } from "@flowscripter/dynamic-cli-framework";
5
+ import type { ProviderRegistry } from "@flowscripter/pluggable-io-framework";
6
+ import { createProviderRegistry } from "../../src/util/providerRegistry.ts";
7
+
8
+ /**
9
+ * Simulates `flowscripter-io-cli plugin:add @flowscripter/io-plugin-filesystem`
10
+ * by symlinking the published package (a devDependency purely for tests)
11
+ * into a temp plugin store, then discovers it through the CLI's registry.
12
+ * Returns a cleanup function.
13
+ */
14
+ export async function installFilesystemPlugin(): Promise<{
15
+ registry: ProviderRegistry;
16
+ cleanup: () => Promise<void>;
17
+ }> {
18
+ const pluginsPath = await mkdtemp(join(tmpdir(), "flowscripter-io-cli-plugins-test-"));
19
+ await mkdir(join(pluginsPath, "@flowscripter"), { recursive: true });
20
+ await symlink(
21
+ resolve(import.meta.dir, "..", "..", "node_modules", "@flowscripter", "io-plugin-filesystem"),
22
+ join(pluginsPath, "@flowscripter", "io-plugin-filesystem"),
23
+ "junction",
24
+ );
25
+ process.env.FLOWSCRIPTER_IO_CLI_PLUGINS_PATH = pluginsPath;
26
+ const registry = await createProviderRegistry();
27
+ return {
28
+ registry,
29
+ cleanup: async () => {
30
+ delete process.env.FLOWSCRIPTER_IO_CLI_PLUGINS_PATH;
31
+ await rm(pluginsPath, { recursive: true, force: true });
32
+ },
33
+ };
34
+ }
35
+
36
+ /** A `file` location argument value. */
37
+ export function fileLocation(path: string, fields: Values = {}): Values {
38
+ return { protocol: "file", file: { path, ...fields } };
39
+ }
@@ -3,10 +3,12 @@ import {
3
3
  DefaultSyntaxHighlighterService,
4
4
  PRETTY_PRINTER_SERVICE_ID,
5
5
  PRINTER_SERVICE_ID,
6
+ SHUTDOWN_SERVICE_ID,
6
7
  SYNTAX_HIGHLIGHTER_SERVICE_ID,
7
8
  type Context,
8
9
  type Icon,
9
10
  type PrinterService,
11
+ type ShutdownService,
10
12
  } from "@flowscripter/dynamic-cli-framework";
11
13
 
12
14
  export interface StubPrinter {
@@ -14,6 +16,7 @@ export interface StubPrinter {
14
16
  icons: (Icon | undefined)[];
15
17
  spinnerMessages: string[];
16
18
  progressUpdates: number[];
19
+ longRunningModes: boolean[];
17
20
  context: Context;
18
21
  }
19
22
 
@@ -22,6 +25,8 @@ export interface StubPrinter {
22
25
  * commands actually call are implemented; everything else would throw if
23
26
  * invoked, which is intentional (a test relying on it should fail loudly).
24
27
  *
28
+ * The shutdown service stub only records long-running mode changes.
29
+ *
25
30
  * The pretty printer and syntax highlighter are the real default
26
31
  * implementations (colorEnabled = false, so highlight() is a no-op) so
27
32
  * `get-properties`/`list` output stays plain, JSON.parse-able text in tests.
@@ -31,6 +36,7 @@ export function createStubContext(): StubPrinter {
31
36
  const icons: (Icon | undefined)[] = [];
32
37
  const spinnerMessages: string[] = [];
33
38
  const progressUpdates: number[] = [];
39
+ const longRunningModes: boolean[] = [];
34
40
  const printerService = {
35
41
  print: async (message: string, icon?: Icon) => {
36
42
  lines.push(message);
@@ -47,6 +53,15 @@ export function createStubContext(): StubPrinter {
47
53
  hideSpinner: async () => {},
48
54
  } as unknown as PrinterService;
49
55
 
56
+ const shutdownService = {
57
+ enterLongRunningMode: () => {
58
+ longRunningModes.push(true);
59
+ },
60
+ leaveLongRunningMode: () => {
61
+ longRunningModes.push(false);
62
+ },
63
+ } as unknown as ShutdownService;
64
+
50
65
  const prettyPrinterService = new DefaultPrettyPrinterService();
51
66
  const syntaxHighlighterService = new DefaultSyntaxHighlighterService();
52
67
  syntaxHighlighterService.colorEnabled = false;
@@ -55,6 +70,7 @@ export function createStubContext(): StubPrinter {
55
70
  [PRINTER_SERVICE_ID]: printerService,
56
71
  [PRETTY_PRINTER_SERVICE_ID]: prettyPrinterService,
57
72
  [SYNTAX_HIGHLIGHTER_SERVICE_ID]: syntaxHighlighterService,
73
+ [SHUTDOWN_SERVICE_ID]: shutdownService,
58
74
  };
59
75
 
60
76
  const context: Context = {
@@ -63,5 +79,5 @@ export function createStubContext(): StubPrinter {
63
79
  doesServiceExist: (id: string) => id in services,
64
80
  };
65
81
 
66
- return { lines, icons, spinnerMessages, progressUpdates, context };
82
+ return { lines, icons, spinnerMessages, progressUpdates, longRunningModes, context };
67
83
  }
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { createByteScale, pickByteUnit } from "../src/byteScale.ts";
2
+ import { createByteScale, pickByteUnit } from "../../src/util/byteScale.ts";
3
3
 
4
4
  describe("pickByteUnit", () => {
5
5
  test("scales to the largest unit that keeps the total at 1 or more", () => {
@@ -0,0 +1,80 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { ShutdownService } from "@flowscripter/dynamic-cli-framework";
3
+ import {
4
+ createInterruptSignals,
5
+ iterateUntilInterrupted,
6
+ } from "../../src/util/interruptSignals.ts";
7
+
8
+ function makeShutdownService(modes: boolean[]): ShutdownService {
9
+ return {
10
+ enterLongRunningMode: () => modes.push(true),
11
+ leaveLongRunningMode: () => modes.push(false),
12
+ } as unknown as ShutdownService;
13
+ }
14
+
15
+ describe("createInterruptSignals", () => {
16
+ test("the first Ctrl-C aborts stop and the second aborts signal", () => {
17
+ const modes: boolean[] = [];
18
+ const signals = createInterruptSignals(makeShutdownService(modes));
19
+
20
+ process.emit("SIGINT");
21
+ expect(signals.stop.aborted).toBe(true);
22
+ expect(signals.signal.aborted).toBe(false);
23
+ process.emit("SIGINT");
24
+ expect(signals.signal.aborted).toBe(true);
25
+
26
+ signals[Symbol.dispose]();
27
+ expect(modes).toEqual([true, false]);
28
+ });
29
+
30
+ test("stops listening once disposed", () => {
31
+ const signals = createInterruptSignals(makeShutdownService([]));
32
+ const listeners = process.listenerCount("SIGINT");
33
+
34
+ signals[Symbol.dispose]();
35
+
36
+ expect(process.listenerCount("SIGINT")).toBe(listeners - 1);
37
+ });
38
+ });
39
+
40
+ describe("iterateUntilInterrupted", () => {
41
+ async function* numbers(): AsyncGenerator<number> {
42
+ yield 1;
43
+ yield 2;
44
+ yield 3;
45
+ }
46
+
47
+ test("yields every item when not interrupted", async () => {
48
+ using signals = createInterruptSignals(makeShutdownService([]));
49
+ const items: number[] = [];
50
+
51
+ for await (const item of iterateUntilInterrupted(numbers(), signals)) items.push(item);
52
+
53
+ expect(items).toEqual([1, 2, 3]);
54
+ });
55
+
56
+ test("ends gracefully once stop is aborted", async () => {
57
+ using signals = createInterruptSignals(makeShutdownService([]));
58
+ const items: number[] = [];
59
+
60
+ for await (const item of iterateUntilInterrupted(numbers(), signals)) {
61
+ items.push(item);
62
+ process.emit("SIGINT");
63
+ }
64
+
65
+ expect(items).toEqual([1]);
66
+ });
67
+
68
+ test("rejects when signal is aborted while waiting for the next item", async () => {
69
+ using signals = createInterruptSignals(makeShutdownService([]));
70
+ const hanging: AsyncIterable<number> = {
71
+ [Symbol.asyncIterator]: () => ({ next: () => new Promise(() => {}) }),
72
+ };
73
+ const iterating = iterateUntilInterrupted(hanging, signals).next();
74
+
75
+ process.emit("SIGINT");
76
+ process.emit("SIGINT");
77
+
78
+ await expect(iterating).rejects.toBeDefined();
79
+ });
80
+ });