1use crate::args::Args;
2pub use crate::rewrite::engine::validate_identity_part;
3use crate::utils::dates::parse_git_time;
4use crate::utils::types::Result;
5use regex::Regex;
6
7pub fn is_valid_email(email: &str) -> bool {
9 Regex::new(r"(?i)^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$")
10 .map(|re| re.is_match(email))
11 .unwrap_or(false)
12}
13
14pub fn validate_inputs(args: &Args) -> Result<()> {
15 if args.docs {
17 return Ok(());
18 }
19
20 let repo_path = args.repo_path.as_ref().unwrap();
22
23 if repo_path.is_empty() {
24 return Err("Repository path cannot be empty".into());
25 }
26 let path = std::path::Path::new(repo_path);
29 if !path.exists() {
30 return Err(format!("Repository path does not exist: {repo_path}").into());
31 }
32 if let Err(e) = git2::Repository::open(path) {
33 return Err(format!("Not a Git repository: {repo_path} ({})", e.message()).into());
34 }
35
36 if args.simulate {
38 if let Some(email) = &args.email {
39 if !is_valid_email(email) {
40 return Err(format!("Invalid email format: {email}").into());
41 }
42 }
43 if let Some(name) = &args.name {
44 validate_identity_part(name, "Name")?;
45 }
46 for (flag, value) in [("start", &args.start), ("end", &args.end)] {
47 if let Some(value) = value {
48 parse_git_time(value).map_err(|e| format!("Invalid {flag} date: {e}"))?;
49 }
50 }
51 }
52
53 if args.show_history || args.pick_specific_commits || args.range || args.simulate || args.docs {
55 return Ok(());
56 }
57
58 let email = args.email.as_ref().ok_or("Missing --email")?;
60 let name = args.name.as_ref().ok_or("Missing --name")?;
61
62 if !is_valid_email(email) {
63 return Err(format!("Invalid email format: {email}").into());
64 }
65
66 if name.trim().is_empty() {
67 return Err("Name cannot be empty".into());
68 }
69 validate_identity_part(name, "Name")?;
70
71 if args.keep_dates {
72 if args.start.is_some() || args.end.is_some() {
73 return Err("--keep-dates cannot be combined with --begin/--end".into());
74 }
75 return Ok(());
76 }
77
78 let start = args.start.as_ref().ok_or("Missing --begin")?;
79 let end = args.end.as_ref().ok_or("Missing --end")?;
80 for (flag, value) in [("--begin", start), ("--end", end)] {
81 if value == "KEEP_ORIGINAL" {
82 return Err(format!(
83 "{flag} KEEP_ORIGINAL is no longer supported; use --keep-dates instead"
84 )
85 .into());
86 }
87 }
88
89 let start_time = parse_git_time(start).map_err(|e| format!("Invalid start date: {e}"))?;
90 let end_time = parse_git_time(end).map_err(|e| format!("Invalid end date: {e}"))?;
91
92 if start_time.seconds >= end_time.seconds {
93 return Err("Start date must be before end date".into());
94 }
95
96 Ok(())
97}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102 use std::fs;
103 use tempfile::TempDir;
104
105 fn create_test_repo() -> (TempDir, String) {
106 let temp_dir = TempDir::new().unwrap();
107 let repo_path = temp_dir.path().to_str().unwrap().to_string();
108
109 let repo = git2::Repository::init(&repo_path).unwrap();
111
112 let file_path = temp_dir.path().join("test.txt");
114 fs::write(&file_path, "test content").unwrap();
115
116 let mut index = repo.index().unwrap();
118 index.add_path(std::path::Path::new("test.txt")).unwrap();
119 index.write().unwrap();
120
121 let tree_id = index.write_tree().unwrap();
122 let tree = repo.find_tree(tree_id).unwrap();
123
124 let sig = git2::Signature::new(
125 "Test User",
126 "test@example.com",
127 &git2::Time::new(1234567890, 0),
128 )
129 .unwrap();
130 repo.commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
131 .unwrap();
132
133 (temp_dir, repo_path)
134 }
135
136 #[test]
137 fn test_validate_inputs_show_history_mode() {
138 let (_temp_dir, repo_path) = create_test_repo();
139 let args = Args {
140 repo_path: Some(repo_path),
141 show_history: true,
142 ..Default::default()
143 };
144
145 let result = validate_inputs(&args);
146 assert!(result.is_ok());
147 }
148
149 #[test]
150 fn test_validate_inputs_pick_specific_commits_mode() {
151 let (_temp_dir, repo_path) = create_test_repo();
152 let args = Args {
153 repo_path: Some(repo_path),
154 pick_specific_commits: true,
155 ..Default::default()
156 };
157
158 let result = validate_inputs(&args);
159 assert!(result.is_ok());
160 }
161
162 #[test]
163 fn test_validate_inputs_full_rewrite_valid() {
164 let (_temp_dir, repo_path) = create_test_repo();
165 let args = Args {
166 repo_path: Some(repo_path),
167 email: Some("test@example.com".to_string()),
168 name: Some("Test User".to_string()),
169 start: Some("2023-01-01 00:00:00".to_string()),
170 end: Some("2023-01-02 00:00:00".to_string()),
171 ..Default::default()
172 };
173
174 let result = validate_inputs(&args);
175 assert!(result.is_ok());
176 }
177
178 #[test]
179 fn test_validate_inputs_invalid_email() {
180 let (_temp_dir, repo_path) = create_test_repo();
181 let _args = Args {
182 repo_path: Some(repo_path),
183 email: Some("invalid-email".to_string()),
184 name: Some("Test User".to_string()),
185 start: Some("2023-01-01 00:00:00".to_string()),
186 end: Some("2023-01-02 00:00:00".to_string()),
187 ..Default::default()
188 };
189
190 let email_re = Regex::new(r"(?i)^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$").unwrap();
193 assert!(!email_re.is_match("invalid-email"));
194 assert!(email_re.is_match("test@example.com"));
195 }
196
197 #[test]
198 fn test_validate_inputs_invalid_date_format() {
199 let (_temp_dir, repo_path) = create_test_repo();
200 let _args = Args {
201 repo_path: Some(repo_path),
202 email: Some("test@example.com".to_string()),
203 name: Some("Test User".to_string()),
204 start: Some("invalid-date".to_string()),
205 end: Some("2023-01-02 00:00:00".to_string()),
206 ..Default::default()
207 };
208
209 let start_re = Regex::new(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$").unwrap();
210 assert!(!start_re.is_match("invalid-date"));
211 assert!(start_re.is_match("2023-01-01 00:00:00"));
212 }
213
214 #[test]
215 fn test_validate_inputs_nonexistent_repo() {
216 let _args = Args {
217 repo_path: Some("/nonexistent/path".to_string()),
218 email: Some("test@example.com".to_string()),
219 name: Some("Test User".to_string()),
220 start: Some("2023-01-01 00:00:00".to_string()),
221 end: Some("2023-01-02 00:00:00".to_string()),
222 ..Default::default()
223 };
224
225 let repo_path = "/nonexistent/path";
227 assert!(!std::path::Path::new(repo_path).exists());
228 }
229
230 #[test]
231 fn test_email_regex_patterns() {
232 assert!(is_valid_email("test@example.com"));
234 assert!(is_valid_email("user.name@domain.org"));
235 assert!(is_valid_email("user+tag@example.co.uk"));
236 assert!(is_valid_email("123@test.io"));
237
238 assert!(!is_valid_email("invalid-email"));
240 assert!(!is_valid_email("@domain.com"));
241 assert!(!is_valid_email("user@"));
242 assert!(!is_valid_email("user@domain"));
243 assert!(!is_valid_email("user@domain."));
244 assert!(!is_valid_email("not-an-email"));
245 }
246
247 #[test]
248 fn test_datetime_regex_patterns() {
249 let datetime_re = Regex::new(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$").unwrap();
250
251 assert!(datetime_re.is_match("2023-01-01 00:00:00"));
253 assert!(datetime_re.is_match("2023-12-31 23:59:59"));
254 assert!(datetime_re.is_match("2023-06-15 12:30:45"));
255
256 assert!(!datetime_re.is_match("2023-1-1 0:0:0"));
258 assert!(!datetime_re.is_match("2023/01/01 00:00:00"));
259 assert!(!datetime_re.is_match("2023-01-01T00:00:00"));
260 assert!(!datetime_re.is_match("23-01-01 00:00:00"));
261 assert!(!datetime_re.is_match("2023-01-01 00:00"));
262 }
263
264 fn create_test_repo_with_commits() -> (TempDir, String) {
265 let temp_dir = TempDir::new().unwrap();
266 let repo_path = temp_dir.path().to_str().unwrap().to_string();
267
268 let repo = git2::Repository::init(&repo_path).unwrap();
270
271 for i in 1..=3 {
273 let file_path = temp_dir.path().join(format!("test{i}.txt"));
274 std::fs::write(&file_path, format!("test content {i}")).unwrap();
275
276 let mut index = repo.index().unwrap();
277 index
278 .add_path(std::path::Path::new(&format!("test{i}.txt")))
279 .unwrap();
280 index.write().unwrap();
281
282 let tree_id = index.write_tree().unwrap();
283 let tree = repo.find_tree(tree_id).unwrap();
284
285 let sig = git2::Signature::new(
286 "Test User",
287 "test@example.com",
288 &git2::Time::new(1234567890 + i as i64 * 3600, 0),
289 )
290 .unwrap();
291
292 let parents = if i == 1 {
293 vec![]
294 } else {
295 let head = repo.head().unwrap();
296 let parent_commit = head.peel_to_commit().unwrap();
297 vec![parent_commit]
298 };
299
300 repo.commit(
301 Some("HEAD"),
302 &sig,
303 &sig,
304 &format!("Commit {i}"),
305 &tree,
306 &parents.iter().collect::<Vec<_>>(),
307 )
308 .unwrap();
309 }
310
311 (temp_dir, repo_path)
312 }
313
314 #[test]
315 fn test_validate_inputs_range_mode() {
316 let (_temp_dir, repo_path) = create_test_repo_with_commits();
317 let args = Args {
318 repo_path: Some(repo_path),
319 range: true,
320 ..Default::default()
321 };
322
323 let result = validate_inputs(&args);
324 assert!(result.is_ok());
325 }
326
327 #[test]
328 fn test_validate_inputs_docs_mode() {
329 let args = Args {
331 repo_path: None, docs: true,
333 ..Default::default()
334 };
335
336 let result = validate_inputs(&args);
337 assert!(result.is_ok());
338 }
339
340 #[test]
341 fn test_validate_inputs_docs_mode_with_invalid_path() {
342 let args = Args {
344 repo_path: Some("/completely/invalid/path/that/does/not/exist".to_string()),
345 email: Some("invalid-email".to_string()), start: Some("invalid-date".to_string()), docs: true,
348 ..Default::default()
349 };
350
351 let result = validate_inputs(&args);
352 assert!(result.is_ok());
353 }
354
355 #[test]
356 fn test_validate_inputs_docs_mode_precedence() {
357 let args = Args {
359 repo_path: Some("/invalid/path".to_string()),
360 show_history: true, pick_specific_commits: true,
362 range: true,
363 simulate: true,
364 docs: true, ..Default::default()
366 };
367
368 let result = validate_inputs(&args);
369 assert!(result.is_ok());
370 }
371
372 #[test]
373 fn test_keep_dates_needs_no_begin_end() {
374 let (_temp_dir, repo_path) = create_test_repo();
375 let args = Args {
376 repo_path: Some(repo_path),
377 email: Some("new@example.com".to_string()),
378 name: Some("New".to_string()),
379 keep_dates: true,
380 ..Default::default()
381 };
382 assert!(validate_inputs(&args).is_ok());
383 }
384
385 #[test]
386 fn test_keep_dates_conflicts_with_begin_end() {
387 let (_temp_dir, repo_path) = create_test_repo();
388 let args = Args {
389 repo_path: Some(repo_path),
390 email: Some("new@example.com".to_string()),
391 name: Some("New".to_string()),
392 start: Some("2023-01-01 00:00:00".to_string()),
393 keep_dates: true,
394 ..Default::default()
395 };
396 assert!(validate_inputs(&args).is_err());
397 }
398
399 #[test]
400 fn test_keep_original_sentinel_is_rejected() {
401 let (_temp_dir, repo_path) = create_test_repo();
402 let args = Args {
403 repo_path: Some(repo_path),
404 email: Some("new@example.com".to_string()),
405 name: Some("New".to_string()),
406 start: Some("KEEP_ORIGINAL".to_string()),
407 end: Some("KEEP_ORIGINAL".to_string()),
408 ..Default::default()
409 };
410 let err = validate_inputs(&args).unwrap_err().to_string();
411 assert!(err.contains("--keep-dates"), "{err}");
412 }
413
414 #[test]
415 fn test_name_with_newline_is_rejected() {
416 let (_temp_dir, repo_path) = create_test_repo();
417 let args = Args {
418 repo_path: Some(repo_path),
419 email: Some("new@example.com".to_string()),
420 name: Some("New\nInjected: header".to_string()),
421 keep_dates: true,
422 ..Default::default()
423 };
424 let err = validate_inputs(&args).unwrap_err().to_string();
425 assert!(err.contains("invalid character"), "{err}");
426 }
427
428 #[test]
429 fn test_simulation_rejects_invalid_email() {
430 let (_temp_dir, repo_path) = create_test_repo();
431 let args = Args {
432 repo_path: Some(repo_path),
433 email: Some("bogus".to_string()),
434 name: Some("N".to_string()),
435 simulate: true,
436 ..Default::default()
437 };
438 assert!(validate_inputs(&args).is_err());
439 }
440}