diff --git a/node/Strings/resources.resjson/en-US/resources.resjson b/node/Strings/resources.resjson/en-US/resources.resjson index 41844a99b..d2f90304e 100644 --- a/node/Strings/resources.resjson/en-US/resources.resjson +++ b/node/Strings/resources.resjson/en-US/resources.resjson @@ -1,36 +1,39 @@ { - "loc.messages.LIB_UnhandledEx": "Unhandled: %s", + "loc.messages.LIB_CopyFileFailed": "Error while copying the file. Attempts left: %s", + "loc.messages.LIB_DirectoryStackEmpty": "Directory stack is empty", + "loc.messages.LIB_EndpointAuthNotExist": "Endpoint auth data not present: %s", + "loc.messages.LIB_EndpointDataNotExist": "Endpoint data parameter %s not present: %s", + "loc.messages.LIB_EndpointNotExist": "Endpoint not present: %s", "loc.messages.LIB_FailOnCode": "Failure return code: %d", + "loc.messages.LIB_InputRequired": "Input required: %s", + "loc.messages.LIB_InvalidEndpointAuth": "Invalid endpoint auth: %s", + "loc.messages.LIB_InvalidPattern": "Invalid pattern: '%s'", + "loc.messages.LIB_InvalidSecureFilesInput": "Invalid secure file input: %s", + "loc.messages.LIB_LocStringNotFound": "Can\\'t find loc string for key: %s", + "loc.messages.LIB_MergeTestResultNotSupported": "Merging test results from multiple files to one test run is not supported on this version of build agent for OSX/Linux, each test result file will be published as a separate test run in VSO/TFS.", "loc.messages.LIB_MkdirFailed": "Unable to create directory '%s'. %s", "loc.messages.LIB_MkdirFailedFileExists": "Unable to create directory '%s'. Conflicting file exists: '%s'", "loc.messages.LIB_MkdirFailedInvalidDriveRoot": "Unable to create directory '%s'. Root directory does not exist: '%s'", "loc.messages.LIB_MkdirFailedInvalidShare": "Unable to create directory '%s'. Unable to verify the directory exists: '%s'. If directory is a file share, please verify the share name is correct, the share is online, and the current process has permission to access the share.", "loc.messages.LIB_MultilineSecret": "Secrets cannot contain multiple lines", + "loc.messages.LIB_NotFoundPreviousDirectory": "Could not find previous directory", + "loc.messages.LIB_OperationFailed": "Failed %s: %s", + "loc.messages.LIB_ParameterIsRequired": "%s not supplied", + "loc.messages.LIB_PathHasNullByte": "Path cannot contain null bytes", + "loc.messages.LIB_PathIsNotADirectory": "Path is not a directory: %s", + "loc.messages.LIB_PathNotFound": "Not found %s: %s", + "loc.messages.LIB_PlatformNotSupported": "Platform not supported: %s", "loc.messages.LIB_ProcessError": "There was an error when attempting to execute the process '%s'. This may indicate the process failed to start. Error: %s", "loc.messages.LIB_ProcessExitCode": "The process '%s' failed with exit code %s", "loc.messages.LIB_ProcessStderr": "The process '%s' failed because one or more lines were written to the STDERR stream", - "loc.messages.LIB_ReturnCode": "Return code: %d", - "loc.messages.LIB_ResourceFileNotExist": "Resource file doesn\\'t exist: %s", "loc.messages.LIB_ResourceFileAlreadySet": "Resource file has already set to: %s", + "loc.messages.LIB_ResourceFileNotExist": "Resource file doesn\\'t exist: %s", "loc.messages.LIB_ResourceFileNotSet": "Resource file haven\\'t set, can\\'t find loc string for key: %s", + "loc.messages.LIB_ReturnCode": "Return code: %d", "loc.messages.LIB_StdioNotClosed": "The STDIO streams did not close within %s seconds of the exit event from process '%s'. This may indicate a child process inherited the STDIO streams and has not yet exited.", - "loc.messages.LIB_WhichNotFound_Linux": "Unable to locate executable file: '%s'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.", - "loc.messages.LIB_WhichNotFound_Win": "Unable to locate executable file: '%s'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.", - "loc.messages.LIB_LocStringNotFound": "Can\\'t find loc string for key: %s", - "loc.messages.LIB_ParameterIsRequired": "%s not supplied", - "loc.messages.LIB_InputRequired": "Input required: %s", - "loc.messages.LIB_InvalidPattern": "Invalid pattern: '%s'", - "loc.messages.LIB_EndpointNotExist": "Endpoint not present: %s", - "loc.messages.LIB_EndpointDataNotExist": "Endpoint data parameter %s not present: %s", - "loc.messages.LIB_EndpointAuthNotExist": "Endpoint auth data not present: %s", - "loc.messages.LIB_InvalidEndpointAuth": "Invalid endpoint auth: %s", - "loc.messages.LIB_InvalidSecureFilesInput": "Invalid secure file input: %s", - "loc.messages.LIB_PathNotFound": "Not found %s: %s", - "loc.messages.LIB_PathHasNullByte": "Path cannot contain null bytes", - "loc.messages.LIB_OperationFailed": "Failed %s: %s", + "loc.messages.LIB_UndefinedNodeVersion": "Node version is undefined.", + "loc.messages.LIB_UnhandledEx": "Unhandled: %s", "loc.messages.LIB_UseFirstGlobMatch": "Multiple workspace matches. using first.", - "loc.messages.LIB_MergeTestResultNotSupported": "Merging test results from multiple files to one test run is not supported on this version of build agent for OSX/Linux, each test result file will be published as a separate test run in VSO/TFS.", - "loc.messages.LIB_PlatformNotSupported": "Platform not supported: %s", - "loc.messages.LIB_CopyFileFailed": "Error while copying the file. Attempts left: %s", - "loc.messages.LIB_UndefinedNodeVersion": "Node version is undefined." + "loc.messages.LIB_WhichNotFound_Linux": "Unable to locate executable file: '%s'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.", + "loc.messages.LIB_WhichNotFound_Win": "Unable to locate executable file: '%s'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file." } \ No newline at end of file diff --git a/node/lib.json b/node/lib.json index 45ffe0717..adbc62565 100644 --- a/node/lib.json +++ b/node/lib.json @@ -1,38 +1,41 @@ { "messages": { - "LIB_UnhandledEx": "Unhandled: %s", + "LIB_CopyFileFailed": "Error while copying the file. Attempts left: %s", + "LIB_DirectoryStackEmpty": "Directory stack is empty", + "LIB_EndpointAuthNotExist": "Endpoint auth data not present: %s", + "LIB_EndpointDataNotExist": "Endpoint data parameter %s not present: %s", + "LIB_EndpointNotExist": "Endpoint not present: %s", "LIB_FailOnCode": "Failure return code: %d", + "LIB_InputRequired": "Input required: %s", + "LIB_InvalidEndpointAuth": "Invalid endpoint auth: %s", + "LIB_InvalidPattern": "Invalid pattern: '%s'", + "LIB_InvalidSecureFilesInput": "Invalid secure file input: %s", + "LIB_LocStringNotFound": "Can\\'t find loc string for key: %s", + "LIB_MergeTestResultNotSupported": "Merging test results from multiple files to one test run is not supported on this version of build agent for OSX/Linux, each test result file will be published as a separate test run in VSO/TFS.", "LIB_MkdirFailed": "Unable to create directory '%s'. %s", "LIB_MkdirFailedFileExists": "Unable to create directory '%s'. Conflicting file exists: '%s'", "LIB_MkdirFailedInvalidDriveRoot": "Unable to create directory '%s'. Root directory does not exist: '%s'", "LIB_MkdirFailedInvalidShare": "Unable to create directory '%s'. Unable to verify the directory exists: '%s'. If directory is a file share, please verify the share name is correct, the share is online, and the current process has permission to access the share.", "LIB_MultilineSecret": "Secrets cannot contain multiple lines", + "LIB_NotFoundPreviousDirectory": "Could not find previous directory", + "LIB_OperationFailed": "Failed %s: %s", + "LIB_ParameterIsRequired": "%s not supplied", + "LIB_PathHasNullByte": "Path cannot contain null bytes", + "LIB_PathIsNotADirectory": "Path is not a directory: %s", + "LIB_PathNotFound": "Not found %s: %s", + "LIB_PlatformNotSupported": "Platform not supported: %s", "LIB_ProcessError": "There was an error when attempting to execute the process '%s'. This may indicate the process failed to start. Error: %s", "LIB_ProcessExitCode": "The process '%s' failed with exit code %s", "LIB_ProcessStderr": "The process '%s' failed because one or more lines were written to the STDERR stream", - "LIB_ReturnCode": "Return code: %d", - "LIB_ResourceFileNotExist": "Resource file doesn\\'t exist: %s", "LIB_ResourceFileAlreadySet": "Resource file has already set to: %s", + "LIB_ResourceFileNotExist": "Resource file doesn\\'t exist: %s", "LIB_ResourceFileNotSet": "Resource file haven\\'t set, can\\'t find loc string for key: %s", + "LIB_ReturnCode": "Return code: %d", "LIB_StdioNotClosed": "The STDIO streams did not close within %s seconds of the exit event from process '%s'. This may indicate a child process inherited the STDIO streams and has not yet exited.", - "LIB_WhichNotFound_Linux": "Unable to locate executable file: '%s'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.", - "LIB_WhichNotFound_Win": "Unable to locate executable file: '%s'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.", - "LIB_LocStringNotFound": "Can\\'t find loc string for key: %s", - "LIB_ParameterIsRequired": "%s not supplied", - "LIB_InputRequired": "Input required: %s", - "LIB_InvalidPattern": "Invalid pattern: '%s'", - "LIB_EndpointNotExist": "Endpoint not present: %s", - "LIB_EndpointDataNotExist": "Endpoint data parameter %s not present: %s", - "LIB_EndpointAuthNotExist": "Endpoint auth data not present: %s", - "LIB_InvalidEndpointAuth": "Invalid endpoint auth: %s", - "LIB_InvalidSecureFilesInput": "Invalid secure file input: %s", - "LIB_PathNotFound": "Not found %s: %s", - "LIB_PathHasNullByte": "Path cannot contain null bytes", - "LIB_OperationFailed": "Failed %s: %s", + "LIB_UndefinedNodeVersion": "Node version is undefined.", + "LIB_UnhandledEx": "Unhandled: %s", "LIB_UseFirstGlobMatch": "Multiple workspace matches. using first.", - "LIB_MergeTestResultNotSupported": "Merging test results from multiple files to one test run is not supported on this version of build agent for OSX/Linux, each test result file will be published as a separate test run in VSO/TFS.", - "LIB_PlatformNotSupported": "Platform not supported: %s", - "LIB_CopyFileFailed": "Error while copying the file. Attempts left: %s", - "LIB_UndefinedNodeVersion": "Node version is undefined." - } -} + "LIB_WhichNotFound_Linux": "Unable to locate executable file: '%s'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.", + "LIB_WhichNotFound_Win": "Unable to locate executable file: '%s'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file." + } +} \ No newline at end of file diff --git a/node/package-lock.json b/node/package-lock.json index 01c3085b1..5dd130839 100644 --- a/node/package-lock.json +++ b/node/package-lock.json @@ -1,6 +1,6 @@ { "name": "azure-pipelines-task-lib", - "version": "4.17.3", + "version": "5.0.0", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/node/package.json b/node/package.json index 3073e290d..099180776 100644 --- a/node/package.json +++ b/node/package.json @@ -1,6 +1,6 @@ { "name": "azure-pipelines-task-lib", - "version": "4.17.3", + "version": "5.0.0", "description": "Azure Pipelines Task SDK", "main": "./task.js", "typings": "./task.d.ts", diff --git a/node/task.ts b/node/task.ts index 7c11beb9a..4abdf3e93 100644 --- a/node/task.ts +++ b/node/task.ts @@ -1,5 +1,4 @@ import Q = require('q'); -import shell = require('shelljs'); import childProcess = require('child_process'); import fs = require('fs'); import path = require('path'); @@ -10,6 +9,13 @@ import tcm = require('./taskcommand'); import trm = require('./toolrunner'); import semver = require('semver'); +type OptionCases = `-${Uppercase | Lowercase}`; + +type OptionsPermutations = + T extends `${infer First}${infer Rest}` + ? OptionCases<`${U}${First}`> | OptionCases<`${First}${U}`> | OptionsPermutations | OptionCases + : OptionCases | ''; + export enum TaskResult { Succeeded = 0, SucceededWithIssues = 1, @@ -681,24 +687,6 @@ export const debug = im._debug; //----------------------------------------------------- // Disk Functions //----------------------------------------------------- -function _checkShell(cmd: string, continueOnError?: boolean) { - var se = shell.error(); - - if (se) { - debug(cmd + ' failed'); - var errMsg = loc('LIB_OperationFailed', cmd, se); - debug(errMsg); - - if (!continueOnError) { - throw new Error(errMsg); - } - } -} - -export interface FsStats extends fs.Stats { - -} - /** * Get's stat on a path. * Useful for checking whether a file or directory. Also getting created, modified and accessed time. @@ -707,7 +695,7 @@ export interface FsStats extends fs.Stats { * @param path path to check * @returns fsStat */ -export function stats(path: string): FsStats { +export function stats(path: string): fs.Stats { return fs.statSync(path); } @@ -796,43 +784,125 @@ export const checkPath = im._checkPath; /** * Change working directory. * - * @param path new working directory path - * @returns void + * @param {string} path - New working directory path + * @returns {void} */ export function cd(path: string): void { - if (path) { - shell.cd(path); - _checkShell('cd'); + if (path === '-') { + if (!process.env.OLDPWD) { + throw new Error(loc('LIB_NotFoundPreviousDirectory')); + } else { + path = process.env.OLDPWD; + } + } + + if (path === '~') { + path = os.homedir(); + } + + if (!fs.existsSync(path)) { + throw new Error(loc('LIB_PathNotFound', 'cd', path)); + } + + if (!fs.statSync(path).isDirectory()) { + throw new Error(loc('LIB_PathIsNotADirectory', path)); } + + try { + const currentPath = process.cwd(); + process.chdir(path); + process.env.OLDPWD = currentPath; + } catch (error) { + debug(loc('LIB_OperationFailed', 'cd', error)); + } +} + +const dirStack: string[] = []; + +function getActualStack() { + return [process.cwd()].concat(dirStack); } /** * Change working directory and push it on the stack * - * @param path new working directory path - * @returns void + * @param {string} dir - New working directory path + * @returns {void} */ -export function pushd(path: string): void { - shell.pushd(path); - _checkShell('pushd'); +export function pushd(dir: string = ''): string[] { + const dirs = getActualStack(); + + let maybeIndex = parseInt(dir); + + if (dir === '+0') { + return dirs; + } else if (dir.length === 0) { + if (dirs.length > 1) { + dirs.splice(0, 0, ...dirs.splice(1, 1)); + } else { + throw new Error(loc('LIB_DirectoryStackEmpty')); + } + } else if (!isNaN(maybeIndex)) { + if (maybeIndex < dirStack.length + 1) { + maybeIndex = dir.charAt(0) === '-' ? maybeIndex - 1 : maybeIndex; + } + dirs.splice(0, dirs.length, ...dirs.slice(maybeIndex).concat(dirs.slice(0, maybeIndex))); + } else { + dirs.unshift(dir); + } + + const _path = path.resolve(dirs.shift()!); + + try { + cd(_path); + } catch (error) { + if (!fs.existsSync(_path)) { + throw new Error(loc('Not found', 'pushd', _path)); + } + + throw error; + } + + dirStack.splice(0, dirStack.length, ...dirs); + return getActualStack(); } /** * Change working directory back to previously pushed directory * - * @returns void + * @param {string} index - Index to remove from the stack + * @returns {void} */ -export function popd(): void { - shell.popd(); - _checkShell('popd'); +export function popd(index: string = ''): string[] { + if (dirStack.length === 0) { + throw new Error(loc('LIB_DirectoryStackEmpty')); + } + + let maybeIndex = parseInt(index); + + if (isNaN(maybeIndex)) { + maybeIndex = 0; + } else if (maybeIndex < dirStack.length + 1) { + maybeIndex = index.charAt(0) === '-' ? maybeIndex - 1 : maybeIndex; + } + + if (maybeIndex > 0 || dirStack.length + maybeIndex === 0) { + maybeIndex = maybeIndex > 0 ? maybeIndex - 1 : maybeIndex; + dirStack.splice(maybeIndex, 1); + } else { + const _path = path.resolve(dirStack.shift()!); + cd(_path); + } + + return getActualStack(); } /** - * Make a directory. Creates the full path with folders in between + * Make a directory. Creates the full path with folders in between * Will throw if it fails * - * @param p path to create - * @returns void + * @param {string} p - Path to create + * @returns {void} */ export function mkdirP(p: string): void { if (!p) { @@ -911,74 +981,280 @@ export function resolve(...pathSegments: any[]): string { export const which = im._which; +type ListOptionsVariants = OptionsPermutations<'ra'>; + /** - * Returns array of files in the given path, or in current directory if no path provided. See shelljs.ls - * @param {string} options Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..) - * @param {string[]} paths Paths to search. - * @return {string[]} An array of files in the given path(s). + * Returns array of files in the given path, or in current directory if no path provided. + * @param {ListOptionsVariants} options - Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..) + * @param {...string[]} paths - Paths to search. + * @return {string[]} - An array of files in the given path(s). */ -export function ls(options: string, paths: string[]): string[] { - if (options) { - return shell.ls(options, paths); - } else { - return shell.ls(paths); +export function ls(options: ListOptionsVariants, ...paths: string[]): string[]; + +/** + * Returns array of files in the given path, or in current directory if no path provided. + * @param {ListOptionsVariants} options - Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..) + * @param {string[]} paths - Paths to search. + * @return {string[]} - An array of files in the given path(s). + */ +export function ls(options: ListOptionsVariants, paths: string[]): string[]; + +/** + * Returns array of files in the given path, or in current directory if no path provided. + * @param {ListOptionsVariants} options - Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..) + * @param {string} paths - Paths to search. + * @return {string[]} - An array of files in the given path(s). + */ +export function ls(options: ListOptionsVariants, paths: string): string[]; + +/** + * Returns array of files in the given path, or in current directory if no path provided. + * @param {string} path - Paths to search. + * @return {string[]} - An array of files in the given path(s). + */ +export function ls(path: string): string[]; + +/** + * Returns array of files in the given path, or in current directory if no path provided. + * @param {string[]} paths - Paths to search. + * @return {string[]} - An array of files in the given path(s). + */ +export function ls(paths: string[]): string[]; + +/** + * Returns array of files in the given path, or in current directory if no path provided. + * @param {...string[]} paths - Paths to search. + * @return {string[]} - An array of files in the given path(s). + */ +export function ls(...paths: string[]): string[]; + +/** + * Returns array of files in the given path, or in current directory if no path provided. + * @param {unknown} optionsOrPaths - Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..) + * @param {unknown[]} paths - Paths to search. + * @return {string[]} - An array of files in the given path(s). + */ +export function ls(optionsOrPaths?: unknown, ...paths: unknown[]): string[] { + let isRecursive = false; + let includeHidden = false; + + if (typeof optionsOrPaths === 'string' && optionsOrPaths.startsWith('-')) { + const options = String(optionsOrPaths).toLowerCase(); + isRecursive = options.includes('r'); + includeHidden = options.includes('a'); + } + + // Flatten paths if the paths argument is array + if (Array.isArray(paths)) { + paths = paths.flat(Infinity); + } + + // If the first argument is not options, then it is a path + if (typeof optionsOrPaths !== 'string' || !optionsOrPaths.startsWith('-')) { + let pathsFromOptions: string[] = []; + + if (Array.isArray(optionsOrPaths)) { + pathsFromOptions = optionsOrPaths; + } else if (optionsOrPaths && typeof optionsOrPaths === 'string') { + pathsFromOptions = [optionsOrPaths]; + } + + if (paths === undefined || paths.length === 0) { + paths = pathsFromOptions; + } else { + paths.push(...pathsFromOptions); + } + } + + if (paths.length === 0) { + paths.push(path.resolve('.')); + } + + const preparedPaths: string[] = []; + + try { + while (paths.length > 0) { + const pathEntry = resolve(paths.shift()); + + if (pathEntry?.includes('*')) { + paths.push(...findMatch(path.dirname(pathEntry), [path.basename(pathEntry)])); + continue; + } + + if (fs.lstatSync(pathEntry).isDirectory()) { + preparedPaths.push(...fs.readdirSync(pathEntry).map(file => path.join(pathEntry, file))); + } else { + preparedPaths.push(pathEntry); + } + } + + const entries: string[] = []; + + while (preparedPaths.length > 0) { + const entry = preparedPaths.shift()!; + const entrybasename = path.basename(entry); + + if (entry?.includes('*')) { + preparedPaths.push(...findMatch(path.dirname(entry), [entrybasename])); + continue; + } + + if (!includeHidden && entrybasename.startsWith('.') && entrybasename !== '.' && entrybasename !== '..') { + continue; + } + + if (fs.lstatSync(entry).isDirectory() && isRecursive) { + preparedPaths.push(...fs.readdirSync(entry).map(x => path.join(entry, x))); + } else { + entries.push(entry); + } + } + + return entries; + } catch (error) { + if (error.code === 'ENOENT') { + throw new Error(loc('LIB_PathNotFound', 'ls', error.message)); + } else { + throw new Error(loc('LIB_OperationFailed', 'ls', error)); + } } } +type CopyOptionsVariants = OptionsPermutations<'frn'>; + /** * Copies a file or folder. - * - * @param source source path - * @param dest destination path - * @param options string -r, -f or -rf for recursive and force - * @param continueOnError optional. whether to continue on error - * @param retryCount optional. Retry count to copy the file. It might help to resolve intermittent issues e.g. with UNC target paths on a remote host. + * @param {string} source - Source path. + * @param {string} destination - Destination path. + * @param {string} [options] - Options string '-r', '-f' , '-n' or '-rfn' for recursive, force and no-clobber. + * @param {boolean} [continueOnError=false] - Optional. Whether to continue on error. + * @param {number} [retryCount=0] - Optional. Retry count to copy the file. It might help to resolve intermittent issues e.g. with UNC target paths on a remote host. + * @returns {void} + */ +export function cp(source: string, destination: string, options?: CopyOptionsVariants, continueOnError?: boolean, retryCount?: number): void; + +/** + * Copies a file or folder. + * @param {string} options - Options string '-r', '-f' , '-n' or '-rfn' for recursive, force and no-clobber. + * @param {string} source - Source path. + * @param {string} [destination] - Destination path. + * @param {boolean} [continueOnError=false] - Optional. Whether to continue on error. + * @param {number} [retryCount=0] - Optional. Retry count to copy the file. It might help to resolve intermittent issues e.g. with UNC target paths on a remote host. + * @returns {void} */ -export function cp(source: string, dest: string, options?: string, continueOnError?: boolean, retryCount: number = 0): void { - while (retryCount >= 0) { +export function cp(options: CopyOptionsVariants, source: string, destination: string, continueOnError?: boolean, retryCount?: number): void; + +/** + * Copies a file or folder. + * @param {string} sourceOrOptions - Either the source path or an option string '-r', '-f' , '-n' or '-rfn' for recursive, force and no-clobber. + * @param {string} destinationOrSource - Destination path or the source path. + * @param {string} [optionsOrDestination] - Options string or the destination path. + * @param {boolean} [continueOnError=false] - Optional. Whether to continue on error. + * @param {number} [retryCount=0] - Optional. Retry count to copy the file. It might help to resolve intermittent issues e.g. with UNC target paths on a remote host. + * @returns {void} + */ +export function cp(sourceOrOptions: unknown, destinationOrSource: string, optionsOrDestination: unknown, continueOnError: boolean = false, retryCount: number = 0): void { + retry(() => { + let recursive = false; + let force = true; + let source = String(sourceOrOptions); + let destination = destinationOrSource; + let options = ''; + + if (typeof sourceOrOptions === 'string' && sourceOrOptions.startsWith('-')) { + options = sourceOrOptions.toLowerCase(); + recursive = options.includes('r'); + force = !options.includes('n'); + source = destinationOrSource; + destination = String(optionsOrDestination)!; + } else if (typeof optionsOrDestination === 'string' && optionsOrDestination && optionsOrDestination.startsWith('-')) { + options = optionsOrDestination.toLowerCase(); + recursive = options.includes('r'); + force = !options.includes('n'); + source = String(sourceOrOptions); + destination = destinationOrSource; + } + + if (!fs.existsSync(destination) && !force) { + throw new Error(loc('LIB_PathNotFound', 'cp', destination)); + } + + const lstatSource = fs.lstatSync(source); + + if (!force && fs.existsSync(destination)) { + return; + } + try { - if (options) { - shell.cp(options, source, dest); - } - else { - shell.cp(source, dest); - } + if (lstatSource.isFile()) { + if (fs.existsSync(destination) && fs.lstatSync(destination).isDirectory()) { + destination = path.join(destination, path.basename(source)); + } - _checkShell('cp', false); - break; - } catch (e) { - if (retryCount <= 0) { - if (continueOnError) { - warning(e, IssueSource.TaskInternal); - break; + if (force) { + fs.copyFileSync(source, destination); } else { - throw e; + fs.copyFileSync(source, destination, fs.constants.COPYFILE_EXCL); } } else { - console.log(loc('LIB_CopyFileFailed', retryCount)); - retryCount--; + fs.cpSync(source, path.join(destination, path.basename(source)), { recursive, force }); } + } catch (error) { + throw new Error(loc('LIB_OperationFailed', 'cp', error)); } - } + }, [], { retryCount, continueOnError}); } +type MoveOptionsVariants = OptionsPermutations<'fn'>; + /** * Moves a path. * - * @param source source path - * @param dest destination path - * @param options string -f or -n for force and no clobber - * @param continueOnError optional. whether to continue on error + * @param {string} source - Source path. + * @param {string} dest - Destination path. + * @param {MoveOptionsVariants} [options] - Option string -f or -n for force and no clobber. + * @param {boolean} [continueOnError] - Optional. Whether to continue on error. + * @returns {void} */ -export function mv(source: string, dest: string, options?: string, continueOnError?: boolean): void { - if (options) { - shell.mv(options, source, dest); - } - else { - shell.mv(source, dest); +export function mv(source: string, dest: string, options?: MoveOptionsVariants, continueOnError?: boolean): void { + let force = false; + + if (options && typeof options === 'string' && options.startsWith('-')) { + const lowercasedOptions = String(options).toLowerCase(); + force = lowercasedOptions.includes('f') && !lowercasedOptions.includes('n'); } - _checkShell('mv', continueOnError); + const sourceExists = fs.existsSync(source); + const destExists = fs.existsSync(dest); + let sources: string[] = []; + + try { + if (!sourceExists) { + if (source.includes('*')) { + sources.push(...findMatch(path.resolve(path.dirname(source)), [path.basename(source)])); + } else { + throw new Error(loc('LIB_PathNotFound', 'mv', source)); + } + } else { + sources.push(source); + } + + if (destExists && !force) { + throw new Error(`File already exists at ${dest}`); + } + + for (const source of sources) { + fs.renameSync(source, dest); + } + } catch (error) { + debug('mv failed'); + var errMsg = loc('LIB_OperationFailed', 'mv', error); + debug(errMsg); + + if (!continueOnError) { + throw new Error(errMsg); + } + } } /** @@ -1423,8 +1699,9 @@ function _legacyFindFiles_getMatchingItems( /** * Remove a path recursively with force * - * @param inputPath path to remove - * @throws when the file or directory exists but could not be deleted. + * @param {string} inputPath - Path to remove + * @return {void} + * @throws When the file or directory exists but could not be deleted. */ export function rmRF(inputPath: string): void { debug('rm -rf ' + inputPath); @@ -1441,8 +1718,7 @@ export function rmRF(inputPath: string): void { debug('removing file ' + inputPath); childProcess.execFileSync("cmd.exe", ["/c", "del", "/f", "/a", inputPath]); } - } - catch (err) { + } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code != 'ENOENT') { @@ -1453,23 +1729,31 @@ export function rmRF(inputPath: string): void { // Shelling out fails to remove a symlink folder with missing source, this unlink catches that try { fs.unlinkSync(inputPath); - } - catch (err) { + } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code != 'ENOENT') { throw new Error(loc('LIB_OperationFailed', 'rmRF', err.message)); } } - } - else { + } else { // get the lstats in order to workaround a bug in shelljs@0.3.0 where symlinks // with missing targets are not handled correctly by "rm('-rf', path)" let lstats: fs.Stats; + try { - lstats = fs.lstatSync(inputPath); - } - catch (err) { + if (inputPath.includes('*')) { + const entries = findMatch(path.dirname(inputPath), [path.basename(inputPath)]); + + for (const entry of entries) { + fs.rmSync(entry, { recursive: true, force: true }); + } + + return; + } else { + lstats = fs.lstatSync(inputPath); + } + } catch (err) { // if you try to delete a file that doesn't exist, desired result is achieved // other errors are valid if (err.code == 'ENOENT') { @@ -1481,9 +1765,18 @@ export function rmRF(inputPath: string): void { if (lstats.isDirectory()) { debug('removing directory'); - shell.rm('-rf', inputPath); - let errMsg: string = shell.error(); - if (errMsg) { + try { + fs.rmSync(inputPath, { recursive: true, force: true }); + } catch (errMsg) { + throw new Error(loc('LIB_OperationFailed', 'rmRF', errMsg)); + } + + return; + } else if (lstats.isSymbolicLink()) { + debug('removing symbolic link'); + try { + fs.unlinkSync(inputPath); + } catch (errMsg) { throw new Error(loc('LIB_OperationFailed', 'rmRF', errMsg)); } @@ -1492,7 +1785,11 @@ export function rmRF(inputPath: string): void { debug('removing file'); try { - fs.unlinkSync(inputPath); + const entries = findMatch(path.dirname(inputPath), [path.basename(inputPath)]); + + for (const entry of entries) { + fs.rmSync(entry, { recursive: true, force: true }); + } } catch (err) { throw new Error(loc('LIB_OperationFailed', 'rmRF', err.message)); @@ -1794,7 +2091,6 @@ function _getDefaultMatchOptions(): MatchOptions { * @param matchOptions defaults to { dot: true, nobrace: true, nocase: process.platform == 'win32' } */ export function findMatch(defaultRoot: string, patterns: string[] | string, findOptions?: FindOptions, matchOptions?: MatchOptions): string[] { - // apply defaults for parameters and trace defaultRoot = defaultRoot || this.getVariable('system.defaultWorkingDirectory') || process.cwd(); debug(`defaultRoot: '${defaultRoot}'`); diff --git a/node/test/cd.ts b/node/test/cd.ts new file mode 100644 index 000000000..409e1ad8d --- /dev/null +++ b/node/test/cd.ts @@ -0,0 +1,147 @@ +import os = require('node:os'); +import fs = require('node:fs'); +import path = require('node:path'); +import assert = require('node:assert'); + +import * as tl from '../_build/task'; + +const DIRNAME = __dirname; + +import * as testutil from './testutil'; + +describe('cd cases', () => { + const TEMP_DIR_1 = path.resolve(DIRNAME, 'temp1'); + const TEMP_DIR_2 = path.resolve(DIRNAME, 'temp2'); + const TEMP_DIR_2_SUBDIR_1 = path.resolve(TEMP_DIR_2, 'subdir1'); + const TEMP_FILE_1 = path.resolve(TEMP_DIR_1, 'file1'); + const TEMP_DIR_2_SUBDIR_1_FILE_1 = path.resolve(TEMP_DIR_2_SUBDIR_1, 'file1'); + const TEMP_DIR_2_SUBDIR_1_SYMLINK_FILE_1 = path.resolve(TEMP_DIR_2_SUBDIR_1, 'symlink_file_1'); + const TEMP_DIR_2_SUBDIR_1_SYMLINK_DIR_1 = path.resolve(TEMP_DIR_2_SUBDIR_1, 'symlink_dir_1'); + + before((done) => { + process.chdir(DIRNAME); + + tl.mkdirP(TEMP_DIR_1); + tl.mkdirP(TEMP_DIR_2); + tl.mkdirP(TEMP_DIR_2_SUBDIR_1); + fs.writeFileSync(TEMP_FILE_1, 'file1'); + fs.writeFileSync(TEMP_DIR_2_SUBDIR_1_FILE_1, 'file1'); + fs.symlinkSync(TEMP_FILE_1, TEMP_DIR_2_SUBDIR_1_SYMLINK_FILE_1); + fs.symlinkSync(TEMP_DIR_1, TEMP_DIR_2_SUBDIR_1_SYMLINK_DIR_1); + + try { + testutil.initialize(); + } catch (error) { + assert.fail(`Failed to load tl lib: ${error.message}`); + } + + done(); + }); + + beforeEach(() => { + process.env.OLDPWD = ''; + process.chdir(DIRNAME); + }); + + after((done) => { + tl.cd(DIRNAME); + tl.rmRF(TEMP_DIR_1); + tl.rmRF(TEMP_DIR_2); + + done(); + }); + + it('Provide a path does not exist', (done) => { + assert.ok(!fs.existsSync('/thisfolderdoesnotexist')); + assert.throws(() => tl.cd('/thisfolderdoesnotexist'), { message: 'Not found cd: /thisfolderdoesnotexist' }); + done(); + }); + + it('Provide all suite possible directories', (done) => { + assert.equal(process.cwd(), DIRNAME); + + tl.cd(TEMP_DIR_1); + assert.equal(process.cwd(), TEMP_DIR_1); + + tl.cd(TEMP_DIR_2); + assert.equal(process.cwd(), TEMP_DIR_2); + + tl.cd(TEMP_DIR_2_SUBDIR_1); + assert.equal(process.cwd(), TEMP_DIR_2_SUBDIR_1); + + tl.cd(TEMP_DIR_2_SUBDIR_1_SYMLINK_DIR_1); + assert.equal(fs.realpathSync('.'), TEMP_DIR_1); + + assert.equal(process.env.OLDPWD, TEMP_DIR_2_SUBDIR_1); + + done(); + }); + + it('Provide path that is a file path', (done) => { + assert.ok(fs.existsSync(TEMP_FILE_1)); + assert.throws(() => tl.cd(TEMP_FILE_1), { message: `Path is not a directory: ${TEMP_FILE_1}` }); + done(); + }); + + it('Provide path that is a file symlink', (done) => { + assert.ok(fs.existsSync(TEMP_DIR_2_SUBDIR_1_SYMLINK_FILE_1)); + assert.throws(() => tl.cd(TEMP_DIR_2_SUBDIR_1_SYMLINK_FILE_1), { message: `Path is not a directory: ${TEMP_DIR_2_SUBDIR_1_SYMLINK_FILE_1}` }); + done(); + }); + + it('Provide path that is a dir symlink', (done) => { + assert.ok(fs.existsSync(TEMP_DIR_2_SUBDIR_1_SYMLINK_DIR_1)); + assert.doesNotThrow(() => tl.cd(TEMP_DIR_2_SUBDIR_1_SYMLINK_DIR_1)); + assert.equal(fs.realpathSync('.'), TEMP_DIR_1); + done(); + }); + + it('Check if there is no previous directory', (done) => { + assert.throws(() => tl.cd('-'), { message: 'Could not find previous directory' }); + done(); + }); + + it('Provide a relative directory path', (done) => { + const relativePath = path.relative(process.cwd(), TEMP_DIR_1); + tl.cd(relativePath); + assert.equal(path.basename(relativePath), relativePath); + done(); + }); + + it('Provide an absolute directory path', (done) => { + tl.cd('/'); + assert.equal(process.cwd(), path.resolve('/')); + done(); + }); + + it('Change directory to a previous directory -', (done) => { + tl.cd('/'); + tl.cd('-'); + assert.ok(process.cwd(), path.resolve(DIRNAME)); + done(); + }); + + it('Change directory with cp', (done) => { + const TEMP_DIR_2_FILE_1 = path.resolve(TEMP_DIR_2, 'file1'); + assert.ok(!fs.existsSync(TEMP_DIR_2_FILE_1)); + + tl.cd(TEMP_DIR_1); + tl.cp(TEMP_FILE_1, path.resolve("..", TEMP_DIR_2)); + tl.cd(path.resolve("..", TEMP_DIR_2)); + + assert.ok(fs.existsSync(TEMP_DIR_2_FILE_1)); + + done(); + }); + + it('Using the tilde expansion', (done) => { + tl.cd('~'); + assert.ok(process.cwd(), os.homedir()); + tl.cd('..'); + assert.notEqual(process.cwd(), os.homedir()); + tl.cd('~'); + assert.equal(process.cwd(), os.homedir()); + + done(); + }); +}); \ No newline at end of file diff --git a/node/test/cp.ts b/node/test/cp.ts new file mode 100644 index 000000000..0c518162c --- /dev/null +++ b/node/test/cp.ts @@ -0,0 +1,143 @@ +import fs = require('node:fs'); +import path = require('node:path'); +import assert = require('node:assert'); + +import * as tl from '../_build/task'; + +const DIRNAME = __dirname; + +import * as testutil from './testutil'; + +describe('cp cases', () => { + const TEMP_DIR_1 = path.resolve(DIRNAME, 'temp1'); + const TEMP_DIR_2 = path.resolve(DIRNAME, 'temp2'); + const TEMP_DIR_2_FILE_1 = path.resolve(TEMP_DIR_2, 'file1'); + const TESTCASE_1 = path.resolve(TEMP_DIR_1, 'testcase_1'); + const TESTCASE_2 = path.resolve(TEMP_DIR_1, 'testcase_2'); + + before((done) => { + tl.mkdirP(TEMP_DIR_1); + tl.mkdirP(TEMP_DIR_2); + tl.cd(TEMP_DIR_1); + + fs.writeFileSync(TEMP_DIR_2_FILE_1, 'file1'); + + try { + testutil.initialize(); + } catch (error) { + assert.fail(`Failed to load tl lib: ${error.message}`); + } + + done(); + }); + + beforeEach((done) => { + fs.writeFileSync(TESTCASE_1, 'testcase_1'); + fs.writeFileSync(TESTCASE_2, 'testcase_2'); + + done(); + }); + + afterEach((done) => { + tl.rmRF(TESTCASE_1); + tl.rmRF(TESTCASE_2); + + done(); + }); + + after((done) => { + tl.cd(DIRNAME); + tl.rmRF(TEMP_DIR_1); + tl.rmRF(TEMP_DIR_2); + + done(); + }); + + it('Provide the source that does not exist', (done) => { + assert.throws(() => tl.cp('pathdoesnotexist', TEMP_DIR_1), { message: /^ENOENT: no such file or directory/ }); + assert.ok(!fs.existsSync(path.join(TEMP_DIR_1, 'pathdoesnotexist'))); + + done(); + }); + + it('Provide the source as empty string', (done) => { + assert.throws(() => tl.cp('', 'pathdoesnotexist'), { message: /^ENOENT: no such file or directory/ }); + + done(); + }); + + it('Provide the destination as empty string', (done) => { + assert.throws(() => tl.cp('pathdoesnotexist', ''), { message: /^ENOENT: no such file or directory/ }); + + done(); + }); + + it('Provide -n attribute to prevent overwrite an existing file at the destination', (done) => { + assert.doesNotThrow(() => tl.cp('-n', TESTCASE_1, TESTCASE_2)); + assert.equal(fs.readFileSync(TESTCASE_2, 'utf8'), 'testcase_2'); + + done(); + }); + + it('Provide two paths, check force default behavior', (done) => { + assert.doesNotThrow(() => tl.cp(TESTCASE_1, TESTCASE_2)); + assert.equal(fs.readFileSync(TESTCASE_2, 'utf8'), 'testcase_1'); + + done(); + }); + + it('Provide two paths, check explicitly force attribute', (done) => { + assert.doesNotThrow(() => tl.cp('-f', TESTCASE_1, TESTCASE_2)); + assert.equal(fs.readFileSync(TESTCASE_2, 'utf8'), 'testcase_1'); + + done(); + }); + + it('Check copying a file to a dir', (done) => { + assert.doesNotThrow(() => tl.cp(TESTCASE_1, TEMP_DIR_2)); + assert.ok(fs.existsSync(path.join(TEMP_DIR_2, 'testcase_1'))); + assert.equal(fs.readFileSync(path.join(TEMP_DIR_2, 'testcase_1'), 'utf8'), 'testcase_1'); + + done(); + }); + + it('Check copying file to a file', (done) => { + assert.doesNotThrow(() => tl.cp(TESTCASE_2, path.join(TEMP_DIR_2, 'testcase_3'))); + assert.ok(fs.existsSync(path.join(TEMP_DIR_2, 'testcase_3'))); + assert.equal(fs.readFileSync(path.join(TEMP_DIR_2, 'testcase_3'), 'utf8'), 'testcase_2'); + + done(); + }); + + it('Check copying file to an existed file with -f option', (done) => { + assert.ok(fs.existsSync(TESTCASE_1)); + assert.ok(fs.existsSync(TESTCASE_2)); + assert.equal(fs.readFileSync(TESTCASE_1, 'utf8'), 'testcase_1'); + assert.equal(fs.readFileSync(TESTCASE_2, 'utf8'), 'testcase_2'); + + assert.doesNotThrow(() => tl.cp('-f', TESTCASE_1, TESTCASE_2)); + + assert.ok(fs.existsSync(TESTCASE_1)); + assert.ok(fs.existsSync(TESTCASE_2)); + assert.equal(fs.readFileSync(TESTCASE_1, 'utf8'), 'testcase_1'); + assert.equal(fs.readFileSync(TESTCASE_2, 'utf8'), 'testcase_1'); + + done(); + }); + + it('Check copying file to an existed file with -n option', (done) => { + assert.ok(fs.existsSync(TESTCASE_1)); + assert.ok(fs.existsSync(TESTCASE_2)); + assert.equal(fs.readFileSync(TESTCASE_1, 'utf8'), 'testcase_1'); + assert.equal(fs.readFileSync(TESTCASE_2, 'utf8'), 'testcase_2'); + + assert.doesNotThrow(() => tl.cp('-n', TESTCASE_1, TESTCASE_2)); + + assert.ok(fs.existsSync(TESTCASE_1)); + assert.ok(fs.existsSync(TESTCASE_2)); + assert.equal(fs.readFileSync(TESTCASE_1, 'utf8'), 'testcase_1'); + assert.equal(fs.readFileSync(TESTCASE_2, 'utf8'), 'testcase_2'); + + done(); + }); +}); \ No newline at end of file diff --git a/node/test/ls.ts b/node/test/ls.ts new file mode 100644 index 000000000..68d8c7b47 --- /dev/null +++ b/node/test/ls.ts @@ -0,0 +1,320 @@ +import os = require('node:os'); +import fs = require('node:fs'); +import path = require('node:path'); +import assert = require('node:assert'); + +import * as tl from '../_build/task'; + +const DIRNAME = __dirname; + +import * as testutil from './testutil'; + +describe('ls cases', () => { + const TEMP_DIR_1 = path.resolve(DIRNAME, 'temp1'); + const TEMP_SUBDIR_1 = path.resolve(TEMP_DIR_1, 'temp1_subdir1'); + let TEMP_FILE_1: string; + let TEMP_FILE_1_JS: string; + let TEMP_FILE_2: string; + let TEMP_FILE_2_JS: string; + let TEMP_FILE_3_ESCAPED: string; + let TEMP_HIDDEN_FILE_1: string; + let TEMP_HIDDEN_DIR_1: string; + let TEMP_SUBDIR_FILE_1: string; + let TEMP_SUBDIR_FILELINK_1: string; + + before((done) => { + try { + testutil.initialize(); + } catch (error) { + assert.fail(`Failed to load tl lib: ${error.message}`); + } + + done(); + }); + + after((done) => { + tl.cd(DIRNAME); + done(); + }); + + beforeEach((done) => { + tl.mkdirP(TEMP_SUBDIR_1); + tl.cd(TEMP_DIR_1); + + TEMP_FILE_1 = path.join(TEMP_DIR_1, 'file1'); + fs.writeFileSync(TEMP_FILE_1, 'test'); + TEMP_FILE_1_JS = path.join(TEMP_DIR_1, 'file1.js'); + fs.writeFileSync(TEMP_FILE_1_JS, 'test'); + TEMP_FILE_2 = path.join(TEMP_DIR_1, 'file2'); + fs.writeFileSync(TEMP_FILE_2, 'test'); + TEMP_FILE_2_JS = path.join(TEMP_DIR_1, 'file2.js'); + fs.writeFileSync(TEMP_FILE_2_JS, 'test'); + TEMP_FILE_3_ESCAPED = path.join(TEMP_DIR_1, '(filename)e$cap3d.[]^-%'); + fs.writeFileSync(TEMP_FILE_3_ESCAPED, 'test'); + TEMP_HIDDEN_FILE_1 = path.join(TEMP_DIR_1, '.hidden_file'); + fs.writeFileSync(TEMP_HIDDEN_FILE_1, 'test'); + TEMP_HIDDEN_DIR_1 = path.join(TEMP_DIR_1, '.hidden_dir'); + fs.mkdirSync(TEMP_HIDDEN_DIR_1); + + TEMP_SUBDIR_FILE_1 = path.join(TEMP_SUBDIR_1, 'file'); + fs.writeFileSync(TEMP_SUBDIR_FILE_1, 'test'); + + TEMP_SUBDIR_FILELINK_1 = path.join(TEMP_SUBDIR_1, 'filelink'); + fs.symlinkSync(TEMP_SUBDIR_FILE_1, TEMP_SUBDIR_FILELINK_1); + + done(); + }); + + afterEach((done) => { + tl.cd(DIRNAME); + tl.rmRF(TEMP_DIR_1); + done(); + }); + + it('Provide the folder which does not exist', (done) => { + assert.ok(!fs.existsSync('/thisfolderdoesnotexist')); + assert.throws(() => tl.ls('/thisfolderdoesnotexist'), { message: /^Not found ls: ENOENT: no such file or directory, lstat/ }); + done(); + }); + + it('Without arguments', (done) => { + const result = tl.ls(); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.ok(result.includes(TEMP_FILE_3_ESCAPED)); + assert.ok(result.includes(TEMP_SUBDIR_1)); + assert.equal(result.length, 6); + + done(); + }); + + it('Passed TEMP_DIR_1 as an argument', (done) => { + const result = tl.ls(TEMP_DIR_1); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.ok(result.includes(TEMP_FILE_3_ESCAPED)); + assert.ok(result.includes(TEMP_SUBDIR_1)); + assert.equal(result.length, 6); + + done(); + }); + + it('Passed file as an argument', (done) => { + const result = tl.ls(TEMP_FILE_1); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.equal(result.length, 1); + + done(); + }); + + it('Provide the -A attribute as an argument', (done) => { + tl.cd(TEMP_DIR_1); + const result = tl.ls('-A'); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.ok(result.includes(TEMP_FILE_3_ESCAPED)); + assert.ok(result.includes(TEMP_SUBDIR_1)); + assert.ok(result.includes(TEMP_HIDDEN_FILE_1)); + assert.ok(result.includes(TEMP_HIDDEN_DIR_1)); + assert.equal(result.length, 8); + + done(); + }); + + it('Wildcard for TEMP_DIR_1', (done) => { + const result = tl.ls(path.join(TEMP_DIR_1, '*')); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.ok(result.includes(TEMP_FILE_3_ESCAPED)); + assert.ok(result.includes(TEMP_SUBDIR_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 7); + + done(); + }); + + it('Wildcard for find f*l*', (done) => { + const result = tl.ls(path.join(TEMP_DIR_1, 'f*l*')); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.equal(result.length, 4); + + done(); + }); + + it('Wildcard f*l*.js', (done) => { + const result = tl.ls(path.join(TEMP_DIR_1, 'f*l*.js')); + + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.equal(result.length, 2); + + done(); + }); + + it('Wildcard that is not valid', (done) => { + const result = tl.ls(path.join(TEMP_DIR_1, '/*.j')); + + assert.equal(result.length, 0); + + done(); + }); + + it('Wildcard *.*', (done) => { + const result = tl.ls(path.join(TEMP_DIR_1, '*.*')); + + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.ok(result.includes(TEMP_FILE_3_ESCAPED)); + assert.equal(result.length, 3); + + done(); + }); + + it('Two wildcards in the array', (done) => { + const result = tl.ls([path.join(TEMP_DIR_1, 'f*le*.js'), path.join(TEMP_SUBDIR_1, '*')]); + + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.ok(result.includes(TEMP_SUBDIR_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 4); + + done(); + }); + + it('Recursive without path argument', (done) => { + tl.cd(TEMP_DIR_1); + const result = tl.ls('-R'); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.ok(result.includes(TEMP_FILE_3_ESCAPED)); + assert.ok(result.includes(TEMP_SUBDIR_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 7); + + done(); + }); + + it('Provide path and recursive attribute', (done) => { + const result = tl.ls('-R', TEMP_DIR_1); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.ok(result.includes(TEMP_FILE_3_ESCAPED)); + assert.ok(result.includes(TEMP_SUBDIR_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 7); + + done(); + }); + + it('Provide path and -RA attributes', (done) => { + const result = tl.ls('-RA', TEMP_DIR_1); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.ok(result.includes(TEMP_FILE_1_JS)); + assert.ok(result.includes(TEMP_FILE_2)); + assert.ok(result.includes(TEMP_FILE_2_JS)); + assert.ok(result.includes(TEMP_FILE_3_ESCAPED)); + assert.ok(result.includes(TEMP_SUBDIR_FILE_1)); + assert.ok(result.includes(TEMP_HIDDEN_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 8); + + done(); + }); + + it('Priovide -RA attribute', (done) => { + const result = tl.ls('-RA', TEMP_SUBDIR_1); + + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 2); + + done(); + }); + + it('Provide path and the -R attribute', (done) => { + const result = tl.ls('-R', TEMP_SUBDIR_1); + + assert.ok(result.includes(TEMP_SUBDIR_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 2); + + done(); + }); + + it('Empty attributes, but several paths as multiple arguments', (done) => { + const result = tl.ls('', TEMP_SUBDIR_1, TEMP_FILE_1); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 3); + + done(); + }); + + it('Empty attributes, but several paths in array', (done) => { + const result = tl.ls('', [TEMP_SUBDIR_1]); + + assert.ok(result.includes(TEMP_SUBDIR_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 2); + + done(); + }); + + it('Empty attributes, but one path', (done) => { + const result = tl.ls('', TEMP_SUBDIR_1); + + assert.ok(result.includes(TEMP_SUBDIR_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 2); + + done(); + }); + + it('Provide path as first argument and subdir as second argument', (done) => { + const result = tl.ls(TEMP_FILE_1, TEMP_SUBDIR_1); + + assert.ok(result.includes(TEMP_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILE_1)); + assert.ok(result.includes(TEMP_SUBDIR_FILELINK_1)); + assert.equal(result.length, 3); + + done(); + }); + + it('New one folder without content', (done) => { + tl.mkdirP('foo'); + + assert.doesNotThrow(() => tl.ls('foo')); + assert.equal(tl.ls('foo').length, 0); + + tl.rmRF('foo'); + + done(); + }); +}); \ No newline at end of file diff --git a/node/test/mv.ts b/node/test/mv.ts new file mode 100644 index 000000000..a0217932a --- /dev/null +++ b/node/test/mv.ts @@ -0,0 +1,151 @@ +import fs = require('node:fs'); +import path = require('node:path'); +import assert = require('node:assert'); + +import * as tl from '../_build/task'; + +const DIRNAME = __dirname; + +import * as testutil from './testutil'; + +describe('mv cases', () => { + const TEMP_DIR = fs.mkdtempSync(DIRNAME + path.sep); + let TEMP_FILE_1: string; + let TEMP_FILE_1_JS: string; + let TEMP_FILE_2: string; + let TEMP_FILE_2_JS: string; + + before((done) => { + try { + testutil.initialize(); + } catch (error) { + assert.fail(`Failed to load tl lib: ${error.message}`); + } + + tl.cd(TEMP_DIR); + done(); + }); + + beforeEach((done) => { + TEMP_FILE_1 = path.join(TEMP_DIR, 'file1'); + fs.writeFileSync(TEMP_FILE_1, 'test'); + TEMP_FILE_1_JS = path.join(TEMP_DIR, 'file1.js'); + fs.writeFileSync(TEMP_FILE_1_JS, 'test'); + TEMP_FILE_2 = path.join(TEMP_DIR, 'file2'); + fs.writeFileSync(TEMP_FILE_2, 'test'); + TEMP_FILE_2_JS = path.join(TEMP_DIR, 'file2.js'); + fs.writeFileSync(TEMP_FILE_2_JS, 'test'); + + done(); + }); + + after((done) => { + tl.cd(DIRNAME); + tl.rmRF(TEMP_DIR); + + done(); + }); + + it('Provide an unsupported option argument', (done) => { + assert.ok(fs.existsSync('file1')); + // @ts-ignore + assert.doesNotThrow(() => tl.mv('file1', 'file1', '-Z', true)); + assert.ok(fs.existsSync('file1')); + + done(); + }); + + it('Provide a source that does not exist', (done) => { + assert.throws(() => tl.mv('pathdoesnotexist1', '..'), { message: /Failed mv: Error: Not found mv: pathdoesnotexist1/ }); + assert.ok(!fs.existsSync('../pathdoesnotexist2')); + + done(); + }); + + it('Provide a source that does not exist, continue on error', (done) => { + assert.doesNotThrow(() => tl.mv('pathdoesnotexist1', '..', '', true)); + assert.ok(!fs.existsSync('../pathdoesnotexist2')); + + done(); + }); + + it('Provide a source that does not exist 2', (done) => { + assert.throws(() => tl.mv('pathdoesnotexist1', 'pathdoesnotexist2'), { message: /Failed mv: Error: Not found mv: pathdoesnotexist1/ }); + assert.ok(!fs.existsSync('../pathdoesnotexist1')); + assert.ok(!fs.existsSync('../pathdoesnotexist2')); + + done(); + }); + + it('Provide a source that does not exist, continue on error', (done) => { + assert.doesNotThrow(() => tl.mv('pathdoesnotexist1', 'pathdoesnotexist2', '', true)); + assert.ok(!fs.existsSync('../pathdoesnotexist1')); + assert.ok(!fs.existsSync('../pathdoesnotexist2')); + + done(); + }); + + it('Provide a destination that already exist', (done) => { + assert.ok(fs.existsSync('file1')); + assert.ok(fs.existsSync('file2')); + + assert.throws(() => tl.mv('file1', 'file2'), { message: /Failed mv: Error: File already exists at file2/ }); + + assert.ok(fs.existsSync('file1')); + assert.ok(fs.existsSync('file2')); + + done(); + }); + + it('Provide a wildcard when dest is file', (done) => { + assert.throws(() => tl.mv('file*', 'file1'), { message: /Failed mv: Error: File already exists at file1/ }); + assert.ok(fs.existsSync('file1')); + assert.ok(fs.existsSync('file2')); + assert.ok(fs.existsSync('file1.js')); + assert.ok(fs.existsSync('file2.js')); + + done(); + }); + + it('Provide a destination that already exist, continue on error', (done) => { + assert.ok(fs.existsSync('file1')); + assert.ok(fs.existsSync('file2')); + + assert.doesNotThrow(() => tl.mv('file1', 'file2', '', true)); + + assert.ok(fs.existsSync('file1')); + assert.ok(fs.existsSync('file2')); + + done(); + }); + + it('Provide a wildcard when dest is file, continue on error', (done) => { + assert.doesNotThrow(() => tl.mv('file*', 'file1', '', true)); + assert.ok(fs.existsSync('file1')); + assert.ok(fs.existsSync('file2')); + assert.ok(fs.existsSync('file1.js')); + assert.ok(fs.existsSync('file2.js')); + + done(); + }); + + it('Move a file and rollback', (done) => { + assert.ok(fs.existsSync('file1')); + tl.mv('file1', 'file3'); + assert.ok(!fs.existsSync('file1')); + assert.ok(fs.existsSync('file3')); + tl.mv('file3', 'file1'); + assert.ok(fs.existsSync('file1')); + + done(); + }); + + it('Move to an existed path with -f attribute', (done) => { + assert.ok(fs.existsSync('file1')); + assert.doesNotThrow(() => tl.mv('file1', 'file2', '-f')); + assert.ok(!fs.existsSync('file1')); + assert.ok(fs.existsSync('file2')); + + done(); + }); +}); \ No newline at end of file diff --git a/node/test/popd.ts b/node/test/popd.ts new file mode 100644 index 000000000..65b9f7d99 --- /dev/null +++ b/node/test/popd.ts @@ -0,0 +1,139 @@ +import path = require('node:path'); +import assert = require('node:assert'); + +import * as tl from '../_build/task'; + +const DIRNAME = __dirname; + +function reset() { + while (true) { + try { + const stack = tl.popd(); + + if (stack.length === 0) { + break; + } + } catch { + break; + } + } + + tl.cd(DIRNAME); +} + +describe('popd cases', () => { + const TEMP_DIR_PATH = path.resolve(DIRNAME, 'test_pushd', 'nested', 'dir'); + + before(() => { + tl.mkdirP(path.resolve(TEMP_DIR_PATH, 'a')); + tl.mkdirP(path.resolve(TEMP_DIR_PATH, 'b', 'c')); + }); + + beforeEach(() => { + reset(); + }); + + after(() => { + tl.cd(DIRNAME); + reset(); + tl.rmRF(path.resolve(TEMP_DIR_PATH)); + }); + + it('The default usage', (done) => { + tl.pushd(TEMP_DIR_PATH); + const trail = tl.popd(); + + assert.ok(process.cwd(), trail[0]); + assert.deepEqual(trail, [DIRNAME]); + + done(); + }); + + it('Using two directories on the stack', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + const trail = tl.popd(); + + assert.ok(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH), + DIRNAME, + ]); + + done(); + }); + + it('Using three directories on the stack', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('b'); + tl.pushd('c'); + const trail = tl.popd(); + + assert.ok(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH, 'b'), + TEMP_DIR_PATH, + DIRNAME, + ]); + + done(); + }); + + it('Valid by index', (done) => { + tl.pushd(TEMP_DIR_PATH); + const trail = tl.popd('+0'); + + assert.ok(process.cwd(), trail[0]); + assert.deepEqual(trail, [DIRNAME]); + + done(); + }); + + it('Using +1 option', (done) => { + tl.pushd(TEMP_DIR_PATH); + const trail = tl.popd('+1'); + + assert.ok(process.cwd(), trail[0]); + assert.deepEqual(trail, [path.resolve(TEMP_DIR_PATH)]); + + done(); + }); + + it('Using -0 option', (done) => { + const r = tl.pushd(TEMP_DIR_PATH); + const trail = tl.popd('-0'); + + assert.ok(process.cwd(), trail[0]); + assert.deepEqual(trail, [path.resolve(TEMP_DIR_PATH)]); + + done(); + }); + + it('Using -1 option', (done) => { + tl.pushd(TEMP_DIR_PATH); + const trail = tl.popd('-1'); + + assert.ok(process.cwd(), trail[0]); + assert.deepEqual(trail, [DIRNAME]); + + done(); + }); + + it('Using when stack is empty', (done) => { + assert.throws(() => tl.popd(), { message: 'Directory stack is empty' }); + + done(); + }); + + it('Using when the DIRNAME is not stored', (done) => { + tl.cd(TEMP_DIR_PATH); + tl.pushd('b'); + const trail = tl.popd(); + + assert.ok(trail[0], path.resolve(TEMP_DIR_PATH)); + assert.ok(process.cwd(), trail[0]); + assert.throws(() => tl.popd(), { message: 'Directory stack is empty' }); + + done(); + }); +}); \ No newline at end of file diff --git a/node/test/pushd.ts b/node/test/pushd.ts new file mode 100644 index 000000000..ab05aa18e --- /dev/null +++ b/node/test/pushd.ts @@ -0,0 +1,338 @@ +import path = require('node:path'); +import assert = require('node:assert'); + +import * as tl from '../_build/task'; + +const DIRNAME = __dirname; + +function reset() { + while (true) { + try { + const stack = tl.popd(); + + if (stack.length === 0) { + break; + } + } catch { + break; + } + } + + tl.cd(DIRNAME); +} + +describe('pushd cases', () => { + const TEMP_DIR_PATH = path.resolve(DIRNAME, 'test_pushd', 'nested', 'dir'); + + before(() => { + tl.mkdirP(path.resolve(TEMP_DIR_PATH, 'a')); + tl.mkdirP(path.resolve(TEMP_DIR_PATH, 'b', 'c')); + }); + + beforeEach(() => { + reset(); + }); + + after(() => { + reset(); + tl.cd(DIRNAME); + tl.rmRF(path.resolve(TEMP_DIR_PATH)); + }); + + it('Push valid directories', (done) => { + const trail = tl.pushd(TEMP_DIR_PATH); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + TEMP_DIR_PATH, + DIRNAME, + ]); + + done(); + }); + + it('Using two directories', (done) => { + tl.pushd(TEMP_DIR_PATH); + const trail = tl.pushd('a'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + DIRNAME, + ]); + + done(); + }); + + it('Using three directories', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + const trail = tl.pushd('../b'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH, 'b'), + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + DIRNAME, + ]); + + done(); + }); + + it('Using four directories', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + const trail = tl.pushd('c'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + path.resolve(TEMP_DIR_PATH, 'b'), + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + DIRNAME, + ]); + + done(); + }); + + it('Using push stuff around with positive indices', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + tl.pushd('c'); + const trail = tl.pushd('+0'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + path.resolve(TEMP_DIR_PATH, 'b'), + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + DIRNAME, + ]); + + done(); + }); + + it('Using +1 option', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + tl.pushd('c'); + const trail = tl.pushd('+1'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH, 'b'), + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + DIRNAME, + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + ]); + + done(); + }); + + it('Using +2 option', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + tl.pushd('c'); + const trail = tl.pushd('+2'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + DIRNAME, + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + path.resolve(TEMP_DIR_PATH, 'b'), + ]); + + done(); + }); + + it('Using +3 option', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + tl.pushd('c'); + const trail = tl.pushd('+3'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + TEMP_DIR_PATH, + DIRNAME, + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + path.resolve(TEMP_DIR_PATH, 'b'), + path.resolve(TEMP_DIR_PATH, 'a'), + ]); + + done(); + }); + + it('Using +4 option', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + tl.pushd('c'); + const trail = tl.pushd('+4'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + DIRNAME, + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + path.resolve(TEMP_DIR_PATH, 'b'), + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + ]); + + done(); + }); + + it('Using negative index', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + tl.pushd('c'); + const trail = tl.pushd('-0'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + DIRNAME, + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + path.resolve(TEMP_DIR_PATH, 'b'), + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + ]); + + done(); + }); + + it('Using -1 option', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + tl.pushd('c'); + const trail = tl.pushd('-1'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + TEMP_DIR_PATH, + DIRNAME, + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + path.resolve(TEMP_DIR_PATH, 'b'), + path.resolve(TEMP_DIR_PATH, 'a'), + ]); + + done(); + }); + + it('Using -2 option', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + tl.pushd('c'); + const trail = tl.pushd('-2'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + DIRNAME, + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + path.resolve(TEMP_DIR_PATH, 'b'), + ]); + + done(); + }); + + it('Using -3 option', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + tl.pushd('c'); + const trail = tl.pushd('-3'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH, 'b'), + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + DIRNAME, + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + ]); + + done(); + }); + + it('Using -4 option', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd('a'); + tl.pushd('../b'); + tl.pushd('c'); + const trail = tl.pushd('-4'); + + assert.equal(process.cwd(), trail[0]); + assert.deepEqual(trail, [ + path.resolve(TEMP_DIR_PATH, 'b', 'c'), + path.resolve(TEMP_DIR_PATH, 'b'), + path.resolve(TEMP_DIR_PATH, 'a'), + TEMP_DIR_PATH, + DIRNAME, + ]); + + done(); + }); + + it('Using invalid directory', (done) => { + const oldCwd = process.cwd(); + + assert.throws(() => tl.pushd('does/not/exist'), { message: /^Not found pushd/ }); + assert.equal(process.cwd(), oldCwd); + + done(); + }); + + it('Using without args swaps top two directories when stack length is 2', (done) => { + let trail = tl.pushd(TEMP_DIR_PATH); + + assert.equal(trail.length, 2); + assert.equal(trail[0], TEMP_DIR_PATH); + assert.equal(trail[1], DIRNAME); + assert.equal(process.cwd(), trail[0]); + + trail = tl.pushd(); + + assert.equal(trail.length, 2); + assert.equal(trail[0], DIRNAME); + assert.equal(trail[1], TEMP_DIR_PATH); + assert.equal(process.cwd(), trail[0]); + + done(); + }); + + it('Using without args swaps top two directories for larger stacks', (done) => { + tl.pushd(TEMP_DIR_PATH); + tl.pushd(); + const trail = tl.pushd(path.join(TEMP_DIR_PATH, 'a')); + + assert.equal(trail.length, 3); + assert.equal(trail[0], path.join(TEMP_DIR_PATH, 'a')); + assert.equal(trail[1], DIRNAME); + assert.equal(trail[2], TEMP_DIR_PATH); + assert.equal(process.cwd(), trail[0]); + + done(); + }); + + it('Using without arguments invalid when stack is empty', (done) => { + assert.throws(() => tl.pushd(), { message: 'Directory stack is empty' }); + + done(); + }); +}); \ No newline at end of file diff --git a/node/test/rm.ts b/node/test/rm.ts new file mode 100644 index 000000000..96d93e0d5 --- /dev/null +++ b/node/test/rm.ts @@ -0,0 +1,134 @@ +import os = require('node:os'); +import fs = require('node:fs'); +import path = require('node:path'); +import assert = require('node:assert'); + +import * as tl from '../_build/task'; + +const DIRNAME = __dirname; + +import * as testutil from './testutil'; + +describe('rm cases', () => { + const TEMP_DIR = fs.mkdtempSync(DIRNAME + path.sep); + const TEMP_NESTED_DIR_LEVEL_1 = path.join(TEMP_DIR, 'a'); + const TEMP_NESTED_DIR_FULL_TREE = path.join(TEMP_NESTED_DIR_LEVEL_1, 'b', 'c'); + const TEMP_FILE_1 = path.join(TEMP_DIR, 'file1'); + + before((done) => { + try { + testutil.initialize(); + } catch (error) { + assert.fail(`Failed to load tl lib: ${error.message}`); + } + + fs.writeFileSync(TEMP_FILE_1, 'test'); + + done(); + }); + + after((done) => { + tl.cd(DIRNAME) + tl.rmRF(TEMP_DIR); + + done(); + }); + + it('Invalid arguments', (done) => { + assert.doesNotThrow(() => tl.rmRF('somefolderpaththatdoesnotexist')); + done(); + }); + + it('Remove TEMP_FILE_1', (done) => { + assert.ok(fs.existsSync(TEMP_FILE_1)); + assert.doesNotThrow(() => tl.rmRF(TEMP_FILE_1)); + assert.ok(!fs.existsSync(TEMP_FILE_1)); + + done(); + }); + + it('Remove subdirectory recursive at TEMP_NESTED_DIR_LEVEL_1', (done) => { + tl.mkdirP(TEMP_NESTED_DIR_FULL_TREE); + + assert.ok(fs.existsSync(TEMP_NESTED_DIR_FULL_TREE)); + assert.doesNotThrow(() => tl.rmRF(TEMP_NESTED_DIR_LEVEL_1)); + assert.ok(!fs.existsSync(TEMP_NESTED_DIR_LEVEL_1)); + + done(); + }); + + it('Remove subdirectory recursive at TEMP_NESTED_DIR_LEVEL_1 with absolute path', (done) => { + tl.mkdirP(TEMP_NESTED_DIR_FULL_TREE); + + assert.ok(fs.existsSync(TEMP_NESTED_DIR_FULL_TREE)); + assert.doesNotThrow(() => tl.rmRF(path.resolve(`./${TEMP_NESTED_DIR_LEVEL_1}`))); + assert.ok(!fs.existsSync(`./${TEMP_NESTED_DIR_LEVEL_1}`)); + + done(); + }); + + it('Remove a read-only file inside temp readonly dir', (done) => { + const READONLY_DIR = path.join(TEMP_DIR, 'readonly'); + tl.mkdirP(READONLY_DIR); + fs.writeFileSync(path.join(READONLY_DIR, 'file'), 'test'); + fs.chmodSync(path.join(READONLY_DIR, 'file'), '0444'); + + assert.doesNotThrow(() => tl.rmRF(path.join(READONLY_DIR, 'file'))); + assert.ok(!fs.existsSync(path.join(READONLY_DIR, 'file'))); + assert.doesNotThrow(() => tl.rmRF(READONLY_DIR)); + + done(); + }); + + it('Remove of a tree containing read-only files (forced)', (done) => { + tl.mkdirP(path.join(TEMP_DIR, 'tree')); + fs.writeFileSync(path.join(TEMP_DIR, 'tree', 'file1'), 'test'); + fs.writeFileSync(path.join(TEMP_DIR, 'tree', 'file2'), 'test'); + fs.chmodSync(path.join(TEMP_DIR, 'tree', 'file1'), '0444'); + + assert.doesNotThrow(() => tl.rmRF(path.join(TEMP_DIR, 'tree'))); + assert.ok(!fs.existsSync(path.join(TEMP_DIR, 'tree'))); + + done(); + }); + + it('removal of a sub-tree containing read-only and hidden files - without glob', (done) => { + const TEMP_TREE4_DIR = path.join(TEMP_DIR, 'tree4'); + tl.mkdirP(path.join(TEMP_TREE4_DIR, 'subtree')); + tl.mkdirP(path.join(TEMP_TREE4_DIR, '.hidden')); + fs.writeFileSync(path.join(TEMP_TREE4_DIR, 'subtree', 'file'), 'test'); + fs.writeFileSync(path.join(TEMP_TREE4_DIR, '.hidden', 'file'), 'test'); + fs.writeFileSync(path.join(TEMP_TREE4_DIR, 'file'), 'test'); + fs.chmodSync(path.join(TEMP_TREE4_DIR, 'file'), '0444'); + fs.chmodSync(path.join(TEMP_TREE4_DIR, 'subtree', 'file'), '0444'); + fs.chmodSync(path.join(TEMP_TREE4_DIR, '.hidden', 'file'), '0444'); + + assert.doesNotThrow(() => tl.rmRF(path.join(TEMP_DIR, 'tree4'))); + assert.ok(!fs.existsSync(path.join(TEMP_DIR, 'tree4'))); + + done(); + }); + + it('Removing symbolic link to a directory', (done) => { + fs.mkdirSync(path.join(TEMP_DIR, 'rm', 'a_dir'), { recursive: true }); + fs.symlinkSync(path.join(TEMP_DIR, 'rm', 'a_dir'), path.join(TEMP_DIR, 'rm', 'link_to_a_dir'), 'dir'); + + assert.doesNotThrow(() => tl.rmRF(path.join(TEMP_DIR, 'rm', 'link_to_a_dir'))); + assert.ok(!fs.existsSync(path.join(TEMP_DIR, 'rm', 'link_to_a_dir'))); + assert.ok(fs.existsSync(path.join(TEMP_DIR, 'rm', 'a_dir'))); + + tl.rmRF(path.join(TEMP_DIR, 'rm')); + + done(); + }); + + it('Remove path with relative non-normalized structure', (done) => { + tl.mkdirP(TEMP_NESTED_DIR_FULL_TREE); + + assert.ok(fs.existsSync(TEMP_NESTED_DIR_FULL_TREE)); + assert.doesNotThrow(() => tl.rmRF(path.join(TEMP_DIR, 'a', '..', './a'))); + assert.ok(!fs.existsSync(path.join(TEMP_DIR, 'a'))); + + done(); + }); +}); \ No newline at end of file diff --git a/node/test/tsconfig.json b/node/test/tsconfig.json index cd084a92f..58d802d2b 100644 --- a/node/test/tsconfig.json +++ b/node/test/tsconfig.json @@ -7,28 +7,35 @@ "moduleResolution": "node" }, "files": [ + "cctests.ts", + "cd.ts", + "commandtests.ts", + "cp.ts", "dirtests.ts", + "disktests.ts", + "fakeModules/fakemodule1.ts", + "fakeModules/fakemodule2.ts", + "filtertests.ts", + "findmatchtests.ts", + "gethttpproxytests.ts", "inputtests.ts", "internalhelpertests.ts", - "commandtests.ts", - "resulttests.ts", - "disktests.ts", + "isuncpathtests.ts", "legacyfindfilestests.ts", - "vaulttests.ts", - "toolrunnertests.ts", - "toolrunnerTestsWithExecAsync.ts", - "cctests.ts", "loctests.ts", + "ls.ts", "matchtests.ts", - "filtertests.ts", - "findmatchtests.ts", + "mockertests.ts", "mocktests.ts", + "mv.ts", + "popd.ts", + "pushd.ts", + "resulttests.ts", "retrytests.ts", - "isuncpathtests.ts", - "gethttpproxytests.ts", - "mockertests.ts", - "fakeModules/fakemodule1.ts", - "fakeModules/fakemodule2.ts", - "taskissuecommandtests.ts" + "rm.ts", + "taskissuecommandtests.ts", + "toolrunnertests.ts", + "toolrunnerTestsWithExecAsync.ts", + "vaulttests.ts" ] } diff --git a/powershell/definitions/shelljs.d.ts b/powershell/definitions/shelljs.d.ts deleted file mode 100644 index 4a40fe541..000000000 --- a/powershell/definitions/shelljs.d.ts +++ /dev/null @@ -1,577 +0,0 @@ -// Type definitions for ShellJS v0.3.0 -// Project: http://shelljs.org -// Definitions by: Niklas Mollenhauer -// Definitions: https://github.com/borisyankov/DefinitelyTyped -// Ting update to match shelljs v0.5.3 12/7/2015 - -declare module "shelljs" -{ - import child = require("child_process"); - - /** - * Changes to directory dir for the duration of the script - * @param {string} dir Directory to change in. - */ - export function cd(dir: string): void; - - /** - * Returns the current directory. - * @return {string} The current directory. - */ - export function pwd(): string; - - /** - * Returns array of files in the given path, or in current directory if no path provided. - * @param {string[]} ...paths Paths to search. - * @return {string[]} An array of files in the given path(s). - */ - export function ls(...paths: string[]): string[]; - - /** - * Returns array of files in the given path, or in current directory if no path provided. - * @param {string} options Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..) - * @param {string[]} ...paths Paths to search. - * @return {string[]} An array of files in the given path(s). - */ - export function ls(options: string, ...paths: string[]): string[]; - - /** - * Returns array of files in the given path, or in current directory if no path provided. - * @param {string[]} paths Paths to search. - * @return {string[]} An array of files in the given path(s). - */ - export function ls(paths: string[]): string[]; - - /** - * Returns array of files in the given path, or in current directory if no path provided. - * @param {string} options Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..) - * @param {string[]} paths Paths to search. - * @return {string[]} An array of files in the given path(s). - */ - export function ls(options: string, paths: string[]): string[]; - - /** - * Returns array of all files (however deep) in the given paths. - * @param {string[]} ...path The path(s) to search. - * @return {string[]} An array of all files (however deep) in the given path(s). - */ - export function find(...path: string[]): string[]; - - /** - * Returns array of all files (however deep) in the given paths. - * @param {string[]} path The path(s) to search. - * @return {string[]} An array of all files (however deep) in the given path(s). - */ - export function find(path: string[]): string[]; - - /** - * Copies files. The wildcard * is accepted. - * @param {string} source The source. - * @param {string} dest The destination. - */ - export function cp(source: string, dest: string): void; - - /** - * Copies files. The wildcard * is accepted. - * @param {string[]} source The source. - * @param {string} dest The destination. - */ - export function cp(source: string[], dest: string): void; - - /** - * Copies files. The wildcard * is accepted. - * @param {string} options Available options: -f (force), -r, -R (recursive) - * @param {strin]} source The source. - * @param {string} dest The destination. - */ - export function cp(options: string, source: string, dest: string): void; - - /** - * Copies files. The wildcard * is accepted. - * @param {string} options Available options: -f (force), -r, -R (recursive) - * @param {string[]} source The source. - * @param {string} dest The destination. - */ - export function cp(options: string, source: string[], dest: string): void; - - /** - * Removes files. The wildcard * is accepted. - * @param {string[]} ...files Files to remove. - */ - export function rm(...files: string[]): void; - - /** - * Removes files. The wildcard * is accepted. - * @param {string[]} files Files to remove. - */ - export function rm(files: string[]): void; - - /** - * Removes files. The wildcard * is accepted. - * @param {string} options Available options: -f (force), -r, -R (recursive) - * @param {string[]} ...files Files to remove. - */ - export function rm(options: string, ...files: string[]): void; - - /** - * Removes files. The wildcard * is accepted. - * @param {string} options Available options: -f (force), -r, -R (recursive) - * @param {string[]} ...files Files to remove. - */ - export function rm(options: string, files: string[]): void; - - /** - * Moves files. The wildcard * is accepted. - * @param {string} source The source. - * @param {string} dest The destination. - */ - export function mv(source: string, dest: string): void; - - /** - * Moves files. The wildcard * is accepted. - * @param {string} options Available options: -f (force) - * @param {string} source The source. - * @param {string} dest The destination. - */ - export function mv(options: string, source: string, dest: string): void; - - - /** - * Moves files. The wildcard * is accepted. - * @param {string[]} source The source. - * @param {string} dest The destination. - */ - export function mv(source: string[], dest: string): void; - - /** - * Moves files. The wildcard * is accepted. - * @param {string} options Available options: -f (force) - * @param {string[]} source The source. - * @param {string} dest The destination. - */ - export function mv(options: string, source: string[], dest: string): void; - - /** - * Creates directories. - * @param {string[]} ...dir Directories to create. - */ - export function mkdir(...dir: string[]): void; - - /** - * Creates directories. - * @param {string[]} dir Directories to create. - */ - export function mkdir(dir: string[]): void; - - /** - * Creates directories. - * @param {string} options Available options: -p (full paths, will create intermediate dirs if necessary) - * @param {string[]} ...dir The directories to create. - */ - export function mkdir(options: string, ...dir: string[]): void; - - /** - * Creates directories. - * @param {string} options Available options: -p (full paths, will create intermediate dirs if necessary) - * @param {string[]} dir The directories to create. - */ - export function mkdir(options: string, dir: string[]): void; - - /** - * Evaluates expression using the available primaries and returns corresponding value. - * @param {string} option '-b': true if path is a block device; '-c': true if path is a character device; '-d': true if path is a directory; '-e': true if path exists; '-f': true if path is a regular file; '-L': true if path is a symboilc link; '-p': true if path is a pipe (FIFO); '-S': true if path is a socket - * @param {string} path The path. - * @return {boolean} See option parameter. - */ - export function test(option: string, path: string): boolean; - - /** - * Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). Wildcard * accepted. - * @param {string[]} ...files Files to use. - * @return {string} A string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). - */ - export function cat(...files: string[]): string; - - /** - * Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). Wildcard * accepted. - * @param {string[]} files Files to use. - * @return {string} A string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). - */ - export function cat(files: string[]): string; - - - // Does not work yet. - export interface String - { - /** - * Analogous to the redirection operator > in Unix, but works with JavaScript strings (such as those returned by cat, grep, etc). Like Unix redirections, to() will overwrite any existing file! - * @param {string} file The file to use. - */ - to(file: string): void; - - /** - * Analogous to the redirect-and-append operator >> in Unix, but works with JavaScript strings (such as those returned by cat, grep, etc). - * @param {string} file The file to append to. - */ - toEnd(file: string): void; - } - - /** - * Reads an input string from file and performs a JavaScript replace() on the input using the given search regex and replacement string or function. Returns the new string after replacement. - * @param {RegExp} searchRegex The regular expression to use for search. - * @param {string} replacement The replacement. - * @param {string} file The file to process. - * @return {string} The new string after replacement. - */ - export function sed(searchRegex: RegExp, replacement: string, file: string): string; - - /** - * Reads an input string from file and performs a JavaScript replace() on the input using the given search regex and replacement string or function. Returns the new string after replacement. - * @param {string} searchRegex The regular expression to use for search. - * @param {string} replacement The replacement. - * @param {string} file The file to process. - * @return {string} The new string after replacement. - */ - export function sed(searchRegex: string, replacement: string, file: string): string; - - /** - * Reads an input string from file and performs a JavaScript replace() on the input using the given search regex and replacement string or function. Returns the new string after replacement. - * @param {string} options Available options: -i (Replace contents of 'file' in-place. Note that no backups will be created!) - * @param {RegExp} searchRegex The regular expression to use for search. - * @param {string} replacement The replacement. - * @param {string} file The file to process. - * @return {string} The new string after replacement. - */ - export function sed(options: string, searchRegex: RegExp, replacement: string, file: string): string; - - /** - * Reads an input string from file and performs a JavaScript replace() on the input using the given search regex and replacement string or function. Returns the new string after replacement. - * @param {string} options Available options: -i (Replace contents of 'file' in-place. Note that no backups will be created!) - * @param {string} searchRegex The regular expression to use for search. - * @param {string} replacement The replacement. - * @param {string} file The file to process. - * @return {string} The new string after replacement. - */ - export function sed(options: string, searchRegex: string, replacement: string, file: string): string; - - /** - * Reads input string from given files and returns a string containing all lines of the file that match the given regex_filter. Wildcard * accepted. - * @param {RegExp} regex_filter The regular expression to use. - * @param {string[]} ...files The files to process. - * @return {string} Returns a string containing all lines of the file that match the given regex_filter. - */ - export function grep(regex_filter: RegExp, ...files: string[]): string; - - /** - * Reads input string from given files and returns a string containing all lines of the file that match the given regex_filter. Wildcard * accepted. - * @param {RegExp} regex_filter The regular expression to use. - * @param {string[]} ...files The files to process. - * @return {string} Returns a string containing all lines of the file that match the given regex_filter. - */ - export function grep(regex_filter: RegExp, files: string[]): string; - - /** - * Reads input string from given files and returns a string containing all lines of the file that match the given regex_filter. Wildcard * accepted. - * @param {string} options Available options: -v (Inverse the sense of the regex and print the lines not matching the criteria.) - * @param {string} regex_filter The regular expression to use. - * @param {string[]} ...files The files to process. - * @return {string} Returns a string containing all lines of the file that match the given regex_filter. - */ - export function grep(options: string, regex_filter: string, ...files: string[]): string; - - /** - * Reads input string from given files and returns a string containing all lines of the file that match the given regex_filter. Wildcard * accepted. - * @param {string} options Available options: -v (Inverse the sense of the regex and print the lines not matching the criteria.) - * @param {string} regex_filter The regular expression to use. - * @param {string[]} files The files to process. - * @return {string} Returns a string containing all lines of the file that match the given regex_filter. - */ - export function grep(options: string, regex_filter: string, files: string[]): string; - - /** - * Searches for command in the system's PATH. On Windows looks for .exe, .cmd, and .bat extensions. - * @param {string} command The command to search for. - * @return {string} Returns string containing the absolute path to the command. - */ - export function which(command: string): string; - - /** - * Prints string to stdout, and returns string with additional utility methods like .to(). - * @param {string[]} ...text The text to print. - * @return {string} Returns the string that was passed as argument. - */ - export function echo(...text: string[]): string; - - /** - * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. - * @param {"+N"} dir Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. - * @return {string[]} Returns an array of paths in the stack. - */ - export function pushd(dir: "+N"): string[]; - - /** - * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. - * @param {"-N"} dir Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. - * @return {string[]} Returns an array of paths in the stack. - */ - export function pushd(dir: "-N"): string[]; - - /** - * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. - * @param {string} dir Makes the current working directory be the top of the stack, and then executes the equivalent of cd dir. - * @return {string[]} Returns an array of paths in the stack. - */ - export function pushd(dir: string): string[]; - - /** - * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. - * @param {string} options Available options: -n (Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated) - * @param {"+N"} dir Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. - * @return {string[]} Returns an array of paths in the stack. - */ - export function pushd(options: string, dir: "+N"): string[]; - - /** - * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. - * @param {string} options Available options: -n (Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated) - * @param {"-N"} dir Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. - * @return {string[]} Returns an array of paths in the stack. - */ - export function pushd(options: string, dir: "-N"): string[]; - - /** - * Save the current directory on the top of the directory stack and then cd to dir. With no arguments, pushd exchanges the top two directories. Returns an array of paths in the stack. - * @param {string} options Available options: -n (Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated) - * @param {string} dir Makes the current working directory be the top of the stack, and then executes the equivalent of cd dir. - * @return {string[]} Returns an array of paths in the stack. - */ - export function pushd(options: string, dir: string): string[]; - - /** - * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. - * @return {string[]} Returns an array of paths in the stack. - */ - export function popd(): string[]; - - /** - * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. - * @param {"+N"} index Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. - * @return {string[]} Returns an array of paths in the stack. - */ - export function popd(index: "+N"): string[]; - - /** - * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. - * @param {"-N"} index Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. - * @return {string[]} Returns an array of paths in the stack. - */ - export function popd(index: "-N"): string[]; - - /** - * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. - * @param {string} index You can only use -N and +N. - * @return {string[]} Returns an array of paths in the stack. - */ - export function popd(index: string): string[]; - - /** - * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. - * @param {string} options Available options: -n (Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated) - * @param {"+N"} index Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. - * @return {string[]} Returns an array of paths in the stack. - */ - export function popd(options: string, index: "+N"): string[]; - - /** - * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. - * @param {string} options Available options: -n (Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated) - * @param {"-N"} index Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. - * @return {string[]} Returns an array of paths in the stack. - */ - export function popd(options: string, index: "-N"): string[]; - - /** - * When no arguments are given, popd removes the top directory from the stack and performs a cd to the new top directory. The elements are numbered from 0 starting at the first directory listed with dirs; i.e., popd is equivalent to popd +0. Returns an array of paths in the stack. - * @param {string} options Available options: -n (Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated) - * @param {string} index You can only use -N and +N. - * @return {string[]} Returns an array of paths in the stack. - */ - export function popd(options: string, index: string): string[]; - - /** - * Display the list of currently remembered directories. Returns an array of paths in the stack. - * @return {string[]} Returns an array of paths in the stack. - */ - export function dirs(): string[]; - - /** - * Clears the directory stack by deleting all of the elements. - * @param {string} options Available options: -c (Clears the directory stack by deleting all of the elements). - * @return {string[]} Returns an array of paths in the stack, or a single path if +N or -N was specified. - */ - export function dirs(options: string): string[]; - - /** - * Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified. - * @param {string} Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. - * @return {any} Returns an array of paths in the stack, or a single path if +N or -N was specified. - */ - export function dirs(index: "+N"): string; - - /** - * Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified. - * @param {string} Displays the Nth directory (counting from the right of the list if -N printed by dirs when invoked without options), starting with zero. - * @return {any} Returns an array of paths in the stack, or a single path if +N or -N was specified. - */ - export function dirs(index: "-N"): string; - - /** - * Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if +N or -N was specified. - * @param {string} Displays the Nth directory (counting from the left of the list if +N or counting from the right of the list if -N printed by dirs when invoked without options), starting with zero. - * @return {any} Returns an array of paths in the stack, or a single path if +N or -N was specified. - */ - export function dirs(index: string): string; - - /** - * Links source to dest. Use -f to force the link, should dest already exist. - * @param {string} source The source. - * @param {string} dest The destination. - */ - export function ln(source: string, dest: string): void; - - /** - * Links source to dest. Use -f to force the link, should dest already exist. - * @param {string} options Available options: s (symlink), f (force) - * @param {string} source The source. - * @param {string} dest The destination. - */ - export function ln(options: string, source: string, dest: string): void; - - /** - * Exits the current process with the given exit code. - * @param {number} code The exit code. - */ - export function exit(code: number): void; - - /** - * Object containing environment variables (both getter and setter). Shortcut to process.env. - */ - export var env: { [key: string]: string }; - - /** - * Executes the given command synchronously. - * @param {string} command The command to execute. - * @return {ExecOutputReturnValue} Returns an object containing the return code and output as string. - */ - export function exec(command: string): ExecOutputReturnValue; - /** - * Executes the given command synchronously. - * @param {string} command The command to execute. - * @param {ExecOptions} options Silence and synchronous options. - * @return {ExecOutputReturnValue | child.ChildProcess} Returns an object containing the return code and output as string, or if {async:true} was passed, a ChildProcess. - */ - export function exec(command: string, options: ExecOptions): ExecOutputReturnValue | child.ChildProcess; - /** - * Executes the given command synchronously. - * @param {string} command The command to execute. - * @param {ExecOptions} options Silence and synchronous options. - * @param {ExecCallback} callback Receives code and output asynchronously. - */ - export function exec(command: string, options: ExecOptions, callback: ExecCallback): child.ChildProcess; - /** - * Executes the given command synchronously. - * @param {string} command The command to execute. - * @param {ExecCallback} callback Receives code and output asynchronously. - */ - export function exec(command: string, callback: ExecCallback): child.ChildProcess; - - export interface ExecCallback { - (code: number, output: string): any; - } - - export interface ExecOptions { - silent?: boolean; - async?: boolean; - } - - export interface ExecOutputReturnValue - { - code: number; - output: string; - } - - /** - * Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: - * - In symbolic modes, 'a-r' and '-r' are identical. No consideration is given to the umask. - * - There is no "quiet" option since default behavior is to run silent. - * @param {number} octalMode The access mode. Octal. - * @param {string} file The file to use. - */ - export function chmod(octalMode: number, file: string): void; - - /** - * Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: - * - In symbolic modes, 'a-r' and '-r' are identical. No consideration is given to the umask. - * - There is no "quiet" option since default behavior is to run silent. - * @param {string} mode The access mode. Can be an octal string or a symbolic mode string. - * @param {string} file The file to use. - */ - export function chmod(mode: string, file: string): void; - - /** - * Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: - * - In symbolic modes, 'a-r' and '-r' are identical. No consideration is given to the umask. - * - There is no "quiet" option since default behavior is to run silent. - * @param {string} options Available options: -v (output a diagnostic for every file processed), -c (like verbose but report only when a change is made), -R (change files and directories recursively. - * @param {number} octalMode The access mode. Octal. - * @param {string} file The file to use. - */ - export function chmod(option: string, octalMode: number, file: string): void; - - /** - * Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: - * - In symbolic modes, 'a-r' and '-r' are identical. No consideration is given to the umask. - * - There is no "quiet" option since default behavior is to run silent. - * @param {string} options Available options: -v (output a diagnostic for every file processed), -c (like verbose but report only when a change is made), -R (change files and directories recursively. - * @param {string} mode The access mode. Can be an octal string or a symbolic mode string. - * @param {string} file The file to use. - */ - export function chmod(option: string, mode: string, file: string): void; - - // Non-Unix commands - - /** - * Searches and returns string containing a writeable, platform-dependent temporary directory. Follows Python's tempfile algorithm. - * @return {string} The temp file path. - */ - export function tempdir(): string; - - /** - * Tests if error occurred in the last command. - * @return {string} Returns null if no error occurred, otherwise returns string explaining the error - */ - export function error(): string; - - // Configuration - - interface ShellConfig - { - /** - * Suppresses all command output if true, except for echo() calls. Default is false. - * @type {boolean} - */ - silent: boolean; - - /** - * If true the script will die on errors. Default is false. - * @type {boolean} - */ - fatal: boolean; - } - - /** - * The shelljs configuration. - * @type {ShellConfig} - */ - export var config: ShellConfig; -}