Skip to main content

git_editor/
args.rs

1use clap::{Parser, ValueEnum};
2use colored::Colorize;
3use tempfile::TempDir;
4
5/// `--committer` policy, mapped onto the engine's [`CommitterMode`].
6#[derive(ValueEnum, Clone, Copy, Debug, Default, PartialEq, Eq)]
7pub enum CommitterArg {
8    #[default]
9    MatchAuthor,
10    Keep,
11}
12
13impl From<CommitterArg> for crate::rewrite::engine::CommitterMode {
14    fn from(arg: CommitterArg) -> Self {
15        match arg {
16            CommitterArg::MatchAuthor => Self::MatchAuthor,
17            CommitterArg::Keep => Self::Keep,
18        }
19    }
20}
21
22const AFTER_HELP: &str = "\
23Examples:
24  git-editor -s                                   Show history (numbers used by --commit/--select)
25  git-editor --simulate --name N --email e@x.io --begin '2024-01-01 09:00:00' --end '2024-02-01 18:00:00'
26  git-editor --name N --email e@x.io --keep-dates --yes        Rewrite identity, keep every date
27  git-editor -p --commit 3 --set-message 'Fix typo' --yes      Edit one commit without menus
28  git-editor -x --select 2-5 --name N --email e@x.io --yes     Edit a range without the table
29
30Agents and scripts:
31  1. git-editor -s --json                 inspect (JSON on stdout, progress on stderr)
32  2. git-editor <edit flags> --simulate --json    preview exactly what would change
33  3. git-editor <edit flags> --yes --json          apply; prints old/new ids and a backup ref
34  Undo: git reset --keep refs/git-editor/backup/<branch>
35
36Dates: 'YYYY-MM-DD HH:MM:SS' is UTC; add an offset ('... +05:30') or use RFC 3339.
37Exit codes: 0 success, 1 error, 2 invalid arguments, 130 cancelled.";
38
39#[derive(Parser, Default)]
40#[command(author, version, about, after_long_help = AFTER_HELP)]
41#[command(group(
42    clap::ArgGroup::new("mode")
43        .args(["show_history", "pick_specific_commits", "range", "docs"])
44        .multiple(false)
45))]
46pub struct Args {
47    #[arg(
48        short = 'r',
49        long = "repo-path",
50        help = "Repository path (any directory inside it) or clone URL; default: current directory"
51    )]
52    pub repo_path: Option<String>,
53
54    #[arg(
55        long,
56        help = "New author email (full rewrite, -p --commit, -x --select)"
57    )]
58    pub email: Option<String>,
59
60    #[arg(
61        short = 'n',
62        long = "name",
63        help = "New author name (full rewrite, -p --commit, -x --select)"
64    )]
65    pub name: Option<String>,
66
67    #[arg(
68        short = 'b',
69        long = "begin",
70        help = "First new date: YYYY-MM-DD HH:MM:SS (UTC) or with an offset like +05:30"
71    )]
72    pub start: Option<String>,
73
74    #[arg(
75        short = 'e',
76        long = "end",
77        help = "Last new date: YYYY-MM-DD HH:MM:SS (UTC) or with an offset like +05:30"
78    )]
79    pub end: Option<String>,
80
81    #[arg(
82        short = 's',
83        long = "show-history",
84        help = "Show commit history with statistics (read-only)"
85    )]
86    pub show_history: bool,
87
88    #[arg(
89        short = 'p',
90        long = "pick-specific-commits",
91        help = "Edit one commit (menu, or non-interactive with --commit)"
92    )]
93    pub pick_specific_commits: bool,
94
95    #[arg(
96        short = 'x',
97        long = "range",
98        help = "Edit a range of commits (table editor, or non-interactive with --select)"
99    )]
100    pub range: bool,
101
102    #[arg(
103        long = "simulate",
104        conflicts_with_all = ["show_history", "docs"],
105        help = "Preview the changes without writing anything (dry run)"
106    )]
107    pub simulate: bool,
108
109    #[arg(
110        long = "show-diff",
111        help = "Show the per-commit change list in previews (simulation and before confirming a rewrite)"
112    )]
113    pub show_diff: bool,
114
115    #[arg(
116        long = "message",
117        requires = "range",
118        help = "Edit only commit messages in range mode (-x)"
119    )]
120    pub edit_message: bool,
121
122    #[arg(
123        long = "author",
124        requires = "range",
125        help = "Edit only author name and email in range mode (-x)"
126    )]
127    pub edit_author: bool,
128
129    #[arg(
130        long = "time",
131        requires = "range",
132        help = "Edit only timestamps in range mode (-x)"
133    )]
134    pub edit_time: bool,
135
136    #[arg(
137        long = "skip-range-check",
138        help = "Allow date ranges shorter than 3 hours per commit (gaps shrink to 5 minutes, then evenly)"
139    )]
140    pub skip_range_check: bool,
141
142    #[arg(
143        long = "committer",
144        value_enum,
145        default_value_t = CommitterArg::MatchAuthor,
146        help = "Committer of rewritten commits: match-author (follow edited author fields) or keep (leave unchanged)"
147    )]
148    pub committer: CommitterArg,
149
150    #[arg(
151        long = "keep-dates",
152        help = "Full rewrite: change only author name/email and keep every commit's original date and time zone"
153    )]
154    pub keep_dates: bool,
155
156    #[arg(
157        long = "json",
158        help = "Print one JSON document on stdout (history, preview or rewrite result, or the error); progress goes to stderr"
159    )]
160    pub json: bool,
161
162    #[arg(
163        short = 'y',
164        long = "yes",
165        help = "Answer yes to the final confirmation (for scripts and agents)"
166    )]
167    pub yes: bool,
168
169    #[arg(
170        long = "select",
171        value_name = "RANGE",
172        requires = "range",
173        help = "With -x: commits to edit without the table, e.g. 2-5, 3 or * (1 = newest, as shown by -s)"
174    )]
175    pub select: Option<String>,
176
177    #[arg(
178        long = "commit",
179        value_name = "REF",
180        requires = "pick_specific_commits",
181        help = "With -p: commit to edit without the menu (hash prefix, or 1-based number from -s; 1 = newest)"
182    )]
183    pub commit: Option<String>,
184
185    #[arg(
186        long = "set-date",
187        value_name = "DATE",
188        requires = "pick_specific_commits",
189        help = "With -p --commit: new author date (YYYY-MM-DD HH:MM:SS [+HH:MM], default UTC)"
190    )]
191    pub set_date: Option<String>,
192
193    #[arg(
194        long = "set-message",
195        value_name = "TEXT",
196        requires = "pick_specific_commits",
197        help = "With -p --commit: new commit message"
198    )]
199    pub set_message: Option<String>,
200
201    #[arg(
202        long = "clone-dir",
203        value_name = "DIR",
204        help = "When --repo-path is a URL, clone into DIR and keep it (required for modes that rewrite history)"
205    )]
206    pub clone_dir: Option<String>,
207
208    #[arg(
209        long = "docs-out",
210        value_name = "PATH",
211        requires = "docs",
212        help = "With --docs: write the HTML documentation to PATH instead of a temporary file"
213    )]
214    pub docs_out: Option<String>,
215
216    #[arg(
217        long = "docs",
218        help = "Open comprehensive documentation in the browser"
219    )]
220    pub docs: bool,
221
222    #[clap(skip)]
223    pub _temp_dir: Option<TempDir>,
224}
225
226impl Args {
227    pub fn ensure_all_args_present(&mut self) -> crate::utils::types::Result<()> {
228        use crate::utils::git_clone::{
229            clone_repository, clone_repository_to, get_repo_name_from_url, is_git_url,
230        };
231        use crate::utils::git_config::{get_git_user_email, get_git_user_name};
232        use crate::utils::prompt::{prompt_for_missing_arg, prompt_with_default};
233
234        if self.repo_path.is_none() {
235            self.repo_path = Some(String::from("./"));
236        }
237
238        // Handle Git URL cloning (not needed for --docs).
239        let repo_path = self.repo_path.clone().unwrap_or_default();
240        if !self.docs && is_git_url(&repo_path) {
241            let read_only = self.show_history || self.simulate;
242            match self.clone_dir.clone() {
243                Some(dir) => {
244                    clone_repository_to(&repo_path, std::path::Path::new(&dir))?;
245                    self.repo_path = Some(dir);
246                }
247                None if read_only => {
248                    let temp_dir = clone_repository(&repo_path)?;
249                    self.repo_path = Some(temp_dir.path().to_string_lossy().to_string());
250                    // Keep the temporary directory alive for the duration of the program
251                    self._temp_dir = Some(temp_dir);
252                }
253                None => {
254                    return Err(format!(
255                        "Refusing to rewrite '{}': the clone would be deleted on exit and the rewrite lost.\n\
256                         Pass --clone-dir <DIR> to keep the rewritten clone (then push from it), or clone it yourself and pass the local path.",
257                        crate::utils::git_clone::redact_url(&repo_path)
258                    )
259                    .into());
260                }
261            }
262            crate::say!(
263                "{} {}",
264                "Repository:".bold(),
265                get_repo_name_from_url(&repo_path).yellow()
266            );
267        }
268
269        // Resolve a path inside a repository (or a bare repository) to the repository itself.
270        if let Some(path) = self.repo_path.clone() {
271            if std::path::Path::new(&path).exists() {
272                if let Ok(repo) = git2::Repository::discover(&path) {
273                    let root = repo.workdir().unwrap_or_else(|| repo.path());
274                    self.repo_path = Some(root.to_string_lossy().to_string());
275                }
276            }
277        }
278
279        // Skip prompting for email, name, start, and end if using show_history, pick_specific_commits, simulation, or docs modes
280        if self.show_history || self.pick_specific_commits || self.simulate || self.docs {
281            return Ok(());
282        }
283
284        // Range mode will prompt for its own parameters interactively
285        if self.range {
286            return Ok(());
287        }
288
289        if self.email.is_none() {
290            // Try to get email from git config first
291            if let Some(git_email) = get_git_user_email(self.repo_path.as_deref()) {
292                self.email = Some(prompt_with_default("Email", &git_email)?);
293            } else {
294                self.email = Some(prompt_for_missing_arg("email")?);
295            }
296        }
297
298        if self.name.is_none() {
299            // Try to get name from git config first
300            if let Some(git_name) = get_git_user_name(self.repo_path.as_deref()) {
301                self.name = Some(prompt_with_default("Name", &git_name)?);
302            } else {
303                self.name = Some(prompt_for_missing_arg("name")?);
304            }
305        }
306
307        if !self.keep_dates && (self.start.is_none() || self.end.is_none()) {
308            // Offer the repository's own date range as defaults; accepting both
309            // keeps every commit's original date (same as --keep-dates).
310            let date_range = self.get_repository_date_range()?;
311
312            match date_range {
313                Some((first, last)) => {
314                    let start = match self.start.clone() {
315                        Some(start) => start,
316                        None => prompt_with_default(
317                            "Start date (YYYY-MM-DD HH:MM:SS UTC, press Enter to keep original dates)",
318                            &first,
319                        )?,
320                    };
321                    let end = match self.end.clone() {
322                        Some(end) => end,
323                        None => prompt_with_default(
324                            "End date (YYYY-MM-DD HH:MM:SS UTC, press Enter to keep original dates)",
325                            &last,
326                        )?,
327                    };
328                    if self.start.is_none() && self.end.is_none() && start == first && end == last {
329                        self.keep_dates = true;
330                    } else {
331                        self.start = Some(start);
332                        self.end = Some(end);
333                    }
334                }
335                None => {
336                    if self.start.is_none() {
337                        self.start =
338                            Some(prompt_for_missing_arg("start date (YYYY-MM-DD HH:MM:SS)")?);
339                    }
340                    if self.end.is_none() {
341                        self.end = Some(prompt_for_missing_arg("end date (YYYY-MM-DD HH:MM:SS)")?);
342                    }
343                }
344            }
345        }
346
347        Ok(())
348    }
349
350    pub fn should_keep_original_timestamps(&self) -> bool {
351        self.keep_dates
352    }
353
354    fn get_repository_date_range(&self) -> crate::utils::types::Result<Option<(String, String)>> {
355        use crate::utils::commit_history::get_commit_history;
356
357        if let Some(repo_path) = &self.repo_path {
358            // Create a temporary Args instance for getting commit history
359            let temp_args = Args {
360                repo_path: Some(repo_path.clone()),
361                show_history: true, // Use show_history mode to avoid validation requirements
362                ..Default::default()
363            };
364
365            match get_commit_history(&temp_args, false) {
366                Ok(commits) => {
367                    if commits.is_empty() {
368                        return Ok(None);
369                    }
370
371                    // Get the date range from the first (newest) and last (oldest) commits
372                    let newest_commit = &commits[0];
373                    let oldest_commit = &commits[commits.len() - 1];
374
375                    // Format the dates as strings
376                    let start_date = oldest_commit
377                        .timestamp
378                        .format("%Y-%m-%d %H:%M:%S")
379                        .to_string();
380                    let end_date = newest_commit
381                        .timestamp
382                        .format("%Y-%m-%d %H:%M:%S")
383                        .to_string();
384
385                    Ok(Some((start_date, end_date)))
386                }
387                Err(e) => {
388                    eprintln!(
389                        "{} Could not read commit history for date defaults: {e}",
390                        "Warning:".yellow()
391                    );
392                    Ok(None)
393                }
394            }
395        } else {
396            Ok(None)
397        }
398    }
399
400    pub fn get_editable_fields(&self) -> (bool, bool, bool, bool) {
401        // (author_name, author_email, timestamp, message)
402        if self.range {
403            if self.edit_author || self.edit_time || self.edit_message {
404                // Selective editing - only edit specified fields
405                let edit_author = self.edit_author;
406                let edit_time = self.edit_time;
407                let edit_message = self.edit_message;
408                (edit_author, edit_author, edit_time, edit_message)
409            } else {
410                // Default: edit all fields when no specific flags are provided
411                (true, true, true, true)
412            }
413        } else {
414            // Not in range mode - this shouldn't be called
415            (false, false, false, false)
416        }
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423
424    #[test]
425    fn test_docs_mode_skips_validation() {
426        let mut args = Args {
427            repo_path: None, // This would normally cause validation to fail
428            docs: true,
429            ..Default::default()
430        };
431
432        // This should not fail even though repo_path is None, because docs mode skips validation
433        let result = args.ensure_all_args_present();
434        assert!(result.is_ok());
435    }
436
437    fn init_repo_with_commit(path: &std::path::Path) {
438        let repo = git2::Repository::init(path).unwrap();
439        let sig = git2::Signature::now("T", "t@example.com").unwrap();
440        let tree = repo
441            .find_tree(repo.index().unwrap().write_tree().unwrap())
442            .unwrap();
443        repo.commit(Some("HEAD"), &sig, &sig, "init", &tree, &[])
444            .unwrap();
445    }
446
447    #[test]
448    fn test_subdirectory_resolves_to_repository_root() {
449        let dir = tempfile::TempDir::new().unwrap();
450        init_repo_with_commit(dir.path());
451        let sub = dir.path().join("nested/deeper");
452        std::fs::create_dir_all(&sub).unwrap();
453        let mut args = Args {
454            repo_path: Some(sub.to_string_lossy().to_string()),
455            show_history: true,
456            ..Default::default()
457        };
458        args.ensure_all_args_present().unwrap();
459        let resolved = std::fs::canonicalize(args.repo_path.unwrap()).unwrap();
460        assert_eq!(resolved, std::fs::canonicalize(dir.path()).unwrap());
461    }
462
463    #[test]
464    fn test_bare_repository_is_accepted() {
465        let dir = tempfile::TempDir::new().unwrap();
466        init_repo_with_commit(&dir.path().join("src"));
467        let bare = dir.path().join("bare.git");
468        git2::build::RepoBuilder::new()
469            .bare(true)
470            .clone(dir.path().join("src").to_str().unwrap(), &bare)
471            .unwrap();
472        let mut args = Args {
473            repo_path: Some(bare.to_string_lossy().to_string()),
474            show_history: true,
475            ..Default::default()
476        };
477        args.ensure_all_args_present().unwrap();
478        assert!(crate::utils::validator::validate_inputs(&args).is_ok());
479    }
480}