| 1 |
|
| 2 |
|
| 3 |
require 'yaml' |
| 4 |
require 'optparse' |
| 5 |
|
| 6 |
require 'mustache' |
| 7 |
require 'mustache/version' |
| 8 |
|
| 9 |
class Mustache |
| 10 |
class CLI |
| 11 |
|
| 12 |
def self.parse_options(args) |
| 13 |
opts = OptionParser.new do |opts| |
| 14 |
opts.banner = "Usage: mustache [-c] [-t] [-e] [-r library] FILE ..." |
| 15 |
|
| 16 |
opts.separator " " |
| 17 |
|
| 18 |
opts.separator "Examples:" |
| 19 |
opts.separator " $ mustache data.yml template.mustache" |
| 20 |
opts.separator " $ cat data.yml | mustache - template.mustache" |
| 21 |
opts.separator " $ mustache -c template.mustache" |
| 22 |
|
| 23 |
opts.separator " " |
| 24 |
|
| 25 |
opts.separator " See mustache(1) or " + |
| 26 |
"http://mustache.github.com/mustache.1.html" |
| 27 |
opts.separator " for more details." |
| 28 |
|
| 29 |
opts.separator " " |
| 30 |
opts.separator "Options:" |
| 31 |
|
| 32 |
opts.on("-c", "--compile FILE", |
| 33 |
"Print the compiled Ruby for a given template.") do |file| |
| 34 |
puts Mustache::Template.new(File.read(file)).compile |
| 35 |
exit |
| 36 |
end |
| 37 |
|
| 38 |
opts.on("-t", "--tokens FILE", |
| 39 |
"Print the tokenized form of a given template.") do |file| |
| 40 |
require 'pp' |
| 41 |
pp Mustache::Template.new(File.read(file)).tokens |
| 42 |
exit |
| 43 |
end |
| 44 |
|
| 45 |
opts.on("-e", "--error", |
| 46 |
"Raise an error on context misses.") do |e| |
| 47 |
Mustache.raise_on_context_miss = true |
| 48 |
end |
| 49 |
|
| 50 |
opts.on('-r', '--require LIB', 'Require a Ruby library before running.') do |lib| |
| 51 |
require lib |
| 52 |
end |
| 53 |
|
| 54 |
opts.separator "Common Options:" |
| 55 |
|
| 56 |
opts.on("-v", "--version", "Print the version") do |v| |
| 57 |
puts "Mustache v#{Mustache::VERSION}" |
| 58 |
exit |
| 59 |
end |
| 60 |
|
| 61 |
opts.on_tail("-h", "--help", "Show this message") do |
| 62 |
puts opts |
| 63 |
exit |
| 64 |
end |
| 65 |
end |
| 66 |
|
| 67 |
opts.separator "" |
| 68 |
|
| 69 |
opts.parse!(args) |
| 70 |
end |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
def self.process_files(input_files) |
| 75 |
doc = input_files.file.read |
| 76 |
|
| 77 |
yaml = nil |
| 78 |
begin |
| 79 |
yaml = YAML.load_stream(doc) |
| 80 |
rescue |
| 81 |
abort "Unable to parse yaml!" |
| 82 |
end |
| 83 |
|
| 84 |
if yaml.nil? |
| 85 |
puts Mustache.render(doc) |
| 86 |
else |
| 87 |
template = input_files.skip.file.read |
| 88 |
|
| 89 |
puts Mustache.render template, yaml.compact.reduce(&:merge) |
| 90 |
end |
| 91 |
end |
| 92 |
end |
| 93 |
end |
| 94 |
|
| 95 |
|
| 96 |
ARGV << '-h' if ARGV.empty? && $stdin.tty? |
| 97 |
|
| 98 |
|
| 99 |
Mustache::CLI.parse_options(ARGV) if $stdin.tty? |
| 100 |
|
| 101 |
|
| 102 |
Mustache::CLI.process_files(ARGF) |
| 103 |
|