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 ".github/pull_request_template.txt",
15 ".github/PULL_REQUEST_TEMPLATE.txt",
16 "pull_request_template.md",
17 "PULL_REQUEST_TEMPLATE.md",
18 "pull_request_template.txt",
19 "PULL_REQUEST_TEMPLATE.txt",
20 "docs/pull_request_template.md",
21 "docs/PULL_REQUEST_TEMPLATE.md",
22 "docs/pull_request_template.txt",
23 "docs/PULL_REQUEST_TEMPLATE.txt",
24] as const;
25
26const TEMPLATE_DIRECTORIES = [
27 ".github/PULL_REQUEST_TEMPLATE",
28 "PULL_REQUEST_TEMPLATE",
29 "docs/PULL_REQUEST_TEMPLATE",
30] as const;
31
32type ExecuteGit = SourceControlHost.SourceControlHost["Service"]["git"]["execute"];
33
34interface TemplateTreeEntry {
35 readonly objectId: string;
36 readonly path: string;
37}
38
39function parseTemplateTreeEntries(output: string): ReadonlyArray<TemplateTreeEntry> {
40 const entries: TemplateTreeEntry[] = [];
41 for (const record of output.split("\0")) {
42 if (record.length === 0) {
43 continue;
44 }
45
46 const separator = record.indexOf("\t");
47 if (separator < 0) {
48 continue;
49 }
50
51 const [mode, type, objectId] = record.slice(0, separator).split(" ");
52 if (
53 type !== "blob" ||
54 (mode !== "100644" && mode !== "100755") ||
55 !objectId ||
56 !/^[0-9a-f]{40,64}$/.test(objectId)
57 ) {
58 continue;
59 }
60
61 entries.push({ objectId, path: record.slice(separator + 1) });
62 }
63 return entries;
64}
65
66function readTemplateBlob(input: {
67 readonly cwd: string;
68 readonly executeGit: ExecuteGit;
69 readonly entry: TemplateTreeEntry;
70}): Effect.Effect<Option.Option<string>, GitCommandError> {
71 return input
72 .executeGit({
73 operation: "gitHubChangeRequestTemplate.readTemplateBlob",
74 cwd: input.cwd,
75 args: ["cat-file", "blob", input.entry.objectId],
76 maxOutputBytes: TEMPLATE_MAX_BYTES,
77 appendTruncationMarker: true,
78 })
79 .pipe(
80 Effect.map((result) => {
81 const template = result.stdout.trim();
82 if (template.length === 0) {
83 return Option.none();
84 }
85 return Option.some(
86 result.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER)
87 ? `${template}\n\n${TRUNCATION_MARKER}`
88 : template,
89 );
90 }),
91 );
92}
93
94type DirectoryTemplateResult =
95 | { readonly _tag: "None" }
96 | { readonly _tag: "Ambiguous" }
97 | { readonly _tag: "Template"; readonly template: string };
98
99const readTemplateDirectory = Effect.fn("gitHubChangeRequestTemplate.readTemplateDirectory")(
100 function* (input: {
101 readonly cwd: string;
102 readonly executeGit: ExecuteGit;
103 readonly entries: ReadonlyArray<TemplateTreeEntry>;
104 readonly directory: string;
105 }): Effect.fn.Return<DirectoryTemplateResult, GitCommandError> {
106 const prefix = `${input.directory}/`;
107 const candidates = input.entries.filter((entry) => {
108 if (!entry.path.startsWith(prefix)) {
109 return false;
110 }
111 const relativePath = entry.path.slice(prefix.length);
112 return !relativePath.includes("/") && /\.(?:md|txt)$/i.test(relativePath);
113 });
114
115 const templates: string[] = [];
116 for (const entry of candidates) {
117 const template = yield* readTemplateBlob({ ...input, entry });
118 if (Option.isSome(template)) {
119 templates.push(template.value);
120 if (templates.length > 1) {
121 return { _tag: "Ambiguous" } as const;
122 }
123 }
124 }
125
126 return templates[0]
127 ? ({ _tag: "Template", template: templates[0] } as const)
128 : ({ _tag: "None" } as const);
129 },
130);
131
132export const detect = Effect.fn("gitHubChangeRequestTemplate.detect")(function* (
133 cwd: string,
134 treeish: string,
135 executeGit: ExecuteGit,
136) {
137 return yield* Effect.gen(function* () {
138 // Read committed regular blobs; worktree paths can become symlinks between validation and open.
139 // ls-tree does not support case-insensitive pathspecs; grep discovers only matching names.
140 const paths = yield* executeGit({
141 operation: "gitHubChangeRequestTemplate.findTemplatePaths",
142 cwd,
143 args: [
144 "grep",
145 "-G",
146 "--no-color",
147 "-l",
148 "-z",
149 "--full-name",
150 "--no-recurse-submodules",
151 "-e",
152 "^",
153 treeish,
154 "--",
155 ...TEMPLATE_PATHS.map((path) => `:(top,icase,literal)${path}`),
156 ],
157 maxOutputBytes: TREE_LIST_MAX_BYTES,
158 }).pipe(
159 Effect.map((result) =>
160 result.stdoutTruncated
161 ? []
162 : result.stdout
163 .split("\0")
164 .filter((path) => path.startsWith(`${treeish}:`))
165 .map((path) => path.slice(treeish.length + 1)),
166 ),
167 // grep exits with status 1 when no nonempty templates match.
168 Effect.orElseSucceed(() => []),
169 );
170 const result = yield* executeGit({
171 operation: "gitHubChangeRequestTemplate.listTemplates",
172 cwd,
173 args: [
174 "ls-tree",
175 "-r",
176 "-z",
177 "--full-tree",
178 treeish,
179 "--",
180 ...new Set([...TEMPLATE_PATHS, ...paths]),
181 ...TEMPLATE_DIRECTORIES,
182 ],
183 maxOutputBytes: TREE_LIST_MAX_BYTES,
184 appendTruncationMarker: true,
185 });
186 if (result.stdoutTruncated) {
187 return Option.none();
188 }
189
190 const entries = parseTemplateTreeEntries(result.stdout);
191 const candidates = [".github/", "", "docs/"].flatMap((location) => {
192 const paths = TEMPLATE_PATHS.filter(
193 (path) => path.slice(0, path.lastIndexOf("/") + 1) === location,
194 );
195 return [
196 ...paths.flatMap((path) => entries.filter((entry) => entry.path === path)),
197 ...entries.filter(
198 (entry) =>
199 !paths.some((path) => path === entry.path) &&
200 paths.some((path) => path.toLowerCase() === entry.path.toLowerCase()),
201 ),
202 ];
203 });
204 for (const entry of candidates) {
205 const template = yield* readTemplateBlob({ cwd, executeGit, entry });
206 if (Option.isSome(template)) {
207 return template;
208 }
209 }
210
211 for (const directory of TEMPLATE_DIRECTORIES) {
212 const directoryTemplate = yield* readTemplateDirectory({
213 cwd,
214 executeGit,
215 entries,
216 directory,
217 });
218 if (directoryTemplate._tag === "Template") {
219 return Option.some(directoryTemplate.template);
220 }
221 if (directoryTemplate._tag === "Ambiguous") {
222 return Option.none();
223 }
224 }
225
226 return Option.none();
227 }).pipe(Effect.orElseSucceed(() => Option.none()));
228});