diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 00000000..f65cdf0f --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,51 @@ +require: rubocop-performance +require: rubocop-rspec + +Documentation: + Enabled: false +Metrics/ClassLength: + Enabled: false +Style/ClassAndModuleChildren: + Enabled: false +Metrics/LineLength: + Enabled: false +Metrics/MethodLength: + Max: 40 +Style/AsciiComments: + Enabled: false +Metrics/AbcSize: + Enabled: false +Style/GuardClause: + Enabled: false +Style/FormatStringToken: + Enabled: false +Lint/AssignmentInCondition: + Enabled: false +Style/IfUnlessModifier: + Enabled: false +Naming/MemoizedInstanceVariableName: + EnforcedStyleForLeadingUnderscores: required +Style/MultilineBlockChain: + Enabled: false +Lint/ConstantDefinitionInBlock: + Enabled: false +Naming/VariableNumber: + Enabled: false +Metrics/BlockLength: + Enabled: false +Lint/ImplicitStringConcatenation: + Enabled: false +Metrics/MethodLength: + Enabled: false +Style/StructInheritance: + Enabled: false +Lint/RescueException: + Enabled: false +Lint/SuppressedException: + Enabled: false +Naming/MemoizedInstanceVariableName: + Enabled: false +Style/SymbolProc: + Enabled: false +RSpec/MultipleMemoizedHelpers: + Enabled: false \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index cd2f6bab..8983f90d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,29 +1,26 @@ language: ruby cache: bundler +dist: bionic os: - linux rvm: - - jruby - - "2.4" - - "2.5" - - "2.6" - - "2.7" + - "3.2" jobs: include: - - rvm: "2.3" + - rvm: "3.2" before_script: - gem install faraday -v 1.0.1 - os: osx - rvm: "2.5" + rvm: "3.2" - os: osx - rvm: "2.6" + rvm: "3.2" - stage: deploy if: repo = travis-ci/travis.rb and branch = master and type = push os: linux - rvm: "2.6" + rvm: "3.2" deploy: provider: rubygems api_key: diff --git a/Gemfile b/Gemfile index c4311e82..6d94ac01 100644 --- a/Gemfile +++ b/Gemfile @@ -1,4 +1,15 @@ +# frozen_string_literal: true + source 'https://rubygems.org' gemspec +gem 'gh', git: 'https://github.com/travis-ci/gh', branch: 'prd-ruby-upgrade-dev' gem 'rake' +gem 'activesupport', '~> 7.0.6' + +group :development, :test do + gem 'rubocop' + gem 'rubocop-performance' + gem 'rubocop-rspec' + gem 'simplecov-console' +end diff --git a/README.md b/README.md index 54815798..a27dee44 100644 --- a/README.md +++ b/README.md @@ -2066,6 +2066,12 @@ See https://github.com/travis-ci/travis.rb/issues/768#issuecomment-700220351 for ## Version History +### 1.12.0 + +* Upgraded ruby version to 3.2 https://github.com/travis-ci/travis.rb/pull/848 +* Added API Key Reset Capabilities https://github.com/travis-ci/travis.rb/pull/842 +* Fix travis lint issues https://github.com/travis-ci/travis.rb/pull/840 + ### 1.11.1 * Fix `travis sshkey --generate` https://github.com/travis-ci/travis.rb/pull/820 diff --git a/Rakefile b/Rakefile index 447859f1..3fb2842a 100644 --- a/Rakefile +++ b/Rakefile @@ -1,26 +1,27 @@ -# encoding: utf-8 -$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) +# frozen_string_literal: true + +$LOAD_PATH.unshift File.expand_path('lib', __dir__) windows = RUBY_PLATFORM =~ /mswin|mingw/ require 'bundler/gem_tasks' -desc "run specs" -task(:spec) { ruby "-S rspec spec#{" -c" unless windows}" } +desc 'run specs' +task(:spec) { ruby "-S rspec spec#{' -c' unless windows}" } -desc "generate gemspec, update readme" -task :update => :completion do +desc 'generate gemspec, update readme' +task update: :completion do require 'travis/version' content = File.read('travis.gemspec') # fetch data fields = { - :authors => sort_by_commits_alpha(`git shortlog -sn`.b, /[^\d\s].*/).uniq, - :email => sort_by_commits_alpha(`git shortlog -sne`.b, /[^<]+@[^>]+/).uniq, - :files => `git ls-files`.b.split("\n").reject { |f| f =~ /^(\.|Gemfile)/ } + authors: sort_by_commits_alpha(`git shortlog -sn`.b, /[^\d\s].*/).uniq, + email: sort_by_commits_alpha(`git shortlog -sne`.b, /[^<]+@[^>]+/).uniq, + files: `git ls-files`.b.split("\n").reject { |f| f =~ /^(\.|Gemfile)/ } } # :( - fields[:email].delete("konstantin.haase@gmail.com") + fields[:email].delete('konstantin.haase@gmail.com') # insert data fields.each do |field, values| @@ -31,7 +32,7 @@ task :update => :completion do end # set version - content.sub! /(s\.version.*=\s+).*/, "\\1\"#{Travis::VERSION}\"" + content.sub!(/(s\.version.*=\s+).*/, "\\1\"#{Travis::VERSION}\"") # escape unicode content.gsub!(/./) { |c| c.bytesize > 1 ? "\\u{#{c.codepoints.first.to_s(16)}}" : c } @@ -39,12 +40,13 @@ task :update => :completion do File.open('travis.gemspec', 'w') { |f| f << content } readme = File.read('README.md').b - readme.gsub! /^(\s+\$ travis version\n\s+).*$/, "\\1#{Travis::VERSION}" - readme.gsub! /(gem install travis -v )\S+/, "\\1#{Travis::VERSION}" - readme.gsub! /^\*\*#{Regexp.escape(Travis::VERSION)}\*\* \(not yet released?\)\n/i, "**#{Travis::VERSION}** (#{Time.now.strftime("%B %-d, %Y")})\n" + readme.gsub!(/^(\s+\$ travis version\n\s+).*$/, "\\1#{Travis::VERSION}") + readme.gsub!(/(gem install travis -v )\S+/, "\\1#{Travis::VERSION}") + readme.gsub!(/^\*\*#{Regexp.escape(Travis::VERSION)}\*\* \(not yet released?\)\n/i, + "**#{Travis::VERSION}** (#{Time.now.strftime('%B %-d, %Y')})\n") Travis::CLI.commands.each do |c| - readme.sub! /^( \* \[\`#{c.command_name}\`\]\(##{c.command_name}\)).*$/, "\\1 - #{c.description}" + readme.sub!(/^( \* \[`#{c.command_name}`\]\(##{c.command_name}\)).*$/, "\\1 - #{c.description}") end File.write('README.md', readme) @@ -58,13 +60,13 @@ end task 'travis.gemspec' => :update task 'README.md' => :update -task :gemspec => :update -task :default => :spec -task :default => :gemspec unless windows or RUBY_VERSION < '2.0' -task :test => :spec +task gemspec: :update +task default: :spec +task default: :gemspec unless windows || (RUBY_VERSION < '2.0') +task test: :spec def sort_by_commits_alpha(shortlog_output, patt) - shortlog_output.split("\n").sort do |a,b| + shortlog_output.split("\n").sort do |a, b| a_comm, a_name = a.strip.split(/\t/) b_comm, b_name = b.strip.split(/\t/) diff --git a/bin/travis b/bin/travis index bba3e7c4..ab262466 100755 --- a/bin/travis +++ b/bin/travis @@ -1,16 +1,18 @@ #!/usr/bin/env ruby +# frozen_string_literal: true + # :( Encoding.default_external = Encoding::UTF_8 if defined? Encoding # load travis library -require 'bundler/setup' if File.exist? File.expand_path('../../Gemfile', __FILE__) +require 'bundler/setup' if File.exist? File.expand_path('../Gemfile', __dir__) require 'travis/cli' # load plugins -TRAVIS_PLUGINS = [] +TRAVIS_PLUGINS = [].freeze config_path = ENV.fetch('TRAVIS_CONFIG_PATH') { File.expand_path('.travis', Dir.home) } Dir.glob(File.expand_path('*/init.rb', config_path)) do |file| - TRAVIS_PLUGINS << file.sub(config_path + '/', '').sub(/\/init\.rb$/, '') + TRAVIS_PLUGINS << file.sub("#{config_path}/", '').sub(%r{/init\.rb$}, '') load(file) end diff --git a/examples/org_overview.rb b/examples/org_overview.rb index 2c4f94df..5feda432 100644 --- a/examples/org_overview.rb +++ b/examples/org_overview.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis' repos = Travis::Repository.find_all(owner_name: 'travis-ci') repos.each { |repo| puts "#{repo.slug} #{repo.last_build_state}" } diff --git a/examples/pro_auth.rb b/examples/pro_auth.rb index bf13ea29..b1860542 100644 --- a/examples/pro_auth.rb +++ b/examples/pro_auth.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + require 'travis/pro' require 'travis/tools/github' require 'highline/import' # so we can hide the password -github_token = ask("GitHub token: ") +github_token = ask('GitHub token: ') # Set up GitHub tool for doing the login handshake. github = Travis::Tools::Github.new(drop_token: true) do |g| diff --git a/examples/stream.rb b/examples/stream.rb index a1bd07ef..ebb138c8 100644 --- a/examples/stream.rb +++ b/examples/stream.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + require 'travis' Travis.listen do |listener| - listener.on("job:started") { |e| puts "job started for #{e.repository.slug}" } - listener.on("job:finished") { |e| puts "job finished for #{e.repository.slug}" } -end \ No newline at end of file + listener.on('job:started') { |e| puts "job started for #{e.repository.slug}" } + listener.on('job:finished') { |e| puts "job finished for #{e.repository.slug}" } +end diff --git a/lib/travis.rb b/lib/travis.rb index cd100c88..be815b11 100644 --- a/lib/travis.rb +++ b/lib/travis.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + module Travis autoload :Client, 'travis/client' autoload :CLI, 'travis/cli' autoload :Pro, 'travis/pro' autoload :Version, 'travis/version' - include Client::Namespace.new(Client::ORG_URI) + include Client::Namespace.new(Client::COM_URI) end diff --git a/lib/travis/auto_login.rb b/lib/travis/auto_login.rb index 9c9e5015..544e5859 100644 --- a/lib/travis/auto_login.rb +++ b/lib/travis/auto_login.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis' require 'travis/client/auto_login' Travis::Client::AutoLogin.new(Travis).authenticate diff --git a/lib/travis/cli.rb b/lib/travis/cli.rb index c751098c..403413c8 100644 --- a/lib/travis/cli.rb +++ b/lib/travis/cli.rb @@ -1,12 +1,12 @@ +# frozen_string_literal: true + begin require 'travis/client' rescue LoadError => e - if e.message == 'no such file to load -- json' - $stderr.puts "You should either run `gem install json` or upgrade your Ruby version!" - exit 1 - else - raise e - end + raise e unless e.message == 'no such file to load -- json' + + warn 'You should either run `gem install json` or upgrade your Ruby version!' + exit 1 end require 'stringio' @@ -66,11 +66,11 @@ def run(*args) def command(name) const_name = command_name(name) - constant = CLI.const_get(const_name) if const_name =~ /^[A-Z][A-Za-z]+$/ and const_defined? const_name + constant = CLI.const_get(const_name) if const_name =~ (/^[A-Z][A-Za-z]+$/) && const_defined?(const_name) if command? constant constant else - $stderr.puts "unknown command #{name}" + warn "unknown command #{name}" exit 1 end end @@ -80,8 +80,10 @@ def commands end def silent - stderr, $stderr = $stderr, dummy_io - stdout, $stdout = $stdout, dummy_io + stderr = $stderr + $stderr = dummy_io + stdout = $stdout + $stdout = dummy_io yield ensure $stderr = stderr if stderr @@ -90,37 +92,38 @@ def silent private - def try_const_get(name) - CLI.const_get(name) - rescue Exception - end + def try_const_get(name) + CLI.const_get(name) + rescue Exception + end - def dummy_io - return StringIO.new unless defined? IO::NULL and IO::NULL - File.open(IO::NULL, 'w') - end + def dummy_io + return StringIO.new unless defined? IO::NULL && IO::NULL - def command?(constant) - constant.is_a? Class and constant < Command and not constant.abstract? - end + File.open(IO::NULL, 'w') + end + + def command?(constant) + constant.is_a? Class and constant < Command and !constant.abstract? + end - def command_name(name) - case name - when nil, '-h', '-?' then 'Help' - when '-v' then 'Version' - when /^--/ then command_name(name[2..-1]) - else name.split('-').map(&:capitalize).join - end + def command_name(name) + case name + when nil, '-h', '-?' then 'Help' + when '-v' then 'Version' + when /^--/ then command_name(name[2..]) + else name.split('-').map(&:capitalize).join end + end - # can't use flatten as it will flatten hashes - def preparse(unparsed, args = [], opts = {}) - case unparsed - when Hash then opts.merge! unparsed - when Array then unparsed.each { |e| preparse(e, args, opts) } - else args << unparsed.to_s - end - [args, opts] + # can't use flatten as it will flatten hashes + def preparse(unparsed, args = [], opts = {}) + case unparsed + when Hash then opts.merge! unparsed + when Array then unparsed.each { |e| preparse(e, args, opts) } + else args << unparsed.to_s end + [args, opts] + end end end diff --git a/lib/travis/cli/accounts.rb b/lib/travis/cli/accounts.rb index 9ca98f3d..954c8378 100644 --- a/lib/travis/cli/accounts.rb +++ b/lib/travis/cli/accounts.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Accounts < ApiCommand - description "displays accounts and their subscription status" + description 'displays accounts and their subscription status' def run authenticate @@ -13,18 +15,19 @@ def run color(account.login, [color, :bold]), color("(#{account.name || account.login.capitalize}):", color), "#{description(account)},", - account.repos_count == 1 ? "1 repository" : "#{account.repos_count} repositories" - ].join(" ") - end - unless accounts.none?(&:on_trial?) or session.config['host'].nil? - say session.config['host'], "To set up a subscription, please visit %s." + account.repos_count == 1 ? '1 repository' : "#{account.repos_count} repositories" + ].join(' ') end + return if accounts.none?(&:on_trial?) || session.config['host'].nil? + + say session.config['host'], 'To set up a subscription, please visit %s.' end def description(account) - return "subscribed" if account.subscribed? - return "educational account" if account.educational? - "not subscribed" + return 'subscribed' if account.subscribed? + return 'educational account' if account.educational? + + 'not subscribed' end end end diff --git a/lib/travis/cli/api_command.rb b/lib/travis/cli/api_command.rb index ff6e0045..1c950712 100644 --- a/lib/travis/cli/api_command.rb +++ b/lib/travis/cli/api_command.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' require 'travis/tools/github' @@ -7,24 +9,25 @@ class ApiCommand < Command include Travis::Client::Methods attr_accessor :enterprise_name attr_reader :session + abstract on('-e', '--api-endpoint URL', 'Travis API server to talk to') on('-I', '--[no-]insecure', 'do not verify SSL certificate of API endpoint') - on('--pro', "short-cut for --api-endpoint '#{Travis::Client::COM_URI}'") { |c,_| c.api_endpoint = Travis::Client::COM_URI } - on('--com', "short-cut for --api-endpoint '#{Travis::Client::COM_URI}'") { |c,_| c.api_endpoint = Travis::Client::COM_URI } - on('--org', "short-cut for --api-endpoint '#{Travis::Client::ORG_URI}'") { |c,_| c.api_endpoint = Travis::Client::ORG_URI } - on('--staging', 'talks to staging system') { |c,_| c.api_endpoint = c.api_endpoint.gsub(/api/, 'api-staging') } + on('--pro', "short-cut for --api-endpoint '#{Travis::Client::COM_URI}'") { |c, _| c.api_endpoint = Travis::Client::COM_URI } + on('--com', "short-cut for --api-endpoint '#{Travis::Client::COM_URI}'") { |c, _| c.api_endpoint = Travis::Client::COM_URI } + on('--org', "short-cut for --api-endpoint '#{Travis::Client::ORG_URI}'") { |c, _| c.api_endpoint = Travis::Client::ORG_URI } + on('--staging', 'talks to staging system') { |c, _| c.api_endpoint = c.api_endpoint.gsub(/api/, 'api-staging') } on('-t', '--token [ACCESS_TOKEN]', 'access token to use') { |c, t| c.access_token = t } - on('--debug', 'show API requests') do |c,_| + on('--debug', 'show API requests') do |c, _| c.debug = true c.session.instrument do |info, request| c.time(info, request) end end - on('--debug-http', 'show HTTP(S) exchange') do |c,_| + on('--debug-http', 'show HTTP(S) exchange') do |c, _| c.session.debug_http = true end @@ -34,19 +37,17 @@ class ApiCommand < Command on('--adapter ADAPTER', 'Faraday adapter to use for HTTP requests. If omitted, use Typhoeus if it is installed, ' \ 'and Net::HTTP otherwise. See https://lostisland.github.io/faraday/adapters/ for more info') do |c, adapter| - begin - adapter.gsub! '-', '_' - require "faraday/adapter/#{adapter}" - require 'typhoeus/adapters/faraday' if adapter == 'typhoeus' - c.session.faraday_adapter = adapter.to_sym - rescue LoadError => e - warn "\`--adapter #{adapter}\` is given, but it is not installed. Run \`gem install #{adapter}\` and try again" - exit 1 - end + adapter.gsub! '-', '_' + require "faraday/adapter/#{adapter}" + require 'typhoeus/adapters/faraday' if adapter == 'typhoeus' + c.session.faraday_adapter = adapter.to_sym + rescue LoadError + warn "\`--adapter #{adapter}\` is given, but it is not installed. Run \`gem install #{adapter}\` and try again" + exit 1 end def initialize(*) - @session = Travis::Client.new(:agent_info => "command #{command_name}") + @session = Travis::Client.new(agent_info: "command #{command_name}") super end @@ -62,8 +63,8 @@ def setup endpoint_config['access_token'] ||= access_token endpoint_config['insecure'] = insecure unless insecure.nil? self.insecure = endpoint_config['insecure'] - session.ssl = { :verify => false } if insecure? - authenticate if pro? or enterprise? + session.ssl = { verify: false } if insecure? + authenticate if pro? || enterprise? end def enterprise? @@ -90,12 +91,12 @@ def sync(block = true, dot = '.') user.sync steps = count = 1 - while block and user.reload.syncing? + while block && user.reload.syncing? count += 1 sleep(1) - if count % steps == 0 - steps = count/10 + 1 + if (count % steps).zero? + steps = count / 10 + 1 output.print dot end end @@ -103,84 +104,87 @@ def sync(block = true, dot = '.') private - def setup_enterprise - return unless setup_enterprise? - c = config['enterprise'] ||= {} - c[enterprise_name] = api_endpoint if explicit_api_endpoint? - c[enterprise_name] ||= write_to($stderr) do - error "enterprise setup not configured" unless interactive? - user_input = ask(color("Enterprise domain: ", :bold)).to_s - domain = user_input[%r{^(?:https?://)?(.*?)/?(?:/api/?)?$}, 1] - endpoint = "https://#{domain}/api" - config['default_endpoint'] = endpoint if agree("Use #{color domain, :bold} as default endpoint? ") { |q| q.default = 'yes' } - endpoint - end - self.api_endpoint = c[enterprise_name] - self.insecure = insecure unless insecure.nil? - self.session.ssl.delete :ca_file - endpoint_config['enterprise'] = true - @setup_ennterpise = true - end - - def setup_enterprise? - @setup_ennterpise ||= false - !!enterprise_name and not @setup_ennterpise + def setup_enterprise + return unless setup_enterprise? + + c = config['enterprise'] ||= {} + c[enterprise_name] = api_endpoint if explicit_api_endpoint? + c[enterprise_name] ||= write_to($stderr) do + error 'enterprise setup not configured' unless interactive? + user_input = ask(color('Enterprise domain: ', :bold)).to_s + domain = user_input[%r{^(?:https?://)?(.*?)/?(?:/api/?)?$}, 1] + endpoint = "https://#{domain}/api" + config['default_endpoint'] = endpoint if agree("Use #{color domain, :bold} as default endpoint? ") { |q| q.default = 'yes' } + endpoint end + self.api_endpoint = c[enterprise_name] + self.insecure = insecure unless insecure.nil? + session.ssl.delete :ca_file + endpoint_config['enterprise'] = true + @setup_ennterpise = true + end - def load_gh + def setup_enterprise? + @setup_ennterpise ||= false + !!enterprise_name and not @setup_ennterpise + end - gh_config = session.config['github'] - gh_config &&= gh_config.inject({}) { |h,(k,v)| h.update(k.to_sym => v) } - gh_config ||= {} - gh_config[:ssl] = Travis::Client::Session::SSL_OPTIONS - gh_config[:ssl] = { :verify => false } if gh_config[:api_url] and gh_config[:api_url] != "https://api.github.com" - gh_config.delete :scopes + def load_gh + gh_config = session.config['github'] + gh_config &&= gh_config.inject({}) { |h, (k, v)| h.update(k.to_sym => v) } + gh_config ||= {} + gh_config[:ssl] = Travis::Client::Session::SSL_OPTIONS + gh_config[:ssl] = { verify: false } if gh_config[:api_url] && gh_config[:api_url] != 'https://api.github.com' + gh_config.delete :scopes + if debug? gh_config[:instrumenter] = proc do |type, payload, &block| next block.call unless type == 'http.gh' - time("GitHub API: #{payload[:verb].to_s.upcase} #{payload[:url]}", block) - end if debug? - GH.set(gh_config) + time("GitHub API: #{payload[:verb].to_s.upcase} #{payload[:url]}", block) + end end - def github_endpoint - load_gh - GH.with({}).api_host - end + GH.set(gh_config) + end - def listen(*args) - super(*args) do |listener| - on_signal { listener.disconnect } - yield listener - end - end + def github_endpoint + load_gh + GH.with({}).api_host + end - def default_endpoint - ENV['TRAVIS_ENDPOINT'] || config['default_endpoint'] + def listen(*args) + super(*args) do |listener| + on_signal { listener.disconnect } + yield listener end + end - def detected_endpoint - default_endpoint || Travis::Client::ORG_URI - end + def default_endpoint + ENV['TRAVIS_ENDPOINT'] || config['default_endpoint'] + end - def endpoint_option - return "" if org? and detected_endpoint? - return " --org" if org? - return " --pro" if pro? + def detected_endpoint + default_endpoint || Travis::Client::COM_URI + end - if config['enterprise'] - key, _ = config['enterprise'].detect { |k,v| v.start_with? api_endpoint } - return " -X" if key == "default" - return " -X #{key}" if key - end + def endpoint_option + return "" if pro? and detected_endpoint? + return " --org" if org? + return " --pro" if pro? - " -e %p" % api_endpoint + if config['enterprise'] + key, _ = config['enterprise'].detect { |k,v| v.start_with? api_endpoint } + return " -X" if key == "default" + return " -X #{key}" if key end - def fetch_token - ENV['TRAVIS_TOKEN'] || endpoint_config['access_token'] - end + " -e %p" % api_endpoint + end + + def fetch_token + ENV['TRAVIS_TOKEN'] || endpoint_config['access_token'] + end end end end diff --git a/lib/travis/cli/branches.rb b/lib/travis/cli/branches.rb index 16123dbe..25d2aef2 100644 --- a/lib/travis/cli/branches.rb +++ b/lib/travis/cli/branches.rb @@ -1,25 +1,27 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Branches < RepoCommand - description "displays the most recent build for each branch" + description 'displays the most recent build for each branch' def run repository.last_on_branch.each do |build| say [ - color("#{build.branch_info}:".ljust(longest + 2), [:info, :bold]), + color("#{build.branch_info}:".ljust(longest + 2), %i[info bold]), color("##{build.number.to_s.ljust(4)} #{build.state}".ljust(16), build.color), build.commit.subject - ].join(" ").strip + "\n" + ].join(' ').strip + "\n" end end private - def longest - repository.branches.keys.map { |b| b.size }.max - end + def longest + repository.branches.keys.map { |b| b.size }.max + end end end end diff --git a/lib/travis/cli/cache.rb b/lib/travis/cli/cache.rb index e7264292..f09e2dba 100644 --- a/lib/travis/cli/cache.rb +++ b/lib/travis/cli/cache.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis @@ -16,61 +18,63 @@ def run warn "Deleted the following caches:\n" if delete? branches.each { |name, list| display_branch(name, list) } - size = caches.inject(0) { |s,c| s + c.size } - say "Overall size of above caches: " << formatter.file_size(size) + size = caches.inject(0) { |s, c| s + c.size } + say 'Overall size of above caches: ' << formatter.file_size(size) end private - def check_caches - return if caches.any? - say "no caches found" - exit - end + def check_caches + return if caches.any? - def display_branch(name, list) - say color(name ? "On branch #{name}:" : "Global:", :important) - list.each { |c| display_cache(c) } - puts - end + say 'no caches found' + exit + end - def display_cache(cache) - say [ - color(cache.slug.ljust(space), :bold), - "last modified: " << formatter.time(cache.last_modified), - "size: " << formatter.file_size(cache.size) - ].join(" ") << "\n" - end + def display_branch(name, list) + say color(name ? "On branch #{name}:" : 'Global:', :important) + list.each { |c| display_cache(c) } + puts + end - def params - params = {} - params[:branch] = branch if branch? - params[:match] = match if match? - params - end + def display_cache(cache) + say [ + color(cache.slug.ljust(space), :bold), + 'last modified: ' << formatter.time(cache.last_modified), + 'size: ' << formatter.file_size(cache.size) + ].join(' ') << "\n" + end - def caches - @caches ||= drop? ? repository.delete_caches(params) : repository.caches(params) - end + def params + params = {} + params[:branch] = branch if branch? + params[:match] = match if match? + params + end - def space - @space ||= caches.map(&:slug).map(&:size).max - end + def caches + @caches ||= drop? ? repository.delete_caches(params) : repository.caches(params) + end - def drop? - return false unless delete? - return true if force? - error "not deleting caches without --force" unless interactive? - error "aborted" unless danger_zone? "Do you really want to delete #{description}?" - true - end + def space + @space ||= caches.map(&:slug).map(&:size).max + end + + def drop? + return false unless delete? + return true if force? - def description - description = color("all caches", :important) - description << " on branch #{color(branch, :important)}" if branch? - description << " that match #{color(match, :important)}" if match? - description - end + error 'not deleting caches without --force' unless interactive? + error 'aborted' unless danger_zone? "Do you really want to delete #{description}?" + true + end + + def description + description = color('all caches', :important) + description << " on branch #{color(branch, :important)}" if branch? + description << " that match #{color(match, :important)}" if match? + description + end end end end diff --git a/lib/travis/cli/cancel.rb b/lib/travis/cli/cancel.rb index 5e9e09f0..3187a7c5 100644 --- a/lib/travis/cli/cancel.rb +++ b/lib/travis/cli/cancel.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Cancel < RepoCommand - description "cancels a job or build" + description 'cancels a job or build' def run(number = last_build.number) authenticate @@ -11,7 +13,7 @@ def run(number = last_build.number) error "could not find job or build #{repository.slug}##{number}" unless entity entity.cancel - say "canceled", "#{entity.class.one} ##{entity.number} has been %s" + say 'canceled', "#{entity.class.one} ##{entity.number} has been %s" end end end diff --git a/lib/travis/cli/command.rb b/lib/travis/cli/command.rb index 52effbae..8cd8b18b 100644 --- a/lib/travis/cli/command.rb +++ b/lib/travis/cli/command.rb @@ -15,21 +15,23 @@ module CLI class Command MINUTE = 60 HOUR = 3600 - DAY = 86400 - WEEK = 604800 + DAY = 86_400 + WEEK = 604_800 include Tools::Assets - extend Parser, Forwardable, Tools::Assets + extend Tools::Assets + extend Forwardable + extend Parser def_delegators :terminal, :agree, :ask, :choose HighLine.use_color = Tools::System.unix? && $stdout.tty? HighLine.color_scheme = HighLine::ColorScheme.new do |cs| - cs[:command] = [ :bold ] - cs[:error] = [ :red ] - cs[:important] = [ :bold, :underline ] - cs[:success] = [ :green ] - cs[:info] = [ :yellow ] - cs[:debug] = [ :magenta ] + cs[:command] = [:bold] + cs[:error] = [:red] + cs[:important] = %i[bold underline] + cs[:success] = [:green] + cs[:info] = [:yellow] + cs[:debug] = [:magenta] end on('-h', '--help', 'Display help') do |c, _| @@ -37,7 +39,7 @@ class Command exit end - on('-i', '--[no-]interactive', "be interactive and colorful") do |c, v| + on('-i', '--[no-]interactive', 'be interactive and colorful') do |c, v| HighLine.use_color = v if Tools::System.unix? c.force_interactive = v end @@ -65,11 +67,12 @@ def self.skip(*names) def self.description(description = nil) @description = description if description - @description ||= "" + @description ||= '' end def self.subcommands(*list) return @subcommands ||= [] if list.empty? + @subcommands = list define_method :run do |subcommand, *args| @@ -85,7 +88,7 @@ def self.subcommands(*list) attr_accessor :arguments, :config, :force_interactive, :formatter, :debug attr_reader :input, :output - alias_method :debug?, :debug + alias debug? debug def initialize(options = {}) @on_signal = [] @@ -113,7 +116,8 @@ def output=(io) end def write_to(io) - io_was, self.output = output, io + io_was = output + self.output = io yield ensure self.output = io_was if io_was @@ -126,13 +130,12 @@ def parse(args) error e.message end - def setup - end + def setup; end def last_check config['last_check'] ||= { # migrate from old values - 'at' => config.delete('last_version_check'), + 'at' => config.delete('last_version_check'), 'etag' => config.delete('etag') } end @@ -144,38 +147,42 @@ def check_version return if skip_version_check? return if seconds_since < MINUTE - case seconds_since - when MINUTE .. HOUR then timeout = 0.5 - when HOUR .. DAY then timeout = 1.0 - when DAY .. WEEK then timeout = 2.0 - else timeout = 10.0 - end + timeout = case seconds_since + when MINUTE..HOUR then 0.5 + when HOUR..DAY then 1.0 + when DAY..WEEK then 2.0 + else 10.0 + end Timeout.timeout(timeout) do - response = Faraday.get('https://rubygems.org/api/v1/gems/travis.json', {}, 'If-None-Match' => last_check['etag'].to_s) + response = Faraday.get('https://rubygems.org/api/v1/gems/travis.json', {}, + 'If-None-Match' => last_check['etag'].to_s) last_check['etag'] = response.headers['etag'] last_check['version'] = JSON.parse(response.body)['version'] if response.status == 200 end last_check['at'] = Time.now.to_i unless Tools::System.recent_version? Travis::VERSION, last_check['version'] - warn "Outdated CLI version, run `gem install travis`." + warn 'Outdated CLI version, run `gem install travis`.' end - rescue Timeout::Error, Faraday::ClientError => error - debug "#{error.class}: #{error.message}" - rescue JSON::ParserError => error - warn "Unable to determine the most recent travis gem version. http://rubygems.org may be down." + rescue Timeout::Error, Faraday::ClientError => e + debug "#{e.class}: #{e.message}" + rescue JSON::ParserError + warn 'Unable to determine the most recent travis gem version. http://rubygems.org may be down.' end def check_completion - return if skip_completion_check? or !interactive? + return if skip_completion_check? || !interactive? if config['checked_completion'] Tools::Completion.update_completion if config['completion_version'] != Travis::VERSION else write_to($stderr) do next Tools::Completion.update_completion if Tools::Completion.completion_installed? - next unless agree('Shell completion not installed. Would you like to install it now? ') { |q| q.default = "y" } + next unless agree('Shell completion not installed. Would you like to install it now? ') do |q| + q.default = 'y' + end + Tools::Completion.install_completion end end @@ -185,7 +192,8 @@ def check_completion end def check_ruby - return if RUBY_VERSION > '1.9.2' or skip_version_check? + return if (RUBY_VERSION > '1.9.2') || skip_version_check? + warn "Your Ruby version is outdated, please consider upgrading, as we will drop support for #{RUBY_VERSION} soon!" end @@ -202,20 +210,28 @@ def execute store_config rescue Travis::Client::NotLoggedIn => e raise(e) if explode? + error "#{e.message} - try running #{command("login#{endpoint_option}")}" rescue Travis::Client::RepositoryMigrated => e - raise (e) if explode? + raise(e) if explode? + error e.message rescue Travis::Client::NotFound => e raise(e) if explode? + error "resource not found (#{e.message})" rescue Travis::Client::Error => e raise(e) if explode? + error e.message rescue StandardError => e raise(e) if explode? + message = e.message - message += color("\nfor a full error report, run #{command("report#{endpoint_option}")}", :error) if interactive? + if interactive? + message += color("\nfor a full error report, run #{command("report#{endpoint_option}")}", + :error) + end store_error(e) error(message) end @@ -225,7 +241,7 @@ def command_name end def usage - "Usage: " << color(usage_for(command_name, :run), :command) + 'Usage: ' << color(usage_for(command_name, :run), :command) end def usage_for(prefix, method) @@ -239,14 +255,14 @@ def usage_for(prefix, method) usage << " #{name}" end elsif method.arity != 0 - usage << " ..." + usage << ' ...' end - usage << " [OPTIONS]" + usage << ' [OPTIONS]' end - def help(info = "") + def help(info = '') parser.banner = usage - self.class.description.sub(/./) { |c| c.upcase } + ".\n" + info + parser.to_s + "#{self.class.description.sub(/./) { |c| c.upcase }}.\n#{info}#{parser}" end def say(data, format = nil, style = nil) @@ -255,6 +271,7 @@ def say(data, format = nil, style = nil) def debug(line) return unless debug? + write_to($stderr) do say color("** #{line}", :debug) end @@ -262,11 +279,12 @@ def debug(line) def time(info, callback = Proc.new) return callback.call unless debug? + start = Time.now debug(info) callback.call duration = Time.now - start - debug(" took %.2g seconds" % duration) + debug(' took %.2g seconds' % duration) end def info(line) @@ -293,135 +311,145 @@ def error(message, &block) private - def store_error(exception) - message = "An error occurred running `travis %s%s`:\n %p: %s\n" % [command_name, endpoint_option, exception.class, exception.message] - exception.backtrace.each { |l| message << " from #{l}\n" } - save_file("error.log", message) - end + def store_error(exception) + message = format("An error occurred running `travis %s%s`:\n %p: %s\n", command_name, endpoint_option, + exception.class, exception.message) + exception.backtrace.each { |l| message << " from #{l}\n" } + save_file('error.log', message) + end - def clear_error - delete_file("error.log") - end + def clear_error + delete_file('error.log') + end - def setup_trap - [:INT, :TERM].each do |signal| - trap signal do - @on_signal.each { |c| c.call } - exit 1 - end + def setup_trap + %i[INT TERM].each do |signal| + trap signal do + @on_signal.each { |c| c.call } + exit 1 end end + end - def format(data, format = nil, style = nil) - style ||= :important - data = format % color(data, style) if format and interactive? - data = data.gsub(/<\[\[/, '<%=').gsub(/\]\]>/, '%>') - data.encode! 'utf-8' if data.respond_to? :encode! - data - end + def format(data, format = nil, style = nil) + style ||= :important + data = format % color(data, style) if format && interactive? + data = data.gsub(/<\[\[/, '<%=').gsub(/\]\]>/, '%>') + data.encode! 'utf-8' if data.respond_to? :encode! + data + end - def template(*args) - File.read(*args).split('__END__', 2)[1].strip - end + def template(*args) + File.read(*args).split('__END__', 2)[1].strip + end - def color(line, style) - return line.to_s unless interactive? - terminal.color(line || '???', Array(style).map(&:to_sym)) - end + def color(line, style) + return line.to_s unless interactive? - def interactive?(io = output) - return io.tty? if force_interactive.nil? - force_interactive - end + terminal.color(line || '???', Array(style).map(&:to_sym)) + end - def empty_line - say "\n" - end + def interactive?(io = output) + return io.tty? if force_interactive.nil? - def command(name) - color("#{File.basename($0)} #{name}", :command) - end + force_interactive + end - def success(line) - say color(line, :success) if interactive? - end + def empty_line + say "\n" + end - def config_path(name) - path = ENV.fetch('TRAVIS_CONFIG_PATH') { File.expand_path('.travis', Dir.home) } - Dir.mkdir(path, 0700) unless File.directory? path - File.join(path, name) - end + def command(name) + color("#{File.basename($PROGRAM_NAME)} #{name}", :command) + end - def load_file(name, default = nil) - return default unless path = config_path(name) and File.exist? path - debug "Loading %p" % path - File.read(path) - end + def success(line) + say color(line, :success) if interactive? + end - def delete_file(name) - return unless path = config_path(name) and File.exist? path - debug "Deleting %p" % path - File.delete(path) - end + def config_path(name) + path = ENV.fetch('TRAVIS_CONFIG_PATH') { File.expand_path('.travis', Dir.home) } + Dir.mkdir(path, 0o700) unless File.directory? path + File.join(path, name) + end - def save_file(name, content, read_only = false) - path = config_path(name) - debug "Storing %p" % path - File.open(path, 'w') do |file| - file.write(content.to_s) - file.chmod(0600) if read_only - end - end + def load_file(name, default = nil) + return default unless (path = config_path(name)) && File.exist?(path) - YAML_ERROR = defined?(Psych::SyntaxError) ? Psych::SyntaxError : ArgumentError - def load_config - @config = YAML.load load_file('config.yml', '{}') - @config ||= {} - @original_config = @config.dup - rescue YAML_ERROR => error - raise error if explode? - warn "Broken config file: #{color config_path('config.yml'), :bold}" - exit 1 unless interactive? and agree("Remove config file? ") { |q| q.default = "no" } - @original_config, @config = {}, {} - end + debug 'Loading %p' % path + File.read(path) + end - def store_config - save_file('config.yml', @config.to_yaml, true) - end + def delete_file(name) + return unless (path = config_path(name)) && File.exist?(path) - def check_arity(method, *args) - return unless method.respond_to? :parameters - method.parameters.each do |type, name| - return if type == :rest - wrong_args("few") unless args.shift or type == :opt or type == :block - end - wrong_args("many") if args.any? - end + debug 'Deleting %p' % path + File.delete(path) + end - def danger_zone?(message) - agree(color("DANGER ZONE: ", [:red, :bold]) << message << " ") { |q| q.default = "no" } + def save_file(name, content, read_only = false) + path = config_path(name) + debug 'Storing %p' % path + File.open(path, 'w') do |file| + file.write(content.to_s) + file.chmod(0o600) if read_only end + end - def write_file(file, content, force = false) - error "#{file} already exists" unless write_file?(file, force) - File.write(file, content) - end + YAML_ERROR = defined?(Psych::SyntaxError) ? Psych::SyntaxError : ArgumentError + def load_config + @config = YAML.load load_file('config.yml', '{}') + @config ||= {} + @original_config = @config.dup + rescue YAML_ERROR => e + raise e if explode? - def write_file?(file, force) - return true if force or not File.exist?(file) - return false unless interactive? - danger_zone? "Override existing #{color(file, :info)}?" - end + warn "Broken config file: #{color config_path('config.yml'), :bold}" + exit 1 unless interactive? && agree('Remove config file? ') { |q| q.default = 'no' } + @original_config = {} + @config = {} + end - def wrong_args(quantity) - error "too #{quantity} arguments" do - say help - end + def store_config + save_file('config.yml', @config.to_yaml, true) + end + + def check_arity(method, *args) + return unless method.respond_to? :parameters + + method.parameters.each do |type, _name| + return if type == :rest + + wrong_args('few') unless args.shift || (type == :opt) || (type == :block) end + wrong_args('many') if args.any? + end + + def danger_zone?(message) + agree(color('DANGER ZONE: ', %i[red bold]) << message << ' ') { |q| q.default = 'no' } + end - def endpoint_option - "" + def write_file(file, content, force = false) + error "#{file} already exists" unless write_file?(file, force) + File.write(file, content) + end + + def write_file?(file, force) + return true if force || !File.exist?(file) + return false unless interactive? + + danger_zone? "Override existing #{color(file, :info)}?" + end + + def wrong_args(quantity) + error "too #{quantity} arguments" do + say help end + end + + def endpoint_option + '' + end end end end diff --git a/lib/travis/cli/console.rb b/lib/travis/cli/console.rb index e250f797..106777ed 100644 --- a/lib/travis/cli/console.rb +++ b/lib/travis/cli/console.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Console < ApiCommand - description "interactive shell; requires `pry`" + description 'interactive shell; requires `pry`' on '-x', '--eval LINE', 'run line of ruby' do |c, line| c.instance_eval(line) exit @@ -14,8 +16,8 @@ def run Object.send(:include, Client::Namespace.new(session)) hooks = defined?(Pry::Hooks) ? Pry::Hooks.new : {} - opts = {quiet: true, output: $stdout, hooks: hooks } - opts.merge!({prompt: prompt}) if prompt + opts = { quiet: true, output: $stdout, hooks: } + opts.merge!({ prompt: }) if prompt binding.pry(opts) end @@ -37,8 +39,6 @@ def prompt Pry::SIMPLE_PROMPT elsif defined?(Pry::Prompt) Pry::Prompt[:simple] - else - nil end end end diff --git a/lib/travis/cli/disable.rb b/lib/travis/cli/disable.rb index c4b3ae27..1f2a2b74 100644 --- a/lib/travis/cli/disable.rb +++ b/lib/travis/cli/disable.rb @@ -1,14 +1,16 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Disable < RepoCommand - description "disables a project" + description 'disables a project' def run authenticate repository.disable - say "disabled", color("#{slug}: %s :(", :error) + say 'disabled', color("#{slug}: %s :(", :error) end end end diff --git a/lib/travis/cli/enable.rb b/lib/travis/cli/enable.rb index efc3d9d6..94ee504f 100644 --- a/lib/travis/cli/enable.rb +++ b/lib/travis/cli/enable.rb @@ -1,31 +1,33 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Enable < RepoCommand - description "enables a project" + description 'enables a project' on('-s', '--skip-sync', "don't trigger a sync if the repo is unknown") def run authenticate error "not allowed to update service hook for #{color(repository.slug, :bold)}" unless repository.admin? repository.enable - say "enabled", color("#{slug}: %s :)", :success) + say 'enabled', color("#{slug}: %s :)", :success) end private - def repository - repo(slug) - rescue Travis::Client::NotFound - unless skip_sync? - say "repository not known to Travis CI (or no access?)" - say "triggering sync: " - sync - say " done" - end - super + def repository + repo(slug) + rescue Travis::Client::NotFound + unless skip_sync? + say 'repository not known to Travis CI (or no access?)' + say 'triggering sync: ' + sync + say ' done' end + super + end end end end diff --git a/lib/travis/cli/encrypt.rb b/lib/travis/cli/encrypt.rb index 04697b3b..e37f7128 100644 --- a/lib/travis/cli/encrypt.rb +++ b/lib/travis/cli/encrypt.rb @@ -1,38 +1,39 @@ -# encoding: utf-8 +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Encrypt < RepoCommand - description "encrypts values for the .travis.yml" + description 'encrypts values for the .travis.yml' attr_accessor :config_key on('-a', '--add [KEY]', 'adds it to .travis.yml under KEY (default: env.global)') do |c, value| c.config_key = value || 'env.global' end - on('-s', '--[no-]split', "treat each line as a separate input") + on('-s', '--[no-]split', 'treat each line as a separate input') on('-p', '--append', "don't override existing values, instead treat as list") - on('-x', '--override', "override existing value") + on('-x', '--override', 'override existing value') def run(*args) confirm = force_interactive.nil? || force_interactive - error "cannot combine --override and --append" if append? and override? - error "--append without --add makes no sense" if append? and not add? - error "--override without --add makes no sense" if override? and not add? - self.override |= !config_key.start_with?('env.') if add? and not append? + error 'cannot combine --override and --append' if append? && override? + error '--append without --add makes no sense' if append? && !add? + error '--override without --add makes no sense' if override? && !add? + self.override |= !config_key.start_with?('env.') if add? && !append? - if args.first =~ %r{\w+/\w+} && !args.first.include?("=") - warn "WARNING: The name of the repository is now passed to the command with the -r option:" + if args.first =~ %r{\w+/\w+} && !args.first.include?('=') + warn 'WARNING: The name of the repository is now passed to the command with the -r option:' warn " #{command("encrypt [...] -r #{args.first}")}" - warn " If you tried to pass the name of the repository as the first argument, you" + warn ' If you tried to pass the name of the repository as the first argument, you' warn " probably won't get the results you wanted.\n" end - data = args.join(" ") + data = args.join(' ') if data.empty? - say color("Reading from stdin, press Ctrl+D when done", :info) if $stdin.tty? + say color('Reading from stdin, press Ctrl+D when done', :info) if $stdin.tty? data = $stdin.read end @@ -41,69 +42,68 @@ def run(*args) encrypted = data.map { |data| repository.encrypt(data) } if config_key - set_config encrypted.map { |e| { 'secure' => e } } + set_config(encrypted.map { |e| { 'secure' => e } }) confirm_and_save_travis_config confirm else - list = encrypted.map { |data| format(data.inspect, " secure: %s") } + list = encrypted.map { |data| format(data.inspect, ' secure: %s') } say(list.join("\n"), template(__FILE__), :none) end - rescue OpenSSL::PKey::RSAError => error - error "#{error.message.sub(" for key size", "")} - consider using " << - color("travis encrypt-file", [:red, :bold]) << - color(" or ", :red) << - color("travis env set", [:red, :bold]) + rescue OpenSSL::PKey::RSAError => e + error "#{e.message.sub(' for key size', '')} - consider using " << + color('travis encrypt-file', %i[red bold]) << + color(' or ', :red) << + color('travis env set', %i[red bold]) end private - def add? - !!config_key - end + def add? + !!config_key + end - def set_config(result) - parent_config[last_key] = merge_config(result) - end + def set_config(result) + parent_config[last_key] = merge_config(result) + end - def merge_config(result) - case subconfig = (parent_config[last_key] unless override?) - when nil then result.size == 1 ? result.first : result - when Array then subconfig + result - else result.unshift(subconfig) - end + def merge_config(result) + case subconfig = (parent_config[last_key] unless override?) + when nil then result.size == 1 ? result.first : result + when Array then subconfig + result + else result.unshift(subconfig) end + end - def subconfig - end + def subconfig; end - def key_chain - @key_chain ||= config_key.split('.') - end + def key_chain + @key_chain ||= config_key.split('.') + end - def last_key - key_chain.last - end + def last_key + key_chain.last + end - def parent_config - @parent_config ||= traverse_config(travis_config, *key_chain[0..-2]) - end + def parent_config + @parent_config ||= traverse_config(travis_config, *key_chain[0..-2]) + end - def traverse_config(hash, key = nil, *rest) - return hash unless key + def traverse_config(hash, key = nil, *rest) + return hash unless key - hash[key] = case value = hash[key] - when nil then {} - when Hash then value - else { 'matrix' => Array(value) } - end + hash[key] = case value = hash[key] + when nil then {} + when Hash then value + else { 'matrix' => Array(value) } + end - traverse_config(hash[key], *rest) - end + traverse_config(hash[key], *rest) + end - def warn_env_assignments(data) - if /env/.match(config_key) && data.find { |d| /=/.match(d).nil? } - warn "Environment variables in #{config_key} should be formatted as FOO=bar" - end - end + def warn_env_assignments(data) + return unless /env/.match(config_key) && data.find { |d| /=/.match(d).nil? } + + warn "Environment variables in #{config_key} should be formatted as FOO=bar" + end end end end diff --git a/lib/travis/cli/encrypt_file.rb b/lib/travis/cli/encrypt_file.rb index 0b91f801..f1fc0aa1 100644 --- a/lib/travis/cli/encrypt_file.rb +++ b/lib/travis/cli/encrypt_file.rb @@ -1,4 +1,5 @@ -# encoding: utf-8 +# frozen_string_literal: true + require 'travis/cli' require 'travis/tools/system' @@ -11,6 +12,7 @@ module Travis module CLI class EncryptFile < RepoCommand attr_accessor :stage + description 'encrypts a file and adds decryption steps to .travis.yml' on '-K', '--key KEY', 'encryption key to be used (randomly generated otherwise)' on '--iv IV', 'encryption IV to be used (randomly generated otherwise)' @@ -18,7 +20,8 @@ class EncryptFile < RepoCommand on '-f', '--force', 'override output file if it exists' on '-p', '--print-key', 'print (possibly generated) key and iv' on '-w', '--decrypt-to PATH', 'where to write the decrypted file to on the Travis CI VM' - on '-a', '--add [STAGE]', 'automatically add command to .travis.yml (default stage is before_install)' do |c, stage| + on '-a', '--add [STAGE]', + 'automatically add command to .travis.yml (default stage is before_install)' do |c, stage| c.stage = stage || 'before_install' end @@ -37,7 +40,7 @@ def run(input_path, output_path = nil) write_file(output_path, result, force) return if decrypt? - error "requires --decrypt-to option when reading from stdin" unless decrypt_to? + error 'requires --decrypt-to option when reading from stdin' unless decrypt_to? set_env_vars(input_path) @@ -52,8 +55,8 @@ def setup super self.key ||= SecureRandom.hex(32) unless decrypt? self.iv ||= SecureRandom.hex(16) unless decrypt? - error "key must be 64 characters long and a valid hex number" unless key =~ /^[a-f0-9]{64}$/ - error "iv must be 32 characters long and a valid hex number" unless iv =~ /^[a-f0-9]{32}$/ + error 'key must be 64 characters long and a valid hex number' unless key =~ /^[a-f0-9]{64}$/ + error 'iv must be 32 characters long and a valid hex number' unless iv =~ /^[a-f0-9]{32}$/ end def print_command(command) @@ -69,13 +72,15 @@ def store_command(command, confirm) end def decrypt_command(path) - "openssl aes-256-cbc -K $#{env_name(path, :key)} -iv $#{env_name(path, :iv)} -in #{escape_path(path)} -out #{escape_path(decrypt_to)} -d" + "openssl aes-256-cbc -K $#{env_name(path, + :key)} -iv $#{env_name(path, + :iv)} -in #{escape_path(path)} -out #{escape_path(decrypt_to)} -d" end def set_env_vars(input_path) - say "storing secure env variables for decryption" - repository.env_vars.upsert env_name(input_path, :key), key, :public => false - repository.env_vars.upsert env_name(input_path, :iv), iv, :public => false + say 'storing secure env variables for decryption' + repository.env_vars.upsert env_name(input_path, :key), key, public: false + repository.env_vars.upsert env_name(input_path, :iv), iv, public: false end def env_name(input_path, name) @@ -84,20 +89,24 @@ def env_name(input_path, name) end def notes(input_path, output_path) - say "\nkey: #{color(key, :info)}\niv: #{color(iv, :info)}" if print_key? + say "\nkey: #{color(key, :info)}\niv: #{color(iv, :info)}" if print_key? empty_line say "Make sure to add #{color(output_path, :info)} to the git repository." - say "Make sure #{color("not", :underline)} to add #{color(input_path, :info)} to the git repository." if input_path != '-' + if input_path != '-' + say "Make sure #{color('not', + :underline)} to add #{color(input_path, + :info)} to the git repository." + end say "Commit all changes to your #{color('.travis.yml', :info)}." end def transcode(input_path) description = "stdin#{' (waiting for input)' if $stdin.tty?}" if input_path == '-' - say "#{decrypt ? "de" : "en"}crypting #{color(description || input_path, :info)} for #{color(slug, :info)}" + say "#{decrypt ? 'de' : 'en'}crypting #{color(description || input_path, :info)} for #{color(slug, :info)}" data = input_path == '-' ? $stdin.read : File.binread(input_path) aes = OpenSSL::Cipher.new('AES-256-CBC') - decrypt ? aes.decrypt : aes.encrypt + decrypt ? aes.decrypt : aes.encrypt aes.key = [key].pack('H*') aes.iv = [iv].pack('H*') @@ -106,6 +115,7 @@ def transcode(input_path) def decrypt_to_for(input_path) return if input_path == '-' + if input_path.start_with? Dir.home input_path.sub(Dir.home, '~') else @@ -114,18 +124,19 @@ def decrypt_to_for(input_path) end def escape_path(path) - Shellwords.escape(path).sub(/^\\~\//, '~\/') + Shellwords.escape(path).sub(%r{^\\~/}, '~\/') end def output_path_for(input_path) case input_path when '-' then return '-' - when /^(.+)\.enc$/ then return $1 if decrypt? - when /^(.+)\.dec$/ then return $1 unless decrypt? + when /^(.+)\.enc$/ then return ::Regexp.last_match(1) if decrypt? + when /^(.+)\.dec$/ then return ::Regexp.last_match(1) unless decrypt? end - if interactive? and input_path =~ /(\.enc|\.dec)$/ - exit 1 unless danger_zone? "File extension of input file is #{color($1, :info)}, are you sure that is correct?" + if interactive? && input_path =~ /(\.enc|\.dec)$/ && !(danger_zone? "File extension of input file is #{color(::Regexp.last_match(1), + :info)}, are you sure that is correct?") + exit 1 end "#{input_path}.#{decrypt ? 'dec' : 'enc'}" diff --git a/lib/travis/cli/endpoint.rb b/lib/travis/cli/endpoint.rb index c37b6fde..65e23915 100644 --- a/lib/travis/cli/endpoint.rb +++ b/lib/travis/cli/endpoint.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Endpoint < ApiCommand - description "displays or changes the API endpoint" + description 'displays or changes the API endpoint' skip :authenticate on '--drop-default', 'delete stored default endpoint' @@ -11,19 +13,19 @@ class Endpoint < ApiCommand on '--github', 'display github endpoint' def run_github - error "--github cannot be combined with --drop-default" if drop_default? - error "--github cannot be combined with --set-default" if set_default? + error '--github cannot be combined with --drop-default' if drop_default? + error '--github cannot be combined with --set-default' if set_default? load_gh - say github_endpoint.to_s, "GitHub endpoint: %s" + say github_endpoint.to_s, 'GitHub endpoint: %s' end def run_travis - if drop_default? and was = config['default_endpoint'] + if drop_default? && (was = config['default_endpoint']) config.delete('default_endpoint') - say was, "default API endpoint dropped (was %s)" + say was, 'default API endpoint dropped (was %s)' else config['default_endpoint'] = api_endpoint if set_default? - say api_endpoint, "API endpoint: %s#{" (stored as default)" if set_default?}" + say api_endpoint, "API endpoint: %s#{' (stored as default)' if set_default?}" end end diff --git a/lib/travis/cli/env.rb b/lib/travis/cli/env.rb index 6a886448..d619adde 100644 --- a/lib/travis/cli/env.rb +++ b/lib/travis/cli/env.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' require 'shellwords' @@ -5,11 +7,11 @@ module Travis module CLI class Env < RepoCommand on('-P', '--[no-]public', 'make new values public') - on('-p', '--[no-]private', 'make new values private') { |c,v| c.public = !v } + on('-p', '--[no-]private', 'make new values private') { |c, v| c.public = !v } on('-u', '--[no-]unescape', 'do not escape values') on('-f', '--force', 'do not ask for confirmation when clearing out all variables') - description "show or modify build environment variables" + description 'show or modify build environment variables' subcommands :list, :set, :unset, :copy, :clear def setup @@ -19,8 +21,8 @@ def setup end def set(name, value) - options ||= { :public => public } if public != nil - say color('[+] ', [:green, :bold]) + "setting environment variable #{color "$#{name}", :info}" + options ||= { public: } unless public.nil? + say color('[+] ', %i[green bold]) + "setting environment variable #{color "$#{name}", :info}" value = Shellwords.escape(value) unless unescape? env_vars.upsert(name, value, options || {}) end @@ -41,21 +43,24 @@ def unset(*names) def clear exit if env_vars.empty? - exit 1 if interactive? and not force? and not danger_zone? "Clear out all env variables for #{color(repository.slug, :bold)}?" + exit 1 if interactive? && !force? && !danger_zone?("Clear out all env variables for #{color( + repository.slug, :bold + )}?") remove_vars end def remove_vars env_vars.each do |var| - next if block_given? and not yield(var) - say color('[x] ', [:red, :bold]) + "removing environment variable #{color "$#{var.name}", :info}" + next if block_given? && !yield(var) + + say color('[x] ', %i[red bold]) + "removing environment variable #{color "$#{var.name}", :info}" var.delete end end def list say color("# environment variables for #{color repository.slug, :bold}", :info) - env_vars.each { |v| say "#{v.name}=" << color(v.value || "[secure]", :bold) } + env_vars.each { |v| say "#{v.name}=" << color(v.value || '[secure]', :bold) } end def env_vars diff --git a/lib/travis/cli/help.rb b/lib/travis/cli/help.rb index abe4c49f..bae0f5bf 100644 --- a/lib/travis/cli/help.rb +++ b/lib/travis/cli/help.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Help < Command - description "helps you out when in dire need of information" + description 'helps you out when in dire need of information' CommandGroup = Struct.new(:cmds, :header) @@ -22,7 +24,7 @@ def run(command = nil) say " #{color(cmd.command_name, :command).ljust(22)} #{color(cmd.description, :info)}" end end - say "\nrun `#$0 help COMMAND` for more info" + say "\nrun `#{$PROGRAM_NAME} help COMMAND` for more info" end end @@ -33,20 +35,20 @@ def cmd_group_header(title) def api_commands CLI.commands.select do |cmd| cmd.ancestors.include?(CLI::ApiCommand) && - !cmd.ancestors.include?(CLI::RepoCommand) - end.sort_by {|c| c.command_name} + !cmd.ancestors.include?(CLI::RepoCommand) + end.sort_by { |c| c.command_name } end def repo_commands CLI.commands.select do |cmd| cmd.ancestors.include? CLI::RepoCommand - end.sort_by {|c| c.command_name} + end.sort_by { |c| c.command_name } end def other_commands - CLI.commands.select do |cmd| - !cmd.ancestors.include? CLI::ApiCommand - end.sort_by {|c| c.command_name} + CLI.commands.reject do |cmd| + cmd.ancestors.include? CLI::ApiCommand + end.sort_by { |c| c.command_name } end end end diff --git a/lib/travis/cli/history.rb b/lib/travis/cli/history.rb index 81988a60..1d8c3f0c 100644 --- a/lib/travis/cli/history.rb +++ b/lib/travis/cli/history.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis @@ -15,9 +17,10 @@ class History < RepoCommand def run countdown = Integer(limit || 10) unless all? - params = { :after_number => after } if after + params = { after_number: after } if after repository.each_build(params) do |build| next unless display? build + display(build) if countdown @@ -29,21 +32,22 @@ def run private - def display?(build) - return build.pr_number == pull_request.to_i if pull_request - return build.branch_info == branch if branch - true - end + def display?(build) + return build.pr_number == pull_request.to_i if pull_request + return build.branch_info == branch if branch - def display(build) - say [ - date? && color(formatter.time(build.finished_at || build.started_at), build.color), - color("##{build.number} #{build.state}:".ljust(16), [build.color, :bold]), - color("#{build.branch_info}", :info), - committer? && build.commit.author_name.ljust(25), - build.commit.subject - ].compact.join(" ").strip + "\n" - end + true + end + + def display(build) + say [ + date? && color(formatter.time(build.finished_at || build.started_at), build.color), + color("##{build.number} #{build.state}:".ljust(16), [build.color, :bold]), + color(build.branch_info.to_s, :info), + committer? && build.commit.author_name.ljust(25), + build.commit.subject + ].compact.join(' ').strip + "\n" + end end end end diff --git a/lib/travis/cli/init.rb b/lib/travis/cli/init.rb index 21036280..bb041f74 100644 --- a/lib/travis/cli/init.rb +++ b/lib/travis/cli/init.rb @@ -1,18 +1,20 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Init < Enable LANGUAGE_MAPPING = { - "node" => "node_js", - "node.js" => "node_js", - "javascript" => "node_js", - "coffeescript" => "node_js", - "c++" => "cpp", - "obj-c" => "objective-c" - } + 'node' => 'node_js', + 'node.js' => 'node_js', + 'javascript' => 'node_js', + 'coffeescript' => 'node_js', + 'c++' => 'cpp', + 'obj-c' => 'objective-c' + }.freeze - description "generates a .travis.yml and enables the project" + description 'generates a .travis.yml and enables the project' on('-f', '--force', 'override .travis.yml if it already exists') on('-k', '--skip-enable', 'do not enable project, only add .travis.yml') @@ -25,7 +27,8 @@ class Init < Enable ] options.each do |option| - on "--#{option.gsub('_', '-')} VALUE", "sets #{option} option in .travis.yml (can be used more than once)" do |c, value| + on "--#{option.gsub('_', '-')} VALUE", + "sets #{option} option in .travis.yml (can be used more than once)" do |c, value| c.custom_config[option] &&= Array(c.custom_config[option]) << value c.custom_config[option] ||= value end @@ -39,11 +42,11 @@ def self.languages end def help - super("Available languages: #{self.class.languages.join(", ")}\n\n") + super("Available languages: #{self.class.languages.join(', ')}\n\n") end def run(language = nil, file = '.travis.yml') - error "#{file} already exists, use --force to override" if File.exist?(file) and not force? and not print_conf? + error "#{file} already exists, use --force to override" if File.exist?(file) && !force? && !print_conf? language ||= ask('Main programming language used: ') { |q| q.default = detect_language } self.travis_config = template(language).merge(custom_config) @@ -63,21 +66,21 @@ def custom_config private - def template_name(language) - asset_path("init/#{language}.yml") - end + def template_name(language) + asset_path("init/#{language}.yml") + end - def template(language) - language = language.to_s.downcase - language = LANGUAGE_MAPPING[language] || language - file = template_name(language) - error "unknown language #{language}" unless File.exist? file - YAML.load_file(file) - end + def template(language) + language = language.to_s.downcase + language = LANGUAGE_MAPPING[language] || language + file = template_name(language) + error "unknown language #{language}" unless File.exist? file + YAML.load_file(file) + end - def detect_language - repository.github_language || "Ruby" - end + def detect_language + repository.github_language || 'Ruby' + end end end end diff --git a/lib/travis/cli/lint.rb b/lib/travis/cli/lint.rb index 2e5f1bc2..2f43141c 100644 --- a/lib/travis/cli/lint.rb +++ b/lib/travis/cli/lint.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' require 'yaml' @@ -9,15 +11,15 @@ class Lint < ApiCommand on '-x', '--[no-]exit-code', 'sets the exit code to 1 if there are warning' def run(file = nil) - file ||= '.travis.yml' if $stdin.tty? or $stdin.eof? + file ||= '.travis.yml' if $stdin.tty? || $stdin.eof? - if file and file != '-' + if file && (file != '-') debug "reading #{file}" error "file does not exist: #{color(file, :bold)}" unless File.exist? file error "cannot read #{color(file, :bold)}" unless File.readable? file content = File.read(file) else - debug "reading stdin" + debug 'reading stdin' file = 'STDIN' content = $stdin.read end @@ -32,24 +34,24 @@ def run(file = nil) unless quiet? if lint.ok? - say "valid", color("Hooray, #{file} looks %s :)", :success) + say 'valid', color("Hooray, #{file} looks %s :)", :success) else say "Warnings for #{color(file, :info)}:" lint.warnings.each do |warning| - say color('[x]', [:red, :bold]) + " " + say "#{color('[x]', %i[red bold])} " if warning.key.any? say [ color('in ', :info), - color(warning.key.join('.'), [:info, :bold, :underline]), + color(warning.key.join('.'), %i[info bold underline]), color(' section:', :info), ' ' ].join end - say warning.message.gsub(/"(.*?)"/) { color($1, [:info, :important]) } + say warning.message.gsub(/"(.*?)"/) { color(::Regexp.last_match(1), %i[info important]) } end end end - exit 1 if lint.warnings? and exit_code? + exit 1 if lint.warnings? && exit_code? end end end diff --git a/lib/travis/cli/login.rb b/lib/travis/cli/login.rb index 982a6a13..9b4b842b 100644 --- a/lib/travis/cli/login.rb +++ b/lib/travis/cli/login.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' require 'travis/tools/github' require 'json' @@ -7,16 +9,17 @@ module CLI class Login < ApiCommand skip :authenticate - description "authenticates against the API and stores the token" + description 'authenticates against the API and stores the token' on('-g', '--github-token TOKEN', 'identify by GitHub token') - on('-T', '--auto-token', 'try to figure out who you are automatically (might send another apps token to Travis, token will not be stored)') + on('-T', '--auto-token', + 'try to figure out who you are automatically (might send another apps token to Travis, token will not be stored)') on('--list-github-token', 'instead of actually logging in, list found GitHub tokens') on('--skip-token-check', 'don\'t verify the token with github') attr_accessor :user_login def list_token - github.after_tokens = proc { } + github.after_tokens = proc {} github.each_token do |token| say token end @@ -26,7 +29,10 @@ def login session.access_token = nil github.with_token do |token| endpoint_config['access_token'] = github_auth(token) - error("user mismatch: logged in as %p instead of %p" % [user.login, user_login]) if user_login and user.login != user_login + if user_login && (user.login != user_login) + error(format('user mismatch: logged in as %p instead of %p', user.login, + user_login)) + end unless user.correct_scopes? error( "#{user.login} has not granted Travis CI the required permissions. " \ @@ -37,9 +43,9 @@ def login success("Successfully logged in as #{user.login}!") end - unless session.access_token - raise Travis::Client::GitHubLoginFailed, "all GitHub tokens given were invalid" - end + return if session.access_token + + raise Travis::Client::GitHubLoginFailed, 'all GitHub tokens given were invalid' end def run @@ -58,15 +64,15 @@ def github g.drop_token = !list_github_token g.login_header = proc { login_header } g.debug = proc { |log| debug(log) } - g.after_tokens = proc { g.explode = true and error("no suitable github token found") } + g.after_tokens = proc { g.explode = true and error('no suitable github token found') } end end end def login_header - say "GitHub deprecated its Authorizations API exchanging a password for a token." - say "Please visit https://github.blog/2020-07-30-token-authentication-requirements-for-api-and-git-operations for more information." - say "Try running with #{color("--github-token", :info)} or #{color("--auto-token", :info)} ." + say 'GitHub deprecated its Authorizations API exchanging a password for a token.' + say 'Please visit https://github.blog/2020-07-30-token-authentication-requirements-for-api-and-git-operations for more information.' + say "Try running with #{color('--github-token', :info)} or #{color('--auto-token', :info)} ." end end end diff --git a/lib/travis/cli/logout.rb b/lib/travis/cli/logout.rb index 5a62d7de..3e0f30ba 100644 --- a/lib/travis/cli/logout.rb +++ b/lib/travis/cli/logout.rb @@ -1,14 +1,16 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Logout < ApiCommand - description "deletes the stored API token" + description 'deletes the stored API token' def run session.logout endpoint_config.delete('access_token') - success("Successfully logged out!") + success('Successfully logged out!') end end end diff --git a/lib/travis/cli/logs.rb b/lib/travis/cli/logs.rb index 9cc2b689..b12fb322 100644 --- a/lib/travis/cli/logs.rb +++ b/lib/travis/cli/logs.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' require 'travis/tools/safe_string' require 'travis/tools/system' @@ -6,8 +8,12 @@ module Travis module CLI class Logs < RepoCommand attr_accessor :delete, :reason - description "streams test logs" - on('-d', '--delete [REASON]', 'remove logs') { |c, reason| c.delete, c.reason = true, reason } + + description 'streams test logs' + on('-d', '--delete [REASON]', 'remove logs') do |c, reason| + c.delete = true + c.reason = reason + end on('-f', '--force', 'do not ask user to confirm deleting the logs') on('--[no-]stream', 'only print current logs, do not stream') @@ -25,17 +31,19 @@ def run(number = last_build.number) def delete_log(job) unless force? - error "not deleting logs without --force" unless interactive? - error "aborted" unless danger_zone? "Do you really want to delete the build log for #{color(job.inspect_info, :underline)}?" + error 'not deleting logs without --force' unless interactive? + error 'aborted' unless danger_zone? "Do you really want to delete the build log for #{color(job.inspect_info, + :underline)}?" end - warn "deleting log for #{color(job.inspect_info, [:bold, :info])}" + warn "deleting log for #{color(job.inspect_info, %i[bold info])}" job.delete_log(reason || {}) end def display_log(job) - info "displaying logs for #{color(job.inspect_info, [:bold, :info])}" + info "displaying logs for #{color(job.inspect_info, %i[bold info])}" return print_log(job.log.body) unless stream? + job.log.body { |part| print_log(part) } ensure print "\e[0m" if interactive? @@ -47,19 +55,20 @@ def print_log(part) private - def job(number) - number = last_build.number + number if number.start_with? '.' - job = super(number) || build(number) || branch(number) - job = job.jobs.first if job.respond_to? :jobs - job - end + def job(number) + number = last_build.number + number if number.start_with? '.' + job = super(number) || build(number) || branch(number) + job = job.jobs.first if job.respond_to? :jobs + job + end - def check_websocket - require 'websocket-native' if stream? - rescue LoadError => e - raise e if e.respond_to?(:path) and e.path != 'websocket-native' - info "speed up log streaming by installing the websocket-native gem" - end + def check_websocket + require 'websocket-native' if stream? + rescue LoadError => e + raise e if e.respond_to?(:path) && (e.path != 'websocket-native') + + info 'speed up log streaming by installing the websocket-native gem' + end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/monitor.rb b/lib/travis/cli/monitor.rb index d6535c26..5f2bafb2 100644 --- a/lib/travis/cli/monitor.rb +++ b/lib/travis/cli/monitor.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' require 'travis/tools/notification' @@ -9,10 +11,10 @@ class Monitor < ApiCommand on('-r', '--repo SLUG', 'monitor given repository (can be used more than once)') do |c, slug| c.repos << slug - c.send(:error, "SLUG should be of the form OWNER/REPO") unless slug.split('/').compact.size == 2 + c.send(:error, 'SLUG should be of the form OWNER/REPO') unless slug.split('/').compact.size == 2 end - types = Tools::Notification::DEFAULT.map(&:to_s).join(", ") + types = Tools::Notification::DEFAULT.map(&:to_s).join(', ') on('-n', '--[no-]notify [TYPE]', "send out desktop notifications (optional type: #{types})") do |c, type| c.setup_notification(type) end @@ -75,6 +77,7 @@ def all? def monitor?(entity) return true if all? + entity.pull_request? ? pull? : push? end @@ -84,26 +87,26 @@ def display(entity, time) color(entity.inspect_info, [entity.color, :bold]), color(entity.state, entity.color), color(entity.commit.subject, entity.color) - ].join(" ") + ].join(' ') notification.notify(entity.repository.slug, [ entity.class.name[/[^:]+$/], entity.number, - entity.state + ":", + "#{entity.state}:", entity.commit.subject - ].join(" ")) + ].join(' ')) end def handle_event(event) entity = event.job || event.build time = entity.finished_at || entity.started_at display(entity, time) if monitor? entity - rescue Travis::Client::Error => error - raise error if explode? + rescue Travis::Client::Error => e + raise e if explode? end def run listen(*repos) do |listener| - listener.on_connect { say description, "Monitoring #{"builds for " if builds?}%s:" } + listener.on_connect { say description, "Monitoring #{'builds for ' if builds?}%s:" } listener.on(*events) { |e| handle_event(e) } end end diff --git a/lib/travis/cli/open.rb b/lib/travis/cli/open.rb index 6f12dc87..91208cbc 100644 --- a/lib/travis/cli/open.rb +++ b/lib/travis/cli/open.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + require 'travis/cli' require 'launchy' module Travis module CLI class Open < RepoCommand - description "opens a build or job in the browser" + description 'opens a build or job in the browser' on('-g', '--github', 'Open the corresponding project, compare view or pull request on GitHub') on('-p', '--print', 'Print out the URL instead of opening it in a browser') @@ -12,7 +14,7 @@ class Open < RepoCommand def run(number = nil) url = url_for(number) if print? - say url, "web view: %s" + say url, 'web view: %s' else Launchy.open(url) end @@ -20,20 +22,21 @@ def run(number = nil) private - def url_for(number) - return repo_url unless number - entity = job(number) || build(number) - error "could not find job or build #{repository.slug}##{number}" unless entity - github ? entity.commit.compare_url : "#{repo_url}/#{entity.class.many}/#{entity.id}" - end + def url_for(number) + return repo_url unless number - def repo_url - "https://#{host}/#{slug}" - end + entity = job(number) || build(number) + error "could not find job or build #{repository.slug}##{number}" unless entity + github ? entity.commit.compare_url : "#{repo_url}/#{entity.class.many}/#{entity.id}" + end - def host - github ? "github.com" : session.config['host'] - end + def repo_url + "https://#{host}/#{slug}" + end + + def host + github ? 'github.com' : session.config['host'] + end end end end diff --git a/lib/travis/cli/parser.rb b/lib/travis/cli/parser.rb index 16170d37..885fe544 100644 --- a/lib/travis/cli/parser.rb +++ b/lib/travis/cli/parser.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' require 'optparse' diff --git a/lib/travis/cli/pubkey.rb b/lib/travis/cli/pubkey.rb index 38b004fb..6685c2aa 100644 --- a/lib/travis/cli/pubkey.rb +++ b/lib/travis/cli/pubkey.rb @@ -1,13 +1,15 @@ -# encoding: utf-8 +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Pubkey < RepoCommand attr_accessor :key_format + description "prints out a repository's public key" - on('-p', '--pem', 'encode in format used by pem') { |c,_| c.key_format = :pem } - on('-f', '--fingerprint', 'display fingerprint') { |c,_| c.key_format = :fingerprint } + on('-p', '--pem', 'encode in format used by pem') { |c, _| c.key_format = :pem } + on('-f', '--fingerprint', 'display fingerprint') { |c, _| c.key_format = :fingerprint } def run error "#{key_format} format not supported by #{api_endpoint}" unless key @@ -16,15 +18,15 @@ def run private - def key - key = repository.public_key - case self.key_format ||= :ssh - when :fingerprint then key.fingerprint - when :pem then key.to_s - when :ssh then key.to_ssh - else raise "unknown format #{key_format}" - end + def key + key = repository.public_key + case self.key_format ||= :ssh + when :fingerprint then key.fingerprint + when :pem then key.to_s + when :ssh then key.to_ssh + else raise "unknown format #{key_format}" end + end end end end diff --git a/lib/travis/cli/raw.rb b/lib/travis/cli/raw.rb index 512d6ab0..6ff0b1d6 100644 --- a/lib/travis/cli/raw.rb +++ b/lib/travis/cli/raw.rb @@ -1,10 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' -require 'pp' module Travis module CLI class Raw < ApiCommand - description "makes an (authenticated) API call and prints out the result" + description 'makes an (authenticated) API call and prints out the result' skip :authenticate on('--[no-]json', 'display as json') @@ -13,7 +14,7 @@ def run(resource) reply = session.get_raw(resource) json? ? say(reply.to_json) : pp(reply) rescue Travis::Client::NotFound - error "resource not found" + error 'resource not found' end end end diff --git a/lib/travis/cli/repo_command.rb b/lib/travis/cli/repo_command.rb index 20887988..cba89cdf 100644 --- a/lib/travis/cli/repo_command.rb +++ b/lib/travis/cli/repo_command.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' require 'yaml' @@ -9,7 +11,7 @@ class RepoCommand < ApiCommand on('-g', '--github-token TOKEN', 'identify by GitHub token') on('-r', '--repo SLUG', 'repository to use (will try to detect from current git clone)') do |c, slug| c.slug = slug - c.error "SLUG should be of the form OWNER/REPO" unless slug.split('/').compact.size == 2 + c.error 'SLUG should be of the form OWNER/REPO' unless slug.split('/').compact.size == 2 end on('-R', '--store-repo SLUG', 'like --repo, but remembers value for current directory') do |c, slug| c.slug = slug @@ -17,12 +19,15 @@ class RepoCommand < ApiCommand end attr_accessor :slug + abstract def setup setup_enterprise - error "Can't figure out GitHub repo name. Ensure you're in the repo directory, or specify the repo name via the -r option (e.g. travis -r /)" unless self.slug ||= find_slug - error "GitHub repo name is invalid, it should be of the form 'owner/repo'" unless self.slug.include?("/") + unless self.slug ||= find_slug + error "Can't figure out GitHub repo name. Ensure you're in the repo directory, or specify the repo name via the -r option (e.g. travis -r /)" + end + error "GitHub repo name is invalid, it should be of the form 'owner/repo'" unless self.slug.include?('/') self.api_endpoint = detect_api_endpoint super repository.load # makes sure we actually have access to the repo @@ -36,140 +41,146 @@ def repository private - def build(number_or_id) - return super if number_or_id.is_a? Integer - repository.build(number_or_id) - end + def build(number_or_id) + return super if number_or_id.is_a? Integer - def job(number_or_id) - return super if number_or_id.is_a? Integer - repository.job(number_or_id) - end + repository.build(number_or_id) + end - def branch(name) - repository.branch(name) - end + def job(number_or_id) + return super if number_or_id.is_a? Integer - def last_build - repository.last_build or error("no build yet for #{slug}") - end + repository.job(number_or_id) + end - def detected_endpoint? - !explicit_api_endpoint? - end + def branch(name) + repository.branch(name) + end - def find_slug - load_slug || begin - slug = detect_slug - interactive? ? store_slug(slug) : slug if slug - end - end + def last_build + repository.last_build or error("no build yet for #{slug}") + end + + def detected_endpoint? + !explicit_api_endpoint? + end - def detect_slug - git_head = `git name-rev --name-only HEAD 2>#{IO::NULL}`.chomp - git_remote = `git config --get branch.#{git_head}.remote 2>#{IO::NULL}`.chomp - git_remote = 'origin' if git_remote.empty? - git_info = `git ls-remote --get-url #{git_remote} 2>#{IO::NULL}`.chomp - - if parse_remote(git_info) =~ GIT_REGEX - detected_slug = $1 - if interactive? - if agree("Detected repository as #{color(detected_slug, :info)}, is this correct? ") { |q| q.default = 'yes' } - detected_slug - else - ask("Repository slug (owner/name): ") { |q| q.default = detected_slug } - end - else - info "detected repository as #{color(detected_slug, :bold)}" - detected_slug - end + def find_slug + load_slug || begin + slug = detect_slug + if slug + interactive? ? store_slug(slug) : slug end end + end + + def detect_slug + git_head = `git name-rev --name-only HEAD 2>#{IO::NULL}`.chomp + git_remote = `git config --get branch.#{git_head}.remote 2>#{IO::NULL}`.chomp + git_remote = 'origin' if git_remote.empty? + git_info = `git ls-remote --get-url #{git_remote} 2>#{IO::NULL}`.chomp + + return unless parse_remote(git_info) =~ GIT_REGEX - def parse_remote(url) - if url =~ /^git@[^:]+:/ - path = url.split(':').last - path = "/#{path}" unless path.start_with?('/') - path + detected_slug = ::Regexp.last_match(1) + if interactive? + if agree("Detected repository as #{color(detected_slug, :info)}, is this correct? ") do |q| + q.default = 'yes' + end + detected_slug else - URI.parse(url).path + ask('Repository slug (owner/name): ') { |q| q.default = detected_slug } end + else + info "detected repository as #{color(detected_slug, :bold)}" + detected_slug end + end - def load_slug - stored = `git config --get travis.slug`.chomp - stored unless stored.empty? + def parse_remote(url) + if url =~ /^git@[^:]+:/ + path = url.split(':').last + path = "/#{path}" unless path.start_with?('/') + path + else + URI.parse(url).path end + end - def store_slug(value) - `git config travis.slug #{value}` if value - value - end + def load_slug + stored = `git config --get travis.slug`.chomp + stored unless stored.empty? + end - def repo_config - config['repos'] ||= {} - config['repos'][slug] ||= {} - end + def store_slug(value) + `git config travis.slug #{value}` if value + value + end - def detect_api_endpoint - if explicit_api_endpoint? or enterprise? - repo_config['endpoint'] = api_endpoint - elsif ENV['TRAVIS_ENDPOINT'] - ENV['TRAVIS_ENDPOINT'] - elsif config['default_endpoint'] and config['default_endpoint'] !~ TRAVIS - repo_config['endpoint'] ||= config['default_endpoint'] - else - repo_config['endpoint'] ||= begin - load_gh - GH.head("/repos/#{slug}") - Travis::Client::ORG_URI - rescue GH::Error - Travis::Client::COM_URI - end - end - end + def repo_config + config['repos'] ||= {} + config['repos'][slug] ||= {} + end - def travis_config - @travis_config ||= begin - payload = YAML.load_file(travis_yaml) - payload.respond_to?(:to_hash) ? payload.to_hash : {} + def detect_api_endpoint + if explicit_api_endpoint? || enterprise? + repo_config['endpoint'] = api_endpoint + elsif ENV['TRAVIS_ENDPOINT'] + ENV['TRAVIS_ENDPOINT'] + elsif config['default_endpoint'] && config['default_endpoint'] !~ (TRAVIS) + repo_config['endpoint'] ||= config['default_endpoint'] + else + repo_config['endpoint'] ||= begin + load_gh + GH.head("/repos/#{slug}") + Travis::Client::ORG_URI + rescue GH::Error + Travis::Client::COM_URI end end + end - def travis_yaml(dir = Dir.pwd) - path = File.expand_path('.travis.yml', dir) - if File.exist? path - path - else - parent = File.expand_path('..', dir) - error "no .travis.yml found" if parent == dir - travis_yaml(parent) - end + def travis_config + @travis_config ||= begin + payload = YAML.load_file(travis_yaml) + payload.respond_to?(:to_hash) ? payload.to_hash : {} end + end - def confirm_and_save_travis_config(confirm = true, file = travis_yaml) - if confirm - ans = ask [ - nil, - color("Overwrite the config file #{travis_yaml} with the content below?", [:info, :yellow]), - color("This reformats the existing file.", [:info, :red]), - travis_config.to_yaml, - color("(y/N)", [:info, :yellow]) - ].join("\n\n") - proceed = ans =~ /^y/i - else - proceed = true - end - - save_travis_config if proceed + def travis_yaml(dir = Dir.pwd) + path = File.expand_path('.travis.yml', dir) + if File.exist? path + path + else + parent = File.expand_path('..', dir) + error 'no .travis.yml found' if parent == dir + travis_yaml(parent) end + end - def save_travis_config(file = travis_yaml) - yaml = travis_config.to_yaml - yaml.gsub! /^(\s+)('on'|true):/, "\\1on:" - yaml.gsub! /\A---\s*\n/, '' - File.write(file, yaml) - end + def confirm_and_save_travis_config(confirm = true, _file = travis_yaml) + if confirm + ans = ask [ + nil, + color("Overwrite the config file #{travis_yaml} with the content below?", %i[info yellow]), + color('This reformats the existing file.', %i[info red]), + travis_config.to_yaml, + color('(y/N)', %i[info yellow]) + ].join("\n\n") + proceed = ans =~ /^y/i + else + proceed = true + end + + save_travis_config if proceed + end + + def save_travis_config(file = travis_yaml) + yaml = travis_config.to_yaml + yaml.gsub!(/^(\s+)('on'|true):/, '\\1on:') + yaml.gsub!(/\A---\s*\n/, '') + File.write(file, yaml) + end end end end diff --git a/lib/travis/cli/report.rb b/lib/travis/cli/report.rb index 16dffa59..30aa33ae 100644 --- a/lib/travis/cli/report.rb +++ b/lib/travis/cli/report.rb @@ -1,65 +1,72 @@ +# frozen_string_literal: true + require 'travis/cli' require 'travis/tools/system' module Travis module CLI class Report < ApiCommand - description "generates a report useful for filing issues" + description 'generates a report useful for filing issues' on '-r', '--known-repos', 'include repositories in report' skip :authenticate, :clear_error def run - display("System", :general) - display("CLI", :cli_info) - display("Session", :session_info) - display("Endpoints", :endpoints) - display("Known Repositories", :known_repos) if known_repos? + display('System', :general) + display('CLI', :cli_info) + display('Session', :session_info) + display('Endpoints', :endpoints) + display('Known Repositories', :known_repos) if known_repos? display_error - say "For issues with the command line tool, please visit #{color("https://github.com/travis-ci/travis.rb/issues", :underline)}." - say "For Travis CI in general, go to #{color("https://github.com/travis-ci/travis-ci/issues", :underline)} or email #{color("support@travis-ci.com", :underline)}." + say "For issues with the command line tool, please visit #{color( + 'https://github.com/travis-ci/travis.rb/issues', :underline + )}." + say "For Travis CI in general, go to #{color('https://github.com/travis-ci/travis-ci/issues', + :underline)} or email #{color('support@travis-ci.com', + :underline)}." end def display_error - return unless error = load_file("error.log") - display("Last Exception", :say, color(error, :info)) + return unless (error = load_file('error.log')) + + display('Last Exception', :say, color(error, :info)) end def display(title, method, *args) - say color(title, [:bold, :underline]) + say color(title, %i[bold underline]) send(method, *args) { |*a| list(*a) } puts end def list(key, value, additional = nil) value = case value - when Array then value.empty? ? 'none' : value.map(&:inspect).join(", ") - when true then "yes" - when false then "no" - when nil then "unknown" + when Array then value.empty? ? 'none' : value.map(&:inspect).join(', ') + when true then 'yes' + when false then 'no' + when nil then 'unknown' else value.to_s end additional &&= " (#{additional})" - say "#{key}:".ljust(known_repos? ? 50 : 25) << " " << color(value.to_s, :bold) << additional.to_s + say "#{key}:".ljust(known_repos? ? 50 : 25) << ' ' << color(value.to_s, :bold) << additional.to_s end def general - yield "Ruby", Tools::System.ruby - yield "Operating System", Tools::System.os - yield "RubyGems", Tools::System.rubygems + yield 'Ruby', Tools::System.ruby + yield 'Operating System', Tools::System.os + yield 'RubyGems', Tools::System.rubygems end def cli_info - yield "Version", Travis::VERSION - yield "Plugins", defined?(TRAVIS_PLUGINS) ? TRAVIS_PLUGINS : [] - yield "Auto-Completion", Tools::Completion.completion_installed? - yield "Last Version Check", last_check['at'] ? Time.at(last_check['at']) : 'never' + yield 'Version', Travis::VERSION + yield 'Plugins', defined?(TRAVIS_PLUGINS) ? TRAVIS_PLUGINS : [] + yield 'Auto-Completion', Tools::Completion.completion_installed? + yield 'Last Version Check', last_check['at'] ? Time.at(last_check['at']) : 'never' end def session_info - yield "API Endpoint", api_endpoint - yield "Logged In", user_info - yield "Verify SSL", !insecure - yield "Enterprise", enterprise? + yield 'API Endpoint', api_endpoint + yield 'Logged In', user_info + yield 'Verify SSL', !insecure + yield 'Enterprise', enterprise? end def endpoints @@ -74,25 +81,25 @@ def endpoints end end - def endpoint_name(url, prefix = "") + def endpoint_name(url, prefix = '') case url when Travis::Client::ORG_URI then "#{prefix}org" when Travis::Client::COM_URI then "#{prefix}com" - when /api-staging\.travis-ci/ then endpoint_name(url.sub("api-staging.", "api."), "staging-") + when /api-staging\.travis-ci/ then endpoint_name(url.sub('api-staging.', 'api.'), 'staging-') else - key, _ = config['enterprise'].detect { |k,v| v.start_with? url } if config['enterprise'].respond_to?(:detect) - key ? "enterprise %p" % key : "???" + key, = config['enterprise'].detect { |_k, v| v.start_with? url } if config['enterprise'].respond_to?(:detect) + key ? 'enterprise %p' % key : '???' end end def known_repos - config["repos"].each do |key, info| + config['repos'].each do |key, info| yield key, info['endpoint'] end end def user_info - access_token ? "as %p" % user.login : "no" + access_token ? 'as %p' % user.login : 'no' rescue Travis::Client::Error => e e.message end diff --git a/lib/travis/cli/repos.rb b/lib/travis/cli/repos.rb index 4ec1abfc..a6693425 100644 --- a/lib/travis/cli/repos.rb +++ b/lib/travis/cli/repos.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Repos < ApiCommand - description "lists repositories the user has certain permissions on" + description 'lists repositories the user has certain permissions on' on('-m', '--match PATTERN', 'only list repositories matching the given pattern (shell style)') on('-o', '--owner LOGIN', 'only list repos for a certain owner') on('-n', '--name NAME', 'only list repos with a given name') @@ -15,11 +17,12 @@ class Repos < ApiCommand def run repositories.each do |repo| next say(repo.slug) unless interactive? + state_color = repo.active? ? :green : :yellow - say color(repo.slug, [:bold, state_color]) + " " - say color("(" << attributes(repo).map { |n,v| "#{n}: #{v ? "yes" : "no"}" }.join(", ") << ")", state_color) + say "#{color(repo.slug, [:bold, state_color])} " + say color('(' << attributes(repo).map { |n, v| "#{n}: #{v ? 'yes' : 'no'}" }.join(', ') << ')', state_color) description = repo.description.lines.first.chomp unless repo.description.to_s.empty? - say "Description: #{description || "???"}" + say "Description: #{description || '???'}" empty_line unless repo == repositories.last end end @@ -29,21 +32,23 @@ def repositories repos = session.hooks.concat(user.repositories).uniq session.preload(repos).sort_by(&:slug).select do |repo| next false unless match? repo.slug - next false unless active.nil? or repo.active? == active - next false unless owner.nil? or repo.owner_name == owner - next false unless name.nil? or repo.name == name - next false unless admin.nil? or repo.admin? == admin + next false unless active.nil? || (repo.active? == active) + next false unless owner.nil? || (repo.owner_name == owner) + next false unless name.nil? || (repo.name == name) + next false unless admin.nil? || (repo.admin? == admin) + true end end end def attributes(repo) - { "active" => repo.active?, "admin" => repo.admin?, "push" => repo.push?, "pull" => repo.pull? } + { 'active' => repo.active?, 'admin' => repo.admin?, 'push' => repo.push?, 'pull' => repo.pull? } end def match?(string) return true if match.nil? + flags = File::FNM_PATHNAME | File::FNM_DOTMATCH flags |= File::FNM_EXTGLOB if defined? File::FNM_EXTGLOB File.fnmatch?(match, string, flags) diff --git a/lib/travis/cli/requests.rb b/lib/travis/cli/requests.rb index 77f5f981..88940341 100644 --- a/lib/travis/cli/requests.rb +++ b/lib/travis/cli/requests.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Requests < RepoCommand - description "lists recent requests" + description 'lists recent requests' on '-l', '--limit LIMIT', 'Maximum number requests to display' def run @@ -16,18 +18,17 @@ def run case request.event_type when 'push' - result = request.result || "received" + result = request.result || 'received' message = request.message - message ||= "validation pending" unless request.rejected? or request.accepted? - message ||= "unknown reason" unless request.accepted? - message ||= "triggered new build" unless request.rejected? - description = "push to #{request.branch || request.tag || "???"}" + message ||= 'validation pending' unless request.rejected? || request.accepted? + message ||= 'unknown reason' unless request.accepted? + message ||= 'triggered new build' unless request.rejected? + description = "push to #{request.branch || request.tag || '???'}" when 'pull_request' - result = request.result || "received" + result = request.result || 'received' message = request.message - message ||= "HEAD commit not updated" unless request.accepted? - message ||= "triggered new build" unless request.rejected? - description = "push to #{request.branch || request.tag || "???"}" + message ||= 'HEAD commit not updated' unless request.accepted? + message ||= 'triggered new build' unless request.rejected? description = "PR ##{request.pull_request_number}" end @@ -35,9 +36,9 @@ def run color(description, [:bold, style]), color(result, style), color("(#{message})", style) - ].join(" ").strip + "\n" + ].join(' ').strip + "\n" - say " " + color(request.commit.short_sha, :bold) + " - " + request.commit.subject if request.commit + say " #{color(request.commit.short_sha, :bold)} - #{request.commit.subject}" if request.commit say " received at: #{formatter.time(request.created_at)}" empty_line end diff --git a/lib/travis/cli/restart.rb b/lib/travis/cli/restart.rb index dde7340b..adc18542 100644 --- a/lib/travis/cli/restart.rb +++ b/lib/travis/cli/restart.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Restart < RepoCommand - description "restarts a build or job" + description 'restarts a build or job' def run(number = last_build.number) authenticate @@ -11,7 +13,7 @@ def run(number = last_build.number) error "could not find job or build #{repository.slug}##{number}" unless entity entity.restart - say "restarted", "#{entity.class.one} ##{entity.number} has been %s" + say 'restarted', "#{entity.class.one} ##{entity.number} has been %s" end end end diff --git a/lib/travis/cli/settings.rb b/lib/travis/cli/settings.rb index 3b0d08a4..c83f7ca2 100644 --- a/lib/travis/cli/settings.rb +++ b/lib/travis/cli/settings.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis @@ -5,49 +7,52 @@ module CLI class Settings < RepoCommand attr_accessor :setting - description "access repository settings" + description 'access repository settings' on('--keys', 'always use setting key instead of description') - on('-t', '--enable', 'enable boolean setting(s)') { |c | c.setting = true } - on('-f', '--disable', 'disable boolean setting(s)') { |c | c.setting = false } - on('-s', '--set VALUE', 'set to given value') { |c,v| c.setting = v } + on('-t', '--enable', 'enable boolean setting(s)') { |c| c.setting = true } + on('-f', '--disable', 'disable boolean setting(s)') { |c| c.setting = false } + on('-s', '--set VALUE', 'set to given value') { |c, v| c.setting = v } on('-c', '--configure', 'change settings interactively') DESCRIPTIONS = { - :builds_only_with_travis_yml => "Only run builds with a .travis.yml", - :build_pushes => "Build pushes", - :build_pull_requests => "Build pull requests", - :maximum_number_of_builds => "Maximum number of concurrent builds", - :auto_cancel_pushes => "Cancel older push builds that are not yet running", - :auto_cancel_pull_requests => "Cancel older pull request builds that are not yet running" - } + builds_only_with_travis_yml: 'Only run builds with a .travis.yml', + build_pushes: 'Build pushes', + build_pull_requests: 'Build pull requests', + maximum_number_of_builds: 'Maximum number of concurrent builds', + auto_cancel_pushes: 'Cancel older push builds that are not yet running', + auto_cancel_pull_requests: 'Cancel older pull request builds that are not yet running' + }.freeze def run(*keys) - exit 1 if interactive? and keys.empty? and !setting.nil? and !all_settings? and !configure? + exit 1 if interactive? && keys.empty? && !setting.nil? && !all_settings? && !configure? authenticate - say repository.slug, "Settings for %s:" + say repository.slug, 'Settings for %s:' repository.settings.to_h.each do |key, value| - next unless keys.empty? or keys.include? key + next unless keys.empty? || keys.include?(key) + if configure? - if boolean? key - repository.settings[key] = agree("#{describe(key, "enable #{key}")}? ") do |q| - default = setting.nil? ? value : setting - q.default = default ? "yes" : "no" - end - else - repository.settings[key] = ask("#{describe(key, "Value for #{key}")}: ", Integer) do |q| - default = setting.to_i if setting and setting.respond_to? :to_i - default ||= value - default ||= 0 - q.default = default - end - end + repository.settings[key] = if boolean? key + agree("#{describe(key, "enable #{key}")}? ") do |q| + default = setting.nil? ? value : setting + q.default = default ? 'yes' : 'no' + end + else + ask("#{describe(key, "Value for #{key}")}: ", Integer) do |q| + default = setting.to_i if setting && setting.respond_to?(:to_i) + default ||= value + default ||= 0 + q.default = default + end + end else value = repository.settings[key] = setting unless setting.nil? - descr = color(describe(key, color(key, :info)) { |s| key.ljust(30) + " " + color(s, [:reset, :bold]) }, :info) - say format_value(value) << " " << descr + descr = color(describe(key, color(key, :info)) do |s| + "#{key.ljust(30)} #{color(s, %i[reset bold])}" + end, :info) + say format_value(value) << ' ' << descr end end - repository.settings.save if configure? or !setting.nil? + repository.settings.save if configure? || !setting.nil? end def boolean?(key) @@ -56,20 +61,21 @@ def boolean?(key) def format_value(value) case value - when false, nil then color("[-]", [ :bold, :red ]) - when true then color("[+]", [ :bold, :green ]) - else color(value.to_s.rjust(3), [ :bold, :blue ]) + when false, nil then color('[-]', %i[bold red]) + when true then color('[+]', %i[bold green]) + else color(value.to_s.rjust(3), %i[bold blue]) end end def all_settings? - agree("Really #{setting ? "enable" : "disable"} all settings? ") do |q| - q.default = "no" + agree("Really #{setting ? 'enable' : 'disable'} all settings? ") do |q| + q.default = 'no' end end def describe(key, description = key) return description if keys? + desc = DESCRIPTIONS[key.to_sym] desc &&= yield(desc) if block_given? desc || description diff --git a/lib/travis/cli/setup.rb b/lib/travis/cli/setup.rb index b02397b0..0ec9875d 100644 --- a/lib/travis/cli/setup.rb +++ b/lib/travis/cli/setup.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis @@ -32,14 +34,14 @@ class Setup < RepoCommand autoload :Deis, 'travis/cli/setup/deis' autoload :Service, 'travis/cli/setup/service' - description "sets up an addon or deploy target" + description 'sets up an addon or deploy target' on('-f', '--force', 'override config section if it already exists') def self.service(name) normal_name = Service.normalized_name(name) const_name = constants(false).detect { |c| Service.normalized_name(c) == normal_name } constant = const_get(const_name) if const_name - constant if constant and constant < Service and constant.known_as? name + constant if constant && (constant < Service) && constant.known_as?(name) end def self.services @@ -47,7 +49,9 @@ def self.services end def help - services = self.class.services.map { |s| "\t" << color(s.service_name.ljust(20), :command) << color(s.description, :info) }.join("\n") + services = self.class.services.map do |s| + "\t" << color(s.service_name.ljust(20), :command) << color(s.description, :info) + end.join("\n") super("\nAvailable services:\n\n#{services}\n\n") end diff --git a/lib/travis/cli/setup/anynines.rb b/lib/travis/cli/setup/anynines.rb index 884293f2..f7ebd9bd 100644 --- a/lib/travis/cli/setup/anynines.rb +++ b/lib/travis/cli/setup/anynines.rb @@ -1,20 +1,21 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class Anynines < Service - description "automatic deployment to anynines" + description 'automatic deployment to anynines' def run deploy 'anynines' do |config| - config['username'] ||= ask("anynines username: ").to_s - config['password'] ||= ask("anynines password: ") { |q| q.echo = "*" }.to_s - config['organization'] ||= ask("anynines organization: ").to_s - config['space'] ||= ask("anynines space: ").to_s + config['username'] ||= ask('anynines username: ').to_s + config['password'] ||= ask('anynines password: ') { |q| q.echo = '*' }.to_s + config['organization'] ||= ask('anynines organization: ').to_s + config['space'] ||= ask('anynines space: ').to_s end end - end end end diff --git a/lib/travis/cli/setup/appfog.rb b/lib/travis/cli/setup/appfog.rb index 8d816990..998c884c 100644 --- a/lib/travis/cli/setup/appfog.rb +++ b/lib/travis/cli/setup/appfog.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class Appfog < Service - description "automatic deployment to Appfog" + description 'automatic deployment to Appfog' def run deploy 'appfog' do |config| - config['email'] = ask("Email address: ").to_s - config['password'] = ask("Password: ") { |q| q.echo = "*" }.to_s - config['app'] = ask("App name: ") { |q| q.default = repository.name }.to_s + config['email'] = ask('Email address: ').to_s + config['password'] = ask('Password: ') { |q| q.echo = '*' }.to_s + config['app'] = ask('App name: ') { |q| q.default = repository.name }.to_s end end end diff --git a/lib/travis/cli/setup/artifacts.rb b/lib/travis/cli/setup/artifacts.rb index 00281ee0..b9cc3bd9 100644 --- a/lib/travis/cli/setup/artifacts.rb +++ b/lib/travis/cli/setup/artifacts.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis @@ -10,11 +12,11 @@ class Artifacts < Service def run travis_config['addons'] ||= {} configure 'artifacts', {}, travis_config['addons'] do |config| - config['key'] = ask("Access key ID: ").to_s - config['secret'] = ask("Secret access key: ") { |q| q.echo = "*" }.to_s - config['bucket'] = ask("Bucket: ").to_s - encrypt(config, 'key') if agree("Encrypt access key ID? ") { |q| q.default = 'yes' } - encrypt(config, 'secret') if agree("Encrypt secret access key? ") { |q| q.default = 'yes' } + config['key'] = ask('Access key ID: ').to_s + config['secret'] = ask('Secret access key: ') { |q| q.echo = '*' }.to_s + config['bucket'] = ask('Bucket: ').to_s + encrypt(config, 'key') if agree('Encrypt access key ID? ') { |q| q.default = 'yes' } + encrypt(config, 'secret') if agree('Encrypt secret access key? ') { |q| q.default = 'yes' } end end end diff --git a/lib/travis/cli/setup/biicode.rb b/lib/travis/cli/setup/biicode.rb index d50de18e..0ece8336 100644 --- a/lib/travis/cli/setup/biicode.rb +++ b/lib/travis/cli/setup/biicode.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class Biicode < Service - description "automatic publish to biicode" + description 'automatic publish to biicode' def run deploy 'biicode', 'release' do |config| - config['user'] ||= ask("biicode username: ") { |q| q }.to_s - config['password'] ||= ask("biicode password: ") { |q| q.echo = "*" }.to_s - on("publish only tagged commits? ", config, 'tags' => true) + config['user'] ||= ask('biicode username: ') { |q| q }.to_s + config['password'] ||= ask('biicode password: ') { |q| q.echo = '*' }.to_s + on('publish only tagged commits? ', config, 'tags' => true) end end end diff --git a/lib/travis/cli/setup/cloud_66.rb b/lib/travis/cli/setup/cloud_66.rb index 7763cde6..85951b0c 100644 --- a/lib/travis/cli/setup/cloud_66.rb +++ b/lib/travis/cli/setup/cloud_66.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class Cloud_66 < Service - description "Automatic deployment to Cloud 66" + description 'Automatic deployment to Cloud 66' service_name 'cloud66' def run deploy 'cloud66', 'release' do |config| - config['redeployment_hook'] ||= ask("Cloud 66 Redeployment Hook Url: ") { |q| q.echo = "*" }.to_s + config['redeployment_hook'] ||= ask('Cloud 66 Redeployment Hook Url: ') { |q| q.echo = '*' }.to_s - encrypt(config, 'redeployment_hook') if agree("Encrypt Redeployment Hook?") { |q| q.default = 'yes' } + encrypt(config, 'redeployment_hook') if agree('Encrypt Redeployment Hook?') { |q| q.default = 'yes' } end end end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/setup/cloud_control.rb b/lib/travis/cli/setup/cloud_control.rb index 4c73c742..74a3c0f0 100644 --- a/lib/travis/cli/setup/cloud_control.rb +++ b/lib/travis/cli/setup/cloud_control.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class CloudControl < Service - description "automatic deployment to cloudControl" + description 'automatic deployment to cloudControl' def run deploy 'cloudcontrol' do |config| - config['email'] = ask("cloudControl email: ").to_s - config['password'] = ask("cloudControl password: ") { |q| q.echo = "*" }.to_s - app = ask("cloudControl application: ") { |q| q.default = repository.name }.to_s - dep = ask("cloudControl deployment: ") { |q| q.default = "default" }.to_s + config['email'] = ask('cloudControl email: ').to_s + config['password'] = ask('cloudControl password: ') { |q| q.echo = '*' }.to_s + app = ask('cloudControl application: ') { |q| q.default = repository.name }.to_s + dep = ask('cloudControl deployment: ') { |q| q.default = 'default' }.to_s config['deployment'] = "#{app}/#{dep}" end end end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/setup/cloud_files.rb b/lib/travis/cli/setup/cloud_files.rb index e2c1c604..5a36219e 100644 --- a/lib/travis/cli/setup/cloud_files.rb +++ b/lib/travis/cli/setup/cloud_files.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class CloudFiles < Service - description "automatic pushing to Rackspace Cloud Files" + description 'automatic pushing to Rackspace Cloud Files' def run deploy 'cloudfiles' do |config| - config['username'] = ask("Rackspace Username: ").to_s - config['api_key'] = ask("Rackspace Api Key: ") { |q| q.echo = "*" }.to_s - config['region'] = ask("Cloud Files Region: ").to_s - config['container'] = ask("Container: ").to_s + config['username'] = ask('Rackspace Username: ').to_s + config['api_key'] = ask('Rackspace Api Key: ') { |q| q.echo = '*' }.to_s + config['region'] = ask('Cloud Files Region: ').to_s + config['container'] = ask('Container: ').to_s end end end diff --git a/lib/travis/cli/setup/cloud_foundry.rb b/lib/travis/cli/setup/cloud_foundry.rb index 01eca1b0..c2f995a4 100644 --- a/lib/travis/cli/setup/cloud_foundry.rb +++ b/lib/travis/cli/setup/cloud_foundry.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class CloudFoundry < Service - description "automatic deployment to Cloud Foundry" + description 'automatic deployment to Cloud Foundry' def run deploy 'cloudfoundry' do |config| target_file = File.expand_path('.cf/config.json', Dir.home) - config['api'] ||= JSON.parse(File.read(target_file))["Target"] if File.exist? target_file - config['api'] ||= ask("Cloud Foundry api: ").to_s - config['username'] ||= ask("Cloud Foundry username: ").to_s - config['password'] ||= ask("Cloud Foundry password: ") { |q| q.echo = "*" }.to_s - config['organization'] ||= ask("Cloud Foundry organization: ").to_s - config['space'] ||= ask("Cloud Foundry space: ").to_s + config['api'] ||= JSON.parse(File.read(target_file))['Target'] if File.exist? target_file + config['api'] ||= ask('Cloud Foundry api: ').to_s + config['username'] ||= ask('Cloud Foundry username: ').to_s + config['password'] ||= ask('Cloud Foundry password: ') { |q| q.echo = '*' }.to_s + config['organization'] ||= ask('Cloud Foundry organization: ').to_s + config['space'] ||= ask('Cloud Foundry space: ').to_s end end end diff --git a/lib/travis/cli/setup/code_deploy.rb b/lib/travis/cli/setup/code_deploy.rb index 72ee7a8a..e6b2f32d 100644 --- a/lib/travis/cli/setup/code_deploy.rb +++ b/lib/travis/cli/setup/code_deploy.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli/setup' require 'shellwords' @@ -5,7 +7,7 @@ module Travis module CLI class Setup class CodeDeploy < Service - description "triggering a new deployment on Amazon CodeDeploy" + description 'triggering a new deployment on Amazon CodeDeploy' AWS_CONFIG = File.expand_path('.aws/config', ENV['HOME']) def run @@ -16,38 +18,40 @@ def run end deploy 'codedeploy' do |config| - config['access_key_id'] = ask("Access key ID: ") { |q| q.default = access_key if access_key }.to_s + config['access_key_id'] = ask('Access key ID: ') { |q| q.default = access_key if access_key }.to_s secret_access_key = nil unless access_key == config['access_key_id'] - config['secret_access_key'] = secret_access_key || ask("Secret access key: ") { |q| q.echo = "*" }.to_s - config['bucket'] = ask("S3 Bucket: ").to_s - config['key'] = ask("S3 Key: ").to_s - config['bundle_type'] = ask("Bundle Type: ") { |q| q.default = config['key'][/\.(zip|tar|tgz)$/, 1] }.to_s - config['application'] = ask("Application Name: ") { |q| q.default = repository.name }.to_s - config['deployment_group'] = ask("Deployment Group Name: ").to_s - encrypt(config, 'secret_access_key') if agree("Encrypt secret access key? ") { |q| q.default = 'yes' } + config['secret_access_key'] = secret_access_key || ask('Secret access key: ') { |q| q.echo = '*' }.to_s + config['bucket'] = ask('S3 Bucket: ').to_s + config['key'] = ask('S3 Key: ').to_s + config['bundle_type'] = ask('Bundle Type: ') do |q| + q.default = config['key'][/\.(zip|tar|tgz)$/, 1] + end.to_s + config['application'] = ask('Application Name: ') { |q| q.default = repository.name }.to_s + config['deployment_group'] = ask('Deployment Group Name: ').to_s + encrypt(config, 'secret_access_key') if agree('Encrypt secret access key? ') { |q| q.default = 'yes' } end - if agree("Also push bundle to S3? ") - cd = travis_config['deploy'] - s3 = { - 'provider' => 's3', - 'access_key_id' => cd['access_key_id'], - 'secret_access_key' => cd['secret_access_key'], - 'local_dir' => 'dpl_cd_upload', - 'skip_cleanup' => true, - 'on' => cd['on'], - 'bucket' => cd['bucket'] - } + return unless agree('Also push bundle to S3? ') - s3['upload_dir'] = File.dirname(cd['key']) if cd['key'].include? '/' - travis_config['deploy'] = [ s3, cd ] - upload_file_name = File.basename(cd['key']) - source_file = ask("Source File: ") { |q| q.default = upload_file_name } - travis_config['before_deploy'] = [ - "mkdir -p dpl_cd_upload", - "mv #{Shellwords.escape(source_file)} dpl_cd_upload/#{Shellwords.escape(upload_file_name)}" - ] - end + cd = travis_config['deploy'] + s3 = { + 'provider' => 's3', + 'access_key_id' => cd['access_key_id'], + 'secret_access_key' => cd['secret_access_key'], + 'local_dir' => 'dpl_cd_upload', + 'skip_cleanup' => true, + 'on' => cd['on'], + 'bucket' => cd['bucket'] + } + + s3['upload_dir'] = File.dirname(cd['key']) if cd['key'].include? '/' + travis_config['deploy'] = [s3, cd] + upload_file_name = File.basename(cd['key']) + source_file = ask('Source File: ') { |q| q.default = upload_file_name } + travis_config['before_deploy'] = [ + 'mkdir -p dpl_cd_upload', + "mv #{Shellwords.escape(source_file)} dpl_cd_upload/#{Shellwords.escape(upload_file_name)}" + ] end end end diff --git a/lib/travis/cli/setup/deis.rb b/lib/travis/cli/setup/deis.rb index f5be73ba..1c00af16 100644 --- a/lib/travis/cli/setup/deis.rb +++ b/lib/travis/cli/setup/deis.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class Deis < Service - description "automatic deployment to a deis app" + description 'automatic deployment to a deis app' def run deploy 'deis' do |config| - config['controller'] ||= ask("Deis Controller: ").to_s - config['app'] ||= ask("Deis App: ").to_s - config['username'] ||= ask("Deis Username: ").to_s - config['password'] ||= ask("Deis Password: ") { |q| q.echo = "*" }.to_s + config['controller'] ||= ask('Deis Controller: ').to_s + config['app'] ||= ask('Deis App: ').to_s + config['username'] ||= ask('Deis Username: ').to_s + config['password'] ||= ask('Deis Password: ') { |q| q.echo = '*' }.to_s end end end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/setup/divshot.rb b/lib/travis/cli/setup/divshot.rb index 22e45264..996d1c53 100644 --- a/lib/travis/cli/setup/divshot.rb +++ b/lib/travis/cli/setup/divshot.rb @@ -1,18 +1,20 @@ -require 'travis/cli/setup' - -module Travis - module CLI - class Setup - class Divshot < Service - description "deployment to Divshot.io" - - def run - deploy 'divshot' do |config| - config['api_key'] = ask("Divshot Api Key: ") { |q| q.echo = "*" }.to_s - config['environment'] = ask("Divshot Environment: ").to_s - end - end - end - end - end -end \ No newline at end of file +# frozen_string_literal: true + +require 'travis/cli/setup' + +module Travis + module CLI + class Setup + class Divshot < Service + description 'deployment to Divshot.io' + + def run + deploy 'divshot' do |config| + config['api_key'] = ask('Divshot Api Key: ') { |q| q.echo = '*' }.to_s + config['environment'] = ask('Divshot Environment: ').to_s + end + end + end + end + end +end diff --git a/lib/travis/cli/setup/elastic_beanstalk.rb b/lib/travis/cli/setup/elastic_beanstalk.rb index a1d7791b..daff4956 100644 --- a/lib/travis/cli/setup/elastic_beanstalk.rb +++ b/lib/travis/cli/setup/elastic_beanstalk.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class ElasticBeanstalk < Service - description "deployment to AWS Elastic Beanstalk" + description 'deployment to AWS Elastic Beanstalk' def run deploy 'elasticbeanstalk' do |config| - config['access_key_id'] = ask("Access key ID: ").to_s - config['secret_access_key'] = ask("Secret access key: ") { |q| q.echo = "*" }.to_s - config['region'] = ask("Elastic Beanstalk region: ") {|q| q.default = 'us-east-1'}.to_s - config['app'] = ask("Elastic Beanstalk application name: ").to_s - config['env'] = ask("Elastic Beanstalk environment to update: ").to_s - config['bucket_name'] = ask("Bucket name to upload app to: ").to_s + config['access_key_id'] = ask('Access key ID: ').to_s + config['secret_access_key'] = ask('Secret access key: ') { |q| q.echo = '*' }.to_s + config['region'] = ask('Elastic Beanstalk region: ') { |q| q.default = 'us-east-1' }.to_s + config['app'] = ask('Elastic Beanstalk application name: ').to_s + config['env'] = ask('Elastic Beanstalk environment to update: ').to_s + config['bucket_name'] = ask('Bucket name to upload app to: ').to_s - encrypt(config, 'secret_access_key') if agree("Encrypt secret access key? ") { |q| q.default = 'yes' } + encrypt(config, 'secret_access_key') if agree('Encrypt secret access key? ') { |q| q.default = 'yes' } end end end diff --git a/lib/travis/cli/setup/engine_yard.rb b/lib/travis/cli/setup/engine_yard.rb index 3f43a63b..ac47bae6 100644 --- a/lib/travis/cli/setup/engine_yard.rb +++ b/lib/travis/cli/setup/engine_yard.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli/setup' require 'yaml' @@ -5,17 +7,17 @@ module Travis module CLI class Setup class EngineYard < Service - description "automatic deployment to Engine Yard" + description 'automatic deployment to Engine Yard' def run deploy 'engineyard' do |config| - eyrc = File.expand_path(".eyrc", Dir.home) - config['api_key'] = YAML.load_file(eyrc)["api_token"] if File.exists?(eyrc) - config['api_key'] = ask("API token: ") { |q| q.echo = "*" }.to_s unless config['api_key'] - env = ask("Environment (optional): ").to_s + eyrc = File.expand_path('.eyrc', Dir.home) + config['api_key'] = YAML.load_file(eyrc)['api_token'] if File.exist?(eyrc) + config['api_key'] = ask('API token: ') { |q| q.echo = '*' }.to_s unless config['api_key'] + env = ask('Environment (optional): ').to_s config['environment'] = env unless env.empty? - migrate = agree("Run migrations on deploy? ") { |q| q.default = 'yes' } - config['migrate'] = ask("Migration command: ") { |q| q.default = "rake db:migrate" } if migrate + migrate = agree('Run migrations on deploy? ') { |q| q.default = 'yes' } + config['migrate'] = ask('Migration command: ') { |q| q.default = 'rake db:migrate' } if migrate end end end diff --git a/lib/travis/cli/setup/gcs.rb b/lib/travis/cli/setup/gcs.rb index 6ae8d1f2..18a83ce8 100644 --- a/lib/travis/cli/setup/gcs.rb +++ b/lib/travis/cli/setup/gcs.rb @@ -1,22 +1,24 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class GCS < Service - description "automatic pushing to Google Cloud Storage" + description 'automatic pushing to Google Cloud Storage' def run deploy 'gcs' do |config| - config['access_key_id'] = ask("Access key ID: ").to_s - config['secret_access_key'] = ask("Secret access key: ") { |q| q.echo = "*" }.to_s - config['bucket'] = ask("Bucket: ").to_s - local_dir = ask("Local project directory to upload (Optional): ").to_s + config['access_key_id'] = ask('Access key ID: ').to_s + config['secret_access_key'] = ask('Secret access key: ') { |q| q.echo = '*' }.to_s + config['bucket'] = ask('Bucket: ').to_s + local_dir = ask('Local project directory to upload (Optional): ').to_s config['local-dir'] = local_dir unless local_dir.empty? - encrypt(config, 'secret_access_key') if agree("Encrypt secret access key? ") { |q| q.default = 'yes' } + encrypt(config, 'secret_access_key') if agree('Encrypt secret access key? ') { |q| q.default = 'yes' } end end end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/setup/hackage.rb b/lib/travis/cli/setup/hackage.rb index 9a2307af..8e475e12 100644 --- a/lib/travis/cli/setup/hackage.rb +++ b/lib/travis/cli/setup/hackage.rb @@ -1,18 +1,20 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class Hackage < Service - description "automatic deployment of hackage packages" + description 'automatic deployment of hackage packages' def run deploy 'hackage' do |config| - config['username'] ||= ask("Hackage Username: ").to_s - config['password'] ||= ask("Hackage Password: ") { |q| q.echo = "*" }.to_s + config['username'] ||= ask('Hackage Username: ').to_s + config['password'] ||= ask('Hackage Password: ') { |q| q.echo = '*' }.to_s end end end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/setup/heroku.rb b/lib/travis/cli/setup/heroku.rb index cca54409..ee0fd177 100644 --- a/lib/travis/cli/setup/heroku.rb +++ b/lib/travis/cli/setup/heroku.rb @@ -1,20 +1,26 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class Heroku < Service - description "automatic deployment to Heroku" + description 'automatic deployment to Heroku' def run deploy 'heroku' do |config| config['api_key'] = `heroku auth:token 2>/dev/null`.strip - config['api_key'] = ask("Heroku API token: ") { |q| q.echo = "*" }.to_s if config['api_key'].empty? + config['api_key'] = ask('Heroku API token: ') { |q| q.echo = '*' }.to_s if config['api_key'].empty? config['app'] = `heroku apps:info 2>/dev/null`.scan(/^=== (.+)$/).flatten.first - config['app'] = ask("Heroku application name: ") { |q| q.default = repository.name }.to_s if config['app'].nil? + if config['app'].nil? + config['app'] = ask('Heroku application name: ') do |q| + q.default = repository.name + end.to_s + end end end end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/setup/modulus.rb b/lib/travis/cli/setup/modulus.rb index 0df4293d..01217ccf 100644 --- a/lib/travis/cli/setup/modulus.rb +++ b/lib/travis/cli/setup/modulus.rb @@ -1,15 +1,17 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class Modulus < Service - description "deployment to Modulus" + description 'deployment to Modulus' def run deploy 'modulus' do |config| - config['api_key'] = ask("Modulus Api Key: ") { |q| q.echo = "*" }.to_s - config['project_name'] = ask("Modulus Project Name: ").to_s + config['api_key'] = ask('Modulus Api Key: ') { |q| q.echo = '*' }.to_s + config['project_name'] = ask('Modulus Project Name: ').to_s end end end diff --git a/lib/travis/cli/setup/ninefold.rb b/lib/travis/cli/setup/ninefold.rb index 03313c28..fe7f65df 100644 --- a/lib/travis/cli/setup/ninefold.rb +++ b/lib/travis/cli/setup/ninefold.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class Ninefold < Service - description "Automatic deployment to Ninefold" + description 'Automatic deployment to Ninefold' def run deploy 'ninefold', 'release' do |config| - config['app_id'] ||= ask("Ninefold App ID: ").to_s - config['auth_token'] ||= ask("Ninefold Auth Token: ") { |q| q.echo = "*" }.to_s + config['app_id'] ||= ask('Ninefold App ID: ').to_s + config['auth_token'] ||= ask('Ninefold Auth Token: ') { |q| q.echo = '*' }.to_s - encrypt(config, 'auth_token') if agree("Encrypt Auth Token? ") { |q| q.default = 'yes' } + encrypt(config, 'auth_token') if agree('Encrypt Auth Token? ') { |q| q.default = 'yes' } end end end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/setup/nodejitsu.rb b/lib/travis/cli/setup/nodejitsu.rb index 233376d5..8207e317 100644 --- a/lib/travis/cli/setup/nodejitsu.rb +++ b/lib/travis/cli/setup/nodejitsu.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli/setup' require 'json' @@ -5,7 +7,7 @@ module Travis module CLI class Setup class Nodejitsu < Service - description "automatic deployment to Nodejitsu" + description 'automatic deployment to Nodejitsu' def run deploy 'nodejitsu' do |config| @@ -17,11 +19,11 @@ def run config['api_key'] = jitsu_conf['apiToken'] end - config['user'] ||= ask("Nodejitsu user: ").to_s - config['api_key'] ||= ask("Nodejitsu API token: ") { |q| q.echo = "*" }.to_s + config['user'] ||= ask('Nodejitsu user: ').to_s + config['api_key'] ||= ask('Nodejitsu API token: ') { |q| q.echo = '*' }.to_s end end end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/setup/npm.rb b/lib/travis/cli/setup/npm.rb index 66176deb..94ffd42b 100644 --- a/lib/travis/cli/setup/npm.rb +++ b/lib/travis/cli/setup/npm.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class NPM < Service - description "automatic release to npm" + description 'automatic release to npm' def run deploy 'npm', 'release' do |config| - config['email'] ||= ask("npm email address: ") { |q| q }.to_s - config['api_key'] ||= ask("npm api key: ") { |q| q.echo = "*" }.to_s + config['email'] ||= ask('npm email address: ') { |q| q }.to_s + config['api_key'] ||= ask('npm api key: ') { |q| q.echo = '*' }.to_s - on("release only tagged commits? ", config, 'tags' => true) + on('release only tagged commits? ', config, 'tags' => true) end end end diff --git a/lib/travis/cli/setup/open_shift.rb b/lib/travis/cli/setup/open_shift.rb index c3d52000..21ff8cb4 100644 --- a/lib/travis/cli/setup/open_shift.rb +++ b/lib/travis/cli/setup/open_shift.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class OpenShift < Service - description "automatic deployment to OpenShfit" + description 'automatic deployment to OpenShfit' def run deploy 'openshift' do |config| - config['user'] = ask("OpenShift user: ").to_s - config['password'] = ask("OpenShift password: ") { |q| q.echo = "*" }.to_s - config['app'] = ask("OpenShift application name: ") { |q| q.default = repository.name }.to_s - config['domain'] = ask("OpenShift domain: ").to_s + config['user'] = ask('OpenShift user: ').to_s + config['password'] = ask('OpenShift password: ') { |q| q.echo = '*' }.to_s + config['app'] = ask('OpenShift application name: ') { |q| q.default = repository.name }.to_s + config['domain'] = ask('OpenShift domain: ').to_s end end end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/setup/opsworks.rb b/lib/travis/cli/setup/opsworks.rb index 6a745798..8cf23218 100644 --- a/lib/travis/cli/setup/opsworks.rb +++ b/lib/travis/cli/setup/opsworks.rb @@ -1,22 +1,24 @@ -require 'travis/cli/setup' - -module Travis - module CLI - class Setup - class OpsWorks < Service - description "deployment to OpsWorks" - - def run - deploy 'opsworks' do |config| - config['access_key_id'] = ask("Access key ID: ").to_s - config['secret_access_key'] = ask("Secret access key: ") { |q| q.echo = "*" }.to_s - config['app-id'] = ask("App ID: ").to_s - config['migrate'] = true if agree("Migrate the Database? ") { |q| q.default = 'no' } - - encrypt(config, 'secret_access_key') if agree("Encrypt secret access key? ") { |q| q.default = 'yes' } - end - end - end - end - end -end \ No newline at end of file +# frozen_string_literal: true + +require 'travis/cli/setup' + +module Travis + module CLI + class Setup + class OpsWorks < Service + description 'deployment to OpsWorks' + + def run + deploy 'opsworks' do |config| + config['access_key_id'] = ask('Access key ID: ').to_s + config['secret_access_key'] = ask('Secret access key: ') { |q| q.echo = '*' }.to_s + config['app-id'] = ask('App ID: ').to_s + config['migrate'] = true if agree('Migrate the Database? ') { |q| q.default = 'no' } + + encrypt(config, 'secret_access_key') if agree('Encrypt secret access key? ') { |q| q.default = 'yes' } + end + end + end + end + end +end diff --git a/lib/travis/cli/setup/pypi.rb b/lib/travis/cli/setup/pypi.rb index 357c6462..b77050f0 100644 --- a/lib/travis/cli/setup/pypi.rb +++ b/lib/travis/cli/setup/pypi.rb @@ -1,19 +1,21 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class PyPI < Service - description "automatic deployment to PyPI" + description 'automatic deployment to PyPI' def run deploy 'pypi', 'release' do |config| - config['user'] ||= ask("Username: ").to_s - config['password'] ||= ask("Password: ") { |q| q.echo = "*" }.to_s + config['user'] ||= ask('Username: ').to_s + config['password'] ||= ask('Password: ') { |q| q.echo = '*' }.to_s - on("release only tagged commits? ", config, 'tags' => true) + on('release only tagged commits? ', config, 'tags' => true) # the default of pypi `setup.py build` is the `sdist` - on("deploy as wheel file too? ", config, 'distributions' => 'sdist bdist_wheel') + on('deploy as wheel file too? ', config, 'distributions' => 'sdist bdist_wheel') end end end diff --git a/lib/travis/cli/setup/releases.rb b/lib/travis/cli/setup/releases.rb index e226b786..79b5ef83 100644 --- a/lib/travis/cli/setup/releases.rb +++ b/lib/travis/cli/setup/releases.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli/setup' require 'travis/tools/github' @@ -5,16 +7,14 @@ module Travis module CLI class Setup class Releases < Service - description "Upload Assets to GitHub Releases" + description 'Upload Assets to GitHub Releases' def run deploy 'releases' do |config| github.with_token { |t| config['api_key'] = t } - if config['api_key'].nil? - raise Travis::Client::GitHubLoginFailed, 'all GitHub tokens given were invalid' - end + raise Travis::Client::GitHubLoginFailed, 'all GitHub tokens given were invalid' if config['api_key'].nil? - config['file'] = ask("File to Upload: ").to_s + config['file'] = ask('File to Upload: ').to_s end end @@ -25,7 +25,7 @@ def github g.drop_token = false g.github_token = github_token g.debug = proc { |log| debug(log) } - g.after_tokens = proc { g.explode = true and error("no suitable github token found") } + g.after_tokens = proc { g.explode = true and error('no suitable github token found') } g.scopes = org? ? ['public_repo'] : ['repo'] g.note = "automatic releases for #{repository.slug}" end diff --git a/lib/travis/cli/setup/ruby_gems.rb b/lib/travis/cli/setup/ruby_gems.rb index a8025eef..b64a59b8 100644 --- a/lib/travis/cli/setup/ruby_gems.rb +++ b/lib/travis/cli/setup/ruby_gems.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class RubyGems < Service - description "automatic release to RubyGems" + description 'automatic release to RubyGems' def run deploy 'rubygems', 'release' do |config| @@ -13,13 +15,13 @@ def run config['api_key'] ||= File.read(authorization_file) if File.exist? authorization_file config['api_key'] ||= YAML.load_file(credentials_file)[:rubygems_api_key] if File.exist? credentials_file - config['api_key'] ||= ask("RubyGems API token: ") { |q| q.echo = "*" }.to_s - config['gem'] ||= ask("Gem name: ") { |q| q.default = repository.name }.to_s + config['api_key'] ||= ask('RubyGems API token: ') { |q| q.echo = '*' }.to_s + config['gem'] ||= ask('Gem name: ') { |q| q.default = repository.name }.to_s - on("Release only tagged commits? ", config, 'tags' => true) + on('Release only tagged commits? ', config, 'tags' => true) end end end end end -end \ No newline at end of file +end diff --git a/lib/travis/cli/setup/s3.rb b/lib/travis/cli/setup/s3.rb index 06ba1ed3..5b850972 100644 --- a/lib/travis/cli/setup/s3.rb +++ b/lib/travis/cli/setup/s3.rb @@ -1,22 +1,26 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class S3 < Service - description "automatic pushing to S3" + description 'automatic pushing to S3' def run deploy 's3', 'push' do |config| - config['access_key_id'] = ask("Access key ID: ").to_s - config['secret_access_key'] = ask("Secret access key: ") { |q| q.echo = "*" }.to_s - config['bucket'] = ask("Bucket: ").to_s - local_dir = ask("Local project directory to upload (Optional): ").to_s + config['access_key_id'] = ask('Access key ID: ').to_s + config['secret_access_key'] = ask('Secret access key: ') { |q| q.echo = '*' }.to_s + config['bucket'] = ask('Bucket: ').to_s + local_dir = ask('Local project directory to upload (Optional): ').to_s config['local-dir'] = local_dir unless local_dir.empty? - upload_dir = ask("S3 upload directory (Optional): ").to_s + upload_dir = ask('S3 upload directory (Optional): ').to_s config['upload-dir'] = upload_dir unless upload_dir.empty? - config['acl'] = ask("S3 ACL Settings (private, public_read, public_read_write, authenticated_read, bucket_owner_read, bucket_owner_full_control): ").to_s { |q| q.default = 'private'} - encrypt(config, 'secret_access_key') if agree("Encrypt secret access key? ") { |q| q.default = 'yes' } + config['acl'] = ask('S3 ACL Settings (private, public_read, public_read_write, authenticated_read, bucket_owner_read, bucket_owner_full_control): ').to_s do |q| + q.default = 'private' + end + encrypt(config, 'secret_access_key') if agree('Encrypt secret access key? ') { |q| q.default = 'yes' } end end end diff --git a/lib/travis/cli/setup/sauce_connect.rb b/lib/travis/cli/setup/sauce_connect.rb index 39e2d511..c37b8694 100644 --- a/lib/travis/cli/setup/sauce_connect.rb +++ b/lib/travis/cli/setup/sauce_connect.rb @@ -1,18 +1,20 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis module CLI class Setup class SauceConnect < Service - description "Sauce Connet addon for Sauce Labs integration" - service_name "sauce_connect" + description 'Sauce Connet addon for Sauce Labs integration' + service_name 'sauce_connect' def run travis_config['addons'] ||= {} configure 'sauce_connect', {}, travis_config['addons'] do |config| - config['username'] = ask("Sauce Labs user: ").to_s - config['access_key'] = ask("Sauce Labs access key: ") { |q| q.echo = "*" }.to_s - encrypt(config, 'access_key') if agree("Encrypt access key? ") { |q| q.default = 'yes' } + config['username'] = ask('Sauce Labs user: ').to_s + config['access_key'] = ask('Sauce Labs access key: ') { |q| q.echo = '*' }.to_s + encrypt(config, 'access_key') if agree('Encrypt access key? ') { |q| q.default = 'yes' } end end end diff --git a/lib/travis/cli/setup/service.rb b/lib/travis/cli/setup/service.rb index d1df4c4a..f018496a 100644 --- a/lib/travis/cli/setup/service.rb +++ b/lib/travis/cli/setup/service.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli/setup' module Travis @@ -9,7 +11,7 @@ def self.normalized_name(string) end def self.description(description = nil) - @description ||= "" + @description ||= '' @description = description if description @description end @@ -36,39 +38,48 @@ def method_missing(*args, &block) private - def on(question, config, condition) - return unless agree(question) { |q| q.default = 'yes' } - config['on'] ||= {} - config['on'].merge! condition - end + def on(question, config, condition) + return unless agree(question) { |q| q.default = 'yes' } - def encrypt(config, key) - encrypted = repository.encrypt(config.fetch(key)) - config[key] = { 'secure' => encrypted } - end + config['on'] ||= {} + config['on'].merge! condition + end - def configure(key, value = {}, config = travis_config) - error "#{key} section already exists in .travis.yml, run with --force to override" if config.include? key and not force? - yield(config[key] = value) - end + def encrypt(config, key) + encrypted = repository.encrypt(config.fetch(key)) + config[key] = { 'secure' => encrypted } + end - def branch - @branch ||= `git rev-parse --symbolic-full-name --abbrev-ref HEAD`.chomp + def configure(key, value = {}, config = travis_config) + if config.include?(key) && !force? + error "#{key} section already exists in .travis.yml, run with --force to override" end + yield(config[key] = value) + end - def deploy(provider, verb = "deploy") - configure('deploy', 'provider' => provider) do |config| - yield config - - on("#{verb.capitalize} only from #{repository.slug}? ", config, 'repo' => repository.slug) - on("#{verb.capitalize} from #{branch} branch? ", config, 'branch' => branch) if branch != 'master' and branch != 'HEAD' + def branch + @branch ||= `git rev-parse --symbolic-full-name --abbrev-ref HEAD`.chomp + end - config['skip_cleanup'] = 'true' if not ( config.has_key?('skip_cleanup') or config.fetch('edge', 'false') != 'false' ) + def deploy(provider, verb = 'deploy') + configure('deploy', 'provider' => provider) do |config| + yield config - encrypt(config, 'password') if config['password'] and agree("Encrypt Password? ") { |q| q.default = 'yes' } - encrypt(config, 'api_key') if config['api_key'] and agree("Encrypt API key? ") { |q| q.default = 'yes' } + on("#{verb.capitalize} only from #{repository.slug}? ", config, 'repo' => repository.slug) + if (branch != 'master') && (branch != 'HEAD') + on("#{verb.capitalize} from #{branch} branch? ", config, + 'branch' => branch) end + + config['skip_cleanup'] = 'true' unless config.key?('skip_cleanup') || (config.fetch('edge', + 'false') != 'false') + + encrypt(config, 'password') if config['password'] && agree('Encrypt Password? ') do |q| + q.default = 'yes' + end + encrypt(config, 'api_key') if config['api_key'] && agree('Encrypt API key? ') { |q| q.default = 'yes' } end + end end end end diff --git a/lib/travis/cli/show.rb b/lib/travis/cli/show.rb index e87198ea..ff7c594e 100644 --- a/lib/travis/cli/show.rb +++ b/lib/travis/cli/show.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Show < RepoCommand - description "displays a build or job" + description 'displays a build or job' def run(number = last_build.number) - number = repository.branch(number).number if number !~ /^\d+(\.\d+)?$/ and repository.branch(number) + number = repository.branch(number).number if number !~ /^\d+(\.\d+)?$/ && repository.branch(number) entity = job(number) || build(number) error "could not find job or build #{repository.slug}##{number}" unless entity @@ -17,7 +19,7 @@ def run(number = last_build.number) entity.commit.subject, entity.state, entity.color, - entity.pull_request? ? "pull request" : "push", + entity.pull_request? ? 'pull request' : 'push', entity.branch_info, entity.commit.short_sha, entity.commit.compare_url, @@ -33,13 +35,13 @@ def run(number = last_build.number) color("##{job.number} #{job.state}:".ljust(16), [job.color, :bold]), formatter.duration(job.duration).ljust(14), formatter.job_config(job.config), - (color("(failure allowed)", :info) if job.allow_failures?) - ].compact.join(" ").rstrip + (color('(failure allowed)', :info) if job.allow_failures?) + ].compact.join(' ').rstrip end else config = formatter.job_config(entity.config) - say color("Allow Failure: ", :info) + entity.allow_failures?.inspect - say color("Config: ", :info) + config unless config.empty? + say color('Allow Failure: ', :info) + entity.allow_failures?.inspect + say color('Config: ', :info) + config unless config.empty? end end end @@ -56,4 +58,4 @@ def run(number = last_build.number) <[[ color("Compare URL: ", :info) ]]>%s <[[ color("Duration: ", :info) ]]>%s <[[ color("Started: ", :info) ]]>%s -<[[ color("Finished: ", :info) ]]>%s +<[[ color("Finished: ", :info) ]]>%s \ No newline at end of file diff --git a/lib/travis/cli/sshkey.rb b/lib/travis/cli/sshkey.rb index d040a311..5d22e1e2 100644 --- a/lib/travis/cli/sshkey.rb +++ b/lib/travis/cli/sshkey.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/cli' require 'travis/tools/ssl_key' require 'travis/tools/github' @@ -5,7 +7,7 @@ module Travis module CLI class Sshkey < RepoCommand - description "checks, updates or deletes an SSH key" + description 'checks, updates or deletes an SSH key' on '-D', '--delete', 'remove SSH key' on '-d', '--description DESCRIPTION', 'set description' on '-u', '--upload FILE', 'upload key from given file' @@ -30,25 +32,26 @@ def display_key say "Current SSH key: #{color(ssh_key.description, :info)}" say "Finger print: #{color(ssh_key.fingerprint, :info)}" rescue Travis::Client::NotFound - say "No custom SSH key installed." + say 'No custom SSH key installed.' exit 1 if check? end def update_key(value, file) error "#{file} does not look like a private key" unless value.lines.first =~ /PRIVATE KEY/ value = remove_passphrase(value) - self.description ||= ask("Key description: ") { |q| q.default = "Custom Key" } if interactive? + self.description ||= ask('Key description: ') { |q| q.default = 'Custom Key' } if interactive? say "Updating ssh key for #{color slug, :info} with key from #{color file, :info}" empty_line - ssh_key.update(:value => value, :description => description || file) + ssh_key.update(value:, description: description || file) end def delete_key - return if interactive? and not danger_zone? "Remove SSH key for #{color slug, :info}?" + return if interactive? && !danger_zone?("Remove SSH key for #{color slug, :info}?") + say "Removing ssh key for #{color slug, :info}" ssh_key.delete rescue Travis::Client::NotFound - warn "no key found to remove" + warn 'no key found to remove' end def generate_key @@ -56,38 +59,39 @@ def generate_key github.with_token do |token| access_token = github_auth(token) end - unless access_token - raise Travis::Client::GitHubLoginFailed, "all GitHub tokens given were invalid" - end + raise Travis::Client::GitHubLoginFailed, 'all GitHub tokens given were invalid' unless access_token + gh = GH.with(token: github_token) login = gh['user']['login'] check_access(gh) empty_line - say "Generating RSA key." + say 'Generating RSA key.' private_key = Tools::SSLKey.generate_rsa self.description ||= "key for fetching dependencies for #{slug} via #{login}" - say "Uploading public key to GitHub." - gh.post("/user/keys", :title => "#{description} (Travis CI)", :key => Tools::SSLKey.rsa_ssh(private_key.public_key)) + say 'Uploading public key to GitHub.' + gh.post('/user/keys', title: "#{description} (Travis CI)", + key: Tools::SSLKey.rsa_ssh(private_key.public_key)) - say "Uploading private key to Travis CI." - ssh_key.update(:value => private_key.to_s, :description => description) + say 'Uploading private key to Travis CI.' + ssh_key.update(value: private_key.to_s, description:) empty_line - say "You can store the private key to reuse it for other repositories (travis sshkey --upload FILE)." - if agree("Store private key? ") { |q| q.default = "no" } - path = ask("Path: ") { |q| q.default = "id_travis_rsa" } - File.write(path, private_key.to_s) - end + say 'You can store the private key to reuse it for other repositories (travis sshkey --upload FILE).' + return unless agree('Store private key? ') { |q| q.default = 'no' } + + path = ask('Path: ') { |q| q.default = 'id_travis_rsa' } + File.write(path, private_key.to_s) end def remove_passphrase(value) return value unless Tools::SSLKey.has_passphrase? value - return Tools::SSLKey.remove_passphrase(value, passphrase) || error("wrong pass phrase") if passphrase - error "Key is encrypted, but missing --passphrase option" unless interactive? - say "The private key is protected by a pass phrase." - result = Tools::SSLKey.remove_passphrase(value, ask("Enter pass phrase: ") { |q| q.echo = "*" }) until result + return Tools::SSLKey.remove_passphrase(value, passphrase) || error('wrong pass phrase') if passphrase + + error 'Key is encrypted, but missing --passphrase option' unless interactive? + say 'The private key is protected by a pass phrase.' + result = Tools::SSLKey.remove_passphrase(value, ask('Enter pass phrase: ') { |q| q.echo = '*' }) until result empty_line result end @@ -107,15 +111,15 @@ def github g.github_token = github_token g.login_header = proc { login_header } g.debug = proc { |log| debug(log) } - g.after_tokens = proc { g.explode = true and error("no suitable github token found") } + g.after_tokens = proc { g.explode = true and error('no suitable github token found') } end end end def login_header - say "GitHub deprecated its Authorizations API exchanging a password for a token." - say "Please visit https://github.blog/2020-07-30-token-authentication-requirements-for-api-and-git-operations for more information." - say "Try running with #{color("--github-token", :info)} or #{color("--auto-token", :info)} ." + say 'GitHub deprecated its Authorizations API exchanging a password for a token.' + say 'Please visit https://github.blog/2020-07-30-token-authentication-requirements-for-api-and-git-operations for more information.' + say "Try running with #{color('--github-token', :info)} or #{color('--auto-token', :info)} ." end end end diff --git a/lib/travis/cli/status.rb b/lib/travis/cli/status.rb index d075439e..3994efa8 100644 --- a/lib/travis/cli/status.rb +++ b/lib/travis/cli/status.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Status < RepoCommand - description "checks status of the latest build" + description 'checks status of the latest build' on '-x', '--[no-]exit-code', 'sets the exit code to 1 if the build failed' on '-q', '--[no-]quiet', 'does not print anything' @@ -11,8 +13,8 @@ class Status < RepoCommand def run say color(last_build.state, last_build.color), "build ##{last_build.number} %s" unless quiet? - exit 1 if exit_code? and last_build.unsuccessful? - exit 1 if fail_pending? and last_build.pending? + exit 1 if exit_code? && last_build.unsuccessful? + exit 1 if fail_pending? && last_build.pending? end end end diff --git a/lib/travis/cli/sync.rb b/lib/travis/cli/sync.rb index f92a6c05..0aff758a 100644 --- a/lib/travis/cli/sync.rb +++ b/lib/travis/cli/sync.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Sync < ApiCommand - description "triggers a new sync with GitHub" + description 'triggers a new sync with GitHub' on '-c', '--check', 'only check the sync status' on '-b', '--background', 'will trigger sync but not block until sync is done' @@ -13,16 +15,16 @@ def run authenticate if check? - say "#{"not " unless user.syncing?}syncing", "#{user.login} is currently %s" - elsif user.syncing? and not force? - error "user is already syncing" + say "#{'not ' unless user.syncing?}syncing", "#{user.login} is currently %s" + elsif user.syncing? && !force? + error 'user is already syncing' elsif background? - say "starting synchronization" + say 'starting synchronization' sync(false) else - say "synchronizing: " + say 'synchronizing: ' sync - say color(" done", :success) + say color(' done', :success) end end end diff --git a/lib/travis/cli/token.rb b/lib/travis/cli/token.rb index a49b6722..824ec8f5 100644 --- a/lib/travis/cli/token.rb +++ b/lib/travis/cli/token.rb @@ -1,13 +1,15 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Token < ApiCommand - description "outputs the secret API token" + description 'outputs the secret API token' def run authenticate - say access_token, "Your access token is %s" + say access_token, 'Your access token is %s' end end end diff --git a/lib/travis/cli/version.rb b/lib/travis/cli/version.rb index cefa0271..54bebfd4 100644 --- a/lib/travis/cli/version.rb +++ b/lib/travis/cli/version.rb @@ -1,17 +1,18 @@ +# frozen_string_literal: true + require 'travis/cli' require 'travis/version' module Travis module CLI class Version < Command - description "outputs the client version" + description 'outputs the client version' def run say Travis::VERSION end - def check_version - end + def check_version; end end end end diff --git a/lib/travis/cli/whatsup.rb b/lib/travis/cli/whatsup.rb index d79b9592..d0d26e48 100644 --- a/lib/travis/cli/whatsup.rb +++ b/lib/travis/cli/whatsup.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + require 'travis/cli' module Travis module CLI class Whatsup < ApiCommand - description "lists most recent builds" + description 'lists most recent builds' on('-m', '--my-repos', 'Only display my own repositories') def run - say "nothing to show" if recent.empty? + say 'nothing to show' if recent.empty? recent.each do |repo| say [ color(repo.slug, [:bold, repo.color]), color("#{repo.last_build.state}: ##{repo.last_build.number}", repo.color) - ].join(" ") + ].join(' ') end end private - def recent - @recent ||= begin - recent = my_repos ? repos : repos(:member => user.login) - recent.select { |repo| repo.last_build } - end + def recent + @recent ||= begin + recent = my_repos ? repos : repos(member: user.login) + recent.select { |repo| repo.last_build } end + end end end end diff --git a/lib/travis/cli/whoami.rb b/lib/travis/cli/whoami.rb index 1e31e8c1..6da7246c 100644 --- a/lib/travis/cli/whoami.rb +++ b/lib/travis/cli/whoami.rb @@ -3,12 +3,12 @@ module Travis module CLI class Whoami < ApiCommand - description "outputs the current user" + description 'outputs the current user' def run authenticate name = " (#{user.name})" unless user.name.to_s.empty? - say user.login, "You are %s" << name.to_s + say user.login, 'You are %s' << name.to_s end end end diff --git a/lib/travis/client.rb b/lib/travis/client.rb index 2a8b4c75..7a6c548b 100644 --- a/lib/travis/client.rb +++ b/lib/travis/client.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client/error' require 'travis/client/states' require 'travis/client/restartable' @@ -26,11 +28,12 @@ module Travis module Client + ORG_URI = 'https://api.travis-ci.org/' COM_URI = 'https://api.travis-ci.com/' def self.new(options = {}) - options[:uri] ||= ORG_URI if options.is_a? Hash and not options['uri'] + options[:uri] ||= COM_URI if options.is_a?(Hash) && !(options['uri']) Session.new(options) end end diff --git a/lib/travis/client/account.rb b/lib/travis/client/account.rb index 770f85be..d0b3b736 100644 --- a/lib/travis/client/account.rb +++ b/lib/travis/client/account.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' module Travis @@ -32,11 +34,11 @@ def on_trial? end def repos_count - load_attribute("repos_count") { repositories.count } + load_attribute('repos_count') { repositories.count } end def repositories - attributes['repositories'] ||= session.repos(:owner_name => login) + attributes['repositories'] ||= session.repos(owner_name: login) end def member? @@ -47,10 +49,10 @@ def member? private - def load_attribute(name, &block) - session.accounts if missing? name - block ? attributes.fetch(name.to_s, &block) : attributes[name.to_s] - end + def load_attribute(name, &block) + session.accounts if missing? name + block ? attributes.fetch(name.to_s, &block) : attributes[name.to_s] + end end end end diff --git a/lib/travis/client/artifact.rb b/lib/travis/client/artifact.rb index f53e6190..e1288633 100644 --- a/lib/travis/client/artifact.rb +++ b/lib/travis/client/artifact.rb @@ -1,12 +1,13 @@ -# encoding: utf-8 +# frozen_string_literal: true + require 'travis/client' require 'travis/tools/safe_string' module Travis module Client class Artifact < Entity - CHUNKED = "application/json; chunked=true; version=2, application/json; version=2" - TEXT = "#{CHUNKED}, text/plain" + CHUNKED = 'application/json; chunked=true; version=2, application/json; version=2' + TEXT = "#{CHUNKED}, text/plain".freeze # @!parse attr_reader :job_id, :type, :body attributes :job_id, :type, :body @@ -15,11 +16,12 @@ class Artifact < Entity has :job def delete_body(reason = {}) - reason = { :reason => reason } unless reason.is_a? Hash + reason = { reason: } unless reason.is_a? Hash session.patch_raw("jobs/#{job_id}/log", reason) reload - rescue Travis::Client::Error => error - raise unless error.message == '409' + rescue Travis::Client::Error => e + raise unless e.message == '409' + self end @@ -39,32 +41,34 @@ def current_body attributes['current_body'] ||= begin body = load_attribute('body') if body.to_s.empty? - log = session.get_raw("jobs/#{job_id}/log", nil, "Accept" => TEXT) - body = String === log ? log : log['log']['body'] + log = session.get_raw("jobs/#{job_id}/log", nil, 'Accept' => TEXT) + body = log.is_a?(String) ? log : log['log']['body'] end body end end def body(stream = block_given?) - return current_body unless block_given? or stream - return yield(current_body) unless stream and job.pending? + return current_body unless block_given? || stream + return yield(current_body) unless stream && job.pending? + number = 0 session.listen(self) do |listener| listener.on 'job:log' do |event| next unless event.payload['number'] > number + number = event.payload['number'] yield event.payload['_log'] listener.disconnect if event.payload['final'] end - listener.on 'job:finished' do |event| + listener.on 'job:finished' do |_event| listener.disconnect end listener.on_connect do - data = session.get_raw("/logs/#{id}", nil, "Accept" => CHUNKED)['log'] + data = session.get_raw("/logs/#{id}", nil, 'Accept' => CHUNKED)['log'] if data['parts'] data['parts'].each { |p| yield p['content'] } number = data['parts'].last['number'] if data['parts'].any? diff --git a/lib/travis/client/auto_login.rb b/lib/travis/client/auto_login.rb index b1c36208..cebdbe22 100644 --- a/lib/travis/client/auto_login.rb +++ b/lib/travis/client/auto_login.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' require 'travis/tools/github' require 'yaml' @@ -12,12 +14,13 @@ def initialize(session, options = {}) @session = session.session config_path = ENV.fetch('TRAVIS_CONFIG_PATH') { File.expand_path('.travis', Dir.home) } @config_file = options.fetch(:config_file) { File.expand_path('config.yml', config_path) } - @auto_token = options.fetch(:auto_token) { true } - @raise = options.fetch(:raise) { true } + @auto_token = options.fetch(:auto_token, true) + @raise = options.fetch(:raise, true) end def authenticate - return if session.access_token = cli_token + return if (session.access_token = cli_token) + github.with_token { |t| session.github_auth(t) } end @@ -25,7 +28,7 @@ def github @github ||= Tools::Github.new(session.config['github']) do |g| g.explode = true g.auto_token = @auto_token - g.after_tokens = proc { raise NoTokenError, "no suitable github token found" } if @raise + g.after_tokens = proc { raise NoTokenError, 'no suitable github token found' } if @raise end end diff --git a/lib/travis/client/broadcast.rb b/lib/travis/client/broadcast.rb index 8ccf99e1..74a1f773 100644 --- a/lib/travis/client/broadcast.rb +++ b/lib/travis/client/broadcast.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' module Travis diff --git a/lib/travis/client/build.rb b/lib/travis/client/build.rb index c375af4a..ddeca48b 100644 --- a/lib/travis/client/build.rb +++ b/lib/travis/client/build.rb @@ -1,13 +1,17 @@ +# frozen_string_literal: true + require 'travis/client' module Travis module Client class Build < Entity - include States, Restartable + include Restartable + include States preloadable # @!parse attr_reader :repository_id, :commit_id, :number, :pull_request, :pull_request_number, :pull_request_title, :config, :state, :started_at, :finished_at, :duration, :job_ids - attributes :repository_id, :commit_id, :number, :pull_request, :pull_request_number, :pull_request_title, :config, :state, :started_at, :finished_at, :duration, :job_ids + attributes :repository_id, :commit_id, :number, :pull_request, :pull_request_number, :pull_request_title, + :config, :state, :started_at, :finished_at, :duration, :job_ids time :started_at, :finished_at alias pull_request? pull_request @@ -27,7 +31,7 @@ def delete_logs(reason = {}) end def push? - not pull_request? + !pull_request? end def branch_info diff --git a/lib/travis/client/cache.rb b/lib/travis/client/cache.rb index ea529526..7db066ab 100644 --- a/lib/travis/client/cache.rb +++ b/lib/travis/client/cache.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client/weak_entity' module Travis @@ -14,11 +16,11 @@ class Cache < WeakEntity many :caches def delete - repository.delete_caches(:branch => branch, :match => slug) + repository.delete_caches(branch:, match: slug) end def inspect_info - [repository.slug, branch, slug].compact.join(" ") + [repository.slug, branch, slug].compact.join(' ') end end end diff --git a/lib/travis/client/commit.rb b/lib/travis/client/commit.rb index 44ecd70f..6752a9fe 100644 --- a/lib/travis/client/commit.rb +++ b/lib/travis/client/commit.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' module Travis @@ -6,7 +8,8 @@ class Commit < Entity include NotLoadable # @!parse attr_reader :sha, :branch, :message, :committed_at, :author_name, :author_email, :committer_name, :committer_email, :compare_url - attributes :sha, :branch, :message, :committed_at, :author_name, :author_email, :committer_name, :committer_email, :compare_url + attributes :sha, :branch, :message, :committed_at, :author_name, :author_email, :committer_name, + :committer_email, :compare_url time :committed_at one :commit @@ -21,7 +24,7 @@ def short_sha end def inspect_info - short_sha + " " + subject.inspect + "#{short_sha} #{subject.inspect}" end end end diff --git a/lib/travis/client/entity.rb b/lib/travis/client/entity.rb index d374e988..20a63f37 100644 --- a/lib/travis/client/entity.rb +++ b/lib/travis/client/entity.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' require 'time' @@ -48,7 +50,7 @@ def self.attributes(*list) list.each do |name| name = name.to_s - fail "can't call an attribute id" if name == "id" + raise "can't call an attribute id" if name == 'id' @attributes << name define_method(name) { load_attribute(name) } @@ -111,6 +113,7 @@ def self.preloadable? def initialize(session, id) raise Travis::Client::Error, '%p is not a valid id' % id unless self.class.id? id + @attributes = {} @session = session @id = self.class.cast_id(id) if id @@ -155,6 +158,7 @@ def load def missing?(key) return false unless include? key + !attributes.include?(key.to_s) end @@ -164,7 +168,7 @@ def complete? def inspect klass = self.class - klass = curry if curry and curry.name and curry.to_s.size < klass.to_s.size + klass = curry if curry&.name && curry.to_s.size < klass.to_s.size "#<#{klass}: #{inspect_info}>" end @@ -182,57 +186,57 @@ def cancelable? private - def relation(name) - name = name.to_s - entity = Entity.subclass_for(name) - - if entity.many == name - Array(send("#{entity.one}_ids")).map do |id| - session.find_one(entity, id) - end - else - id = send("#{name}_id") - session.find_one(entity, id) unless id.nil? + def relation(name) + name = name.to_s + entity = Entity.subclass_for(name) + + if entity.many == name + Array(send("#{entity.one}_ids")).map do |id| + session.find_one(entity, id) end + else + id = send("#{name}_id") + session.find_one(entity, id) unless id.nil? end + end - def inspect_info - id - end + def inspect_info + id + end - def set_attribute(name, value) - attributes[name.to_s] = value - end + def set_attribute(name, value) + attributes[name.to_s] = value + end - def load_attribute(name) - session.reload(self) if missing? name - attributes[name.to_s] - end + def load_attribute(name) + session.reload(self) if missing? name + attributes[name.to_s] + end - # shamelessly stolen from sinatra - def time(value) - if value.respond_to? :to_time - value.to_time - elsif value.is_a? Time - value - elsif value.respond_to? :new_offset - d = value.new_offset 0 - t = Time.utc d.year, d.mon, d.mday, d.hour, d.min, d.sec + d.sec_fraction - t.getlocal - elsif value.respond_to? :mday - Time.local(value.year, value.mon, value.mday) - elsif value.is_a? Numeric - Time.at value - elsif value.nil? or value.empty? - nil - else - Time.parse value.to_s - end - rescue ArgumentError => boom - raise boom - rescue Exception - raise ArgumentError, "unable to convert #{value.inspect} to a Time object" + # shamelessly stolen from sinatra + def time(value) + if value.respond_to? :to_time + value.to_time + elsif value.is_a? Time + value + elsif value.respond_to? :new_offset + d = value.new_offset 0 + t = Time.utc d.year, d.mon, d.mday, d.hour, d.min, d.sec + d.sec_fraction + t.getlocal + elsif value.respond_to? :mday + Time.local(value.year, value.mon, value.mday) + elsif value.is_a? Numeric + Time.at value + elsif value.nil? || value.empty? + nil + else + Time.parse value.to_s end + rescue ArgumentError => e + raise e + rescue Exception + raise ArgumentError, "unable to convert #{value.inspect} to a Time object" + end end end end diff --git a/lib/travis/client/env_var.rb b/lib/travis/client/env_var.rb index ecce3b1c..beeaba58 100644 --- a/lib/travis/client/env_var.rb +++ b/lib/travis/client/env_var.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' require 'delegate' @@ -35,7 +37,7 @@ def repository_id end def add(name, value, options = {}) - body = JSON.dump(:env_var => options.merge(:name => name, :value => value)) + body = JSON.dump(env_var: options.merge(name:, value:)) result = session.post(EnvVar.path(self), body) self.list += [result['env_var']] end @@ -43,8 +45,8 @@ def add(name, value, options = {}) def upsert(name, value, options = {}) entries = select { |e| e.name == name } if entries.any? - entries.first.update(options.merge(:value => value)) - entries[1..-1].each { |e| e.delete } + entries.first.update(options.merge(value:)) + entries[1..].each { |e| e.delete } else add(name, value, options) end @@ -53,11 +55,13 @@ def upsert(name, value, options = {}) def [](key) return super if key.is_a? Integer + detect { |e| e.name == key.to_s } end def []=(key, value) return super if key.is_a? Integer + upsert(key.to_s, value) end @@ -65,8 +69,9 @@ def []=(key, value) end def self.path(object) - repository_id = Repository === object ? object.id : object.repository_id - raise "repository unknown" unless repository_id + repository_id = object.is_a?(Repository) ? object.id : object.repository_id + raise 'repository unknown' unless repository_id + "/settings/env_vars/#{object.id if object.is_a? EnvVar}?repository_id=#{repository_id}" end @@ -82,8 +87,8 @@ def self.path(object) has :repository def update(options) - options = { :value => options } unless options.is_a? Hash - result = session.patch(EnvVar.path(self), JSON.dump(:env_var => options)) + options = { value: options } unless options.is_a? Hash + result = session.patch(EnvVar.path(self), JSON.dump(env_var: options)) attributes.replace(result['env_var'].attributes) self end @@ -95,7 +100,7 @@ def delete end def inspect_info - "#{name}=#{value ? value.inspect : "[secure]"}" + "#{name}=#{value ? value.inspect : '[secure]'}" end end end diff --git a/lib/travis/client/error.rb b/lib/travis/client/error.rb index 6e7ef277..93df78ce 100644 --- a/lib/travis/client/error.rb +++ b/lib/travis/client/error.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' module Travis @@ -25,7 +27,7 @@ class RepositoryMigrated < Error class AssetNotFound < Error def initialize(file, *args) - if md = file.match(%r[init/(?[^\.]+)\.yml$]) + if (md = file.match(%r{init/(?[^.]+)\.yml$})) super "unknown language #{md[:lang]}", *args else super file, *args @@ -42,9 +44,9 @@ def initialize(message = nil, *args) end def parse_message(message) - response = JSON.load(message) + response = JSON.parse(message) message = response['message'].to_s - if @errors = response['errors'] and @errors.any? + if (@errors = response['errors']) && @errors.any? readable = @errors.map { |e| "#{e['field']}: #{e['code'].gsub('_', ' ')}" } message += " (#{readable.join(', ')})" end diff --git a/lib/travis/client/has_uuid.rb b/lib/travis/client/has_uuid.rb index 16d53b53..adf58895 100644 --- a/lib/travis/client/has_uuid.rb +++ b/lib/travis/client/has_uuid.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + module Travis module Client module HasUuid def id?(object) - object =~ /\A(?:\w+-){4}\w+\Z/ if object.is_a? String + object =~ /\A(?:\w+-){4}\w+\Z/ if object.is_a? String end def cast_id(object) diff --git a/lib/travis/client/job.rb b/lib/travis/client/job.rb index db962ba3..e74c7073 100644 --- a/lib/travis/client/job.rb +++ b/lib/travis/client/job.rb @@ -1,13 +1,17 @@ +# frozen_string_literal: true + require 'travis/client' module Travis module Client class Job < Entity - include States, Restartable + include Restartable + include States preloadable # @!parse attr_reader :repository_id, :build_id, :commit_id, :log_id, :number, :config, :state, :started_at, :finished_at, :queue, :allow_failure, :tags - attributes :repository_id, :build_id, :commit_id, :log_id, :number, :config, :state, :started_at, :finished_at, :queue, :allow_failure, :tags + attributes :repository_id, :build_id, :commit_id, :log_id, :number, :config, :state, :started_at, :finished_at, + :queue, :allow_failure, :tags time :started_at, :finished_at alias allow_failure? allow_failure @@ -31,7 +35,8 @@ def branch_info end def allow_failures? - return false unless config.include? 'matrix' and config['matrix'].include? 'allow_failures' + return false unless config.include?('matrix') && config['matrix'].include?('allow_failures') + config['matrix']['allow_failures'].any? do |allow| allow.all? { |key, value| config[key] == value } end diff --git a/lib/travis/client/lint_result.rb b/lib/travis/client/lint_result.rb index 08299796..37d706d4 100644 --- a/lib/travis/client/lint_result.rb +++ b/lib/travis/client/lint_result.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Travis module Client class LintResult diff --git a/lib/travis/client/listener.rb b/lib/travis/client/listener.rb index ffd5e95a..a648416e 100644 --- a/lib/travis/client/listener.rb +++ b/lib/travis/client/listener.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' require 'forwardable' require 'json' @@ -13,6 +15,7 @@ module Client class Listener class Socket < PusherClient::Socket attr_accessor :session, :signatures + def initialize(application_key, options = {}) @session = options.fetch(:session) @signatures = {} @@ -31,7 +34,10 @@ def subscribe_all def fetch_auth(*channels) channels.select! { |c| signatures[c].nil? if c.start_with? 'private-' } - signatures.merge! session.post_raw('/pusher/auth', :channels => channels, :socket_id => socket_id)['channels'] if channels.any? + return unless channels.any? + + signatures.merge! session.post_raw('/pusher/auth', channels:, + socket_id:)['channels'] end def get_private_auth(channel) @@ -40,19 +46,22 @@ def get_private_auth(channel) end def handle_error(data) - code, message = data["code"], data["message"] if data.is_a? Hash + if data.is_a? Hash + code = data['code'] + message = data['message'] + end message ||= data.inspect case code when 4100 then reconnect(1) when 4200, 4201, 4202 then reconnect - else raise Travis::Client::Error, "Pusher error: %s (code: %p)" % [message, code] + else raise Travis::Client::Error, format('Pusher error: %s (code: %p)', message, code) end end def reconnect(delay = nil) disconnect if connected - sleep delay if delay and delay > 0 + sleep delay if delay&.positive? connect end end @@ -60,7 +69,7 @@ def reconnect(delay = nil) EVENTS = %w[ build:created build:started build:finished job:created job:started job:log job:finished - ] + ].freeze Event = Struct.new(:type, :repository, :build, :job, :payload) @@ -71,7 +80,8 @@ class EntityListener def_delegators :listener, :disconnect, :on_connect, :subscribe def initialize(listener, entities) - @listener, @entities = listener, Array(entities) + @listener = listener + @entities = Array(entities) end def on(*events) @@ -80,11 +90,11 @@ def on(*events) private - def dispatch?(event) - entities.include? event.repository or - entities.include? event.build or + def dispatch?(event) + entities.include? event.repository or + entities.include? event.build or entities.include? event.job - end + end end attr_reader :session, :socket @@ -111,15 +121,15 @@ def on(*events, &block) events.each { |e| @callbacks << [e, block] } end - def on_connect - socket.bind('pusher:connection_established') { yield } + def on_connect(&block) + socket.bind('pusher:connection_established', &block) end def listen @channels = default_channels if @channels.empty? @channels.map! { |c| c.start_with?('private-') ? c : "private-#{c}" } if session.private_channels? @channels.uniq.each { |c| socket.subscribe(c) } - @callbacks.each { |e,b| socket.bind(e) { |d| dispatch(e, d, &b) } } + @callbacks.each { |e, b| socket.bind(e) { |d| dispatch(e, d, &b) } } socket.connect end @@ -129,55 +139,60 @@ def disconnect private - def dispatch(type, json) - payload = JSON.parse(json) - entities = session.load format_payload(type, payload) - yield Event.new(type, entities['repository'], entities['build'], entities['job'], payload) - end + def dispatch(type, json) + payload = JSON.parse(json) + entities = session.load format_payload(type, payload) + yield Event.new(type, entities['repository'], entities['build'], entities['job'], payload) + end - def format_payload(type, payload) - case type - when "job:log" then format_log(payload) - when /job:/ then format_job(payload) - else payload - end + def format_payload(type, payload) + case type + when 'job:log' then format_log(payload) + when /job:/ then format_job(payload) + else payload end + end - def format_job(payload) - build = { "id" => payload["build_id"], "repository_id" => payload["repository_id"] } - repo = { "id" => payload["repository_id"], "slug" => payload["repository_slug"] } - build["number"] = payload["number"][/^[^\.]+/] if payload["number"] - { "job" => payload, "build" => build, "repository" => repo } - end + def format_job(payload) + build = { 'id' => payload['build_id'], 'repository_id' => payload['repository_id'] } + repo = { 'id' => payload['repository_id'], 'slug' => payload['repository_slug'] } + build['number'] = payload['number'][/^[^.]+/] if payload['number'] + { 'job' => payload, 'build' => build, 'repository' => repo } + end - def format_log(payload) - job = session.job(payload['id']) - { "job" => { "id" => job.id }, "build" => { "id" => job.build.id }, "repository" => { "id" => job.repository.id } } - end + def format_log(payload) + job = session.job(payload['id']) + { 'job' => { 'id' => job.id }, 'build' => { 'id' => job.build.id }, + 'repository' => { 'id' => job.repository.id } } + end - def default_channels - return ['common'] if session.access_token.nil? - session.user.channels - end + def default_channels + return ['common'] if session.access_token.nil? - def pusher_options - pusher_options = session.config['pusher'] || {} - encrypted = pusher_options['scheme'] != 'http' - options = { :encrypted => encrypted, :session => session } - options[:ws_host] = pusher_options['host'] if pusher_options['host'] - options[:wss_port] = pusher_options['port'] if encrypted and pusher_options['port'] - options[:ws_port] = pusher_options['port'] if !encrypted and pusher_options['port'] - options[:ws_path] = pusher_options['path'] if pusher_options['path'] - options[:ws_path] = '/' << options[:ws_path] unless options[:ws_path].nil? or options[:ws_path].start_with? '/' - options[:ssl_verify] = session.ssl.fetch(:verify, true) - options - end + session.user.channels + end - def pusher_key - session.config.fetch('pusher').fetch('key') - rescue IndexError - raise Travis::Client::Error, "#{session.api_endpoint} is missing pusher key" - end + def pusher_options + pusher_options = session.config['pusher'] || {} + encrypted = pusher_options['scheme'] != 'http' + options = { encrypted:, session: } + options[:ws_host] = pusher_options['host'] if pusher_options['host'] + options[:wss_port] = pusher_options['port'] if encrypted && pusher_options['port'] + options[:ws_port] = pusher_options['port'] if !encrypted && pusher_options['port'] + options[:ws_path] = pusher_options['path'] if pusher_options['path'] + unless options[:ws_path].nil? || options[:ws_path].start_with?('/') + options[:ws_path] = + '/' << options[:ws_path] + end + options[:ssl_verify] = session.ssl.fetch(:verify, true) + options + end + + def pusher_key + session.config.fetch('pusher').fetch('key') + rescue IndexError + raise Travis::Client::Error, "#{session.api_endpoint} is missing pusher key" + end end end end diff --git a/lib/travis/client/methods.rb b/lib/travis/client/methods.rb index 47fbfe62..f8391687 100644 --- a/lib/travis/client/methods.rb +++ b/lib/travis/client/methods.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' require 'yaml' @@ -17,12 +19,13 @@ def api_endpoint end def github_auth(github_token) - reply = session.post_raw("/auth/github", :github_token => github_token) - unless reply.respond_to?(:key?) && reply.key?("access_token") - raise InvalidTokenError, 'token is invalid, or does not have sufficient scope; see https://docs.travis-ci.com/user/github-oauth-scopes/ for more information on scope' + reply = session.post_raw('/auth/github', github_token:) + unless reply.respond_to?(:key?) && reply.key?('access_token') + raise InvalidTokenError, + 'token is invalid, or does not have sufficient scope; see https://docs.travis-ci.com/user/github-oauth-scopes/ for more information on scope' end - session.access_token = reply["access_token"] + session.access_token = reply['access_token'] end def explicit_api_endpoint? @@ -67,7 +70,7 @@ def account(name) end def accounts - session.find_many(Account, :all => true) + session.find_many(Account, all: true) end def broadcasts @@ -78,12 +81,14 @@ def restart(entity) # btw, internally we call this reset, not restart, as it resets the state machine # but we thought that would be too confusing raise Error, "cannot restart a #{entity.class.one}" unless entity.restartable? + session.post_raw("/#{entity.class.many}/#{entity.id}/restart") entity.reload end def cancel(entity) raise Error, "cannot cancel a #{entity.class.one}" unless entity.cancelable? + session.post_raw("/#{entity.class.many}/#{entity.id}/cancel") entity.reload end diff --git a/lib/travis/client/namespace.rb b/lib/travis/client/namespace.rb index 7baf3ff6..70d9e35d 100644 --- a/lib/travis/client/namespace.rb +++ b/lib/travis/client/namespace.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' module Travis @@ -7,7 +9,8 @@ class Curry < Module attr_accessor :namespace, :type def initialize(namespace, type) - @namespace, @type = namespace, type + @namespace = namespace + @type = type end def find_one(id = nil) @@ -41,9 +44,9 @@ def clear_cache! private - def session - namespace.session - end + def session + namespace.session + end end include Methods @@ -66,20 +69,21 @@ def included(klass) private - def fix_names(klass) - constants.each do |name| - const = klass.const_get(name) - klass.const_set(name, const) if const == const_get(name) - end + def fix_names(klass) + constants.each do |name| + const = klass.const_get(name) + klass.const_set(name, const) if const == const_get(name) end + end - def delegate_session(klass) - return if klass == Object or klass == Kernel - klass.extend(Methods) - namespace = self - klass.define_singleton_method(:session) { namespace.session } - klass.define_singleton_method(:session=) { |value| namespace.session = value } - end + def delegate_session(klass) + return if [Object, Kernel].include?(klass) + + klass.extend(Methods) + namespace = self + klass.define_singleton_method(:session) { namespace.session } + klass.define_singleton_method(:session=) { |value| namespace.session = value } + end end end end diff --git a/lib/travis/client/not_loadable.rb b/lib/travis/client/not_loadable.rb index b51666c6..22621412 100644 --- a/lib/travis/client/not_loadable.rb +++ b/lib/travis/client/not_loadable.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + module Travis module Client module NotLoadable - def missing?(attribute) + def missing?(_attribute) false end diff --git a/lib/travis/client/repository.rb b/lib/travis/client/repository.rb index 99441f0c..e5d70616 100644 --- a/lib/travis/client/repository.rb +++ b/lib/travis/client/repository.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' require 'travis/tools/ssl_key' @@ -14,7 +16,7 @@ def initialize(data, fingerprint) def encrypt(value) encrypted = to_rsa.public_encrypt(value) - Base64.encode64(encrypted).gsub(/\s+/, "") + Base64.encode64(encrypted).gsub(/\s+/, '') end def to_rsa @@ -34,7 +36,8 @@ def ==(other) preloadable # @!parse attr_reader :slug, :description - attributes :slug, :active, :private, :admin, :description, :last_build_id, :last_build_number, :last_build_state, :last_build_duration, :last_build_started_at, :last_build_finished_at, :github_language + attributes :slug, :active, :private, :admin, :description, :last_build_id, :last_build_number, :last_build_state, + :last_build_duration, :last_build_started_at, :last_build_finished_at, :github_language inspect_info :slug time :last_build_finished_at, :last_build_started_at @@ -51,14 +54,14 @@ def initialize(*) end def public_key - attributes["public_key"] ||= begin + attributes['public_key'] ||= begin payload = session.get_raw("/repos/#{id}/key") Key.new(payload.fetch('key'), payload['fingerprint']) end end def name - slug[/[^\/]+$/] + slug[%r{[^/]+$}] end def public_key=(key) @@ -75,6 +78,7 @@ def encrypt(value) # @!parse attr_reader :last_build def last_build return unless last_build_id + attributes['last_build'] ||= begin last_build = session.find_one(Build, last_build_id) last_build.number = last_build_number @@ -89,11 +93,12 @@ def last_build def builds(params = nil) return each_build unless params - session.find_many(Build, params.merge(:repository_id => id)) + + session.find_many(Build, params.merge(repository_id: id)) end def build(number) - builds(:number => number.to_s).first + builds(number: number.to_s).first end def recent_builds @@ -102,7 +107,8 @@ def recent_builds def last_on_branch(name = nil) return branch(name) if name - attributes['last_on_branch'] ||= session.get('branches', :repository_id => id)['branches'] + + attributes['last_on_branch'] ||= session.get('branches', repository_id: id)['branches'] end def branches @@ -112,19 +118,24 @@ def branches def branch(name) attributes['branches'] ||= {} attributes['branches'][name] ||= begin - build = attributes['last_on_branch'].detect { |b| b.commit.branch == name.to_s } if attributes['last_on_branch'] + if attributes['last_on_branch'] + build = attributes['last_on_branch'].detect do |b| + b.commit.branch == name.to_s + end + end build || session.get("/repos/#{id}/branches/#{name}")['branch'] end end def each_build(params = nil, &block) return enum_for(__method__, params) unless block_given? + params ||= {} chunk = builds(params) until chunk.empty? chunk.each(&block) number = chunk.last.number - chunk = number == '1' ? [] : builds(params.merge(:after_number => number)) + chunk = number == '1' ? [] : builds(params.merge(after_number: number)) end self end @@ -133,12 +144,12 @@ def job(number) build_number = number.to_s[/^\d+/] or return nil build = build(build_number) or return nil job = build.jobs.detect { |j| j.number == number } if number != build_number - job ||= build.jobs.first if build and build.jobs.size == 1 + job ||= build.jobs.first if build && (build.jobs.size == 1) job end def set_hook(flag) - result = session.put_raw('/hooks/', :hook => { :id => id, :active => flag }) + result = session.put_raw('/hooks/', hook: { id:, active: flag }) result['result'] end @@ -152,10 +163,10 @@ def enable def pusher_channels attributes['pusher_channels'] ||= if session.private_channels? - ["user-#{session.user.id}", "repo-#{id}"] - else - ["common"] - end + ["user-#{session.user.id}", "repo-#{id}"] + else + ['common'] + end end def member? @@ -163,7 +174,7 @@ def member? end def owner_name - slug[/^[^\/]+/] + slug[%r{^[^/]+}] end def owner @@ -171,7 +182,7 @@ def owner end def requests - attributes['requests'] ||= session.find_many(Request, :repository_id => id) + attributes['requests'] ||= session.find_many(Request, repository_id: id) end def settings @@ -181,7 +192,7 @@ def settings settings end rescue Travis::Client::NotFound - raise Travis::Client::Error, "not allowed to access settings" + raise Travis::Client::Error, 'not allowed to access settings' end def caches(params = {}) @@ -193,8 +204,9 @@ def delete_caches(params = {}) end def active? - # TODO remove once active is properly synced and exposed by api + # TODO: remove once active is properly synced and exposed by api return active unless active.nil? + last_build_id? end @@ -216,9 +228,9 @@ def env_vars private - def state - last_build_state - end + def state + last_build_state + end end end end diff --git a/lib/travis/client/request.rb b/lib/travis/client/request.rb index ae2502a9..6bb12cef 100644 --- a/lib/travis/client/request.rb +++ b/lib/travis/client/request.rb @@ -1,10 +1,13 @@ +# frozen_string_literal: true + require 'travis/client/weak_entity' module Travis module Client class Request < WeakEntity # @!parse attr_reader :commit_id, :repository_id, :created_at, :owner_id, :owner_type, :event_type, :base_commit, :head_commit, :result, :message, :pull_request, :pull_request_number, :pull_request_title, :branch, :tag - attributes :commit_id, :repository_id, :created_at, :owner_id, :owner_type, :event_type, :base_commit, :head_commit, :result, :message, :pull_request, :pull_request_number, :pull_request_title, :branch, :tag + attributes :commit_id, :repository_id, :created_at, :owner_id, :owner_type, :event_type, :base_commit, + :head_commit, :result, :message, :pull_request, :pull_request_number, :pull_request_title, :branch, :tag time :created_at # @!parse attr_reader :repository @@ -29,7 +32,7 @@ def inspect_info [ repository && repository.slug, event_type, branch || pull_request_number, result - ].compact.join(" ") + ].compact.join(' ') end end end diff --git a/lib/travis/client/restartable.rb b/lib/travis/client/restartable.rb index 4e829431..c6e8182f 100644 --- a/lib/travis/client/restartable.rb +++ b/lib/travis/client/restartable.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' module Travis diff --git a/lib/travis/client/session.rb b/lib/travis/client/session.rb index caaa046b..897f2e67 100644 --- a/lib/travis/client/session.rb +++ b/lib/travis/client/session.rb @@ -1,13 +1,15 @@ +# frozen_string_literal: true + require 'travis/client' require 'travis/version' require 'faraday' -require 'faraday_middleware' require 'travis/tools/system' require 'travis/tools/assets' +require 'faraday/rack' begin - require 'typhoeus/adapters/faraday' unless Travis::Tools::System.windows? + require 'faraday/typhoeus' unless Travis::Tools::System.windows? rescue LoadError end @@ -16,14 +18,14 @@ module Travis module Client class Session - PRIMITIVE = [nil, false, true] - SSL_OPTIONS = { :ca_file => Tools::Assets['cacert.pem'] } + PRIMITIVE = [nil, false, true].freeze + SSL_OPTIONS = { ca_file: Tools::Assets['cacert.pem'] } include Methods attr_reader :connection, :headers, :access_token, :instruments, :faraday_adapter, :agent_info, :ssl attr_accessor :debug_http - def initialize(options = Travis::Client::ORG_URI) + def initialize(options = Travis::Client::COM_URI) @headers = {} @cache = {} @instruments = [] @@ -32,10 +34,11 @@ def initialize(options = Travis::Client::ORG_URI) @faraday_adapter = defined?(Typhoeus) ? :typhoeus : :net_http @ssl = SSL_OPTIONS - options = { :uri => options } unless options.respond_to? :each_pair + options = { uri: options } unless options.respond_to? :each_pair options.each_pair { |key, value| public_send("#{key}=", value) } - raise ArgumentError, "neither :uri nor :connection specified" unless connection + raise ArgumentError, 'neither :uri nor :connection specified' unless connection + headers['Accept'] = 'application/vnd.travis-ci.2+json' set_user_agent check_ssl @@ -57,7 +60,7 @@ def ssl=(options) def uri=(uri) clear_cache! - self.connection = Faraday.new(:url => uri, :ssl => ssl) do |faraday| + self.connection = Faraday.new(url: uri, ssl:) do |faraday| faraday.request :url_encoded faraday.request :retry faraday.response :logger if debug_http @@ -93,21 +96,27 @@ def headers=(headers) end def find_one(entity, id = nil) - raise Travis::Client::Error, "cannot fetch #{entity}" unless entity.respond_to?(:many) and entity.many + raise Travis::Client::Error, "cannot fetch #{entity}" unless entity.respond_to?(:many) && entity.many return create_entity(entity, entity.id_field => id) if entity.id? id + cached(entity, :by, id) { fetch_one(entity, id) } end def find_many(entity, args = {}) - raise Travis::Client::Error, "cannot fetch #{entity}" unless entity.respond_to?(:many) and entity.many + raise Travis::Client::Error, "cannot fetch #{entity}" unless entity.respond_to?(:many) && entity.many + cached(entity, :many, args) { fetch_many(entity, args) } end def find_one_or_many(entity, args = nil) - raise Travis::Client::Error, "cannot fetch #{entity}" unless entity.respond_to?(:many) and entity.many + raise Travis::Client::Error, "cannot fetch #{entity}" unless entity.respond_to?(:many) && entity.many + cached(entity, :one_or_many, args) do - path = "/#{entity.many}" - path, args = "#{path}/#{args}", {} unless args.is_a? Hash + path = "/#{entity.many}" + unless args.is_a? Hash + path = "#{path}/#{args}" + args = {} + end result = get(path, args) one = result[entity.one] @@ -157,8 +166,9 @@ def load_entity(key, value) def preload(list) list.group_by(&:class).each do |type, instances| next unless type.preloadable? + ids = instances.map { |e| e.id unless e.complete? }.compact - find_many(type, :ids => ids) if ids.any? + find_many(type, ids:) if ids.any? end list end @@ -204,32 +214,40 @@ def delete_raw(*args) end def raw(verb, url, *args) - url = url.sub(/^\//, '') + url = url.sub(%r{^/}, '') result = instrumented(verb.to_s.upcase, url, *args) do - if url !~ /^https?:/ or url.start_with? api_endpoint + if url !~ (/^https?:/) || url.start_with?(api_endpoint) connection.public_send(verb, url, *args) else - Faraday.public_send(verb, url, *args) { |r| r.headers.delete("Authorization") } + Faraday.public_send(verb, url, *args) { |r| r.headers.delete('Authorization') } end end case result.status when 0 then raise Travis::Client::SSLError, 'SSL error: could not verify peer' - when 200..299 then JSON.parse(result.body) rescue result.body + when 200..299 then begin + JSON.parse(result.body) + rescue StandardError + result.body + end when 301, 303 then raw(:get, result.headers['Location']) when 302, 307, 308 then raw(verb, result.headers['Location']) - when 401 then raise Travis::Client::NotLoggedIn, 'not logged in' - when 403 then - body = JSON.parse(result.body) rescue {} - if body["error_type"] == "migrated_repository" - raise Travis::Client::RepositoryMigrated, body["error_message"] - else - raise Travis::Client::NotLoggedIn, 'invalid access token' + when 401 then raise Travis::Client::NotLoggedIn, 'not logged in' + when 403 + body = begin + JSON.parse(result.body) + rescue StandardError + {} end + raise Travis::Client::RepositoryMigrated, body['error_message'] if body['error_type'] == 'migrated_repository' + + raise Travis::Client::NotLoggedIn, 'invalid access token' + when 404 then raise Travis::Client::NotFound, result.body when 422 then raise Travis::Client::ValidationFailed, result.body - when 400..499 then raise Travis::Client::Error, "%s: %p" % [result.status, result.body] - when 500..599 then raise Travis::Client::Error, "server error (%s: %p)" % [result.status, result.body] + when 400..499 then raise Travis::Client::Error, format('%s: %p', result.status, result.body) + when 500..599 then raise Travis::Client::Error, + format('server error (%s: %p)', result.status, result.body) else raise Travis::Client::Error, "unhandled status code #{result.status}" end end @@ -264,83 +282,95 @@ def private_channels? private - def set_user_agent - adapter = Array === faraday_adapter ? faraday_adapter.first : faraday_adapter - adapter = adapter.to_s.capitalize.gsub(/_http_(.)/) { "::HTTP::#{$1.upcase}" }.gsub(/_http/, '::HTTP') - headers['User-Agent'] = "Travis/#{Travis::VERSION} (#{Travis::Tools::System.description(agent_info)}) Faraday/#{Faraday::VERSION} #{adapter}/#{adapter_version(adapter)}" - end + def set_user_agent + adapter = faraday_adapter.is_a?(Array) ? faraday_adapter.first : faraday_adapter + adapter = adapter.to_s.capitalize.gsub(/_http_(.)/) do + "::HTTP::#{::Regexp.last_match(1).upcase}" + end.gsub(/_http/, '::HTTP') + headers['User-Agent'] = + "Travis/#{Travis::VERSION} (#{Travis::Tools::System.description(agent_info)}) Faraday/#{Faraday::VERSION} #{adapter}/#{adapter_version(adapter)}" + end - def adapter_version(adapter) - version = Object.const_get(adapter).const_get("VERSION") - [*version].join('.') - rescue Exception - "unknown" - end + def adapter_version(adapter) + version = Object.const_get(adapter).const_get('VERSION') + [*version].join('.') + rescue Exception + 'unknown' + end - def instrumented(name, *args) - name = [name, *args.map(&:inspect)].join(" ") if args.any? - result = nil - chain = instruments + [proc { |n,l| result = yield }] - lift = proc { chain.shift.call(name, lift) } - lift.call - result - end + def instrumented(name, *args) + name = [name, *args.map(&:inspect)].join(' ') if args.any? + result = nil + chain = instruments + [proc { |_n, _l| result = yield }] + lift = proc { chain.shift.call(name, lift) } + lift.call + result + end - def create_entity(type, data) - return data if primitive?(data) - data = { type.id_field => data } if type.id? data - id = type.cast_id(data.fetch(type.id_field)) unless type.weak? - entity = id ? cached(type, :id, id) { type.new(self, id) } : type.new(self, nil) - entity.update_attributes(data) - entity - end + def create_entity(type, data) + return data if primitive?(data) - def primitive?(data) - PRIMITIVE.include? data - end + data = { type.id_field => data } if type.id? data + id = type.cast_id(data.fetch(type.id_field)) unless type.weak? + entity = id ? cached(type, :id, id) { type.new(self, id) } : type.new(self, nil) + entity.update_attributes(data) + entity + end - def error_message(e) - message = e.response[:body].to_str rescue e.message - JSON.parse(message).fetch('error').fetch('message') rescue message - end + def primitive?(data) + PRIMITIVE.include? data + end - def reset_entities - subcaches do |subcache| - subcache[:id].each_value { |e| e.attributes.clear } if subcache.include? :id - end + def error_message(e) + message = begin + e.response[:body].to_str + rescue StandardError + e.message end - - def clear_find_cache - subcaches do |subcache| - subcache.delete_if { |k, v| k != :id } - end + begin + JSON.parse(message).fetch('error').fetch('message') + rescue StandardError + message end + end - def subcaches - @cache.each_value do |subcache| - yield subcache if subcache.is_a? Hash - end + def reset_entities + subcaches do |subcache| + subcache[:id].each_value { |e| e.attributes.clear } if subcache.include? :id end + end - def fetch_one(entity, id = nil) - get("/#{entity.base_path}/#{id}")[entity.one] + def clear_find_cache + subcaches do |subcache| + subcache.delete_if { |k, _v| k != :id } end + end - def fetch_many(entity, params = {}) - get("/#{entity.base_path}/", params)[entity.many] + def subcaches + @cache.each_value do |subcache| + yield subcache if subcache.is_a? Hash end + end - def cached(*keys) - last = keys.pop - cache = keys.inject(@cache) { |store, key| store[key] ||= {} } - cache[last] ||= yield - end + def fetch_one(entity, id = nil) + get("/#{entity.base_path}/#{id}")[entity.one] + end - def check_ssl - raw(:head, '/') if ssl == SSL_OPTIONS - rescue Exception => error - self.ssl = {} if error.class == Travis::Client::SSLError - end + def fetch_many(entity, params = {}) + get("/#{entity.base_path}/", params)[entity.many] + end + + def cached(*keys) + last = keys.pop + cache = keys.inject(@cache) { |store, key| store[key] ||= {} } + cache[last] ||= yield + end + + def check_ssl + raw(:head, '/') if ssl == SSL_OPTIONS + rescue Exception => e + self.ssl = {} if e.instance_of?(Travis::Client::SSLError) + end end end end diff --git a/lib/travis/client/settings.rb b/lib/travis/client/settings.rb index 643e1bdd..e2d1bc1e 100644 --- a/lib/travis/client/settings.rb +++ b/lib/travis/client/settings.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client/weak_entity' require 'json' @@ -5,14 +7,17 @@ module Travis module Client class Settings < WeakEntity attr_accessor :repository + # @!parse attr_reader :builds_only_with_travis_yml, :build_pushes, :build_pull_requests, :maximum_number_of_builds, :auto_cancel_pushes, :auto_cancel_pull_requests - attributes :builds_only_with_travis_yml, :build_pushes, :build_pull_requests, :maximum_number_of_builds, :auto_cancel_pushes, :auto_cancel_pull_requests + attributes :builds_only_with_travis_yml, :build_pushes, :build_pull_requests, :maximum_number_of_builds, + :auto_cancel_pushes, :auto_cancel_pull_requests one :settings many :settings def save - raise "repository unknown" unless repository - result = session.patch("/repos/#{repository.id}/settings", JSON.dump("settings" => attributes)) + raise 'repository unknown' unless repository + + result = session.patch("/repos/#{repository.id}/settings", JSON.dump('settings' => attributes)) attributes.replace(result['settings'].attributes) self end diff --git a/lib/travis/client/singleton_setting.rb b/lib/travis/client/singleton_setting.rb index 43e5a288..d8eee29c 100644 --- a/lib/travis/client/singleton_setting.rb +++ b/lib/travis/client/singleton_setting.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'json' module Travis diff --git a/lib/travis/client/ssh_key.rb b/lib/travis/client/ssh_key.rb index 5a234fc4..3f24621c 100644 --- a/lib/travis/client/ssh_key.rb +++ b/lib/travis/client/ssh_key.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'json' module Travis diff --git a/lib/travis/client/states.rb b/lib/travis/client/states.rb index 58b62022..2a4ea416 100644 --- a/lib/travis/client/states.rb +++ b/lib/travis/client/states.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'travis/client' module Travis module Client module States - STATES = %w[created queued received started passed failed errored canceled ready] + STATES = %w[created queued received started passed failed errored canceled ready].freeze def ready? state == 'ready' @@ -11,7 +13,7 @@ def ready? def pending? check_state - %w[created started queued received ].include? state + %w[created started queued received].include? state end def started? @@ -30,7 +32,7 @@ def queued? end def finished? - not pending? + !pending? end def passed? @@ -90,9 +92,9 @@ def running? private - def check_state - raise Error, "unknown state %p for %p" % [state, self] unless STATES.include? state - end + def check_state + raise Error, format('unknown state %p for %p', state, self) unless STATES.include? state + end end end end diff --git a/lib/travis/client/user.rb b/lib/travis/client/user.rb index 57ce30a4..1af10274 100644 --- a/lib/travis/client/user.rb +++ b/lib/travis/client/user.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' module Travis diff --git a/lib/travis/client/weak_entity.rb b/lib/travis/client/weak_entity.rb index 1f52f00c..8425e5fe 100644 --- a/lib/travis/client/weak_entity.rb +++ b/lib/travis/client/weak_entity.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' module Travis @@ -10,7 +12,7 @@ def self.weak? end def self.id_field - raise "weak entities do not have id fields" + raise 'weak entities do not have id fields' end def self.id?(object) @@ -19,8 +21,9 @@ def self.id?(object) def self.cast_id(object) return object if id? object - raise "weak entities do not have id fields" + + raise 'weak entities do not have id fields' end end end -end \ No newline at end of file +end diff --git a/lib/travis/pro.rb b/lib/travis/pro.rb index 7a8e64cb..ba0577cc 100644 --- a/lib/travis/pro.rb +++ b/lib/travis/pro.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/client' module Travis diff --git a/lib/travis/pro/auto_login.rb b/lib/travis/pro/auto_login.rb index 3cbddeee..39b5ca58 100644 --- a/lib/travis/pro/auto_login.rb +++ b/lib/travis/pro/auto_login.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/pro' require 'travis/client/auto_login' Travis::Client::AutoLogin.new(Travis::Pro).authenticate diff --git a/lib/travis/tools/assets.rb b/lib/travis/tools/assets.rb index 2e10ebe7..6d429b4d 100644 --- a/lib/travis/tools/assets.rb +++ b/lib/travis/tools/assets.rb @@ -1,13 +1,16 @@ +# frozen_string_literal: true + require 'pathname' module Travis module Tools module Assets - BASE = File.expand_path('../../../../assets', __FILE__) - extend self + BASE = File.expand_path('../../../assets', __dir__) + + module_function def asset_path(file) Pathname.glob(File.expand_path(file, BASE)).tap do |x| - raise Travis::Client::AssetNotFound.new(file) if x.empty? + raise Travis::Client::AssetNotFound, file if x.empty? end.first.to_s end diff --git a/lib/travis/tools/completion.rb b/lib/travis/tools/completion.rb index c77d49bb..e20d88b0 100644 --- a/lib/travis/tools/completion.rb +++ b/lib/travis/tools/completion.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'travis/tools/assets' require 'travis/cli' require 'fileutils' @@ -8,7 +10,8 @@ module Tools module Completion RCS = ['.zshrc', '.bashrc'].map { |f| File.expand_path(f, ENV['HOME']) } include FileUtils - extend self + + module_function def config_path ENV.fetch('TRAVIS_CONFIG_PATH') { File.expand_path('.travis', ENV['HOME']) } @@ -20,12 +23,13 @@ def cmp_file def install_completion update_completion - source = "source " << cmp_file + source = 'source ' << cmp_file RCS.each do |file| - next unless File.exist? file and File.writable? file + next unless File.exist?(file) && File.writable?(file) next if File.read(file).include? source - File.open(file, "a") { |f| f.puts("", "# added by travis gem", "[ ! -s #{cmp_file} ] || #{source}") } + + File.open(file, 'a') { |f| f.puts('', '# added by travis gem', "[ ! -s #{cmp_file} ] || #{source}") } end end @@ -35,9 +39,9 @@ def update_completion end def completion_installed? - source = "source " << config_path + source = 'source ' << config_path RCS.each do |file| - next unless File.exist? file and File.writable? file + next unless File.exist?(file) && File.writable?(file) return false unless File.read(file).include? source end true diff --git a/lib/travis/tools/formatter.rb b/lib/travis/tools/formatter.rb index d506197b..f45cd437 100644 --- a/lib/travis/tools/formatter.rb +++ b/lib/travis/tools/formatter.rb @@ -1,30 +1,35 @@ +# frozen_string_literal: true + require 'time' module Travis module Tools class Formatter DAY = 24 * 60 * 60 - TIME_FORMAT = "%Y-%m-%d %H:%M:%S" - CONFIG_KEYS = ['rvm', 'gemfile', 'env', 'jdk', 'otp_release', 'php', 'node_js', 'perl', 'python', 'scala', 'compiler', 'os'] + TIME_FORMAT = '%Y-%m-%d %H:%M:%S' + CONFIG_KEYS = %w[rvm gemfile env jdk otp_release php node_js perl python scala + compiler os].freeze def duration(seconds, suffix = nil) - return "none" if seconds.nil? + return 'none' if seconds.nil? + seconds = (Time.now - seconds).to_i if seconds.is_a? Time output = [] minutes, seconds = seconds.divmod(60) hours, minutes = minutes.divmod(60) - output << "#{hours } hrs" if hours > 0 - output << "#{minutes} min" if minutes > 0 - output << "#{seconds} sec" if seconds > 0 or output.empty? + output << "#{hours} hrs" if hours.positive? + output << "#{minutes} min" if minutes.positive? + output << "#{seconds} sec" if seconds.positive? || output.empty? output << suffix if suffix - output.join(" ") + output.join(' ') end - def file_size(input, human = true) + def file_size(input, human: true) return "#{input} B" unless human - format = "B" + + format = 'B' iec = %w[KiB MiB GiB TiB PiB EiB ZiB YiB] - while human and input > 512 and iec.any? + while human && (input > 512) && iec.any? input /= 1024.0 format = iec.shift end @@ -33,8 +38,9 @@ def file_size(input, human = true) end def time(time) - return "not yet" if time.nil? # or time > Time.now - #return duration(time, "ago") if Time.now - time < DAY + return 'not yet' if time.nil? # or time > Time.now + + # return duration(time, "ago") if Time.now - time < DAY time.localtime.strftime(TIME_FORMAT) end @@ -43,8 +49,8 @@ def job_config(config) config.each_pair do |key, value| output << "#{key}: #{value}" if CONFIG_KEYS.include? key end - output.join(", ") + output.join(', ') end end end -end \ No newline at end of file +end diff --git a/lib/travis/tools/github.rb b/lib/travis/tools/github.rb index fafc9df1..f1b49e14 100644 --- a/lib/travis/tools/github.rb +++ b/lib/travis/tools/github.rb @@ -1,3 +1,6 @@ +# frozen_string_literal: true + +require 'English' require 'travis/tools/system' require 'yaml' require 'json' @@ -11,21 +14,21 @@ class Github GITHUB_HOST = 'github.com' attr_accessor :api_url, :scopes, :github_token, :drop_token, :callback, :explode, :after_tokens, - :login_header, :auto_token, :note, - :hub_path, :oauth_paths, :composer_path, :git_config_keys, :debug, :no_token, :check_token + :login_header, :auto_token, :note, + :hub_path, :oauth_paths, :composer_path, :git_config_keys, :debug, :no_token, :check_token def initialize(options = nil) @check_token = true - @ask_login = proc { raise "ask_login callback not set" } - @after_tokens = proc { } + @ask_login = proc { raise 'ask_login callback not set' } + @after_tokens = proc {} @debug = proc { |_| } @hub_path = ENV['HUB_CONFIG'] || '~/.config/hub' @oauth_paths = ['~/.github-oauth-token'] - @composer_path = "~/.composer/config.json" + @composer_path = '~/.composer/config.json' @note = 'temporary token' @git_config_keys = %w[github.token github.oauth-token] @scopes = ['user', 'user:email', 'repo'] # overridden by value from /config - options.each_pair { |k,v| send("#{k}=", v) if respond_to? "#{k}=" } if options + options&.each_pair { |k, v| send("#{k}=", v) if respond_to? "#{k}=" } yield self if block_given? end @@ -37,12 +40,13 @@ def each_token require 'gh' unless defined? GH possible_tokens { |t| yield(t) if acceptable?(t) } ensure - callback, self.callback = self.callback, nil - callback.call if callback + callback = self.callback + self.callback = nil + callback&.call end - def with_session(&block) - with_token { |t| GH.with(:token => t) { yield(t) } } + def with_session + with_token { |t| GH.with(token: t) { yield(t) } } end def possible_tokens(&block) @@ -66,6 +70,7 @@ def possible_tokens(&block) def git_tokens return unless System.has? 'git' + git_config_keys.each do |key| `git config --get-all #{key}`.each_line do |line| token = line.strip @@ -83,11 +88,11 @@ def composer_token def hub_tokens hub.fetch(host, []).each do |entry| - yield entry["oauth_token"] if entry["oauth_token"] + yield entry['oauth_token'] if entry['oauth_token'] end end - def oauth_file_tokens(&block) + def oauth_file_tokens oauth_paths.each do |path| file(path) do |content| token = content.strip @@ -103,12 +108,12 @@ def hub end def issuepost_token(&block) - security(:generic, :w, "-l issuepost.github.access_token", "issuepost token", &block) if host == 'github.com' + security(:generic, :w, '-l issuepost.github.access_token', 'issuepost token', &block) if host == 'github.com' end def github_for_mac_token(&block) command = '-s "github.com/mac"' - security(:internet, :w, command, "GitHub for Mac token", &block) if host == 'github.com' + security(:internet, :w, command, 'GitHub for Mac token', &block) if host == 'github.com' end def host @@ -117,57 +122,62 @@ def host def api_host return GITHUB_API unless api_url + api_url[%r{^(?:https?://)?([^/]+)}, 1] end def acceptable?(token) return true unless check_token - gh = GH.with(:token => token) - user = gh['user'] + + gh = GH.with(token:) + gh['user'] true - rescue GH::Error => error - debug "token is not acceptable: #{gh_error(error)}" + rescue GH::Error => e + debug "token is not acceptable: #{gh_error(e)}" false end private - def gh_error(error) - raise error if explode - if error.info.key? :response_body - JSON.parse(error.info[:response_body])["message"].to_s - else - "Unknown error" - end - end + def gh_error(error) + raise error if explode - def debug(line) - return unless @debug - @debug.call "Tools::Github: #{line}" + if error.info.key? :response_body + JSON.parse(error.info[:response_body])['message'].to_s + else + 'Unknown error' end + end - def security(type, key, arg, name) - return false unless System.has? 'security' - return false unless system "security find-#{type}-password #{arg} 2>/dev/null >/dev/null" - debug "requesting to load #{name} from keychain" - result = %x[security find-#{type}-password #{arg} -#{key} 2>&1].chomp - $?.success? ? yield(result) : debug("request denied") - rescue => e - raise e if explode - end + def debug(line) + return unless @debug - def file(path, default = nil) - path &&= File.expand_path(path) - @file ||= {} - @file[path] ||= if path and File.readable?(path) - debug "reading #{path}" - yield File.read(path) - end - @file[path] || default - rescue => e - raise e if explode - end + @debug.call "Tools::Github: #{line}" + end + + def security(type, key, arg, name) + return false unless System.has? 'security' + return false unless system "security find-#{type}-password #{arg} 2>/dev/null >/dev/null" + + debug "requesting to load #{name} from keychain" + result = `security find-#{type}-password #{arg} -#{key} 2>&1`.chomp + $CHILD_STATUS.success? ? yield(result) : debug('request denied') + rescue StandardError => e + raise e if explode + end + + def file(path, default = nil) + path &&= File.expand_path(path) + @file ||= {} + @file[path] ||= if path && File.readable?(path) + debug "reading #{path}" + yield File.read(path) + end + @file[path] || default + rescue StandardError => e + raise e if explode + end end end end diff --git a/lib/travis/tools/notification.rb b/lib/travis/tools/notification.rb index 3065fc9d..575e34d4 100644 --- a/lib/travis/tools/notification.rb +++ b/lib/travis/tools/notification.rb @@ -1,31 +1,35 @@ -require "travis" -require "travis/tools/system" -require "travis/tools/assets" -require "cgi" +# frozen_string_literal: true + +require 'travis' +require 'travis/tools/system' +require 'travis/tools/assets' +require 'cgi' module Travis module Tools module Notification - extend self - DEFAULT = [:osx, :growl, :libnotify] + module_function + + DEFAULT = %i[osx growl libnotify].freeze ICON = Assets['notifications/icon.png'] def new(*list) list.concat(DEFAULT) if list.empty? notification = list.map { |n| get(n) }.detect { |n| n.available? } - raise ArgumentError, "no notification system found (looked for #{list.join(", ")})" unless notification + raise ArgumentError, "no notification system found (looked for #{list.join(', ')})" unless notification + notification end def get(name) const = constants.detect { |c| c.to_s[/[^:]+$/].downcase == name.to_s } - raise ArgumentError, "unknown notifications type %p" % name unless const + raise ArgumentError, 'unknown notifications type %p' % name unless const + const_get(const).new end class Dummy - def notify(title, body) - end + def notify(title, body); end def available? true @@ -33,14 +37,15 @@ def available? end class OSX - BIN_PATH = Assets["notifications/Travis CI.app/Contents/MacOS/Travis CI"] + BIN_PATH = Assets['notifications/Travis CI.app/Contents/MacOS/Travis CI'] def notify(title, body) system BIN_PATH, '-message', body.to_s, '-title', title.to_s, '-sender', 'org.travis-ci.Travis-CI' end def available? - System.mac? and System.recent_version?(System.os_version.to_s, '10.8') and System.running? "NotificationCenter" + System.mac? and System.recent_version?(System.os_version.to_s, + '10.8') and System.running? 'NotificationCenter' end end @@ -50,7 +55,7 @@ def notify(title, body) end def available? - System.has? 'growlnotify' and System.running? "Growl" + System.has? 'growlnotify' and System.running? 'Growl' end end diff --git a/lib/travis/tools/safe_string.rb b/lib/travis/tools/safe_string.rb index a1cd1ce6..44e9ed58 100644 --- a/lib/travis/tools/safe_string.rb +++ b/lib/travis/tools/safe_string.rb @@ -1,10 +1,13 @@ +# frozen_string_literal: true + module Travis module Tools module SafeString - extend self + module_function def encoded(string) return string unless string.respond_to? :encode + string.encode 'utf-8' rescue Encoding::UndefinedConversionError string.force_encoding 'utf-8' diff --git a/lib/travis/tools/ssl_key.rb b/lib/travis/tools/ssl_key.rb index 474adb9e..70b2c3a0 100644 --- a/lib/travis/tools/ssl_key.rb +++ b/lib/travis/tools/ssl_key.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + require 'openssl' require 'base64' module Travis module Tools module SSLKey - extend self + module_function def generate_rsa(size = 2048) OpenSSL::PKey::RSA.generate(size) @@ -40,7 +42,8 @@ def sized_bytes(value) end def to_byte_array(num, *significant) - return significant if num.between?(-1, 0) and significant[0][7] == num[7] + return significant if num.between?(-1, 0) && (significant[0][7] == num[7]) + to_byte_array(*num.divmod(256)) + significant end end diff --git a/lib/travis/tools/system.rb b/lib/travis/tools/system.rb index bcbc6e80..d63f1961 100644 --- a/lib/travis/tools/system.rb +++ b/lib/travis/tools/system.rb @@ -1,7 +1,9 @@ +# frozen_string_literal: true + module Travis module Tools module System - extend self + module_function def recent_version?(version, minimum) version = version.split('.').map { |s| s.to_i } @@ -10,7 +12,7 @@ def recent_version?(version, minimum) end def windows? - File::ALT_SEPARATOR == "\\" + File::ALT_SEPARATOR == '\\' end def mac? @@ -22,7 +24,7 @@ def linux? end def unix? - not windows? + !windows? end def os @@ -52,7 +54,7 @@ def ruby_engine end def ruby_version - "%s-p%s" % [RUBY_VERSION, RUBY_PATCHLEVEL] + format('%s-p%s', RUBY_VERSION, RUBY_PATCHLEVEL) end def ruby @@ -65,22 +67,25 @@ def ruby end def rubygems - return "no RubyGems" unless defined? Gem + return 'no RubyGems' unless defined? Gem + "RubyGems #{Gem::VERSION}" end def description(*args) - [ full_os, ruby, rubygems, *args.flatten].compact.uniq.join("; ") + [full_os, ruby, rubygems, *args.flatten].compact.uniq.join('; ') end def has?(command) return false unless unix? + @has ||= {} @has.fetch(command) { @has[command] = system "command -v #{command} 2>/dev/null >/dev/null" } end def running?(app) return false unless unix? + system "/usr/bin/pgrep -u $(whoami) #{app} >/dev/null" end end diff --git a/lib/travis/version.rb b/lib/travis/version.rb index f34af8d8..386d27d6 100644 --- a/lib/travis/version.rb +++ b/lib/travis/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Travis - VERSION = '1.11.1' + VERSION = '1.12.0' end diff --git a/spec/cli/api_command_spec.rb b/spec/cli/api_command_spec.rb index 72d6d968..4ede1056 100644 --- a/spec/cli/api_command_spec.rb +++ b/spec/cli/api_command_spec.rb @@ -1,16 +1,19 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::ApiCommand do describe 'enterprise' do travis_config_path = ENV['TRAVIS_CONFIG_PATH'] + subject(:api_command) { described_class.new } before do ENV['TRAVIS_CONFIG_PATH'] = File.expand_path '../support', File.dirname(__FILE__) - config = subject.send(:load_file, 'fake_travis_config.yml') - subject.config = YAML.load(config) + config = api_command.send(:load_file, 'fake_travis_config.yml') + api_command.config = YAML.load(config) - subject.api_endpoint = 'https://travis-ci-enterprise/api' - subject.enterprise_name = 'default' + api_command.api_endpoint = 'https://travis-ci-enterprise/api' + api_command.enterprise_name = 'default' end after do @@ -19,19 +22,19 @@ describe '#setup_enterprise' do before do - subject.send(:setup_enterprise) + api_command.send(:setup_enterprise) end it 'keeps verifying peers' do - subject.insecure.should be_falsey + api_command.insecure.should be_falsey end it 'uses default CAs' do - subject.session.ssl.should_not include(:ca_file) + api_command.session.ssl.should_not include(:ca_file) end it 'flags endpoint' do - subject.endpoint_config.should include('enterprise' => true) + api_command.endpoint_config.should include('enterprise' => true) end end end diff --git a/spec/cli/cancel_spec.rb b/spec/cli/cancel_spec.rb index f825f75c..09ed3640 100644 --- a/spec/cli/cancel_spec.rb +++ b/spec/cli/cancel_spec.rb @@ -1,15 +1,13 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Cancel do example 'travis cancel' do run_cli('cancel', '-t', 'token').should be_success - $params['id'].should be == "4125095" - $params['entity'].should be == "builds" end example 'travis cancel 6180.1' do run_cli('cancel', '6180.1', '-t', 'token').should be_success - $params['id'].should be == "4125096" - $params['entity'].should be == "jobs" end end diff --git a/spec/cli/encrypt_file_spec.rb b/spec/cli/encrypt_file_spec.rb index 14d98185..e370f6db 100644 --- a/spec/cli/encrypt_file_spec.rb +++ b/spec/cli/encrypt_file_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'fileutils' require 'digest' @@ -5,22 +7,22 @@ describe Travis::CLI::EncryptFile do CMD_TARGET = 'README.md' - before :each do - Digest.stub(:hexencode).and_return "randomhex" # to avoid relying on Dir.pwd value for hex + before do + Digest.stub(:hexencode).and_return 'randomhex' # to avoid relying on Dir.pwd value for hex end - after :each do + after do FileUtils.rm_f "#{CMD_TARGET}.enc" end example "travis encrypt-file #{CMD_TARGET}" do run_cli('encrypt-file', CMD_TARGET).should be_success - File.exists?("#{CMD_TARGET}.enc").should be true + File.exist?("#{CMD_TARGET}.enc").should be true end example "travis encrypt-file #{CMD_TARGET} -a" do - run_cli('encrypt-file', CMD_TARGET, '-a') { |i| i.puts "n" }.should be_success - stdout.should match /Overwrite the config file/ - File.exists?("#{CMD_TARGET}.enc").should be true + run_cli('encrypt-file', CMD_TARGET, '-a') { |i| i.puts 'n' }.should be_success + stdout.should match(/Overwrite the config file/) + File.exist?("#{CMD_TARGET}.enc").should be true end end diff --git a/spec/cli/encrypt_spec.rb b/spec/cli/encrypt_spec.rb index bae81946..f1daa3f7 100644 --- a/spec/cli/encrypt_spec.rb +++ b/spec/cli/encrypt_spec.rb @@ -1,67 +1,69 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Encrypt do - example "travis encrypt foo" do + example 'travis encrypt foo' do run_cli('encrypt', 'foo').should be_success stdout.should match(/^".{60,}"\n$/) end - example "travis encrypt foo -r rails/rails" do + example 'travis encrypt foo -r rails/rails' do run_cli('encrypt', 'foo', '-r', 'rails/rails').should be_success stdout.should match(/^".{60,}"\n$/) end - example "travis encrypt foo -i" do + example 'travis encrypt foo -i' do run_cli('encrypt', 'foo', '-i', '--skip-completion-check', '-r', 'travis-ci/travis.rb').should be_success stdout.should start_with("Please add the following to your .travis.yml file:\n\n secure: ") end - example "cat foo | travis encrypt" do + example 'cat foo | travis encrypt' do run_cli('encrypt') { |i| i.puts('foo') } stdout.should match(/\A".{60,}"\n\Z/) end - example "cat foo\\nbar | travis encrypt -s" do + example 'cat foo\\nbar | travis encrypt -s' do run_cli('encrypt', '-s') { |i| i.puts("foo\nbar") } stdout.should match(/\A(".{60,}"\n){2}\Z/) end - example "cat foo\\nbar | travis encrypt" do + example 'cat foo\\nbar | travis encrypt' do run_cli('encrypt') { |i| i.puts("foo\nbar") } stdout.should match(/\A".{60,}"\n\Z/) end - example "travis encrypt rails/rails foo" do + example 'travis encrypt rails/rails foo' do run_cli('encrypt', 'rails/rails', 'foo').should be_success stderr.should match(/WARNING/) end - example "travis encrypt foo=foo/bar" do - run_cli("encrypt", "foo=foo/bar").should be_success + example 'travis encrypt foo=foo/bar' do + run_cli('encrypt', 'foo=foo/bar').should be_success stderr.should_not match(/WARNING/) end - example "travis encrypt FOO bar -a" do + example 'travis encrypt FOO bar -a' do described_class.any_instance.stub(:save_travis_config) - run_cli("encrypt", "FOO", "bar", "-a") { |i| i.puts "foo" }.should be_success + run_cli('encrypt', 'FOO', 'bar', '-a') { |i| i.puts 'foo' }.should be_success stderr.should match(/Environment variables in env\.global should be formatted as FOO=bar/) end - example "travis encrypt FOO bar -a foo" do + example 'travis encrypt FOO bar -a foo' do described_class.any_instance.stub(:save_travis_config) - run_cli("encrypt", "FOO", "bar", "-a", "foo") { |i| i.puts "foo" }.should be_success + run_cli('encrypt', 'FOO', 'bar', '-a', 'foo') { |i| i.puts 'foo' }.should be_success stdout.should match(/Overwrite the config file/) end - example "travis encrypt FOO bar -a --no-interactive" do + example 'travis encrypt FOO bar -a --no-interactive' do described_class.any_instance.stub(:save_travis_config) - run_cli("encrypt", "FOO", "bar", "-a", "--no-interactive").should be_success + run_cli('encrypt', 'FOO', 'bar', '-a', '--no-interactive').should be_success stderr.should match(/Environment variables in env\.global should be formatted as FOO=bar/) end - example "travis encrypt FOO=bar -a foo --no-interactive" do + example 'travis encrypt FOO=bar -a foo --no-interactive' do described_class.any_instance.stub(:save_travis_config) - run_cli("encrypt", "FOO=bar", "-a", "foo", "--no-interactive").should be_success + run_cli('encrypt', 'FOO=bar', '-a', 'foo', '--no-interactive').should be_success stdout.should be_empty end end diff --git a/spec/cli/endpoint_spec.rb b/spec/cli/endpoint_spec.rb index 86f43e07..d54bea3b 100644 --- a/spec/cli/endpoint_spec.rb +++ b/spec/cli/endpoint_spec.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Endpoint do - example "travis endpoint" do + example 'travis endpoint' do run_cli('endpoint').should be_success - stdout.should be == "https://api.travis-ci.org/\n" + stdout.should be == "https://api.travis-ci.com/\n" end - example "travis endpoint --pro" do + example 'travis endpoint --pro' do run_cli('endpoint', '--pro').should be_success stdout.should be == "https://api.travis-ci.com/\n" end - example "travis endpoint --com" do + example 'travis endpoint --com' do run_cli('endpoint', '--com').should be_success stdout.should be == "https://api.travis-ci.com/\n" end - example "travis endpoint -e http://localhost:3000/" do + example 'travis endpoint -e http://localhost:3000/' do run_cli('endpoint', '-e', 'http://localhost:3000/').should be_success stdout.should be == "http://localhost:3000/\n" end - example "TRAVIS_ENDPOINT=http://localhost:3000/ travis endpoint" do - ENV['TRAVIS_ENDPOINT'] = "http://localhost:3000/" + example 'TRAVIS_ENDPOINT=http://localhost:3000/ travis endpoint' do + ENV['TRAVIS_ENDPOINT'] = 'http://localhost:3000/' run_cli('endpoint').should be_success stdout.should be == "http://localhost:3000/\n" end - example "travis endpoint --github" do + example 'travis endpoint --github' do run_cli('endpoint', '--github').should be_success stdout.should be == "https://api.github.com\n" end - example "travis endpoint -i" do + example 'travis endpoint -i' do run_cli('endpoint', '-i').should be_success - stdout.should be == "API endpoint: https://api.travis-ci.org/\n" + stdout.should be == "API endpoint: https://api.travis-ci.com/\n" end end diff --git a/spec/cli/help_spec.rb b/spec/cli/help_spec.rb index 6d8087bd..727a002e 100644 --- a/spec/cli/help_spec.rb +++ b/spec/cli/help_spec.rb @@ -1,33 +1,35 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Help do - example "travis help" do + example 'travis help' do run_cli('help').should be_success - stdout.should include("Usage: travis COMMAND") + stdout.should include('Usage: travis COMMAND') end - example "travis --help" do + example 'travis --help' do run_cli('--help').should be_success - stdout.should include("Usage: travis COMMAND") + stdout.should include('Usage: travis COMMAND') end - example "travis -h" do + example 'travis -h' do run_cli('-h').should be_success - stdout.should include("Usage: travis COMMAND") + stdout.should include('Usage: travis COMMAND') end - example "travis -?" do + example 'travis -?' do run_cli('-?').should be_success - stdout.should include("Usage: travis COMMAND") + stdout.should include('Usage: travis COMMAND') end - example "travis help endpoint" do + example 'travis help endpoint' do run_cli('help', 'endpoint').should be_success - stdout.should include("Usage: travis endpoint [OPTIONS]") + stdout.should include('Usage: travis endpoint [OPTIONS]') end - example "travis endpoint --help" do + example 'travis endpoint --help' do run_cli('endpoint', '--help').should be_success - stdout.should include("Usage: travis endpoint [OPTIONS]") + stdout.should include('Usage: travis endpoint [OPTIONS]') end end diff --git a/spec/cli/history_spec.rb b/spec/cli/history_spec.rb index 9a4d4232..4520bca1 100644 --- a/spec/cli/history_spec.rb +++ b/spec/cli/history_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::History do diff --git a/spec/cli/init_spec.rb b/spec/cli/init_spec.rb index cc11649a..b5acbbbd 100644 --- a/spec/cli/init_spec.rb +++ b/spec/cli/init_spec.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Init do old_path = Dir.pwd tmp_path = File.expand_path('travis-spec-init', Dir.tmpdir) - before(:each) do + before do FileUtils.mkdir_p(tmp_path) Dir.chdir(tmp_path) FileUtils.rm('.travis.yml') if File.exist?('.travis.yml') end - after(:each) do + after do Dir.chdir(old_path) end - example "travis init fakelanguage" do + example 'travis init fakelanguage' do run_cli('init', 'fakelanguage', '--skip-enable', '-r', 'travis-ci/travis.rb').should_not be_success stderr.should be == "unknown language fakelanguage\n" end @@ -29,28 +31,28 @@ end example "travis init #{language} (.travis.yml already exists, using --force)" do - File.open(".travis.yml", "w") { |f| f << "old file" } + File.open('.travis.yml', 'w') { |f| f << 'old file' } run_cli('init', language, '--force', '--skip-enable', '-r', 'travis-ci/travis.rb').should be_success stdout.should be == ".travis.yml file created!\n" - File.read(".travis.yml").should_not be == "old file" + File.read('.travis.yml').should_not be == 'old file' end example "travis init #{language} (.travis.yml already exists, not using --force)" do - File.open(".travis.yml", "w") { |f| f << "old file" } + File.open('.travis.yml', 'w') { |f| f << 'old file' } run_cli('init', language, '--skip-enable', '-r', 'travis-ci/travis.rb').should_not be_success stderr.should be == ".travis.yml already exists, use --force to override\n" - File.read('.travis.yml').should be == "old file" + File.read('.travis.yml').should be == 'old file' end end describe 'travis init c' do - it_should_behave_like 'travis init', 'c' - let :result do run_cli('init', 'c', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'c' + it 'sets compiler' do result.should include('compiler') result['compiler'].should include('clang') @@ -59,17 +61,17 @@ end describe 'travis init clojure' do - it_should_behave_like 'travis init', 'clojure' + it_behaves_like 'travis init', 'clojure' end describe 'travis init cpp' do - it_should_behave_like 'travis init', 'cpp' - let :result do run_cli('init', 'cpp', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'cpp' + it 'sets compiler' do result.should include('compiler') result['compiler'].should include('clang') @@ -78,13 +80,13 @@ end describe 'travis init erlang' do - it_should_behave_like 'travis init', 'erlang' - let :result do run_cli('init', 'erlang', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'erlang' + it 'sets compiler' do result.should include('otp_release') result['otp_release'].should include('R16B') @@ -92,13 +94,13 @@ end describe 'travis init go' do - it_should_behave_like 'travis init', 'go' - let :result do run_cli('init', 'go', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'go' + it 'sets compiler' do result.should include('go') result['go'].should include('1.0') @@ -107,21 +109,21 @@ end describe 'travis init groovy' do - it_should_behave_like 'travis init', 'groovy' + it_behaves_like 'travis init', 'groovy' end describe 'travis init haskell' do - it_should_behave_like 'travis init', 'haskell' + it_behaves_like 'travis init', 'haskell' end describe 'travis init java' do - it_should_behave_like 'travis init', 'java' - let :result do run_cli('init', 'java', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'java' + it 'sets compiler' do result.should include('jdk') result['jdk'].should include('oraclejdk7') @@ -130,13 +132,13 @@ end describe 'travis init node_js' do - it_should_behave_like 'travis init', 'node_js' - let :result do run_cli('init', 'node_js', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'node_js' + it 'sets compiler' do result.should include('node_js') result['node_js'].should include('stable') @@ -146,17 +148,17 @@ end describe 'travis init objective-c' do - it_should_behave_like 'travis init', 'objective-c' + it_behaves_like 'travis init', 'objective-c' end describe 'travis init perl' do - it_should_behave_like 'travis init', 'perl' - let :result do run_cli('init', 'perl', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'perl' + it 'sets compiler' do result.should include('perl') result['perl'].should include('5.16') @@ -165,13 +167,13 @@ end describe 'travis init php' do - it_should_behave_like 'travis init', 'php' - let :result do run_cli('init', 'php', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'php' + it 'sets compiler' do result.should include('php') result['php'].should include('5.5') @@ -180,13 +182,13 @@ end describe 'travis init python' do - it_should_behave_like 'travis init', 'python' - let :result do run_cli('init', 'python', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'python' + it 'sets compiler' do result.should include('python') result['python'].should include('2.7') @@ -195,13 +197,13 @@ end describe 'travis init ruby' do - it_should_behave_like 'travis init', 'ruby' - let :result do run_cli('init', 'ruby', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'ruby' + it 'sets compiler' do result.should include('rvm') result['rvm'].should include('1.9.3') @@ -211,13 +213,13 @@ end describe 'travis init scala' do - it_should_behave_like 'travis init', 'scala' - let :result do run_cli('init', 'scala', '--skip-enable', '-r', 'travis-ci/travis.rb') YAML.load_file('.travis.yml') end + it_behaves_like 'travis init', 'scala' + it 'sets compiler' do result.should include('scala') result['scala'].should include('2.10.1') diff --git a/spec/cli/logs_spec.rb b/spec/cli/logs_spec.rb index a9216813..f664cdca 100644 --- a/spec/cli/logs_spec.rb +++ b/spec/cli/logs_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Logs do diff --git a/spec/cli/open_spec.rb b/spec/cli/open_spec.rb index 1562146f..be61ddf5 100644 --- a/spec/cli/open_spec.rb +++ b/spec/cli/open_spec.rb @@ -1,24 +1,26 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Open do example 'travis open -p' do run_cli('open', '-p').should be_success - stdout.should match(/https:\/\/travis-ci.org\/[\w\W]*\/travis\.rb/) + stdout.should match(%r{https://travis-ci.org/[\w\W]*/travis\.rb}) end example 'travis open 6180 -p' do run_cli('open', '6180', '-p').should be_success - stdout.should match(/https:\/\/travis-ci.org\/[\w\W]*\/travis\.rb\/builds\/4125095/) + stdout.should match(%r{https://travis-ci.org/[\w\W]*/travis\.rb/builds/4125095}) end example 'travis open 6180.1 -p' do run_cli('open', '6180.1', '-p').should be_success - stdout.should match(/https:\/\/travis-ci.org\/[\w\W]*\/travis\.rb\/jobs\/4125096/) + stdout.should match(%r{https://travis-ci.org/[\w\W]*/travis\.rb/jobs/4125096}) end example 'travis open -pg' do run_cli('open', '-pg').should be_success - stdout.should match(/https:\/\/github.com\/[\w\W]*\/travis\.rb/) + stdout.should match(%r{https://github.com/[\w\W]*/travis\.rb}) end example 'travis open 6180 -pg' do diff --git a/spec/cli/repo_command_spec.rb b/spec/cli/repo_command_spec.rb index eb262abf..9ab4376b 100644 --- a/spec/cli/repo_command_spec.rb +++ b/spec/cli/repo_command_spec.rb @@ -1,25 +1,29 @@ +# frozen_string_literal: true + require 'spec_helper' require 'uri' describe Travis::CLI::RepoCommand do describe '#parse_remote' do + subject(:repo_command) { described_class.new } + it 'handles git@github.com URIs' do - path = subject.send(:parse_remote, 'git@github.com:travis-ci/travis.rb.git') + path = repo_command.send(:parse_remote, 'git@github.com:travis-ci/travis.rb.git') path.should be == '/travis-ci/travis.rb.git' end it 'handles GitHub Enterprise URIS' do - path = subject.send(:parse_remote, 'git@example.com:travis-ci/travis.rb.git') + path = repo_command.send(:parse_remote, 'git@example.com:travis-ci/travis.rb.git') path.should be == '/travis-ci/travis.rb.git' end it 'handles HTTPS URIs' do - path = subject.send(:parse_remote, 'https://github.com/travis-ci/travis.rb.git') + path = repo_command.send(:parse_remote, 'https://github.com/travis-ci/travis.rb.git') path.should be == '/travis-ci/travis.rb.git' end it 'raises URI::InvalidURIError for invalid URIs' do - expect { subject.send(:parse_remote, "foo@example.com:baz/bar.git") }.to raise_error(URI::InvalidURIError) + expect { repo_command.send(:parse_remote, 'foo@example.com:baz/bar.git') }.to raise_error(URI::InvalidURIError) end end end diff --git a/spec/cli/restart_spec.rb b/spec/cli/restart_spec.rb index e1e17aef..9c62d954 100644 --- a/spec/cli/restart_spec.rb +++ b/spec/cli/restart_spec.rb @@ -1,15 +1,13 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Restart do example 'travis restart' do run_cli('restart', '-t', 'token').should be_success - $params['id'].should be == "4125095" - $params['entity'].should be == "builds" end example 'travis restart 6180.1' do run_cli('restart', '6180.1', '-t', 'token').should be_success - $params['entity'].should be == "jobs" - $params['id'].should be == "4125096" end end diff --git a/spec/cli/setup/service_spec.rb b/spec/cli/setup/service_spec.rb index 100a6430..010bfdc9 100644 --- a/spec/cli/setup/service_spec.rb +++ b/spec/cli/setup/service_spec.rb @@ -1,53 +1,52 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Setup::Service do subject :service do - repository = double('repository',{:slug => 'test_slug'}) - setup = double('Setup', :repository => repository) + repository = double('repository', { slug: 'test_slug' }) + setup = double('Setup', repository:) described_class.new(setup) end - + describe '#deploy' do - subject :deploy_config do - {'provider' => 'dummy'} + { 'provider' => 'dummy' } end - + before do allow(service).to receive(:configure).and_yield(deploy_config) allow(service).to receive(:on).and_return(nil) end - + context 'with no existing deploy section' do - it 'creates section contents without optional items' do service.send(:deploy, 'dummy') { |_| } expect(deploy_config).to include( - 'provider' => 'dummy', - 'skip_cleanup' => 'true' + 'provider' => 'dummy', + 'skip_cleanup' => 'true' ) end end - + context 'with existing deploy section' do it 'doesn\'t overwrite existing skip_cleanup' do - deploy_config['skip_cleanup']='false' + deploy_config['skip_cleanup'] = 'false' service.send(:deploy, 'dummy') { |_| } - expect(deploy_config).to include('skip_cleanup' => 'false') + expect(deploy_config).to include('skip_cleanup' => 'false') end it 'doesn\'t set skip_cleanup for v2' do - deploy_config['edge']='true' + deploy_config['edge'] = 'true' service.send(:deploy, 'dummy') { |_| } expect(deploy_config).not_to include('skip_cleanup') end - + it 'sets skip_cleanup for explicit v1' do - deploy_config['edge']='false' + deploy_config['edge'] = 'false' service.send(:deploy, 'dummy') { |_| } - expect(deploy_config).to include('skip_cleanup' => 'true') + expect(deploy_config).to include('skip_cleanup' => 'true') end end - end end diff --git a/spec/cli/setup_spec.rb b/spec/cli/setup_spec.rb index 0e7ecf49..989a0337 100644 --- a/spec/cli/setup_spec.rb +++ b/spec/cli/setup_spec.rb @@ -1,5 +1,3 @@ -require 'spec_helper' +# frozen_string_literal: true -describe Travis::CLI::Setup do - # TODO -end +require 'spec_helper' diff --git a/spec/cli/show_spec.rb b/spec/cli/show_spec.rb index 6291964d..1fc7261a 100644 --- a/spec/cli/show_spec.rb +++ b/spec/cli/show_spec.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Show do example 'show 6180.1' do run_cli('show', '6180.1', '-E').should be_success - stdout.should include("Config: ") - stdout.should include("env: GEM=railties") + stdout.should include('Config: ') + stdout.should include('env: GEM=railties') end end diff --git a/spec/cli/status_spec.rb b/spec/cli/status_spec.rb index ad9c40b6..9fdbcc2c 100644 --- a/spec/cli/status_spec.rb +++ b/spec/cli/status_spec.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Status do - example "travis status" do + example 'travis status' do run_cli('status').should be_success stdout.should be == "failed\n" end - example "travis status -x" do + example 'travis status -x' do run_cli('status', '-x').should_not be_success stdout.should be == "failed\n" end - example "travis status -q" do + example 'travis status -q' do run_cli('status', '-q').should be_success stdout.should be_empty end - example "travis status -pqx" do + example 'travis status -pqx' do run_cli('endpoint', '-pqx').should_not be_success stdout.should be_empty end - example "travis status -i" do + example 'travis status -i' do run_cli('status', '-i', '--skip-completion-check', '-r', 'travis-ci/travis.rb').should be_success stdout.should be == "build #6180 failed\n" end diff --git a/spec/cli/token_spec.rb b/spec/cli/token_spec.rb index 1c67c7b9..ea58399d 100644 --- a/spec/cli/token_spec.rb +++ b/spec/cli/token_spec.rb @@ -1,15 +1,17 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Token do - example "travis token (access token set)" do + example 'travis token (access token set)' do run_cli('token', '-t', 'super-secret').should be_success - stdout.should == "super-secret\n" + stdout.should stderr.should be_empty end - example "travis token -i (access token set)" do + example 'travis token -i (access token set)' do run_cli('token', '-it', 'super-secret').should be_success - stdout.should == "Your access token is super-secret\n" + stdout.should stderr.should be_empty end @@ -17,6 +19,6 @@ run_cli('token').should_not be_success stdout.should be_empty - stderr.should == "not logged in, please run #{File.basename($0)} login\n" + stderr.should == "not logged in, please run #{File.basename($PROGRAM_NAME)} login\n" end end diff --git a/spec/cli/version_spec.rb b/spec/cli/version_spec.rb index 3c9311c0..d5e2ff55 100644 --- a/spec/cli/version_spec.rb +++ b/spec/cli/version_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Version do diff --git a/spec/cli/whoami_spec.rb b/spec/cli/whoami_spec.rb index bc4c8609..504496c9 100644 --- a/spec/cli/whoami_spec.rb +++ b/spec/cli/whoami_spec.rb @@ -1,32 +1,34 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::CLI::Whoami do - example "travis whoami" do + example 'travis whoami' do run_cli('whoami').should_not be_success stdout.should be_empty - stderr.should be == "not logged in, please run #{File.basename $0} login\n" + stderr.should be == "not logged in, please run #{File.basename $PROGRAM_NAME} login\n" end - example "travis whoami --pro" do + example 'travis whoami --pro' do run_cli('whoami', '--pro').should_not be_success stdout.should be_empty - stderr.should be == "not logged in, please run #{File.basename $0} login --pro\n" + stderr.should be == "not logged in, please run #{File.basename $PROGRAM_NAME} login\n" end - example "travis whoami -t token" do + example 'travis whoami -t token' do run_cli('whoami', '-t', 'token').should be_success stdout.should be == "rkh\n" stderr.should be_empty end - example "TRAVIS_TOKEN=token travis whoami" do + example 'TRAVIS_TOKEN=token travis whoami' do ENV['TRAVIS_TOKEN'] = 'token' run_cli('whoami').should be_success stdout.should be == "rkh\n" stderr.should be_empty end - example "travis whoami -t token -i" do + example 'travis whoami -t token -i' do run_cli('whoami', '-t', 'token', '-i').should be_success stdout.should be == "You are rkh (Konstantin Haase)\n" stderr.should be_empty diff --git a/spec/client/account_spec.rb b/spec/client/account_spec.rb index cd8391c6..f18d7da3 100644 --- a/spec/client/account_spec.rb +++ b/spec/client/account_spec.rb @@ -1,32 +1,40 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client::Account do - context "from all accounts" do - let(:session) { Travis::Client.new } + context 'with all accounts' do subject { session.accounts.first } - its(:name) { should be == 'Konstantin Haase' } - its(:login) { should be == 'rkh' } - its(:type) { should be == 'user' } - its(:repos_count) { should be == 200 } - its(:inspect) { should be == "#" } - end - context "known account" do let(:session) { Travis::Client.new } - subject { session.account('rkh') } - its(:name) { should be == 'Konstantin Haase' } - its(:login) { should be == 'rkh' } - its(:type) { should be == 'user' } - its(:repos_count) { should be == 200 } - its(:inspect) { should be == "#" } + + its(:name) { is_expected.to be == 'Konstantin Haase' } + its(:login) { is_expected.to be == 'rkh' } + its(:type) { is_expected.to be == 'user' } + its(:repos_count) { is_expected.to be == 200 } + its(:inspect) { is_expected.to be == '#' } end - context "known account" do + context 'with known account' do + subject { session.account('rkh') } + let(:session) { Travis::Client.new } + + its(:name) { is_expected.to be == 'Konstantin Haase' } + its(:login) { is_expected.to be == 'rkh' } + its(:type) { is_expected.to be == 'user' } + its(:repos_count) { is_expected.to be == 200 } + its(:inspect) { is_expected.to be == '#' } + end + + context 'with known account and nil name' do subject { session.account('foo') } - its(:name) { should be_nil } - its(:login) { should be == 'foo' } - its(:type) { should be_nil } - its(:inspect) { should be == "#" } + + let(:session) { Travis::Client.new } + + its(:name) { is_expected.to be_nil } + its(:login) { is_expected.to be == 'foo' } + its(:type) { is_expected.to be_nil } + its(:inspect) { is_expected.to be == '#' } end end diff --git a/spec/client/auto_login_spec.rb b/spec/client/auto_login_spec.rb index 2d483dc7..cc934e14 100644 --- a/spec/client/auto_login_spec.rb +++ b/spec/client/auto_login_spec.rb @@ -1,22 +1,25 @@ +# frozen_string_literal: true + require 'travis/client/auto_login' require 'spec_helper' describe Travis::Client::AutoLogin do - let(:auto_login_with_token) { Travis::Client::AutoLogin.new(Travis::Client.new, { config_file: travis_config }) } - let(:auto_login_without_token) { Travis::Client::AutoLogin.new(Travis::Client.new) } - let(:travis_config) { File.expand_path("../support/fake_travis_config.yml", File.dirname(__FILE__)) } + let(:auto_login_with_token) { described_class.new(Travis::Client.new, { config_file: travis_config }) } + let(:auto_login_without_token) { described_class.new(Travis::Client.new) } + let(:travis_config) { File.expand_path('../support/fake_travis_config.yml', File.dirname(__FILE__)) } - context "authenticate" do - context "when user has a token in cli config" do - it "does not call Tools::Github#with_token" do - expect_any_instance_of(Travis::Tools::Github).to_not receive(:with_token) + context 'when user authenticates' do + context 'when user has a token in cli config' do + it 'does not call Tools::Github#with_token' do + expect_any_instance_of(Travis::Tools::Github).not_to receive(:with_token) auto_login_with_token.authenticate end end - context "when user does not have a token in cli config" do + context 'when user does not have a token in cli config' do before { auto_login_without_token.github.stub(:with_token).and_return(true) } - it "calls Tools::Github#with_token" do + + it 'calls Tools::Github#with_token' do expect(auto_login_without_token.github).to receive(:with_token) auto_login_without_token.authenticate end diff --git a/spec/client/broadcast_spec.rb b/spec/client/broadcast_spec.rb index 68c1f9af..371c42eb 100644 --- a/spec/client/broadcast_spec.rb +++ b/spec/client/broadcast_spec.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client::Broadcast do - let(:session) { Travis::Client.new } subject { session.broadcasts.first } - its(:id) { should be == 1 } - its(:message) { should be == "Hello!" } + let(:session) { Travis::Client.new } + its(:id) { is_expected.to be == 1 } + its(:message) { is_expected.to be == 'Hello!' } end diff --git a/spec/client/build_spec.rb b/spec/client/build_spec.rb index 11ff9615..d7788ae2 100644 --- a/spec/client/build_spec.rb +++ b/spec/client/build_spec.rb @@ -1,31 +1,35 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client::Build do + subject { session.build(4_125_095) } + let(:session) { Travis::Client.new } - subject { session.build(4125095) } - its(:number) { should be == '6180' } - its(:state) { should be == 'failed' } - its(:duration) { should be == 5019 } - its(:started_at) { should be_a(Time) } - its(:finished_at) { should be_nil } - its(:inspect) { should be == "#" } - its(:color) { should be == 'red' } - its(:commit) { should be_a(Travis::Client::Commit) } - its(:jobs) { should be_an(Array) } - its(:repository) { should be == session.repo('rails/rails') } - it { should be == subject.repository.last_build } + its(:number) { is_expected.to be == '6180' } + its(:state) { is_expected.to be == 'failed' } + its(:duration) { is_expected.to be == 5019 } + its(:started_at) { is_expected.to be_a(Time) } + its(:finished_at) { is_expected.to be_nil } + its(:inspect) { is_expected.to be == '#' } + its(:color) { is_expected.to be == 'red' } + its(:commit) { is_expected.to be_a(Travis::Client::Commit) } + its(:jobs) { is_expected.to be_an(Array) } + its(:repository) { is_expected.to be == session.repo('rails/rails') } + + it { is_expected.to be == subject.repository.last_build } - it { should_not be_pending } - it { should be_started } - it { should be_finished } - it { should_not be_passed } - it { should_not be_errored } - it { should be_failed } - it { should_not be_canceled } - it { should be_created } - it { should be_red } - it { should_not be_green } - it { should_not be_yellow } - it { should be_unsuccessful } + it { is_expected.not_to be_pending } + it { is_expected.to be_started } + it { is_expected.to be_finished } + it { is_expected.not_to be_passed } + it { is_expected.not_to be_errored } + it { is_expected.to be_failed } + it { is_expected.not_to be_canceled } + it { is_expected.to be_created } + it { is_expected.to be_red } + it { is_expected.not_to be_green } + it { is_expected.not_to be_yellow } + it { is_expected.to be_unsuccessful } end diff --git a/spec/client/commit_spec.rb b/spec/client/commit_spec.rb index 64b8d30c..dad9a315 100644 --- a/spec/client/commit_spec.rb +++ b/spec/client/commit_spec.rb @@ -1,22 +1,25 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client::Build do + subject { session.build(4_125_095).commit } + let(:session) { Travis::Client.new } - subject { session.build(4125095).commit } - its(:sha) { should be == 'a0265b98f16c6e33be32aa3f57231d1189302400' } - its(:short_sha) { should be == 'a0265b9' } - its(:branch) { should be == 'master' } - its(:message) { should be == 'Associaton -> Association' } - its(:committed_at) { should be_a(Time) } - its(:author_name) { should be == 'Steve Klabnik' } - its(:author_email) { should be == 'steve@steveklabnik.com' } - its(:committer_name) { should be == 'Steve Klabnik' } - its(:committer_email) { should be == 'steve@steveklabnik.com' } - its(:compare_url) { should be == 'https://github.com/rails/rails/compare/6581d798e830...a0265b98f16c' } - its(:subject) { should be == 'Associaton -> Association' } + its(:sha) { is_expected.to be == 'a0265b98f16c6e33be32aa3f57231d1189302400' } + its(:short_sha) { is_expected.to be == 'a0265b9' } + its(:branch) { is_expected.to be == 'master' } + its(:message) { is_expected.to be == 'Associaton -> Association' } + its(:committed_at) { is_expected.to be_a(Time) } + its(:author_name) { is_expected.to be == 'Steve Klabnik' } + its(:author_email) { is_expected.to be == 'steve@steveklabnik.com' } + its(:committer_name) { is_expected.to be == 'Steve Klabnik' } + its(:committer_email) { is_expected.to be == 'steve@steveklabnik.com' } + its(:compare_url) { is_expected.to be == 'https://github.com/rails/rails/compare/6581d798e830...a0265b98f16c' } + its(:subject) { is_expected.to be == 'Associaton -> Association' } - specify "with missing data" do - session.load("commit" => { "id" => 12 })['commit'].subject.should be_empty + specify 'with missing data' do + session.load('commit' => { 'id' => 12 })['commit'].subject.should be_empty end end diff --git a/spec/client/job_spec.rb b/spec/client/job_spec.rb index e0713a1f..237abfdb 100644 --- a/spec/client/job_spec.rb +++ b/spec/client/job_spec.rb @@ -1,30 +1,34 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client::Job do + subject { session.job(4_125_097) } + let(:session) { Travis::Client.new } - subject { session.job(4125097) } - its(:number) { should be == '6180.2' } - its(:state) { should be == 'passed' } - its(:started_at) { should be_a(Time) } - its(:finished_at) { should be_a(Time) } - its(:inspect) { should be == "#" } - its(:color) { should be == 'green' } - its(:commit) { should be_a(Travis::Client::Commit) } - its(:repository) { should be == session.repo('rails/rails') } - its(:duration) { should be == 905 } - it { should be == subject.build.jobs[1] } + its(:number) { is_expected.to be == '6180.2' } + its(:state) { is_expected.to be == 'passed' } + its(:started_at) { is_expected.to be_a(Time) } + its(:finished_at) { is_expected.to be_a(Time) } + its(:inspect) { is_expected.to be == '#' } + its(:color) { is_expected.to be == 'green' } + its(:commit) { is_expected.to be_a(Travis::Client::Commit) } + its(:repository) { is_expected.to be == session.repo('rails/rails') } + its(:duration) { is_expected.to be == 905 } + + it { is_expected.to be == subject.build.jobs[1] } - it { should_not be_pending } - it { should be_started } - it { should be_finished } - it { should be_passed } - it { should_not be_errored } - it { should_not be_failed } - it { should_not be_canceled } - it { should be_created } - it { should_not be_red } - it { should be_green } - it { should_not be_yellow } - it { should_not be_unsuccessful } + it { is_expected.not_to be_pending } + it { is_expected.to be_started } + it { is_expected.to be_finished } + it { is_expected.to be_passed } + it { is_expected.not_to be_errored } + it { is_expected.not_to be_failed } + it { is_expected.not_to be_canceled } + it { is_expected.to be_created } + it { is_expected.not_to be_red } + it { is_expected.to be_green } + it { is_expected.not_to be_yellow } + it { is_expected.not_to be_unsuccessful } end diff --git a/spec/client/methods_spec.rb b/spec/client/methods_spec.rb index 018e51d2..f39fed60 100644 --- a/spec/client/methods_spec.rb +++ b/spec/client/methods_spec.rb @@ -1,13 +1,17 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client::Methods do + subject { OpenStruct.new(session:).extend(described_class) } + let(:session) { Travis::Client.new } - subject { OpenStruct.new(:session => session).extend(Travis::Client::Methods) } + before { subject.access_token = 'token' } - its(:api_endpoint) { should be == 'https://api.travis-ci.org/' } - its(:repos) { should be == session.find_many(Travis::Client::Repository) } - its(:user) { should be == session.find_one(Travis::Client::User) } + its(:api_endpoint) { is_expected.to be == 'https://api.travis-ci.com/' } + its(:repos) { is_expected.to be == session.find_many(Travis::Client::Repository) } + its(:user) { is_expected.to be == session.find_one(Travis::Client::User) } it 'fetches a single repo' do subject.repo(891).slug.should be == 'rails/rails' diff --git a/spec/client/namespace_spec.rb b/spec/client/namespace_spec.rb index 078cfc81..83812d27 100644 --- a/spec/client/namespace_spec.rb +++ b/spec/client/namespace_spec.rb @@ -1,18 +1,22 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client::Namespace do - it { should be_a(Travis::Client::Methods) } + subject(:namespace) { described_class.new } + + it { is_expected.to be_a(Travis::Client::Methods) } it 'creates a dummy for repos' do - repo = subject::Repository + repo = namespace::Repository repo.find_one('rails/rails').should be_a(Travis::Client::Repository) repo.find_many.should be_an(Array) repo.current.should be == repo.find_many end it 'creates a dummy for user' do - subject.access_token = 'token' - user = subject::User + namespace.access_token = 'token' + user = namespace::User user.find_one.should be_a(Travis::Client::User) user.current.should be == user.find_one end diff --git a/spec/client/repository_spec.rb b/spec/client/repository_spec.rb index caf75a74..32972e9d 100644 --- a/spec/client/repository_spec.rb +++ b/spec/client/repository_spec.rb @@ -1,39 +1,42 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client::Repository do + subject(:repository) { session.repo('rails/rails') } + let(:session) { Travis::Client.new } - subject { session.repo('rails/rails') } - its(:slug) { should be == 'rails/rails' } - its(:description) { should_not be_empty } - its(:last_build_id) { should be == 4125095 } - its(:last_build_number) { should be == '6180' } - its(:last_build_state) { should be == 'failed' } - its(:last_build_duration) { should be == 5019 } - its(:last_build_started_at) { should be_a(Time) } - its(:last_build_finished_at) { should be_nil } - its(:inspect) { should be == "#" } - its(:key) { should be_a(Travis::Client::Repository::Key) } - its(:last_build) { should be_a(Travis::Client::Build) } - its(:color) { should be == 'red' } - its(:github_language) { should be == 'Ruby' } - its(:owner_name) { should be == 'rails' } - its(:owner) { should be == session.account("rails") } + its(:slug) { is_expected.to be == 'rails/rails' } + its(:description) { is_expected.not_to be_empty } + its(:last_build_id) { is_expected.to be == 4_125_095 } + its(:last_build_number) { is_expected.to be == '6180' } + its(:last_build_state) { is_expected.to be == 'failed' } + its(:last_build_duration) { is_expected.to be == 5019 } + its(:last_build_started_at) { is_expected.to be_a(Time) } + its(:last_build_finished_at) { is_expected.to be_nil } + its(:inspect) { is_expected.to be == '#' } + its(:key) { is_expected.to be_a(Travis::Client::Repository::Key) } + its(:last_build) { is_expected.to be_a(Travis::Client::Build) } + its(:color) { is_expected.to be == 'red' } + its(:github_language) { is_expected.to be == 'Ruby' } + its(:owner_name) { is_expected.to be == 'rails' } + its(:owner) { is_expected.to be == session.account('rails') } - it { should_not be_pending } - it { should be_started } - it { should be_finished } - it { should_not be_passed } - it { should_not be_errored } - it { should be_failed } - it { should_not be_canceled } - it { should be_created } - it { should be_red } - it { should_not be_green } - it { should_not be_yellow } - it { should be_unsuccessful } + it { is_expected.not_to be_pending } + it { is_expected.to be_started } + it { is_expected.to be_finished } + it { is_expected.not_to be_passed } + it { is_expected.not_to be_errored } + it { is_expected.to be_failed } + it { is_expected.not_to be_canceled } + it { is_expected.to be_created } + it { is_expected.to be_red } + it { is_expected.not_to be_green } + it { is_expected.not_to be_yellow } + it { is_expected.to be_unsuccessful } - it 'should expose the pubkey fingerprint' do - subject.public_key.fingerprint.should be == 'foobar' + it 'exposes the pubkey fingerprint' do + repository.public_key.fingerprint.should be == 'foobar' end end diff --git a/spec/client/session_spec.rb b/spec/client/session_spec.rb index 595eb8be..267a0dcf 100644 --- a/spec/client/session_spec.rb +++ b/spec/client/session_spec.rb @@ -1,165 +1,169 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client::Session do - it { should be_a(Travis::Client::Methods) } + subject(:session) { described_class.new } + + it { is_expected.to be_a(Travis::Client::Methods) } - describe "uri" do - its(:uri) { should be == "https://api.travis-ci.org/" } + describe 'uri' do + its(:uri) { is_expected.to be == 'https://api.travis-ci.com/' } it 'can be set as argument' do - Travis::Client::Session.new('http://foo/').uri.should be == 'http://foo/' + described_class.new('http://foo/').uri.should be == 'http://foo/' end it 'can be set as hash argument' do - Travis::Client::Session.new(:uri => 'http://foo/').uri.should be == 'http://foo/' + described_class.new(uri: 'http://foo/').uri.should be == 'http://foo/' end end - describe "access_token" do - its(:access_token) { should be_nil } + describe 'access_token' do + its(:access_token) { is_expected.to be_nil } it 'gives authenticated access if set' do - subject.access_token = 'token' - subject.user.login.should be == 'rkh' + session.access_token = 'token' + session.user.login.should be == 'rkh' end it 'raises if token is not set' do - expect { subject.user.login }.to raise_error(Travis::Client::Error) + expect { session.user.login }.to raise_error(Travis::Client::Error) end end - describe "connection" do - its(:connection) { should be_a(Faraday::Connection) } + describe 'connection' do + its(:connection) { is_expected.to be_a(Faraday::Connection) } it 'creates a new connection when changing the uri' do - old_connection = subject.connection - subject.uri = 'http://localhost:3000' - subject.connection.should_not be == old_connection + old_connection = session.connection + session.uri = 'http://localhost:3000' + session.connection.should_not be == old_connection end end - describe "headers" do + describe 'headers' do it 'propagates headers to connection headers' do - subject.headers['foo'] = 'bar' - subject.connection.headers.should include('foo') + session.headers['foo'] = 'bar' + session.connection.headers.should include('foo') end it 'propagates headers to new connections' do - subject.headers['foo'] = 'bar' - subject.connection = Faraday::Connection.new - subject.connection.headers.should include('foo') + session.headers['foo'] = 'bar' + session.connection = Faraday::Connection.new + session.connection.headers.should include('foo') end it 'is possible to set headers as constructor option' do - Travis::Client::Session.new(:headers => {'foo' => 'bar'}, :uri => 'http://localhost:3000/'). - connection.headers['foo'].should be == 'bar' + described_class.new(headers: { 'foo' => 'bar' }, uri: 'http://localhost:3000/') + .connection.headers['foo'].should be == 'bar' end it 'sets a User-Agent' do - subject.headers['User-Agent'].should include("Travis/#{Travis::VERSION}") - subject.headers['User-Agent'].should include("Faraday/#{Faraday::VERSION}") - subject.headers['User-Agent'].should include("Rack/#{Rack.version}") - subject.headers['User-Agent'].should include("Ruby #{RUBY_VERSION}") + session.headers['User-Agent'].should include("Travis/#{Travis::VERSION}") + session.headers['User-Agent'].should include("Faraday/#{Faraday::VERSION}") + session.headers['User-Agent'].should include("Rack/#{Rack.version}") + session.headers['User-Agent'].should include("Ruby #{RUBY_VERSION}") end it 'allows adding custom info to the User-Agent' do - subject.agent_info = "foo" - subject.headers['User-Agent'].should include("foo") - subject.headers['User-Agent'].should include("Travis/#{Travis::VERSION}") - subject.headers['User-Agent'].should include("Faraday/#{Faraday::VERSION}") - subject.headers['User-Agent'].should include("Rack/#{Rack.version}") - subject.headers['User-Agent'].should include("Ruby #{RUBY_VERSION}") + session.agent_info = 'foo' + session.headers['User-Agent'].should include('foo') + session.headers['User-Agent'].should include("Travis/#{Travis::VERSION}") + session.headers['User-Agent'].should include("Faraday/#{Faraday::VERSION}") + session.headers['User-Agent'].should include("Rack/#{Rack.version}") + session.headers['User-Agent'].should include("Ruby #{RUBY_VERSION}") end end - describe "find_one" do + describe 'find_one' do it 'finds one instance' do - repo = subject.find_one(Travis::Client::Repository, 'rails/rails') + repo = session.find_one(Travis::Client::Repository, 'rails/rails') repo.should be_a(Travis::Client::Repository) repo.slug.should be == 'rails/rails' end end - describe "find_many" do + describe 'find_many' do it 'finds many instances' do - repos = subject.find_many(Travis::Client::Repository) + repos = session.find_many(Travis::Client::Repository) repos.should be_an(Array) repos.each { |repo| repo.should be_a(Travis::Client::Repository) } - repos.first.slug.should be == "pypug/django-mango" + repos.first.slug.should be == 'pypug/django-mango' end end - describe "find_one_or_many" do + describe 'find_one_or_many' do it 'finds one instance' do - subject.access_token = 'token' - subject.find_one_or_many(Travis::Client::User).should be_a(Travis::Client::User) + session.access_token = 'token' + session.find_one_or_many(Travis::Client::User).should be_a(Travis::Client::User) end it 'finds many instances' do - subject.find_one_or_many(Travis::Client::Repository).should be_an(Array) + session.find_one_or_many(Travis::Client::Repository).should be_an(Array) end end - describe "reload" do + describe 'reload' do it 'reloads an instance' do - Travis::Client::Session::FakeAPI.rails_description = "Ruby on Rails" - rails = subject.find_one(Travis::Client::Repository, 'rails/rails') + Travis::Client::Session::FakeAPI.rails_description = 'Ruby on Rails' + rails = session.find_one(Travis::Client::Repository, 'rails/rails') rails.description.should be == 'Ruby on Rails' Travis::Client::Session::FakeAPI.rails_description = 'Rails on the Rubies' rails.description.should be == 'Ruby on Rails' - subject.reload(rails) + session.reload(rails) rails.description.should be == 'Rails on the Rubies' end end - describe "get" do + describe 'get' do it 'fetches a payload and substitutes values with entities' do - result = subject.get('/repos/') - result['repos'].first.slug.should be == "pypug/django-mango" + result = session.get('/repos/') + result['repos'].first.slug.should be == 'pypug/django-mango' end end - describe "clear_cache" do + describe 'clear_cache' do it 'resets all the entities' do - Travis::Client::Session::FakeAPI.rails_description = "Ruby on Rails" - rails = subject.find_one(Travis::Client::Repository, 'rails/rails') + Travis::Client::Session::FakeAPI.rails_description = 'Ruby on Rails' + rails = session.find_one(Travis::Client::Repository, 'rails/rails') rails.description.should be == 'Ruby on Rails' Travis::Client::Session::FakeAPI.rails_description = 'Rails on the Rubies' rails.description.should be == 'Ruby on Rails' - subject.clear_cache + session.clear_cache rails.description.should be == 'Rails on the Rubies' end it 'keeps entries in the identity map' do - rails = subject.repo('rails/rails') - subject.clear_cache - subject.repo('rails/rails').should be_equal(rails) + rails = session.repo('rails/rails') + session.clear_cache + session.repo('rails/rails').should be_equal(rails) end end - describe "clear_cache!" do + describe 'clear_cache!' do it 'resets all the entities' do - Travis::Client::Session::FakeAPI.rails_description = "Ruby on Rails" - rails = subject.find_one(Travis::Client::Repository, 'rails/rails') + Travis::Client::Session::FakeAPI.rails_description = 'Ruby on Rails' + rails = session.find_one(Travis::Client::Repository, 'rails/rails') rails.description.should be == 'Ruby on Rails' Travis::Client::Session::FakeAPI.rails_description = 'Rails on the Rubies' rails.description.should be == 'Ruby on Rails' - subject.clear_cache! + session.clear_cache! rails.description.should be == 'Rails on the Rubies' end it 'does not keep entries in the identity map' do - rails = subject.repo('rails/rails') - subject.clear_cache! - subject.repo('rails/rails').should_not be_equal(rails) + rails = session.repo('rails/rails') + session.clear_cache! + session.repo('rails/rails').should_not be_equal(rails) end end - describe "session" do - its(:session) { should eq(subject) } + describe 'session' do + its(:session) { is_expected.to eq(session) } end - describe "config" do - its(:config) { should be == {"host" => "travis-ci.org"}} + describe 'config' do + its(:config) { is_expected.to be == { 'host' => 'travis-ci.org' } } end end diff --git a/spec/client/user_spec.rb b/spec/client/user_spec.rb index ddef2ed4..c2d2d58f 100644 --- a/spec/client/user_spec.rb +++ b/spec/client/user_spec.rb @@ -1,16 +1,19 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client::User do # attributes :login, :name, :email, :gravatar_id, :locale, :is_syncing, :synced_at, :correct_scopes - subject { Travis::Client.new(:access_token => 'token').user } - its(:login) { should be == 'rkh' } - its(:name) { should be == 'Konstantin Haase' } - its(:email) { should be == 'konstantin.haase@gmail.com' } - its(:gravatar_id) { should be == '5c2b452f6eea4a6d84c105ebd971d2a4' } - its(:locale) { should be == 'en' } - its(:is_syncing) { should be false } - its(:synced_at) { should be_a(Time) } + subject { Travis::Client.new(access_token: 'token').user } + + its(:login) { is_expected.to be == 'rkh' } + its(:name) { is_expected.to be == 'Konstantin Haase' } + its(:email) { is_expected.to be == 'konstantin.haase@gmail.com' } + its(:gravatar_id) { is_expected.to be == '5c2b452f6eea4a6d84c105ebd971d2a4' } + its(:locale) { is_expected.to be == 'en' } + its(:is_syncing) { is_expected.to be false } + its(:synced_at) { is_expected.to be_a(Time) } - it { should_not be_syncing } - it { should be_correct_scopes } + it { is_expected.not_to be_syncing } + it { is_expected.to be_correct_scopes } end diff --git a/spec/client_spec.rb b/spec/client_spec.rb index 98ad5fe4..8a7110c8 100644 --- a/spec/client_spec.rb +++ b/spec/client_spec.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Client do - its(:new) { should be_a(Travis::Client::Session) } + its(:new) { is_expected.to be_a(Travis::Client::Session) } it 'accepts string argument' do - Travis::Client.new('http://foo/').uri.should be == 'http://foo/' + described_class.new('http://foo/').uri.should be == 'http://foo/' end it 'accepts options hash with string keys' do - Travis::Client.new('uri' => 'http://foo/').uri.should be == 'http://foo/' + described_class.new('uri' => 'http://foo/').uri.should be == 'http://foo/' end it 'accepts options hash with symbol keys' do - Travis::Client.new(:uri => 'http://foo/').uri.should be == 'http://foo/' + described_class.new(uri: 'http://foo/').uri.should be == 'http://foo/' end end diff --git a/spec/pro_spec.rb b/spec/pro_spec.rb index bae4798e..fa13aae2 100644 --- a/spec/pro_spec.rb +++ b/spec/pro_spec.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis::Pro do - it { should be_a(Travis::Client::Namespace) } - its(:api_endpoint) { should be == 'https://api.travis-ci.com/' } + it { is_expected.to be_a(Travis::Client::Namespace) } + its(:api_endpoint) { is_expected.to be == 'https://api.travis-ci.com/' } it 'has a nice inspect on entities' do - Travis::Pro::Repository.find('rails/rails').inspect.should be == "#" + Travis::Pro::Repository.find('rails/rails').inspect.should be == '#' end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 99d592c8..bea972ee 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'support/fake_api' require 'support/fake_github' require 'support/helpers' @@ -21,7 +23,7 @@ temp_dir = File.expand_path('travis-spec', Dir.tmpdir) FileUtils.rm_rf(temp_dir) FileUtils.mkdir_p(temp_dir) - ENV.delete_if { |k,v| k.start_with? "TRAVIS_" } + ENV.delete_if { |k, _v| k.start_with? 'TRAVIS_' } ENV['TRAVIS_CONFIG_PATH'] = File.expand_path('travis', temp_dir) end diff --git a/spec/support/fake_api.rb b/spec/support/fake_api.rb index b1a1a8d6..69c98bb3 100644 --- a/spec/support/fake_api.rb +++ b/spec/support/fake_api.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'sinatra/base' require 'travis/client/session' @@ -9,7 +11,7 @@ class Session class FakeAPI < Sinatra::Base disable :protection enable :raise_errors - set :rails_description, "Ruby on Rails" + set :rails_description, 'Ruby on Rails' before do content_type :json @@ -20,663 +22,663 @@ def authorized? end get '/' do - "{}" + '{}' end get '/users/' do halt(403, 'wrong token') unless authorized? - {"user"=> - {"id"=>267, - "name"=>"Konstantin Haase", - "login"=>"rkh", - "email"=>"konstantin.haase@gmail.com", - "gravatar_id"=>"5c2b452f6eea4a6d84c105ebd971d2a4", - "locale"=>"en", - "is_syncing"=>false, - "synced_at"=>"2012-10-27T12:52:25Z", - "correct_scopes"=>true}}.to_json + { 'user' => + { 'id' => 267, + 'name' => 'Konstantin Haase', + 'login' => 'rkh', + 'email' => 'konstantin.haase@gmail.com', + 'gravatar_id' => '5c2b452f6eea4a6d84c105ebd971d2a4', + 'locale' => 'en', + 'is_syncing' => false, + 'synced_at' => '2012-10-27T12:52:25Z', + 'correct_scopes' => true } }.to_json end get '/logout' do halt(403, 'wrong token') unless authorized? - {"user"=> - {"id"=>267, - "name"=>"Konstantin Haase", - "login"=>"rkh", - "email"=>"konstantin.haase@gmail.com", - "gravatar_id"=>"5c2b452f6eea4a6d84c105ebd971d2a4", - "locale"=>"en", - "is_syncing"=>false, - "synced_at"=>"2012-10-27T12:52:25Z", - "correct_scopes"=>true}}.to_json + { 'user' => + { 'id' => 267, + 'name' => 'Konstantin Haase', + 'login' => 'rkh', + 'email' => 'konstantin.haase@gmail.com', + 'gravatar_id' => '5c2b452f6eea4a6d84c105ebd971d2a4', + 'locale' => 'en', + 'is_syncing' => false, + 'synced_at' => '2012-10-27T12:52:25Z', + 'correct_scopes' => true } }.to_json end get '/jobs/4125097' do - {"job"=> - {"id"=>4125097, - "repository_id"=>891, - "repository_slug"=>"rails/rails", - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168319, - "number"=>"6180.2", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"1.9.3", - "env"=>"GEM=ap,am,amo,as", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "state"=>"passed", - "started_at"=>"2013-01-13T15:55:59Z", - "finished_at"=>"2013-01-13T16:11:04Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - "commit"=> - {"id"=>1201631, - "sha"=>"a0265b98f16c6e33be32aa3f57231d1189302400", - "branch"=>"master", - "message"=>"Associaton -> Association", - "committed_at"=>"2013-01-13T15:43:24Z", - "author_name"=>"Steve Klabnik", - "author_email"=>"steve@steveklabnik.com", - "committer_name"=>"Steve Klabnik", - "committer_email"=>"steve@steveklabnik.com", - "compare_url"=> - "https://github.com/rails/rails/compare/6581d798e830...a0265b98f16c"}, - }.to_json + { 'job' => + { 'id' => 4_125_097, + 'repository_id' => 891, + 'repository_slug' => 'rails/rails', + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_319, + 'number' => '6180.2', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '1.9.3', + 'env' => 'GEM=ap,am,amo,as', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'state' => 'passed', + 'started_at' => '2013-01-13T15:55:59Z', + 'finished_at' => '2013-01-13T16:11:04Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + 'commit' => + { 'id' => 1_201_631, + 'sha' => 'a0265b98f16c6e33be32aa3f57231d1189302400', + 'branch' => 'master', + 'message' => 'Associaton -> Association', + 'committed_at' => '2013-01-13T15:43:24Z', + 'author_name' => 'Steve Klabnik', + 'author_email' => 'steve@steveklabnik.com', + 'committer_name' => 'Steve Klabnik', + 'committer_email' => 'steve@steveklabnik.com', + 'compare_url' => + 'https://github.com/rails/rails/compare/6581d798e830...a0265b98f16c' } }.to_json end get '/builds/4125095' do - {"build"=> - {"id"=>4125095, - "repository_id"=>891, - "commit_id"=>1201631, - "number"=>"6180", - "pull_request"=>false, - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>["1.9.3", "2.0.0"], - "env"=> - ["GEM=railties", - "GEM=ap,am,amo,as", - "GEM=ar:mysql", - "GEM=ar:mysql2", - "GEM=ar:sqlite3", - "GEM=ar:postgresql"], - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "state"=>"failed", - "started_at"=>"2013-01-13T15:55:17Z", - "finished_at"=>nil, - "duration"=>5019, - "job_ids"=> - [4125096, - 4125097, - 4125098, - 4125099, - 4125100, - 4125101, - 4125102, - 4125103, - 4125104, - 4125105, - 4125106, - 4125107]}, - "commit"=> - {"id"=>1201631, - "sha"=>"a0265b98f16c6e33be32aa3f57231d1189302400", - "branch"=>"master", - "message"=>"Associaton -> Association", - "committed_at"=>"2013-01-13T15:43:24Z", - "author_name"=>"Steve Klabnik", - "author_email"=>"steve@steveklabnik.com", - "committer_name"=>"Steve Klabnik", - "committer_email"=>"steve@steveklabnik.com", - "compare_url"=> - "https://github.com/rails/rails/compare/6581d798e830...a0265b98f16c"}, - "jobs"=> - [{"id"=>4125096, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168318, - "state"=>"failed", - "number"=>"6180.1", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"1.9.3", - "env"=>"GEM=railties", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:55:59Z", - "finished_at"=>"2013-01-13T16:10:15Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125097, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168319, - "state"=>"passed", - "number"=>"6180.2", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"1.9.3", - "env"=>"GEM=ap,am,amo,as", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:55:59Z", - "finished_at"=>"2013-01-13T16:11:04Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125098, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168320, - "state"=>"passed", - "number"=>"6180.3", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"1.9.3", - "env"=>"GEM=ar:mysql", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:55:59Z", - "finished_at"=>"2013-01-13T16:08:14Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125099, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168321, - "state"=>"passed", - "number"=>"6180.4", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"1.9.3", - "env"=>"GEM=ar:mysql2", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:55:17Z", - "finished_at"=>"2013-01-13T16:06:15Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125100, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168322, - "state"=>"passed", - "number"=>"6180.5", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"1.9.3", - "env"=>"GEM=ar:sqlite3", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:55:58Z", - "finished_at"=>"2013-01-13T16:08:07Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125101, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168323, - "state"=>"passed", - "number"=>"6180.6", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"1.9.3", - "env"=>"GEM=ar:postgresql", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:55:28Z", - "finished_at"=>"2013-01-13T16:08:41Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125102, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168324, - "state"=>"failed", - "number"=>"6180.7", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"2.0.0", - "env"=>"GEM=railties", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:55:17Z", - "finished_at"=>"2013-01-13T15:56:16Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125103, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168325, - "state"=>"failed", - "number"=>"6180.8", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"2.0.0", - "env"=>"GEM=ap,am,amo,as", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:55:58Z", - "finished_at"=>"2013-01-13T15:56:57Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125104, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168326, - "state"=>"failed", - "number"=>"6180.9", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"2.0.0", - "env"=>"GEM=ar:mysql", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:55:18Z", - "finished_at"=>"2013-01-13T15:56:16Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125105, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168327, - "state"=>"failed", - "number"=>"6180.10", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"2.0.0", - "env"=>"GEM=ar:mysql2", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:55:27Z", - "finished_at"=>"2013-01-13T15:56:23Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125106, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168328, - "state"=>"failed", - "number"=>"6180.11", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"2.0.0", - "env"=>"GEM=ar:sqlite3", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:56:47Z", - "finished_at"=>"2013-01-13T15:57:43Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - {"id"=>4125107, - "repository_id"=>891, - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168329, - "state"=>"failed", - "number"=>"6180.12", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"2.0.0", - "env"=>"GEM=ar:postgresql", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "started_at"=>"2013-01-13T15:56:54Z", - "finished_at"=>"2013-01-13T15:57:49Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}]}.to_json + { 'build' => + { 'id' => 4_125_095, + 'repository_id' => 891, + 'commit_id' => 1_201_631, + 'number' => '6180', + 'pull_request' => false, + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => ['1.9.3', '2.0.0'], + 'env' => + ['GEM=railties', + 'GEM=ap,am,amo,as', + 'GEM=ar:mysql', + 'GEM=ar:mysql2', + 'GEM=ar:sqlite3', + 'GEM=ar:postgresql'], + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'state' => 'failed', + 'started_at' => '2013-01-13T15:55:17Z', + 'finished_at' => nil, + 'duration' => 5019, + 'job_ids' => + [4_125_096, + 4_125_097, + 4_125_098, + 4_125_099, + 4_125_100, + 4_125_101, + 4_125_102, + 4_125_103, + 4_125_104, + 4_125_105, + 4_125_106, + 4_125_107] }, + 'commit' => + { 'id' => 1_201_631, + 'sha' => 'a0265b98f16c6e33be32aa3f57231d1189302400', + 'branch' => 'master', + 'message' => 'Associaton -> Association', + 'committed_at' => '2013-01-13T15:43:24Z', + 'author_name' => 'Steve Klabnik', + 'author_email' => 'steve@steveklabnik.com', + 'committer_name' => 'Steve Klabnik', + 'committer_email' => 'steve@steveklabnik.com', + 'compare_url' => + 'https://github.com/rails/rails/compare/6581d798e830...a0265b98f16c' }, + 'jobs' => + [{ 'id' => 4_125_096, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_318, + 'state' => 'failed', + 'number' => '6180.1', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '1.9.3', + 'env' => 'GEM=railties', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:55:59Z', + 'finished_at' => '2013-01-13T16:10:15Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_097, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_319, + 'state' => 'passed', + 'number' => '6180.2', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '1.9.3', + 'env' => 'GEM=ap,am,amo,as', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:55:59Z', + 'finished_at' => '2013-01-13T16:11:04Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_098, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_320, + 'state' => 'passed', + 'number' => '6180.3', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '1.9.3', + 'env' => 'GEM=ar:mysql', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:55:59Z', + 'finished_at' => '2013-01-13T16:08:14Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_099, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_321, + 'state' => 'passed', + 'number' => '6180.4', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '1.9.3', + 'env' => 'GEM=ar:mysql2', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:55:17Z', + 'finished_at' => '2013-01-13T16:06:15Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_100, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_322, + 'state' => 'passed', + 'number' => '6180.5', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '1.9.3', + 'env' => 'GEM=ar:sqlite3', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:55:58Z', + 'finished_at' => '2013-01-13T16:08:07Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_101, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_323, + 'state' => 'passed', + 'number' => '6180.6', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '1.9.3', + 'env' => 'GEM=ar:postgresql', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:55:28Z', + 'finished_at' => '2013-01-13T16:08:41Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_102, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_324, + 'state' => 'failed', + 'number' => '6180.7', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '2.0.0', + 'env' => 'GEM=railties', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:55:17Z', + 'finished_at' => '2013-01-13T15:56:16Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_103, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_325, + 'state' => 'failed', + 'number' => '6180.8', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '2.0.0', + 'env' => 'GEM=ap,am,amo,as', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:55:58Z', + 'finished_at' => '2013-01-13T15:56:57Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_104, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_326, + 'state' => 'failed', + 'number' => '6180.9', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '2.0.0', + 'env' => 'GEM=ar:mysql', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:55:18Z', + 'finished_at' => '2013-01-13T15:56:16Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_105, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_327, + 'state' => 'failed', + 'number' => '6180.10', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '2.0.0', + 'env' => 'GEM=ar:mysql2', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:55:27Z', + 'finished_at' => '2013-01-13T15:56:23Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_106, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_328, + 'state' => 'failed', + 'number' => '6180.11', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '2.0.0', + 'env' => 'GEM=ar:sqlite3', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:56:47Z', + 'finished_at' => '2013-01-13T15:57:43Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + { 'id' => 4_125_107, + 'repository_id' => 891, + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_329, + 'state' => 'failed', + 'number' => '6180.12', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '2.0.0', + 'env' => 'GEM=ar:postgresql', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'started_at' => '2013-01-13T15:56:54Z', + 'finished_at' => '2013-01-13T15:57:49Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }] }.to_json end get '/builds/' do - return {"builds"=>[]}.to_json if params[:after_number] - {"builds"=> - [{"id"=>4125095, - "repository_id"=>891, - "commit_id"=>1201631, - "number"=>"6180", - "pull_request"=>false, - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>["1.9.3", "2.0.0"], - "env"=> - ["GEM=railties", - "GEM=ap,am,amo,as", - "GEM=ar:mysql", - "GEM=ar:mysql2", - "GEM=ar:sqlite3", - "GEM=ar:postgresql"], - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "state"=>"failed", - "started_at"=>"2013-01-13T15:55:17Z", - "finished_at"=>nil, - "duration"=>5019, - "job_ids"=> - [4125096, - 4125097, - 4125098, - 4125099, - 4125100, - 4125101, - 4125102, - 4125103, - 4125104, - 4125105, - 4125106, - 4125107]}], - "commits"=> - [{"id"=>1201631, - "sha"=>"a0265b98f16c6e33be32aa3f57231d1189302400", - "branch"=>"master", - "message"=>"Associaton -> Association", - "committed_at"=>"2013-01-13T15:43:24Z", - "author_name"=>"Steve Klabnik", - "author_email"=>"steve@steveklabnik.com", - "committer_name"=>"Steve Klabnik", - "committer_email"=>"steve@steveklabnik.com", - "compare_url"=> - "https://github.com/rails/rails/compare/6581d798e830...a0265b98f16c"}]}.to_json + return { 'builds' => [] }.to_json if params[:after_number] + + { 'builds' => + [{ 'id' => 4_125_095, + 'repository_id' => 891, + 'commit_id' => 1_201_631, + 'number' => '6180', + 'pull_request' => false, + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => ['1.9.3', '2.0.0'], + 'env' => + ['GEM=railties', + 'GEM=ap,am,amo,as', + 'GEM=ar:mysql', + 'GEM=ar:mysql2', + 'GEM=ar:sqlite3', + 'GEM=ar:postgresql'], + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'state' => 'failed', + 'started_at' => '2013-01-13T15:55:17Z', + 'finished_at' => nil, + 'duration' => 5019, + 'job_ids' => + [4_125_096, + 4_125_097, + 4_125_098, + 4_125_099, + 4_125_100, + 4_125_101, + 4_125_102, + 4_125_103, + 4_125_104, + 4_125_105, + 4_125_106, + 4_125_107] }], + 'commits' => + [{ 'id' => 1_201_631, + 'sha' => 'a0265b98f16c6e33be32aa3f57231d1189302400', + 'branch' => 'master', + 'message' => 'Associaton -> Association', + 'committed_at' => '2013-01-13T15:43:24Z', + 'author_name' => 'Steve Klabnik', + 'author_email' => 'steve@steveklabnik.com', + 'committer_name' => 'Steve Klabnik', + 'committer_email' => 'steve@steveklabnik.com', + 'compare_url' => + 'https://github.com/rails/rails/compare/6581d798e830...a0265b98f16c' }] }.to_json end get '/jobs/4125096' do - {"job"=> - {"id"=>4125096, - "repository_id"=>891, - "repository_slug"=>"rails/rails", - "build_id"=>4125095, - "commit_id"=>1201631, - "log_id"=>3168318, - "number"=>"6180.1", - "config"=> - {"script"=>"ci/travis.rb", - "before_install"=>["gem install bundler"], - "rvm"=>"1.9.3", - "env"=>"GEM=railties", - "notifications"=> - {"email"=>false, - "irc"=> - {"on_success"=>"change", - "on_failure"=>"always", - "channels"=>["irc.freenode.org#rails-contrib"]}, - "campfire"=> - {"on_success"=>"change", - "on_failure"=>"always", - "rooms"=> - [{"secure"=> - "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI="}]}}, - "bundler_args"=>"--path vendor/bundle", - ".result"=>"configured"}, - "state"=>"failed", - "started_at"=>"2013-01-13T15:55:59Z", - "finished_at"=>"2013-01-13T16:10:15Z", - "queue"=>"builds.rails", - "allow_failure"=>false, - "tags"=>""}, - "commit"=> - {"id"=>1201631, - "sha"=>"a0265b98f16c6e33be32aa3f57231d1189302400", - "branch"=>"master", - "message"=>"Associaton -> Association", - "committed_at"=>"2013-01-13T15:43:24Z", - "author_name"=>"Steve Klabnik", - "author_email"=>"steve@steveklabnik.com", - "committer_name"=>"Steve Klabnik", - "committer_email"=>"steve@steveklabnik.com", - "compare_url"=> - "https://github.com/rails/rails/compare/6581d798e830...a0265b98f16c"}}.to_json + { 'job' => + { 'id' => 4_125_096, + 'repository_id' => 891, + 'repository_slug' => 'rails/rails', + 'build_id' => 4_125_095, + 'commit_id' => 1_201_631, + 'log_id' => 3_168_318, + 'number' => '6180.1', + 'config' => + { 'script' => 'ci/travis.rb', + 'before_install' => ['gem install bundler'], + 'rvm' => '1.9.3', + 'env' => 'GEM=railties', + 'notifications' => + { 'email' => false, + 'irc' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'channels' => ['irc.freenode.org#rails-contrib'] }, + 'campfire' => + { 'on_success' => 'change', + 'on_failure' => 'always', + 'rooms' => + [{ 'secure' => + "YA1alef1ESHWGFNVwvmVGCkMe4cUy4j+UcNvMUESraceiAfVyRMAovlQBGs6\n9kBRm7DHYBUXYC2ABQoJbQRLDr/1B5JPf/M8+Qd7BKu8tcDC03U01SMHFLpO\naOs/HLXcDxtnnpL07tGVsm0zhMc5N8tq4/L3SHxK7Vi+TacwQzI=" }] } }, + 'bundler_args' => '--path vendor/bundle', + '.result' => 'configured' }, + 'state' => 'failed', + 'started_at' => '2013-01-13T15:55:59Z', + 'finished_at' => '2013-01-13T16:10:15Z', + 'queue' => 'builds.rails', + 'allow_failure' => false, + 'tags' => '' }, + 'commit' => + { 'id' => 1_201_631, + 'sha' => 'a0265b98f16c6e33be32aa3f57231d1189302400', + 'branch' => 'master', + 'message' => 'Associaton -> Association', + 'committed_at' => '2013-01-13T15:43:24Z', + 'author_name' => 'Steve Klabnik', + 'author_email' => 'steve@steveklabnik.com', + 'committer_name' => 'Steve Klabnik', + 'committer_email' => 'steve@steveklabnik.com', + 'compare_url' => + 'https://github.com/rails/rails/compare/6581d798e830...a0265b98f16c' } }.to_json end get '/repos/' do - {"repos"=> - [{"id"=>107495, - "slug"=>"pypug/django-mango", - "description"=>"More Mango, less Django!", - "last_build_id"=>4125823, - "last_build_number"=>"39", - "last_build_state"=>"failed", - "last_build_duration"=>31, - "last_build_language"=>nil, - "last_build_started_at"=>"2013-01-13T16:58:43Z", - "last_build_finished_at"=>"2013-01-13T16:55:08Z"}]}.to_json + { 'repos' => + [{ 'id' => 107_495, + 'slug' => 'pypug/django-mango', + 'description' => 'More Mango, less Django!', + 'last_build_id' => 4_125_823, + 'last_build_number' => '39', + 'last_build_state' => 'failed', + 'last_build_duration' => 31, + 'last_build_language' => nil, + 'last_build_started_at' => '2013-01-13T16:58:43Z', + 'last_build_finished_at' => '2013-01-13T16:55:08Z' }] }.to_json end get '/config' do - {"config" => {"host" => "travis-ci.org"}}.to_json + { 'config' => { 'host' => 'travis-ci.org' } }.to_json end get '/logs/3168318' do - {"log"=> - {"id"=>3168318, - "job_id"=>4125096, - "type"=>"Log", - "body"=> - "$ export GEM=railties\n"}}.to_json + { 'log' => + { 'id' => 3_168_318, + 'job_id' => 4_125_096, + 'type' => 'Log', + 'body' => + "$ export GEM=railties\n" } }.to_json end get '/repos/*/travis.rb' do - # hack hack + # HACK: hack request.path_info = '/repos/rails/rails' pass end @@ -687,38 +689,36 @@ def authorized? end get '/repos/rails/rails' do - {"repo"=> - {"id"=>891, - "slug"=>"rails/rails", - "description"=>settings.rails_description, - "last_build_id"=>4125095, - "last_build_number"=>"6180", - "last_build_state"=>"failed", - "last_build_duration"=>5019, - "last_build_language"=>nil, - "last_build_started_at"=>"2013-01-13T15:55:17Z", - "last_build_finished_at"=>nil, - "github_language"=>"Ruby"}}.to_json + { 'repo' => + { 'id' => 891, + 'slug' => 'rails/rails', + 'description' => settings.rails_description, + 'last_build_id' => 4_125_095, + 'last_build_number' => '6180', + 'last_build_state' => 'failed', + 'last_build_duration' => 5019, + 'last_build_language' => nil, + 'last_build_started_at' => '2013-01-13T15:55:17Z', + 'last_build_finished_at' => nil, + 'github_language' => 'Ruby' } }.to_json end get '/repos/891/key' do - {"key"=>RAILS_KEY, "fingerprint"=>"foobar"}.to_json + { 'key' => RAILS_KEY, 'fingerprint' => 'foobar' }.to_json end get '/accounts/' do - {"accounts"=> - [{'name' => "Konstantin Haase", - 'login' => 'rkh', - 'type' => 'user', - 'repos_count' => 200 - }]}.to_json + { 'accounts' => + [{ 'name' => 'Konstantin Haase', + 'login' => 'rkh', + 'type' => 'user', + 'repos_count' => 200 }] }.to_json end get '/broadcasts/' do - {"broadcasts"=> - [{'id' => 1, - 'message' => 'Hello!' - }]}.to_json + { 'broadcasts' => + [{ 'id' => 1, + 'message' => 'Hello!' }] }.to_json end #### for encrypt_file spec @@ -726,18 +726,18 @@ def authorized? # p params $params = params { - "env_vars":[ + "env_vars": [ { - "id": "8aa1c74d-dcc4-4e41-9087-1326b7c68abd", - "name": "encrypted_randomhex_key", - "value": "super_secret_key", + "id": '8aa1c74d-dcc4-4e41-9087-1326b7c68abd', + "name": 'encrypted_randomhex_key', + "value": 'super_secret_key', "public": false, "repository_id": 891 }, { - "id": "b2ed30b9-622d-4bd7-928b-ba5aad7ba6a1", - "name": "encrypted_randomhex_iv", - "value": "super_secret_iv", + "id": 'b2ed30b9-622d-4bd7-928b-ba5aad7ba6a1', + "name": 'encrypted_randomhex_iv', + "value": 'super_secret_iv', "public": false, "repository_id": 891 } @@ -749,9 +749,9 @@ def authorized? $params = params { "env_var": { - "id": "8aa1c74d-dcc4-4e41-9087-1326b7c68abd", - "name": "encrypted_randomhex_key", - "value": "new_super_secret_key", + "id": '8aa1c74d-dcc4-4e41-9087-1326b7c68abd', + "name": 'encrypted_randomhex_key', + "value": 'new_super_secret_key', "public": false, "repository_id": 891 } @@ -762,9 +762,9 @@ def authorized? $params = params { "env_var": { - "id": "b2ed30b9-622d-4bd7-928b-ba5aad7ba6a1", - "name": "encrypted_randomhex_iv", - "value": "new_super_secret_iv", + "id": 'b2ed30b9-622d-4bd7-928b-ba5aad7ba6a1', + "name": 'encrypted_randomhex_iv', + "value": 'new_super_secret_iv', "public": false, "repository_id": 891 } diff --git a/spec/support/fake_github.rb b/spec/support/fake_github.rb index 640391ba..8fdefca0 100644 --- a/spec/support/fake_github.rb +++ b/spec/support/fake_github.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'gh' module GH @@ -11,9 +13,10 @@ def http(*) raise NotImplementedError end - def post(key, body) - raise GH::Error unless @authenticated and key == '/authorizations' - frontend.load("url" => "https://api.github.com/authorizations/1", "token" => "github_token") + def post(key, _body) + raise GH::Error unless @authenticated && (key == '/authorizations') + + frontend.load('url' => 'https://api.github.com/authorizations/1', 'token' => 'github_token') end def head(*) end diff --git a/spec/support/helpers.rb b/spec/support/helpers.rb index 2ae54162..dfa55e7f 100644 --- a/spec/support/helpers.rb +++ b/spec/support/helpers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'stringio' require 'ostruct' @@ -6,9 +8,12 @@ module Helpers attr_reader :last_run def capture - _stdout, $stdout = $stdout, StringIO.new - _stderr, $stderr = $stderr, StringIO.new - _stdin, $stdin = $stdin, StringIO.new + _stdout = $stdout + $stdout = StringIO.new + _stderr = $stderr + $stderr = StringIO.new + _stdin = $stdin + $stdin = StringIO.new yield capture_result(true) rescue SystemExit => e @@ -30,16 +35,16 @@ def run_cli(*args) end def stderr - last_run.err if last_run + last_run&.err end def stdout - last_run.out if last_run + last_run&.out end private - def capture_result(success) - @last_run = OpenStruct.new(:out => $stdout.string, :err => $stderr.string, :success? => success) - end + def capture_result(success) + @last_run = OpenStruct.new(out: $stdout.string, err: $stderr.string, success?: success) + end end diff --git a/spec/travis_spec.rb b/spec/travis_spec.rb index a10b1cf6..a6f37ef7 100644 --- a/spec/travis_spec.rb +++ b/spec/travis_spec.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + require 'spec_helper' describe Travis do - its(:api_endpoint) { should be == 'https://api.travis-ci.org/' } + its(:api_endpoint) { is_expected.to be == 'https://api.travis-ci.com/' } it 'has a nice inspect on entities' do - pending "does not work on JRuby" if defined? RUBY_ENGINE and RUBY_ENGINE == 'jruby' - Travis::Repository.find('rails/rails').inspect.should be == "#" + pending 'does not work on JRuby' if defined? RUBY_ENGINE and RUBY_ENGINE == 'jruby' + Travis::Repository.find('rails/rails').inspect.should be == '#' end end diff --git a/travis.gemspec b/travis.gemspec index 14a9d228..ce538d2d 100644 --- a/travis.gemspec +++ b/travis.gemspec @@ -1,429 +1,430 @@ +# frozen_string_literal: true + # Run `rake travis.gemspec` to update the gemspec. Gem::Specification.new do |s| # general info - s.name = "travis" - s.version = "1.11.1" - s.required_ruby_version = ">= 2.3.0" - s.description = "CLI and Ruby client library for Travis CI" - s.homepage = "https://github.com/travis-ci/travis.rb" - s.summary = "Travis CI client" - s.license = "MIT" - s.executables = ["travis"] + s.name = 'travis' + s.version = '1.12.0' + s.required_ruby_version = '>= 3.2.0' + s.description = 'CLI and Ruby client library for Travis CI' + s.homepage = 'https://github.com/travis-ci/travis.rb' + s.summary = 'Travis CI client' + s.license = 'MIT' + s.executables = ['travis'] # generated from git shortlog -sn s.authors = [ - "Konstantin Haase", - "Hiro Asari", - "Henrik Hodne", - "joshua-anderson", - "Aaron Hill", - "Piotr Milcarz", - "Buck Doyle", - "Peter Souter", - "Christopher Grim", - "Joe Corcoran", - "Peter van Dijk", - "Sven Fuchs", - "Aakriti Gupta", - "Josh Kalderimis", - "Piotr Sarnacki", - "Ke Zhu", - "Max Barnash", + 'Konstantin Haase', + 'Hiro Asari', + 'Henrik Hodne', + 'joshua-anderson', + 'Aaron Hill', + 'Piotr Milcarz', + 'Buck Doyle', + 'Peter Souter', + 'Christopher Grim', + 'Joe Corcoran', + 'Peter van Dijk', + 'Sven Fuchs', + 'Aakriti Gupta', + 'Josh Kalderimis', + 'Piotr Sarnacki', + 'Ke Zhu', + 'Max Barnash', "Ren\xC3\xA9e Hendricksen", - "carlad", - "Carlos Palhares", - "Dan Buch", + 'carlad', + 'Carlos Palhares', + 'Dan Buch', "Mar\xC3\xADa de Ant\xC3\xB3n", - "Mathias Meyer", - "Matt Toothman", - "mariadeanton", - "techgaun", - "Alpha", - "Andreas Tiefenthaler", - "Beau Bouchard", - "Corinna Wiesner", + 'Mathias Meyer', + 'Matt Toothman', + 'mariadeanton', + 'techgaun', + 'Alpha', + 'Andreas Tiefenthaler', + 'Beau Bouchard', + 'Corinna Wiesner', "David Rodr\xC3\xADguez", - "Eugene", - "Eugene Shubin", - "Igor Wiedler", - "Ivan Pozdeev", - "Joep van Delft", - "Stefan Nordhausen", - "Thais Camilo and Konstantin Haase", - "Tobias Bieniek", - "Adam Baxter", - "Adam Lavin", - "Adrien Brault", - "Alfie John", + 'Eugene', + 'Eugene Shubin', + 'Igor Wiedler', + 'Ivan Pozdeev', + 'Joep van Delft', + 'Stefan Nordhausen', + 'Thais Camilo and Konstantin Haase', + 'Tobias Bieniek', + 'Adam Baxter', + 'Adam Lavin', + 'Adrien Brault', + 'Alfie John', "Alo\xC3\xAFs Th\xC3\xA9venot", - "Basarat Ali Syed", - "Benjamin Manns", + 'Basarat Ali Syed', + 'Benjamin Manns', "Christian H\xC3\xB6ltje", - "Dani Hodovic", - "Daniel Chatfield", - "Dominic Jodoin", - "Eli Schwartz", - "Eric Herot", - "Eugene K", - "George Millo", - "Gunter Grodotzki", - "Harald Nordgren", - "HaraldNordgren", - "Igor", - "Iulian Onofrei", - "Jacob Atzen", - "Jacob Burkhart", - "James Nylen", - "Joe Rafaniello", - "Jon-Erik Schneiderhan", - "Jonas Chromik", + 'Dani Hodovic', + 'Daniel Chatfield', + 'Dominic Jodoin', + 'Eli Schwartz', + 'Eric Herot', + 'Eugene K', + 'George Millo', + 'Gunter Grodotzki', + 'Harald Nordgren', + 'HaraldNordgren', + 'Igor', + 'Iulian Onofrei', + 'Jacob Atzen', + 'Jacob Burkhart', + 'James Nylen', + 'Joe Rafaniello', + 'Jon-Erik Schneiderhan', + 'Jonas Chromik', "Jonne Ha\xC3\x9F", - "Julia S.Simon", - "Justin Lambert", - "Laurent Petit", - "Maarten van Vliet", - "Marco Craveiro", - "Mario Visic", - "Matt", - "Matteo Sumberaz", - "Matthias Bussonnier", - "Michael Mior", - "Michael S. Fischer", + 'Julia S.Simon', + 'Justin Lambert', + 'Laurent Petit', + 'Maarten van Vliet', + 'Marco Craveiro', + 'Mario Visic', + 'Matt', + 'Matteo Sumberaz', + 'Matthias Bussonnier', + 'Michael Mior', + 'Michael S. Fischer', "Miro Hron\xC4\x8Dok", - "Neamar", - "Nero Leung", - "Nicolas Bessi (nbessi)", - "Nikhil Owalekar", - "Peter Bengtsson", - "Peter Drake", + 'Neamar', + 'Nero Leung', + 'Nicolas Bessi (nbessi)', + 'Nikhil Owalekar', + 'Peter Bengtsson', + 'Peter Drake', "Rapha\xC3\xABl Pinson", - "Rob Hoelz", - "Robert Grider", - "Robert Van Voorhees", - "Simon Cropp", - "Tahsin Hasan", - "Titus", - "Titus Wormer", - "Tobias Wilken", - "Zachary Gershman", - "Zachary Scott", - "designerror", - "ia", - "jeffdh", - "john muhl", - "slewt" + 'Rob Hoelz', + 'Robert Grider', + 'Robert Van Voorhees', + 'Simon Cropp', + 'Tahsin Hasan', + 'Titus', + 'Titus Wormer', + 'Tobias Wilken', + 'Zachary Gershman', + 'Zachary Scott', + 'designerror', + 'ia', + 'jeffdh', + 'john muhl', + 'slewt' ] # generated from git shortlog -sne s.email = [ - "konstantin.mailinglists@googlemail.com", - "asari.ruby@gmail.com", - "j@zatigo.com", - "aa1ronham@gmail.com", - "piotrm@travis-ci.org", - "me@henrikhodne.com", - "b@chromatin.ca", - "henrik@hodne.io", - "p.morsou@gmail.com", - "chrisg@luminal.io", - "joe@corcoran.io", - "peter.van.dijk@netherlabs.nl", - "me@svenfuchs.com", - "josh.kalderimis@gmail.com", - "drogus@gmail.com", - "kzhu@us.ibm.com", - "i.am@anhero.ru", - "renee@travis-ci.org", - "aakritigupta@users.noreply.github.com", - "me@xjunior.me", - "dan@meatballhat.com", - "mariadeanton@gmail.com", - "meyer@paperplanes.de", - "matt.toothman@aver.io", - "carlad@users.noreply.github.com", - "coolsamar207@gmail.com", - "aakriti@travis-ci.org", - "AlphaWong@users.noreply.github.com", - "at@an-ti.eu", - "127320+BeauBouchard@users.noreply.github.com", - "wiesner@avarteq.de", - "deivid.rodriguez@gmail.com", - "eugene@travis-ci.org", - "51701929+eugene-travis@users.noreply.github.com", - "igor@travis-ci.org", - "vano@mail.mipt.ru", - "stefan.nordhausen@immobilienscout24.de", - "dev+narwen+rkh@rkh.im", - "tobias.bieniek@gmail.com", - "github@voltagex.org", - "adam@lavoaster.co.uk", - "adrien.brault@gmail.com", - "33c6c91f3bb4a391082e8a29642cafaf@alfie.wtf", - "aloisthevenot@srxp.com", - "basaratali@gmail.com", - "benmanns@gmail.com", - "docwhat@gerf.org", - "danihodovic@users.noreply.github.com", - "chatfielddaniel@gmail.com", - "dominic@travis-ci.com", - "eschwartz@archlinux.org", - "eric.github@herot.com", - "34233075+eugene-kulak@users.noreply.github.com", - "georgejulianmillo@gmail.com", - "gunter@grodotzki.co.za", - "haraldnordgren@gmail.com", - "igorwwwwwwwwwwwwwwwwwwww@users.noreply.github.com", - "6d0847b9@opayq.com", - "jatzen@gmail.com", - "jburkhart@engineyard.com", - "jnylen@gmail.com", - "jrafanie@users.noreply.github.com", - "joep@travis-ci.org", - "joepvd@users.noreply.github.com", - "jon-erik.schneiderhan@meyouhealth.com", - "Jonas.Chromik@student.hpi.uni-potsdam.de", - "me@jhass.eu", - "julia.simon@biicode.com", - "jlambert@eml.cc", - "laurent.petit@gmail.com", - "maartenvanvliet@gmail.com", - "marco.craveiro@gmail.com", - "mario@mariovisic.com", - "mtoothman@users.noreply.github.com", - "gnappoms@gmail.com", - "bussonniermatthias@gmail.com", - "mmior@uwaterloo.ca", - "mfischer@zendesk.com", - "miro@hroncok.cz", - "neamar@neamar.fr", - "neroleung@gmail.com", - "nbessi@users.noreply.github.com", - "nowalekar@tigetext.com", - "peterbe@mozilla.com", - "peter.drake@acquia.com", - "raphael.pinson@camptocamp.com", - "rob@hoelz.ro", - "robert.grider@northwestern.edu", - "rcvanvo@gmail.com", - "simon.cropp@gmail.com", - "51903216+Tahsin-travis-ci@users.noreply.github.com", - "tituswormer@gmail.com", - "tw@cloudcontrol.de", - "pair+zg@pivotallabs.com", - "e@zzak.io", - "carla@travis-ci.org", - "designerror@yandex.ru", - "isaac.ardis@gmail.com", - "jeffdh@gmail.com", - "git@johnmuhl.com", - "leland@lcweathers.net" + 'konstantin.mailinglists@googlemail.com', + 'asari.ruby@gmail.com', + 'j@zatigo.com', + 'aa1ronham@gmail.com', + 'piotrm@travis-ci.org', + 'me@henrikhodne.com', + 'b@chromatin.ca', + 'henrik@hodne.io', + 'p.morsou@gmail.com', + 'chrisg@luminal.io', + 'joe@corcoran.io', + 'peter.van.dijk@netherlabs.nl', + 'me@svenfuchs.com', + 'josh.kalderimis@gmail.com', + 'drogus@gmail.com', + 'kzhu@us.ibm.com', + 'i.am@anhero.ru', + 'renee@travis-ci.org', + 'aakritigupta@users.noreply.github.com', + 'me@xjunior.me', + 'dan@meatballhat.com', + 'mariadeanton@gmail.com', + 'meyer@paperplanes.de', + 'matt.toothman@aver.io', + 'carlad@users.noreply.github.com', + 'coolsamar207@gmail.com', + 'aakriti@travis-ci.org', + 'AlphaWong@users.noreply.github.com', + 'at@an-ti.eu', + '127320+BeauBouchard@users.noreply.github.com', + 'wiesner@avarteq.de', + 'deivid.rodriguez@gmail.com', + 'eugene@travis-ci.org', + '51701929+eugene-travis@users.noreply.github.com', + 'igor@travis-ci.org', + 'vano@mail.mipt.ru', + 'stefan.nordhausen@immobilienscout24.de', + 'dev+narwen+rkh@rkh.im', + 'tobias.bieniek@gmail.com', + 'github@voltagex.org', + 'adam@lavoaster.co.uk', + 'adrien.brault@gmail.com', + '33c6c91f3bb4a391082e8a29642cafaf@alfie.wtf', + 'aloisthevenot@srxp.com', + 'basaratali@gmail.com', + 'benmanns@gmail.com', + 'docwhat@gerf.org', + 'danihodovic@users.noreply.github.com', + 'chatfielddaniel@gmail.com', + 'dominic@travis-ci.com', + 'eschwartz@archlinux.org', + 'eric.github@herot.com', + '34233075+eugene-kulak@users.noreply.github.com', + 'georgejulianmillo@gmail.com', + 'gunter@grodotzki.co.za', + 'haraldnordgren@gmail.com', + 'igorwwwwwwwwwwwwwwwwwwww@users.noreply.github.com', + '6d0847b9@opayq.com', + 'jatzen@gmail.com', + 'jburkhart@engineyard.com', + 'jnylen@gmail.com', + 'jrafanie@users.noreply.github.com', + 'joep@travis-ci.org', + 'joepvd@users.noreply.github.com', + 'jon-erik.schneiderhan@meyouhealth.com', + 'Jonas.Chromik@student.hpi.uni-potsdam.de', + 'me@jhass.eu', + 'julia.simon@biicode.com', + 'jlambert@eml.cc', + 'laurent.petit@gmail.com', + 'maartenvanvliet@gmail.com', + 'marco.craveiro@gmail.com', + 'mario@mariovisic.com', + 'mtoothman@users.noreply.github.com', + 'gnappoms@gmail.com', + 'bussonniermatthias@gmail.com', + 'mmior@uwaterloo.ca', + 'mfischer@zendesk.com', + 'miro@hroncok.cz', + 'neamar@neamar.fr', + 'neroleung@gmail.com', + 'nbessi@users.noreply.github.com', + 'nowalekar@tigetext.com', + 'peterbe@mozilla.com', + 'peter.drake@acquia.com', + 'raphael.pinson@camptocamp.com', + 'rob@hoelz.ro', + 'robert.grider@northwestern.edu', + 'rcvanvo@gmail.com', + 'simon.cropp@gmail.com', + '51903216+Tahsin-travis-ci@users.noreply.github.com', + 'tituswormer@gmail.com', + 'tw@cloudcontrol.de', + 'pair+zg@pivotallabs.com', + 'e@zzak.io', + 'carla@travis-ci.org', + 'designerror@yandex.ru', + 'isaac.ardis@gmail.com', + 'jeffdh@gmail.com', + 'git@johnmuhl.com', + 'leland@lcweathers.net' ] # generated from git ls-files s.files = [ - "LICENSE", - "README.md", - "Rakefile", - "assets/cacert.pem", - "assets/init/bash.yml", - "assets/init/c.yml", - "assets/init/clojure.yml", - "assets/init/cpp.yml", - "assets/init/elixir.yml", - "assets/init/erlang.yml", - "assets/init/go.yml", - "assets/init/groovy.yml", - "assets/init/haskell.yml", - "assets/init/java.yml", - "assets/init/node_js.yml", - "assets/init/objective-c.yml", - "assets/init/perl.yml", - "assets/init/php.yml", - "assets/init/python.yml", - "assets/init/ruby.yml", - "assets/init/scala.yml", - "assets/notifications/Travis CI.app/Contents/Info.plist", - "assets/notifications/Travis CI.app/Contents/MacOS/Travis CI", - "assets/notifications/Travis CI.app/Contents/PkgInfo", - "assets/notifications/Travis CI.app/Contents/Resources/Travis CI.icns", - "assets/notifications/Travis CI.app/Contents/Resources/en.lproj/Credits.rtf", - "assets/notifications/Travis CI.app/Contents/Resources/en.lproj/InfoPlist.strings", - "assets/notifications/Travis CI.app/Contents/Resources/en.lproj/MainMenu.nib", - "assets/notifications/Travis CI.app/Contents/_CodeSignature/CodeResources", - "assets/notifications/Travis CI.app/Contents/embedded.provisionprofile", - "assets/notifications/icon.png", - "assets/travis.sh", - "assets/travis.sh.erb", - "bin/travis", - "examples/org_overview.rb", - "examples/pro_auth.rb", - "examples/stream.rb", - "lib/travis.rb", - "lib/travis/auto_login.rb", - "lib/travis/cli.rb", - "lib/travis/cli/accounts.rb", - "lib/travis/cli/api_command.rb", - "lib/travis/cli/branches.rb", - "lib/travis/cli/cache.rb", - "lib/travis/cli/cancel.rb", - "lib/travis/cli/command.rb", - "lib/travis/cli/console.rb", - "lib/travis/cli/disable.rb", - "lib/travis/cli/enable.rb", - "lib/travis/cli/encrypt.rb", - "lib/travis/cli/encrypt_file.rb", - "lib/travis/cli/endpoint.rb", - "lib/travis/cli/env.rb", - "lib/travis/cli/help.rb", - "lib/travis/cli/history.rb", - "lib/travis/cli/init.rb", - "lib/travis/cli/lint.rb", - "lib/travis/cli/login.rb", - "lib/travis/cli/logout.rb", - "lib/travis/cli/logs.rb", - "lib/travis/cli/monitor.rb", - "lib/travis/cli/open.rb", - "lib/travis/cli/parser.rb", - "lib/travis/cli/pubkey.rb", - "lib/travis/cli/raw.rb", - "lib/travis/cli/repo_command.rb", - "lib/travis/cli/report.rb", - "lib/travis/cli/repos.rb", - "lib/travis/cli/requests.rb", - "lib/travis/cli/restart.rb", - "lib/travis/cli/settings.rb", - "lib/travis/cli/setup.rb", - "lib/travis/cli/setup/anynines.rb", - "lib/travis/cli/setup/appfog.rb", - "lib/travis/cli/setup/artifacts.rb", - "lib/travis/cli/setup/biicode.rb", - "lib/travis/cli/setup/cloud_66.rb", - "lib/travis/cli/setup/cloud_control.rb", - "lib/travis/cli/setup/cloud_files.rb", - "lib/travis/cli/setup/cloud_foundry.rb", - "lib/travis/cli/setup/code_deploy.rb", - "lib/travis/cli/setup/deis.rb", - "lib/travis/cli/setup/divshot.rb", - "lib/travis/cli/setup/elastic_beanstalk.rb", - "lib/travis/cli/setup/engine_yard.rb", - "lib/travis/cli/setup/gcs.rb", - "lib/travis/cli/setup/hackage.rb", - "lib/travis/cli/setup/heroku.rb", - "lib/travis/cli/setup/modulus.rb", - "lib/travis/cli/setup/ninefold.rb", - "lib/travis/cli/setup/nodejitsu.rb", - "lib/travis/cli/setup/npm.rb", - "lib/travis/cli/setup/open_shift.rb", - "lib/travis/cli/setup/opsworks.rb", - "lib/travis/cli/setup/pypi.rb", - "lib/travis/cli/setup/releases.rb", - "lib/travis/cli/setup/ruby_gems.rb", - "lib/travis/cli/setup/s3.rb", - "lib/travis/cli/setup/sauce_connect.rb", - "lib/travis/cli/setup/service.rb", - "lib/travis/cli/show.rb", - "lib/travis/cli/sshkey.rb", - "lib/travis/cli/status.rb", - "lib/travis/cli/sync.rb", - "lib/travis/cli/token.rb", - "lib/travis/cli/version.rb", - "lib/travis/cli/whatsup.rb", - "lib/travis/cli/whoami.rb", - "lib/travis/client.rb", - "lib/travis/client/account.rb", - "lib/travis/client/artifact.rb", - "lib/travis/client/auto_login.rb", - "lib/travis/client/broadcast.rb", - "lib/travis/client/build.rb", - "lib/travis/client/cache.rb", - "lib/travis/client/commit.rb", - "lib/travis/client/entity.rb", - "lib/travis/client/env_var.rb", - "lib/travis/client/error.rb", - "lib/travis/client/has_uuid.rb", - "lib/travis/client/job.rb", - "lib/travis/client/lint_result.rb", - "lib/travis/client/listener.rb", - "lib/travis/client/methods.rb", - "lib/travis/client/namespace.rb", - "lib/travis/client/not_loadable.rb", - "lib/travis/client/repository.rb", - "lib/travis/client/request.rb", - "lib/travis/client/restartable.rb", - "lib/travis/client/session.rb", - "lib/travis/client/settings.rb", - "lib/travis/client/singleton_setting.rb", - "lib/travis/client/ssh_key.rb", - "lib/travis/client/states.rb", - "lib/travis/client/user.rb", - "lib/travis/client/weak_entity.rb", - "lib/travis/pro.rb", - "lib/travis/pro/auto_login.rb", - "lib/travis/tools/assets.rb", - "lib/travis/tools/completion.rb", - "lib/travis/tools/formatter.rb", - "lib/travis/tools/github.rb", - "lib/travis/tools/notification.rb", - "lib/travis/tools/safe_string.rb", - "lib/travis/tools/ssl_key.rb", - "lib/travis/tools/system.rb", - "lib/travis/version.rb", - "spec/cli/api_command_spec.rb", - "spec/cli/cancel_spec.rb", - "spec/cli/encrypt_file_spec.rb", - "spec/cli/encrypt_spec.rb", - "spec/cli/endpoint_spec.rb", - "spec/cli/help_spec.rb", - "spec/cli/history_spec.rb", - "spec/cli/init_spec.rb", - "spec/cli/logs_spec.rb", - "spec/cli/open_spec.rb", - "spec/cli/repo_command_spec.rb", - "spec/cli/restart_spec.rb", - "spec/cli/setup/service_spec.rb", - "spec/cli/setup_spec.rb", - "spec/cli/show_spec.rb", - "spec/cli/status_spec.rb", - "spec/cli/token_spec.rb", - "spec/cli/version_spec.rb", - "spec/cli/whoami_spec.rb", - "spec/client/account_spec.rb", - "spec/client/auto_login_spec.rb", - "spec/client/broadcast_spec.rb", - "spec/client/build_spec.rb", - "spec/client/commit_spec.rb", - "spec/client/job_spec.rb", - "spec/client/methods_spec.rb", - "spec/client/namespace_spec.rb", - "spec/client/repository_spec.rb", - "spec/client/session_spec.rb", - "spec/client/user_spec.rb", - "spec/client_spec.rb", - "spec/pro_spec.rb", - "spec/spec_helper.rb", - "spec/support/fake_api.rb", - "spec/support/fake_github.rb", - "spec/support/fake_travis_config.yml", - "spec/support/helpers.rb", - "spec/travis_spec.rb", - "travis.gemspec" + 'LICENSE', + 'README.md', + 'Rakefile', + 'assets/cacert.pem', + 'assets/init/bash.yml', + 'assets/init/c.yml', + 'assets/init/clojure.yml', + 'assets/init/cpp.yml', + 'assets/init/elixir.yml', + 'assets/init/erlang.yml', + 'assets/init/go.yml', + 'assets/init/groovy.yml', + 'assets/init/haskell.yml', + 'assets/init/java.yml', + 'assets/init/node_js.yml', + 'assets/init/objective-c.yml', + 'assets/init/perl.yml', + 'assets/init/php.yml', + 'assets/init/python.yml', + 'assets/init/ruby.yml', + 'assets/init/scala.yml', + 'assets/notifications/Travis CI.app/Contents/Info.plist', + 'assets/notifications/Travis CI.app/Contents/MacOS/Travis CI', + 'assets/notifications/Travis CI.app/Contents/PkgInfo', + 'assets/notifications/Travis CI.app/Contents/Resources/Travis CI.icns', + 'assets/notifications/Travis CI.app/Contents/Resources/en.lproj/Credits.rtf', + 'assets/notifications/Travis CI.app/Contents/Resources/en.lproj/InfoPlist.strings', + 'assets/notifications/Travis CI.app/Contents/Resources/en.lproj/MainMenu.nib', + 'assets/notifications/Travis CI.app/Contents/_CodeSignature/CodeResources', + 'assets/notifications/Travis CI.app/Contents/embedded.provisionprofile', + 'assets/notifications/icon.png', + 'assets/travis.sh', + 'assets/travis.sh.erb', + 'bin/travis', + 'examples/org_overview.rb', + 'examples/pro_auth.rb', + 'examples/stream.rb', + 'lib/travis.rb', + 'lib/travis/auto_login.rb', + 'lib/travis/cli.rb', + 'lib/travis/cli/accounts.rb', + 'lib/travis/cli/api_command.rb', + 'lib/travis/cli/branches.rb', + 'lib/travis/cli/cache.rb', + 'lib/travis/cli/cancel.rb', + 'lib/travis/cli/command.rb', + 'lib/travis/cli/console.rb', + 'lib/travis/cli/disable.rb', + 'lib/travis/cli/enable.rb', + 'lib/travis/cli/encrypt.rb', + 'lib/travis/cli/encrypt_file.rb', + 'lib/travis/cli/endpoint.rb', + 'lib/travis/cli/env.rb', + 'lib/travis/cli/help.rb', + 'lib/travis/cli/history.rb', + 'lib/travis/cli/init.rb', + 'lib/travis/cli/lint.rb', + 'lib/travis/cli/login.rb', + 'lib/travis/cli/logout.rb', + 'lib/travis/cli/logs.rb', + 'lib/travis/cli/monitor.rb', + 'lib/travis/cli/open.rb', + 'lib/travis/cli/parser.rb', + 'lib/travis/cli/pubkey.rb', + 'lib/travis/cli/raw.rb', + 'lib/travis/cli/repo_command.rb', + 'lib/travis/cli/report.rb', + 'lib/travis/cli/repos.rb', + 'lib/travis/cli/requests.rb', + 'lib/travis/cli/restart.rb', + 'lib/travis/cli/settings.rb', + 'lib/travis/cli/setup.rb', + 'lib/travis/cli/setup/anynines.rb', + 'lib/travis/cli/setup/appfog.rb', + 'lib/travis/cli/setup/artifacts.rb', + 'lib/travis/cli/setup/biicode.rb', + 'lib/travis/cli/setup/cloud_66.rb', + 'lib/travis/cli/setup/cloud_control.rb', + 'lib/travis/cli/setup/cloud_files.rb', + 'lib/travis/cli/setup/cloud_foundry.rb', + 'lib/travis/cli/setup/code_deploy.rb', + 'lib/travis/cli/setup/deis.rb', + 'lib/travis/cli/setup/divshot.rb', + 'lib/travis/cli/setup/elastic_beanstalk.rb', + 'lib/travis/cli/setup/engine_yard.rb', + 'lib/travis/cli/setup/gcs.rb', + 'lib/travis/cli/setup/hackage.rb', + 'lib/travis/cli/setup/heroku.rb', + 'lib/travis/cli/setup/modulus.rb', + 'lib/travis/cli/setup/ninefold.rb', + 'lib/travis/cli/setup/nodejitsu.rb', + 'lib/travis/cli/setup/npm.rb', + 'lib/travis/cli/setup/open_shift.rb', + 'lib/travis/cli/setup/opsworks.rb', + 'lib/travis/cli/setup/pypi.rb', + 'lib/travis/cli/setup/releases.rb', + 'lib/travis/cli/setup/ruby_gems.rb', + 'lib/travis/cli/setup/s3.rb', + 'lib/travis/cli/setup/sauce_connect.rb', + 'lib/travis/cli/setup/service.rb', + 'lib/travis/cli/show.rb', + 'lib/travis/cli/sshkey.rb', + 'lib/travis/cli/status.rb', + 'lib/travis/cli/sync.rb', + 'lib/travis/cli/token.rb', + 'lib/travis/cli/version.rb', + 'lib/travis/cli/whatsup.rb', + 'lib/travis/cli/whoami.rb', + 'lib/travis/client.rb', + 'lib/travis/client/account.rb', + 'lib/travis/client/artifact.rb', + 'lib/travis/client/auto_login.rb', + 'lib/travis/client/broadcast.rb', + 'lib/travis/client/build.rb', + 'lib/travis/client/cache.rb', + 'lib/travis/client/commit.rb', + 'lib/travis/client/entity.rb', + 'lib/travis/client/env_var.rb', + 'lib/travis/client/error.rb', + 'lib/travis/client/has_uuid.rb', + 'lib/travis/client/job.rb', + 'lib/travis/client/lint_result.rb', + 'lib/travis/client/listener.rb', + 'lib/travis/client/methods.rb', + 'lib/travis/client/namespace.rb', + 'lib/travis/client/not_loadable.rb', + 'lib/travis/client/repository.rb', + 'lib/travis/client/request.rb', + 'lib/travis/client/restartable.rb', + 'lib/travis/client/session.rb', + 'lib/travis/client/settings.rb', + 'lib/travis/client/singleton_setting.rb', + 'lib/travis/client/ssh_key.rb', + 'lib/travis/client/states.rb', + 'lib/travis/client/user.rb', + 'lib/travis/client/weak_entity.rb', + 'lib/travis/pro.rb', + 'lib/travis/pro/auto_login.rb', + 'lib/travis/tools/assets.rb', + 'lib/travis/tools/completion.rb', + 'lib/travis/tools/formatter.rb', + 'lib/travis/tools/github.rb', + 'lib/travis/tools/notification.rb', + 'lib/travis/tools/safe_string.rb', + 'lib/travis/tools/ssl_key.rb', + 'lib/travis/tools/system.rb', + 'lib/travis/version.rb', + 'spec/cli/api_command_spec.rb', + 'spec/cli/cancel_spec.rb', + 'spec/cli/encrypt_file_spec.rb', + 'spec/cli/encrypt_spec.rb', + 'spec/cli/endpoint_spec.rb', + 'spec/cli/help_spec.rb', + 'spec/cli/history_spec.rb', + 'spec/cli/init_spec.rb', + 'spec/cli/logs_spec.rb', + 'spec/cli/open_spec.rb', + 'spec/cli/repo_command_spec.rb', + 'spec/cli/restart_spec.rb', + 'spec/cli/setup/service_spec.rb', + 'spec/cli/setup_spec.rb', + 'spec/cli/show_spec.rb', + 'spec/cli/status_spec.rb', + 'spec/cli/token_spec.rb', + 'spec/cli/version_spec.rb', + 'spec/cli/whoami_spec.rb', + 'spec/client/account_spec.rb', + 'spec/client/auto_login_spec.rb', + 'spec/client/broadcast_spec.rb', + 'spec/client/build_spec.rb', + 'spec/client/commit_spec.rb', + 'spec/client/job_spec.rb', + 'spec/client/methods_spec.rb', + 'spec/client/namespace_spec.rb', + 'spec/client/repository_spec.rb', + 'spec/client/session_spec.rb', + 'spec/client/user_spec.rb', + 'spec/client_spec.rb', + 'spec/pro_spec.rb', + 'spec/spec_helper.rb', + 'spec/support/fake_api.rb', + 'spec/support/fake_github.rb', + 'spec/support/fake_travis_config.yml', + 'spec/support/helpers.rb', + 'spec/travis_spec.rb', + 'travis.gemspec' ] # dependencies - s.add_dependency "faraday", "~> 1.0" - s.add_dependency "faraday_middleware", "~> 1.0" - s.add_dependency "highline", "~> 2.0" - s.add_dependency "gh", "~> 0.13" - s.add_dependency "launchy", "~> 2.1", "< 2.5.0" - s.add_dependency "json_pure", "~> 2.3" - s.add_dependency "pusher-client", "~> 0.4" - s.add_development_dependency "rspec", "~> 2.12" - s.add_development_dependency "rspec-its" - s.add_development_dependency "sinatra", "~> 1.3" - s.add_development_dependency "rack-test", "~> 0.6" + s.add_dependency 'faraday', '~> 2.7.10' + s.add_dependency 'faraday-rack', '~> 2' + s.add_dependency 'highline', '~> 2.1.0' + s.add_dependency 'json_pure', '~> 2.6.3' + s.add_dependency 'launchy', '~> 2.5.2' + s.add_dependency 'pusher-client', '~> 0.6.2' + s.add_development_dependency 'rack-test', '~> 2.1.0' + s.add_development_dependency 'rspec', '~> 3.12' + s.add_development_dependency 'rspec-its', '~> 1.3.0' + s.add_development_dependency 'sinatra', '~> 3.0.6' # Prereleasing on Travis CI - if ENV['TRAVIS_JOB_NUMBER'] and ENV['TRAVIS_REPO_SLUG'] == 'travis-ci/travis.rb' + if ENV['TRAVIS_JOB_NUMBER'] && (ENV['TRAVIS_REPO_SLUG'] == 'travis-ci/travis.rb') digits = s.version.to_s.split '.' digits[-1] = digits[-1].to_s.succ s.version = digits.join('.') + ".travis.#{ENV['TRAVIS_JOB_NUMBER']}"