Skip to content

Commit c80f4f1

Browse files
[Penify] Full Repo Documentation (#90)
* Generated Documentation * Generated Documentation * Generated Documentation * Generated Documentation * Generated Documentation * Generated Documentation * Generated Documentation * Generated Documentation --------- Co-authored-by: penify-dev[bot] <146478655+penify-dev[bot]@users.noreply.github.com>
1 parent 1fab3f0 commit c80f4f1

17 files changed

Lines changed: 338 additions & 742 deletions

penify_hook/api_client.py

Lines changed: 17 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -10,29 +10,7 @@ def __init__(self, api_url, api_token: str = None, bearer_token: str = None):
1010
self.BEARER_TOKEN = bearer_token
1111

1212
def send_file_for_docstring_generation(self, file_name, content, line_numbers, repo_details = None):
13-
"""Send file content and modified lines to the API and return modified
14-
content.
15-
16-
This function constructs a payload containing the file path, content,
17-
and modified line numbers, and sends it to a specified API endpoint for
18-
processing. It handles the response from the API, returning the modified
19-
content if the request is successful. If the request fails, it logs the
20-
error details and returns the original content.
21-
22-
Args:
23-
file_name (str): The path to the file being sent.
24-
content (str): The content of the file to be processed.
25-
line_numbers (list): A list of line numbers that have been modified.
26-
repo_details (str?): Additional repository details if applicable. Defaults to None.
27-
28-
Returns:
29-
str: The modified content returned by the API, or the original content if the
30-
request fails.
31-
32-
Raises:
33-
Exception: If there is an error in processing the file and no specific error
34-
message is provided.
35-
"""
13+
"""Send file content and modified lines to the API and return modified content."""
3614
payload = {
3715
'file_path': file_name,
3816
'content': content,
@@ -53,25 +31,22 @@ def send_file_for_docstring_generation(self, file_name, content, line_numbers, r
5331
raise Exception(f"API Error: {error_message}")
5432

5533
def generate_commit_summary(self, git_diff, instruction: str = "", repo_details = None, jira_context: dict = None):
56-
"""Generate a commit summary by sending a POST request to the API endpoint.
57-
58-
This function constructs a payload containing the git diff and any
59-
additional instructions provided. It then sends this payload to a
60-
specified API endpoint to generate a summary of the commit. If the
61-
request is successful, it returns the response from the API; otherwise,
62-
it returns None.
63-
34+
"""Generates a commit summary by sending a POST request to the API endpoint.
35+
36+
This function constructs a payload containing the git diff and any additional
37+
instructions provided. It then sends this payload to a specified API endpoint
38+
to generate a summary of the commit. If the request is successful, it returns
39+
the response from the API; otherwise, it returns None. The function also
40+
handles optional repository details and JIRA context if they are provided.
41+
6442
Args:
6543
git_diff (str): The git diff of the commit.
66-
instruction (str??): Additional instruction for the commit. Defaults to "".
67-
repo_details (dict??): Details of the git repository. Defaults to None.
68-
jira_context (dict??): JIRA issue details to enhance the commit summary. Defaults to None.
69-
44+
instruction (str): Additional instruction for the commit. Defaults to "".
45+
repo_details (dict): Details of the git repository. Defaults to None.
46+
jira_context (dict): JIRA issue details to enhance the commit summary. Defaults to None.
47+
7048
Returns:
7149
dict: The response from the API if the request is successful, None otherwise.
72-
73-
Raises:
74-
Exception: If there is an error during the API request.
7550
"""
7651
payload = {
7752
'git_diff': git_diff,
@@ -100,18 +75,8 @@ def generate_commit_summary(self, git_diff, instruction: str = "", repo_details
10075
return None
10176

10277
def get_supported_file_types(self) -> list[str]:
103-
"""Retrieve the supported file types from the API.
104-
105-
This function sends a request to the API endpoint
106-
`/v1/file/supported_languages` to obtain a list of supported file types.
107-
If the API call is successful (status code 200), it parses the JSON
108-
response and returns the list of supported file types. If the API call
109-
fails, it returns a default list of common file types.
110-
111-
Returns:
112-
list[str]: A list of supported file types, either from the API or a default set.
113-
"""
11478

79+
"""Retrieve supported file types from the API or return a default list."""
11580
url = self.api_url+"/v1/cli/supported_languages"
11681
response = requests.get(url)
11782
if response.status_code == 200:
@@ -121,21 +86,8 @@ def get_supported_file_types(self) -> list[str]:
12186
return ["py", "js", "ts", "java", "kt", "cs", "c"]
12287

12388
def generate_commit_summary_with_llm(self, diff, message, generate_description: bool, repo_details, llm_client : LLMClient, jira_context=None):
124-
"""Generates a commit summary using a local LLM client. If an error occurs
125-
during the generation process,
126-
it falls back to using the API.
127-
128-
Args:
129-
diff (str): The Git diff of changes.
130-
message (str): User-provided commit message or instructions.
131-
generate_description (bool): Flag indicating whether to generate a description for the commit.
132-
repo_details (dict): Details about the repository.
133-
llm_client (LLMClient): An instance of LLMClient used to generate the summary.
134-
jira_context (JIRAContext?): Optional JIRA issue context to enhance the summary.
135-
136-
Returns:
137-
dict: A dictionary containing the title and description for the commit.
138-
"""
89+
"""Generates a commit summary using a local LLM client; falls back to API on
90+
error."""
13991
try:
14092
return llm_client.generate_commit_summary(diff, message, generate_description, repo_details, jira_context)
14193
except Exception as e:
@@ -144,17 +96,9 @@ def generate_commit_summary_with_llm(self, diff, message, generate_description:
14496
return self.generate_commit_summary(diff, message, repo_details, jira_context)
14597

14698
def get_api_key(self):
147-
"""Fetch an API key from a specified URL.
148-
149-
This function sends a GET request to retrieve an API token using a
150-
Bearer token in the headers. It handles the response and returns the API
151-
key if the request is successful, or `None` otherwise.
152-
153-
Returns:
154-
str: The API key if the request is successful, `None` otherwise.
155-
"""
15699

157100

101+
"""Fetch an API key from a specified URL using a Bearer token."""
158102
url = self.api_url+"/v1/apiToken/get"
159103
response = requests.get(url, headers={"Authorization": f"Bearer {self.BEARER_TOKEN}"}, timeout=60*10)
160104
if response.status_code == 200:

penify_hook/commands/auth_commands.py

Lines changed: 20 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,26 @@
99
from pathlib import Path
1010

1111
def save_credentials(api_key):
12-
"""
13-
Save the token and API keys based on priority:
14-
1. .env file in Git repo root (if in a git repo)
15-
2. .penify file in home directory (global fallback)
12+
# Try to save in .env file in git repo first
13+
"""Save the API key in a priority-based manner.
14+
15+
This function attempts to save the API key in two locations, based on priority:
16+
1. In a `.env` file located in the root of the Git repository if one is found.
17+
2. In a global `.penify` file located in the user's home directory as a
18+
fallback. The function first tries to locate the Git repository using
19+
`recursive_search_git_folder`. If a Git repository is found, it reads the
20+
existing `.env` file (if present), updates or adds the API key under the key
21+
`PENIFY_API_TOKEN`, and writes the updated content back. If any error occurs
22+
during this process, it falls back to saving the credentials in the global
23+
`.penify` file. The function handles exceptions and prints appropriate error
24+
messages.
1625
1726
Args:
18-
api_key: The API key to save
19-
27+
api_key (str): The API key to save.
28+
2029
Returns:
21-
bool: True if saved successfully, False otherwise
30+
bool: True if the API key is saved successfully, False otherwise.
2231
"""
23-
# Try to save in .env file in git repo first
2432
try:
2533
from ..utils import recursive_search_git_folder
2634
current_dir = os.getcwd()
@@ -80,21 +88,7 @@ def save_credentials(api_key):
8088
return False
8189

8290
def login(api_url, dashboard_url):
83-
"""Open the login page in a web browser and listen for the redirect URL to
84-
capture the token.
85-
86-
This function generates a random redirect port, constructs the full
87-
login URL with the provided dashboard URL, opens the login page in the
88-
default web browser, and sets up a simple HTTP server to listen for the
89-
redirect. Upon receiving the redirect, it extracts the token from the
90-
query parameters, fetches API keys using the token, saves them if
91-
successful, and handles login failures by notifying the user.
92-
93-
Args:
94-
api_url (str): The URL of the API service to fetch API keys.
95-
dashboard_url (str): The URL of the dashboard where the user will be redirected after logging
96-
in.
97-
"""
91+
"""Open the login page in a web browser and capture the token via redirect."""
9892
redirect_port = random.randint(30000, 50000)
9993
redirect_url = f"http://localhost:{redirect_port}/callback"
10094

@@ -105,16 +99,9 @@ def login(api_url, dashboard_url):
10599

106100
class TokenHandler(http.server.SimpleHTTPRequestHandler):
107101
def do_GET(self):
108-
"""Handle a GET request to process login token and redirect or display
109-
error message.
110-
111-
This method processes the incoming GET request, extracts the token from
112-
the query string, and performs actions based on whether the token is
113-
present. If the token is valid, it redirects the user to the Penify
114-
dashboard and fetches API keys if successful. If the token is invalid,
115-
it displays an error message.
116-
"""
117102

103+
"""Handle a GET request to process login token and redirect or display error
104+
message."""
118105
query = urllib.parse.urlparse(self.path).query
119106
query_components = urllib.parse.parse_qs(query)
120107
token = query_components.get("token", [None])[0]
@@ -171,6 +158,7 @@ def do_GET(self):
171158

172159
def log_message(self, format, *args):
173160
# Suppress log messages
161+
"""Suppress log messages."""
174162
return
175163

176164
with socketserver.TCPServer(("", redirect_port), TokenHandler) as httpd:

penify_hook/commands/commit_commands.py

Lines changed: 11 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -8,29 +8,27 @@
88
def commit_code(api_url, token, message, open_terminal, generate_description,
99
llm_model=None, llm_api_base=None, llm_api_key=None,
1010
jira_url=None, jira_user=None, jira_api_token=None):
11-
"""Enhance Git commits with AI-powered commit messages.
12-
13-
This function allows for the generation of enhanced commit messages
14-
using natural language processing models and optionally integrates with
15-
JIRA for additional context. It processes the current Git folder to find
16-
relevant files and generates a detailed commit message based on the
17-
provided parameters.
1811

12+
"""Enhance Git commits with AI-powered commit messages.
13+
14+
This function allows for the generation of enhanced commit messages using
15+
natural language processing models and optionally integrates with JIRA for
16+
additional context. It processes the current Git folder to find relevant files
17+
and generates a detailed commit message based on the provided parameters.
18+
1919
Args:
2020
api_url (str): URL of the API endpoint.
2121
token (str): Authentication token for the API.
2222
message (str): Initial commit message provided by the user.
2323
open_terminal (bool): Whether to open the terminal after committing.
2424
generate_description (bool): Whether to generate a detailed description in the commit message.
25-
llm_model (str?): The language model to use for generating the commit message. Defaults to
26-
None.
25+
llm_model (str?): The language model to use for generating the commit message. Defaults to None.
2726
llm_api_base (str?): Base URL of the LLM API. Defaults to None.
2827
llm_api_key (str?): API key for accessing the LLM service. Defaults to None.
2928
jira_url (str?): URL of the JIRA instance. Defaults to None.
3029
jira_user (str?): Username for authenticating with JIRA. Defaults to None.
3130
jira_api_token (str?): API token for accessing JIRA. Defaults to None.
3231
"""
33-
3432
from penify_hook.ui_utils import print_error
3533
from penify_hook.utils import recursive_search_git_folder
3634
from ..commit_analyzer import CommitDocGenHook
@@ -98,18 +96,8 @@ def commit_code(api_url, token, message, open_terminal, generate_description,
9896

9997

10098
def setup_commit_parser(parser):
101-
"""Generates a parser for setting up a command to generate smart commit
102-
messages.
103-
104-
This function sets up an argument parser that can be used to generate
105-
commit messages with contextual information. It allows users to specify
106-
options such as including a message, opening an edit terminal before
107-
committing, and generating a detailed commit message.
108-
109-
Args:
110-
parser (argparse.ArgumentParser): The ArgumentParser object to be configured.
111-
"""
11299

100+
"""Sets up an argument parser for generating smart commit messages."""
113101
commit_parser_description = """
114102
It generates smart commit messages. By default, it will just generate just the Title of the commit message.
115103
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 +114,9 @@ def setup_commit_parser(parser):
126114
parser.add_argument("-d", "--description", action="store_false", help="It will generate commit message with title and description.", default=False)
127115

128116
def handle_commit(args):
129-
"""Handle the commit functionality by processing arguments and invoking the
130-
appropriate commands.
131-
132-
This function processes the provided command-line arguments to configure
133-
settings for commit operations, including LLM (Language Model) and Jira
134-
configurations. It then calls the `commit_code` function with these
135-
configurations to perform the actual commit operation.
136-
137-
Args:
138-
args (argparse.Namespace): The parsed command-line arguments containing options like terminal,
139-
description, message, etc.
140-
"""
141117

118+
"""Handle commit functionality by processing arguments and invoking the
119+
appropriate commands."""
142120
from penify_hook.commands.commit_commands import commit_code
143121
from penify_hook.commands.config_commands import get_jira_config, get_llm_config, get_token
144122
from penify_hook.constants import API_URL

0 commit comments

Comments
 (0)