Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3
4import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
5
6// Forgejo's Markdown lookup order also preserves Gitea's root, .gitea, .github order.
7const TEMPLATE_PATHS = ["", ".forgejo/", ".gitea/", ".github/", "docs/"].flatMap((directory) => [
8 `${directory}PULL_REQUEST_TEMPLATE.md`,
9 `${directory}pull_request_template.md`,
10]);
11const TEMPLATE_MAX_BYTES = 8_000;
12const TREE_LIST_MAX_BYTES = 100_000;
13const TRUNCATION_MARKER = "[truncated]";
14
15type ExecuteGit = SourceControlHost.SourceControlHost["Service"]["git"]["execute"];
16
17export const detect = Effect.fn("forgejoChangeRequestTemplate.detect")(
18 function* (cwd: string, treeish: string, executeGit: ExecuteGit) {
19 const listing = yield* executeGit({
20 operation: "forgejoChangeRequestTemplate.listTemplates",
21 cwd,
22 args: ["ls-tree", "-z", "--full-tree", treeish, "--", ...TEMPLATE_PATHS],
23 maxOutputBytes: TREE_LIST_MAX_BYTES,
24 appendTruncationMarker: true,
25 });
26 if (listing.stdoutTruncated) {
27 return Option.none();
28 }
29
30 // Read only regular blobs from the target tree, including when the worktree has a symlink.
31 const objectsByPath = new Map<string, string>();
32 for (const record of listing.stdout.split("\0")) {
33 const entry = /^100(?:644|755) blob ([0-9a-f]{40,64})\t(.+)$/.exec(record);
34 if (entry?.[1] && entry[2]) {
35 objectsByPath.set(entry[2], entry[1]);
36 }
37 }
38
39 for (const path of TEMPLATE_PATHS) {
40 const objectId = objectsByPath.get(path);
41 if (!objectId) {
42 continue;
43 }
44 const blob = yield* executeGit({
45 operation: "forgejoChangeRequestTemplate.readTemplate",
46 cwd,
47 args: ["cat-file", "blob", objectId],
48 maxOutputBytes: TEMPLATE_MAX_BYTES,
49 appendTruncationMarker: true,
50 });
51 const template = blob.stdout.trim();
52 if (template.length > 0) {
53 return Option.some(
54 blob.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER)
55 ? `${template}\n\n${TRUNCATION_MARKER}`
56 : template,
57 );
58 }
59 }
60 return Option.none();
61 },
62 Effect.orElseSucceed(() => Option.none()),
63);