dn42-scripts/scripts/utils.rb

84 lines
1.5 KiB
Ruby

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
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(" ")
system(cmd, *args)
end
def die(msg)
$stderr.puts(msg)
exit(1)
end
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
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
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