jirabulkupdatecomponentlead/fixComponentLead.py
2023-05-08 23:07:56 +00:00

72 lines
2.5 KiB
Python

import base64
import json
import os
import requests
from datetime import datetime
jira_base_url = "https://jira.someserver.com"
username = "userName"
password = "passWord! @#"
project_key = "projectKey"
# 1. Pull a project's component list
response = requests.get(
f"{jira_base_url}/rest/api/2/project/{project_key}/components",
auth=(username, password),
headers={"Content-Type": "application/json"},
)
raw_data = response.json()
# 2. Create a mapping of component ID, component name, and the assignee name
component_data = [
base64.b64encode(json.dumps({"id": comp["id"], "name": comp["name"], "assignee": comp["assignee"]["name"]}).encode("utf-8")).decode("utf-8")
for comp in raw_data
]
# 3. Show a comma-separated list of the usernames and ask which username we want to replace
usernames = ", ".join(sorted(set([comp["assignee"]["name"] for comp in raw_data])))
print(f"Usernames: {usernames}")
old_username = input("Enter the username you want to replace: ")
# 4. Check if the entered username is in the list
if old_username not in usernames:
print("Username not found in the list. Please select a name from the list.")
exit(1)
# 5. Ask for the new username
new_username = input("Enter the new username: ")
# Create a folder for the source username and history.txt file
os.makedirs(old_username, exist_ok=True)
history_file = os.path.join(old_username, "history.txt")
# 6. Create a new mapping of the IDs and new assignees we will be changing
components_to_update = [
json.loads(base64.b64decode(comp_b64).decode("utf-8"))
for comp_b64 in component_data
if json.loads(base64.b64decode(comp_b64).decode("utf-8"))["assignee"] == old_username
]
# 7. Push an update to the Jira Server API to update those component leads
for component in components_to_update:
component_id = component["id"]
component_name = component["name"]
if not component_id or not component_name:
continue
requests.put(
f"{jira_base_url}/rest/api/2/component/{component_id}",
auth=(username, password),
headers={"Content-Type": "application/json"},
json={"leadUserName": new_username},
)
# Save the changed component ID and timestamp to the history file
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_line = f"Updated component {component_name} ({component_id}) with new assignee {new_username} at {timestamp}"
print(log_line)
with open(history_file, "a") as history:
history.write(log_line + "\n")