Skip to content

Commit 71dce29

Browse files
authored
chore: add pre-commit hooks and fix clippy/fmt issues (#26)
* chore: ignore .codebuddy directory - add .codebuddy/ to .gitignore Signed-off-by: staryxchen <staryxchen@tencent.com> * chore: add pre-commit configuration for Rust - Add pre-commit hooks for rustfmt, clippy, and cargo-check - Update documentation Signed-off-by: staryxchen <staryxchen@tencent.com> * refactor: modernize Rust syntax and simplify code structure - Use `format!` inline variables throughout the codebase. - Derive `Default` trait for enums instead of manual implementation. - Replace `loop { if let ... }` patterns with `while let ...`. - Simplify test configuration initialization using struct update syntax. - Update assertions from `assert_eq!(..., true)` to `assert!(...)`. Signed-off-by: staryxchen <staryxchen@tencent.com> * chore(pre-commit): add standard pre-commit hooks - add trailing-whitespace hook - add end-of-file-fixer hook - add check-yaml hook - add check-toml hook - add check-merge-conflict hook - add check-added-large-files hook Signed-off-by: staryxchen <staryxchen@tencent.com> * style: clean up whitespace and line endings - Remove trailing whitespace in workflow, gitignore, and readme files - Ensure newline at end of file in docs/TEXT_WRAPPING.md Signed-off-by: staryxchen <staryxchen@tencent.com> --------- Signed-off-by: staryxchen <staryxchen@tencent.com>
1 parent 9565f0b commit 71dce29

15 files changed

Lines changed: 211 additions & 147 deletions

.github/workflows/release.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ on:
55
tags:
66
- 'v*'
77
workflow_dispatch:
8-
8+
99

1010
jobs:
1111
build:

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
/target
2+
.codebuddy/

.pre-commit-config.yaml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
repos:
2+
- repo: https://github.com/pre-commit/pre-commit-hooks
3+
rev: v5.0.0
4+
hooks:
5+
- id: trailing-whitespace
6+
- id: end-of-file-fixer
7+
- id: check-yaml
8+
- id: check-toml
9+
- id: check-merge-conflict
10+
- id: check-added-large-files
11+
- repo: https://github.com/doublify/pre-commit-rust
12+
rev: v1.0
13+
hooks:
14+
- id: fmt
15+
args: ["--all", "--", "--check"]
16+
- id: clippy
17+
args: ["--all-targets", "--all-features", "--", "-D", "warnings"]
18+
- id: cargo-check

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,29 @@ NOTE: All common config can be configured via `~/.fastcommit/config.toml`
114114
fastcommit -c --commit-args "-s" --commit-args "--no-verify"
115115
```
116116

117+
## Development
118+
119+
### Pre-commit Hooks
120+
121+
This project uses [pre-commit](https://pre-commit.com/) to run code quality checks before each commit.
122+
123+
```bash
124+
# Install pre-commit
125+
pip install pre-commit
126+
127+
# Install the git hooks
128+
pre-commit install
129+
130+
# (Optional) Run all hooks manually
131+
pre-commit run --all-files
132+
```
133+
134+
The following checks will run automatically on `git commit`:
135+
136+
- **rustfmt** — Code formatting check
137+
- **clippy** — Static analysis with warnings as errors
138+
- **cargo-check** — Compilation check
139+
117140
## GitHub PR Integration
118141

119142
`fastcommit` can generate commit messages for GitHub Pull Requests, which is useful when merging PRs.

README_CN.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,29 @@ fastcommit pr 123 -l zh
151151

152152
更多详情请参阅 [GitHub PR 集成指南](docs/github-pr-integration.md)
153153

154+
## 开发
155+
156+
### Pre-commit Hooks
157+
158+
本项目使用 [pre-commit](https://pre-commit.com/) 在每次提交前自动运行代码质量检查。
159+
160+
```bash
161+
# 安装 pre-commit
162+
pip install pre-commit
163+
164+
# 安装 git hooks
165+
pre-commit install
166+
167+
# (可选)手动运行所有检查
168+
pre-commit run --all-files
169+
```
170+
171+
以下检查会在 `git commit` 时自动执行:
172+
173+
- **rustfmt** — 代码格式化检查
174+
- **clippy** — 静态分析,警告视为错误
175+
- **cargo-check** — 编译检查
176+
154177
## 贡献
155178

156179
欢迎贡献代码或提出建议!请先阅读 [贡献指南](CONTRIBUTING.md)

docs/TEXT_WRAPPING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -420,4 +420,4 @@ Contributions are welcome! Please refer to:
420420

421421
## License
422422

423-
This feature follows the project's MIT license.
423+
This feature follows the project's MIT license.

src/config.rs

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -102,15 +102,15 @@ impl Config {
102102
let api_base = if api_base.ends_with("/") {
103103
api_base.to_owned()
104104
} else {
105-
format!("{}/", api_base)
105+
format!("{api_base}/")
106106
};
107107

108108
api_base
109109
}
110110
}
111111

112112
/// Commit message verbosity level.
113-
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Copy, clap::ValueEnum)]
113+
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Copy, clap::ValueEnum, Default)]
114114
pub enum Verbosity {
115115
/// Detailed commit message.
116116
#[serde(rename = "verbose")]
@@ -123,17 +123,12 @@ pub enum Verbosity {
123123
/// Quiet commit message.
124124
#[serde(rename = "quiet")]
125125
#[clap(name = "quiet")]
126+
#[default]
126127
Quiet,
127128
}
128129

129-
impl Default for Verbosity {
130-
fn default() -> Self {
131-
Verbosity::Quiet
132-
}
133-
}
134-
135130
impl Verbosity {
136-
pub fn to_template_level(&self) -> &'static str {
131+
pub fn as_template_level(self) -> &'static str {
137132
match self {
138133
Verbosity::Verbose => "详细",
139134
Verbosity::Normal => "中等",
@@ -142,22 +137,17 @@ impl Verbosity {
142137
}
143138
}
144139

145-
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
140+
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, clap::ValueEnum, Default)]
146141
pub enum CommitLanguage {
147142
#[clap(name = "en")]
148143
#[serde(rename = "en")]
149144
English,
150145
#[clap(name = "zh")]
151146
#[serde(rename = "zh")]
147+
#[default]
152148
Chinese,
153149
}
154150

155-
impl Default for CommitLanguage {
156-
fn default() -> Self {
157-
CommitLanguage::Chinese
158-
}
159-
}
160-
161151
impl Display for CommitLanguage {
162152
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163153
match self {

src/generate.rs

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ pub async fn generate_commit_message(
3333
if desc.trim().is_empty() {
3434
desc
3535
} else {
36-
format!("commit message: {}", desc)
36+
format!("commit message: {desc}")
3737
}
3838
});
3939

@@ -91,22 +91,17 @@ fn delete_thinking_contents(orig: &str) -> String {
9191
let end_tag = "</think>";
9292

9393
let start_idx = orig.find(start_tag).unwrap_or(orig.len());
94-
let end_idx = orig.find(end_tag).unwrap_or_else(|| 0);
95-
let s = if start_idx < end_idx {
94+
let end_idx = orig.find(end_tag).unwrap_or(0);
95+
if start_idx < end_idx {
9696
let mut result = orig[..start_idx].to_string();
9797
result.push_str(&orig[end_idx..]);
9898
log::debug!(
99-
"Delete thinking contents, start_idx: {}, end_idx: {}: {:?} => {:?}",
100-
start_idx,
101-
end_idx,
102-
orig,
103-
result
99+
"Delete thinking contents, start_idx: {start_idx}, end_idx: {end_idx}: {orig:?} => {result:?}"
104100
);
105101
result
106102
} else {
107103
orig.to_string()
108-
};
109-
s
104+
}
110105
}
111106

112107
fn extract_aicommit_message(response: &str) -> anyhow::Result<String> {

src/main.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -155,12 +155,10 @@ fn print_wrapped_content(wrapper: &Option<TextWrapper>, content: &str, prefix: O
155155
} else {
156156
println!("{}", wrapper.wrap(content));
157157
}
158+
} else if let Some(p) = prefix {
159+
println!("{p} {content}");
158160
} else {
159-
if let Some(p) = prefix {
160-
println!("{} {}", p, content);
161-
} else {
162-
println!("{}", content);
163-
}
161+
println!("{content}");
164162
}
165163
}
166164

src/sanitizer.rs

Lines changed: 12 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -76,31 +76,23 @@ pub fn sanitize(
7676

7777
// Apply builtin patterns
7878
for (kind, re) in builtin.iter() {
79-
loop {
80-
if let Some(m) = re.find(&sanitized) {
81-
counter += 1;
82-
let placeholder = format!("[REDACTED:{}#{}]", kind, counter);
83-
sanitized.replace_range(m.start()..m.end(), &placeholder);
84-
redactions.push(Redaction::new(kind, placeholder));
85-
} else {
86-
break;
87-
}
79+
while let Some(m) = re.find(&sanitized) {
80+
counter += 1;
81+
let placeholder = format!("[REDACTED:{kind}#{counter}]");
82+
sanitized.replace_range(m.start()..m.end(), &placeholder);
83+
redactions.push(Redaction::new(kind, placeholder));
8884
}
8985
}
9086

9187
// Apply custom patterns – use their provided name (converted to static via leak for simplicity)
9288
for meta in custom_patterns {
93-
loop {
94-
if let Some(m) = meta.regex.find(&sanitized) {
95-
counter += 1;
96-
let placeholder = format!("[REDACTED:{}#{}]", meta.name, counter);
97-
sanitized.replace_range(m.start()..m.end(), &placeholder);
98-
// We leak the string to get a 'static str; acceptable given tiny count and CLI nature
99-
let leaked: &'static str = Box::leak(meta.name.clone().into_boxed_str());
100-
redactions.push(Redaction::new(leaked, placeholder));
101-
} else {
102-
break;
103-
}
89+
while let Some(m) = meta.regex.find(&sanitized) {
90+
counter += 1;
91+
let placeholder = format!("[REDACTED:{}#{counter}]", meta.name);
92+
sanitized.replace_range(m.start()..m.end(), &placeholder);
93+
// We leak the string to get a 'static str; acceptable given tiny count and CLI nature
94+
let leaked: &'static str = Box::leak(meta.name.clone().into_boxed_str());
95+
redactions.push(Redaction::new(leaked, placeholder));
10496
}
10597
}
10698

0 commit comments

Comments
 (0)