Class: TTNT::Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/ttnt/storage.rb

Overview

A utility class to store TTNT data such as test-to-code mapping and metadata.

Instance Method Summary collapse

Constructor Details

#initialize(repo, sha = nil) ⇒ Storage

Initialize the storage from given repo and sha. This reads contents from a ‘.ttnt` file. When sha is not nil, contents of the file on that commit is read. Data can be written only when sha is nil (written to current working tree).

Parameters:

  • repo (Rugged::Repository)
  • sha (String) (defaults to: nil)

    sha of the commit which data should be read from. nil means reading from/writing to current working tree.



14
15
16
17
# File 'lib/ttnt/storage.rb', line 14

def initialize(repo, sha = nil)
  @repo = repo
  @sha = sha
end

Instance Method Details

#filenameObject (private)



54
55
56
# File 'lib/ttnt/storage.rb', line 54

def filename
  "#{TTNT.root_dir}/.ttnt"
end

#filename_from_repository_rootObject (private)



58
59
60
# File 'lib/ttnt/storage.rb', line 58

def filename_from_repository_root
  filename.gsub(@repo.workdir, '')
end

#read(section) ⇒ Hash

Read data from the storage in the given section.

Parameters:

  • section (String)

Returns:

  • (Hash)


23
24
25
26
27
28
29
30
31
# File 'lib/ttnt/storage.rb', line 23

def read(section)
  str = read_storage_content

  if str.length > 0
    JSON.parse(str)[section] || {}
  else
    {}
  end
end

#read_storage_contentObject (private)



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/ttnt/storage.rb', line 76

def read_storage_content
  if @sha
    if oid = storage_file_oid
      @repo.lookup(oid).content
    else
      '' # Storage file is not committed for the commit of given sha
    end
  else
    File.exist?(filename) ? File.read(filename) : ''
  end
end

#storage_file_oidObject (private)



62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/ttnt/storage.rb', line 62

def storage_file_oid
  tree = @repo.lookup(@sha).tree
  paths = filename_from_repository_root.split(File::SEPARATOR)
  dirs, filename = paths[0...-1], paths[-1]
  dirs.each do |dir|
    obj = tree[dir]
    return nil unless obj
    tree = @repo.lookup(obj[:oid])
  end
  obj = tree[filename]
  return nil unless obj
  obj[:oid]
end

#write!(section, value) ⇒ Object

Write value to the given section in the storage. Locks the file so that concurrent write does not occur.

Parameters:

  • section (String)
  • value (Hash)


38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/ttnt/storage.rb', line 38

def write!(section, value)
  raise 'Data cannot be written to the storage back in git history' unless @sha.nil?
  File.open(filename, File::RDWR|File::CREAT, 0644) do |f|
    f.flock(File::LOCK_EX)
    str = f.read
    data = str.length > 0 ? JSON.parse(str) : {}
    data[section] = value
    f.rewind
    f.write(data.to_json)
    f.flush
    f.truncate(f.pos)
  end
end