-
Notifications
You must be signed in to change notification settings - Fork 42
/
main.ts
389 lines (344 loc) · 12.4 KB
/
main.ts
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
/* eslint-disable max-len */
import * as fse from 'fs-extra';
import { intersection } from 'lodash';
import {
isAbsolute, join, resolve, relative,
} from 'path';
import { Index } from './src/index';
import { Commit } from './src/commit';
import { DirItem, OSWALK, osWalk } from './src/io';
import { Reference } from './src/reference';
import {
StatusEntry, FILTER, Repository, RESET,
} from './src/repository';
import { TreeDir, TreeFile } from './src/treedir';
const program = require('commander');
const chalk = require('chalk');
program
.version('0.9.1')
.description('SnowFS - a fast, scalable version control file storage for graphic files.');
program
.command('init [path] [commondir]')
.option('--debug', 'add more debug information on errors')
.description('initialize a SnowFS repository')
.action(async (path: string, commondir?: string, opts?: any) => {
const repoPath: string = path ?? '.';
try {
await Repository.initExt(repoPath, { commondir });
} catch (error) {
if (opts.debug) {
throw error;
} else {
console.log(`fatal: ${error.message}`);
process.exit(-1);
}
}
console.log(`Initialized empty SnowFS repository at ${resolve(repoPath)}`);
});
program
.command('rm [path]')
.option('--debug', 'add more debug information on errors')
.description('Remove files from the working tree and from the index')
.action(async (path: string, opts?: any) => {
try {
const repo = await Repository.open(process.cwd());
const filepathAbs: string = isAbsolute(path) ? path : join(repo.workdir(), path);
fse.unlinkSync(filepathAbs);
const index: Index = repo.getIndex();
index.deleteFiles([path]);
await index.writeFiles();
} catch (error) {
if (opts.debug) {
throw error;
} else {
console.log(`fatal: ${error.message}`);
process.exit(-1);
}
}
});
program
.command('add <path>')
.option('--debug', 'add more debug information on errors')
.description('add file contents to the index')
.action(async (path: string, opts?: any) => {
try {
const repo = await Repository.open(process.cwd());
const files: string[] = [];
const stats: fse.Stats = fse.statSync(path);
if (stats.isDirectory()) {
const dirItems: DirItem[] = await osWalk(path, OSWALK.FILES);
for (const dirItem of dirItems) files.push(resolve(dirItem.path));
} else files.push(resolve(path));
if (files.length === 0) return;
const statusFiles: StatusEntry[] = await repo.getStatus(FILTER.INCLUDE_UNTRACKED);
const index: Index = repo.getIndex();
index.addFiles(intersection(files, statusFiles.map((v: StatusEntry) => resolve(v.path))));
await index.writeFiles();
} catch (error) {
if (opts.debug) {
throw error;
} else {
console.log(`fatal: ${error.message}`);
process.exit(-1);
}
}
});
program
.command('branch [branch-name] [start-point]')
.option('--debug', 'add more debug information on errors')
.option('--no-color')
.description('create a new branch')
.action(async (branchName: string | undefined, startPoint: string, opts: any) => {
if (opts.noColor) {
chalk.level = 0;
}
try {
const repo = await Repository.open(process.cwd());
await repo.createNewReference(branchName, startPoint, startPoint);
} catch (error) {
if (opts.debug) {
throw error;
} else {
console.log(`fatal: ${error.message}`);
process.exit(-1);
}
}
});
const checkoutDesc = `checkout a commit, or create a branch
${chalk.bold('Examples')}
Checkout a commit
$ snow checkout 75f4d24726ce95dde1376c19a1ce16e53e7b1db7ffcb508f8abf57026784c040
- If there is only one reference pointing to '75f4d24..' then the reference is checked out.
If you still need to be in a detached head after the command, pass '-d'.
- If there is more than one reference pointing to '75f4d24..' an error is raised.
- If no reference is pointing to '75f4d24..', then the commit is checked out.
Create a new branch
$ snow checkout -b <branch-name> <start-point>
- The branch must not exist yet, otherwise an error is raised`;
program
.command('checkout [target]')
.option('-b, --branch <branch-name>')
.option('-d, --detach', 'detach the branch')
.option('-n, --no-reset', "don't modify the worktree")
.option('--debug', 'add more debug information on errors')
.option('--no-color')
.description(checkoutDesc)
.action(async (target: string | undefined, opts: any) => {
if (opts.noColor) {
chalk.level = 0;
}
try {
const repo = await Repository.open(process.cwd());
if (opts.branch) { // snow checkout -b branch-name
await repo.createNewReference(opts.branch[0], repo.getHead().hash, repo.getHead().hash);
} else if (target) { // snow checkout [hash]
let reset: RESET = RESET.NONE;
if (opts.reset) {
reset |= RESET.DEFAULT;
}
if (opts.detach) {
reset |= RESET.DETACH;
}
await repo.restore(target, reset);
}
} catch (error) {
if (opts.debug) {
throw error;
} else {
console.log(`fatal: ${error.message}`);
process.exit(-1);
}
}
});
program
.command('status')
.option('--no-color')
.option('--output [format]', "currently supported output formats 'json', 'json-pretty'")
.option('--debug', 'add more debug information on errors')
.description('show the working tree status')
.action(async (opts: any) => {
if (opts.noColor) {
chalk.level = 0;
}
try {
const repo = await Repository.open(process.cwd());
const files: StatusEntry[] = await repo.getStatus(FILTER.INCLUDE_IGNORED | FILTER.INCLUDE_UNTRACKED);
const newFiles: StatusEntry[] = [];
const modifiedFiles: StatusEntry[] = [];
const deletedFiles: StatusEntry[] = [];
for (const file of files) {
if (file.isNew()) {
newFiles.push(file);
} else if (file.isModified()) {
modifiedFiles.push(file);
} else if (file.isDeleted()) {
deletedFiles.push(file);
}
}
const index = repo.getIndex();
if (opts.output === 'json' || opts.output === 'json-pretty') {
const o = { new_files: newFiles, modified_files: modifiedFiles, deleted_files: deletedFiles };
process.stdout.write(JSON.stringify(o, (key, value) => {
if (value instanceof StatusEntry) {
return {
path: value.path, isdir: value.isdir,
};
}
return value;
}, opts.output === 'json-pretty' ? ' ' : ''));
} else {
console.log(`On branch ${repo.getHead().getName()}`);
console.log('Changes not staged for commit:');
console.log('use "snow add <file>..." to update what will be committed');
// console.log(`use "snow restore <file>..." to discard changes in working directory`);
for (const modifiedFile of modifiedFiles) {
console.log(modifiedFile.path);
}
process.stdout.write('\n');
if (deletedFiles.length > 0) {
console.log('Deleted files:');
for (const deleteFile of deletedFiles) {
console.log(deleteFile.path);
}
} else {
console.log('no deleted changes added to commit (use "snow rm")');
}
process.stdout.write('\n');
if (newFiles.length > 0) {
console.log('New files:');
for (const newFile of newFiles) {
if (index.adds.has(relative(repo.workdir(), newFile.path))) {
process.stdout.write(chalk.red('+ '));
}
console.log(newFile.path);
}
} else {
console.log('no changes added to commit (use "snow add"');
}
}
} catch (error) {
if (opts.debug) {
throw error;
} else {
console.log(`fatal: ${error.message}`);
process.exit(-1);
}
}
});
program
.command('commit')
.option('-m, --message [message]', 'input file')
.option('--allow-empty', 'allow an empty commit without any changes, not set by default')
.option('--debug', 'add more debug information on errors')
.description('complete the commit')
.action(async (opts: any) => {
try {
const repo = await Repository.open(process.cwd());
const index: Index = repo.getIndex();
const newCommit: Commit = await repo.createCommit(index, opts.message, opts);
console.log(`[${repo.getHead().getName()} (root-commit) ${newCommit.hash.substr(0, 6)}]`);
} catch (error) {
if (opts.debug) {
throw error;
} else {
console.log(`fatal: ${error.message}`);
process.exit(-1);
}
}
});
program
.command('log')
.option('--no-color')
.option('-v, --verbose', 'verbose')
.option('--output [format]', "currently supported output formats 'json', 'json-pretty'")
.option('--debug', 'add more debug information on errors')
.description('print the log to the console')
.action(async (opts: any) => {
if (opts.noColor) {
chalk.level = 0;
}
try {
const repo = await Repository.open(process.cwd());
const commits: Commit[] = repo.getAllCommits();
commits.sort((a: Commit, b: Commit) => {
const aDate = a.date.getTime();
const bDate = b.date.getTime();
if (aDate > bDate) {
return 1;
} if (aDate < bDate) {
return -1;
}
return 0;
});
const refs: Reference[] = repo.getAllReferences();
const headHash: string = repo.getHead().hash;
const headName: string = repo.getHead().getName();
if (opts.output === 'json' || opts.output === 'json-pretty') {
const o = { commits: commits.reverse(), refs, head: headName };
process.stdout.write(JSON.stringify(o, (key, value) => {
if (value instanceof Commit) {
return {
hash: value.hash, message: value.message, date: value.date.getTime() / 1000.0, root: opts.verbose ? value.root : undefined,
};
} if (value instanceof TreeDir) {
return { path: value.path, hash: value.hash, children: value.children };
} if (value instanceof TreeFile) {
return {
path: value.path,
hash: value.hash,
ctime: value.ctime / 1000.0,
mtime: value.mtime / 1000.0,
size: value.size,
};
} if (value instanceof Reference) {
return { name: value.getName(), hash: value.hash };
}
return value;
}, opts.output === 'json-pretty' ? ' ' : ''));
} else {
for (const commit of commits.reverse()) {
process.stdout.write(chalk.magenta.bold(`commit: ${commit.hash}`));
const branchRefs: Reference[] = refs.filter((ref: Reference) => ref.hash === commit.hash);
if (repo.getHead().isDetached() && commit.hash === headHash) {
branchRefs.unshift(repo.getHead());
}
if (branchRefs.length > 0) {
process.stdout.write(' (');
process.stdout.write(`${branchRefs.map((ref) => {
if (ref.hash === commit.hash) {
if (ref.getName() === headName) {
if (headName === 'HEAD') {
return chalk.blue.bold(ref.getName());
}
return chalk.blue.bold(`HEAD -> ${ref.getName()}`);
}
return chalk.rgb(255, 165, 0)(ref.getName());
}
return null;
}).filter((x) => !!x).join(', ')}`);
process.stdout.write(')');
}
process.stdout.write('\n');
process.stdout.write(`Date: ${commit.date}\n`);
process.stdout.write(`\n ${commit.message}\n\n`);
if (opts.verbose) {
const files = commit.root.getAllTreeFiles({ entireHierarchy: true, includeDirs: true });
for (const file of Array.from(files)) {
process.stdout.write(` ${file[0]}\n`);
}
if (files.size > 0) {
process.stdout.write('\n');
}
}
}
}
} catch (error) {
if (opts.debug) {
throw error;
} else {
console.log(`fatal: ${error.message}`);
process.exit(-1);
}
}
});
program.parse(process.argv.filter((x) => x !== '--'));