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
95function readTemplateDirectory(input: {
96 readonly cwd: string;
97 readonly executeGit: ExecuteGit;
98 readonly entries: ReadonlyArray<TemplateTreeEntry>;
99 readonly directory: string;
100}): Effect.Effect<DirectoryTemplateResult, GitCommandError> {
101 return Effect.gen(function* () {
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 // Worktree paths can be replaced between validation and open. Read regular blobs from the
135 // committed base tree so repository-controlled symlinks and path races never reach the host filesystem.
136 const result = yield* executeGit({
137 operation: "gitHubChangeRequestTemplate.listTemplates",
138 cwd,
139 args: ["ls-tree", "-r", "-z", "--full-tree", treeish, "--", ...TREE_PATHS],
140 maxOutputBytes: TREE_LIST_MAX_BYTES,
141 appendTruncationMarker: true,
142 });
143 if (result.stdoutTruncated) {
144 return Option.none();
145 }
146
147 const entries = parseTemplateTreeEntries(result.stdout);
148 const entriesByPath = new Map(entries.map((entry) => [entry.path, entry]));
149 for (const templatePath of TEMPLATE_PATHS) {
150 const entry = entriesByPath.get(templatePath);
151 if (!entry) {
152 continue;
153 }
154 const template = yield* readTemplateBlob({ cwd, executeGit, entry });
155 if (Option.isSome(template)) {
156 return template;
157 }
158 }
159
160 for (const directory of TEMPLATE_DIRECTORIES) {
161 const directoryTemplate = yield* readTemplateDirectory({
162 cwd,
163 executeGit,
164 entries,
165 directory,
166 });
167 if (directoryTemplate._tag === "Template") {
168 return Option.some(directoryTemplate.template);
169 }
170 if (directoryTemplate._tag === "Ambiguous") {
171 return Option.none();
172 }
173 }
174
175 return Option.none();
176 }).pipe(Effect.orElseSucceed(() => Option.none()));
177});