Create a gist now

Instantly share code, notes, and snippets.

@123jimin /trash.js
Last active Dec 16, 2015

I have committed a lot of terrible mistakes involving rm, so I coded this script to prevent any further accidents.
#!/usr/bin/env node
var fs = require('fs');
var help = "Usage : trash [-lhx] files...\n\t-l : list trashcan\n\t-x : cancel (files: timestamp)\n\t-h : help";
var trash = process.env['HOME'] + "/.trash/";
(function(argv, log, error) {
argv = require('optimist').parse(argv);
if (typeof argv.l === 'string') {
argv._.unshift(argv.l);
argv.l = true;
}
if (typeof argv.x === 'string') {
argv._.unshift(argv.x);
argv.x = true;
}
if (!argv.l && (argv._.length == 0 || argv.h)) {
log(help);
return;
}
var timestamp, rmfolder;
if (argv.l) {
log(fs.readdirSync(trash).join(' '));
return;
}
if (argv.x) {
timestamp = argv._[0];
rmfolder = trash + timestamp + '/';
if (!fs.existsSync(rmfolder)) {
error("Error: %s does not exist!", rmfolder);
return;
}
fs.readdirSync(rmfolder).map(function(item) {
log("Recovering: %s", item);
fs.renameSync(rmfolder + item, item);
});
fs.rmdirSync(rmfolder);
return;
}
timestamp = Date.now().toString(36).toLowerCase();
rmfolder = trash + timestamp + '/';
log("Trash can ID: %s", timestamp);
fs.mkdirSync(rmfolder);
for (var i = 0; i < argv._.length; i++) {
fs.renameSync(argv._[i], rmfolder + argv._[i]);
}
}(process.argv.slice(2), console.log.bind(console), console.error.bind(console)));
@123jimin
Owner

PS. mkdir ~/.trash before use this.

@123jimin
Owner

PPS. I know that there are some trashcan utilities.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment