git-repos-manager 0.7.5

Scan and manage git repositories with ease
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
use crate::event::{EventHandler, GitDataUpdate, TerminalEvent};
use crate::git_repo::GitRepo;
use crate::util::{strip_unc_pathbuf, strip_unc_prefix};
use color_eyre::Result;
use crossterm::{
    event::{KeyCode, KeyModifiers},
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{Terminal, backend::CrosstermBackend, widgets::TableState};
use std::io;
use std::path::Path;

/// Filter mode for displaying repositories
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterMode {
    All,
    NoUpstream,
    Modified,
    Behind,
}

impl FilterMode {
    /// Get the next filter mode in the cycle
    pub fn next(&self) -> Self {
        match self {
            FilterMode::All => FilterMode::NoUpstream,
            FilterMode::NoUpstream => FilterMode::Behind,
            FilterMode::Behind => FilterMode::Modified,
            FilterMode::Modified => FilterMode::All,
        }
    }

    /// Get the previous filter mode in the cycle
    pub fn previous(&self) -> Self {
        match self {
            FilterMode::All => FilterMode::Modified,
            FilterMode::Modified => FilterMode::Behind,
            FilterMode::Behind => FilterMode::NoUpstream,
            FilterMode::NoUpstream => FilterMode::All,
        }
    }

    /// Get display name for the filter mode
    pub fn display_name(&self) -> &str {
        match self {
            FilterMode::All => "All",
            FilterMode::NoUpstream => "No Upstream",
            FilterMode::Modified => "Modified",
            FilterMode::Behind => "Behind",
        }
    }
}

/// Application state
pub struct App {
    pub repos: Vec<GitRepo>,
    pub scan_path: String,
    pub table_state: TableState,
    should_quit: bool,
    needs_redraw: bool,
    event_handler: EventHandler,
    pub selected_repo: Option<String>,
    pub fetching_repos: Vec<usize>,
    pub cloning_repos: Vec<usize>,
    pub deleting_repos: Vec<usize>,
    pub fetch_animation_frame: usize,
    pub filter_mode: FilterMode,
    search_query: String,
    search_mode: bool,
    delete_confirmation: Option<usize>,
    root_path: Option<std::path::PathBuf>,
    pub cwd_file_enabled: bool,
}

impl App {
    /// Sort repositories: existing first (alphabetically), then missing (alphabetically)
    fn sort_repos(repos: &mut [GitRepo]) {
        repos.sort_by(|a, b| match (a.is_missing(), b.is_missing()) {
            (false, true) => std::cmp::Ordering::Less,
            (true, false) => std::cmp::Ordering::Greater,
            _ => {
                let a_name = a.display_short().to_lowercase();
                let b_name = b.display_short().to_lowercase();
                a_name.cmp(&b_name)
            }
        });
    }

    /// Find repository index by path after sorting
    fn find_repo_index(repos: &[GitRepo], path: &std::path::Path) -> Option<usize> {
        repos.iter().position(|r| r.path() == path)
    }

    /// Spawn task to load git data for a repository
    ///
    /// Now sends FetchProgress and FetchComplete events for proper animation.
    fn spawn_git_data_load(
        tx: tokio::sync::mpsc::UnboundedSender<GitDataUpdate>,
        idx: usize,
        path: std::path::PathBuf,
    ) {
        let tx_clone = tx.clone();
        tokio::spawn(async move {
            // Start fetch animation
            let _ = tx_clone.send(GitDataUpdate::FetchProgress(idx));

            let remote_status = tokio::task::spawn_blocking({
                let path = path.clone();
                move || GitRepo::read_remote_status(&path)
            })
            .await
            .unwrap_or_else(|_| "error".to_string());

            let status = tokio::task::spawn_blocking(move || GitRepo::read_status(&path))
                .await
                .unwrap_or_else(|_| "error".to_string());

            let _ = tx_clone.send(GitDataUpdate::RemoteStatus(idx, remote_status));
            let _ = tx_clone.send(GitDataUpdate::Status(idx, status));

            // End fetch animation
            let _ = tx_clone.send(GitDataUpdate::FetchComplete(idx));
        });
    }

    /// Spawn task to fetch and update a repository (manual update with fast-forward)
    fn spawn_manual_update(
        tx: tokio::sync::mpsc::UnboundedSender<GitDataUpdate>,
        idx: usize,
        path: std::path::PathBuf,
    ) {
        let tx_clone = tx.clone();
        tokio::spawn(async move {
            // Start fetch animation
            let _ = tx_clone.send(GitDataUpdate::FetchProgress(idx));

            // First read initial status
            let remote_status = tokio::task::spawn_blocking({
                let path = path.clone();
                move || GitRepo::read_remote_status(&path)
            })
            .await
            .unwrap_or_else(|_| "error".to_string());

            // Perform fetch with fast-forward if repo has remote
            if remote_status != "local-only" && remote_status != "error" {
                let fetch_result = tokio::task::spawn_blocking({
                    let path = path.clone();
                    move || GitRepo::fetch(&path, true) // Always fast-forward for manual update
                })
                .await;

                if fetch_result.is_ok() {
                    // Re-read remote status after fetch
                    let new_remote_status = tokio::task::spawn_blocking({
                        let path = path.clone();
                        move || GitRepo::read_remote_status(&path)
                    })
                    .await
                    .unwrap_or_else(|_| "error".to_string());

                    let _ = tx_clone.send(GitDataUpdate::RemoteStatus(idx, new_remote_status));
                }
            } else {
                let _ = tx_clone.send(GitDataUpdate::RemoteStatus(idx, remote_status));
            }

            // Read working tree status (might have changed after fast-forward)
            let status = tokio::task::spawn_blocking(move || GitRepo::read_status(&path))
                .await
                .unwrap_or_else(|_| "error".to_string());

            let _ = tx_clone.send(GitDataUpdate::Status(idx, status));

            // End fetch animation
            let _ = tx_clone.send(GitDataUpdate::FetchComplete(idx));
        });
    }

    /// Create a new App instance
    pub fn new(repos: Vec<GitRepo>, scan_path: &Path, fetch: bool, update: bool) -> Self {
        Self::new_with_root(repos, scan_path, fetch, update, None, false)
    }

    /// Create a new App instance with optional root path
    pub fn new_with_root(
        mut repos: Vec<GitRepo>,
        scan_path: &Path,
        fetch: bool,
        update: bool,
        root_path: Option<std::path::PathBuf>,
        cwd_file_enabled: bool,
    ) -> Self {
        Self::sort_repos(&mut repos);

        let mut table_state = TableState::default();
        if !repos.is_empty() {
            table_state.select(Some(0));
        }
        // Convert to normal path display (strip \?\ prefix on Windows)
        let path_str = scan_path.display().to_string();
        let display_path = strip_unc_prefix(&path_str).to_string();

        // Create event handler and spawn git data loading tasks
        let repos_clone = repos.clone();
        let event_handler = EventHandler::new(
            repos.len(),
            move |idx| repos_clone[idx].path().to_path_buf(),
            fetch,
            update,
        );

        Self {
            repos,
            scan_path: display_path,
            table_state,
            should_quit: false,
            needs_redraw: false,
            event_handler,
            selected_repo: None,
            fetching_repos: Vec::new(),
            cloning_repos: Vec::new(),
            deleting_repos: Vec::new(),
            fetch_animation_frame: 0,
            filter_mode: FilterMode::All,
            search_query: String::new(),
            search_mode: false,
            delete_confirmation: None,
            root_path,
            cwd_file_enabled,
        }
    }

    /// Run the TUI application
    pub async fn run(&mut self) -> Result<()> {
        // Setup terminal
        enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(stdout, EnterAlternateScreen)?;
        let backend = CrosstermBackend::new(stdout);
        let mut terminal = Terminal::new(backend)?;

        // Main loop
        let result = self.run_loop(&mut terminal).await;

        // Restore terminal
        disable_raw_mode()?;
        execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
        terminal.show_cursor()?;

        result
    }

    /// Get the repositories (for saving cache)
    pub fn repos(&self) -> &[GitRepo] {
        &self.repos
    }

    /// Main event loop
    async fn run_loop(
        &mut self,
        terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    ) -> Result<()> {
        // Create a timer for animation updates
        let mut animation_interval = tokio::time::interval(tokio::time::Duration::from_millis(100));

        loop {
            terminal.draw(|f| f.render_widget(&mut *self, f.area()))?;
            self.needs_redraw = false;

            if self.should_quit {
                break;
            }

            // Wait for next event or animation tick
            tokio::select! {
                result = self.event_handler.next() => {
                    if let Some(event) = result? {
                        self.handle_event(event)?;
                    }
                }
                _ = animation_interval.tick() => {
                    if !self.fetching_repos.is_empty() || !self.cloning_repos.is_empty() || !self.deleting_repos.is_empty() {
                        self.fetch_animation_frame = (self.fetch_animation_frame + 1) % 10;
                        self.needs_redraw = true;
                    }
                }
            }
        }
        Ok(())
    }

    /// Handle terminal events
    fn handle_event(&mut self, event: TerminalEvent) -> Result<()> {
        match event {
            TerminalEvent::Key(code, modifiers) => {
                if self.is_confirmation_mode() {
                    self.handle_confirmation_key(code);
                } else if self.search_mode {
                    self.handle_search_key(code);
                } else {
                    self.handle_normal_key(code, modifiers);
                }
            }
            TerminalEvent::GitUpdate(update) => self.handle_git_update(update),
        }
        Ok(())
    }

    /// Handle key press in search mode
    fn handle_search_key(&mut self, code: KeyCode) {
        match code {
            KeyCode::Esc => {
                self.search_mode = false;
                self.search_query.clear();
                self.table_state.select(Some(0));
                self.needs_redraw = true;
            }
            KeyCode::Enter => {
                self.search_mode = false;
                self.needs_redraw = true;
            }
            KeyCode::Backspace => {
                self.search_query.pop();
                self.table_state.select(Some(0));
                self.needs_redraw = true;
            }
            KeyCode::Char(c) => {
                self.search_query.push(c);
                self.table_state.select(Some(0));
                self.needs_redraw = true;
            }
            _ => {}
        }
    }

    /// Handle key press in normal mode
    ///
    /// Shortcuts:
    ///   q / Q: Quit
    ///   Ctrl+C: Quit
    ///   Enter: Select repo (if cwd_file_enabled)
    ///   j / Down: Next repo
    ///   k / Up: Previous repo
    ///   [ / ]: Cycle filter mode
    ///   /: Search
    ///   d / D: Drop repo
    ///   c / C: Clone missing repo
    ///   u / U: Update selected repo (fetch + status)
    fn handle_normal_key(&mut self, code: KeyCode, modifiers: KeyModifiers) {
        match code {
            KeyCode::Char('q') | KeyCode::Char('Q') => {
                self.should_quit = true;
            }
            KeyCode::Char('c') if modifiers.contains(KeyModifiers::CONTROL) => {
                self.should_quit = true;
            }
            KeyCode::Enter => {
                if self.cwd_file_enabled
                    && let Some(repo) = self.table_state.selected().and_then(|i| self.repos.get(i))
                {
                    self.selected_repo = Some(repo.path().display().to_string());
                    self.should_quit = true;
                }
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.next();
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.previous();
            }
            KeyCode::Char('[') => {
                self.filter_mode = self.filter_mode.previous();
                self.table_state.select(Some(0));
                self.needs_redraw = true;
            }
            KeyCode::Char(']') => {
                self.filter_mode = self.filter_mode.next();
                self.table_state.select(Some(0));
                self.needs_redraw = true;
            }
            KeyCode::Char('/') => {
                self.search_mode = true;
                self.search_query.clear();
                self.needs_redraw = true;
            }
            KeyCode::Char('d') | KeyCode::Char('D') => {
                self.handle_drop_repo();
            }
            KeyCode::Char('c') | KeyCode::Char('C') => {
                self.handle_clone_repo();
            }
            KeyCode::Char('u') | KeyCode::Char('U') => {
                self.handle_update_repo();
            }
            _ => {}
        }
    }

    /// Handle keys in confirmation mode
    fn handle_confirmation_key(&mut self, code: KeyCode) {
        match code {
            KeyCode::Char('y') | KeyCode::Char('Y') => {
                self.perform_drop_repo();
            }
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                self.cancel_confirmation();
            }
            _ => {}
        }
    }

    /// Update the selected repository (fetch + status), with animation.
    ///
    /// This is triggered by the 'u' shortcut in normal mode.
    fn handle_update_repo(&mut self) {
        let Some(selected) = self.table_state.selected() else {
            return;
        };
        let Some(repo) = self.repos.get(selected) else {
            return;
        };
        if repo.is_missing() {
            return;
        }
        // Mark as fetching for animation
        if !self.fetching_repos.contains(&selected) {
            self.fetching_repos.push(selected);
        }
        self.needs_redraw = true;
        let tx = self.event_handler.git_tx();
        let path = repo.path().to_path_buf();
        let idx = selected;
        // Manual update always fetches with fast-forward
        Self::spawn_manual_update(tx, idx, path);
    }

    /// Handle git data updates
    fn handle_git_update(&mut self, update: GitDataUpdate) {
        match update {
            GitDataUpdate::RemoteStatus(idx, status) => {
                if let Some(repo) = self.repos.get_mut(idx) {
                    repo.set_remote_status(status);
                    self.needs_redraw = true;
                }
            }
            GitDataUpdate::Status(idx, status) => {
                if let Some(repo) = self.repos.get_mut(idx) {
                    repo.set_status(status);
                    self.needs_redraw = true;
                }
            }
            GitDataUpdate::FetchProgress(idx) => {
                if !self.fetching_repos.contains(&idx) {
                    self.fetching_repos.push(idx);
                    self.needs_redraw = true;
                }
            }
            GitDataUpdate::FetchComplete(idx) => {
                self.fetching_repos.retain(|&i| i != idx);
                self.fetch_animation_frame = (self.fetch_animation_frame + 1) % 10;
                self.needs_redraw = true;
            }
            GitDataUpdate::CloneProgress(idx) => {
                if !self.cloning_repos.contains(&idx) {
                    self.cloning_repos.push(idx);
                    self.needs_redraw = true;
                }
            }
            GitDataUpdate::CloneComplete(idx) => {
                self.cloning_repos.retain(|&i| i != idx);

                // Refresh the repository by recreating it as a normal repo
                if let Some(repo) = self.repos.get(idx) {
                    let path = repo.path().to_path_buf();

                    // Only refresh if the clone was successful (directory exists)
                    if path.exists() {
                        self.repos[idx] = GitRepo::new(path.clone());
                        Self::sort_repos(&mut self.repos);

                        if let Some(new_idx) = Self::find_repo_index(&self.repos, &path) {
                            self.table_state.select(Some(new_idx));
                            Self::spawn_git_data_load(self.event_handler.git_tx(), new_idx, path);
                        }
                    }
                }

                self.needs_redraw = true;
            }
            GitDataUpdate::DeleteProgress(idx) => {
                if !self.deleting_repos.contains(&idx) {
                    self.deleting_repos.push(idx);
                    self.needs_redraw = true;
                }
            }
            GitDataUpdate::DeleteComplete(idx) => {
                self.deleting_repos.retain(|&i| i != idx);

                if let Some(repo) = self.repos.get_mut(idx) {
                    let repo_path = repo.path().to_path_buf();
                    repo.set_missing();
                    Self::sort_repos(&mut self.repos);

                    if let Some(new_idx) = Self::find_repo_index(&self.repos, &repo_path) {
                        self.table_state.select(Some(new_idx));
                    }
                }

                self.needs_redraw = true;
            }
        }
    }

    /// Get filtered list of repository indices based on current filter mode
    pub fn filtered_repos(&self) -> Vec<usize> {
        self.repos
            .iter()
            .enumerate()
            .filter(|(_, repo)| self.matches_search(repo) && self.matches_filter(repo))
            .map(|(idx, _)| idx)
            .collect()
    }

    /// Check if repository matches search query
    fn matches_search(&self, repo: &GitRepo) -> bool {
        if self.search_query.is_empty() {
            return true;
        }

        let query_lower = self.search_query.to_lowercase();
        let name_match = repo
            .name()
            .map(|n| n.to_lowercase().contains(&query_lower))
            .unwrap_or(false);
        let parent_match = repo
            .parent_name()
            .map(|p| p.to_lowercase().contains(&query_lower))
            .unwrap_or(false);

        name_match || parent_match
    }

    /// Check if repository matches filter mode
    fn matches_filter(&self, repo: &GitRepo) -> bool {
        // Missing repos only show in "All" filter
        if repo.is_missing() && self.filter_mode != FilterMode::All {
            return false;
        }

        match self.filter_mode {
            FilterMode::All => true,
            FilterMode::NoUpstream => {
                let remote = repo.remote_status();
                remote == "local-only" || remote == "no-tracking"
            }
            FilterMode::Modified => {
                let status = repo.status();
                status != "clean" && status != "loading..."
            }
            FilterMode::Behind => repo.remote_status().contains('↓'),
        }
    }

    /// Check if search mode is active
    pub fn is_search_mode(&self) -> bool {
        self.search_mode
    }

    /// Get current search query
    pub fn search_query(&self) -> &str {
        &self.search_query
    }

    /// Check if in delete confirmation mode
    pub fn is_confirmation_mode(&self) -> bool {
        self.delete_confirmation.is_some()
    }

    /// Get the repository name being confirmed for deletion
    pub fn confirmation_repo_name(&self) -> Option<String> {
        self.delete_confirmation
            .and_then(|idx| self.repos.get(idx))
            .map(|repo| repo.display_short().to_string())
    }

    /// Cancel the delete confirmation
    fn cancel_confirmation(&mut self) {
        self.delete_confirmation = None;
        self.needs_redraw = true;
    }

    /// Move to next item
    fn next(&mut self) {
        let filtered = self.filtered_repos();
        if filtered.is_empty() {
            return;
        }

        let current_selected = self.table_state.selected().unwrap_or(0);
        let current_pos = filtered.iter().position(|&idx| idx == current_selected);

        let next_pos = match current_pos {
            Some(pos) if pos >= filtered.len() - 1 => 0,
            Some(pos) => pos + 1,
            None => 0,
        };

        self.table_state.select(Some(filtered[next_pos]));
    }

    /// Move to previous item
    fn previous(&mut self) {
        let filtered = self.filtered_repos();
        if filtered.is_empty() {
            return;
        }

        let current_selected = self.table_state.selected().unwrap_or(0);
        let current_pos = filtered.iter().position(|&idx| idx == current_selected);

        let prev_pos = match current_pos {
            Some(0) | None => filtered.len() - 1,
            Some(pos) => pos - 1,
        };

        self.table_state.select(Some(filtered[prev_pos]));
    }

    /// Handle dropping a repository
    fn handle_drop_repo(&mut self) {
        let Some(selected) = self.table_state.selected() else {
            return;
        };

        let Some(_repo) = self.repos.get(selected) else {
            return;
        };

        // Request confirmation
        self.delete_confirmation = Some(selected);
        self.needs_redraw = true;
    }

    /// Perform the actual deletion after confirmation
    fn perform_drop_repo(&mut self) {
        let Some(selected) = self.delete_confirmation.take() else {
            return;
        };

        let Some(repo) = self.repos.get(selected) else {
            return;
        };

        let is_missing = repo.is_missing();
        let repo_path = repo.path().to_path_buf();

        if is_missing {
            // Missing repo: remove from cache
            if let Some(root_path) = &self.root_path {
                let cleaned_path = strip_unc_pathbuf(repo_path.as_path());

                if let Ok(relative_path) = cleaned_path.strip_prefix(root_path)
                    && crate::config::remove_from_cache(relative_path).is_ok()
                {
                    // Remove from repos list
                    self.repos.remove(selected);

                    // Adjust selection
                    if !self.repos.is_empty() {
                        let new_selected = if selected >= self.repos.len() {
                            self.repos.len() - 1
                        } else {
                            selected
                        };
                        self.table_state.select(Some(new_selected));
                    } else {
                        self.table_state.select(None);
                    }

                    self.needs_redraw = true;
                }
            }
        } else {
            // Normal repo: delete directory asynchronously and mark as missing
            self.deleting_repos.push(selected);
            self.needs_redraw = true;

            let tx = self.event_handler.git_tx();
            let idx = selected;

            tokio::spawn(async move {
                // Send delete progress
                let _ = tx.send(GitDataUpdate::DeleteProgress(idx));

                // Perform deletion
                let delete_result =
                    tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&repo_path)).await;

                // Send delete complete
                let _ = tx.send(GitDataUpdate::DeleteComplete(idx));

                drop(delete_result); // Ignore result
            });
        }
    }

    /// Handle cloning a missing repository
    fn handle_clone_repo(&mut self) {
        let Some(selected) = self.table_state.selected() else {
            return;
        };

        let Some(repo) = self.repos.get(selected) else {
            return;
        };

        // Only clone missing repositories
        if !repo.is_missing() {
            return;
        }

        // Mark as cloning
        self.cloning_repos.push(selected);
        self.needs_redraw = true;

        // Clone the repository in background
        let repo_clone = repo.clone();
        let tx = self.event_handler.git_tx();
        let idx = selected;

        tokio::spawn(async move {
            // Send clone progress
            let _ = tx.send(GitDataUpdate::CloneProgress(idx));

            // Perform clone
            let clone_result =
                tokio::task::spawn_blocking(move || repo_clone.clone_repository()).await;

            // Send clone complete
            let _ = tx.send(GitDataUpdate::CloneComplete(idx));

            // If successful, the UI will be updated through CloneComplete handler
            if clone_result.is_ok() {
                // Repository will be refreshed when user selects it again or on next scan
            }
        });
    }
}