Skip to content

Instantly share code, notes, and snippets.

@rattrayalex
Last active August 5, 2021 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rattrayalex/ca91eacfd3b4329168bbaa957e50ef51 to your computer and use it in GitHub Desktop.
Save rattrayalex/ca91eacfd3b4329168bbaa957e50ef51 to your computer and use it in GitHub Desktop.
Bash function to choose an open jira ticket and create a branch and empty commit for it
source "$HOME/.env"
jira-branch() (
set -eo pipefail
local jira_instance jq_template query username api_key ticket_id jira_title commit_title
username="$JIRA_USERNAME"
api_key="$JIRA_API_KEY"
jira_instance="$JIRA_INSTANCE"
query="project=MAIN AND statusCategory!=Done AND assignee=currentUser()"
jq_template='"'\
'\(.key). \(.fields.summary) [\(.fields.issuetype.name)]'\
'\t'\
'Reporter: \(.fields.reporter.displayName)\n'\
'Created: \(.fields.created)\n'\
'Updated: \(.fields.updated)\n\n'\
'\(.fields.description)'\
'"'
jira_title=$(
curl --silent --compressed \
-H "Content-Type: application/json" \
--user "$username:$api_key" \
--data-urlencode "jql=$query" \
--get \
"https://$jira_instance/rest/api/2/search" |
jq ".issues[] | $jq_template" |
sed -e 's/"\(.*\)"/\1/' -e 's/\\t/\t/' |
fzf \
--with-nth=1 \
--delimiter='\t' \
--preview='echo -e {2}' \
--preview-window=top:wrap |
cut -f1
)
if [ -n "$jira_title" ]; then
ticket_id=$(echo "$jira_title" | perl -pE 's/\. .+//')
ticket_title=$(echo -e "$jira_title" | perl -pE 's/^\S+\. //; s/ \[\w+\]$//')
ticket_type=$(echo -e "$jira_title" | perl -pE 's/.+\[(\w+)\]$/\1/')
branch_type=$(case $ticket_type in
(Story) echo "feature";;
(Task) echo "enhancement";;
(Bug) echo "bugfix";;
(*) echo "feature";;
esac)
commit_title="$ticket_id $ticket_title"
branch_name="$branch_type""/""$ticket_id""/"$(echo "$commit_title" | perl -pE 's/^[A-Z]+-\d+//; s/[^0-9a-zA-Z]+/-/g; s/(^-|-$)//g; s/[A-Z]/\L$&/g')
main_branch=$(git branch -rl '*/HEAD' | rev | cut -d/ -f1 | rev)
git fetch --force origin "$main_branch":"$main_branch" --update-head-ok
git branch -D "$branch_name" &>/dev/null || true
git checkout -b "$branch_name" "$main_branch"
git commit --allow-empty -m "$(printf "%s\n\n%s" "$commit_title" "https://$jira_instance/browse/$ticket_id")"
curl --silent --compressed \
-H "Content-Type: application/json" \
--user "$username:$api_key" \
-d '{"transition": {"id": "321"}}' \
"https://$jira_instance/rest/api/2/issue/$ticket_id/transitions"
fi
)
JIRA_USERNAME="me@example.com"
JIRA_API_KEY="follow these instructions: https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/"
JIRA_INSTANCE="my-company.atlassian.net"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment