git-commit-msg-ai 1.4.1__tar.gz → 1.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/PKG-INFO +57 -1
  2. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/README.md +54 -0
  3. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai/ai_client.py +10 -0
  4. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai/cli.py +16 -0
  5. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai/editor.py +16 -0
  6. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai/git_ops.py +17 -1
  7. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai.egg-info/PKG-INFO +57 -1
  8. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai.egg-info/requires.txt +2 -0
  9. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/pyproject.toml +2 -2
  10. git_commit_msg_ai-1.5.0/tests/test_ai_client.py +158 -0
  11. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/tests/test_cli.py +71 -1
  12. git_commit_msg_ai-1.5.0/tests/test_editor.py +245 -0
  13. git_commit_msg_ai-1.5.0/tests/test_git_ops.py +189 -0
  14. git_commit_msg_ai-1.4.1/tests/test_ai_client.py +0 -80
  15. git_commit_msg_ai-1.4.1/tests/test_editor.py +0 -137
  16. git_commit_msg_ai-1.4.1/tests/test_git_ops.py +0 -81
  17. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai/__init__.py +0 -0
  18. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai/exceptions.py +0 -0
  19. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai.egg-info/SOURCES.txt +0 -0
  20. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai.egg-info/dependency_links.txt +0 -0
  21. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai.egg-info/entry_points.txt +0 -0
  22. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/git_commit_msg_ai.egg-info/top_level.txt +0 -0
  23. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/setup.cfg +0 -0
  24. {git_commit_msg_ai-1.4.1 → git_commit_msg_ai-1.5.0}/tests/test_exceptions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: git-commit-msg-ai
3
- Version: 1.4.1
3
+ Version: 1.5.0
4
4
  Summary: AI-powered git commit message generator following Conventional Commits
5
5
  License-Expression: MIT
6
6
  Requires-Python: >=3.10
@@ -11,6 +11,8 @@ Requires-Dist: mypy; extra == "dev"
11
11
  Requires-Dist: ruff; extra == "dev"
12
12
  Requires-Dist: pytest; extra == "dev"
13
13
  Requires-Dist: pytest-cov; extra == "dev"
14
+ Requires-Dist: build; extra == "dev"
15
+ Requires-Dist: twine; extra == "dev"
14
16
 
15
17
  # git-commit-msg-ai
16
18
 
@@ -29,6 +31,38 @@ AI-powered git commit message generator that follows the [Conventional Commits](
29
31
  [System.Environment]::SetEnvironmentVariable('ANTHROPIC_API_KEY', 'sk-ant-...', 'User') # Windows
30
32
  ```
31
33
 
34
+ ## Development Setup
35
+
36
+ Clone the repository, create a virtual environment, and install the project in editable mode with all dev dependencies:
37
+
38
+ ```sh
39
+ python -m venv .venv
40
+ ```
41
+
42
+ Activate the virtual environment:
43
+
44
+ ```sh
45
+ # macOS/Linux
46
+ source .venv/bin/activate
47
+
48
+ # Windows PowerShell
49
+ .venv\Scripts\Activate.ps1
50
+ ```
51
+
52
+ Install the project and dev dependencies:
53
+
54
+ ```sh
55
+ pip install -e ".[dev]"
56
+ ```
57
+
58
+ After activation the `git-commit-msg-ai` entry-point is on your PATH. You can also run the dev toolchain:
59
+
60
+ ```sh
61
+ pytest # run tests with coverage
62
+ ruff check . # lint
63
+ mypy . # type-check
64
+ ```
65
+
32
66
  ## Installation
33
67
 
34
68
  ```sh
@@ -79,3 +113,25 @@ BREAKING CHANGE: /v1/legacy is no longer available
79
113
  ```
80
114
 
81
115
  Supported types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`
116
+
117
+ ## Debugging
118
+
119
+ By default the tool produces no diagnostic output. To enable logging, set the `GIT_COMMIT_AI_LOG_LEVEL` environment variable before running the command. Logs are written to **stderr** and do not interfere with the generated commit message on **stdout**.
120
+
121
+ Valid values: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`
122
+
123
+ ```sh
124
+ # macOS/Linux - show all internal diagnostic messages
125
+ GIT_COMMIT_AI_LOG_LEVEL=DEBUG git-commit-msg-ai
126
+
127
+ # Windows PowerShell
128
+ $env:GIT_COMMIT_AI_LOG_LEVEL = 'DEBUG'
129
+ git-commit-msg-ai
130
+ ```
131
+
132
+ | Level | What you see |
133
+ |---|---|
134
+ | `DEBUG` | git commands run, API model/token params, temp file paths, char counts |
135
+ | `INFO` | commit message generated, commit created |
136
+ | `WARNING` | no staged changes found |
137
+ | `ERROR` | git not found, API failures, editor errors |
@@ -15,6 +15,38 @@ AI-powered git commit message generator that follows the [Conventional Commits](
15
15
  [System.Environment]::SetEnvironmentVariable('ANTHROPIC_API_KEY', 'sk-ant-...', 'User') # Windows
16
16
  ```
17
17
 
18
+ ## Development Setup
19
+
20
+ Clone the repository, create a virtual environment, and install the project in editable mode with all dev dependencies:
21
+
22
+ ```sh
23
+ python -m venv .venv
24
+ ```
25
+
26
+ Activate the virtual environment:
27
+
28
+ ```sh
29
+ # macOS/Linux
30
+ source .venv/bin/activate
31
+
32
+ # Windows PowerShell
33
+ .venv\Scripts\Activate.ps1
34
+ ```
35
+
36
+ Install the project and dev dependencies:
37
+
38
+ ```sh
39
+ pip install -e ".[dev]"
40
+ ```
41
+
42
+ After activation the `git-commit-msg-ai` entry-point is on your PATH. You can also run the dev toolchain:
43
+
44
+ ```sh
45
+ pytest # run tests with coverage
46
+ ruff check . # lint
47
+ mypy . # type-check
48
+ ```
49
+
18
50
  ## Installation
19
51
 
20
52
  ```sh
@@ -65,3 +97,25 @@ BREAKING CHANGE: /v1/legacy is no longer available
65
97
  ```
66
98
 
67
99
  Supported types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`
100
+
101
+ ## Debugging
102
+
103
+ By default the tool produces no diagnostic output. To enable logging, set the `GIT_COMMIT_AI_LOG_LEVEL` environment variable before running the command. Logs are written to **stderr** and do not interfere with the generated commit message on **stdout**.
104
+
105
+ Valid values: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`
106
+
107
+ ```sh
108
+ # macOS/Linux - show all internal diagnostic messages
109
+ GIT_COMMIT_AI_LOG_LEVEL=DEBUG git-commit-msg-ai
110
+
111
+ # Windows PowerShell
112
+ $env:GIT_COMMIT_AI_LOG_LEVEL = 'DEBUG'
113
+ git-commit-msg-ai
114
+ ```
115
+
116
+ | Level | What you see |
117
+ |---|---|
118
+ | `DEBUG` | git commands run, API model/token params, temp file paths, char counts |
119
+ | `INFO` | commit message generated, commit created |
120
+ | `WARNING` | no staged changes found |
121
+ | `ERROR` | git not found, API failures, editor errors |
@@ -1,3 +1,4 @@
1
+ import logging
1
2
  import textwrap
2
3
  from typing import Final, cast
3
4
 
@@ -5,6 +6,8 @@ import anthropic
5
6
 
6
7
  from git_commit_msg_ai.exceptions import AIError
7
8
 
9
+ logger = logging.getLogger(__name__)
10
+
8
11
  SYSTEM_PROMPT: Final[str] = textwrap.dedent("""\
9
12
  You are a Git commit message generator. Output only the commit message, nothing else. Follow the Conventional Commits specification:
10
13
  - First line: <type>(<optional scope>)<!>: <short subject> (50 chars max); append ! before the colon if the commit introduces a breaking change
@@ -21,6 +24,7 @@ def generate_commit_message(diff: str) -> str:
21
24
  try:
22
25
  anthropic_client = anthropic.Anthropic()
23
26
 
27
+ logger.debug('Calling Anthropic API: model=%s max_tokens=%d', MODEL, MAX_TOKENS)
24
28
  anthropic_api_response = anthropic_client.messages.create(
25
29
  model=MODEL,
26
30
  max_tokens=MAX_TOKENS,
@@ -28,15 +32,21 @@ def generate_commit_message(diff: str) -> str:
28
32
  messages=[{'role': 'user', 'content': diff}],
29
33
  )
30
34
  except anthropic.AuthenticationError:
35
+ logger.error('Anthropic authentication error')
31
36
  raise AIError('Anthropic API key is missing or invalid. Set the ANTHROPIC_API_KEY environment variable.')
32
37
  except anthropic.RateLimitError:
38
+ logger.error('Anthropic rate limit error')
33
39
  raise AIError('Anthropic API rate limit reached. Wait a moment and try again.')
34
40
  except anthropic.APIConnectionError:
41
+ logger.error('Anthropic API connection error')
35
42
  raise AIError('Could not reach the Anthropic API. Check your network connection.')
36
43
  except anthropic.APIStatusError as error:
44
+ logger.error('Anthropic API status error: %s', error.status_code)
37
45
  raise AIError(f'Anthropic API returned an error: {error.status_code}.')
38
46
 
39
47
  anthropic_api_response_message = anthropic_api_response.content[0]
40
48
  commit_message = cast(anthropic.types.TextBlock, anthropic_api_response_message).text.strip()
41
49
 
50
+ logger.info('Commit message generated: %d chars', len(commit_message))
51
+
42
52
  return commit_message
@@ -1,10 +1,26 @@
1
+ import logging
2
+ import os
1
3
  import sys
4
+ from typing import Final
2
5
 
3
6
  from git_commit_msg_ai import ai_client, editor, git_ops
4
7
  from git_commit_msg_ai.exceptions import GitCommitAIError
5
8
 
9
+ LOG_LEVEL_ENV_VAR: Final[str] = 'GIT_COMMIT_AI_LOG_LEVEL'
10
+
6
11
 
7
12
  def main() -> None:
13
+ log_level_name = os.environ.get(LOG_LEVEL_ENV_VAR, 'WARNING').upper()
14
+ numeric_log_level = getattr(logging, log_level_name, None)
15
+
16
+ if not isinstance(numeric_log_level, int):
17
+ numeric_log_level = logging.WARNING
18
+
19
+ logging.basicConfig(level=numeric_log_level, format='%(levelname)s:%(name)s:%(message)s', stream=sys.stderr)
20
+
21
+ if not isinstance(getattr(logging, log_level_name, None), int):
22
+ logging.warning('Invalid %s value %r, defaulting to WARNING', LOG_LEVEL_ENV_VAR, log_level_name)
23
+
8
24
  try:
9
25
  diff = git_ops.get_staged_diff()
10
26
  commit_message = ai_client.generate_commit_message(diff)
@@ -1,3 +1,4 @@
1
+ import logging
1
2
  import os
2
3
  import platform
3
4
  import subprocess
@@ -5,6 +6,8 @@ import tempfile
5
6
 
6
7
  from git_commit_msg_ai.exceptions import EditorError
7
8
 
9
+ logger = logging.getLogger(__name__)
10
+
8
11
 
9
12
  def get_default_editor() -> str:
10
13
  current_platform = platform.system()
@@ -19,25 +22,38 @@ def open_in_editor(initial_text: str) -> str:
19
22
  temp_file.write(initial_text)
20
23
  temp_file_path = temp_file.name
21
24
  except OSError:
25
+ logger.error('Could not create temporary file')
22
26
  raise EditorError('Could not create a temporary file.')
23
27
 
28
+ logger.debug('Temporary file created: %s', temp_file_path)
29
+
24
30
  platform_default_editor = get_default_editor()
25
31
  editor_command = os.environ.get('EDITOR', platform_default_editor)
26
32
 
33
+ logger.debug('Selected editor: %s', editor_command)
34
+
27
35
  try:
28
36
  try:
37
+ logger.debug('Opening editor: %s %s', editor_command, temp_file_path)
29
38
  subprocess.run([editor_command, temp_file_path], check=True)
30
39
  except FileNotFoundError:
40
+ logger.error('Editor not found: %s', editor_command)
31
41
  raise EditorError(f'Editor "{editor_command}" was not found. Set the EDITOR environment variable to a valid editor.')
32
42
  except subprocess.CalledProcessError:
43
+ logger.error('Editor exited with error: %s', editor_command)
33
44
  raise EditorError(f'Editor "{editor_command}" exited with an error.')
34
45
 
46
+ logger.debug('Editor closed, reading edited content')
47
+
35
48
  try:
36
49
  with open(temp_file_path) as temp_file:
37
50
  edited_text = temp_file.read().strip()
38
51
  except OSError:
52
+ logger.error('Could not read temporary file: %s', temp_file_path)
39
53
  raise EditorError('Could not read the edited commit message from the temporary file.')
40
54
  finally:
41
55
  os.unlink(temp_file_path)
42
56
 
57
+ logger.debug('Edited text read: %d chars', len(edited_text))
58
+
43
59
  return edited_text
@@ -1,3 +1,4 @@
1
+ import logging
1
2
  import subprocess
2
3
  from typing import Final
3
4
 
@@ -10,18 +11,28 @@ COMMIT_SUBCOMMAND: Final[str] = 'commit'
10
11
  MESSAGE_FLAG: Final[str] = '-m'
11
12
  UTF8_ENCODING: Final[str] = 'utf-8'
12
13
 
14
+ logger = logging.getLogger(__name__)
15
+
13
16
 
14
17
  def get_staged_diff() -> str:
15
18
  try:
16
- staged_diff = subprocess.check_output([GIT_COMMAND, DIFF_SUBCOMMAND, CACHED_FLAG]).decode(UTF8_ENCODING)
19
+ logger.debug('Running: %s %s %s', GIT_COMMAND, DIFF_SUBCOMMAND, CACHED_FLAG)
20
+ raw_diff_bytes = subprocess.check_output([GIT_COMMAND, DIFF_SUBCOMMAND, CACHED_FLAG])
21
+ staged_diff = raw_diff_bytes.decode(UTF8_ENCODING)
17
22
  except FileNotFoundError:
23
+ logger.error('git not found on PATH')
18
24
  raise GitError('git is not installed or not on PATH.')
19
25
  except subprocess.CalledProcessError:
26
+ logger.error('git diff --cached exited non-zero')
20
27
  raise GitError('Failed to get staged diff. Are you inside a git repository?')
21
28
  except UnicodeDecodeError:
29
+ logger.error('Staged diff could not be decoded as UTF-8')
22
30
  raise GitError('Staged diff contains bytes that could not be decoded as UTF-8.')
23
31
 
32
+ logger.debug('Staged diff received: %d chars', len(staged_diff))
33
+
24
34
  if not staged_diff:
35
+ logger.warning('No staged changes found')
25
36
  raise GitError('No staged changes found. Stage files with git add before running.')
26
37
 
27
38
  return staged_diff
@@ -29,8 +40,13 @@ def get_staged_diff() -> str:
29
40
 
30
41
  def commit(message: str) -> None:
31
42
  try:
43
+ logger.debug('Running: %s %s %s <message>', GIT_COMMAND, COMMIT_SUBCOMMAND, MESSAGE_FLAG)
32
44
  subprocess.run([GIT_COMMAND, COMMIT_SUBCOMMAND, MESSAGE_FLAG, message], check=True)
33
45
  except FileNotFoundError:
46
+ logger.error('git not found on PATH')
34
47
  raise GitError('git is not installed or not on PATH.')
35
48
  except subprocess.CalledProcessError:
49
+ logger.error('git commit exited non-zero')
36
50
  raise GitError('git commit failed.')
51
+
52
+ logger.info('Commit created successfully')
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: git-commit-msg-ai
3
- Version: 1.4.1
3
+ Version: 1.5.0
4
4
  Summary: AI-powered git commit message generator following Conventional Commits
5
5
  License-Expression: MIT
6
6
  Requires-Python: >=3.10
@@ -11,6 +11,8 @@ Requires-Dist: mypy; extra == "dev"
11
11
  Requires-Dist: ruff; extra == "dev"
12
12
  Requires-Dist: pytest; extra == "dev"
13
13
  Requires-Dist: pytest-cov; extra == "dev"
14
+ Requires-Dist: build; extra == "dev"
15
+ Requires-Dist: twine; extra == "dev"
14
16
 
15
17
  # git-commit-msg-ai
16
18
 
@@ -29,6 +31,38 @@ AI-powered git commit message generator that follows the [Conventional Commits](
29
31
  [System.Environment]::SetEnvironmentVariable('ANTHROPIC_API_KEY', 'sk-ant-...', 'User') # Windows
30
32
  ```
31
33
 
34
+ ## Development Setup
35
+
36
+ Clone the repository, create a virtual environment, and install the project in editable mode with all dev dependencies:
37
+
38
+ ```sh
39
+ python -m venv .venv
40
+ ```
41
+
42
+ Activate the virtual environment:
43
+
44
+ ```sh
45
+ # macOS/Linux
46
+ source .venv/bin/activate
47
+
48
+ # Windows PowerShell
49
+ .venv\Scripts\Activate.ps1
50
+ ```
51
+
52
+ Install the project and dev dependencies:
53
+
54
+ ```sh
55
+ pip install -e ".[dev]"
56
+ ```
57
+
58
+ After activation the `git-commit-msg-ai` entry-point is on your PATH. You can also run the dev toolchain:
59
+
60
+ ```sh
61
+ pytest # run tests with coverage
62
+ ruff check . # lint
63
+ mypy . # type-check
64
+ ```
65
+
32
66
  ## Installation
33
67
 
34
68
  ```sh
@@ -79,3 +113,25 @@ BREAKING CHANGE: /v1/legacy is no longer available
79
113
  ```
80
114
 
81
115
  Supported types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`
116
+
117
+ ## Debugging
118
+
119
+ By default the tool produces no diagnostic output. To enable logging, set the `GIT_COMMIT_AI_LOG_LEVEL` environment variable before running the command. Logs are written to **stderr** and do not interfere with the generated commit message on **stdout**.
120
+
121
+ Valid values: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`
122
+
123
+ ```sh
124
+ # macOS/Linux - show all internal diagnostic messages
125
+ GIT_COMMIT_AI_LOG_LEVEL=DEBUG git-commit-msg-ai
126
+
127
+ # Windows PowerShell
128
+ $env:GIT_COMMIT_AI_LOG_LEVEL = 'DEBUG'
129
+ git-commit-msg-ai
130
+ ```
131
+
132
+ | Level | What you see |
133
+ |---|---|
134
+ | `DEBUG` | git commands run, API model/token params, temp file paths, char counts |
135
+ | `INFO` | commit message generated, commit created |
136
+ | `WARNING` | no staged changes found |
137
+ | `ERROR` | git not found, API failures, editor errors |
@@ -5,3 +5,5 @@ mypy
5
5
  ruff
6
6
  pytest
7
7
  pytest-cov
8
+ build
9
+ twine
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "git-commit-msg-ai"
7
- version = "1.4.1"
7
+ version = "1.5.0"
8
8
  description = "AI-powered git commit message generator following Conventional Commits"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -15,7 +15,7 @@ dependencies = ["anthropic"]
15
15
  git-commit-msg-ai = "git_commit_msg_ai.cli:main"
16
16
 
17
17
  [project.optional-dependencies]
18
- dev = ["mypy", "ruff", "pytest", "pytest-cov"]
18
+ dev = ["mypy", "ruff", "pytest", "pytest-cov", "build", "twine"]
19
19
 
20
20
  [tool.ruff]
21
21
  target-version = "py310"
@@ -0,0 +1,158 @@
1
+ import logging
2
+ from contextlib import ExitStack
3
+ from unittest.mock import MagicMock, patch
4
+
5
+ import anthropic
6
+ import pytest
7
+
8
+ from git_commit_msg_ai.ai_client import MAX_TOKENS, MODEL, generate_commit_message
9
+ from git_commit_msg_ai.exceptions import AIError
10
+
11
+
12
+ def _make_api_response(text: str) -> MagicMock:
13
+ mock_text_block = MagicMock(spec=anthropic.types.TextBlock)
14
+ mock_text_block.text = text
15
+
16
+ mock_response = MagicMock(spec=anthropic.types.Message)
17
+ mock_response.content = [mock_text_block]
18
+
19
+ return mock_response
20
+
21
+
22
+ def _make_status_error(exception_class: type[anthropic.APIStatusError], status_code: int) -> anthropic.APIStatusError:
23
+ mock_response = MagicMock()
24
+ mock_response.status_code = status_code
25
+
26
+ return exception_class('error', response=mock_response, body={})
27
+
28
+
29
+ class TestGenerateCommitMessage:
30
+ def test_returns_stripped_commit_message(self) -> None:
31
+ with ExitStack() as stack:
32
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
33
+ mock_client = MagicMock()
34
+ mock_client.messages.create.return_value = _make_api_response(' feat: add feature ')
35
+ mock_anthropic_class.return_value = mock_client
36
+
37
+ result = generate_commit_message('diff content')
38
+
39
+ assert result == 'feat: add feature'
40
+
41
+ def test_raises_ai_error_on_authentication_error(self) -> None:
42
+ with ExitStack() as stack:
43
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
44
+ mock_client = MagicMock()
45
+ mock_client.messages.create.side_effect = _make_status_error(anthropic.AuthenticationError, 401)
46
+ mock_anthropic_class.return_value = mock_client
47
+
48
+ with pytest.raises(AIError, match='ANTHROPIC_API_KEY'):
49
+ generate_commit_message('diff content')
50
+
51
+ def test_raises_ai_error_on_rate_limit_error(self) -> None:
52
+ with ExitStack() as stack:
53
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
54
+ mock_client = MagicMock()
55
+ mock_client.messages.create.side_effect = _make_status_error(anthropic.RateLimitError, 429)
56
+ mock_anthropic_class.return_value = mock_client
57
+
58
+ with pytest.raises(AIError, match='rate limit'):
59
+ generate_commit_message('diff content')
60
+
61
+ def test_raises_ai_error_on_api_connection_error(self) -> None:
62
+ mock_request = MagicMock()
63
+
64
+ with ExitStack() as stack:
65
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
66
+ mock_client = MagicMock()
67
+ mock_client.messages.create.side_effect = anthropic.APIConnectionError(request=mock_request)
68
+ mock_anthropic_class.return_value = mock_client
69
+
70
+ with pytest.raises(AIError, match='network'):
71
+ generate_commit_message('diff content')
72
+
73
+ def test_raises_ai_error_on_api_status_error_with_status_code(self) -> None:
74
+ with ExitStack() as stack:
75
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
76
+ mock_client = MagicMock()
77
+ mock_client.messages.create.side_effect = _make_status_error(anthropic.APIStatusError, 500)
78
+ mock_anthropic_class.return_value = mock_client
79
+
80
+ with pytest.raises(AIError, match='500'):
81
+ generate_commit_message('diff content')
82
+
83
+ def test_logs_debug_before_api_call(self, caplog: pytest.LogCaptureFixture) -> None:
84
+ with caplog.at_level(logging.DEBUG, logger='git_commit_msg_ai.ai_client'):
85
+ with ExitStack() as stack:
86
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
87
+ mock_client = MagicMock()
88
+ mock_client.messages.create.return_value = _make_api_response('feat: add feature')
89
+ mock_anthropic_class.return_value = mock_client
90
+ generate_commit_message('diff content')
91
+
92
+ messages = [r.message for r in caplog.records]
93
+ assert any(MODEL in m and str(MAX_TOKENS) in m for m in messages)
94
+
95
+ def test_logs_info_after_message_generated(self, caplog: pytest.LogCaptureFixture) -> None:
96
+ with caplog.at_level(logging.INFO, logger='git_commit_msg_ai.ai_client'):
97
+ with ExitStack() as stack:
98
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
99
+ mock_client = MagicMock()
100
+ mock_client.messages.create.return_value = _make_api_response('feat: add feature')
101
+ mock_anthropic_class.return_value = mock_client
102
+ generate_commit_message('diff content')
103
+
104
+ assert any(r.levelno == logging.INFO and 'Commit message generated' in r.message for r in caplog.records)
105
+
106
+ def test_logs_error_on_authentication_error(self, caplog: pytest.LogCaptureFixture) -> None:
107
+ with caplog.at_level(logging.ERROR, logger='git_commit_msg_ai.ai_client'):
108
+ with ExitStack() as stack:
109
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
110
+ mock_client = MagicMock()
111
+ mock_client.messages.create.side_effect = _make_status_error(anthropic.AuthenticationError, 401)
112
+ mock_anthropic_class.return_value = mock_client
113
+
114
+ with pytest.raises(AIError):
115
+ generate_commit_message('diff content')
116
+
117
+ assert any(r.levelno == logging.ERROR for r in caplog.records)
118
+
119
+ def test_logs_error_on_rate_limit_error(self, caplog: pytest.LogCaptureFixture) -> None:
120
+ with caplog.at_level(logging.ERROR, logger='git_commit_msg_ai.ai_client'):
121
+ with ExitStack() as stack:
122
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
123
+ mock_client = MagicMock()
124
+ mock_client.messages.create.side_effect = _make_status_error(anthropic.RateLimitError, 429)
125
+ mock_anthropic_class.return_value = mock_client
126
+
127
+ with pytest.raises(AIError):
128
+ generate_commit_message('diff content')
129
+
130
+ assert any(r.levelno == logging.ERROR for r in caplog.records)
131
+
132
+ def test_logs_error_on_api_connection_error(self, caplog: pytest.LogCaptureFixture) -> None:
133
+ mock_request = MagicMock()
134
+
135
+ with caplog.at_level(logging.ERROR, logger='git_commit_msg_ai.ai_client'):
136
+ with ExitStack() as stack:
137
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
138
+ mock_client = MagicMock()
139
+ mock_client.messages.create.side_effect = anthropic.APIConnectionError(request=mock_request)
140
+ mock_anthropic_class.return_value = mock_client
141
+
142
+ with pytest.raises(AIError):
143
+ generate_commit_message('diff content')
144
+
145
+ assert any(r.levelno == logging.ERROR for r in caplog.records)
146
+
147
+ def test_logs_error_on_api_status_error(self, caplog: pytest.LogCaptureFixture) -> None:
148
+ with caplog.at_level(logging.ERROR, logger='git_commit_msg_ai.ai_client'):
149
+ with ExitStack() as stack:
150
+ mock_anthropic_class = stack.enter_context(patch('git_commit_msg_ai.ai_client.anthropic.Anthropic'))
151
+ mock_client = MagicMock()
152
+ mock_client.messages.create.side_effect = _make_status_error(anthropic.APIStatusError, 500)
153
+ mock_anthropic_class.return_value = mock_client
154
+
155
+ with pytest.raises(AIError):
156
+ generate_commit_message('diff content')
157
+
158
+ assert any(r.levelno == logging.ERROR and '500' in r.message for r in caplog.records)
@@ -1,9 +1,11 @@
1
+ import logging
2
+ import sys
1
3
  from contextlib import ExitStack
2
4
  from unittest.mock import MagicMock, patch
3
5
 
4
6
  import pytest
5
7
 
6
- from git_commit_msg_ai.cli import main
8
+ from git_commit_msg_ai.cli import LOG_LEVEL_ENV_VAR, main
7
9
  from git_commit_msg_ai.exceptions import AIError, GitError
8
10
 
9
11
  COMMIT_MESSAGE = 'feat: add feature'
@@ -147,3 +149,71 @@ class TestMain:
147
149
 
148
150
  assert exc_info.value.code == 1
149
151
  assert 'Aborted.' in capsys.readouterr().out
152
+
153
+
154
+ class TestLoggingConfiguration:
155
+ def _run_main_rejecting(self) -> None:
156
+ mock_git_ops = MagicMock()
157
+ mock_git_ops.get_staged_diff.return_value = 'diff'
158
+
159
+ mock_ai_client = MagicMock()
160
+ mock_ai_client.generate_commit_message.return_value = 'feat: x'
161
+
162
+ with ExitStack() as stack:
163
+ stack.enter_context(patch('git_commit_msg_ai.cli.git_ops', mock_git_ops))
164
+ stack.enter_context(patch('git_commit_msg_ai.cli.ai_client', mock_ai_client))
165
+ stack.enter_context(patch('git_commit_msg_ai.cli.editor'))
166
+ stack.enter_context(patch('builtins.input', return_value='r'))
167
+ main()
168
+
169
+ def test_uses_warning_level_when_env_var_absent(self) -> None:
170
+ with ExitStack() as stack:
171
+ mock_basic_config = stack.enter_context(patch('git_commit_msg_ai.cli.logging.basicConfig'))
172
+ stack.enter_context(patch.dict('os.environ', {}, clear=True))
173
+ self._run_main_rejecting()
174
+
175
+ mock_basic_config.assert_called_once_with(level=logging.WARNING, format='%(levelname)s:%(name)s:%(message)s', stream=sys.stderr)
176
+
177
+ def test_uses_debug_level_from_env_var(self) -> None:
178
+ with ExitStack() as stack:
179
+ mock_basic_config = stack.enter_context(patch('git_commit_msg_ai.cli.logging.basicConfig'))
180
+ stack.enter_context(patch.dict('os.environ', {LOG_LEVEL_ENV_VAR: 'DEBUG'}))
181
+ self._run_main_rejecting()
182
+
183
+ mock_basic_config.assert_called_once_with(level=logging.DEBUG, format='%(levelname)s:%(name)s:%(message)s', stream=sys.stderr)
184
+
185
+ def test_uses_info_level_from_env_var(self) -> None:
186
+ with ExitStack() as stack:
187
+ mock_basic_config = stack.enter_context(patch('git_commit_msg_ai.cli.logging.basicConfig'))
188
+ stack.enter_context(patch.dict('os.environ', {LOG_LEVEL_ENV_VAR: 'INFO'}))
189
+ self._run_main_rejecting()
190
+
191
+ mock_basic_config.assert_called_once_with(level=logging.INFO, format='%(levelname)s:%(name)s:%(message)s', stream=sys.stderr)
192
+
193
+ def test_invalid_env_var_falls_back_to_warning(self) -> None:
194
+ with ExitStack() as stack:
195
+ mock_basic_config = stack.enter_context(patch('git_commit_msg_ai.cli.logging.basicConfig'))
196
+ mock_log_warning = stack.enter_context(patch('git_commit_msg_ai.cli.logging.warning'))
197
+ stack.enter_context(patch.dict('os.environ', {LOG_LEVEL_ENV_VAR: 'BANANA'}))
198
+ self._run_main_rejecting()
199
+
200
+ mock_basic_config.assert_called_once_with(level=logging.WARNING, format='%(levelname)s:%(name)s:%(message)s', stream=sys.stderr)
201
+ assert 'BANANA' in str(mock_log_warning.call_args)
202
+
203
+ def test_logs_to_stderr(self) -> None:
204
+ with ExitStack() as stack:
205
+ mock_basic_config = stack.enter_context(patch('git_commit_msg_ai.cli.logging.basicConfig'))
206
+ stack.enter_context(patch.dict('os.environ', {}, clear=True))
207
+ self._run_main_rejecting()
208
+
209
+ _, kwargs = mock_basic_config.call_args
210
+ assert kwargs['stream'] is sys.stderr
211
+
212
+ def test_uses_expected_log_format(self) -> None:
213
+ with ExitStack() as stack:
214
+ mock_basic_config = stack.enter_context(patch('git_commit_msg_ai.cli.logging.basicConfig'))
215
+ stack.enter_context(patch.dict('os.environ', {}, clear=True))
216
+ self._run_main_rejecting()
217
+
218
+ _, kwargs = mock_basic_config.call_args
219
+ assert kwargs['format'] == '%(levelname)s:%(name)s:%(message)s'