Add easy way to prune tree with `Walker`
@@ -5,14 +5,17 @@ class Walker {
private toAdd; // Directories to be added to the stack, unless pruned by the user
private stack; // Directories to be traversed later on
- init(root='.') {
+ init(root='.', prune=[]) {
this.prev = nil;
this.stack = [root];
this.toAdd = [];
+ this.prune = prune; // Public attribute; can be updated in between calls to `next`.
}
next() {
- this.stack.extend(this.toAdd.map(def (x) => Path.join(this.prev, x)));
+ var filtered = this.toAdd.filter(def (x) => !this.prune.contains(x));
+ var joined = filtered.map(def (x) => Path.join(this.prev, x));
+ this.stack.extend(joined);
if (!this.stack.len()) return nil;
@@ -34,7 +37,9 @@ class Walker {
}
-var walker = Walker();
+// Traverse the file system starting from the current directory. Prune every directory named 'docs'
+// from the tree.
+var walker = Walker('.', ['docs']);
while {
var tmp = walker.next();
@@ -44,6 +49,10 @@ while {
print([dirpath, dirnames, filenames]);
print();
+ // This is another way to prune the traversal, and can also be used to expand it if you create
+ // new directories in between calls to `walker.next`. It's more flexible than providing a
+ // `prune` list when the class is instantiated, but less convenient when the flexibility is not
+ // needed. As demonstrated here, both of these methods of pruning the search can be combined.
var prune = ['.git'];
for (var j = 0; j < prune.len(); j += 1)
if (dirnames.contains(prune[j]))
