/
mustache
executable file
·100 lines (77 loc) · 2.53 KB
/
mustache
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env ruby
require 'yaml'
require 'optparse'
require 'mustache'
require 'mustache/version'
class Mustache
class CLI
# Return a structure describing the options.
def self.parse_options(args)
opts = OptionParser.new do |opts|
opts.banner = "Usage: mustache [-c] [-t] [-r library] FILE ..."
opts.separator " "
opts.separator "Examples:"
opts.separator " $ mustache data.yml template.mustache"
opts.separator " $ cat data.yml | mustache - template.mustache"
opts.separator " $ mustache -c template.mustache"
opts.separator " "
opts.separator " See mustache(1) or " +
"http://mustache.github.com/mustache.1.html"
opts.separator " for more details."
opts.separator " "
opts.separator "Options:"
opts.on("-c", "--compile FILE",
"Print the compiled Ruby for a given template.") do |file|
puts Mustache::Template.new(File.read(file)).compile
exit
end
opts.on("-t", "--tokens FILE",
"Print the tokenized form of a given template.") do |file|
require 'pp'
pp Mustache::Template.new(File.read(file)).tokens
exit
end
opts.on('-r', '--require LIB', 'Require a Ruby library before running.') do |lib|
require lib
end
opts.separator "Common Options:"
opts.on("-v", "--version", "Print the version") do |v|
puts "Mustache v#{Mustache::Version}"
exit
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end
opts.separator ""
opts.parse!(args)
end
# Does the dirty work of reading files from STDIN and the command
# line then processing them. The meat of this script, if you will.
def self.process_files(input_stream)
doc = input_stream.read
if doc =~ /^(\s*---(.+)---\s*)/m
yaml = $2.strip
template = doc.sub($1, '')
if RUBY_VERSION >= '1.9.3'
YAML.load_stream(yaml) do |data|
puts Mustache.render(template, data)
end
else
YAML.each_document(yaml) do |data|
puts Mustache.render(template, data)
end
end
else
puts Mustache.render(doc)
end
end
end
end
# Help is the default.
ARGV << '-h' if ARGV.empty? && $stdin.tty?
# Process options
Mustache::CLI.parse_options(ARGV) if $stdin.tty?
# Still here - process ARGF
Mustache::CLI.process_files(ARGF)