Skip to main content

git_editor/rewrite/
rewrite_specific.rs

1use crate::rewrite::engine::{self, CommitterMode, Edit, Plan};
2use crate::rewrite::report::print_outcome;
3use crate::utils::dates::{format_git_time, parse_git_time};
4use crate::utils::prompt::{cancelled, confirm};
5use crate::utils::prompt::{read_prompted_line, read_prompted_line_raw};
6use crate::utils::simulation::{report_simulation, simulation_from_plan};
7use crate::utils::types::Result;
8use crate::utils::types::{CommitInfo, EditOptions};
9use crate::utils::validator::{is_valid_email, validate_identity_part};
10use crate::{args::Args, utils::commit_history::get_commit_history};
11use colored::Colorize;
12use git2::Repository;
13use std::io::{self, Write};
14
15pub fn select_commit(commits: &[CommitInfo]) -> Result<usize> {
16    crate::say!("\n{}", "Commit History:".bold().green());
17    crate::say!("{}", "-".repeat(80).cyan());
18
19    for (i, commit) in commits.iter().enumerate() {
20        crate::say!(
21            "{:3}. {} {} {} {}",
22            i + 1,
23            commit.short_hash.yellow().bold(),
24            commit
25                .timestamp
26                .format("%Y-%m-%d %H:%M:%S")
27                .to_string()
28                .blue(),
29            crate::utils::sanitize::safe(&commit.author_name).magenta(),
30            commit
31                .message
32                .lines()
33                .next()
34                .unwrap_or("(no message)")
35                .white()
36        );
37    }
38
39    crate::say!("{}", "-".repeat(80).cyan());
40    crate::say_inline!(
41        "\n{} {} ",
42        "Select commit number to edit:".bold().green(),
43        "(Esc to cancel)".bright_black()
44    );
45    io::stdout().flush()?;
46
47    let input = read_prompted_line()?;
48
49    let selection = input.parse::<usize>().map_err(|_| "Invalid number")?;
50
51    if selection < 1 || selection > commits.len() {
52        return Err("Selection out of range".into());
53    }
54
55    Ok(selection - 1)
56}
57
58pub fn show_commit_details(commit: &CommitInfo, repo: &Repository) -> Result<()> {
59    crate::say!("\n{}", "Selected Commit Details:".bold().green());
60    crate::say!("{}", "=".repeat(80).cyan());
61
62    crate::say!("{}: {}", "Hash".bold(), commit.oid.to_string().yellow());
63    crate::say!("{}: {}", "Short Hash".bold(), commit.short_hash.yellow());
64    crate::say!(
65        "{}: {}",
66        "Author".bold(),
67        format!("{} <{}>", commit.author_name, commit.author_email).magenta()
68    );
69    crate::say!(
70        "{}: {}",
71        "Date".bold(),
72        commit
73            .timestamp
74            .format("%Y-%m-%d %H:%M:%S")
75            .to_string()
76            .blue()
77    );
78    crate::say!(
79        "{}: {}",
80        "Parent Count".bold(),
81        commit.parent_count.to_string().white()
82    );
83
84    crate::say!("\n{}", "Message:".bold());
85    crate::say!("{}", commit.message.white());
86
87    // Show parent commits
88    if commit.parent_count > 0 {
89        let git_commit = repo.find_commit(commit.oid)?;
90        crate::say!("\n{}", "Parent Commits:".bold());
91        for (i, parent_id) in git_commit.parent_ids().enumerate() {
92            let parent = repo.find_commit(parent_id)?;
93            crate::say!(
94                "  {}: {} - {}",
95                i + 1,
96                parent_id.to_string()[..8].to_string().yellow(),
97                parent
98                    .summary()
99                    .ok()
100                    .flatten()
101                    .unwrap_or("(no message)")
102                    .white()
103            );
104        }
105    }
106
107    crate::say!("{}", "=".repeat(80).cyan());
108    Ok(())
109}
110
111/// Parse a comma-separated menu selection; `5` means "all of the above".
112fn parse_edit_selection(input: &str) -> Result<Vec<usize>> {
113    let mut selected = Vec::new();
114    for token in input.split(',').map(str::trim).filter(|t| !t.is_empty()) {
115        match token.parse::<usize>() {
116            Ok(5) => selected.extend(1..=4),
117            Ok(n @ 1..=4) => selected.push(n),
118            _ => return Err(format!("Invalid option '{token}' (choose 1-5)").into()),
119        }
120    }
121    selected.sort_unstable();
122    selected.dedup();
123    if selected.is_empty() {
124        return Err("No option selected; nothing to edit".into());
125    }
126    Ok(selected)
127}
128
129fn prompt_line(label: &str) -> Result<String> {
130    crate::say_inline!("{} {} ", label.bold(), "(Esc to cancel)".bright_black());
131    io::stdout().flush()?;
132    read_prompted_line()
133}
134
135/// Read a multi-line message; a line containing only `.` ends it.
136fn prompt_message() -> Result<String> {
137    crate::say!(
138        "{} {} ",
139        "New commit message (finish with a line containing only '.'):".bold(),
140        "(Esc to cancel)".bright_black()
141    );
142    let mut lines = Vec::new();
143    loop {
144        let line = read_prompted_line_raw()?;
145        if line.trim() == "." {
146            break;
147        }
148        lines.push(line);
149    }
150    build_message(&lines)
151}
152
153/// Join entered lines into a message, dropping leading/trailing blank lines.
154fn build_message(lines: &[String]) -> Result<String> {
155    let start = lines.iter().position(|l| !l.trim().is_empty());
156    let end = lines.iter().rposition(|l| !l.trim().is_empty());
157    match (start, end) {
158        (Some(start), Some(end)) => Ok(lines[start..=end].join("\n") + "\n"),
159        _ => Err("Commit message cannot be empty".into()),
160    }
161}
162
163// Get user input for what to change
164pub fn get_edit_options() -> Result<EditOptions> {
165    crate::say!("\n{}", "What would you like to edit?".bold().green());
166    crate::say!("1. Author name");
167    crate::say!("2. Author email");
168    crate::say!("3. Commit timestamp");
169    crate::say!("4. Commit message");
170    crate::say!("5. All of the above");
171
172    let selections = parse_edit_selection(&prompt_line("Select option(s) (comma-separated):")?)?;
173    let mut options = EditOptions::default();
174
175    for selection in selections {
176        match selection {
177            1 => {
178                let name = prompt_line("New author name:")?;
179                validate_identity_part(&name, "Author name")?;
180                options.author_name = Some(name);
181            }
182            2 => {
183                let email = prompt_line("New author email:")?;
184                if !is_valid_email(&email) {
185                    return Err(format!("Invalid email format: {email}").into());
186                }
187                options.author_email = Some(email);
188            }
189            3 => {
190                let timestamp =
191                    prompt_line("New timestamp (YYYY-MM-DD HH:MM:SS [+HH:MM], default UTC):")?;
192                options.timestamp = Some(parse_git_time(&timestamp)?);
193            }
194            4 => options.message = Some(prompt_message()?),
195            _ => unreachable!("parse_edit_selection only returns 1-4"),
196        }
197    }
198
199    Ok(options)
200}
201
202/// Find a commit by unique hash prefix (4+ hex digits) or by 1-based list
203/// number (1 = newest, as shown by `-s`). A hash prefix wins when both match.
204fn resolve_commit<'a>(commits: &'a [CommitInfo], reference: &str) -> Result<&'a CommitInfo> {
205    let reference = reference.trim().to_ascii_lowercase();
206    if reference.len() >= 4 && reference.chars().all(|c| c.is_ascii_hexdigit()) {
207        let mut matches = commits
208            .iter()
209            .filter(|c| c.oid.to_string().starts_with(&reference));
210        match (matches.next(), matches.next()) {
211            (Some(commit), None) => return Ok(commit),
212            (Some(_), Some(_)) => {
213                return Err(format!("--commit '{reference}' matches several commits").into())
214            }
215            (None, _) => {}
216        }
217    }
218    match reference.parse::<usize>() {
219        Ok(number) if (1..=commits.len()).contains(&number) => Ok(&commits[number - 1]),
220        _ => Err(format!(
221            "--commit '{reference}' matches no commit hash and is not a number between 1 and {}",
222            commits.len()
223        )
224        .into()),
225    }
226}
227
228/// Edits requested with --name/--email/--set-date/--set-message.
229fn edit_options_from_args(args: &Args) -> Result<EditOptions> {
230    if let Some(name) = &args.name {
231        validate_identity_part(name, "Author name")?;
232    }
233    if let Some(email) = &args.email {
234        if !is_valid_email(email) {
235            return Err(format!("Invalid email format: {email}").into());
236        }
237    }
238    let options = EditOptions {
239        author_name: args.name.clone(),
240        author_email: args.email.clone(),
241        timestamp: args.set_date.as_deref().map(parse_git_time).transpose()?,
242        message: args.set_message.clone(),
243    };
244    if options.author_name.is_none()
245        && options.author_email.is_none()
246        && options.timestamp.is_none()
247        && options.message.is_none()
248    {
249        return Err("Nothing to change: pass --name, --email, --set-date and/or --set-message with --commit".into());
250    }
251    if options
252        .message
253        .as_deref()
254        .is_some_and(|m| m.trim().is_empty())
255    {
256        return Err("Commit message cannot be empty".into());
257    }
258    Ok(options)
259}
260
261pub fn rewrite_specific_commits(args: &Args) -> Result<()> {
262    let commits = get_commit_history(args, false)?;
263
264    if commits.is_empty() {
265        crate::say!("{}", "No commits found!".red());
266        return Ok(());
267    }
268
269    let repo = Repository::open(args.repo_path.as_ref().unwrap())?;
270    // Fail early on a detached/unborn HEAD and remember the tip the edit is based on.
271    let head = engine::current_branch(&repo)?.head;
272
273    let (selected_commit, edit_options) = match &args.commit {
274        // Flag-driven (non-interactive) edit.
275        Some(reference) => (
276            resolve_commit(&commits, reference)?,
277            edit_options_from_args(args)?,
278        ),
279        None => {
280            let selected = &commits[select_commit(&commits)?];
281            show_commit_details(selected, &repo)?;
282            (selected, get_edit_options()?)
283        }
284    };
285
286    // Confirm changes
287    crate::say!("\n{}", "Planned changes:".bold().yellow());
288    if let Some(ref name) = edit_options.author_name {
289        crate::say!(
290            "  Author name: {} -> {}",
291            crate::utils::sanitize::safe(&selected_commit.author_name).red(),
292            name.green()
293        );
294    }
295    if let Some(ref email) = edit_options.author_email {
296        crate::say!(
297            "  Author email: {} -> {}",
298            crate::utils::sanitize::safe(&selected_commit.author_email).red(),
299            email.green()
300        );
301    }
302    if let Some(ref timestamp) = edit_options.timestamp {
303        crate::say!(
304            "  Timestamp: {} -> {}",
305            selected_commit
306                .timestamp
307                .format("%Y-%m-%d %H:%M:%S")
308                .to_string()
309                .red(),
310            format_git_time(*timestamp).green()
311        );
312    }
313    if let Some(ref message) = edit_options.message {
314        crate::say!(
315            "  Message: {} -> {}",
316            crate::utils::sanitize::safe(selected_commit.message.lines().next().unwrap_or(""))
317                .red(),
318            crate::utils::sanitize::safe(message.lines().next().unwrap_or("")).green()
319        );
320    }
321
322    if args.simulate {
323        let plan = Plan {
324            edits: [(selected_commit.oid, edit_from_options(&edit_options))]
325                .into_iter()
326                .collect(),
327            committer: args.committer.into(),
328        };
329        let preview = simulation_from_plan(&commits, &plan, "Specific Commit Edit");
330        report_simulation(&preview, args.show_diff, true);
331        crate::say!("{}", "Simulation only: nothing was written.".cyan());
332        return Ok(());
333    }
334
335    if !confirm(&format!("\n{}", "Proceed with changes?".bold()), args.yes)? {
336        return Err(cancelled());
337    }
338
339    // Apply changes
340    apply_commit_changes(
341        &repo,
342        selected_commit,
343        &edit_options,
344        head,
345        args.committer.into(),
346    )?;
347
348    if args.show_history {
349        get_commit_history(args, true)?;
350    }
351
352    Ok(())
353}
354
355fn edit_from_options(options: &EditOptions) -> Edit {
356    Edit {
357        name: options.author_name.clone(),
358        email: options.author_email.clone(),
359        time: options.timestamp,
360        message: options.message.clone(),
361    }
362}
363
364/// Rewrite only the selected commit (descendants are re-parented, ancestors reused).
365fn apply_commit_changes(
366    repo: &Repository,
367    target_commit: &CommitInfo,
368    options: &EditOptions,
369    expected_head: git2::Oid,
370    committer: CommitterMode,
371) -> Result<()> {
372    let plan = Plan {
373        edits: [(target_commit.oid, edit_from_options(options))]
374            .into_iter()
375            .collect(),
376        committer,
377    };
378    let outcome = engine::apply(repo, &plan, expected_head)?;
379    print_outcome(&outcome);
380    Ok(())
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use std::fs;
387    use tempfile::TempDir;
388
389    fn create_test_repo_with_commits() -> (TempDir, String) {
390        let temp_dir = TempDir::new().unwrap();
391        let repo_path = temp_dir.path().to_str().unwrap().to_string();
392
393        // Initialize git repo
394        let repo = git2::Repository::init(&repo_path).unwrap();
395
396        // Create multiple commits
397        for i in 1..=3 {
398            let file_path = temp_dir.path().join(format!("test{i}.txt"));
399            fs::write(&file_path, format!("test content {i}")).unwrap();
400
401            let mut index = repo.index().unwrap();
402            index
403                .add_path(std::path::Path::new(&format!("test{i}.txt")))
404                .unwrap();
405            index.write().unwrap();
406
407            let tree_id = index.write_tree().unwrap();
408            let tree = repo.find_tree(tree_id).unwrap();
409
410            let sig = git2::Signature::new(
411                "Test User",
412                "test@example.com",
413                &git2::Time::new(1234567890 + i as i64 * 3600, 0),
414            )
415            .unwrap();
416
417            let parents = if i == 1 {
418                vec![]
419            } else {
420                let head = repo.head().unwrap();
421                let parent_commit = head.peel_to_commit().unwrap();
422                vec![parent_commit]
423            };
424
425            repo.commit(
426                Some("HEAD"),
427                &sig,
428                &sig,
429                &format!("Commit {i}"),
430                &tree,
431                &parents.iter().collect::<Vec<_>>(),
432            )
433            .unwrap();
434        }
435
436        (temp_dir, repo_path)
437    }
438
439    #[test]
440    fn test_show_commit_details() {
441        let (_temp_dir, repo_path) = create_test_repo_with_commits();
442        let repo = Repository::open(&repo_path).unwrap();
443
444        // Get commit info
445        let args = Args {
446            repo_path: Some(repo_path),
447            ..Default::default()
448        };
449
450        let commits = get_commit_history(&args, false).unwrap();
451        let commit = &commits[0];
452
453        // Test that show_commit_details doesn't crash
454        let result = show_commit_details(commit, &repo);
455        assert!(result.is_ok());
456    }
457
458    #[test]
459    fn test_build_message_keeps_body_structure() {
460        let lines: Vec<String> = ["", "subject", "", "  indented body", ""]
461            .iter()
462            .map(|s| s.to_string())
463            .collect();
464        assert_eq!(
465            build_message(&lines).unwrap(),
466            "subject\n\n  indented body\n"
467        );
468        assert!(build_message(&["  ".to_string()]).is_err());
469    }
470
471    #[test]
472    fn test_resolve_commit_by_number_and_prefix() {
473        let make = |hex: &str| CommitInfo {
474            oid: git2::Oid::from_str(hex).unwrap(),
475            ..Default::default()
476        };
477        let commits = vec![
478            make("abcdef0000000000000000000000000000000000"),
479            make("abcd120000000000000000000000000000000000"),
480            make("1234560000000000000000000000000000000000"),
481        ];
482        assert_eq!(resolve_commit(&commits, "1").unwrap().oid, commits[0].oid);
483        assert_eq!(resolve_commit(&commits, "3").unwrap().oid, commits[2].oid);
484        assert_eq!(
485            resolve_commit(&commits, "1234").unwrap().oid,
486            commits[2].oid
487        );
488        assert_eq!(
489            resolve_commit(&commits, "ABCDEF").unwrap().oid,
490            commits[0].oid
491        );
492        assert!(resolve_commit(&commits, "abcd").is_err()); // ambiguous
493        assert!(resolve_commit(&commits, "4").is_err());
494        assert!(resolve_commit(&commits, "ffff").is_err());
495    }
496
497    #[test]
498    fn test_edit_options_from_args_requires_a_change() {
499        let args = Args {
500            pick_specific_commits: true,
501            commit: Some("1".into()),
502            ..Default::default()
503        };
504        assert!(edit_options_from_args(&args).is_err());
505        let args = Args {
506            email: Some("not-an-email".into()),
507            ..args
508        };
509        assert!(edit_options_from_args(&args).is_err());
510    }
511
512    #[test]
513    fn test_parse_edit_selection() {
514        assert_eq!(parse_edit_selection("1").unwrap(), vec![1]);
515        assert_eq!(parse_edit_selection(" 3, 1 ,3").unwrap(), vec![1, 3]);
516        assert_eq!(parse_edit_selection("5").unwrap(), vec![1, 2, 3, 4]);
517        assert!(parse_edit_selection("9").is_err());
518        assert!(parse_edit_selection("1,x").is_err());
519        assert!(parse_edit_selection("").is_err());
520    }
521}