-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·393 lines (347 loc) · 11.9 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
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#!/usr/bin/env node
const { program } = require('commander');
const fs = require("fs").promises
const Configstore = require('configstore');
const chalk = require('chalk');
const path = require('path');
const inquirer = require('inquirer');
let treeify = require('treeify');
const cfg = new Configstore("gitn", { 'INIT': false });
let INIT = cfg.get('INIT');
let NOTE_DIR = cfg.get('NOTE_DIR');
let CURRENT_BRANCH = cfg.get('CURRENT_BRANCH');
let CONFIG = cfg.all;
program.version('0.1.1');
program
.command('config')
.option('-g , --globaldir <directory>', 'set global notes directory path')
.description('view/edit global config file')
.action(async (args) => {
if (args.globaldir) {
let p = args.globaldir;
if (process.platform === "win32") {
p += (p.endsWith('\\') ? '' : '\\');
} else {
p += (p.endsWith('/') ? '' : '/');
}
let filehandle;
try {
if (!path.isAbsolute(p)) throw new Error("Please provide absolute path")
await fs.mkdir(p, { recursive: true });
filehandle = await fs.open(`${p}master.txt`, 'w'); //wx fails if exists
cfg.set('INIT', true);
cfg.set('NOTE_DIR', p);
cfg.set('CURRENT_BRANCH', 'master');
} catch (e) {
// if (e.code == 'EEXIST') {
// console.log(chalk.red('global directory already exists here. using it now.'))
// } else
if (e.code == 'ENOENT') {
console.log(chalk.red('invalid path provided'))
} else {
console.log(chalk.red(e.message))
}
} finally {
if (filehandle !== undefined)
await filehandle.close();
}
} else {
console.log(`${chalk.red('Do not edit manually !! Things may start breaking\n')}`);
console.log(chalk.blue("use 'gitn config -g <absolute_path_to_notes_directory>' to change notes directory"))
}
});
function isInitialised(CONFIG) {
if (CONFIG.INIT === false) {
// console.log(chalk.red.bold('notes directory not set !!\n'));
console.log(chalk.blue("use 'gitn config -g <absolute_path_to_notes_directory>' to initialise gitn"));
return false;
}
return true;
}
program
.command('status')
.description('outputs current branch')
.action(() => {
try {
if (!isInitialised(CONFIG)) throw new Error("Initialize notes directory to begin !");
console.log(chalk.green(`On branch ${chalk.bold.blue(cfg.get('CURRENT_BRANCH'))}\n`));
} catch (e) {
console.log(chalk.red(e.message));
}
})
program
.command('log')
.option('-g --grep <pattern>', 'find notes by searching string/pattern')
.description('outputs notes on current branch')
.action(async (args) => {
let filehandle;
try {
if (!isInitialised(CONFIG)) throw new Error("Initialize notes directory to begin !");
filehandle = await fs.open(`${NOTE_DIR}${CURRENT_BRANCH}.txt`, 'r');
data = await filehandle.readFile('utf-8');
console.log(chalk.green(`On branch ${chalk.bold.blue(CURRENT_BRANCH)}`));
notes = data.split("\n");
notes.pop();
if (notes.length === 0) {
console.log(chalk.red('no notes found'));
return;
}
if (args.grep) {
let re = new RegExp(args.grep);
notes = notes.map(e => {
return e.split(" ");
})
for (let i = 0; i < notes.length; i++) {
let noteToPrint = "";
for (let j = 0; j < notes[i].length; j++) {
if (notes[i][j].trim().length != 0 && re.test(notes[i][j])) {
noteToPrint += `${chalk.blue(notes[i][j])} `;
} else {
noteToPrint += `${notes[i][j]} `;
}
}
console.log(`${chalk.bold.blue('├─ ')}${noteToPrint}`);
}
} else {
notes.forEach(e => {
console.log(`${chalk.bold.blue('├─ ')}${e}`)
})
}
} catch (e) {
console.log(chalk.red(e));
} finally {
if (filehandle !== undefined)
await filehandle.close();
}
})
program
.command('commit')
.requiredOption('-m , --message <msg>', 'commit must have a mesage')
.description('add new note')
.action(async (args) => {
let filehandle;
try {
if (!isInitialised(CONFIG)) throw new Error("Initialize notes directory to begin !");
filehandle = await fs.open(`${NOTE_DIR}${CURRENT_BRANCH}.txt`, 'a', 666);
await fs.appendFile(filehandle, args.message + '\n', 'utf-8');
} catch (e) {
console.log(e.message)
} finally {
if (filehandle !== undefined)
await filehandle.close();
}
})
program
.command('branch [branch]')
.option('-d --delete ', 'delete a branch')
.option('-a --all', 'show all branches with commits')
.action(async (branch) => {
let files;
let filehandle;
try {
if (!isInitialised(CONFIG)) throw new Error("Initialize notes directory to begin !");
} catch (e) {
console.log(chalk.red(e.message));
return;
}
if (program.args.includes('-d') || program.args.includes('--delete')) {
try {
if (!branch) throw new Error(" option '-d --delete' requires <branch> to be specified");
if (CURRENT_BRANCH == branch) throw new Error("On same branch. Switch to another branch.");
await fs.unlink(`${NOTE_DIR}${branch}.txt`);
console.log(chalk.green(`branch ${chalk.bold.blue(branch)} deleted`))
} catch (e) {
if (e.errno === -2) {
console.log(chalk.red(`branch '${chalk.bold(branch)}' does not exist.`));
} else
console.log(chalk.red(e.message));
}
} else if (program.args.includes('-a') || program.args.includes('--all')) {
try {
if (branch) throw new Error(" option '-a --all' does not take any argument");
let branchNotesTree = {};
files = await fs.readdir(`${NOTE_DIR}`, 'utf-8');
for (let i = 0; i < files.length; i++) {
files[i] = files[i].split('.')[0]
branchNotesTree[`${chalk.bold.blue(files[i])}`] = {};
filehandle = await fs.open(`${NOTE_DIR}${files[i]}.txt`, 'r');
data = await filehandle.readFile('utf-8');
notes = data.split("\n");
notes.pop();
notes.forEach(e => {
branchNotesTree[`${chalk.bold.blue(files[i])}`][`${chalk.green(e)}`] = null;
})
}
console.log(treeify.asTree(branchNotesTree, true));
} catch (e) {
console.log(chalk.red(e.message));
}
}
else if (!branch) {
try {
files = await fs.readdir(`${NOTE_DIR}`, 'utf-8');
console.log(`${chalk.green('showing ')}${chalk.bold.blue('all branches')}`)
files.forEach(e => {
e = e.split('.')[0] // only file(branch) name
if (e === CURRENT_BRANCH)
console.log(`${chalk.bold.blue('├─ ')}${e}${chalk.bold.green('*')}`);
else
console.log(`${chalk.bold.blue('├─ ')}${e}`)
})
} catch (e) {
console.log(chalk.red('some error occured:'), e)
}
} else {
try {
filehandle = await fs.open(`${NOTE_DIR}${branch}.txt`, 'wx'); // wx
console.log(chalk.green(`new branch ${chalk.bold.blue(branch)} created.`))
//fails if exist, so may use w
// console.log(filehandle)
} catch (e) {
if (e.code == 'EEXIST') {
console.log(chalk.red('branch already exists'))
} else {
console.log(e)
}
} finally {
if (filehandle !== undefined)
await filehandle.close();
}
}
})
program
.command('reset')
.description('deletes all commits on current branch')
.action(async (args) => {
try {
if (!isInitialised(CONFIG)) throw new Error("Initialize notes directory to begin !");
await fs.truncate(`${NOTE_DIR}${CURRENT_BRANCH}.txt`);
console.log(`${chalk.green('reset successful')}`)
} catch (e) {
console.log(e.message);
return;
}
})
program
.command('checkout <branch>')
.option('-b --newBranch', 'create a new branch')
.description('create/switch branch')
.action(async (branch) => {
try {
if (!isInitialised(CONFIG)) throw new Error("Initialize notes directory to begin !");
} catch (e) {
console.log(chalk.red(e.message));
return;
}
let filehandle;
if (program.args.includes('-b') || program.args.includes('--createBranch')) {
try {
filehandle = await fs.open(`${NOTE_DIR}${branch}.txt`, 'wx'); // wx fails if exist, so may use w
cfg.set('CURRENT_BRANCH', `${branch}`)
console.log(chalk.green(`created and switched to new branch ${chalk.bold.blue(branch)}`))
} catch (e) {
if (e.code == 'EEXIST') {
cfg.set('CURRENT_BRANCH', `${branch}`)
console.log(chalk.red(`switched to already existing branch ${chalk.green(branch)}`))
} else {
console.log(e)
}
} finally {
if (filehandle !== undefined)
await filehandle.close();
}
}
else {
let files;
try {
files = await fs.readdir(`${NOTE_DIR}`, 'utf-8');
let changed = false;
files.forEach(e => {
e = e.split('.')[0] // only file(branch) name
if (e === branch) {
changed = true;
console.log(`${chalk.green('switched to branch ')}${chalk.bold.blue(branch)}`)
cfg.set('CURRENT_BRANCH', `${branch}`)
}
})
if (!changed) {
throw new Error('no such branch exists.');
}
} catch (e) {
console.log(chalk.red(e.message));
}
}
})
program
.command('merge <branch>')
.description('merge branch into current branch')
.action(async (branch) => {
let filehandle;
let currentFilehandle;
try {
if (!isInitialised(CONFIG)) throw new Error("Initialize notes directory to begin !");
if (branch === CURRENT_BRANCH) throw ({ errno: 8989, message: 'on same branch' })
filehandle = await fs.open(`${NOTE_DIR}${branch}.txt`, 'r');
data = await filehandle.readFile('utf-8');
currentFilehandle = await fs.open(`${NOTE_DIR}${CURRENT_BRANCH}.txt`, 'a', 666);
await fs.appendFile(currentFilehandle, data, 'utf-8');
await fs.unlink(`${NOTE_DIR}${branch}.txt`);
} catch (e) {
if (e.errno === -2) {
console.log(chalk.red('no such branch'));
} else if (e.errno === 8989) {
console.log(chalk.red(e.message));
} else
console.log(e.message);
} finally {
if (filehandle !== undefined)
await filehandle.close();
if (currentFilehandle !== undefined)
await currentFilehandle.close();
}
})
program
.command('rebase')
.description('delete notes on branch')
.action(async () => {
let filehandle;
try {
if (!isInitialised(CONFIG)) throw new Error("Initialize notes directory to begin !");
filehandle = await fs.open(`${NOTE_DIR}${CURRENT_BRANCH}.txt`, "r+");
data = await filehandle.readFile('utf-8');
if (filehandle !== undefined)
await filehandle.close();
console.log(chalk.green(`On branch ${chalk.bold.blue(CURRENT_BRANCH)}`));
notes = data.split('\n');
notes.pop();
if (notes.length === 0) {
console.log(chalk.red('no notes found'));
return;
}
let choices = [];
choices = notes.map(i => { return { name: i } });
let resp = await inquirer
.prompt([
{
type: 'checkbox',
message: 'Select Notes to Delete',
name: 'delete',
choices,
}
])
if (resp.delete.length !== 0) {
notes = notes.filter(n => {
return !resp.delete.includes(n)
})
let updatedNotes = notes.reduce((acc, curr) => {
acc = acc + curr + "\n";
return acc;
}, "")
await fs.writeFile(`${NOTE_DIR}${CURRENT_BRANCH}.txt`, updatedNotes)
console.log(`saved`)
}
} catch (e) {
console.log(chalk.red(e.message));
}
})
program.parse(process.argv);