summaryrefslogtreecommitdiff
path: root/tool/lib/output.rb
blob: 5e0e878322224d8fbd0d107cf4c96d286d5dc41e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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