Skip to content

Instantly share code, notes, and snippets.

@edjames
Created November 22, 2017 15:54
Show Gist options
  • Save edjames/c88aba26d4f1228a4ef1775816fcec57 to your computer and use it in GitHub Desktop.
Save edjames/c88aba26d4f1228a4ef1775816fcec57 to your computer and use it in GitHub Desktop.
workflow-cli
#!/usr/bin/env ruby
require 'thor'
require 'readline'
begin
require 'tracker_api'
rescue LoadError
puts 'Please install the tracker_api gem.'
puts 'Exiting ...'
exit
end
module Global
API_TOKEN = ENV.fetch('PIVOTAL_API_TOKEN')
PROJECT_ID = ENV.fetch('PIVOTAL_PROJECT_ID')
end
class Base < Thor
include Thor::Actions
include Global
trap(:INT) do
puts 'Exiting...'
exit
end
private
def project
@project ||= client.project(PROJECT_ID)
end
def client
@client ||= TrackerApi::Client.new(token: API_TOKEN)
end
end
module Git
class Branch < Base
desc 'create <id>', 'Create a new git branch from Pivotal Tracker story'
method_option :story_id, aliases: '-s', type: :string, required: true
def create
story = project.story(story_id)
say_status "Found story: ", story.name, :yellow
normalized_name = story.name.gsub(/\W/, '-').squeeze('-').downcase
pr_branch = "#{story.id}-#{normalized_name}"
branch_name = ask_for_branch_name(pr_branch)
system("git checkout -b #{branch_name}")
rescue TrackerApi::Errors::ClientError
say_status 'Story not found', story_id, :red
exit
end
private
def story_id
normalize_id(options[:story_id])
end
def normalize_id(id)
id.match(/\d+/)[0]
end
def ask_for_branch_name(default)
IO.popen('pbcopy', 'w') { |f| f << default }
say_status "Branch name: ", default, :yellow
puts; puts 'Hit (enter) to use branch name, or Cmd+V to paste and edit ...'
input = Readline.readline
input.empty? ? default : input
end
end
end
module Git
class PullRequest < Base
desc 'create', 'Create a pull request based on the branch name'
def create
story = project.story(story_id)
title = "(#{story_id}) #{story.name}"
git_url = "https://github.com/#{git_repo}/compare/#{current_branch}?expand=1&pull_request[title]=#{title}"
system('open', URI.escape(git_url))
end
private
def git_repo
git_remote.match(/github\.com:(.+)\.git/)[1]
end
def git_remote
`git config --get remote.origin.url`
end
def story_id
current_branch.match(/(\d+)/)[0]
end
def current_branch
`git rev-parse --abbrev-ref HEAD`.strip
end
end
end
class WorkflowCLI < Thor
VERSION = '1.0.1'
register(Git::Branch, 'git:branch', 'git:branch <command>', 'Git branch commands')
register(Git::PullRequest, 'git:pr', 'git:pr <command>', 'Git pull request commands')
package_name 'Pivotal Tracker CLI Toolkit'
map %w(--version -v) => :version
desc '--version, -v', 'Print the version'
def version
puts VERSION
end
end
WorkflowCLI.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment