-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathobject_url.ts
59 lines (54 loc) · 1.67 KB
/
object_url.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { execute, type ExecuteOptions } from "./process.ts";
import { getHostingService, type Range } from "./hosting_service/mod.ts";
import { getRemoteContains, getRemoteFetchURL } from "./util.ts";
type Options = ExecuteOptions & {
remote?: string;
permalink?: boolean;
aliases?: Record<string, string>;
};
export async function getObjectURL(
commitish: string,
path: string,
options: Options = {},
): Promise<URL> {
const remote = options.remote ??
await getRemoteContains(commitish, options) ??
"origin";
const fetchURL = await getRemoteFetchURL(remote, options);
if (!fetchURL) {
throw new Error(`No remote '${remote}' found`);
}
const hostingService = getHostingService(fetchURL, options);
const [normPath, range] = parsePath(path);
const objectType = await getObjectType(commitish, normPath, options);
if (objectType === "tree") {
return hostingService.getTreeURL(fetchURL, commitish, normPath);
}
return hostingService.getBlobURL(fetchURL, commitish, normPath, { range });
}
type ObjectType = "blob" | "tree" | "commit";
async function getObjectType(
commitish: string,
path: string,
options: ExecuteOptions = {},
): Promise<ObjectType | undefined> {
const stdout = await execute(
["ls-tree", "-t", commitish, path],
options,
);
return stdout
.trim()
.split("\n")
.find((line) => line.includes(path))
?.split(" ")
.at(1) as ObjectType;
}
function parsePath(path: string): [string, Range | undefined] {
const m = path.match(/^(.*?):(\d+)(?::(\d+))?$/);
if (!m) {
return [path, undefined];
} else if (m[3]) {
return [m[1], [Number(m[2]), Number(m[3])]];
}
return [m[1], Number(m[2])];
}