Skip to content

Instantly share code, notes, and snippets.

@apeiros
Created October 11, 2009 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apeiros/207646 to your computer and use it in GitHub Desktop.
Save apeiros/207646 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'optparse'
utf8 = true
colors = false
opts = OptionParser.new("", 24, ' ') do |opts|
opts.banner = "Usage: #{$PROGRAM_NAME} [options] [directory]"
opts.separator "Directory defaults to the current working directory."
opts.separator "Options:"
opts.on('-u', "--[no-]utf8", "use utf-8 for output (defaults to utf8)") { |use|
utf8 = use
}
opts.on('-c', "--[no-]colors", "color output (defaults to no-colors, colors require ANSI capable terminal)") { |use|
colors = use
}
opts.parse! ARGV
end
directory = ARGV.first || Dir.getwd
entries = Hash.new(0)
if utf8 then
straight = "\342\224\202\302\240\302\240"
node = "\342\224\234\342\224\200\302\240"
last_node = "\342\224\224\342\224\200\302\240"
nothing = "\302\240\302\240\302\240"
else
straight = "| "
node = "|-- "
last_node = "`-- "
nothing = " "
end
# Find all paths and sort them
glob = Dir.chdir(directory) { Dir['**/*'].sort }.sort_by { |path|
path.split(File::Separator) # change this to change sort order, e.g. could implement case insensitive sorting
}
# Prepare for drawing the proper lines at the right place
glob.each do |path| entries[File.dirname(path)] += 1 end
# Print the tree
puts File.expand_path(directory)
glob.each do |path|
dir,file = File.split(path)
entries[dir] -= 1
prefix = (entries[dir].zero? ? last_node : node).dup
until dir == '.'
dir = File.dirname(dir)
prefix[0,0] = entries[dir].zero? ? nothing : straight
end
# Color the output
if colors then
stat = File.stat(File.join(directory,path))
foreground = case
when stat.file? then nil
when stat.directory? then 34
when stat.symlink? then 32
else nil
end
background = nil
file = "\e[#{[foreground,background].compact.join(';')}m#{file}\e[0m"
end
puts "#{prefix}#{file}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment