Class: DPL::Provider

Inherits:
Object
  • Object
show all
Includes:
FileUtils
Defined in:
lib/dpl/provider.rb

Constant Summary collapse

GEM_NAME_OF =

map of DPL provider class name constants to their corresponding file names. There is no simple rule to map them automatically (camel-cases, snake-cases, call-caps, etc.), so we need an explicit map.

{
  'Anynines'            => 'anynines',
  'Appfog'              => 'appfog',
  'Atlas'               => 'atlas',
  'AzureWebApps'        => 'azure_webapps',
  'Bintray'             => 'bintray',
  'BitBalloon'          => 'bitballoon',
  'BluemixCloudFoundry' => 'bluemix_cloud_foundry',
  'Boxfuse'             => 'boxfuse',
  'Catalyze'            => 'catalyze',
  'ChefSupermarket'     => 'chef_supermarket',
  'Cloud66'             => 'cloud66',
  'CloudFiles'          => 'cloud_files',
  'CloudFoundry'        => 'cloud_foundry',
  'CodeDeploy'          => 'code_deploy',
  'Cargo'               => 'cargo',
  'Deis'                => 'deis',
  'ElasticBeanstalk'    => 'elastic_beanstalk',
  'EngineYard'          => 'engine_yard',
  'Firebase'            => 'firebase',
  'GAE'                 => 'gae',
  'GCS'                 => 'gcs',
  'Hackage'             => 'hackage',
  'Hephy'               => 'hephy',
  'Heroku'              => 'heroku',
  'Lambda'              => 'lambda',
  'Launchpad'           => 'launchpad',
  'Nodejitsu'           => 'nodejitsu',
  'NPM'                 => 'npm',
  'Openshift'           => 'openshift',
  'OpsWorks'            => 'ops_works',
  'Packagecloud'        => 'packagecloud',
  'Pages'               => 'pages',
  'PuppetForge'         => 'puppet_forge',
  'PyPI'                => 'pypi',
  'Releases'            => 'releases',
  'RubyGems'            => 'rubygems',
  'S3'                  => 's3',
  'Scalingo'            => 'scalingo',
  'Script'              => 'script',
  'Snap'                => 'snap',
  'Surge'               => 'surge',
  'TestFairy'           => 'testfairy',
  'Transifex'           => 'transifex',
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context, options) ⇒ Provider

Returns a new instance of Provider.



159
160
161
162
163
164
165
166
# File 'lib/dpl/provider.rb', line 159

def initialize(context, options)
  @context, @options = context, options
  if options.key?(:needs_git_http_user_agent) && !options[:needs_git_http_user_agent]
    context.env.delete 'GIT_HTTP_USER_AGENT'
  else
    context.env['GIT_HTTP_USER_AGENT'] = user_agent(git: `git --version`[/[\d\.]+/])
  end
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



157
158
159
# File 'lib/dpl/provider.rb', line 157

def context
  @context
end

#optionsObject (readonly)

Returns the value of attribute options.



157
158
159
# File 'lib/dpl/provider.rb', line 157

def options
  @options
end

Class Method Details

.apt_get(name, command = name) ⇒ Object



133
134
135
# File 'lib/dpl/provider.rb', line 133

def self.apt_get(name, command = name)
  context.shell("sudo apt-get -qq install #{name}", retry: true) if `which #{command}`.chop.empty?
end

.class_of(filename) ⇒ Object



153
154
155
# File 'lib/dpl/provider.rb', line 153

def self.class_of(filename)
  GEM_NAME_OF.keys.detect { |p| p.to_s.downcase == filename }
end

.contextObject



125
126
127
# File 'lib/dpl/provider.rb', line 125

def self.context
  self
end

.deprecated(*lines) ⇒ Object



117
118
119
120
121
122
123
# File 'lib/dpl/provider.rb', line 117

def self.deprecated(*lines)
  puts ''
  lines.each do |line|
    puts "\e[31;1m#{line}\e[0m"
  end
  puts ''
end

.experimental(name) ⇒ Object



113
114
115
# File 'lib/dpl/provider.rb', line 113

def self.experimental(name)
  puts "", "!!! #{name} support is experimental !!!", ""
end

.new(context, options) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/dpl/provider.rb', line 59

def self.new(context, options)
  return super if self < Provider

  # when requiring the file corresponding to the provider name
  # given in the options, the general strategy is to normalize
  # the option to lower-case alphanumeric, then
  # use that key to find the file name using the GEM_NAME_OF map.

  context.fold("Installing deploy dependencies") do
    begin
      opt_lower = super.option(:provider).to_s.downcase
      opt = opt_lower.gsub(/[^a-z0-9]/, '')
      class_name = class_of(opt)
      raise Error, "could not find provider %p" % opt unless class_name
      require "dpl/provider/#{GEM_NAME_OF[class_name]}"
      provider = const_get(class_name).new(context, options)
    rescue NameError, LoadError => e
      if /uninitialized constant DPL::Provider::(?<provider_wanted>\S+)/ =~ e.message
        provider_gem_name = GEM_NAME_OF[provider_wanted]
      elsif %r(cannot load such file -- dpl/provider/(?<provider_file_name>\S+)) =~ e.message
        provider_gem_name = GEM_NAME_OF[class_name]
      else
        # don't know what to do with this error
        raise e
      end
      install_cmd = "gem install dpl-#{provider_gem_name || opt} -v #{ENV['DPL_VERSION'] || DPL::VERSION}"

      if File.exist?(local_gem = File.join(Dir.pwd, "dpl-#{GEM_NAME_OF[provider_gem_name] || opt_lower}-#{ENV['DPL_VERSION'] || DPL::VERSION}.gem"))
        install_cmd = "gem install #{local_gem}"
      end

      context.shell(install_cmd)
      Gem.clear_paths

      require "dpl/provider/#{GEM_NAME_OF[class_name]}"
      provider = const_get(class_name).new(context, options)
    rescue DPL::Error
      if opt_lower
        provider = const_get(opt.capitalize).new(context, options)
      else
        raise Error, 'missing provider'
      end
    end

    if options[:no_deploy]
      def provider.deploy; end
    else
      provider.install_deploy_dependencies if provider.respond_to? :install_deploy_dependencies
    end

    provider
  end
end

.npm_g(name, command = name) ⇒ Object



149
150
151
# File 'lib/dpl/provider.rb', line 149

def self.npm_g(name, command = name)
  context.shell("npm install -g #{name}", retry: true) if `which #{command}`.chop.empty?
end

.pip(name, command = name, version = nil) ⇒ Object



137
138
139
140
141
142
143
144
145
146
147
# File 'lib/dpl/provider.rb', line 137

def self.pip(name, command = name, version = nil)
  if version
    puts "pip install --user #{name}==#{version}"
    context.shell("pip uninstall --user -y #{name}") unless `which #{command}`.chop.empty?
    context.shell("pip install --user #{name}==#{version}", retry: true)
  else
    puts "pip install --user #{name}"
    context.shell("pip install --user #{name}", retry: true) if `which #{command}`.chop.empty?
  end
  context.shell("export PATH=$PATH:$HOME/.local/bin")
end

.shell(command, options = {}) ⇒ Object



129
130
131
# File 'lib/dpl/provider.rb', line 129

def self.shell(command, options = {})
  system(command)
end

Instance Method Details

#check_appObject



242
243
# File 'lib/dpl/provider.rb', line 242

def check_app
end

#cleanupObject



223
224
225
226
227
228
229
230
231
# File 'lib/dpl/provider.rb', line 223

def cleanup
  return if options[:skip_cleanup]
  context.shell "mv .dpl ~/dpl"
  log "Cleaning up git repository with `git stash --all`. " \
    "If you need build artifacts for deployment, set `deploy.skip_cleanup: true`. " \
    "See https://docs.travis-ci.com/user/deployment#Uploading-Files-and-skip_cleanup."
  context.shell "git stash --all"
  context.shell "mv ~/dpl .dpl"
end

#commit_msgObject



219
220
221
# File 'lib/dpl/provider.rb', line 219

def commit_msg
  @commit_msg ||= %x{git log #{sha} -n 1 --pretty=%B}.strip
end

#create_key(file) ⇒ Object



245
246
247
# File 'lib/dpl/provider.rb', line 245

def create_key(file)
  context.shell "ssh-keygen -t rsa -N \"\" -C #{option(:key_name)} -f #{file}"
end

#default_text_charsetObject



275
276
277
# File 'lib/dpl/provider.rb', line 275

def default_text_charset
  options[:default_text_charset].downcase
end

#default_text_charset?Boolean

Returns:

  • (Boolean)


271
272
273
# File 'lib/dpl/provider.rb', line 271

def default_text_charset?
  options[:default_text_charset]
end

#deployObject



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/dpl/provider.rb', line 181

def deploy
  setup_git_credentials
  rm_rf ".dpl"
  mkdir_p ".dpl"

  context.fold("Preparing deploy") do
    check_auth
    check_app

    if needs_key?
      create_key(".dpl/id_rsa")
      setup_key(".dpl/id_rsa.pub")
      setup_git_ssh(".dpl/git-ssh", ".dpl/id_rsa")
    end

    cleanup
  end

  context.fold("Deploying application") { push_app }

  Array(options[:run]).each do |command|
    if command == 'restart'
      context.fold("Restarting application") { restart }
    else
      context.fold("Running %p" % command) { run(command) }
    end
  end
ensure
  if needs_key?
    remove_key rescue nil
  end
  uncleanup
end

#detect_encoding?Boolean

Returns:

  • (Boolean)


267
268
269
# File 'lib/dpl/provider.rb', line 267

def detect_encoding?
  options[:detect_encoding]
end

#encoding_for(path) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/dpl/provider.rb', line 282

def encoding_for(path)
  file_cmd_output = `file '#{path}'`
  case file_cmd_output
  when /gzip compressed/
    'gzip'
  when /compress'd/
    'compress'
  when /text/
    'text'
  when /data/
    # Shrugs?
  end
end

#error(message) ⇒ Object

Raises:



308
309
310
# File 'lib/dpl/provider.rb', line 308

def error(message)
  raise Error, message
end

#install_deploy_dependenciesObject



279
280
# File 'lib/dpl/provider.rb', line 279

def install_deploy_dependencies
end

#log(message) ⇒ Object



296
297
298
# File 'lib/dpl/provider.rb', line 296

def log(message)
  $stderr.puts(message)
end

#needs_key?Boolean

Returns:

  • (Boolean)


238
239
240
# File 'lib/dpl/provider.rb', line 238

def needs_key?
  true
end

#option(name, *alternatives) ⇒ Object



175
176
177
178
179
# File 'lib/dpl/provider.rb', line 175

def option(name, *alternatives)
  options.fetch(name) do
    alternatives.any? ? option(*alternatives) : raise(Error, "missing #{name}")
  end
end

#run(command) ⇒ Object



304
305
306
# File 'lib/dpl/provider.rb', line 304

def run(command)
  error "running commands not supported"
end

#setup_git_credentialsObject



249
250
251
252
# File 'lib/dpl/provider.rb', line 249

def setup_git_credentials
  context.shell "git config user.email >/dev/null 2>/dev/null || git config user.email `whoami`@localhost"
  context.shell "git config user.name >/dev/null 2>/dev/null || git config user.name `whoami`@localhost"
end

#setup_git_ssh(path, key_path) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/dpl/provider.rb', line 254

def setup_git_ssh(path, key_path)
  key_path = File.expand_path(key_path)
  path     = File.expand_path(path)

  File.open(path, 'w') do |file|
    file.write "#!/bin/sh\n"
    file.write "exec ssh -o StrictHostKeychecking=no -o CheckHostIP=no -o UserKnownHostsFile=/dev/null -i #{key_path} -- \"$@\"\n"
  end

  chmod(0740, path)
  context.env['GIT_SSH'] = path
end

#shaObject



215
216
217
# File 'lib/dpl/provider.rb', line 215

def sha
  @sha ||= context.env['TRAVIS_COMMIT'] || `git rev-parse HEAD`.strip
end

#uncleanupObject



233
234
235
236
# File 'lib/dpl/provider.rb', line 233

def uncleanup
  return if options[:skip_cleanup]
  context.shell "git stash pop"
end

#user_agent(*strings) ⇒ Object



168
169
170
171
172
173
# File 'lib/dpl/provider.rb', line 168

def user_agent(*strings)
  strings.unshift "dpl/#{DPL::VERSION}"
  strings.unshift "travis/0.1.0" if context.env['TRAVIS']
  strings = strings.flat_map { |e| Hash === e ? e.map { |k,v| "#{k}/#{v}" } : e }
  strings.join(" ").gsub(/\s+/, " ").strip
end

#warn(message) ⇒ Object



300
301
302
# File 'lib/dpl/provider.rb', line 300

def warn(message)
  log "\e[31;1m#{message}\e[0m"
end