Skip to main content

git_editor/rewrite/
rewrite_range.rs

1use crate::rewrite::engine::{self, Edit, GitTime, Plan};
2use crate::rewrite::report::print_outcome;
3use crate::rewrite::rewrite_all::begin_offset;
4use crate::utils::dates::{format_git_time, parse_git_time, parse_utc};
5use crate::utils::datetime::spread_timestamps;
6use crate::utils::prompt::read_prompted_line;
7use crate::utils::prompt::{cancelled, confirm};
8use crate::utils::simulation::{report_simulation, simulation_from_plan};
9use crate::utils::types::CommitInfo;
10use crate::utils::types::Result;
11use crate::utils::validator::{is_valid_email, validate_identity_part};
12use crate::{args::Args, utils::commit_history::get_commit_history};
13use chrono::NaiveDateTime;
14use colored::Colorize;
15use crossterm::{
16    cursor,
17    event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
18    terminal::{self, Clear, ClearType},
19    ExecutableCommand,
20};
21use git2::Repository;
22use std::io::{self, Write};
23
24#[derive(Debug, Clone)]
25struct CommitEdit {
26    index: usize,
27    original: CommitInfo,
28    author_name: String,
29    author_email: String,
30    /// Author date as UTC; `offset_minutes` is the zone it is written in.
31    timestamp: NaiveDateTime,
32    offset_minutes: i32,
33    message: String,
34    is_modified: bool,
35    modifications: ModificationFlags,
36}
37
38#[derive(Debug, Clone, Default)]
39struct ModificationFlags {
40    author_name_changed: bool,
41    author_email_changed: bool,
42    timestamp_changed: bool,
43    message_changed: bool,
44}
45
46/// What the table loop should do after a key press.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48enum TableAction {
49    Continue,
50    SaveAndExit,
51    Cancel,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq)]
55enum TableColumn {
56    Index = 0,
57    Hash = 1,
58    AuthorName = 2,
59    AuthorEmail = 3,
60    Timestamp = 4,
61    Message = 5,
62}
63
64/// Draws the table on the alternate screen and restores the terminal (raw mode
65/// off, original screen back) when dropped — on success, error or panic.
66struct TerminalGuard;
67
68impl TerminalGuard {
69    fn enter() -> Result<Self> {
70        io::stdout().execute(terminal::EnterAlternateScreen)?;
71        Ok(Self)
72    }
73}
74
75impl Drop for TerminalGuard {
76    fn drop(&mut self) {
77        let _ = terminal::disable_raw_mode();
78        let _ = io::stdout().execute(terminal::LeaveAlternateScreen);
79        let _ = io::stdout().execute(cursor::Show);
80    }
81}
82
83struct InteractiveTable {
84    commits: Vec<CommitEdit>,
85    current_row: usize,
86    current_col: TableColumn,
87    editing: bool,
88    edit_buffer: String,
89    /// Last validation error, shown below the table (never stored in a field).
90    status: Option<String>,
91    editable_fields: (bool, bool, bool, bool), // (author_name, author_email, timestamp, message)
92}
93
94impl InteractiveTable {
95    fn new(
96        commits: Vec<CommitInfo>,
97        start_idx: usize,
98        end_idx: usize,
99        editable_fields: (bool, bool, bool, bool),
100    ) -> Self {
101        let mut commit_edits = Vec::new();
102
103        for (i, commit) in commits[start_idx..=end_idx].iter().enumerate() {
104            commit_edits.push(CommitEdit {
105                index: start_idx + i,
106                original: commit.clone(),
107                author_name: commit.author_name.clone(),
108                author_email: commit.author_email.clone(),
109                timestamp: commit.timestamp,
110                offset_minutes: commit.author_offset_min,
111                message: commit.message.clone(), // Keep full message, truncate only for display
112                is_modified: false,
113                modifications: ModificationFlags::default(),
114            });
115        }
116
117        // Find the first editable column as starting position
118        let starting_col = if editable_fields.0 {
119            // author_name
120            TableColumn::AuthorName
121        } else if editable_fields.1 {
122            // author_email
123            TableColumn::AuthorEmail
124        } else if editable_fields.2 {
125            // timestamp
126            TableColumn::Timestamp
127        } else if editable_fields.3 {
128            // message
129            TableColumn::Message
130        } else {
131            TableColumn::AuthorName // fallback
132        };
133
134        Self {
135            commits: commit_edits,
136            current_row: 0,
137            current_col: starting_col,
138            editing: false,
139            edit_buffer: String::new(),
140            status: None,
141            editable_fields,
142        }
143    }
144
145    fn draw_table(&self) {
146        // Clear screen using crossterm
147        let _ = io::stdout().execute(Clear(ClearType::All));
148        let _ = io::stdout().execute(cursor::MoveTo(0, 0));
149
150        crate::say!(
151            "{}",
152            "Interactive Commit Editor - Range Mode".bold().green()
153        );
154
155        // Show which fields are editable
156        let editable_info = if self.editable_fields == (true, true, true, true) {
157            "All fields editable".to_string()
158        } else {
159            let mut editable = Vec::new();
160            if self.editable_fields.0 || self.editable_fields.1 {
161                editable.push("Author");
162            }
163            if self.editable_fields.2 {
164                editable.push("Time");
165            }
166            if self.editable_fields.3 {
167                editable.push("Message");
168            }
169            format!("Editable: {}", editable.join(", "))
170        };
171        crate::say!("{}", editable_info.cyan());
172        crate::say!(
173            "{}",
174            "Arrow keys/hjkl: move  Enter: edit  Esc: save & exit  q or Ctrl+C: cancel without saving"
175                .yellow()
176        );
177        crate::say!();
178
179        // Print header
180        crate::say!(
181            "{:<4} {:<8} {:<15} {:<20} {:<19} {}",
182            "#".bold().white(),
183            "HASH".bold().white(),
184            "AUTHOR NAME".bold().white(),
185            "AUTHOR EMAIL".bold().white(),
186            "TIMESTAMP (UTC)".bold().white(),
187            "MESSAGE".bold().white()
188        );
189
190        // Draw only the rows that fit on screen, keeping the cursor row visible.
191        let screen_rows = terminal::size().map(|(_, h)| h as usize).unwrap_or(24);
192        let (first, count) = viewport(
193            self.current_row,
194            self.commits.len(),
195            screen_rows.saturating_sub(TABLE_CHROME_LINES),
196        );
197        for (row_idx, commit) in self.commits.iter().enumerate().skip(first).take(count) {
198            let is_current_row = row_idx == self.current_row;
199
200            // Prepare content
201            let index_str = format!("{}", commit.index + 1);
202            let hash_str = self.truncate_text(&commit.original.short_hash, 8);
203            let author_name_str = self.truncate_text(&commit.author_name, 15);
204            let author_email_str = self.truncate_text(&commit.author_email, 20);
205            let timestamp_str = commit.timestamp.format("%Y-%m-%d %H:%M:%S").to_string();
206            let first_line_message = commit.message.lines().next().unwrap_or("");
207            let message_str = self.truncate_text(first_line_message, 40);
208
209            // Add modification indicators and current cell brackets
210            let is_current_cell_index =
211                is_current_row && matches!(self.current_col, TableColumn::Index);
212            let is_current_cell_hash =
213                is_current_row && matches!(self.current_col, TableColumn::Hash);
214            let is_current_cell_author_name =
215                is_current_row && matches!(self.current_col, TableColumn::AuthorName);
216            let is_current_cell_author_email =
217                is_current_row && matches!(self.current_col, TableColumn::AuthorEmail);
218            let is_current_cell_timestamp =
219                is_current_row && matches!(self.current_col, TableColumn::Timestamp);
220            let is_current_cell_message =
221                is_current_row && matches!(self.current_col, TableColumn::Message);
222
223            let index_final = index_str; // Index is never editable, so no brackets
224            let hash_final = hash_str; // Hash is never editable, so no brackets
225
226            let author_name_with_mod = if commit.modifications.author_name_changed {
227                format!("*{author_name_str}")
228            } else {
229                author_name_str
230            };
231            let author_name_final = author_name_with_mod;
232
233            let author_email_with_mod = if commit.modifications.author_email_changed {
234                format!("*{author_email_str}")
235            } else {
236                author_email_str
237            };
238            let author_email_final = author_email_with_mod;
239
240            let timestamp_with_mod = if commit.modifications.timestamp_changed {
241                format!("*{timestamp_str}")
242            } else {
243                timestamp_str
244            };
245            let timestamp_final = timestamp_with_mod;
246
247            let message_with_mod = if commit.modifications.message_changed {
248                format!("*{message_str}")
249            } else {
250                message_str
251            };
252            let message_final = message_with_mod;
253
254            // Apply formatting and colors
255            if is_current_row {
256                if self.editing {
257                    crate::say!(
258                        "{:<4} {:<8} {:<15} {:<20} {:<19} {}",
259                        index_final.black().on_yellow(),
260                        hash_final.black().on_yellow(),
261                        author_name_final.black().on_yellow(),
262                        author_email_final.black().on_yellow(),
263                        timestamp_final.black().on_yellow(),
264                        message_final.black().on_yellow()
265                    );
266                } else {
267                    // Current row, not editing - highlight current cell with special background
268                    let index_styled = if is_current_cell_index {
269                        index_final.white().on_blue()
270                    } else {
271                        index_final.white().on_bright_black()
272                    };
273                    let hash_styled = if is_current_cell_hash {
274                        hash_final.white().on_blue()
275                    } else {
276                        hash_final.yellow().on_bright_black()
277                    };
278                    let author_name_styled =
279                        if is_current_cell_author_name && self.editable_fields.0 {
280                            author_name_final.white().on_blue()
281                        } else {
282                            author_name_final.cyan().on_bright_black()
283                        };
284                    let author_email_styled =
285                        if is_current_cell_author_email && self.editable_fields.1 {
286                            author_email_final.white().on_blue()
287                        } else {
288                            author_email_final.blue().on_bright_black()
289                        };
290                    let timestamp_styled = if is_current_cell_timestamp && self.editable_fields.2 {
291                        timestamp_final.white().on_blue()
292                    } else {
293                        timestamp_final.magenta().on_bright_black()
294                    };
295                    let message_styled = if is_current_cell_message && self.editable_fields.3 {
296                        message_final.white().on_blue()
297                    } else {
298                        message_final.green().on_bright_black()
299                    };
300
301                    crate::say!(
302                        "{index_styled:<4} {hash_styled:<8} {author_name_styled:<15} {author_email_styled:<20} {timestamp_styled:<19} {message_styled}"
303                    );
304                }
305            } else {
306                crate::say!(
307                    "{:<4} {:<8} {:<15} {:<20} {:<19} {}",
308                    index_final.white(),
309                    hash_final.yellow(),
310                    author_name_final.cyan(),
311                    author_email_final.blue(),
312                    timestamp_final.magenta(),
313                    message_final.green()
314                );
315            }
316        }
317
318        if count < self.commits.len() {
319            crate::say!(
320                "{}",
321                format!(
322                    "Rows {}-{} of {} (scroll with ↑↓)",
323                    first + 1,
324                    first + count,
325                    self.commits.len()
326                )
327                .dimmed()
328            );
329        }
330        crate::say!();
331
332        if let Some(status) = &self.status {
333            crate::say!("{} {}", "Error:".red().bold(), status.red());
334        }
335        if self.editing {
336            crate::say!("{}: {}", "Editing".bold().yellow(), self.edit_buffer);
337            crate::say!(
338                "{}",
339                "Press Enter to save, Esc to cancel this edit, Ctrl+C to abandon all edits"
340                    .italic()
341            );
342        } else {
343            crate::say!(
344                "{}",
345                "Navigation: ←→↑↓  Edit: Enter  Save & Exit: Esc  Cancel: q / Ctrl+C".italic()
346            );
347            crate::say!(
348                "{}",
349                "Tip: Use '*' when selecting range to edit ALL commits at once".dimmed()
350            );
351        }
352    }
353
354    fn truncate_text(&self, text: &str, max_width: usize) -> String {
355        truncate_chars(text, max_width)
356    }
357
358    fn handle_navigation_key_input(&mut self, key: KeyCode) -> TableAction {
359        match key {
360            KeyCode::Up if self.current_row > 0 => {
361                self.current_row -= 1;
362            }
363            KeyCode::Down if self.current_row < self.commits.len() - 1 => {
364                self.current_row += 1;
365            }
366            KeyCode::Left => {
367                self.move_to_prev_editable_column();
368            }
369            KeyCode::Right => {
370                self.move_to_next_editable_column();
371            }
372            KeyCode::Char('h') => {
373                // Left (vim-style)
374                self.move_to_prev_editable_column();
375            }
376            KeyCode::Char('l') => {
377                // Right (vim-style)
378                self.move_to_next_editable_column();
379            }
380            KeyCode::Char('k') if self.current_row > 0 => {
381                // Up (vim-style)
382                self.current_row -= 1;
383            }
384            KeyCode::Char('j') if self.current_row < self.commits.len() - 1 => {
385                // Down (vim-style)
386                self.current_row += 1;
387            }
388            KeyCode::Enter => self.start_editing(),
389            KeyCode::Esc => return TableAction::SaveAndExit,
390            KeyCode::Char('q') => return TableAction::Cancel,
391            _ => {}
392        }
393        TableAction::Continue
394    }
395
396    fn is_column_editable(&self, col: &TableColumn) -> bool {
397        match col {
398            TableColumn::Index | TableColumn::Hash => false,
399            TableColumn::AuthorName => self.editable_fields.0,
400            TableColumn::AuthorEmail => self.editable_fields.1,
401            TableColumn::Timestamp => self.editable_fields.2,
402            TableColumn::Message => self.editable_fields.3,
403        }
404    }
405
406    fn move_to_next_editable_column(&mut self) {
407        let columns = [
408            TableColumn::Index,
409            TableColumn::Hash,
410            TableColumn::AuthorName,
411            TableColumn::AuthorEmail,
412            TableColumn::Timestamp,
413            TableColumn::Message,
414        ];
415
416        let current_index = columns
417            .iter()
418            .position(|c| std::mem::discriminant(c) == std::mem::discriminant(&self.current_col))
419            .unwrap_or(0);
420
421        for i in 1..columns.len() {
422            let next_index = (current_index + i) % columns.len();
423            let next_col = &columns[next_index];
424            if self.is_column_editable(next_col) {
425                self.current_col = *next_col;
426                return;
427            }
428        }
429    }
430
431    fn move_to_prev_editable_column(&mut self) {
432        let columns = [
433            TableColumn::Index,
434            TableColumn::Hash,
435            TableColumn::AuthorName,
436            TableColumn::AuthorEmail,
437            TableColumn::Timestamp,
438            TableColumn::Message,
439        ];
440
441        let current_index = columns
442            .iter()
443            .position(|c| std::mem::discriminant(c) == std::mem::discriminant(&self.current_col))
444            .unwrap_or(0);
445
446        for i in 1..columns.len() {
447            let prev_index = if current_index >= i {
448                current_index - i
449            } else {
450                columns.len() - (i - current_index)
451            };
452            let prev_col = &columns[prev_index];
453            if self.is_column_editable(prev_col) {
454                self.current_col = *prev_col;
455                return;
456            }
457        }
458    }
459
460    fn start_editing(&mut self) {
461        if !self.is_column_editable(&self.current_col) {
462            return; // This column is not editable
463        }
464
465        self.editing = true;
466
467        // Initialize edit buffer with current value
468        self.edit_buffer = match self.current_col {
469            TableColumn::AuthorName => self.commits[self.current_row].author_name.clone(),
470            TableColumn::AuthorEmail => self.commits[self.current_row].author_email.clone(),
471            TableColumn::Timestamp => {
472                let commit = &self.commits[self.current_row];
473                format_git_time(GitTime::new(
474                    commit.timestamp.and_utc().timestamp(),
475                    commit.offset_minutes,
476                ))
477            }
478            TableColumn::Message => {
479                // Use the full original message when editing, not the truncated display version
480                if self.commits[self.current_row].modifications.message_changed {
481                    self.commits[self.current_row].message.clone()
482                } else {
483                    // Get the full original message from the first line or full message
484                    self.commits[self.current_row].original.message.clone()
485                }
486            }
487            _ => String::new(),
488        };
489    }
490
491    fn handle_edit_key_input(&mut self, key: KeyCode) -> TableAction {
492        if key != KeyCode::Enter {
493            self.status = None;
494        }
495        match key {
496            KeyCode::Esc => {
497                // Esc - cancel edit
498                self.editing = false;
499                self.edit_buffer.clear();
500            }
501            KeyCode::Enter => {
502                // Enter - save edit
503                if let Err(e) = self.save_current_edit() {
504                    // Keep the user's input and stay in edit mode; show the error separately.
505                    self.status = Some(format!(
506                        "{e} (fix the value or press Esc to cancel the edit)"
507                    ));
508                    return TableAction::Continue;
509                }
510                self.status = None;
511                self.editing = false;
512                self.edit_buffer.clear();
513            }
514            KeyCode::Backspace => {
515                self.edit_buffer.pop();
516            }
517            KeyCode::Char(c) => {
518                // Handle printable characters
519                self.edit_buffer.push(c);
520            }
521            _ => {}
522        }
523        TableAction::Continue
524    }
525
526    /// Route one key press; Ctrl+C always abandons the session.
527    fn handle_key(&mut self, key: KeyEvent) -> TableAction {
528        if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
529            return TableAction::Cancel;
530        }
531        if self.editing {
532            self.handle_edit_key_input(key.code)
533        } else {
534            self.handle_navigation_key_input(key.code)
535        }
536    }
537
538    fn save_current_edit(&mut self) -> Result<()> {
539        let commit = &mut self.commits[self.current_row];
540
541        match self.current_col {
542            TableColumn::AuthorName => {
543                crate::utils::validator::validate_identity_part(&self.edit_buffer, "Author name")?;
544                if commit.author_name != self.edit_buffer {
545                    commit.author_name = self.edit_buffer.clone();
546                    commit.modifications.author_name_changed =
547                        commit.original.author_name != commit.author_name;
548                }
549            }
550            TableColumn::AuthorEmail => {
551                if self.edit_buffer.trim().is_empty() {
552                    return Err("Author email cannot be empty".into());
553                }
554                if !crate::utils::validator::is_valid_email(&self.edit_buffer) {
555                    return Err("Invalid email format".into());
556                }
557                if commit.author_email != self.edit_buffer {
558                    commit.author_email = self.edit_buffer.clone();
559                    commit.modifications.author_email_changed =
560                        commit.original.author_email != commit.author_email;
561                }
562            }
563            TableColumn::Timestamp => {
564                let time = parse_git_time(&self.edit_buffer)?;
565                commit.timestamp = parse_utc(&self.edit_buffer)?;
566                commit.offset_minutes = time.offset_minutes;
567                commit.modifications.timestamp_changed = commit.original.timestamp
568                    != commit.timestamp
569                    || commit.original.author_offset_min != commit.offset_minutes;
570            }
571            TableColumn::Message => {
572                if self.edit_buffer.trim().is_empty() {
573                    return Err("Commit message cannot be empty".into());
574                }
575                if commit.message != self.edit_buffer {
576                    commit.message = self.edit_buffer.clone();
577                    commit.modifications.message_changed =
578                        commit.original.message != commit.message;
579                }
580            }
581            _ => {}
582        }
583        // A value edited back to the original no longer counts as a change.
584        let m = &commit.modifications;
585        commit.is_modified = m.author_name_changed
586            || m.author_email_changed
587            || m.timestamp_changed
588            || m.message_changed;
589        Ok(())
590    }
591
592    fn run(&mut self) -> Result<bool> {
593        let _terminal = TerminalGuard::enter()?;
594        loop {
595            // Disable raw mode for drawing the table
596            let _ = terminal::disable_raw_mode();
597            self.draw_table();
598
599            // Enable raw mode only for reading input
600            terminal::enable_raw_mode()?;
601
602            if let Event::Key(key) = event::read()? {
603                if key.kind != KeyEventKind::Press {
604                    continue;
605                }
606                match self.handle_key(key) {
607                    TableAction::Continue => {}
608                    TableAction::SaveAndExit => break Ok(true),
609                    TableAction::Cancel => break Ok(false),
610                }
611            }
612        }
613    }
614
615    fn get_modified_commits(&self) -> Vec<&CommitEdit> {
616        self.commits.iter().filter(|c| c.is_modified).collect()
617    }
618}
619
620/// Lines used by the table header, footer and help text.
621const TABLE_CHROME_LINES: usize = 12;
622
623/// First visible row and number of rows for a window of `height` rows that keeps `current` visible.
624fn viewport(current: usize, total: usize, height: usize) -> (usize, usize) {
625    let height = height.max(3).min(total);
626    let first = current.saturating_sub(height / 2).min(total - height);
627    (first, height)
628}
629
630/// Shorten `text` to at most `max_width` characters (never splitting a UTF-8 char).
631fn truncate_chars(text: &str, max_width: usize) -> String {
632    let text = &*crate::utils::sanitize::safe(text);
633    if text.chars().count() > max_width {
634        let kept: String = text.chars().take(max_width.saturating_sub(1)).collect();
635        format!("{kept}…")
636    } else {
637        text.to_string()
638    }
639}
640
641pub fn parse_range_input(input: &str, total_commits: usize) -> Result<(usize, usize)> {
642    let trimmed_input = input.trim();
643
644    // Check if user entered '*' to select all commits
645    if trimmed_input == "*" {
646        if total_commits == 0 {
647            return Err("No commits available to select".into());
648        }
649        return Ok((1, total_commits)); // Return 1-based indexing for all commits
650    }
651
652    let parts: Vec<&str> = trimmed_input.split('-').collect();
653
654    if parts.len() != 2 {
655        return Err("Invalid range format. Use format like '5-11' or '*' for all commits".into());
656    }
657
658    let start = parts[0]
659        .trim()
660        .parse::<usize>()
661        .map_err(|_| "Invalid start number in range")?;
662    let end = parts[1]
663        .trim()
664        .parse::<usize>()
665        .map_err(|_| "Invalid end number in range")?;
666
667    if start < 1 {
668        return Err("Start position must be 1 or greater".into());
669    }
670
671    if end < start {
672        return Err("End position must be greater than or equal to start position".into());
673    }
674
675    Ok((start, end))
676}
677
678pub fn select_commit_range(commits: &[CommitInfo]) -> Result<(usize, usize)> {
679    crate::say!("\n{}", "Commit History:".bold().green());
680    crate::say!("{}", "-".repeat(80).cyan());
681
682    for (i, commit) in commits.iter().enumerate() {
683        crate::say!(
684            "{:3}. {} {} {} {}",
685            i + 1,
686            commit.short_hash.yellow().bold(),
687            commit
688                .timestamp
689                .format("%Y-%m-%d %H:%M:%S")
690                .to_string()
691                .blue(),
692            crate::utils::sanitize::safe(&commit.author_name).magenta(),
693            crate::utils::sanitize::safe(commit.message.lines().next().unwrap_or("")).white()
694        );
695    }
696
697    crate::say!("{}", "-".repeat(80).cyan());
698    crate::say!(
699        "\n{}",
700        "Enter range in format 'start-end' (e.g., '5-11') or '*' for all commits:"
701            .bold()
702            .green()
703    );
704    crate::say_inline!("{} {} ", "Range:".bold(), "(Esc to cancel)".bright_black());
705    io::stdout().flush()?;
706
707    let input = read_prompted_line()?;
708    parse_selection(&input, commits.len())
709}
710
711/// Parse `N-M`, `N` or `*` (1-based, 1 = newest) into 0-based inclusive indices.
712pub fn parse_selection(input: &str, total_commits: usize) -> Result<(usize, usize)> {
713    let input = input.trim();
714    let (start, end) = match input.parse::<usize>() {
715        Ok(single) => (single, single),
716        Err(_) => parse_range_input(input, total_commits)?,
717    };
718    if start < 1 || end > total_commits {
719        return Err(format!("Range out of bounds. Available commits: 1-{total_commits}").into());
720    }
721    Ok((start - 1, end - 1))
722}
723
724pub fn show_range_details(commits: &[CommitInfo], start_idx: usize, end_idx: usize) -> Result<()> {
725    let total_selected = end_idx - start_idx + 1;
726    let is_all_commits = total_selected == commits.len();
727
728    if is_all_commits {
729        crate::say!("\n{}", "Selected All Commits for Editing:".bold().green());
730    } else {
731        crate::say!("\n{}", "Selected Commit Range:".bold().green());
732    }
733    crate::say!("{}", "=".repeat(80).cyan());
734
735    for (idx, commit) in commits[start_idx..=end_idx].iter().enumerate() {
736        crate::say!(
737            "\n{}: {} ({})",
738            format!("Commit {}", start_idx + idx + 1).bold(),
739            commit.short_hash.yellow(),
740            &commit.oid.to_string()[..8]
741        );
742        crate::say!(
743            "{}: {}",
744            "Author".bold(),
745            format!("{} <{}>", commit.author_name, commit.author_email).magenta()
746        );
747        crate::say!(
748            "{}: {}",
749            "Date".bold(),
750            commit
751                .timestamp
752                .format("%Y-%m-%d %H:%M:%S")
753                .to_string()
754                .blue()
755        );
756        crate::say!(
757            "{}: {}",
758            "Message".bold(),
759            crate::utils::sanitize::safe(commit.message.lines().next().unwrap_or("")).white()
760        );
761    }
762
763    crate::say!("\n{}", "=".repeat(80).cyan());
764    if is_all_commits {
765        crate::say!(
766            "{} {} commits selected for editing {}",
767            "Total:".bold(),
768            total_selected.to_string().green(),
769            "(ALL COMMITS)".bold().yellow()
770        );
771    } else {
772        crate::say!(
773            "{} {} commits selected for editing",
774            "Total:".bold(),
775            total_selected.to_string().green()
776        );
777    }
778
779    Ok(())
780}
781
782pub fn rewrite_range_commits(args: &Args) -> Result<()> {
783    let commits = get_commit_history(args, false)?;
784
785    if commits.is_empty() {
786        crate::say!("{}", "No commits found!".red());
787        return Ok(());
788    }
789    // Fail early on a detached/unborn HEAD and remember the tip the edits are based on.
790    let head = engine::current_branch(&Repository::open(args.repo_path.as_ref().unwrap())?)?.head;
791
792    if let Some(selection) = &args.select {
793        return rewrite_selection_from_flags(args, &commits, selection, head);
794    }
795
796    let (start_idx, end_idx) = select_commit_range(&commits)?;
797
798    // Show range details for user feedback
799    show_range_details(&commits, start_idx, end_idx)?;
800
801    // Get editable fields based on command line flags
802    let editable_fields = args.get_editable_fields();
803
804    // Launch interactive table editor
805    let mut table = InteractiveTable::new(commits.clone(), start_idx, end_idx, editable_fields);
806    let should_save = table.run()?;
807
808    if !should_save {
809        return Err(cancelled());
810    }
811
812    let modified_commits = table.get_modified_commits();
813
814    if modified_commits.is_empty() {
815        crate::say!("{}", "No changes made.".yellow());
816        return Ok(());
817    }
818
819    // Show summary of changes
820    crate::say!("\n{}", "Summary of Changes:".bold().green());
821    crate::say!("{}", "=".repeat(80).cyan());
822
823    for commit_edit in &modified_commits {
824        crate::say!(
825            "\n{}: {} ({})",
826            format!("Commit {}", commit_edit.index + 1).bold(),
827            commit_edit.original.short_hash.yellow(),
828            &commit_edit.original.oid.to_string()[..8]
829        );
830
831        if commit_edit.modifications.author_name_changed {
832            crate::say!(
833                "  {}: {} -> {}",
834                "Author Name".bold(),
835                crate::utils::sanitize::safe(&commit_edit.original.author_name).red(),
836                crate::utils::sanitize::safe(&commit_edit.author_name).green()
837            );
838        }
839
840        if commit_edit.modifications.author_email_changed {
841            crate::say!(
842                "  {}: {} -> {}",
843                "Author Email".bold(),
844                crate::utils::sanitize::safe(&commit_edit.original.author_email).red(),
845                crate::utils::sanitize::safe(&commit_edit.author_email).green()
846            );
847        }
848
849        if commit_edit.modifications.timestamp_changed {
850            crate::say!(
851                "  {}: {} -> {}",
852                "Timestamp".bold(),
853                commit_edit
854                    .original
855                    .timestamp
856                    .format("%Y-%m-%d %H:%M:%S")
857                    .to_string()
858                    .red(),
859                commit_edit
860                    .timestamp
861                    .format("%Y-%m-%d %H:%M:%S")
862                    .to_string()
863                    .green()
864            );
865        }
866
867        if commit_edit.modifications.message_changed {
868            let original_first_line = commit_edit.original.message.lines().next().unwrap_or("");
869            let new_first_line = commit_edit.message.lines().next().unwrap_or("");
870            crate::say!(
871                "  {}: {} -> {}",
872                "Message".bold(),
873                crate::utils::sanitize::safe(original_first_line).red(),
874                crate::utils::sanitize::safe(new_first_line).green()
875            );
876        }
877    }
878
879    if args.simulate {
880        let plan = plan_from_table(&table.commits, args.committer.into());
881        let preview = simulation_from_plan(&commits, &plan, "Range Edit");
882        report_simulation(&preview, args.show_diff, true);
883        crate::say!("{}", "Simulation only: nothing was written.".cyan());
884        return Ok(());
885    }
886
887    if !confirm(&format!("\n{}", "Apply these changes?".bold()), args.yes)? {
888        return Err(cancelled());
889    }
890
891    // Apply changes
892    apply_interactive_range_changes(args, &table.commits, head)?;
893
894    if args.show_history {
895        get_commit_history(args, true)?;
896    }
897
898    Ok(())
899}
900
901/// Non-interactive range edit: `--select` with `--name/--email/--begin/--end`.
902fn rewrite_selection_from_flags(
903    args: &Args,
904    commits: &[CommitInfo],
905    selection: &str,
906    expected_head: git2::Oid,
907) -> Result<()> {
908    let (first, last) = parse_selection(selection, commits.len())?;
909    // Selected commits, oldest first.
910    let selected: Vec<&CommitInfo> = commits[first..=last].iter().rev().collect();
911
912    if let Some(name) = &args.name {
913        validate_identity_part(name, "Author name")?;
914    }
915    if let Some(email) = &args.email {
916        if !is_valid_email(email) {
917            return Err(format!("Invalid email format: {email}").into());
918        }
919    }
920    let times: Option<Vec<GitTime>> = match (&args.start, &args.end) {
921        (Some(begin), Some(end)) => {
922            let spread = spread_timestamps(
923                parse_utc(begin)?,
924                parse_utc(end)?,
925                selected.len(),
926                args.skip_range_check,
927            )?;
928            let offset = begin_offset(args);
929            Some(
930                spread
931                    .iter()
932                    .map(|t| GitTime::new(t.and_utc().timestamp(), offset))
933                    .collect(),
934            )
935        }
936        (None, None) => None,
937        _ => return Err("--begin and --end must be given together".into()),
938    };
939    if args.name.is_none() && args.email.is_none() && times.is_none() {
940        return Err(
941            "Nothing to change: pass --name, --email and/or --begin/--end with --select".into(),
942        );
943    }
944    if let Some(times) = &times {
945        warn_if_out_of_order(commits, first, last, times);
946    }
947
948    let edits = selected
949        .iter()
950        .enumerate()
951        .map(|(i, commit)| {
952            let edit = Edit {
953                name: args.name.clone(),
954                email: args.email.clone(),
955                time: times.as_ref().map(|t| t[i]),
956                message: None,
957            };
958            (commit.oid, edit)
959        })
960        .collect();
961    let plan = Plan {
962        edits,
963        committer: args.committer.into(),
964    };
965
966    let preview = simulation_from_plan(commits, &plan, "Range Edit");
967    report_simulation(&preview, args.show_diff, args.simulate);
968    if args.simulate {
969        crate::say!("{}", "Simulation only: nothing was written.".cyan());
970        return Ok(());
971    }
972    if !confirm(&format!("\n{}", "Apply these changes?".bold()), args.yes)? {
973        return Err(cancelled());
974    }
975    let repo = Repository::open(args.repo_path.as_ref().unwrap())?;
976    let outcome = engine::apply(&repo, &plan, expected_head)?;
977    print_outcome(&outcome);
978    Ok(())
979}
980
981/// Warn when new dates would put the selection before its parent or after its child.
982fn warn_if_out_of_order(commits: &[CommitInfo], first: usize, last: usize, times: &[GitTime]) {
983    let older_neighbor = commits
984        .get(last + 1)
985        .map(|c| c.timestamp.and_utc().timestamp());
986    let newer_neighbor = first
987        .checked_sub(1)
988        .map(|i| commits[i].timestamp.and_utc().timestamp());
989    let (Some(earliest), Some(latest)) = (times.first(), times.last()) else {
990        return;
991    };
992    if older_neighbor.is_some_and(|t| t > earliest.seconds)
993        || newer_neighbor.is_some_and(|t| t < latest.seconds)
994    {
995        crate::say!(
996            "{} the new dates are not in order with the commits around the selection",
997            "Warning:".yellow().bold()
998        );
999    }
1000}
1001
1002/// Plan for the commits edited in the table (keyed by id; untouched commits are absent).
1003fn plan_from_table(
1004    edited_commits: &[CommitEdit],
1005    committer: crate::rewrite::engine::CommitterMode,
1006) -> Plan {
1007    let edits = edited_commits
1008        .iter()
1009        .filter(|c| c.is_modified)
1010        .map(|c| {
1011            let m = &c.modifications;
1012            let edit = Edit {
1013                name: m.author_name_changed.then(|| c.author_name.clone()),
1014                email: m.author_email_changed.then(|| c.author_email.clone()),
1015                time: m
1016                    .timestamp_changed
1017                    .then(|| GitTime::new(c.timestamp.and_utc().timestamp(), c.offset_minutes)),
1018                message: m.message_changed.then(|| c.message.clone()),
1019            };
1020            (c.original.oid, edit)
1021        })
1022        .collect();
1023    Plan { edits, committer }
1024}
1025
1026/// Rewrite only the commits edited in the table; older commits keep their ids.
1027fn apply_interactive_range_changes(
1028    args: &Args,
1029    edited_commits: &[CommitEdit],
1030    expected_head: git2::Oid,
1031) -> Result<()> {
1032    let repo = Repository::open(args.repo_path.as_ref().unwrap())?;
1033    let plan = plan_from_table(edited_commits, args.committer.into());
1034    let outcome = engine::apply(&repo, &plan, expected_head)?;
1035    print_outcome(&outcome);
1036    Ok(())
1037}
1038
1039#[cfg(test)]
1040mod tests {
1041    use super::*;
1042    use std::fs;
1043    use tempfile::TempDir;
1044
1045    fn create_test_repo_with_commits() -> (TempDir, String) {
1046        let temp_dir = TempDir::new().unwrap();
1047        let repo_path = temp_dir.path().to_str().unwrap().to_string();
1048
1049        // Initialize git repo
1050        let repo = git2::Repository::init(&repo_path).unwrap();
1051
1052        // Create multiple commits
1053        for i in 1..=5 {
1054            let file_path = temp_dir.path().join(format!("test{i}.txt"));
1055            fs::write(&file_path, format!("test content {i}")).unwrap();
1056
1057            let mut index = repo.index().unwrap();
1058            index
1059                .add_path(std::path::Path::new(&format!("test{i}.txt")))
1060                .unwrap();
1061            index.write().unwrap();
1062
1063            let tree_id = index.write_tree().unwrap();
1064            let tree = repo.find_tree(tree_id).unwrap();
1065
1066            let sig = git2::Signature::new(
1067                "Test User",
1068                "test@example.com",
1069                &git2::Time::new(1234567890 + i as i64 * 3600, 0),
1070            )
1071            .unwrap();
1072
1073            let parents = if i == 1 {
1074                vec![]
1075            } else {
1076                let head = repo.head().unwrap();
1077                let parent_commit = head.peel_to_commit().unwrap();
1078                vec![parent_commit]
1079            };
1080
1081            repo.commit(
1082                Some("HEAD"),
1083                &sig,
1084                &sig,
1085                &format!("Commit {i}"),
1086                &tree,
1087                &parents.iter().collect::<Vec<_>>(),
1088            )
1089            .unwrap();
1090        }
1091
1092        (temp_dir, repo_path)
1093    }
1094
1095    fn table_with_one_commit() -> InteractiveTable {
1096        let commit = CommitInfo {
1097            author_name: "Old Author".into(),
1098            author_email: "old@example.com".into(),
1099            message: "msg\n".into(),
1100            ..Default::default()
1101        };
1102        InteractiveTable::new(vec![commit], 0, 0, (true, true, true, true))
1103    }
1104
1105    #[test]
1106    fn test_validation_error_is_not_saved_as_value() {
1107        let mut table = table_with_one_commit();
1108        table.current_col = TableColumn::AuthorName;
1109        table.start_editing();
1110        for _ in 0.."Old Author".len() {
1111            table.handle_edit_key_input(KeyCode::Backspace);
1112        }
1113        table.handle_edit_key_input(KeyCode::Enter);
1114        assert!(table.status.is_some());
1115        assert!(table.editing);
1116        assert_eq!(table.edit_buffer, "");
1117        table.handle_edit_key_input(KeyCode::Enter);
1118        assert_eq!(table.commits[0].author_name, "Old Author");
1119        assert!(!table.commits[0].is_modified);
1120    }
1121
1122    #[test]
1123    fn test_ctrl_c_and_q_cancel_esc_saves() {
1124        let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
1125        let mut table = table_with_one_commit();
1126        assert_eq!(table.handle_key(ctrl_c), TableAction::Cancel);
1127        table.start_editing();
1128        assert_eq!(table.handle_key(ctrl_c), TableAction::Cancel);
1129        assert!(!table.edit_buffer.ends_with('c'));
1130
1131        let mut table = table_with_one_commit();
1132        let q = KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE);
1133        assert_eq!(table.handle_key(q), TableAction::Cancel);
1134        let esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
1135        assert_eq!(table.handle_key(esc), TableAction::SaveAndExit);
1136    }
1137
1138    #[test]
1139    fn test_reverted_edit_is_not_a_change() {
1140        let mut table = table_with_one_commit();
1141        table.current_col = TableColumn::AuthorName;
1142        table.start_editing();
1143        table.edit_buffer = "Someone Else".into();
1144        table.handle_edit_key_input(KeyCode::Enter);
1145        assert!(table.commits[0].is_modified);
1146        table.start_editing();
1147        table.edit_buffer = "Old Author".into();
1148        table.handle_edit_key_input(KeyCode::Enter);
1149        assert!(!table.commits[0].is_modified);
1150        assert!(table.get_modified_commits().is_empty());
1151    }
1152
1153    #[test]
1154    fn test_viewport_keeps_current_row_visible() {
1155        assert_eq!(viewport(0, 5, 20), (0, 5));
1156        assert_eq!(viewport(0, 100, 10), (0, 10));
1157        assert_eq!(viewport(50, 100, 10), (45, 10));
1158        assert_eq!(viewport(99, 100, 10), (90, 10));
1159        assert_eq!(viewport(1, 2, 0), (0, 2));
1160        for current in 0..100 {
1161            let (first, count) = viewport(current, 100, 7);
1162            assert!(first <= current && current < first + count);
1163        }
1164    }
1165
1166    #[test]
1167    fn test_truncate_chars_handles_multibyte_text() {
1168        assert_eq!(truncate_chars("张三李四王五", 5), "张三李四…");
1169        assert_eq!(truncate_chars("émoji 🎉 ok", 20), "émoji 🎉 ok");
1170        assert_eq!(truncate_chars("abcdef", 4), "abc…");
1171        assert_eq!(truncate_chars("", 3), "");
1172    }
1173
1174    #[test]
1175    fn test_parse_selection_bounds_and_forms() {
1176        assert_eq!(parse_selection("2-4", 5).unwrap(), (1, 3));
1177        assert_eq!(parse_selection("3", 5).unwrap(), (2, 2));
1178        assert_eq!(parse_selection("*", 5).unwrap(), (0, 4));
1179        assert!(parse_selection("4-9", 5).is_err());
1180        assert!(parse_selection("0", 5).is_err());
1181        assert!(parse_selection("3-2", 5).is_err());
1182    }
1183
1184    #[test]
1185    fn test_parse_range_input_valid() {
1186        let result = parse_range_input("5-11", 20);
1187        assert!(result.is_ok());
1188        let (start, end) = result.unwrap();
1189        assert_eq!(start, 5);
1190        assert_eq!(end, 11);
1191    }
1192
1193    #[test]
1194    fn test_parse_range_input_with_spaces() {
1195        let result = parse_range_input(" 3 - 8 ", 20);
1196        assert!(result.is_ok());
1197        let (start, end) = result.unwrap();
1198        assert_eq!(start, 3);
1199        assert_eq!(end, 8);
1200    }
1201
1202    #[test]
1203    fn test_parse_range_input_asterisk() {
1204        let result = parse_range_input("*", 10);
1205        assert!(result.is_ok());
1206        let (start, end) = result.unwrap();
1207        assert_eq!(start, 1);
1208        assert_eq!(end, 10);
1209
1210        // Test with empty repository
1211        let result = parse_range_input("*", 0);
1212        assert!(result.is_err());
1213    }
1214
1215    #[test]
1216    fn test_parse_range_input_invalid_format() {
1217        let result = parse_range_input("5", 20);
1218        assert!(result.is_err());
1219
1220        let result = parse_range_input("5-11-15", 20);
1221        assert!(result.is_err());
1222
1223        let result = parse_range_input("abc-def", 20);
1224        assert!(result.is_err());
1225    }
1226
1227    #[test]
1228    fn test_parse_range_input_invalid_range() {
1229        let result = parse_range_input("11-5", 20);
1230        assert!(result.is_err());
1231
1232        let result = parse_range_input("0-5", 20);
1233        assert!(result.is_err());
1234    }
1235
1236    #[test]
1237    fn test_apply_range_changes_correct_commit_ordering() {
1238        // This test verifies that editing commit at display index 0 (newest)
1239        // actually modifies the newest commit, not the oldest.
1240        let (_temp_dir, repo_path) = create_test_repo_with_commits();
1241        let args = Args {
1242            repo_path: Some(repo_path.clone()),
1243            range: true,
1244            ..Default::default()
1245        };
1246
1247        // get_commit_history returns newest-first
1248        let commits = get_commit_history(&args, false).unwrap();
1249        assert_eq!(commits.len(), 5);
1250        assert_eq!(commits[0].message, "Commit 5"); // newest
1251        assert_eq!(commits[4].message, "Commit 1"); // oldest
1252
1253        // Simulate editing only the newest commit (display index 0)
1254        let new_timestamp =
1255            NaiveDateTime::parse_from_str("2099-06-15 12:00:00", "%Y-%m-%d %H:%M:%S").unwrap();
1256
1257        let mut edited_commits: Vec<CommitEdit> = commits
1258            .iter()
1259            .enumerate()
1260            .map(|(i, c)| CommitEdit {
1261                index: i,
1262                original: c.clone(),
1263                author_name: c.author_name.clone(),
1264                author_email: c.author_email.clone(),
1265                timestamp: c.timestamp,
1266                offset_minutes: c.author_offset_min,
1267                message: c.message.clone(),
1268                is_modified: false,
1269                modifications: ModificationFlags::default(),
1270            })
1271            .collect();
1272
1273        // Mark only index 0 (newest = "Commit 5") as modified
1274        edited_commits[0].timestamp = new_timestamp;
1275        edited_commits[0].is_modified = true;
1276        edited_commits[0].modifications.timestamp_changed = true;
1277
1278        // Apply changes
1279        let original_ids: Vec<_> = commits.iter().map(|c| c.oid).collect();
1280        apply_interactive_range_changes(&args, &edited_commits, commits[0].oid).unwrap();
1281
1282        // Re-read and verify
1283        let updated_commits = get_commit_history(&args, false).unwrap();
1284        assert_eq!(updated_commits.len(), 5);
1285
1286        // The newest commit (index 0, "Commit 5") should have the new timestamp
1287        assert_eq!(
1288            updated_commits[0].timestamp, new_timestamp,
1289            "Newest commit should have the edited timestamp"
1290        );
1291
1292        // The oldest commit (index 4, "Commit 1") should NOT have the new timestamp
1293        assert_ne!(
1294            updated_commits[4].timestamp, new_timestamp,
1295            "Oldest commit should NOT have the edited timestamp"
1296        );
1297
1298        // All older commits are reused untouched: same ids, same timestamps.
1299        for (i, commit) in updated_commits.iter().enumerate().skip(1) {
1300            assert_eq!(commit.oid, original_ids[i], "commit {i} must keep its id");
1301            assert_eq!(commit.timestamp, commits[i].timestamp);
1302        }
1303    }
1304
1305    #[test]
1306    fn test_editing_middle_commit_keeps_older_commit_ids() {
1307        let (_temp_dir, repo_path) = create_test_repo_with_commits();
1308        let args = Args {
1309            repo_path: Some(repo_path.clone()),
1310            range: true,
1311            ..Default::default()
1312        };
1313        let commits = get_commit_history(&args, false).unwrap();
1314        let mut edits: Vec<CommitEdit> = commits
1315            .iter()
1316            .enumerate()
1317            .map(|(i, c)| CommitEdit {
1318                index: i,
1319                original: c.clone(),
1320                author_name: c.author_name.clone(),
1321                author_email: c.author_email.clone(),
1322                timestamp: c.timestamp,
1323                offset_minutes: c.author_offset_min,
1324                message: c.message.clone(),
1325                is_modified: false,
1326                modifications: ModificationFlags::default(),
1327            })
1328            .collect();
1329        // Display index 2 = "Commit 3"; commits 1 and 2 are older.
1330        edits[2].timestamp += chrono::Duration::hours(1);
1331        edits[2].is_modified = true;
1332        edits[2].modifications.timestamp_changed = true;
1333
1334        apply_interactive_range_changes(&args, &edits, commits[0].oid).unwrap();
1335
1336        let updated = get_commit_history(&args, false).unwrap();
1337        assert_eq!(updated[3].oid, commits[3].oid);
1338        assert_eq!(updated[4].oid, commits[4].oid);
1339        assert_ne!(updated[2].oid, commits[2].oid);
1340        assert_eq!(updated[2].timestamp, edits[2].timestamp);
1341        assert_eq!(updated[0].message, "Commit 5");
1342    }
1343}