2022-10-31 22:08:47 -04:00
|
|
|
require_relative 'vpath'
|
|
|
|
require_relative 'colorize'
|
|
|
|
|
|
|
|
class Output
|
|
|
|
attr_reader :path, :vpath
|
|
|
|
|
|
|
|
def initialize
|
|
|
|
@path = @timestamp = @ifchange = @color = nil
|
|
|
|
@vpath = VPath.new
|
|
|
|
end
|
|
|
|
|
|
|
|
def def_options(opt)
|
2022-11-01 22:37:54 -04:00
|
|
|
opt.separator(" Output common options:")
|
2022-10-31 22:08:47 -04:00
|
|
|
opt.on('-o', '--output=PATH') {|v| @path = v}
|
|
|
|
opt.on('-t', '--timestamp[=PATH]') {|v| @timestamp = v || true}
|
|
|
|
opt.on('-c', '--[no-]if-change') {|v| @ifchange = v}
|
|
|
|
opt.on('--color') {@color = true}
|
|
|
|
@vpath.def_options(opt)
|
|
|
|
end
|
|
|
|
|
2022-11-01 23:18:17 -04:00
|
|
|
def write(data, overwrite: false)
|
2022-10-31 22:08:47 -04:00
|
|
|
unless @path
|
|
|
|
$stdout.print data
|
|
|
|
return true
|
|
|
|
end
|
|
|
|
color = Colorize.new(@color)
|
|
|
|
unchanged = color.pass("unchanged")
|
|
|
|
updated = color.fail("updated")
|
2022-11-01 23:18:17 -04:00
|
|
|
outpath = nil
|
2022-10-31 22:08:47 -04:00
|
|
|
|
2022-11-01 23:18:17 -04:00
|
|
|
if @ifchange and (@vpath.open(@path, "rb") {|f| outpath = f.path; f.read == data} rescue false)
|
|
|
|
puts "#{outpath} #{unchanged}"
|
2022-10-31 22:08:47 -04:00
|
|
|
written = false
|
|
|
|
else
|
2022-11-01 23:18:17 -04:00
|
|
|
unless overwrite and outpath and (File.binwrite(outpath, data) rescue nil)
|
|
|
|
File.binwrite(outpath = @path, data)
|
|
|
|
end
|
|
|
|
puts "#{outpath} #{updated}"
|
2022-10-31 22:08:47 -04:00
|
|
|
written = true
|
|
|
|
end
|
|
|
|
if timestamp = @timestamp
|
|
|
|
if timestamp == true
|
|
|
|
dir, base = File.split(@path)
|
|
|
|
timestamp = File.join(dir, ".time." + base)
|
|
|
|
end
|
|
|
|
File.binwrite(timestamp, '')
|
|
|
|
File.utime(nil, nil, timestamp)
|
|
|
|
end
|
|
|
|
written
|
|
|
|
end
|
|
|
|
end
|