Skip to content

Instantly share code, notes, and snippets.

@k2052
Last active August 29, 2015 14:11
Show Gist options
  • Save k2052/436355abcc2de24e5a9e to your computer and use it in GitHub Desktop.
Save k2052/436355abcc2de24e5a9e to your computer and use it in GitHub Desktop.
Turns a Markdown list into a directory structure. Very messy and not nearly enough safety checks (there are none) but it works for my use case
  • animals
    • dogs
      • dog.rb
    • penguins
  • humans
  • cats.md
require 'fileutils'
dir_structure_file = ARGV[0]
tree = File.read(dir_structure_file)
tree = tree.split(/\n/)
tree_out = []
def put_out_tree tree
tree.each do |item|
put_out item
end
end
def nested? line
spaces = line[/\A */].size
spaces > 0
end
def put_out file_or_dir
if file_or_dir[:type] == :dir
FileUtils.mkdir(file_or_dir[:path])
put_out_tree file_or_dir[:children] if file_or_dir.key? :children
else
FileUtils.touch(file_or_dir[:path])
end
end
last = nil
tree.each_with_index do |line, lineno|
file_or_dir = line.gsub!(/-\s*/,"")
if !File.extname(file_or_dir).empty?
file_or_dir = {type: :file, raw_line: line, path: file_or_dir.gsub(/\s*/,"")}
else
file_or_dir = {type: :dir, raw_line: line, path: file_or_dir.gsub(/\s*/,""), children: []}
end
if nested? line
parent = last
parent = last[:parent] if parent[:raw_line][/\A */].size == line[/\A */].size # we are a sibling
file_or_dir[:path] = "#{parent[:path]}/#{file_or_dir[:path]}"
file_or_dir[:parent] = parent
parent[:children].push file_or_dir
else
tree_out.push file_or_dir
end
last = file_or_dir if file_or_dir[:type] == :dir
end
put_out_tree tree_out
$ ruby mdListToDir.rb example.md
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment