summaryrefslogtreecommitdiff
path: root/tool/checksum.rb
blob: bcc60ee14a63d93a4e89e7c3b060831d6644fccf (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!ruby

require_relative 'lib/vpath'

class Checksum
  def initialize(vpath)
    @vpath = vpath
  end

  attr_reader :source, :target

  def source=(source)
    @source = source
    @checksum = File.basename(source, ".*") + ".chksum"
  end

  def target=(target)
    @target = target
  end

  def update?
    src = @vpath.read(@source)
    @len = src.length
    @sum = src.sum
    return false unless @vpath.search(File.method(:exist?), @target)
    begin
      data = @vpath.read(@checksum)
    rescue
      return false
    else
      return false unless data[/src="([0-9a-z_.-]+)",/, 1] == @source
      return false unless @len == data[/\blen=(\d+)/, 1].to_i
      return false unless @sum == data[/\bchecksum=(\d+)/, 1].to_i
      return true
    end
  end

  def update!
    open(@checksum, "wb") {|f|
      f.puts("src=\"#{@source}\", len=#{@len}, checksum=#{@sum}")
    }
  end

  def update
    return true if update?
    update! if ret = yield(self)
    ret
  end

  def copy(name)
    @vpath.open(name, "rb") {|f|
      IO.copy_stream(f, name)
    }
    true
  end

  def make(*args)
    system(@make, *args)
  end

  def def_options(opt = (require 'optparse'; OptionParser.new))
    @vpath.def_options(opt)
    opt.on("--make=PATH") {|v| @make = v}
    opt
  end

  def self.update(argv)
    k = new(VPath.new)
    k.source, k.target, *argv = k.def_options.parse(*argv)
    k.update {|_| yield(_, *argv)}
  end
end