1
0
Fork 0
mirror of https://github.com/haml/haml.git synced 2022-11-09 12:33:31 -05:00
haml--haml/lib/hamlit/cli.rb

90 lines
2.1 KiB
Ruby
Raw Normal View History

2015-03-15 13:54:54 +09:00
require 'hamlit'
require 'thor'
module Hamlit
class CLI < Thor
2015-03-25 01:34:55 +09:00
IGNORED_COMPILERS = ['HTML'].freeze
2015-03-15 13:54:54 +09:00
desc 'render HAML', 'Render haml template'
2015-03-28 12:17:19 +09:00
option :ugly, type: :boolean, aliases: ['-u']
2015-03-15 13:54:54 +09:00
def render(file)
code = generate_code(file)
puts eval(code)
end
desc 'compile HAML', 'Show generated rendering code'
2015-03-28 12:17:19 +09:00
option :ugly, type: :boolean, aliases: ['-u']
2015-03-15 13:54:54 +09:00
def compile(file)
code = generate_code(file)
puts code
end
desc 'temple HAML', 'Show a compile result of hamlit AST'
2015-03-28 12:17:19 +09:00
option :ugly, type: :boolean, aliases: ['-u']
2015-03-15 13:54:54 +09:00
def temple(file)
pp generate_temple_ast(file)
end
desc 'parse HAML', 'Show parse result'
def parse(file)
pp generate_hamlit_ast(file)
end
private
# Flexible default_task, compatible with haml's CLI
def method_missing(*args)
return super(*args) if args.length > 1
render(args.first.to_s)
end
def generate_code(file)
template = File.read(file)
2015-03-28 12:17:19 +09:00
Hamlit::Engine.new(options).call(template)
2015-03-15 13:54:54 +09:00
end
def generate_temple_ast(file)
chain = Hamlit::Engine.chain.map(&:first).map(&:to_s)
compilers = chain.select do |compiler|
2015-03-25 01:34:55 +09:00
compiler =~ /\AHamlit::/ && !ignored_compilers.include?(compiler)
2015-03-15 13:54:54 +09:00
end
template = File.read(file)
compilers.inject(template) do |exp, compiler|
2015-03-28 12:17:19 +09:00
Module.const_get(compiler).new(options).call(exp)
2015-03-15 13:54:54 +09:00
end
end
def generate_hamlit_ast(file)
template = File.read(file)
Hamlit::Parser.new.call(template)
end
# Enable colored pretty printing only for development environment.
# I don't think it is a good idea to add pry as runtime dependency
# just for debug color printing.
def pp(arg)
begin
require 'pry'
Pry::ColorPrinter.pp(arg)
rescue LoadError
require 'pp'
super(arg)
end
end
2015-03-25 01:34:55 +09:00
def ignored_compilers
IGNORED_COMPILERS.map { |name| "Hamlit::#{name}" }
end
2015-03-28 12:17:19 +09:00
def options
symbolize_keys(super)
end
def symbolize_keys(hash)
{}.tap { |h| hash.each { |k, v| h[k.to_sym] = v } }
end
2015-03-15 13:54:54 +09:00
end
end