-
Notifications
You must be signed in to change notification settings - Fork 148
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·323 lines (286 loc) · 8.64 KB
/
Copy pathcli.js
File metadata and controls
executable file
·323 lines (286 loc) · 8.64 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#!/usr/bin/env node
/* eslint-disable no-console */
const path = require('path')
const yargs = require('yargs')
const chalk = require('chalk')
const inquirer = require('inquirer')
const didYouMean = require('didyoumean')
// Setting edit length to be 60% of the input string's length
didYouMean.threshold = 0.6
const init = require('./init')
const generate = require('./generate')
const util = require('./util')
const repo = require('./repo')
const updateContributors = require('./contributors')
const {getContributors} = require('./discover')
const {getLearner} = require('./discover/learner')
const cwd = process.cwd()
const defaultRCFile = path.join(cwd, '.all-contributorsrc')
const yargv = yargs
.help('help')
.alias('h', 'help')
.alias('v', 'version')
.version()
.command('generate', 'Generate the list of contributors')
.usage('Usage: $0 generate')
.command('add', 'add a new contributor')
.usage('Usage: $0 add <username> <contribution>')
.command('init', 'Prepare the project to be used with this tool')
.usage('Usage: $0 init')
.command(
'check',
'Compares contributors from the repository with the ones credited in .all-contributorsrc',
)
.usage('Usage: $0 check')
.boolean('commit')
.default('files', ['README.md'])
.default('contributorsPerLine', 7)
.default('contributors', [])
.default('config', defaultRCFile)
.config('config', configPath => {
try {
return util.configFile.readConfig(configPath)
} catch (error) {
if (error instanceof SyntaxError || configPath !== defaultRCFile) {
onError(error)
}
}
}).argv
function suggestCommands(cmd) {
const availableCommands = ['generate', 'add', 'init', 'check']
const suggestion = didYouMean(cmd, availableCommands)
if (suggestion) {
console.log(chalk.bold(`Did you mean ${suggestion}`))
}
}
function startGeneration(argv) {
return Promise.all(
argv.files.map(file => {
const filePath = path.join(cwd, file)
return util.markdown.read(filePath).then(fileContent => {
const newFileContent = generate(argv, argv.contributors, fileContent)
return util.markdown.write(filePath, newFileContent)
})
}),
)
}
function addContribution(argv) {
/* Example: (for clarity & debugging purposes)
{
_: [ 'add' ],
projectName: 'cz-cli',
projectOwner: 'commitizen',
repoType: 'github',
repoHost: 'https://github.com',
files: [ 'AC.md' ],
imageSize: 100,
commit: false,
commitConvention: 'angular',
contributors: [],
contributorsPerLine: 7,
'contributors-per-line': 7,
config: '/mnt/c/Users/max/Projects/cz-cli/.all-contributorsrc',
'$0': '../all-contributors-cli/src/cli.js'
}
*/
const username = argv._[1]
const contributions = argv._[2]
// Add or update contributor in the config file
return updateContributors(argv, username, contributions).then(
data => {
argv.contributors = data.contributors
/* Example
[ { login: 'Berkmann18',
name: 'Maximilian Berkmann',
avatar_url: 'https://avatars0.githubusercontent.com/u/8260834?v=4',
profile: 'http://maxcubing.wordpress.com',
contributions: [ 'code', 'ideas' ] },
{ already in argv.contributors } ]
*/
return startGeneration(argv).then(
() => {
if (argv.commit) {
return util.git.commit(argv, data)
}
},
err => console.error('Generation fail:', err),
)
},
err => console.error('Contributor Update fail:', err),
)
}
function checkContributors(argv) {
const configData = util.configFile.readConfig(argv.config)
return repo
.getContributors(
configData.projectOwner,
configData.projectName,
configData.repoType,
configData.repoHost,
)
.then(repoContributors => {
const checkKey = repo.getCheckKey(configData.repoType)
const knownContributions = configData.contributors.reduce((obj, item) => {
obj[item[checkKey]] = item.contributions
return obj
}, {})
const knownContributors = configData.contributors.map(
contributor => contributor[checkKey],
)
const missingInConfig = repoContributors.filter(
key => !knownContributors.includes(key),
)
const missingFromRepo = knownContributors.filter(key => {
return (
!repoContributors.includes(key) &&
(knownContributions[key].includes('code') ||
knownContributions[key].includes('test'))
)
})
if (missingInConfig.length) {
process.stdout.write(
chalk.bold('Missing contributors in .all-contributorsrc:\n'),
)
process.stdout.write(` ${missingInConfig.join(', ')}\n`)
}
if (missingFromRepo.length) {
process.stdout.write(
chalk.bold('Unknown contributors found in .all-contributorsrc:\n'),
)
process.stdout.write(`${missingFromRepo.join(', ')}\n`)
}
})
}
async function fetchContributors(argv) {
const {reviewers, commitAuthors, issueCreators} = await getContributors(
argv.projectOwner,
argv.projectName,
)
const args = {...argv, _: []}
const contributorsToAdd = []
const learner = await getLearner()
reviewers.forEach(usr => {
contributorsToAdd.push({login: usr.login, contributions: ['review']})
console.log(
`Adding ${chalk.underline('Reviewer')} ${chalk.blue(usr.login)}`,
)
})
issueCreators.forEach(usr => {
const contributor = {
login: usr.login,
contributions: [],
}
usr.labels.forEach(lbl => {
const guessedCategory = learner.classify(lbl).find(c => c && c !== 'null')
if (!guessedCategory) {
console.warn(
`Oops, I couldn't find any category for the "${lbl}" label`,
)
return
}
if (!contributor.contributions.includes(guessedCategory)) {
contributor.contributions.push(guessedCategory)
console.log(
`Adding ${chalk.blue(usr.login)} for ${chalk.underline(
guessedCategory,
)}`,
)
}
})
const existingContributor = contributorsToAdd.find(
c => c.login === usr.login,
)
if (existingContributor) {
existingContributor.contributions.push(...contributor.contributions)
} else {
contributorsToAdd.push(contributor)
}
})
commitAuthors.forEach(usr => {
const existingContributor = contributorsToAdd.find(
c => c.login === usr.login,
)
if (existingContributor) {
// There's no label or commit message info so use only code for now
if (!existingContributor.contributions.includes('code')) {
existingContributor.contributions.push('code')
}
} else {
contributorsToAdd.push({login: usr.login, contributions: ['code']})
}
})
// TODO: Roll onto other contribution categories following https://www.draw.io/#G1uL9saIuZl3rj8sOo9xsLOPByAe28qhwa
for (const contributor of contributorsToAdd) {
if (!contributor.contributions.length) {
console.log('Skipping', contributor.login)
return
}
console.log(
`Adding ${chalk.blue(contributor.login)} for ${chalk.underline(
contributor.contributions.join('/'),
)}`,
)
args._ = ['', contributor.login, contributor.contributions.join(',')]
/* eslint-disable no-await-in-loop */
await addContribution(args)
}
}
function onError(error) {
if (error) {
console.error(error.message)
process.exit(1)
}
process.exit(0)
}
function promptForCommand(argv) {
const questions = [
{
type: 'list',
name: 'command',
message: 'What do you want to do?',
choices: [
{
name: 'Add new contributor or edit contribution type',
value: 'add',
},
{
name: 'Re-generate the contributors list',
value: 'generate',
},
{
name:
'Compare contributors from the repository with the credited ones',
value: 'check',
},
{
name: 'Fetch contributors from the repository',
value: 'fetch',
},
],
when: !argv._[0],
default: 0,
},
]
return inquirer.prompt(questions).then(answers => {
return answers.command || argv._[0]
})
}
promptForCommand(yargv)
.then(command => {
switch (command) {
case 'init':
return init()
case 'generate':
return startGeneration(yargv)
case 'add':
return addContribution(yargv)
case 'check':
return checkContributors(yargv)
case 'fetch':
return fetchContributors(yargv)
default:
suggestCommands(command)
throw new Error(`Unknown command ${command}`)
}
})
.catch(onError)