mirror of https://github.com/theNewDynamic/gohugo-theme-ananke.git

Patrick Kollitsch
yesterday ae0c6ae00a249f9c3cc819edbfb899fe309d406e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
#!/usr/bin/env node
 
import { spawn } from "node:child_process";
import { constants } from "node:fs";
import {
    access,
    copyFile,
    cp,
    mkdir,
    mkdtemp,
    readFile,
    rm,
    stat,
    writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
 
/**
 * Absolute path to the theme repository root (the parent of `scripts/`).
 */
const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
 
interface CommandResult {
    code: number | null;
    signal: NodeJS.Signals | null;
    stdout: string;
    stderr: string;
    combined: string;
    durationMs: number;
}
 
interface StepDefinition {
    name: string;
    command: string;
    args: string[];
    cwd: string;
    expectedFiles?: string[];
}
 
/**
 * Where the theme under test comes from.
 *
 * - `local`: install the local working tree of this repository (default), so the
 *   test exercises the actual code on the current branch, including uncommitted
 *   changes. This is what makes the test meaningful as a pre-push / CI gate.
 * - `submodule`: clone the published theme from its remote via `git submodule add`,
 *   reproducing the documented quickstart install. Useful to verify the public
 *   install path, but does **not** see local changes.
 */
type ThemeSource = "local" | "submodule";
 
interface RoutineOptions {
    projectName: string;
    themeSource: ThemeSource;
    themePath: string;
    themeRepo: string;
    themeDir: string;
    themeName: string;
    configFile: string;
    keepOnSuccess: boolean;
    keepOnFailure: boolean;
    verbose: boolean;
}
 
interface StepReport {
    step: string;
    commandLine: string;
    cwd: string;
    result: CommandResult;
}
 
interface HtmlAssertion {
    description: string;
    test: (html: string) => boolean;
}
 
const DEFAULT_OPTIONS: RoutineOptions = {
    projectName: "quickstart",
    themeSource: "local",
    themePath: REPO_ROOT,
    themeRepo: "https://github.com/gohugo-ananke/ananke.git",
    themeDir: "themes/ananke",
    themeName: "ananke",
    configFile: "hugo.toml",
    keepOnSuccess: false,
    keepOnFailure: true,
    verbose: true,
};
 
/**
 * Print CLI help.
 */
function printHelp(): void {
    console.log(
        `
Usage:
  node scripts/test-hugo-quickstart.ts [options]
 
Options:
  --project-name=<name>         Hugo project folder name inside the temp directory
  --theme-path=<path>           Install the theme from this local directory (default: this repo).
                                Implies local mode; tests the actual working tree.
  --use-submodule               Install the published theme via "git submodule add" instead
                                of the local working tree (verifies the documented quickstart).
  --theme-repo=<url>            Git URL for the theme submodule (only used with --use-submodule)
  --theme-dir=<path>            Theme target directory inside the project
  --theme-name=<name>           Theme name written into hugo.toml
  --config-file=<file>          Hugo config file to update
  --keep-on-success             Do not delete the temp directory when the test passes
  --no-keep-on-failure          Delete the temp directory when the test fails
  --quiet                       Reduce step logging
  --help                        Show this help
`.trim(),
    );
}
 
/**
 * Parse CLI arguments into routine options.
 *
 * @param argv Raw CLI arguments after the executable and script path.
 * @returns Parsed routine options.
 * @throws Error when an unknown argument is passed.
 */
function parseArgs(argv: string[]): RoutineOptions {
    const options: RoutineOptions = { ...DEFAULT_OPTIONS };
 
    for (const arg of argv) {
        if (arg === "--help") {
            printHelp();
            process.exit(0);
        }
 
        if (arg === "--keep-on-success") {
            options.keepOnSuccess = true;
            continue;
        }
 
        if (arg === "--no-keep-on-failure") {
            options.keepOnFailure = false;
            continue;
        }
 
        if (arg === "--quiet") {
            options.verbose = false;
            continue;
        }
 
        if (arg === "--use-submodule") {
            options.themeSource = "submodule";
            continue;
        }
 
        if (arg.startsWith("--theme-path=")) {
            options.themePath = resolve(arg.slice("--theme-path=".length));
            options.themeSource = "local";
            continue;
        }
 
        if (arg.startsWith("--project-name=")) {
            options.projectName = arg.slice("--project-name=".length);
            continue;
        }
 
        if (arg.startsWith("--theme-repo=")) {
            options.themeRepo = arg.slice("--theme-repo=".length);
            continue;
        }
 
        if (arg.startsWith("--theme-dir=")) {
            options.themeDir = arg.slice("--theme-dir=".length);
            continue;
        }
 
        if (arg.startsWith("--theme-name=")) {
            options.themeName = arg.slice("--theme-name=".length);
            continue;
        }
 
        if (arg.startsWith("--config-file=")) {
            options.configFile = arg.slice("--config-file=".length);
            continue;
        }
 
        throw new Error(`Unknown argument: ${arg}`);
    }
 
    return options;
}
 
/**
 * Format a command for human-readable logging.
 *
 * @param command Executable name.
 * @param args Executable arguments.
 * @returns Full command line.
 */
function formatCommand(command: string, args: string[]): string {
    return [command, ...args]
        .map((part) => (/\s/.test(part) ? JSON.stringify(part) : part))
        .join(" ");
}
 
/**
 * Run a command and capture stdout/stderr.
 *
 * @param command Executable name.
 * @param args Executable arguments.
 * @param cwd Working directory.
 * @returns Command execution result.
 */
async function runCommand(
    command: string,
    args: string[],
    cwd: string,
): Promise<CommandResult> {
    const started = Date.now();
 
    return new Promise<CommandResult>((resolve, reject) => {
        const child = spawn(command, args, {
            cwd,
            env: process.env,
            stdio: ["ignore", "pipe", "pipe"],
        });
 
        let stdout = "";
        let stderr = "";
 
        child.stdout.on("data", (chunk: Buffer | string) => {
            stdout += chunk.toString();
        });
 
        child.stderr.on("data", (chunk: Buffer | string) => {
            stderr += chunk.toString();
        });
 
        child.on("error", (error: Error) => {
            reject(error);
        });
 
        child.on("close", (code, signal) => {
            const durationMs = Date.now() - started;
            const combined = [stdout, stderr]
                .filter(Boolean)
                .join(stdout && stderr ? "\n" : "");
 
            resolve({
                code,
                signal,
                stdout,
                stderr,
                combined,
                durationMs,
            });
        });
    });
}
 
/**
 * Ensure a file or directory exists.
 *
 * @param filePath Absolute path to check.
 */
async function assertFileExists(filePath: string): Promise<void> {
    await access(filePath, constants.F_OK);
}
 
/**
 * Ensure a file or directory does not exist.
 *
 * @param filePath Absolute path to check.
 */
async function assertFileDoesNotExist(filePath: string): Promise<void> {
    try {
        await access(filePath, constants.F_OK);
        throw new Error(`Unexpected path exists: ${filePath}`);
    } catch (error: unknown) {
        if (
            error instanceof Error &&
            error.message.startsWith("Unexpected path exists:")
        ) {
            throw error;
        }
    }
}
 
/**
 * Read a UTF-8 text file.
 *
 * @param filePath Absolute file path.
 * @returns File contents.
 */
async function readTextFile(filePath: string): Promise<string> {
    return readFile(filePath, "utf8");
}
 
/**
 * Write a UTF-8 text file.
 *
 * @param filePath Absolute file path.
 * @param content File contents.
 */
async function writeTextFile(filePath: string, content: string): Promise<void> {
    await writeFile(filePath, content, "utf8");
}
 
/**
 * Remove the generated public directory inside the temporary project.
 *
 * @param projectRoot Absolute path to the temporary quickstart project.
 */
async function removePublicDir(projectRoot: string): Promise<void> {
    const publicPath = join(projectRoot, "public");
    await rm(publicPath, { recursive: true, force: true });
}
 
/**
 * Execute one step and validate success.
 *
 * @param step Step definition.
 * @returns Step report.
 * @throws Error when the command fails or an expected file is missing.
 */
async function executeStep(step: StepDefinition): Promise<StepReport> {
    const result = await runCommand(step.command, step.args, step.cwd);
    const commandLine = formatCommand(step.command, step.args);
 
    if (result.code !== 0) {
        const details = [
            `Step failed: ${step.name}`,
            `Command: ${commandLine}`,
            `Working directory: ${step.cwd}`,
            `Exit code: ${String(result.code)}`,
            result.signal ? `Signal: ${result.signal}` : "",
            result.stdout ? `STDOUT:\n${result.stdout}` : "",
            result.stderr ? `STDERR:\n${result.stderr}` : "",
        ]
            .filter(Boolean)
            .join("\n\n");
 
        throw new Error(details);
    }
 
    if (step.expectedFiles) {
        for (const relativePath of step.expectedFiles) {
            const absolutePath = join(step.cwd, relativePath);
 
            try {
                await assertFileExists(absolutePath);
            } catch (error: unknown) {
                const message =
                    error instanceof Error
                        ? error.message
                        : "Unknown file assertion error";
 
                throw new Error(
                    [
                        `Step failed: ${step.name}`,
                        `Command: ${commandLine}`,
                        `Working directory: ${step.cwd}`,
                        `Expected file missing: ${absolutePath}`,
                        `Details: ${message}`,
                        result.stdout ? `STDOUT:\n${result.stdout}` : "",
                        result.stderr ? `STDERR:\n${result.stderr}` : "",
                    ]
                        .filter(Boolean)
                        .join("\n\n"),
                );
            }
        }
    }
 
    return {
        step: step.name,
        commandLine,
        cwd: step.cwd,
        result,
    };
}
 
/**
 * Determine whether a Hugo command generates output in `public/`.
 *
 * @param step Step definition.
 * @returns True when the command is a build command.
 */
function isHugoBuildCommand(step: StepDefinition): boolean {
    if (step.command !== "hugo") {
        return false;
    }
 
    if (step.args.length === 0) {
        return true;
    }
 
    if (step.args.includes("--buildDrafts")) {
        return true;
    }
 
    return false;
}
 
/**
 * Execute a Hugo build command after clearing the generated public directory.
 *
 * @param step Step definition.
 * @param projectRoot Absolute path to the temporary quickstart project.
 * @returns Step report.
 */
async function executeHugoBuildStep(
    step: StepDefinition,
    projectRoot: string,
): Promise<StepReport> {
    await removePublicDir(projectRoot);
    return executeStep(step);
}
 
/**
 * Escape a string for safe use in a regular expression.
 *
 * @param value Raw string.
 * @returns Escaped string.
 */
function escapeRegExp(value: string): string {
    return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
 
/**
 * Assert that Hugo config contains the expected theme assignment somewhere in
 * the file, without requiring the whole config to match a fixed template.
 *
 * Accepts either single or double quotes, for example:
 * - theme = 'ananke'
 * - theme = "ananke"
 *
 * @param configPath Absolute config path.
 * @param themeName Expected theme name.
 * @throws Error when the config does not contain the expected theme line.
 */
async function assertThemeConfigured(
    configPath: string,
    themeName: string,
): Promise<void> {
    const config = await readTextFile(configPath);
    const themePattern = new RegExp(
        String.raw`^\s*theme\s*=\s*['"]${escapeRegExp(themeName)}['"]\s*$`,
        "m",
    );
 
    if (!themePattern.test(config)) {
        throw new Error(
            [
                "Strict assertion failed: theme configuration missing or incorrect.",
                `Config file: ${configPath}`,
                `Expected to find a line like: theme = '${themeName}'`,
                "Actual file contents:",
                config,
            ].join("\n\n"),
        );
    }
}
 
/**
 * Return homepage assertions for the initial static build.
 *
 * @returns List of homepage assertions.
 */
function getHomepageAssertions(): HtmlAssertion[] {
    return [
        {
            description: "homepage contains an HTML document root",
            test: (html: string): boolean => /<html\b/i.test(html),
        },
        {
            description: "homepage contains a document title",
            test: (html: string): boolean => /<title>[\s\S]*?<\/title>/i.test(html),
        },
        {
            description: "homepage contains a body element",
            test: (html: string): boolean => /<body\b/i.test(html),
        },
        {
            description: "homepage contains at least one stylesheet reference",
            test: (html: string): boolean =>
                /<link\b[^>]*rel=["']stylesheet["'][^>]*>/i.test(html),
        },
        {
            description: "homepage contains at least one navigation-related landmark",
            test: (html: string): boolean => /<(nav|header)\b/i.test(html),
        },
        {
            description: "homepage contains theme-generated CSS class markers",
            test: (html: string): boolean =>
                /\b(ma[0-9]|pa[0-9]|bg-black|near-white|sans-serif)\b/i.test(html),
        },
        {
            description: "homepage contains a main content area",
            test: (html: string): boolean => /<(main|article|section)\b/i.test(html),
        },
    ];
}
 
/**
 * Assert that the generated homepage looks like a real themed render.
 *
 * @param homepagePath Absolute path to `public/index.html`.
 * @throws Error when one or more assertions fail.
 */
async function assertHomepageLooksValid(homepagePath: string): Promise<void> {
    const html = await readTextFile(homepagePath);
    const failures: string[] = [];
 
    if (html.trim().length === 0) {
        throw new Error(
            [
                "Strict assertion failed: generated homepage is empty.",
                `Homepage file: ${homepagePath}`,
            ].join("\n\n"),
        );
    }
 
    for (const assertion of getHomepageAssertions()) {
        if (!assertion.test(html)) {
            failures.push(`- ${assertion.description}`);
        }
    }
 
    if (failures.length > 0) {
        throw new Error(
            [
                "Strict assertion failed: generated homepage did not match expected render checks.",
                `Homepage file: ${homepagePath}`,
                "Failed assertions:",
                ...failures,
            ].join("\n"),
        );
    }
}
 
/**
 * Extract the auto-generated date line from a Hugo content file with TOML frontmatter.
 *
 * @param content Raw file contents.
 * @returns Original date line.
 * @throws Error when the date line is missing.
 */
function extractGeneratedDateLine(content: string): string {
    const match = content.match(/^\s*date\s*=\s*.+$/m);
 
    if (!match) {
        throw new Error(
            [
                "Strict assertion failed: could not find auto-generated date line in content file.",
                "Actual file contents:",
                content,
            ].join("\n\n"),
        );
    }
 
    return match[0];
}
 
/**
 * Replace the generated content with the requested sample draft while preserving
 * the original date line created by `hugo new`.
 *
 * @param contentPath Absolute path to the content file.
 */
async function replaceGeneratedContent(contentPath: string): Promise<void> {
    const original = await readTextFile(contentPath);
    const dateLine = extractGeneratedDateLine(original);
 
    const updated = [
        "+++",
        "title = 'My First Post'",
        dateLine,
        "draft = true",
        "+++",
        "## Introduction",
        "",
        "This is **bold** text, and this is *emphasized* text.",
        "",
        "Visit the [Hugo](https://gohugo.io) website!",
        "",
    ].join("\n");
 
    await writeTextFile(contentPath, updated);
}
 
/**
 * Replace the root Hugo config with the requested quickstart config.
 *
 * @param configPath Absolute path to `hugo.toml`.
 * @param themeName Theme name to set.
 */
async function replaceHugoConfig(
    configPath: string,
    themeName: string,
): Promise<void> {
    const content = [
        "baseURL = 'https://example.com/'",
        "locale = 'en-gb'",
        "title = 'Ananke Test Quickstart'",
        `theme = '${themeName}'`,
        "",
    ].join("\n");
 
    await writeTextFile(configPath, content);
}
 
/**
 * Assert that the generated page contains the expected rendered draft content.
 *
 * @param pageHtml HTML from `public/foo/index.html`.
 */
function assertDraftPageRendered(pageHtml: string): void {
    const failures: string[] = [];
 
    if (!/<h2[^>]*>\s*Introduction\s*<\/h2>/i.test(pageHtml)) {
        failures.push("- heading 'Introduction' was not rendered as an h2 element");
    }
 
    if (!/<strong>\s*bold\s*<\/strong>/i.test(pageHtml)) {
        failures.push("- bold Markdown was not rendered as a <strong> element");
    }
 
    if (!/<em>\s*emphasized\s*<\/em>/i.test(pageHtml)) {
        failures.push("- emphasized Markdown was not rendered as an <em> element");
    }
 
    if (
        !/<a[^>]+href=["']https:\/\/gohugo\.io["'][^>]*>\s*Hugo\s*<\/a>/i.test(
            pageHtml,
        )
    ) {
        failures.push("- Markdown link was not rendered as an anchor element");
    }
 
    if (!/My First Post/i.test(pageHtml)) {
        failures.push("- post title was not visible on the rendered page");
    }
 
    if (failures.length > 0) {
        throw new Error(
            [
                "Strict assertion failed: draft page content was not rendered as expected.",
                "Failed assertions:",
                ...failures,
            ].join("\n"),
        );
    }
}
 
/**
 * Assert that the generated homepage reflects updated title and locale configuration.
 *
 * Locale is checked strictly on the `<html>` tag.
 *
 * @param homepageHtml HTML from `public/index.html`.
 */
function assertUpdatedConfigInOutput(homepageHtml: string): void {
    const failures: string[] = [];
 
    if (!/Ananke Test Quickstart/i.test(homepageHtml)) {
        failures.push(
            "- updated site title was not visible in the generated output",
        );
    }
 
    if (!/<html[^>]+lang=["']en-gb["'][^>]*>/i.test(homepageHtml)) {
        failures.push(
            "- updated locale 'en-gb' was not present in the <html lang=\"en-gb\"> tag",
        );
    }
 
    if (failures.length > 0) {
        throw new Error(
            [
                "Strict assertion failed: updated config was not reflected in the generated output.",
                "Failed assertions:",
                ...failures,
            ].join("\n"),
        );
    }
}
 
/**
 * Assert that the draft page is not part of the production build.
 *
 * @param projectRoot Project root.
 * @param homepagePath Absolute path to `public/index.html`.
 */
async function assertDraftHiddenInProduction(
    projectRoot: string,
    homepagePath: string,
): Promise<void> {
    const draftOutputPath = join(projectRoot, "public", "foo", "index.html");
    await assertFileDoesNotExist(draftOutputPath);
 
    const homepageHtml = await readTextFile(homepagePath);
 
    if (/My First Post/i.test(homepageHtml)) {
        throw new Error(
            [
                "Strict assertion failed: draft post title was visible in the production homepage output.",
                `Homepage file: ${homepagePath}`,
            ].join("\n\n"),
        );
    }
}
 
/**
 * Determine whether a directory is the work tree of a Git repository.
 *
 * @param path Absolute directory path.
 * @returns True when `path` is inside a Git work tree.
 */
async function isGitWorkTree(path: string): Promise<boolean> {
    const result = await runCommand(
        "git",
        ["-C", path, "rev-parse", "--is-inside-work-tree"],
        path,
    );
 
    return result.code === 0 && result.stdout.trim() === "true";
}
 
/**
 * Copy the local theme working tree into the project's theme directory.
 *
 * When the source is a Git work tree, the file list is derived from Git so that
 * ignored paths (`node_modules`, `public`, generated resources, ...) are skipped
 * automatically while uncommitted and untracked-but-not-ignored changes are still
 * included. This makes the test reflect the exact state of the current branch.
 *
 * @param themePath Absolute path to the local theme source directory.
 * @param destination Absolute path to the theme directory inside the project.
 * @throws Error when the source contains no theme files.
 */
async function copyLocalTheme(
    themePath: string,
    destination: string,
): Promise<void> {
    if (await isGitWorkTree(themePath)) {
        const listing = await runCommand(
            "git",
            [
                "-C",
                themePath,
                "ls-files",
                "-z",
                "--cached",
                "--others",
                "--exclude-standard",
            ],
            themePath,
        );
 
        if (listing.code !== 0) {
            throw new Error(
                `Failed to list theme files via git in ${themePath}:\n${listing.stderr}`,
            );
        }
 
        const relativePaths = listing.stdout.split("\0").filter(Boolean);
 
        if (relativePaths.length === 0) {
            throw new Error(`No theme files found in ${themePath}`);
        }
 
        for (const relativePath of relativePaths) {
            const source = join(themePath, relativePath);
 
            try {
                const stats = await stat(source);
                if (!stats.isFile()) {
                    continue;
                }
            } catch {
                // Tracked but deleted in the work tree: nothing to copy.
                continue;
            }
 
            const target = join(destination, relativePath);
            await mkdir(dirname(target), { recursive: true });
            await copyFile(source, target);
        }
 
        return;
    }
 
    // Fallback for a non-Git source directory: copy recursively while excluding
    // heavy or generated paths that would never ship with the theme.
    const excludedNames = new Set(["node_modules", "public", ".git"]);
    await cp(themePath, destination, {
        recursive: true,
        filter: (source: string): boolean => {
            if (excludedNames.has(basename(source))) {
                return false;
            }
 
            return !source.includes(join("resources", "_gen"));
        },
    });
}
 
/**
 * Install the theme into the temporary project, either from the local working
 * tree (default) or from the published remote via a Git submodule.
 *
 * @param options Runtime options.
 * @param projectRoot Absolute path to the temporary quickstart project.
 * @param reports Accumulated step reports (appended to in submodule mode).
 * @throws Error when installation fails or the theme is incomplete.
 */
async function installTheme(
    options: RoutineOptions,
    projectRoot: string,
    reports: StepReport[],
): Promise<void> {
    const destination = join(projectRoot, options.themeDir);
 
    if (options.verbose) {
        console.log(`\n[RUN] Install theme (source: ${options.themeSource})`);
    }
 
    if (options.themeSource === "submodule") {
        const step: StepDefinition = {
            name: "Add theme as Git submodule",
            command: "git",
            args: ["submodule", "add", options.themeRepo, options.themeDir],
            cwd: projectRoot,
            expectedFiles: [options.themeDir, ".gitmodules"],
        };
        const report = await executeStep(step);
        reports.push(report);
 
        if (options.verbose) {
            console.log(
                `[OK ] ${step.name} (${report.result.durationMs} ms, exit ${String(report.result.code)})`,
            );
        }
 
        return;
    }
 
    const started = Date.now();
    await copyLocalTheme(options.themePath, destination);
 
    // Sanity check: a usable theme must at least expose theme.toml and layouts.
    await assertFileExists(join(destination, "theme.toml"));
    await assertFileExists(join(destination, "layouts"));
 
    if (options.verbose) {
        console.log(
            `[OK ] Copied local theme from ${options.themePath} (${Date.now() - started} ms)`,
        );
    }
}
 
/**
 * Run a list of command steps with consistent logging and reporting.
 *
 * @param steps Steps to execute in order.
 * @param options Runtime options.
 * @param projectRoot Absolute path to the temporary quickstart project.
 * @param reports Accumulated step reports (appended to).
 */
async function runSteps(
    steps: StepDefinition[],
    options: RoutineOptions,
    projectRoot: string,
    reports: StepReport[],
): Promise<void> {
    for (const step of steps) {
        if (options.verbose) {
            console.log(`\n[RUN] ${step.name}`);
            console.log(`      ${formatCommand(step.command, step.args)}`);
        }
 
        const report = isHugoBuildCommand(step)
            ? await executeHugoBuildStep(step, projectRoot)
            : await executeStep(step);
 
        reports.push(report);
 
        if (options.verbose) {
            console.log(
                `[OK ] ${step.name} (${report.result.durationMs} ms, exit ${String(report.result.code)})`,
            );
 
            const trimmedOutput = report.result.combined.trim();
            if (trimmedOutput) {
                console.log(trimmedOutput);
            }
        }
    }
}
 
/**
 * Run the full Hugo quickstart verification routine.
 *
 * @param options Runtime options.
 * @returns Process exit code.
 */
async function runRoutine(options: RoutineOptions): Promise<number> {
    const sandboxRoot = await mkdtemp(join(tmpdir(), "hugo-quickstart-"));
    const projectRoot = join(sandboxRoot, options.projectName);
 
    const reports: StepReport[] = [];
 
    // Steps that prepare the project before the theme is installed.
    const setupSteps: StepDefinition[] = [
        {
            name: "Create Hugo project",
            command: "hugo",
            args: ["new", "project", options.projectName],
            cwd: sandboxRoot,
            expectedFiles: [join(options.projectName, options.configFile)],
        },
        {
            name: "Initialise Git repository",
            command: "git",
            args: ["init"],
            cwd: projectRoot,
            expectedFiles: [".git"],
        },
    ];
 
    // Steps that run once the theme is in place.
    const buildSteps: StepDefinition[] = [
        {
            name: "Configure theme in Hugo config",
            command: "bash",
            args: [
                "-lc",
                `printf "\\ntheme = '${options.themeName}'\\n" >> ${JSON.stringify(options.configFile)}`,
            ],
            cwd: projectRoot,
            expectedFiles: [options.configFile],
        },
        {
            name: "Build site",
            command: "hugo",
            args: [],
            cwd: projectRoot,
            expectedFiles: ["public/index.html"],
        },
    ];
 
    try {
        console.log(`Test root: ${sandboxRoot}`);
        console.log(`Project root: ${projectRoot}`);
        console.log(
            options.themeSource === "submodule"
                ? `Theme source: submodule (${options.themeRepo})`
                : `Theme source: local (${options.themePath})`,
        );
 
        await runSteps(setupSteps, options, projectRoot, reports);
        await installTheme(options, projectRoot, reports);
        await runSteps(buildSteps, options, projectRoot, reports);
 
        const configPath = join(projectRoot, options.configFile);
        const homepagePath = join(projectRoot, "public/index.html");
        const contentPath = join(projectRoot, "content/foo.md");
        const draftOutputPath = join(projectRoot, "public", "foo", "index.html");
 
        console.log("\n[RUN] Strict config assertion");
        await assertThemeConfigured(configPath, options.themeName);
        console.log("[OK ] Strict config assertion");
 
        console.log("\n[RUN] Strict homepage assertion");
        await assertHomepageLooksValid(homepagePath);
        console.log("[OK ] Strict homepage assertion");
 
        console.log("\n[RUN] Create sample content");
        const createContentStep: StepDefinition = {
            name: "Create sample content",
            command: "hugo",
            args: ["new", "foo.md"],
            cwd: projectRoot,
            expectedFiles: ["content/foo.md"],
        };
        const createContentReport = await executeStep(createContentStep);
        reports.push(createContentReport);
 
        if (options.verbose) {
            console.log(
                `      ${formatCommand(createContentStep.command, createContentStep.args)}`,
            );
            console.log(
                `[OK ] ${createContentStep.name} (${createContentReport.result.durationMs} ms, exit ${String(createContentReport.result.code)})`,
            );
 
            const trimmedOutput = createContentReport.result.combined.trim();
            if (trimmedOutput) {
                console.log(trimmedOutput);
            }
        }
 
        console.log("\n[RUN] Replace generated content with quickstart sample");
        await replaceGeneratedContent(contentPath);
        console.log("[OK ] Replace generated content with quickstart sample");
 
        console.log("\n[RUN] Build drafts and verify rendered draft content");
        const draftBuildStep: StepDefinition = {
            name: "Build site with drafts",
            command: "hugo",
            args: ["--buildDrafts"],
            cwd: projectRoot,
            expectedFiles: ["public/index.html", "public/foo/index.html"],
        };
        const draftBuildReport = await executeHugoBuildStep(
            draftBuildStep,
            projectRoot,
        );
        reports.push(draftBuildReport);
 
        if (options.verbose) {
            console.log(
                `      ${formatCommand(draftBuildStep.command, draftBuildStep.args)}`,
            );
            console.log(
                `[OK ] ${draftBuildStep.name} (${draftBuildReport.result.durationMs} ms, exit ${String(draftBuildReport.result.code)})`,
            );
 
            const trimmedOutput = draftBuildReport.result.combined.trim();
            if (trimmedOutput) {
                console.log(trimmedOutput);
            }
        }
 
        const draftPageHtml = await readTextFile(draftOutputPath);
        assertDraftPageRendered(draftPageHtml);
        console.log("[OK ] Build drafts and verify rendered draft content");
 
        console.log("\n[RUN] Replace root hugo.toml with quickstart config");
        await replaceHugoConfig(configPath, options.themeName);
        console.log("[OK ] Replace root hugo.toml with quickstart config");
 
        console.log("\n[RUN] Build drafts and verify updated title and locale");
        const configBuildStep: StepDefinition = {
            name: "Build site with updated config and drafts",
            command: "hugo",
            args: ["--buildDrafts"],
            cwd: projectRoot,
            expectedFiles: ["public/index.html", "public/foo/index.html"],
        };
        const configBuildReport = await executeHugoBuildStep(
            configBuildStep,
            projectRoot,
        );
        reports.push(configBuildReport);
 
        if (options.verbose) {
            console.log(
                `      ${formatCommand(configBuildStep.command, configBuildStep.args)}`,
            );
            console.log(
                `[OK ] ${configBuildStep.name} (${configBuildReport.result.durationMs} ms, exit ${String(configBuildReport.result.code)})`,
            );
 
            const trimmedOutput = configBuildReport.result.combined.trim();
            if (trimmedOutput) {
                console.log(trimmedOutput);
            }
        }
 
        const updatedHomepageHtml = await readTextFile(homepagePath);
        assertUpdatedConfigInOutput(updatedHomepageHtml);
        console.log("[OK ] Build drafts and verify updated title and locale");
 
        console.log("\n[RUN] Production build should exclude draft content");
        const productionBuildStep: StepDefinition = {
            name: "Build production site without drafts",
            command: "hugo",
            args: [],
            cwd: projectRoot,
            expectedFiles: ["public/index.html"],
        };
        const productionBuildReport = await executeHugoBuildStep(
            productionBuildStep,
            projectRoot,
        );
        reports.push(productionBuildReport);
 
        if (options.verbose) {
            console.log(
                `      ${formatCommand(productionBuildStep.command, productionBuildStep.args)}`,
            );
            console.log(
                `[OK ] ${productionBuildStep.name} (${productionBuildReport.result.durationMs} ms, exit ${String(productionBuildReport.result.code)})`,
            );
 
            const trimmedOutput = productionBuildReport.result.combined.trim();
            if (trimmedOutput) {
                console.log(trimmedOutput);
            }
        }
 
        await assertDraftHiddenInProduction(projectRoot, homepagePath);
        console.log("[OK ] Production build should exclude draft content");
 
        console.log("\nResult: PASS");
 
        if (options.keepOnSuccess) {
            console.log(`Keeping successful test directory: ${projectRoot}`);
        } else {
            await rm(sandboxRoot, { recursive: true, force: true });
            console.log(`Deleted successful test directory: ${sandboxRoot}`);
        }
 
        return 0;
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : "Unknown error";
 
        console.error("\nResult: FAIL");
        console.error(message);
 
        if (reports.length > 0) {
            console.error("\nCompleted command steps before failure:");
            for (const report of reports) {
                console.error(`- ${report.step}`);
            }
        }
 
        if (options.keepOnFailure) {
            console.error(
                `\nKept failing test directory for inspection: ${projectRoot}`,
            );
        } else {
            await rm(sandboxRoot, { recursive: true, force: true });
            console.error(`\nDeleted failing test directory: ${sandboxRoot}`);
        }
 
        return 1;
    }
}
 
/**
 * Main entry point.
 */
async function main(): Promise<void> {
    try {
        const options = parseArgs(process.argv.slice(2));
        const exitCode = await runRoutine(options);
        process.exit(exitCode);
    } catch (error: unknown) {
        const message =
            error instanceof Error ? error.message : "Unknown fatal error";
        console.error(`Fatal error: ${message}`);
        process.exit(1);
    }
}
 
await main();