@alessiofrittoli/node-scripts
Version:
Utility library with common Node.js scripts
248 lines (240 loc) • 10.4 kB
TypeScript
import { ParsedPath } from 'path';
import { Stats } from 'fs';
import { AbortSignal } from '@alessiofrittoli/abort-controller';
import { Git, NodeJS, Package } from './types.js';
export { Release } from './types.js';
declare const FileSystem: {
readonly ENOENT: "ERR:ENOENT";
};
declare const ErrorCode: {
ENOENT: "ERR:ENOENT";
UNKNOWN: "ERR:UNKNOWN";
ABORT: "ERR:ABORT";
EMPTY_VALUE: "ERR:EMPTYVALUE";
WRONG_VALUE: "ERR:WRONGVALUE";
EXPIRED: "ERR:EXPIRED";
TOO_EARLY: "ERR:TOOEARLY";
TOO_MANY: "ERR:TOOMANY";
QUOTA_REACHED: "ERR:QUOTAREACHED";
NOT_FOUND: "ERR:NOTFOUND";
OFFLINE: "ERR:INTERNETDISCONNECTED";
};
type ErrorCode = typeof ErrorCode[keyof typeof ErrorCode];
interface DirectoryTreeEntry {
path: string;
parsedPath: ParsedPath;
stats: Stats;
}
type OnIterationOptions = DirectoryTreeEntry;
type OnIteration<T = unknown> = (options: OnIterationOptions, index: number, total: number) => T | Promise<T>;
interface ForEachDirectoryEntryOptions<T = unknown, TCode = ErrorCode> {
/** The root directory path to start traversal. */
path: string;
/** Excluded paths. */
exclude?: string[];
/** An AbortSignal to cancel the iteration early. */
signal?: AbortSignal<TCode>;
/** Callback function invoked for each directory entry. */
onIteration: OnIteration<T>;
}
/**
* Recursively retrieves the directory tree starting from the specified path.
*
* @param path The root directory path to start traversing.
* @param exclude Optional array of directory paths to exclude from the traversal.
*
* @returns An array of {@linkcode DirectoryTreeEntry} objects representing files and directories found.
* @throws A new Exception if the specified `path` does not exist.
*
* @remarks
* - If `path` is in the `exclude` list, an empty array is returned.
* - If `path` is a file, returns an array containing only that file's entry.
* - If `path` is a directory, recursively traverses its contents, excluding any paths listed in `exclude`.
*/
declare const getDirectoryTree: (path: string, exclude?: string[]) => DirectoryTreeEntry[];
/**
* Asynchronously iterates over each entry in a directory tree, applying a callback function to each entry.
*
* @template T The type of the result returned by the iteration callback.
* @template TCode The type representing error codes.
*
* @param options Configuration options for the iteration. See {@linkcode ForEachDirectoryEntryOptions} for more info.
*
* @returns A new Promise that resolves to an array of results returned by the callback for each entry.
*/
declare const forEachDirectoryEntry: <T = unknown, TCode = ErrorCode>(options: ForEachDirectoryEntryOptions<T, TCode>) => Promise<T[]>;
/**
* Retrieves the list of Git remotes and their URLs.
*
* This function executes the `git remote -v` command to get the list of remotes and their URLs.
* It then parses the output and organizes the remotes into a Map where each remote name maps to another Map containing the remote's name and URLs.
* The URLs are further categorized by their type (fetch or push).
*
* @returns A Map where each key is a remote name and the value is another Map containing the remote's name and URLs.
*
* @remarks
* The list of remotes is ordered in alphabetical order.
*/
declare const getRemotes: () => Map<string, Git.Remote.Map<Git.Remote.MapKey>>;
/**
* Retrieves the default remote and branch of the current Git repository.
*
* This function executes a Git command to list all remote branches and filters
* the output to find the default branch (HEAD). It then parses the result to
* extract the remote name and branch name.
*
* @returns A tuple containing the remote name and branch name as strings.
* If the default remote and branch cannot be determined, both values
* in the tuple will be `null`.
*/
declare const getDefaultRemoteAndBranch: () => ([string | null, string | null]);
/**
* Retrieves the default remote.
*
* This function attempts to get the default remote name by first
* calling `getDefaultRemoteAndBranch` to obtain the remote name. If a
* remote name is found, it retrieves the corresponding remote from the
* list of remotes. If no default remote is found, it returns the first
* remote in the list of remotes.
*
* @returns The default remote, or the first remote in the list if no default is found.
*/
declare const getDefaultRemote: () => Git.Remote.Map<Git.Remote.MapKey> | undefined;
/**
* Retrieves the list of stashes from the git repository.
*
* This function executes the `git stash list` command and parses the output
* to return an array of stash objects. Each stash object contains the index,
* branch, and name of the stash.
*
* @returns An array of stash objects.
*
* @example
* ```ts
* console.log( getStashList() )
* // Output:
* // [
* // { index: 0, branch: 'main', name: 'WIP on main: 1234567' },
* // { index: 1, branch: 'feature-branch', name: 'WIP on feature-branch: 89abcdef' },
* // ...
* // ]
* ```
*/
declare const getStashList: () => Git.Stash[];
/**
* Formats a given stash string into an object containing index, branch, and name.
*
* @param stash - The stash string to format.
* @returns An object containing the index, branch, and name of the stash, or null if the stash is invalid.
*
* @example
* ```ts
* console.log( formatStash( 'stash@{0}: WIP on main: 1234567 Commit message' ) )
* // Outputs: { index: 0, branch: 'main', name: '1234567 Commit message' }
* ```
*
* @remarks
* The function expects the stash string to be in the format "stash@{index}: branch: name".
* If the stash string is invalid or the index is not a number, the function returns null.
*/
declare const formatStash: (stash: string) => Git.Stash | null;
/**
* Formats a list of git stashes.
*
* @param stashes - An array of strings representing git stashes.
* @returns An array of formatted git stashes.
*/
declare const formatStashList: (stashes: string[]) => (Git.Stash | null)[];
/**
* Retrieves a stash entry based on the provided options.
*
* @param options - The options to filter the stash entries.
* @returns The stash entry that matches the provided options, or undefined if no match is found.
*
* @example
* ```ts
* const stash = getStashBy( { name: 'WIP on feature-branch: 89abcdef' } )
* if ( stash ) {
* console.log( `Found stash: ${ stash.name }` )
* } else {
* console.log( 'No matching stash found.' )
* }
* ```
*/
declare const getStashBy: (options: Git.GetStashByOptions) => Git.Stash | undefined;
/**
* Pop a stash entry by stash index.
*
* @param index The numeric stash index.
* @returns The `git stash pop` command `stdout`.
*/
declare const popStashByIndex: (index: number) => NonSharedBuffer;
/**
* Retrieves the list of npm packages in JSON format.
*
* @template T - A boolean type that determines whether to fetch global or local packages.
* @param global - If true, fetches global packages; otherwise, fetches local packages.
* @returns - The list of npm packages in JSON format.
*/
declare const getPackage: <T extends true | false = false>(global?: T) => T extends true ? NodeJS.Deps.Global : NodeJS.Deps.Local;
/**
* Checks if a given package is installed.
*
* @param name - The name of the package to check.
* @param global - Optional. If true, checks for the package in the global scope. Defaults to false.
* @returns A boolean indicating whether the package is installed.
*/
declare const isPackageInstalled: (name: string, global?: boolean) => boolean;
type PackageJson = (Record<string, string | Record<string, string>> & {
name: string;
});
/**
* Reads and parses the `package.json` file from the specified root directory.
*
* @param root - The root directory where the `package.json` file is located.
* @returns The parsed contents of the `package.json` file as an object.
* @throws Will throw an error if the file cannot be read or parsed.
*/
declare const getPackageJson: (root: Package["root"]) => PackageJson;
/**
* Determines if the script is running in an external project.
*
* @param project - The options object excluding the 'outputFile' property.
* @returns A boolean indicating whether the script is running in an external project.
* @throws Will throw an error if `INIT_CWD` is not set or if the script cannot determine the project status.
*/
declare const isExternalPackage: ({ root, name }: Package) => boolean;
/**
* Get package pre-release tag.
*
* @param version The package version.
* @returns The pre-release tag.
*/
declare const getPreReleaseTag: (version: string) => string | null;
/**
* Retrieves the root directory of the current process.
*
* @returns The root directory of the current process, determined by the `INIT_CWD` environment variable if set,
* otherwise the current working directory.
*/
declare const getProcessRoot: () => string;
/**
* Generates a Map of process options from the command line arguments.
*
* The function processes `process.argv` to create a Map where each key-value pair represents
* an option and its corresponding value. The first two arguments are treated as special cases:
* - The first argument (index 0) is mapped to `--executable`.
* - The second argument (index 1) is mapped to `--scriptPath`.
*
* For subsequent arguments:
* - If an argument starts with a hyphen (`-`), it is considered an option key.
* - If the next argument does not start with a hyphen, it is considered the value for the current option key.
* - If the next argument does start with a hyphen, the current option key is mapped to `null`.
*
* @template K - The type of the keys in the resulting Map.
* @template V - The type of the values in the resulting Map, extending `NodeJS.Process.ArgvValue`.
*
* @returns {Map<K, V>} A Map containing the processed command line options.
*/
declare const getProcessOptions: <K, V extends NodeJS.Process.ArgvValue>() => Map<K, V>;
export { type DirectoryTreeEntry, ErrorCode, FileSystem, type ForEachDirectoryEntryOptions, Git, NodeJS, type OnIteration, type OnIterationOptions, Package, type PackageJson, forEachDirectoryEntry, formatStash, formatStashList, getDefaultRemote, getDefaultRemoteAndBranch, getDirectoryTree, getPackage, getPackageJson, getPreReleaseTag, getProcessOptions, getProcessRoot, getRemotes, getStashBy, getStashList, isExternalPackage, isPackageInstalled, popStashByIndex };