Class: Cimas::Cli::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/cimas/cli/command.rb

Constant Summary collapse

DEFAULT_CONFIG =
{
  'dry_run' => false,
  'verbose' => false,
  'groups' => ['all'],
  'pull_branch' => 'master',
  'force_push' => false,
  'assignees' => [],
  'reviewers' => []
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Command

Returns a new instance of Command.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/cimas/cli/command.rb', line 23

def initialize(options)
  unless options['config_file_path'].exist?
    raise "[ERROR] config_file_path #{options['config_file_path']} does not exist, aborting."
  end

  @data = YAML.load(IO.read(options['config_file_path']))

  @config = DEFAULT_CONFIG.merge(settings).merge(options)

  unless repos_path.exist?
    FileUtils.mkdir_p repos_path
  end

  if ENV["GITHUB_TOKEN"]
    @config['github_token'] ||= ENV["GITHUB_TOKEN"]
  end
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



11
12
13
# File 'lib/cimas/cli/command.rb', line 11

def config
  @config
end

#github_clientObject

Returns the value of attribute github_client.



11
12
13
# File 'lib/cimas/cli/command.rb', line 11

def github_client
  @github_client
end

Instance Method Details

#commit_messageObject



282
283
284
285
286
287
# File 'lib/cimas/cli/command.rb', line 282

def commit_message
  if config['commit_message'].nil?
    raise OptionParser::MissingArgument, "Missing -m/--message value"
  end
  config['commit_message']
end

#config_master_pathObject



91
92
93
# File 'lib/cimas/cli/command.rb', line 91

def config_master_path
  config['config_master_path']
end

#dataObject



57
58
59
# File 'lib/cimas/cli/command.rb', line 57

def data
  @data
end

#diffObject



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/cimas/cli/command.rb', line 150

def diff
  sanity_check
  unless config['config_master_path'].exist?
    raise "[ERROR] config_master_path not set, aborting."
  end

  filtered_repo_names.each do |repo_name|

    repo = repo_by_name(repo_name)
    if repo.nil?
      puts "[WARNING] #{repo_name} not configured, skipping."
      next
    end

    repo_dir = File.join(repos_path, repo_name)
    unless File.exist?(repo_dir)
      puts "[ERROR] #{repo_name} is missing in #{repos_path}, skipping diff for it."
      next
    end

    g = Git.open(repo_dir)
    # g.checkout(branch)
    # g.reset_hard(branch)
    # g.clean(force: true)

    # puts "Syncing files in #{repo_name}..."
    #
    # files.each do |target, source|
    #   # puts "file #{source} => #{target}"
    #   source_path = File.join(config_master_path, source)
    #   target_path = File.join(repos_path, repo_name, target)
    #   # puts "file #{source_path} => #{target_path}"
    #
    #   copy_file(source_path, target_path)
    #   # g.add(target_path)
    # end

    puts "======================= DIFF FOR #{repo_name} ========================="
    # Debugging to see if files have been changed
    diff = g.diff
    puts diff.patch

    # g.status.changed.each do |file, status|
   #    puts "Updated files in #{repo_name}:"
   #    puts status.blob(:index).contents
   #  end
  end
end

#filtered_repo_namesObject

def lint(options)

config_master_path = options['config_master_path']
appveyor_token = options['appveyor_token']

config = YAML.load_file(File.join(config_master_path, 'ci.yml'))

validated = []

config['repos'].each do |_, repo_ci|
  travisci, appveyor = repo_ci.values_at('.travis.yml', 'appveyor.yml')

  if travisci && !validated.include?(travisci)
    valid = system("travis lint #{File.join(config_master_path, travisci)}", :out => :close)
    puts "#{travisci} valid: #{valid}"
    validated << travisci
  end

  if appveyor && !validated.include?(appveyor)
    uri = URI('https://ci.appveyor.com/api/projects/validate-yaml')
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    req = Net::HTTP::Post.new(uri.path, {
      "Content-Type" => "application/json",
      "Authorization" => "Bearer #{appveyor_token}"
    })
    req.body = File.read(File.join(config_master_path, appveyor))

    valid = http.request(req).kind_of? Net::HTTPSuccess

    puts "#{appveyor} valid: #{valid}"
    validated << appveyor
  end
end

end



235
236
237
238
239
240
241
242
# File 'lib/cimas/cli/command.rb', line 235

def filtered_repo_names
  return repositories unless config['groups']

  # puts "config['groups'] #{config['groups'].inspect}"
  config['groups'].inject([]) do |acc, group|
    acc + group_repo_names(group)
  end.uniq
end

#force_pushObject



311
312
313
# File 'lib/cimas/cli/command.rb', line 311

def force_push
  config['force_push']
end

#git_remote_to_github_name(remote) ⇒ Object



370
371
372
# File 'lib/cimas/cli/command.rb', line 370

def git_remote_to_github_name(remote)
  remote.match(/github.com\/(.*)/)[1]
end

#merge_branchObject



303
304
305
306
307
308
# File 'lib/cimas/cli/command.rb', line 303

def merge_branch
  if config['merge_branch'].nil?
    raise OptionParser::MissingArgument, "Missing -b/--merge-branch value"
  end
  config['merge_branch']
end

#open_prsObject



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'lib/cimas/cli/command.rb', line 374

def open_prs
  sanity_check
  branch = merge_branch
  message = pr_message
  assignees = config['assignees']
  reviewers = config['reviewers']

  filtered_repo_names.each do |repo_name|
    repo = repo_by_name(repo_name)
    if repo.nil?
      puts "[WARNING] #{repo_name} not configured, skipping."
      next
    end

    repo_dir = File.join(repos_path, repo_name)
    unless File.exist?(repo_dir)
      puts "[ERROR] #{repo_name} is missing in #{repos_path}, skipping sync_and_commit for it."
      next
    end

    g = Git.open(repo_dir)
    github_slug = git_remote_to_github_name(repo.remote)

    dry_run("Opening GitHub PR: #{github_slug}, branch #{repo.branch} <- #{branch}, message '#{message}'") do
      puts "Opening GitHub PR: #{github_slug}, branch #{repo.branch} <- #{branch}, message '#{message}'"

      begin
        pr = github_client.create_pull_request(
          github_slug,
          repo.branch,
          branch,
          message,
          "As title. \n\n _Generated by Cimas_."
        )
        number = pr['number']
        puts "PR #{github_slug}\##{number} created"

      rescue Octokit::Error => e
        # puts e.inspect
        # puts '------'
        # puts "e.message #{e.message}"

        case e.message
        when /A pull request already exists/
          puts "[WARNING] PR already exists for #{branch}."

        when /field: head\s+code: invalid/
          puts "[WARNING] Branch #{branch} does not exist on #{github_slug}. Did you run `push`? Skipping."
          next

        when /message: No commits between/
          puts "[WARNING] Target branch (#{repo.branch}) is on par with new branch (#{branch}). Skipping."
          next

        else
          raise e
        end
      end

      # puts pr.inspect

      unless pr
        puts "[WARNING] Detecting PR from GitHub..."
        github_branch_owner = github_slug.match(/(.*)\/.*/)[1]
        prs = github_client.pull_requests(github_slug, head: "#{github_branch_owner}:#{branch}")
        pr = prs.first
        puts "[WARNING] Detected PR to be #{github_slug}\##{pr['number']}, continue processing."
      end

      # TODO: Catch

      number = pr['number']

      unless reviewers.empty?
        puts "Requesting #{github_slug}\##{number} review from: [#{reviewers.join(',')}]"
        begin
          github_client.request_pull_request_review(
            github_slug,
            number,
            reviewers: reviewers
          )

        rescue Octokit::Error => e
          # puts e.inspect
          # puts '------'
          # puts "e.message #{e.message}"

          # TODO: When command is first run, should exclude the PR author from 'reviewers'
          case e.message
          when /Review cannot be requested from pull request author./
            puts "[WARNING] #{e.message}, skipping."
            next
          else
            raise e
          end

        end
      end

      unless assignees.empty?
        puts "Assigning #{github_slug}\##{number} to: [#{assignees.join(',')}]"
        github_client.add_assignees(
          github_slug,
          number,
          assignees
        )
      end

    end
  end
end

#pr_messageObject



289
290
291
292
293
294
# File 'lib/cimas/cli/command.rb', line 289

def pr_message
  if config['pr_message'].nil?
    raise OptionParser::MissingArgument, "Missing -m/--message value"
  end
  config['pr_message']
end

#pullObject



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/cimas/cli/command.rb', line 248

def pull
  sanity_check
  filtered_repo_names.each do |repo_name|

    repo = repo_by_name(repo_name)

    if repo.nil?
      puts "[WARNING] #{repo_name} not configured, skipping."
      next
    end

    repo_dir = File.join(repos_path, repo_name)
    unless File.exist?(repo_dir)
      puts(
        "[ERROR] #{repo_name} is missing in #{repos_path}, " \
        " skipping pull for it."
      )

      next
    end

    g = Git.open(repo_dir)

    dry_run("Pulling from #{repo_name}...") do
      puts "Pulling from #{repo_name}..."
      g.reset_hard(repo.branch)
      g.checkout(repo.branch)
      g.pull
    end
  end

  puts "Done!"
end

#pushObject



315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/cimas/cli/command.rb', line 315

def push
  sanity_check

  filtered_repo_names.each do |repo_name|
    repo = repo_by_name(repo_name)

    if repo.nil?
      puts "[WARNING] #{repo_name} not configured, skipping."
      next
    end

    repo_dir = File.join(repos_path, repo_name)
    unless File.exist?(repo_dir)
      puts "[ERROR] #{repo_name} is missing in #{repos_path}, skipping push for it."
      next
    end

    g = Git.open(repo_dir)
    dry_run("Pushing branch #{push_to_branch} (commit #{g.object('HEAD').sha}) to #{g.remotes.first}:#{repo_name}") do
      puts "repo.branch #{repo.branch}"
      g.checkout(repo.branch)
      g.reset(repo.branch)
      g.branch(push_to_branch).delete
      g.add(all: true)
      g.branch(push_to_branch).checkout

      if g.status.changed.empty? &&
          g.status.added.empty? &&
          g.status.deleted.empty?

        puts "Skipping commit on #{repo_name}, no changes detected."
      else
        puts "Committing on #{repo_name}."
        g.commit_all(commit_message)#, amend: true)
      end

      # Still push even if there was no commit, as the remote branch
      # may have been deleted. If the remote branch is deleted we can't
      # make PRs in the next stage.

      if force_push
        puts "Force-pushing branch #{push_to_branch} (commit #{g.object('HEAD').sha}) to #{g.remotes.first}:#{repo_name}."
        g.push(g.remotes.first, push_to_branch, force: true)
      else
        puts "Pushing branch #{push_to_branch} (commit #{g.object('HEAD').sha}) to #{g.remotes.first}:#{repo_name}."
        g.push(g.remotes.first, push_to_branch)
      end
    end
  end

  # do two separate `git add` because one of it may be missing
  # run_cmd("git -C #{repos_path} multi -c add .travis.yml", dry_run)
  # run_cmd("git -C #{repos_path} multi -c add appveyor.yml")
end

#push_to_branchObject



296
297
298
299
300
301
# File 'lib/cimas/cli/command.rb', line 296

def push_to_branch
  if config['push_to_branch'].nil?
    raise OptionParser::MissingArgument, "Missing -b/--push-branch value"
  end
  config['push_to_branch']
end

#repo_by_name(name) ⇒ Object



244
245
246
# File 'lib/cimas/cli/command.rb', line 244

def repo_by_name(name)
  Cimas::Repository.new(name, data["repositories"][name])
end

#repos_pathObject



95
96
97
# File 'lib/cimas/cli/command.rb', line 95

def repos_path
  config['repos_path']
end

#repositoriesObject



99
100
101
# File 'lib/cimas/cli/command.rb', line 99

def repositories
  data['repositories']
end

#sanity_checkObject



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/cimas/cli/command.rb', line 74

def sanity_check
  unsynced = []

  repositories.each_pair do |repo_name, attribs|
    repo_dir = File.join(repos_path, repo_name)
    unless File.exist?(repo_dir) && File.exist?(File.join(repo_dir, '.git'))
      unsynced << repo_name
    end
  end

  unsynced.uniq!

  return true if unsynced.empty?

  raise "[ERROR] These repositories have not been setup, please run `setup` first: #{unsynced.inspect}"
end

#settingsObject



41
42
43
# File 'lib/cimas/cli/command.rb', line 41

def settings
  data['settings']
end

#setupObject



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/cimas/cli/command.rb', line 61

def setup
  repositories.each_pair do |repo_name, attribs|
    repo_dir = File.join(repos_path, repo_name)
    # puts "attribs #{attribs.inspect}"
    unless File.exist?(repo_dir) && File.exist?(File.join(repo_dir, '.git'))
      puts "Git cloning #{repo_name} from #{attribs['remote']}..."
      Git.clone(attribs['remote'], repo_name, path: repos_path)
    else
      puts "Skip cloning #{repo_name}, already exists."
    end
  end
end

#syncObject



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/cimas/cli/command.rb', line 103

def sync
  sanity_check
  unless config['config_master_path'].exist?
    raise "[ERROR] config_master_path not set, aborting."
  end

  filtered_repo_names.each do |repo_name|

    repo = repo_by_name(repo_name)
    if repo.nil?
      puts "[WARNING] #{repo_name} not configured, skipping."
      next
    end

    repo_dir = File.join(repos_path, repo_name)
    unless File.exist?(repo_dir)
      puts "[ERROR] #{repo_name} is missing in #{repos_path}, skipping sync for it."
      next
    end

    dry_run("Copying files to #{repo_name} and staging them") do
      g = Git.open(repo_dir)
      g.checkout(repo.branch)
      g.reset_hard(repo.branch)
      g.clean(force: true)

      puts "Syncing and staging files in #{repo_name}..."

      repo.files.each do |target, source|
        # puts "file #{source} => #{target}"
        source_path = File.join(config_master_path, source)
        target_path = File.join(repos_path, repo_name, target)
        # puts "file #{source_path} => #{target_path}"

        copy_file(source_path, target_path)
        g.add(target_path)
      end

      # Debugging to see if files have been changed
      # g.status.changed.each do |file, status|
      #   puts "Updated files in #{repo_name}:"
      #   puts status.blob(:index).contents
      # end
    end
  end
end