g-cli 0.1.0

Git that talks back. A human-friendly CLI wrapper for Git.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use colored::Colorize;
use dialoguer::{Confirm, Select};

use crate::git;

// ---------------------------------------------------------------------------
// Action detection — parse reflog into structured action types
// ---------------------------------------------------------------------------

#[derive(Debug)]
enum Action {
    Commit { message: String, is_amend: bool, is_merge: bool, is_initial: bool },
    Pull,
    Merge { branch: String },
    Checkout { from: String, to: String },
    Rebase,
    CherryPick,
    Reset,
    StashApply,
    Other { description: String },
}

fn detect_action(reflog_entry: &str) -> Action {
    let e = reflog_entry.trim();

    if let Some(rest) = e.strip_prefix("commit (amend): ") {
        return Action::Commit { message: rest.to_string(), is_amend: true, is_merge: false, is_initial: false };
    }
    if let Some(rest) = e.strip_prefix("commit (merge): ") {
        return Action::Commit { message: rest.to_string(), is_amend: false, is_merge: true, is_initial: false };
    }
    if let Some(rest) = e.strip_prefix("commit (initial): ") {
        return Action::Commit { message: rest.to_string(), is_amend: false, is_merge: false, is_initial: true };
    }
    if let Some(rest) = e.strip_prefix("commit: ") {
        return Action::Commit { message: rest.to_string(), is_amend: false, is_merge: false, is_initial: false };
    }
    if e.starts_with("pull") {
        return Action::Pull;
    }
    if let Some(rest) = e.strip_prefix("merge ") {
        return Action::Merge { branch: rest.to_string() };
    }
    if e.starts_with("checkout: moving from") {
        let parts: Vec<&str> = e.splitn(2, " to ").collect();
        let from = e
            .strip_prefix("checkout: moving from ")
            .unwrap_or("")
            .split(" to ")
            .next()
            .unwrap_or("?")
            .to_string();
        let to = parts.get(1).unwrap_or(&"?").to_string();
        return Action::Checkout { from, to };
    }
    if e.starts_with("rebase") {
        return Action::Rebase;
    }
    if e.starts_with("cherry-pick") {
        return Action::CherryPick;
    }
    if e.starts_with("reset") {
        return Action::Reset;
    }
    if e.contains("stash") {
        return Action::StashApply;
    }

    Action::Other { description: e.to_string() }
}

fn action_icon(action: &Action) -> &str {
    match action {
        Action::Commit { is_amend: true, .. } => "✏️",
        Action::Commit { is_merge: true, .. } => "🔀",
        Action::Commit { is_initial: true, .. } => "🌱",
        Action::Commit { .. } => "💾",
        Action::Pull => "⬇️",
        Action::Merge { .. } => "🔀",
        Action::Checkout { .. } => "🔄",
        Action::Rebase => "📐",
        Action::CherryPick => "🍒",
        Action::Reset => "",
        Action::StashApply => "📦",
        Action::Other { .. } => "",
    }
}

fn action_description(action: &Action) -> String {
    match action {
        Action::Commit { message, is_amend: true, .. } =>
            format!("Amended commit: \"{}\"", message),
        Action::Commit { message, is_merge: true, .. } =>
            format!("Merge commit: \"{}\"", message),
        Action::Commit { message, is_initial: true, .. } =>
            format!("Initial commit: \"{}\"", message),
        Action::Commit { message, .. } =>
            format!("Commit: \"{}\"", message),
        Action::Pull =>
            "Pulled from remote".to_string(),
        Action::Merge { branch } =>
            format!("Merged branch '{}'", branch),
        Action::Checkout { from, to } =>
            format!("Switched from '{}' to '{}'", from, to),
        Action::Rebase =>
            "Rebased branch".to_string(),
        Action::CherryPick =>
            "Cherry-picked a commit".to_string(),
        Action::Reset =>
            "Reset branch".to_string(),
        Action::StashApply =>
            "Applied stash".to_string(),
        Action::Other { description } =>
            description.clone(),
    }
}

// ---------------------------------------------------------------------------
// Entry points
// ---------------------------------------------------------------------------

pub fn run(list: bool) {
    if list {
        run_list();
    } else {
        run_undo();
    }
}

// ---------------------------------------------------------------------------
// g undo --list  — interactive undo timeline
// ---------------------------------------------------------------------------

fn run_list() {
    let entries = git::reflog_entries(20);
    if entries.is_empty() {
        println!();
        println!("  {} No actions found in history.", "".yellow());
        println!();
        return;
    }

    println!();
    println!("  {}:", "Undo timeline".bold());
    println!("  {}", "Pick any action to rewind to the state before it.".dimmed());
    println!();

    let mut items: Vec<(String, String, Action)> = vec![];
    for (hash, desc, time) in &entries {
        let action = detect_action(desc);
        items.push((hash.clone(), time.clone(), action));
    }

    let display: Vec<String> = items
        .iter()
        .map(|(_, time, action)| {
            format!(
                "  {} {} {}",
                action_icon(action),
                action_description(action),
                format!("({})", time).dimmed()
            )
        })
        .collect();

    let refs: Vec<&str> = display.iter().map(|s| s.as_str()).collect();

    let selection = Select::new()
        .with_prompt("  Rewind to before which action?")
        .items(&refs)
        .default(0)
        .interact();

    let selection = match selection {
        Ok(s) => s,
        Err(_) => {
            println!("  Cancelled.");
            println!();
            return;
        }
    };

    let (_, _, action) = &items[selection];
    let reflog_target = format!("HEAD@{{{}}}", selection);

    println!();

    // Show preview of what will change
    show_rewind_preview(&reflog_target);

    // Confirm
    let confirm = Confirm::new()
        .with_prompt(format!(
            "  {} Rewind to before: {}?",
            "".yellow(),
            action_description(action).bold()
        ))
        .default(false)
        .interact();

    match confirm {
        Ok(true) => {}
        _ => {
            println!("  Cancelled.");
            println!();
            return;
        }
    }

    println!();
    let result = git::run(&["reset", "--hard", &reflog_target]);
    if result.success {
        println!("  {} Rewound successfully.", "".green().bold());
        println!("  You're now at the state before that action.");
    } else {
        println!("  {} Failed: {}", "".red(), result.stderr);
    }
    println!();
}

// ---------------------------------------------------------------------------
// g undo  — smart single-action undo
// ---------------------------------------------------------------------------

fn run_undo() {
    println!();

    // First: check for staged changes — offer to unstage
    let files = git::parse_status();
    let staged: Vec<&git::FileStatus> = files.iter().filter(|f| f.staged).collect();
    if !staged.is_empty() {
        println!("  {}:", "Staged changes detected".yellow().bold());
        for f in &staged {
            println!("    {} {}", f.kind.icon().green(), f.path);
        }
        println!();

        let options = &[
            "Unstage all files (keep changes in working directory)",
            "Continue to undo last action instead",
            "Cancel",
        ];

        let selection = Select::new()
            .with_prompt("  What would you like to undo?")
            .items(options)
            .default(0)
            .interact();

        match selection {
            Ok(0) => {
                let result = git::run(&["reset", "HEAD"]);
                if result.success {
                    println!();
                    println!("  {} Unstaged {} file(s).", "".green().bold(), staged.len());
                    println!("  Your changes are still in your working directory.");
                } else {
                    println!("  {} Failed: {}", "".red(), result.stderr);
                }
                println!();
                return;
            }
            Ok(1) => {
                // Fall through to normal undo
            }
            _ => {
                println!("  Cancelled.");
                println!();
                return;
            }
        }
        println!();
    }

    // Detect last action from reflog
    let action_str = git::last_action_type();
    if action_str.is_none() {
        println!("  {} No recent actions found to undo.", "".yellow());
        println!();
        return;
    }

    let action = detect_action(action_str.as_deref().unwrap());

    println!("  {} Last action detected:", "".to_string());
    println!(
        "    {} {}",
        action_icon(&action),
        action_description(&action).bold()
    );
    println!();

    match action {
        Action::Commit { ref message, is_amend, is_merge, is_initial } => {
            undo_commit(message, is_amend, is_merge, is_initial);
        }
        Action::Pull | Action::Merge { .. } => {
            undo_merge_or_pull(&action);
        }
        Action::Checkout { ref from, ref to } => {
            undo_checkout(from, to);
        }
        Action::Rebase => {
            undo_generic("rebase", "ORIG_HEAD");
        }
        Action::CherryPick => {
            undo_generic("cherry-pick", "HEAD~1");
        }
        Action::Reset => {
            undo_via_reflog("reset");
        }
        Action::StashApply | Action::Other { .. } => {
            undo_via_reflog("last action");
        }
    }
}

// ---------------------------------------------------------------------------
// Undo handlers
// ---------------------------------------------------------------------------

fn undo_commit(_message: &str, is_amend: bool, _is_merge: bool, is_initial: bool) {
    // Show what this commit changed
    show_commit_preview();

    let verb = if is_amend { "amend" } else { "commit" };

    let options = &[
        format!("Undo {}, keep all changes staged", verb),
        format!("Undo {}, keep changes unstaged", verb),
        format!("Undo {} and discard all changes", verb),
        "Cancel".to_string(),
    ];

    let refs: Vec<&str> = options.iter().map(|s| s.as_str()).collect();

    let selection = Select::new()
        .with_prompt("  What would you like to do?")
        .items(&refs)
        .default(0)
        .interact();

    let selection = match selection {
        Ok(s) => s,
        Err(_) => {
            println!("  Cancelled.");
            println!();
            return;
        }
    };

    println!();

    match selection {
        0 => {
            // Soft reset — keep staged
            let ok = if is_initial {
                let r = git::run(&["update-ref", "-d", "HEAD"]);
                r.success
            } else {
                git::run(&["reset", "--soft", "HEAD~1"]).success
            };
            if ok {
                println!("  {} Commit undone.", "".green().bold());
                println!("  Your changes are staged and ready to re-commit.");
            } else {
                println!("  {} Failed to undo commit.", "".red());
            }
        }
        1 => {
            // Mixed reset — unstaged
            let ok = if is_initial {
                let r = git::run(&["update-ref", "-d", "HEAD"]);
                if r.success { git::run(&["rm", "-r", "--cached", "."]).success } else { false }
            } else {
                git::run(&["reset", "--mixed", "HEAD~1"]).success
            };
            if ok {
                println!("  {} Commit undone.", "".green().bold());
                println!("  Your changes are in your working directory (unstaged).");
            } else {
                println!("  {} Failed to undo commit.", "".red());
            }
        }
        2 => {
            // Hard reset — destructive, needs confirmation
            println!("  {} This will permanently discard these changes:", "⚠ WARNING".red().bold());
            show_commit_preview();

            let confirm = Confirm::new()
                .with_prompt("  Are you sure? This cannot be undone")
                .default(false)
                .interact();

            match confirm {
                Ok(true) => {
                    let ok = if is_initial {
                        let r = git::run(&["update-ref", "-d", "HEAD"]);
                        if r.success {
                            git::run(&["rm", "-r", "--cached", "."]).success;
                            git::run(&["clean", "-fd"]).success
                        } else { false }
                    } else {
                        git::run(&["reset", "--hard", "HEAD~1"]).success
                    };
                    if ok {
                        println!("  {} Commit undone and changes discarded.", "".green().bold());
                    } else {
                        println!("  {} Failed to undo commit.", "".red());
                    }
                }
                _ => {
                    println!("  Cancelled. Nothing was changed.");
                }
            }
        }
        _ => {
            println!("  Cancelled.");
        }
    }
    println!();
}

fn undo_merge_or_pull(action: &Action) {
    // Show what came in
    let diff = git::run(&["diff", "--stat", "HEAD@{1}", "HEAD"]);
    if diff.success && !diff.stdout.is_empty() {
        println!("  {}:", "Changes that came in".dimmed());
        for line in diff.stdout.lines().take(10) {
            println!("    {}", line.dimmed());
        }
        println!();
    }

    let label = match action {
        Action::Pull => "pull",
        Action::Merge { .. } => "merge",
        _ => "action",
    };

    let options = &[
        format!("Undo {} (reset to state before)", label),
        "Cancel".to_string(),
    ];

    let refs: Vec<&str> = options.iter().map(|s| s.as_str()).collect();

    let selection = Select::new()
        .with_prompt("  What would you like to do?")
        .items(&refs)
        .default(0)
        .interact();

    match selection {
        Ok(0) => {
            println!();
            let result = git::run(&["reset", "--hard", "HEAD@{1}"]);
            if result.success {
                println!("  {} {} undone.", "".green().bold(), label);
                println!("  You're back to the state before the {}.", label);
            } else {
                println!("  {} Failed: {}", "".red(), result.stderr);
            }
        }
        _ => {
            println!("  Cancelled.");
        }
    }
    println!();
}

fn undo_checkout(from: &str, to: &str) {
    println!("  You switched from '{}' to '{}'.", from.dimmed(), to.cyan());
    println!();

    let options = &[
        format!("Switch back to '{}'", from),
        "Cancel".to_string(),
    ];

    let refs: Vec<&str> = options.iter().map(|s| s.as_str()).collect();

    let selection = Select::new()
        .with_prompt("  What would you like to do?")
        .items(&refs)
        .default(0)
        .interact();

    match selection {
        Ok(0) => {
            println!();
            let result = git::run(&["checkout", from]);
            if result.success {
                println!("  {} Switched back to '{}'.", "".green().bold(), from.cyan());
            } else {
                println!("  {} Failed: {}", "".red(), result.stderr);
            }
        }
        _ => {
            println!("  Cancelled.");
        }
    }
    println!();
}

fn undo_generic(action_name: &str, reset_target: &str) {
    show_rewind_preview("HEAD@{1}");

    let options = &[
        format!("Undo {} (reset to before)", action_name),
        "Cancel".to_string(),
    ];

    let refs: Vec<&str> = options.iter().map(|s| s.as_str()).collect();

    let selection = Select::new()
        .with_prompt("  What would you like to do?")
        .items(&refs)
        .default(0)
        .interact();

    match selection {
        Ok(0) => {
            println!();
            // Try ORIG_HEAD first (set by rebase/merge), fall back to reflog
            let result = git::run(&["reset", "--hard", reset_target]);
            if result.success {
                println!("  {} {} undone.", "".green().bold(), action_name);
            } else {
                // Fallback to reflog
                let result = git::run(&["reset", "--hard", "HEAD@{1}"]);
                if result.success {
                    println!("  {} {} undone.", "".green().bold(), action_name);
                } else {
                    println!("  {} Failed: {}", "".red(), result.stderr);
                }
            }
        }
        _ => {
            println!("  Cancelled.");
        }
    }
    println!();
}

fn undo_via_reflog(action_name: &str) {
    show_rewind_preview("HEAD@{1}");

    let options = &[
        format!("Rewind to state before {}", action_name),
        "Cancel".to_string(),
    ];

    let refs: Vec<&str> = options.iter().map(|s| s.as_str()).collect();

    let selection = Select::new()
        .with_prompt("  What would you like to do?")
        .items(&refs)
        .default(0)
        .interact();

    match selection {
        Ok(0) => {
            println!();

            // Safety confirmation
            let confirm = Confirm::new()
                .with_prompt(format!(
                    "  {} This will hard reset. Continue?",
                    "".yellow()
                ))
                .default(false)
                .interact();

            match confirm {
                Ok(true) => {
                    let result = git::run(&["reset", "--hard", "HEAD@{1}"]);
                    if result.success {
                        println!("  {} Rewound to previous state.", "".green().bold());
                    } else {
                        println!("  {} Failed: {}", "".red(), result.stderr);
                    }
                }
                _ => {
                    println!("  Cancelled.");
                }
            }
        }
        _ => {
            println!("  Cancelled.");
        }
    }
    println!();
}

// ---------------------------------------------------------------------------
// Preview helpers
// ---------------------------------------------------------------------------

fn show_commit_preview() {
    let stat = git::run(&["diff", "--stat", "HEAD~1", "HEAD"]);
    if stat.success && !stat.stdout.is_empty() {
        println!("  {}:", "Files in this commit".dimmed());
        for line in stat.stdout.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() { continue; }
            if trimmed.contains('|') {
                let parts: Vec<&str> = trimmed.splitn(2, '|').collect();
                let filename = parts[0].trim();
                let changes = parts.get(1).map(|s| s.trim()).unwrap_or("");
                println!("    {} {}", filename, changes.dimmed());
            } else {
                println!("    {}", trimmed.dimmed());
            }
        }
        println!();
    }
}

fn show_rewind_preview(target: &str) {
    let diff = git::run(&["diff", "--stat", target, "HEAD"]);
    if diff.success && !diff.stdout.is_empty() {
        println!("  {}:", "Changes that will be undone".yellow());
        for line in diff.stdout.lines().take(10) {
            let trimmed = line.trim();
            if !trimmed.is_empty() {
                println!("    {}", trimmed.dimmed());
            }
        }
        let total_lines: Vec<&str> = diff.stdout.lines().collect();
        if total_lines.len() > 10 {
            println!("    {}", format!("(+{} more files)", total_lines.len() - 10).dimmed());
        }
        println!();
    }
}