Class: S5::Sync

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(local_path: nil, remote_bucket: nil) ⇒ Sync

Returns a new instance of Sync.



8
9
10
11
12
13
# File 'lib/s5/sync.rb', line 8

def initialize(local_path: nil, remote_bucket: nil)
  raise "You must set local_path argument." unless local_path
  @local_path = local_path.to_s
  @remote_bucket = remote_bucket || AWS.iam.users.first.name + '-s5sync'
  @options = {}
end

Instance Attribute Details

#remote_bucketObject (readonly)

Returns the value of attribute remote_bucket.



2
3
4
# File 'lib/s5/sync.rb', line 2

def remote_bucket
  @remote_bucket
end

Class Method Details

.encrypt_key_pathObject



4
5
6
# File 'lib/s5/sync.rb', line 4

def self.encrypt_key_path
  ENV['HOME'] + '/.s5.key'
end

Instance Method Details

#delete(key) ⇒ Object



15
16
17
18
# File 'lib/s5/sync.rb', line 15

def delete(key)
  (path, s3_key) = generate_path_and_key(key)
  s3_object(s3_key).tap{|o| o.delete }
end

#encrypt!Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/s5/sync.rb', line 20

def encrypt!
  key_path = self.class.encrypt_key_path
  unless File.exists?(key_path)
    File.open(key_path, 'w:BINARY', 0600) do |f|
      f.write OpenSSL::Cipher::AES256.new(:CBC).random_key
    end
  end
  @options[:server_side_encryption] = :aes256
  @options[:encryption_key] = File.binread(key_path)
end

#get(key) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/s5/sync.rb', line 31

def get(key)
  (path, s3_key) = generate_path_and_key(key)
  FileUtils.mkdir_p(File.dirname(path))
  File.open(path, 'wb') do |f|
    f.write s3_object(s3_key).read(@options)
  end
end

#local_listObject



39
40
41
42
43
44
45
46
# File 'lib/s5/sync.rb', line 39

def local_list
  raise unless @local_path
  offset = @local_path.to_s.length + 1
  Hash[Dir.glob(@local_path + '/**/*').to_a.map{|f|
         next unless File.file?(f)
         [f[offset..-1], File.mtime(f)]
       }.compact]
end

#put(key) ⇒ Object



48
49
50
51
# File 'lib/s5/sync.rb', line 48

def put(key)
  (path, s3_key) = generate_path_and_key(key)
  s3_object(s3_key).write(File.binread(path), @options)
end

#remote_listObject



53
54
55
56
57
# File 'lib/s5/sync.rb', line 53

def remote_list
  Hash[s3_objects.to_a.map do |object|
    [object.key, object.last_modified]
  end.sort_by{|o| o.first }]
end

#sync!Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/s5/sync.rb', line 59

def sync!
  local_list = self.local_list
  remote_list = self.remote_list
  need_put = local_list.select do |name, mtime|
    if remote_list[name] && mtime <= remote_list[name]
      remote_list.delete(name)
      false
    else
      true
    end
  end
  need_put.each do |name, mtime|
    self.put name
  end
  remote_list.each do |key, last_modified|
    self.get key
  end
end