-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.js
104 lines (87 loc) · 2.14 KB
/
index.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
'use strict';
const fs = require('fs');
const path = require('path');
const co = require('co');
const auth = require('./lib/auth');
const label = require('./lib/label');
const color = require('./lib/colors.json');
const dotfile = getDotFile();
const GitHubApi = require('github');
module.exports = program => {
const github = new GitHubApi({
version: '3.0.0',
protocol: 'https',
pathPrefix: program.pathPrefix,
host: program.host,
});
co(function* () {
let token = program.token || readToken();
const opt = {
config: parse(program.config),
token,
repo: program.args[0],
github,
};
/*
Github Authorization
*/
token = yield auth(opt);
if (token) {
yield saveToken(token);
}
console.info('>> Authorized');
/*
Force option will delete add existing labels
*/
if (program.force) {
console.info('>> Delete existing labels');
yield label.deleteAll(opt);
}
/*
Create labels from your given config
*/
console.info('>> Create labels');
yield label.create(opt);
console.info('>> Done');
}).catch(err => console.error(err));
};
function parse(config) {
try {
config = JSON.parse(fs.readFileSync(path.resolve(config)));
} catch (e) {
console.error('>> Parse config error');
console.error(e.stack);
process.exit(1);
}
if (!(config && Array.isArray(config))) return null;
return config.map(function(item) {
if (typeof item !== 'object') {
item = { name: item, color: randomColor() };
} else {
item.color = item.color || randomColor();
}
return item;
});
}
function readToken() {
if (fs.existsSync(dotfile)) {
return fs.readFileSync(dotfile, 'utf8').replace(/\n$/, '');
}
return null;
}
function saveToken(token) {
return function(callback) {
fs.writeFile(dotfile, token, callback);
};
}
function randomColor() {
const len = color.length;
return color[Math.floor(Math.random() * len)];
}
function getDotFile() {
let home = process.env.HOME;
if (!home) {
home = process.env.HOMEDRIVE + process.env.HOMEPATH;
}
return home + '/.github-labels';
}