Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopLinuxUrlHandler.test.ts

707 lines27.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Cause from "effect/Cause";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as PlatformError from "effect/PlatformError";
14import * as Sink from "effect/Sink";
15import * as Stream from "effect/Stream";
16import * as TestClock from "effect/testing/TestClock";
17import * as ChildProcess from "effect/process/ChildProcess";
18import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19​
20import * as DesktopEnvironment from "./DesktopEnvironment.ts";
21import * as DesktopAssets from "./DesktopAssets.ts";
22import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
23​
24interface RecordedRegistration {
25 readonly directories: string[];
26 readonly files: Array<{ readonly path: string; readonly content: string }>;
27 readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
28 readonly copies: Array<{ readonly source: string; readonly destination: string }>;
29 readonly icons: Array<{ readonly path: string; readonly bytes: ReadonlyArray<number> }>;
31​
32const ICON_BYTES = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
33​
34const makeEnvironment = (path: Path.Path, overrides: Record<string, unknown> = {}) =>
35 DesktopEnvironment.DesktopEnvironment.of({
36 platform: "linux",
37 isPackaged: true,
38 isDevelopment: false,
39 displayName: "T3 Code (Alpha)",
40 linuxDesktopEntryName: "com.t3tools.T3Code.desktop",
41 linuxApplicationsDir: "/home/alice/.local/share/applications",
42 desktopLauncherPath: Option.none(),
43 appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
44 path,
45 ...overrides,
46 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
47​
48const mockProcess = (exitCode: number, stalled = false) =>
49 ChildProcessSpawner.makeHandle({
50 pid: ChildProcessSpawner.ProcessId(1),
51 exitCode: stalled ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
52 isRunning: Effect.succeed(false),
53 kill: () => Effect.void,
54 unref: Effect.succeed(Effect.void),
55 stdin: Sink.drain,
56 stdout: Stream.empty,
57 stderr: Stream.empty,
58 all: Stream.empty,
59 getInputFd: () => Sink.drain,
60 getOutputFd: () => Stream.empty,
61 });
62​
63const layerHandler = (
64 recorded: RecordedRegistration,
65 input: {
66 readonly environment?: Record<string, unknown>;
67 readonly processSpawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
68 readonly updateDesktopDatabaseExitCode?: number;
69 readonly updateDesktopDatabaseStalled?: boolean;
70 readonly updateDesktopDatabaseStarted?: Deferred.Deferred<void>;
71 readonly xdgMimeExitCode?: number;
72 readonly writeError?: PlatformError.PlatformError;
73 readonly existingEntry?: string;
74 readonly iconSource?: string;
75 readonly iconWriteError?: PlatformError.PlatformError;
76 } = {},
77) =>
78 DesktopLinuxUrlHandler.layer.pipe(
79 Layer.provide(
80 Layer.mergeAll(
81 Layer.effect(
82 DesktopEnvironment.DesktopEnvironment,
83 Path.Path.pipe(
84 Effect.map((path) => makeEnvironment(path, input.environment)),
85 Effect.provide(Path.layer),
86 ),
87 ),
88 Layer.succeed(DesktopAssets.DesktopAssets, {
89 iconPaths: Effect.succeed({
90 png: Option.fromUndefinedOr(input.iconSource),
91 ico: Option.none(),
92 icns: Option.none(),
93 }),
94 resolveResourcePath: () => Effect.succeedNone,
95 }),
96 FileSystem.layerNoop({
97 copyFile: (source, destination) =>
98 Effect.sync(() => {
99 recorded.copies.push({ source, destination });
100 }),
101 readFile: (path) =>
102 path === input.iconSource
103 ? Effect.succeed(ICON_BYTES)
104 : Effect.fail(
105 PlatformError.systemError({
106 _tag: "NotFound",
107 module: "FileSystem",
108 method: "readFile",
109 pathOrDescriptor: path,
110 }),
111 ),
112 writeFile: (path, bytes) =>
113 input.iconWriteError
114 ? Effect.fail(input.iconWriteError)
115 : Effect.sync(() => {
116 recorded.icons.push({ path, bytes: [...bytes] });
117 }),
118 readFileString: () => Effect.succeed(input.existingEntry ?? ""),
119 makeDirectory: (path) =>
120 Effect.sync(() => {
121 recorded.directories.push(path);
122 }),
123 writeFileString: (path, content) =>
124 input.writeError
125 ? Effect.fail(input.writeError)
126 : Effect.sync(() => {
127 recorded.files.push({ path, content });
128 }),
129 }),
130 Layer.succeed(
131 ChildProcessSpawner.ChildProcessSpawner,
132 ChildProcessSpawner.make((command) => {
133 if (input.processSpawner) return input.processSpawner.spawn(command);
134 const childProcess = command as unknown as {
135 readonly command: string;
136 readonly args: ReadonlyArray<string>;
137 };
138 if (childProcess.command === "update-desktop-database") {
139 assert.isTrue(
140 recorded.files.length > 0 || input.existingEntry !== undefined,
141 "the desktop entry must exist before refreshing the MIME cache",
142 );
143 }
144 recorded.commands.push({
145 command: childProcess.command,
146 args: childProcess.args,
147 });
148 const exitCode =
149 childProcess.command === "update-desktop-database"
150 ? (input.updateDesktopDatabaseExitCode ?? 0)
151 : (input.xdgMimeExitCode ?? 0);
152 const handle = mockProcess(
153 exitCode,
154 childProcess.command === "update-desktop-database" &&
155 input.updateDesktopDatabaseStalled === true,
156 );
157 return childProcess.command === "update-desktop-database" &&
158 input.updateDesktopDatabaseStarted
159 ? Deferred.succeed(input.updateDesktopDatabaseStarted, undefined).pipe(
160 Effect.as(handle),
161 )
162 : Effect.succeed(handle);
163 }),
164 ),
165 ),
166 ),
167 );
168​
169const runRegister = (
170 recorded: RecordedRegistration,
171 input: Parameters<typeof layerHandler>[1] = {},
172) =>
173 Effect.gen(function* () {
174 const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
175 yield* handler.register;
176 }).pipe(Effect.provide(layerHandler(recorded, input)));
177​
178const emptyRecording = (): RecordedRegistration => ({
179 directories: [],
180 files: [],
181 commands: [],
182 copies: [],
183 icons: [],
184});
185​
186describe("DesktopLinuxUrlHandler", () => {
187 it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
188 const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
189 displayName: "T3 Code (Nightly)",
190 execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
191 scheme: "t3code",
192 iconPath: "/home/al ice/icons/T3\\x.png",
193 });
194​
195 assert.include(entry, "[Desktop Entry]");
196 assert.include(entry, "Name=T3 Code (Nightly)");
197 assert.include(
198 entry,
199 'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
200 );
201 assert.include(entry, "NoDisplay=true");
202 assert.notInclude(entry, "StartupWMClass=");
203 assert.include(entry, "MimeType=x-scheme-handler/t3code;");
204 assert.include(entry, "Icon=/home/al ice/icons/T3\\\\x.png");
205 });
206​
207 it.effect(
208 "writes the handler entry, refreshes the MIME cache, and claims the scheme default",
209 () => {
210 const recorded = emptyRecording();
211​
212 return Effect.gen(function* () {
213 yield* runRegister(recorded);
214​
215 assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
216 assert.equal(recorded.files.length, 1);
217 assert.equal(
218 recorded.files[0]?.path,
219 "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
220 );
221 assert.include(
222 recorded.files[0]?.content,
223 "Exec=/home/alice/Applications/T3-Code.AppImage %U",
224 );
225 assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
226 assert.deepEqual(recorded.commands, [
227 {
228 command: "update-desktop-database",
229 args: ["/home/alice/.local/share/applications"],
230 },
231 {
232 command: "xdg-mime",
233 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
234 },
235 ]);
236 });
237 },
238 );
239​
240 it.effect("falls back to the process executable outside an AppImage", () => {
241 const recorded = emptyRecording();
242​
243 return Effect.gen(function* () {
244 yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
245​
246 assert.include(
247 recorded.files[0]?.content,
248 DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
249 displayName: "T3 Code (Alpha)",
250 execTarget: process.execPath,
251 scheme: "t3code",
252 iconPath: "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png",
253 }),
254 );
255 });
256 });
257​
258 it.effect("launches a distribution package through its configured launcher", () => {
259 const recorded = emptyRecording();
260​
261 return Effect.gen(function* () {
262 yield* runRegister(recorded, {
263 environment: { desktopLauncherPath: Option.some("/opt/T3 Code/t3code") },
264 });
265​
266 assert.include(recorded.files[0]?.content, 'Exec="/opt/T3 Code/t3code" %U');
267 });
268 });
269​
270 it.effect("does not rewrite the pre-ready entry while the portal can be reading it", () => {
271 const recorded = emptyRecording();
272​
273 return Effect.gen(function* () {
274 yield* runRegister(recorded, {
275 existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
276 displayName: "T3 Code (Alpha)",
277 execTarget: "/home/alice/Applications/T3-Code.AppImage",
278 scheme: "t3code",
279 iconPath: "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png",
280 }),
281 });
282​
283 assert.deepEqual(recorded.files, []);
284 assert.deepEqual(recorded.directories, []);
285 assert.deepEqual(recorded.commands, [
286 {
287 command: "update-desktop-database",
288 args: ["/home/alice/.local/share/applications"],
289 },
290 {
291 command: "xdg-mime",
292 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
293 },
294 ]);
295 });
296 });
297​
298 it.effect("installs a persistent icon even when the desktop entry is already current", () => {
299 const recorded = emptyRecording();
300 const iconPath = "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png";
301 return Effect.gen(function* () {
302 yield* runRegister(recorded, {
303 iconSource: "/tmp/.mount_T3/resources/icon.png",
304 existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
305 displayName: "T3 Code (Alpha)",
306 execTarget: "/home/alice/Applications/T3-Code.AppImage",
307 scheme: "t3code",
308 iconPath,
309 }),
310 });
311 assert.deepEqual(recorded.files, []);
312 assert.deepEqual(recorded.copies, [], "icon must not be copied out of the app bundle");
313 assert.deepEqual(recorded.icons, [{ path: iconPath, bytes: [...ICON_BYTES] }]);
314 assert.equal(recorded.commands.at(-1)?.command, "xdg-mime");
315 });
316 });
317​
318 it.effect("still registers the handler when installing its icon fails", () => {
319 const recorded = emptyRecording();
320 return Effect.gen(function* () {
321 yield* runRegister(recorded, {
322 iconSource: "/tmp/.mount_T3/resources/icon.png",
323 iconWriteError: PlatformError.systemError({
324 _tag: "PermissionDenied",
325 module: "FileSystem",
326 method: "writeFile",
327 description: "read-only icon directory",
328 }),
329 });
330 assert.equal(recorded.files.length, 1);
331 assert.deepEqual(
332 recorded.commands.map(({ command }) => command),
333 ["update-desktop-database", "xdg-mime"],
334 );
335 });
336 });
337​
338 it.effect("writes the portal identity without claiming the URL scheme in development", () => {
339 const nonLinux = emptyRecording();
340 const unpackaged = emptyRecording();
341​
342 return Effect.gen(function* () {
343 yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
344 yield* runRegister(unpackaged, {
345 environment: {
346 isPackaged: false,
347 linuxDesktopEntryName: "com.t3tools.T3Code.Development.desktop",
348 },
349 });
350​
351 assert.deepEqual(nonLinux.files, []);
352 assert.equal(
353 unpackaged.files[0]?.path,
354 "/home/alice/.local/share/applications/com.t3tools.T3Code.Development.desktop",
355 );
356 assert.deepEqual(unpackaged.commands, []);
357 });
358 });
359​
360 it.effect("never fails startup when registration cannot complete", () => {
361 const desktopDatabaseFailed = emptyRecording();
362 const xdgMimeFailed = emptyRecording();
363 const writeFailed = emptyRecording();
364​
365 return Effect.gen(function* () {
366 yield* runRegister(desktopDatabaseFailed, { updateDesktopDatabaseExitCode: 1 });
367 yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
368 yield* runRegister(writeFailed, {
369 writeError: PlatformError.systemError({
370 _tag: "PermissionDenied",
371 module: "FileSystem",
372 method: "writeFileString",
373 description: "read-only filesystem",
374 pathOrDescriptor: "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
375 }),
376 });
377​
378 assert.deepEqual(
379 desktopDatabaseFailed.commands.map(({ command }) => command),
380 ["update-desktop-database", "xdg-mime"],
381 );
382 assert.equal(xdgMimeFailed.files.length, 1);
383 assert.deepEqual(writeFailed.commands, []);
384 });
385 });
386​
387 for (const stalledHelper of ["update-desktop-database", "xdg-mime"] as const) {
388 it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
389 `finishes registration after a timed-out ${stalledHelper} ignores SIGTERM`,
390 () =>
391 Effect.gen(function* () {
392 const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
393 const nodeExecutable = yield* HostProcess.ExecutablePath;
394 const recorded = emptyRecording();
395 const spawned = yield* Deferred.make<ChildProcessSpawner.ChildProcessHandle>();
396 const ready = yield* Deferred.make<void>();
397 const processSpawner = ChildProcessSpawner.make((command) =>
398 Effect.gen(function* () {
399 if (!ChildProcess.isStandardCommand(command)) {
400 return yield* Effect.die("expected a single registration command");
401 }
402 recorded.commands.push({ command: command.command, args: command.args.map(String) });
403 if (command.command !== stalledHelper) return mockProcess(0);
404 const child = yield* realSpawner.spawn(
405 ChildProcess.make(
406 nodeExecutable,
407 [
408 "-e",
409 // The watchdog makes the unfixed case exit with a distinguishable code.
410 "process.on('SIGTERM', () => setTimeout(() => process.exit(99), 5000));" +
411 "process.stdout.write('ready\\n'); setInterval(() => {}, 2147483647);",
412 ],
413 { ...command.options, stdout: "pipe" },
414 ),
415 );
416 yield* Deferred.succeed(spawned, child);
417 yield* Stream.runHead(child.stdout);
418 yield* Deferred.succeed(ready, undefined);
419 return child;
420 }),
421 );
422 const registration = yield* runRegister(recorded, { processSpawner }).pipe(
423 Effect.forkScoped,
424 );
425 const child = yield* Deferred.await(spawned);
426 yield* Effect.addFinalizer(() =>
427 child.isRunning.pipe(
428 Effect.flatMap((running) =>
429 running ? child.kill({ killSignal: "SIGKILL" }) : Effect.void,
430 ),
431 Effect.ignore,
432 ),
433 );
434 yield* Deferred.await(ready);
435 yield* TestClock.adjust("5 seconds");
436 yield* Fiber.join(registration);
437​
438 const exit = yield* Effect.exit(child.exitCode);
439 if (Exit.isFailure(exit)) {
440 assert.include(Cause.pretty(exit.cause), "SIGKILL");
441 } else {
442 assert.fail(`${stalledHelper} exited with ${exit.value} instead of being force-killed`);
443 }
444 assert.deepEqual(
445 recorded.commands.map(({ command }) => command),
446 ["update-desktop-database", "xdg-mime"],
447 );
448 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
449 );
450 }
451});
452​
453interface ThemeIconRun {
454 readonly root: string;
455 readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
456 readonly iconCacheOptions?: Array<Record<string, unknown>>;
457 readonly sourceMissing?: boolean;
458 readonly iconCacheExitCode?: number;
459 readonly iconCacheSpawnFails?: boolean;
460 readonly iconCacheStalled?: boolean;
461 readonly iconCacheStarted?: Deferred.Deferred<void>;
462 // Stands in for gtk-update-icon-cache rewriting the cache on success.
463 readonly onIconCacheRefresh?: Effect.Effect<void>;
465​
466const registerWithRealFileSystem = (run: ThemeIconRun) =>
467 Effect.gen(function* () {
468 const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
469 yield* handler.register;
470 }).pipe(
471 Effect.provide(
472 DesktopLinuxUrlHandler.layer.pipe(
473 Layer.provide(
474 Layer.mergeAll(
475 Layer.effect(
476 DesktopEnvironment.DesktopEnvironment,
477 Path.Path.pipe(
478 Effect.map((path) =>
479 makeEnvironment(path, {
480 linuxApplicationsDir: path.join(run.root, "applications"),
481 }),
482 ),
483 ),
484 ),
485 Layer.effect(
486 DesktopAssets.DesktopAssets,
487 Path.Path.pipe(
488 Effect.map((path) => ({
489 iconPaths: Effect.succeed({
490 png: Option.none(),
491 ico: Option.none(),
492 icns: Option.none(),
493 }),
494 resolveResourcePath: (fileName: string) =>
495 Effect.succeed(
496 fileName === "icons/256x256.png"
497 ? Option.some(
498 path.join(
499 run.root,
500 run.sourceMissing ? "missing" : "resources",
501 fileName,
502 ),
503 )
504 : Option.none(),
505 ),
506 })),
507 ),
508 ),
509 Layer.succeed(
510 ChildProcessSpawner.ChildProcessSpawner,
511 ChildProcessSpawner.make((command) => {
512 const childProcess = command as unknown as {
513 readonly command: string;
514 readonly args: ReadonlyArray<string>;
515 };
516 run.commands.push({ command: childProcess.command, args: childProcess.args });
517 if (childProcess.command !== "gtk-update-icon-cache") {
518 return Effect.succeed(mockProcess(0));
519 }
520 run.iconCacheOptions?.push(
521 (command as unknown as { readonly options: Record<string, unknown> }).options,
522 );
523 if (run.iconCacheSpawnFails) {
524 return Effect.fail(
525 PlatformError.systemError({
526 _tag: "NotFound",
527 module: "ChildProcess",
528 method: "spawn",
529 description: "gtk-update-icon-cache is not installed",
530 }),
531 );
532 }
533 const exitCode = run.iconCacheExitCode ?? 0;
534 const handle = mockProcess(exitCode, run.iconCacheStalled === true);
535 const refreshed =
536 exitCode === 0 && run.onIconCacheRefresh ? run.onIconCacheRefresh : Effect.void;
537 return refreshed.pipe(
538 Effect.andThen(
539 run.iconCacheStarted
540 ? Deferred.succeed(run.iconCacheStarted, undefined)
541 : Effect.void,
542 ),
543 Effect.as(handle),
544 );
545 }),
546 ),
547 ),
548 ),
549 ),
550 ),
551 );
552​
553const themeIconFixture = (source: Uint8Array) =>
554 Effect.gen(function* () {
555 const fileSystem = yield* FileSystem.FileSystem;
556 const path = yield* Path.Path;
557 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-theme-icons-" });
558 yield* fileSystem.makeDirectory(path.join(root, "resources", "icons"), { recursive: true });
559 yield* fileSystem.writeFile(path.join(root, "resources", "icons", "256x256.png"), source);
560 const hicolorDir = path.join(root, "icons", "hicolor");
561 const appsDir = path.join(hicolorDir, "256x256", "apps");
562 const cachePath = path.join(hicolorDir, "icon-theme.cache");
563 const pastSeconds = 1_600_000_000;
564 const seedCache = Effect.gen(function* () {
565 yield* fileSystem.makeDirectory(appsDir, { recursive: true });
566 yield* fileSystem.writeFile(cachePath, new Uint8Array([0]));
567 yield* fileSystem.utimes(cachePath, pastSeconds, pastSeconds);
568 });
569 const rewriteCache = fileSystem
570 .writeFile(cachePath, new Uint8Array([1]))
571 .pipe(Effect.orDie, Effect.provideService(FileSystem.FileSystem, fileSystem));
572 return { root, hicolorDir, appsDir, cachePath, pastSeconds, seedCache, rewriteCache };
573 });
574​
575const iconCacheRuns = (run: ThemeIconRun) =>
576 run.commands.filter(({ command }) => command === "gtk-update-icon-cache").length;
577​
578it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => {
579 it.effect("installs both app id spellings without creating an icon cache", () =>
580 Effect.gen(function* () {
581 const fileSystem = yield* FileSystem.FileSystem;
582 const path = yield* Path.Path;
583 const icon = new Uint8Array([137, 80, 78, 71, 1, 2, 3]);
584 const fixture = yield* themeIconFixture(icon);
585 const run: ThemeIconRun = { root: fixture.root, commands: [] };
586​
587 yield* registerWithRealFileSystem(run);
588 assert.deepEqual([...(yield* fileSystem.readDirectory(fixture.appsDir))].sort(), [
589 "com.t3tools.T3Code.png",
590 "com.t3tools.t3code.png",
591 ]);
592 for (const name of ["com.t3tools.t3code", "com.t3tools.T3Code"]) {
593 const target = path.join(fixture.appsDir, `${name}.png`);
594 assert.deepEqual([...(yield* fileSystem.readFile(target))], [...icon]);
595 yield* fileSystem.utimes(target, fixture.pastSeconds, fixture.pastSeconds);
596 }
597​
598 yield* registerWithRealFileSystem(run);
599 for (const name of ["com.t3tools.t3code", "com.t3tools.T3Code"]) {
600 const info = yield* fileSystem.stat(path.join(fixture.appsDir, `${name}.png`));
601 assert.equal(Option.getOrThrow(info.mtime).getTime(), fixture.pastSeconds * 1000);
602 }
603 assert.isFalse(yield* fileSystem.exists(fixture.cachePath));
604 assert.equal(iconCacheRuns(run), 0);
605 }).pipe(Effect.scoped),
606 );
607​
608 it.effect("replaces same-length stale icons and refreshes an existing cache once", () =>
609 Effect.gen(function* () {
610 const fileSystem = yield* FileSystem.FileSystem;
611 const path = yield* Path.Path;
612 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
613 yield* fixture.seedCache;
614 const lower = path.join(fixture.appsDir, "com.t3tools.t3code.png");
615 const upper = path.join(fixture.appsDir, "com.t3tools.T3Code.png");
616 yield* fileSystem.writeFile(lower, new Uint8Array([3, 2, 1]));
617 yield* fileSystem.writeFile(upper, new Uint8Array([1, 2, 3]));
618 for (const target of [lower, upper]) {
619 yield* fileSystem.utimes(target, fixture.pastSeconds, fixture.pastSeconds);
620 }
621 const run: ThemeIconRun = {
622 root: fixture.root,
623 commands: [],
624 onIconCacheRefresh: fixture.rewriteCache,
625 };
626​
627 yield* registerWithRealFileSystem(run);
628 yield* registerWithRealFileSystem(run);
629​
630 assert.deepEqual([...(yield* fileSystem.readFile(lower))], [1, 2, 3]);
631 const upperInfo = yield* fileSystem.stat(upper);
632 assert.equal(Option.getOrThrow(upperInfo.mtime).getTime(), fixture.pastSeconds * 1000);
633 assert.deepEqual(
634 run.commands.filter(({ command }) => command === "gtk-update-icon-cache"),
635 [{ command: "gtk-update-icon-cache", args: ["-f", "-t", fixture.hicolorDir] }],
636 );
637 }).pipe(Effect.scoped),
638 );
639​
640 it.effect("refreshes when this launch changed an icon even if the cache looks newer", () =>
641 Effect.gen(function* () {
642 const fileSystem = yield* FileSystem.FileSystem;
643 const path = yield* Path.Path;
644 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
645 yield* fixture.seedCache;
646 const run: ThemeIconRun = {
647 root: fixture.root,
648 commands: [],
649 onIconCacheRefresh: fixture.rewriteCache,
650 };
651 const future = fixture.pastSeconds + 10 * 365 * 24 * 60 * 60;
652 yield* fileSystem.utimes(fixture.cachePath, future, future);
653​
654 yield* registerWithRealFileSystem(run);
655​
656 assert.isTrue(yield* fileSystem.exists(path.join(fixture.appsDir, "com.t3tools.T3Code.png")));
657 assert.equal(iconCacheRuns(run), 1);
658 }).pipe(Effect.scoped),
659 );
660​
661 it.effect("retries a failed icon cache refresh on the next launch", () =>
662 Effect.gen(function* () {
663 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
664 yield* fixture.seedCache;
665 const failing: ThemeIconRun = { root: fixture.root, commands: [], iconCacheExitCode: 1 };
666 yield* registerWithRealFileSystem(failing);
667 assert.equal(iconCacheRuns(failing), 1);
668 assert.deepEqual(failing.commands.map(({ command }) => command).slice(1), [
669 "update-desktop-database",
670 "xdg-mime",
671 ]);
672​
673 const recovering: ThemeIconRun = {
674 root: fixture.root,
675 commands: [],
676 onIconCacheRefresh: fixture.rewriteCache,
677 };
678 yield* registerWithRealFileSystem(recovering);
679 yield* registerWithRealFileSystem(recovering);
680 assert.equal(iconCacheRuns(recovering), 1);
681 }).pipe(Effect.scoped),
682 );
683​
684 it.effect("still registers the handler when the theme icon install fails", () =>
685 Effect.gen(function* () {
686 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
687 const missingSource: ThemeIconRun = { root: fixture.root, commands: [], sourceMissing: true };
688 yield* registerWithRealFileSystem(missingSource);
689 assert.deepEqual(
690 missingSource.commands.map(({ command }) => command),
691 ["update-desktop-database", "xdg-mime"],
692 );
693​
694 yield* fixture.seedCache;
695 const missingTool: ThemeIconRun = {
696 root: fixture.root,
697 commands: [],
698 iconCacheSpawnFails: true,
699 };
700 yield* registerWithRealFileSystem(missingTool);
701 assert.deepEqual(
702 missingTool.commands.map(({ command }) => command),
703 ["gtk-update-icon-cache", "update-desktop-database", "xdg-mime"],
704 );
705 }).pipe(Effect.scoped),
706 );
707});