-
-
Save sinisterchipmunk/925102 to your computer and use it in GitHub Desktop.
I found myself having to construct a series of near-identical directory structures, and wanted a quick visualization of their contents. Was too lazy to open a file manager, and was happy for the excuse to code some Ruby. This was the result.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
TAB_STOP = 2 | |
$directories_only = false | |
$use_color = true | |
class Tree | |
attr_reader :word, :branches | |
def initialize(word = '/') | |
@word = word | |
@branches = {} | |
end | |
def branch(word) | |
branches[word] ||= Tree.new(word) | |
end | |
def to_s(indent = 0) | |
lines = [] | |
lines << (" "*TAB_STOP*indent) + word | |
branches.each do |name, branch| | |
lines << branch.to_s(indent+1) | |
end | |
lines.join "\n" | |
end | |
end | |
def help | |
puts "Usage: tree [-d]" | |
puts "\t d : list directories only" | |
puts "\t c : disable color" | |
exit | |
end | |
help if ARGV.include? "--help" | |
ARGV.each do |arg| | |
if arg[0] == ?- | |
arg.bytes.each do |opt| | |
case opt | |
when ?d then $directories_only = true | |
when ?c then $use_color = false | |
when ?h then help | |
when ?- then ; | |
else raise "Unrecognized option: "+opt.chr | |
end | |
end | |
end | |
end | |
def blue(str) | |
$use_color ? "\e[0;34m#{str}\e[0;0m" : str | |
end | |
base = Dir.pwd | |
tree = Tree.new(blue(File.basename(base)+"/")) | |
Dir[File.join(Dir.pwd, "**", "*")].each do |fi| | |
next if $directories_only && !(File.directory? fi) | |
relative = fi.gsub(/^#{Regexp::escape File.join(base, '')}/, '') | |
nest = relative.split(/\//) | |
trunk = tree | |
nest.each_with_index do |word, i| | |
if i != nest.length-1 || File.directory?(fi) | |
word = blue(word + "/") | |
end | |
trunk = trunk.branch word | |
end | |
end | |
puts tree |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment