cspell-gitignore
Version:
Gitignore Glob matcher for cspell
93 lines • 3.1 kB
JavaScript
import * as path from 'node:path';
import { findUp } from 'find-up-simple';
export function factoryPathHelper(path) {
function directoryRoot(directory) {
const p = path.parse(directory);
return p.root;
}
async function findRepoRoot(directory) {
const foundDir = (await findUp('.git', { cwd: directory, type: 'directory' })) || '';
const foundFile = (await findUp('.git', { cwd: directory, type: 'file' })) || '';
const found = foundDir.length >= foundFile.length ? foundDir : foundFile;
if (!found)
return undefined;
return path.dirname(found);
}
function isParentOf(parent, child) {
const rel = path.relative(parent, child);
return !!rel && !path.isAbsolute(rel) && rel[0] !== '.';
}
function contains(parent, child) {
const rel = path.relative(parent, child);
return !rel || (!path.isAbsolute(rel) && rel[0] !== '.');
}
function makeRelativeTo(child, parent) {
const rel = path.relative(parent, child);
if (path.isAbsolute(rel) || rel[0] === '.')
return undefined;
return normalizePath(rel);
}
function normalizePath(path) {
return path.replaceAll('\\', '/');
}
return {
directoryRoot,
findRepoRoot,
isParentOf,
contains,
normalizePath,
makeRelativeTo,
};
}
const defaultHelper = factoryPathHelper(path);
/**
* Parse a directory and return its root
* @param directory - directory to parse.
* @returns root directory
*/
export const directoryRoot = defaultHelper.directoryRoot;
/**
* Find the git repository root directory.
* @param directory - directory to search up from.
* @returns resolves to `.git` root or undefined
*/
export const findRepoRoot = defaultHelper.findRepoRoot;
/**
* Checks to see if the child directory is nested under the parent directory.
* @param parent - parent directory
* @param child - possible child directory
* @returns true iff child is a child of parent.
*/
export const isParentOf = defaultHelper.isParentOf;
/**
* Check to see if a parent directory contains a child directory.
* @param parent - parent directory
* @param child - child directory
* @returns true iff child is the same as the parent or nested in the parent.
*/
export const contains = defaultHelper.contains;
/**
* Make a path relative to another if the other is a parent.
* @param path - the path to make relative
* @param rootPath - a root of path
* @returns the normalized relative path or undefined if rootPath is not a parent.
*/
export const makeRelativeTo = defaultHelper.makeRelativeTo;
/**
* Normalize a path to have only forward slashes.
* @param path - path to normalize
* @returns a normalized string.
*/
export const normalizePath = defaultHelper.normalizePath;
export const DefaultPathHelper = {
directoryRoot,
findRepoRoot,
isParentOf,
contains,
makeRelativeTo,
normalizePath,
};
export function isDefined(v) {
return v !== undefined && v !== null;
}
//# sourceMappingURL=helpers.js.map