August 28, 2008
print_dir.pl

I needed to print out an ASCII representation of a directory structure.

I'm sure there is probably some simple built in unix command line tool that does this automatically, but what fun would that be?

Here is the result:

#!/usr/bin/perl
use warnings;
use strict;
use Tree::Simple;
use Tree::Simple::Visitor::LoadDirectoryTree;
use Tree::Simple::View::ASCII;
use Cwd;

my $dir = shift(@ARGV) || cwd();
if (!-d $dir) {
die "$dir is not a directory, smart ass.";
}

# create a Tree::Simple object whose
# node is path to a directory
my $tree = Tree::Simple->new($dir);
my $visitor = Tree::Simple::Visitor::LoadDirectoryTree->new();

# set the directory sorting style
$visitor->setSortStyle( $visitor->SORT_FILES_FIRST );

# create node filter to filter
# out certain files and directories
$visitor->setNodeFilter(
sub {
my ($item) = @_;
return 0 if ($item =~ /CVS|svn/ || ($item =~ /^.*/ && -f $item));
return 1;
}
);

# pass the visitor to a Tree::Simple object
$tree->accept($visitor);

my $tree_view = Tree::Simple::View::ASCII->new($tree);
$tree_view->includeTrunk(1);
print $tree_view->expandAll();

exit(0);


Posted by ed at 11:51 AM