Skip to content

Instantly share code, notes, and snippets.

@agius
Created August 20, 2013 04:53
Show Gist options
  • Select an option

  • Save agius/6277233 to your computer and use it in GitHub Desktop.

Select an option

Save agius/6277233 to your computer and use it in GitHub Desktop.
Recursively browse directory and convert all .haml files to .erb via Herbalizer (https://github.com/danchoi/herbalizer)
#!/usr/bin/env ruby
require 'open3'
# things herbalizer hates:
# nested hashes: %div{data: {href: src }} -> %div{data: Hash[href: src] }
# comments in the first line
# blank first line
# ruby-style interpolation: Message to #{person} -> Message to \ = person
# ternary operators inside blocks: %div{href: one ? two : three } -> put on separate line
@failures = []
def convert_dir(path)
dir = Dir.new(path)
dir.each do |f|
next if f == '.' || f == '..'
convert_dir(File.join(dir.path, f)) and next if File.ftype(File.join(dir.path, f)) == "directory"
next unless f =~ /\.haml$/
filename = File.join(dir.path, f)
dest = filename.gsub(/haml/, 'erb')
stdout_str, stderr_str, status = Open3.capture3("herbalizer #{filename}")
if stdout_str =~ /expecting new-line/
File.open(filename, "a") {|f| f.write("\n") }
stdout_str, stderr_str, status = Open3.capture3("herbalizer #{filename}")
end
if status == 0 && !(stdout_str =~ /\(line \d+, column \d+\):/)
$stderr.puts "Writing #{filename[(@dir_path.length)..-1].gsub(/haml/, 'erb')}: #{stdout_str[0..20]}"
File.open(dest, 'w') {|f| f.write(stdout_str) }
`rm #{filename}` if File.exists?(dest)
else
fname = filename[(@dir_path.length)..-1]
@failures << "#{fname}: #{stdout_str.gsub(/\s+/, ' ')}"
end
end
end
if ARGV.count == 0
puts "Usage: hamlconvert.rb PATH"
exit(1)
end
@dir_path = ARGV.first
convert_dir(@dir_path)
if @failures.count > 0
puts "Failed on the following files:"
puts @failures.join("\n")
else
puts "Success!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment