Skip to content

Commit 86cfdca

Browse files
committed
[Cache] Add cache command.
Signed-off-by: Eric Wang <[email protected]>
1 parent 65aaa21 commit 86cfdca

File tree

3 files changed

+94
-0
lines changed

3 files changed

+94
-0
lines changed

Diff for: lib/cache.js

+16
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
var fs = require('fs');
2+
var path = require('path');
23

34
var h = require('./helper');
45

@@ -29,4 +30,19 @@ cache.del = function(k) {
2930
return true;
3031
};
3132

33+
cache.list = function() {
34+
var dir = h.getCacheDir();
35+
if (!fs.existsSync(dir)) return [];
36+
37+
return fs.readdirSync(dir).map(function(filename) {
38+
var k = path.basename(filename, '.json');
39+
var stat = fs.statSync(h.getCacheFile(k));
40+
return {
41+
name: k,
42+
size: stat.size,
43+
mtime: stat.mtimeMs
44+
};
45+
});
46+
};
47+
3248
module.exports = cache;

Diff for: lib/commands/cache.js

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
var log = require('loglevel');
2+
var sprintf = require('sprintf-js').sprintf;
3+
var _ = require('underscore');
4+
5+
var cache = require('../cache');
6+
var h = require('../helper');
7+
8+
var cmd = {
9+
command: 'cache',
10+
desc: 'show cached problems',
11+
builder: {
12+
all: {
13+
alias: 'a',
14+
type: 'boolean',
15+
describe: 'Delete all cached problems',
16+
default: false
17+
},
18+
delete: {
19+
alias: 'd',
20+
type: 'string',
21+
describe: 'Delete specific cached problem'
22+
}
23+
}
24+
};
25+
26+
cmd.handler = function(argv) {
27+
if (argv.delete === undefined) {
28+
_.sortBy(cache.list(), function(f) {
29+
var x = parseInt(f.name.split('.')[0], 10);
30+
if (_.isNaN(x)) x = 0;
31+
return x;
32+
})
33+
.forEach(function(f) {
34+
log.info(sprintf('%-50s %8s %s ago',
35+
f.name,
36+
h.prettySize(f.size),
37+
h.prettyTime(f.mtime)));
38+
});
39+
} else if (argv.all) {
40+
cache.list().forEach(function(f) {
41+
if (f.name === '.user') return;
42+
cache.del(f.name);
43+
});
44+
} else {
45+
cache.del(argv.delete);
46+
}
47+
};
48+
49+
module.exports = cmd;

Diff for: lib/helper.js

+29
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,35 @@ h.prettyText = function(text, yesNo) {
2323
}
2424
};
2525

26+
h.prettySize = function(size) {
27+
var units = 'BKMG';
28+
var i = 0;
29+
while (size >= 1024 && i < units.length) {
30+
size /= 1024.0;
31+
++i;
32+
}
33+
return size.toFixed(2) + units[i];
34+
};
35+
36+
h.prettyTime = function(t) {
37+
var units = [
38+
[60, 'secs'],
39+
[60, 'mins'],
40+
[24, 'hours'],
41+
[7, 'weeks'],
42+
[4, 'months'],
43+
[12, 'years']
44+
];
45+
46+
var d = (Date.now() - t) / 1000;
47+
var i = 0;
48+
while (d > units[i][0] && i < units.length) {
49+
d /= units[i][0];
50+
++i;
51+
}
52+
return d.toFixed(0) + ' ' + units[i][1];
53+
};
54+
2655
h.levelToName = function(level) {
2756
switch (level) {
2857
case 1: return 'Easy';

0 commit comments

Comments
 (0)