[6a3a178] | 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 |
|
---|
| 8 | const {env, cwd} = process;
|
---|
| 9 |
|
---|
| 10 | const isWritable = path => {
|
---|
| 11 | try {
|
---|
| 12 | fs.accessSync(path, fs.constants.W_OK);
|
---|
| 13 | return true;
|
---|
| 14 | } catch (_) {
|
---|
| 15 | return false;
|
---|
| 16 | }
|
---|
| 17 | };
|
---|
| 18 |
|
---|
| 19 | function useDirectory(directory, options) {
|
---|
| 20 | if (options.create) {
|
---|
| 21 | makeDir.sync(directory);
|
---|
| 22 | }
|
---|
| 23 |
|
---|
| 24 | if (options.thunk) {
|
---|
| 25 | return (...arguments_) => path.join(directory, ...arguments_);
|
---|
| 26 | }
|
---|
| 27 |
|
---|
| 28 | return directory;
|
---|
| 29 | }
|
---|
| 30 |
|
---|
| 31 | function getNodeModuleDirectory(directory) {
|
---|
| 32 | const nodeModules = path.join(directory, 'node_modules');
|
---|
| 33 |
|
---|
| 34 | if (
|
---|
| 35 | !isWritable(nodeModules) &&
|
---|
| 36 | (fs.existsSync(nodeModules) || !isWritable(path.join(directory)))
|
---|
| 37 | ) {
|
---|
| 38 | return;
|
---|
| 39 | }
|
---|
| 40 |
|
---|
| 41 | return nodeModules;
|
---|
| 42 | }
|
---|
| 43 |
|
---|
| 44 | module.exports = (options = {}) => {
|
---|
| 45 | if (env.CACHE_DIR && !['true', 'false', '1', '0'].includes(env.CACHE_DIR)) {
|
---|
| 46 | return useDirectory(path.join(env.CACHE_DIR, 'find-cache-dir'), options);
|
---|
| 47 | }
|
---|
| 48 |
|
---|
| 49 | let {cwd: directory = cwd()} = options;
|
---|
| 50 |
|
---|
| 51 | if (options.files) {
|
---|
| 52 | directory = commonDir(directory, options.files);
|
---|
| 53 | }
|
---|
| 54 |
|
---|
| 55 | directory = pkgDir.sync(directory);
|
---|
| 56 |
|
---|
| 57 | if (!directory) {
|
---|
| 58 | return;
|
---|
| 59 | }
|
---|
| 60 |
|
---|
| 61 | const nodeModules = getNodeModuleDirectory(directory);
|
---|
| 62 | if (!nodeModules) {
|
---|
| 63 | return undefined;
|
---|
| 64 | }
|
---|
| 65 |
|
---|
| 66 | return useDirectory(path.join(directory, 'node_modules', '.cache', options.name), options);
|
---|
| 67 | };
|
---|