-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathcompiler.rb
More file actions
91 lines (74 loc) · 2.29 KB
/
compiler.rb
File metadata and controls
91 lines (74 loc) · 2.29 KB
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
require 'open3'
require 'stringio'
require 'tempfile'
module Closure
# We raise a Closure::Error when compilation fails for any reason.
class Error < StandardError; end
# The Closure::Compiler is a basic wrapper around the actual JAR. There's not
# much to see here.
class Compiler
attr_accessor :options
DEFAULT_OPTIONS = {
:warning_level => 'QUIET',
:language_in => 'ECMASCRIPT5'
}
# When you create a Compiler, pass in the flags and options.
def initialize(options={})
@java = options.delete(:java) || JAVA_COMMAND
@jar = options.delete(:jar_file) || COMPILER_JAR
@options = DEFAULT_OPTIONS.merge(options)
end
# Can compile a JavaScript string or open IO object. Returns the compiled
# JavaScript as a string or yields an IO object containing the response to a
# block, for streaming.
def compile(io)
tempfile = Tempfile.new('closure_compiler')
if io.respond_to? :read
while buffer = io.read(4096) do
tempfile.write(buffer)
end
else
tempfile.write(io.to_s)
end
tempfile.flush
begin
result = compile_files(tempfile.path)
rescue Exception => e
raise e
ensure
tempfile.close!
end
yield(StringIO.new(result)) if block_given?
result
end
alias_method :compress, :compile
# Takes an array of javascript file paths or a single path. Returns the
# resulting JavaScript as a string or yields an IO object containing the
# response to a block, for streaming.
def compile_files(files)
stdout, stderr, status = Open3::capture3 *command(js: files)
unless status == 0
raise Error, stderr
end
# Let them see the warnings.
$stderr.write stderr
yield(StringIO.new(stdout)) if block_given?
stdout
end
alias_method :compile_file, :compile_files
private
# Serialize hash options to the command-line format.
def serialize_options(options)
options.map do |k, v|
if (v.is_a?(Array))
v.map {|v2| ["--#{k}", v2.to_s]}
else
["--#{k}", v.to_s]
end
end.flatten
end
def command(**options)
%W(#@java -jar #@jar) + serialize_options(@options.merge(options))
end
end
end