Skip to content

Commit

Permalink
🐛 bugfix(hook): Fix bug in commit message hook for LOG (#6)
Browse files Browse the repository at this point in the history
## 💌 Description

<!-- Add a more detailed description of the changes if needed. -->

## 🩹 Related issue

<!-- If your PR refers to a related issue, link it here. -->
Fixes: #

## 🏗️ Type of change

<!-- Mark with an `x` all the checkboxes that apply (like `[x]`) -->

- [ ] 📚 Examples / docs / tutorials / dependencies update
- [ ] 🐛 Bug fix (non-breaking change which fixes an issue)
- [ ] 🥂 Improvement (non-breaking change which improves an existing
feature)
- [ ] 🚀 New feature (non-breaking change which adds functionality)
- [ ] 💥 Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] 🔐 Security fix
- [ ] ⬆️ Dependencies update

## ✅ Checklist

<!-- Mark with an `x` all the checkboxes that apply (like `[x]`) -->

- [ ] I've read the
[`CODE_OF_CONDUCT.md`](https://github.com/DariuszPorowski/chatgpt-pre-commit-hooks/blob/main/CODE_OF_CONDUCT.md)
document.
- [ ] I've read the
[`CONTRIBUTING.md`](https://github.com/DariuszPorowski/chatgpt-pre-commit-hooks/blob/main/CONTRIBUTING.md)
guide.
- [ ] I've written tests for all new methods and classes that I created.
- [ ] I've written the docstring in Google format for all the methods
and classes that I used.
  • Loading branch information
DariuszPorowski authored Apr 18, 2023
1 parent d661bf7 commit 2a7ad34
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 35 deletions.
2 changes: 2 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,6 @@ repos:
- "500"
- "--emoji"
- "--description"
- "--log-level"
- "debug"
stages: [prepare-commit-msg]
22 changes: 11 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ Example:
```yaml
repos:
- repo: https://github.com/DariuszPorowski/chatgpt-pre-commit-hooks
rev: v0.1.1
rev: v0.1.2
hooks:
- id: chatgpt-commit-message
```
Expand All @@ -174,7 +174,7 @@ repos:
- or include it in a `requirements.txt` file in your project:

```text
chatgpt-pre-commit-hooks~=0.1.1
chatgpt-pre-commit-hooks~=0.1.2
```

and run:
Expand Down Expand Up @@ -204,25 +204,25 @@ repos:

1. Add to your `.pre-commit-config.yaml`

```yml
```yaml
repos:
- repo: local
hooks:
- id: ... # follow 🎣 Hooks section to see available hooks IDs
name: Run chatgpt-pre-commit-hooks (<name>)
entry: chatgpt-pre-commit-hooks.<id> # follow 🎣 Hooks section to see available hooks IDs
- id: <id> # follow 🎣 Hooks section to see available hooks IDs
name: Run <name>
entry: <id> # follow 🎣 Hooks section to see available hooks IDs
language: system
```

Example:

```yml
```yaml
repos:
- repo: local
- repo: local
hooks:
- id: chatgpt-commit-message
name: Run chatgpt-pre-commit-hooks (chatgpt-commit-message)
entry: chatgpt-pre-commit-hooks.chatgpt-commit-message
- id: chatgpt-commit-message
name: Run ChatGPT commit-message
entry: chatgpt-commit-message
language: system
```

Expand Down
46 changes: 24 additions & 22 deletions chatgpt_pre_commit_hooks/chatgpt_commit_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import tiktoken
from git.repo import Repo

logger = logging.getLogger(__name__)
LOG = logging.getLogger(__name__)


def get_args() -> argparse.Namespace:
Expand Down Expand Up @@ -66,13 +66,13 @@ def get_git_diff(max_char_count: int, git_repo_path: str) -> str:
diff = repo.git.diff(staged=True)
if len(diff) > max_char_count:
diff = repo.git.diff(staged=True, stat=True)
logger.debug(f"GIT_DIFF: {diff}")
LOG.debug(f"GIT_DIFF: {diff}")
return diff


def get_user_commit_message(commit_msg_file_path: str, prepare_commit_message_source: Optional[str]) -> Optional[str]:
"""Get user commit message (if specified)."""
logger.debug(f"PREPARE_COMMIT_MESSAGE_SOURCE: {prepare_commit_message_source}")
LOG.debug(f"PREPARE_COMMIT_MESSAGE_SOURCE: {prepare_commit_message_source}")
user_commit_message = None
if prepare_commit_message_source == "message" or prepare_commit_message_source is None:
commit_msg_file = Path(commit_msg_file_path)
Expand All @@ -83,7 +83,7 @@ def get_user_commit_message(commit_msg_file_path: str, prepare_commit_message_so
if lines != []:
user_commit_message = "".join(lines).strip()

logger.debug(f"USER_COMMIT_MESSAGE: {user_commit_message}")
LOG.debug(f"USER_COMMIT_MESSAGE: {user_commit_message}")

if user_commit_message is not None:
skip_keywords = ["#no-ai", "#no-openai", "#no-chatgpt", "#no-gpt", "#skip-ai", "#skip-openai", "#skip-chatgpt", "#skip-gpt"]
Expand Down Expand Up @@ -131,8 +131,8 @@ def get_openai_chat_prompt_messages(user_commit_message: Optional[str], git_diff
role_system_prompt = " ".join(role_system)
role_user_prompt = " ".join(role_user)

logger.debug(f"ROLE_SYSTEM_PROMPT: {role_system_prompt}")
logger.debug(f"ROLE_USER_PROMPT: {role_user_prompt}")
LOG.debug(f"ROLE_SYSTEM_PROMPT: {role_system_prompt}")
LOG.debug(f"ROLE_USER_PROMPT: {role_user_prompt}")

return [
{"role": "system", "content": role_system_prompt},
Expand All @@ -142,7 +142,7 @@ def get_openai_chat_prompt_messages(user_commit_message: Optional[str], git_diff

def get_openai_chat_response(messages: List[Dict[str, str]], args: argparse.Namespace) -> str:
"""Get OpenAI Chat Response."""
if logger.isEnabledFor(logging.DEBUG):
if LOG.isEnabledFor(logging.DEBUG):
_num_tokens_from_messages(messages, str(args.openai_model))
openai.debug = True

Expand All @@ -161,7 +161,7 @@ def get_openai_chat_response(messages: List[Dict[str, str]], args: argparse.Name
temperature=0,
top_p=0.1,
)
logger.debug(f"OPENAI_CHAT_RESPONSE: {response}")
LOG.debug(f"OPENAI_CHAT_RESPONSE: {response}")

return response["choices"][0]["message"]["content"]

Expand Down Expand Up @@ -197,7 +197,7 @@ def _num_tokens_from_messages(messages: List[Dict[str, str]], model: str) -> int
if key == "name":
num_tokens += tokens_per_name
num_tokens += 3 # every reply is primed with <|start|>assistant<|message|>
logger.debug(f"NUM_TOKENS: {num_tokens}")
LOG.debug(f"NUM_TOKENS: {num_tokens}")
return num_tokens


Expand All @@ -211,8 +211,21 @@ def set_commit_message(commit_msg_file_path: str, commit_msg: str) -> None:
commit_msg_file_wrapper.close()


def main(args: argparse.Namespace) -> int:
def main() -> int:
"""Main function of module."""
global LOG # noqa: PLW0603

args = get_args()
LOG = logging.getLogger(__name__)
LOG.setLevel(args.log_level.upper())

if LOG.isEnabledFor(logging.DEBUG):
fh = logging.FileHandler(filename="debug.log", mode="w")
LOG.addHandler(fh)

LOG.debug(f"SYS_ARGV: {sys.argv}")
LOG.debug(f"ARGS: {args}")

try:
user_commit_message = get_user_commit_message(args.commit_msg_filename, args.prepare_commit_message_source)
git_diff = get_git_diff(args.max_char_count, ".")
Expand All @@ -226,15 +239,4 @@ def main(args: argparse.Namespace) -> int:


if __name__ == "__main__":
args = get_args()
logger = logging.getLogger(__name__)
logger.setLevel(args.log_level.upper())

if logger.isEnabledFor(logging.DEBUG):
fh = logging.FileHandler(filename="debug.log", mode="w")
logger.addHandler(fh)

logger.debug(f"SYS_ARGV: {sys.argv}")
logger.debug(f"ARGS: {args}")

sys.exit(main(args))
sys.exit(main())
4 changes: 2 additions & 2 deletions docs/chatgpt_commit_message.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Add to your `.pre-commit-config.yaml`
```yaml
repos:
- repo: https://github.com/DariuszPorowski/chatgpt-pre-commit-hooks
rev: v0.1.1 # Use the ref you want to point at, see ⚠️ NOTE below!
rev: v0.1.2 # Use the ref you want to point at, see ⚠️ NOTE below!
hooks:
- id: chatgpt-commit-message
```
Expand All @@ -49,7 +49,7 @@ Example:
```yaml
repos:
- repo: https://github.com/DariuszPorowski/chatgpt-pre-commit-hooks
rev: v0.1.1 # Use the ref you want to point at, see ⚠️ NOTE below!
rev: v0.1.2 # Use the ref you want to point at, see ⚠️ NOTE below!
hooks:
- id: chatgpt-commit-message
args:
Expand Down

0 comments on commit 2a7ad34

Please sign in to comment.