1use crate::rewrite::engine::Plan;
2use crate::utils::message_trailers::rewrite_author_trailers;
3use crate::utils::types::CommitInfo;
4use chrono::NaiveDateTime;
5use colored::Colorize;
6
7#[derive(Debug, Clone)]
8pub struct SimulationChange {
9 pub commit_oid: git2::Oid,
10 pub short_hash: String,
11 pub original_author: String,
12 pub original_email: String,
13 pub original_timestamp: NaiveDateTime,
14 pub original_message: String,
15 pub new_author: Option<String>,
16 pub new_email: Option<String>,
17 pub new_timestamp: Option<NaiveDateTime>,
18 pub new_message: Option<String>,
19}
20
21#[derive(Debug)]
22pub struct SimulationStats {
23 pub total_commits: usize,
24 pub commits_to_change: usize,
25 pub authors_changed: usize,
26 pub emails_changed: usize,
27 pub timestamps_changed: usize,
28 pub messages_changed: usize,
29 pub date_range_start: Option<NaiveDateTime>,
30 pub date_range_end: Option<NaiveDateTime>,
31}
32
33#[derive(Debug)]
34pub struct SimulationResult {
35 pub changes: Vec<SimulationChange>,
36 pub stats: SimulationStats,
37 pub operation_mode: String,
38}
39
40impl SimulationChange {
41 pub fn has_changes(&self) -> bool {
42 self.new_author.is_some()
43 || self.new_email.is_some()
44 || self.new_timestamp.is_some()
45 || self.new_message.is_some()
46 }
47
48 pub fn get_change_summary(&self) -> Vec<String> {
49 let mut changes = Vec::new();
50
51 if let Some(ref new_author) = self.new_author {
52 if new_author != &self.original_author {
53 changes.push(format!(
54 "Author: {} → {}",
55 crate::utils::sanitize::safe(&self.original_author).red(),
56 crate::utils::sanitize::safe(new_author).green()
57 ));
58 }
59 }
60
61 if let Some(ref new_email) = self.new_email {
62 if new_email != &self.original_email {
63 changes.push(format!(
64 "Email: {} → {}",
65 crate::utils::sanitize::safe(&self.original_email).red(),
66 crate::utils::sanitize::safe(new_email).green()
67 ));
68 }
69 }
70
71 if let Some(ref new_timestamp) = self.new_timestamp {
72 if new_timestamp != &self.original_timestamp {
73 changes.push(format!(
74 "Date: {} → {}",
75 self.original_timestamp
76 .format("%Y-%m-%d %H:%M:%S")
77 .to_string()
78 .red(),
79 new_timestamp
80 .format("%Y-%m-%d %H:%M:%S")
81 .to_string()
82 .green()
83 ));
84 }
85 }
86
87 if let Some(ref new_message) = self.new_message {
88 let original_first_line = self.original_message.lines().next().unwrap_or("");
89 let new_first_line = new_message.lines().next().unwrap_or("");
90 if new_first_line != original_first_line {
91 changes.push(format!(
92 "Message: {} → {}",
93 crate::utils::sanitize::safe(original_first_line).red(),
94 crate::utils::sanitize::safe(new_first_line).green()
95 ));
96 }
97 }
98
99 changes
100 }
101}
102
103impl SimulationStats {
104 pub fn new(commits: &[CommitInfo]) -> Self {
105 let total_commits = commits.len();
106 let (date_range_start, date_range_end) = if !commits.is_empty() {
107 let mut timestamps: Vec<_> = commits.iter().map(|c| c.timestamp).collect();
108 timestamps.sort();
109 (timestamps.first().copied(), timestamps.last().copied())
110 } else {
111 (None, None)
112 };
113
114 Self {
115 total_commits,
116 commits_to_change: 0,
117 authors_changed: 0,
118 emails_changed: 0,
119 timestamps_changed: 0,
120 messages_changed: 0,
121 date_range_start,
122 date_range_end,
123 }
124 }
125
126 pub fn update_from_changes(&mut self, changes: &[SimulationChange]) {
127 self.commits_to_change = changes.iter().filter(|c| c.has_changes()).count();
128
129 for change in changes {
130 if change.new_author.is_some() {
131 self.authors_changed += 1;
132 }
133 if change.new_email.is_some() {
134 self.emails_changed += 1;
135 }
136 if change.new_timestamp.is_some() {
137 self.timestamps_changed += 1;
138 }
139 if change.new_message.is_some() {
140 self.messages_changed += 1;
141 }
142 }
143 }
144
145 pub fn print_summary(&self, operation_mode: &str) {
146 crate::say!("\n{}", "📊 SIMULATION SUMMARY".bold().cyan());
147 crate::say!("{}", "=".repeat(50).cyan());
148
149 crate::say!("{}: {}", "Operation Mode".bold(), operation_mode.yellow());
150 crate::say!(
151 "{}: {}",
152 "Total Commits".bold(),
153 self.total_commits.to_string().cyan()
154 );
155 crate::say!(
156 "{}: {}",
157 "Commits to Change".bold(),
158 if self.commits_to_change > 0 {
159 self.commits_to_change.to_string().yellow()
160 } else {
161 self.commits_to_change.to_string().green()
162 }
163 );
164
165 if self.commits_to_change > 0 {
166 crate::say!("\n{}", "Changes Breakdown:".bold());
167 if self.authors_changed > 0 {
168 crate::say!(
169 " • {} commits will have author names changed",
170 self.authors_changed.to_string().yellow()
171 );
172 }
173 if self.emails_changed > 0 {
174 crate::say!(
175 " • {} commits will have author emails changed",
176 self.emails_changed.to_string().yellow()
177 );
178 }
179 if self.timestamps_changed > 0 {
180 crate::say!(
181 " • {} commits will have timestamps changed",
182 self.timestamps_changed.to_string().yellow()
183 );
184 }
185 if self.messages_changed > 0 {
186 crate::say!(
187 " • {} commits will have messages changed",
188 self.messages_changed.to_string().yellow()
189 );
190 }
191 }
192
193 if let (Some(start), Some(end)) = (self.date_range_start, self.date_range_end) {
194 crate::say!("\n{}", "Date Range:".bold());
195 crate::say!(
196 " {} → {}",
197 start.format("%Y-%m-%d %H:%M:%S").to_string().blue(),
198 end.format("%Y-%m-%d %H:%M:%S").to_string().blue()
199 );
200 }
201
202 if self.commits_to_change == 0 {
203 crate::say!(
204 "\n{}",
205 "✅ No changes would be made with current parameters."
206 .green()
207 .bold()
208 );
209 } else {
210 crate::say!(
211 "\n{}",
212 "⚠️ This is a simulation - no actual changes have been made."
213 .yellow()
214 .bold()
215 );
216 crate::say!(
217 "{}",
218 " Run without --simulate to apply these changes.".bright_black()
219 );
220 }
221 }
222}
223
224pub fn simulation_from_plan(
229 commits: &[CommitInfo],
230 plan: &Plan,
231 operation_mode: &str,
232) -> SimulationResult {
233 let changes: Vec<SimulationChange> = commits
234 .iter()
235 .map(|commit| {
236 let edit = plan.edits.get(&commit.oid).cloned().unwrap_or_default();
237 let new_author = edit.name.clone();
238 let new_email = edit.email.clone();
239 let new_timestamp = edit.time.map(|t| {
240 chrono::DateTime::from_timestamp(t.seconds, 0)
241 .unwrap_or_default()
242 .naive_utc()
243 });
244 let identity_changed = new_author.is_some() || new_email.is_some();
245 let base = edit
246 .message
247 .clone()
248 .unwrap_or_else(|| commit.message.clone());
249 let message = if identity_changed && commit.message_is_utf8 {
250 rewrite_author_trailers(
251 &base,
252 &commit.author_name,
253 &commit.author_email,
254 new_author.as_deref().unwrap_or(&commit.author_name),
255 new_email.as_deref().unwrap_or(&commit.author_email),
256 )
257 } else {
258 base
259 };
260 let new_message = (message != commit.message).then_some(message);
261
262 SimulationChange {
263 commit_oid: commit.oid,
264 short_hash: commit.short_hash.clone(),
265 original_author: commit.author_name.clone(),
266 original_email: commit.author_email.clone(),
267 original_timestamp: commit.timestamp,
268 original_message: commit.message.clone(),
269 new_author: new_author.filter(|n| *n != commit.author_name),
270 new_email: new_email.filter(|e| *e != commit.author_email),
271 new_timestamp: new_timestamp.filter(|t| *t != commit.timestamp),
272 new_message,
273 }
274 })
275 .collect();
276
277 let mut stats = SimulationStats::new(commits);
278 stats.update_from_changes(&changes);
279
280 SimulationResult {
281 changes,
282 stats,
283 operation_mode: operation_mode.to_string(),
284 }
285}
286
287pub fn report_simulation(result: &SimulationResult, show_diff: bool, final_result: bool) {
290 if final_result && crate::output::json_mode() {
291 crate::output::emit(&crate::output::simulation_json(result));
292 return;
293 }
294 result.stats.print_summary(&result.operation_mode);
295 if show_diff {
296 print_detailed_diff(result);
297 }
298}
299
300pub fn print_detailed_diff(result: &SimulationResult) {
301 crate::say!("\n{}", "📋 DETAILED CHANGE PREVIEW".bold().cyan());
302 crate::say!("{}", "=".repeat(70).cyan());
303
304 let changes_to_show: Vec<_> = result.changes.iter().filter(|c| c.has_changes()).collect();
305
306 if changes_to_show.is_empty() {
307 crate::say!("{}", "No changes to display.".green());
308 return;
309 }
310
311 for (i, change) in changes_to_show.iter().enumerate() {
312 crate::say!(
313 "\n{} {} {} ({})",
314 format!("{}.", i + 1).bold(),
315 "Commit".bold(),
316 change.short_hash.yellow().bold(),
317 change.commit_oid.to_string()[..16]
318 .to_string()
319 .bright_black()
320 );
321
322 let change_summary = change.get_change_summary();
323 for summary_line in change_summary {
324 crate::say!(" {summary_line}");
325 }
326
327 if i < changes_to_show.len() - 1 {
328 crate::say!("{}", "─".repeat(50).bright_black());
329 }
330 }
331
332 crate::say!(
333 "\n{}",
334 format!(
335 "Showing {} changes out of {} total commits",
336 changes_to_show.len(),
337 result.changes.len()
338 )
339 .bright_black()
340 );
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346 use crate::rewrite::engine::{CommitterMode, Edit, GitTime};
347 use chrono::NaiveDateTime;
348
349 fn create_test_commit(
350 oid_str: &str,
351 author: &str,
352 email: &str,
353 timestamp_str: &str,
354 message: &str,
355 ) -> CommitInfo {
356 CommitInfo {
357 oid: git2::Oid::from_str(oid_str).unwrap(),
358 short_hash: oid_str[..8].to_string(),
359 timestamp: NaiveDateTime::parse_from_str(timestamp_str, "%Y-%m-%d %H:%M:%S").unwrap(),
360 author_name: author.to_string(),
361 author_email: email.to_string(),
362 message: message.to_string(),
363 parent_count: 1,
364 ..Default::default()
365 }
366 }
367
368 #[test]
369 fn test_simulation_change_has_changes() {
370 let commit = create_test_commit(
371 "1234567890abcdef1234567890abcdef12345678",
372 "Test User",
373 "test@example.com",
374 "2023-01-01 10:00:00",
375 "Test commit",
376 );
377
378 let change = SimulationChange {
379 commit_oid: commit.oid,
380 short_hash: commit.short_hash,
381 original_author: commit.author_name,
382 original_email: commit.author_email,
383 original_timestamp: commit.timestamp,
384 original_message: commit.message,
385 new_author: Some("New Author".to_string()),
386 new_email: None,
387 new_timestamp: None,
388 new_message: None,
389 };
390
391 assert!(change.has_changes());
392 }
393
394 #[test]
395 fn test_simulation_change_no_changes() {
396 let commit = create_test_commit(
397 "1234567890abcdef1234567890abcdef12345678",
398 "Test User",
399 "test@example.com",
400 "2023-01-01 10:00:00",
401 "Test commit",
402 );
403
404 let change = SimulationChange {
405 commit_oid: commit.oid,
406 short_hash: commit.short_hash,
407 original_author: commit.author_name,
408 original_email: commit.author_email,
409 original_timestamp: commit.timestamp,
410 original_message: commit.message,
411 new_author: None,
412 new_email: None,
413 new_timestamp: None,
414 new_message: None,
415 };
416
417 assert!(!change.has_changes());
418 }
419
420 #[test]
421 fn test_simulation_stats_creation() {
422 let commits = vec![
423 create_test_commit(
424 "1234567890abcdef1234567890abcdef12345678",
425 "User1",
426 "user1@example.com",
427 "2023-01-01 10:00:00",
428 "First commit",
429 ),
430 create_test_commit(
431 "abcdef1234567890abcdef1234567890abcdef12",
432 "User2",
433 "user2@example.com",
434 "2023-01-02 15:30:00",
435 "Second commit",
436 ),
437 ];
438
439 let stats = SimulationStats::new(&commits);
440
441 assert_eq!(stats.total_commits, 2);
442 assert_eq!(stats.commits_to_change, 0);
443 assert!(stats.date_range_start.is_some());
444 assert!(stats.date_range_end.is_some());
445 }
446
447 #[test]
448 fn test_simulation_from_plan_matches_edits_by_commit_id() {
449 let newest = create_test_commit(
451 "2222222222222222222222222222222222222222",
452 "Old User",
453 "old@example.com",
454 "2023-01-02 10:00:00",
455 "Second commit",
456 );
457 let oldest = create_test_commit(
458 "1111111111111111111111111111111111111111",
459 "Old User",
460 "old@example.com",
461 "2023-01-01 10:00:00",
462 "First commit",
463 );
464 let early =
465 NaiveDateTime::parse_from_str("2023-06-01 09:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
466 let late =
467 NaiveDateTime::parse_from_str("2023-06-02 09:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
468 let edit = |t: NaiveDateTime| Edit {
469 name: Some("New User".into()),
470 email: Some("new@example.com".into()),
471 time: Some(GitTime::new(t.and_utc().timestamp(), 0)),
472 message: None,
473 };
474 let plan = Plan {
475 edits: [(oldest.oid, edit(early)), (newest.oid, edit(late))]
476 .into_iter()
477 .collect(),
478 committer: CommitterMode::MatchAuthor,
479 };
480
481 let result = simulation_from_plan(&[newest, oldest], &plan, "Full History Rewrite");
482
483 assert_eq!(result.stats.commits_to_change, 2);
484 assert_eq!(result.changes[0].new_timestamp, Some(late));
485 assert_eq!(result.changes[1].new_timestamp, Some(early));
486 assert_eq!(result.changes[1].new_author.as_deref(), Some("New User"));
487 }
488
489 #[test]
490 fn test_simulation_from_plan_ignores_unchanged_values() {
491 let commit = create_test_commit(
492 "1111111111111111111111111111111111111111",
493 "Same User",
494 "same@example.com",
495 "2023-01-01 10:00:00",
496 "msg",
497 );
498 let plan = Plan {
499 edits: [(
500 commit.oid,
501 Edit {
502 name: Some("Same User".into()),
503 email: Some("same@example.com".into()),
504 ..Default::default()
505 },
506 )]
507 .into_iter()
508 .collect(),
509 committer: CommitterMode::MatchAuthor,
510 };
511 let result = simulation_from_plan(&[commit], &plan, "x");
512 assert_eq!(result.stats.commits_to_change, 0);
513 }
514}