Skip to content

Instantly share code, notes, and snippets.

@slhck
Created November 10, 2011 15:15
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 slhck/1355084 to your computer and use it in GitHub Desktop.
Save slhck/1355084 to your computer and use it in GitHub Desktop.
Create an XML representation of a directory tree
#!/usr/bin/env ruby
# xml-directory.rb
# Author: Werner Robitza
# Synopsis: A basic XML writer that parses the current directory and files
# Usage: xml-reader.rb <path> <output> [-a]
# <path> the directory path that should be analyzed
# <output> the output file
# -a output with XML attributes too instead of just using XML elements
require 'nokogiri'
require 'builder'
require 'pp'
require 'filemagic'
def show_usage
puts "Usage: xml-directory.rb <path> <output> [-a]"
puts "<path> the directory path that should be analyzed"
puts "<output> the output file"
puts "-a output with XML attributes too instead of just using XML elements"
exit
end
# Recursively build XML output, using XML elements or attributes
def build_directory(dir, xml)
Dir.glob("#{dir}/*") do |entry|
if File.directory? entry
if @use_attributes
xml.directory(attributes_for_entry(entry)) { build_directory(entry, xml) }
else
xml.directory {
elements_for_entry entry, xml
build_directory entry, xml
}
end
else
if @use_attributes
xml.file attributes_for_entry entry
else
xml.file { elements_for_entry entry, xml }
end
end
end
end
# Outputs common elements for a directory or file
def elements_for_entry(entry, xml)
xml.name File.basename(entry)
xml.size File.size(entry)
xml.ctime File.ctime(entry)
xml.mtime File.mtime(entry)
xml.owner File.stat(entry).uid
end
# Outputs common attributes for a directory or file
def attributes_for_entry(entry)
attributes = Hash.new
attributes[:name] = File.basename(entry)
attributes[:size] = File.size(entry)
attributes[:ctime] = File.ctime(entry)
attributes[:mtime] = File.mtime(entry)
attributes[:owner] = File.stat(entry).uid
attributes
end
# -----------------------------------------------------------------------------
show_usage if ARGV.size < 2 or ARGV.size > 3
@path, @output, @use_attributes = ARGV
xml = Builder::XmlMarkup.new(:indent => 2)
xml.instruct!
xml.listing { build_directory @path, xml }
File.open(@output, 'w') { |f| f.write(xml.target!) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment