goobits-repos 2.1.0

Fast Git repository management and synchronization tool
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
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//! Basic git operations and command execution

use anyhow::Result;
use dashmap::DashMap;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::time::Duration;
use tokio::process::Command;

use super::status::Status;

// Timeout constants
const GIT_OPERATION_TIMEOUT_SECS: u64 = 180; // 3 minutes per repository

// Git command arguments
const GIT_DIFF_INDEX_ARGS: &[&str] = &["diff-index", "--quiet", "HEAD", "--"];
const GIT_REMOTE_ARGS: &[&str] = &["remote"];
const GIT_REV_PARSE_HEAD_ARGS: &[&str] = &["rev-parse", "--abbrev-ref", "HEAD"];
const GIT_FETCH_ARGS: &[&str] = &["fetch", "--quiet"];
const GIT_PUSH_ARGS: &[&str] = &["push"];
const GIT_CONFIG_GET_ARGS: &[&str] = &["config", "--get"];
const GIT_ADD_ARGS: &[&str] = &["add"];
const GIT_RESTORE_STAGED_ARGS: &[&str] = &["restore", "--staged"];
const GIT_STATUS_PORCELAIN_ARGS: &[&str] = &["status", "--porcelain"];
const GIT_COMMIT_ARGS: &[&str] = &["commit", "-m"];
const GIT_DIFF_CACHED_ARGS: &[&str] = &["diff", "--cached", "--quiet"];

// Status messages
const DETACHED_HEAD_BRANCH: &str = "HEAD";
const STATUS_NO_REMOTE: &str = "no remote";
const STATUS_DETACHED_HEAD: &str = "detached HEAD";
const STATUS_NO_UPSTREAM: &str = "no tracking";
const STATUS_SYNCED: &str = "up to date";

/// Runs a git command in the specified directory with a timeout
///
/// **INTERNAL API**: This is a low-level helper function intended for internal use.
/// While marked `pub` for crate organization, this API is not stable and may change
/// without notice. External crates should not depend on this function directly.
///
/// Returns `(success, stdout, stderr)` tuple:
/// - `success`: true if git command exit code was 0
/// - `stdout`: trimmed standard output as String
/// - `stderr`: trimmed standard error as String
///
/// Includes a 180-second timeout to prevent hanging on network operations.
#[doc(hidden)]
pub async fn run_git(path: &Path, args: &[&str]) -> Result<(bool, String, String)> {
    let timeout_duration = Duration::from_secs(GIT_OPERATION_TIMEOUT_SECS);

    let result = tokio::time::timeout(
        timeout_duration,
        Command::new("git").args(args).current_dir(path).output(),
    )
    .await;

    match result {
        Ok(Ok(output)) => {
            // Optimize string allocations: only allocate if non-empty (5-10% faster)
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stdout_trimmed = stdout.trim();
            let stdout_string = if stdout_trimmed.is_empty() {
                String::new() // No heap allocation for empty strings
            } else {
                stdout_trimmed.to_string()
            };

            let stderr = String::from_utf8_lossy(&output.stderr);
            let stderr_trimmed = stderr.trim();
            let stderr_string = if stderr_trimmed.is_empty() {
                String::new() // No heap allocation for empty strings
            } else {
                stderr_trimmed.to_string()
            };

            Ok((output.status.success(), stdout_string, stderr_string))
        }
        Ok(Err(e)) => Err(e.into()),
        Err(_) => Err(anyhow::anyhow!(
            "Git operation timed out after {} seconds",
            GIT_OPERATION_TIMEOUT_SECS
        )),
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_string_allocation_optimization() {
        // Test that empty strings don't allocate unnecessarily
        let empty_bytes: Vec<u8> = vec![];
        let whitespace_bytes: Vec<u8> = vec![b' ', b'\t', b'\n'];

        // Simulate the optimization
        let empty_str = String::from_utf8_lossy(&empty_bytes);
        let empty_trimmed = empty_str.trim();
        let empty_result = if empty_trimmed.is_empty() {
            String::new()
        } else {
            empty_trimmed.to_string()
        };

        let whitespace_str = String::from_utf8_lossy(&whitespace_bytes);
        let whitespace_trimmed = whitespace_str.trim();
        let whitespace_result = if whitespace_trimmed.is_empty() {
            String::new()
        } else {
            whitespace_trimmed.to_string()
        };

        // Both should be empty strings
        assert_eq!(empty_result, "");
        assert_eq!(whitespace_result, "");

        // Test with actual content
        let content_bytes: Vec<u8> = b"  hello world  ".to_vec();
        let content_str = String::from_utf8_lossy(&content_bytes);
        let content_trimmed = content_str.trim();
        let content_result = if content_trimmed.is_empty() {
            String::new()
        } else {
            content_trimmed.to_string()
        };

        assert_eq!(content_result, "hello world");
    }

    #[test]
    fn test_repo_visibility_enum_basics() {
        use super::RepoVisibility;

        // Test enum variants exist and are comparable
        let public = RepoVisibility::Public;
        let private = RepoVisibility::Private;
        let unknown = RepoVisibility::Unknown;

        assert_eq!(public, RepoVisibility::Public);
        assert_eq!(private, RepoVisibility::Private);
        assert_eq!(unknown, RepoVisibility::Unknown);
        assert_ne!(public, private);
    }
}

/// Reads a git config value from the specified repository
/// Returns the config value if it exists, None if not found
pub(crate) async fn get_git_config(path: &Path, key: &str) -> Result<Option<String>> {
    let mut args = Vec::from(GIT_CONFIG_GET_ARGS);
    args.push(key);

    match run_git(path, &args).await {
        Ok((true, value, _)) => {
            if value.is_empty() {
                Ok(None)
            } else {
                Ok(Some(value))
            }
        }
        Ok((false, _, _)) => Ok(None), // Key not found
        Err(e) => Err(e),
    }
}

/// Sets a git config value in the specified repository (local scope)
/// Returns success status
pub(crate) async fn set_git_config(path: &Path, key: &str, value: &str) -> Result<bool> {
    let args = vec!["config", key, value];

    match run_git(path, &args).await {
        Ok((success, _, _)) => Ok(success),
        Err(e) => Err(e),
    }
}

/// Detects if an error message indicates a rate limit issue
fn is_rate_limit_error(error_msg: &str) -> bool {
    let error_lower = error_msg.to_lowercase();
    error_lower.contains("rate limit")
        || error_lower.contains("too many requests")
        || error_lower.contains("secondary rate limit")
        || (error_lower.contains("403") && error_lower.contains("github"))
}

/// Result of the fetch phase for a repository
#[derive(Clone)]
pub struct FetchResult {
    pub has_uncommitted: bool,
    pub current_branch: String,
    pub ahead_count: u32,
    pub upstream_exists: bool,
    pub status: Status,
    pub message: String,
}

/// Phase 1: Fetch and analyze repository state (read-only, can be highly concurrent)
/// Returns FetchResult with repository state after fetching
pub async fn fetch_and_analyze(path: &Path, _force_push: bool) -> FetchResult {
    use crate::core::clean_error_message;

    // Refresh the index to ensure accurate diff-index results
    let _ = run_git(path, &["update-index", "--refresh"]).await;

    // Check if directory has uncommitted changes
    let has_uncommitted = match run_git(path, GIT_DIFF_INDEX_ARGS).await {
        Ok((false, _, _)) => true,
        Ok((true, _, _)) => false,
        Err(_) => false,
    };

    // Get list of remotes
    let remotes = match run_git(path, GIT_REMOTE_ARGS).await {
        Ok((true, output, _)) => output,
        Ok((false, _, _)) | Err(_) => {
            return FetchResult {
                has_uncommitted,
                current_branch: String::new(),
                ahead_count: 0,
                upstream_exists: false,
                status: Status::NoRemote,
                message: STATUS_NO_REMOTE.to_string(),
            };
        }
    };

    if remotes.trim().is_empty() {
        return FetchResult {
            has_uncommitted,
            current_branch: String::new(),
            ahead_count: 0,
            upstream_exists: false,
            status: Status::NoRemote,
            message: STATUS_NO_REMOTE.to_string(),
        };
    }

    // Get current branch
    let current_branch = match run_git(path, GIT_REV_PARSE_HEAD_ARGS).await {
        Ok((true, branch, _)) => branch,
        Ok((false, _, _)) | Err(_) => {
            return FetchResult {
                has_uncommitted,
                current_branch: String::new(),
                ahead_count: 0,
                upstream_exists: false,
                status: Status::Skip,
                message: STATUS_DETACHED_HEAD.to_string(),
            };
        }
    };

    // Skip if in detached HEAD state
    if current_branch == DETACHED_HEAD_BRANCH {
        return FetchResult {
            has_uncommitted,
            current_branch: String::new(),
            ahead_count: 0,
            upstream_exists: false,
            status: Status::Skip,
            message: STATUS_DETACHED_HEAD.to_string(),
        };
    }

    // Fetch latest changes to ensure we have up-to-date refs
    if let Err(e) = run_git(path, GIT_FETCH_ARGS).await {
        let error_message = clean_error_message(&e.to_string());
        let final_message = if is_rate_limit_error(&error_message) {
            format!("⚠️ RATE LIMIT: {}", error_message)
        } else {
            error_message
        };
        return FetchResult {
            has_uncommitted,
            current_branch,
            ahead_count: 0,
            upstream_exists: false,
            status: Status::Error,
            message: final_message,
        };
    }

    // Check if current branch has an upstream
    let upstream_check = run_git(path, &["rev-parse", "--abbrev-ref", "@{upstream}"]).await;
    let upstream_exists = upstream_check.as_ref().is_ok_and(|result| result.0);

    if !upstream_exists {
        // Will be pushed in phase 2 (with or without force flag)
        let status = Status::NoUpstream;
        return FetchResult {
            has_uncommitted,
            current_branch,
            ahead_count: 0,
            upstream_exists: false,
            status,
            message: STATUS_NO_UPSTREAM.to_string(),
        };
    }

    // Check if local is ahead of remote
    let ahead_check = run_git(path, &["rev-list", "--count", "HEAD", "^@{upstream}"]).await;
    let ahead_count: u32 = match ahead_check {
        Ok((true, count_str, _)) => count_str.trim().parse().unwrap_or(0),
        _ => 0,
    };

    // Check if local is behind remote (to detect diverged branches)
    let behind_check = run_git(path, &["rev-list", "--count", "@{upstream}", "^HEAD"]).await;
    let behind_count: u32 = match behind_check {
        Ok((true, count_str, _)) => count_str.trim().parse().unwrap_or(0),
        _ => 0,
    };

    // Branches have diverged - both ahead and behind
    if ahead_count > 0 && behind_count > 0 {
        return FetchResult {
            has_uncommitted,
            current_branch,
            ahead_count,
            upstream_exists: true,
            status: Status::Error,
            message: format!(
                "diverged: {} ahead, {} behind (pull required before push)",
                ahead_count, behind_count
            ),
        };
    }

    if ahead_count == 0 {
        FetchResult {
            has_uncommitted,
            current_branch,
            ahead_count: 0,
            upstream_exists: true,
            status: Status::Synced,
            message: STATUS_SYNCED.to_string(),
        }
    } else {
        FetchResult {
            has_uncommitted,
            current_branch,
            ahead_count,
            upstream_exists: true,
            status: Status::Synced, // Will be pushed in phase 2
            message: format!("{} commits ahead", ahead_count),
        }
    }
}

/// Phase 2: Push repository if needed (write operation, moderate concurrency)
/// Returns (status, message, has_uncommitted_changes)
pub async fn push_if_needed(path: &Path, fetch_result: &FetchResult, force_push: bool) -> (Status, String, bool) {
    use crate::core::clean_error_message;

    // If already synced or has errors, return immediately
    if fetch_result.status != Status::Synced && fetch_result.status != Status::NoUpstream {
        return (fetch_result.status, fetch_result.message.clone(), fetch_result.has_uncommitted);
    }

    // Handle no upstream case
    if !fetch_result.upstream_exists {
        if force_push {
            // Detect the actual remote name instead of assuming "origin"
            let remote_name = match run_git(path, GIT_REMOTE_ARGS).await {
                Ok((true, remotes, _)) => {
                    remotes.lines().next().unwrap_or("origin").to_string()
                }
                _ => "origin".to_string(), // Fallback to origin if detection fails
            };

            let push_args = vec!["push", "-u", &remote_name, &fetch_result.current_branch];
            match run_git(path, &push_args).await {
                Ok((true, _, _)) => {
                    return (
                        Status::Pushed,
                        format!("set upstream ({}) & pushed", remote_name),
                        fetch_result.has_uncommitted,
                    );
                }
                Ok((false, _, stderr)) => {
                    let error_message = clean_error_message(&stderr);
                    return (Status::Error, error_message, fetch_result.has_uncommitted);
                }
                Err(e) => {
                    let error_message = clean_error_message(&e.to_string());
                    return (Status::Error, error_message, fetch_result.has_uncommitted);
                }
            }
        } else {
            return (Status::NoUpstream, STATUS_NO_UPSTREAM.to_string(), fetch_result.has_uncommitted);
        }
    }

    // If no commits ahead, already synced
    if fetch_result.ahead_count == 0 {
        return (Status::Synced, STATUS_SYNCED.to_string(), fetch_result.has_uncommitted);
    }

    // Push changes
    match run_git(path, GIT_PUSH_ARGS).await {
        Ok((true, _, _)) => {
            let commits_word = if fetch_result.ahead_count == 1 {
                "commit"
            } else {
                "commits"
            };
            (
                Status::Pushed,
                format!("{} {} pushed", fetch_result.ahead_count, commits_word),
                fetch_result.has_uncommitted,
            )
        }
        Ok((false, _, stderr)) => {
            let error_message = clean_error_message(&stderr);
            let final_message = if is_rate_limit_error(&error_message) {
                format!("⚠️ RATE LIMIT: {}", error_message)
            } else {
                error_message
            };
            (Status::Error, final_message, fetch_result.has_uncommitted)
        }
        Err(e) => {
            let error_message = clean_error_message(&e.to_string());
            let final_message = if is_rate_limit_error(&error_message) {
                format!("⚠️ RATE LIMIT: {}", error_message)
            } else {
                error_message
            };
            (Status::Error, final_message, fetch_result.has_uncommitted)
        }
    }
}

/// Stages files matching the given pattern in the specified repository
/// Returns (success, stdout, stderr)
pub async fn stage_files(path: &Path, pattern: &str) -> Result<(bool, String, String)> {
    let mut args = Vec::from(GIT_ADD_ARGS);
    args.push(pattern);
    run_git(path, &args).await
}

/// Unstages files matching the given pattern in the specified repository
/// Returns (success, stdout, stderr)
pub async fn unstage_files(path: &Path, pattern: &str) -> Result<(bool, String, String)> {
    let mut args = Vec::from(GIT_RESTORE_STAGED_ARGS);
    args.push(pattern);
    run_git(path, &args).await
}

/// Gets the staging status of the repository
/// Returns (stdout, stderr) with git status --porcelain output
pub async fn get_staging_status(path: &Path) -> Result<(String, String)> {
    match run_git(path, GIT_STATUS_PORCELAIN_ARGS).await {
        Ok((_, stdout, stderr)) => Ok((stdout, stderr)),
        Err(e) => Err(e),
    }
}

/// Checks if repository has staged changes ready to commit
/// Returns true if there are staged changes, false if staging area is clean
pub async fn has_staged_changes(path: &Path) -> Result<bool> {
    match run_git(path, GIT_DIFF_CACHED_ARGS).await {
        Ok((success, _, _)) => Ok(!success), // Command succeeds when NO changes (exit 0), so invert
        Err(e) => Err(e),
    }
}

/// Commits staged changes with the given message
/// Returns (success, stdout, stderr)
pub async fn commit_changes(
    path: &Path,
    message: &str,
    allow_empty: bool,
) -> Result<(bool, String, String)> {
    let mut args = Vec::from(GIT_COMMIT_ARGS);
    args.push(message);

    if allow_empty {
        args.insert(1, "--allow-empty"); // Insert after "commit" but before "-m"
    }

    run_git(path, &args).await
}

/// Checks if a repository has uncommitted changes (tracked files only)
///
/// This checks only tracked files using `git diff-index --quiet HEAD`.
/// Returns true if there are uncommitted changes, false otherwise.
///
/// Note: There are synchronous versions in subrepo/{mod.rs, sync.rs} for use
/// in non-async contexts. The sync.rs version is more conservative and includes
/// untracked files.
pub async fn has_uncommitted_changes(path: &Path) -> bool {
    // Refresh the index to ensure accurate diff-index results
    let _ = run_git(path, &["update-index", "--refresh"]).await;

    // Check if directory has uncommitted changes
    match run_git(path, GIT_DIFF_INDEX_ARGS).await {
        Ok((false, _, _)) => true, // Command failed means there are changes
        Ok((true, _, _)) => false, // Command succeeded means no changes
        Err(_) => false,           // Error checking, assume no changes
    }
}

/// Creates a git tag and pushes it to the remote
/// Returns (success, message)
pub async fn create_and_push_tag(path: &Path, tag_name: &str) -> (bool, String) {
    // Create the tag
    let tag_result = run_git(path, &["tag", tag_name]).await;

    if let Err(e) = tag_result {
        return (false, format!("failed to create tag: {}", e));
    }

    let (success, _, stderr) = tag_result.unwrap();
    if !success {
        // Tag might already exist
        if stderr.contains("already exists") {
            return (true, "tag already exists".to_string());
        }
        return (false, format!("failed to create tag: {}", stderr));
    }

    // Push the tag
    let push_result = run_git(path, &["push", "origin", tag_name]).await;

    match push_result {
        Ok((true, _, _)) => (true, format!("tagged & pushed {}", tag_name)),
        Ok((false, _, stderr)) => {
            // Tag was created but push failed - that's okay, we'll leave the local tag
            (true, format!("tagged {} (push failed: {})", tag_name, stderr.lines().next().unwrap_or("unknown error")))
        }
        Err(e) => {
            (true, format!("tagged {} (push failed: {})", tag_name, e))
        }
    }
}

/// Result of the fetch phase for pull operation
#[derive(Clone)]
pub struct PullFetchResult {
    pub has_uncommitted: bool,
    pub behind_count: u32,
    pub status: Status,
    pub message: String,
}

/// Phase 1: Fetch and analyze repository state for pull (read-only, can be highly concurrent)
/// Returns PullFetchResult with repository state after fetching
pub async fn fetch_and_analyze_for_pull(path: &Path) -> PullFetchResult {
    use crate::core::clean_error_message;

    // Refresh the index to ensure accurate diff-index results
    let _ = run_git(path, &["update-index", "--refresh"]).await;

    // Check if directory has uncommitted changes
    let has_uncommitted = match run_git(path, GIT_DIFF_INDEX_ARGS).await {
        Ok((false, _, _)) => true,
        Ok((true, _, _)) => false,
        Err(_) => false,
    };

    // Get list of remotes
    let remotes = match run_git(path, GIT_REMOTE_ARGS).await {
        Ok((true, output, _)) => output,
        Ok((false, _, _)) | Err(_) => {
            return PullFetchResult {
                has_uncommitted,
                behind_count: 0,
                status: Status::NoRemote,
                message: STATUS_NO_REMOTE.to_string(),
            };
        }
    };

    if remotes.trim().is_empty() {
        return PullFetchResult {
            has_uncommitted,
            behind_count: 0,
            status: Status::NoRemote,
            message: STATUS_NO_REMOTE.to_string(),
        };
    }

    // Get current branch
    let current_branch = match run_git(path, GIT_REV_PARSE_HEAD_ARGS).await {
        Ok((true, branch, _)) => branch,
        Ok((false, _, _)) | Err(_) => {
            return PullFetchResult {
                has_uncommitted,
                behind_count: 0,
                status: Status::Skip,
                message: STATUS_DETACHED_HEAD.to_string(),
            };
        }
    };

    // Skip if in detached HEAD state
    if current_branch == DETACHED_HEAD_BRANCH {
        return PullFetchResult {
            has_uncommitted,
            behind_count: 0,
            status: Status::Skip,
            message: STATUS_DETACHED_HEAD.to_string(),
        };
    }

    // Fetch latest changes to ensure we have up-to-date refs
    if let Err(e) = run_git(path, GIT_FETCH_ARGS).await {
        let error_message = clean_error_message(&e.to_string());
        let final_message = if is_rate_limit_error(&error_message) {
            format!("⚠️ RATE LIMIT: {}", error_message)
        } else {
            error_message
        };
        return PullFetchResult {
            has_uncommitted,
            behind_count: 0,
            status: Status::Error,
            message: final_message,
        };
    }

    // Check if current branch has an upstream
    let upstream_check = run_git(path, &["rev-parse", "--abbrev-ref", "@{upstream}"]).await;
    let upstream_exists = upstream_check.as_ref().is_ok_and(|result| result.0);

    if !upstream_exists {
        return PullFetchResult {
            has_uncommitted,
            behind_count: 0,
            status: Status::NoUpstream,
            message: STATUS_NO_UPSTREAM.to_string(),
        };
    }

    // Check if local is behind remote
    let behind_check = run_git(path, &["rev-list", "--count", "@{upstream}", "^HEAD"]).await;
    let behind_count: u32 = match behind_check {
        Ok((true, count_str, _)) => count_str.trim().parse().unwrap_or(0),
        _ => 0,
    };

    // Check if local is ahead of remote (to detect diverged branches)
    let ahead_check = run_git(path, &["rev-list", "--count", "HEAD", "^@{upstream}"]).await;
    let ahead_count: u32 = match ahead_check {
        Ok((true, count_str, _)) => count_str.trim().parse().unwrap_or(0),
        _ => 0,
    };

    // Branches have diverged - both ahead and behind
    if ahead_count > 0 && behind_count > 0 {
        return PullFetchResult {
            has_uncommitted,
            behind_count,
            status: Status::PullError,
            message: format!(
                "diverged: {} ahead, {} behind (manual merge required)",
                ahead_count, behind_count
            ),
        };
    }

    if behind_count == 0 {
        PullFetchResult {
            has_uncommitted,
            behind_count: 0,
            status: Status::Synced,
            message: STATUS_SYNCED.to_string(),
        }
    } else {
        PullFetchResult {
            has_uncommitted,
            behind_count,
            status: Status::Synced, // Will be pulled in phase 2
            message: format!("{} commits behind", behind_count),
        }
    }
}

/// Phase 2: Pull repository if needed (write operation, moderate concurrency)
/// Returns (status, message, has_uncommitted_changes)
pub async fn pull_if_needed(
    path: &Path,
    fetch_result: &PullFetchResult,
    use_rebase: bool,
) -> (Status, String, bool) {
    use crate::core::clean_error_message;

    // If already synced or has errors, return immediately
    if fetch_result.status != Status::Synced {
        return (
            fetch_result.status,
            fetch_result.message.clone(),
            fetch_result.has_uncommitted,
        );
    }

    // If no commits behind, already synced
    if fetch_result.behind_count == 0 {
        return (
            Status::Synced,
            STATUS_SYNCED.to_string(),
            fetch_result.has_uncommitted,
        );
    }

    // Pull changes with appropriate strategy
    let pull_args = if use_rebase {
        // Use --autostash to safely stash uncommitted changes during rebase
        vec!["pull", "--rebase", "--autostash"]
    } else {
        vec!["pull", "--ff-only"]
    };

    match run_git(path, &pull_args).await {
        Ok((true, _, _)) => {
            let commits_word = if fetch_result.behind_count == 1 {
                "commit"
            } else {
                "commits"
            };
            (
                Status::Pulled,
                format!("{} {} pulled", fetch_result.behind_count, commits_word),
                fetch_result.has_uncommitted,
            )
        }
        Ok((false, _, stderr)) => {
            let error_message = clean_error_message(&stderr);

            // Check for common pull errors
            let final_message = if error_message.to_lowercase().contains("conflict") {
                format!("merge conflict: {}", error_message)
            } else if error_message.to_lowercase().contains("would be overwritten") {
                format!("uncommitted changes conflict: {}", error_message)
            } else if is_rate_limit_error(&error_message) {
                format!("⚠️ RATE LIMIT: {}", error_message)
            } else {
                error_message
            };
            (Status::PullError, final_message, fetch_result.has_uncommitted)
        }
        Err(e) => {
            let error_message = clean_error_message(&e.to_string());
            let final_message = if is_rate_limit_error(&error_message) {
                format!("⚠️ RATE LIMIT: {}", error_message)
            } else {
                error_message
            };
            (Status::PullError, final_message, fetch_result.has_uncommitted)
        }
    }
}

/// Repository visibility status
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RepoVisibility {
    Public,
    Private,
    Unknown,
}

// In-memory cache for repository visibility to avoid repeated gh CLI calls
// Using DashMap for lock-free concurrent access
// Cache is cleared when the program exits
static VISIBILITY_CACHE: OnceLock<DashMap<PathBuf, RepoVisibility>> = OnceLock::new();

/// Gets or initializes the visibility cache
fn get_visibility_cache() -> &'static DashMap<PathBuf, RepoVisibility> {
    VISIBILITY_CACHE.get_or_init(|| DashMap::new())
}

/// Detects repository visibility using gh CLI with in-memory caching
/// Returns RepoVisibility (defaults to Unknown if gh is not available or repo is not on GitHub)
/// Results are cached in-memory for the lifetime of the program to avoid repeated gh CLI calls
pub async fn get_repo_visibility(path: &Path) -> RepoVisibility {
    let path_buf = path.to_path_buf();
    let cache = get_visibility_cache();

    // Check cache first - lock-free read
    if let Some(visibility) = cache.get(&path_buf) {
        return *visibility;
    }

    // Not in cache, perform the expensive check
    let visibility = get_repo_visibility_uncached(path).await;

    // Store in cache - lock-free insert
    cache.insert(path_buf, visibility);

    visibility
}

/// Internal function to check visibility without caching
async fn get_repo_visibility_uncached(path: &Path) -> RepoVisibility {
    // First check if this is a GitHub repository by looking at the remote URL
    let remote_url = match run_git(path, &["remote", "get-url", "origin"]).await {
        Ok((true, url, _)) => url,
        _ => return RepoVisibility::Unknown,
    };

    // Check if it's a GitHub URL
    if !remote_url.contains("github.com") {
        return RepoVisibility::Unknown;
    }

    // Use gh CLI to check repository visibility
    // gh repo view --json isPrivate returns {"isPrivate": true/false}
    let timeout_duration = Duration::from_secs(10); // Shorter timeout for API calls

    let result = tokio::time::timeout(
        timeout_duration,
        Command::new("gh")
            .args(["repo", "view", "--json", "isPrivate", "-q", ".isPrivate"])
            .current_dir(path)
            .output(),
    )
    .await;

    match result {
        Ok(Ok(output)) if output.status.success() => {
            let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
            match stdout.as_str() {
                "true" => RepoVisibility::Private,
                "false" => RepoVisibility::Public,
                _ => RepoVisibility::Unknown,
            }
        }
        _ => RepoVisibility::Unknown, // gh CLI not available or command failed
    }
}