commitwise 0.1.4__py3-none-any.whl → 0.1.6__py3-none-any.whl

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.
commitwise/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__='0.1.4'
1
+ __version__='0.1.6'
commitwise/ai/base.py CHANGED
@@ -1,60 +1,60 @@
1
- from abc import ABC, abstractmethod
2
-
3
-
4
- class AIEngine(ABC):
5
- """
6
- Base interface for AI enignes used by CommitWise
7
- """
8
-
9
- default_prompt: str = """
10
- You are generating a Git commit message.
11
-
12
- STRICT RULES:
13
- - Output ONLY the commit message text.
14
- - Do NOT include explanations, markdown, code fences, or extra text.
15
- - Do NOT say things like "Here is" or "This commit message".
16
-
17
- FORMAT:
18
- 1. Use Conventional Commits format:
19
- <type>(<optional scope>): <short imperative summary>
20
-
21
- 2. Allowed types:
22
- feat, fix, refactor, docs, test, chore
23
-
24
- 3. The first line:
25
- - Must be imperative (e.g. add, fix, refactor, remove)
26
- - Must be concise and clear
27
- - Must be at most 72 characters
28
-
29
- 4. If a body is needed:
30
- - Leave exactly one blank line after the title
31
- - Each line MUST start with "- "
32
- - Describe WHAT changed (not why)
33
- - Keep lines short and scannable
34
-
35
- 5. Do NOT invent changes.
36
- - Only describe what is present in the staged diff.
37
-
38
- EXAMPLE OUTPUT:
39
-
40
- refactor(ai): centralize and enforce strict commit prompt
41
-
42
- - move AI commit prompt to base AIEngine
43
- - enforce clean, git-ready output rules
44
- - remove duplicated prompt logic from AI engines
45
-
46
- STAGED DIFF:
47
-
48
- """
49
-
50
- def __init__(self, prompt: str):
51
- # use provided prompt or default
52
- self.prompt = prompt or self.default_prompt
53
-
54
- @abstractmethod
55
- def generate_commit(self, diff: str) -> str:
56
- """
57
- Generate a git commit message from a staged diff
58
- """
59
-
60
- raise NotImplementedError
1
+ from abc import ABC, abstractmethod
2
+
3
+
4
+ class AIEngine(ABC):
5
+ """
6
+ Base interface for AI enignes used by CommitWise
7
+ """
8
+
9
+ default_prompt: str = """
10
+ You are generating a Git commit message.
11
+
12
+ STRICT RULES:
13
+ - Output ONLY the commit message text.
14
+ - Do NOT include explanations, markdown, code fences, or extra text.
15
+ - Do NOT say things like "Here is" or "This commit message".
16
+
17
+ FORMAT:
18
+ 1. Use Conventional Commits format:
19
+ <type>(<optional scope>): <short imperative summary>
20
+
21
+ 2. Allowed types:
22
+ feat, fix, refactor, docs, test, chore
23
+
24
+ 3. The first line:
25
+ - Must be imperative (e.g. add, fix, refactor, remove)
26
+ - Must be concise and clear
27
+ - Must be at most 72 characters
28
+
29
+ 4. If a body is needed:
30
+ - Leave exactly one blank line after the title
31
+ - Each line MUST start with "- "
32
+ - Describe WHAT changed (not why)
33
+ - Keep lines short and scannable
34
+
35
+ 5. Do NOT invent changes.
36
+ - Only describe what is present in the staged diff.
37
+
38
+ EXAMPLE OUTPUT:
39
+
40
+ refactor(ai): centralize and enforce strict commit prompt
41
+
42
+ - move AI commit prompt to base AIEngine
43
+ - enforce clean, git-ready output rules
44
+ - remove duplicated prompt logic from AI engines
45
+
46
+ STAGED DIFF:
47
+
48
+ """
49
+
50
+ def __init__(self, prompt: str):
51
+ # use provided prompt or default
52
+ self.prompt = prompt or self.default_prompt
53
+
54
+ @abstractmethod
55
+ def generate_commit(self, diff: str) -> str:
56
+ """
57
+ Generate a git commit message from a staged diff
58
+ """
59
+
60
+ raise NotImplementedError
@@ -1,39 +1,69 @@
1
- import requests
2
-
3
- from commitwise.ai.base import AIEngine
4
-
5
-
6
- class LocalAIEngine(AIEngine):
7
- """
8
- Local AI engine using Ollama.
9
- """
10
-
11
- def __init__(self, model: str, url: str):
12
- self.model = model
13
- self.url = url.rstrip("/")
14
-
15
- def generate_commit(self, diff: str) -> str:
16
- prompt = self.default_prompt + f"\n{diff}"
17
-
18
- response = requests.post(
19
- f"{self.url}/api/generate",
20
- json={
21
- "model": self.model,
22
- "prompt": prompt,
23
- "stream": False,
24
- },
25
- timeout=60,
26
- )
27
-
28
- if response.status_code != 200:
29
- raise RuntimeError(
30
- f"Local AI request failed (status {response.status_code})"
31
- )
32
-
33
- data = response.json()
34
- message = data.get("response", "").strip()
35
-
36
- if not message:
37
- raise RuntimeError("Local AI returned an empty commit message.")
38
-
39
- return message
1
+ import requests
2
+
3
+ from requests.exceptions import Timeout, ConnectionError as ReqConnectionError
4
+
5
+ from commitwise.ai.base import AIEngine
6
+ from commitwise.errors import (
7
+ AIProviderUnavailable,
8
+ AIProviderTimeout,
9
+ AIProviderConnectionError,
10
+ AIProviderResponseInvalid,
11
+ )
12
+
13
+ DEFAULT_TIMEOUT = 60
14
+
15
+
16
+ class LocalAIEngine(AIEngine):
17
+ """
18
+ Local AI engine using Ollama.
19
+ """
20
+
21
+ def __init__(self, model: str, url: str):
22
+ self.model = model
23
+ self.url = url.rstrip("/")
24
+
25
+ def generate_commit(self, diff: str) -> str:
26
+ prompt = self.default_prompt + f"\n{diff}"
27
+
28
+ try:
29
+ response = requests.post(
30
+ f"{self.url}/api/generate",
31
+ json={
32
+ "model": self.model,
33
+ "prompt": prompt,
34
+ "stream": False,
35
+ },
36
+ timeout=DEFAULT_TIMEOUT,
37
+ )
38
+
39
+ except Timeout:
40
+ raise AIProviderTimeout(
41
+ "Local AI model did not respond in time.\n\n "
42
+ "Try staging fewer changes or using a faster model."
43
+ )
44
+
45
+ except ReqConnectionError:
46
+ raise AIProviderUnavailable(
47
+ "Local AI service is not reachable.\n\n "
48
+ "Make sure Ollama is running (ollama serve)."
49
+ )
50
+
51
+ except Exception as exc:
52
+ raise AIProviderConnectionError(
53
+ f"Unexpected error while communicating with local AI: {exc}"
54
+ ) from exc
55
+
56
+ else:
57
+ if response.status_code != 200:
58
+ raise AIProviderUnavailable(
59
+ f"Local AI request failed with status {response.status_code}."
60
+ )
61
+
62
+ data = response.json()
63
+ message = data.get("response", "").strip()
64
+
65
+ if not message:
66
+ raise AIProviderResponseInvalid(
67
+ "Local AI returned an empty commit message."
68
+ )
69
+ return message
@@ -1,35 +1,66 @@
1
- from commitwise.ai.base import AIEngine
2
-
3
-
4
- class OpenAIEngine(AIEngine):
5
- """
6
- OpenAI-based AI engine (optional).
7
- """
8
-
9
- def __init__(self, api_key: str, model: str):
10
- self.api_key = api_key
11
- self.model = model
12
-
13
- def generate_commit(self, diff) -> str:
14
- try:
15
- from openai import OpenAI
16
- except ImportError as exc:
17
- raise RuntimeError(
18
- "OpenAI SDK is not installed. Install it with: pip install openai"
19
- ) from exc
20
- client = OpenAI(api_key=self.api_key)
21
-
22
- prompt = self.default_prompt + f"\n{diff}"
23
-
24
- response = client.chat.completions.create(
25
- model=self.model,
26
- message=[
27
- {"role": "user", "content": prompt},
28
- ],
29
- )
30
-
31
- message = response.choices[0].message.content.strip()
32
-
33
- if not message:
34
- raise RuntimeError("OpenAI returned an empty commit message.")
35
- return message
1
+ from commitwise.ai.base import AIEngine
2
+ from commitwise.errors import (
3
+ AIProviderNotConfigured,
4
+ AIProviderAuthError,
5
+ AIProviderRateLimitError,
6
+ AIProviderTimeout,
7
+ AIProviderConnectionError,
8
+ AIProviderResponseInvalid,
9
+ )
10
+
11
+
12
+ from openai import OpenAI
13
+ from openai import (
14
+ AuthenticationError,
15
+ RateLimitError,
16
+ APIConnectionError,
17
+ APITimeoutError,
18
+ OpenAIError,
19
+ )
20
+
21
+
22
+ class OpenAIEngine(AIEngine):
23
+ """
24
+ OpenAI-based AI engine (optional).
25
+ """
26
+
27
+ def __init__(self, api_key: str, model: str):
28
+ if not api_key:
29
+ raise AIProviderNotConfigured("OPENAI_API_KEY is not set.")
30
+
31
+ self.client = OpenAI(api_key=api_key)
32
+ self.model = model
33
+
34
+ def generate_commit(self, diff) -> str:
35
+ prompt = self.default_prompt + f"\n{diff}"
36
+ try:
37
+ response = self.client.chat.completions.create(
38
+ model=self.model,
39
+ messages=[
40
+ {"role": "user", "content": prompt},
41
+ ],
42
+ )
43
+ except AuthenticationError:
44
+ raise AIProviderAuthError("Invalid OpenAI API key.")
45
+
46
+ except RateLimitError:
47
+ raise AIProviderRateLimitError("OpenAI rate limit exceeded.")
48
+
49
+ except APITimeoutError:
50
+ raise AIProviderTimeout("OpenAI request timed out.")
51
+
52
+ except APIConnectionError:
53
+ raise AIProviderConnectionError("Failed to connect to OpenAI API.")
54
+
55
+ except OpenAIError as exc:
56
+ raise AIProviderConnectionError(f"Unexpected OpenAI error: {exc}") from exc
57
+
58
+ try:
59
+ message = response.choices[0].message.content.strip()
60
+ except Exception:
61
+ raise AIProviderResponseInvalid("OpenAI returned an invalid response.")
62
+
63
+ if not message:
64
+ raise AIProviderResponseInvalid("OpenAI returned an empty commit message.")
65
+
66
+ return message
commitwise/ai_source.py CHANGED
@@ -1,48 +1,56 @@
1
- from commitwise.config import (
2
- OPENAI_API_KEY,
3
- LOCAL_MODEL,
4
- LOCAL_API_URL,
5
- )
6
-
7
- from commitwise.ai.openai_engine import OpenAIEngine
8
- from commitwise.ai.local_engine import LocalAIEngine
9
-
10
-
11
- def generate_ai_commit_message(diff: str) -> str:
12
- """
13
- Generate a git commit message using the best available AI provider.
14
-
15
- Priority:
16
- 1. OpenAI (if OPENAI_API_KEY is set)
17
- 2. Local AI (Ollama)
18
-
19
- Raises a clear error if no AI provider is available.
20
- """
21
- # Try OpenAI
22
- if OPENAI_API_KEY:
23
- try:
24
- engine = OpenAIEngine(
25
- api_key=OPENAI_API_KEY,
26
- model="gpt-4.1-mini",
27
- )
28
- return engine.generate_commit(diff)
29
- except Exception as exc:
30
- raise RuntimeError(
31
- "Failed to generate commit message using OpenAI."
32
- ) from exc
33
-
34
- # Fallback to Local AI
35
- try:
36
- engine = LocalAIEngine(
37
- model=LOCAL_MODEL,
38
- url=LOCAL_API_URL,
39
- )
40
- return engine.generate_commit(diff)
41
- except Exception as exc:
42
- raise RuntimeError(
43
- "No AI provider available.\n\n"
44
- "To use AI commits, you must either:\n"
45
- "- Set OPENAI_API_KEY to use OpenAI\n"
46
- "- Or install and run a local AI model (e.g. Ollama)\n\n"
47
- "https://ollama.com"
48
- ) from exc
1
+ from commitwise.config import (
2
+ OPENAI_API_KEY,
3
+ LOCAL_MODEL,
4
+ LOCAL_API_URL,
5
+ )
6
+
7
+ from commitwise.ai.openai_engine import OpenAIEngine
8
+ from commitwise.ai.local_engine import LocalAIEngine
9
+ from commitwise.errors import AIError, AIProviderNotConfigured
10
+
11
+
12
+ def generate_ai_commit_message(diff: str) -> str:
13
+ """
14
+ Generate a git commit message using the best available AI provider.
15
+
16
+ Priority:
17
+ 1. OpenAI (if OPENAI_API_KEY is set)
18
+ 2. Local AI (Ollama)
19
+
20
+ Raises a clear error if no AI provider is available.
21
+ """
22
+
23
+ last_error: AIError | None = None
24
+
25
+ # Try OpenAI
26
+ if OPENAI_API_KEY:
27
+ try:
28
+ engine = OpenAIEngine(
29
+ api_key=OPENAI_API_KEY,
30
+ model="gpt-4.1-mini",
31
+ )
32
+ return engine.generate_commit(diff)
33
+ except AIError as exc:
34
+ last_error = exc
35
+
36
+ # Fallback to Local AI
37
+ if LOCAL_MODEL and LOCAL_API_URL:
38
+ try:
39
+ engine = LocalAIEngine(
40
+ model=LOCAL_MODEL,
41
+ url=LOCAL_API_URL,
42
+ )
43
+ return engine.generate_commit(diff)
44
+ except AIError as exc:
45
+ last_error = exc
46
+
47
+ if last_error:
48
+ raise last_error
49
+
50
+ raise AIProviderNotConfigured(
51
+ "No AI provider is configured.\n\n"
52
+ "To use AI commits, you must either:\n"
53
+ "- Set OPENAI_API_KEY to use OpenAI\n"
54
+ "- Or install and run a local AI model (e.g. Ollama)\n\n"
55
+ "https://ollama.com"
56
+ )
commitwise/cli.py CHANGED
@@ -1,59 +1,96 @@
1
- import sys
2
-
3
- from commitwise import __version__
4
- from commitwise.cli_utils import (
5
- build_parser,
6
- )
7
- from commitwise.git_utils import (
8
- get_staged_diff,
9
- git_commit_with_message,
10
- confirm_commit,
11
- )
12
- from commitwise.file_source import read_commit_file
13
- from commitwise.ai_source import generate_ai_commit_message
14
-
15
-
16
- def main() -> None:
17
- parser = build_parser()
18
- args = parser.parse_args()
19
-
20
- # version flag
21
- if args.version:
22
- print(f"commitwise {__version__}")
23
- sys.exit(0)
24
-
25
- # [X] both flags used
26
- if args.ai and args.file:
27
- parser.error("Use either --ai or --file, not both.")
28
-
29
- # [X] no mode selected
30
- if not args.ai and not args.file:
31
- parser.print_help()
32
- sys.exit(0)
33
-
34
- try:
35
- # AI mode
36
- if args.ai:
37
- diff = get_staged_diff()
38
- message = generate_ai_commit_message(diff)
39
-
40
- if not confirm_commit(message):
41
- print("\n\nCommit aborted.")
42
- sys.exit(0)
43
-
44
- git_commit_with_message(message)
45
- return
46
-
47
- # File mode
48
- if args.file:
49
- message = read_commit_file(args.file)
50
- git_commit_with_message(message)
51
- return
52
-
53
- except Exception as e:
54
- print(f"\n [X] Error: {e}", file=sys.stderr)
55
- sys.exit(1)
56
-
57
-
58
- if __name__ == "__main__":
59
- main()
1
+ import sys
2
+
3
+ from commitwise import __version__
4
+ from commitwise.cli_utils import (
5
+ build_parser,
6
+ )
7
+ from commitwise.git_utils import (
8
+ get_staged_diff,
9
+ git_commit_with_message,
10
+ confirm_commit,
11
+ )
12
+ from commitwise.file_source import read_commit_file
13
+ from commitwise.ai_source import generate_ai_commit_message
14
+ from commitwise.errors import (
15
+ CommitWiseError,
16
+ NoStagedChangesError,
17
+ UserAbortError,
18
+ AIProviderTimeout,
19
+ AIProviderAuthError,
20
+ )
21
+
22
+
23
+ def main() -> None:
24
+ parser = build_parser()
25
+ args = parser.parse_args()
26
+
27
+ # version flag
28
+ if args.version:
29
+ print(f"commitwise {__version__}")
30
+ sys.exit(0)
31
+
32
+ # [X] both flags used
33
+ if args.ai and args.file:
34
+ parser.error("Use either --ai or --file, not both.")
35
+
36
+ # [X] no mode selected
37
+ if not args.ai and not args.file:
38
+ parser.print_help()
39
+ sys.exit(0)
40
+
41
+ try:
42
+ # AI mode
43
+ if args.ai:
44
+ diff = get_staged_diff()
45
+ message = generate_ai_commit_message(diff)
46
+
47
+ if not confirm_commit(message):
48
+ print("\n\nCommit aborted.")
49
+ sys.exit(0)
50
+
51
+ git_commit_with_message(message)
52
+ return
53
+
54
+ # File mode
55
+ if args.file:
56
+ message = read_commit_file(args.file)
57
+ git_commit_with_message(message)
58
+ return
59
+
60
+ except UserAbortError:
61
+ print("\nCommit aborted.")
62
+ sys.exit(0)
63
+
64
+ except AIProviderTimeout:
65
+ print(
66
+ "\n[X] AI provider timed out.\n\n"
67
+ "This may happen due to a large diff or slow local inference.\n"
68
+ "Try committing smaller changes or another AI provider."
69
+ )
70
+ sys.exit(2)
71
+
72
+ except AIProviderAuthError:
73
+ print(
74
+ "\n[X] AI authentication failed.\n\n"
75
+ "Please check your API key configuration."
76
+ )
77
+ sys.exit(3)
78
+
79
+ except NoStagedChangesError:
80
+ print(
81
+ "\n[X] No staged changes found.\n\n"
82
+ "Please run `git add` before using CommitWise."
83
+ )
84
+ sys.exit(0)
85
+
86
+ except CommitWiseError as e:
87
+ print(f"\n[X] {e}", file=sys.stderr)
88
+ sys.exit(1)
89
+
90
+ except Exception as e:
91
+ print(f"\n[X] {e}", file=sys.stderr)
92
+ sys.exit(1)
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()