From 0eb20603acf2831c7240e40c8bff3c4110c546ba Mon Sep 17 00:00:00 2001 From: b1ek Date: Tue, 21 Mar 2023 20:44:55 +1000 Subject: [PATCH] add rm command --- src/emulator/commands/index.js | 1 + src/emulator/commands/rm.js | 57 ++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 src/emulator/commands/rm.js diff --git a/src/emulator/commands/index.js b/src/emulator/commands/index.js index bbdff12..77a4689 100644 --- a/src/emulator/commands/index.js +++ b/src/emulator/commands/index.js @@ -12,6 +12,7 @@ let cmds = { 'zsh': require('./zsh'), 'ps': require('./ps'), 'clear': require('./clear'), + 'rm': require('./rm'), // alias l='ls -l' 'l': (a,t) => {require('./ls')([...a, '-l'], t)}, diff --git a/src/emulator/commands/rm.js b/src/emulator/commands/rm.js new file mode 100644 index 0000000..c6e913a --- /dev/null +++ b/src/emulator/commands/rm.js @@ -0,0 +1,57 @@ +const { Terminal } = require("xterm"); +const fs = require('../fs') + +/** + * + * @param {string[]} argv + * @param {Terminal} terminal + */ +module.exports = (argv, terminal) => { + if (argv.indexOf('--help') != -1) { + terminal.write( +`Usage: ${argv[0]} [...FILES] [OPTIONS] +Delete specified flies + -r -R --recursive Recursively delete all files in directory + -f --force Ignore nonexistant files and arguments +` + ); + return; + } + + let files = [...argv]; + files.shift(); + files = files.filter(file => !file.startsWith('-')); + + let args = [...argv].filter(arg => arg.startsWith('-')); + + // explode -abc => -a -b -c + args.forEach((arg, i) => { + if (arg.match(/-\w{2,}/)) { + args.splice(i, 1); + arg.substring(1).split('').forEach(part => args.push('-' + part)); + } + }) + + const recursive = args.indexOf('-r') != -1; + const force = args.indexOf('-f') != -1; + + files.forEach(file => { + try { + const stat = fs.lstatSync(file); + + if (stat.isDirectory()) { + if (!recursive) { + if (!force) + terminal.writeln(`${argv[0]}: cannot remove ${file}: is a directory`); + return -1; + } + fs.readdirSync(file).forEach(file => fs.unlinkSync(file)); + fs.rmdirSync(file); + } + fs.unlinkSync(file); + } catch (err) { + if (!force) + terminal.writeln(`${argv[0]}: cannot remove ${file}: ${err}`); + } + }); +} \ No newline at end of file