commitwise 0.1.1__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 ADDED
File without changes
File without changes
commitwise/ai/base.py ADDED
@@ -0,0 +1,37 @@
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
+ Rules:
13
+ - Output ONLY the commit message text.
14
+ - Do NOT include explanations.
15
+ - Do NOT include markdown.
16
+ - Do NOT include code fences.
17
+ - Do NOT include phrases like "Here is" or "This commit message".
18
+
19
+ Format:
20
+ - First line: short imperative summary (max 72 chars)
21
+ - Blank line
22
+ - Optional detailed description
23
+
24
+ Staged diff:
25
+ """
26
+
27
+ def __init__(self, prompt: str):
28
+ # use provided prompt or default
29
+ self.prompt = prompt or self.default_prompt
30
+
31
+ @abstractmethod
32
+ def generate_commit(self, diff: str) -> str:
33
+ """
34
+ Generate a git commit message from a staged diff
35
+ """
36
+
37
+ raise NotImplementedError
@@ -0,0 +1,39 @@
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
@@ -0,0 +1,35 @@
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
@@ -0,0 +1,48 @@
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
commitwise/cli.py ADDED
@@ -0,0 +1,73 @@
1
+ import argparse
2
+ import sys
3
+
4
+ from commitwise.git_utils import (
5
+ get_staged_diff,
6
+ git_commit_with_message,
7
+ )
8
+ from commitwise.file_source import read_commit_file
9
+ from commitwise.ai_source import generate_ai_commit_message
10
+
11
+
12
+ def build_parser() -> argparse.ArgumentParser:
13
+ parser = argparse.ArgumentParser(
14
+ prog="commitwise",
15
+ description="CommitWise - Smart Git commits, wisely.",
16
+ formatter_class=argparse.RawTextHelpFormatter,
17
+ )
18
+
19
+ parser.add_argument(
20
+ "--ai",
21
+ action="store_true",
22
+ help=(
23
+ "Generate commit message using AI.\n"
24
+ "Automatically uses OpenAI if OPENAI_APP_KEY is set,\n"
25
+ "otherwise falls back to a local model (Ollama)."
26
+ ),
27
+ )
28
+
29
+ parser.add_argument(
30
+ "--file",
31
+ metavar="PATH",
32
+ help=(
33
+ "Read commit message from a text file and commit it\n"
34
+ "exactly as written (preserves formatting)."
35
+ ),
36
+ )
37
+
38
+ return parser
39
+
40
+
41
+ def main() -> None:
42
+ parser = build_parser()
43
+ args = parser.parse_args()
44
+
45
+ # [X] both flags used
46
+ if args.ai and args.file:
47
+ parser.error("Use either --ai or --file, not both.")
48
+
49
+ # [X] no mode selected
50
+ if not args.ai and not args.file:
51
+ parser.print_help()
52
+ sys.exit(0)
53
+
54
+ try:
55
+ # AI mode
56
+ if args.ai:
57
+ diff = get_staged_diff()
58
+ message = generate_ai_commit_message(diff)
59
+ git_commit_with_message(message)
60
+ return
61
+
62
+ # File mode
63
+ if args.file:
64
+ message = read_commit_file(args.file)
65
+ git_commit_with_message(message)
66
+ return
67
+ except Exception as e:
68
+ print(f"\n [X] Error: {e}", file=sys.stderr)
69
+ sys.exit(1)
70
+
71
+
72
+ if __name__ == "__main__":
73
+ main()
commitwise/config.py ADDED
@@ -0,0 +1,9 @@
1
+ import os
2
+
3
+ # OpenAI configuration (optional)
4
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
5
+
6
+
7
+ # Local AI (Ollama) configuration
8
+ LOCAL_MODEL = os.getenv("LOCAL_MODEL", "llama3")
9
+ LOCAL_API_URL = os.getenv("LOCAL_API_URL", "http://localhost:11434")
@@ -0,0 +1,25 @@
1
+ from pathlib import Path
2
+
3
+
4
+ def read_commit_file(path: str) -> str:
5
+ """
6
+ Read a commit message from a text file and return it exactly as written.
7
+ Preserves formatting, newlines, spacing, and punctuation
8
+ """
9
+
10
+ file_path = Path(path)
11
+
12
+ if not file_path.exists():
13
+ raise FileNotFoundError(f"Commit message file not found: {path}")
14
+
15
+ if not file_path.is_file():
16
+ raise ValueError(f"Provided path is not a file: {path}")
17
+
18
+ content = file_path.read_text(encoding="utf-8")
19
+
20
+ if not content.strip():
21
+ raise ValueError("Commit message file is empty.")
22
+
23
+ # Do NOT modify formatting.
24
+ # Only ensure there is no excessive trailing whitespace at the end.
25
+ return content.rstrip()
@@ -0,0 +1,47 @@
1
+ import subprocess
2
+ import tempfile
3
+ import os
4
+
5
+
6
+ def get_staged_diff() -> str:
7
+ """
8
+ Return the staged git diff
9
+ Raises an error if there are no staged changes
10
+ """
11
+
12
+ result = subprocess.run(["git", "diff", "--cached"], capture_output=True, text=True)
13
+
14
+ diff = result.stdout.strip()
15
+
16
+ if not diff:
17
+ raise RuntimeError(
18
+ "No staged changes found.\nPlease run `git add` before using CommitWise."
19
+ )
20
+ return diff
21
+
22
+
23
+ def git_commit_with_message(message: str) -> None:
24
+ """
25
+ Perform a git commit using the given commit message.
26
+ The message is written to a temporary file and passed to
27
+ `git commit -F` to preserve formatting exactly.
28
+ """
29
+
30
+ if not message or not message.strip():
31
+ raise ValueError("Commit message is empty.")
32
+
33
+ temp_file_path = None
34
+
35
+ try:
36
+ with tempfile.NamedTemporaryFile(
37
+ mode="w",
38
+ encoding="utf-8",
39
+ delete=False,
40
+ ) as tmp:
41
+ tmp.write(message.rstrip() + "\n")
42
+ temp_file_path = tmp.name
43
+
44
+ subprocess.run(["git", "commit", "-F", temp_file_path], check=True)
45
+ finally:
46
+ if temp_file_path and os.path.exists(temp_file_path):
47
+ os.remove(temp_file_path)
@@ -0,0 +1,85 @@
1
+ Metadata-Version: 2.4
2
+ Name: commitwise
3
+ Version: 0.1.1
4
+ Summary: Generate clean git commit messages from files or AI
5
+ Author-email: Abolfazl Hassan Zade <abolfazl.hassanzade.81@gmail.com>
6
+ License: MIT
7
+ Project-URL: homepage, https://github.com/hasssan-hasssan/commitwise
8
+ Project-URL: repository, https://github.com/hasssan-hasssan/commitwise
9
+ Project-URL: issues, https://github.com/hasssan-hasssan/commitwise/issues
10
+ Keywords: git,commit,cli,ai
11
+ Requires-Python: >=3.9
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: requests>=2.31.0
14
+
15
+ CommitWise
16
+ ===========
17
+
18
+ CommitWise is a smart and simple tool for generating clean Git commit messages.
19
+ It can create commit messages from a text file or using AI models.
20
+
21
+ With CommitWise, your commits are always:
22
+ - Clean and readable
23
+ - Following Git best practices
24
+ - Well-structured and informative
25
+
26
+ Features
27
+ --------
28
+
29
+ - Generate commits from text files, preserving exact formatting, spacing, and paragraphs
30
+ - Generate commits using AI (local with Ollama or OpenAI API)
31
+ - Simple and easy-to-use CLI with only a few flags
32
+ - Works seamlessly in any Git project
33
+
34
+ Installation
35
+ ------------
36
+
37
+ pip install commitwise
38
+
39
+ Usage
40
+ -----
41
+
42
+ Generate commit from AI (local or OpenAI):
43
+ commitwise --ai
44
+
45
+ Generate commit from a text file:
46
+ commitwise --file ./my_commit.txt
47
+
48
+ Show help:
49
+ commitwise --help
50
+
51
+ Requirements
52
+ ------------
53
+
54
+ - Python >= 3.9
55
+ - For local AI: Ollama installed and the desired model downloaded
56
+ - For online AI: OpenAI API Key (if using OpenAI)
57
+
58
+ Professional Note
59
+ -----------------
60
+
61
+ CommitWise ensures that AI-generated commit messages are clean and Git-ready,
62
+ without extra explanations, markdown, or educational text.
63
+ This is guaranteed through strict prompting and output cleaning.
64
+
65
+ Links
66
+ -----
67
+
68
+ GitHub Repository: https://github.com/hasssan-hasssan/commitwise
69
+
70
+ PyPI: https://pypi.org/project/commitwise
71
+
72
+ Support
73
+ -------
74
+
75
+ If CommitWise is helpful, please give it a star on GitHub so others can find it!
76
+
77
+ GitHub About Section
78
+ -------------------
79
+
80
+ CommitWise: Generate clean Git commit messages from files or AI.
81
+
82
+ Supports local AI (Ollama) or OpenAI API for automatic commit generation.
83
+
84
+ Simple CLI with --ai and --file modes.
85
+
@@ -0,0 +1,15 @@
1
+ commitwise/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ commitwise/ai_source.py,sha256=BD79fQQb654AaKmHH2_JzVidzwUEHd55ny5aO0e5vtU,1417
3
+ commitwise/cli.py,sha256=BqHfbTrXBcyClCWloFxGeiJn5cYgSzlTqXxG1cCUpJQ,1878
4
+ commitwise/config.py,sha256=Jovf7YfV0N8CFz2jBns_UBAgfuO8un8fivezNFGSbYc,253
5
+ commitwise/file_source.py,sha256=3pzFAsFYyXQSLQrfr_YGA5GAV-vtUP5Co4YhG-XOhnc,751
6
+ commitwise/git_utils.py,sha256=ylqrKvsMratrHZS74cQy4xqAI6HJjJhJ_nU9amqWoUo,1289
7
+ commitwise/ai/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ commitwise/ai/base.py,sha256=v7DoQLPOeYmOfVXtvMtDWVS7DBMOGQylDv_dvScXkBk,929
9
+ commitwise/ai/local_engine.py,sha256=YwiusAokL_t0PiJ53gf8IAJGynHrEYAv0Cyy_QpdnpM,1007
10
+ commitwise/ai/openai_engine.py,sha256=8_xErkmsjzXyNwlPVgrlwxumt2y5ZhhWYo1I9nUKpqE,1006
11
+ commitwise-0.1.1.dist-info/METADATA,sha256=iyeWtu9JVRbRTigRNkV6h6ScADsUSrJPETZjOYCLbro,2249
12
+ commitwise-0.1.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
13
+ commitwise-0.1.1.dist-info/entry_points.txt,sha256=WUow9mgob_PQfVpk5QuVpoWXYnALsOar3NCyDWJCQuk,51
14
+ commitwise-0.1.1.dist-info/top_level.txt,sha256=8uL7do0ZoZw67O5fzMSxbqQcJkMH3OHeHhONQuS3D88,11
15
+ commitwise-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ commitwise = commitwise.cli:main
@@ -0,0 +1 @@
1
+ commitwise