-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
executable file
·103 lines (85 loc) · 2.58 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
#!/usr/bin/env node
const program = require('commander');
const chokidar = require('chokidar');
const gitignore = require('parse-gitignore');
const mkdirp = require('mkdirp');
const fs = require('fs');
const getDirName = require('path').dirname;
const log = console.log.bind(console);
const changesMap = {};
const type2printFucmap = {
'added' : (path) => { log( `\x1b[92m${path}\x1b[0m` ) },
'changed': (path) => { log( `\x1b[93m${path}\x1b[0m` ) },
'removed': (path) => { log( `\x1b[91m${path}\x1b[0m` ) }
}
initProgramm(program);
const patterns = gitignore( program.poll + '/.gitignore' ).concat( gitignore( program.copy + '/.gitignore' ) );
log( 'Ignored patterns: ', patterns.map( p => `${program.poll}/${p}` ) );
const watcher = chokidar.watch(program.poll, {
ignored: patterns.map( p => `${program.poll}/${p}` ),
ignoreInitial : true,
persistent: true
});
watcher
.on('add', (path) => {
addInChanges( changesMap, path, 'added' );
printChanges( changesMap )
})
.on('addDir', (path) => {
log('Directory', path, 'has been added');
addInChanges( changesMap, path, 'added' );
})
.on('change', (path) => {
addInChanges( changesMap, path, 'changed' );
printChanges( changesMap );
})
.on('unlink', (path) => {
addInChanges( changesMap, path, 'removed' );
printChanges( changesMap )
})
.on('unlinkDir', (path) => {
log('Directory', path, 'has been removed');
})
.on('error', (error) => {
log('Error happened', error);
})
.on('ready', () => {
log('Initial scan complete. Ready for changes.');
})
function initProgramm(program) {
program
.version('0.1.0')
.option('-p, --poll [value]', 'Polling directory')
.option('-c, --copy [value]', 'Copy to directory')
.parse(process.argv);
log('Polling directory: ', program.poll);
log('Copy to directory: ', program.copy);
}
function addInChanges( changesMap, path, type ) {
changesMap[path] = type;
if ( type === 'remove' )
remove( path );
else
copy( path )
}
function printChanges(changesMap) {
log('\n');
for (var prop in changesMap) {
type2printFucmap[changesMap[prop]](prop);
};
}
function copy( oldPath ) {
if ( !!program.copy ) {
let newPath = oldPath.replace(program.poll, program.copy);
mkdirp(getDirName(newPath), function (err) {
if (err) return log(err);
fs.createReadStream( oldPath ).pipe(fs.createWriteStream( newPath ));
})
}
}
function remove( oldPath ) {
if ( !!program.copy ) {
let newPath = oldPath.replace(program.poll, program.copy);
fs.unlink( newPath );
}
}