From 692d5c10757311179f5f34011037b7a96d856a1d Mon Sep 17 00:00:00 2001 From: "penify-dev[bot]" <146478655+penify-dev[bot]@users.noreply.github.com> Date: Thu, 17 Apr 2025 06:34:14 +0000 Subject: [PATCH] Generated Documentation --- penify_hook/api_client.py | 86 +++++----- penify_hook/base_analyzer.py | 6 + penify_hook/commands/commit_commands.py | 45 +++-- penify_hook/commands/doc_commands.py | 46 +++-- penify_hook/commands/hook_commands.py | 20 +-- penify_hook/commit_analyzer.py | 70 ++++---- penify_hook/config_command.py | 31 ++-- penify_hook/file_analyzer.py | 41 ++--- penify_hook/folder_analyzer.py | 39 ++--- penify_hook/git_analyzer.py | 72 ++++---- penify_hook/jira_client.py | 148 ++++++++-------- penify_hook/llm_client.py | 46 +++-- penify_hook/login_command.py | 21 ++- penify_hook/main.py | 15 +- penify_hook/ui_utils.py | 140 ++++++++-------- tests/test_commit_commands.py | 199 ++++++++++------------ tests/test_config_commands.py | 213 ++++++++++-------------- tests/test_doc_commands.py | 171 +++++++++---------- tests/test_web_config.py | 45 ++--- 19 files changed, 669 insertions(+), 785 deletions(-) diff --git a/penify_hook/api_client.py b/penify_hook/api_client.py index 6c527eb..cfec092 100644 --- a/penify_hook/api_client.py +++ b/penify_hook/api_client.py @@ -5,33 +5,35 @@ class APIClient: def __init__(self, api_url, api_token: str = None, bearer_token: str = None): + """Initialize an instance of the API client with necessary authentication tokens. + + Args: + api_url (str): The base URL of the API. + api_token (str?): An API token for authentication. Defaults to None. + bearer_token (str?): A Bearer token for authentication. Defaults to None. + """ self.api_url = api_url self.AUTH_TOKEN = api_token self.BEARER_TOKEN = bearer_token def send_file_for_docstring_generation(self, file_name, content, line_numbers, repo_details = None): - """Send file content and modified lines to the API and return modified - content. - - This function constructs a payload containing the file path, content, - and modified line numbers, and sends it to a specified API endpoint for - processing. It handles the response from the API, returning the modified - content if the request is successful. If the request fails, it logs the - error details and returns the original content. - + """Send file content and modified lines to the API and return modified content. + + This function constructs a payload containing the file path, content, and modified line numbers, and sends it to a + specified API endpoint for processing. It handles the response from the API, returning the modified content if the + request is successful. If the request fails, it logs the error details and returns the original content. + Args: file_name (str): The path to the file being sent. content (str): The content of the file to be processed. line_numbers (list): A list of line numbers that have been modified. repo_details (str?): Additional repository details if applicable. Defaults to None. - + Returns: - str: The modified content returned by the API, or the original content if the - request fails. - + str: The modified content returned by the API, or the original content if the request fails. + Raises: - Exception: If there is an error in processing the file and no specific error - message is provided. + Exception: If there is an error in processing the file and no specific error message is provided. """ payload = { 'file_path': file_name, @@ -54,22 +56,20 @@ def send_file_for_docstring_generation(self, file_name, content, line_numbers, r def generate_commit_summary(self, git_diff, instruction: str = "", repo_details = None, jira_context: dict = None): """Generate a commit summary by sending a POST request to the API endpoint. - - This function constructs a payload containing the git diff and any - additional instructions provided. It then sends this payload to a - specified API endpoint to generate a summary of the commit. If the - request is successful, it returns the response from the API; otherwise, - it returns None. - + + This function constructs a payload containing the git diff and any additional instructions provided. It then sends this + payload to a specified API endpoint to generate a summary of the commit. If the request is successful, it returns the + response from the API; otherwise, it returns None. + Args: git_diff (str): The git diff of the commit. - instruction (str??): Additional instruction for the commit. Defaults to "". - repo_details (dict??): Details of the git repository. Defaults to None. - jira_context (dict??): JIRA issue details to enhance the commit summary. Defaults to None. - + instruction (str): Additional instruction for the commit. Defaults to "". + repo_details (dict): Details of the git repository. Defaults to None. + jira_context (dict): JIRA issue details to enhance the commit summary. Defaults to None. + Returns: dict: The response from the API if the request is successful, None otherwise. - + Raises: Exception: If there is an error during the API request. """ @@ -100,18 +100,16 @@ def generate_commit_summary(self, git_diff, instruction: str = "", repo_details return None def get_supported_file_types(self) -> list[str]: - """Retrieve the supported file types from the API. - - This function sends a request to the API endpoint - `/v1/file/supported_languages` to obtain a list of supported file types. - If the API call is successful (status code 200), it parses the JSON - response and returns the list of supported file types. If the API call - fails, it returns a default list of common file types. + """Retrieve the supported file types from the API. + + This function sends a request to the API endpoint `/v1/file/supported_languages` to obtain a list of supported file + types. If the API call is successful (status code 200), it parses the JSON response and returns the list of supported + file types. If the API call fails, it returns a default list of common file types. + Returns: list[str]: A list of supported file types, either from the API or a default set. """ - url = self.api_url+"/v1/file/supported_languages" response = requests.get(url) if response.status_code == 200: @@ -121,10 +119,9 @@ def get_supported_file_types(self) -> list[str]: return ["py", "js", "ts", "java", "kt", "cs", "c"] def generate_commit_summary_with_llm(self, diff, message, generate_description: bool, repo_details, llm_client : LLMClient, jira_context=None): - """Generates a commit summary using a local LLM client. If an error occurs - during the generation process, + """Generates a commit summary using a local LLM client. If an error occurs during the generation process, it falls back to using the API. - + Args: diff (str): The Git diff of changes. message (str): User-provided commit message or instructions. @@ -132,7 +129,7 @@ def generate_commit_summary_with_llm(self, diff, message, generate_description: repo_details (dict): Details about the repository. llm_client (LLMClient): An instance of LLMClient used to generate the summary. jira_context (JIRAContext?): Optional JIRA issue context to enhance the summary. - + Returns: dict: A dictionary containing the title and description for the commit. """ @@ -144,17 +141,16 @@ def generate_commit_summary_with_llm(self, diff, message, generate_description: return self.generate_commit_summary(diff, message, repo_details, jira_context) def get_api_key(self): - """Fetch an API key from a specified URL. - This function sends a GET request to retrieve an API token using a - Bearer token in the headers. It handles the response and returns the API - key if the request is successful, or `None` otherwise. + """Fetch an API key from a specified URL. + + This function sends a GET request to retrieve an API token using a Bearer token in the headers. It handles the response + and returns the API key if the request is successful, or `None` otherwise. + Returns: str: The API key if the request is successful, `None` otherwise. """ - - url = self.api_url+"/v1/apiToken/get" response = requests.get(url, headers={"Authorization": f"Bearer {self.BEARER_TOKEN}"}, timeout=60*10) if response.status_code == 200: diff --git a/penify_hook/base_analyzer.py b/penify_hook/base_analyzer.py index f1cda81..65cf1c7 100644 --- a/penify_hook/base_analyzer.py +++ b/penify_hook/base_analyzer.py @@ -7,6 +7,12 @@ class BaseAnalyzer: def __init__(self, folder_path: str, api_client: APIClient): + """Initialize an instance of YourClassName with a folder path and an API client. + + Args: + folder_path (str): The path to the directory containing the repository. + api_client (APIClient): An instance of the APIClient class for interacting with external services. + """ self.folder_path = folder_path self.repo_path = recursive_search_git_folder(folder_path) self.repo = None diff --git a/penify_hook/commands/commit_commands.py b/penify_hook/commands/commit_commands.py index a9d93f8..85ac817 100644 --- a/penify_hook/commands/commit_commands.py +++ b/penify_hook/commands/commit_commands.py @@ -8,29 +8,26 @@ def commit_code(api_url, token, message, open_terminal, generate_description, llm_model=None, llm_api_base=None, llm_api_key=None, jira_url=None, jira_user=None, jira_api_token=None): - """Enhance Git commits with AI-powered commit messages. - - This function allows for the generation of enhanced commit messages - using natural language processing models and optionally integrates with - JIRA for additional context. It processes the current Git folder to find - relevant files and generates a detailed commit message based on the - provided parameters. + """Enhance Git commits with AI-powered commit messages. + + This function allows for the generation of enhanced commit messages using natural language processing models and + optionally integrates with JIRA for additional context. It processes the current Git folder to find relevant files and + generates a detailed commit message based on the provided parameters. + Args: api_url (str): URL of the API endpoint. token (str): Authentication token for the API. message (str): Initial commit message provided by the user. open_terminal (bool): Whether to open the terminal after committing. generate_description (bool): Whether to generate a detailed description in the commit message. - llm_model (str?): The language model to use for generating the commit message. Defaults to - None. + llm_model (str?): The language model to use for generating the commit message. Defaults to None. llm_api_base (str?): Base URL of the LLM API. Defaults to None. llm_api_key (str?): API key for accessing the LLM service. Defaults to None. jira_url (str?): URL of the JIRA instance. Defaults to None. jira_user (str?): Username for authenticating with JIRA. Defaults to None. jira_api_token (str?): API token for accessing JIRA. Defaults to None. """ - from penify_hook.ui_utils import print_error from penify_hook.utils import recursive_search_git_folder from ..commit_analyzer import CommitDocGenHook @@ -98,18 +95,16 @@ def commit_code(api_url, token, message, open_terminal, generate_description, def setup_commit_parser(parser): - """Generates a parser for setting up a command to generate smart commit - messages. - - This function sets up an argument parser that can be used to generate - commit messages with contextual information. It allows users to specify - options such as including a message, opening an edit terminal before - committing, and generating a detailed commit message. + """Generates a parser for setting up a command to generate smart commit messages. + + This function sets up an argument parser that can be used to generate commit messages with contextual information. It + allows users to specify options such as including a message, opening an edit terminal before committing, and generating + a detailed commit message. + Args: parser (argparse.ArgumentParser): The ArgumentParser object to be configured. """ - commit_parser_description = """ It generates smart commit messages. By default, it will just generate just the Title of the commit message. 1. If you have not configured LLM, it will give an error. You either need to configure LLM or use the API key. @@ -126,19 +121,17 @@ def setup_commit_parser(parser): parser.add_argument("-d", "--description", action="store_false", help="It will generate commit message with title and description.", default=False) def handle_commit(args): - """Handle the commit functionality by processing arguments and invoking the - appropriate commands. - - This function processes the provided command-line arguments to configure - settings for commit operations, including LLM (Language Model) and Jira - configurations. It then calls the `commit_code` function with these - configurations to perform the actual commit operation. + """Handle the commit functionality by processing arguments and invoking the appropriate commands. + + This function processes the provided command-line arguments to configure settings for commit operations, including LLM + (Language Model) and Jira configurations. It then calls the `commit_code` function with these configurations to perform + the actual commit operation. + Args: args (argparse.Namespace): The parsed command-line arguments containing options like terminal, description, message, etc. """ - from penify_hook.commands.commit_commands import commit_code from penify_hook.commands.config_commands import get_jira_config, get_llm_config, get_token from penify_hook.constants import API_URL diff --git a/penify_hook/commands/doc_commands.py b/penify_hook/commands/doc_commands.py index 5fb3273..68a7d16 100644 --- a/penify_hook/commands/doc_commands.py +++ b/penify_hook/commands/doc_commands.py @@ -4,22 +4,20 @@ import os def generate_doc(api_url, token, location=None): - """Generates documentation based on the given parameters. - This function initializes an API client using the provided API URL and - token. It then generates documentation by analyzing the specified - location, which can be a folder, a file, or the current working - directory if no location is provided. The function handles different - types of analysis based on the input location and reports any errors + """Generates documentation based on the given parameters. + + This function initializes an API client using the provided API URL and token. It then generates documentation by + analyzing the specified location, which can be a folder, a file, or the current working directory if no location is + provided. The function handles different types of analysis based on the input location and reports any errors encountered during the process. - + Args: api_url (str): The URL of the API to connect to for documentation generation. token (str): The authentication token for accessing the API. location (str?): The path to a specific file or folder to analyze. If not provided, the current working directory is used. """ - import os import sys from ..folder_analyzer import FolderAnalyzerGenHook @@ -80,19 +78,16 @@ def generate_doc(api_url, token, location=None): """ def setup_docgen_parser(parser): - """Set up and configure a parser for documentation generation using Git - commands. - - This function configures a parser with various subcommands and arguments - necessary for generating documentation for Git diffs, files, or folders. - It also installs and uninstalls commit hooks to automate documentation - generation on commits. + # We don't need to create a new docgen_parser since it's passed as a parameter + """Set up and configure a parser for documentation generation using Git commands. + + This function configures a parser with various subcommands and arguments necessary for generating documentation for Git + diffs, files, or folders. It also installs and uninstalls commit hooks to automate documentation generation on commits. + Args: parser (argparse.ArgumentParser): The parser to configure. """ - - # We don't need to create a new docgen_parser since it's passed as a parameter docgen_parser_description = """ It generates Documentation for the Git diff, file or folder. 1. By default, it will git diff documentation - visit https://penify.wiki/dcdc for more details. @@ -122,19 +117,16 @@ def setup_docgen_parser(parser): default=os.getcwd()) def handle_docgen(args): - """Handle various subcommands related to document generation and hook - management. - - This function processes different subcommands such as installing or - uninstalling git hooks, and directly generating documentation based on - provided arguments. + # Only import dependencies needed for docgen functionality here + """Handle various subcommands related to document generation and hook management. + + This function processes different subcommands such as installing or uninstalling git hooks, and directly generating + documentation based on provided arguments. + Args: - args (Namespace): Parsed command-line arguments containing the subcommand and location - details. + args (Namespace): Parsed command-line arguments containing the subcommand and location details. """ - - # Only import dependencies needed for docgen functionality here from penify_hook.commands.config_commands import get_token import sys from penify_hook.commands.doc_commands import generate_doc diff --git a/penify_hook/commands/hook_commands.py b/penify_hook/commands/hook_commands.py index 1a49bfe..05528eb 100644 --- a/penify_hook/commands/hook_commands.py +++ b/penify_hook/commands/hook_commands.py @@ -10,14 +10,11 @@ """ def install_git_hook(location, token): - """Install a post-commit hook in the specified location that generates - documentation - for changed files after each commit. - + """Install a post-commit hook in the specified location that generates documentation for changed files after each commit. + Args: location (str): The path to the Git repository where the hook should be installed. - token (str): The authentication token required to access the documentation generation - service. + token (str): The authentication token required to access the documentation generation service. """ hooks_dir = Path(location) / ".git/hooks" hook_path = hooks_dir / HOOK_FILENAME @@ -35,12 +32,11 @@ def install_git_hook(location, token): def uninstall_git_hook(location): """Uninstalls the post-commit hook from the specified location. - - This function attempts to remove a post-commit git hook located at the - given path. It constructs the path to the hook and checks if it exists. - If the hook is found, it is deleted, and a confirmation message is - printed. If no hook is found, a message indicating this is also printed. - + + This function attempts to remove a post-commit git hook located at the given path. It constructs the path to the hook + and checks if it exists. If the hook is found, it is deleted, and a confirmation message is printed. If no hook is + found, a message indicating this is also printed. + Args: location (Path): The base directory where the .git/hooks directory is located. """ diff --git a/penify_hook/commit_analyzer.py b/penify_hook/commit_analyzer.py index 31ab46b..6d22902 100644 --- a/penify_hook/commit_analyzer.py +++ b/penify_hook/commit_analyzer.py @@ -13,6 +13,14 @@ class CommitDocGenHook(BaseAnalyzer): def __init__(self, repo_path: str, api_client: APIClient, llm_client=None, jira_client=None): + """Initialize a new instance of the class. + + Args: + repo_path (str): The path to the repository. + api_client (APIClient): An instance of the API client. + llm_client (LLMClient?): An instance of the LLM client. Defaults to None. + jira_client (JiraClient?): An instance of the JIRA client. Defaults to None. + """ super().__init__(repo_path, api_client) self.llm_client = llm_client # Add LLM client as an optional parameter @@ -20,25 +28,20 @@ def __init__(self, repo_path: str, api_client: APIClient, llm_client=None, jira_ def get_summary(self, instruction: str, generate_description: bool) -> dict: """Generate a summary for the commit based on the staged changes. - - This function retrieves the differences of the staged changes in the - repository and generates a commit summary using the provided - instruction. If there are no changes staged for commit, an exception is - raised. If a JIRA client is connected, it will attempt to extract issue - keys from the current branch and use them to fetch context. The summary - can be generated either with a Language Model (LLM) client or through - the API client. - + + This function retrieves the differences of the staged changes in the repository and generates a commit summary using the + provided instruction. If there are no changes staged for commit, an exception is raised. If a JIRA client is connected, + it will attempt to extract issue keys from the current branch and use them to fetch context. The summary can be + generated either with a Language Model (LLM) client or through the API client. + Args: instruction (str): A string containing instructions for generating the commit summary. generate_description (bool): Whether to include detailed descriptions in the summary. - + Returns: - dict: The generated commit summary based on the staged changes, provided - instruction, and any relevant JIRA context. The dictionary contains keys - such as 'summary', 'description', etc., depending on whether a - description was requested. - + dict: The generated commit summary based on the staged changes, provided instruction, and any relevant JIRA context. The + dictionary contains keys such as 'summary', 'description', etc., depending on whether a description was requested. + Raises: ValueError: If there are no changes staged for commit. """ @@ -72,19 +75,18 @@ def get_summary(self, instruction: str, generate_description: bool) -> dict: def run(self, msg: Optional[str], edit_commit_message: bool, generate_description: bool): """Run the post-commit hook. - - This method processes the modified files from the last commit, stages - them, and creates an auto-commit with an optional message. It also - handles JIRA integration if available. If there is an error generating - the commit summary, an exception is raised. - + + This method processes the modified files from the last commit, stages them, and creates an auto-commit with an optional + message. It also handles JIRA integration if available. If there is an error generating the commit summary, an exception + is raised. + Args: msg (Optional[str]): An optional message to include in the commit. edit_commit_message (bool): A flag indicating whether to open the git commit edit terminal after committing. generate_description (bool): A flag indicating whether to include a description in the commit message. - + Raises: Exception: If there is an error generating the commit summary. """ @@ -111,18 +113,21 @@ def run(self, msg: Optional[str], edit_commit_message: bool, generate_descriptio self._amend_commit() def process_jira_integration(self, title: str, description: str, msg: str) -> tuple: + # Look for JIRA issue keys in commit message, title, description and user message """Process JIRA integration for the commit message. - + + This function looks for JIRA issue keys within the provided commit title, description, and user message. It then + extracts any additional issue keys from the current branch name. If JIRA issues are found, it formats the commit message + with this information and adds a comment to each relevant JIRA issue. + Args: title (str): Generated commit title. description (str): Generated commit description. msg (str): Original user message that might contain JIRA references. - + Returns: - tuple: A tuple containing the updated commit title and description with - included JIRA information. + tuple: A tuple containing the updated commit title and description with included JIRA information. """ - # Look for JIRA issue keys in commit message, title, description and user message issue_keys = [] if self.jira_client: # Extract from message content @@ -160,12 +165,11 @@ def process_jira_integration(self, title: str, description: str, msg: str) -> tu return title, description def _amend_commit(self): - """Open the default git editor for editing the commit message. - - This function changes the current working directory to the repository - path, runs the git command to amend the last commit, and opens the - default editor for the user to modify the commit message. After the - operation, it returns to the original directory. + """Amend the last commit's message using the default git editor. + + This function changes the current working directory to the repository path, runs the `git commit --amend` command to + modify the last commit, and opens the default git editor for the user to edit the commit message. After the operation, + it returns to the original directory. """ try: # Change to the repository directory diff --git a/penify_hook/config_command.py b/penify_hook/config_command.py index 1d9a6ab..f6ecece 100644 --- a/penify_hook/config_command.py +++ b/penify_hook/config_command.py @@ -2,19 +2,17 @@ def setup_config_parser(parent_parser): - """Set up a configuration parser with subparsers for different types of - configurations. - - This function configures and adds subcommands to the parent parser. Each - subcommand corresponds to a specific type of configuration, such as LLM - (Language Model) or JIRA. It allows users to configure settings for - these systems through command-line arguments. + # Config subcommand: Create subparsers for config types + """Set up a configuration parser with subparsers for different types of configurations. + + This function configures and adds subcommands to the parent parser. Each subcommand corresponds to a specific type of + configuration, such as LLM (Language Model) or JIRA. It allows users to configure settings for these systems through + command-line arguments. + Args: parent_parser (argparse.ArgumentParser): The parent parser to which the config subparsers will be added. """ - - # Config subcommand: Create subparsers for config types parser = parent_parser.add_subparsers(title="config_type", dest="config_type") # Config subcommand: llm @@ -39,20 +37,19 @@ def setup_config_parser(parent_parser): # Add all other necessary arguments for config command def handle_config(args): - """Handle configuration settings based on the specified config type. - - This function processes different types of configurations such as LLM - (Language Model) and JIRA. It saves configurations, sets up web-based - configurations, and verifies JIRA connections. + # Only import dependencies needed for config functionality here + """Handle configuration settings based on the specified config type. + + This function processes different types of configurations such as LLM (Language Model) and JIRA. It saves + configurations, sets up web-based configurations, and verifies JIRA connections. + Args: args (argparse.Namespace): Command-line arguments containing the type of configuration to handle. - + Returns: int: Exit code indicating success or failure. """ - - # Only import dependencies needed for config functionality here from penify_hook.commands.config_commands import save_llm_config from penify_hook.jira_client import JiraClient # Import moved here from penify_hook.commands.config_commands import config_jira_web, config_llm_web, save_jira_config diff --git a/penify_hook/file_analyzer.py b/penify_hook/file_analyzer.py index c161afc..17f0183 100644 --- a/penify_hook/file_analyzer.py +++ b/penify_hook/file_analyzer.py @@ -19,24 +19,27 @@ class FileAnalyzerGenHook(BaseAnalyzer): def __init__(self, file_path: str, api_client: APIClient): + """Initialize a new instance of the class with the given file path and API client. + + Args: + file_path (str): The path to the file. + api_client (APIClient): An instance of the APIClient class. + """ self.file_path = file_path super().__init__(file_path, api_client) def process_file(self, file_path, pbar): - """Process a file by reading its content and sending it to an API for - processing. - - This function validates the provided file extension, reads the content - of the file, and sends it to an API client for further processing. If - the API responds successfully, the original file content is replaced - with the response. - + """Process a file by reading its content and sending it to an API for processing. + + This function validates the provided file extension, reads the content of the file, and sends it to an API client for + further processing. If the API responds successfully, the original file content is replaced with the response. + Args: file_path (str): The relative path to the file that needs to be processed. pbar (tqdm): Progress bar to update during processing. - + Returns: bool: True if the file was processed successfully, False otherwise. """ @@ -104,7 +107,7 @@ def process_file(self, file_path, pbar): def print_processing(self, file_path): """Print a processing message for a file. - + Args: file_path (str): The path to the file being processed. """ @@ -112,20 +115,18 @@ def print_processing(self, file_path): print(f"\n{format_highlight(f'Processing file: {formatted_path}')}") def run(self): + + # Create a progress bar with appropriate stages """Run the post-commit hook. - - This method executes the post-commit hook by processing a specified - file. It attempts to process the file located at `self.file_path`. If an - error occurs during the processing, it catches the exception and prints - an error message indicating that the file was not processed. The method - displays a progress bar and colored output to provide visual feedback on - the processing status. - + + This method executes the post-commit hook by processing a specified file. It attempts to process the file located at + `self.file_path`. If an error occurs during the processing, it catches the exception and prints an error message + indicating that the file was not processed. The method displays a progress bar and colored output to provide visual + feedback on the processing status. + Args: self (PostCommitHook): An instance of the PostCommitHook class. """ - - # Create a progress bar with appropriate stages stages = ["Validating", "Reading content", "Documenting", "Writing changes", "Completed"] pbar, _ = create_stage_progress_bar(stages, f"Starting documenting") diff --git a/penify_hook/folder_analyzer.py b/penify_hook/folder_analyzer.py index 15ec20f..089e589 100644 --- a/penify_hook/folder_analyzer.py +++ b/penify_hook/folder_analyzer.py @@ -8,26 +8,29 @@ class FolderAnalyzerGenHook(BaseAnalyzer): def __init__(self, dir_path: str, api_client: APIClient): + """Initialize a new instance of the class. + + Args: + dir_path (str): The directory path. + api_client (APIClient): An API client instance. + """ self.dir_path = dir_path super().__init__(dir_path, api_client) def list_all_files_in_dir(self, dir_path: str): - """List all non-hidden files in a directory and its subdirectories. - - This function recursively traverses the specified directory and its - subdirectories, collecting paths of all non-hidden files. It filters out - hidden directories and files (those starting with a dot) to ensure only - visible files are returned. + """List all non-hidden files in a directory and its subdirectories. + + This function recursively traverses the specified directory and its subdirectories, collecting paths of all non-hidden + files. It filters out hidden directories and files (those starting with a dot) to ensure only visible files are + returned. + Args: - dir_path (str): The path to the directory whose files and subdirectory files need to be - listed. - + dir_path (str): The path to the directory whose files and subdirectory files need to be listed. + Returns: - list: A list containing the full paths of all non-hidden files within the - specified directory and its subdirectories. + list: A list containing the full paths of all non-hidden files within the specified directory and its subdirectories. """ - files = [] for dirpath, dirnames, filenames in os.walk(dir_path): dirnames[:] = [d for d in dirnames if not d.startswith(".")] @@ -39,13 +42,11 @@ def list_all_files_in_dir(self, dir_path: str): def run(self): """Run the post-commit hook. - - This function processes all files in a specified directory using a - progress bar. It lists all files, initializes a `FileAnalyzerGenHook` - for each file, and runs it. Errors during processing of individual files - are caught and logged, but do not stop the processing of other files. A - progress bar is displayed indicating the number of files processed. - + + This function processes all files in a specified directory using a progress bar. It lists all files, initializes a + `FileAnalyzerGenHook` for each file, and runs it. Errors during processing of individual files are caught and logged, + but do not stop the processing of other files. A progress bar is displayed indicating the number of files processed. + Args: self (PostCommitHook): The instance of the post-commit hook class. """ diff --git a/penify_hook/git_analyzer.py b/penify_hook/git_analyzer.py index f9e7127..9ea8be7 100644 --- a/penify_hook/git_analyzer.py +++ b/penify_hook/git_analyzer.py @@ -18,17 +18,21 @@ class GitDocGenHook(BaseAnalyzer): def __init__(self, repo_path: str, api_client: APIClient): + """Initialize a new instance of the class with the specified repository path and API client. + + Args: + repo_path (str): The path to the local git repository. + api_client (APIClient): An instance of the APIClient class used for interacting with the API. + """ super().__init__(repo_path, api_client) def get_modified_files_in_last_commit(self): """Get the list of files modified in the last commit. - - This function retrieves the files that were modified in the most recent - commit of the repository. It accesses the last commit and iterates - through the differences to compile a list of unique file paths that were - changed. The function returns this list for further processing or - analysis. - + + This function retrieves the files that were modified in the most recent commit of the repository. It accesses the last + commit and iterates through the differences to compile a list of unique file paths that were changed. The function + returns this list for further processing or analysis. + Returns: list: A list of file paths that were modified in the last commit. """ @@ -40,17 +44,15 @@ def get_modified_files_in_last_commit(self): return modified_files def get_modified_lines(self, diff_text): - """Extract modified line numbers from a diff text. - - This function processes a diff text to identify and extract the line - numbers that have been modified. It distinguishes between added and - deleted lines and keeps track of the current line number as it parses - through the diff. The function handles hunk headers and ensures that any - deletions at the end of the file are also captured. - + """Extracts and returns a list of unique line numbers that have been modified in the given diff text. + + This function processes a diff text to identify and extract the line numbers that have been modified. It distinguishes + between added and deleted lines and keeps track of the current line number as it parses through the diff. The function + handles hunk headers and ensures that any deletions at the end of the file are also captured. + Args: diff_text (str): A string containing the diff text to be processed. - + Returns: list: A sorted list of unique line numbers that have been modified. """ @@ -89,23 +91,18 @@ def get_modified_lines(self, diff_text): return sorted(set(modified_lines)) # Remove duplicates and sort def process_file(self, file_path): - """Process a file by checking its type, reading its content, and sending it - to an API. - - This method constructs the absolute path of the specified file and - verifies if the file has a valid extension. If the file type is - supported, it reads the content of the file and retrieves the - differences from the last commit in the repository. If changes are - detected, it sends the file content along with the modified lines to an - API for further processing. If the API response indicates no changes, - the original file will not be overwritten. - + """Process a file by checking its type, reading its content, and sending it to an API. + + This method constructs the absolute path of the specified file and verifies if the file has a valid extension. If the + file type is supported, it reads the content of the file and retrieves the differences from the last commit in the + repository. If changes are detected, it sends the file content along with the modified lines to an API for further + processing. If the API response indicates no changes, the original file will not be overwritten. + Args: file_path (str): The relative path to the file to be processed. - + Returns: - bool: True if the file was successfully processed and updated, False - otherwise. + bool: True if the file was successfully processed and updated, False otherwise. """ file_abs_path = os.path.join(self.repo_path, file_path) file_extension = os.path.splitext(file_path)[1].lower() @@ -151,15 +148,12 @@ def process_file(self, file_path): def run(self): """Run the post-commit hook. - - This method retrieves the list of modified files from the last commit - and processes each file. It stages any files that have been modified - during processing and creates an auto-commit if changes were made. A - progress bar is displayed to indicate the processing status of each - file. The method handles any exceptions that occur during file - processing, printing an error message for each file that fails to - process. If any modifications are made to the files, an auto-commit is - created to save those changes. + + This method retrieves the list of modified files from the last commit and processes each file. It stages any files that + have been modified during processing and creates an auto-commit if changes were made. A progress bar is displayed to + indicate the processing status of each file. The method handles any exceptions that occur during file processing, + printing an error message for each file that fails to process. If any modifications are made to the files, an auto- + commit is created to save those changes. """ logger.info("Starting doc_gen_hook processing") print_info("Starting doc_gen_hook processing") diff --git a/penify_hook/jira_client.py b/penify_hook/jira_client.py index 56d2e22..b31c384 100644 --- a/penify_hook/jira_client.py +++ b/penify_hook/jira_client.py @@ -15,13 +15,12 @@ class JiraClient: """ def __init__(self, jira_url: str = None, jira_user: str = None, jira_api_token: str = None): - """ - Initialize the JIRA client. + """Initialize the JIRA client. Args: - jira_url: Base URL for JIRA instance (e.g., "https://your-domain.atlassian.net") - jira_user: JIRA username or email - jira_api_token: JIRA API token + jira_url (str): Base URL for JIRA instance (e.g., "https://your-domain.atlassian.net") + jira_user (str): JIRA username or email + jira_api_token (str): JIRA API token """ self.jira_url = jira_url self.jira_user = jira_user @@ -45,36 +44,33 @@ def __init__(self, jira_url: str = None, jira_user: str = None, jira_api_token: def is_connected(self) -> bool: """Check if the JIRA client is connected. - - This function verifies whether the JIRA client has successfully - established a connection. It returns `True` if the client is connected, - and `False` otherwise. - + + This function verifies whether the JIRA client has successfully established a connection. It returns `True` if the + client is connected, and `False` otherwise. + Returns: bool: True if the JIRA client is connected, False otherwise """ return self.jira_client is not None def extract_issue_keys_from_branch(self, branch_name: str) -> List[str]: + # Common JIRA issue key pattern: PROJECT-123 """Extracts JIRA issue keys from a branch name. - - This function searches through a given git branch name to find and - return any JIRA issue keys that match the pattern. Common conventions - for JIRA issue keys in branch names include: - - feature/PROJECT-123-description - bugfix/PROJECT-123-fix-something - - hotfix/PROJECT-123/short-desc - + + This function searches through a given git branch name to find and return any JIRA issue keys that match the pattern. + Common conventions for JIRA issue keys in branch names include: - feature/PROJECT-123-description - + bugfix/PROJECT-123-fix-something - hotfix/PROJECT-123/short-desc + Args: branch_name (str): The name of the git branch to search for JIRA issue keys. - + Returns: List[str]: A list of unique JIRA issue keys found in the branch name. - + Examples: extract_issue_keys_from_branch("feature/PROJ-456-add-new-feature") # Output: ['PROJ-456'] """ - # Common JIRA issue key pattern: PROJECT-123 pattern = r'[A-Z][A-Z0-9_]+-[0-9]+' matches = re.findall(pattern, branch_name) if matches: @@ -82,44 +78,37 @@ def extract_issue_keys_from_branch(self, branch_name: str) -> List[str]: return list(set(matches)) # Remove duplicates def extract_issue_keys(self, text: str) -> List[str]: + # Common JIRA issue key pattern: PROJECT-123 """Extract JIRA issue keys from a given text. - - This function searches through the provided text to find and return all - unique JIRA issue keys. A JIRA issue key typically follows the pattern - of PROJECT-123, where PROJECT is alphanumeric and consists of at least - one uppercase letter followed by one or more alphanumeric characters, - and 123 is a numeric sequence. - + + This function searches through the provided text to find and return all unique JIRA issue keys. A JIRA issue key + typically follows the pattern of PROJECT-123, where PROJECT is alphanumeric and consists of at least one uppercase + letter followed by one or more alphanumeric characters, and 123 is a numeric sequence. + Args: text (str): The text in which to search for JIRA issue keys. - + Returns: List[str]: A list of unique JIRA issue keys found in the text. """ - # Common JIRA issue key pattern: PROJECT-123 pattern = r'[A-Z][A-Z0-9_]+-[0-9]+' matches = re.findall(pattern, text) return list(set(matches)) # Remove duplicates def get_issue_details(self, issue_key: str) -> Optional[Dict[str, Any]]: """Retrieve details of a JIRA issue based on its key. - - This function fetches detailed information about a specified JIRA issue - using the provided issue key. It checks if the JIRA client is connected - before attempting to retrieve the issue. If the client is not connected, - it logs a warning and returns `None`. The function then attempts to - fetch the issue from the JIRA server and constructs a dictionary - containing various details about the issue such as its key, summary, - status, description, assignee, reporter, type, priority, and URL. If any - errors occur during this process, they are logged, and `None` is - returned. - + + This function fetches detailed information about a specified JIRA issue using the provided issue key. It checks if the + JIRA client is connected before attempting to retrieve the issue. If the client is not connected, it logs a warning and + returns `None`. The function then attempts to fetch the issue from the JIRA server and constructs a dictionary + containing various details about the issue such as its key, summary, status, description, assignee, reporter, type, + priority, and URL. If any errors occur during this process, they are logged, and `None` is returned. + Args: issue_key (str): The JIRA issue key (e.g., "PROJECT-123"). - + Returns: - Dict[str, Any] or None: A dictionary containing the details of the JIRA - issue if found, otherwise `None`. + Dict[str, Any] or None: A dictionary containing the details of the JIRA issue if found, otherwise `None`. """ if not self.is_connected(): logging.warning("JIRA client not connected") @@ -144,13 +133,13 @@ def get_issue_details(self, issue_key: str) -> Optional[Dict[str, Any]]: def add_comment(self, issue_key: str, comment: str) -> bool: """Add a comment to a JIRA issue. - + Args: - issue_key (str): JIRA issue key (e.g., "PROJECT-123") - comment (str): Comment text to add - + issue_key (str): The JIRA issue key, e.g., "PROJECT-123". + comment (str): The text of the comment to be added. + Returns: - bool: True if the comment was added successfully, False otherwise + bool: True if the comment was added successfully, False otherwise. """ if not self.is_connected(): logging.warning("JIRA client not connected") @@ -166,11 +155,16 @@ def add_comment(self, issue_key: str, comment: str) -> bool: def update_issue_status(self, issue_key: str, transition_name: str) -> bool: """Update the status of a JIRA issue. - + + This function updates the status of a specified JIRA issue by transitioning it to a new state based on the provided + transition name. It first checks if the JIRA client is connected and then attempts to find the appropriate transition ID + from the available transitions. If found, it applies the transition and logs the update. If any errors occur during the + process, it logs an error message. + Args: issue_key (str): The key of the JIRA issue to be updated. transition_name (str): The name of the desired transition. - + Returns: bool: True if the status was successfully updated, False otherwise. """ @@ -202,20 +196,20 @@ def update_issue_status(self, issue_key: str, transition_name: str) -> bool: return False def format_commit_message_with_jira_info(self, commit_title: str, commit_description: str, issue_keys: List[str] = None) -> tuple: + # If no issue keys provided, extract them from title and description """Format commit message with JIRA issue information. - + Args: commit_title (str): The original commit title. commit_description (str): The original commit description. issue_keys (List[str]?): A list of JIRA issue keys to include in the commit message. If not provided, issue keys will be extracted from both the title and the description. - + Returns: tuple: A tuple containing the updated commit title and description with JIRA information included. """ - # If no issue keys provided, extract them from title and description if not issue_keys: title_keys = self.extract_issue_keys(commit_title) desc_keys = self.extract_issue_keys(commit_description) @@ -252,19 +246,16 @@ def format_commit_message_with_jira_info(self, commit_title: str, commit_descrip return updated_title, updated_description def get_detailed_issue_context(self, issue_key: str) -> Dict[str, Any]: - """Retrieve comprehensive details about a JIRA issue including context for - better commit messages. - - This function fetches detailed information from a specified JIRA issue - and constructs a dictionary containing various context fields such as - the issue summary, description, type, status, priority, comments, URL, - and additional custom fields like acceptance criteria and sprint - information. If any errors occur during the fetching process, - appropriate warnings or errors are logged. - + """Retrieve comprehensive details about a JIRA issue including context for better commit messages. + + This function fetches detailed information from a specified JIRA issue and constructs a dictionary containing various + context fields such as the issue summary, description, type, status, priority, comments, URL, and additional custom + fields like acceptance criteria and sprint information. If any errors occur during the fetching process, appropriate + warnings or errors are logged. + Args: issue_key (str): The JIRA issue key (e.g., "PROJECT-123"). - + Returns: Dict[str, Any]: A dictionary containing business and technical context from the issue. """ @@ -336,19 +327,16 @@ def get_detailed_issue_context(self, issue_key: str) -> Dict[str, Any]: return {} def get_commit_context_from_issues(self, issue_keys: List[str]) -> Dict[str, Any]: - """Gather contextual information from JIRA issues to improve commit - messages. - - This function processes a list of JIRA issue keys, retrieves detailed - context for each issue, and aggregates it into a dictionary that can be - used to enhance commit messages. It first retrieves the primary issue - (the first key in the list) and then gathers basic details for any - related issues. The resulting context includes information from both the - primary and related issues, along with all issue keys. - + """Gather contextual information from JIRA issues to improve commit messages. + + This function processes a list of JIRA issue keys, retrieves detailed context for each issue, and aggregates it into a + dictionary that can be used to enhance commit messages. It first retrieves the primary issue (the first key in the list) + and then gathers basic details for any related issues. The resulting context includes information from both the primary + and related issues, along with all issue keys. + Args: issue_keys: List of JIRA issue keys to gather information from - + Returns: Dict containing business and technical context from the issues """ @@ -375,17 +363,15 @@ def get_commit_context_from_issues(self, issue_keys: List[str]) -> Dict[str, Any return context def enhance_commit_message(self, title: str, description: str, issue_keys: List[str]) -> tuple: - """Enhance a commit message with business and technical context from JIRA - issues. - + """Enhance a commit message with business and technical context from JIRA issues. + Args: title (str): Original commit title. description (str): Original commit description. issue_keys (List[str]): List of JIRA issue keys to include in the enhanced commit message. - + Returns: - tuple: A tuple containing the enhanced commit title and description with added - context from JIRA issues. + tuple: A tuple containing the enhanced commit title and description with added context from JIRA issues. """ if not issue_keys or not self.is_connected(): return title, description diff --git a/penify_hook/llm_client.py b/penify_hook/llm_client.py index e5fe2b2..e7ad94c 100644 --- a/penify_hook/llm_client.py +++ b/penify_hook/llm_client.py @@ -10,15 +10,17 @@ class LLMClient: """ def __init__(self, model: str = None, api_base: str = None, api_key: str = None): - """ - Initialize the LLM client. + # Configure litellm if parameters are provided + """Initialize the LLM client. + + This function configures and initializes the LLM client with the provided model, API base URL, and API key. If any of + these parameters are provided, they will be used to set environment variables for interacting with the LLM service. Args: - model: LLM model to use (e.g., "gpt-4", "ollama/llama2", etc.) - api_base: Base URL for API requests (e.g., "http://localhost:11434" for Ollama) - api_key: API key for the LLM service - """ - # Configure litellm if parameters are provided + model (str?): The LLM model to use (e.g., "gpt-4", "ollama/llama2", etc.). Defaults to None. + api_base (str?): The base URL for API requests (e.g., "http://localhost:11434" for Ollama). Defaults to None. + api_key (str?): The API key for the LLM service. Defaults to None. + """ self.model = model if api_base: os.environ["OPENAI_API_BASE"] = api_base @@ -26,28 +28,24 @@ def __init__(self, model: str = None, api_base: str = None, api_key: str = None) os.environ["OPENAI_API_KEY"] = api_key def generate_commit_summary(self, diff: str, message: str, generate_description: bool, repo_details: Dict, jira_context: Dict = None) -> Dict: - """Generate a commit summary using the LLM. - - This function generates a concise and descriptive commit summary based - on the provided Git diff, user instructions, repository details, and - optional JIRA context. It constructs a prompt for the LLM to produce a - commit title and an optional detailed description, adhering to Semantic - Commit Messages guidelines. If the JIRA context is provided, it enriches - the prompt with relevant issue information. - + """Generate a concise and descriptive commit summary using the LLM. + + This function generates a concise and descriptive commit summary based on the provided Git diff, user instructions, + repository details, and optional JIRA context. It constructs a prompt for the LLM to produce a commit title and an + optional detailed description, adhering to Semantic Commit Messages guidelines. If the JIRA context is provided, it + enriches the prompt with relevant issue information. + Args: diff (str): Git diff of changes. message (str): User-provided commit message or instructions. - generate_description (bool): Flag indicating whether to include a detailed description in the - summary. + generate_description (bool): Flag indicating whether to include a detailed description in the summary. repo_details (Dict): Details about the repository. - jira_context (Dict?): Optional JIRA issue context to enhance the summary. - + jira_context (Dict?): Optional JIRA issue context to enhance the summary. Defaults to None. + Returns: - Dict: A dictionary containing the title and description for the commit. If - generate_description is False, - the 'description' key may be absent. - + Dict: A dictionary containing the title and description for the commit. If generate_description is False, + the 'description' key may be absent. + Raises: ValueError: If the LLM model is not configured. """ diff --git a/penify_hook/login_command.py b/penify_hook/login_command.py index 2d97cc3..31d8bd2 100644 --- a/penify_hook/login_command.py +++ b/penify_hook/login_command.py @@ -1,22 +1,29 @@ def setup_login_parser(parser): + """Setup and configure the argument parser for the login command. + + This function adds necessary arguments to the provided `parser` object, specifically for handling login operations via + API tokens. The parser is expected to be configured with additional arguments as required for a complete login command. + + Args: + parser (argparse.ArgumentParser): The argument parser object to which login-specific arguments will be added. + """ parser.add_argument("--token", help="Specify API token directly") # Add all other necessary arguments for login command def handle_login(args): - """Handle the login command. - - Initiates a user login process by calling the `login` function from the - `penify_hook.commands.auth_commands` module using predefined constants - `API_URL` and `DASHBOARD_URL` from the `penify_hook.constants` module. + """Handle the login command. + + Initiates a user login process by calling the `login` function from the `penify_hook.commands.auth_commands` module + using predefined constants `API_URL` and `DASHBOARD_URL` from the `penify_hook.constants` module. + Args: args (argparse.Namespace): Parsed arguments containing necessary parameters for the login command. - + Returns: None: This function does not return any value; it is expected to handle the login process internally. """ - from penify_hook.constants import API_URL, DASHBOARD_URL from penify_hook.commands.auth_commands import login diff --git a/penify_hook/main.py b/penify_hook/main.py index 2f4312f..ee7797e 100644 --- a/penify_hook/main.py +++ b/penify_hook/main.py @@ -4,19 +4,16 @@ def main(): - """Main function to handle command-line interface (CLI) interactions with - Penify services. - - This tool provides a command-line interface for generating smart commit - messages, configuring local-LLM and JIRA, and generating code - documentation. It supports basic commands that do not require login and - advanced commands that require user authentication. The `--version` flag - can be used to display the version information. + """Main function to handle command-line interface (CLI) interactions with Penify services. + + This tool provides a comprehensive command-line interface for generating smart commit messages, configuring local-LLM + and JIRA, and generating code documentation. It supports both basic commands that do not require login and advanced + commands that require user authentication. The `--version` flag can be used to display the version information. + Returns: int: Exit status of the program (0 for success, 1 for error). """ - parser = argparse.ArgumentParser( description="""Penify CLI tool for: 1. AI commit message generation with JIRA integration to enhance commit messages. diff --git a/penify_hook/ui_utils.py b/penify_hook/ui_utils.py index 5fce269..3a60297 100644 --- a/penify_hook/ui_utils.py +++ b/penify_hook/ui_utils.py @@ -27,10 +27,10 @@ def format_info(message): """Format an informational message with appropriate color. - + Args: message (str): The text of the informational message to be formatted. - + Returns: str: The formatted informational message with the specified color. """ @@ -38,15 +38,14 @@ def format_info(message): def format_success(message): """Format a success message with appropriate color. - - This function takes a message as input and wraps it in ANSI escape codes - to display it in green, indicating a successful operation. The - Style.RESET_ALL is applied at the end to ensure that any subsequent text - is displayed in the default style. - + + This function takes a message as input and wraps it in ANSI escape codes to display it in green, indicating a successful + operation. The `Style.RESET_ALL` is applied at the end to ensure that any subsequent text is displayed in the default + style. + Args: message (str): The message to be formatted as a success message. - + Returns: str: The formatted success message with green color and reset style. """ @@ -54,10 +53,13 @@ def format_success(message): def format_warning(message): """Format a warning message with appropriate color. - + + This function takes a warning message as input and returns it formatted with the specified color using ANSI escape + codes. + Args: message (str): The warning message to be formatted. - + Returns: str: The formatted warning message with the specified color. """ @@ -65,26 +67,25 @@ def format_warning(message): def format_error(message): """Format an error message with appropriate color. - - This function takes a plain error message and wraps it in ANSI escape - codes to apply the specified error color, ensuring that the error - message is visually distinct when output. The function supports various - error colors defined by constants like `ERROR_COLOR`. - + + Takes a plain text error message and wraps it in ANSI escape codes to apply the specified error color, ensuring that the + error message is visually distinct when output. The function supports various error colors defined by constants like + `ERROR_COLOR`. + Args: message (str): The plain text error message to be formatted. - + Returns: str: The formatted error message with the error color applied. """ return f"{ERROR_COLOR}{message}{Style.RESET_ALL}" def format_highlight(message): - """Format a highlighted message with appropriate color. - + """Highlight a message with an appropriate color. + Args: message (str): The message to be formatted and highlighted. - + Returns: str: The formatted message with applied highlight style. """ @@ -92,14 +93,13 @@ def format_highlight(message): def format_file_path(file_path): """Format a file path with appropriate color. - - This function takes a file path as input and wraps it in ANSI escape - codes to apply a warning color. The original file path is then reset to - default style using Style.RESET_ALL. - + + This function takes a file path as input and wraps it in ANSI escape codes to apply a warning color. The original file + path is then reset to default style using Style.RESET_ALL. + Args: file_path (str): The file path to be formatted. - + Returns: str: The formatted file path with the warning color applied. """ @@ -107,11 +107,10 @@ def format_file_path(file_path): def print_info(message): """Print an informational message with appropriate formatting. - - This function takes a string message as input and prints it in a - formatted manner. It utilizes the `format_info` function to apply any - necessary formatting before printing. - + + This function takes a string message as input and prints it in a formatted manner. It utilizes the `format_info` + function to apply any necessary formatting before printing. + Args: message (str): The message to be printed. """ @@ -119,11 +118,10 @@ def print_info(message): def print_success(message): """Print a formatted success message. - - This function takes a string `message` and prints it as a formatted - success message. The formatting includes adding a prefix "Success: " to - the message and enclosing it within asterisks for emphasis. - + + This function takes a string `message` and prints it as a formatted success message. The formatting includes adding a + prefix "Success: " to the message and enclosing it within asterisks for emphasis. + Args: message (str): The message to be printed as a success message. """ @@ -131,11 +129,10 @@ def print_success(message): def print_warning(message): """Print a warning message with appropriate formatting. - - This function takes a warning message as input and prints it with - formatted output. The formatting may include color, timestamp, or other - styles to emphasize that it is a warning. - + + This function takes a warning message as input and prints it with formatted output. The formatting may include color, + timestamp, or other styles to emphasize that it is a warning. + Args: message (str): The warning message to be printed. """ @@ -143,11 +140,10 @@ def print_warning(message): def print_error(message): """Print an error message with appropriate formatting. - - This function takes a string message, formats it as an error message, - and then prints it. The formatting typically includes prefixing the - message with "Error: " to clearly indicate that it is an error. - + + This function takes a string message, formats it as an error message, and then prints it. The formatting typically + includes prefixing the message with "Error: " to clearly indicate that it is an error. + Args: message (str): The error message to be printed. """ @@ -155,11 +151,10 @@ def print_error(message): def print_processing(file_path): """Print a processing message for a specified file. - - This function takes a file path, formats it using `format_file_path`, - and then prints a formatted message indicating that the file is being - processed. The formatted path is highlighted using `format_highlight`. - + + This function takes a file path, formats it using `format_file_path`, and then prints a formatted message indicating + that the file is being processed. The formatted path is highlighted using `format_highlight`. + Args: file_path (str): The path of the file to be processed. """ @@ -168,12 +163,10 @@ def print_processing(file_path): def print_status(status, message): """Print a status message with an appropriate symbol. - - This function takes a status and a message, then prints them with a - colored symbol that corresponds to the given status. The available - statuses are 'success', 'warning', 'error', and any other value will - default to a processing indicator. - + + This function takes a status and a message, then prints them with a colored symbol that corresponds to the given status. + The available statuses are 'success', 'warning', 'error', and any other value will default to a processing indicator. + Args: status (str): The status type ('success', 'warning', 'error') or another string. message (str): The message to be displayed along with the symbol. @@ -189,12 +182,12 @@ def print_status(status, message): def create_progress_bar(total, desc="Processing", unit="item"): """Create a tqdm progress bar with consistent styling. - + Args: total (int): Total number of items to process. desc (str): Description for the progress bar. Defaults to "Processing". unit (str): Unit label for the progress items. Defaults to "item". - + Returns: tqdm: A configured tqdm progress bar instance. """ @@ -207,17 +200,15 @@ def create_progress_bar(total, desc="Processing", unit="item"): ) def create_stage_progress_bar(stages, desc="Processing"): - """Create a tqdm progress bar for processing stages with consistent - styling. - - This function initializes and returns a tqdm progress bar object for - tracking the progress through a series of stages. It also provides a - description for the progress bar to enhance its usability. - + """Create a tqdm progress bar for processing stages with consistent styling. + + This function initializes and returns a tqdm progress bar object for tracking the progress through a series of stages. + It also provides a description for the progress bar to enhance its usability. + Args: stages (list): A list of strings representing individual stages in the process. desc (str?): A description for the progress bar. Defaults to "Processing". - + Returns: tuple: A tuple containing the tqdm progress bar object and the list of stages. """ @@ -231,18 +222,17 @@ def create_stage_progress_bar(stages, desc="Processing"): return pbar, stages def update_stage(pbar, stage_name): + # Force refresh with a custom description and ensure it's visible """Update the progress bar with a new stage name. - - This function updates the provided tqdm progress bar to reflect the - current stage of a process. It clears any existing postfix and sets a - new description based on the provided stage name. The display is then - refreshed to ensure that the update is visible immediately. - + + This function updates the provided tqdm progress bar to reflect the current stage of a process. It clears any existing + postfix and sets a new description based on the provided stage name. The display is then refreshed to ensure that the + update is visible immediately. + Args: pbar (tqdm): The progress bar object to be updated. stage_name (str): A string representing the current stage of the process. """ - # Force refresh with a custom description and ensure it's visible pbar.set_postfix_str("") # Clear any existing postfix pbar.set_description_str(f"{format_info(stage_name)}") pbar.refresh() # Force refresh the display diff --git a/tests/test_commit_commands.py b/tests/test_commit_commands.py index daf4b0f..fc6eaa0 100644 --- a/tests/test_commit_commands.py +++ b/tests/test_commit_commands.py @@ -9,17 +9,15 @@ class TestCommitCommands: @pytest.fixture def mock_api_client(self): - """Mocks an instance of APIClient using unittest.mock. - - This function creates a mock object for APIClient and yields it along - with the mocked instance. It is useful for testing purposes where real - API calls should be avoided. + """Mocks an instance of APIClient using unittest.mock. + + This function creates a mock object for APIClient and yields it along with the mocked instance. It is useful for testing + purposes where real API calls should be avoided. + Yields: - tuple: A tuple containing the mock of APIClient and the mocked instance of - APIClient. + tuple: A tuple containing the mock of APIClient and the mocked instance of APIClient. """ - with patch('penify_hook.api_client.APIClient', create=True) as mock: api_client_instance = MagicMock() mock.return_value = api_client_instance @@ -27,19 +25,18 @@ def mock_api_client(self): @pytest.fixture def mock_llm_client(self): - """Mock an instance of LLMClient for testing purposes. - - This function yields a mock object representing an instance of - LLMClient, which can be used to simulate interactions with a language - model during testing. The mock is patched to replace the actual - LLMClient class from the penify_hook module. + """Mock an instance of LLMClient for testing purposes. + + This function yields a mock object representing an instance of LLMClient, which can be used to simulate interactions + with a language model during testing. The mock is patched to replace the actual LLMClient class from the penify_hook + module. + Yields: tuple: A tuple containing two elements: - mock (MagicMock): The mock object for LLMClient. - llm_client_instance (MagicMock): An instance of the mocked LLMClient. """ - with patch('penify_hook.llm_client.LLMClient', create=True) as mock: llm_client_instance = MagicMock() mock.return_value = llm_client_instance @@ -47,18 +44,16 @@ def mock_llm_client(self): @pytest.fixture def mock_jira_client(self): - """Create a mock JIRA client for testing purposes. - - This function yields a tuple containing a mock JIRA client instance and - its `is_connected` method. The mock client is configured to simulate an - active connection. This is useful for unit tests that require - interaction with a JIRA client without making actual network calls. + """Create a mock JIRA client for testing purposes. + + This function yields a tuple containing a mock JIRA client instance and its `is_connected` method. The mock client is + configured to simulate an active connection, making it useful for unit tests that require interaction with a JIRA client + without making actual network calls. + Yields: - tuple: A tuple containing the mocked JIRA client instance and its - `is_connected` method. + tuple: A tuple containing the mocked JIRA client instance and its `is_connected` method. """ - with patch('penify_hook.jira_client.JiraClient', create=True) as mock: jira_instance = MagicMock() jira_instance.is_connected.return_value = True @@ -67,22 +62,18 @@ def mock_jira_client(self): @pytest.fixture def mock_commit_doc_gen(self): - """Mocks the CommitDocGenHook class and returns a MagicMock instance. - - This function uses the `patch` decorator from the `unittest.mock` module - to create a mock of the `CommitDocGenHook` class. It then sets up this - mock to return a new `MagicMock` instance when invoked. The function - yields both the mock object and the mocked instance, allowing for easy - testing of functions that rely on `CommitDocGenHook`. + """Mocks the CommitDocGenHook class and returns a MagicMock instance. + + This function uses the `patch` decorator from the `unittest.mock` module to create a mock of the `CommitDocGenHook` + class. It then sets up this mock to return a new `MagicMock` instance when invoked. The function yields both the mock + object and the mocked instance, allowing for easy testing of functions that rely on `CommitDocGenHook`. + Returns: tuple: A tuple containing two elements: - - mock (patch): The patch object used to mock the `CommitDocGenHook` - class. - - doc_gen_instance (MagicMock): The mocked instance of - `CommitDocGenHook`. + - mock (patch): The patch object used to mock the `CommitDocGenHook` class. + - doc_gen_instance (MagicMock): The mocked instance of `CommitDocGenHook`. """ - with patch('penify_hook.commit_analyzer.CommitDocGenHook', create=True) as mock: doc_gen_instance = MagicMock() mock.return_value = doc_gen_instance @@ -90,39 +81,34 @@ def mock_commit_doc_gen(self): @pytest.fixture def mock_git_folder_search(self): - """Mock the `recursive_search_git_folder` function to return a predefined - git folder path. - - This function uses the `patch` decorator from the `unittest.mock` module - to intercept calls to `penify_hook.utils.recursive_search_git_folder`. - When called, it will return '/mock/git/folder' instead of performing an - actual search. This is useful for testing purposes where you need a - consistent response without interacting with the file system. + """Mock the `recursive_search_git_folder` function to return a predefined git folder path. + + This function uses the `patch` decorator from the `unittest.mock` module to intercept calls to + `penify_hook.utils.recursive_search_git_folder`. When called, it will return '/mock/git/folder' instead of performing an + actual search. This is useful for testing purposes where you need a consistent response without interacting with the + file system. + Yields: MagicMock: A mock object that simulates the `recursive_search_git_folder` function. """ - with patch('penify_hook.utils.recursive_search_git_folder', create=True) as mock: mock.return_value = '/mock/git/folder' yield mock @pytest.fixture def mock_print_functions(self): - """Mocks the print functions from `penify_hook.ui_utils` for testing - purposes. - - This function uses Python's `unittest.mock.patch` to replace the actual - print functions (`print`, `print_warning`, and `print_error`) with mock - objects. These mock objects can be used in tests to capture calls made - to these print functions without actually printing anything. + """Mocks the print functions from `penify_hook.ui_utils` for testing purposes. + + This function uses Python's `unittest.mock.patch` to replace the actual print functions (`print`, `print_warning`, and + `print_error`) with mock objects. These mock objects can be used in tests to capture calls made to these print + functions without actually printing anything. + Yields: tuple: A tuple containing three mock objects corresponding to `print_info`, - `print_warning`, - and `print_error`. + `print_warning`, and `print_error`. """ - with patch('penify_hook.ui_utils.print_info', create=True) as mock_info, \ patch('penify_hook.ui_utils.print_warning', create=True) as mock_warning, \ patch('penify_hook.ui_utils.print_error', create=True) as mock_error: @@ -138,12 +124,13 @@ def mock_print_functions(self): def test_commit_code_with_llm_client(self, mock_error, mock_warning, mock_info, mock_git_folder_search, mock_doc_gen, mock_llm_client, mock_api_client): - """Test committing code using an LLM client. - - This function sets up mock objects for various components and then calls - the `commit_code` function with specified parameters. It verifies that - the correct mocks are created and called with the appropriate arguments. + # Setup mocks + """Test committing code using an LLM client. + + This function sets up mock objects for various components and then calls the `commit_code` function with specified + parameters. It verifies that the correct mocks are created and called with the appropriate arguments. + Args: mock_error (MagicMock): Mock object for error handling. mock_warning (MagicMock): Mock object for warning logging. @@ -153,8 +140,6 @@ def test_commit_code_with_llm_client(self, mock_error, mock_warning, mock_info, mock_llm_client (MagicMock): Mock object for LLM client interaction. mock_api_client (MagicMock): Mock object for API client interaction. """ - - # Setup mocks api_instance = MagicMock() mock_api_client.return_value = api_instance @@ -199,15 +184,15 @@ def test_commit_code_with_llm_client(self, mock_error, mock_warning, mock_info, def test_commit_code_with_jira_client(self, mock_error, mock_warning, mock_info, mock_git_folder_search, mock_doc_gen, mock_jira_client, mock_llm_client, mock_api_client): - """Test committing code using a JIRA client. - - This function tests the commit_code function with various parameters, - including API and JIRA credentials. It sets up mock objects for - dependencies such as the JIRA client, LLM client, and doc generator to - simulate the behavior of the real classes. The function then calls - commit_code and verifies that the JIRA client and doc generator are - called with the correct parameters. + # Setup mocks + """Test committing code using a JIRA client. + + This function tests the commit_code function with various parameters, including API and JIRA credentials. It sets up + mock objects for dependencies such as the JIRA client, LLM client, and doc generator to simulate the behavior of the + real classes. The function then calls commit_code and verifies that the JIRA client and doc generator are called with + the correct parameters. + Args: mock_error (MagicMock): A MagicMock object for simulating error logging. mock_warning (MagicMock): A MagicMock object for simulating warning logging. @@ -218,8 +203,6 @@ def test_commit_code_with_jira_client(self, mock_error, mock_warning, mock_info, mock_llm_client (MagicMock): A MagicMock object for simulating the LLM client class. mock_api_client (MagicMock): A MagicMock object for simulating the API client class. """ - - # Setup mocks api_instance = MagicMock() mock_api_client.return_value = api_instance @@ -268,14 +251,14 @@ def test_commit_code_with_jira_client(self, mock_error, mock_warning, mock_info, def test_commit_code_with_jira_connection_failure(self, mock_error, mock_warning, mock_info, mock_git_folder_search, mock_doc_gen, mock_jira_client, mock_api_client): - """Test the commit_code function when JIRA connection fails. - - This function tests the scenario where the JIRA connection fails during - a code commit. It sets up various mocks to simulate different components - of the system and then calls the `commit_code` function with specific - parameters. The function is expected to handle the JIRA connection - failure gracefully by logging an appropriate warning. + # Setup mocks + """Test the commit_code function when JIRA connection fails. + + This function tests the scenario where the JIRA connection fails during a code commit. It sets up various mocks to + simulate different components of the system and then calls the `commit_code` function with specific parameters. The + function is expected to handle the JIRA connection failure gracefully by logging an appropriate warning. + Args: mock_error (MagicMock): Mock for error logging. mock_warning (MagicMock): Mock for warning logging. @@ -285,8 +268,6 @@ def test_commit_code_with_jira_connection_failure(self, mock_error, mock_warning mock_jira_client (MagicMock): Mock for creating a JIRA client. mock_api_client (MagicMock): Mock for creating an API client. """ - - # Setup mocks api_instance = MagicMock() mock_api_client.return_value = api_instance @@ -322,25 +303,21 @@ def test_commit_code_with_jira_connection_failure(self, mock_error, mock_warning @patch('builtins.print') def test_commit_code_error_handling(self, mock_print, mock_exit, mock_git_folder_search, mock_doc_gen, mock_api_client): - """Test the error handling in the test_commit_code function. - - This function sets up mocks to simulate exceptions and test the error - handling of the commit_code function. It verifies that the function - correctly prints an error message and exits with a status code of 1 when - an exception occurs during documentation generation. + # Setup mocks + """Test the error handling in the test_commit_code function. + + This function sets up mocks to simulate exceptions and test the error handling of the commit_code function. It verifies + that the function correctly prints an error message and exits with a status code of 1 when an exception occurs during + documentation generation. + Args: mock_print (MagicMock): Mock for the print function, used to verify error message output. mock_exit (MagicMock): Mock for the sys.exit function, used to verify exit behavior. - mock_git_folder_search (MagicMock): Mock for the git_folder_search function, returning a mock Git folder - path. - mock_doc_gen (MagicMock): Mock for the doc_gen function, simulating an exception during - documentation generation. - mock_api_client (MagicMock): Mock for the API client class, not directly used but referenced in the - function signature. + mock_git_folder_search (MagicMock): Mock for the git_folder_search function, returning a mock Git folder path. + mock_doc_gen (MagicMock): Mock for the doc_gen function, simulating an exception during documentation generation. + mock_api_client (MagicMock): Mock for the API client class, not directly used but referenced in the function signature. """ - - # Setup mocks mock_doc_gen.side_effect = Exception("Test error") mock_git_folder_search.return_value = '/mock/git/folder' @@ -357,20 +334,17 @@ def test_commit_code_error_handling(self, mock_print, mock_exit, mock_exit.assert_called_once_with(1) def test_setup_commit_parser(self): - """Set up the argument parser for the commit command. - - This function configures an argument parser to handle various options - for committing changes. It adds three arguments: - '-m' or '--message': - An optional argument to specify a contextual commit message with a - default value of "N/A". - '-e' or '--terminal': A boolean flag to open - an edit terminal before committing. - '-d' or '--description': A boolean - flag that, when set to False, indicates the generation of a commit - message with title and description. + """Set up the argument parser for the commit command. + + This function configures an argument parser to handle various options for committing changes. It adds three arguments: + - '-m' or '--message': An optional argument to specify a contextual commit message with a default value of "N/A". - '-e' + or '--terminal': A boolean flag to open an edit terminal before committing. - '-d' or '--description': A boolean flag + that, when set to False, indicates the generation of a commit message with title and description. + Args: parser (MagicMock): The argument parser to be configured. """ - parser = MagicMock() setup_commit_parser(parser) @@ -388,13 +362,14 @@ def test_setup_commit_parser(self): @patch('penify_hook.constants.API_URL', "http://api.example.com") def test_handle_commit(self, mock_print_info, mock_commit_code, mock_get_token, mock_get_llm_config, mock_get_jira_config): - """Test the handle_commit function with various mock objects. - - This function sets up mocks for retrieving LLM configuration, JIRA - configuration, and commit code. It then creates an argument object and - calls the handle_commit function. Finally, it verifies that the mock - functions were called with the expected arguments. + # Setup mocks + """Test the handle_commit function with various mock objects. + + This function sets up mocks for retrieving LLM configuration, JIRA configuration, and commit code. It then creates an + argument object and calls the handle_commit function. Finally, it verifies that the mock functions were called with the + expected arguments. + Args: mock_print_info (MagicMock): Mock object for printing information. mock_commit_code (MagicMock): Mock object for committing code. @@ -402,8 +377,6 @@ def test_handle_commit(self, mock_print_info, mock_commit_code, mock_get_token, mock_get_llm_config (MagicMock): Mock object for retrieving LLM configuration. mock_get_jira_config (MagicMock): Mock object for retrieving JIRA configuration. """ - - # Setup mocks mock_get_llm_config.return_value = { 'model': 'test-model', 'api_base': 'http://llm-api.example.com', diff --git a/tests/test_config_commands.py b/tests/test_config_commands.py index 995f5ae..68b0274 100644 --- a/tests/test_config_commands.py +++ b/tests/test_config_commands.py @@ -20,20 +20,18 @@ class TestConfigCommands: @patch('os.makedirs') @patch('builtins.open', new_callable=mock_open) def test_get_penify_config_existing_dir(self, mock_file_open, mock_makedirs, mock_path, mock_git_folder): - """Test the get_penify_config function when the .penify config directory - exists. - - It should not create a new directory and assert that all mocked - functions were called correctly. + # Mock git folder search + """Test the get_penify_config function when the .penify config directory exists. + + It should not create a new directory and assert that all mocked functions were called correctly. + Args: mock_file_open (MagicMock): A MagicMock object simulating the open() function. mock_makedirs (MagicMock): A MagicMock object simulating the os.makedirs() function. mock_path (MagicMock): A MagicMock object simulating the Path class from pathlib module. mock_git_folder (MagicMock): A MagicMock object simulating the git_folder_search() function. """ - - # Mock git folder search mock_git_folder.return_value = '/mock/git/folder' # Mock Path operations @@ -58,22 +56,19 @@ def test_get_penify_config_existing_dir(self, mock_file_open, mock_makedirs, moc @patch('os.makedirs') @patch('builtins.open', new_callable=mock_open) def test_get_penify_config_new_dir(self, mock_file_open, mock_makedirs, mock_path, mock_git_folder): - """Test the behavior of get_penify_config when the .penify directory does - not exist. - - This function mocks various system calls to simulate a scenario where - the .penify directory is not present. It then asserts that the - appropriate actions are taken to create the directory and write an empty - JSON file. + # Mock git folder search + """Test the behavior of get_penify_config when the .penify directory does not exist. + + Mock various system calls to simulate a scenario where the .penify directory is not present. Assert that the appropriate + actions are taken to create the directory and write an empty JSON file. + Args: mock_file_open (MagicMock): A MagicMock object simulating the `open` function. mock_makedirs (MagicMock): A MagicMock object simulating the `os.makedirs` function. mock_path (MagicMock): A MagicMock object simulating the `Path` class from `pathlib`. mock_git_folder (MagicMock): A MagicMock object simulating a git folder search function. """ - - # Mock git folder search mock_git_folder.return_value = '/mock/git/folder' # Mock Path operations @@ -95,20 +90,18 @@ def test_get_penify_config_new_dir(self, mock_file_open, mock_makedirs, mock_pat @patch('penify_hook.commands.config_commands.get_penify_config') @patch('builtins.open', new_callable=mock_open, read_data='{"llm": {"model": "gpt-4", "api_base": "https://api.openai.com", "api_key": "test-key"}}') def test_get_llm_config_exists(self, mock_file_open, mock_get_config): - """Test the get_llm_config function when the configuration file exists. - - This function sets up a mock configuration file that exists and returns - it when called. It then calls the get_llm_config function and asserts - that it returns the correct configuration dictionary. Additionally, it - checks that the mock_file_open function was called with the correct - arguments. + # Setup mock + """Test the get_llm_config function when the configuration file exists. + + This function sets up a mock configuration file that exists and returns it when called. It then calls the get_llm_config + function and asserts that it returns the correct configuration dictionary. Additionally, it checks that the + mock_file_open function was called with the correct arguments. + Args: mock_file_open (MagicMock): A mock for the open() function. mock_get_config (MagicMock): A mock for the get_config() function. """ - - # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True mock_get_config.return_value = mock_config_file @@ -127,20 +120,18 @@ def test_get_llm_config_exists(self, mock_file_open, mock_get_config): @patch('penify_hook.commands.config_commands.get_penify_config') @patch('builtins.open', new_callable=mock_open, read_data='{}') def test_get_llm_config_empty(self, mock_file_open, mock_get_config): - """Test the behavior of get_llm_config when called with an empty - configuration file. - - This function sets up a mock configuration file that exists but returns - no content. It then calls the `get_llm_config` function and asserts that - it returns an empty dictionary and that the file open method was called - exactly once with the correct arguments. + # Setup mock + """Test the behavior of get_llm_config when called with an empty configuration file. + + This function sets up a mock configuration file that exists but returns no content. It then calls the `get_llm_config` + function and asserts that it returns an empty dictionary and that the file open method was called exactly once with the + correct arguments. + Args: mock_file_open (MagicMock): A MagicMock object simulating the built-in open function. mock_get_config (MagicMock): A MagicMock object simulating the get_config function. """ - - # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True mock_get_config.return_value = mock_config_file @@ -156,21 +147,13 @@ def test_get_llm_config_empty(self, mock_file_open, mock_get_config): @patch('builtins.open', new_callable=mock_open, read_data='invalid json') @patch('builtins.print') def test_get_llm_config_invalid_json(self, mock_print, mock_file_open, mock_get_config): - """Test function to verify the behavior of get_llm_config when reading an - invalid JSON file. - - It sets up a mock configuration file that exists but contains invalid - JSON. The function is expected to handle this gracefully by printing an - error message and returning an empty dictionary. - - Args: - mock_print (MagicMock): Mock for the print function. - mock_file_open (MagicMock): Mock for the open function. - mock_get_config (MagicMock): Mock for the get_config function, which returns the mock configuration - file. - """ # Setup mock + """Test function to verify the behavior of get_llm_config when reading an invalid JSON file. + + It sets up a mock configuration file that exists but contains invalid JSON. The function is expected to handle this + gracefully by printing an error message and returning an empty dictionary. + """ mock_config_file = MagicMock() mock_config_file.exists.return_value = True mock_get_config.return_value = mock_config_file @@ -186,25 +169,21 @@ def test_get_llm_config_invalid_json(self, mock_print, mock_file_open, mock_get_ @patch('penify_hook.commands.config_commands.get_penify_config') @patch('builtins.open', new_callable=mock_open, read_data='{"jira": {"url": "https://jira.example.com", "username": "user", "api_token": "token"}}') def test_get_jira_config_exists(self, mock_file_open, mock_get_config): - """Test that get_jira_config returns the correct JIRA configuration when - the configuration file exists. - - It sets up a mock for the configuration file to simulate its existence - and verifies that the function reads from the correct file and returns - the expected JIRA configuration dictionary. Additionally, it checks that - the mock file open is called with the appropriate arguments. + # Setup mock + """Test that get_jira_config returns the correct JIRA configuration when + the configuration file exists. This function sets up a mock for the configuration file to simulate its existence and + verifies that the function reads from the correct file and returns the expected JIRA configuration dictionary. It also + checks that the mock file open is called with the appropriate arguments. + Args: mock_file_open (MagicMock): A mock for the `open` function. mock_get_config (MagicMock): A mock for the `get_config` function, which is expected to return a mock configuration file object. - + Returns: - None: This test function does not explicitly return anything. Its assertions - serve as the verification of its correctness. + None: This test function does not explicitly return anything. Its assertions serve as the verification of its correctness. """ - - # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True mock_get_config.return_value = mock_config_file @@ -225,21 +204,20 @@ def test_get_jira_config_exists(self, mock_file_open, mock_get_config): @patch('json.dump') @patch('builtins.print') def test_save_llm_config_success(self, mock_print, mock_json_dump, mock_file_open, mock_get_config): - """Test the save_llm_config function successfully. - - This function tests that the save_llm_config function correctly saves an - LLM configuration and handles various mock objects and side effects. It - ensures that the function returns True upon successful execution, writes - the expected configuration to a file, and prints a confirmation message. + # Setup mock + """Test the save_llm_config function successfully. + + This function tests that the save_llm_config function correctly saves an LLM configuration and handles various mock + objects and side effects. It ensures that the function returns True upon successful execution, writes the expected + configuration to a file, and prints a confirmation message. + Args: mock_print (MagicMock): A mock object for the print function. mock_json_dump (MagicMock): A mock object for json.dump. mock_file_open (MagicMock): A mock object for file opening. mock_get_config (MagicMock): A mock object to return a configuration file mock. """ - - # Setup mock mock_config_file = MagicMock() mock_get_config.return_value = mock_config_file mock_file_open.return_value.__enter__.return_value = mock_file_open @@ -267,26 +245,22 @@ def test_save_llm_config_success(self, mock_print, mock_json_dump, mock_file_ope @patch('builtins.open', side_effect=IOError("Permission denied")) @patch('builtins.print') def test_save_llm_config_failure(self, mock_print, mock_file_open, mock_get_config): - """Test function to verify that the save_llm_config function returns False - and prints an error message when it fails to save the LLM configuration - due to a permission error. - - It sets up a mock configuration file that exists and calls the - save_llm_config function with valid parameters. The function is expected - to return False and print "Error saving LLM configuration: Permission - denied" in case of a failure. + # Setup mock + """Test function to verify that the save_llm_config function returns False and prints an error message when it fails to + save the LLM configuration due to a permission error. + + It sets up a mock configuration file that exists and calls the save_llm_config function with valid parameters. The + function is expected to return False and print "Error saving LLM configuration: Permission denied" in case of a failure. + Args: self (TestLLMConfig): An instance of the test class. - mock_print (MagicMock): A MagicMock object representing the print function, which will be used - to assert that it was called with the expected error message. - mock_file_open (MagicMock): A MagicMock object representing the open function, which is not used in - this test but is included as a parameter for completeness. - mock_get_config (MagicMock): A MagicMock object representing the get_config function, which will be - used to return the mock configuration file. + mock_print (MagicMock): A MagicMock object representing the print function, which will be used to assert that it was called with the expected + error message. + mock_file_open (MagicMock): A MagicMock object representing the open function, which is not used in this test but is included as a parameter for + completeness. + mock_get_config (MagicMock): A MagicMock object representing the get_config function, which will be used to return the mock configuration file. """ - - # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True mock_get_config.return_value = mock_config_file @@ -303,22 +277,20 @@ def test_save_llm_config_failure(self, mock_print, mock_file_open, mock_get_conf @patch('json.dump') @patch('builtins.print') def test_save_jira_config_success(self, mock_print, mock_json_dump, mock_file_open, mock_path): - """Test the save_jira_config function to ensure it saves JIRA configuration - successfully. - - This function sets up mocks for various dependencies and tests the - functionality of saving a JIRA configuration. It asserts that the - function returns `True`, the JSON dump is called with the correct - configuration, and the print statement contains the expected message. + # Setup mock + """Test the save_jira_config function to ensure it saves JIRA configuration successfully. + + This function sets up mocks for various dependencies and tests the functionality of saving a JIRA configuration. It + asserts that the function returns `True`, the JSON dump is called with the correct configuration, and the print + statement contains the expected message. + Args: mock_print (MagicMock): Mock for the print function. mock_json_dump (MagicMock): Mock for the json.dump function. mock_file_open (MagicMock): Mock for the open function. mock_path (MagicMock): Mock for the path module. """ - - # Setup mock mock_home_dir = MagicMock() mock_path.home.return_value = mock_home_dir mock_home_dir.__truediv__.return_value = mock_home_dir @@ -347,20 +319,13 @@ def test_save_jira_config_success(self, mock_print, mock_json_dump, mock_file_op @patch('penify_hook.commands.config_commands.Path') @patch('builtins.open', new_callable=mock_open, read_data='{"api_keys": "config-token"}') def test_get_token_from_env(self, mock_file_open, mock_path, mock_getenv): - """Test retrieving a token from the environment variable. - - This function tests the behavior of `get_token` when an environment - variable is set. It verifies that if the 'PENIFY_API_TOKEN' environment - variable exists, the function returns its value without attempting to - read a file. - - Args: - mock_file_open (MagicMock): A MagicMock object for simulating file operations. - mock_path (MagicMock): A MagicMock object for simulating path operations. - mock_getenv (MagicMock): A MagicMock object for simulating environment variable retrieval. - """ # Setup mock for env var + """Test retrieving a token from the environment variable. + + This function tests the behavior of `get_token` when an environment variable is set. It verifies that if the + 'PENIFY_API_TOKEN' environment variable exists, the function returns its value without attempting to read a file. + """ mock_getenv.return_value = "env-token" # Call function @@ -376,21 +341,19 @@ def test_get_token_from_env(self, mock_file_open, mock_path, mock_getenv): @patch('penify_hook.commands.config_commands.Path') @patch('builtins.open', new_callable=mock_open, read_data='{"api_keys": "config-token"}') def test_get_token_from_config(self, mock_file_open, mock_path, mock_getenv): - """Test retrieving a token from the configuration. - - This function sets up mocks for environment variables and configuration - files, calls the `get_token` function, and asserts its behavior. It - verifies that when the environment variable is not found, the function - reads a token from a configuration file located in the user's home - directory. + # Setup mock for env var (not found) + """Test retrieving a token from the configuration. + + This function sets up mocks for environment variables and configuration files, calls the `get_token` function, and + asserts its behavior. It verifies that when the environment variable is not found, the function reads a token from a + configuration file located in the user's home directory. + Args: mock_file_open (MagicMock): A mock for the `open` function. mock_path (MagicMock): A mock for the `pathlib.Path` class. mock_getenv (MagicMock): A mock for the `os.getenv` function. """ - - # Setup mock for env var (not found) mock_getenv.return_value = None # Setup mock for config file @@ -411,27 +374,23 @@ def test_get_token_from_config(self, mock_file_open, mock_path, mock_getenv): @patch('penify_hook.commands.config_commands.Path') @patch('builtins.open', new_callable=mock_open, read_data='{"other_key": "value"}') def test_get_token_not_found(self, mock_file_open, mock_path, mock_getenv): - """Test the get_token function when the API token environment variable is - not found. - - This function tests the scenario where the `PENIFY_API_TOKEN` - environment variable is not set. It mocks the environment variable to - return `None`, and verifies that the function returns `None`. The test - also checks that the environment variable is accessed once and that a - file open operation is attempted on a configuration file located in the - user's home directory. + # Setup mock for env var (not found) + """Test the get_token function when the API token environment variable is not found. + + This function tests the scenario where the `PENIFY_API_TOKEN` environment variable is not set. It mocks the environment + variable to return `None`, and verifies that the function returns `None`. The test also checks that the environment + variable is accessed once and that a file open operation is attempted on a configuration file located in the user's home + directory. + Args: mock_file_open (MagicMock): Mock for the built-in `open` function. mock_path (MagicMock): Mock for the `pathlib.Path` module. mock_getenv (MagicMock): Mock for the `os.getenv` function. - + Returns: - None: The function does not return anything; it asserts conditions to verify - correctness. + None: The function does not return anything; it asserts conditions to verify correctness. """ - - # Setup mock for env var (not found) mock_getenv.return_value = None # Setup mock for config file diff --git a/tests/test_doc_commands.py b/tests/test_doc_commands.py index a51ba53..8b1b325 100644 --- a/tests/test_doc_commands.py +++ b/tests/test_doc_commands.py @@ -21,14 +21,14 @@ def test_generate_doc_no_location(mock_getcwd, mock_api_client, mock_folder_analyzer, mock_file_analyzer, mock_git_analyzer): - """Test function to generate documentation without location information. - - This function sets up mocks for the API client, current working - directory, and Git analyzer. It then calls the `generate_doc` function - with a fake API URL and token. The function is expected to initialize - the API client, configure the Git analyzer, and run it without any - location information. + # Setup + """Test function to generate documentation without location information. + + This function sets up mocks for the API client, current working directory, and Git analyzer. It then calls the + `generate_doc` function with a fake API URL and token. The function is expected to initialize the API client, configure + the Git analyzer, and run it without any location information. + Args: mock_getcwd (MagicMock): Mock for os.getcwd(). mock_api_client (MagicMock): Mock for creating an API client. @@ -36,8 +36,6 @@ def test_generate_doc_no_location(mock_getcwd, mock_api_client, mock_file_analyzer (MagicMock): Mock for file analysis. mock_git_analyzer (MagicMock): Mock for Git analyzer setup. """ - - # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance mock_getcwd.return_value = '/fake/current/dir' @@ -61,22 +59,20 @@ def test_generate_doc_no_location(mock_getcwd, mock_api_client, @patch('penify_hook.api_client.APIClient') def test_generate_doc_file_location(mock_api_client, mock_folder_analyzer, mock_file_analyzer, mock_git_analyzer): - """Test generating a documentation file location. - - This function tests the process of generating a documentation file - location using mock objects for API client, folder analyzer, file - analyzer, and Git analyzer. It sets up the necessary mocks, calls the - `generate_doc` function with specified parameters, and asserts that the - appropriate methods on the mock objects are called as expected. + # Setup + """Test generating a documentation file location. + + This function tests the process of generating a documentation file location using mock objects for API client, folder + analyzer, file analyzer, and Git analyzer. It sets up the necessary mocks, calls the `generate_doc` function with + specified parameters, and asserts that the appropriate methods on the mock objects are called as expected. + Args: mock_api_client (MagicMock): Mock object for the API client. mock_folder_analyzer (MagicMock): Mock object for the folder analyzer. mock_file_analyzer (MagicMock): Mock object for the file analyzer. mock_git_analyzer (MagicMock): Mock object for the Git analyzer. """ - - # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance mock_file_instance = MagicMock() @@ -99,21 +95,20 @@ def test_generate_doc_file_location(mock_api_client, mock_folder_analyzer, @patch('penify_hook.api_client.APIClient') def test_generate_doc_folder_location(mock_api_client, mock_folder_analyzer, mock_file_analyzer, mock_git_analyzer): - """Test the function to generate documentation for a folder location. - - It sets up mock objects for API client, folder analyzer, file analyzer, - and Git analyzer, then calls the `generate_doc` function with specified - parameters. Finally, it asserts that the correct methods on the mock - objects were called as expected. + # Setup + """Test the function to generate documentation for a folder location. + + It sets up mock objects for API client, folder analyzer, file analyzer, and Git analyzer, then calls the `generate_doc` + function with specified parameters. Finally, it asserts that the correct methods on the mock objects were called as + expected. + Args: mock_api_client (MagicMock): Mock object for the API client. mock_folder_analyzer (MagicMock): Mock object for the folder analyzer. mock_file_analyzer (MagicMock): Mock object for the file analyzer. mock_git_analyzer (MagicMock): Mock object for the Git analyzer. """ - - # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance mock_folder_instance = MagicMock() @@ -134,27 +129,23 @@ def test_generate_doc_folder_location(mock_api_client, mock_folder_analyzer, @patch('penify_hook.commands.doc_commands.GitDocGenHook') @patch('penify_hook.api_client.APIClient') def test_generate_doc_error_handling(mock_api_client, mock_git_analyzer, mock_exit): - """Generate a documentation string for the provided code snippet using - Google Docstring style. - - Short one line description: Test function to ensure proper error - handling during API calls with GitAnalyzer. Multiline long description: - This test function is designed to verify that the generate_doc function - handles exceptions correctly when an error occurs during API interaction - with GitAnalyzer. It sets up a mock API client and a mock Git analyzer, - causing the analyzer to raise an exception to simulate a failure - condition. The function then asserts that the exit code is set to 1 when - the error handling mechanism is invoked. + # Setup + """Generate a documentation string for the provided code snippet using + Google Docstring style. Short one line description: Test function to ensure proper error handling during API calls with + GitAnalyzer. Multiline long description: This test function is designed to verify that the generate_doc function handles + exceptions correctly when an error occurs during API interaction with GitAnalyzer. It sets up a mock API client and a + mock Git analyzer, causing the analyzer to raise an exception to simulate a failure condition. The function then asserts + that the exit code is set to 1 when the error handling mechanism is invoked. + Args: mock_api_client (MagicMock): A mock object simulating the API client. - mock_git_analyzer (MagicMock): A mock object simulating the Git analyzer, configured to raise an - exception. - mock_exit (MagicMock): A mock object representing the exit function, which should be called - with an error code. + mock_git_analyzer (MagicMock): A mock object simulating the Git analyzer, configured to raise an exception. + mock_exit (MagicMock): A mock object representing the exit function, which should be called with an error code. + + Raises: + AssertionError: If the exit code is not set to 1 when an error occurs during API interaction. """ - - # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance mock_git_analyzer.side_effect = Exception("Test error") @@ -167,13 +158,11 @@ def test_generate_doc_error_handling(mock_api_client, mock_git_analyzer, mock_ex def test_setup_docgen_parser(): - """Test the setup_docgen_parser function to ensure it properly configures - the ArgumentParser for docgen options. - It verifies that the parser correctly sets up docgen options and handles + """Test the setup_docgen_parser function to ensure it properly configures + the ArgumentParser for docgen options. It verifies that the parser correctly sets up docgen options and handles different subcommands like 'install-hook' and 'uninstall-hook'. """ - parser = ArgumentParser() setup_docgen_parser(parser) @@ -199,13 +188,14 @@ def test_setup_docgen_parser(): @patch('sys.exit') def test_handle_docgen_install_hook(mock_exit, mock_get_token, mock_generate_doc, mock_uninstall_hook, mock_install_hook): - """Test the handling of the 'install-hook' subcommand. - - This function sets up a mock environment where it simulates the - execution of the 'install-hook' subcommand. It verifies that the - `mock_install_hook` is called with the correct arguments, while - `mock_generate_doc` and `mock_uninstall_hook` are not called. + # Setup + """Test the handling of the 'install-hook' subcommand. + + This function sets up a mock environment to simulate the execution of the 'install-hook' subcommand. It verifies that + the `mock_install_hook` is called with the correct arguments, while `mock_generate_doc` and `mock_uninstall_hook` are + not called. + Args: mock_exit (MagicMock): Mock object for sys.exit. mock_get_token (MagicMock): Mock object to simulate fetching a token. @@ -213,8 +203,6 @@ def test_handle_docgen_install_hook(mock_exit, mock_get_token, mock_generate_doc mock_uninstall_hook (MagicMock): Mock object to simulate uninstalling a hook. mock_install_hook (MagicMock): Mock object to simulate installing a hook. """ - - # Setup mock_get_token.return_value = 'fake-token' # Test install-hook subcommand @@ -232,11 +220,12 @@ def test_handle_docgen_install_hook(mock_exit, mock_get_token, mock_generate_doc @patch('sys.exit') def test_handle_docgen_uninstall_hook(mock_exit, mock_get_token, mock_generate_doc, mock_uninstall_hook, mock_install_hook): - """Test the uninstall-hook subcommand of the handle_docgen function. - This test case sets up a mock environment and verifies that the - uninstall-hook is called with the correct location, while generate_doc - and install_hook are not called. + # Setup + """Test the uninstall-hook subcommand of the handle_docgen function. + This test case sets up a mock environment and verifies that the uninstall-hook is called with the correct location, + while generate_doc and install_hook are not called. + Args: mock_exit (MagicMock): A mock for the exit function. mock_get_token (MagicMock): A mock for the get_token function. @@ -244,8 +233,6 @@ def test_handle_docgen_uninstall_hook(mock_exit, mock_get_token, mock_generate_d mock_uninstall_hook (MagicMock): A mock for the uninstall_hook function. mock_install_hook (MagicMock): A mock for the install_hook function. """ - - # Setup mock_get_token.return_value = 'fake-token' # Test uninstall-hook subcommand @@ -262,20 +249,19 @@ def test_handle_docgen_uninstall_hook(mock_exit, mock_get_token, mock_generate_d @patch('penify_hook.commands.doc_commands.get_token') def test_handle_docgen_generate(mock_get_token, mock_generate_doc, mock_uninstall_hook, mock_install_hook): - """Test the direct documentation generation functionality. - - This function tests the `handle_docgen` function when no subcommand is - provided. It verifies that the document generation hook is called and - the uninstall and install hooks are not called. + # Setup + """Test the direct documentation generation functionality. + + This function tests the `handle_docgen` function when no subcommand is provided. It verifies that the document + generation hook is called and the uninstall and install hooks are not called. + Args: mock_get_token (MagicMock): Mocked function to get authentication token. mock_generate_doc (MagicMock): Mocked function for generating documentation. mock_uninstall_hook (MagicMock): Mocked function for uninstalling the document generation hook. mock_install_hook (MagicMock): Mocked function for installing the document generation hook. """ - - # Setup mock_get_token.return_value = 'fake-token' # Test direct documentation generation @@ -289,19 +275,17 @@ def test_handle_docgen_generate(mock_get_token, mock_generate_doc, @patch('penify_hook.commands.doc_commands.get_token') @patch('sys.exit') def test_handle_docgen_no_token(mock_exit, mock_get_token): - """Test the behavior of the `handle_docgen` function when no token is - provided. - - This function asserts that if no token is returned by `mock_get_token`, - the `handle_docgen` function will call `mock_exit` with a status code of - 1. + # Test with no token + """Test the behavior of the `handle_docgen` function when no token is provided. + + This function asserts that if no token is returned by `mock_get_token`, the `handle_docgen` function will call + `mock_exit` with a status code of 1. + Args: mock_exit (MagicMock): A MagicMock object simulating the `exit` function. mock_get_token (MagicMock): A MagicMock object simulating the `get_token` function. """ - - # Test with no token mock_get_token.return_value = None args = MagicMock(docgen_subcommand=None, location='doc_location') handle_docgen(args) @@ -311,18 +295,20 @@ def test_handle_docgen_no_token(mock_exit, mock_get_token): @patch('penify_hook.commands.doc_commands.os.getcwd') @patch('penify_hook.api_client.APIClient') def test_generate_doc_with_file_exception(mock_api_client, mock_getcwd): - """Generate documentation from a Python source file. - - This function reads a Python file and generates a docstring based on its - content. It uses mock objects to simulate API calls and directory - operations during testing. + # Setup + """Generate documentation from a Python source file. + + This function reads a Python file and generates a docstring based on its content. It uses mock objects to simulate API + calls and directory operations during testing. + Args: mock_api_client (unittest.mock.MagicMock): A mock object for simulating API client behavior. mock_getcwd (unittest.mock.MagicMock): A mock object for simulating the current working directory function. + + Raises: + SystemExit: If an error occurs while generating documentation, causing the script to exit. """ - - # Setup mock_api_client.side_effect = Exception("API error") mock_getcwd.return_value = '/fake/current/dir' @@ -334,21 +320,22 @@ def test_generate_doc_with_file_exception(mock_api_client, mock_getcwd): @patch('penify_hook.commands.doc_commands.os.getcwd') @patch('penify_hook.api_client.APIClient') def test_generate_doc_with_folder_exception(mock_api_client, mock_getcwd): - """Generate documentation from a given API endpoint and save it to a - folder. - - This function fetches data from the specified API endpoint, processes - it, and saves the generated documentation in the provided folder. If an - error occurs during the fetching process, a SystemExit exception is - raised with an appropriate message. + # Setup + """Generate documentation from a given API endpoint and save it to a folder. + + This function fetches data from the specified API endpoint, processes it, and saves the generated documentation in the + provided folder. If an error occurs during the fetching process, a SystemExit exception is raised with an appropriate + message. + Args: api_url (str): The URL of the API endpoint from which data will be fetched. token (str): The authentication token required to access the API. folder_path (str): The path to the folder where the documentation will be saved. + + Raises: + SystemExit: If an error occurs during the fetching process. """ - - # Setup mock_api_client.side_effect = Exception("API error") mock_getcwd.return_value = '/fake/current/dir' diff --git a/tests/test_web_config.py b/tests/test_web_config.py index c87c87e..7cd9ad6 100644 --- a/tests/test_web_config.py +++ b/tests/test_web_config.py @@ -16,28 +16,31 @@ class TestWebConfig: @patch('socketserver.TCPServer') @patch('pkg_resources.resource_filename') def test_config_llm_web_server_setup(self, mock_resource_filename, mock_server, mock_webbrowser): - """Set up and test the web server configuration for an LLM (Large Language - Model) web interface. - - This function configures a mock web server for testing purposes, - including setting up resource filenames, mocking server behavior, and - verifying that the web browser is opened and the server starts - correctly. The function uses various mocks to simulate external - dependencies such as `resource_filename` and `server`. + # Setup mocks + """Set up and test the web server configuration for an LLM (Large Language Model) web interface. + + This function configures a mock web server for testing purposes, including setting up resource filenames, mocking server + behavior, and verifying that the web browser is opened and the server starts correctly. The function uses various mocks + to simulate external dependencies such as `resource_filename` and `server`. + Args: mock_resource_filename (MagicMock): A MagicMock object simulating the `resource_filename` function. mock_server (MagicMock): A MagicMock object simulating the context manager for the web server. mock_webbrowser (MagicMock): A MagicMock object simulating the `webbrowser` module. """ - - # Setup mocks mock_resource_filename.return_value = 'mock/template/path' mock_server_instance = MagicMock() mock_server.return_value.__enter__.return_value = mock_server_instance # Mock the serve_forever method to stop after being called once def stop_server_after_call(): + """Stops a server instance after it has been called once. + + This function is used to mock the `serve_forever` method, which typically blocks until an explicit call to `shutdown` is + made. By calling `shutdown` within `stop_server_after_call`, the server is instructed to stop after processing its + current request. + """ mock_server_instance.shutdown() mock_server_instance.serve_forever.side_effect = stop_server_after_call @@ -57,27 +60,31 @@ def stop_server_after_call(): @patch('socketserver.TCPServer') @patch('pkg_resources.resource_filename') def test_config_jira_web_server_setup(self, mock_resource_filename, mock_server, mock_webbrowser): - """Test the configuration and setup of a JIRA web server. - - This function tests the entire process of setting up a JIRA web server, - including mocking necessary resources, configuring the server to shut - down after handling one request, and verifying that the web browser is - opened with the correct URL. The function uses several mocks to simulate - external dependencies such as resource files, servers, and web browsers. + # Setup mocks + """Test the configuration and setup of a JIRA web server. + + This function tests the entire process of setting up a JIRA web server, including mocking necessary resources, + configuring the server to shut down after handling one request, and verifying that the web browser is opened with the + correct URL. The function uses several mocks to simulate external dependencies such as resource files, servers, and web + browsers. + Args: mock_resource_filename (MagicMock): A MagicMock object for simulating the `resource_filename` function. mock_server (MagicMock): A MagicMock object for simulating the server setup. mock_webbrowser (MagicMock): A MagicMock object for simulating the web browser opening. """ - - # Setup mocks mock_resource_filename.return_value = 'mock/template/path' mock_server_instance = MagicMock() mock_server.return_value.__enter__.return_value = mock_server_instance # Mock the serve_forever method to stop after being called once def stop_server_after_call(): + """Stops a server instance after it has been called once. + + This function is used to mock the `serve_forever` method of a server, causing it to shut down immediately after being + invoked. + """ mock_server_instance.shutdown() mock_server_instance.serve_forever.side_effect = stop_server_after_call