1 var assert = require('assert')
2 var dirname = require('path').dirname
3 var resolve = require('path').resolve
4 var isInside = require('path-is-inside')
6 var rimraf = require('rimraf')
7 var lstat = require('graceful-fs').lstat
8 var readdir = require('graceful-fs').readdir
9 var rmdir = require('graceful-fs').rmdir
10 var unlink = require('graceful-fs').unlink
12 module.exports = vacuum
14 function vacuum (leaf, options, cb) {
15 assert(typeof leaf === 'string', 'must pass in path to remove')
16 assert(typeof cb === 'function', 'must pass in callback')
18 if (!options) options = {}
19 assert(typeof options === 'object', 'options must be an object')
21 var log = options.log ? options.log : function () {}
23 leaf = leaf && resolve(leaf)
24 var base = options.base && resolve(options.base)
25 if (base && !isInside(leaf, base)) {
26 return cb(new Error(leaf + ' is not a child of ' + base))
29 lstat(leaf, function (error, stat) {
31 if (error.code === 'ENOENT') return cb(null)
37 if (!(stat && (stat.isDirectory() || stat.isSymbolicLink() || stat.isFile()))) {
38 log(leaf, 'is not a directory, file, or link')
39 return cb(new Error(leaf + ' is not a directory, file, or link'))
44 rimraf(leaf, function (error) {
45 if (error) return cb(error)
49 } else if (!stat.isDirectory()) {
51 unlink(leaf, function (error) {
52 if (error) return cb(error)
61 function next (branch) {
62 branch = branch && resolve(branch)
63 // either we've reached the base or we've reached the root
64 if ((base && branch === base) || branch === dirname(branch)) {
65 log('finished vacuuming up to', branch)
69 readdir(branch, function (error, files) {
71 if (error.code === 'ENOENT') return cb(null)
73 log('unable to check directory', branch, 'due to', error.message)
77 if (files.length > 0) {
78 log('quitting because other entries in', branch)
82 log('removing', branch)
83 lstat(branch, function (error, stat) {
85 if (error.code === 'ENOENT') return cb(null)
87 log('unable to lstat', branch, 'due to', error.message)
91 var remove = stat.isDirectory() ? rmdir : unlink
92 remove(branch, function (error) {
94 if (error.code === 'ENOENT') {
95 log('quitting because lost the race to remove', branch)
98 if (error.code === 'ENOTEMPTY' || error.code === 'EEXIST') {
99 log('quitting because new (racy) entries in', branch)
103 log('unable to remove', branch, 'due to', error.message)
107 next(dirname(branch))