webgururobin
7/20/2016 - 9:24 PM

use travis-ci to deploy a middleman app

use travis-ci to deploy a middleman app

task :build do
  puts `bundle exec middleman build`
end

task :sync do
  require 'fog'
  require 'digest'

  path = './build'
  bucket = 'APPNAME.melang.ent.io'
  connection = Fog::Storage.new({
    :provider                             => 'Google',
    :google_storage_access_key_id         => ENV['GOOGLE_STORAGE_ACCESS_KEY_ID'],
    :google_storage_secret_access_key     => ENV['GOOGLE_STORAGE_SECRET_ACCESS_KEY']
  })

  directory = connection.directories.get(bucket)

  files = Dir["#{path}/**/**"].map { |f| f[path.length+1,f.length-path.length] }

  files.each do |f|
    f_path = "#{path}/#{f}"
    if File.file? f_path
      upload = false
      f_etag = "\"#{Digest::MD5.file(f_path).to_s}\""
      if remote_file = directory.files.head(f)
        puts "FILE EXISTS: #{f}"
        puts " - comparing etag: #{remote_file.etag} <==> #{f_etag}"
        unless remote_file.etag == f_etag
          puts " - file changed."
          upload = true
        end
      else
        puts "NEW FILE: #{f}"
        upload = true
      end
      case f
      when /(.html$|.htm$)/
        cache_control = 'public, max-age=300'
      else
        cache_control = 'public, max-age=604800'
      end
      if upload == true
        puts " - uploading #{f}..."
        puts " - cache_control: #{cache_control}"
        file = directory.files.create(
          :key            => f,
          :body           => File.open("#{path}/#{f}"),
          :cache_control  => cache_control,
          :public         => true
        )
        puts " - #{f} uploaded."
      end
    end
  end
end

task :deploy => [:build, :sync] do
  puts "Deployed!"
end