export function rmRF()

in node/task.ts [1235:1307]


export function rmRF(inputPath: string): void {
    debug('rm -rf ' + inputPath);

    if (getPlatform() == Platform.Windows) {
        // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another
        // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del.
        try {
            if (fs.statSync(inputPath).isDirectory()) {
                debug('removing directory ' + inputPath);
                childProcess.execSync(`rd /s /q "${inputPath}"`);
            }
            else {
                debug('removing file ' + inputPath);
                childProcess.execSync(`del /f /a "${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') {
                throw new Error(loc('LIB_OperationFailed', 'rmRF', err.message));
            }
        }

        // Shelling out fails to remove a symlink folder with missing source, this unlink catches that
        try {
            fs.unlinkSync(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') {
                throw new Error(loc('LIB_OperationFailed', 'rmRF', err.message));
            }
        }
    }
    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 you try to delete a file that doesn't exist, desired result is achieved
            // other errors are valid
            if (err.code == 'ENOENT') {
                return;
            }

            throw new Error(loc('LIB_OperationFailed', 'rmRF', err.message));
        }

        if (lstats.isDirectory()) {
            debug('removing directory');
            shell.rm('-rf', inputPath);
            let errMsg: string = shell.error();
            if (errMsg) {
                throw new Error(loc('LIB_OperationFailed', 'rmRF', errMsg));
            }

            return;
        }

        debug('removing file');
        try {
            fs.unlinkSync(inputPath);
        }
        catch (err) {
            throw new Error(loc('LIB_OperationFailed', 'rmRF', err.message));
        }
    }
}