-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithubClient.js
More file actions
120 lines (99 loc) · 3.2 KB
/
githubClient.js
File metadata and controls
120 lines (99 loc) · 3.2 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
class GitHubClient {
constructor({token, appName, debug = false, fetcher = fetch}) {
this.fetcher = fetcher;
this.domain = 'https://api.github.com';
this.debug = debug;
this.headers = {
Accept: 'application/vnd.github.v3+json',
Authorization: `token ${token}`,
'User-Agent': appName
};
}
log(message, data) {
if (this.debug) {
console.log(`[GitHubClient] ${message}`, data || '');
}
}
async request(url, options = {}) {
try {
this.log(`Request: ${options.method || 'GET'} ${url}`);
const response = await this.fetcher(url, {
method: options.method || 'GET',
headers: this.headers,
body: options.body ? JSON.stringify(options.body) : undefined
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`GitHub API Error: ${response.status} ${response.statusText} - ${errorText}`);
}
const data = await response.json();
this.log('Response:', data);
return data;
} catch (error) {
console.error(`GitHub API request failed: ${error.message}`);
throw error;
}
}
async getBranch(owner, repo, branch) {
const data = await this.request(
`${this.domain}/repos/${owner}/${repo}/branches/${branch}`
);
if (!data?.commit?.sha) {
throw new Error(`Failed to get commit SHA from branch: ${branch}`);
}
return data.commit.sha;
}
async getTree(owner, repo, sha) {
const data = await this.request(
`${this.domain}/repos/${owner}/${repo}/git/trees/${sha}`
);
if (!data?.tree) {
throw new Error(`Failed to get tree for SHA: ${sha}`);
}
return data.tree;
}
async createTree(owner, repo, tree) {
const data = await this.request(
`${this.domain}/repos/${owner}/${repo}/git/trees`,
{
method: 'POST',
body: { tree }
}
);
if (!data?.sha) {
throw new Error('Failed to create tree');
}
return data.sha;
}
async createCommit(owner, repo, message, treeSha) {
const data = await this.request(
`${this.domain}/repos/${owner}/${repo}/git/commits`,
{
method: 'POST',
body: {
message,
tree: treeSha
}
}
);
if (!data?.sha) {
throw new Error('Failed to create commit');
}
return data.sha;
}
async updateReference(owner, repo, branch, sha, force = false) {
const data = await this.request(
`${this.domain}/repos/${owner}/${repo}/git/refs/heads/${branch}`,
{
method: 'PATCH',
body: {
sha,
force
}
}
);
this.log('Reference updated successfully', data);
return data;
}
}
module.exports = GitHubClient;