/
dedup.js
305 lines (271 loc) · 8.44 KB
/
dedup.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
/**
* node-dedup.js
*
* @version 0.0.1
* @date last modified 11/28/2011
* @author NodeSocket <http://www.nodesocket.com> <hello@nodesocket.com>
* @copyright (c) 2011 NodeSocket. All Rights Reserved.
*/
/*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
////
// Requires
////
var logger = require('./lib/logger');
var progress_hash = require('./lib/progressbar').create(process.stdout);
var progress_deduplicate = require('./lib/progressbar').create(process.stdout);
var exec = require('child_process').exec;
var fs = require('fs');
var crypto = require('crypto');
var path = require('path');
////
// dedup
////
var dedup = module.exports = {
//Verion of node-dedup
version: '0.0.1',
//Base directory path to start working from
base: null,
//Array of objects; each object contains a hash, path, and link
files: [],
////
// init
// parameters: p_base (String) base directory path to start from
////
init: function(p_base) {
//Confirm that p_base directory exists
path.exists(p_base, function(p_exists) {
//Base directory path exists
if(p_exists) {
//Set global base equal to p_base, removes trailing slashes if it exists
dedup.base = p_base.replace(/\/$/, '');
logger.log("Notice: Deduplicating from '" + dedup.base + "'.", 'notice');
//Check if node-dedup database directory exists
path.exists(dedup.base + '/node-dedup-db', function(p_exists) {
//Database directory does not exist
if(!p_exists) {
logger.log("Notice: No database directory found in '" + dedup.base + "', automatically creating it.", 'notice');
//Create database directory
fs.mkdir(dedup.base + '/node-dedup-db', function(p_err) {
if(p_err) {
logger.log(p_err.message, 'error');
} else {
//Call getFiles
dedup.getFiles(dedup.base);
}
});
}
//Database directory exists
else {
//Call getFiles
dedup.getFiles(dedup.base);
}
});
}
//Base directory path does not exist
else {
logger.log("Error: Provided base directory '" + p_base + "' does not exist.", 'error');
process.exit(-2);
}
});
},
////
// getFiles
// parameters: p_base (String) base directory path to start from
////
getFiles: function(p_base) {
logger.log("Reading files...", 'info');
////
// todo:
// It may be faster to use native node and fs.readdir() recursively instead of find. Needs benchmarking.
////
//Find files, exclude .DS_Store and everything inside node-dedup-db directory
exec('find ' + p_base + ' -type f \\( -not -iname ".DS_Store" -and -not -ipath "' + dedup.base + '/node-dedup-db/*" \\) | sort', function(p_err, p_stdout, p_stderr) {
if(p_err) {
logger.log(p_err.message, 'error');
} else if(p_stderr) {
logger.log(p_stderr, 'error');
} else {
//Split the paths on newline into an array
var paths = p_stdout.split('\n');
//Remove the last element if its empty
if(paths[paths.length - 1] === '') {
paths.pop();
}
//Call generateHashes
dedup.generateHashes(paths);
}
});
},
////
// generateHashes
// parameters: p_paths (Array) list of file paths to generate hashes for
////
generateHashes: function(p_paths) {
//Tracks callbacks
var counter = 0;
if(p_paths.length > 0) {
logger.log("Generating hashes... (Can take a while if there are a lot of files).", 'info');
}
//Loop through file paths
for(var i = 0; i < p_paths.length; i++) {
var hash = crypto.createHash('sha256');
var stream = fs.ReadStream(p_paths[i]);
//OnData
stream.on('data', function(p_data) {
this.hash.update(p_data);
}.bind({
hash: hash
}));
//OnEnd
stream.on('end', function() {
//Add file object to the global files array
dedup.files.push({
hash: this.hash.digest('hex'),
path: this.path,
link: null
});
//Increment counter
counter++;
//Update progress bar
progress_hash.update(counter / p_paths.length);
//Done looping through paths
if(counter === p_paths.length) {
//Call findDuplicates
dedup.findDuplicates();
}
}.bind({
hash: hash,
path: p_paths[i]
}));
}
},
////
// findDuplicates
// parameters: none
////
findDuplicates: function() {
//Sort files array by hash, neat trick; thanks stackoverflow.
dedup.files.sort(function(p_a, p_b) {
return p_a.hash.localeCompare(p_b.hash);
});
//A pointer to array objects for previous, current, and the file that is kept
var prev = null;
var current = null;
var keep = null;
//Keeps track of callbacks so we know when we are done
var total = 0;
var callbacks = 0;
if(dedup.files.length > 0) {
logger.log("\n\tDeduplicating...", 'info');
}
//Loop through files array
for(var i = 0; i < dedup.files.length; i++) {
//Set previous, assuming not the first time through the loop
if(i > 0) {
prev = dedup.files[i - 1];
}
//Set current
current = dedup.files[i];
//Set keep to current, if its the first time through the loop
if(prev === null) {
keep = current;
//Previous equals current
} else if(prev.hash === current.hash) {
//Increment total
total++;
//Call deleteAndSymlink
dedup.deleteAndSymlink(keep, current, function() {
//Increment callbacks
callbacks++;
//Update progress bar
progress_deduplicate.update(callbacks / total);
//Done with all deletes and symlinks
if(callbacks === total) {
//Call writeDatabaseFile
dedup.writeDatabaseFile();
}
});
}
//New file, set keep to current
else {
keep = current;
}
}
},
////
// deleteAndSymlink
// parameters: p_keep (Object) File to link too
// p_delete (Object) File to delete and create symbolic link from
// p_callback (Function) Called on complete
////
deleteAndSymlink: function(p_keep, p_delete, p_callback) {
//Delete p_delete file
fs.unlink(p_delete.path, function(p_err) {
if(p_err) {
logger.log(p_err.message, 'error');
} else {
//Create the symbolic link from p_keep path to the p_delete path
fs.symlink(p_keep.path, p_delete.path, function(p_err) {
if(p_err) {
logger.log(p_err.message, 'error');
} else {
//Update p_delete link to p_keep's path
p_delete.link = p_keep.path;
//Call the callback, if it exists
typeof p_callback === "function" ? p_callback.call() : null;
}
});
}
});
},
////
// writeDatabaseFile
// parameters: none
////
writeDatabaseFile: function() {
var db_file_name = Math.round((new Date()).getTime() / 1000) + '.json';
logger.log("\n\tNotice: Writing database file '" + db_file_name + "' to database directory '" + dedup.base + "/node-dedup-db'", 'notice');
//Write the database file in base directory path with the filename being UNIX timestamp.json
fs.writeFile(dedup.base + "/node-dedup-db/" + db_file_name, JSON.stringify(dedup.files), 'utf8', function(p_err) {
if(p_err) {
logger.log(p_err.message, 'error');
} else {
logger.log("Complete!", 'info');
//Exit nicely
process.exit(0);
}
});
}
}
////
// Execution begins
////
//argv[2] undefined, show error and exit
if(typeof process.argv[2] === "undefined") {
logger.log("Usage: node dedup.js /Users/john", 'warning');
process.exit(-1);
}
//argv[2] is set
else {
if(process.argv[2] === '-v' || process.argv[2] === '--version' ) {
console.log(dedup.version);
} else {
//Call init, passing argv[2] as the base directory path
dedup.init(process.argv[2]);
}
}