commitwise 0.1.4__py3-none-any.whl → 0.1.5__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.5'
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,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
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,35 +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
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
commitwise/ai_source.py CHANGED
@@ -1,48 +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
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 CHANGED
@@ -1,59 +1,59 @@
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
+
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()
commitwise/cli_utils.py CHANGED
@@ -1,87 +1,87 @@
1
- import argparse
2
- import os
3
- import sys
4
-
5
-
6
- def build_parser() -> argparse.ArgumentParser:
7
- """
8
- Defines and return all command-line flags for the CommitWise CLI.
9
-
10
- Flags:
11
- --version, -V
12
- Display the currently installed commitwise version.
13
-
14
- --ai
15
- Generate a commit message using AI.
16
-
17
- --file PATH
18
- Read a commit message from a text file and commit it
19
- exactly as written, preserving formatting.
20
-
21
- Returns:
22
- argparser.ArgumentParser: Configured parser with all CLI flags.
23
- """
24
-
25
- parser = argparse.ArgumentParser(
26
- prog="commitwise",
27
- description="CommitWise - Smart Git commits, wisely.",
28
- formatter_class=argparse.RawTextHelpFormatter,
29
- )
30
-
31
- parser.add_argument(
32
- "--version",
33
- "-V",
34
- action="store_true",
35
- help="Display the version of commitwise that is currently installed.",
36
- )
37
-
38
- parser.add_argument(
39
- "--ai",
40
- action="store_true",
41
- help=(
42
- "Generate commit message using AI.\n"
43
- "Automatically uses OpenAI if OPENAI_APP_KEY is set,\n"
44
- "otherwise falls back to a local model (Ollama)."
45
- ),
46
- )
47
-
48
- parser.add_argument(
49
- "--file",
50
- metavar="PATH",
51
- help=(
52
- "Read commit message from a text file and commit it\n"
53
- "exactly as written (preserves formatting)."
54
- ),
55
- )
56
-
57
- return parser
58
-
59
-
60
- def read_single_key() -> str:
61
- """
62
- Reads a single keypress from the user without requiring Enter.
63
-
64
- Works cross-platform:
65
- - Windows: uses msvcrt.getch()
66
- - Linux/macOS: uses termios and tty to set raw input mode.
67
-
68
- Returns:
69
- str: The pressed key as a lowercase string.
70
- """
71
-
72
- if os.name == "nt":
73
- import msvcrt
74
-
75
- return msvcrt.getch().decode("utf-8", errors="ignore").lower()
76
- else:
77
- import termios
78
- import tty
79
-
80
- fd = sys.stdin.fileno()
81
- old_settings = termios.tcgetattr(fd)
82
- try:
83
- tty.setraw(fd)
84
- ch = sys.stdin.read(1).lower()
85
- finally:
86
- termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
87
- return ch
1
+ import argparse
2
+ import os
3
+ import sys
4
+
5
+
6
+ def build_parser() -> argparse.ArgumentParser:
7
+ """
8
+ Defines and return all command-line flags for the CommitWise CLI.
9
+
10
+ Flags:
11
+ --version, -V
12
+ Display the currently installed commitwise version.
13
+
14
+ --ai
15
+ Generate a commit message using AI.
16
+
17
+ --file PATH
18
+ Read a commit message from a text file and commit it
19
+ exactly as written, preserving formatting.
20
+
21
+ Returns:
22
+ argparser.ArgumentParser: Configured parser with all CLI flags.
23
+ """
24
+
25
+ parser = argparse.ArgumentParser(
26
+ prog="commitwise",
27
+ description="CommitWise - Smart Git commits, wisely.",
28
+ formatter_class=argparse.RawTextHelpFormatter,
29
+ )
30
+
31
+ parser.add_argument(
32
+ "--version",
33
+ "-V",
34
+ action="store_true",
35
+ help="Display the version of commitwise that is currently installed.",
36
+ )
37
+
38
+ parser.add_argument(
39
+ "--ai",
40
+ action="store_true",
41
+ help=(
42
+ "Generate commit message using AI.\n"
43
+ "Automatically uses OpenAI if OPENAI_APP_KEY is set,\n"
44
+ "otherwise falls back to a local model (Ollama)."
45
+ ),
46
+ )
47
+
48
+ parser.add_argument(
49
+ "--file",
50
+ metavar="PATH",
51
+ help=(
52
+ "Read commit message from a text file and commit it\n"
53
+ "exactly as written (preserves formatting)."
54
+ ),
55
+ )
56
+
57
+ return parser
58
+
59
+
60
+ def read_single_key() -> str:
61
+ """
62
+ Reads a single keypress from the user without requiring Enter.
63
+
64
+ Works cross-platform:
65
+ - Windows: uses msvcrt.getch()
66
+ - Linux/macOS: uses termios and tty to set raw input mode.
67
+
68
+ Returns:
69
+ str: The pressed key as a lowercase string.
70
+ """
71
+
72
+ if os.name == "nt":
73
+ import msvcrt
74
+
75
+ return msvcrt.getch().decode("utf-8", errors="ignore").lower()
76
+ else:
77
+ import termios
78
+ import tty
79
+
80
+ fd = sys.stdin.fileno()
81
+ old_settings = termios.tcgetattr(fd)
82
+ try:
83
+ tty.setraw(fd)
84
+ ch = sys.stdin.read(1).lower()
85
+ finally:
86
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
87
+ return ch
commitwise/config.py CHANGED
@@ -1,9 +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")
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")
commitwise/file_source.py CHANGED
@@ -1,25 +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()
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()
commitwise/git_utils.py CHANGED
@@ -1,80 +1,80 @@
1
- import subprocess
2
- import tempfile
3
- import os
4
-
5
- from commitwise.cli_utils import read_single_key
6
-
7
-
8
- def get_staged_diff() -> str:
9
- """
10
- Return the staged git diff
11
- Raises an error if there are no staged changes
12
- """
13
-
14
- result = subprocess.run(["git", "diff", "--cached"], capture_output=True, text=True)
15
-
16
- diff = result.stdout.strip()
17
-
18
- if not diff:
19
- raise RuntimeError(
20
- "No staged changes found.\nPlease run `git add` before using CommitWise."
21
- )
22
- return diff
23
-
24
-
25
- def git_commit_with_message(message: str) -> None:
26
- """
27
- Perform a git commit using the given commit message.
28
- The message is written to a temporary file and passed to
29
- `git commit -F` to preserve formatting exactly.
30
- """
31
-
32
- if not message or not message.strip():
33
- raise ValueError("Commit message is empty.")
34
-
35
- temp_file_path = None
36
-
37
- try:
38
- with tempfile.NamedTemporaryFile(
39
- mode="w",
40
- encoding="utf-8",
41
- delete=False,
42
- ) as tmp:
43
- tmp.write(message.rstrip() + "\n")
44
- temp_file_path = tmp.name
45
-
46
- # subprocess.run(["git", "commit", "-F", temp_file_path], check=True)
47
- result = subprocess.run(
48
- ["git", "commit", "-F", temp_file_path],
49
- capture_output=True,
50
- text=True,
51
- ).stdout.strip()
52
-
53
- output_message = (
54
- f"\n\n[✔] Commit created successfully. More details:\n\n{result}"
55
- )
56
-
57
- print(output_message)
58
-
59
- finally:
60
- if temp_file_path and os.path.exists(temp_file_path):
61
- os.remove(temp_file_path)
62
-
63
-
64
- def confirm_commit(message: str) -> bool:
65
- """
66
- Confirm the suggested commit message.
67
- """
68
- print("\nProposed commit message:\n")
69
- print("-" * 40)
70
- print(message.strip())
71
- print("-" * 40)
72
- print("\nCommit this message? [y/n] ", end="", flush=True)
73
-
74
- while True:
75
- key = read_single_key()
76
- if key == "y":
77
- return True
78
-
79
- if key == "n":
80
- return False
1
+ import subprocess
2
+ import tempfile
3
+ import os
4
+
5
+ from commitwise.cli_utils import read_single_key
6
+
7
+
8
+ def get_staged_diff() -> str:
9
+ """
10
+ Return the staged git diff
11
+ Raises an error if there are no staged changes
12
+ """
13
+
14
+ result = subprocess.run(["git", "diff", "--cached"], capture_output=True, text=True)
15
+
16
+ diff = result.stdout.strip()
17
+
18
+ if not diff:
19
+ raise RuntimeError(
20
+ "No staged changes found.\nPlease run `git add` before using CommitWise."
21
+ )
22
+ return diff
23
+
24
+
25
+ def git_commit_with_message(message: str) -> None:
26
+ """
27
+ Perform a git commit using the given commit message.
28
+ The message is written to a temporary file and passed to
29
+ `git commit -F` to preserve formatting exactly.
30
+ """
31
+
32
+ if not message or not message.strip():
33
+ raise ValueError("Commit message is empty.")
34
+
35
+ temp_file_path = None
36
+
37
+ try:
38
+ with tempfile.NamedTemporaryFile(
39
+ mode="w",
40
+ encoding="utf-8",
41
+ delete=False,
42
+ ) as tmp:
43
+ tmp.write(message.rstrip() + "\n")
44
+ temp_file_path = tmp.name
45
+
46
+ # subprocess.run(["git", "commit", "-F", temp_file_path], check=True)
47
+ result = subprocess.run(
48
+ ["git", "commit", "-F", temp_file_path],
49
+ capture_output=True,
50
+ text=True,
51
+ ).stdout.strip()
52
+
53
+ output_message = (
54
+ f"\n\n[✔] Commit created successfully. More details:\n\n{result}"
55
+ )
56
+
57
+ print(output_message)
58
+
59
+ finally:
60
+ if temp_file_path and os.path.exists(temp_file_path):
61
+ os.remove(temp_file_path)
62
+
63
+
64
+ def confirm_commit(message: str) -> bool:
65
+ """
66
+ Confirm the suggested commit message.
67
+ """
68
+ print("\nProposed commit message:\n")
69
+ print("-" * 40)
70
+ print(message.strip())
71
+ print("-" * 40)
72
+ print("\nCommit this message? [y/n] ", end="", flush=True)
73
+
74
+ while True:
75
+ key = read_single_key()
76
+ if key == "y":
77
+ return True
78
+
79
+ if key == "n":
80
+ return False
@@ -1,145 +1,147 @@
1
- Metadata-Version: 2.4
2
- Name: commitwise
3
- Version: 0.1.4
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
- CommitWise is a smart and simple tool for generating clean Git commit messages.
18
- It can create commit messages from a text file or using AI models.
19
-
20
- **With CommitWise, your commits are always:**
21
- - **Clean and readable**
22
- - **Following Git best practices**
23
- - **Well-structured and informative**
24
- <br>
25
-
26
- Features
27
- --------
28
- - Generate commits from text files, preserving exact formatting, spacing, and paragraphs
29
-
30
- - Generate commits using AI (local with Ollama or OpenAI API)
31
-
32
- - Simple and easy-to-use CLI with only a few flags
33
-
34
- - Works seamlessly in any Git project
35
- <br>
36
-
37
- Requirements
38
- ------------
39
- - Python >= **`3.9`**
40
-
41
- - For local AI : **`Ollama`** installed and the desired model downloaded
42
-
43
- - For online AI : **`OpenAI API Key`** (if using OpenAI)
44
- <br>
45
-
46
- Installation
47
- ------------
48
- ```
49
- $> pip install commitwise
50
- ```
51
- <br>
52
-
53
- AI Configuration
54
- ----------------
55
- CommitWise supports two AI modes:
56
- - Local AI using Ollama (recommended)
57
-
58
- - OpenAI API
59
-
60
- **You only need to configure ONE of them**.
61
-
62
- <br>
63
-
64
- >Local AI (Ollama)
65
- >----------------
66
- >
67
- >1. Install Ollama:
68
- > https://ollama.com
69
- >
70
- >2. Download a model :
71
- > ```
72
- > $> ollama pull llama3
73
- > ```
74
- >
75
- >3. Make sure Ollama is running:
76
- > ```
77
- > $> ollama serve
78
- > ```
79
- >
80
- >CommitWise will automatically detect Ollama at :
81
- > `http://localhost:11434`
82
- >
83
- >**No additional configuration is required.**
84
-
85
- <br>
86
-
87
- >OpenAI Configuration
88
- >--------------------
89
- >
90
- >- If you prefer using OpenAI instead of local AI, set your `API-KEY` as an environment variable.
91
- >
92
- > - Windows :
93
- > ```
94
- > $> setx OPENAI_API_KEY "your_api_key_here"
95
- > ```
96
- >
97
- > - Linux / macOS :
98
- > ```
99
- > $> export OPENAI_API_KEY="your_api_key_here"
100
- > ```
101
- >
102
- >**CommitWise will automatically use OpenAI when the API key is available.**
103
-
104
- <br>
105
-
106
- Usage
107
- -----
108
- Generate commit from AI (local or OpenAI):
109
- ```
110
- $> commitwise --ai
111
- ```
112
-
113
- Generate commit from a text file:
114
- ```
115
- $> commitwise --file ./my_commit.txt
116
- ```
117
-
118
- Show help:
119
- ```
120
- $> commitwise --help
121
- ```
122
-
123
- <br>
124
-
125
- Professional Note
126
- -----------------
127
- CommitWise ensures that AI-generated commit messages are clean and Git-ready,
128
- without extra explanations, markdown, or educational text.
129
- This is guaranteed through strict prompting and output cleaning.
130
-
131
- <br>
132
-
133
- Links
134
- -----
135
-
136
- [GitHub](https://github.com/hasssan-hasssan/commitwise "GitHub repository") |
137
- [PyPi](https://pypi.org/project/commitwise)
138
-
139
- <br>
140
-
141
- Support
142
- -------
143
- If CommitWise is helpful, please give it a star on [GitHub](https://github.com/hasssan-hasssan/commitwise "GitHub repository") so others can find it!
144
-
145
- <br>
1
+ Metadata-Version: 2.4
2
+ Name: commitwise
3
+ Version: 0.1.5
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
+ License-File: LICENSE
14
+ Requires-Dist: requests>=2.31.0
15
+ Dynamic: license-file
16
+
17
+ CommitWise
18
+ ===========
19
+ CommitWise is a smart and simple tool for generating clean Git commit messages.
20
+ It can create commit messages from a text file or using AI models.
21
+
22
+ **With CommitWise, your commits are always:**
23
+ - **Clean and readable**
24
+ - **Following Git best practices**
25
+ - **Well-structured and informative**
26
+ <br>
27
+
28
+ Features
29
+ --------
30
+ - Generate commits from text files, preserving exact formatting, spacing, and paragraphs
31
+
32
+ - Generate commits using AI (local with Ollama or OpenAI API)
33
+
34
+ - Simple and easy-to-use CLI with only a few flags
35
+
36
+ - Works seamlessly in any Git project
37
+ <br>
38
+
39
+ Requirements
40
+ ------------
41
+ - Python >= **`3.9`**
42
+
43
+ - For local AI : **`Ollama`** installed and the desired model downloaded
44
+
45
+ - For online AI : **`OpenAI API Key`** (if using OpenAI)
46
+ <br>
47
+
48
+ Installation
49
+ ------------
50
+ ```
51
+ $> pip install commitwise
52
+ ```
53
+ <br>
54
+
55
+ AI Configuration
56
+ ----------------
57
+ CommitWise supports two AI modes:
58
+ - Local AI using Ollama (recommended)
59
+
60
+ - OpenAI API
61
+
62
+ **You only need to configure ONE of them**.
63
+
64
+ <br>
65
+
66
+ >Local AI (Ollama)
67
+ >----------------
68
+ >
69
+ >1. Install Ollama:
70
+ > https://ollama.com
71
+ >
72
+ >2. Download a model :
73
+ > ```
74
+ > $> ollama pull llama3
75
+ > ```
76
+ >
77
+ >3. Make sure Ollama is running:
78
+ > ```
79
+ > $> ollama serve
80
+ > ```
81
+ >
82
+ >CommitWise will automatically detect Ollama at :
83
+ > `http://localhost:11434`
84
+ >
85
+ >**No additional configuration is required.**
86
+
87
+ <br>
88
+
89
+ >OpenAI Configuration
90
+ >--------------------
91
+ >
92
+ >- If you prefer using OpenAI instead of local AI, set your `API-KEY` as an environment variable.
93
+ >
94
+ > - Windows :
95
+ > ```
96
+ > $> setx OPENAI_API_KEY "your_api_key_here"
97
+ > ```
98
+ >
99
+ > - Linux / macOS :
100
+ > ```
101
+ > $> export OPENAI_API_KEY="your_api_key_here"
102
+ > ```
103
+ >
104
+ >**CommitWise will automatically use OpenAI when the API key is available.**
105
+
106
+ <br>
107
+
108
+ Usage
109
+ -----
110
+ Generate commit from AI (local or OpenAI):
111
+ ```
112
+ $> commitwise --ai
113
+ ```
114
+
115
+ Generate commit from a text file:
116
+ ```
117
+ $> commitwise --file ./my_commit.txt
118
+ ```
119
+
120
+ Show help:
121
+ ```
122
+ $> commitwise --help
123
+ ```
124
+
125
+ <br>
126
+
127
+ Professional Note
128
+ -----------------
129
+ CommitWise ensures that AI-generated commit messages are clean and Git-ready,
130
+ without extra explanations, markdown, or educational text.
131
+ This is guaranteed through strict prompting and output cleaning.
132
+
133
+ <br>
134
+
135
+ Links
136
+ -----
137
+
138
+ [GitHub](https://github.com/hasssan-hasssan/commitwise "GitHub repository") |
139
+ [PyPi](https://pypi.org/project/commitwise)
140
+
141
+ <br>
142
+
143
+ Support
144
+ -------
145
+ If CommitWise is helpful, please give it a star on [GitHub](https://github.com/hasssan-hasssan/commitwise "GitHub repository") so others can find it!
146
+
147
+ <br>
@@ -0,0 +1,17 @@
1
+ commitwise/__init__.py,sha256=oJSalUWG2ttcT11vxI08kKlRMDMdsGH7rL5zIJl3Gx0,19
2
+ commitwise/ai_source.py,sha256=DT_2kJio_tAWthQHeC--viL4T-LQ9jclcNsrrBkRBJY,1369
3
+ commitwise/cli.py,sha256=Tgfpq4fnX_AJNO--b114TtglnqLIjq4RsJb6QxgAHTE,1359
4
+ commitwise/cli_utils.py,sha256=kFyIEChnPEaZ0lgVD9kdStdLYB9PutSJrwoBKtLOYjQ,2198
5
+ commitwise/config.py,sha256=sZnaj7xDNCYT6LyU7-8W2SWQoJOeNMDFj5yZ8gKwzK4,244
6
+ commitwise/file_source.py,sha256=sEW4As2kjpJORcaBpLTHgtp4PSwwTp-aYcua1XyBxxY,726
7
+ commitwise/git_utils.py,sha256=jTo396zCRZYnRVzVT_ZiaTiKfcqqaDOW4ZUywlX3lN8,2030
8
+ commitwise/ai/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ commitwise/ai/base.py,sha256=TgeK5-mqNa_MI0AxwIAjgNiEL0yCDwXTtEMJIU3LS2I,1677
10
+ commitwise/ai/local_engine.py,sha256=OJrKHgaBfun60TwudX9Kk97g0vi9ukA5iA9Aex48W8g,968
11
+ commitwise/ai/openai_engine.py,sha256=5T5B5JpDqWm89qoioWy7CnqIDk9t7sPdNV9kwkel7TQ,971
12
+ commitwise-0.1.5.dist-info/licenses/LICENSE,sha256=sWZTMpF4wDYY-DK0fNpf3cyQfMKyuiMrC0kvWeNQh00,1077
13
+ commitwise-0.1.5.dist-info/METADATA,sha256=T3H3UNKgw5Vw_Wub3Vf4tn9LA7rTRbeFLobdfwdFMNc,3148
14
+ commitwise-0.1.5.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
15
+ commitwise-0.1.5.dist-info/entry_points.txt,sha256=WUow9mgob_PQfVpk5QuVpoWXYnALsOar3NCyDWJCQuk,51
16
+ commitwise-0.1.5.dist-info/top_level.txt,sha256=8uL7do0ZoZw67O5fzMSxbqQcJkMH3OHeHhONQuS3D88,11
17
+ commitwise-0.1.5.dist-info/RECORD,,
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Abolfazl Hassan Zade
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,16 +0,0 @@
1
- commitwise/__init__.py,sha256=Xrz0EUwWpxrSR-X3O-Nw0Kt1zy_W_Q6GvyVJPrqok1U,19
2
- commitwise/ai_source.py,sha256=BD79fQQb654AaKmHH2_JzVidzwUEHd55ny5aO0e5vtU,1417
3
- commitwise/cli.py,sha256=TiGYUgeoKF70IHLNNMJVTB6MkDJCkmpctOvEgbnHtpg,1418
4
- commitwise/cli_utils.py,sha256=QN2N8JaNQ9hLFXTGZPCKwjJ4wK5sTljNLEuOttYU-yc,2285
5
- commitwise/config.py,sha256=Jovf7YfV0N8CFz2jBns_UBAgfuO8un8fivezNFGSbYc,253
6
- commitwise/file_source.py,sha256=3pzFAsFYyXQSLQrfr_YGA5GAV-vtUP5Co4YhG-XOhnc,751
7
- commitwise/git_utils.py,sha256=BvccuWoBbJzblWaEnCeCiXKD2eE6mIc1Z5vwGcCzNHE,2110
8
- commitwise/ai/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
- commitwise/ai/base.py,sha256=XYEzORaAiKvMd8tYRKqE_eE2D3iK2zXK3dXl5rJxNCs,1737
10
- commitwise/ai/local_engine.py,sha256=YwiusAokL_t0PiJ53gf8IAJGynHrEYAv0Cyy_QpdnpM,1007
11
- commitwise/ai/openai_engine.py,sha256=8_xErkmsjzXyNwlPVgrlwxumt2y5ZhhWYo1I9nUKpqE,1006
12
- commitwise-0.1.4.dist-info/METADATA,sha256=60LLPGcaO7Gdb45YdZcgiCCXlFdnIs6FZFBjH6-jib0,3249
13
- commitwise-0.1.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
14
- commitwise-0.1.4.dist-info/entry_points.txt,sha256=WUow9mgob_PQfVpk5QuVpoWXYnALsOar3NCyDWJCQuk,51
15
- commitwise-0.1.4.dist-info/top_level.txt,sha256=8uL7do0ZoZw67O5fzMSxbqQcJkMH3OHeHhONQuS3D88,11
16
- commitwise-0.1.4.dist-info/RECORD,,