Skip to content

Commit d454eeb

Browse files
committed
refactor: enhance author validation
- add constants for default author email and name - implement email format validation using regex pattern - add fallback to environment variables for invalid values - detect and handle empty or whitespace author names - improve warning messages with configurable defaults Signed-off-by: mingcheng <mingcheng@apache.org>
1 parent 3d42e36 commit d454eeb

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

src/git/repository.rs

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,17 @@
99
* File Created: 2025-10-16 15:07:05
1010
*
1111
* Modified By: mingcheng <mingcheng@apache.org>
12-
* Last Modified: 2025-10-24 16:33:57
12+
* Last Modified: 2025-11-06 15:00:29
1313
*/
1414

1515
use git2::{Oid, Repository as _Repo, RepositoryOpenFlags, Signature};
16+
use regex::Regex;
1617
use std::error::Error;
1718
use std::fmt::{Display, Formatter};
1819
use tracing::{trace, warn};
1920

2021
use crate::git::message::GitMessage;
22+
use crate::utils::get_env;
2123

2224
/// Author information from git configuration
2325
pub struct Author {
@@ -123,6 +125,10 @@ impl Repository {
123125
pub fn get_author(&self) -> Result<Author, Box<dyn Error>> {
124126
let config = self.repository.config()?;
125127

128+
// Default email if none found
129+
const UNKNOWN_EMAIL: &str = "unknown@users.noreply.github.com";
130+
const UNKNOWN_AUTHOR: &str = "Unknown Author";
131+
126132
// Try to get user.email from config, fall back to environment or default
127133
let email = config
128134
.get_string("user.email")
@@ -131,10 +137,21 @@ impl Repository {
131137
std::env::var("GIT_AUTHOR_EMAIL")
132138
})
133139
.unwrap_or_else(|_| {
134-
warn!("using default email: unknown@example.com");
135-
"unknown@example.com".to_string()
140+
warn!("using default email: {}", UNKNOWN_EMAIL);
141+
get_env("GIT_FALLBACK_EMAIL", UNKNOWN_EMAIL)
136142
});
137143

144+
// Validate email format using regex
145+
let email = if Regex::new(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
146+
.unwrap()
147+
.is_match(&email)
148+
{
149+
email
150+
} else {
151+
warn!("invalid email format: {}, using default", UNKNOWN_EMAIL);
152+
get_env("GIT_FALLBACK_EMAIL", UNKNOWN_EMAIL)
153+
};
154+
138155
// Try to get user.name from config, fall back to environment or default
139156
let name = config
140157
.get_string("user.name")
@@ -147,6 +164,14 @@ impl Repository {
147164
"Unknown User".to_string()
148165
});
149166

167+
// Detect if name is empty or whitespace
168+
let name = if name.trim().is_empty() {
169+
warn!("author name is empty, using default: Unknown Author");
170+
get_env("GIT_FALLBACK_NAME", UNKNOWN_AUTHOR)
171+
} else {
172+
name
173+
};
174+
150175
Ok(Author { name, email })
151176
}
152177

0 commit comments

Comments
 (0)