Module: Lich::Util::Update::FileWriter

Defined in:
documented/common/update/file_writer.rb

Class Method Summary collapse

Class Method Details

.build_local_sha_map(dir, pattern = '*.lic') ⇒ Hash

Builds a SHA1 hash map for files in a directory matching a given pattern.

Examples:

sha_map = Lich::Util::Update::FileWriter.build_local_sha_map('/path/to/dir')
puts sha_map

Parameters:

  • dir (String)

    the directory to scan for files.

  • pattern (String) (defaults to: '*.lic')

    the pattern to match files (default is '*.lic').

Returns:

  • (Hash)

    a hash mapping file names to their SHA1 hashes.



46
47
48
49
50
51
# File 'documented/common/update/file_writer.rb', line 46

def self.build_local_sha_map(dir, pattern = '*.lic')
  Dir[File.join(dir, pattern)].each_with_object({}) do |path, map|
    body = File.binread(path)
    map[File.basename(path)] = Digest::SHA1.hexdigest("blob #{body.size}\0#{body}")
  end
end

.safe_write(path, content) ⇒ void

This method returns an undefined value.

Safely writes content to a file using a temporary rename-delete pattern.

Parameters:

  • path (String)

    the path to the file to write.

  • content (String)

    the content to write to the file.

Raises:

  • (StandardError)

    if the write operation fails.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'documented/common/update/file_writer.rb', line 23

def self.safe_write(path, content)
  tmp = "#{path}.tmp"
  old = "#{path}.old"
  File.rename(path, old) if File.exist?(path)
  begin
    File.binwrite(tmp, content)
    File.rename(tmp, path)
  rescue StandardError
    File.rename(old, path) if File.exist?(old)
    File.delete(tmp) if File.exist?(tmp)
    raise
  end
  File.delete(old) if File.exist?(old)
end