Class: Fire::Digest

Inherits:
Object
  • Object
show all
Defined in:
lib/fire/digest.rb

Constant Summary collapse

DEFAULT_FILE =
".fire/digest"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Digest

Returns a new instance of Digest.



26
27
28
29
30
31
32
33
34
35
# File 'lib/fire/digest.rb', line 26

def initialize(options={})
  @file   = options[:file]   || DEFAULT_FILE
  @ignore = options[:ignore] || []

  @current = {}
  @saved   = {}

  read
  refresh
end

Instance Attribute Details

#currentObject (readonly)

Returns the value of attribute current.



17
18
19
# File 'lib/fire/digest.rb', line 17

def current
  @current
end

#fileObject (readonly)

Returns the value of attribute file.



14
15
16
# File 'lib/fire/digest.rb', line 14

def file
  @file
end

#ignoreObject (readonly)

Returns the value of attribute ignore.



23
24
25
# File 'lib/fire/digest.rb', line 23

def ignore
  @ignore
end

#savedObject (readonly)

Returns the value of attribute saved.



20
21
22
# File 'lib/fire/digest.rb', line 20

def saved
  @saved
end

Instance Method Details

#checksum(file) ⇒ String

Compute the sha1 identifer for a file.

Parameters:

  • file

    path to a file

Returns:

  • (String)

    Returns String SHA1 digest string.



100
101
102
103
104
105
106
107
108
# File 'lib/fire/digest.rb', line 100

def checksum(file)
  sha = ::Digest::SHA1.new
  File.open(file, 'r') do |fh|
    fh.each_line do |l|
      sha << l
    end
  end
  sha.hexdigest
end

#readObject

Load saved digest.



38
39
40
41
42
43
44
45
# File 'lib/fire/digest.rb', line 38

def read
  return unless File.exist?(file)
  File.read(file).lines.each do |line|
    if md = /^(\w+)\s+(.*?)$/.match(line)
      @saved[md[2]] = md[1]
    end
  end
end

#refreshvoid

This method returns an undefined value.

Gather current digest for all files.



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/fire/digest.rb', line 66

def refresh
  list = Dir['**/*']
  list = list.reject{ |path| ignore.any?{ |ig| /^#{ig}/ =~ path } }
  list.each do |path|
    if File.directory?(path)
      # how to handle directories as a whole?
    elsif File.exist?(path)
      id = checksum(path)
      @current[path] = id
    end
  end
end

#saveObject

Save current digest.



80
81
82
83
84
# File 'lib/fire/digest.rb', line 80

def save
  dir = File.dirname(file)
  FileUtils.mkdir(dir) unless File.directory?(dir)
  File.open(file, 'w'){ |f| f << to_s }      
end

#to_sObject

Returns [String] digest file format.



87
88
89
90
91
92
93
# File 'lib/fire/digest.rb', line 87

def to_s
  s = ""
  current.each do |path, id|
    s << "#{id} #{path}\n"
  end
  s
end