-
Notifications
You must be signed in to change notification settings - Fork 1
/
sync.js
107 lines (98 loc) · 2.44 KB
/
sync.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
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
const axios = require('axios');
const debug = require('debug')('hub-sync');
class HubSync {
constructor(config) {
const { token } = config;
this.config = token;
this.axios = axios.create({
baseURL: 'https://api.github.com',
timeout: 10000,
maxContentLength: 20000,
headers: { Authorization: 'token ' + token },
});
this.axios.interceptors.response.use((r) => {
debug(r.status + ' ' + r.statusText);
return r;
}, (e) => {
debug(e.response.status + ' ' + e.response.statusText);
return Promise.reject(e);
});
}
run(cfg) {
debug(cfg);
return this.axios(cfg);
}
async getRefs({ user, repo, branch }) {
const { data } = await this.run({
method: 'get',
url: `/repos/${user}/${repo}/git/refs/heads/${branch}`,
});
return data.object.sha;
}
async setRefs({ user, repo, branch }, sha, { force, create }) {
if (create) {
const { data } = await this.run({
method: 'post',
url: `/repos/${user}/${repo}/git/refs`,
data: {
ref: `refs/heads/${branch}`,
sha,
},
});
return data;
}
const { data } = await this.run({
method: 'patch',
url: `/repos/${user}/${repo}/git/refs/heads/${branch}`,
data: {
sha,
force: !!force,
},
});
return data;
}
async delRefs({ user, repo, branch }) {
const { data } = await this.run({
method: 'delete',
url: `/repos/${user}/${repo}/git/refs/heads/${branch}`,
});
return true;
}
async getRepo({ user, repo }) {
const { data } = await this.run({
method: 'get',
url: `/repos/${user}/${repo}`,
});
return data;
}
async getMe() {
const { data } = await this.run({
method: 'get',
url: '/user',
});
return data.login;
}
async fill({ what: { user, repo, branch }, from, force }) {
user = user || await this.getMe();
if (!from.sha1) {
if (!from.user || !branch) {
const { default_branch, parent } = await this.getRepo({ user, repo });
branch = branch || default_branch;
if (!from.user) {
from = {
user: parent.owner.login,
repo: parent.name,
};
}
}
from.repo = from.repo || repo;
from.branch = from.branch || branch;
}
return {
what: { user, repo, branch },
from,
force,
};
}
}
module.exports = HubSync;