This repository has been archived by the owner on Dec 24, 2019. It is now read-only.
/
renderable.rb
69 lines (57 loc) · 1.63 KB
/
renderable.rb
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
module Babushka
class Renderable
include ShellHelpers
include RunHelpers
SEAL_REGEXP = /# Generated by babushka-[\d\.]+ at [a-zA-Z\d\-\:\s+]+, from [0-9a-f]{40}+\. [0-9a-f]{40}/
attr_reader :path
def initialize path
@path = path.p
end
def render source, opts = {}
shell("cat > '#{path}'",
:input => inkan_output_for(source, opts),
:sudo => opts[:sudo]
).tap {|result|
if result
sudo "chmod #{opts[:perms]} '#{path}'" if opts[:perms]
end
}
end
def exists?
path.exists?
end
def clean?
Inkan.legitimate? path
end
def from? source
exists? && source_sha == sha_of(source)
end
def source_sha
path.open {|f|
[f.gets, f.gets].compact.detect {|l|
l[/^#!/].nil? # The first line that isn't a hashbang
} || ''
}.scan(/, from ([0-9a-f]{40})\./).flatten.first
end
private
def inkan_output_for source, opts = {}
Inkan.render {|inkan|
inkan.credit = "Generated #{_by_babushka}, from #{sha_of(source)}"
inkan.comment = opts[:comment] if opts[:comment]
inkan.comment_suffix = opts[:comment_suffix] if opts[:comment_suffix]
inkan.print render_erb(source, opts[:context])
}
end
def render_erb source, custom_context
require 'erb'
(custom_context || self).instance_eval {
ERB.new(source.p.read).result(binding)
}
end
def sha_of source
require 'digest/sha1'
raise "Source doesn't exist: #{source.p}" unless source.p.exists?
Digest::SHA1.hexdigest(source.p.read)
end
end
end