-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
77 lines (66 loc) · 2.08 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
#!/usr/local/bin/node
var path = require('path');
var fs = require('fs');
var home = process.env.HOME;
var destFile = home + '/.zsh_history';
// process.argv: [node path, file path, arg[0] ]
var syncFile = process.argv[2];
function readFile(path) {
return new Promise(function (resolve, reject) {
if (!fs.existsSync(path)) {
console.warn(path + ' isn\'t exists, creating...')
fs.writeFileSync(path, '')
}
fs.readFile(path, 'utf8', function (err, data) {
if (err) {
console.log(err);
reject(err);
}
resolve(data.split('\n: ').filter(function (command) {
return command && command.length;
}).map(function (command) {
command = command.replace(/(\\| )$/igm, '');
if (command.slice(0, 2) !== ': ') {
return ': ' + command + '\n';
}
return command + '\n';
}));
});
});
}
function writeFile(path, content) {
return new Promise(function (resolve, reject) {
fs.writeFile(path, content, 'utf8', function (err) {
if (err) {
reject(err);
} else {
resolve(content);
}
});
});
}
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
Promise.all([readFile(home + '/.zsh_history'), readFile(syncFile)])
.then(function (values) {
var sourceItems = values[0];
var newItems = values[1];
var items = [];
Array.prototype.push.apply(items, sourceItems);
Array.prototype.push.apply(items, newItems);
items = items.filter(onlyUnique).sort();
var newContent = items.join('');
writeFile(destFile, newContent).then(function () {
writeFile(syncFile, newContent);
console.log(`\n======== Start ${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()} ========`);
console.log('merge succeed! \nexisted commands '
+ sourceItems.length
+ '\nnew commands '
+ newItems.length
+ '\nduplicated '
+ (sourceItems.length + newItems.length - items.length)
+ '\ntotal ' + items.length);
console.log('======== End ========');
});
});