-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpull_request_url.ts
102 lines (98 loc) · 2.46 KB
/
pull_request_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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { execute, type ExecuteOptions } from "./process.ts";
import {
getHostingService,
type HostingService,
} from "./hosting_service/mod.ts";
import {
__throw,
getCommitSHA1,
getRemoteContains,
getRemoteFetchURL,
} from "./util.ts";
type Options = ExecuteOptions & {
remote?: string;
aliases?: Record<string, string>;
};
export async function getPullRequestURL(
commitish: 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);
if (!hostingService.getPullRequestURL) {
throw new Error(
`Hosting service of ${fetchURL} has no pull request URL`,
);
}
const pr = await getPullRequestContains(
hostingService,
commitish,
remote,
options,
);
if (!pr) {
throw new Error(`No pull request found for ${commitish}`);
}
return hostingService.getPullRequestURL(fetchURL, pr);
}
async function getPullRequestContains(
hostingService: HostingService,
commitish: string,
remote: string,
options: ExecuteOptions = {},
): Promise<number | undefined> {
if (!hostingService.extractPullRequestID) {
throw new Error("Hosting service has no pull request ID extractor");
}
const branch = await getRemoteDefaultBranch(remote, options) ?? "main";
const sha = await getCommitSHA1(commitish, options) ?? __throw(
new Error(`No commit found for ${commitish}`),
);
let stdout: string;
// The sha may points to a merge commit itself.
stdout = await execute(
[
"log",
"-1",
sha,
],
options,
);
const pr = hostingService.extractPullRequestID(stdout);
if (pr) {
return pr;
}
// Try to find the merge commit that contains the sha
const ancestraryPath = `${sha}...${remote}/${branch}`;
stdout = await execute(
[
"log",
"--merges",
"--reverse",
"--ancestry-path",
ancestraryPath,
],
options,
);
return hostingService.extractPullRequestID(stdout);
}
async function getRemoteDefaultBranch(
remote: string,
options: ExecuteOptions = {},
): Promise<string | undefined> {
const stdout = await execute(
["remote", "show", remote],
options,
);
const m = stdout.match(/HEAD branch: (.*)/);
if (!m) {
return undefined;
}
return m[1].trim();
}