-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
81 lines (68 loc) · 2.4 KB
/
index.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import process from 'node:process'
import fs from 'node:fs'
import fsPromises from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
/**
* @typedef {Object} FindUpOptions
* @property {string} [cwd]
* @property {string} [type]
* @property {string} [stopAt]
*/
function toPath(urlOrPath) {
return urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath
}
function isObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
// Function from https://github.com/sindresorhus/find-up-simple/blob/v1.0.0/index.js.
export async function findUp(/** @type {string} */ name, /** @type {FindUpOptions} */ { cwd = process.cwd(), type = 'file', stopAt } = {}) {
let directory = path.resolve(toPath(cwd) ?? '')
const { root } = path.parse(directory)
stopAt = path.resolve(directory, toPath(stopAt ?? root))
while (directory && directory !== stopAt && directory !== root) {
const filePath = path.isAbsolute(name) ? name : path.join(directory, name)
try {
const stats = await fsPromises.stat(filePath) // eslint-disable-line no-await-in-loop
if (
(type === 'file' && stats.isFile()) ||
(type === 'directory' && stats.isDirectory())
) {
return filePath
}
} catch {}
directory = path.dirname(directory)
}
}
export function findUpSync(/** @type {string} */ name, /** @type {FindUpOptions} */ { cwd = process.cwd(), type = 'file', stopAt } = {}) {
let directory = path.resolve(toPath(cwd) ?? '')
const { root } = path.parse(directory)
stopAt = path.resolve(directory, toPath(stopAt ?? root))
while (directory && directory !== stopAt && directory !== root) {
const filePath = path.isAbsolute(name) ? name : path.join(directory, name)
try {
const stats = fs.statSync(filePath)
if (
(type === 'file' && stats.isFile()) ||
(type === 'directory' && stats.isDirectory())
) {
return filePath
}
} catch {}
directory = path.dirname(directory)
}
}
// Modified function from https://stackoverflow.com/a/34749873.
export function skipArrayMergeDeep(/** @type {any} */ target, /** @type {any} */ source) {
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} })
skipArrayMergeDeep(target[key], source[key])
} else {
Object.assign(target, { [key]: source[key] })
}
}
}
return target
}