-
-
Notifications
You must be signed in to change notification settings - Fork 200
/
Copy pathpackage-up.js
59 lines (51 loc) · 1.71 KB
/
package-up.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
* This file is part of the Symfony Webpack Encore package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const { fileURLToPath } = require('url');
/**
* Inlined version of the package "package-up" (ESM only).
*
* @param {object} options
* @param {string} options.cwd The directory to start searching from.
* @returns {string|undefined} The path to the nearest package.json file or undefined if not found.
*/
module.exports = function({ cwd }) {
return findUpSync('package.json', { cwd });
};
/**
* @param {string|URL} urlOrPath
* @returns {string}
*/
function toPath(urlOrPath) {
return urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;
}
/**
* Inlined and simplified version of the package "find-up-simple" (ESM only).
*
* @param {string} name The name of the file to find
* @param {object} options
* @param {string=} options.cwd The directory to start searching from.
* @returns {string|undefined} The path to the file found or undefined if not found.
*/
function findUpSync(name, { cwd = process.cwd() } = {}) {
let directory = path.resolve(toPath(cwd) || '');
const { root } = path.parse(directory);
while (directory && directory !== root) {
const filePath = path.isAbsolute(name) ? name : path.join(directory, name);
try {
const stats = fs.statSync(filePath, { throwIfNoEntry: false });
if (stats && stats.isFile()) {
return filePath;
}
} catch (e) {}
directory = path.dirname(directory);
}
}