-
Notifications
You must be signed in to change notification settings - Fork 1
/
cli.js
executable file
·280 lines (242 loc) · 6.83 KB
/
cli.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
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
#!/usr/bin/env node
"use strict";
const chalk = require('chalk');
const meow = require('meow');
const inquirer = require('inquirer');
const github = require('github')();
const simpleGit = require('simple-git')();
const Preferences = require('preferences');
const files = require('./lib/files');
const pkg = require('./package.json');
const prefs = new Preferences('ginit');
const cli = meow({
description: false,
help: `
Usage
${chalk.yellow('ginit [command] [option]')}
The command argument is optional. If no command is provided,
then the ${chalk.yellow('init')} command will be run by default.
Commands
${chalk.yellow('auth')} Sign into github
${chalk.yellow('init')} Initialize current directory as git repository
Options
${chalk.yellow('--interactive, -i')} Enter interactive mode
${chalk.yellow('--force, -f')} Force initialization
${chalk.yellow('--version, -v')} Print version
${chalk.yellow('--help, -h')} Print help
Examples
ginit auth ${chalk.dim('# Sign into github')}
ginit ${chalk.dim('# Initialize current directory as git repository')}
ginit -i ${chalk.dim('# Enter interactive mode')}
`,
flags: {
interactive: {
type: 'boolean',
alias: 'i'
},
force: {
type: 'boolean',
alias: 'f'
},
version: {
type: 'boolean',
alias: 'v'
},
help: {
type: 'boolean',
alias: 'h'
}
}
});
run(cli.input, cli.flags);
function run (input, flags) {
const command = input[0];
const interactive = flags.interactive;
const force = flags.force;
switch (command) {
case 'auth': return runAuth();
case 'init':
default: return runInit(interactive, force);
}
}
async function runAuth () {
const { username, password } = await promptAuth();
github.authenticate({ type: 'basic', username, password });
await github.authorization.create({
scopes: ['user', 'public_repo', 'repo', 'repo:status'],
note: 'ginit: cli for easy `git init`ing',
fingerprint: `ginit v${pkg.version}`
}, (err, res) => {
if (err) {
switch (err.code) {
case 401:
console.log(chalk.red('Couldn\'t log you in. Please try again.'));
break;
case 422:
console.log(chalk.red('You already have an access token.'));
console.log(`Try revoking your ginit access token and then trying again.`);
console.log(' url: https://github.com/settings/tokens');
break;
}
} else if (res.data.token) {
prefs.github = {
token: res.data.token
};
console.log(chalk.green('Successfully authenticated.'));
}
});
}
async function runInit (interactive, force) {
const token = prefs.github ? prefs.github.token : false;
if (!token) {
console.log(chalk.red('Unauthorized. Please ensure you are logged in using `ginit auth`.'));
process.exit(1);
}
if (files.directoryExists('.git')) {
console.log(chalk.red('This directory is already a git repository. Exiting.'));
process.exit(1);
}
if (!files.directoryHasFiles('.') && !interactive && !force) {
console.log(chalk.red('This directory has no files to commit. Try running in interactive or force modes.'));
process.exit(1);
}
github.authenticate({ type: 'oauth', token });
const data = {};
if (interactive) {
const { name, description, visibility } = await promptCreateQuestions();
data.name = name;
data.description = description;
data.private = (visibility === 'private');
const { wantReadme, wantIgnore, wantAttributes, wantEditorConfig } = await promptFileQuestions(name);
if (wantReadme) {
const defaults = [
`# ${name}`,
''
];
files.createFile('README.md', defaults.join('\n'));
}
if (wantIgnore) {
const defaults = [
'node_modules',
'.DS_Store',
'*.log',
''
];
files.createFile('.gitignore', defaults.join('\n'));
}
if (wantAttributes) {
const defaults = [
'* text=auto',
'*.js text eol=lf',
''
];
files.createFile('.gitattributes', defaults.join('\n'));
}
if (wantEditorConfig) {
const defaults = [
'root = true',
'',
'[*]',
'charset = utf-8',
'indent_style = space',
'indent_size = 2',
'end_of_line = lf',
'insert_final_newline = true',
'trim_trailing_whitespace = true',
''
];
files.createFile('.editorconfig', defaults.join('\n'));
}
}
try {
const { data: repoData } = await createRepository(data);
const fileStatus = await setupRepository(repoData.ssh_url);
console.log(chalk.green(`Repository initalized ${fileStatus}.`));
} catch (e) {
console.log(chalk.red(e));
}
}
function promptAuth () {
return inquirer.prompt([
{
name: 'username',
message: 'Enter your Github username or e-mail address:',
type: 'input',
validate: val => val.length ? true : 'Input required'
},
{
name: 'password',
message: 'Enter your password:',
type: 'password',
validate: val => val.length ? true : 'Input required'
}
])
}
function promptCreateQuestions () {
return inquirer.prompt([
{
name: 'name',
message: 'Enter a name for the repository:',
type: 'input',
default: files.getCurrentDirectoryBase(),
validate: val => val.length ? true : 'Input required'
},
{
name: 'description',
message: 'Enter a description for the repository (optional):',
type: 'input',
default: null
},
{
name: 'visibility',
message: 'Public or private:',
type: 'list',
choices: [ 'public', 'private' ],
default: 'public'
}
]);
}
function promptFileQuestions (name) {
return inquirer.prompt([
{
name: 'wantReadme',
message: 'Do you want to create a README.md?',
type: 'confirm'
},
{
name: 'wantIgnore',
message: 'Do you want to create a .gitignore?',
type: 'confirm'
},
{
name: 'wantAttributes',
message: 'Do you want to create a .gitattributes?',
type: 'confirm'
},
{
name: 'wantEditorConfig',
message: 'Do you want to create a .editorconfig?',
type: 'confirm'
}
]);
}
function createRepository (data) {
if (!data.name) {
data.name = files.getCurrentDirectoryBase();
}
return github.repos.create(data);
}
function setupRepository (url) {
if (files.directoryHasFiles('.')) {
simpleGit.init()
.add('.')
.commit('Initial commit')
.addRemote('origin', url)
.push('origin', 'master')
return 'with files';
} else {
simpleGit.init()
.addRemote('origin', url)
return 'without files';
}
}