Skip to content

Instantly share code, notes, and snippets.

@mflorida
Last active September 5, 2017 22:17
Show Gist options
  • Save mflorida/c57cec7ccf71b8bf02d00b9d93237796 to your computer and use it in GitHub Desktop.
Save mflorida/c57cec7ccf71b8bf02d00b9d93237796 to your computer and use it in GitHub Desktop.
Create JSON and/or YAML representation of a directory tree.
#!/usr/bin/env ruby
require 'yaml'
require 'json'
# arguments: start_dir output_filename file_format
# dir=./ name=file-list.json skip=.vagrant,.work
$args_obj = {}
ARGV.each do |arg|
arg_parts = arg.split('=')
$args_obj[arg_parts[0]] = arg_parts[1] || ''
end
$start_dir = $args_obj['dir'] || ARGV[0] || '.'
$dir_name = ($start_dir == '.' || $start_dir == './') ? Dir.pwd : $start_dir || Dir.pwd
$dir_name = File.basename($dir_name)
$file_name = $args_obj['name'] || $args_obj['file'] || ARGV[1] || 'files.*'
# regex to match files/folders to skip
$skip_regex = /^([.](DS_Store|_|git|vagrant|gradle|idea))/i
# if ther's a 'skip=*' argument, extract the names from a comma-separated list'
$skip_list = $args_obj['skip'] ? $args_obj['skip'].split(',') : ARGV[2] || []
def dir_hash (path, name=$dir_name)
_out = {}
_out[name] = _files = []
Dir.foreach(path) {|item|
unless ($skip_list.include?(item)) || $skip_regex.match(item) || item == '.' || item == '..'
full_path = File.join(path, item)
if File.directory?(full_path)
_obj = dir_hash(full_path, item)
_files.push(_obj)
else
_files.push(File.basename(item))
end
end
}
return _out
end
# CREATE THE FILE TREE OBJECT
$obj = dir_hash($start_dir, $dir_name)
# create JSON file for filename argument with '.json' or '.*' extension
$json_regex = /\.json|\.\*$/i
$json_file = $json_regex.match($file_name) ? "#{$file_name.split($json_regex)[0]}.json" : ''
# create YAML file for filename argument with '.yaml', '.yml' or '.*' extension
$yaml_regex = /\.yaml|\.yml|\.\*$/i
$yaml_name = $yaml_regex.match($file_name) ? $file_name.split($yaml_regex)[0] : ''
$yaml_file = ''
if $yaml_name != ''
# preserve '.yaml' or '.yml' file extension ('.yaml' for '.*')
$yaml_ext = /\.yaml|\.\*$/i.match($file_name) ? 'yaml' : 'yml'
$yaml_file = "#{$yaml_name}.#{$yaml_ext}"
end
# JSON output
if $json_file != ''
File.open($json_file, 'wb') {|file|
file.truncate(0)
# file.puts $obj.to_json
file.puts JSON.pretty_generate($obj, { indent: ' ' })
}
end
# YAML output
if $yaml_file != ''
File.open($yaml_file, 'wb') {|file|
file.truncate(0)
file.puts $obj.to_yaml
}
end
# puts "#{$obj}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment