All files / src/commands rm.js

100% Statements 28/28
100% Branches 12/12
100% Functions 2/2
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57        1x 1x 1x 1x 1x 1x   1x         1x 1x   1x         8x 8x   8x 1x     7x 7x   7x 1x     6x 1x     5x       5x 1x         4x        
/**
 * Removes a directory or a file
 * Usage: rm /existingDir
 */
import parseOptions from 'parser/option-parser';
import * as FileOp from 'fs/operations-with-permissions/file-operations';
import * as DirOp from 'fs/operations-with-permissions/directory-operations';
import * as OutputFactory from 'emulator-output/output-factory';
import { resolvePath } from 'emulator-state/util';
import { makeError, fsErrorType } from 'fs/fs-error';
 
export const optDef = {
  '--no-preserve-root, --noPreserveRoot': '',
  '-r, --recursive': ''
};
 
const makeNoPathErrorOutput = () => {
  const noSuchFileOrDirError = makeError(fsErrorType.NO_SUCH_FILE_OR_DIRECTORY);
 
  return {
    output: OutputFactory.makeErrorOutput(noSuchFileOrDirError)
  };
};
 
export default (state, commandOptions) => {
  const {argv, options} = parseOptions(commandOptions, optDef);
 
  if (argv.length === 0) {
    return {}; // do nothing if no arguments are given
  }
 
  const deletionPath = resolvePath(state, argv[0]);
  const fs = state.getFileSystem();
 
  if (deletionPath === '/' && options.noPreserveRoot !== true) {
    return {}; // do nothing as cannot safely delete the root
  }
 
  if (!fs.has(deletionPath)) {
    return makeNoPathErrorOutput();
  }
 
  const {fs: deletedPathFS, err} = options.recursive === true ?
    DirOp.deleteDirectory(fs, deletionPath, true) :
    FileOp.deleteFile(fs, deletionPath);
 
  if (err) {
    return {
      output: OutputFactory.makeErrorOutput(err)
    };
  }
 
  return {
    state: state.setFileSystem(deletedPathFS)
  };
};