Class: AmazonStaticSite::Client::Upload

Inherits:
Base
  • Object
show all
Defined in:
lib/amazon_static_site/client/upload.rb

Constant Summary collapse

GZIP_FILES =
/\.(js|css)$/

Instance Attribute Summary

Attributes inherited from Base

#service

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from AmazonStaticSite::Client::Base

Instance Method Details

#filesize(size) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/amazon_static_site/client/upload.rb', line 61

def filesize(size)
  units = ['B', 'KB', 'MB', 'GB', 'TB', 'Pb', 'EB']

  return '0.0 B' if size == 0
  exp = (Math.log(size) / Math.log(1024)).to_i
  exp += 1 if (size.to_f / 1024 ** exp >= 1024 - 0.05)
  exp = 6 if exp > 6 

  '%.1f %s' % [size.to_f / 1024 ** exp, units[exp]]
end

#upload_file(file:, upload_to:, destination:) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/amazon_static_site/client/upload.rb', line 53

def upload_file(file:, upload_to:, destination:)
  aws_options = {
    acl: "public-read",
    content_type: MIME::Types.type_for(file).first&.content_type
  }
  destination.object(upload_to).upload_file(file, aws_options)
end

#upload_to(destination) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/amazon_static_site/client/upload.rb', line 8

def upload_to(destination)
  result = FileList.new(config.folder + "/**/*.*")
  result -= [config.file] # don not upload config file

  puts "Uploading:"

  total_uploaded = 0

  result.each do |file|
    pathname  = Pathname.new(file)
    basename  = pathname.basename
    upload_to = pathname.to_s.gsub(config.folder, "").gsub(/^\//, "")

    size = File.size(file)
    total_uploaded += size

    puts "    #{file}...#{filesize(size)}".green
    upload_file(file: file, upload_to: upload_to, destination: destination)

    if file.downcase =~ GZIP_FILES
      temp_filename = "#{basename}.gz"
      temp          = BetterTempfile.new(temp_filename)
      # gzip file in temp folder
      Zlib::GzipWriter.open(temp.path) do |gz|
        gz.mtime     = File.mtime(file)
        gz.orig_name = temp_filename
        gz.write IO.binread(file)
      end

      size = File.size(temp.path)
      total_uploaded += size

      # print progress
      print "      GZip: #{temp_filename}".dark_green
      print "...#{filesize(size)}\n".green

      upload_file(file: temp.path, upload_to: upload_to + ".gz", destination: destination)
      # delete temp file
      temp.unlink
    end
  end
  puts "Total uploaded: #{filesize(total_uploaded)}"
  result
end