dn42-scripts/scripts/utils.rb

84 lines
1.5 KiB
Ruby
Raw Normal View History

2015-01-13 07:19:32 +00:00
require "ostruct"
require "fileutils"
require "erb"
require "json"
require "pathname"
require "pry"
class Registry
PATH = Pathname.new(File.expand_path("../../registry.json", __FILE__))
def initialize
@data = JSON.load(File.open(Registry::PATH))
end
attr_accessor :data
def save
f = File.open(Registry::PATH, "w+")
f.puts JSON.pretty_generate(@data)
f.close
end
end
def atomic_write(path, content)
dir = File.dirname(path)
unless Dir.exist?(dir)
FileUtils.mkdir_p(dir)
end
2015-01-13 07:19:32 +00:00
temp_path = path.to_s + ".tmp"
File.open(temp_path, 'w+') do |f|
f.write(content)
end
FileUtils.mv(temp_path, path)
end
def sh(cmd, *args)
puts "$ #{cmd} "+ args.map {|a| "'#{a}'" }.join(" ")
2015-01-15 07:39:32 +00:00
system(cmd, *args)
2015-01-13 07:19:32 +00:00
end
def die(msg)
$stderr.puts(msg)
exit(1)
end
2015-01-19 08:18:25 +00:00
def try(hash, *args)
result = hash
args.each do |arg|
if result.respond_to?(:[]) && result[arg]
result = result[arg]
else
return nil
end
end
result
end
2015-01-13 07:19:32 +00:00
class TemplateContext < OpenStruct
def get_binding
binding
end
end
class Template
def initialize(path)
@erb = ERB.new(File.read(path), nil, '-')
end
def render(params={})
@erb.result(TemplateContext.new(params).get_binding)
end
end
2015-01-19 07:37:35 +00:00
class CommandTemplate
def initialize(command)
@erb = ERB.new(command, nil, '-')
end
def execute(params={})
args = params.dup
args.each do |k,v|
args[k] = Shellwords.escape(v)
end
cmd = @erb.result(TemplateContext.new(args).get_binding)
sh(cmd)
end
end