Class: Dotenv::Sync::Syncer

Inherits:
Object
  • Object
show all
Defined in:
lib/dotenv/sync/syncer.rb

Constant Summary collapse

GITIGNORE =
'.gitignore'
DEFAULT_SORT_FILE =
'.env'
DEFAULT_SECRET_FILE =
'.env.local'
DEFAULT_ENCRYPTED_FILE =
'.env-encrypted'
DEFAULT_KEY_FILE =
'.env-key'
DEFAULT_CONFIG_FILE =
'.env-config'
SEPARATOR =
">>>><<<<"

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Syncer

Returns a new instance of Syncer.



17
18
19
20
21
22
# File 'lib/dotenv/sync/syncer.rb', line 17

def initialize(options = {})
  @key_filename = options[:key] || DEFAULT_KEY_FILE
  @secret_filename = options[:secret] || DEFAULT_SECRET_FILE
  @encrypted_filename = options[:encrypted] || DEFAULT_ENCRYPTED_FILE
  validate_gitignore
end

Instance Method Details

#generate_keyObject



24
25
26
27
# File 'lib/dotenv/sync/syncer.rb', line 24

def generate_key
  key = cipher.random_key
  write_64(@key_filename, key)
end

#load_dataObject



67
68
69
70
71
72
73
74
75
76
# File 'lib/dotenv/sync/syncer.rb', line 67

def load_data
  validate_file! @encrypted_filename
  key = read_key!
  data = read_64 @encrypted_filename
  iv, encrypted = data.split(SEPARATOR)
  cipher.decrypt
  cipher.iv = iv
  cipher.key = key
  data = cipher.update(encrypted) + cipher.final
end

#mergeObject



52
53
54
55
56
57
58
# File 'lib/dotenv/sync/syncer.rb', line 52

def merge
  existing_data = read(@secret_filename)
  merged_data = merge_lines(load_data, existing_data)
  write(@secret_filename, merged_data)
  puts "Successfully merged #{@secret_filename}"
  merged_data
end

#merge_lines(left, right) ⇒ Object



60
61
62
63
64
65
# File 'lib/dotenv/sync/syncer.rb', line 60

def merge_lines(left, right)
  left_lines = left.lines.map(&:strip)
  right_lines = right.lines.map(&:strip)
  merged = left_lines + (right_lines - left_lines)
  sort_lines(merged)
end

#pullObject



45
46
47
48
49
50
# File 'lib/dotenv/sync/syncer.rb', line 45

def pull
  data = load_data
  write(@secret_filename, data)
  puts "Successfully decrypted #{@secret_filename}"
  data
end

#pushObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dotenv/sync/syncer.rb', line 29

def push
  validate_file! @secret_filename
  key = read_key!
  data = read(@secret_filename)
  data = sort_lines(data.lines)
  cipher.encrypt
  cipher.key = key
  random_iv = cipher.random_iv
  cipher.iv = random_iv
  encrypted = cipher.update(data) + cipher.final
  encrypted = random_iv + SEPARATOR + encrypted
  write_64 @encrypted_filename, encrypted
  puts "Successfully encrypted #{@secret_filename}"
  data
end

#sort(filename) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/dotenv/sync/syncer.rb', line 78

def sort(filename)
  validate_file!(filename)
  lines = open(filename).readlines()
  output = sort_lines(lines)
  write(filename, output)
  puts "Done sorting"
end