website
git clone https://git.pyrossh.dev/website
木 Personal website of pyrossh. Built with astrojs, shiki, vite.
778948f
— pyrossh
2026-07-07T11:31:05+05:30
feat: port business logic to @pyrossh/core package
- packages/shared/core/package.json +25 -0
- packages/shared/core/src/content.ts +47 -0
- packages/shared/core/src/files.ts +113 -0
- packages/shared/core/src/gitBug.ts +268 -0
- packages/shared/core/src/gitReader.ts +741 -0
- packages/shared/core/src/index.ts +21 -0
- packages/shared/core/src/markdown.ts +20 -0
- packages/shared/core/src/repoContent.ts +8 -0
- packages/shared/core/tsconfig.json +4 -0
- pnpm-lock.yaml +58 -0
packages/shared/core/package.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@pyrossh/core",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"types": "src/index.ts",
|
|
8
|
+
"dependencies": {
|
|
9
|
+
"@pyrossh/config": "workspace:*",
|
|
10
|
+
"@pyrossh/types": "workspace:*",
|
|
11
|
+
"diff": "^9.0.0",
|
|
12
|
+
"diff2html": "^3.4.52",
|
|
13
|
+
"gray-matter": "^4.0.3",
|
|
14
|
+
"pretty-bytes": "^7.1.0",
|
|
15
|
+
"rehype-expressive-code": "^0.44.0",
|
|
16
|
+
"rehype-stringify": "^10.0.1",
|
|
17
|
+
"remark-parse": "^11.0.0",
|
|
18
|
+
"remark-rehype": "^11.1.2",
|
|
19
|
+
"spamscanner": "^6.1.5",
|
|
20
|
+
"unified": "^11.0.5"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"vscode-icons": "https://github.com/vscode-icons/vscode-icons.git"
|
|
24
|
+
}
|
|
25
|
+
}
|
packages/shared/core/src/content.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import matter from "gray-matter";
|
|
2
|
+
import { REPOS } from "@pyrossh/config";
|
|
3
|
+
import type { RuntimeRepo, RuntimePost } from "@pyrossh/types";
|
|
4
|
+
import { renderMarkdown } from "./markdown";
|
|
5
|
+
|
|
6
|
+
const toDate = (value: unknown) => (value instanceof Date ? value : new Date(String(value)));
|
|
7
|
+
|
|
8
|
+
export const getRepos = (): RuntimeRepo[] =>
|
|
9
|
+
REPOS.map((repo) => ({ id: repo.title, data: { ...repo } }));
|
|
10
|
+
|
|
11
|
+
export const getRepo = (repoId?: string) => getRepos().find((repo) => repo.id === repoId);
|
|
12
|
+
|
|
13
|
+
const CONTENT_PREFIX = "content/";
|
|
14
|
+
|
|
15
|
+
export const getPosts = async (bucket: R2Bucket): Promise<RuntimePost[]> => {
|
|
16
|
+
const objects = await bucket.list({ prefix: CONTENT_PREFIX });
|
|
17
|
+
const posts: RuntimePost[] = [];
|
|
18
|
+
|
|
19
|
+
for (const obj of objects.objects) {
|
|
20
|
+
if (!obj.key.endsWith(".md") && !obj.key.endsWith(".mdx")) continue;
|
|
21
|
+
const file = await bucket.get(obj.key);
|
|
22
|
+
if (!file) continue;
|
|
23
|
+
const source = await file.text();
|
|
24
|
+
const parsed = matter(source);
|
|
25
|
+
const id = obj.key.replace(CONTENT_PREFIX, "").replace(/\.(md|mdx)$/, "");
|
|
26
|
+
|
|
27
|
+
posts.push({
|
|
28
|
+
id,
|
|
29
|
+
data: {
|
|
30
|
+
title: String(parsed.data.title ?? ""),
|
|
31
|
+
description: String(parsed.data.description ?? ""),
|
|
32
|
+
pubDate: toDate(parsed.data.pubDate),
|
|
33
|
+
updatedDate: parsed.data.updatedDate ? toDate(parsed.data.updatedDate) : undefined,
|
|
34
|
+
heroImage: parsed.data.heroImage ? String(parsed.data.heroImage) : undefined,
|
|
35
|
+
},
|
|
36
|
+
body: parsed.content,
|
|
37
|
+
html: await renderMarkdown(parsed.content),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return posts.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export const getPost = async (bucket: R2Bucket, postId?: string) => {
|
|
45
|
+
const posts = await getPosts(bucket);
|
|
46
|
+
return posts.find((post) => post.id === postId);
|
|
47
|
+
};
|
packages/shared/core/src/files.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { extensions as folderExtensions } from "vscode-icons/src/iconsManifest/supportedFolders.ts";
|
|
2
|
+
import { extensions as fileExtensions } from "vscode-icons/src/iconsManifest/supportedExtensions.ts";
|
|
3
|
+
|
|
4
|
+
export interface FileNode {
|
|
5
|
+
name: string;
|
|
6
|
+
path: string;
|
|
7
|
+
size: number;
|
|
8
|
+
ext: string;
|
|
9
|
+
absolutePath: string;
|
|
10
|
+
isDirectory: boolean;
|
|
11
|
+
children?: FileNode[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const sortAll = (a: FileNode, b: FileNode): number => {
|
|
15
|
+
if (a.isDirectory && !b.isDirectory) return -1;
|
|
16
|
+
if (!a.isDirectory && b.isDirectory) return 1;
|
|
17
|
+
return a.name.localeCompare(b.name);
|
|
18
|
+
};
|
|
19
|
+
export const sortChildren = (nodes: FileNode[]) => {
|
|
20
|
+
for (const node of nodes) {
|
|
21
|
+
if (node.isDirectory && node.children) {
|
|
22
|
+
node.children.sort(sortAll);
|
|
23
|
+
sortChildren(node.children);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return nodes.sort(sortAll);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const buildFileTree = (files: any[]): FileNode[] => {
|
|
30
|
+
const root: FileNode[] = [];
|
|
31
|
+
|
|
32
|
+
for (const file of files) {
|
|
33
|
+
const parts = file.name.split("/");
|
|
34
|
+
let currentLevel = root;
|
|
35
|
+
|
|
36
|
+
for (let i = 0; i < parts.length; i++) {
|
|
37
|
+
const part = parts[i];
|
|
38
|
+
const isLastPart = i === parts.length - 1;
|
|
39
|
+
const currentPath = parts.slice(0, i + 1).join("/");
|
|
40
|
+
|
|
41
|
+
let existingNode = currentLevel.find((node) => node.name === part);
|
|
42
|
+
|
|
43
|
+
if (!existingNode) {
|
|
44
|
+
const newNode: FileNode = {
|
|
45
|
+
name: part,
|
|
46
|
+
path: currentPath,
|
|
47
|
+
isDirectory: !isLastPart,
|
|
48
|
+
size: file.size,
|
|
49
|
+
ext: file.ext,
|
|
50
|
+
absolutePath: file.absolutePath,
|
|
51
|
+
};
|
|
52
|
+
if (!isLastPart) {
|
|
53
|
+
newNode.children = [];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
currentLevel.push(newNode);
|
|
57
|
+
existingNode = newNode;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (!isLastPart) {
|
|
61
|
+
currentLevel = existingNode.children!;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
return root;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
export const resolveFolderIcon = (foldername: string) => {
|
|
70
|
+
for (const item of folderExtensions.supported) {
|
|
71
|
+
if (item.extensions?.includes(foldername)) {
|
|
72
|
+
return item.icon;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return folderExtensions.default.folder?.icon;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
export const resolveFileIcon = (filename: string, fileExt: string) => {
|
|
79
|
+
const baseName = filename.split("/").pop() || filename;
|
|
80
|
+
|
|
81
|
+
for (const item of fileExtensions.supported) {
|
|
82
|
+
if (item.filename && item.extensions?.includes(baseName)) {
|
|
83
|
+
return item.icon;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
for (const item of fileExtensions.supported) {
|
|
88
|
+
if (item.extensions?.includes(fileExt)) {
|
|
89
|
+
return item.icon;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
for (const item of fileExtensions.supported) {
|
|
94
|
+
for (const lang of item.languages ?? []) {
|
|
95
|
+
if (lang?.knownExtensions?.includes(fileExt)) {
|
|
96
|
+
const langIds = Array.isArray(lang.ids) ? lang.ids : [lang.ids];
|
|
97
|
+
if (langIds.includes(fileExt)) {
|
|
98
|
+
return item.icon;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
for (const item of fileExtensions.supported) {
|
|
105
|
+
for (const lang of item.languages ?? []) {
|
|
106
|
+
if (lang?.knownExtensions?.includes(fileExt)) {
|
|
107
|
+
return item.icon;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return fileExtensions.default.file?.icon;
|
|
113
|
+
};
|
packages/shared/core/src/gitBug.ts
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
export type GitBugIssueState = "open" | "closed";
|
|
2
|
+
|
|
3
|
+
export interface GitBugIssue {
|
|
4
|
+
id: string;
|
|
5
|
+
title: string;
|
|
6
|
+
state: GitBugIssueState;
|
|
7
|
+
author?: string;
|
|
8
|
+
createdAt: string;
|
|
9
|
+
updatedAt: string;
|
|
10
|
+
labels: string[];
|
|
11
|
+
body?: string;
|
|
12
|
+
comments: GitBugComment[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface GitBugComment {
|
|
16
|
+
id: string;
|
|
17
|
+
author?: string;
|
|
18
|
+
createdAt: string;
|
|
19
|
+
body: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface GitBugIssuesResult {
|
|
23
|
+
issues: GitBugIssue[];
|
|
24
|
+
isAvailable: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type SpamScanner = typeof import("spamscanner").default.prototype;
|
|
28
|
+
|
|
29
|
+
const safeRepoId = (repoId: string) => {
|
|
30
|
+
if (!/^[a-zA-Z0-9._-]+$/.test(repoId)) {
|
|
31
|
+
throw new Error("Invalid repository id.");
|
|
32
|
+
}
|
|
33
|
+
return repoId;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const safeIssueId = (issueId: string) => {
|
|
37
|
+
if (!/^[a-f0-9]{16}$/.test(issueId)) {
|
|
38
|
+
throw new Error("Invalid issue id.");
|
|
39
|
+
}
|
|
40
|
+
return issueId;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const makeIssueId = () => crypto.randomUUID().replaceAll("-", "").slice(0, 16);
|
|
44
|
+
const issuesPrefix = (repoId: string) => `${safeRepoId(repoId)}/issues/`;
|
|
45
|
+
const issueKey = (repoId: string, issueId: string) =>
|
|
46
|
+
`${issuesPrefix(repoId)}${safeIssueId(issueId)}.json`;
|
|
47
|
+
let spamScanner: SpamScanner | undefined;
|
|
48
|
+
|
|
49
|
+
const normalizeLabels = (labels?: string[]) =>
|
|
50
|
+
labels?.map((label) => label.trim()).filter(Boolean) ?? [];
|
|
51
|
+
|
|
52
|
+
const safeHeaderValue = (value: string) => value.replaceAll(/[\r\n]+/g, " ").trim();
|
|
53
|
+
|
|
54
|
+
const getSpamScanner = async () => {
|
|
55
|
+
if (!spamScanner) {
|
|
56
|
+
try {
|
|
57
|
+
const { default: SpamScanner } = await import("spamscanner");
|
|
58
|
+
spamScanner = new SpamScanner({
|
|
59
|
+
enableAuthentication: false,
|
|
60
|
+
enableNsfwDetection: true,
|
|
61
|
+
enableReputation: true,
|
|
62
|
+
enableToxicityDetection: true,
|
|
63
|
+
timeout: 10_000,
|
|
64
|
+
});
|
|
65
|
+
} catch {
|
|
66
|
+
console.warn("Spam scanner not available (unsupported in Workers environment)");
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return spamScanner;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const makeSpamScanEmail = (input: {
|
|
75
|
+
subject: string;
|
|
76
|
+
body?: string;
|
|
77
|
+
author?: string;
|
|
78
|
+
labels?: string[];
|
|
79
|
+
}) => {
|
|
80
|
+
const author = input.author?.trim() || "anonymous";
|
|
81
|
+
return [
|
|
82
|
+
"From: git-bug <[email protected]>",
|
|
83
|
+
"To: [email protected]",
|
|
84
|
+
`Subject: ${safeHeaderValue(input.subject)}`,
|
|
85
|
+
`X-GitBug-Author: ${safeHeaderValue(author)}`,
|
|
86
|
+
input.labels?.length
|
|
87
|
+
? `X-GitBug-Labels: ${safeHeaderValue(input.labels.join(", "))}`
|
|
88
|
+
: undefined,
|
|
89
|
+
"",
|
|
90
|
+
input.body?.trim() ?? "",
|
|
91
|
+
]
|
|
92
|
+
.filter((line) => line !== undefined)
|
|
93
|
+
.join("\n");
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const assertNotSpam = async (input: {
|
|
97
|
+
subject: string;
|
|
98
|
+
body?: string;
|
|
99
|
+
author?: string;
|
|
100
|
+
labels?: string[];
|
|
101
|
+
}) => {
|
|
102
|
+
const scanner = await getSpamScanner();
|
|
103
|
+
if (!scanner) return;
|
|
104
|
+
|
|
105
|
+
const result = await scanner.scan(makeSpamScanEmail(input));
|
|
106
|
+
|
|
107
|
+
if (result.isSpam) {
|
|
108
|
+
throw new Error(`Spam detected: ${result.message}`);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const getObjectJson = async <T>(bucket: R2Bucket, key: string) => {
|
|
113
|
+
try {
|
|
114
|
+
const object = await bucket.get(key);
|
|
115
|
+
if (object === null) return undefined;
|
|
116
|
+
const body = await object.text();
|
|
117
|
+
return body ? (JSON.parse(body) as T) : undefined;
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (error && typeof error === "object" && "name" in error && error.name === "NoSuchKey") {
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const putIssue = async (bucket: R2Bucket, repoId: string, issue: GitBugIssue) => {
|
|
128
|
+
await bucket.put(issueKey(repoId, issue.id), JSON.stringify(issue, null, 2), {
|
|
129
|
+
httpMetadata: { contentType: "application/json; charset=utf-8" },
|
|
130
|
+
});
|
|
131
|
+
return issue;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
export const getGitBugIssues = async (
|
|
135
|
+
bucket: R2Bucket,
|
|
136
|
+
repoId: string,
|
|
137
|
+
): Promise<GitBugIssuesResult> => {
|
|
138
|
+
try {
|
|
139
|
+
const issues: GitBugIssue[] = [];
|
|
140
|
+
let cursor: string | undefined;
|
|
141
|
+
|
|
142
|
+
do {
|
|
143
|
+
const page = await bucket.list({
|
|
144
|
+
prefix: issuesPrefix(repoId),
|
|
145
|
+
cursor,
|
|
146
|
+
});
|
|
147
|
+
const pageIssues = await Promise.all(
|
|
148
|
+
page.objects
|
|
149
|
+
.filter((object) => object.key.endsWith(".json"))
|
|
150
|
+
.map(async (object) => {
|
|
151
|
+
return await getObjectJson<GitBugIssue>(bucket, object.key);
|
|
152
|
+
}),
|
|
153
|
+
);
|
|
154
|
+
|
|
155
|
+
issues.push(...pageIssues.filter((issue): issue is GitBugIssue => Boolean(issue)));
|
|
156
|
+
cursor = page.truncated ? page.cursor : undefined;
|
|
157
|
+
} while (cursor);
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
issues: issues.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)),
|
|
161
|
+
isAvailable: true,
|
|
162
|
+
};
|
|
163
|
+
} catch {
|
|
164
|
+
return {
|
|
165
|
+
issues: [],
|
|
166
|
+
isAvailable: false,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
export const getGitBugIssue = async (
|
|
172
|
+
bucket: R2Bucket,
|
|
173
|
+
repoId: string,
|
|
174
|
+
issueId: string,
|
|
175
|
+
): Promise<GitBugIssue | undefined> => {
|
|
176
|
+
return await getObjectJson<GitBugIssue>(bucket, issueKey(repoId, issueId));
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
export const createGitBugIssue = async (
|
|
180
|
+
bucket: R2Bucket,
|
|
181
|
+
repoId: string,
|
|
182
|
+
input: {
|
|
183
|
+
title: string;
|
|
184
|
+
body?: string;
|
|
185
|
+
author?: string;
|
|
186
|
+
labels?: string[];
|
|
187
|
+
},
|
|
188
|
+
) => {
|
|
189
|
+
const labels = normalizeLabels(input.labels);
|
|
190
|
+
await assertNotSpam({
|
|
191
|
+
subject: input.title,
|
|
192
|
+
body: input.body,
|
|
193
|
+
author: input.author,
|
|
194
|
+
labels,
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
const now = new Date().toISOString();
|
|
198
|
+
const issue: GitBugIssue = {
|
|
199
|
+
id: makeIssueId(),
|
|
200
|
+
title: input.title.trim(),
|
|
201
|
+
state: "open",
|
|
202
|
+
author: input.author?.trim() || "anonymous",
|
|
203
|
+
createdAt: now,
|
|
204
|
+
updatedAt: now,
|
|
205
|
+
labels,
|
|
206
|
+
body: input.body?.trim(),
|
|
207
|
+
comments: [],
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
return await putIssue(bucket, repoId, issue);
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
export const addGitBugIssueComment = async (
|
|
214
|
+
bucket: R2Bucket,
|
|
215
|
+
repoId: string,
|
|
216
|
+
issueId: string,
|
|
217
|
+
input: {
|
|
218
|
+
body: string;
|
|
219
|
+
author?: string;
|
|
220
|
+
},
|
|
221
|
+
) => {
|
|
222
|
+
const issue = await getGitBugIssue(bucket, repoId, issueId);
|
|
223
|
+
if (!issue) {
|
|
224
|
+
throw new Error("Issue not found.");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
await assertNotSpam({
|
|
228
|
+
subject: `Comment on ${issue.title}`,
|
|
229
|
+
body: input.body,
|
|
230
|
+
author: input.author,
|
|
231
|
+
labels: issue.labels,
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
const now = new Date().toISOString();
|
|
235
|
+
return await putIssue(bucket, repoId, {
|
|
236
|
+
...issue,
|
|
237
|
+
updatedAt: now,
|
|
238
|
+
comments: [
|
|
239
|
+
...issue.comments,
|
|
240
|
+
{
|
|
241
|
+
id: makeIssueId(),
|
|
242
|
+
author: input.author?.trim() || "anonymous",
|
|
243
|
+
createdAt: now,
|
|
244
|
+
body: input.body.trim(),
|
|
245
|
+
},
|
|
246
|
+
],
|
|
247
|
+
});
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
export const setGitBugIssueState = async (
|
|
251
|
+
bucket: R2Bucket,
|
|
252
|
+
repoId: string,
|
|
253
|
+
issueId: string,
|
|
254
|
+
state: GitBugIssueState,
|
|
255
|
+
author?: string,
|
|
256
|
+
) => {
|
|
257
|
+
const issue = await getGitBugIssue(bucket, repoId, issueId);
|
|
258
|
+
if (!issue) {
|
|
259
|
+
throw new Error("Issue not found.");
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return await putIssue(bucket, repoId, {
|
|
263
|
+
...issue,
|
|
264
|
+
author: author?.trim() || issue.author,
|
|
265
|
+
state,
|
|
266
|
+
updatedAt: new Date().toISOString(),
|
|
267
|
+
});
|
|
268
|
+
};
|
packages/shared/core/src/gitReader.ts
ADDED
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
import { type FileNode } from "./files";
|
|
2
|
+
|
|
3
|
+
export interface Commit {
|
|
4
|
+
hash: string;
|
|
5
|
+
message: string;
|
|
6
|
+
body: string;
|
|
7
|
+
author_name: string;
|
|
8
|
+
author_email: string;
|
|
9
|
+
date: string;
|
|
10
|
+
branches: string[];
|
|
11
|
+
tags: string[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface TreeEntry {
|
|
15
|
+
mode: string;
|
|
16
|
+
name: string;
|
|
17
|
+
oid: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface ParsedIdx {
|
|
21
|
+
fanout: Uint32Array;
|
|
22
|
+
names: Uint8Array;
|
|
23
|
+
offsets: Uint32Array;
|
|
24
|
+
resolvedOffsets: Float64Array;
|
|
25
|
+
packKey: string;
|
|
26
|
+
packSize?: number;
|
|
27
|
+
nextOffsetByIndex: Float64Array;
|
|
28
|
+
offsetToNextOffset: Map<number, number>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const hexToBytes = (hex: string): Uint8Array => {
|
|
32
|
+
const bytes = new Uint8Array(20);
|
|
33
|
+
for (let i = 0; i < 20; i++) {
|
|
34
|
+
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
35
|
+
}
|
|
36
|
+
return bytes;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const bytesToHex = (bytes: Uint8Array): string => {
|
|
40
|
+
return Array.from(bytes)
|
|
41
|
+
.map((b) => b.toString(16).padStart(2, "0"))
|
|
42
|
+
.join("");
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const compareBytes = (a: Uint8Array, b: Uint8Array): number => {
|
|
46
|
+
for (let i = 0; i < a.length && i < b.length; i++) {
|
|
47
|
+
if (a[i] !== b[i]) return a[i] - b[i];
|
|
48
|
+
}
|
|
49
|
+
return a.length - b.length;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const inflate = async (data: Uint8Array): Promise<Uint8Array> => {
|
|
53
|
+
const ds = new DecompressionStream("deflate");
|
|
54
|
+
const writer = ds.writable.getWriter();
|
|
55
|
+
writer.write(data);
|
|
56
|
+
writer.close();
|
|
57
|
+
const reader = ds.readable.getReader();
|
|
58
|
+
const chunks: Uint8Array[] = [];
|
|
59
|
+
while (true) {
|
|
60
|
+
const { done, value } = await reader.read();
|
|
61
|
+
if (done) break;
|
|
62
|
+
if (value) chunks.push(value);
|
|
63
|
+
}
|
|
64
|
+
const total = chunks.reduce((a, c) => a + c.length, 0);
|
|
65
|
+
const result = new Uint8Array(total);
|
|
66
|
+
let offset = 0;
|
|
67
|
+
for (const chunk of chunks) {
|
|
68
|
+
result.set(chunk, offset);
|
|
69
|
+
offset += chunk.length;
|
|
70
|
+
}
|
|
71
|
+
return result;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const readText = async (bucket: R2Bucket, key: string): Promise<string | null> => {
|
|
75
|
+
const obj = await bucket.get(key);
|
|
76
|
+
if (obj === null) return null;
|
|
77
|
+
return await obj.text();
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const readBytes = async (bucket: R2Bucket, key: string): Promise<Uint8Array | null> => {
|
|
81
|
+
const obj = await bucket.get(key);
|
|
82
|
+
if (obj === null) return null;
|
|
83
|
+
return await obj.bytes();
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const readRange = async (
|
|
87
|
+
bucket: R2Bucket,
|
|
88
|
+
key: string,
|
|
89
|
+
offset: number,
|
|
90
|
+
length: number,
|
|
91
|
+
): Promise<Uint8Array | null> => {
|
|
92
|
+
const obj = await bucket.get(key, { range: { offset, length } });
|
|
93
|
+
if (obj === null) return null;
|
|
94
|
+
return await obj.bytes();
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const resolvePackedRef = async (
|
|
98
|
+
bucket: R2Bucket,
|
|
99
|
+
repoId: string,
|
|
100
|
+
refPath: string,
|
|
101
|
+
): Promise<string | undefined> => {
|
|
102
|
+
const packed = await readText(bucket, `${repoId}/.git/packed-refs`);
|
|
103
|
+
if (packed === null) return undefined;
|
|
104
|
+
for (const line of packed.split("\n")) {
|
|
105
|
+
if (line.startsWith("#") || line.startsWith("^")) continue;
|
|
106
|
+
const space = line.indexOf(" ");
|
|
107
|
+
if (space === -1) continue;
|
|
108
|
+
if (line.slice(space + 1).trim() === refPath) {
|
|
109
|
+
return line.slice(0, space).trim() || undefined;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return undefined;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const resolveRef = async (bucket: R2Bucket, repoId: string): Promise<string | undefined> => {
|
|
116
|
+
const head = await readText(bucket, `${repoId}/.git/HEAD`);
|
|
117
|
+
if (head === null) return undefined;
|
|
118
|
+
const trimmed = head.trim();
|
|
119
|
+
if (trimmed.startsWith("ref: ")) {
|
|
120
|
+
const refPath = trimmed.slice(5);
|
|
121
|
+
const oid = await readText(bucket, `${repoId}/.git/${refPath}`);
|
|
122
|
+
if (oid) return oid.trim() || undefined;
|
|
123
|
+
return await resolvePackedRef(bucket, repoId, refPath);
|
|
124
|
+
}
|
|
125
|
+
return trimmed || undefined;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const parseIdx = (data: Uint8Array, packKey: string): ParsedIdx => {
|
|
129
|
+
const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
|
|
130
|
+
const fanout = new Uint32Array(256);
|
|
131
|
+
for (let i = 0; i < 256; i++) {
|
|
132
|
+
fanout[i] = view.getUint32(8 + i * 4);
|
|
133
|
+
}
|
|
134
|
+
const count = fanout[255];
|
|
135
|
+
const namesOffset = 8 + 256 * 4;
|
|
136
|
+
const names = data.slice(namesOffset, namesOffset + count * 20);
|
|
137
|
+
const crcOffset = namesOffset + count * 20;
|
|
138
|
+
const offsetOffset = crcOffset + count * 4;
|
|
139
|
+
const offsets = new Uint32Array(count);
|
|
140
|
+
const resolvedOffsets = new Float64Array(count);
|
|
141
|
+
let needsLarge = false;
|
|
142
|
+
for (let i = 0; i < count; i++) {
|
|
143
|
+
offsets[i] = view.getUint32(offsetOffset + i * 4);
|
|
144
|
+
if (offsets[i] & 0x80000000) needsLarge = true;
|
|
145
|
+
}
|
|
146
|
+
if (needsLarge) {
|
|
147
|
+
const largeOffsetOffset = offsetOffset + count * 4;
|
|
148
|
+
let largeIdx = 0;
|
|
149
|
+
for (let i = 0; i < count; i++) {
|
|
150
|
+
if (offsets[i] & 0x80000000) {
|
|
151
|
+
const v = view.getBigUint64(largeOffsetOffset + largeIdx * 8);
|
|
152
|
+
resolvedOffsets[i] = Number(v);
|
|
153
|
+
largeIdx++;
|
|
154
|
+
} else {
|
|
155
|
+
resolvedOffsets[i] = offsets[i];
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
} else {
|
|
159
|
+
for (let i = 0; i < count; i++) {
|
|
160
|
+
resolvedOffsets[i] = offsets[i];
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const sortedIndices = new Uint32Array(count);
|
|
165
|
+
for (let i = 0; i < count; i++) sortedIndices[i] = i;
|
|
166
|
+
sortedIndices.sort((a, b) => resolvedOffsets[a] - resolvedOffsets[b]);
|
|
167
|
+
|
|
168
|
+
const nextOffsetByIndex = new Float64Array(count);
|
|
169
|
+
const offsetToNextOffset = new Map<number, number>();
|
|
170
|
+
for (let si = 0; si < count; si++) {
|
|
171
|
+
const idx = sortedIndices[si];
|
|
172
|
+
const offset = resolvedOffsets[idx];
|
|
173
|
+
const nextSi = si + 1;
|
|
174
|
+
if (nextSi < count) {
|
|
175
|
+
const nextOffset = resolvedOffsets[sortedIndices[nextSi]];
|
|
176
|
+
nextOffsetByIndex[idx] = nextOffset;
|
|
177
|
+
offsetToNextOffset.set(offset, nextOffset);
|
|
178
|
+
} else {
|
|
179
|
+
nextOffsetByIndex[idx] = Infinity;
|
|
180
|
+
offsetToNextOffset.set(offset, Infinity);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
fanout,
|
|
186
|
+
names,
|
|
187
|
+
offsets,
|
|
188
|
+
resolvedOffsets,
|
|
189
|
+
packKey,
|
|
190
|
+
nextOffsetByIndex,
|
|
191
|
+
offsetToNextOffset,
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
const findOidInIdx = (idx: ParsedIdx, oidHex: string): number | undefined => {
|
|
196
|
+
const oidBytes = hexToBytes(oidHex);
|
|
197
|
+
const firstByte = oidBytes[0];
|
|
198
|
+
const lo = firstByte > 0 ? idx.fanout[firstByte - 1] : 0;
|
|
199
|
+
const hi = idx.fanout[firstByte];
|
|
200
|
+
let left = lo;
|
|
201
|
+
let right = hi;
|
|
202
|
+
while (left < right) {
|
|
203
|
+
const mid = Math.floor((left + right) / 2);
|
|
204
|
+
const midOid = idx.names.slice(mid * 20, mid * 20 + 20);
|
|
205
|
+
const cmp = compareBytes(midOid, oidBytes);
|
|
206
|
+
if (cmp < 0) left = mid + 1;
|
|
207
|
+
else if (cmp > 0) right = mid;
|
|
208
|
+
else return mid;
|
|
209
|
+
}
|
|
210
|
+
return undefined;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const getOffsetInIdx = (idx: ParsedIdx, index: number): number => {
|
|
214
|
+
return idx.resolvedOffsets[index];
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const parseVarint = (data: Uint8Array, offset: number): { value: number; size: number } => {
|
|
218
|
+
let value = 0;
|
|
219
|
+
let shift = 0;
|
|
220
|
+
let i = offset;
|
|
221
|
+
while (i < data.length) {
|
|
222
|
+
const byte = data[i];
|
|
223
|
+
value |= (byte & 0x7f) << shift;
|
|
224
|
+
shift += 7;
|
|
225
|
+
i++;
|
|
226
|
+
if (!(byte & 0x80)) break;
|
|
227
|
+
}
|
|
228
|
+
return { value, size: i - offset };
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const GIT_OBJECT_TYPES = ["", "commit", "tree", "blob", "tag"];
|
|
232
|
+
|
|
233
|
+
let idxCache: Map<string, ParsedIdx> | undefined;
|
|
234
|
+
let packIdxKeysCache: Map<string, string[]> | undefined;
|
|
235
|
+
|
|
236
|
+
const getPackIdxKeys = async (bucket: R2Bucket, repoId: string): Promise<string[]> => {
|
|
237
|
+
if (!packIdxKeysCache) packIdxKeysCache = new Map();
|
|
238
|
+
let keys = packIdxKeysCache.get(repoId);
|
|
239
|
+
if (keys) return keys;
|
|
240
|
+
const packPrefix = `${repoId}/.git/objects/pack/`;
|
|
241
|
+
const idxResult = await bucket.list({ prefix: packPrefix, delimiter: "/" });
|
|
242
|
+
keys = idxResult.objects.map((o) => o.key).filter((k) => k.endsWith(".idx"));
|
|
243
|
+
packIdxKeysCache.set(repoId, keys);
|
|
244
|
+
return keys;
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
const getParsedIdx = async (bucket: R2Bucket, idxKey: string): Promise<ParsedIdx | undefined> => {
|
|
248
|
+
if (!idxCache) idxCache = new Map();
|
|
249
|
+
let idx = idxCache.get(idxKey);
|
|
250
|
+
if (idx) return idx;
|
|
251
|
+
const data = await readBytes(bucket, idxKey);
|
|
252
|
+
if (data === null) return undefined;
|
|
253
|
+
const packKey = idxKey.replace(/\.idx$/, ".pack");
|
|
254
|
+
idx = parseIdx(data, packKey);
|
|
255
|
+
idxCache.set(idxKey, idx);
|
|
256
|
+
return idx;
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
const readRawObject = async (
|
|
260
|
+
bucket: R2Bucket,
|
|
261
|
+
repoId: string,
|
|
262
|
+
oid: string,
|
|
263
|
+
): Promise<{ type: string; payload: Uint8Array } | undefined> => {
|
|
264
|
+
const idxKeys = await getPackIdxKeys(bucket, repoId);
|
|
265
|
+
|
|
266
|
+
for (const idxKey of idxKeys) {
|
|
267
|
+
const idx = await getParsedIdx(bucket, idxKey);
|
|
268
|
+
if (!idx) continue;
|
|
269
|
+
const objectIndex = findOidInIdx(idx, oid);
|
|
270
|
+
if (objectIndex === undefined) continue;
|
|
271
|
+
|
|
272
|
+
const offset = getOffsetInIdx(idx, objectIndex);
|
|
273
|
+
return await readPackedObject(
|
|
274
|
+
bucket,
|
|
275
|
+
repoId,
|
|
276
|
+
idx.packKey,
|
|
277
|
+
offset,
|
|
278
|
+
new Set(),
|
|
279
|
+
idx.nextOffsetByIndex[objectIndex],
|
|
280
|
+
idx.offsetToNextOffset,
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
return undefined;
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
const readPackedObject = async (
|
|
287
|
+
bucket: R2Bucket,
|
|
288
|
+
repoId: string,
|
|
289
|
+
packKey: string,
|
|
290
|
+
offset: number,
|
|
291
|
+
visited: Set<string>,
|
|
292
|
+
nextOffset?: number,
|
|
293
|
+
offsetToNextOffset?: Map<number, number>,
|
|
294
|
+
): Promise<{ type: string; payload: Uint8Array } | undefined> => {
|
|
295
|
+
const maxRead =
|
|
296
|
+
nextOffset && nextOffset !== Infinity
|
|
297
|
+
? Math.min(nextOffset - offset, 5 * 1024 * 1024)
|
|
298
|
+
: 5 * 1024 * 1024;
|
|
299
|
+
const headerBuf = await readRange(bucket, packKey, offset, Math.min(128, maxRead));
|
|
300
|
+
if (headerBuf === null) return undefined;
|
|
301
|
+
|
|
302
|
+
const { value: typeSize, size: hdrSize } = parseVarint(headerBuf, 0);
|
|
303
|
+
const type = (typeSize >> 4) & 0x07;
|
|
304
|
+
|
|
305
|
+
if (type === 6) {
|
|
306
|
+
let i = hdrSize;
|
|
307
|
+
let byte = headerBuf[i++];
|
|
308
|
+
let negOffset = byte & 0x7f;
|
|
309
|
+
while (byte & 0x80) {
|
|
310
|
+
negOffset += 1;
|
|
311
|
+
byte = headerBuf[i++];
|
|
312
|
+
negOffset = (negOffset << 7) + (byte & 0x7f);
|
|
313
|
+
}
|
|
314
|
+
const ofsSize = i - hdrSize;
|
|
315
|
+
const baseOffset = offset - negOffset;
|
|
316
|
+
const objStart = offset + hdrSize + ofsSize;
|
|
317
|
+
const dataLen = nextOffset
|
|
318
|
+
? Math.min(nextOffset - objStart, maxRead - hdrSize - ofsSize)
|
|
319
|
+
: maxRead;
|
|
320
|
+
const compressed = await readRange(bucket, packKey, objStart, dataLen);
|
|
321
|
+
if (compressed === null) return undefined;
|
|
322
|
+
const inflated = await inflate(compressed);
|
|
323
|
+
const baseNextOffset = offsetToNextOffset?.get(baseOffset);
|
|
324
|
+
const base = await readPackedObject(
|
|
325
|
+
bucket,
|
|
326
|
+
repoId,
|
|
327
|
+
packKey,
|
|
328
|
+
baseOffset,
|
|
329
|
+
visited,
|
|
330
|
+
baseNextOffset,
|
|
331
|
+
offsetToNextOffset,
|
|
332
|
+
);
|
|
333
|
+
if (!base) return undefined;
|
|
334
|
+
return { type: base.type, payload: applyDelta(inflated, base.payload) };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (type === 7) {
|
|
338
|
+
const baseOid = bytesToHex(headerBuf.slice(hdrSize, hdrSize + 20));
|
|
339
|
+
if (visited.has(baseOid)) return undefined;
|
|
340
|
+
visited.add(baseOid);
|
|
341
|
+
const objStart = offset + hdrSize + 20;
|
|
342
|
+
const dataLen = nextOffset ? Math.min(nextOffset - objStart, maxRead - hdrSize - 20) : maxRead;
|
|
343
|
+
const compressed = await readRange(bucket, packKey, objStart, dataLen);
|
|
344
|
+
if (compressed === null) return undefined;
|
|
345
|
+
const inflated = await inflate(compressed);
|
|
346
|
+
const base = await readRawObject(bucket, repoId, baseOid);
|
|
347
|
+
if (!base) return undefined;
|
|
348
|
+
return { type: base.type, payload: applyDelta(inflated, base.payload) };
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const objStart = offset + hdrSize;
|
|
352
|
+
const dataLen = nextOffset ? nextOffset - objStart : maxRead;
|
|
353
|
+
const compressed = await readRange(bucket, packKey, objStart, dataLen);
|
|
354
|
+
if (compressed === null) return undefined;
|
|
355
|
+
const payload = await inflate(compressed);
|
|
356
|
+
const typeName = GIT_OBJECT_TYPES[type] || "unknown";
|
|
357
|
+
return { type: typeName, payload };
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
const applyDelta = (delta: Uint8Array, base: Uint8Array): Uint8Array => {
|
|
361
|
+
let i = 0;
|
|
362
|
+
const { value: baseSize, size: bs } = parseVarint(delta, i);
|
|
363
|
+
i += bs;
|
|
364
|
+
const { value: resultSize, size: rs } = parseVarint(delta, i);
|
|
365
|
+
i += rs;
|
|
366
|
+
|
|
367
|
+
const result = new Uint8Array(resultSize);
|
|
368
|
+
let outPos = 0;
|
|
369
|
+
|
|
370
|
+
while (i < delta.length) {
|
|
371
|
+
const cmd = delta[i];
|
|
372
|
+
i++;
|
|
373
|
+
if (cmd & 0x80) {
|
|
374
|
+
let copyOffset = 0;
|
|
375
|
+
let copySize = 0;
|
|
376
|
+
if (cmd & 0x01) copyOffset = delta[i++];
|
|
377
|
+
if (cmd & 0x02) copyOffset |= delta[i++] << 8;
|
|
378
|
+
if (cmd & 0x04) copyOffset |= delta[i++] << 16;
|
|
379
|
+
if (cmd & 0x08) copyOffset |= delta[i++] << 24;
|
|
380
|
+
if (cmd & 0x10) copySize = delta[i++];
|
|
381
|
+
if (cmd & 0x20) copySize |= delta[i++] << 8;
|
|
382
|
+
if (cmd & 0x40) copySize |= delta[i++] << 16;
|
|
383
|
+
if (copySize === 0) copySize = 0x10000;
|
|
384
|
+
for (let j = 0; j < copySize; j++) {
|
|
385
|
+
result[outPos + j] = base[copyOffset + j];
|
|
386
|
+
}
|
|
387
|
+
outPos += copySize;
|
|
388
|
+
} else {
|
|
389
|
+
for (let j = 0; j < cmd; j++) {
|
|
390
|
+
result[outPos + j] = delta[i + j];
|
|
391
|
+
}
|
|
392
|
+
i += cmd;
|
|
393
|
+
outPos += cmd;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
return result;
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
const readGitObject = async (
|
|
401
|
+
bucket: R2Bucket,
|
|
402
|
+
repoId: string,
|
|
403
|
+
oid: string,
|
|
404
|
+
): Promise<{ type: string; payload: Uint8Array } | undefined> => {
|
|
405
|
+
return await readRawObject(bucket, repoId, oid);
|
|
406
|
+
};
|
|
407
|
+
|
|
408
|
+
const parseCommit = (
|
|
409
|
+
payload: Uint8Array,
|
|
410
|
+
): {
|
|
411
|
+
tree: string;
|
|
412
|
+
parents: string[];
|
|
413
|
+
message: string;
|
|
414
|
+
author?: { name: string; email: string; when: string };
|
|
415
|
+
} => {
|
|
416
|
+
const text = new TextDecoder().decode(payload);
|
|
417
|
+
const lines = text.split("\n");
|
|
418
|
+
let i = 0;
|
|
419
|
+
let tree = "";
|
|
420
|
+
const parents: string[] = [];
|
|
421
|
+
let author: { name: string; email: string; when: string } | undefined;
|
|
422
|
+
|
|
423
|
+
while (i < lines.length && lines[i] !== "") {
|
|
424
|
+
const line = lines[i];
|
|
425
|
+
if (line.startsWith("tree ")) tree = line.slice(5);
|
|
426
|
+
else if (line.startsWith("parent ")) parents.push(line.slice(7));
|
|
427
|
+
else if (line.startsWith("author ")) {
|
|
428
|
+
const match = line.slice(7).match(/^(.*?) <(.*?)> (\d+)/);
|
|
429
|
+
if (match) author = { name: match[1], email: match[2], when: match[3] };
|
|
430
|
+
}
|
|
431
|
+
i++;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const message = lines
|
|
435
|
+
.slice(i + 1)
|
|
436
|
+
.join("\n")
|
|
437
|
+
.trim();
|
|
438
|
+
return { tree, parents, message, author };
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
const parseTree = (payload: Uint8Array): TreeEntry[] => {
|
|
442
|
+
const entries: TreeEntry[] = [];
|
|
443
|
+
let offset = 0;
|
|
444
|
+
while (offset < payload.length) {
|
|
445
|
+
const nullByte = payload.indexOf(0, offset);
|
|
446
|
+
if (nullByte === -1) break;
|
|
447
|
+
const header = new TextDecoder().decode(payload.slice(offset, nullByte));
|
|
448
|
+
const space = header.indexOf(" ");
|
|
449
|
+
if (space === -1) break;
|
|
450
|
+
const mode = header.slice(0, space);
|
|
451
|
+
const name = header.slice(space + 1);
|
|
452
|
+
offset = nullByte + 1;
|
|
453
|
+
const oidBytes = payload.slice(offset, offset + 20);
|
|
454
|
+
if (oidBytes.length < 20) break;
|
|
455
|
+
const oid = bytesToHex(oidBytes);
|
|
456
|
+
entries.push({ mode, name, oid });
|
|
457
|
+
offset += 20;
|
|
458
|
+
}
|
|
459
|
+
return entries;
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
const buildCommit = (oid: string, parsed: ReturnType<typeof parseCommit>): Commit => ({
|
|
463
|
+
hash: oid,
|
|
464
|
+
message: parsed.message.split("\n")[0],
|
|
465
|
+
body: parsed.message,
|
|
466
|
+
author_name: parsed.author?.name ?? "",
|
|
467
|
+
author_email: parsed.author?.email ?? "",
|
|
468
|
+
date: parsed.author?.when ? new Date(parseInt(parsed.author.when) * 1000).toISOString() : "",
|
|
469
|
+
branches: [],
|
|
470
|
+
tags: [],
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
export const getCommits = async (bucket: R2Bucket, repoId: string): Promise<Commit[]> => {
|
|
474
|
+
const cached = await bucket.get(`${repoId}/.git/commits.json`);
|
|
475
|
+
if (cached) {
|
|
476
|
+
return (await cached.json()) as Commit[];
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const headOid = await resolveRef(bucket, repoId);
|
|
480
|
+
if (!headOid) return [];
|
|
481
|
+
|
|
482
|
+
const commits: Commit[] = [];
|
|
483
|
+
let oid: string | undefined = headOid;
|
|
484
|
+
|
|
485
|
+
while (oid) {
|
|
486
|
+
const obj = await readGitObject(bucket, repoId, oid);
|
|
487
|
+
if (!obj || obj.type !== "commit") break;
|
|
488
|
+
const parsed = parseCommit(obj.payload);
|
|
489
|
+
commits.push(buildCommit(oid, parsed));
|
|
490
|
+
oid = parsed.parents[0];
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return commits;
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
export const getFiles = async (bucket: R2Bucket, repoId: string): Promise<FileNode[]> => {
|
|
497
|
+
const cached = await bucket.get(`${repoId}/.git/files.json`);
|
|
498
|
+
if (cached) {
|
|
499
|
+
return (await cached.json()) as FileNode[];
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const prefix = `${repoId}/`;
|
|
503
|
+
const files: FileNode[] = [];
|
|
504
|
+
let cursor: string | undefined;
|
|
505
|
+
|
|
506
|
+
do {
|
|
507
|
+
const result = await bucket.list({ prefix, cursor });
|
|
508
|
+
for (const obj of result.objects) {
|
|
509
|
+
const key = obj.key;
|
|
510
|
+
if (key.startsWith(`${prefix}.git`)) continue;
|
|
511
|
+
if (key.endsWith("/")) continue;
|
|
512
|
+
|
|
513
|
+
const relativePath = key.slice(prefix.length);
|
|
514
|
+
if (!relativePath) continue;
|
|
515
|
+
|
|
516
|
+
const extIndex = relativePath.lastIndexOf(".");
|
|
517
|
+
const ext = extIndex >= 0 ? relativePath.slice(extIndex + 1) : "";
|
|
518
|
+
|
|
519
|
+
files.push({
|
|
520
|
+
name: relativePath,
|
|
521
|
+
path: relativePath,
|
|
522
|
+
ext,
|
|
523
|
+
size: obj.size,
|
|
524
|
+
isDirectory: false,
|
|
525
|
+
absolutePath: relativePath,
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
cursor = result.truncated ? result.cursor : undefined;
|
|
529
|
+
} while (cursor);
|
|
530
|
+
|
|
531
|
+
return files;
|
|
532
|
+
};
|
|
533
|
+
|
|
534
|
+
const fileOidInTree = async (
|
|
535
|
+
bucket: R2Bucket,
|
|
536
|
+
repoId: string,
|
|
537
|
+
treeOid: string,
|
|
538
|
+
filePath: string,
|
|
539
|
+
): Promise<string | undefined> => {
|
|
540
|
+
const parts = filePath.split("/");
|
|
541
|
+
let currentTree = treeOid;
|
|
542
|
+
for (const part of parts) {
|
|
543
|
+
const obj = await readGitObject(bucket, repoId, currentTree);
|
|
544
|
+
if (!obj || obj.type !== "tree") return undefined;
|
|
545
|
+
const entries = parseTree(obj.payload);
|
|
546
|
+
const entry = entries.find((e) => e.name === part);
|
|
547
|
+
if (!entry) return undefined;
|
|
548
|
+
if (part === parts[parts.length - 1]) return entry.oid;
|
|
549
|
+
if (entry.mode !== "40000") return undefined;
|
|
550
|
+
currentTree = entry.oid;
|
|
551
|
+
}
|
|
552
|
+
return undefined;
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
export const getFileHistory = async (
|
|
556
|
+
bucket: R2Bucket,
|
|
557
|
+
repoId: string,
|
|
558
|
+
filePath: string,
|
|
559
|
+
): Promise<Commit[]> => {
|
|
560
|
+
const headOid = await resolveRef(bucket, repoId);
|
|
561
|
+
if (!headOid) return [];
|
|
562
|
+
|
|
563
|
+
const commits: Commit[] = [];
|
|
564
|
+
let oid: string | undefined = headOid;
|
|
565
|
+
|
|
566
|
+
while (oid) {
|
|
567
|
+
const commitObj = await readGitObject(bucket, repoId, oid);
|
|
568
|
+
if (!commitObj || commitObj.type !== "commit") break;
|
|
569
|
+
const parsed = parseCommit(commitObj.payload);
|
|
570
|
+
|
|
571
|
+
const fileOid = await fileOidInTree(bucket, repoId, parsed.tree, filePath);
|
|
572
|
+
let parentFileOid: string | undefined;
|
|
573
|
+
if (parsed.parents[0]) {
|
|
574
|
+
const parentObj = await readGitObject(bucket, repoId, parsed.parents[0]);
|
|
575
|
+
if (parentObj && parentObj.type === "commit") {
|
|
576
|
+
const parentParsed = parseCommit(parentObj.payload);
|
|
577
|
+
parentFileOid = await fileOidInTree(bucket, repoId, parentParsed.tree, filePath);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (fileOid !== parentFileOid) {
|
|
582
|
+
commits.push(buildCommit(oid, parsed));
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
oid = parsed.parents[0];
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
return commits;
|
|
589
|
+
};
|
|
590
|
+
|
|
591
|
+
export const getFileContentData = async (
|
|
592
|
+
bucket: R2Bucket,
|
|
593
|
+
repoId: string,
|
|
594
|
+
filePath: string,
|
|
595
|
+
): Promise<Uint8Array | undefined> => {
|
|
596
|
+
const obj = await bucket.get(`${repoId}/${filePath}`);
|
|
597
|
+
if (obj === null) return undefined;
|
|
598
|
+
return await obj.bytes();
|
|
599
|
+
};
|
|
600
|
+
|
|
601
|
+
interface Change {
|
|
602
|
+
filepath: string;
|
|
603
|
+
changeType: "added" | "deleted" | "modified";
|
|
604
|
+
newOid?: string;
|
|
605
|
+
oldOid?: string;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
const getTreeEntries = async (
|
|
609
|
+
bucket: R2Bucket,
|
|
610
|
+
repoId: string,
|
|
611
|
+
treeOid: string,
|
|
612
|
+
): Promise<Map<string, { mode: string; oid: string }>> => {
|
|
613
|
+
const map = new Map<string, { mode: string; oid: string }>();
|
|
614
|
+
const obj = await readGitObject(bucket, repoId, treeOid);
|
|
615
|
+
if (!obj || obj.type !== "tree") return map;
|
|
616
|
+
const entries = parseTree(obj.payload);
|
|
617
|
+
for (const entry of entries) {
|
|
618
|
+
map.set(entry.name, { mode: entry.mode, oid: entry.oid });
|
|
619
|
+
}
|
|
620
|
+
return map;
|
|
621
|
+
};
|
|
622
|
+
|
|
623
|
+
const diffTrees = async (
|
|
624
|
+
bucket: R2Bucket,
|
|
625
|
+
repoId: string,
|
|
626
|
+
oldTreeOid: string | undefined,
|
|
627
|
+
newTreeOid: string,
|
|
628
|
+
prefix = "",
|
|
629
|
+
): Promise<Change[]> => {
|
|
630
|
+
const changes: Change[] = [];
|
|
631
|
+
const oldEntries = oldTreeOid ? await getTreeEntries(bucket, repoId, oldTreeOid) : new Map();
|
|
632
|
+
const newEntries = await getTreeEntries(bucket, repoId, newTreeOid);
|
|
633
|
+
|
|
634
|
+
const allNames = new Set([...oldEntries.keys(), ...newEntries.keys()]);
|
|
635
|
+
|
|
636
|
+
for (const name of allNames) {
|
|
637
|
+
const path = prefix ? `${prefix}/${name}` : name;
|
|
638
|
+
const oldEntry = oldEntries.get(name);
|
|
639
|
+
const newEntry = newEntries.get(name);
|
|
640
|
+
|
|
641
|
+
if (!newEntry) {
|
|
642
|
+
if (oldEntry && oldEntry.mode !== "40000") {
|
|
643
|
+
changes.push({ filepath: path, changeType: "deleted", oldOid: oldEntry.oid });
|
|
644
|
+
}
|
|
645
|
+
} else if (!oldEntry) {
|
|
646
|
+
if (newEntry.mode !== "40000") {
|
|
647
|
+
changes.push({ filepath: path, changeType: "added", newOid: newEntry.oid });
|
|
648
|
+
} else {
|
|
649
|
+
changes.push(...(await diffTrees(bucket, repoId, undefined, newEntry.oid, path)));
|
|
650
|
+
}
|
|
651
|
+
} else if (oldEntry.mode === "40000" && newEntry.mode === "40000") {
|
|
652
|
+
changes.push(...(await diffTrees(bucket, repoId, oldEntry.oid, newEntry.oid, path)));
|
|
653
|
+
} else if (oldEntry.oid !== newEntry.oid) {
|
|
654
|
+
if (newEntry.mode !== "40000") {
|
|
655
|
+
changes.push({
|
|
656
|
+
filepath: path,
|
|
657
|
+
changeType: "modified",
|
|
658
|
+
newOid: newEntry.oid,
|
|
659
|
+
oldOid: oldEntry.oid,
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
return changes;
|
|
666
|
+
};
|
|
667
|
+
|
|
668
|
+
const readBlobText = async (bucket: R2Bucket, repoId: string, oid: string): Promise<string> => {
|
|
669
|
+
const obj = await readGitObject(bucket, repoId, oid);
|
|
670
|
+
if (!obj || obj.type !== "blob") return "";
|
|
671
|
+
return new TextDecoder().decode(obj.payload);
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
export const generateHTMLDiff = async (
|
|
675
|
+
bucket: R2Bucket,
|
|
676
|
+
repoId: string,
|
|
677
|
+
hash: string,
|
|
678
|
+
): Promise<string> => {
|
|
679
|
+
const { html, parse } = await import("diff2html");
|
|
680
|
+
const { createTwoFilesPatch } = await import("diff");
|
|
681
|
+
|
|
682
|
+
const commitObj = await readGitObject(bucket, repoId, hash);
|
|
683
|
+
if (!commitObj || commitObj.type !== "commit") return "<p>Commit not found.</p>";
|
|
684
|
+
const parsed = parseCommit(commitObj.payload);
|
|
685
|
+
const parentOid = parsed.parents[0];
|
|
686
|
+
|
|
687
|
+
let parentTreeOid: string | undefined;
|
|
688
|
+
if (parentOid) {
|
|
689
|
+
const parentObj = await readGitObject(bucket, repoId, parentOid);
|
|
690
|
+
if (parentObj && parentObj.type === "commit") {
|
|
691
|
+
parentTreeOid = parseCommit(parentObj.payload).tree;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
const changes = parentTreeOid
|
|
696
|
+
? await diffTrees(bucket, repoId, parentTreeOid, parsed.tree)
|
|
697
|
+
: await diffTrees(bucket, repoId, undefined, parsed.tree);
|
|
698
|
+
|
|
699
|
+
if (changes.length === 0) {
|
|
700
|
+
return "<p>No changes in this commit.</p>";
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const chunks: string[] = [];
|
|
704
|
+
for (const change of changes) {
|
|
705
|
+
if (change.changeType === "added" && change.newOid) {
|
|
706
|
+
const content = await readBlobText(bucket, repoId, change.newOid);
|
|
707
|
+
chunks.push(createTwoFilesPatch(`/dev/null`, `b/${change.filepath}`, "", content));
|
|
708
|
+
} else if (change.changeType === "deleted" && change.oldOid) {
|
|
709
|
+
const content = await readBlobText(bucket, repoId, change.oldOid);
|
|
710
|
+
chunks.push(createTwoFilesPatch(`a/${change.filepath}`, `/dev/null`, content, ""));
|
|
711
|
+
} else if (change.changeType === "modified" && change.newOid && change.oldOid) {
|
|
712
|
+
const [oldContent, newContent] = await Promise.all([
|
|
713
|
+
readBlobText(bucket, repoId, change.oldOid),
|
|
714
|
+
readBlobText(bucket, repoId, change.newOid),
|
|
715
|
+
]);
|
|
716
|
+
if (oldContent.length > 1024 * 512 || newContent.length > 1024 * 512) {
|
|
717
|
+
chunks.push(`diff --git a/${change.filepath} b/${change.filepath}\n`);
|
|
718
|
+
chunks.push(`--- a/${change.filepath}\n+++ b/${change.filepath}\n`);
|
|
719
|
+
chunks.push(`@@ -1 +1 @@\n-File too large to diff\n+File too large to diff\n`);
|
|
720
|
+
} else {
|
|
721
|
+
chunks.push(
|
|
722
|
+
createTwoFilesPatch(
|
|
723
|
+
`a/${change.filepath}`,
|
|
724
|
+
`b/${change.filepath}`,
|
|
725
|
+
oldContent,
|
|
726
|
+
newContent,
|
|
727
|
+
),
|
|
728
|
+
);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
const diffText = chunks.join("\n");
|
|
734
|
+
if (diffText.length > 1024 * 512) {
|
|
735
|
+
return "<p>Diff too large to display.</p>";
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
const diffJson = parse(diffText);
|
|
739
|
+
const diffHtml = html(diffJson, { drawFileList: true, matching: "lines" });
|
|
740
|
+
return diffHtml;
|
|
741
|
+
};
|
packages/shared/core/src/index.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export { renderMarkdown } from "./markdown";
|
|
2
|
+
export { getRepos, getRepo, getPosts, getPost } from "./content";
|
|
3
|
+
export {
|
|
4
|
+
getGitBugIssues,
|
|
5
|
+
getGitBugIssue,
|
|
6
|
+
createGitBugIssue,
|
|
7
|
+
addGitBugIssueComment,
|
|
8
|
+
setGitBugIssueState,
|
|
9
|
+
} from "./gitBug";
|
|
10
|
+
export type { GitBugIssueState, GitBugIssue, GitBugComment, GitBugIssuesResult } from "./gitBug";
|
|
11
|
+
export { getRepoReadme } from "./repoContent";
|
|
12
|
+
export { buildFileTree, sortChildren, sortAll, resolveFolderIcon, resolveFileIcon } from "./files";
|
|
13
|
+
export type { FileNode } from "./files";
|
|
14
|
+
export {
|
|
15
|
+
getCommits,
|
|
16
|
+
getFiles,
|
|
17
|
+
getFileHistory,
|
|
18
|
+
getFileContentData,
|
|
19
|
+
generateHTMLDiff,
|
|
20
|
+
} from "./gitReader";
|
|
21
|
+
export type { Commit } from "./gitReader";
|
packages/shared/core/src/markdown.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import rehypeExpressiveCode from "rehype-expressive-code";
|
|
2
|
+
import rehypeStringify from "rehype-stringify";
|
|
3
|
+
import remarkParse from "remark-parse";
|
|
4
|
+
import remarkRehype from "remark-rehype";
|
|
5
|
+
import { unified } from "unified";
|
|
6
|
+
|
|
7
|
+
const ecConfig = {
|
|
8
|
+
shiki: { engine: "javascript" },
|
|
9
|
+
styleOverrides: { codeFontSize: "0.8rem", uiFontSize: "0.8rem" },
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export const renderMarkdown = async (markdown: string) => {
|
|
13
|
+
const file = await unified()
|
|
14
|
+
.use(remarkParse)
|
|
15
|
+
.use(remarkRehype)
|
|
16
|
+
.use(rehypeExpressiveCode, ecConfig)
|
|
17
|
+
.use(rehypeStringify)
|
|
18
|
+
.process(markdown);
|
|
19
|
+
return String(file);
|
|
20
|
+
};
|
packages/shared/core/src/repoContent.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const getRepoReadme = async (
|
|
2
|
+
bucket: R2Bucket,
|
|
3
|
+
repoId: string,
|
|
4
|
+
): Promise<string | undefined> => {
|
|
5
|
+
const obj = await bucket.get(`${repoId}/README.md`);
|
|
6
|
+
if (obj === null) return undefined;
|
|
7
|
+
return await obj.text();
|
|
8
|
+
};
|
packages/shared/core/tsconfig.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../../tsconfig.base.json",
|
|
3
|
+
"include": ["src"]
|
|
4
|
+
}
|
pnpm-lock.yaml
CHANGED
|
@@ -319,6 +319,51 @@ importers:
|
|
|
319
319
|
|
|
320
320
|
packages/shared/config: {}
|
|
321
321
|
|
|
322
|
+
packages/shared/core:
|
|
323
|
+
dependencies:
|
|
324
|
+
'@pyrossh/config':
|
|
325
|
+
specifier: workspace:*
|
|
326
|
+
version: link:../config
|
|
327
|
+
'@pyrossh/types':
|
|
328
|
+
specifier: workspace:*
|
|
329
|
+
version: link:../types
|
|
330
|
+
diff:
|
|
331
|
+
specifier: ^9.0.0
|
|
332
|
+
version: 9.0.0
|
|
333
|
+
diff2html:
|
|
334
|
+
specifier: ^3.4.52
|
|
335
|
+
version: 3.4.56
|
|
336
|
+
gray-matter:
|
|
337
|
+
specifier: ^4.0.3
|
|
338
|
+
version: 4.0.3
|
|
339
|
+
pretty-bytes:
|
|
340
|
+
specifier: ^7.1.0
|
|
341
|
+
version: 7.1.0
|
|
342
|
+
rehype-expressive-code:
|
|
343
|
+
specifier: ^0.44.0
|
|
344
|
+
version: 0.44.0
|
|
345
|
+
rehype-stringify:
|
|
346
|
+
specifier: ^10.0.1
|
|
347
|
+
version: 10.0.1
|
|
348
|
+
remark-parse:
|
|
349
|
+
specifier: ^11.0.0
|
|
350
|
+
version: 11.0.0
|
|
351
|
+
remark-rehype:
|
|
352
|
+
specifier: ^11.1.2
|
|
353
|
+
version: 11.1.2
|
|
354
|
+
spamscanner:
|
|
355
|
+
specifier: ^6.1.5
|
|
356
|
+
version: 6.1.5(@tensorflow/[email protected](@tensorflow/[email protected]))(@tensorflow/[email protected])(@tensorflow/[email protected]([email protected]))([email protected])([email protected])
|
|
357
|
+
unified:
|
|
358
|
+
specifier: ^11.0.5
|
|
359
|
+
version: 11.0.5
|
|
360
|
+
devDependencies:
|
|
361
|
+
vscode-icons:
|
|
362
|
+
specifier: https://github.com/vscode-icons/vscode-icons.git
|
|
363
|
+
version: https://codeload.github.com/vscode-icons/vscode-icons/tar.gz/7edc186619964d42ddf7da6f36c46e7cd6bcb0a8
|
|
364
|
+
|
|
365
|
+
packages/shared/types: {}
|
|
366
|
+
|
|
322
367
|
packages:
|
|
323
368
|
|
|
324
369
|
'@antfu/[email protected]':
|
|
@@ -5465,6 +5510,11 @@ packages:
|
|
|
5465
5510
|
|
|
5466
5511
|
resolution: {integrity: sha512-ulCrSnFnfQ16YzvwnYUgEbUEl/ZG7u2eV27YhvLObSHKkb8fw1Z9cgsnUwjTEeDIdJDoTDTDpxuhQwoenoLNMg==}
|
|
5467
5512
|
|
|
5513
|
+
vscode-icons@https://codeload.github.com/vscode-icons/vscode-icons/tar.gz/7edc186619964d42ddf7da6f36c46e7cd6bcb0a8:
|
|
5514
|
+
resolution: {gitHosted: true, integrity: sha512-UlXu55W0F7EFAA1tHF+sJzGKx8P784KlHwPJ7xYOqxaGPJSWU9rfUmj0vpHtewu2ATTTwZQTF95jUIm0dWFZig==, tarball: https://codeload.github.com/vscode-icons/vscode-icons/tar.gz/7edc186619964d42ddf7da6f36c46e7cd6bcb0a8}
|
|
5515
|
+
version: 12.19.0
|
|
5516
|
+
engines: {node: '>=18.15.0', vscode: ^1.82.0}
|
|
5517
|
+
|
|
5468
5518
|
vscode-icons@https://codeload.github.com/vscode-icons/vscode-icons/tar.gz/e4668f9a6cd557cfa4c2546a2449b66a8bb66ddb:
|
|
5469
5519
|
resolution: {gitHosted: true, integrity: sha512-wHJnKRT1j2gGk/gSzbLZjCCz06ptkd4gWtrBwRZ15Rp9G7ghROy6Jh9wo1LlR2YoZDey2hsqSYdlWHuDcl475A==, tarball: https://codeload.github.com/vscode-icons/vscode-icons/tar.gz/e4668f9a6cd557cfa4c2546a2449b66a8bb66ddb}
|
|
5470
5520
|
version: 12.19.0
|
|
@@ -11002,6 +11052,14 @@ snapshots:
|
|
|
11002
11052
|
vscode-languageserver-types: 3.18.0
|
|
11003
11053
|
vscode-uri: 3.1.0
|
|
11004
11054
|
|
|
11055
|
+
vscode-icons@https://codeload.github.com/vscode-icons/vscode-icons/tar.gz/7edc186619964d42ddf7da6f36c46e7cd6bcb0a8:
|
|
11056
|
+
dependencies:
|
|
11057
|
+
inversify: 6.2.2([email protected])
|
|
11058
|
+
lodash: 4.18.1
|
|
11059
|
+
open: 8.4.2
|
|
11060
|
+
reflect-metadata: 0.2.2
|
|
11061
|
+
semver: 7.8.5
|
|
11062
|
+
|
|
11005
11063
|
vscode-icons@https://codeload.github.com/vscode-icons/vscode-icons/tar.gz/e4668f9a6cd557cfa4c2546a2449b66a8bb66ddb:
|
|
11006
11064
|
dependencies:
|
|
11007
11065
|
inversify: 6.2.2([email protected])
|