diff --git a/README.md b/README.md index c8fef2e..f8f2f26 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,35 @@ Run `source ~/.zshrc` or restart terminal. ## Usage ⚔ +## Project structure + +GitHappens is split into focused modules so the CLI entry point stays small and command workflows can be tested independently: + +```text +gitHappens.py # CLI entry point and argument dispatch +config.py # Config and template file loading +gitlab_api.py # GitLab API and glab command integrations +git_utils.py # Local git helpers +templates.py # Issue template selection and lookup +interactive.py # Interactive prompt helpers +commands/ + create_issue.py # Issue, branch, and merge request creation workflow + open_mr.py # Open the active merge request in the browser + review.py # Reviewers, time tracking, AI review, and auto-merge + summary.py # Commit summary commands + deploy.py # Last production deployment lookup +tests/ # Unit tests for the extracted modules +``` + +### Testing + +Install runtime dependencies and pytest, then run the test suite: + +```bash +pip install -r requirements.txt pytest +pytest +``` + ### Project selection - Project selection is made automatically if you run script in same path as your project is located. @@ -225,4 +254,3 @@ I suggest checking Gitlab's official API documentation: https://docs.gitlab.com/ ## Donating šŸ’œ Make sure to check this project on [OpenPledge](https://app.openpledge.io/repositories/zigcBenx/gitHappens). - diff --git a/commands/__init__.py b/commands/__init__.py new file mode 100644 index 0000000..096b815 --- /dev/null +++ b/commands/__init__.py @@ -0,0 +1 @@ +"""Command workflows for the GitHappens CLI.""" diff --git a/commands/create_issue.py b/commands/create_issue.py new file mode 100644 index 0000000..005aefd --- /dev/null +++ b/commands/create_issue.py @@ -0,0 +1,181 @@ +import inquirer + +from git_utils import getProjectLinkFromCurrentDir +from gitlab_api import ( + closeOpenedIssue, + create_branch, + create_merge_request, + executeIssueCreate, + getActiveIteration, + get_all_projects, + list_epics, + list_iterations, + list_milestones, +) +from interactive import ( + enterProjectId, + getSelectedEpic, + getSelectedIteration, + getSelectedMilestone, + select_epic, + select_iteration, + select_milestone, + selectLabels, +) + + +def get_project_id(): + project_link = getProjectLinkFromCurrentDir() + if project_link == -1: + return enterProjectId() + + all_projects = get_all_projects(project_link) + matching_id = None + for project in all_projects: + if project.get("ssh_url_to_repo") == project_link: + matching_id = project.get("id") + break + return matching_id + + +def get_milestone(manual): + if manual: + milestones = list_milestones() + return getSelectedMilestone(select_milestone(milestones), milestones) + return list_milestones(True) + + +def get_iteration(manual): + if manual: + iterations = list_iterations() + return getSelectedIteration(select_iteration(iterations), iterations) + return getActiveIteration() + + +def get_epic(): + epics = list_epics() + return getSelectedEpic(select_epic(epics), epics) + + +def createIssue(title, project_id, milestoneId, epic, iteration, settings): + if settings: + issue_type = settings.get("type") or "issue" + return executeIssueCreate( + project_id, + title, + settings.get("labels"), + milestoneId, + epic, + iteration, + settings.get("weight"), + settings.get("estimated_time"), + issue_type, + ) + print("No settings in template") + exit(2) + + +def startIssueCreation(project_id, title, milestone, epic, iteration, selectedSettings, onlyIssue, main_branch): + estimated_time = inquirer.prompt( + [ + inquirer.Text( + "estimated_time", + message="Estimated time to complete this issue (in minutes, optional)", + validate=lambda _, value: value == "" or value.isdigit(), + ) + ] + )["estimated_time"] + + if isinstance(project_id, list): + estimated_time_per_project = int(estimated_time) / len(project_id) if estimated_time else None + else: + estimated_time_per_project = estimated_time + + if estimated_time_per_project: + selectedSettings = selectedSettings.copy() if selectedSettings else {} + selectedSettings["estimated_time"] = int(estimated_time_per_project) + + created_issue = createIssue(title, project_id, milestone, epic, iteration, selectedSettings) + print(f"Issue #{created_issue['iid']}: {created_issue['title']} created.") + + if onlyIssue: + return created_issue + + created_branch = create_branch(project_id, created_issue, main_branch) + created_merge_request = create_merge_request( + project_id, + created_branch, + created_issue, + selectedSettings.get("labels"), + milestone, + main_branch, + ) + print(f"Merge request #{created_merge_request['iid']}: {created_merge_request['title']} created.") + + print("Run:") + print(" git fetch origin") + print( + f" git checkout -b '{created_merge_request['source_branch']}' " + f"'origin/{created_merge_request['source_branch']}'" + ) + print("to switch to new branch.") + + return created_issue + + +def process_report(text, minutes): + from config import CONFIG + + try: + incident_project_id = CONFIG.get("DEFAULT", "incident_project_id") + except Exception: + print("Error: incident_project_id not found in config.ini") + print("Please add your incident project ID to configs/config.ini under [DEFAULT] section:") + print("incident_project_id = your_project_id_here") + return + + issue_title = f"Incident Report: {text}" + selected_label = selectLabels("Department") + incident_settings = { + "labels": ["incident", "report"], + "onlyIssue": True, + "type": "incident", + } + + if selected_label: + incident_settings["labels"].append(selected_label) + + try: + iteration = getActiveIteration() + created_issue = createIssue( + issue_title, + incident_project_id, + False, + False, + iteration, + incident_settings, + ) + issue_iid = created_issue["iid"] + + closeOpenedIssue(issue_iid, incident_project_id) + print(f"Incident issue #{issue_iid} created successfully.") + print(f"Title: {issue_title}") + + import subprocess + + time_tracking_command = [ + "glab", + "api", + f"/projects/{incident_project_id}/issues/{issue_iid}/add_spent_time", + "-f", + f"duration={minutes}m", + ] + + try: + subprocess.run(time_tracking_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + print(f"Added {minutes} minutes to issue time tracking.") + except subprocess.CalledProcessError as error: + print(f"Error adding time tracking: {str(error)}") + + except Exception as error: + print(f"Error creating incident issue: {str(error)}") diff --git a/commands/deploy.py b/commands/deploy.py new file mode 100644 index 0000000..d26c76a --- /dev/null +++ b/commands/deploy.py @@ -0,0 +1,98 @@ +import datetime + +from config import PRODUCTION_MAPPINGS +from git_utils import getMainBranch +from gitlab_api import get_pipeline_jobs, get_recent_pipelines + +from .create_issue import get_project_id + + +def find_production_deployment(pipelines, jobs_loader, project_id, production_mappings): + for pipeline in pipelines: + jobs = jobs_loader(project_id, pipeline["id"]) + if jobs is None: + continue + + for job in jobs: + job_name = job.get("name", "") + stage = job.get("stage", "") + job_status = job.get("status", "").lower() + if job_status != "success": + continue + + project_mapping = production_mappings.get(str(project_id)) + if project_mapping: + expected_stage = project_mapping.get("stage", "").lower() + expected_job = project_mapping.get("job", "").lower() + + if stage.lower() == expected_stage or ( + expected_job and job_name.lower() == expected_job + ): + return { + "pipeline": pipeline, + "production_job": job, + } + else: + print("Didn't find deployment pipeline") + return None + + +def get_last_production_deploy(): + try: + project_id = get_project_id() + try: + ref = getMainBranch() + except Exception: + ref = "main" + + pipelines = get_recent_pipelines(project_id, ref=ref) + if pipelines is None: + return + + production_pipeline = find_production_deployment( + pipelines, + get_pipeline_jobs, + project_id, + PRODUCTION_MAPPINGS, + ) + + if not production_pipeline: + print("No production deployment found matching pattern") + return + + pipeline = production_pipeline["pipeline"] + job = production_pipeline["production_job"] + + print("Last Production Deployment:") + print(f" Pipeline: #{pipeline['id']} - {pipeline['status']}") + print(f" Job: {job['name']} ({job['status']})") + print(f" Branch/Tag: {pipeline['ref']}") + print(f" Started: {job.get('started_at', 'N/A')}") + print(f" Finished: {job.get('finished_at', 'N/A')}") + if job.get("duration"): + print(f" Duration: {job.get('duration', 'N/A')} seconds") + else: + print(" Duration: N/A") + print(f" Commit: {pipeline['sha'][:8]}") + print(f" URL: {pipeline['web_url']}") + + if job.get("finished_at"): + try: + finished_time = datetime.datetime.fromisoformat( + job["finished_at"].replace("Z", "+00:00") + ) + time_diff = datetime.datetime.now(datetime.timezone.utc) - finished_time + + if time_diff.days > 0: + print(f" {time_diff.days} days ago") + elif time_diff.seconds > 3600: + hours = time_diff.seconds // 3600 + print(f" {hours} hours ago") + else: + minutes = time_diff.seconds // 60 + print(f" {minutes} minutes ago") + except Exception: + pass + + except Exception as error: + print(f"Error fetching last production deploy: {str(error)}") diff --git a/commands/open_mr.py b/commands/open_mr.py new file mode 100644 index 0000000..23c5663 --- /dev/null +++ b/commands/open_mr.py @@ -0,0 +1,31 @@ +import webbrowser + +from config import BASE_URL +from git_utils import getCurrentBranch +from gitlab_api import getMergeRequestForBranch + +from .create_issue import get_project_id + + +def openMergeRequestInBrowser(): + try: + merge_request_id = getActiveMergeRequestId() + import subprocess + + remote_url = subprocess.check_output( + ["git", "config", "--get", "remote.origin.url"], text=True + ).strip() + url = BASE_URL + "/" + remote_url.split(":")[1][:-4] + webbrowser.open(f"{url}/-/merge_requests/{merge_request_id}") + except Exception: + return None + + +def getActiveMergeRequestId(): + branch_to_find = getCurrentBranch() + return find_merge_request_id_by_branch(branch_to_find) + + +def find_merge_request_id_by_branch(branch_name): + merge_request = getMergeRequestForBranch(get_project_id(), branch_name) + return merge_request["iid"] diff --git a/commands/review.py b/commands/review.py new file mode 100644 index 0000000..f50ef8d --- /dev/null +++ b/commands/review.py @@ -0,0 +1,69 @@ +import subprocess + +from config import API_URL, GITLAB_TOKEN, REVIEWERS +from git_utils import getCurrentBranch +from gitlab_api import addReviewersToMergeRequest, getMergeRequestForBranch, setMergeRequestToAutoMerge +from interactive import chooseReviewersManually + +from .create_issue import get_project_id +from .open_mr import getActiveMergeRequestId + + +def getCurrentIssueId(): + merge_request = getMergeRequestForBranch(get_project_id(), getCurrentBranch()) + return merge_request["description"].replace('"', "").replace("#", "").split()[1] + + +def track_issue_time(): + try: + project_id = get_project_id() + issue_id = getCurrentIssueId() + except Exception as error: + print(f"Error getting issue details: {str(error)}") + return + + import inquirer + + spent_time = inquirer.prompt( + [ + inquirer.Text( + "spent_time", + message="How many minutes did you actually spend on this issue?", + validate=lambda _, value: value.isdigit(), + ) + ] + )["spent_time"] + + time_tracking_command = [ + "glab", + "api", + f"/projects/{project_id}/issues/{issue_id}/notes", + "-f", + f"body=/spend {spent_time}m", + ] + + try: + subprocess.run(time_tracking_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) + print(f"Added {spent_time} minutes to issue {issue_id} time tracking.") + except subprocess.CalledProcessError as error: + print(f"Error adding time tracking: {str(error)}") + except Exception as error: + print(f"Error tracking issue time: {str(error)}") + + +def review_current_merge_request(auto_merge=False, select=False): + track_issue_time() + reviewers = chooseReviewersManually() if select else REVIEWERS + project_id = get_project_id() + mr_id = getActiveMergeRequestId() + addReviewersToMergeRequest(project_id, mr_id, reviewers) + + try: + from ai_code_review import run_review_for_mr + + run_review_for_mr(project_id, mr_id, GITLAB_TOKEN, API_URL) + except Exception as error: + print(f"AI review skipped: {error}") + + if auto_merge: + setMergeRequestToAutoMerge(project_id, mr_id) diff --git a/commands/summary.py b/commands/summary.py new file mode 100644 index 0000000..6714520 --- /dev/null +++ b/commands/summary.py @@ -0,0 +1,41 @@ +from config import CONFIG +from git_utils import get_two_weeks_commits + + +def generate_smart_summary(): + commits = get_two_weeks_commits(return_output=True) + if not commits: + return + + openai_api_key = CONFIG.get("DEFAULT", "OPENAI_API_KEY", fallback=None) + if not openai_api_key: + print("OpenAI API key not set. Skipping AI summary generation.") + return + + try: + import openai + except ImportError: + print("OpenAI package not installed. Please install it using: pip install openai") + return + + openai.api_key = openai_api_key + + try: + response = openai.chat.completions.create( + model="gpt-3.5-turbo", + messages=[ + { + "role": "system", + "content": "You are a helpful assistant that summarizes git commits. Provide a concise, well-organized summary of the main changes and themes.", + }, + { + "role": "user", + "content": f"Please summarize these git commits in a clear, bulleted format:\n\n{commits}", + }, + ], + ) + + print("\nAI-Generated Summary of Recent Changes:\n") + print(response.choices[0].message.content) + except Exception as error: + print(f"Error generating AI summary: {error}") diff --git a/config.py b/config.py new file mode 100644 index 0000000..daf469a --- /dev/null +++ b/config.py @@ -0,0 +1,56 @@ +import configparser +import json +from pathlib import Path + +ROOT_DIR = Path(__file__).resolve().parent +CONFIG_DIR = ROOT_DIR / "configs" +CONFIG_PATH = CONFIG_DIR / "config.ini" +TEMPLATES_PATH = CONFIG_DIR / "templates.json" + + +def load_config(path=CONFIG_PATH): + parser = configparser.ConfigParser() + parser.read(path) + return parser + + +CONFIG = load_config() + + +def config_value(option, fallback="", strip_quotes=False): + value = CONFIG.get("DEFAULT", option, fallback=fallback) + if strip_quotes and isinstance(value, str): + return value.strip("\"'") + return value + + +def config_bool(option, fallback=False): + value = CONFIG.get("DEFAULT", option, fallback=str(fallback)) + return str(value).lower() == "true" + + +BASE_URL = config_value("base_url", "https://gitlab.com") +API_URL = f"{BASE_URL}/api/v4" +GROUP_ID = config_value("group_id") +CUSTOM_TEMPLATE = config_value("custom_template", "Custom") +GITLAB_TOKEN = config_value("GITLAB_TOKEN", strip_quotes=True) +DELETE_BRANCH = config_bool("delete_branch_after_merge") +DEVELOPER_EMAIL = config_value("developer_email", None) +SQUASH_COMMITS = config_bool("squash_commits") +PRODUCTION_PIPELINE_NAME = config_value("production_pipeline_name", "deploy") +PRODUCTION_JOB_NAME = config_value("production_job_name", None) +PRODUCTION_REF = config_value("production_ref", None) +DEFAULT_MAIN_BRANCH = "master" + + +def load_template_config(path=TEMPLATES_PATH): + if not Path(path).exists(): + return {"templates": [], "reviewers": [], "productionMappings": {}} + with open(path, "r", encoding="utf-8") as template_file: + return json.load(template_file) + + +TEMPLATE_CONFIG = load_template_config() +TEMPLATES = TEMPLATE_CONFIG.get("templates", []) +REVIEWERS = TEMPLATE_CONFIG.get("reviewers", []) +PRODUCTION_MAPPINGS = TEMPLATE_CONFIG.get("productionMappings", {}) diff --git a/gitHappens.py b/gitHappens.py index 27d47f3..9c3da30 100755 --- a/gitHappens.py +++ b/gitHappens.py @@ -1,761 +1,50 @@ #!/usr/bin/env python3 -import subprocess -import json import argparse -import configparser -import inquirer -import datetime -import re -import os -import requests import sys -import webbrowser - -# Setup config parser and read settings -config = configparser.ConfigParser() -absolute_config_path = os.path.dirname(os.path.abspath(__file__)) -config_path = os.path.join(absolute_config_path, 'configs/config.ini') -config.read(config_path) - -BASE_URL = config.get('DEFAULT', 'base_url') -API_URL = BASE_URL + '/api/v4' -GROUP_ID = config.get('DEFAULT', 'group_id') -CUSTOM_TEMPLATE = config.get('DEFAULT', 'custom_template') -GITLAB_TOKEN = config.get('DEFAULT', 'GITLAB_TOKEN').strip('\"\'') -DELETE_BRANCH = config.get('DEFAULT', 'delete_branch_after_merge').lower() == 'true' -DEVELOPER_EMAIL = config.get('DEFAULT', 'developer_email', fallback=None) -SQUASH_COMMITS = config.get('DEFAULT', 'squash_commits').lower() == 'true' -PRODUCTION_PIPELINE_NAME = config.get('DEFAULT', 'production_pipeline_name', fallback='deploy') -PRODUCTION_JOB_NAME = config.get('DEFAULT', 'production_job_name', fallback=None) -PRODUCTION_REF = config.get('DEFAULT', 'production_ref', fallback=None) -MAIN_BRANCH = 'master' - -# Read templates from json config -with open(os.path.join(absolute_config_path,'configs/templates.json'), 'r') as f: - jsonConfig = json.load(f) -TEMPLATES = jsonConfig['templates'] -REVIEWERS = jsonConfig['reviewers'] -PRODUCTION_MAPPINGS = jsonConfig.get('productionMappings', {}) - -def get_project_id(): - project_link = getProjectLinkFromCurrentDir() - if (project_link == -1): - return enterProjectId() - - allProjects = get_all_projects(project_link) - # Find projects id by project ssh link gathered from repo - matching_id = None - for project in allProjects: - if project.get("ssh_url_to_repo") == project_link: - matching_id = project.get("id") - break - return matching_id - -def get_all_projects(project_link): - url = API_URL + "/projects?membership=true&search=" + project_link.split('/')[-1].split('.')[0] - - headers = { - "PRIVATE-TOKEN": GITLAB_TOKEN - } - - response = requests.get(url, headers=headers) - - if response.status_code == 200: - return response.json() - elif response.status_code == 401: - print("Error: Unauthorized (401). Your GitLab token is probably expired, invalid, or missing required permissions.") - print("Please generate a new token and update your configs/config.ini.") - exit(1) - else: - print(f"Request failed with status code {response.status_code}") - return None - -def getProjectLinkFromCurrentDir(): - try: - cmd = 'git remote get-url origin' - result = subprocess.run(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) - if result.returncode == 0: - output = result.stdout.decode('utf-8').strip() - return output - else: - return -1 - except FileNotFoundError: - return -1 - -def enterProjectId(): - while True: - project_id = input('Please enter the ID of your GitLab project: ') - if project_id: - return project_id - exit('Invalid project ID.') - -def list_milestones(current=False): - cmd = f'glab api /groups/{GROUP_ID}/milestones?state=active' - result = subprocess.run(cmd.split(), stdout=subprocess.PIPE) - milestones = json.loads(result.stdout) - if current: - today = datetime.date.today().strftime('%Y-%m-%d') - active_milestones = [] - for milestone in milestones: - start_date = milestone['start_date'] - due_date = milestone['due_date'] - if start_date and due_date and start_date <= today and due_date >= today: - active_milestones.append(milestone) - active_milestones.sort(key=lambda x: x['due_date']) - return active_milestones[0] - return milestones - -def select_template(): - template_names = [t['name'] for t in TEMPLATES] - template_names.append(CUSTOM_TEMPLATE) - questions = [ - inquirer.List('template', - message="Select template:", - choices=template_names, - ), - ] - answer = inquirer.prompt(questions) - return answer['template'] - -def getIssueSettings(template_name): - if template_name == CUSTOM_TEMPLATE: - return {} - return next((t for t in TEMPLATES if t['name'] == template_name), None) - -def createIssue(title, project_id, milestoneId, epic, iteration, settings): - if settings: - issueType = settings.get('type') or 'issue' - return executeIssueCreate(project_id, title, settings.get('labels'), milestoneId, epic, iteration, settings.get('weight'), settings.get('estimated_time'), issueType) - print("No settings in template") - exit(2) - pass - -def executeIssueCreate(project_id, title, labels, milestoneId, epic, iteration, weight, estimated_time, issue_type='issue'): - labels = ",".join(labels) if type(labels) == list else labels - assignee_id = getAuthorizedUser()['id'] - issue_command = [ - "glab", "api", - f"/projects/{str(project_id)}/issues", - "-f", f'title={title}', - "-f", f'assignee_ids={assignee_id}', - "-f", f'issue_type={issue_type}' - ] - if labels: - issue_command.append("-f") - issue_command.append(f'labels={labels}') - - if weight: - issue_command.append("-f") - issue_command.append(f'weight={str(weight)}') - - if milestoneId: - issue_command.append("-f") - issue_command.append(f'milestone_id={str(milestoneId)}') - - if epic: - epicId = epic['id'] - issue_command.append("-f") - issue_command.append(f'epic_id={str(epicId)}') - - # Set the description, including iteration, estimated time, and other info - description = "" - if iteration: - iterationId = iteration['id'] - description += f"/iteration *iteration:{str(iterationId)} " - - if estimated_time: - description += f"\n/estimate {estimated_time}m " - - issue_command.extend(["-f", f'description={description}']) - - issue_output = subprocess.check_output(issue_command) - return json.loads(issue_output.decode()) - -def select_milestone(milestones): - milestones = [t['title'] for t in milestones] - questions = [ - inquirer.List('milestones', - message="Select milestone:", - choices=milestones, - ), - ] - answer = inquirer.prompt(questions) - return answer['milestones'] - -def getSelectedMilestone(milestone, milestones): - return next((t for t in milestones if t['title'] == milestone), None) - -def get_milestone(manual): - if manual: - milestones = list_milestones() - return getSelectedMilestone(select_milestone(milestones), milestones) - milestone = list_milestones(True) # select active for today - return milestone - -def get_iteration(manual): - if manual: - iterations = list_iterations() - return getSelectedIteration(select_iteration(iterations), iterations) - return getActiveIteration() - -def getSelectedIteration(iteration, iterations): - return next((t for t in iterations if t['start_date'] + ' - ' + t['due_date'] == iteration), None) - -def select_iteration(iterations): - iterations = [t['start_date'] + ' - ' + t['due_date'] for t in iterations] - questions = [ - inquirer.List('iterations', - message="Select iteration:", - choices=iterations, - ), - ] - answer = inquirer.prompt(questions) - return answer['iterations'] - -def list_iterations(): - cmd = f'glab api /groups/{GROUP_ID}/iterations?state=opened' - result = subprocess.run(cmd.split(), stdout=subprocess.PIPE) - iterations = json.loads(result.stdout) - return iterations - -def getActiveIteration(): - iterations = list_iterations() - today = datetime.date.today().strftime('%Y-%m-%d') - active_iterations = [] - for iteration in iterations: - start_date = iteration['start_date'] - due_date = iteration['due_date'] - if start_date and due_date and start_date <= today and due_date >= today: - active_iterations.append(iteration) - active_iterations.sort(key=lambda x: x['due_date']) - return active_iterations[0] - -def getAuthorizedUser(): - output = subprocess.check_output(["glab", "api", "/user"]) - return json.loads(output) - -def list_epics(): - cmd = f'glab api /groups/{GROUP_ID}/epics?per_page=1000&state=opened' - result = subprocess.run(cmd.split(), stdout=subprocess.PIPE) - return json.loads(result.stdout) - -def select_epic(epics): - epics = [t['title'] for t in epics] - search_query = inquirer.prompt([ - inquirer.Text('search_query', message='Search epic:'), - ])['search_query'] - - # Filter choices based on search query - filtered_epics = [c for c in epics if search_query.lower() in c.lower()] - questions = [ - inquirer.List('epics', - message="Select epic:", - choices=filtered_epics, - ), - ] - answer = inquirer.prompt(questions) - return answer['epics'] - -def getSelectedEpic(epic, epics): - return next((t for t in epics if t['title'] == epic), None) - -def get_epic(): - epics = list_epics() - return getSelectedEpic(select_epic(epics), epics) - -def create_branch(project_id, issue): - issueId = str(issue['iid']) - title = re.sub('\\s+', '-', issue['title']).lower() - title = issueId + '-' + title.replace(':','').replace('(',' ').replace(')', '').replace(' ','-') - branch_output = subprocess.check_output(["glab", "api", f"/projects/{str(project_id)}/repository/branches", "-f", f'branch={title}', "-f", f'ref={MAIN_BRANCH}', "-f", f'issue_iid={issueId}']) - return json.loads(branch_output.decode()) - -def create_merge_request(project_id, branch, issue, labels, milestoneId): - issueId = str(issue['iid']) - branch = branch['name'] - title = issue['title'] - assignee_id = getAuthorizedUser()['id'] - labels = ",".join(labels) if type(labels) == list else labels - merge_request_command = [ - "glab", "api", - f"/projects/{str(project_id)}/merge_requests", - "-f", f'title={title}', - "-f", f'description="Closes #{issueId}"', - "-f", f'source_branch={branch}', - "-f", f'target_branch={MAIN_BRANCH}', - "-f", f'issue_iid={issueId}', - "-f", f'assignee_ids={assignee_id}' - ] - - if SQUASH_COMMITS: - merge_request_command.append("-f") - merge_request_command.append("squash=true") - - if DELETE_BRANCH: - merge_request_command.append("-f") - merge_request_command.append("remove_source_branch=true") - - if labels: - merge_request_command.append("-f") - merge_request_command.append(f'labels={labels}') - - if milestoneId: - merge_request_command.append("-f") - merge_request_command.append(f'milestone_id={str(milestoneId)}') - - mr_output = subprocess.check_output(merge_request_command) - return json.loads(mr_output.decode()) - -def startIssueCreation(project_id, title, milestone, epic, iteration, selectedSettings, onlyIssue): - # Prompt for estimated time - estimated_time = inquirer.prompt([ - inquirer.Text('estimated_time', - message='Estimated time to complete this issue (in minutes, optional)', - validate=lambda _, x: x == '' or x.isdigit()) - ])['estimated_time'] - - # If multiple project IDs, split the estimated time - if isinstance(project_id, list): - estimated_time_per_project = int(estimated_time) / len(project_id) if estimated_time else None - else: - estimated_time_per_project = estimated_time - - # Modify settings to include estimated time - if estimated_time_per_project: - selectedSettings = selectedSettings.copy() if selectedSettings else {} - selectedSettings['estimated_time'] = int(estimated_time_per_project) - - createdIssue = createIssue(title, project_id, milestone, epic, iteration, selectedSettings) - print(f"Issue #{createdIssue['iid']}: {createdIssue['title']} created.") - - if onlyIssue: - return createdIssue - - createdBranch = create_branch(project_id, createdIssue) - - createdMergeRequest = create_merge_request(project_id, createdBranch, createdIssue, selectedSettings.get('labels'), milestone) - print(f"Merge request #{createdMergeRequest['iid']}: {createdMergeRequest['title']} created.") - - print("Run:") - print(" git fetch origin") - print(f" git checkout -b '{createdMergeRequest['source_branch']}' 'origin/{createdMergeRequest['source_branch']}'") - print("to switch to new branch.") - - return createdIssue - -def getCurrentBranch(): - return subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], text=True).strip() - -def openMergeRequestInBrowser(): - try: - merge_request_id = getActiveMergeRequestId() - remote_url = subprocess.check_output(["git", "config", "--get", "remote.origin.url"], text=True).strip() - url = BASE_URL + '/' + remote_url.split(':')[1][:-4] - webbrowser.open(f"{url}/-/merge_requests/{merge_request_id}") - except subprocess.CalledProcessError: - return None - -def getActiveMergeRequestId(): - branch_to_find = getCurrentBranch() - return find_merge_request_id_by_branch(branch_to_find) - -def find_merge_request_id_by_branch(branch_name): - return getMergeRequestForBranch(branch_name)['iid'] - -def getMergeRequestForBranch(branchName): - project_id = get_project_id() - api_url = f"{API_URL}/projects/{project_id}/merge_requests" - headers = {"Private-Token": GITLAB_TOKEN} - - params = { - "source_branch": branchName, - } - - response = requests.get(api_url, headers=headers, params=params) - if response.status_code == 200: - merge_requests = response.json() - for mr in merge_requests: - if mr["source_branch"] == branchName: - return mr - else: - print(f"Failed to fetch Merge Requests: {response.status_code} - {response.text}") - return None - -def chooseReviewersManually(): - """Prompt the user to select reviewers manually from the available list, showing names.""" - # Fetch user details for each reviewer ID - reviewer_choices = [] - for reviewer_id in REVIEWERS: - api_url = f"{API_URL}/users/{reviewer_id}" - headers = {"Private-Token": GITLAB_TOKEN} - try: - response = requests.get(api_url, headers=headers) - if response.status_code == 200: - user = response.json() - display_name = f"{user.get('name')} ({user.get('username')})" - reviewer_choices.append((display_name, reviewer_id)) - else: - reviewer_choices.append((str(reviewer_id), reviewer_id)) - except Exception: - reviewer_choices.append((str(reviewer_id), reviewer_id)) - - questions = [ - inquirer.Checkbox( - "selected_reviewers", - message="Select reviewers", - choices=[(name, str(rid)) for name, rid in reviewer_choices], - ) - ] - answers = inquirer.prompt(questions) - if answers and "selected_reviewers" in answers: - return [int(r) for r in answers["selected_reviewers"]] - else: - return [] - -def addReviewersToMergeRequest(reviewers=None): - project_id = get_project_id() - mr_id = getActiveMergeRequestId() - api_url = f"{API_URL}/projects/{project_id}/merge_requests/{mr_id}" - headers = {"Private-Token": GITLAB_TOKEN} - - data = { - "reviewer_ids": reviewers if reviewers is not None else REVIEWERS - } - - requests.put(api_url, headers=headers, json=data) - -def setMergeRequestToAutoMerge(): - project_id = get_project_id() - mr_id = getActiveMergeRequestId() - api_url = f"{API_URL}/projects/{project_id}/merge_requests/{mr_id}/merge" - headers = {"Private-Token": GITLAB_TOKEN} - - data = { - "id": project_id, - "merge_request_iid": mr_id, - "should_remove_source_branch": True, - "merge_when_pipeline_succeeds": True, - "auto_merge_strategy": "merge_when_pipeline_succeeds", - } - - requests.put(api_url, headers=headers, json=data) - -def getMainBranch(): - command = "git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@'" - output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT, universal_newlines=True) - return output.strip() - - -def get_two_weeks_commits(return_output=False): - two_weeks_ago = (datetime.datetime.now() - datetime.timedelta(weeks=2)).strftime('%Y-%m-%d') - - cmd = f'git log --since={two_weeks_ago} --format="%ad - %ae - %s" --date=short | grep -v "Merge branch"' - if (DEVELOPER_EMAIL): - cmd = f'{cmd} | grep {DEVELOPER_EMAIL}' - try: - output = subprocess.check_output(cmd, shell=True, text=True, stderr=subprocess.DEVNULL, universal_newlines=True).strip() - if output: - if return_output: - return output - print(output) - else: - print("No commits found.") - return "" if return_output else None - except subprocess.CalledProcessError as e: - print(f"No commits were found or an error occurred. (exit status {e.returncode})") - return "" if return_output else None - except FileNotFoundError: - print("Git is not installed or not found in PATH.") - return "" if return_output else None - -def generate_smart_summary(): - commits = get_two_weeks_commits(return_output=True) - if not commits: - return - - # Check if OpenAI API key is set - openai_api_key = config.get('DEFAULT', 'OPENAI_API_KEY', fallback=None) - if not openai_api_key: - print("OpenAI API key not set. Skipping AI summary generation.") - return - - # Dynamically import openai only if API key is present - try: - import openai - except ImportError: - print("OpenAI package not installed. Please install it using: pip install openai") - return - - openai.api_key = openai_api_key - - try: - response = openai.chat.completions.create( - model="gpt-3.5-turbo", - messages=[ - {"role": "system", "content": "You are a helpful assistant that summarizes git commits. Provide a concise, well-organized summary of the main changes and themes."}, - {"role": "user", "content": f"Please summarize these git commits in a clear, bulleted format:\n\n{commits}"} - ] - ) - - print("\nšŸ“‹ AI-Generated Summary of Recent Changes:\n") - print(response.choices[0].message.content) - except Exception as e: - print(f"Error generating AI summary: {e}") - -def process_report(text, minutes): - # Get the incident project ID from config - try: - incident_project_id = config.get('DEFAULT', 'incident_project_id') - except (configparser.NoOptionError, configparser.NoSectionError): - print("Error: incident_project_id not found in config.ini") - print("Please add your incident project ID to configs/config.ini under [DEFAULT] section:") - print("incident_project_id = your_project_id_here") - return - - issue_title = f"Incident Report: {text}" - - selected_label = selectLabels('Department') - - incident_settings = { - 'labels': ['incident', 'report'], - 'onlyIssue': True, - 'type': 'incident' - } - - if selected_label: - incident_settings['labels'].append(selected_label) - - try: - # Create the incident issue - iteration = getActiveIteration() - created_issue = createIssue(issue_title, incident_project_id, False, False, iteration, incident_settings) - issue_iid = created_issue['iid'] - - closeOpenedIssue(issue_iid, incident_project_id) - print(f"Incident issue #{issue_iid} created successfully.") - print(f"Title: {issue_title}") - - # Add time tracking to the issue - time_tracking_command = [ - "glab", "api", - f"/projects/{incident_project_id}/issues/{issue_iid}/add_spent_time", - "-f", f"duration={minutes}m" - ] - - try: - subprocess.run(time_tracking_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - print(f"Added {minutes} minutes to issue time tracking.") - except subprocess.CalledProcessError as e: - print(f"Error adding time tracking: {str(e)}") - - except Exception as e: - print(f"Error creating incident issue: {str(e)}") - -def closeOpenedIssue(issue_iid, project_id): - issue_command = [ - "glab", "api", - f"/projects/{project_id}/issues/{issue_iid}", - '-X', 'PUT', - '-f', 'state_event=close' - ] - try: - subprocess.run(issue_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - except subprocess.CalledProcessError as e: - print(f"Error closing issue: {str(e)}") - -def selectLabels(search, multiple = False): - labels = getLabelsOfGroup(search) - labels = sorted([t['name'] for t in labels]) - - question_type = inquirer.Checkbox if multiple else inquirer.List - questions = [ - question_type( - 'labels', - message="Select one or more department labels:", - choices=labels, - ), - ] - answer = inquirer.prompt(questions) - return answer['labels'] - -def getLabelsOfGroup(search=''): - cmd = f'glab api /groups/{GROUP_ID}/labels?search={search}' - try: - result = subprocess.run(cmd.split(), stdout=subprocess.PIPE, check=True) - return json.loads(result.stdout) - except subprocess.CalledProcessError as e: - print(f"Error getting labels: {str(e)}") - return [] - -def getCurrentIssueId(): - mr = getMergeRequestForBranch(getCurrentBranch()) - return mr['description'].replace('"','').replace('#','').split()[1] - -def track_issue_time(): - # Get the current merge request - try: - project_id = get_project_id() - issue_id = getCurrentIssueId() - except Exception as e: - print(f"Error getting issue details: {str(e)}") - return - - # Prompt for actual time spent - spent_time = inquirer.prompt([ - inquirer.Text('spent_time', - message='How many minutes did you actually spend on this issue?', - validate=lambda _, x: x.isdigit()) - ])['spent_time'] - - # Add spent time to the issue description - time_tracking_command = [ - "glab", "api", - f"/projects/{project_id}/issues/{issue_id}/notes", - "-f", f"body=/spend {spent_time}m" - ] - - try: - subprocess.run(time_tracking_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) - print(f"Added {spent_time} minutes to issue {issue_id} time tracking.") - except subprocess.CalledProcessError as e: - print(f"Error adding time tracking: {str(e)}") - except Exception as e: - print(f"Error tracking issue time: {str(e)}") - -def get_last_production_deploy(): - try: - project_id = get_project_id() - api_url = f"{API_URL}/projects/{project_id}/pipelines" - headers = {"Private-Token": GITLAB_TOKEN} - - # Set up parameters for the pipeline search - params = { - "per_page": 50, - "order_by": "updated_at", - "sort": "desc" - } - - # Add ref filter if specified in config - if MAIN_BRANCH: - params["ref"] = MAIN_BRANCH - else: - # Use main branch if no specific ref is configured - try: - main_branch = getMainBranch() - params["ref"] = main_branch - except: - # Fallback to common main branch names - params["ref"] = "main" - - response = requests.get(api_url, headers=headers, params=params) - - if response.status_code != 200: - print(f"Failed to fetch pipelines: {response.status_code} - {response.text}") - return - - pipelines = response.json() - production_pipeline = None - - # Look for production pipeline by name pattern - for pipeline in pipelines: - # Get pipeline details to check jobs - pipeline_detail_url = f"{API_URL}/projects/{project_id}/pipelines/{pipeline['id']}/jobs" - detail_response = requests.get(pipeline_detail_url, headers=headers) - - if detail_response.status_code == 200: - jobs = detail_response.json() - - # Check if this pipeline contains production deployment - for job in jobs: - job_name = job.get('name', '') - stage = job.get('stage', '') - job_status = job.get('status', '').lower() - - # Only consider successful jobs - if job_status != 'success': - continue - - # Check project-specific mapping first - project_mapping = PRODUCTION_MAPPINGS.get(str(project_id)) - if project_mapping: - expected_stage = project_mapping.get('stage', '').lower() - expected_job = project_mapping.get('job', '').lower() - - if (stage.lower() == expected_stage or - (expected_job and job_name.lower() == expected_job)): - production_pipeline = { - 'pipeline': pipeline, - 'production_job': job - } - break - else: - print('Didn\'t find deployment pipeline') - - if production_pipeline: - break - - if not production_pipeline: - print(f"No production deployment found matching pattern") - return - - # Display the results - pipeline = production_pipeline['pipeline'] - job = production_pipeline['production_job'] - - print(f"šŸš€ Last Production Deployment:") - print(f" Pipeline: #{pipeline['id']} - {pipeline['status']}") - print(f" Job: {job['name']} ({job['status']})") - print(f" Branch/Tag: {pipeline['ref']}") - print(f" Started: {job.get('started_at', 'N/A')}") - print(f" Finished: {job.get('finished_at', 'N/A')}") - print(f" Duration: {job.get('duration', 'N/A')} seconds" if job.get('duration') else " Duration: N/A") - print(f" Commit: {pipeline['sha'][:8]}") - print(f" URL: {pipeline['web_url']}") - - # Show time since deployment - if job.get('finished_at'): - try: - finished_time = datetime.datetime.fromisoformat(job['finished_at'].replace('Z', '+00:00')) - time_diff = datetime.datetime.now(datetime.timezone.utc) - finished_time - - if time_diff.days > 0: - print(f" ā° {time_diff.days} days ago") - elif time_diff.seconds > 3600: - hours = time_diff.seconds // 3600 - print(f" ā° {hours} hours ago") - else: - minutes = time_diff.seconds // 60 - print(f" ā° {minutes} minutes ago") - except: - pass - - except Exception as e: - print(f"Error fetching last production deploy: {str(e)}") - -def main(): - global MAIN_BRANCH +from commands.create_issue import ( + get_epic, + get_iteration, + get_milestone, + get_project_id, + process_report, + startIssueCreation, +) +from commands.deploy import get_last_production_deploy +from commands.open_mr import openMergeRequestInBrowser +from commands.review import review_current_merge_request +from commands.summary import generate_smart_summary +from git_utils import getMainBranch, get_two_weeks_commits +from templates import getIssueSettings, select_template + + +def build_parser(): parser = argparse.ArgumentParser("Argument description of Git happens") parser.add_argument("title", nargs="+", help="Title of issue") - parser.add_argument(f"--project_id", type=str, help="Id or URL-encoded path of project") - parser.add_argument("-m", "--milestone", action='store_true', help="Add this flag, if you want to manually select milestone") + parser.add_argument("--project_id", type=str, help="Id or URL-encoded path of project") + parser.add_argument("-m", "--milestone", action="store_true", help="Add this flag, if you want to manually select milestone") parser.add_argument("--no_epic", action="store_true", help="Add this flag if you don't want to pick epic") parser.add_argument("--no_milestone", action="store_true", help="Add this flag if you don't want to pick milestone") parser.add_argument("--no_iteration", action="store_true", help="Add this flag if you don't want to pick iteration") parser.add_argument("--only_issue", action="store_true", help="Add this flag if you don't want to create merge request and branch alongside issue") parser.add_argument("-am", "--auto_merge", action="store_true", help="Add this flag to review if you want to set merge request to auto merge when pipeline succeeds") parser.add_argument("--select", action="store_true", help="Manually select reviewers for merge request (interactive)") + return parser + - # If no arguments passed, show help - if len(sys.argv) <= 1: +def main(argv=None): + argv = argv if argv is not None else sys.argv[1:] + parser = build_parser() + + if not argv: parser.print_help() exit(1) - args = parser.parse_args() - if args.title[0] == 'report': + args = parser.parse_args(argv) + if args.title[0] == "report": parts = args.title if len(parts) != 3: - print("Invalid report format. Use: gh report \"text\" minutes") + print('Invalid report format. Use: gh report "text" minutes') return text = parts[1] @@ -766,80 +55,78 @@ def main(): print("Invalid minutes. Please provide a valid number.") return - # So it takes all text until first known argument title = " ".join(args.title) - if title == 'open': + if title == "open": openMergeRequestInBrowser() return - elif title == 'review': - track_issue_time() - reviewers = None - if getattr(args, "select", False): - reviewers = chooseReviewersManually() - addReviewersToMergeRequest(reviewers=reviewers) - - # Run AI code review and post to MR - try: - from ai_code_review import run_review_for_mr - project_id = get_project_id() - mr_id = getActiveMergeRequestId() - run_review_for_mr(project_id, mr_id, GITLAB_TOKEN, API_URL) - except Exception as e: - print(f"AI review skipped: {e}") - - if(args.auto_merge): - setMergeRequestToAutoMerge() + if title == "review": + review_current_merge_request(auto_merge=args.auto_merge, select=args.select) return - elif title == 'summary': + if title == "summary": get_two_weeks_commits() return - elif title == 'summaryAI': + if title == "summaryAI": generate_smart_summary() return - elif title == 'last deploy': + if title == "last deploy": get_last_production_deploy() return - elif title == 'ai review': + if title == "ai review": from ai_code_review import run_review + run_review() return - # Get settings for issue from template - selectedSettings = getIssueSettings(select_template()) + selectedSettings = getIssueSettings(select_template()) or {} - # If template is False, ask for each settings if not len(selectedSettings): - print('Custom selection of issue settings is not supported yet') - pass + print("Custom selection of issue settings is not supported yet") - if args.project_id and selectedSettings.get('projectIds'): - print('NOTE: Overwriting project id from argument...') + if args.project_id and selectedSettings.get("projectIds"): + print("NOTE: Overwriting project id from argument...") - project_id = selectedSettings.get('projectIds') or args.project_id or get_project_id() + project_id = selectedSettings.get("projectIds") or args.project_id or get_project_id() milestone = False if not args.no_milestone: - milestone = get_milestone(args.milestone)['id'] + milestone = get_milestone(args.milestone)["id"] iteration = False if not args.no_iteration: - # manual pick iteration iteration = get_iteration(True) epic = False if not args.no_epic: epic = get_epic() - MAIN_BRANCH = getMainBranch() - - onlyIssue = selectedSettings.get('onlyIssue') or args.only_issue + main_branch = getMainBranch() + onlyIssue = selectedSettings.get("onlyIssue") or args.only_issue if type(project_id) == list: - for id in project_id: - startIssueCreation(id, title, milestone, epic, iteration, selectedSettings, onlyIssue) + for item_id in project_id: + startIssueCreation( + item_id, + title, + milestone, + epic, + iteration, + selectedSettings, + onlyIssue, + main_branch, + ) else: - startIssueCreation(project_id, title, milestone, epic, iteration, selectedSettings, onlyIssue) + startIssueCreation( + project_id, + title, + milestone, + epic, + iteration, + selectedSettings, + onlyIssue, + main_branch, + ) + -if __name__ == '__main__': - main() \ No newline at end of file +if __name__ == "__main__": + main() diff --git a/git_utils.py b/git_utils.py new file mode 100644 index 0000000..c51db6e --- /dev/null +++ b/git_utils.py @@ -0,0 +1,69 @@ +import datetime +import subprocess + +from config import DEVELOPER_EMAIL + + +def getProjectLinkFromCurrentDir(): + try: + result = subprocess.run( + ["git", "remote", "get-url", "origin"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + if result.returncode == 0: + return result.stdout.decode("utf-8").strip() + return -1 + except FileNotFoundError: + return -1 + + +def getCurrentBranch(): + return subprocess.check_output( + ["git", "rev-parse", "--abbrev-ref", "HEAD"], text=True + ).strip() + + +def getMainBranch(): + command = "git symbolic-ref refs/remotes/origin/HEAD | sed 's@^refs/remotes/origin/@@'" + output = subprocess.check_output( + command, + shell=True, + stderr=subprocess.STDOUT, + universal_newlines=True, + ) + return output.strip() + + +def get_two_weeks_commits(return_output=False): + two_weeks_ago = ( + datetime.datetime.now() - datetime.timedelta(weeks=2) + ).strftime("%Y-%m-%d") + + cmd = ( + f'git log --since={two_weeks_ago} --format="%ad - %ae - %s" ' + '--date=short | grep -v "Merge branch"' + ) + if DEVELOPER_EMAIL: + cmd = f"{cmd} | grep {DEVELOPER_EMAIL}" + try: + output = subprocess.check_output( + cmd, + shell=True, + text=True, + stderr=subprocess.DEVNULL, + universal_newlines=True, + ).strip() + if output: + if return_output: + return output + print(output) + else: + print("No commits found.") + return "" if return_output else None + except subprocess.CalledProcessError as error: + print(f"No commits were found or an error occurred. (exit status {error.returncode})") + return "" if return_output else None + except FileNotFoundError: + print("Git is not installed or not found in PATH.") + return "" if return_output else None diff --git a/gitlab_api.py b/gitlab_api.py new file mode 100644 index 0000000..e486958 --- /dev/null +++ b/gitlab_api.py @@ -0,0 +1,316 @@ +import datetime +import json +import re +import subprocess + +import requests + +from config import ( + API_URL, + DELETE_BRANCH, + GITLAB_TOKEN, + GROUP_ID, + SQUASH_COMMITS, +) + + +def private_token_headers(): + return {"PRIVATE-TOKEN": GITLAB_TOKEN} + + +def get_all_projects(project_link): + url = API_URL + "/projects?membership=true&search=" + project_link.split("/")[-1].split(".")[0] + response = requests.get(url, headers=private_token_headers()) + + if response.status_code == 200: + return response.json() + if response.status_code == 401: + print("Error: Unauthorized (401). Your GitLab token is probably expired, invalid, or missing required permissions.") + print("Please generate a new token and update your configs/config.ini.") + exit(1) + print(f"Request failed with status code {response.status_code}") + return None + + +def list_milestones(current=False): + result = subprocess.run( + ["glab", "api", f"/groups/{GROUP_ID}/milestones?state=active"], + stdout=subprocess.PIPE, + ) + milestones = json.loads(result.stdout) + if current: + today = datetime.date.today().strftime("%Y-%m-%d") + active_milestones = [] + for milestone in milestones: + start_date = milestone["start_date"] + due_date = milestone["due_date"] + if start_date and due_date and start_date <= today and due_date >= today: + active_milestones.append(milestone) + active_milestones.sort(key=lambda item: item["due_date"]) + return active_milestones[0] + return milestones + + +def list_iterations(): + result = subprocess.run( + ["glab", "api", f"/groups/{GROUP_ID}/iterations?state=opened"], + stdout=subprocess.PIPE, + ) + return json.loads(result.stdout) + + +def getActiveIteration(): + iterations = list_iterations() + today = datetime.date.today().strftime("%Y-%m-%d") + active_iterations = [] + for iteration in iterations: + start_date = iteration["start_date"] + due_date = iteration["due_date"] + if start_date and due_date and start_date <= today and due_date >= today: + active_iterations.append(iteration) + active_iterations.sort(key=lambda item: item["due_date"]) + return active_iterations[0] + + +def getAuthorizedUser(): + output = subprocess.check_output(["glab", "api", "/user"]) + return json.loads(output) + + +def list_epics(): + result = subprocess.run( + ["glab", "api", f"/groups/{GROUP_ID}/epics?per_page=1000&state=opened"], + stdout=subprocess.PIPE, + ) + return json.loads(result.stdout) + + +def get_user(user_id): + api_url = f"{API_URL}/users/{user_id}" + response = requests.get(api_url, headers=private_token_headers()) + if response.status_code == 200: + return response.json() + return None + + +def build_issue_command( + project_id, + title, + labels, + assignee_id, + milestoneId, + epic, + iteration, + weight, + estimated_time, + issue_type="issue", +): + labels = ",".join(labels) if type(labels) == list else labels + issue_command = [ + "glab", + "api", + f"/projects/{str(project_id)}/issues", + "-f", + f"title={title}", + "-f", + f"assignee_ids={assignee_id}", + "-f", + f"issue_type={issue_type}", + ] + if labels: + issue_command.extend(["-f", f"labels={labels}"]) + if weight: + issue_command.extend(["-f", f"weight={str(weight)}"]) + if milestoneId: + issue_command.extend(["-f", f"milestone_id={str(milestoneId)}"]) + if epic: + issue_command.extend(["-f", f"epic_id={str(epic['id'])}"]) + + description = "" + if iteration: + description += f"/iteration *iteration:{str(iteration['id'])} " + if estimated_time: + description += f"\n/estimate {estimated_time}m " + issue_command.extend(["-f", f"description={description}"]) + return issue_command + + +def executeIssueCreate( + project_id, + title, + labels, + milestoneId, + epic, + iteration, + weight, + estimated_time, + issue_type="issue", +): + assignee_id = getAuthorizedUser()["id"] + issue_command = build_issue_command( + project_id, + title, + labels, + assignee_id, + milestoneId, + epic, + iteration, + weight, + estimated_time, + issue_type, + ) + issue_output = subprocess.check_output(issue_command) + return json.loads(issue_output.decode()) + + +def format_branch_name(issue): + issue_id = str(issue["iid"]) + title = re.sub("\\s+", "-", issue["title"]).lower() + title = title.replace(":", "").replace("(", " ").replace(")", "").replace(" ", "-") + return f"{issue_id}-{title}" + + +def create_branch(project_id, issue, main_branch): + issue_id = str(issue["iid"]) + branch_name = format_branch_name(issue) + branch_output = subprocess.check_output( + [ + "glab", + "api", + f"/projects/{str(project_id)}/repository/branches", + "-f", + f"branch={branch_name}", + "-f", + f"ref={main_branch}", + "-f", + f"issue_iid={issue_id}", + ] + ) + return json.loads(branch_output.decode()) + + +def build_merge_request_command(project_id, branch, issue, labels, milestoneId, assignee_id, main_branch): + issue_id = str(issue["iid"]) + labels = ",".join(labels) if type(labels) == list else labels + merge_request_command = [ + "glab", + "api", + f"/projects/{str(project_id)}/merge_requests", + "-f", + f"title={issue['title']}", + "-f", + f'description="Closes #{issue_id}"', + "-f", + f"source_branch={branch['name']}", + "-f", + f"target_branch={main_branch}", + "-f", + f"issue_iid={issue_id}", + "-f", + f"assignee_ids={assignee_id}", + ] + if SQUASH_COMMITS: + merge_request_command.extend(["-f", "squash=true"]) + if DELETE_BRANCH: + merge_request_command.extend(["-f", "remove_source_branch=true"]) + if labels: + merge_request_command.extend(["-f", f"labels={labels}"]) + if milestoneId: + merge_request_command.extend(["-f", f"milestone_id={str(milestoneId)}"]) + return merge_request_command + + +def create_merge_request(project_id, branch, issue, labels, milestoneId, main_branch): + assignee_id = getAuthorizedUser()["id"] + merge_request_command = build_merge_request_command( + project_id, + branch, + issue, + labels, + milestoneId, + assignee_id, + main_branch, + ) + mr_output = subprocess.check_output(merge_request_command) + return json.loads(mr_output.decode()) + + +def getMergeRequestForBranch(project_id, branchName): + api_url = f"{API_URL}/projects/{project_id}/merge_requests" + params = {"source_branch": branchName} + response = requests.get(api_url, headers=private_token_headers(), params=params) + if response.status_code == 200: + merge_requests = response.json() + for merge_request in merge_requests: + if merge_request["source_branch"] == branchName: + return merge_request + else: + print(f"Failed to fetch Merge Requests: {response.status_code} - {response.text}") + return None + + +def addReviewersToMergeRequest(project_id, mr_id, reviewers): + api_url = f"{API_URL}/projects/{project_id}/merge_requests/{mr_id}" + data = {"reviewer_ids": reviewers} + requests.put(api_url, headers=private_token_headers(), json=data) + + +def setMergeRequestToAutoMerge(project_id, mr_id): + api_url = f"{API_URL}/projects/{project_id}/merge_requests/{mr_id}/merge" + data = { + "id": project_id, + "merge_request_iid": mr_id, + "should_remove_source_branch": True, + "merge_when_pipeline_succeeds": True, + "auto_merge_strategy": "merge_when_pipeline_succeeds", + } + requests.put(api_url, headers=private_token_headers(), json=data) + + +def closeOpenedIssue(issue_iid, project_id): + issue_command = [ + "glab", + "api", + f"/projects/{project_id}/issues/{issue_iid}", + "-X", + "PUT", + "-f", + "state_event=close", + ] + try: + subprocess.run(issue_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + except subprocess.CalledProcessError as error: + print(f"Error closing issue: {str(error)}") + + +def getLabelsOfGroup(search=""): + try: + result = subprocess.run( + ["glab", "api", f"/groups/{GROUP_ID}/labels?search={search}"], + stdout=subprocess.PIPE, + check=True, + ) + return json.loads(result.stdout) + except subprocess.CalledProcessError as error: + print(f"Error getting labels: {str(error)}") + return [] + + +def get_recent_pipelines(project_id, ref=None, per_page=50): + api_url = f"{API_URL}/projects/{project_id}/pipelines" + params = {"per_page": per_page, "order_by": "updated_at", "sort": "desc"} + if ref: + params["ref"] = ref + response = requests.get(api_url, headers=private_token_headers(), params=params) + if response.status_code != 200: + print(f"Failed to fetch pipelines: {response.status_code} - {response.text}") + return None + return response.json() + + +def get_pipeline_jobs(project_id, pipeline_id): + api_url = f"{API_URL}/projects/{project_id}/pipelines/{pipeline_id}/jobs" + response = requests.get(api_url, headers=private_token_headers()) + if response.status_code == 200: + return response.json() + return None diff --git a/interactive.py b/interactive.py new file mode 100644 index 0000000..ec6d4a9 --- /dev/null +++ b/interactive.py @@ -0,0 +1,115 @@ +import inquirer + +from config import REVIEWERS +from gitlab_api import getLabelsOfGroup, get_user + + +def enterProjectId(): + while True: + project_id = input("Please enter the ID of your GitLab project: ") + if project_id: + return project_id + exit("Invalid project ID.") + + +def select_milestone(milestones): + choices = [milestone["title"] for milestone in milestones] + questions = [ + inquirer.List( + "milestones", + message="Select milestone:", + choices=choices, + ), + ] + answer = inquirer.prompt(questions) + return answer["milestones"] + + +def getSelectedMilestone(milestone, milestones): + return next((item for item in milestones if item["title"] == milestone), None) + + +def getSelectedIteration(iteration, iterations): + return next( + ( + item + for item in iterations + if item["start_date"] + " - " + item["due_date"] == iteration + ), + None, + ) + + +def select_iteration(iterations): + choices = [item["start_date"] + " - " + item["due_date"] for item in iterations] + questions = [ + inquirer.List( + "iterations", + message="Select iteration:", + choices=choices, + ), + ] + answer = inquirer.prompt(questions) + return answer["iterations"] + + +def select_epic(epics): + epic_titles = [epic["title"] for epic in epics] + search_query = inquirer.prompt( + [inquirer.Text("search_query", message="Search epic:")] + )["search_query"] + + filtered_epics = [ + choice for choice in epic_titles if search_query.lower() in choice.lower() + ] + questions = [ + inquirer.List( + "epics", + message="Select epic:", + choices=filtered_epics, + ), + ] + answer = inquirer.prompt(questions) + return answer["epics"] + + +def getSelectedEpic(epic, epics): + return next((item for item in epics if item["title"] == epic), None) + + +def chooseReviewersManually(): + reviewer_choices = [] + for reviewer_id in REVIEWERS: + user = get_user(reviewer_id) + if user: + display_name = f"{user.get('name')} ({user.get('username')})" + reviewer_choices.append((display_name, reviewer_id)) + else: + reviewer_choices.append((str(reviewer_id), reviewer_id)) + + questions = [ + inquirer.Checkbox( + "selected_reviewers", + message="Select reviewers", + choices=[(name, str(reviewer_id)) for name, reviewer_id in reviewer_choices], + ) + ] + answers = inquirer.prompt(questions) + if answers and "selected_reviewers" in answers: + return [int(reviewer) for reviewer in answers["selected_reviewers"]] + return [] + + +def selectLabels(search, multiple=False): + labels = getLabelsOfGroup(search) + choices = sorted([label["name"] for label in labels]) + question_type = inquirer.Checkbox if multiple else inquirer.List + questions = [ + question_type( + "labels", + message="Select one or more department labels:", + choices=choices, + ), + ] + answer = inquirer.prompt(questions) + return answer["labels"] diff --git a/templates.py b/templates.py new file mode 100644 index 0000000..e2fa57a --- /dev/null +++ b/templates.py @@ -0,0 +1,23 @@ +import inquirer + +from config import CUSTOM_TEMPLATE, TEMPLATES + + +def select_template(): + template_names = [template["name"] for template in TEMPLATES] + template_names.append(CUSTOM_TEMPLATE) + questions = [ + inquirer.List( + "template", + message="Select template:", + choices=template_names, + ), + ] + answer = inquirer.prompt(questions) + return answer["template"] + + +def getIssueSettings(template_name): + if template_name == CUSTOM_TEMPLATE: + return {} + return next((template for template in TEMPLATES if template["name"] == template_name), None) diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..3f7139c --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,23 @@ +import pytest + +import gitHappens + + +def test_main_without_args_prints_help_and_exits(): + with pytest.raises(SystemExit) as error: + gitHappens.main([]) + + assert error.value.code == 1 + + +def test_summary_command_dispatches(monkeypatch): + called = {"summary": False} + + def fake_summary(): + called["summary"] = True + + monkeypatch.setattr(gitHappens, "get_two_weeks_commits", fake_summary) + + gitHappens.main(["summary"]) + + assert called["summary"] is True diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 0000000..d8c1c18 --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,21 @@ +import json + +import config + + +def test_load_template_config_returns_defaults_for_missing_file(tmp_path): + missing_path = tmp_path / "missing.json" + + assert config.load_template_config(missing_path) == { + "templates": [], + "reviewers": [], + "productionMappings": {}, + } + + +def test_load_template_config_reads_templates(tmp_path): + template_path = tmp_path / "templates.json" + payload = {"templates": [{"name": "Bug"}], "reviewers": [1], "productionMappings": {}} + template_path.write_text(json.dumps(payload), encoding="utf-8") + + assert config.load_template_config(template_path) == payload diff --git a/tests/test_create_issue_command.py b/tests/test_create_issue_command.py new file mode 100644 index 0000000..9674ffc --- /dev/null +++ b/tests/test_create_issue_command.py @@ -0,0 +1,19 @@ +from commands import create_issue + + +def test_get_project_id_matches_current_remote(monkeypatch): + monkeypatch.setattr(create_issue, "getProjectLinkFromCurrentDir", lambda: "git@gitlab.com:org/app.git") + monkeypatch.setattr( + create_issue, + "get_all_projects", + lambda project_link: [{"ssh_url_to_repo": "git@gitlab.com:org/app.git", "id": 123}], + ) + + assert create_issue.get_project_id() == 123 + + +def test_get_project_id_prompts_when_not_in_git_repo(monkeypatch): + monkeypatch.setattr(create_issue, "getProjectLinkFromCurrentDir", lambda: -1) + monkeypatch.setattr(create_issue, "enterProjectId", lambda: "456") + + assert create_issue.get_project_id() == "456" diff --git a/tests/test_deploy_command.py b/tests/test_deploy_command.py new file mode 100644 index 0000000..8643687 --- /dev/null +++ b/tests/test_deploy_command.py @@ -0,0 +1,18 @@ +from commands.deploy import find_production_deployment + + +def test_find_production_deployment_matches_mapping(): + pipelines = [{"id": 1, "status": "success"}] + + def jobs_loader(project_id, pipeline_id): + return [{"name": "deploy-to-production", "stage": "deploy", "status": "success"}] + + result = find_production_deployment( + pipelines, + jobs_loader, + project_id=123, + production_mappings={"123": {"stage": "deploy", "job": "deploy-to-production"}}, + ) + + assert result["pipeline"] == pipelines[0] + assert result["production_job"]["name"] == "deploy-to-production" diff --git a/tests/test_git_utils.py b/tests/test_git_utils.py new file mode 100644 index 0000000..588ef0a --- /dev/null +++ b/tests/test_git_utils.py @@ -0,0 +1,23 @@ +import subprocess +from types import SimpleNamespace + +import git_utils + + +def test_get_project_link_from_current_dir_returns_remote(monkeypatch): + def fake_run(command, stdout, stderr): + assert command == ["git", "remote", "get-url", "origin"] + return SimpleNamespace(returncode=0, stdout=b"git@gitlab.com:group/project.git\n") + + monkeypatch.setattr(subprocess, "run", fake_run) + + assert git_utils.getProjectLinkFromCurrentDir() == "git@gitlab.com:group/project.git" + + +def test_get_project_link_from_current_dir_returns_minus_one_when_git_fails(monkeypatch): + def fake_run(command, stdout, stderr): + return SimpleNamespace(returncode=1, stdout=b"") + + monkeypatch.setattr(subprocess, "run", fake_run) + + assert git_utils.getProjectLinkFromCurrentDir() == -1 diff --git a/tests/test_gitlab_api.py b/tests/test_gitlab_api.py new file mode 100644 index 0000000..ab8048c --- /dev/null +++ b/tests/test_gitlab_api.py @@ -0,0 +1,45 @@ +import gitlab_api + + +def test_format_branch_name_matches_existing_cleanup(): + issue = {"iid": 42, "title": "Fix: Thing (Now)"} + + assert gitlab_api.format_branch_name(issue) == "42-fix-thing--now" + + +def test_build_issue_command_includes_optional_fields(): + command = gitlab_api.build_issue_command( + project_id=123, + title="Fix login", + labels=["Bug", "P::1"], + assignee_id=55, + milestoneId=10, + epic={"id": 7}, + iteration={"id": 9}, + weight=3, + estimated_time=30, + ) + + assert command[:3] == ["glab", "api", "/projects/123/issues"] + assert "title=Fix login" in command + assert "labels=Bug,P::1" in command + assert "milestone_id=10" in command + assert "epic_id=7" in command + assert "description=/iteration *iteration:9 \n/estimate 30m " in command + + +def test_build_merge_request_command_targets_main_branch(): + command = gitlab_api.build_merge_request_command( + project_id=123, + branch={"name": "42-fix-login"}, + issue={"iid": 42, "title": "Fix login"}, + labels=None, + milestoneId=None, + assignee_id=55, + main_branch="main", + ) + + assert command[:3] == ["glab", "api", "/projects/123/merge_requests"] + assert "source_branch=42-fix-login" in command + assert "target_branch=main" in command + assert "issue_iid=42" in command diff --git a/tests/test_interactive.py b/tests/test_interactive.py new file mode 100644 index 0000000..0e2f0d8 --- /dev/null +++ b/tests/test_interactive.py @@ -0,0 +1,19 @@ +import interactive + + +def test_get_selected_milestone_by_title(): + milestones = [{"title": "Sprint 1", "id": 1}, {"title": "Sprint 2", "id": 2}] + + assert interactive.getSelectedMilestone("Sprint 2", milestones) == {"title": "Sprint 2", "id": 2} + + +def test_get_selected_iteration_by_date_range(): + iterations = [{"start_date": "2026-01-01", "due_date": "2026-01-14", "id": 1}] + + assert interactive.getSelectedIteration("2026-01-01 - 2026-01-14", iterations) == iterations[0] + + +def test_get_selected_epic_by_title(): + epics = [{"title": "Billing", "id": 7}] + + assert interactive.getSelectedEpic("Billing", epics) == epics[0] diff --git a/tests/test_open_mr_command.py b/tests/test_open_mr_command.py new file mode 100644 index 0000000..235ad2f --- /dev/null +++ b/tests/test_open_mr_command.py @@ -0,0 +1,12 @@ +from commands import open_mr + + +def test_find_merge_request_id_by_branch(monkeypatch): + monkeypatch.setattr(open_mr, "get_project_id", lambda: 123) + monkeypatch.setattr( + open_mr, + "getMergeRequestForBranch", + lambda project_id, branch: {"iid": 9, "source_branch": branch}, + ) + + assert open_mr.find_merge_request_id_by_branch("feature") == 9 diff --git a/tests/test_review_command.py b/tests/test_review_command.py new file mode 100644 index 0000000..d92aa0a --- /dev/null +++ b/tests/test_review_command.py @@ -0,0 +1,13 @@ +from commands import review + + +def test_get_current_issue_id_from_merge_request_description(monkeypatch): + monkeypatch.setattr(review, "get_project_id", lambda: 123) + monkeypatch.setattr(review, "getCurrentBranch", lambda: "feature") + monkeypatch.setattr( + review, + "getMergeRequestForBranch", + lambda project_id, branch: {"description": '"Closes #77"'}, + ) + + assert review.getCurrentIssueId() == "77" diff --git a/tests/test_summary_command.py b/tests/test_summary_command.py new file mode 100644 index 0000000..939d60d --- /dev/null +++ b/tests/test_summary_command.py @@ -0,0 +1,14 @@ +from commands import summary + + +def test_generate_smart_summary_returns_without_commits(monkeypatch): + called = {"value": False} + + def fake_get_two_weeks_commits(return_output=False): + called["value"] = return_output + return "" + + monkeypatch.setattr(summary, "get_two_weeks_commits", fake_get_two_weeks_commits) + + assert summary.generate_smart_summary() is None + assert called["value"] is True diff --git a/tests/test_templates.py b/tests/test_templates.py new file mode 100644 index 0000000..d89bd6e --- /dev/null +++ b/tests/test_templates.py @@ -0,0 +1,15 @@ +import templates + + +def test_get_issue_settings_returns_empty_for_custom(monkeypatch): + monkeypatch.setattr(templates, "CUSTOM_TEMPLATE", "Custom") + + assert templates.getIssueSettings("Custom") == {} + + +def test_get_issue_settings_finds_named_template(monkeypatch): + expected = {"name": "Bug", "labels": ["Bug"]} + monkeypatch.setattr(templates, "CUSTOM_TEMPLATE", "Custom") + monkeypatch.setattr(templates, "TEMPLATES", [expected]) + + assert templates.getIssueSettings("Bug") == expected