Skip to content

Instantly share code, notes, and snippets.

@smiklosovic
Last active February 26, 2024 09:44
Show Gist options
  • Save smiklosovic/0fb9144f798764901eee5087649745b6 to your computer and use it in GitHub Desktop.
Save smiklosovic/0fb9144f798764901eee5087649745b6 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import sys
import argparse
import json
import requests
import os
from jira import JIRA
from datetime import datetime, timezone
import random
import string
import subprocess
import webbrowser
jira_add_comment_url = "https://issues.apache.org/jira/rest/api/latest/issue/%s/comment"
jira = JIRA('https://issues.apache.org/jira', token_auth='PUT YOUR OWN')
verbose = False
args = None
git_branch = None
selected_command = None
def parse_arguments():
parser = argparse.ArgumentParser(description="Jira helper")
parser.add_argument('--branch', help="git branch")
parser.add_argument('--verbose', '-v', help="verbose mode", action='store_true')
parser.add_argument('--comment', '-c', help="write comment", action='store_true')
parser.add_argument('--ticket', '-t', help="open ticket", action='store_true')
parsed = parser.parse_args()
verbose = parsed.verbose
return parsed
def resolve_git_branch(git_branch):
if git_branch == None:
return os.popen("git rev-parse --abbrev-ref HEAD").read().replace("\n","")
else:
if not git_branch.startswith("CASSANDRA"):
return "CASSANDRA-" + git_branch
else:
return git_branch
def resolve_ticket(args):
return "CASSANDRA-" + resolve_git_branch(args.branch).split('-')[1]
# JIRA ########################################
def get_assignee_from_jira(ticket):
"""
Get the assignee for the given JIRA ticket.
:param ticket:
:return:
"""
r = requests.get("https://issues.apache.org/jira/rest/api/latest/issue/" + ticket).json()
data = json.loads(json.dumps(r))
if data['fields']['assignee']:
return data['fields']['assignee']['displayName']
return None
def get_reviewers_from_jira(ticket):
"""
Get the assignee for the given JIRA ticket.
:param ticket:
:return:
"""
r = requests.get("https://issues.apache.org/jira/rest/api/latest/issue/" + ticket).json()
data = json.loads(json.dumps(r))
reviewers = data['fields']['customfield_12313420']
if reviewers:
return ', '.join([reviewer['displayName'] for reviewer in reviewers])
return None
def comment(ticket, data):
jira.add_comment(ticket, data)
def print_comment(comment):
def print_multiline(text, max_line_length=80):
words = text.split()
lines = []
current_line = ""
for word in words:
if len(current_line) + len(word) + 1 <= max_line_length:
current_line += word + " "
else:
lines.append(current_line.strip())
current_line = word + " "
lines.append(current_line.strip())
for line in lines:
if line is not None:
print(line)
def format_date(date_to_format):
return datetime.strftime(datetime.strptime(date_to_format, "%Y-%m-%dT%H:%M:%S.%f+0000"), "%d/%m/%Y %H:%M")
green("{} -> {}".format(format_date(comment.created), comment.author))
print_multiline(comment.body)
print("")
def dump_comments(ticket):
for comment_id in jira.comments(ticket):
comment = jira.comment(ticket, comment_id)
print_comment(comment)
# Utils #################################
def write_comment(starting_comment = None):
def generate_random_string(length):
characters = string.ascii_letters + string.digits
random_string = ''.join(random.choice(characters) for _ in range(length))
return random_string
file = "/tmp/%s" % generate_random_string(10)
if starting_comment != None:
with open(file, 'w') as jira_comment:
jira_comment.write(starting_comment)
jira_comment.flush()
subprocess.run(["gedit", file])
file_content = None
try:
with open(file, 'r') as jira_comment:
file_content = jira_comment.read()
finally:
os.remove(file)
return file_content
def open_ticket(ticket):
webbrowser.open("https://issues.apache.org/jira/browse/%s" % ticket)
def color_print(text, color, colorful):
if colorful:
print(f"\033[{color}m{text}\033[0m")
else:
print(text)
def red(text, colorful = True):
color_print(text, 31, colorful)
def green(text, colorful = True):
color_print(text, 32, colorful)
def yellow(text, colorful = True):
color_print(text, 33, colorful)
def blue(text, colorful = True):
color_print(text, 34, colorful)
def white(text, colorful = True):
color_print(text, 37, colorful)
def main():
args = parse_arguments()
ticket = resolve_ticket(args)
data = None
if not sys.stdin.isatty():
data = sys.stdin.read()
if data == None and args.ticket:
open_ticket(ticket)
return
elif data == None and not args.comment:
dump_comments(ticket)
return
elif data != None and args.comment:
data = write_comment(starting_comment = data)
elif args.comment:
data = write_comment()
if data is not None:
comment(ticket, data)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment