-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub_api.js
More file actions
105 lines (90 loc) · 3.04 KB
/
github_api.js
File metadata and controls
105 lines (90 loc) · 3.04 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
const https = require('https');
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const fs = require('fs');
const writeFileAsync = util.promisify(fs.writeFile);
const readdirAsync = util.promisify(fs.readdir);
const renameAsync = util.promisify(fs.rename);
async function renameCase(correctName) {
const lst = await readdirAsync('./');
for (let file of lst) {
if (file.toLowerCase() === correctName.toLowerCase()) {
await renameAsync(file, correctName);
return true;
}
}
return false;
}
class GithubInit {
constructor(auth) {
this.auth = auth;
}
api_v3(api_path, data={}) {
return new Promise((resolve, reject) => {
const match = /^([A-Z]+) (.*)$/.exec(api_path);
if (!match) {
reject('Invalid api_path');
return;
}
const path = match[2];
const method = match[1];
const queryData = JSON.stringify(data);
const req = https.request(`https://api.github.com${path}`, {
auth: this.auth,
method,
headers: {
'user-agent': '',
'accept': 'application/vnd.github.v3+json'
}
}, res => {
res.setEncoding('utf8');
let buff = Buffer.alloc(0);
res.on('data', (chunk) => {
buff = Buffer.concat([buff, Buffer.from(chunk)]);
});
res.on('end', () => {
resolve(JSON.parse(buff.toString()));
});
});
req.on('error', err => {
reject(err);
});
req.write(queryData);
req.end();
});
}
async createPrivateRepo(name) {
const response = await this.api_v3('POST /user/repos', {
name: name,
private: true
});
if (response.errors) return false;
return response.ssh_url;
}
async initPrivateRepo(name) {
const ssh_url = await this.createPrivateRepo(name);
await renameCase('README.md');
try {await writeFileAsync('README.md', `# ${name}
`, { flag: "wx" });} catch (err) {}
if (ssh_url) {
await this.cmd(`git init`);
await this.cmd(`git add README.md`);
await this.cmd(`git commit -m "Initial commit"`);
await this.cmd(`git remote add origin ${ssh_url}`);
await this.cmd(`git push -u origin master`);
}
else throw new Error('Cannot create remote repo. Check if repo already exists.');
}
async cmd(command) {
let stdout, stderr;
try {
const res = await exec(command);
stdout = res.stdout;
stderr = res.stderr;
console.log(stdout);
} catch (err) {
console.log(err.message);
}
}
}
module.exports = GithubInit;