Skip to content

Instantly share code, notes, and snippets.

@michaelcinquin
Last active January 31, 2020 19:37
Show Gist options
  • Save michaelcinquin/a00e16355f18441d3936e90d26b74bdd to your computer and use it in GitHub Desktop.
Save michaelcinquin/a00e16355f18441d3936e90d26b74bdd to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# encoding: utf-8
#
require 'rubygems'
require 'rexml/document'
require 'nokogiri'
require 'cobravsmongoose'
require 'json'
#adapated from code provided by Shailendra Kamath (shailendrakamath) on
#https://www.ruby-forum.com/topic/159008
class DirectoryStructure
@@excludes = ["..","."]
@@doc = REXML::Document.new %{ <?xml version="1.0" encoding="UTF-8" ?> }
def self.traverse_directory(root_path)
@root_path=root_path
#traverse initial directory structure
folder = @@doc.add_element( 'rootfs',{'id' => root_path} )
#call loop_path with root_path and parent_node
loop_path(root_path,folder)
#create xml file
xml = Nokogiri::XML( @@doc.to_s ) do |config| #FIXME, use REXML or Nokogir, not both
config.noblanks
end
return xml
end
def self.loop_path(path,parent_node)
dir_entries= Dir.entries(path)
# don't need '.','..'
dir_entries = dir_entries-['.','..']
dir_entries.each do | entry |
fullpath=path+"/"+entry
shortpath=path.sub(@root_path,"")+"/"+entry
# check if directory or file
if File.directory?(fullpath)
#Folders Loop -------------------------------------------------
#Gets the directories of the current node.
#It changes for each recursive call
folder = parent_node.add_element( 'folder' ,{ 'label' =>entry,
'mtime' => File.mtime(fullpath),
'size' => File.size(fullpath),
'path' => shortpath
} )
loop_path( fullpath, folder )
else
#Files Loop ------------------------------------------------------
file = parent_node.add_element( 'file' ,{ 'label' =>entry,
'mtime' => File.mtime(fullpath),
'size' => File.size(fullpath),
'path' => shortpath
} )
end
end
end
end
xml=DirectoryStructure.traverse_directory("Downloads/pydio-core-6.4.1/conf")
#as suggested by http://stackoverflow.com/a/4819763
puts CobraVsMongoose.xml_to_hash(xml).to_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment