summaryrefslogtreecommitdiff
path: root/tool/lib/output.rb
diff options
context:
space:
mode:
authorNobuyoshi Nakada <nobu@ruby-lang.org>2022-11-01 11:08:47 +0900
committerNobuyoshi Nakada <nobu@ruby-lang.org>2022-11-01 14:34:05 +0900
commita2e7b11f2ae13f96171cb8a5aa6ae3cc75f6f083 (patch)
treed14c8b090dd66e94ad7a77a995e91053fd063411 /tool/lib/output.rb
parent99a79dc40bf20e0e5d588db4f93b69617affa7f3 (diff)
downloadruby-a2e7b11f2ae13f96171cb8a5aa6ae3cc75f6f083.tar.gz
output.rb: extract from generic_erb.rb
- writing to a file or stdout - touching timestamp files - overwriting only if changed - colorizing
Diffstat (limited to 'tool/lib/output.rb')
-rw-r--r--tool/lib/output.rb47
1 files changed, 47 insertions, 0 deletions
diff --git a/tool/lib/output.rb b/tool/lib/output.rb
new file mode 100644
index 0000000000..5e0e878322
--- /dev/null
+++ b/tool/lib/output.rb
@@ -0,0 +1,47 @@
+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)
+ 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
+
+ def write(data)
+ unless @path
+ $stdout.print data
+ return true
+ end
+ color = Colorize.new(@color)
+ unchanged = color.pass("unchanged")
+ updated = color.fail("updated")
+
+ if @ifchange and (@vpath.read(@path, "rb") == data rescue false)
+ puts "#{@path} #{unchanged}"
+ written = false
+ else
+ File.binwrite(@path, data)
+ puts "#{@path} #{updated}"
+ 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