ruby/tool/lib/output.rb
Nobuyoshi Nakada d9242cab17
Skip generating gemspec if the newer target exists
Because of difference of rubygems versions, between baseruby and the
bundled source, the generated gemspec may differ even equivalent
actually.
2026-05-13 11:55:57 +09:00

72 lines
2.2 KiB
Ruby

require_relative 'vpath'
require_relative 'colorize'
class Output
attr_reader :path, :vpath
def initialize(path: nil, timestamp: nil, ifchange: nil, color: nil,
overwrite: false, create_only: false, vpath: VPath.new)
@path = path
@timestamp = timestamp
@ifchange = ifchange
@color = color
@overwrite = overwrite
@create_only = create_only
@vpath = vpath
end
COLOR_WHEN = {
'always' => true, 'auto' => nil, 'never' => false,
nil => true, false => false,
}
def def_options(opt)
opt.separator(" Output common options:")
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('--[no-]color=[WHEN]', COLOR_WHEN.keys) {|v| @color = COLOR_WHEN[v]}
opt.on('--[no-]create-only') {|v| @create_only = v}
opt.on('--[no-]overwrite') {|v| @overwrite = v}
@vpath.def_options(opt)
end
def write(data, overwrite: @overwrite, create_only: @create_only, name: nil, newer: nil, quiet: false)
unless (name = name ? (@path ? File.join(@path, name) : name) : @path)
$stdout.print data
return true
end
color = Colorize.new(@color)
unchanged = color.pass("unchanged")
updated = color.fail("updated")
outpath = nil
if (@ifchange or overwrite or create_only or newer) and (@vpath.open(name, "rb") {|f|
outpath = f.path
next true if newer and f.mtime > newer
if @ifchange or create_only
original = f.read
(@ifchange and original == data) or (create_only and !original.empty?)
end
} rescue false)
puts "#{outpath} #{unchanged}" unless quiet
written = false
else
unless overwrite and outpath and (File.binwrite(outpath, data) rescue nil)
File.binwrite(outpath = name, data)
end
puts "#{outpath} #{updated}" unless quiet
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