#!/usr/bin/env ruby # encoding: UTF-8 # # git-jira-branch # # Suggest a branch name from the given JIRA issue ID # # Assumes the branches are named as: # - # require 'rubygems' require 'optparse' require 'jira-ruby' require 'readline' require 'term/ansicolor' require 'git-whistles/app' require 'git-whistles/jira' class App < Git::Whistles::App def initialize super @client = Git::Whistles::Jira.new.get_client rescue die('Aborting.') end def main(args) super parse_args!(args) if args.count < 1 show_and_exit usage end issue_id = args[0] # get JIRA Issue info issue = get_jira_info(issue_id) branch_name_suggested = "#{issue_id.upcase}/#{issue.fields['summary'].downcase}" branch_name_suggested.gsub!(/[^\w\d\/]/, '-').gsub!(/-+/, '-') puts 'The suggested branch name is: ' << Term::ANSIColor.yellow(branch_name_suggested) puts ' Press ENTER if you agree' puts ' or Write any other name and press ENTER' puts ' or Press CTRL-D to cancel' branch_name = Readline.readline ' > ', false if branch_name.nil? log.warn "\nCancelled by user" exit 2 end puts 'Would you like to transition the issue?' issue.transitions.all.each do |t| puts "#{t.id} - #{t.name}" end puts 'Type the number or enter to continue' transition = Readline.readline ' > ', false branch_name = branch_name.empty? ? branch_name_suggested : branch_name # create branch `cd #{ENV['PWD']} && git checkout -b #{branch_name}` # issue.notes.create :text => "Created branch #{branch_name}" # issue.update :current_state => 'started' attrs = { update: { comment: [ { add: { body: "Created branch #{branch_name}" } } ], assignee: [ { set: { name: username } } ] } } issue.save!(attrs) if transition attrs = { transition: { id: transition } } issue.client.post("#{issue.url}/transitions", attrs.to_json) end puts Term::ANSIColor.green('Created branch and started JIRA issue') end private def usage 'Usage: git jira-branch JIRA_ID' end def show_and_exit(message) puts message exit 1 end def option_parser @option_parser ||= OptionParser.new do |op| op.banner = usage op.on_tail('-h', '--help', 'Show this message') do show_and_exit op end end end def username @username ||= `git config jira.username`.strip end def get_jira_info(issue_id) log.info "Finding your JIRA Issue¬" issue = @client.Issue.find(issue_id) log.info '.' log.info "Found issue #{issue_id} in '#{issue.fields['project']['name']}'" issue rescue => e log.info e.message log.warn "Apologies... I could not find issue #{issue_id}." exit 1 end end ############################################################################ App.run!