source-store.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. var util = require('util'),
  2. os = require('os'),
  3. path = require('path'),
  4. mkdirp = require('mkdirp'),
  5. rimraf = require('rimraf'),
  6. fs = require('fs');
  7. function SourceStore(/*opts*/) {
  8. }
  9. SourceStore.prototype.registerSource = function (/* filePath, sourceText */) {
  10. throw new Error('registerSource must be overridden');
  11. };
  12. SourceStore.prototype.getSource = function (/* filePath */) {
  13. throw new Error('getSource must be overridden');
  14. };
  15. SourceStore.prototype.dispose = function () {
  16. };
  17. function MemoryStore() {
  18. this.data = {};
  19. }
  20. util.inherits(MemoryStore, SourceStore);
  21. MemoryStore.prototype.registerSource = function (filePath, sourceText) {
  22. this.data[filePath] = sourceText;
  23. };
  24. MemoryStore.prototype.getSource = function (filePath) {
  25. return this.data[filePath] || null;
  26. };
  27. function FileStore(opts) {
  28. opts = opts || {};
  29. var tmpDir = opts.tmpdir || os.tmpdir();
  30. this.counter = 0;
  31. this.mappings = [];
  32. this.basePath = path.resolve(tmpDir, '.istanbul', 'cache_');
  33. mkdirp.sync(path.dirname(this.basePath));
  34. }
  35. util.inherits(FileStore, SourceStore);
  36. FileStore.prototype.registerSource = function (filePath, sourceText) {
  37. if (this.mappings[filePath]) {
  38. return;
  39. }
  40. this.counter += 1;
  41. var mapFile = this.basePath + this.counter;
  42. this.mappings[filePath] = mapFile;
  43. fs.writeFileSync(mapFile, sourceText, 'utf8');
  44. };
  45. FileStore.prototype.getSource = function (filePath) {
  46. var mapFile = this.mappings[filePath];
  47. if (!mapFile) {
  48. return null;
  49. }
  50. return fs.readFileSync(mapFile, 'utf8');
  51. };
  52. FileStore.prototype.dispose = function () {
  53. this.mappings = [];
  54. rimraf.sync(path.dirname(this.basePath));
  55. };
  56. module.exports = {
  57. create: function (type, opts) {
  58. opts = opts || {};
  59. type = (type || 'memory').toLowerCase();
  60. if (type === 'file') {
  61. return new FileStore(opts);
  62. }
  63. return new MemoryStore(opts);
  64. }
  65. };