git-camus 0.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Evgeny Rachlenko
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.
@@ -0,0 +1,207 @@
1
+ Metadata-Version: 2.4
2
+ Name: git-camus
3
+ Version: 0.5.0
4
+ Summary: Craft Git commit messages with existential flair using local Ollama
5
+ Author-email: Evgeny Rachlenko <evgeny.rachlenko@gmail.com>
6
+ Maintainer-email: Evgeny Rachlenko <evgeny.rachlenko@gmail.com>
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/rachlenko/git-camus
9
+ Project-URL: Documentation, https://git-camus.readthedocs.io/
10
+ Project-URL: Repository, https://github.com/rachlenko/git-camus
11
+ Project-URL: Changelog, https://github.com/rachlenko/git-camus/blob/main/CHANGELOG.md
12
+ Project-URL: Issues, https://github.com/rachlenko/git-camus/issues
13
+ Project-URL: Discussions, https://github.com/rachlenko/git-camus/discussions
14
+ Keywords: git,commit,ollama,ai,philosophy,camus,existentialism
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Topic :: Software Development :: Version Control :: Git
26
+ Classifier: Topic :: Text Processing :: Linguistic
27
+ Requires-Python: >=3.9
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Requires-Dist: click>=8.0.0
31
+ Requires-Dist: httpx>=0.24.0
32
+ Requires-Dist: pydantic>=2.0.0
33
+ Requires-Dist: pydantic-settings>=2.0.0
34
+ Provides-Extra: dev
35
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
36
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
37
+ Requires-Dist: pytest-xdist>=3.0.0; extra == "dev"
38
+ Requires-Dist: black>=23.0.0; extra == "dev"
39
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
40
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
41
+ Requires-Dist: pre-commit>=3.0.0; extra == "dev"
42
+ Provides-Extra: docs
43
+ Requires-Dist: sphinx>=7.0.0; extra == "docs"
44
+ Requires-Dist: sphinx-rtd-theme>=1.0.0; extra == "docs"
45
+ Requires-Dist: myst-parser>=1.0.0; extra == "docs"
46
+ Provides-Extra: test
47
+ Requires-Dist: pytest>=7.0.0; extra == "test"
48
+ Requires-Dist: pytest-cov>=4.0.0; extra == "test"
49
+ Requires-Dist: pytest-xdist>=3.0.0; extra == "test"
50
+ Dynamic: license-file
51
+
52
+ # git-camus
53
+
54
+ Craft Git commit messages with existential flair using [Ollama](https://ollama.com), [OpenAI](https://platform.openai.com/), [Claude](https://docs.anthropic.com/), or the [Claude CLI](https://docs.claude.com/en/docs/claude-code).
55
+
56
+ git-camus analyzes your staged changes and generates philosophical commit messages inspired by Albert Camus — reflecting on the absurdity, rebellion, and human condition behind every diff.
57
+
58
+ ## Prerequisites
59
+
60
+ - Python 3.9+
61
+ - One of the following LLM providers:
62
+ - **Ollama** (default) — running locally or accessible via network, with a pulled model (default: `llama3.2`)
63
+ - **OpenAI** — an API key with access to chat completions (default model: `gpt-4o-mini`)
64
+ - **Claude** — an Anthropic API key (default model: `claude-sonnet-4-20250514`)
65
+ - **Claude CLI** — a locally-installed Claude CLI with active login (no API key required)
66
+
67
+ ## Installation
68
+
69
+ Install the latest release directly from GitHub:
70
+
71
+ ```bash
72
+ pip install git+https://github.com/rachlenko/git-camus.git
73
+ ```
74
+
75
+ Or install a specific tag:
76
+
77
+ ```bash
78
+ pip install git+https://github.com/rachlenko/git-camus.git@v0.5.0
79
+ ```
80
+
81
+ A PyPI release is planned; once published, `pip install git-camus` will pull the same version.
82
+
83
+ ### Standalone install (isolated virtualenv + wrapper binary)
84
+
85
+ ```bash
86
+ git clone https://github.com/rachlenko/git-camus.git
87
+ cd git-camus
88
+ ./install.sh --prefix /usr/local
89
+ ```
90
+
91
+ This creates an isolated virtual environment under `PREFIX/lib/git-camus/` and places the `git-camus` executable in `PREFIX/bin/`. The default prefix is `/usr/local`.
92
+
93
+ ```bash
94
+ # Install to a custom location
95
+ ./install.sh --prefix ~/.local
96
+
97
+ # Install system-wide (may require sudo)
98
+ sudo ./install.sh --prefix /usr/local
99
+ ```
100
+
101
+ ### From a local checkout
102
+
103
+ ```bash
104
+ pip install .
105
+ ```
106
+
107
+ For development:
108
+
109
+ ```bash
110
+ pip install -e ".[dev]"
111
+ ```
112
+
113
+ ## Usage
114
+
115
+ Stage your changes, then run:
116
+
117
+ ```bash
118
+ git-camus
119
+ ```
120
+
121
+ ### Options
122
+
123
+ | Flag | Description |
124
+ |------|-------------|
125
+ | `--show`, `-s` | Preview the generated message without committing |
126
+ | `--message`, `-m` | Provide context to guide the philosophical reflection |
127
+ | `--provider`, `-p` | LLM provider: `ollama` (default), `openai`, `claude`, or `claude-cli` |
128
+
129
+ ### Examples
130
+
131
+ ```bash
132
+ # Generate and commit using Ollama (default)
133
+ git add .
134
+ git-camus
135
+
136
+ # Preview without committing
137
+ git-camus --show
138
+
139
+ # Provide context
140
+ git-camus -m "fixed auth token expiry"
141
+
142
+ # Use OpenAI
143
+ export OPENAI_API_KEY="sk-..."
144
+ git-camus --provider openai
145
+
146
+ # Use Claude
147
+ export ANTHROPIC_API_KEY="sk-ant-..."
148
+ git-camus --provider claude
149
+
150
+ # Set the default provider via environment variable
151
+ export GIT_CAMUS_PROVIDER=claude
152
+ git-camus
153
+ ```
154
+
155
+ ## Configuration
156
+
157
+ ### Ollama (default provider)
158
+
159
+ | Variable | Default | Description |
160
+ |----------|---------|-------------|
161
+ | `OLLAMA_HOST` | `http://localhost:11434` | Ollama API endpoint |
162
+ | `OLLAMA_MODEL` | `llama3.2` | Model to use for generation |
163
+
164
+ ### OpenAI
165
+
166
+ | Variable | Default | Description |
167
+ |----------|---------|-------------|
168
+ | `OPENAI_API_KEY` | *(required)* | OpenAI API key |
169
+ | `OPENAI_API_HOST` | `https://api.openai.com/v1` | OpenAI-compatible API endpoint |
170
+ | `OPENAI_MODEL` | `gpt-4o-mini` | Model to use for generation |
171
+
172
+ ### Claude
173
+
174
+ | Variable | Default | Description |
175
+ |----------|---------|-------------|
176
+ | `ANTHROPIC_API_KEY` | *(required)* | Anthropic API key |
177
+ | `ANTHROPIC_API_HOST` | `https://api.anthropic.com` | Anthropic-compatible API endpoint |
178
+ | `ANTHROPIC_MODEL` | `claude-sonnet-4-20250514` | Model to use for generation |
179
+
180
+ ### `claude-cli` provider
181
+
182
+ Generate the message with your locally-installed **Claude CLI** (`claude -p`),
183
+ using the CLI's own login — **no `ANTHROPIC_API_KEY` required**:
184
+
185
+ ```bash
186
+ git-camus -p claude-cli # or: GIT_CAMUS_PROVIDER=claude-cli git-camus
187
+ ```
188
+
189
+ | Variable | Default | Description |
190
+ |----------|---------|-------------|
191
+ | `GIT_CAMUS_CLAUDE_CLI_BIN` | `claude` | Path to the Claude CLI binary |
192
+
193
+ Requires the `claude` CLI on your `PATH` and logged in. Unlike the `claude` provider (Anthropic HTTP API,
194
+ needs a key), `claude-cli` strips `ANTHROPIC_API_KEY`/`ANTHROPIC_AUTH_TOKEN` so
195
+ the CLI authenticates the same way it does when you run it directly.
196
+
197
+ ### General
198
+
199
+ | Variable | Default | Description |
200
+ |----------|---------|-------------|
201
+ | `GIT_CAMUS_PROVIDER` | `ollama` | Default provider (`ollama`, `openai`, `claude`, or `claude-cli`) |
202
+
203
+ The `OPENAI_API_HOST` and `ANTHROPIC_API_HOST` variables allow using any compatible API proxy or gateway.
204
+
205
+ ## License
206
+
207
+ [MIT](LICENSE)
@@ -0,0 +1,156 @@
1
+ # git-camus
2
+
3
+ Craft Git commit messages with existential flair using [Ollama](https://ollama.com), [OpenAI](https://platform.openai.com/), [Claude](https://docs.anthropic.com/), or the [Claude CLI](https://docs.claude.com/en/docs/claude-code).
4
+
5
+ git-camus analyzes your staged changes and generates philosophical commit messages inspired by Albert Camus — reflecting on the absurdity, rebellion, and human condition behind every diff.
6
+
7
+ ## Prerequisites
8
+
9
+ - Python 3.9+
10
+ - One of the following LLM providers:
11
+ - **Ollama** (default) — running locally or accessible via network, with a pulled model (default: `llama3.2`)
12
+ - **OpenAI** — an API key with access to chat completions (default model: `gpt-4o-mini`)
13
+ - **Claude** — an Anthropic API key (default model: `claude-sonnet-4-20250514`)
14
+ - **Claude CLI** — a locally-installed Claude CLI with active login (no API key required)
15
+
16
+ ## Installation
17
+
18
+ Install the latest release directly from GitHub:
19
+
20
+ ```bash
21
+ pip install git+https://github.com/rachlenko/git-camus.git
22
+ ```
23
+
24
+ Or install a specific tag:
25
+
26
+ ```bash
27
+ pip install git+https://github.com/rachlenko/git-camus.git@v0.5.0
28
+ ```
29
+
30
+ A PyPI release is planned; once published, `pip install git-camus` will pull the same version.
31
+
32
+ ### Standalone install (isolated virtualenv + wrapper binary)
33
+
34
+ ```bash
35
+ git clone https://github.com/rachlenko/git-camus.git
36
+ cd git-camus
37
+ ./install.sh --prefix /usr/local
38
+ ```
39
+
40
+ This creates an isolated virtual environment under `PREFIX/lib/git-camus/` and places the `git-camus` executable in `PREFIX/bin/`. The default prefix is `/usr/local`.
41
+
42
+ ```bash
43
+ # Install to a custom location
44
+ ./install.sh --prefix ~/.local
45
+
46
+ # Install system-wide (may require sudo)
47
+ sudo ./install.sh --prefix /usr/local
48
+ ```
49
+
50
+ ### From a local checkout
51
+
52
+ ```bash
53
+ pip install .
54
+ ```
55
+
56
+ For development:
57
+
58
+ ```bash
59
+ pip install -e ".[dev]"
60
+ ```
61
+
62
+ ## Usage
63
+
64
+ Stage your changes, then run:
65
+
66
+ ```bash
67
+ git-camus
68
+ ```
69
+
70
+ ### Options
71
+
72
+ | Flag | Description |
73
+ |------|-------------|
74
+ | `--show`, `-s` | Preview the generated message without committing |
75
+ | `--message`, `-m` | Provide context to guide the philosophical reflection |
76
+ | `--provider`, `-p` | LLM provider: `ollama` (default), `openai`, `claude`, or `claude-cli` |
77
+
78
+ ### Examples
79
+
80
+ ```bash
81
+ # Generate and commit using Ollama (default)
82
+ git add .
83
+ git-camus
84
+
85
+ # Preview without committing
86
+ git-camus --show
87
+
88
+ # Provide context
89
+ git-camus -m "fixed auth token expiry"
90
+
91
+ # Use OpenAI
92
+ export OPENAI_API_KEY="sk-..."
93
+ git-camus --provider openai
94
+
95
+ # Use Claude
96
+ export ANTHROPIC_API_KEY="sk-ant-..."
97
+ git-camus --provider claude
98
+
99
+ # Set the default provider via environment variable
100
+ export GIT_CAMUS_PROVIDER=claude
101
+ git-camus
102
+ ```
103
+
104
+ ## Configuration
105
+
106
+ ### Ollama (default provider)
107
+
108
+ | Variable | Default | Description |
109
+ |----------|---------|-------------|
110
+ | `OLLAMA_HOST` | `http://localhost:11434` | Ollama API endpoint |
111
+ | `OLLAMA_MODEL` | `llama3.2` | Model to use for generation |
112
+
113
+ ### OpenAI
114
+
115
+ | Variable | Default | Description |
116
+ |----------|---------|-------------|
117
+ | `OPENAI_API_KEY` | *(required)* | OpenAI API key |
118
+ | `OPENAI_API_HOST` | `https://api.openai.com/v1` | OpenAI-compatible API endpoint |
119
+ | `OPENAI_MODEL` | `gpt-4o-mini` | Model to use for generation |
120
+
121
+ ### Claude
122
+
123
+ | Variable | Default | Description |
124
+ |----------|---------|-------------|
125
+ | `ANTHROPIC_API_KEY` | *(required)* | Anthropic API key |
126
+ | `ANTHROPIC_API_HOST` | `https://api.anthropic.com` | Anthropic-compatible API endpoint |
127
+ | `ANTHROPIC_MODEL` | `claude-sonnet-4-20250514` | Model to use for generation |
128
+
129
+ ### `claude-cli` provider
130
+
131
+ Generate the message with your locally-installed **Claude CLI** (`claude -p`),
132
+ using the CLI's own login — **no `ANTHROPIC_API_KEY` required**:
133
+
134
+ ```bash
135
+ git-camus -p claude-cli # or: GIT_CAMUS_PROVIDER=claude-cli git-camus
136
+ ```
137
+
138
+ | Variable | Default | Description |
139
+ |----------|---------|-------------|
140
+ | `GIT_CAMUS_CLAUDE_CLI_BIN` | `claude` | Path to the Claude CLI binary |
141
+
142
+ Requires the `claude` CLI on your `PATH` and logged in. Unlike the `claude` provider (Anthropic HTTP API,
143
+ needs a key), `claude-cli` strips `ANTHROPIC_API_KEY`/`ANTHROPIC_AUTH_TOKEN` so
144
+ the CLI authenticates the same way it does when you run it directly.
145
+
146
+ ### General
147
+
148
+ | Variable | Default | Description |
149
+ |----------|---------|-------------|
150
+ | `GIT_CAMUS_PROVIDER` | `ollama` | Default provider (`ollama`, `openai`, `claude`, or `claude-cli`) |
151
+
152
+ The `OPENAI_API_HOST` and `ANTHROPIC_API_HOST` variables allow using any compatible API proxy or gateway.
153
+
154
+ ## License
155
+
156
+ [MIT](LICENSE)
File without changes
@@ -0,0 +1,58 @@
1
+ """Anthropic Claude API client functionality."""
2
+
3
+ import sys
4
+ from typing import Any
5
+
6
+ import click
7
+ import httpx
8
+
9
+ DEFAULT_SYSTEM_PROMPT = (
10
+ "You are an AI assistant that generates philosophical commit messages in the style of Albert Camus. "
11
+ "Your task is to analyze git changes and create a commit message that reflects on the absurdity, rebellion, and human condition."
12
+ )
13
+
14
+
15
+ class ClaudeClient:
16
+ """Client for interacting with the Anthropic Messages API."""
17
+
18
+ def __init__(self, host: str, api_key: str) -> None:
19
+ self.host = host
20
+ self.api_key = api_key
21
+
22
+ def generate_commit_message_request(
23
+ self, diff: str, status: str, model_name: str, prompt_message: str, max_diff_length: int = 8000
24
+ ) -> dict[str, Any]:
25
+ if len(diff) > max_diff_length:
26
+ diff = diff[:max_diff_length] + "\n... (truncated)"
27
+
28
+ prompt = prompt_message.format(diff=diff, status=status)
29
+
30
+ return {
31
+ "model": model_name,
32
+ "max_tokens": 256,
33
+ "system": DEFAULT_SYSTEM_PROMPT,
34
+ "messages": [{"role": "user", "content": prompt}],
35
+ }
36
+
37
+ def call_api(self, request_data: dict[str, Any]) -> dict[str, Any]:
38
+ headers = {
39
+ "x-api-key": self.api_key,
40
+ "anthropic-version": "2023-06-01",
41
+ "Content-Type": "application/json",
42
+ }
43
+ try:
44
+ click.echo("Sending request to Claude API...", err=True)
45
+ response = httpx.post(
46
+ f"{self.host}/v1/messages", json=request_data, headers=headers, timeout=120.0
47
+ )
48
+ response.raise_for_status()
49
+ content_blocks = response.json().get("content", [])
50
+ if not content_blocks:
51
+ return {"message": {"content": ""}}
52
+ return {"message": {"content": content_blocks[0].get("text", "")}}
53
+ except httpx.ConnectError:
54
+ click.echo(f"Could not connect to Claude API at {self.host}", err=True)
55
+ sys.exit(1)
56
+ except httpx.HTTPError as e:
57
+ click.echo(f"Claude API error: {e}", err=True)
58
+ sys.exit(1)
@@ -0,0 +1,99 @@
1
+ """Configuration management for git-camus."""
2
+
3
+ import os
4
+ from typing import Tuple
5
+
6
+ from pydantic import BaseModel
7
+ from pydantic_settings import BaseSettings
8
+
9
+
10
+ class OllamaConfig(BaseModel):
11
+ """Ollama API configuration."""
12
+ host: str = "http://localhost:11434"
13
+
14
+
15
+ class OpenAIConfig(BaseModel):
16
+ """OpenAI API configuration."""
17
+ host: str = "https://api.openai.com/v1"
18
+ model_name: str = "gpt-4o-mini"
19
+ api_key: str = ""
20
+
21
+
22
+ class ClaudeConfig(BaseModel):
23
+ """Anthropic Claude API configuration."""
24
+ host: str = "https://api.anthropic.com"
25
+ model_name: str = "claude-sonnet-4-20250514"
26
+ api_key: str = ""
27
+
28
+
29
+ class RunConfig(BaseModel):
30
+ """Runtime configuration."""
31
+ host: str = "0.0.0.0"
32
+ port: int = 8000
33
+ provider: str = "ollama"
34
+ model_name: str = "llama3.2"
35
+ prompt_message: str = (
36
+ "You are an AI assistant that generates philosophical commit messages in the style of Albert Camus.\n"
37
+ "Your task is to analyze git changes and create a commit message that reflects on the absurdity, rebellion, and human condition.\n\n"
38
+ "Git Diff:\n{diff}\n\nGit Status:\n{status}\n\n"
39
+ "Generate a philosophical commit message that:\n"
40
+ "1. Reflects on the nature of the changes made\n"
41
+ "2. Incorporates themes of existentialism and the absurd\n"
42
+ "3. Is concise but meaningful (max 150 characters)\n"
43
+ "4. Avoids technical jargon in favor of philosophical reflection\n\n"
44
+ "Respond with only the commit message, no explanations or additional text."
45
+ )
46
+
47
+
48
+ class ApiPrefix(BaseModel):
49
+ """API prefix configuration."""
50
+ prefix: str = "/api"
51
+
52
+
53
+ class Settings(BaseSettings):
54
+ """Application settings."""
55
+ ollama: OllamaConfig = OllamaConfig()
56
+ openai: OpenAIConfig = OpenAIConfig()
57
+ claude: ClaudeConfig = ClaudeConfig()
58
+ run: RunConfig = RunConfig()
59
+ api: ApiPrefix = ApiPrefix()
60
+
61
+
62
+ settings = Settings()
63
+
64
+
65
+ def get_config_values() -> Tuple[str, str, str]:
66
+ """Get configuration values from config file or defaults.
67
+
68
+ Returns:
69
+ tuple: (ollama_host, model_name, prompt_message)
70
+ """
71
+ # Default values
72
+ default_host = "http://localhost:11434"
73
+ default_model = "llama3.2"
74
+ default_prompt = (
75
+ "You are an AI assistant that generates philosophical commit messages in the style of Albert Camus.\n"
76
+ "Your task is to analyze git changes and create a commit message that reflects on the absurdity, rebellion, and human condition.\n\n"
77
+ "Git Diff:\n{diff}\n\nGit Status:\n{status}\n\n"
78
+ "Generate a philosophical commit message that:\n"
79
+ "1. Reflects on the nature of the changes made\n"
80
+ "2. Incorporates themes of existentialism and the absurd\n"
81
+ "3. Is concise but meaningful (max 150 characters)\n"
82
+ "4. Avoids technical jargon in favor of philosophical reflection\n\n"
83
+ "Respond with only the commit message, no explanations or additional text."
84
+ )
85
+
86
+ try:
87
+ ollama_host = settings.ollama.host
88
+ model_name = settings.run.model_name
89
+ prompt_message = settings.run.prompt_message
90
+ except Exception:
91
+ ollama_host = default_host
92
+ model_name = default_model
93
+ prompt_message = default_prompt
94
+
95
+ # Environment variables take precedence
96
+ ollama_host = os.environ.get("OLLAMA_HOST", ollama_host)
97
+ model_name = os.environ.get("OLLAMA_MODEL", model_name)
98
+
99
+ return ollama_host, model_name, prompt_message
@@ -0,0 +1,52 @@
1
+ """Git operations functionality."""
2
+
3
+ import subprocess
4
+ import sys
5
+
6
+ import click
7
+
8
+
9
+ def get_git_diff() -> str:
10
+ """Get the git diff of staged changes."""
11
+ try:
12
+ return subprocess.check_output(
13
+ ["git", "diff", "--cached"], text=True, stderr=subprocess.PIPE
14
+ )
15
+ except subprocess.CalledProcessError:
16
+ return ""
17
+
18
+
19
+ def get_git_status() -> str:
20
+ """Get the git status of staged changes."""
21
+ try:
22
+ return subprocess.check_output(
23
+ ["git", "status", "--porcelain"], text=True, stderr=subprocess.PIPE
24
+ )
25
+ except subprocess.CalledProcessError:
26
+ return ""
27
+
28
+
29
+ def perform_git_commit(message: str) -> None:
30
+ """Perform the git commit with the given message."""
31
+ try:
32
+ subprocess.run(["git", "commit", "-m", message], check=True, text=True)
33
+ click.echo(f"Committed with message: {message}")
34
+ except subprocess.CalledProcessError as e:
35
+ click.echo(f"Error committing: {e}", err=True)
36
+ sys.exit(1)
37
+
38
+
39
+ def check_git_repository() -> None:
40
+ """Check if we're in a git repository."""
41
+ try:
42
+ subprocess.run(
43
+ ["git", "rev-parse", "--is-inside-work-tree"], check=True, capture_output=True
44
+ )
45
+ except subprocess.CalledProcessError:
46
+ click.echo("Error: Not in a git repository", err=True)
47
+ sys.exit(1)
48
+
49
+
50
+ def has_staged_changes(status: str) -> bool:
51
+ """Check if there are any staged changes."""
52
+ return bool(status.strip())
@@ -0,0 +1,89 @@
1
+ """Ollama API client functionality."""
2
+
3
+ import sys
4
+ from typing import Any, TypedDict
5
+
6
+ import click
7
+ import httpx
8
+
9
+
10
+ class OllamaMessage(TypedDict):
11
+ """Type for an Ollama API message."""
12
+
13
+ role: str
14
+ content: str
15
+
16
+
17
+ class OllamaRequest(TypedDict):
18
+ """Type for an Ollama API request."""
19
+
20
+ model: str
21
+ messages: list[OllamaMessage]
22
+ stream: bool
23
+ options: dict[str, Any]
24
+
25
+
26
+ class OllamaClient:
27
+ """Client for interacting with Ollama API."""
28
+
29
+ def __init__(self, host: str) -> None:
30
+ """Initialize the Ollama client.
31
+
32
+ Args:
33
+ host: The Ollama host URL
34
+ """
35
+ self.host = host
36
+
37
+ def generate_commit_message_request(
38
+ self, diff: str, status: str, model_name: str, prompt_message: str, max_diff_length: int = 8000
39
+ ) -> OllamaRequest:
40
+ """Format the git diff and status data for the Ollama API.
41
+
42
+ Args:
43
+ diff: The git diff output
44
+ status: The git status output
45
+ model_name: The model to use
46
+ prompt_message: The prompt template
47
+ max_diff_length: Maximum length for git diff
48
+
49
+ Returns:
50
+ OllamaRequest: The formatted request for the Ollama API
51
+ """
52
+ # Truncate diff if it's too long
53
+ if len(diff) > max_diff_length:
54
+ diff = diff[:max_diff_length] + "\n... (truncated)"
55
+
56
+ prompt = prompt_message.format(diff=diff, status=status)
57
+
58
+ return {
59
+ "model": model_name,
60
+ "messages": [{"role": "user", "content": prompt}],
61
+ "stream": False,
62
+ "options": {"temperature": 0.7, "top_p": 0.9, "max_tokens": 150},
63
+ }
64
+
65
+ def call_api(self, request_data: OllamaRequest) -> dict[str, Any]:
66
+ """Call the local Ollama API to generate a commit message.
67
+
68
+ Args:
69
+ request_data: The formatted request data
70
+
71
+ Returns:
72
+ dict[str, Any]: The API response containing the generated message
73
+
74
+ Raises:
75
+ SystemExit: If the API call fails
76
+ """
77
+ try:
78
+ click.echo("Sending request to Ollama API...", err=True)
79
+ response = httpx.post(f"{self.host}/api/chat", json=request_data, timeout=120.0)
80
+ response.raise_for_status()
81
+ return response.json() # type: ignore[no-any-return]
82
+ except httpx.HTTPError as e:
83
+ click.echo(f"API error: {e}", err=True)
84
+ click.echo("Make sure Ollama is running and accessible", err=True)
85
+ sys.exit(1)
86
+ except httpx.ConnectError:
87
+ click.echo(f"Could not connect to Ollama at {self.host}", err=True)
88
+ click.echo("Make sure Ollama is running and the host/port is correct", err=True)
89
+ sys.exit(1)