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

DesktopLinuxUrlHandler.test.ts

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