From 722743c4b4c9b98828f2d8cbb1edc1a40b8b7535 Mon Sep 17 00:00:00 2001 From: "penify-dev[bot]" <146478655+penify-dev[bot]@users.noreply.github.com> Date: Tue, 22 Apr 2025 18:01:49 +0000 Subject: [PATCH 1/2] Generated Documentation --- penify_hook/api_client.py | 184 +++++++---- penify_hook/base_analyzer.py | 22 ++ penify_hook/commands/commit_commands.py | 99 +++--- penify_hook/commands/doc_commands.py | 95 ++++-- penify_hook/commands/hook_commands.py | 55 +++- penify_hook/commit_analyzer.py | 152 ++++++--- penify_hook/config_command.py | 61 ++-- penify_hook/file_analyzer.py | 110 +++++-- penify_hook/folder_analyzer.py | 82 +++-- penify_hook/git_analyzer.py | 146 ++++++--- penify_hook/jira_client.py | 327 ++++++++++++------- penify_hook/llm_client.py | 69 ++-- penify_hook/login_command.py | 51 ++- penify_hook/main.py | 30 +- penify_hook/ui_utils.py | 409 +++++++++++++++++------- 15 files changed, 1298 insertions(+), 594 deletions(-) diff --git a/penify_hook/api_client.py b/penify_hook/api_client.py index 6c527eb..617bedd 100644 --- a/penify_hook/api_client.py +++ b/penify_hook/api_client.py @@ -5,33 +5,54 @@ class APIClient: def __init__(self, api_url, api_token: str = None, bearer_token: str = None): + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. - + dictionary (dict): The processed files map. + Returns: - 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. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ payload = { 'file_path': file_name, @@ -53,25 +74,27 @@ def send_file_for_docstring_generation(self, file_name, content, line_numbers, r raise Exception(f"API Error: {error_message}") 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. - + dictionary (dict): The processed files map. + 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. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ payload = { 'git_diff': git_diff, @@ -100,18 +123,29 @@ 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + Returns: - list[str]: A list of supported file types, either from the API or a default set. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - url = self.api_url+"/v1/file/supported_languages" response = requests.get(url) if response.status_code == 200: @@ -121,20 +155,27 @@ 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, - it falls back to using the API. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - diff (str): The Git diff of changes. - message (str): User-provided commit message or instructions. - generate_description (bool): Flag indicating whether to generate a description for the commit. - 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. - + dictionary (dict): The processed files map. + Returns: - dict: A dictionary containing the title and description for the commit. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ try: return llm_client.generate_commit_summary(diff, message, generate_description, repo_details, jira_context) @@ -144,17 +185,30 @@ 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + Returns: - str: The API key if the request is successful, `None` otherwise. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - 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..11ade0e 100644 --- a/penify_hook/base_analyzer.py +++ b/penify_hook/base_analyzer.py @@ -7,6 +7,28 @@ class BaseAnalyzer: def __init__(self, folder_path: str, api_client: APIClient): + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ 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..b45ece0 100644 --- a/penify_hook/commands/commit_commands.py +++ b/penify_hook/commands/commit_commands.py @@ -8,29 +8,29 @@ 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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_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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - from penify_hook.ui_utils import print_error from penify_hook.utils import recursive_search_git_folder from ..commit_analyzer import CommitDocGenHook @@ -98,18 +98,29 @@ 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - parser (argparse.ArgumentParser): The ArgumentParser object to be configured. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - 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 +137,29 @@ 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - args (argparse.Namespace): The parsed command-line arguments containing options like terminal, - description, message, etc. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - 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..ac03ee2 100644 --- a/penify_hook/commands/doc_commands.py +++ b/penify_hook/commands/doc_commands.py @@ -4,22 +4,29 @@ 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 - encountered during the process. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - import os import sys from ..folder_analyzer import FolderAnalyzerGenHook @@ -80,19 +87,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - parser (argparse.ArgumentParser): The parser to configure. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # 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 +140,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - args (Namespace): Parsed command-line arguments containing the subcommand and location - details. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # 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..7662419 100644 --- a/penify_hook/commands/hook_commands.py +++ b/penify_hook/commands/hook_commands.py @@ -10,14 +10,27 @@ """ def install_git_hook(location, token): - """Install a post-commit hook in the specified location that generates - documentation - for changed files after each commit. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ hooks_dir = Path(location) / ".git/hooks" hook_path = hooks_dir / HOOK_FILENAME @@ -34,15 +47,27 @@ def install_git_hook(location, token): print(f"Documentation will now be automatically generated after each commit.") 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - location (Path): The base directory where the .git/hooks directory is located. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ hook_path = Path(location) / ".git/hooks" / HOOK_FILENAME diff --git a/penify_hook/commit_analyzer.py b/penify_hook/commit_analyzer.py index 31ab46b..438cc9a 100644 --- a/penify_hook/commit_analyzer.py +++ b/penify_hook/commit_analyzer.py @@ -13,34 +13,55 @@ class CommitDocGenHook(BaseAnalyzer): def __init__(self, repo_path: str, api_client: APIClient, llm_client=None, jira_client=None): + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ super().__init__(repo_path, api_client) self.llm_client = llm_client # Add LLM client as an optional parameter self.jira_client: JiraClient = jira_client # Add JIRA client as an optional parameter 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - instruction (str): A string containing instructions for generating the commit summary. - generate_description (bool): Whether to include detailed descriptions in the summary. - + dictionary (dict): The processed files map. + 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. - - Raises: - ValueError: If there are no changes staged for commit. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ diff = self.repo.git.diff('--cached') if not diff: @@ -71,22 +92,27 @@ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ summary: dict = self.get_summary(msg, True) if not summary: @@ -111,18 +137,29 @@ 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: - """Process JIRA integration for the commit message. - + # Look for JIRA issue keys in commit message, title, description and user message + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - title (str): Generated commit title. - description (str): Generated commit description. - msg (str): Original user message that might contain JIRA references. - + dictionary (dict): The processed files map. + Returns: - tuple: A tuple containing the updated commit title and description with - included JIRA information. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - # 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 +197,27 @@ 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ try: # Change to the repository directory diff --git a/penify_hook/config_command.py b/penify_hook/config_command.py index 1d9a6ab..92fe570 100644 --- a/penify_hook/config_command.py +++ b/penify_hook/config_command.py @@ -2,19 +2,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - parent_parser (argparse.ArgumentParser): The parent parser to which the config subparsers will be added. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Config subcommand: Create subparsers for config types parser = parent_parser.add_subparsers(title="config_type", dest="config_type") # Config subcommand: llm @@ -39,20 +50,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - args (argparse.Namespace): Command-line arguments containing the type of configuration to handle. - + dictionary (dict): The processed files map. + Returns: - int: Exit code indicating success or failure. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # 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..97c3c38 100644 --- a/penify_hook/file_analyzer.py +++ b/penify_hook/file_analyzer.py @@ -19,26 +19,55 @@ class FileAnalyzerGenHook(BaseAnalyzer): def __init__(self, file_path: str, api_client: APIClient): + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - file_path (str): The relative path to the file that needs to be processed. - pbar (tqdm): Progress bar to update during processing. - + dictionary (dict): The processed files map. + Returns: - bool: True if the file was processed successfully, False otherwise. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ file_abs_path = os.path.join(os.getcwd(), file_path) file_extension = os.path.splitext(file_path)[1].lower() @@ -103,29 +132,56 @@ def process_file(self, file_path, pbar): return False def print_processing(self, file_path): - """Print a processing message for a file. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - file_path (str): The path to the file being processed. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ formatted_path = format_file_path(file_path) print(f"\n{format_highlight(f'Processing file: {formatted_path}')}") def run(self): - """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. - - Args: - self (PostCommitHook): An instance of the PostCommitHook class. - """ # Create a progress bar with appropriate stages + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ 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..3c47961 100644 --- a/penify_hook/folder_analyzer.py +++ b/penify_hook/folder_analyzer.py @@ -8,26 +8,55 @@ class FolderAnalyzerGenHook(BaseAnalyzer): def __init__(self, dir_path: str, api_client: APIClient): + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - dir_path (str): The path to the directory whose files and subdirectory files need to be - listed. - + dictionary (dict): The processed files map. + Returns: - list: A list containing the full paths of all non-hidden files within the - specified directory and its subdirectories. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - files = [] for dirpath, dirnames, filenames in os.walk(dir_path): dirnames[:] = [d for d in dirnames if not d.startswith(".")] @@ -38,16 +67,27 @@ def list_all_files_in_dir(self, dir_path: str): return files 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - self (PostCommitHook): The instance of the post-commit hook class. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ try: file_list = self.list_all_files_in_dir(self.dir_path) diff --git a/penify_hook/git_analyzer.py b/penify_hook/git_analyzer.py index f9e7127..eaa83d0 100644 --- a/penify_hook/git_analyzer.py +++ b/penify_hook/git_analyzer.py @@ -18,19 +18,52 @@ class GitDocGenHook(BaseAnalyzer): def __init__(self, repo_path: str, api_client: APIClient): + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + Returns: - list: A list of file paths that were modified in the last commit. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ last_commit = self.repo.head.commit modified_files = [] @@ -40,19 +73,27 @@ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - diff_text (str): A string containing the diff text to be processed. - + dictionary (dict): The processed files map. + Returns: - list: A sorted list of unique line numbers that have been modified. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ modified_lines = [] current_line = 0 @@ -89,23 +130,27 @@ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - file_path (str): The relative path to the file to be processed. - + dictionary (dict): The processed files map. + Returns: - bool: True if the file was successfully processed and updated, False - otherwise. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ file_abs_path = os.path.join(self.repo_path, file_path) file_extension = os.path.splitext(file_path)[1].lower() @@ -150,16 +195,27 @@ def process_file(self, file_path): return True 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ 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..aa91d9d 100644 --- a/penify_hook/jira_client.py +++ b/penify_hook/jira_client.py @@ -15,13 +15,27 @@ class JiraClient: """ def __init__(self, jira_url: str = None, jira_user: str = None, jira_api_token: str = None): - """ - Initialize the JIRA client. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. 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 + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ self.jira_url = jira_url self.jira_user = jira_user @@ -44,37 +58,54 @@ def __init__(self, jira_url: str = None, jira_user: str = None, jira_api_token: self.jira_client = None 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + Returns: - bool: True if the JIRA client is connected, False otherwise + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ return self.jira_client is not None def extract_issue_keys_from_branch(self, branch_name: str) -> List[str]: - """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 - + # Common JIRA issue key pattern: PROJECT-123 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - branch_name (str): The name of the git branch to search for JIRA issue keys. - + dictionary (dict): The processed files map. + 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'] + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - # 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 +113,55 @@ 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]: - """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. - + # Common JIRA issue key pattern: PROJECT-123 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - text (str): The text in which to search for JIRA issue keys. - + dictionary (dict): The processed files map. + Returns: - List[str]: A list of unique JIRA issue keys found in the text. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - # 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - issue_key (str): The JIRA issue key (e.g., "PROJECT-123"). - + dictionary (dict): The processed files map. + Returns: - Dict[str, Any] or None: A dictionary containing the details of the JIRA - issue if found, otherwise `None`. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ if not self.is_connected(): logging.warning("JIRA client not connected") @@ -143,14 +185,27 @@ def get_issue_details(self, issue_key: str) -> Optional[Dict[str, Any]]: return None def add_comment(self, issue_key: str, comment: str) -> bool: - """Add a comment to a JIRA issue. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - issue_key (str): JIRA issue key (e.g., "PROJECT-123") - comment (str): Comment text to add - + dictionary (dict): The processed files map. + Returns: - bool: True if the comment was added successfully, False otherwise + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ if not self.is_connected(): logging.warning("JIRA client not connected") @@ -165,14 +220,27 @@ def add_comment(self, issue_key: str, comment: str) -> bool: return False def update_issue_status(self, issue_key: str, transition_name: str) -> bool: - """Update the status of a JIRA issue. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - issue_key (str): The key of the JIRA issue to be updated. - transition_name (str): The name of the desired transition. - + dictionary (dict): The processed files map. + Returns: - bool: True if the status was successfully updated, False otherwise. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ if not self.is_connected(): logging.warning("JIRA client not connected") @@ -202,20 +270,29 @@ 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: - """Format commit message with JIRA issue information. - + # If no issue keys provided, extract them from title and description + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. - + dictionary (dict): The processed files map. + Returns: - tuple: A tuple containing the updated commit title and description with JIRA - information included. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - # 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,21 +329,27 @@ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - issue_key (str): The JIRA issue key (e.g., "PROJECT-123"). - + dictionary (dict): The processed files map. + Returns: - Dict[str, Any]: A dictionary containing business and technical context from the issue. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ if not self.is_connected(): logging.warning("JIRA client not connected") @@ -336,21 +419,27 @@ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - issue_keys: List of JIRA issue keys to gather information from - + dictionary (dict): The processed files map. + Returns: - Dict containing business and technical context from the issues + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ if not issue_keys or not self.is_connected(): return {} @@ -375,17 +464,27 @@ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. - + dictionary (dict): The processed files map. + Returns: - tuple: A tuple containing the enhanced commit title and description with added - context from JIRA issues. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ 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..126136a 100644 --- a/penify_hook/llm_client.py +++ b/penify_hook/llm_client.py @@ -10,15 +10,29 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. 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 + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ self.model = model if api_base: os.environ["OPENAI_API_BASE"] = api_base @@ -26,30 +40,27 @@ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. - repo_details (Dict): Details about the repository. - jira_context (Dict?): Optional JIRA issue context to enhance the summary. - + dictionary (dict): The processed files map. + Returns: - 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. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ if not self.model: raise ValueError("LLM model not configured. Please provide a model when initializing LLMClient.") diff --git a/penify_hook/login_command.py b/penify_hook/login_command.py index 2d97cc3..ed25b8f 100644 --- a/penify_hook/login_command.py +++ b/penify_hook/login_command.py @@ -1,22 +1,53 @@ def setup_login_parser(parser): + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - args (argparse.Namespace): Parsed arguments containing necessary parameters for the login command. - + dictionary (dict): The processed files map. + Returns: - None: This function does not return any value; it is expected to handle the - login process internally. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - 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..e831104 100644 --- a/penify_hook/main.py +++ b/penify_hook/main.py @@ -4,19 +4,29 @@ 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + Returns: - int: Exit status of the program (0 for success, 1 for error). + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - 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..32e37b9 100644 --- a/penify_hook/ui_utils.py +++ b/penify_hook/ui_utils.py @@ -26,157 +26,303 @@ PROCESSING_SYMBOL = "⟳" def format_info(message): - """Format an informational message with appropriate color. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - message (str): The text of the informational message to be formatted. - + dictionary (dict): The processed files map. + Returns: - str: The formatted informational message with the specified color. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ return f"{INFO_COLOR}{message}{Style.RESET_ALL}" 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - message (str): The message to be formatted as a success message. - + dictionary (dict): The processed files map. + Returns: - str: The formatted success message with green color and reset style. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ return f"{SUCCESS_COLOR}{message}{Style.RESET_ALL}" def format_warning(message): - """Format a warning message with appropriate color. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - message (str): The warning message to be formatted. - + dictionary (dict): The processed files map. + Returns: - str: The formatted warning message with the specified color. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ return f"{WARNING_COLOR}{message}{Style.RESET_ALL}" 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`. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - message (str): The plain text error message to be formatted. - + dictionary (dict): The processed files map. + Returns: - str: The formatted error message with the error color applied. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ return f"{ERROR_COLOR}{message}{Style.RESET_ALL}" def format_highlight(message): - """Format a highlighted message with appropriate color. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - message (str): The message to be formatted and highlighted. - + dictionary (dict): The processed files map. + Returns: - str: The formatted message with applied highlight style. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ return f"{HIGHLIGHT_COLOR}{message}{Style.RESET_ALL}" 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - file_path (str): The file path to be formatted. - + dictionary (dict): The processed files map. + Returns: - str: The formatted file path with the warning color applied. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ return f"{WARNING_COLOR}{file_path}{Style.RESET_ALL}" 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - message (str): The message to be printed. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ print(format_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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - message (str): The message to be printed as a success message. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ print(format_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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - message (str): The warning message to be printed. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ print(format_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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - message (str): The error message to be printed. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ print(format_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`. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - file_path (str): The path of the file to be processed. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ formatted_path = format_file_path(file_path) print(f"\n{format_highlight(f'Processing file: {formatted_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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - status (str): The status type ('success', 'warning', 'error') or another string. - message (str): The message to be displayed along with the symbol. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ if status == 'success': print(f" {SUCCESS_COLOR}{SUCCESS_SYMBOL} {message}{Style.RESET_ALL}") @@ -188,15 +334,27 @@ def print_status(status, message): print(f" {PROCESSING_SYMBOL} {message}") def create_progress_bar(total, desc="Processing", unit="item"): - """Create a tqdm progress bar with consistent styling. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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". - + dictionary (dict): The processed files map. + Returns: - tqdm: A configured tqdm progress bar instance. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ return tqdm( total=total, @@ -207,19 +365,27 @@ 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. - + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - stages (list): A list of strings representing individual stages in the process. - desc (str?): A description for the progress bar. Defaults to "Processing". - + dictionary (dict): The processed files map. + Returns: - tuple: A tuple containing the tqdm progress bar object and the list of stages. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ pbar = tqdm( total=len(stages), @@ -231,18 +397,29 @@ def create_stage_progress_bar(stages, desc="Processing"): return pbar, stages def update_stage(pbar, stage_name): - """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. - + # Force refresh with a custom description and ensure it's visible + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - pbar (tqdm): The progress bar object to be updated. - stage_name (str): A string representing the current stage of the process. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - # 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 From 037c9ae7375689aec408a07dc8c5c151b5ac35bc Mon Sep 17 00:00:00 2001 From: "penify-dev[bot]" <146478655+penify-dev[bot]@users.noreply.github.com> Date: Tue, 22 Apr 2025 18:01:51 +0000 Subject: [PATCH 2/2] Generated Documentation --- tests/test_commit_commands.py | 404 ++++++++++++++++++++------------- tests/test_config_commands.py | 405 +++++++++++++++++++++------------- tests/test_doc_commands.py | 359 +++++++++++++++++++----------- tests/test_web_config.py | 111 +++++++--- 4 files changed, 817 insertions(+), 462 deletions(-) diff --git a/tests/test_commit_commands.py b/tests/test_commit_commands.py index daf4b0f..20593d8 100644 --- a/tests/test_commit_commands.py +++ b/tests/test_commit_commands.py @@ -9,17 +9,29 @@ 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. - - Yields: - tuple: A tuple containing the mock of APIClient and the mocked instance of - APIClient. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - with patch('penify_hook.api_client.APIClient', create=True) as mock: api_client_instance = MagicMock() mock.return_value = api_client_instance @@ -27,19 +39,29 @@ 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. - Yields: - tuple: A tuple containing two elements: - - mock (MagicMock): The mock object for LLMClient. - - llm_client_instance (MagicMock): An instance of the mocked LLMClient. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - with patch('penify_hook.llm_client.LLMClient', create=True) as mock: llm_client_instance = MagicMock() mock.return_value = llm_client_instance @@ -47,18 +69,29 @@ 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. - - Yields: - tuple: A tuple containing the mocked JIRA client instance and its - `is_connected` method. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - with patch('penify_hook.jira_client.JiraClient', create=True) as mock: jira_instance = MagicMock() jira_instance.is_connected.return_value = True @@ -67,22 +100,29 @@ 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`. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + 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`. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - with patch('penify_hook.commit_analyzer.CommitDocGenHook', create=True) as mock: doc_gen_instance = MagicMock() mock.return_value = doc_gen_instance @@ -90,39 +130,58 @@ 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. - Yields: - MagicMock: A mock object that simulates the `recursive_search_git_folder` function. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - 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. - Yields: - tuple: A tuple containing three mock objects corresponding to `print_info`, - `print_warning`, - and `print_error`. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - 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,23 +197,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - mock_error (MagicMock): Mock object for error handling. - mock_warning (MagicMock): Mock object for warning logging. - mock_info (MagicMock): Mock object for info logging. - mock_git_folder_search (MagicMock): Mock object to simulate git folder search. - mock_doc_gen (MagicMock): Mock object for document generation. - mock_llm_client (MagicMock): Mock object for LLM client interaction. - mock_api_client (MagicMock): Mock object for API client interaction. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mocks api_instance = MagicMock() mock_api_client.return_value = api_instance @@ -199,27 +265,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - mock_error (MagicMock): A MagicMock object for simulating error logging. - mock_warning (MagicMock): A MagicMock object for simulating warning logging. - mock_info (MagicMock): A MagicMock object for simulating info logging. - mock_git_folder_search (MagicMock): A MagicMock object for simulating the git folder search function. - mock_doc_gen (MagicMock): A MagicMock object for simulating the doc generator function. - mock_jira_client (MagicMock): A MagicMock object for simulating the JIRA client class. - 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mocks api_instance = MagicMock() mock_api_client.return_value = api_instance @@ -268,25 +337,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - mock_error (MagicMock): Mock for error logging. - mock_warning (MagicMock): Mock for warning logging. - mock_info (MagicMock): Mock for info logging. - mock_git_folder_search (MagicMock): Mock for searching the Git folder. - mock_doc_gen (MagicMock): Mock for generating documentation. - mock_jira_client (MagicMock): Mock for creating a JIRA client. - mock_api_client (MagicMock): Mock for creating an API client. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mocks api_instance = MagicMock() mock_api_client.return_value = api_instance @@ -322,25 +396,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mocks mock_doc_gen.side_effect = Exception("Test error") mock_git_folder_search.return_value = '/mock/git/folder' @@ -357,20 +436,29 @@ 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. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - parser (MagicMock): The argument parser to be configured. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - parser = MagicMock() setup_commit_parser(parser) @@ -388,22 +476,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - mock_print_info (MagicMock): Mock object for printing information. - mock_commit_code (MagicMock): Mock object for committing code. - mock_get_token (MagicMock): Mock object for retrieving API token. - mock_get_llm_config (MagicMock): Mock object for retrieving LLM configuration. - mock_get_jira_config (MagicMock): Mock object for retrieving JIRA configuration. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # 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..abf830e 100644 --- a/tests/test_config_commands.py +++ b/tests/test_config_commands.py @@ -20,20 +20,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Mock git folder search mock_git_folder.return_value = '/mock/git/folder' # Mock Path operations @@ -58,22 +68,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Mock git folder search mock_git_folder.return_value = '/mock/git/folder' # Mock Path operations @@ -95,20 +113,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - mock_file_open (MagicMock): A mock for the open() function. - mock_get_config (MagicMock): A mock for the get_config() function. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True mock_get_config.return_value = mock_config_file @@ -127,20 +155,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True mock_get_config.return_value = mock_config_file @@ -156,21 +194,30 @@ 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. + # Setup mock + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True mock_get_config.return_value = mock_config_file @@ -186,25 +233,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. - + dictionary (dict): The processed files map. + Returns: - None: This test function does not explicitly return anything. Its assertions - serve as the verification of its correctness. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True mock_get_config.return_value = mock_config_file @@ -225,21 +277,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # 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 +328,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock mock_config_file = MagicMock() mock_config_file.exists.return_value = True mock_get_config.return_value = mock_config_file @@ -303,22 +368,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # 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 +420,30 @@ 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. + # Setup mock for env var + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock for env var mock_getenv.return_value = "env-token" # Call function @@ -376,21 +459,30 @@ 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) + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock for env var (not found) mock_getenv.return_value = None # Setup mock for config file @@ -411,27 +503,30 @@ 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) + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. - + dictionary (dict): The processed files map. + Returns: - None: The function does not return anything; it asserts conditions to verify - correctness. + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # 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..9670936 100644 --- a/tests/test_doc_commands.py +++ b/tests/test_doc_commands.py @@ -21,23 +21,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - mock_getcwd (MagicMock): Mock for os.getcwd(). - mock_api_client (MagicMock): Mock for creating an API client. - mock_folder_analyzer (MagicMock): Mock for folder analysis. - mock_file_analyzer (MagicMock): Mock for file analysis. - mock_git_analyzer (MagicMock): Mock for Git analyzer setup. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance mock_getcwd.return_value = '/fake/current/dir' @@ -61,22 +68,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance mock_file_instance = MagicMock() @@ -99,21 +114,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance mock_folder_instance = MagicMock() @@ -134,27 +158,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock_api_instance = MagicMock() mock_api_client.return_value = mock_api_instance mock_git_analyzer.side_effect = Exception("Test error") @@ -167,13 +194,29 @@ 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 - different subcommands like 'install-hook' and 'uninstall-hook'. + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - parser = ArgumentParser() setup_docgen_parser(parser) @@ -199,22 +242,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - mock_exit (MagicMock): Mock object for sys.exit. - mock_get_token (MagicMock): Mock object to simulate fetching a token. - mock_generate_doc (MagicMock): Mock object to simulate generating documentation. - mock_uninstall_hook (MagicMock): Mock object to simulate uninstalling a hook. - mock_install_hook (MagicMock): Mock object to simulate installing a hook. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock_get_token.return_value = 'fake-token' # Test install-hook subcommand @@ -232,20 +283,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - mock_exit (MagicMock): A mock for the exit function. - mock_get_token (MagicMock): A mock for the get_token function. - mock_generate_doc (MagicMock): A mock for the generate_doc function. - mock_uninstall_hook (MagicMock): A mock for the uninstall_hook function. - mock_install_hook (MagicMock): A mock for the install_hook function. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock_get_token.return_value = 'fake-token' # Test uninstall-hook subcommand @@ -262,20 +323,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock_get_token.return_value = 'fake-token' # Test direct documentation generation @@ -289,19 +360,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + Args: - mock_exit (MagicMock): A MagicMock object simulating the `exit` function. - mock_get_token (MagicMock): A MagicMock object simulating the `get_token` function. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Test with no token mock_get_token.return_value = None args = MagicMock(docgen_subcommand=None, location='doc_location') handle_docgen(args) @@ -311,18 +393,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # Setup mock_api_client.side_effect = Exception("API error") mock_getcwd.return_value = '/fake/current/dir' @@ -334,21 +428,30 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # 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..0da4802 100644 --- a/tests/test_web_config.py +++ b/tests/test_web_config.py @@ -16,28 +16,58 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # 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(): + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ mock_server_instance.shutdown() mock_server_instance.serve_forever.side_effect = stop_server_after_call @@ -57,27 +87,58 @@ 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 + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + 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. + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } """ - - # 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(): + """Save the processed files map to a JSON file. + + Function parameters should be documented in the ``Args`` section. The name of each parameter is required. The type and + description of each parameter is optional, but should be included if not obvious. + + Args: + dictionary (dict): The processed files map. + + Returns: + bool: True if successful, False otherwise. + The return type is optional and may be specified at the beginning of + the ``Returns`` section followed by a colon. + The ``Returns`` section may span multiple lines and paragraphs. + Following lines should be indented to match the first line. + The ``Returns`` section supports any reStructuredText formatting, + including literal blocks:: + + { + 'param1': param1, + 'param2': param2 + } + """ mock_server_instance.shutdown() mock_server_instance.serve_forever.side_effect = stop_server_after_call