mono/packages/commons/dist/glob-parent.js
2025-01-24 20:47:57 +01:00

58 lines
1.7 KiB
JavaScript

import { posix } from 'path';
import { platform } from 'os';
import { hasMagic } from 'glob';
const isWin32 = platform() === 'win32';
const slash = '/';
const backslash = /\\/g;
const escaped = /\\([!*?|[\](){}])/g;
export const globParent = (str, opts) => {
const options = { flipBackslashes: true, ...opts };
// flip windows path separators
if (options.flipBackslashes && isWin32 && !str.includes(slash)) {
str = str.replace(backslash, slash);
}
// special case for strings ending in enclosure containing path separator
if (isEnclosure(str)) {
str += slash;
}
// preserves full path in case of trailing path separator
str += 'a';
// remove path parts that are globby
do {
str = posix.dirname(str);
} while (isGlobby(str));
// remove escape chars and return result
return str.replace(escaped, '$1');
};
function isEnclosure(str) {
const lastChar = str.slice(-1);
let enclosureStart;
switch (lastChar) {
case '}':
enclosureStart = '{';
break;
case ']':
enclosureStart = '[';
break;
default:
return false;
}
const foundIndex = str.indexOf(enclosureStart);
if (foundIndex < 0) {
return false;
}
return str.slice(foundIndex + 1, -1).includes(slash);
}
function isGlobby(str) {
if (/\([^()]+$/.test(str)) {
return true;
}
if (str[0] === '{' || str[0] === '[') {
return true;
}
if (/[^\\][{[]/.test(str)) {
return true;
}
return hasMagic(str);
}
//# sourceMappingURL=glob-parent.js.map