Class: Grdn::Storage

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

Constant Summary collapse

DIR_NAME =
'.grdn'
DEFAULT_LOCATION =
File.expand_path(File.join(ENV['HOME'], DIR_NAME))
SALT =
"\xB9R\xB5d\xBC#I?I7\x85<\xCD\xD6UW"
VALUE_FILENAME =
'seed.enc'
FINAL_MARKER =
'____final____'
KEY_TEXT =
'password is correct'

Instance Method Summary collapse

Constructor Details

#initialize(password, location = DEFAULT_LOCATION) ⇒ Storage

Returns a new instance of Storage.



14
15
16
17
18
19
# File 'lib/grdn/storage.rb', line 14

def initialize(password, location = DEFAULT_LOCATION)
  @location = location
  @key = key_for(password)
  FileUtils.mkdir_p @location
  set_or_verify_password
end

Instance Method Details

#get(path) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/grdn/storage.rb', line 30

def get(path)
  unless exists? path
    raise Grdn::Error.new('Does not exist') 
  end

  decrypt File.read(value_file_for(path))
end

#listObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/grdn/storage.rb', line 42

def list
  absolute_paths = Dir.glob(File.join(@location, '**', VALUE_FILENAME))
  paths = absolute_paths
    .map { |p| File.dirname p }
    .map { |p| p.gsub(@location + '/', '') }
    .map { |p| p.split('/') }

  tree = {}
  
  paths.each do |path|
    cursor = tree
    path.each do |part|
      cursor[part] ||= {}
      cursor = cursor[part]
    end
    cursor[FINAL_MARKER] = true
  end
  
  tree
end

#remove(path) ⇒ Object



38
39
40
# File 'lib/grdn/storage.rb', line 38

def remove(path)
  FileUtils.rm_rf dir_for(path)
end

#set(path, value) ⇒ Object



21
22
23
24
25
26
27
28
# File 'lib/grdn/storage.rb', line 21

def set(path, value)
  if exists? path
    raise Grdn::Error.new('Already exists, refusing to overwrite') 
  end

  FileUtils.mkdir_p dir_for(path)
  File.write value_file_for(path), encrypt(value)
end