UNPKG

@stryke/path

Version:

A package containing various utilities that expand the functionality of NodeJs's built-in `path` module

69 lines (67 loc) 2.48 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); const require_runtime = require('./_virtual/_rolldown/runtime.cjs'); const require_slash = require('./slash.cjs'); const require_correct_path = require('./correct-path.cjs'); let _stryke_type_checks_is_set_string = require("@stryke/type-checks/is-set-string"); //#region src/common.ts /** * Get the common path from an array of paths * * @example * ```ts * commonPath(['/foo/bar/baz', '/foo/bar/qux', '/foo/bar/baz/quux']); * // returns '/foo/bar' * * commonPath(['C:/foo/bar/baz', 'C:/foo/bar/qux', 'C:/foo/bar/baz/quux']); * // returns 'C:/foo/bar' * ``` * * @param paths - The array of paths * @returns The common path */ function commonPath(paths) { const [first = "", ...remaining] = paths.map((path) => require_correct_path.correctPath(require_slash.slash(path))); if (!first) return ""; if (remaining.length === 0) return first; let endOfPrefix = first.split("/").length; for (const path of remaining) { const compare = path.split("/"); for (let i = 0; i < endOfPrefix; i++) if (compare[i] !== first.split("/")[i]) endOfPrefix = i; if (endOfPrefix === 0) return ""; } return require_correct_path.withoutTrailingSlash(first.split("/").slice(0, endOfPrefix).join("/")); } const findCommonPath = commonPath; /** * Find the base path from a string path/glob or an array of string paths/globs. If a string is provided, it is returned as the base path. If an array of strings is provided, the common path among them is returned. If the input is invalid or empty, "/" is returned. * * @example * ```ts * findBasePath('/foo/bar/baz'); * // returns '/foo/bar/baz' * * findBasePath(['/foo/bar/baz', '/foo/bar/qux', '/foo/bar/baz/quux']); * // returns '/foo/bar' * * findBasePath(['C:/foo/bar/baz', 'C:/foo/bar/qux', 'C:/foo/bar/baz/quux']); * // returns 'C:/foo/bar' * * findBasePath(['foo/bar/**\/baz', 'foo/bar/qux/*', 'foo/bar/baz/quux']); * // returns 'foo/bar' * * findBasePath([]); * // returns '/' * ``` * * @param paths - The string or array of strings to find the base path from * @returns The base path */ function findBasePath(paths) { if ((0, _stryke_type_checks_is_set_string.isSetString)(paths)) return paths; else if (Array.isArray(paths) && paths.length > 0) return commonPath(paths.map((path) => require_correct_path.stripStars(path))); return "/"; } //#endregion exports.commonPath = commonPath; exports.findBasePath = findBasePath; exports.findCommonPath = findCommonPath;