1 |
|
/* |
2 |
|
Copyright (c) 2012, Yahoo! Inc. All rights reserved. |
3 |
|
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. |
4 |
|
*/ |
5 |
|
|
6 |
1 |
var util = require('util'), |
7 |
|
path = require('path'), |
8 |
|
os = require('os'), |
9 |
|
fs = require('fs'), |
10 |
|
mkdirp = require('mkdirp'), |
11 |
|
Store = require('./index'); |
12 |
|
|
13 |
1 |
function makeTempDir() { |
14 |
1 |
var dir = path.join(os.tmpDir ? os.tmpDir() : (process.env.TMPDIR || '/tmp'), 'ts' + new Date().getTime()); |
15 |
1 |
mkdirp.sync(dir); |
16 |
1 |
return dir; |
17 |
|
} |
18 |
|
/** |
19 |
|
* a `Store` implementation using temporary files. |
20 |
|
* |
21 |
|
* Usage |
22 |
|
* ----- |
23 |
|
* |
24 |
|
* var store = require('istanbul').Store.create('tmp'); |
25 |
|
* |
26 |
|
* |
27 |
|
* @class TmpStore |
28 |
|
* @extends Store |
29 |
|
* @param {Object} opts Optional. |
30 |
|
* @param {String} [opts.tmp] a pre-existing directory to use as the `tmp` directory. When not specified, a random directory |
31 |
|
* is created under `os.tmpDir()` |
32 |
|
* @constructor |
33 |
|
*/ |
34 |
1 |
function TmpStore(opts) { |
35 |
1 |
opts = opts || {}; |
36 |
1 |
this.tmp = opts.tmp || makeTempDir(); |
37 |
1 |
this.map = {}; |
38 |
1 |
this.seq = 0; |
39 |
1 |
this.prefix = 't' + new Date().getTime() + '-'; |
40 |
|
} |
41 |
|
|
42 |
1 |
TmpStore.TYPE = 'tmp'; |
43 |
1 |
util.inherits(TmpStore, Store); |
44 |
|
|
45 |
1 |
Store.mix(TmpStore, { |
46 |
|
generateTmpFileName: function () { |
47 |
2 |
this.seq += 1; |
48 |
2 |
return this.prefix + this.seq + '.tmp'; |
49 |
|
}, |
50 |
|
|
51 |
|
set: function (key, contents) { |
52 |
2 |
var tmpFile = this.generateTmpFileName(); |
53 |
2 |
fs.writeFileSync(tmpFile, contents, 'utf8'); |
54 |
2 |
this.map[key] = tmpFile; |
55 |
|
}, |
56 |
|
|
57 |
|
get: function (key) { |
58 |
3 |
var tmpFile = this.map[key]; |
59 |
3 |
if (!tmpFile) { throw new Error('Unable to find tmp entry for [' + tmpFile + ']'); } |
60 |
2 |
return fs.readFileSync(tmpFile, 'utf8'); |
61 |
|
}, |
62 |
|
|
63 |
|
hasKey: function (key) { |
64 |
3 |
return !!this.map[key]; |
65 |
|
}, |
66 |
|
|
67 |
|
keys: function () { |
68 |
4 |
return Object.keys(this.map); |
69 |
|
}, |
70 |
|
|
71 |
|
dispose: function () { |
72 |
1 |
var map = this.map; |
73 |
1 |
Object.keys(map).forEach(function (key) { |
74 |
2 |
fs.unlinkSync(map[key]); |
75 |
|
}); |
76 |
1 |
this.map = {}; |
77 |
|
} |
78 |
|
}); |
79 |
|
|
80 |
1 |
module.exports = TmpStore; |
81 |
|
|