Class: Diffcrypt::File

Inherits:
Object
  • Object
show all
Defined in:
lib/diffcrypt/file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ File

Returns a new instance of File.



9
10
11
# File 'lib/diffcrypt/file.rb', line 9

def initialize(path)
  @path = ::File.absolute_path path
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



7
8
9
# File 'lib/diffcrypt/file.rb', line 7

def file
  @file
end

Instance Method Details

#cipherObject

Determines the cipher to use for encryption/decryption



18
19
20
21
22
# 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) ⇒ Object

TODO: Add a test to verify this does descrypt properly



63
64
65
66
67
# 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) ⇒ Object

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



56
57
58
59
60
# 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?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/diffcrypt/file.rb', line 13

def encrypted?
  to_yaml['cipher']
end

#exists?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/diffcrypt/file.rb', line 25

def exists?
  ::File.exist?(@path)
end

#formatString

Determines the format to be used for encryption

Returns:

  • (String)

    diffcrypt|activesupport



31
32
33
34
35
36
# File 'lib/diffcrypt/file.rb', line 31

def format
  return 'diffcrypt' if read == ''
  return 'diffcrypt' if read.index('---')&.zero?

  'activesupport'
end

#readString

Returns Raw contents of the file.

Returns:

  • (String)

    Raw contents of the file



39
40
41
42
43
44
# File 'lib/diffcrypt/file.rb', line 39

def read
  return '' unless ::File.exist?(@path)

  @read ||= ::File.read(@path)
  @read
end

#to_yamlObject



69
70
71
# File 'lib/diffcrypt/file.rb', line 69

def to_yaml
  @to_yaml ||= YAML.safe_load(read) || {}
end

#write(key, data, cipher: nil) ⇒ Boolean

Save the encrypted contents back to disk

Returns:

  • (Boolean)

    True is file save was successful



48
49
50
51
52
53
# 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