-
Notifications
You must be signed in to change notification settings - Fork 1
/
github.service.js
65 lines (57 loc) · 2.07 KB
/
github.service.js
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
import {Octokit} from "@octokit/core";
class GitHubService {
constructor(authToken, org, repo) {
this.authToken = authToken;
this.org = org;
this.repo = repo;
this.octokit = new Octokit({
auth: this.authToken
});
}
async isBranchExists(branch) {
console.log(`Checking if branch ${branch} exists in ${this.org}/${this.repo}`);
try {
const response = await this.octokit.request('GET /repos/{owner}/{repo}/branches/{branch}', {
owner: this.org,
repo: this.repo,
branch: branch
});
return response.status === 200;
} catch (e) {
console.log(`Branch ${branch} does not exist in ${this.org}/${this.repo}`);
return false;
}
}
async createBranch(branch, headBranch = "main") {
console.log(`Creating branch ${branch} in ${this.org}/${this.repo}`);
console.log(`Getting head branch: ${headBranch} sha`);
const referenceRes = await this.octokit.request(
"GET /repos/{owner}/{repo}/git/ref/{ref}",
{
owner: this.org,
repo: this.repo,
ref: `heads/${headBranch}`,
}
);
const ref = referenceRes?.data;
const sha = ref?.object?.sha;
console.log(`Head branch sha: ${sha}`);
if (!sha) {
throw new Error(`Head branch ${headBranch} does not exist in ${this.org}/${this.repo}`);
}
console.log(`Creating branch ${branch} with sha ${sha}`);
try {
const response = await this.octokit.request('POST /repos/{owner}/{repo}/git/refs', {
owner: this.org,
repo: this.repo,
ref: `refs/heads/${branch}`,
sha: sha
});
return response.status === 201;
} catch (e) {
console.log(`Branch ${branch} creation failed in ${this.org}/${this.repo}: [ERROR] ${e.message}`);
throw e;
}
}
}
export {GitHubService};