Class: Qwe::DB::CommitsFile

Inherits:
Object
  • Object
show all
Includes:
DRb::DRbUndumped
Defined in:
lib/qwe/db/commits_file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir) ⇒ CommitsFile

Returns a new instance of CommitsFile.



12
13
14
15
16
# File 'lib/qwe/db/commits_file.rb', line 12

def initialize(dir)
  @path = File.join(dir, "commits")
  @archive_path = File.join(dir, "commits.zst")
  open
end

Instance Attribute Details

#archive_pathObject (readonly)

Returns the value of attribute archive_path.



10
11
12
# File 'lib/qwe/db/commits_file.rb', line 10

def archive_path
  @archive_path
end

#fileObject (readonly)

Returns the value of attribute file.



10
11
12
# File 'lib/qwe/db/commits_file.rb', line 10

def file
  @file
end

#pathObject (readonly)

Returns the value of attribute path.



10
11
12
# File 'lib/qwe/db/commits_file.rb', line 10

def path
  @path
end

Instance Method Details

#archive!Object



68
69
70
71
72
73
# File 'lib/qwe/db/commits_file.rb', line 68

def archive!
  File.binwrite(archive_path, Zstd.compress(read))
  close
  FileUtils.rm_f(path)
  @file = nil
end

#closeObject



79
80
81
# File 'lib/qwe/db/commits_file.rb', line 79

def close
  file&.close unless file&.closed?
end

#flushObject



75
76
77
# File 'lib/qwe/db/commits_file.rb', line 75

def flush
  file&.flush
end

#openObject



18
19
20
21
# File 'lib/qwe/db/commits_file.rb', line 18

def open
  return if @file && !@file.closed? || File.exist?(@archive_path)
  @file = File.open(@path, "a+")
end

#read(line = nil) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/qwe/db/commits_file.rb', line 39

def read(line = nil)
  if file && !file.closed?
    file.flush
    file.rewind
    if line
      lines = file.readlines
      lines[0, line].join("\n")
    else
      file.read
    end
  else
    cs = if File.exist?(archive_path)
      read_archive
    else
      File.read(path)
    end

    if line
      cs.lines[0, line].join("")
    else
      cs
    end
  end
end

#read_archiveObject



64
65
66
# File 'lib/qwe/db/commits_file.rb', line 64

def read_archive
  Zstd.decompress(File.binread(archive_path)).force_encoding("UTF-8")
end

#write(str) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/qwe/db/commits_file.rb', line 23

def write(str)
  if !file
    log "Write #{str} to archived commits file #{path}, unpacking"
    data = read_archive
    @file = File.open(@path, "a+")
    @file.write(data)
    FileUtils.rm_f(archive_path)
  elsif file.closed?
    open
  end
  file.write(str)
rescue => e
  log "Couldn't write #{str} to #{path}: #{e.full_message}"
  0
end