@skathi-native/cli 0.1.0-beta.2 → 0.1.0-beta.4

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 (50) hide show
  1. package/aot/host-globals.json +105 -0
  2. package/aot/native.ts +142 -0
  3. package/aot/pin.ts +67 -0
  4. package/aot/toolchain.lock.json +17 -0
  5. package/aot/transform.ts +69 -0
  6. package/check/codes.ts +19 -0
  7. package/check/command.ts +5 -3
  8. package/check/index.ts +44 -1
  9. package/cli/aot-build.ts +192 -0
  10. package/cli/build-app.ts +102 -31
  11. package/cli/config.ts +45 -102
  12. package/cli/create.ts +12 -54
  13. package/cli/dev.ts +109 -19
  14. package/cli/effects.ts +162 -0
  15. package/cli/elf.ts +3 -2
  16. package/cli/help.ts +56 -148
  17. package/cli/host-fetch.ts +116 -54
  18. package/cli/host.ts +59 -39
  19. package/cli/sk.ts +440 -246
  20. package/cli/skpk.ts +6 -0
  21. package/cli/stamp.ts +2 -2
  22. package/cli/term.ts +169 -38
  23. package/cli/workload-cache.ts +258 -0
  24. package/effects/compile.ts +952 -0
  25. package/effects/redslangc.json +23 -0
  26. package/effects/redslangc.ts +220 -0
  27. package/effects/sk.slang +558 -0
  28. package/package.json +6 -2
  29. package/templates/icon.png +0 -0
  30. package/templates/minimal/.vscode/settings.json +3 -0
  31. package/templates/minimal/src/App.vue +2 -2
  32. package/templates/showcase/.vscode/settings.json +3 -0
  33. package/templates/showcase/shaders/sheen.slang +23 -0
  34. package/templates/showcase/src/components/Titlebar.vue +7 -3
  35. package/templates/showcase/src/engine.ts +3 -26
  36. package/templates/showcase/src/pages/AudioPage.vue +6 -9
  37. package/templates/showcase/src/pages/FilesPage.vue +11 -15
  38. package/templates/showcase/src/pages/FormsPage.vue +2 -3
  39. package/templates/showcase/src/pages/GraphicsPage.vue +13 -15
  40. package/templates/showcase/src/pages/HomePage.vue +1 -2
  41. package/templates/showcase/src/pages/LocalePage.vue +2 -2
  42. package/templates/showcase/src/pages/MediaPage.vue +1 -1
  43. package/templates/showcase/src/pages/MotionPage.vue +1 -1
  44. package/templates/showcase/src/pages/NetworkPage.vue +6 -5
  45. package/templates/showcase/src/pages/PermissionsPage.vue +2 -2
  46. package/templates/showcase/src/pages/StoragePage.vue +23 -36
  47. package/templates/showcase/src/pages/StylesPage.vue +9 -1
  48. package/templates/showcase/src/pages/SystemPage.vue +3 -3
  49. package/templates/showcase/src/styles.css +2 -2
  50. package/templates/showcase/src/components/Missing.vue +0 -26
package/cli/skpk.ts CHANGED
@@ -25,6 +25,9 @@ export const KIND = {
25
25
  WINDOW: 2,
26
26
  SCRIPT: 3,
27
27
  BYTECODE: 4,
28
+ NATIVE_MANIFEST: 5,
29
+ NATIVE_IMAGE: 6,
30
+ EFFECT: 7,
28
31
  ASSET: 16,
29
32
  } as const;
30
33
 
@@ -33,6 +36,9 @@ export const NAMES = {
33
36
  WINDOW: "sk/window.json",
34
37
  SCRIPT: "sk/app.js",
35
38
  BYTECODE: "sk/app.bc",
39
+ NATIVE_MANIFEST: "sk/app.native.json",
40
+ NATIVE_IMAGE: "sk/app.image",
41
+ EFFECTS_DIR: "sk/effects/",
36
42
  } as const;
37
43
 
38
44
  export const FLAG_HAS_BYTECODE = 1;
package/cli/stamp.ts CHANGED
@@ -98,14 +98,14 @@ export function stamp(options: StampOptions): StampResult {
98
98
  const t0 = performance.now();
99
99
  const partial = `${options.out}.partial`;
100
100
  rmSync(partial, { force: true });
101
- retrying("copying the host", () => copyFileSync(options.host, partial), log);
101
+ retrying("copying the workload", () => copyFileSync(options.host, partial), log);
102
102
  const tCopy = performance.now();
103
103
 
104
104
  let strippedSignature = false;
105
105
  let result: StampResult | null = null;
106
106
  try {
107
107
  strippedSignature = stripSignature(partial);
108
- if (strippedSignature) log("removed the host's certificate table — sign the stamped exe instead");
108
+ if (strippedSignature) log("removed the workload's certificate table — sign the stamped exe instead");
109
109
 
110
110
  const before = readPe(partial);
111
111
  let skew = 0;
package/cli/term.ts CHANGED
@@ -40,39 +40,98 @@ export function paint(on: boolean): Paint {
40
40
 
41
41
  export const seconds = (ms: number) => (ms < 1000 ? `${Math.round(ms)}ms` : `${(ms / 1000).toFixed(1)}s`);
42
42
 
43
+ export const mib = (bytes: number) => `${(bytes / 2 ** 20).toFixed(1)} MiB`;
44
+
45
+ /** False on the legacy Windows console, whose fonts have no Braille or check marks. */
46
+ export function unicodeTerminal(env: NodeJS.ProcessEnv = process.env, platform: string = process.platform): boolean {
47
+ if (platform !== "win32") return env.TERM !== "linux";
48
+ return Boolean(
49
+ env.WT_SESSION ||
50
+ env.TERM_PROGRAM === "vscode" ||
51
+ env.TERMINAL_EMULATOR === "JetBrains-JediTerm" ||
52
+ env.ConEmuTask === "{cmd::Cmder}" ||
53
+ env.TERM === "xterm-256color" ||
54
+ env.TERM === "alacritty",
55
+ );
56
+ }
57
+
58
+ /** A terminal that can take a redrawn line: a TTY, not TERM=dumb, not a CI log that merely has a pty. */
59
+ export function interactive(stream: { isTTY?: boolean }, env: NodeJS.ProcessEnv = process.env): boolean {
60
+ const ci = env.CI !== undefined && env.CI !== "" && env.CI !== "0" && env.CI !== "false";
61
+ return stream.isTTY === true && env.TERM !== "dumb" && !ci;
62
+ }
63
+
64
+ export interface Glyphs {
65
+ ok: string;
66
+ fail: string;
67
+ frames: string[];
68
+ done: string;
69
+ todo: string;
70
+ more: string;
71
+ }
72
+
73
+ export function glyphs(unicode: boolean): Glyphs {
74
+ return unicode
75
+ ? {
76
+ ok: "✓",
77
+ fail: "✗",
78
+ frames: ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"],
79
+ done: "━",
80
+ todo: "─",
81
+ more: "…",
82
+ }
83
+ : { ok: "+", fail: "x", frames: ["-", "\\", "|", "/"], done: "#", todo: "-", more: "~" };
84
+ }
85
+
43
86
  export interface Progress {
44
87
  /** Starts a phase (ending the previous one); `total` shows a counter that `tick` advances. */
45
88
  step(label: string, total?: number): void;
46
- tick(): void;
89
+ tick(by?: number): void;
90
+ /** A download's position: a bar on a terminal. */
91
+ bytes(done: number, total: number): void;
47
92
  /** What the finished phase line says after its label. */
48
93
  detail(text: string): void;
49
94
  /** A line printed above the spinner. */
50
95
  info(text: string): void;
51
96
  warn(text: string): void;
97
+ /** Ends the current phase as failed, then everything. */
98
+ fail(): void;
52
99
  end(): void;
53
100
  }
54
101
 
55
- export const quietProgress: Progress = { step() {}, tick() {}, detail() {}, info() {}, warn() {}, end() {} };
102
+ export const quietProgress: Progress = {
103
+ step() {},
104
+ tick() {},
105
+ bytes() {},
106
+ detail() {},
107
+ info() {},
108
+ warn() {},
109
+ fail() {},
110
+ end() {},
111
+ };
56
112
 
57
113
  /** Progress as plain lines (CI logs, pipes): each finished phase is one line. */
58
- export function lineProgress(write: (line: string) => void, color: boolean): Progress {
114
+ export function lineProgress(write: (line: string) => void, color: boolean, unicode = true): Progress {
59
115
  const p = paint(color);
116
+ const g = glyphs(unicode);
60
117
  let label: string | null = null;
61
118
  let note = "";
62
119
  let began = 0;
63
- const finish = () => {
120
+ const finish = (ok: boolean) => {
64
121
  if (label === null) return;
65
- write(`${p.green("✓")} ${label}${note ? ` ${p.dim(note)}` : ""} ${p.dim(seconds(performance.now() - began))}`);
122
+ const mark = ok ? p.green(g.ok) : p.red(g.fail);
123
+ write(`${mark} ${label}${note ? ` ${p.dim(note)}` : ""} ${p.dim(seconds(performance.now() - began))}`);
66
124
  label = null;
67
125
  };
68
126
  return {
69
127
  step(next) {
70
- finish();
128
+ finish(true);
71
129
  label = next;
72
130
  note = "";
73
131
  began = performance.now();
74
132
  },
75
133
  tick() {},
134
+ bytes() {},
76
135
  detail(text) {
77
136
  note = text;
78
137
  },
@@ -82,13 +141,16 @@ export function lineProgress(write: (line: string) => void, color: boolean): Pro
82
141
  warn(text) {
83
142
  write(`${p.yellow("warning")}: ${text}`);
84
143
  },
85
- end: finish,
144
+ fail: () => finish(false),
145
+ end: () => finish(true),
86
146
  };
87
147
  }
88
148
 
89
- /** The spinner on a terminal, plain lines otherwise. */
149
+ /** The spinner on an interactive terminal, plain lines otherwise. */
90
150
  export function progressFor(stream: NodeJS.WriteStream, color = colorEnabled(stream)): Progress {
91
- return stream.isTTY ? spinner(stream, color) : lineProgress((line) => stream.write(`${line}\n`), color);
151
+ return interactive(stream)
152
+ ? spinner(stream, color)
153
+ : lineProgress((line) => stream.write(`${line}\n`), color, !stream.isTTY || unicodeTerminal());
92
154
  }
93
155
 
94
156
  /** A `log(line)` callback onto a progress: "warning: …" lines become warnings. */
@@ -100,56 +162,127 @@ export function logTo(progress: Progress): (line: string) => void {
100
162
  };
101
163
  }
102
164
 
103
- const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
165
+ const SIGNALS: [NodeJS.Signals, number][] = [
166
+ ["SIGINT", 130],
167
+ ["SIGTERM", 143],
168
+ ["SIGHUP", 129],
169
+ ...(process.platform === "win32" ? [["SIGBREAK", 149] as [NodeJS.Signals, number]] : []),
170
+ ];
104
171
 
105
- /** A one-line spinner on a terminal stream; phases leave a ✓ line with their time. */
106
- export function spinner(stream: NodeJS.WriteStream, color: boolean): Progress {
172
+ /**
173
+ * A one-line spinner on a terminal stream; phases leave a ✓ (or ✗) line with their time. The line is
174
+ * redrawn in one write and cut to the terminal's width; console output while it spins lands above it.
175
+ */
176
+ export function spinner(stream: NodeJS.WriteStream, color: boolean, unicode = unicodeTerminal()): Progress {
107
177
  const p = paint(color);
178
+ const g = glyphs(unicode);
108
179
  let label: string | null = null;
109
180
  let note = "";
110
181
  let total = 0;
111
182
  let done = 0;
112
- let frame = 0;
183
+ let download: { done: number; total: number } | null = null;
113
184
  let began = 0;
185
+ let shown = false;
114
186
  let drawn = 0;
115
- const clear = () => stream.write("\r\x1b[2K");
187
+ let over = false;
188
+
189
+ const bar = (part: number, whole: number, width: number) => {
190
+ const filled = whole > 0 ? Math.min(width, Math.round((part / whole) * width)) : 0;
191
+ return p.cyan(g.done.repeat(filled)) + p.dim(g.todo.repeat(width - filled));
192
+ };
193
+ const line = () => {
194
+ const now = performance.now();
195
+ const frame = g.frames[Math.floor((now - began) / 80) % g.frames.length]!;
196
+ const time = seconds(now - began);
197
+ const counter = download
198
+ ? ` ${(download.done / 2 ** 20).toFixed(1)}/${(download.total / 2 ** 20).toFixed(1)} MiB`
199
+ : total
200
+ ? ` ${done}/${total}`
201
+ : "";
202
+ const width = Math.max(20, (stream.columns || 80) - 1);
203
+ const meter = download && width >= 60 ? 20 : 0;
204
+ const fixed = 2 + counter.length + 1 + time.length + (meter ? meter + 1 : 0);
205
+ const fit = (text: string, room: number) =>
206
+ text.length <= room ? text : text.slice(0, Math.max(0, room - g.more.length)) + g.more;
207
+ if (fixed + 1 + g.more.length > width) return `${p.cyan(frame)} ${fit(label ?? "", width - 2)}`;
208
+ const text = fit(label ?? "", width - fixed);
209
+ const drawnBar = meter && download ? ` ${bar(download.done, download.total, meter)}` : "";
210
+ return `${p.cyan(frame)} ${text}${drawnBar}${p.dim(counter)} ${p.dim(time)}`;
211
+ };
116
212
  const draw = () => {
117
- if (label === null) return;
213
+ if (label === null || over) return;
118
214
  drawn = performance.now();
119
- frame = (frame + 1) % FRAMES.length;
120
- const count = total ? ` ${done}/${total}` : "";
121
- clear();
122
- stream.write(`${p.cyan(FRAMES[frame]!)} ${label}${p.dim(count)} ${p.dim(seconds(drawn - began))}`);
215
+ stream.write(`\r${line()}\x1b[K`);
216
+ shown = true;
217
+ };
218
+ const clear = () => {
219
+ if (!shown) return;
220
+ stream.write("\r\x1b[K");
221
+ shown = false;
123
222
  };
124
- const finish = () => {
223
+ const finish = (ok: boolean) => {
125
224
  if (label === null) return;
126
225
  clear();
226
+ const mark = ok ? p.green(g.ok) : p.red(g.fail);
127
227
  const what = note ? ` ${p.dim(note)}` : "";
128
- stream.write(`${p.green("✓")} ${label}${what} ${p.dim(seconds(performance.now() - began))}\n`);
228
+ stream.write(`${mark} ${label}${what} ${p.dim(seconds(performance.now() - began))}\n`);
129
229
  label = null;
130
230
  };
131
- const restore = () => stream.write("\x1b[?25h");
132
- const interrupt = () => {
133
- clear();
134
- restore();
135
- process.exit(130);
136
- };
231
+
232
+ const consoleBefore = { log: console.log, info: console.info, warn: console.warn, error: console.error };
233
+ const above =
234
+ (original: ((...data: unknown[]) => void) | undefined) =>
235
+ (...data: unknown[]) => {
236
+ clear();
237
+ original?.(...data);
238
+ draw();
239
+ };
240
+ console.log = above(consoleBefore.log);
241
+ console.info = above(consoleBefore.info);
242
+ console.warn = above(consoleBefore.warn);
243
+ console.error = above(consoleBefore.error);
244
+ const showCursor = () => stream.write("\x1b[?25h");
245
+ const onSignal = SIGNALS.map(([signal, code]) => {
246
+ const handler = () => {
247
+ clear();
248
+ showCursor();
249
+ process.exit(code);
250
+ };
251
+ process.once(signal, handler);
252
+ return [signal, handler] as const;
253
+ });
137
254
  stream.write("\x1b[?25l");
138
- process.once("exit", restore);
139
- process.once("SIGINT", interrupt);
255
+ process.once("exit", showCursor);
140
256
  const timer = setInterval(draw, 80);
257
+ timer.unref();
258
+
259
+ const end = () => {
260
+ if (over) return;
261
+ finish(true);
262
+ over = true;
263
+ clearInterval(timer);
264
+ Object.assign(console, consoleBefore);
265
+ for (const [signal, handler] of onSignal) process.off(signal, handler);
266
+ showCursor();
267
+ process.off("exit", showCursor);
268
+ };
141
269
  return {
142
270
  step(next, count = 0) {
143
- finish();
271
+ finish(true);
144
272
  label = next;
145
273
  note = "";
146
274
  total = count;
147
275
  done = 0;
276
+ download = null;
148
277
  began = performance.now();
149
278
  draw();
150
279
  },
151
- tick() {
152
- done++;
280
+ tick(by = 1) {
281
+ done += by;
282
+ if (performance.now() - drawn > 50) draw();
283
+ },
284
+ bytes(at, of) {
285
+ download = { done: at, total: of };
153
286
  if (performance.now() - drawn > 50) draw();
154
287
  },
155
288
  detail(text) {
@@ -165,12 +298,10 @@ export function spinner(stream: NodeJS.WriteStream, color: boolean): Progress {
165
298
  stream.write(`${p.yellow("warning")}: ${text}\n`);
166
299
  draw();
167
300
  },
168
- end() {
169
- finish();
170
- clearInterval(timer);
171
- restore();
172
- process.off("exit", restore);
173
- process.off("SIGINT", interrupt);
301
+ fail() {
302
+ finish(false);
303
+ end();
174
304
  },
305
+ end,
175
306
  };
176
307
  }
@@ -0,0 +1,258 @@
1
+ // The per-user caches `sk workload list` shows and `sk prune` empties: the workloads and sk-aot of each
2
+ // Skathi version (<cache>/skathi/hosts/<version>/<variant>|aot), the effect shader compiler
3
+ // (<cache>/skathi/redslangc/<version>), the native images AOT apps expand at start (Windows), and caches
4
+ // older versions of sk left behind.
5
+
6
+ import { existsSync, lstatSync, readdirSync, rmdirSync, rmSync } from "node:fs";
7
+ import { dirname, join } from "node:path";
8
+ import { compilerCacheRoot, compilerExe, PIN } from "../effects/redslangc";
9
+ import { cacheRoot } from "./host";
10
+ import { currentPlatform, hostsFor, type Platform } from "./platform";
11
+ import { mib, paint } from "./term";
12
+
13
+ export type CacheKind = "workload" | "compiler" | "shader-compiler" | "native-images" | "legacy" | "other";
14
+
15
+ export interface CacheEntry {
16
+ kind: CacheKind;
17
+ path: string;
18
+ bytes: number;
19
+ version?: string;
20
+ variant?: string;
21
+ /** False when the executable is missing, e.g. after an interrupted download. */
22
+ complete?: boolean;
23
+ items?: number;
24
+ }
25
+
26
+ export interface CacheRoots {
27
+ workloads: string;
28
+ shaderCompilers: string;
29
+ nativeImages: string | null;
30
+ legacy: string[];
31
+ }
32
+
33
+ export function cacheRoots(platform: Platform = currentPlatform()): CacheRoots {
34
+ const workloads = cacheRoot(platform);
35
+ const skathi = dirname(workloads);
36
+ const native = process.env.SK_AOT_CACHE_DIR || (platform === "windows" ? join(skathi, "native-aot", "v1") : null);
37
+ return {
38
+ workloads,
39
+ shaderCompilers: compilerCacheRoot(platform),
40
+ nativeImages: native,
41
+ legacy: [join(skathi, "aot-toolchain")],
42
+ };
43
+ }
44
+
45
+ const names = (dir: string): string[] => {
46
+ try {
47
+ return readdirSync(dir);
48
+ } catch {
49
+ return [];
50
+ }
51
+ };
52
+
53
+ const isDir = (path: string) => {
54
+ try {
55
+ return lstatSync(path).isDirectory();
56
+ } catch {
57
+ return false;
58
+ }
59
+ };
60
+
61
+ export function sizeOf(path: string): number {
62
+ try {
63
+ const st = lstatSync(path);
64
+ if (!st.isDirectory()) return st.size;
65
+ } catch {
66
+ return 0;
67
+ }
68
+ return names(path).reduce((n, name) => n + sizeOf(join(path, name)), 0);
69
+ }
70
+
71
+ /** Newest first; a release before its prereleases. */
72
+ export function compareVersions(a: string, b: string): number {
73
+ const split = (v: string) => {
74
+ const at = v.indexOf("-");
75
+ return at < 0 ? { main: v, pre: null } : { main: v.slice(0, at), pre: v.slice(at + 1) };
76
+ };
77
+ const x = split(a);
78
+ const y = split(b);
79
+ const numeric = { numeric: true } as const;
80
+ if (x.main !== y.main) return y.main.localeCompare(x.main, "en", numeric);
81
+ if (x.pre === null || y.pre === null) return (x.pre === null ? -1 : 0) - (y.pre === null ? -1 : 0);
82
+ return y.pre.localeCompare(x.pre, "en", numeric);
83
+ }
84
+
85
+ export function inventory(roots: CacheRoots, platform: Platform = currentPlatform()): CacheEntry[] {
86
+ const exe = hostsFor(platform).cachedFile;
87
+ const compiler = `sk-aot${platform === "windows" ? ".exe" : ""}`;
88
+ const entries: CacheEntry[] = [];
89
+ const top = names(roots.workloads);
90
+ for (const version of top.filter((n) => isDir(join(roots.workloads, n))).sort(compareVersions)) {
91
+ const dir = join(roots.workloads, version);
92
+ for (const child of names(dir).sort((a, b) => Number(a === "aot") - Number(b === "aot") || a.localeCompare(b))) {
93
+ const path = join(dir, child);
94
+ const bytes = sizeOf(path);
95
+ if (!isDir(path)) entries.push({ kind: "other", path, bytes, version });
96
+ else if (child === "aot")
97
+ entries.push({ kind: "compiler", path, bytes, version, complete: existsSync(join(path, compiler)) });
98
+ else
99
+ entries.push({ kind: "workload", path, bytes, version, variant: child, complete: existsSync(join(path, exe)) });
100
+ }
101
+ }
102
+ for (const name of top.filter((n) => !isDir(join(roots.workloads, n))).sort()) {
103
+ const path = join(roots.workloads, name);
104
+ entries.push({ kind: "other", path, bytes: sizeOf(path) });
105
+ }
106
+ const redslangc = compilerExe(platform);
107
+ for (const version of names(roots.shaderCompilers).sort(compareVersions)) {
108
+ const path = join(roots.shaderCompilers, version);
109
+ const complete = isDir(path) && existsSync(join(path, redslangc));
110
+ entries.push({ kind: "shader-compiler", path, bytes: sizeOf(path), version, complete });
111
+ }
112
+ const images = roots.nativeImages ? names(roots.nativeImages) : [];
113
+ if (roots.nativeImages && images.length) {
114
+ entries.push({
115
+ kind: "native-images",
116
+ path: roots.nativeImages,
117
+ bytes: sizeOf(roots.nativeImages),
118
+ items: images.length,
119
+ });
120
+ }
121
+ for (const path of roots.legacy) if (existsSync(path)) entries.push({ kind: "legacy", path, bytes: sizeOf(path) });
122
+ return entries;
123
+ }
124
+
125
+ export interface KeepOptions {
126
+ /** The version this sk is. */
127
+ current: string;
128
+ keep?: string[];
129
+ all?: boolean;
130
+ }
131
+
132
+ /** Whether `entry` stays: a complete workload or compiler of the current version or a kept one, or the pinned redslangc. */
133
+ export function needed(entry: CacheEntry, options: KeepOptions): boolean {
134
+ if (options.all || entry.version === undefined || entry.complete === false) return false;
135
+ if (entry.kind === "shader-compiler") return entry.version === PIN.version;
136
+ if (entry.kind === "native-images" || entry.kind === "legacy") return false;
137
+ return entry.version === options.current || (options.keep ?? []).includes(entry.version);
138
+ }
139
+
140
+ export interface PruneResult {
141
+ removed: CacheEntry[];
142
+ failed: { entry: CacheEntry; error: string }[];
143
+ bytes: number;
144
+ }
145
+
146
+ /** Removes what is not {@link needed}; an image a running app holds open is skipped, not an error. */
147
+ export function prune(
148
+ entries: CacheEntry[],
149
+ options: KeepOptions & { dryRun?: boolean; roots?: CacheRoots },
150
+ ): PruneResult {
151
+ const result: PruneResult = { removed: [], failed: [], bytes: 0 };
152
+ for (const entry of entries) {
153
+ if (needed(entry, options)) continue;
154
+ if (options.dryRun) {
155
+ result.removed.push(entry);
156
+ result.bytes += entry.bytes;
157
+ continue;
158
+ }
159
+ const parts = entry.kind === "native-images" ? names(entry.path).map((n) => join(entry.path, n)) : [entry.path];
160
+ let freed = 0;
161
+ let error: string | null = null;
162
+ for (const part of parts) {
163
+ const bytes = sizeOf(part);
164
+ try {
165
+ rmSync(part, { recursive: true, force: true });
166
+ freed += bytes;
167
+ } catch (e) {
168
+ error ??= e instanceof Error ? e.message : String(e);
169
+ }
170
+ }
171
+ result.bytes += freed;
172
+ if (error) result.failed.push({ entry, error });
173
+ else result.removed.push(entry);
174
+ }
175
+ if (!options.dryRun && options.roots) {
176
+ for (const version of names(options.roots.workloads)) {
177
+ const dir = join(options.roots.workloads, version);
178
+ if (isDir(dir) && !names(dir).length) rmdirSync(dir);
179
+ }
180
+ }
181
+ return result;
182
+ }
183
+
184
+ export function entryName(e: CacheEntry): string {
185
+ if (e.kind === "workload") return `${e.variant} workload`;
186
+ if (e.kind === "compiler") return "sk-aot";
187
+ if (e.kind === "shader-compiler") return `redslangc ${e.version}`;
188
+ if (e.kind === "native-images") return `native images (${e.items})`;
189
+ if (e.kind === "legacy") return "old AOT toolchain";
190
+ return "stray file";
191
+ }
192
+
193
+ /** The Skathi version column: a shader compiler has its own version, in its name. */
194
+ const skathiVersion = (e: CacheEntry) => (e.kind === "shader-compiler" ? "" : (e.version ?? ""));
195
+
196
+ type Line = readonly [version: string, name: string, size: string, note: string];
197
+
198
+ function lines(rows: Line[], p: ReturnType<typeof paint>): string[] {
199
+ const width = (i: 0 | 1 | 2) => Math.max(...rows.map((r) => r[i].length));
200
+ const [w0, w1, w2] = [width(0), width(1), width(2)];
201
+ return rows.map(([v, name, size, note]) =>
202
+ ` ${p.cyan(v.padEnd(w0))} ${name.padEnd(w1)} ${size.padStart(w2)} ${note}`.trimEnd(),
203
+ );
204
+ }
205
+
206
+ const where = (e: CacheEntry, p: ReturnType<typeof paint>) => (e.version === undefined ? p.dim(e.path) : "");
207
+
208
+ export function formatInventory(
209
+ entries: CacheEntry[],
210
+ roots: CacheRoots,
211
+ options: KeepOptions,
212
+ color: boolean,
213
+ ): string {
214
+ const p = paint(color);
215
+ if (!entries.length) return `${p.dim("nothing cached in")} ${roots.workloads}`;
216
+ const rows = entries.map((e): Line => {
217
+ const state =
218
+ e.complete === false
219
+ ? p.yellow("incomplete")
220
+ : !needed(e, options)
221
+ ? ""
222
+ : e.version === options.current || e.kind === "shader-compiler"
223
+ ? p.green("this sk")
224
+ : p.green("kept");
225
+ return [skathiVersion(e), entryName(e), mib(e.bytes), [state, where(e, p)].filter(Boolean).join(" ")];
226
+ });
227
+ const total = entries.reduce((n, e) => n + e.bytes, 0);
228
+ const free = entries.filter((e) => !needed(e, options)).reduce((n, e) => n + e.bytes, 0);
229
+ return [
230
+ `${p.bold("Workloads")} ${p.dim(roots.workloads)}`,
231
+ ...lines(rows, p),
232
+ "",
233
+ `${mib(total)} in all; sk prune frees ${free ? p.bold(mib(free)) : "nothing"}`,
234
+ ].join("\n");
235
+ }
236
+
237
+ export function formatPrune(result: PruneResult, options: KeepOptions & { dryRun?: boolean }, color: boolean): string {
238
+ const p = paint(color);
239
+ const kept = [options.current, ...(options.keep ?? [])].join(", ");
240
+ if (!result.removed.length && !result.failed.length) return `nothing to prune; the workloads of ${kept} stay`;
241
+ const verb = options.dryRun ? "would remove" : "removed";
242
+ const rows = [
243
+ ...result.removed.map((e): Line => [skathiVersion(e), entryName(e), mib(e.bytes), p.dim(verb)]),
244
+ ...result.failed.map(({ entry: e, error }): Line => [
245
+ skathiVersion(e),
246
+ entryName(e),
247
+ mib(e.bytes),
248
+ p.yellow(error),
249
+ ]),
250
+ ];
251
+ return [
252
+ ...lines(rows, p),
253
+ "",
254
+ `${options.dryRun ? "would free" : "freed"} ${p.bold(mib(result.bytes))}` +
255
+ (options.all ? "" : `; the workloads of ${kept} stay (--all removes them too)`),
256
+ ...(result.failed.length ? [`${p.yellow("in use")}: close the apps that hold them and run sk prune again`] : []),
257
+ ].join("\n");
258
+ }