From e5fdb1ffe414ad14d71bc2b4a399a8c938dbb491 Mon Sep 17 00:00:00 2001 From: Ivan Duplenskikh <115665590+ivanduplenskikh@users.noreply.github.com> Date: Tue, 24 Dec 2024 15:30:33 +0100 Subject: [PATCH] Replace all methods of shelljs module --- node/package-lock.json | 2 +- node/package.json | 2 +- node/task.ts | 351 +++++++++++++---- node/test/cd.ts | 113 ++++++ node/test/cp.ts | 125 ++++++ node/test/ls.ts | 254 ++++++++++++ node/test/mv.ts | 112 ++++++ node/test/popd.ts | 123 ++++++ node/test/pushd.ts | 301 +++++++++++++++ node/test/rm.ts | 117 ++++++ node/test/tsconfig.json | 7 + powershell/definitions/shelljs.d.ts | 577 ---------------------------- 12 files changed, 1425 insertions(+), 659 deletions(-) create mode 100644 node/test/cd.ts create mode 100644 node/test/cp.ts create mode 100644 node/test/ls.ts create mode 100644 node/test/mv.ts create mode 100644 node/test/popd.ts create mode 100644 node/test/pushd.ts create mode 100644 node/test/rm.ts delete mode 100644 powershell/definitions/shelljs.d.ts 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..d41f0bd7d 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'); @@ -681,24 +680,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 +688,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); } @@ -800,31 +781,112 @@ export const checkPath = im._checkPath; * @returns void */ export function cd(path: string): void { - if (path) { - shell.cd(path); - _checkShell('cd'); + if (path === '-') { + if (!process.env.OLDPWD) { + throw new Error(`Failed cd: could not find previous directory`); + } else { + path = process.env.OLDPWD; + } + } + + if (path === '~') { + path = os.homedir(); + } + + if (!fs.existsSync(path)) { + throw new Error(`Failed cd: no such file or directory: ${path}`) + } + + if (!fs.statSync(path).isDirectory()) { + throw new Error(`Failed cd: not a directory: ${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 + * @param 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(`Failed pushd: no other directory`); + } + } 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(`Failed pushd: no such file or directory: ${_path}`); + } + + throw error; + } + dirStack.splice(0, dirStack.length, ...dirs); + return getActualStack(); } /** * Change working directory back to previously pushed directory * + * @param 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(`Failed popd: directory stack empty`); + } + + 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(); } /** @@ -917,49 +979,158 @@ export const which = im._which; * @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(optionsOrPaths?: string | string[], ...paths: string[]): string[] { + try { + let isRecursive = false; + let includeHidden = false; + let handleAsOptions = false; + + if (typeof optionsOrPaths == 'string' && optionsOrPaths.includes('-')) { + isRecursive = optionsOrPaths.includes('R'); + includeHidden = optionsOrPaths.includes('A'); + handleAsOptions = isRecursive || includeHidden; + } + + if (paths === undefined || paths.length === 0) { + if (Array.isArray(optionsOrPaths)) { + paths = optionsOrPaths as string[]; + } else if (optionsOrPaths && !handleAsOptions) { + paths = [optionsOrPaths]; + } else { + paths = []; + } + } + + if (paths.length === 0) { + paths.push(path.resolve('.')); + } + + const preparedPaths: string[] = []; + + 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(`Failed ls: ${error}`); + } else { + throw new Error(loc('LIB_OperationFailed', 'ls', error)); + } + } +} + +function retryer(func: Function, retryCount: number = 0, continueOnError: boolean = false) { + while (retryCount >= 0) { + try { + return func(); + } catch (error) { + if (!continueOnError || error.code === "ENOENT") { + throw error; + } + + console.log(loc('LIB_CopyFileFailed', retryCount)); + retryCount--; + + if (retryCount < 0) { + warning(error, IssueSource.TaskInternal); + break; + } + } } } /** * 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} sourceOrOptions - Either the source path or an option string '-r', '-f' or '-rf' for recursive and force. + * @param {string} destinationOrSource - The destination path or the source path. + * @param {string} [optionsOrDestination] - Options string or the destination path. + * @param {boolean} [continueOnError] - 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. */ -export function cp(source: string, dest: string, options?: string, continueOnError?: boolean, retryCount: number = 0): void { - while (retryCount >= 0) { +export function cp(sourceOrOptions: string, destinationOrSource: string, optionsOrDestination?: string, continueOnError?: boolean, retryCount: number = 0): void { + retryer(() => { + const isOptions = sourceOrOptions.startsWith('-') && sourceOrOptions.length > 1; + let recursive = false; + let force = true; + let source = sourceOrOptions; + let destination = destinationOrSource; + + if (isOptions) { + sourceOrOptions = sourceOrOptions.toLowerCase(); + recursive = sourceOrOptions.includes('r'); + force = !sourceOrOptions.includes('n'); + source = destinationOrSource; + destination = optionsOrDestination!; + } + + if (!fs.existsSync(destination) && !force) { + throw new Error(`ENOENT: no such file or directory: ${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) { + if (error.code === 'ENOENT') { + throw new Error(error); + } else { + throw new Error(loc('LIB_OperationFailed', 'cp', error)); } } - } + }, retryCount, continueOnError); } /** @@ -971,14 +1142,24 @@ export function cp(source: string, dest: string, options?: string, continueOnErr * @param continueOnError optional. whether to continue on error */ export function mv(source: string, dest: string, options?: string, continueOnError?: boolean): void { - if (options) { - shell.mv(options, source, dest); - } - else { - shell.mv(source, dest); - } + try { + const isForce = !options?.toLowerCase()?.includes('-n') && options?.toLowerCase()?.includes('-f'); + const destExists = fs.existsSync(dest); + + if (!fs.existsSync(source)) { + throw new Error(loc('LIB_PathNotFound', source)); + } + + if (destExists && !isForce) { + throw new Error(loc('LIB_PathNotFound', dest)); + } - _checkShell('mv', continueOnError); + fs.renameSync(source, dest); + } catch (error) { + debug('mv failed'); + var errMsg = loc('LIB_OperationFailed', 'mv', error); + debug(errMsg); + } } /** @@ -1441,8 +1622,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 +1633,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 +1669,9 @@ 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)); } @@ -1492,7 +1680,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 +1986,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..3f5e54e36 --- /dev/null +++ b/node/test/cd.ts @@ -0,0 +1,113 @@ +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', () => { + let TEMP_DIR_PATH: string; + const TEMP_DIR_1 = path.resolve(DIRNAME, 'temp1'); + const TEMP_DIR_2 = path.resolve(DIRNAME, 'temp2'); + const TEMP_FILE_1 = path.resolve(TEMP_DIR_1, 'file1'); + + before((done) => { + fs.mkdirSync(TEMP_DIR_1); + fs.mkdirSync(TEMP_DIR_2); + fs.writeFileSync(TEMP_FILE_1, 'file1'); + + try { + testutil.initialize(); + } catch (error) { + assert.fail(`Failed to load tl lib: ${error.message}`); + } + + done(); + }); + + beforeEach((done) => { + TEMP_DIR_PATH = fs.mkdtempSync('temp_test_'); + process.chdir(DIRNAME); + + if (!fs.existsSync(TEMP_DIR_PATH)) { + fs.mkdirSync(TEMP_DIR_PATH); + } + + done(); + }); + + afterEach((done) => { + process.chdir(DIRNAME); + if (fs.existsSync(TEMP_DIR_PATH)) { + fs.rmdirSync(TEMP_DIR_PATH, { recursive: true }); + } + + done(); + }); + + after((done) => { + fs.rmdirSync(TEMP_DIR_1, { recursive: true }); + fs.rmdirSync(TEMP_DIR_2, { recursive: true }); + done(); + }); + + it('Check change directory for a folder that does not exist', (done) => { + assert.ok(!fs.existsSync('/thisfolderdoesnotexist')); + assert.throws(() => tl.cd('/thisfolderdoesnotexist'), { message: "Failed cd: no such file or directory: /thisfolderdoesnotexist" }); + done(); + }); + + it('Change directory to a file path', (done) => { + const filePath = path.resolve(DIRNAME, 'scripts', 'match-input-exe.cs'); + assert.ok(fs.existsSync(filePath)); + assert.throws(() => tl.cd(filePath), { message: `Failed cd: not a directory: ${filePath}` }); + done(); + }); + + it('There is no previous directory', (done) => { + assert.throws(() => tl.cd('-'), { message: 'Failed cd: could not find previous directory' }); + done(); + }); + + it('Change direcotry to a relative path', (done) => { + tl.cd(TEMP_DIR_PATH); + assert.equal(path.basename(TEMP_DIR_PATH), TEMP_DIR_PATH); + done(); + }); + + it('Change directory to an absolute 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) => { + assert.ok(!fs.existsSync(path.resolve(TEMP_DIR_PATH, "file1"))); + tl.cd(TEMP_DIR_1); + tl.cp(TEMP_FILE_1, path.resolve("..", TEMP_DIR_PATH)); + tl.cd(path.resolve("..", TEMP_DIR_PATH)); + assert.ok(fs.existsSync('file1')); + 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..4d122ab4f --- /dev/null +++ b/node/test/cp.ts @@ -0,0 +1,125 @@ +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) => { + fs.rmSync(TEMP_DIR_1, { recursive: true}); + fs.rmSync(TEMP_DIR_2, { recursive: true}); + 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'); + 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..ba7627d9d --- /dev/null +++ b/node/test/ls.ts @@ -0,0 +1,254 @@ +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: /^Failed ls: Error: 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', (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('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..22ce7c9b5 --- /dev/null +++ b/node/test/mv.ts @@ -0,0 +1,112 @@ +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 + '/'); + 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) => { + fs.rmSync(TEMP_DIR, { recursive: true }); + done(); + }); + + it('Provide invalid arguments', (done) => { + // @ts-ignore + assert.doesNotThrow(() => tl.mv()); + // @ts-ignore + assert.doesNotThrow(() => tl.mv('file1')); + // @ts-ignore + assert.doesNotThrow(() => tl.mv('-f')); + done(); + }); + + it('Provide an unsupported option argument', (done) => { + assert.ok(fs.existsSync('file1')); + assert.doesNotThrow(() => tl.mv('file1', 'file1', '-Z')); + assert.ok(fs.existsSync('file1')); + done(); + }); + + it('Provide a source that does not exist', (done) => { + assert.doesNotThrow(() => tl.mv('pathdoesntexist1', '..')); + assert.ok(!fs.existsSync('../pathdoesntexist2')); + done(); + }); + + it('Provide a source that does not exist', (done) => { + assert.doesNotThrow(() => tl.mv('pathdoesntexist1', 'pathdoesntexist2', '..')); + assert.ok(!fs.existsSync('../pathdoesntexist1')); + assert.ok(!fs.existsSync('../pathdoesntexist2')); + done(); + }); + + it('Provide a destination that already exist', (done) => { + assert.ok(fs.existsSync('file1')); + assert.ok(fs.existsSync('file2')); + assert.doesNotThrow(() => tl.mv('file1', 'file2')); + assert.ok(fs.existsSync('file1')); + assert.ok(fs.existsSync('file2')); + done(); + }); + + it('Provide a wildcard when dest is file', (done) => { + assert.doesNotThrow(() => tl.mv('file*', '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('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..51e3534fd --- /dev/null +++ b/node/test/popd.ts @@ -0,0 +1,123 @@ +import fs = require('node:fs'); +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('test_pushd', 'nested', 'dir'); + + before(() => { + fs.mkdirSync(path.resolve(DIRNAME, TEMP_DIR_PATH, 'a'), { recursive: true }); + fs.mkdirSync(path.resolve(DIRNAME, TEMP_DIR_PATH, 'b', 'c'), { recursive: true }); + }); + + beforeEach(() => { + reset(); + }); + + + after(() => { + reset(); + fs.rmSync(path.resolve(DIRNAME, TEMP_DIR_PATH), { recursive: true }); + }); + + 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(DIRNAME, 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(DIRNAME, 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(DIRNAME, 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: 'Failed popd: directory stack 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(DIRNAME, TEMP_DIR_PATH)); + assert.ok(process.cwd(), trail[0]); + assert.throws(() => tl.popd(), { message: 'Failed popd: directory stack 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..ca40fef6f --- /dev/null +++ b/node/test/pushd.ts @@ -0,0 +1,301 @@ +import fs = require('node:fs'); +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(() => { + fs.mkdirSync(path.resolve(TEMP_DIR_PATH, 'a'), { recursive: true }); + fs.mkdirSync(path.resolve(TEMP_DIR_PATH, 'b', 'c'), { recursive: true }); + }); + + beforeEach(() => { + reset(); + }); + + after(() => { + reset(); + fs.rmSync(path.resolve(TEMP_DIR_PATH), { recursive: true }); + }); + + 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: /^Failed pushd: no such file or directory:/ }); + 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: 'Failed pushd: no other directory' }); + 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..997999e4a --- /dev/null +++ b/node/test/rm.ts @@ -0,0 +1,117 @@ +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 + '/'); + 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) => { + fs.rmSync(TEMP_DIR, { recursive: true }); + done(); + }); + + it('Invalid arguments', (done) => { + // @ts-ignore + assert.throws(() => tl.rmRF(), { message: 'Failed rmRF: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined' }); + 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'))); + fs.rmSync(path.join(TEMP_DIR, 'rm'), { recursive: true }); + 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..31131f42e 100644 --- a/node/test/tsconfig.json +++ b/node/test/tsconfig.json @@ -7,6 +7,13 @@ "moduleResolution": "node" }, "files": [ + "mv.ts", + "ls.ts", + "cp.ts", + "rm.ts", + "cd.ts", + "popd.ts", + "pushd.ts", "dirtests.ts", "inputtests.ts", "internalhelpertests.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; -}