Module: Hoe::Travis

Defined in:
lib/hoe/travis.rb

Overview

The travis plugin for Hoe manages your .travis.yml file for you in a clean and extensible way you can use across projects or by through integration with other Hoe plugins.

Setup

The travis plugin can be used without this setup. By following these instructions you can enable and disable a travis-ci hook for your ruby projects from rake through rake travis:enable and rake travis:disable.

Github API access

Set your github username and password in your ~/.gitconfig:

git config --global github.user username
git config --global github.password password
chmod 600 ~/.gitconfig

Travis token

As of this writing there isn’t an easy way to retrieve the travis token programmatically. You can find your travis token at travis-ci.org/profile underneath your github username and email address.

To set this in your hoerc run rake config_hoe and edit the “token:” entry.

Tasks

You can extend the following tasks in your Rakefile or Hoe plugins to add extra checks to travis-ci.

travis

Run by travis-ci. Defaults to running your tests and checking your manifest file. You can run this locally to check what travis-ci will do.

travis:before

Runs as the before_script on travis-ci. Defaults to installing your development dependencies.

travis:check

Runs travis-lint against your .travis.yml.

travis:edit

Pulls up your .travis.yml in your EDITOR and runs travis-lint upon saving. Does not allow you to save a bad .travis.yml.

travis:generate

Generates a .travis.yml based on your Hoe spec and .hoerc then brings it up in your EDITOR and runs travis-lint upon saving. Does not allow you to save a bad .travis.yml.

travis:enable

Enables the travis hook on github.com. Requires further setup as described below.

travis:disable

Disables the travis hook on github.com. Requires further setup as described below.

travis:force

Forces a travis-ci run, equivalent to clicking the “test” button on the travis-ci hook page.

Hoe Configuration

The Hoe configuration is used to generate the .travis.yml. After you’ve generated a .travis.yml you may any changes you wish to it and the following defaults will not apply. If you have multiple projects, setting up a common custom configuration in ~/.hoerc can save you time.

The following default configuration options are provided under the “travis” key of the Hoe configuration (accessible from Hoe#with_config):

before_script

Array of commands run before the test script. Defaults to installing hoe-travis and its dependencies (rake and hoe) followed by running the travis:before rake task.

script

Runs the travis rake task.

token

Your travis-ci token. See @Setup above

versions

The versions of ruby used to run your tests. Note that if you have multiruby installed, your installed versions will be preferred over the defaults of ruby 1.8.7, 1.9.2 and 1.9.3.

In your .hoerc you may provide a “notifications” key such as:

travis:
  notifications:
    irc: "irc.example#your_channel"

Notifications specified in a .hoerc will override the default email notifications created from the Hoe spec.

Constant Summary collapse

VERSION =

This version of Hoe::Travis

'1.2'
YAML_EXCEPTIONS =

:nodoc:

if defined?(Psych) then # :nodoc:
  if Psych.const_defined? :Exception then
    [Psych::SyntaxError] # Ruby 1.9.2
  else
    [Psych::Exception, Psych::SyntaxError]
  end
else
  [YAML::Error]
end

Instance Method Summary collapse

Instance Method Details

#define_travis_tasksObject

Adds travis tasks to rake



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
214
215
216
217
# File 'lib/hoe/travis.rb', line 152

def define_travis_tasks
  desc "Runs your tests for travis"
  task :travis => %w[test]

  namespace :travis do
    desc "Run by travis-ci after running the default checks"
    task :after => %w[
      travis:fake_config
      check_manifest
    ]

    desc "Run by travis-ci before running the default checks"
    task :before => %w[
      install_plugins
      check_extra_deps
    ]

    desc "Runs travis-lint on your .travis.yml"
    task :check do
      abort unless check_travis_yml '.travis.yml'
    end

    desc "Disables the travis-ci hook"
    task :disable do
      travis_disable
    end

    desc "Brings .travis.yml up in your EDITOR then checks it on save"
    task :edit do
      Tempfile.open 'travis.yml' do |io|
        io.write File.read '.travis.yml'
        io.rewind

        ok = travis_yml_edit io.path

        travis_yml_write io.path if ok
      end
    end

    desc "Enables the travis-ci hook"
    task :enable do
      travis_enable
    end

    desc "Triggers the travis-ci hook"
    task :force do
      travis_force
    end

    task :fake_config do
      travis_fake_config
    end

    desc "Generates a new .travis.yml and allows you to customize it with your EDITOR"
    task :generate do
      Tempfile.open 'travis.yml' do |io|
        io.write travis_yml_generate
        io.rewind

        ok = travis_yml_edit io.path

        travis_yml_write io.path if ok
      end
    end
  end
end

#initialize_travisObject

:nodoc:



145
146
147
# File 'lib/hoe/travis.rb', line 145

def initialize_travis # :nodoc:
  @github_api = URI 'https://api.github.com'
end

#travis_after_scriptObject

Extracts the travis after_script from your .hoerc



222
223
224
225
226
227
# File 'lib/hoe/travis.rb', line 222

def travis_after_script
  with_config { |config, _|
    config['travis']['after_script'] or
      Hoe::DEFAULT_CONFIG['travis']['after_script']
  }
end

#travis_before_scriptObject

Extracts the travis before_script from your .hoerc



232
233
234
235
236
237
# File 'lib/hoe/travis.rb', line 232

def travis_before_script
  with_config { |config, _|
    config['travis']['before_script'] or
      Hoe::DEFAULT_CONFIG['travis']['before_script']
  }
end

#travis_disableObject

Disables travis-ci for this repository.



242
243
244
245
246
247
248
# File 'lib/hoe/travis.rb', line 242

def travis_disable
  _, repo, = travis_github_check

  if hook = travis_have_hook?(repo) then
    travis_edit_hook repo, hook, false if hook['active']
  end
end

#travis_edit_hook(repo, hook, enable = true) ⇒ Object

Edits the travis hook definition for repo (from the github URL) to enable (default) or disable it.



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/hoe/travis.rb', line 254

def travis_edit_hook repo, hook, enable = true
  patch = unless Net::HTTP.const_defined? :Patch then
            # Ruby 1.8
            Class.new Net::HTTPRequest do |c|
              c.const_set :METHOD, 'PATCH'
              c.const_set :REQUEST_HAS_BODY, true
              c.const_set :RESPONSE_HAS_BODY, true
            end
          else
            Net::HTTP::Patch
          end


  id = hook['id']

  body = {
    'name'   => hook['name'],
    'active' => enable,
    'config' => hook['config']
  }

  travis_github_request "/repos/#{repo}/hooks/#{id}", body, patch
end

#travis_enableObject

Enables travis-ci for this repository.



281
282
283
284
285
286
287
288
289
# File 'lib/hoe/travis.rb', line 281

def travis_enable
  user, repo, token = travis_github_check

  if hook = travis_have_hook?(repo) then
    travis_edit_hook repo, hook unless hook['active']
  else
    travis_make_hook repo, user, token
  end
end

#travis_fake_configObject

Creates a fake config file for use on travis-ci. Running this with a pre-existing .hoerc has no effect.



295
296
297
298
299
300
301
302
303
304
305
# File 'lib/hoe/travis.rb', line 295

def travis_fake_config
  fake_hoerc = File.expand_path '~/.hoerc'

  return if File.exist? fake_hoerc

  config = { 'exclude' => /\.(git|travis)/ }

  open fake_hoerc, 'w' do |io|
    YAML.dump config, io
  end
end

#travis_forceObject

Forces the travis-ci hook



310
311
312
313
314
315
316
317
318
# File 'lib/hoe/travis.rb', line 310

def travis_force
  user, repo, token = travis_github_check

  unless hook = travis_have_hook?(repo)
    hook = travis_make_hook repo, user, token
  end

  travis_github_request "/repos/#{repo}/hooks/#{hook['id']}/test", {}
end

#travis_github_checkObject

Ensures you have proper setup for editing the github travis hook



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/hoe/travis.rb', line 323

def travis_github_check
  user = `git config github.user`.chomp
  abort <<-ABORT unless user
Set your github user and token in ~/.gitconfig

See: ri Hoe::Travis and
\thttp://help.github.com/set-your-user-name-email-and-github-token/
  ABORT

  `git config remote.origin.url` =~ /^git@github\.com:(.*).git$/
  repo = $1

  abort <<-ABORT unless repo
Unable to determine your github repository.

Expected \"[email protected]:[repo].git\" as your remote origin
  ABORT

  token = with_config do |config, _|
    config['travis']['token']
  end

  abort 'Please set your travis token via `rake config_hoe` - ' \
        'See: ri Hoe::Travis' if token =~ /FIX/

  return user, repo, token
end

#travis_github_request(path, body = nil, method = body ? Net::HTTP::Post : Net::HTTP::Get) ⇒ Object

Makes a github request at path with an optional body Hash which will be sent as JSON. The default method without a body is a GET request, otherwise POST.



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/hoe/travis.rb', line 356

def travis_github_request(path, body = nil,
                          method = body ? Net::HTTP::Post : Net::HTTP::Get)
  begin
    require 'json'
  rescue LoadError => e
    raise unless e.message.end_with? 'json'

    abort 'Please gem install json like modern ruby versions have'
  end

  uri = @github_api + path

  http = Net::HTTP.new uri.host, uri.port
  http.use_ssl = uri.scheme.downcase == 'https'
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  http.cert_store = OpenSSL::X509::Store.new
  http.cert_store.set_default_paths

  req = method.new uri.request_uri
  if body then
    req.content_type = 'application/json'
    req.body = JSON.dump body
  end

  user = `git config github.user`.chomp
  pass = `git config github.password`.chomp
  req.basic_auth user, pass

  res = http.request req

  body = JSON.parse res.body if res.class.body_permitted?

  unless Net::HTTPSuccess === res then
    message = ": #{res['message']}" if body

    raise "github API error #{res.code}#{message}"
  end

  body
end

#travis_have_hook?(repo) ⇒ Boolean

Returns the github hook definition for the “travis” hook on repo (from the github URL), if it exists.

Returns:

  • (Boolean)


401
402
403
404
405
# File 'lib/hoe/travis.rb', line 401

def travis_have_hook? repo
  body = travis_github_request "/repos/#{repo}/hooks"

  body.find { |hook| hook['name'] == 'travis' }
end

#travis_make_hook(repo, user, token) ⇒ Object

Creates a travis hook for user on the given repo (from the github URL) that uses the users token.



411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/hoe/travis.rb', line 411

def travis_make_hook repo, user, token
  body = {
    "name" => "travis",
    "active" => true,
    "config" => {
      "domain" => "",
      "token" => token,
      "user" => user,
    }
  }

  travis_github_request "/repos/#{repo}/hooks", body
end

#travis_notificationsObject

Creates the travis notifications hash from the developers for your project. The developer will be merged with the travis notifications from your .hoerc.



430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/hoe/travis.rb', line 430

def travis_notifications
  email = @email.compact
  email.delete ''

  default_notifications = { 'email' => email }
  notifications = with_config do |config, _|
    config['travis']['notifications'] or
      Hoe::DEFAULT_CONFIG['travis']['notifications']
  end || {}

  default_notifications.merge notifications
end

#travis_scriptObject

Extracts the travis script from your .hoerc



446
447
448
449
450
451
# File 'lib/hoe/travis.rb', line 446

def travis_script
  with_config { |config, _|
    config['travis']['script'] or
      Hoe::DEFAULT_CONFIG['travis']['script']
  }
end

#travis_versionsObject

Determines the travis versions from multiruby, if available, or your .hoerc.



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/hoe/travis.rb', line 457

def travis_versions
  if have_gem? 'ZenTest' and
     File.exist?(File.expand_path('~/.multiruby')) then
    `multiruby -v` =~ /^Passed: (.*)/

      $1.split(', ').map do |ruby_release|
      ruby_release.sub(/-.*/, '')
    end
  else
    with_config do |config, _|
      config['travis']['versions'] or
        Hoe::DEFAULT_CONFIG['travis']['versions']
    end
  end.sort
end

#travis_yml_check(path) ⇒ Object

Runs travis-lint against the travis.yml in path. If the file is OK true is returned, otherwise the issues are displayed on $stderr and false is returned.



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/hoe/travis.rb', line 478

def travis_yml_check path
  require 'travis/lint'

  travis_yml = YAML.load_file path

  issues = Travis::Lint::Linter.validate travis_yml

  return true if issues.empty?

  issues.each do |issue|
    warn "There is an issue with the key #{issue[:key].inspect}:"
    warn "\t#{issue[:issue]}"
  end

  false
rescue *YAML_EXCEPTIONS => e
  warn "invalid YAML in travis.yml file at #{path}: #{e.message}"

  return false
end

#travis_yml_edit(path) ⇒ Object

Loads the travis.yml in path in your EDITOR (or vi if unset). Upon saving the travis.yml is checked with travis-lint. If any problems are found you will be asked to retry the edit.

If the edited travis.yml is OK true is returned, otherwise false.



506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
# File 'lib/hoe/travis.rb', line 506

def travis_yml_edit path
  loop do
    editor = ENV['EDITOR'] || 'vi'

    system "#{editor} #{path}"

    break true if travis_yml_check path

    abort unless $stdout.tty?

    print "\nRetry edit? [Yn]\n> "
    $stdout.flush

    break false if $stdin.gets =~ /\An/i
  end
end

#travis_yml_generateObject

Generates a travis.yml from .hoerc, the Hoe spec and the default configuration.



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# File 'lib/hoe/travis.rb', line 527

def travis_yml_generate
  travis_yml = {
    'after_script'  => travis_after_script,
    'before_script' => travis_before_script,
    'language'      => 'ruby',
    'notifications' => travis_notifications,
    'rvm'           => travis_versions,
    'script'        => travis_script,
  }

  travis_yml.each do |key, value|
    travis_yml.delete key unless value
  end

  YAML.dump travis_yml
end

#travis_yml_write(source_file) ⇒ Object

Writes the travis.yml in source_file to .travis.yml in the current directory. Overwrites an existing .travis.yml.



548
549
550
551
552
553
554
# File 'lib/hoe/travis.rb', line 548

def travis_yml_write source_file
  open source_file do |source_io|
    open '.travis.yml', 'w' do |dest_io|
      dest_io.write source_io.read
    end
  end
end