Class: Ralph::Git::FileSnapshot

Inherits:
Object
  • Object
show all
Defined in:
lib/ralph/git/file_snapshot.rb

Overview

Captures and compares file state via git for change detection

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(files) ⇒ FileSnapshot

Returns a new instance of FileSnapshot.



11
12
13
# File 'lib/ralph/git/file_snapshot.rb', line 11

def initialize(files)
  @files = files
end

Instance Attribute Details

#filesObject (readonly)

Returns the value of attribute files.



9
10
11
# File 'lib/ralph/git/file_snapshot.rb', line 9

def files
  @files
end

Class Method Details

.captureObject

Capture a snapshot of all tracked/modified files and their git hashes



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
# File 'lib/ralph/git/file_snapshot.rb', line 16

def self.capture
  files = {}
  begin
    status, _, _ = Open3.capture3("git", "status", "--porcelain")
    tracked, _, _ = Open3.capture3("git", "ls-files")

    all_files = Set.new
    status.strip.each_line do |line|
      name = line[3..]&.strip
      all_files.add(name) if name && !name.empty?
    end
    tracked.strip.each_line do |file|
      f = file.strip
      all_files.add(f) unless f.empty?
    end

    all_files.each do |file|
      begin
        hash, _, _ = Open3.capture3("git", "hash-object", file)
        files[file] = hash.strip unless hash.strip.empty?
      rescue StandardError
        # skip
      end
    end
  rescue StandardError
    # git not available
  end
  new(files)
end

Instance Method Details

#modified_since(other) ⇒ Object

Return list of files that changed between this snapshot and a later one



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/ralph/git/file_snapshot.rb', line 47

def modified_since(other)
  Array.new.tap do |changed|
    other.files.each do |file, hash|
      changed << file if files[file] != hash
    end

    files.each_key do |file|
      changed << file unless other.files.key?(file)
    end
  end
end