Open History to see the last commit
1import type { GitCommandError } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4
5import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
6
7const TEMPLATE_MAX_BYTES = 8_000;
8const TREE_LIST_MAX_BYTES = 100_000;
9const TRUNCATION_MARKER = "[truncated]";
10
11const TEMPLATE_PATHS = [
12 ".github/pull_request_template.md",
13 ".github/PULL_REQUEST_TEMPLATE.md",
14 "pull_request_template.md",
15 "PULL_REQUEST_TEMPLATE.md",
16 "docs/pull_request_template.md",
17 "docs/PULL_REQUEST_TEMPLATE.md",
18] as const;
19
20const TEMPLATE_DIRECTORIES = [
21 ".github/PULL_REQUEST_TEMPLATE",
22 "PULL_REQUEST_TEMPLATE",
23 "docs/PULL_REQUEST_TEMPLATE",
24] as const;
25
26const TREE_PATHS = [...TEMPLATE_PATHS, ...TEMPLATE_DIRECTORIES] as const;
27
28type ExecuteGit = SourceControlHost.SourceControlHost["Service"]["git"]["execute"];
29
30interface TemplateTreeEntry {
31 readonly objectId: string;
32 readonly path: string;
33}
34
35function parseTemplateTreeEntries(output: string): ReadonlyArray<TemplateTreeEntry> {
36 const entries: TemplateTreeEntry[] = [];
37 for (const record of output.split("\0")) {
38 if (record.length === 0) {
39 continue;
40 }
41
42 const separator = record.indexOf("\t");
43 if (separator < 0) {
44 continue;
45 }
46
47 const [mode, type, objectId] = record.slice(0, separator).split(" ");
48 if (
49 type !== "blob" ||
50 (mode !== "100644" && mode !== "100755") ||
51 !objectId ||
52 !/^[0-9a-f]{40,64}$/.test(objectId)
53 ) {
54 continue;
55 }
56
57 entries.push({ objectId, path: record.slice(separator + 1) });
58 }
59 return entries;
60}
61
62function readTemplateBlob(input: {
63 readonly cwd: string;
64 readonly executeGit: ExecuteGit;
65 readonly entry: TemplateTreeEntry;
66}): Effect.Effect<Option.Option<string>, GitCommandError> {
67 return input
68 .executeGit({
69 operation: "gitHubChangeRequestTemplate.readTemplateBlob",
70 cwd: input.cwd,
71 args: ["cat-file", "blob", input.entry.objectId],
72 maxOutputBytes: TEMPLATE_MAX_BYTES,
73 appendTruncationMarker: true,
74 })
75 .pipe(
76 Effect.map((result) => {
77 const template = result.stdout.trim();
78 if (template.length === 0) {
79 return Option.none();
80 }
81 return Option.some(
82 result.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER)
83 ? `${template}\n\n${TRUNCATION_MARKER}`
84 : template,
85 );
86 }),
87 );
88}
89
90type DirectoryTemplateResult =
91 | { readonly _tag: "None" }
92 | { readonly _tag: "Ambiguous" }
93 | { readonly _tag: "Template"; readonly template: string };
94
95const readTemplateDirectory = Effect.fn("gitHubChangeRequestTemplate.readTemplateDirectory")(
96 function* (input: {
97 readonly cwd: string;
98 readonly executeGit: ExecuteGit;
99 readonly entries: ReadonlyArray<TemplateTreeEntry>;
100 readonly directory: string;
101 }): Effect.fn.Return<DirectoryTemplateResult, GitCommandError> {
102 const prefix = `${input.directory}/`;
103 const candidates = input.entries.filter((entry) => {
104 if (!entry.path.startsWith(prefix)) {
105 return false;
106 }
107 const relativePath = entry.path.slice(prefix.length);
108 return !relativePath.includes("/") && relativePath.toLowerCase().endsWith(".md");
109 });
110
111 const templates: string[] = [];
112 for (const entry of candidates) {
113 const template = yield* readTemplateBlob({ ...input, entry });
114 if (Option.isSome(template)) {
115 templates.push(template.value);
116 if (templates.length > 1) {
117 return { _tag: "Ambiguous" } as const;
118 }
119 }
120 }
121
122 return templates[0]
123 ? ({ _tag: "Template", template: templates[0] } as const)
124 : ({ _tag: "None" } as const);
125 },
126);
127
128export const detect = Effect.fn("gitHubChangeRequestTemplate.detect")(function* (
129 cwd: string,
130 treeish: string,
131 executeGit: ExecuteGit,
132) {
133 return yield* Effect.gen(function* () {
134 // Read committed regular blobs; worktree paths can become symlinks between validation and open.
135 const result = yield* executeGit({
136 operation: "gitHubChangeRequestTemplate.listTemplates",
137 cwd,
138 args: ["ls-tree", "-r", "-z", "--full-tree", treeish, "--", ...TREE_PATHS],
139 maxOutputBytes: TREE_LIST_MAX_BYTES,
140 appendTruncationMarker: true,
141 });
142 if (result.stdoutTruncated) {
143 return Option.none();
144 }
145
146 const entries = parseTemplateTreeEntries(result.stdout);
147 const entriesByPath = new Map(entries.map((entry) => [entry.path, entry]));
148 for (const templatePath of TEMPLATE_PATHS) {
149 const entry = entriesByPath.get(templatePath);
150 if (!entry) {
151 continue;
152 }
153 const template = yield* readTemplateBlob({ cwd, executeGit, entry });
154 if (Option.isSome(template)) {
155 return template;
156 }
157 }
158
159 for (const directory of TEMPLATE_DIRECTORIES) {
160 const directoryTemplate = yield* readTemplateDirectory({
161 cwd,
162 executeGit,
163 entries,
164 directory,
165 });
166 if (directoryTemplate._tag === "Template") {
167 return Option.some(directoryTemplate.template);
168 }
169 if (directoryTemplate._tag === "Ambiguous") {
170 return Option.none();
171 }
172 }
173
174 return Option.none();
175 }).pipe(Effect.orElseSucceed(() => Option.none()));
176});