mono/packages/commons/src/fs/glob-base.ts
2025-01-25 08:08:52 +01:00

58 lines
1.2 KiB
TypeScript

/*!
* glob-base <https://github.com/jonschlinkert/glob-base>
*
* Copyright (c) 2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
import { dirname as pathDirname } from 'path'
import { hasMagic } from 'glob'
import { globParent } from './glob-parent.js'
interface GlobBaseResult {
base: string;
isGlob: boolean;
glob: string;
}
function dirname(glob: string): string {
if (glob.slice(-1) === '/') return glob;
return pathDirname(glob);
}
export const globBase = (pattern: string): GlobBaseResult =>{
if (typeof pattern !== 'string') {
throw new TypeError('glob-base expects a string.');
}
const res: GlobBaseResult = {
base: globParent(pattern),
isGlob: hasMagic(pattern),
glob: ''
};
if (res.base !== '.') {
res.glob = pattern.substr(res.base.length);
if (res.glob.charAt(0) === '/') {
res.glob = res.glob.substr(1);
}
} else {
res.glob = pattern;
}
if (!res.isGlob) {
res.base = dirname(pattern);
res.glob = res.base !== '.'
? pattern.substr(res.base.length)
: pattern;
}
if (res.glob.substr(0, 2) === './') {
res.glob = res.glob.substr(2);
}
if (res.glob.charAt(0) === '/') {
res.glob = res.glob.substr(1);
}
return res;
}