commitwise 0.1.5__tar.gz → 0.2.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 (47) hide show
  1. commitwise-0.2.0/PKG-INFO +190 -0
  2. commitwise-0.2.0/README.md +169 -0
  3. commitwise-0.2.0/commitwise/__init__.py +1 -0
  4. commitwise-0.2.0/commitwise/__main__.py +5 -0
  5. commitwise-0.2.0/commitwise/cli.py +184 -0
  6. commitwise-0.2.0/commitwise/config/__init__.py +6 -0
  7. commitwise-0.2.0/commitwise/config/manager.py +131 -0
  8. commitwise-0.2.0/commitwise/config/paths.py +18 -0
  9. commitwise-0.2.0/commitwise/config/schema.py +66 -0
  10. commitwise-0.2.0/commitwise/core/__init__.py +1 -0
  11. commitwise-0.2.0/commitwise/core/diff.py +39 -0
  12. commitwise-0.2.0/commitwise/core/generator.py +46 -0
  13. commitwise-0.2.0/commitwise/core/git.py +92 -0
  14. commitwise-0.2.0/commitwise/core/validation.py +35 -0
  15. commitwise-0.2.0/commitwise/errors.py +135 -0
  16. commitwise-0.2.0/commitwise/prompts/__init__.py +1 -0
  17. commitwise-0.2.0/commitwise/prompts/commit_message.py +78 -0
  18. commitwise-0.2.0/commitwise/providers/__init__.py +1 -0
  19. commitwise-0.2.0/commitwise/providers/base.py +73 -0
  20. commitwise-0.2.0/commitwise/providers/factory.py +38 -0
  21. commitwise-0.2.0/commitwise/providers/ollama.py +90 -0
  22. commitwise-0.2.0/commitwise/providers/openrouter.py +83 -0
  23. commitwise-0.2.0/commitwise.egg-info/PKG-INFO +190 -0
  24. commitwise-0.2.0/commitwise.egg-info/SOURCES.txt +29 -0
  25. commitwise-0.2.0/commitwise.egg-info/requires.txt +7 -0
  26. {commitwise-0.1.5 → commitwise-0.2.0}/pyproject.toml +14 -4
  27. commitwise-0.1.5/PKG-INFO +0 -147
  28. commitwise-0.1.5/README.md +0 -131
  29. commitwise-0.1.5/commitwise/__init__.py +0 -1
  30. commitwise-0.1.5/commitwise/ai/__init__.py +0 -0
  31. commitwise-0.1.5/commitwise/ai/base.py +0 -60
  32. commitwise-0.1.5/commitwise/ai/local_engine.py +0 -39
  33. commitwise-0.1.5/commitwise/ai/openai_engine.py +0 -35
  34. commitwise-0.1.5/commitwise/ai_source.py +0 -48
  35. commitwise-0.1.5/commitwise/cli.py +0 -59
  36. commitwise-0.1.5/commitwise/cli_utils.py +0 -87
  37. commitwise-0.1.5/commitwise/config.py +0 -9
  38. commitwise-0.1.5/commitwise/file_source.py +0 -25
  39. commitwise-0.1.5/commitwise/git_utils.py +0 -80
  40. commitwise-0.1.5/commitwise.egg-info/PKG-INFO +0 -147
  41. commitwise-0.1.5/commitwise.egg-info/SOURCES.txt +0 -20
  42. commitwise-0.1.5/commitwise.egg-info/requires.txt +0 -1
  43. {commitwise-0.1.5 → commitwise-0.2.0}/LICENSE +0 -0
  44. {commitwise-0.1.5 → commitwise-0.2.0}/commitwise.egg-info/dependency_links.txt +0 -0
  45. {commitwise-0.1.5 → commitwise-0.2.0}/commitwise.egg-info/entry_points.txt +0 -0
  46. {commitwise-0.1.5 → commitwise-0.2.0}/commitwise.egg-info/top_level.txt +0 -0
  47. {commitwise-0.1.5 → commitwise-0.2.0}/setup.cfg +0 -0
@@ -0,0 +1,190 @@
1
+ Metadata-Version: 2.4
2
+ Name: commitwise
3
+ Version: 0.2.0
4
+ Summary: AI-powered Git commit message suggestions from staged diffs
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,conventional-commits,ollama,openrouter
11
+ Requires-Python: >=3.15
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: requests>=2.31.0
15
+ Requires-Dist: platformdirs>=4.2.0
16
+ Requires-Dist: tomlkit>=0.12.0
17
+ Requires-Dist: pyperclip>=1.8.2
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest<10.0,>=9.1; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # CommitWise
23
+
24
+ **Commit your code Wisely ...**
25
+
26
+ [![PyPI version](https://img.shields.io/pypi/v/commitwise)](https://pypi.org/project/commitwise/)
27
+ [![Python](https://img.shields.io/badge/python-3.15%2B-blue)](https://www.python.org/)
28
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
29
+
30
+ CommitWise is an AI-powered command-line assistant that turns your **Git staged changes** into three clear, English [Conventional Commit](https://www.conventionalcommits.org/) message suggestions.
31
+
32
+ Choose the AI provider that fits your workflow:
33
+ - **Local:** run a model on your machine with [Ollama](https://ollama.com/).
34
+ - **Online:** generate suggestions with a model available through [OpenRouter](https://openrouter.ai/).
35
+
36
+ > **You stay in control.** CommitWise suggests commit messages; it never creates commits or changes your Git repository.
37
+
38
+ ## Why CommitWise?
39
+
40
+ Writing a good commit message takes attention away from the code you're working on. CommitWise reads the changes you've already staged, asks your selected AI provider for three alternatives, validates their format, and lets you choose the one you want.
41
+
42
+ - **Three suggestions, one staged diff:** every suggestion describes the complete staged change set, not an individual file.
43
+ - **Your choice of AI:** use Ollama locally or OpenRouter online.
44
+ - **Conventional Commits:** suggestions follow the Conventional Commits header format.
45
+ - **Safe by design:** Git access is read-only; you decide what gets committed.
46
+ - **Global settings:** configure providers once and reuse the settings across repositories.
47
+ - **Focused changes:** a configurable diff-size limit helps keep commits manageable.
48
+
49
+ ## Quick start
50
+
51
+ ### 1. Requirements
52
+
53
+ - Python **3.15 or newer**
54
+ - Git installed and available on your `PATH`
55
+ - One configured AI provider:
56
+ - Ollama running locally with a model downloaded, or
57
+ - an OpenRouter API key and model name
58
+
59
+ ### 2. Install
60
+
61
+ ```bash
62
+ pip install commitwise
63
+ ```
64
+
65
+ ### 3. Stage your changes and generate suggestions
66
+
67
+ Stage the files you want to describe:
68
+
69
+ ```bash
70
+ git add <files>
71
+ ```
72
+
73
+ Then choose **one** provider:
74
+
75
+ ```bash
76
+ commitwise --ai-local
77
+ ```
78
+
79
+ or:
80
+
81
+ ```bash
82
+ commitwise --ai-online
83
+ ```
84
+
85
+ CommitWise displays three suggestions and asks you to select one. The selected message is copied to your clipboard when a clipboard backend is available. Review it, then run the Git commit command yourself.
86
+
87
+ ## Choose a provider
88
+
89
+ ### Local AI with Ollama
90
+
91
+ Start Ollama and download a model. For example:
92
+
93
+ ```bash
94
+ ollama pull llama3.1
95
+ ```
96
+
97
+ The default local endpoint is `http://localhost:11434`, and the default model is `llama3.1`.
98
+
99
+ Run CommitWise:
100
+
101
+ ```bash
102
+ commitwise --ai-local
103
+ ```
104
+
105
+ Ollama responses are streamed while they are generated. If a stream is interrupted, CommitWise discards the incomplete response and retries the generation from the beginning. It makes up to three total attempts; it does not attempt token-level resume.
106
+
107
+ ### Online AI with OpenRouter
108
+
109
+ Configure your OpenRouter model and API key:
110
+
111
+ ```bash
112
+ commitwise config set online.model "your-provider/your-model"
113
+ commitwise config set online.api_key "YOUR_OPENROUTER_API_KEY"
114
+ ```
115
+
116
+ Then run:
117
+
118
+ ```bash
119
+ commitwise --ai-online
120
+ ```
121
+
122
+ The API key is stored in your per-user configuration file and masked when configuration is displayed. Treat that file as sensitive and do not share it.
123
+
124
+ ## Configuration
125
+
126
+ Settings are stored globally for your user account, so you do not need to configure every repository separately.
127
+
128
+ | Platform | Configuration path |
129
+ | --- | --- |
130
+ | Windows | `%APPDATA%\\CommitWise\\config.toml` |
131
+ | Linux | `~/.config/commitwise/config.toml` |
132
+
133
+ Show the current configuration (with secrets masked):
134
+
135
+ ```bash
136
+ commitwise config show
137
+ ```
138
+
139
+ Show the configuration file location:
140
+
141
+ ```bash
142
+ commitwise config path
143
+ ```
144
+
145
+ Change a setting:
146
+
147
+ ```bash
148
+ commitwise config set local.model "qwen2.5-coder"
149
+ commitwise config set general.max_diff_size 50000
150
+ ```
151
+
152
+ The default staged-diff limit is **50,000 bytes**. If the staged diff exceeds the configured limit, CommitWise stops before contacting the AI provider and asks you to split the work into smaller commits.
153
+
154
+ ## Safety and behavior
155
+
156
+ CommitWise is intentionally limited to suggesting messages:
157
+
158
+ - It reads **staged changes only**; unstaged working-tree changes are not included.
159
+ - It does not run `git add`, `git commit`, `git reset`, `git checkout`, `git switch`, or `git restore`.
160
+ - It does not stage, commit, reset, or otherwise modify your working tree, index, refs, or Git history.
161
+ - If nothing is staged or the staged diff is empty, it stops without making an AI request.
162
+ - The local and online flags are mutually exclusive. There is no automatic provider fallback.
163
+ - It requests exactly three single-line Conventional Commit suggestions and rejects structurally invalid output.
164
+ - It does not truncate or automatically split large diffs.
165
+
166
+ Always review the generated message before using it. AI suggestions can be imperfect, especially when the change itself is ambiguous.
167
+
168
+ ## Development
169
+
170
+ Clone the repository, install the development dependencies, and run the test suite:
171
+
172
+ ```bash
173
+ git clone https://github.com/hasssan-hasssan/commitwise.git
174
+ cd commitwise
175
+ python -m pip install -e ".[dev]"
176
+ python -m pytest -q
177
+ ```
178
+
179
+ The CI workflow runs the unit tests on Windows and Linux with Python 3.15 and builds the package to smoke-test the installed CLI.
180
+
181
+ ## Project links
182
+
183
+ - [Source code](https://github.com/hasssan-hasssan/commitwise)
184
+ - [Changelog](CHANGELOG.md)
185
+ - [Architecture overview](docs/architecture.md)
186
+ - [Report a bug or request a feature](https://github.com/hasssan-hasssan/commitwise/issues)
187
+
188
+ ---
189
+
190
+ **Commit your code Wisely ...**
@@ -0,0 +1,169 @@
1
+ # CommitWise
2
+
3
+ **Commit your code Wisely ...**
4
+
5
+ [![PyPI version](https://img.shields.io/pypi/v/commitwise)](https://pypi.org/project/commitwise/)
6
+ [![Python](https://img.shields.io/badge/python-3.15%2B-blue)](https://www.python.org/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
8
+
9
+ CommitWise is an AI-powered command-line assistant that turns your **Git staged changes** into three clear, English [Conventional Commit](https://www.conventionalcommits.org/) message suggestions.
10
+
11
+ Choose the AI provider that fits your workflow:
12
+ - **Local:** run a model on your machine with [Ollama](https://ollama.com/).
13
+ - **Online:** generate suggestions with a model available through [OpenRouter](https://openrouter.ai/).
14
+
15
+ > **You stay in control.** CommitWise suggests commit messages; it never creates commits or changes your Git repository.
16
+
17
+ ## Why CommitWise?
18
+
19
+ Writing a good commit message takes attention away from the code you're working on. CommitWise reads the changes you've already staged, asks your selected AI provider for three alternatives, validates their format, and lets you choose the one you want.
20
+
21
+ - **Three suggestions, one staged diff:** every suggestion describes the complete staged change set, not an individual file.
22
+ - **Your choice of AI:** use Ollama locally or OpenRouter online.
23
+ - **Conventional Commits:** suggestions follow the Conventional Commits header format.
24
+ - **Safe by design:** Git access is read-only; you decide what gets committed.
25
+ - **Global settings:** configure providers once and reuse the settings across repositories.
26
+ - **Focused changes:** a configurable diff-size limit helps keep commits manageable.
27
+
28
+ ## Quick start
29
+
30
+ ### 1. Requirements
31
+
32
+ - Python **3.15 or newer**
33
+ - Git installed and available on your `PATH`
34
+ - One configured AI provider:
35
+ - Ollama running locally with a model downloaded, or
36
+ - an OpenRouter API key and model name
37
+
38
+ ### 2. Install
39
+
40
+ ```bash
41
+ pip install commitwise
42
+ ```
43
+
44
+ ### 3. Stage your changes and generate suggestions
45
+
46
+ Stage the files you want to describe:
47
+
48
+ ```bash
49
+ git add <files>
50
+ ```
51
+
52
+ Then choose **one** provider:
53
+
54
+ ```bash
55
+ commitwise --ai-local
56
+ ```
57
+
58
+ or:
59
+
60
+ ```bash
61
+ commitwise --ai-online
62
+ ```
63
+
64
+ CommitWise displays three suggestions and asks you to select one. The selected message is copied to your clipboard when a clipboard backend is available. Review it, then run the Git commit command yourself.
65
+
66
+ ## Choose a provider
67
+
68
+ ### Local AI with Ollama
69
+
70
+ Start Ollama and download a model. For example:
71
+
72
+ ```bash
73
+ ollama pull llama3.1
74
+ ```
75
+
76
+ The default local endpoint is `http://localhost:11434`, and the default model is `llama3.1`.
77
+
78
+ Run CommitWise:
79
+
80
+ ```bash
81
+ commitwise --ai-local
82
+ ```
83
+
84
+ Ollama responses are streamed while they are generated. If a stream is interrupted, CommitWise discards the incomplete response and retries the generation from the beginning. It makes up to three total attempts; it does not attempt token-level resume.
85
+
86
+ ### Online AI with OpenRouter
87
+
88
+ Configure your OpenRouter model and API key:
89
+
90
+ ```bash
91
+ commitwise config set online.model "your-provider/your-model"
92
+ commitwise config set online.api_key "YOUR_OPENROUTER_API_KEY"
93
+ ```
94
+
95
+ Then run:
96
+
97
+ ```bash
98
+ commitwise --ai-online
99
+ ```
100
+
101
+ The API key is stored in your per-user configuration file and masked when configuration is displayed. Treat that file as sensitive and do not share it.
102
+
103
+ ## Configuration
104
+
105
+ Settings are stored globally for your user account, so you do not need to configure every repository separately.
106
+
107
+ | Platform | Configuration path |
108
+ | --- | --- |
109
+ | Windows | `%APPDATA%\\CommitWise\\config.toml` |
110
+ | Linux | `~/.config/commitwise/config.toml` |
111
+
112
+ Show the current configuration (with secrets masked):
113
+
114
+ ```bash
115
+ commitwise config show
116
+ ```
117
+
118
+ Show the configuration file location:
119
+
120
+ ```bash
121
+ commitwise config path
122
+ ```
123
+
124
+ Change a setting:
125
+
126
+ ```bash
127
+ commitwise config set local.model "qwen2.5-coder"
128
+ commitwise config set general.max_diff_size 50000
129
+ ```
130
+
131
+ The default staged-diff limit is **50,000 bytes**. If the staged diff exceeds the configured limit, CommitWise stops before contacting the AI provider and asks you to split the work into smaller commits.
132
+
133
+ ## Safety and behavior
134
+
135
+ CommitWise is intentionally limited to suggesting messages:
136
+
137
+ - It reads **staged changes only**; unstaged working-tree changes are not included.
138
+ - It does not run `git add`, `git commit`, `git reset`, `git checkout`, `git switch`, or `git restore`.
139
+ - It does not stage, commit, reset, or otherwise modify your working tree, index, refs, or Git history.
140
+ - If nothing is staged or the staged diff is empty, it stops without making an AI request.
141
+ - The local and online flags are mutually exclusive. There is no automatic provider fallback.
142
+ - It requests exactly three single-line Conventional Commit suggestions and rejects structurally invalid output.
143
+ - It does not truncate or automatically split large diffs.
144
+
145
+ Always review the generated message before using it. AI suggestions can be imperfect, especially when the change itself is ambiguous.
146
+
147
+ ## Development
148
+
149
+ Clone the repository, install the development dependencies, and run the test suite:
150
+
151
+ ```bash
152
+ git clone https://github.com/hasssan-hasssan/commitwise.git
153
+ cd commitwise
154
+ python -m pip install -e ".[dev]"
155
+ python -m pytest -q
156
+ ```
157
+
158
+ The CI workflow runs the unit tests on Windows and Linux with Python 3.15 and builds the package to smoke-test the installed CLI.
159
+
160
+ ## Project links
161
+
162
+ - [Source code](https://github.com/hasssan-hasssan/commitwise)
163
+ - [Changelog](CHANGELOG.md)
164
+ - [Architecture overview](docs/architecture.md)
165
+ - [Report a bug or request a feature](https://github.com/hasssan-hasssan/commitwise/issues)
166
+
167
+ ---
168
+
169
+ **Commit your code Wisely ...**
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"
@@ -0,0 +1,5 @@
1
+ """Allow running CommitWise with `python -m commitwise`."""
2
+
3
+ from commitwise.cli import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,184 @@
1
+ """Command-line interface for CommitWise's safe, staged-diff workflow."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from typing import List, Optional
7
+
8
+ import pyperclip
9
+
10
+ from commitwise import __version__
11
+ from commitwise.config.manager import ConfigError, ConfigManager
12
+ from commitwise.core.diff import DiffAnalyzer
13
+ from commitwise.core.generator import CommitMessageGenerator, TRANSIENT_ERRORS
14
+ from commitwise.core.git import GitClient
15
+ from commitwise.errors import (
16
+ CommitWiseError,
17
+ DiffTooLargeError,
18
+ NoStagedChangesError,
19
+ )
20
+ from commitwise.providers.factory import create_provider
21
+
22
+
23
+ def build_parser() -> argparse.ArgumentParser:
24
+ """Build the public CLI; provider selection is explicit and exclusive."""
25
+ parser = argparse.ArgumentParser(
26
+ prog="commitwise",
27
+ description="Commit your code Wisely ...",
28
+ )
29
+ parser.add_argument(
30
+ "--version", "-V", action="version",
31
+ version="commitwise {}".format(__version__),
32
+ )
33
+ provider_group = parser.add_mutually_exclusive_group()
34
+ provider_group.add_argument(
35
+ "--ai-local", action="store_true",
36
+ help="Generate suggestions with the local Ollama model.",
37
+ )
38
+ provider_group.add_argument(
39
+ "--ai-online", action="store_true",
40
+ help="Generate suggestions with OpenRouter.",
41
+ )
42
+
43
+ commands = parser.add_subparsers(dest="command")
44
+ config_parser = commands.add_parser("config", help="Manage global configuration.")
45
+ config_commands = config_parser.add_subparsers(dest="config_command")
46
+
47
+ config_commands.add_parser("show", help="Show global configuration (secrets masked).")
48
+ config_commands.add_parser("path", help="Show the global configuration file path.")
49
+
50
+ set_parser = config_commands.add_parser("set", help="Set one global configuration value.")
51
+ set_parser.add_argument("key", help="Dotted setting name, e.g. online.model.")
52
+ set_parser.add_argument("value", help="New setting value.")
53
+
54
+ return parser
55
+
56
+
57
+ def _show_no_staged_files(mode: str) -> None:
58
+ command = "commitwise --ai-online" if mode == "online" else "commitwise --ai-local"
59
+ print(
60
+ "No staged files found!\n\n"
61
+ "No files have been staged for commit.\n\n"
62
+ "Please stage your changes first:\n\n"
63
+ "git add <files>\n\n"
64
+ "Then run:\n\n"
65
+ "{}".format(command),
66
+ file=sys.stderr,
67
+ )
68
+
69
+
70
+ def _run_config(args: argparse.Namespace, manager: ConfigManager) -> int:
71
+ if args.config_command == "show":
72
+ print(json.dumps(manager.get_masked_config(), indent=2, sort_keys=True))
73
+ return 0
74
+ if args.config_command == "path":
75
+ print(str(manager.config_path))
76
+ return 0
77
+ if args.config_command == "set":
78
+ manager.set_value(args.key, args.value)
79
+ displayed = manager.get_masked_config()
80
+ section, name = args.key.split(".", 1)
81
+ print("{} = {}".format(args.key, json.dumps(displayed[section][name])))
82
+ return 0
83
+ print("Use 'commitwise config --help' to see configuration commands.")
84
+ return 0
85
+
86
+
87
+ def _run_generation(mode: str, manager: ConfigManager) -> int:
88
+ config = manager.load()
89
+ analysis = DiffAnalyzer(
90
+ GitClient(),
91
+ max_diff_size=config["general"]["max_diff_size"],
92
+ ).analyze()
93
+
94
+ print(
95
+ "Analyzing {} staged file(s) ({} bytes).".format(
96
+ len(analysis.files), analysis.size_bytes
97
+ )
98
+ )
99
+ if mode == "local":
100
+ print("Generating with Ollama; response is received incrementally.")
101
+ else:
102
+ print("Generating with OpenRouter.")
103
+
104
+ provider = create_provider(mode, config)
105
+ suggestions = CommitMessageGenerator(provider).generate(analysis.diff)
106
+
107
+ print("\nCommit message suggestions:\n")
108
+ for index, suggestion in enumerate(suggestions, start=1):
109
+ print("{}. {}".format(index, suggestion))
110
+
111
+ try:
112
+ selected = input("\nSelect a suggestion to copy [1-3, q to quit]: ").strip()
113
+ except (EOFError, KeyboardInterrupt):
114
+ print("\nSelection cancelled.")
115
+ return 0
116
+
117
+ if selected.lower() == "q":
118
+ print("No suggestion selected.")
119
+ return 0
120
+ if selected not in ("1", "2", "3"):
121
+ print("Invalid selection. No message was copied.", file=sys.stderr)
122
+ return 2
123
+
124
+ message = suggestions[int(selected) - 1]
125
+ try:
126
+ pyperclip.copy(message)
127
+ print("\nCopied to clipboard. Run this yourself when ready:")
128
+ except pyperclip.PyperclipException:
129
+ print("\nClipboard is unavailable. Copy the message manually:")
130
+ print(message)
131
+ return 0
132
+
133
+ print('git commit -m "{}"'.format(message.replace('"', '\\"')))
134
+ return 0
135
+
136
+
137
+ def main(argv: Optional[List[str]] = None) -> int:
138
+ """Run a CLI command and translate expected errors into useful messages."""
139
+ parser = build_parser()
140
+ args = parser.parse_args(argv)
141
+ manager = ConfigManager()
142
+
143
+ if args.command == "config":
144
+ try:
145
+ return _run_config(args, manager)
146
+ except (ConfigError, ValueError) as exc:
147
+ print("Error: {}".format(exc), file=sys.stderr)
148
+ return 1
149
+
150
+ mode = "local" if args.ai_local else "online" if args.ai_online else None
151
+ if mode is None:
152
+ parser.print_help()
153
+ return 0
154
+
155
+ try:
156
+ return _run_generation(mode, manager)
157
+ except NoStagedChangesError:
158
+ _show_no_staged_files(mode)
159
+ return 1
160
+ except DiffTooLargeError as exc:
161
+ print(
162
+ "Staged diff is too large ({} bytes; limit: {} bytes).\n"
163
+ "Split the changes into smaller commits and try again.".format(
164
+ exc.actual_size, exc.maximum_size
165
+ ),
166
+ file=sys.stderr,
167
+ )
168
+ return 1
169
+ except TRANSIENT_ERRORS as exc:
170
+ print(
171
+ "The AI provider failed after three attempts.\n{}".format(exc),
172
+ file=sys.stderr,
173
+ )
174
+ return 1
175
+ except (CommitWiseError, ConfigError) as exc:
176
+ print("Error: {}".format(exc), file=sys.stderr)
177
+ return 1
178
+ except KeyboardInterrupt:
179
+ print("\nCancelled.")
180
+ return 130
181
+
182
+
183
+ if __name__ == "__main__":
184
+ raise SystemExit(main())
@@ -0,0 +1,6 @@
1
+ """Global configuration support for CommitWise."""
2
+
3
+ from commitwise.config.manager import ConfigManager
4
+ from commitwise.config.schema import DEFAULT_CONFIG
5
+
6
+ __all__ = ["ConfigManager", "DEFAULT_CONFIG"]
@@ -0,0 +1,131 @@
1
+ """Load, validate, update, and safely write global CommitWise config."""
2
+
3
+ import os
4
+ import tempfile
5
+ from copy import deepcopy
6
+ from pathlib import Path
7
+ from typing import Any, Dict, Optional
8
+
9
+ import tomlkit
10
+
11
+ from commitwise.config.paths import get_config_dir, get_config_path
12
+ from commitwise.config.schema import (
13
+ ALLOWED_SETTINGS,
14
+ default_config,
15
+ validate_config,
16
+ )
17
+
18
+
19
+ class ConfigError(Exception):
20
+ """Raised when CommitWise configuration cannot be read or updated."""
21
+
22
+
23
+ class ConfigManager:
24
+ """Manage the single per-user CommitWise TOML configuration."""
25
+
26
+ def __init__(
27
+ self,
28
+ config_path: Optional[Path] = None,
29
+ config_dir: Optional[Path] = None,
30
+ ) -> None:
31
+ self.config_path = Path(config_path) if config_path else get_config_path()
32
+ self.config_dir = (
33
+ Path(config_dir) if config_dir else self.config_path.parent
34
+ )
35
+
36
+ def load(self) -> Dict[str, Any]:
37
+ """Load the configuration, creating a default file on first use."""
38
+ if not self.config_path.exists():
39
+ config = default_config()
40
+ self.save(config)
41
+ return config
42
+
43
+ try:
44
+ with self.config_path.open("r", encoding="utf-8") as config_file:
45
+ parsed = tomlkit.parse(config_file.read())
46
+ config = self._to_plain_dict(parsed)
47
+ validate_config(config)
48
+ return config
49
+ except (OSError, ValueError, tomlkit.exceptions.ParseError) as exc:
50
+ raise ConfigError(
51
+ "Unable to load configuration at {}: {}".format(
52
+ self.config_path, exc
53
+ )
54
+ ) from exc
55
+
56
+ def save(self, config: Dict[str, Any]) -> None:
57
+ """Validate and atomically save a complete configuration."""
58
+ try:
59
+ validate_config(config)
60
+ document = tomlkit.document()
61
+ for section_name, values in config.items():
62
+ section = tomlkit.table()
63
+ for key, value in values.items():
64
+ section.add(key, value)
65
+ document.add(section_name, section)
66
+
67
+ self.config_dir.mkdir(parents=True, exist_ok=True)
68
+ file_descriptor, temporary_name = tempfile.mkstemp(
69
+ prefix=".commitwise-",
70
+ suffix=".toml.tmp",
71
+ dir=str(self.config_dir),
72
+ )
73
+ try:
74
+ with os.fdopen(file_descriptor, "w", encoding="utf-8", newline="\n") as temp_file:
75
+ temp_file.write(tomlkit.dumps(document))
76
+ temp_file.flush()
77
+ os.fsync(temp_file.fileno())
78
+ os.replace(temporary_name, str(self.config_path))
79
+ finally:
80
+ if os.path.exists(temporary_name):
81
+ os.unlink(temporary_name)
82
+ except (OSError, ValueError, TypeError) as exc:
83
+ raise ConfigError("Unable to save configuration: {}".format(exc)) from exc
84
+
85
+ def set_value(self, key: str, value: Any) -> Dict[str, Any]:
86
+ """Update one allowlisted dotted setting and persist the result."""
87
+ if key not in ALLOWED_SETTINGS:
88
+ raise ConfigError("Unknown configuration setting: {}".format(key))
89
+
90
+ expected_type = ALLOWED_SETTINGS[key]
91
+ if expected_type is int:
92
+ try:
93
+ if isinstance(value, bool):
94
+ raise ValueError
95
+ converted_value = int(value)
96
+ except (TypeError, ValueError) as exc:
97
+ raise ConfigError("{} must be an integer.".format(key)) from exc
98
+ else:
99
+ converted_value = str(value)
100
+
101
+ config = self.load()
102
+ section, name = key.split(".", 1)
103
+ config[section][name] = converted_value
104
+ try:
105
+ validate_config(config)
106
+ except ValueError as exc:
107
+ raise ConfigError(str(exc)) from exc
108
+ self.save(config)
109
+ return config
110
+
111
+ def get_masked_config(self) -> Dict[str, Any]:
112
+ """Return configuration safe for display; never reveal the API key."""
113
+ config = deepcopy(self.load())
114
+ api_key = config["online"].get("api_key", "")
115
+ if api_key:
116
+ config["online"]["api_key"] = "********"
117
+ return config
118
+
119
+ @staticmethod
120
+ def _to_plain_dict(parsed: Any) -> Dict[str, Any]:
121
+ """Convert TOMLKit tables into ordinary Python dictionaries."""
122
+ result: Dict[str, Any] = {}
123
+ for section_name, values in parsed.items():
124
+ if not hasattr(values, "items"):
125
+ result[section_name] = values
126
+ continue
127
+ result[section_name] = {
128
+ key: value.unwrap() if hasattr(value, "unwrap") else value
129
+ for key, value in values.items()
130
+ }
131
+ return result