[79a0317] | 1 | import process from 'node:process';
|
---|
| 2 | import path from 'node:path';
|
---|
| 3 | import fs from 'node:fs';
|
---|
| 4 | import commonPathPrefix from 'common-path-prefix';
|
---|
| 5 | import {packageDirectorySync} from 'pkg-dir';
|
---|
| 6 |
|
---|
| 7 | const {env, cwd} = process;
|
---|
| 8 |
|
---|
| 9 | const isWritable = path => {
|
---|
| 10 | try {
|
---|
| 11 | fs.accessSync(path, fs.constants.W_OK);
|
---|
| 12 | return true;
|
---|
| 13 | } catch {
|
---|
| 14 | return false;
|
---|
| 15 | }
|
---|
| 16 | };
|
---|
| 17 |
|
---|
| 18 | function useDirectory(directory, options) {
|
---|
| 19 | if (options.create) {
|
---|
| 20 | fs.mkdirSync(directory, {recursive: true});
|
---|
| 21 | }
|
---|
| 22 |
|
---|
| 23 | if (options.thunk) {
|
---|
| 24 | return (...arguments_) => path.join(directory, ...arguments_);
|
---|
| 25 | }
|
---|
| 26 |
|
---|
| 27 | return directory;
|
---|
| 28 | }
|
---|
| 29 |
|
---|
| 30 | function getNodeModuleDirectory(directory) {
|
---|
| 31 | const nodeModules = path.join(directory, 'node_modules');
|
---|
| 32 |
|
---|
| 33 | if (
|
---|
| 34 | !isWritable(nodeModules)
|
---|
| 35 | && (fs.existsSync(nodeModules) || !isWritable(path.join(directory)))
|
---|
| 36 | ) {
|
---|
| 37 | return;
|
---|
| 38 | }
|
---|
| 39 |
|
---|
| 40 | return nodeModules;
|
---|
| 41 | }
|
---|
| 42 |
|
---|
| 43 | export default function findCacheDirectory(options = {}) {
|
---|
| 44 | if (env.CACHE_DIR && !['true', 'false', '1', '0'].includes(env.CACHE_DIR)) {
|
---|
| 45 | return useDirectory(path.join(env.CACHE_DIR, options.name), options);
|
---|
| 46 | }
|
---|
| 47 |
|
---|
| 48 | let {cwd: directory = cwd()} = options;
|
---|
| 49 |
|
---|
| 50 | if (options.files) {
|
---|
| 51 | directory = commonPathPrefix(options.files.map(file => path.resolve(directory, file)));
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 54 | directory = packageDirectorySync({cwd: directory});
|
---|
| 55 |
|
---|
| 56 | if (!directory) {
|
---|
| 57 | return;
|
---|
| 58 | }
|
---|
| 59 |
|
---|
| 60 | const nodeModules = getNodeModuleDirectory(directory);
|
---|
| 61 | if (!nodeModules) {
|
---|
| 62 | return;
|
---|
| 63 | }
|
---|
| 64 |
|
---|
| 65 | return useDirectory(path.join(directory, 'node_modules', '.cache', options.name), options);
|
---|
| 66 | }
|
---|