source-store.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Copyright 2015, Yahoo Inc.
  3. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
  4. */
  5. 'use strict';
  6. const fs = require('fs');
  7. const os = require('os');
  8. const path = require('path');
  9. const mkdirp = require('make-dir');
  10. const rimraf = require('rimraf');
  11. /* This exists for compatibility only to avoid changing the
  12. * prototype chain. */
  13. class SourceStore {}
  14. class MemoryStore extends SourceStore {
  15. constructor() {
  16. super();
  17. this.data = {};
  18. }
  19. registerSource(filePath, sourceText) {
  20. this.data[filePath] = sourceText;
  21. }
  22. getSource(filePath) {
  23. return this.data[filePath] || null;
  24. }
  25. dispose() {}
  26. }
  27. class FileStore extends SourceStore {
  28. constructor(opts = {}) {
  29. super();
  30. const tmpDir = opts.tmpdir || os.tmpdir();
  31. this.counter = 0;
  32. this.mappings = [];
  33. this.basePath = path.resolve(tmpDir, '.istanbul', 'cache_');
  34. mkdirp.sync(path.dirname(this.basePath));
  35. }
  36. registerSource(filePath, sourceText) {
  37. if (this.mappings[filePath]) {
  38. return;
  39. }
  40. this.counter += 1;
  41. const mapFile = this.basePath + this.counter;
  42. this.mappings[filePath] = mapFile;
  43. fs.writeFileSync(mapFile, sourceText, 'utf8');
  44. }
  45. getSource(filePath) {
  46. const mapFile = this.mappings[filePath];
  47. if (!mapFile) {
  48. return null;
  49. }
  50. return fs.readFileSync(mapFile, 'utf8');
  51. }
  52. dispose() {
  53. this.mappings = [];
  54. rimraf.sync(path.dirname(this.basePath));
  55. }
  56. }
  57. module.exports = {
  58. create(type = 'memory', opts = {}) {
  59. if (type.toLowerCase() === 'file') {
  60. return new FileStore(opts);
  61. }
  62. return new MemoryStore(opts);
  63. }
  64. };