eazygit 0.5.1

A fast TUI for Git with staging, conflicts, rebase, and palette-first UX
Documentation
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
//! High-level rebase operations.
//!
//! This module provides the main business logic for rebase operations,
//! coordinating between validation, I/O, and Git operations.

use crate::services::GitService;
use crate::app::rebase::{RebaseSession, RebaseEntry, RebaseAction, RebasePhase};
use crate::app::rebase::validation::{RebaseValidator, RebaseValidationError};
use crate::app::rebase::io::RebaseIO;
use std::path::Path;

/// Result of rebase operations
#[derive(Debug)]
pub enum RebaseResult {
    /// Operation completed successfully
    Success,
    /// Conflicts detected during operation
    Conflicts { conflicted_files: Vec<String> },
    /// Rebase completed entirely
    Completed,
    /// Operation was aborted
    Aborted,
}

/// High-level rebase operations coordinator
pub struct RebaseOperations;

/// Recovery operations for interrupted rebases
pub struct RebaseRecovery;

impl RebaseRecovery {
    /// Detect if there's an interrupted rebase in the repository
    pub fn detect_interrupted_rebase(repo_path: &str) -> Result<Option<RebaseRecoveryInfo>, RebaseValidationError> {
        let git_dir = std::path::Path::new(repo_path).join(".git");

        // Check for rebase directories
        let rebase_merge_dir = git_dir.join("rebase-merge");
        let rebase_apply_dir = git_dir.join("rebase-apply");

        if rebase_merge_dir.exists() {
            // Interactive rebase in progress
            let todo_path = rebase_merge_dir.join("git-rebase-todo");
            let done_path = rebase_merge_dir.join("done");

            let current_commit = std::fs::read_to_string(rebase_merge_dir.join("head-name"))
                .unwrap_or_else(|_| "unknown".to_string())
                .trim()
                .to_string();

            let todo_lines = if todo_path.exists() {
                std::fs::read_to_string(&todo_path)
                    .unwrap_or_default()
                    .lines()
                    .map(|s| s.to_string())
                    .collect()
            } else {
                Vec::new()
            };

            let done_lines = if done_path.exists() {
                std::fs::read_to_string(&done_path)
                    .unwrap_or_default()
                    .lines()
                    .map(|s| s.to_string())
                    .collect()
            } else {
                Vec::new()
            };

            Ok(Some(RebaseRecoveryInfo {
                recovery_type: RebaseRecoveryType::Interactive,
                current_commit,
                remaining_steps: todo_lines.len(),
                completed_steps: done_lines.len(),
                has_conflicts: Self::check_for_conflicts(repo_path)?,
            }))
        } else if rebase_apply_dir.exists() {
            // Apply-style rebase (less common)
            Ok(Some(RebaseRecoveryInfo {
                recovery_type: RebaseRecoveryType::Apply,
                current_commit: "unknown".to_string(),
                remaining_steps: 0,
                completed_steps: 0,
                has_conflicts: Self::check_for_conflicts(repo_path)?,
            }))
        } else {
            Ok(None)
        }
    }

    /// Check if there are unresolved conflicts in the working directory
    fn check_for_conflicts(repo_path: &str) -> Result<bool, RebaseValidationError> {
        // Use git status to check for conflicts
        match std::process::Command::new("git")
            .args(&["status", "--porcelain"])
            .current_dir(repo_path)
            .output()
        {
            Ok(output) => {
                let status = String::from_utf8_lossy(&output.stdout);
                let has_conflicts = status.lines()
                    .any(|line| line.starts_with("U ") || line.starts_with("AA ") || line.starts_with("DD "));
                Ok(has_conflicts)
            }
            Err(_) => Ok(false), // Assume no conflicts if we can't check
        }
    }

    /// Attempt to continue the interrupted rebase
    pub fn continue_interrupted_rebase(
        git_service: &GitService,
        repo_path: &str,
        session: &mut RebaseSession,
    ) -> Result<RebaseResult, RebaseValidationError> {
        // First, try to detect what's going on
        if let Some(recovery_info) = Self::detect_interrupted_rebase(repo_path)? {
            if recovery_info.has_conflicts {
                // Conflicts need to be resolved first
                session.phase = RebasePhase::Conflict;
                return Ok(RebaseResult::Conflicts {
                    conflicted_files: Vec::new() // We'll let the conflict resolution handle detection
                });
            }

            // Try to continue the rebase
            match recovery_info.recovery_type {
                RebaseRecoveryType::Interactive => {
                    // For interactive rebases, we can try to continue
                    git_service
                        .rebase_continue(repo_path, None, None, None)
                        .map_err(|e| RebaseValidationError::InvalidRepositoryState(e.to_string()))?;

                    session.phase = RebasePhase::Active;
                    Ok(RebaseResult::Success)
                }
                RebaseRecoveryType::Apply => {
                    // For apply-style rebases, continue might work
                    git_service
                        .rebase_continue(repo_path, None, None, None)
                        .map_err(|e| RebaseValidationError::InvalidRepositoryState(e.to_string()))?;

                    session.phase = RebasePhase::Active;
                    Ok(RebaseResult::Success)
                }
            }
        } else {
            Err(RebaseValidationError::InvalidRepositoryState("No interrupted rebase found".to_string()))
        }
    }

    /// Abort the interrupted rebase
    pub fn abort_interrupted_rebase(
        git_service: &GitService,
        repo_path: &str,
    ) -> Result<(), RebaseValidationError> {
        git_service
            .rebase_abort(repo_path)
            .map_err(|e| RebaseValidationError::InvalidRepositoryState(e.to_string()))
    }
}

/// Information about an interrupted rebase
#[derive(Debug, Clone)]
pub struct RebaseRecoveryInfo {
    pub recovery_type: RebaseRecoveryType,
    pub current_commit: String,
    pub remaining_steps: usize,
    pub completed_steps: usize,
    pub has_conflicts: bool,
}

/// Type of rebase that was interrupted
#[derive(Debug, Clone)]
pub enum RebaseRecoveryType {
    /// Interactive rebase (--interactive)
    Interactive,
    /// Apply-style rebase
    Apply,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn setup_test_repo() -> (TempDir, String) {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp directory");
        let repo_path = temp_dir.path().to_string();

        // Initialize git repo
        let output = std::process::Command::new("git")
            .args(&["init"])
            .current_dir(&repo_path)
            .output()
            .expect("Failed to init git repo");

        assert!(output.status.success(), "Git init failed");

        // Configure git
        std::process::Command::new("git")
            .args(&["config", "user.name", "Test User"])
            .current_dir(&repo_path)
            .output()
            .expect("Failed to configure git user");

        std::process::Command::new("git")
            .args(&["config", "user.email", "test@example.com"])
            .current_dir(&repo_path)
            .output()
            .expect("Failed to configure git email");

        // Create initial commit
        fs::write(temp_dir.path().join("file.txt"), "initial content").unwrap();
        std::process::Command::new("git")
            .args(&["add", "file.txt"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        std::process::Command::new("git")
            .args(&["commit", "-m", "Initial commit"])
            .current_dir(&repo_path)
            .output()
            .unwrap();

        (temp_dir, repo_path)
    }

    #[test]
    fn test_start_planning_session() {
        let commit_hashes = vec![
            "abc123def456".to_string(),
            "def456ghi789".to_string(),
            "ghi789jkl012".to_string(),
        ];

        let result = RebaseOperations::start_planning_session(
            commit_hashes,
            Some("HEAD~3".to_string()),
            false,
        );

        assert!(result.is_ok());
        let session = result.unwrap();
        assert_eq!(session.phase, crate::RebasePhase::Planning);
        assert_eq!(session.entries.len(), 3);
        assert_eq!(session.base_commit, Some("HEAD~3".to_string()));
        assert!(!session.use_root);
    }

    #[test]
    fn test_recovery_detection_no_rebase() {
        let (_temp_dir, repo_path) = setup_test_repo();

        let result = RebaseRecovery::detect_interrupted_rebase(&repo_path);
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_recovery_info_creation() {
        let recovery_info = RebaseRecoveryInfo {
            recovery_type: RebaseRecoveryType::Interactive,
            current_commit: "feature-branch".to_string(),
            remaining_steps: 5,
            completed_steps: 2,
            has_conflicts: true,
        };

        assert_eq!(recovery_info.recovery_type, RebaseRecoveryType::Interactive);
        assert_eq!(recovery_info.current_commit, "feature-branch");
        assert_eq!(recovery_info.remaining_steps, 5);
        assert_eq!(recovery_info.completed_steps, 2);
        assert!(recovery_info.has_conflicts);
    }

    #[test]
    fn test_rebase_session_state_transitions() {
        let mut session = RebaseSession::new();
        assert_eq!(session.phase, RebasePhase::Planning);

        // Simulate starting execution
        session.phase = RebasePhase::Active;
        assert_eq!(session.phase, RebasePhase::Active);

        // Simulate hitting conflicts
        session.phase = RebasePhase::Conflict;
        assert_eq!(session.phase, RebasePhase::Conflict);

        // Simulate completion
        session.phase = RebasePhase::Completed;
        assert_eq!(session.phase, RebasePhase::Completed);
    }

    #[test]
    fn test_rebase_entry_creation() {
        let entry = crate::RebaseEntry::new(
            "abc123def456".to_string(),
            "Test commit message".to_string(),
            crate::RebaseAction::Pick,
        );

        assert_eq!(entry.hash, "abc123def456");
        assert_eq!(entry.message, "Test commit message");
        assert_eq!(entry.action, crate::RebaseAction::Pick);
        assert_eq!(entry.short_hash, "abc123"); // Short hash is first 6 chars
    }

    #[test]
    fn test_rebase_action_string_conversion() {
        assert_eq!(crate::RebaseAction::Pick.to_str(), "pick");
        assert_eq!(crate::RebaseAction::Reword.to_str(), "reword");
        assert_eq!(crate::RebaseAction::Edit.to_str(), "edit");
        assert_eq!(crate::RebaseAction::Squash.to_str(), "squash");
        assert_eq!(crate::RebaseAction::Fixup.to_str(), "fixup");
        assert_eq!(crate::RebaseAction::Drop.to_str(), "drop");
    }

    #[test]
    fn test_rebase_session_default() {
        let session = RebaseSession::default();
        assert_eq!(session.phase, RebasePhase::Planning);
        assert!(session.entries.is_empty());
        assert_eq!(session.cursor, 0);
        assert!(session.todo_path.is_none());
        assert!(session.base_commit.is_none());
        assert!(!session.use_root);
        assert!(!session.dirty);
    }

    #[test]
    fn test_rebase_validation_errors() {
        use crate::validation::RebaseValidationError;

        // Test validation error creation
        let error = RebaseValidationError::InvalidRepositoryState("test error".to_string());
        match error {
            RebaseValidationError::InvalidRepositoryState(msg) => assert_eq!(msg, "test error"),
            _ => panic!("Wrong error type"),
        }

        let error = RebaseValidationError::SessionNotFound("test session".to_string());
        match error {
            RebaseValidationError::SessionNotFound(name) => assert_eq!(name, "test session"),
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_rebase_workflow_state_transitions() {
        // Test the complete workflow state machine
        let mut session = RebaseSession::default();

        // Start planning
        assert_eq!(session.phase, RebasePhase::Planning);

        // Move to active (simulating execution)
        session.phase = RebasePhase::Active;
        assert_eq!(session.phase, RebasePhase::Active);

        // Hit conflicts
        session.phase = RebasePhase::Conflict;
        assert_eq!(session.phase, RebasePhase::Conflict);

        // Resolve conflicts and continue
        session.phase = RebasePhase::Active;
        assert_eq!(session.phase, RebasePhase::Active);

        // Complete successfully
        session.phase = RebasePhase::Completed;
        assert_eq!(session.phase, RebasePhase::Completed);

        // Test aborted state
        session.phase = RebasePhase::Aborted;
        assert_eq!(session.phase, RebasePhase::Aborted);
    }

    #[test]
    fn test_rebase_session_with_entries() {
        let mut session = RebaseSession::default();

        // Add some entries
        session.entries.push(crate::RebaseEntry::new(
            "abc123".to_string(),
            "First commit".to_string(),
            crate::RebaseAction::Pick,
        ));
        session.entries.push(crate::RebaseEntry::new(
            "def456".to_string(),
            "Second commit".to_string(),
            crate::RebaseAction::Reword,
        ));

        assert_eq!(session.entries.len(), 2);
        assert_eq!(session.entries[0].action, crate::RebaseAction::Pick);
        assert_eq!(session.entries[1].action, crate::RebaseAction::Reword);
        assert_eq!(session.cursor, 0);

        // Test cursor movement
        session.cursor = 1;
        assert_eq!(session.cursor, 1);

        // Test dirty flag
        assert!(!session.dirty);
        session.dirty = true;
        assert!(session.dirty);
    }
}

impl RebaseOperations {
    /// Start a new interactive rebase planning session
    pub fn start_planning_session(
        commit_hashes: Vec<String>,
        base_commit: Option<String>,
        use_root: bool,
    ) -> Result<RebaseSession, RebaseValidationError> {
        let mut session = RebaseSession::new();
        session.phase = RebasePhase::Planning;
        session.base_commit = base_commit;
        session.use_root = use_root;

        // Convert commit hashes to RebaseEntry objects
        // Note: In a real implementation, we'd fetch commit messages from Git
        // For now, we'll create placeholder entries
        session.entries = commit_hashes
            .into_iter()
            .enumerate()
            .map(|(i, hash)| {
                RebaseEntry::new(
                    hash,
                    format!("Commit {}", i + 1), // Placeholder message
                    RebaseAction::Pick, // Default action
                )
            })
            .collect();

        // Validate the session
        RebaseValidator::validate_session_entries(&session)?;

        Ok(session)
    }

    /// Execute a planned rebase (Planning → Active)
    pub fn execute_rebase(
        git_service: &GitService,
        repo_path: &str,
        session: &mut RebaseSession,
    ) -> Result<RebaseResult, RebaseValidationError> {
        // Validate before execution
        RebaseValidator::validate_before_execution(git_service, repo_path, session)?;

        // Format entries to git-rebase-todo format
        let todo_content = RebaseIO::format_todo_content(&session.entries);

        // Execute rebase with custom todo
        let result = git_service
            .start_rebase_with_todo(
                repo_path,
                session.base_commit.as_deref().unwrap_or("HEAD~1"),
                &todo_content,
                session.use_root,
            )
            .map_err(|e| RebaseValidationError::InvalidRepositoryState(e.to_string()))?;

        // Update session state
        session.phase = RebasePhase::Active;
        session.todo_path = Some(Path::new(&result).to_path_buf());
        session.dirty = false;

        // Check for immediate conflicts
        match git_service.status_porcelain(repo_path) {
            Ok(status) => {
                let conflicted_files: Vec<String> = status
                    .lines()
                    .filter(|line| line.starts_with("U ") || line.starts_with("AA ") || line.starts_with("DD "))
                    .map(|line| line[3..].trim().to_string()) // Remove status prefix
                    .collect();

                if !conflicted_files.is_empty() {
                    session.phase = RebasePhase::Conflict;
                    Ok(RebaseResult::Conflicts { conflicted_files })
                } else {
                    Ok(RebaseResult::Success)
                }
            }
            Err(_) => {
                // If we can't check status, assume success for now
                // In production, this should be handled better
                Ok(RebaseResult::Success)
            }
        }
    }

    /// Continue an active rebase to the next step
    pub fn continue_rebase(
        git_service: &GitService,
        repo_path: &str,
        session: &mut RebaseSession,
    ) -> Result<RebaseResult, RebaseValidationError> {
        // Validate session state
        RebaseValidator::validate_session_state(session, "continue_rebase")?;

        // Continue rebase
        git_service
            .rebase_continue(repo_path, None, None, None)
            .map_err(|e| RebaseValidationError::InvalidRepositoryState(e.to_string()))?;

        // Check for conflicts after continue
        match git_service.status_porcelain(repo_path) {
            Ok(status) => {
                let conflicted_files: Vec<String> = status
                    .lines()
                    .filter(|line| line.starts_with("U ") || line.starts_with("AA ") || line.starts_with("DD "))
                    .map(|line| line[3..].trim().to_string())
                    .collect();

                if !conflicted_files.is_empty() {
                    session.phase = RebasePhase::Conflict;
                    Ok(RebaseResult::Conflicts { conflicted_files })
                } else {
                    // Check if rebase is complete
                    // Note: In real implementation, check if .git/rebase-* dirs still exist
                    // For now, assume success
                    Ok(RebaseResult::Success)
                }
            }
            Err(_) => {
                // If we can't check status, assume success for now
                Ok(RebaseResult::Success)
            }
        }
    }

    /// Skip the current rebase step
    pub fn skip_rebase_step(
        git_service: &GitService,
        repo_path: &str,
        session: &mut RebaseSession,
    ) -> Result<RebaseResult, RebaseValidationError> {
        // Validate session state
        RebaseValidator::validate_session_state(session, "continue_rebase")?;

        // Skip current step
        git_service
            .rebase_skip(repo_path)
            .map_err(|e| RebaseValidationError::InvalidRepositoryState(e.to_string()))?;

        // Check for conflicts after skip
        match git_service.status_porcelain(repo_path) {
            Ok(status) => {
                let conflicted_files: Vec<String> = status
                    .lines()
                    .filter(|line| line.starts_with("U ") || line.starts_with("AA ") || line.starts_with("DD "))
                    .map(|line| line[3..].trim().to_string())
                    .collect();

                if !conflicted_files.is_empty() {
                    session.phase = RebasePhase::Conflict;
                    Ok(RebaseResult::Conflicts { conflicted_files })
                } else {
                    Ok(RebaseResult::Success)
                }
            }
            Err(_) => {
                // If we can't check status, assume success for now
                Ok(RebaseResult::Success)
            }
        }
    }

    /// Abort the current rebase
    pub fn abort_rebase(
        git_service: &GitService,
        repo_path: &str,
        session: &mut RebaseSession,
    ) -> Result<RebaseResult, RebaseValidationError> {
        // Validate session state
        RebaseValidator::validate_session_state(session, "abort_rebase")?;

        // Abort rebase
        git_service
            .rebase_abort(repo_path)
            .map_err(|e| RebaseValidationError::InvalidRepositoryState(e.to_string()))?;

        // Reset session to planning state
        session.phase = RebasePhase::Planning;
        session.entries.clear();
        session.todo_path = None;
        session.dirty = false;

        Ok(RebaseResult::Aborted)
    }

    /// Save current todo changes to disk
    pub fn save_todo_changes(
        session: &mut RebaseSession,
    ) -> Result<(), RebaseValidationError> {
        if let Some(todo_path) = &session.todo_path {
            let todo_content = RebaseIO::format_todo_content(&session.entries);
            RebaseIO::write_todo_atomically(todo_path, &todo_content)
                .map_err(|e| RebaseValidationError::InvalidRepositoryState(
                    format!("Failed to save todo file: {}", e)
                ))?;
            session.dirty = false;
        }
        Ok(())
    }
}