Skip to content

Instantly share code, notes, and snippets.

@mrb
Created October 21, 2010 04:33
Show Gist options
  • Save mrb/637939 to your computer and use it in GitHub Desktop.
Save mrb/637939 to your computer and use it in GitHub Desktop.
Batch publish markdown files as HTML
#! /usr/bin/env ruby
# Given a directory with several chapter subdirectories each containing a markdown file
# And a header and footer file in a directory called 00-shared,
# When I run ./publish -p html
# I should get individual html files from the markdown
# And I should get a book.html file with everything compiled together
# Example layout (cribbed from github.com/progit/progit):
#
# 00-shared
# \--- header.html
# \--- footer.html
# 01-chapter1
# \--- 01-chapter1.markdown
# 02-chapter2
# \--- 01-chapter2.markdown
require 'rubygems'
require 'clap'
FORMATS = ["html"]
if ARGV.empty?
puts "usage: [-p format]"
end
class Publish
HEADER = "00-shared/header.html"
FOOTER = "00-shared/footer.html"
CHAPTER_FILES = Dir.glob("*").collect{|g|
next if File.file?(g)
Dir.foreach(g).collect{|i_g|
next if i_g.match(/markdown/).nil?
"#{g}/#{i_g}"
}
}.flatten!.compact!
CHAPTER_HTML = CHAPTER_FILES.collect{|f| f.gsub('markdown','html')}
def self.publish(format)
puts "Cleaning old files...\n"
clean
puts "Converting individual chapters....\n\n"
convert_chapters
if format == "html"
puts "\nGenerating HTML Book"
File.delete('book.html') if File.exists?('book.html')
CHAPTER_HTML.collect{|f|
puts "Collecting #{f}\n"
system <<-HTML
cat #{HEADER} >> book.html && cat #{f} >> book.html && cat #{FOOTER} >> book.html
HTML
}
end
end
def self.convert_chapters
CHAPTER_FILES.each do |chapter_file|
puts "Converting #{chapter_file}\n"
chapter_html = chapter_file.gsub('markdown','html')
system <<-MARKITDOWN
markdown #{chapter_file} > #{chapter_html}
MARKITDOWN
end
end
def self.clean
CHAPTER_FILES.each{|f| File.delete(f.gsub('markdown','html'))}
end
end
args = Clap.run ARGV,
"-p" => lambda{|format| Publish.publish(format) if FORMATS.include?(format)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment