index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const path = require('path');
  3. const fs = require('fs');
  4. const commonDir = require('commondir');
  5. const pkgDir = require('pkg-dir');
  6. const makeDir = require('make-dir');
  7. const {env, cwd} = process;
  8. const isWritable = path => {
  9. try {
  10. fs.accessSync(path, fs.constants.W_OK);
  11. return true;
  12. } catch (_) {
  13. return false;
  14. }
  15. };
  16. function useDirectory(directory, options) {
  17. if (options.create) {
  18. makeDir.sync(directory);
  19. }
  20. if (options.thunk) {
  21. return (...arguments_) => path.join(directory, ...arguments_);
  22. }
  23. return directory;
  24. }
  25. function getNodeModuleDirectory(directory) {
  26. const nodeModules = path.join(directory, 'node_modules');
  27. if (
  28. !isWritable(nodeModules) &&
  29. (fs.existsSync(nodeModules) || !isWritable(path.join(directory)))
  30. ) {
  31. return;
  32. }
  33. return nodeModules;
  34. }
  35. module.exports = (options = {}) => {
  36. if (env.CACHE_DIR && !['true', 'false', '1', '0'].includes(env.CACHE_DIR)) {
  37. return useDirectory(path.join(env.CACHE_DIR, options.name), options);
  38. }
  39. let {cwd: directory = cwd()} = options;
  40. if (options.files) {
  41. directory = commonDir(directory, options.files);
  42. }
  43. directory = pkgDir.sync(directory);
  44. if (!directory) {
  45. return;
  46. }
  47. const nodeModules = getNodeModuleDirectory(directory);
  48. if (!nodeModules) {
  49. return undefined;
  50. }
  51. return useDirectory(path.join(directory, 'node_modules', '.cache', options.name), options);
  52. };