aboutsummaryrefslogtreecommitdiff
path: root/node_modules/stylus/lib/cache/fs.js
blob: 910bf9fb520d163d89aab9c7b30948f7df83c0b9 (plain)
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
/**
 * Module dependencies.
 */

var crypto = require('crypto')
  , fs = require('fs')
  , join = require('path').join
  , version = require('../../package').version
  , nodes = require('../nodes');

var FSCache = module.exports = function(options) {
  options = options || {};
  this._location = options['cache location'] || '.styl-cache';
  if (!fs.existsSync(this._location)) fs.mkdirSync(this._location);
};

/**
 * Set cache item with given `key` to `value`.
 *
 * @param {String} key
 * @param {Object} value
 * @api private
 */

FSCache.prototype.set = function(key, value) {
  fs.writeFileSync(join(this._location, key), JSON.stringify(value));
};

/**
 * Get cache item with given `key`.
 *
 * @param {String} key
 * @return {Object}
 * @api private
 */

FSCache.prototype.get = function(key) {
  var data = fs.readFileSync(join(this._location, key), 'utf-8');
  return JSON.parse(data, FSCache.fromJSON);
};

/**
 * Check if cache has given `key`.
 *
 * @param {String} key
 * @return {Boolean}
 * @api private
 */

FSCache.prototype.has = function(key) {
  return fs.existsSync(join(this._location, key));
};

/**
 * Generate key for the source `str` with `options`.
 *
 * @param {String} str
 * @param {Object} options
 * @return {String}
 * @api private
 */

FSCache.prototype.key = function(str, options) {
  var hash = crypto.createHash('sha1');
  hash.update(str + version + options.prefix);
  return hash.digest('hex');
};

/**
 * JSON to Stylus nodes converter.
 *
 * @api private
 */

FSCache.fromJSON = function(key, val) {
  if (val && val.__type) {
    val.__proto__ = nodes[val.__type].prototype;
  }
  return val;
};