/
index.js
114 lines (84 loc) · 2.24 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
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
util = require('util'),
async = require('async'),
moment = require('moment'),
events = require('events'),
findit = require('findit');
module.exports = Scythe;
function Scythe (opts) {
opts = opts || {};
var self = this;
this.threshold = opts.threshold || new Date - 604800000;
this.searchPaths = opts.searchPaths || ".";
this.truncate = opts.truncate || true;
this.limit = opts.limit || 5;
this.simulation = ! opts.force;
this.verbose = opts.verbose || this.simulation;
}
util.inherits(Scythe, events.EventEmitter);
Scythe.prototype.walkPath = function (dir, cb) {
var self = this;
var finder = findit(dir);
var dirs = [];
finder.on('directory', function (d, stat, stop) {
if (dir !== d)
dirs.push(d);
});
finder.on('file', function (file, stat) {
if (stat.mtime < self.threshold) {
if (! self.simulation) {
try {
fs.unlinkSync(path.resolve(file));
} catch (e) {
self.emit('error', JSON.stringify(e));
}
}
self.emit('unlinkFile', file);
} else {
self.emit('preserveFile', file);
}
});
finder.on('end', function () {
dirs = self.sortDirectories(dirs);
if (self.truncate) {
self.truncateDirs(dirs);
}
return cb(null);
});
};
Scythe.prototype.sortDirectories = function (dirs) {
return _.sortBy(dirs, function (dir) {
dir = dir.split(path.sep);
return - dir.length;
});
};
Scythe.prototype.execute = function (cb) {
var self = this;
async.each(this.searchPaths, this.walkPath.bind(this), function (e) {
if (e) {
self.emit('error', JSON.stringify(e));
return cb(JSON.stringify(e));
} else {
self.emit('complete');
return cb();
}
});
};
Scythe.prototype.truncateDirs = function (dirs) {
var self = this;
_.each(dirs, function (dir) {
var files = fs.readdirSync(dir);
if (files.length > 0) {
self.emit('preserveDir', dir);
return;
}
try {
if (! self.simulation) fs.rmdirSync(path.resolve(dir));
self.emit('unlinkDir', dir);
} catch (e) {
self.emit('error', JSON.stringify(e));
}
});
};