Module: Ucode::Repo::AtomicWrites

Overview

Atomic, idempotent file-write helpers shared by CodepointWriter and AggregateWriter.

  • Atomic: write to a sibling ‘.tmp` file, then rename. A crash mid-write leaves either the old file or no file, never a truncated one.

  • Idempotent: byte-compare the existing file before writing; identical content is a no-op. Safe to re-run on the full dataset.

Instance Method Summary collapse

Instance Method Details

#same_content?(path, payload) ⇒ Boolean

Parameters:

  • path (Pathname)
  • payload (String)

Returns:

  • (Boolean)


36
37
38
# File 'lib/ucode/repo/atomic_writes.rb', line 36

def same_content?(path, payload)
  path.exist? && path.read == payload
end

#to_pretty_json(value) ⇒ String

Pretty JSON for any Hash/Array value.

Parameters:

  • value (Hash, Array)

Returns:

  • (String)


43
44
45
# File 'lib/ucode/repo/atomic_writes.rb', line 43

def to_pretty_json(value)
  JSON.pretty_generate(value)
end

#write_atomic(path, payload) ⇒ Boolean

Returns true if the file was written, false if skipped.

Parameters:

  • path (Pathname)
  • payload (String)

    the exact bytes to write

Returns:

  • (Boolean)

    true if the file was written, false if skipped



23
24
25
26
27
28
29
30
31
# File 'lib/ucode/repo/atomic_writes.rb', line 23

def write_atomic(path, payload)
  return false if same_content?(path, payload)

  path.dirname.mkpath
  tmp = Paths.tmp_path(path)
  tmp.write(payload)
  tmp.rename(path.to_s)
  true
end