agpm-cli 0.4.14

AGent Package Manager - A Git-based package manager for coding agents
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
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
//! Type-safe Git command builder for consistent command execution
//!
//! This module provides a fluent API for building and executing Git commands,
//! eliminating duplication and ensuring consistent error handling across the codebase.

use anyhow::{Context, Result};
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::timeout;

use crate::core::AgpmError;
use crate::utils::platform::get_git_command;

/// Type-safe builder for constructing and executing Git commands with consistent error handling.
///
/// This builder provides a fluent API for Git command construction that ensures
/// consistent behavior across AGPM's Git operations. It handles platform-specific
/// differences, timeout management, error context, and output capture in a unified way.
///
/// # Features
///
/// - **Fluent API**: Chainable methods for building commands
/// - **Error Context**: Automatic error message enhancement with context
/// - **Timeout Management**: Configurable timeouts with sensible defaults
/// - **Platform Independence**: Works across Windows, macOS, and Linux
/// - **Output Capture**: Flexible handling of command output and errors
/// - **Environment Variables**: Support for Git-specific environment settings
///
/// # Examples
///
/// ```rust,ignore
/// use agpm_cli::git::command_builder::GitCommand;
/// use std::path::Path;
///
/// # async fn example() -> anyhow::Result<()> {
/// // Simple command with output capture
/// let output = GitCommand::new()
///     .args(["status", "--porcelain"])
///     .current_dir(Path::new("/path/to/repo"))
///     .execute()
///     .await?;
///
/// // Command with timeout and error context
/// let result = GitCommand::new()
///     .args(["clone", "https://github.com/example/repo.git"])
///     .timeout(std::time::Duration::from_secs(60))
///     .with_context("Cloning community repository")
///     .execute_success()
///     .await?;
///
/// // Interactive command (no output capture)
/// GitCommand::new()
///     .args(["merge", "--interactive"])
///     .inherit_stdio()
///     .execute_success()
///     .await?;
/// # Ok(())
/// # }
/// ```
///
/// # Default Configuration
///
/// New commands are created with sensible defaults:
/// - **Timeout**: 5 minutes (300 seconds)
/// - **Output capture**: Enabled
/// - **Working directory**: Current process directory
/// - **Environment**: Inherits from parent process
///
/// # Platform Compatibility
///
/// The builder automatically handles platform-specific Git command location:
/// - **Windows**: Uses `git.exe` from PATH or common installation directories
/// - **Unix-like**: Uses `git` from PATH
/// - **Error handling**: Provides clear messages if Git is not installed
pub struct GitCommand {
    /// Command arguments to pass to Git (e.g., ["clone", "url", "path"])
    args: Vec<String>,

    /// Working directory for command execution (defaults to current directory)
    current_dir: Option<std::path::PathBuf>,

    /// Whether to capture command output (true) or inherit stdio (false)
    capture_output: bool,

    /// Environment variables to set for the Git process
    env_vars: Vec<(String, String)>,

    /// Maximum duration to wait for command completion (None = no timeout)
    timeout_duration: Option<Duration>,

    /// Optional context string for enhanced error messages
    context: Option<String>,

    /// For clone commands, store the URL for better error messages
    clone_url: Option<String>,
}

impl Default for GitCommand {
    fn default() -> Self {
        Self {
            args: Vec::new(),
            clone_url: None,
            current_dir: None,
            capture_output: true,
            env_vars: Vec::new(),
            // Default timeout of 5 minutes for most git operations
            timeout_duration: Some(Duration::from_secs(300)),
            context: None,
        }
    }
}

impl GitCommand {
    /// Creates a new Git command builder with default settings.
    ///
    /// The new builder is initialized with:
    /// - Empty argument list
    /// - Current process directory as working directory
    /// - Output capture enabled
    /// - 5-minute timeout
    /// - No additional environment variables
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// let cmd = GitCommand::new()
    ///     .args(["status", "--short"])
    ///     .current_dir("/path/to/repo");
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the working directory for Git command execution.
    ///
    /// The command will be executed in the specified directory, which should
    /// typically be a Git repository root or subdirectory. If not set, the
    /// command executes in the current process working directory.
    ///
    /// # Arguments
    ///
    /// * `dir` - Path to the directory where the Git command should run
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use agpm_cli::git::command_builder::GitCommand;
    /// use std::path::Path;
    ///
    /// let cmd = GitCommand::new()
    ///     .current_dir("/path/to/repository")
    ///     .args(["log", "--oneline"]);
    ///
    /// // Can also use Path references
    /// let repo_path = Path::new("/path/to/repo");
    /// let cmd2 = GitCommand::new()
    ///     .current_dir(repo_path)
    ///     .args(["status"]);
    /// ```
    pub fn current_dir(mut self, dir: impl AsRef<Path>) -> Self {
        self.current_dir = Some(dir.as_ref().to_path_buf());
        self
    }

    /// Adds a single argument to the Git command.
    ///
    /// Arguments are passed to Git in the order they are added. This method
    /// is useful when building commands dynamically or when you need to add
    /// arguments conditionally.
    ///
    /// # Arguments
    ///
    /// * `arg` - The argument to add (will be converted to String)
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// let cmd = GitCommand::new()
    ///     .arg("clone")
    ///     .arg("--depth")
    ///     .arg("1")
    ///     .arg("https://github.com/example/repo.git");
    /// ```
    ///
    /// # Note
    ///
    /// For adding multiple arguments at once, consider using [`args`](Self::args)
    /// which is more efficient for static argument lists.
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.args.push(arg.into());
        self
    }

    /// Adds multiple arguments to the Git command.
    ///
    /// This is the preferred method for adding multiple arguments at once,
    /// as it's more efficient than multiple calls to [`arg`](Self::arg).
    /// Arguments can be provided as any iterable of string-like types.
    ///
    /// # Arguments
    ///
    /// * `args` - An iterable of arguments to add to the command
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// // Using array literals
    /// let cmd = GitCommand::new()
    ///     .args(["clone", "--recursive", "https://github.com/example/repo.git"]);
    ///
    /// // Using vectors
    /// let clone_args = vec!["clone", "--depth", "1"];
    /// let cmd2 = GitCommand::new().args(clone_args);
    ///
    /// // Mixing with other methods
    /// let cmd3 = GitCommand::new()
    ///     .args(["fetch", "origin"])
    ///     .arg("--prune");
    /// ```
    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.args.extend(args.into_iter().map(Into::into));
        self
    }

    /// Adds an environment variable for the Git command execution.
    ///
    /// Environment variables are useful for configuring Git behavior without
    /// modifying global Git configuration. Common use cases include setting
    /// credentials, configuration overrides, and locale settings.
    ///
    /// # Arguments
    ///
    /// * `key` - Environment variable name
    /// * `value` - Environment variable value
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// // Set Git configuration for this command only
    /// let cmd = GitCommand::new()
    ///     .args(["clone", "https://github.com/example/repo.git"])
    ///     .env("GIT_CONFIG_GLOBAL", "/dev/null")  // Ignore global config
    ///     .env("GIT_CONFIG_SYSTEM", "/dev/null"); // Ignore system config
    ///
    /// // Set locale for consistent output parsing
    /// let cmd2 = GitCommand::new()
    ///     .args(["log", "--oneline"])
    ///     .env("LC_ALL", "C");
    /// ```
    ///
    /// # Common Environment Variables
    ///
    /// - `GIT_DIR`: Override Git directory location
    /// - `GIT_WORK_TREE`: Override working tree location
    /// - `GIT_CONFIG_*`: Override configuration file locations
    /// - `LC_ALL`: Set locale for consistent output parsing
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.env_vars.push((key.into(), value.into()));
        self
    }

    /// Disables output capture, allowing the command to inherit parent stdio.
    ///
    /// By default, Git commands have their output captured for processing.
    /// This method disables capture, allowing the command to write directly
    /// to the terminal. This is useful for interactive commands or when you
    /// want to show Git output directly to the user.
    ///
    /// # Use Cases
    ///
    /// - Interactive Git commands (merge conflicts, rebase, etc.)
    /// - Commands where you want real-time output streaming
    /// - Debugging Git operations by seeing output immediately
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// // Interactive merge that may require user input
    /// # async fn example() -> anyhow::Result<()> {
    /// GitCommand::new()
    ///     .args(["merge", "feature-branch"])
    ///     .inherit_stdio()  // Allow user interaction
    ///     .execute_success()
    ///     .await?;
    ///
    /// // Show clone progress to user
    /// GitCommand::new()
    ///     .args(["clone", "--progress", "https://github.com/large/repo.git"])
    ///     .inherit_stdio()  // Show progress bars
    ///     .execute_success()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Note
    ///
    /// When stdio is inherited, you cannot use [`execute`](Self::execute) to
    /// capture output. Use [`execute_success`](Self::execute_success) instead.
    pub const fn inherit_stdio(mut self) -> Self {
        self.capture_output = false;
        self
    }

    /// Set a custom timeout for the command (None for no timeout)
    pub const fn with_timeout(mut self, duration: Option<Duration>) -> Self {
        self.timeout_duration = duration;
        self
    }

    /// Set a context for logging (e.g., dependency name)
    ///
    /// The context is included in debug log messages to help distinguish between
    /// concurrent operations when processing multiple dependencies in parallel.
    /// This is especially useful when using worktrees for parallel Git operations.
    ///
    /// # Arguments
    ///
    /// * `context` - A string identifier for this operation (typically dependency name)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let output = GitCommand::fetch()
    ///     .with_context("my-dependency")
    ///     .current_dir("/path/to/repo")
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Logging Output
    ///
    /// With context, log messages will include the context identifier:
    /// ```text
    /// (my-dependency) Executing command: git -C /path/to/repo fetch --all --tags
    /// (my-dependency) Command completed successfully
    /// ```
    pub fn with_context(mut self, context: impl Into<String>) -> Self {
        self.context = Some(context.into());
        self
    }

    /// Execute the command and return the output
    pub async fn execute(self) -> Result<GitCommandOutput> {
        let start = std::time::Instant::now();
        let git_command = get_git_command();
        let mut cmd = Command::new(git_command);

        // Always set git's CWD to system temp directory to prevent issues when
        // test directories are deleted. Git may access CWD even with -C flag.
        cmd.current_dir(std::env::temp_dir());

        // Build the full arguments list including -C flag if needed
        let mut full_args = Vec::new();
        if let Some(ref dir) = self.current_dir {
            // Use -C flag to specify working directory
            // This makes git operations independent of the process's current directory
            full_args.push("-C".to_string());
            // Use the path as-is to avoid symlink resolution issues on macOS
            // (e.g., /var vs /private/var)
            full_args.push(dir.display().to_string());
        }
        full_args.extend(self.args.clone());

        cmd.args(&full_args);

        if let Some(ref ctx) = self.context {
            tracing::debug!(
                target: "git",
                "({}) Executing command: {} {}",
                ctx,
                git_command,
                full_args.join(" ")
            );
        } else {
            tracing::debug!(
                target: "git",
                "Executing command: {} {}",
                git_command,
                full_args.join(" ")
            );
        }

        for (key, value) in &self.env_vars {
            tracing::trace!(target: "git", "Setting env var: {}={}", key, value);
            cmd.env(key, value);
        }

        if self.capture_output {
            cmd.stdout(Stdio::piped());
            cmd.stderr(Stdio::piped());
        } else {
            cmd.stdout(Stdio::inherit());
            cmd.stderr(Stdio::inherit());
        }

        // CRITICAL: Always close stdin to prevent Git from hanging on credential prompts.
        // In CI environments (non-TTY), Git may wait indefinitely for input if stdin is
        // inherited. This is the root cause of CI test hangs.
        cmd.stdin(Stdio::null());

        // Disable Git terminal prompts to prevent hanging on authentication requests.
        // This ensures Git fails fast instead of waiting for user input.
        cmd.env("GIT_TERMINAL_PROMPT", "0");

        // CRITICAL: kill_on_drop ensures the child process is killed when the future is
        // dropped (e.g., on timeout). Without this, timed-out git processes become zombies
        // that hold file locks and cause deadlocks in concurrent operations.
        cmd.kill_on_drop(true);

        // Use spawn() + wait_with_output() instead of output() to ensure kill_on_drop works.
        // The output() method doesn't guarantee child process cleanup on future cancellation.
        let child = cmd.spawn().context(format!("Failed to spawn git {}", full_args.join(" ")))?;
        let output_future = child.wait_with_output();

        let output = if let Some(duration) = self.timeout_duration {
            if let Ok(result) = timeout(duration, output_future).await {
                tracing::trace!(target: "git", "Command completed within timeout");
                result.context(format!("Failed to execute git {}", full_args.join(" ")))?
            } else {
                tracing::warn!(
                    target: "git",
                    "Command timed out after {} seconds: git {}",
                    duration.as_secs(),
                    full_args.join(" ")
                );
                // Extract the actual git operation (skip -C and path if present)
                let git_operation =
                    if full_args.first() == Some(&"-C".to_string()) && full_args.len() > 2 {
                        full_args.get(2).cloned().unwrap_or_else(|| "unknown".to_string())
                    } else {
                        full_args.first().cloned().unwrap_or_else(|| "unknown".to_string())
                    };
                return Err(AgpmError::GitCommandError {
                    operation: git_operation,
                    stderr: format!(
                        "Git command timed out after {} seconds. This may indicate:\n\
                        - Network connectivity issues\n\
                        - Authentication prompts waiting for input\n\
                        - Large repository operations taking too long\n\
                        Try running the command manually: git {}",
                        duration.as_secs(),
                        full_args.join(" ")
                    ),
                }
                .into());
            }
        } else {
            tracing::trace!(target: "git", "Executing command without timeout");
            output_future.await.context(format!("Failed to execute git {}", full_args.join(" ")))?
        };

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);

            tracing::debug!(
                target: "git",
                "Command failed with exit code: {:?}",
                output.status.code()
            );
            if !stderr.is_empty() {
                tracing::debug!(target: "git", "Error: {}", stderr);
            }
            if !stdout.is_empty() && stderr.is_empty() {
                tracing::debug!(target: "git", "Error output: {}", stdout);
            }

            // Provide context-specific error messages
            // Skip -C flag arguments when checking command type
            let args_start = if full_args.first() == Some(&"-C".to_string()) && full_args.len() > 2
            {
                2
            } else {
                0
            };
            let effective_args = &full_args[args_start..];

            let error = if effective_args.first().is_some_and(|arg| arg == "clone") {
                // Use the URL we stored when building the command, not by parsing args
                let url = self.clone_url.unwrap_or_else(|| "unknown".to_string());
                AgpmError::GitCloneFailed {
                    url,
                    reason: stderr.to_string(),
                }
            } else if effective_args.first().is_some_and(|arg| arg == "checkout") {
                let reference = effective_args.get(1).cloned().unwrap_or_default();
                AgpmError::GitCheckoutFailed {
                    reference,
                    reason: stderr.to_string(),
                }
            } else if effective_args.first().is_some_and(|arg| arg == "worktree") {
                let subcommand = effective_args.get(1).cloned().unwrap_or_default();
                AgpmError::GitCommandError {
                    operation: format!("worktree {subcommand}"),
                    stderr: if stderr.is_empty() {
                        stdout.to_string()
                    } else {
                        stderr.to_string()
                    },
                }
            } else {
                AgpmError::GitCommandError {
                    operation: effective_args
                        .first()
                        .cloned()
                        .unwrap_or_else(|| "unknown".to_string()),
                    stderr: stderr.to_string(),
                }
            };

            return Err(error.into());
        }

        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();

        // Log stdout/stderr without prefixes if they're not empty
        if !stdout.is_empty() {
            if let Some(ref ctx) = self.context {
                tracing::debug!(target: "git", "({}) {}", ctx, stdout.trim());
            } else {
                tracing::debug!(target: "git", "{}", stdout.trim());
            }
        }
        if !stderr.is_empty() {
            if let Some(ref ctx) = self.context {
                tracing::debug!(target: "git", "({}) {}", ctx, stderr.trim());
            } else {
                tracing::debug!(target: "git", "{}", stderr.trim());
            }
        }

        let elapsed = start.elapsed();

        // Log performance for expensive operations
        if elapsed.as_secs() > 1 {
            let operation = if full_args.first() == Some(&"-C".to_string()) && full_args.len() > 2 {
                full_args.get(2).cloned().unwrap_or_else(|| "unknown".to_string())
            } else {
                full_args.first().cloned().unwrap_or_else(|| "unknown".to_string())
            };

            if let Some(ref ctx) = self.context {
                tracing::info!(target: "git::perf", "({}) Git {} took {:.2}s", ctx, operation, elapsed.as_secs_f64());
            } else {
                tracing::info!(target: "git::perf", "Git {} took {:.2}s", operation, elapsed.as_secs_f64());
            }
        } else if elapsed.as_millis() > 100 {
            // Log debug for moderately slow operations
            let operation = if full_args.first() == Some(&"-C".to_string()) && full_args.len() > 2 {
                full_args.get(2).cloned().unwrap_or_else(|| "unknown".to_string())
            } else {
                full_args.first().cloned().unwrap_or_else(|| "unknown".to_string())
            };

            if let Some(ref ctx) = self.context {
                tracing::debug!(target: "git::perf", "({}) Git {} took {}ms", ctx, operation, elapsed.as_millis());
            } else {
                tracing::debug!(target: "git::perf", "Git {} took {}ms", operation, elapsed.as_millis());
            }
        }

        Ok(GitCommandOutput {
            stdout,
            stderr,
        })
    }

    /// Execute the command and return only stdout as a trimmed string
    pub async fn execute_stdout(self) -> Result<String> {
        let output = self.execute().await?;
        Ok(output.stdout.trim().to_string())
    }

    /// Execute a Git command with stdin input.
    ///
    /// This method is designed for commands that accept input via stdin, such as
    /// `git rev-parse --stdin` for batch SHA resolution. It reduces process spawn
    /// overhead by allowing multiple refs to be resolved in a single Git process.
    ///
    /// # Arguments
    ///
    /// * `stdin_data` - The data to write to the command's stdin
    ///
    /// # Returns
    ///
    /// The command output wrapped in `GitCommandOutput`
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// // Resolve multiple refs in a single git process
    /// let refs = "v1.0.0\nmain\norigin/develop";
    /// let output = GitCommand::new()
    ///     .args(["rev-parse", "--stdin"])
    ///     .current_dir("/path/to/repo")
    ///     .execute_with_stdin(refs)
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn execute_with_stdin(self, stdin_data: &str) -> Result<GitCommandOutput> {
        use tokio::io::AsyncWriteExt;

        let start = std::time::Instant::now();
        let git_command = get_git_command();
        let mut cmd = Command::new(git_command);

        // Always set git's CWD to system temp directory to prevent issues when
        // test directories are deleted. Git may access CWD even with -C flag.
        cmd.current_dir(std::env::temp_dir());

        // Build the full arguments list including -C flag if needed
        let mut full_args = Vec::new();
        if let Some(ref dir) = self.current_dir {
            full_args.push("-C".to_string());
            full_args.push(dir.display().to_string());
        }
        full_args.extend(self.args.clone());

        cmd.args(&full_args);

        if let Some(ref ctx) = self.context {
            tracing::debug!(
                target: "git",
                "({}) Executing command with stdin: {} {}",
                ctx,
                git_command,
                full_args.join(" ")
            );
        } else {
            tracing::debug!(
                target: "git",
                "Executing command with stdin: {} {}",
                git_command,
                full_args.join(" ")
            );
        }

        for (key, value) in &self.env_vars {
            tracing::trace!(target: "git", "Setting env var: {}={}", key, value);
            cmd.env(key, value);
        }

        // Set up piped stdin for writing
        cmd.stdin(Stdio::piped());
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        // Disable Git terminal prompts
        cmd.env("GIT_TERMINAL_PROMPT", "0");

        // kill_on_drop ensures the child process is killed on timeout
        cmd.kill_on_drop(true);

        let mut child =
            cmd.spawn().context(format!("Failed to spawn git {}", full_args.join(" ")))?;

        // Write to stdin and close it
        if let Some(mut stdin) = child.stdin.take() {
            stdin.write_all(stdin_data.as_bytes()).await.context("Failed to write to git stdin")?;
            // stdin is dropped here, closing the pipe
        }

        let output_future = child.wait_with_output();

        let output = if let Some(duration) = self.timeout_duration {
            if let Ok(result) = timeout(duration, output_future).await {
                result.context(format!("Failed to execute git {}", full_args.join(" ")))?
            } else {
                let git_operation =
                    if full_args.first() == Some(&"-C".to_string()) && full_args.len() > 2 {
                        full_args.get(2).cloned().unwrap_or_else(|| "unknown".to_string())
                    } else {
                        full_args.first().cloned().unwrap_or_else(|| "unknown".to_string())
                    };
                return Err(AgpmError::GitCommandError {
                    operation: git_operation,
                    stderr: format!("Git command timed out after {} seconds", duration.as_secs()),
                }
                .into());
            }
        } else {
            output_future.await.context(format!("Failed to execute git {}", full_args.join(" ")))?
        };

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            let stdout = String::from_utf8_lossy(&output.stdout);

            tracing::debug!(
                target: "git",
                "Command failed with exit code: {:?}",
                output.status.code()
            );

            let args_start = if full_args.first() == Some(&"-C".to_string()) && full_args.len() > 2
            {
                2
            } else {
                0
            };
            let effective_args = &full_args[args_start..];

            return Err(AgpmError::GitCommandError {
                operation: effective_args.first().cloned().unwrap_or_else(|| "unknown".to_string()),
                stderr: if stderr.is_empty() {
                    stdout.to_string()
                } else {
                    stderr.to_string()
                },
            }
            .into());
        }

        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();

        let elapsed = start.elapsed();
        if elapsed.as_secs() > 1 {
            let operation = if full_args.first() == Some(&"-C".to_string()) && full_args.len() > 2 {
                full_args.get(2).cloned().unwrap_or_else(|| "unknown".to_string())
            } else {
                full_args.first().cloned().unwrap_or_else(|| "unknown".to_string())
            };

            if let Some(ref ctx) = self.context {
                tracing::info!(target: "git::perf", "({}) Git {} with stdin took {:.2}s", ctx, operation, elapsed.as_secs_f64());
            } else {
                tracing::info!(target: "git::perf", "Git {} with stdin took {:.2}s", operation, elapsed.as_secs_f64());
            }
        }

        Ok(GitCommandOutput {
            stdout,
            stderr,
        })
    }

    /// Execute the command and check for success without capturing output
    pub async fn execute_success(self) -> Result<()> {
        self.execute().await?;
        Ok(())
    }
}

/// Output from a Git command
pub struct GitCommandOutput {
    /// Standard output from the Git command
    pub stdout: String,
    /// Standard error output from the Git command
    pub stderr: String,
}

// Convenience builders for common Git operations

impl GitCommand {
    /// Create a clone command
    pub fn clone(url: &str, target: impl AsRef<Path>) -> Self {
        let mut cmd = Self::new();
        cmd.args.push("clone".to_string());
        cmd.args.push("--progress".to_string());
        cmd.args.push("--filter=blob:none".to_string());
        cmd.args.push("--recurse-submodules".to_string());
        cmd.args.push(url.to_string());
        cmd.args.push(target.as_ref().display().to_string());
        cmd.clone_url = Some(url.to_string());
        cmd
    }

    /// Create a clone command with specific depth
    ///
    /// Create a fetch command
    pub fn fetch() -> Self {
        // Use --all to fetch from all remotes and --tags to get tags
        // For bare repositories, we need to ensure remote tracking branches are created
        Self::new().args(["fetch", "--all", "--tags", "--force"])
    }

    /// Create a checkout command
    pub fn checkout(ref_name: &str) -> Self {
        Self::new().args(["checkout", ref_name])
    }

    /// Create a checkout command that forces branch creation/update
    pub fn checkout_branch(branch_name: &str, remote_ref: &str) -> Self {
        Self::new().args(["checkout", "-B", branch_name, remote_ref])
    }

    /// Create a reset command
    pub fn reset_hard() -> Self {
        Self::new().args(["reset", "--hard", "HEAD"])
    }

    /// Create a tag list command
    pub fn list_tags() -> Self {
        Self::new().args(["tag", "-l", "--sort=version:refname"])
    }

    /// Create a branch list command
    pub fn list_branches() -> Self {
        Self::new().args(["branch", "-r"])
    }

    /// Create a rev-parse command
    pub fn rev_parse(ref_name: &str) -> Self {
        Self::new().args(["rev-parse", ref_name])
    }

    /// Create a command to get the current commit hash
    pub fn current_commit() -> Self {
        Self::new().args(["rev-parse", "HEAD"])
    }

    /// Create a command to get the remote URL
    pub fn remote_url() -> Self {
        Self::new().args(["remote", "get-url", "origin"])
    }

    /// Create a command to set the remote URL
    pub fn set_remote_url(url: &str) -> Self {
        Self::new().args(["remote", "set-url", "origin", url])
    }

    /// Create a ls-remote command for repository verification
    pub fn ls_remote(url: &str) -> Self {
        Self::new().args(["ls-remote", "--heads", url])
    }

    /// Create a command to verify a reference exists
    pub fn verify_ref(ref_name: &str) -> Self {
        Self::new().args(["rev-parse", "--verify", ref_name])
    }

    /// Create a command to get the current branch
    pub fn current_branch() -> Self {
        Self::new().args(["branch", "--show-current"])
    }

    /// Create an init command
    pub fn init() -> Self {
        Self::new().arg("init")
    }

    /// Create an add command
    pub fn add(pathspec: &str) -> Self {
        Self::new().args(["add", pathspec])
    }

    /// Create a commit command
    pub fn commit(message: &str) -> Self {
        Self::new().args(["commit", "-m", message])
    }

    /// Create a push command
    pub fn push() -> Self {
        Self::new().arg("push")
    }

    /// Create a status command
    pub fn status() -> Self {
        Self::new().arg("status")
    }

    /// Create a diff command
    pub fn diff() -> Self {
        Self::new().arg("diff")
    }

    /// Create a git clone --bare command for bare repository.
    ///
    /// Bare repositories are optimized for use as a source for worktrees,
    /// allowing multiple concurrent checkouts without conflicts. This is
    /// the preferred method for parallel operations in AGPM.
    ///
    /// # Arguments
    ///
    /// * `url` - The remote repository URL to clone
    /// * `target` - The local directory where the bare repository will be stored
    ///
    /// # Returns
    ///
    /// A configured `GitCommand` ready for execution.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// GitCommand::clone_bare(
    ///     "https://github.com/example/repo.git",
    ///     "/tmp/repo.git"
    /// )
    /// .execute_success()
    /// .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Worktree Usage
    ///
    /// Bare repositories created with this command are designed to be used
    /// with [`worktree_add`](#method.worktree_add) for parallel operations:
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// # async fn worktree_example() -> anyhow::Result<()> {
    /// // Clone bare repository
    /// GitCommand::clone_bare("https://github.com/example/repo.git", "/tmp/repo.git")
    ///     .execute_success()
    ///     .await?;
    ///
    /// // Create working directory from bare repo
    /// GitCommand::worktree_add("/tmp/work1", Some("v1.0.0"))
    ///     .current_dir("/tmp/repo.git")
    ///     .execute_success()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn clone_bare(url: &str, target: impl AsRef<Path>) -> Self {
        let mut cmd = Self::new();
        let mut args = vec!["clone".to_string(), "--bare".to_string(), "--progress".to_string()];

        // Only use partial clone for remote repositories
        // Local repositories (file://, absolute paths, relative paths) need full clones
        // to work properly with worktrees, especially when they're bare repositories
        let is_local = url.starts_with("file://")
            || url.starts_with('/')
            || url.starts_with('.')
            || url.starts_with('~')
            || (url.len() > 1 && url.chars().nth(1) == Some(':')); // Windows paths like C:

        if !is_local {
            args.push("--filter=blob:none".to_string());
        }

        args.extend(vec![
            "--recurse-submodules".to_string(),
            url.to_string(),
            target.as_ref().display().to_string(),
        ]);

        cmd.args.extend(args);
        cmd.clone_url = Some(url.to_string());
        cmd
    }

    /// Create a clone command for local file:// URLs with proper arguments and error context.
    ///
    /// This method is specifically designed for cloning local repositories via file:// URLs.
    /// It clones with all branches to ensure commit availability and sets proper error context.
    ///
    /// # Arguments
    ///
    /// * `url` - The file:// URL to clone from
    /// * `target` - The target directory where the repository will be cloned
    ///
    /// # Returns
    ///
    /// A configured `GitCommand` that clones the local repository with all branches.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use agpm_cli::git::command_builder::GitCommand;
    /// use std::path::Path;
    ///
    /// let cmd = GitCommand::clone_local(
    ///     "file:///path/to/local/repo.git",
    ///     Path::new("/tmp/cloned-repo")
    /// );
    /// ```
    pub fn clone_local(url: &str, target: impl AsRef<Path>) -> Self {
        let mut cmd = Self::new();
        cmd.args = vec![
            "clone".to_string(),
            "--progress".to_string(),
            "--no-single-branch".to_string(),
            "--recurse-submodules".to_string(),
            url.to_string(),
            target.as_ref().display().to_string(),
        ];
        cmd.clone_url = Some(url.to_string()); // Properly set for error reporting
        cmd
    }

    /// Create a worktree add command for parallel-safe Git operations.
    ///
    /// Worktrees allow multiple working directories to be checked out from
    /// a single bare repository, enabling safe parallel operations on different
    /// versions of the same repository without conflicts.
    ///
    /// # Arguments
    ///
    /// * `worktree_path` - The path where the new worktree will be created
    /// * `reference` - Optional Git reference (branch, tag, or commit) to checkout
    ///
    /// # Returns
    ///
    /// A configured `GitCommand` that must be executed from a bare repository directory.
    ///
    /// # Parallel Safety
    ///
    /// Each worktree is independent and can be safely accessed concurrently:
    /// - Different dependencies can use different worktrees simultaneously
    /// - No conflicts between parallel checkout operations
    /// - Each worktree maintains its own working directory state
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// // Create worktree with specific version
    /// GitCommand::worktree_add("/tmp/work-v1", Some("v1.0.0"))
    ///     .current_dir("/tmp/bare-repo.git")
    ///     .execute_success()
    ///     .await?;
    ///
    /// // Create worktree with default branch
    /// GitCommand::worktree_add("/tmp/work-main", None)
    ///     .current_dir("/tmp/bare-repo.git")
    ///     .execute_success()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Concurrency Control
    ///
    /// AGPM uses a global semaphore to limit concurrent Git operations and
    /// prevent resource exhaustion. This is handled automatically by the
    /// cache layer when using worktrees for parallel installations.
    ///
    /// # Reference Types
    ///
    /// The `reference` parameter supports various Git reference types:
    /// - **Tags**: `"v1.0.0"` (most common for package versions)
    /// - **Branches**: `"main"`, `"develop"`
    /// - **Commits**: `"abc123"` (specific commit hashes)
    /// - **None**: Uses repository's default branch
    pub fn worktree_add(worktree_path: impl AsRef<Path>, reference: Option<&str>) -> Self {
        let mut cmd = Self::new();
        cmd.args.push("worktree".to_string());
        cmd.args.push("add".to_string());

        // Add the worktree path
        cmd.args.push(worktree_path.as_ref().display().to_string());

        // Add the reference if provided
        if let Some(ref_name) = reference {
            cmd.args.push(ref_name.to_string());
        }

        cmd
    }

    /// Remove a worktree and clean up associated files.
    ///
    /// This command removes a worktree that was created with [`worktree_add`]
    /// and cleans up Git's internal bookkeeping. The `--force` flag is used
    /// to ensure removal even if the worktree has local modifications.
    ///
    /// # Arguments
    ///
    /// * `worktree_path` - The path to the worktree to remove
    ///
    /// # Returns
    ///
    /// A configured `GitCommand` that must be executed from the bare repository.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// // Remove a worktree
    /// GitCommand::worktree_remove("/tmp/work-v1")
    ///     .current_dir("/tmp/bare-repo.git")
    ///     .execute_success()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Force Removal
    ///
    /// The command uses `--force` to ensure removal succeeds even when:
    /// - The worktree has uncommitted changes
    /// - Files are locked or in use
    /// - The worktree directory structure has been modified
    ///
    /// This is appropriate for AGPM's use case where worktrees are temporary
    /// and any local changes should be discarded.
    ///
    /// [`worktree_add`]: #method.worktree_add
    pub fn worktree_remove(worktree_path: impl AsRef<Path>) -> Self {
        Self::new().args([
            "worktree",
            "remove",
            "--force",
            &worktree_path.as_ref().display().to_string(),
        ])
    }

    /// List all worktrees associated with a repository.
    ///
    /// This command returns information about all worktrees linked to the
    /// current bare repository. The `--porcelain` flag provides machine-readable
    /// output that's easier to parse programmatically.
    ///
    /// # Returns
    ///
    /// A configured `GitCommand` that must be executed from a bare repository.
    ///
    /// # Output Format
    ///
    /// The porcelain output format provides structured information:
    /// ```text
    /// worktree /path/to/worktree1
    /// HEAD abc123def456...
    /// branch refs/heads/main
    ///
    /// worktree /path/to/worktree2
    /// HEAD def456abc123...
    /// detached
    /// ```
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let output = GitCommand::worktree_list()
    ///     .current_dir("/tmp/bare-repo.git")
    ///     .execute_stdout()
    ///     .await?;
    ///
    /// // Parse output to find worktree paths
    /// for line in output.lines() {
    ///     if line.starts_with("worktree ") {
    ///         let path = line.strip_prefix("worktree ").unwrap();
    ///         println!("Found worktree: {}", path);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn worktree_list() -> Self {
        Self::new().args(["worktree", "list", "--porcelain"])
    }

    /// Prune stale worktree administrative files.
    ///
    /// This command cleans up worktree entries that no longer have corresponding
    /// directories on disk. It's useful for maintenance after worktrees have been
    /// manually deleted or when cleaning up after failed operations.
    ///
    /// # Returns
    ///
    /// A configured `GitCommand` that must be executed from a bare repository.
    ///
    /// # When to Use
    ///
    /// Prune worktrees when:
    /// - Worktree directories have been manually deleted
    /// - After bulk cleanup operations
    /// - During cache maintenance
    /// - When Git reports stale worktree references
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::git::command_builder::GitCommand;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// // Clean up stale worktree references
    /// GitCommand::worktree_prune()
    ///     .current_dir("/tmp/bare-repo.git")
    ///     .execute_success()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Performance
    ///
    /// This is a lightweight operation that only updates Git's internal
    /// bookkeeping. It doesn't remove actual worktree directories.
    pub fn worktree_prune() -> Self {
        Self::new().args(["worktree", "prune"])
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_command_builder_basic() {
        let cmd = GitCommand::new().arg("status").arg("--short");
        assert_eq!(cmd.args, vec!["status", "--short"]);
    }

    #[tokio::test]
    async fn test_git_command_logging() {
        // This test verifies that git stdout/stderr are logged at debug level
        // Run with RUST_LOG=debug to see the output
        let result = GitCommand::new().args(["--version"]).execute().await;

        assert!(result.is_ok(), "Git --version should succeed");
        let output = result.unwrap();
        assert!(!output.stdout.is_empty(), "Git version should produce stdout");
        // When run with RUST_LOG=debug, this should produce:
        // - "Executing git command: git --version"
        // - "Git command completed successfully"
        // - "Git stdout (raw): git version X.Y.Z"
    }

    #[test]
    fn test_command_builder_with_dir() {
        let cmd = GitCommand::new().current_dir("/tmp/repo").arg("status");
        assert_eq!(cmd.current_dir, Some(std::path::PathBuf::from("/tmp/repo")));
    }

    #[test]
    fn test_clone_builder() {
        let cmd = GitCommand::clone("https://example.com/repo.git", "/tmp/target");
        assert_eq!(cmd.args[0], "clone");
        assert_eq!(cmd.args[1], "--progress");
        assert!(cmd.args.contains(&"https://example.com/repo.git".to_string()));
    }

    #[test]
    fn test_checkout_branch_builder() {
        let cmd = GitCommand::checkout_branch("main", "origin/main");
        assert_eq!(cmd.args, vec!["checkout", "-B", "main", "origin/main"]);
    }
}