class Diffcrypt::File

Attributes

file[R]

Public Class Methods

new(path) click to toggle source
# File lib/diffcrypt/file.rb, line 9
def initialize(path)
  @path = ::File.absolute_path path
end

Public Instance Methods

cipher() click to toggle source

Determines the cipher to use for encryption/decryption

# File lib/diffcrypt/file.rb, line 18
def cipher
  return 'aes-128-gcm' if format == 'activesupport'

  to_yaml['cipher'] || Encryptor::DEFAULT_CIPHER
end
decrypt(key) click to toggle source

TODO: Add a test to verify this does descrypt properly

# File lib/diffcrypt/file.rb, line 63
def decrypt(key)
  return read unless encrypted?

  Encryptor.new(key, cipher: cipher).decrypt(read)
end
encrypt(key, cipher: DEFAULT_CIPHER) click to toggle source

TODO: This seems useless, figure out what's up

# File lib/diffcrypt/file.rb, line 56
def encrypt(key, cipher: DEFAULT_CIPHER)
  return read if encrypted?

  Encryptor.new(key, cipher: cipher).encrypt(read)
end
encrypted?() click to toggle source
# File lib/diffcrypt/file.rb, line 13
def encrypted?
  to_yaml['cipher']
end
exists?() click to toggle source

@return [Boolean]

# File lib/diffcrypt/file.rb, line 25
def exists?
  ::File.exist?(@path)
end
format() click to toggle source

Determines the format to be used for encryption @return [String] diffcrypt|activesupport

# File lib/diffcrypt/file.rb, line 31
def format
  return 'diffcrypt' if read == ''
  return 'diffcrypt' if read.index('---')&.zero?

  'activesupport'
end
read() click to toggle source

@return [String] Raw contents of the file

# File lib/diffcrypt/file.rb, line 39
def read
  return '' unless ::File.exist?(@path)

  @read ||= ::File.read(@path)
  @read
end
to_yaml() click to toggle source
# File lib/diffcrypt/file.rb, line 69
def to_yaml
  @to_yaml ||= YAML.safe_load(read) || {}
end
write(key, data, cipher: nil) click to toggle source

Save the encrypted contents back to disk @return [Boolean] True is file save was successful

# File lib/diffcrypt/file.rb, line 48
def write(key, data, cipher: nil)
  cipher ||= self.cipher
  yaml = ::YAML.dump(data)
  contents = Encryptor.new(key, cipher: cipher).encrypt(yaml)
  ::File.write(@path, contents)
end