-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathclaude_binary.rs
More file actions
857 lines (736 loc) · 30.1 KB
/
claude_binary.rs
File metadata and controls
857 lines (736 loc) · 30.1 KB
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
use anyhow::Result;
use log::{debug, error, info, warn};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
/// Shared module for detecting Claude Code binary installations
/// Supports NVM installations, aliased paths, and version-based selection
use std::path::PathBuf;
use std::process::Command;
use tauri::Manager;
/// Type of Claude installation
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum InstallationType {
/// System-installed binary
System,
/// Custom path specified by user
Custom,
}
/// Represents a Claude installation with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeInstallation {
/// Full path to the Claude binary
pub path: String,
/// Version string if available
pub version: Option<String>,
/// Source of discovery (e.g., "nvm", "system", "homebrew", "which")
pub source: String,
/// Type of installation
pub installation_type: InstallationType,
}
/// Main function to find the Claude binary
/// Checks database first for stored path and preference, then prioritizes accordingly
pub fn find_claude_binary(app_handle: &tauri::AppHandle) -> Result<String, String> {
info!("Searching for claude binary...");
// First check if we have a stored path and preference in the database
if let Ok(app_data_dir) = app_handle.path().app_data_dir() {
let db_path = app_data_dir.join("agents.db");
if db_path.exists() {
if let Ok(conn) = rusqlite::Connection::open(&db_path) {
// Check for stored path first
if let Ok(stored_path) = conn.query_row(
"SELECT value FROM app_settings WHERE key = 'claude_binary_path'",
[],
|row| row.get::<_, String>(0),
) {
info!("Found stored claude path in database: {}", stored_path);
// Check if the path still exists
let path_buf = PathBuf::from(&stored_path);
if path_buf.exists() && path_buf.is_file() {
return Ok(stored_path);
} else {
warn!("Stored claude path no longer exists: {}", stored_path);
}
}
// Check user preference
let preference = conn.query_row(
"SELECT value FROM app_settings WHERE key = 'claude_installation_preference'",
[],
|row| row.get::<_, String>(0),
).unwrap_or_else(|_| "system".to_string());
info!("User preference for Claude installation: {}", preference);
}
}
}
// Discover all available system installations
let installations = discover_system_installations();
if installations.is_empty() {
error!("Could not find claude binary in any location");
return Err("Claude Code not found. Please ensure it's installed in one of these locations: PATH, /usr/local/bin, /opt/homebrew/bin, ~/.nvm/versions/node/*/bin, ~/.claude/local, ~/.local/bin".to_string());
}
// Log all found installations
for installation in &installations {
info!("Found Claude installation: {:?}", installation);
}
// Select the best installation (highest version)
if let Some(best) = select_best_installation(installations) {
info!(
"Selected Claude installation: path={}, version={:?}, source={}",
best.path, best.version, best.source
);
Ok(best.path)
} else {
Err("No valid Claude installation found".to_string())
}
}
/// Discovers all available Claude installations and returns them for selection
/// This allows UI to show a version selector
pub fn discover_claude_installations() -> Vec<ClaudeInstallation> {
info!("Discovering all Claude installations...");
let mut installations = discover_system_installations();
// Sort by version (highest first), then by source preference
installations.sort_by(|a, b| {
match (&a.version, &b.version) {
(Some(v1), Some(v2)) => {
// Compare versions in descending order (newest first)
match compare_versions(v2, v1) {
Ordering::Equal => {
// If versions are equal, prefer by source
source_preference(a).cmp(&source_preference(b))
}
other => other,
}
}
(Some(_), None) => Ordering::Less, // Version comes before no version
(None, Some(_)) => Ordering::Greater,
(None, None) => source_preference(a).cmp(&source_preference(b)),
}
});
installations
}
/// Returns a preference score for installation sources (lower is better)
fn source_preference(installation: &ClaudeInstallation) -> u8 {
match installation.source.as_str() {
"which" => 1,
"homebrew" => 2,
"system" => 3,
"nvm-active" => 4,
source if source.starts_with("nvm") => 5,
"asdf" => 6,
"local-bin" => 7,
"claude-local" => 8,
"npm-global" => 9,
"yarn" | "yarn-global" => 10,
"bun" => 11,
"node-modules" => 12,
"home-bin" => 13,
"PATH" => 14,
_ => 15,
}
}
/// Discovers all Claude installations on the system
fn discover_system_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
// 1. Try 'which' command first (now works in production)
if let Some(installation) = try_which_command() {
installations.push(installation);
}
// 2. Check asdf shims first (before NVM)
installations.extend(find_asdf_installations());
// 3. Check NVM paths (includes current active NVM)
installations.extend(find_nvm_installations());
// 4. Check standard paths
installations.extend(find_standard_installations());
// Remove duplicates by path
let mut unique_paths = std::collections::HashSet::new();
installations.retain(|install| unique_paths.insert(install.path.clone()));
installations
}
/// Try using the 'which' command to find Claude
#[cfg(unix)]
fn try_which_command() -> Option<ClaudeInstallation> {
debug!("Trying 'which claude' to find binary...");
match Command::new("which").arg("claude").output() {
Ok(output) if output.status.success() => {
let output_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
if output_str.is_empty() {
return None;
}
// Parse aliased output: "claude: aliased to /path/to/claude"
let path = if output_str.starts_with("claude:") && output_str.contains("aliased to") {
output_str
.split("aliased to")
.nth(1)
.map(|s| s.trim().to_string())
} else {
Some(output_str)
}?;
debug!("'which' found claude at: {}", path);
// Verify the path exists
if !PathBuf::from(&path).exists() {
warn!("Path from 'which' does not exist: {}", path);
return None;
}
// Get version
let version = get_claude_version(&path).ok().flatten();
Some(ClaudeInstallation {
path,
version,
source: "which".to_string(),
installation_type: InstallationType::System,
})
}
_ => None,
}
}
#[cfg(windows)]
fn try_which_command() -> Option<ClaudeInstallation> {
debug!("Trying 'where claude' to find binary...");
match Command::new("where").arg("claude").output() {
Ok(output) if output.status.success() => {
let output_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
if output_str.is_empty() {
return None;
}
// On Windows, `where` can return multiple paths, newline-separated. We take the first one.
let path = output_str.lines().next().unwrap_or("").trim().to_string();
if path.is_empty() {
return None;
}
debug!("'where' found claude at: {}", path);
// Verify the path exists
if !PathBuf::from(&path).exists() {
warn!("Path from 'where' does not exist: {}", path);
return None;
}
// Get version
let version = get_claude_version(&path).ok().flatten();
Some(ClaudeInstallation {
path,
version,
source: "where".to_string(),
installation_type: InstallationType::System,
})
}
_ => None,
}
}
/// Find Claude installations in asdf shims directories
#[cfg(unix)]
fn find_asdf_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
let mut checked_paths = std::collections::HashSet::new();
// Check ASDF_DIR environment variable first
if let Ok(asdf_dir) = std::env::var("ASDF_DIR") {
let claude_path = PathBuf::from(&asdf_dir).join("shims").join("claude");
if claude_path.exists() && claude_path.is_file() {
debug!("Found Claude via ASDF_DIR: {:?}", claude_path);
let path_str = claude_path.to_string_lossy().to_string();
checked_paths.insert(path_str.clone());
let version = get_claude_version(&path_str)
.ok()
.flatten();
installations.push(ClaudeInstallation {
path: path_str,
version,
source: "asdf".to_string(),
installation_type: InstallationType::System,
});
}
}
// Then check default ~/.asdf location (skip if already found via ASDF_DIR)
if let Ok(home) = std::env::var("HOME") {
let asdf_shims_path = PathBuf::from(&home)
.join(".asdf")
.join("shims")
.join("claude");
let path_str = asdf_shims_path.to_string_lossy().to_string();
// Skip if we already found this path via ASDF_DIR
if !checked_paths.contains(&path_str) {
debug!("Checking asdf shims directory: {:?}", asdf_shims_path);
if asdf_shims_path.exists() && asdf_shims_path.is_file() {
debug!("Found Claude in asdf shims: {}", path_str);
// Get Claude version
let version = get_claude_version(&path_str).ok().flatten();
installations.push(ClaudeInstallation {
path: path_str,
version,
source: "asdf".to_string(),
installation_type: InstallationType::System,
});
}
}
}
installations
}
#[cfg(windows)]
fn find_asdf_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
let mut checked_paths = std::collections::HashSet::new();
// Check ASDF_DIR environment variable first
if let Ok(asdf_dir) = std::env::var("ASDF_DIR") {
let claude_path = PathBuf::from(&asdf_dir).join("shims").join("claude.exe");
if claude_path.exists() && claude_path.is_file() {
debug!("Found Claude via ASDF_DIR: {:?}", claude_path);
let path_str = claude_path.to_string_lossy().to_string();
checked_paths.insert(path_str.clone());
let version = get_claude_version(&path_str)
.ok()
.flatten();
installations.push(ClaudeInstallation {
path: path_str,
version,
source: "asdf".to_string(),
installation_type: InstallationType::System,
});
}
}
// Then check default location (skip if already found via ASDF_DIR)
if let Ok(user_profile) = std::env::var("USERPROFILE") {
let asdf_shims_path = PathBuf::from(&user_profile)
.join(".asdf")
.join("shims")
.join("claude.exe");
let path_str = asdf_shims_path.to_string_lossy().to_string();
// Skip if we already found this path via ASDF_DIR
if !checked_paths.contains(&path_str) {
debug!("Checking asdf shims directory: {:?}", asdf_shims_path);
if asdf_shims_path.exists() && asdf_shims_path.is_file() {
debug!("Found Claude in asdf shims: {}", path_str);
let version = get_claude_version(&path_str).ok().flatten();
installations.push(ClaudeInstallation {
path: path_str,
version,
source: "asdf".to_string(),
installation_type: InstallationType::System,
});
}
}
}
installations
}
/// Find Claude installations in NVM directories
#[cfg(unix)]
fn find_nvm_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
// First check NVM_BIN environment variable (current active NVM)
if let Ok(nvm_bin) = std::env::var("NVM_BIN") {
let claude_path = PathBuf::from(&nvm_bin).join("claude");
if claude_path.exists() && claude_path.is_file() {
debug!("Found Claude via NVM_BIN: {:?}", claude_path);
let version = get_claude_version(&claude_path.to_string_lossy())
.ok()
.flatten();
installations.push(ClaudeInstallation {
path: claude_path.to_string_lossy().to_string(),
version,
source: "nvm-active".to_string(),
installation_type: InstallationType::System,
});
}
}
// Then check all NVM directories
if let Ok(home) = std::env::var("HOME") {
let nvm_dir = PathBuf::from(&home)
.join(".nvm")
.join("versions")
.join("node");
debug!("Checking NVM directory: {:?}", nvm_dir);
if let Ok(entries) = std::fs::read_dir(&nvm_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let claude_path = entry.path().join("bin").join("claude");
if claude_path.exists() && claude_path.is_file() {
let path_str = claude_path.to_string_lossy().to_string();
let node_version = entry.file_name().to_string_lossy().to_string();
debug!("Found Claude in NVM node {}: {}", node_version, path_str);
// Get Claude version
let version = get_claude_version(&path_str).ok().flatten();
installations.push(ClaudeInstallation {
path: path_str,
version,
source: format!("nvm ({})", node_version),
installation_type: InstallationType::System,
});
}
}
}
}
}
installations
}
#[cfg(windows)]
fn find_nvm_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
if let Ok(nvm_home) = std::env::var("NVM_HOME") {
debug!("Checking NVM_HOME directory: {:?}", nvm_home);
if let Ok(entries) = std::fs::read_dir(&nvm_home) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
let claude_path = entry.path().join("claude.exe");
if claude_path.exists() && claude_path.is_file() {
let path_str = claude_path.to_string_lossy().to_string();
let node_version = entry.file_name().to_string_lossy().to_string();
debug!("Found Claude in NVM node {}: {}", node_version, path_str);
// Get Claude version
let version = get_claude_version(&path_str).ok().flatten();
installations.push(ClaudeInstallation {
path: path_str,
version,
source: format!("nvm ({})", node_version),
installation_type: InstallationType::System,
});
}
}
}
}
}
installations
}
/// Check standard installation paths
#[cfg(unix)]
fn find_standard_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
// Common installation paths for claude
let mut paths_to_check: Vec<(String, String)> = vec![
("/usr/local/bin/claude".to_string(), "system".to_string()),
(
"/opt/homebrew/bin/claude".to_string(),
"homebrew".to_string(),
),
("/usr/bin/claude".to_string(), "system".to_string()),
("/bin/claude".to_string(), "system".to_string()),
];
// Also check user-specific paths
if let Ok(home) = std::env::var("HOME") {
paths_to_check.extend(vec![
(
format!("{}/.claude/local/claude", home),
"claude-local".to_string(),
),
(
format!("{}/.local/bin/claude", home),
"local-bin".to_string(),
),
(
format!("{}/.npm-global/bin/claude", home),
"npm-global".to_string(),
),
(format!("{}/.yarn/bin/claude", home), "yarn".to_string()),
(format!("{}/.bun/bin/claude", home), "bun".to_string()),
(format!("{}/bin/claude", home), "home-bin".to_string()),
// Check common node_modules locations
(
format!("{}/node_modules/.bin/claude", home),
"node-modules".to_string(),
),
(
format!("{}/.config/yarn/global/node_modules/.bin/claude", home),
"yarn-global".to_string(),
),
]);
}
// Check each path
for (path, source) in paths_to_check {
let path_buf = PathBuf::from(&path);
if path_buf.exists() && path_buf.is_file() {
debug!("Found claude at standard path: {} ({})", path, source);
// Get version
let version = get_claude_version(&path).ok().flatten();
installations.push(ClaudeInstallation {
path,
version,
source,
installation_type: InstallationType::System,
});
}
}
// Also check if claude is available in PATH (without full path)
if let Ok(output) = Command::new("claude").arg("--version").output() {
if output.status.success() {
debug!("claude is available in PATH");
let version = extract_version_from_output(&output.stdout);
installations.push(ClaudeInstallation {
path: "claude".to_string(),
version,
source: "PATH".to_string(),
installation_type: InstallationType::System,
});
}
}
installations
}
#[cfg(windows)]
fn find_standard_installations() -> Vec<ClaudeInstallation> {
let mut installations = Vec::new();
// Common installation paths for claude on Windows
let mut paths_to_check: Vec<(String, String)> = vec![];
// Check user-specific paths
if let Ok(user_profile) = std::env::var("USERPROFILE") {
paths_to_check.extend(vec![
(
format!("{}\\.claude\\local\\claude.exe", user_profile),
"claude-local".to_string(),
),
(
format!("{}\\.local\\bin\\claude.exe", user_profile),
"local-bin".to_string(),
),
(
format!("{}\\AppData\\Roaming\\npm\\claude.cmd", user_profile),
"npm-global".to_string(),
),
(
format!("{}\\.yarn\\bin\\claude.cmd", user_profile),
"yarn".to_string(),
),
(
format!("{}\\.bun\\bin\\claude.exe", user_profile),
"bun".to_string(),
),
]);
}
// Check each path
for (path, source) in paths_to_check {
let path_buf = PathBuf::from(&path);
if path_buf.exists() && path_buf.is_file() {
debug!("Found claude at standard path: {} ({})", path, source);
// Get version
let version = get_claude_version(&path).ok().flatten();
installations.push(ClaudeInstallation {
path,
version,
source,
installation_type: InstallationType::System,
});
}
}
// Also check if claude is available in PATH (without full path)
if let Ok(output) = Command::new("claude.exe").arg("--version").output() {
if output.status.success() {
debug!("claude.exe is available in PATH");
let version = extract_version_from_output(&output.stdout);
installations.push(ClaudeInstallation {
path: "claude.exe".to_string(),
version,
source: "PATH".to_string(),
installation_type: InstallationType::System,
});
}
}
installations
}
/// Get Claude version by running --version command
fn get_claude_version(path: &str) -> Result<Option<String>, String> {
match Command::new(path).arg("--version").output() {
Ok(output) => {
if output.status.success() {
Ok(extract_version_from_output(&output.stdout))
} else {
Ok(None)
}
}
Err(e) => {
warn!("Failed to get version for {}: {}", path, e);
Ok(None)
}
}
}
/// Extract version string from command output
fn extract_version_from_output(stdout: &[u8]) -> Option<String> {
let output_str = String::from_utf8_lossy(stdout);
// Debug log the raw output
debug!("Raw version output: {:?}", output_str);
// Use regex to directly extract version pattern (e.g., "1.0.41")
// This pattern matches:
// - One or more digits, followed by
// - A dot, followed by
// - One or more digits, followed by
// - A dot, followed by
// - One or more digits
// - Optionally followed by pre-release/build metadata
let version_regex =
regex::Regex::new(r"(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?)").ok()?;
if let Some(captures) = version_regex.captures(&output_str) {
if let Some(version_match) = captures.get(1) {
let version = version_match.as_str().to_string();
debug!("Extracted version: {:?}", version);
return Some(version);
}
}
debug!("No version found in output");
None
}
/// Select the best installation based on version
fn select_best_installation(installations: Vec<ClaudeInstallation>) -> Option<ClaudeInstallation> {
// In production builds, version information may not be retrievable because
// spawning external processes can be restricted. We therefore no longer
// discard installations that lack a detected version – the mere presence
// of a readable binary on disk is enough to consider it valid. We still
// prefer binaries with version information when it is available so that
// in development builds we keep the previous behaviour of picking the
// most recent version.
installations.into_iter().max_by(|a, b| {
match (&a.version, &b.version) {
// If both have versions, compare them semantically.
(Some(v1), Some(v2)) => compare_versions(v1, v2),
// Prefer the entry that actually has version information.
(Some(_), None) => Ordering::Greater,
(None, Some(_)) => Ordering::Less,
// Neither have version info: prefer the one that is not just
// the bare "claude" lookup from PATH, because that may fail
// at runtime if PATH is modified.
(None, None) => {
if a.path == "claude" && b.path != "claude" {
Ordering::Less
} else if a.path != "claude" && b.path == "claude" {
Ordering::Greater
} else {
Ordering::Equal
}
}
}
})
}
/// Compare two version strings
fn compare_versions(a: &str, b: &str) -> Ordering {
// Simple semantic version comparison
let a_parts: Vec<u32> = a
.split('.')
.filter_map(|s| {
// Handle versions like "1.0.17-beta" by taking only numeric part
s.chars()
.take_while(|c| c.is_numeric())
.collect::<String>()
.parse()
.ok()
})
.collect();
let b_parts: Vec<u32> = b
.split('.')
.filter_map(|s| {
s.chars()
.take_while(|c| c.is_numeric())
.collect::<String>()
.parse()
.ok()
})
.collect();
// Compare each part
for i in 0..std::cmp::max(a_parts.len(), b_parts.len()) {
let a_val = a_parts.get(i).unwrap_or(&0);
let b_val = b_parts.get(i).unwrap_or(&0);
match a_val.cmp(b_val) {
Ordering::Equal => continue,
other => return other,
}
}
Ordering::Equal
}
/// Helper function to create a Command with proper environment variables
/// This ensures commands like Claude can find Node.js and other dependencies
pub fn create_command_with_env(program: &str) -> Command {
let mut cmd = Command::new(program);
info!("Creating command for: {}", program);
// Inherit essential environment variables from parent process
for (key, value) in std::env::vars() {
// Pass through PATH and other essential environment variables
if key == "PATH"
|| key == "HOME"
|| key == "USER"
|| key == "SHELL"
|| key == "LANG"
|| key == "LC_ALL"
|| key.starts_with("LC_")
|| key == "NODE_PATH"
|| key == "NVM_DIR"
|| key == "NVM_BIN"
|| key == "HOMEBREW_PREFIX"
|| key == "HOMEBREW_CELLAR"
// Add asdf environment variables
|| key == "ASDF_DIR"
|| key == "ASDF_DATA_DIR"
|| key == "ASDF_CONFIG_FILE"
// Add proxy environment variables (only uppercase)
|| key == "HTTP_PROXY"
|| key == "HTTPS_PROXY"
|| key == "NO_PROXY"
|| key == "ALL_PROXY"
{
debug!("Inheriting env var: {}={}", key, value);
cmd.env(&key, &value);
}
}
// Log proxy-related environment variables for debugging
info!("Command will use proxy settings:");
if let Ok(http_proxy) = std::env::var("HTTP_PROXY") {
info!(" HTTP_PROXY={}", http_proxy);
}
if let Ok(https_proxy) = std::env::var("HTTPS_PROXY") {
info!(" HTTPS_PROXY={}", https_proxy);
}
// Add NVM support if the program is in an NVM directory
if program.contains("/.nvm/versions/node/") {
if let Some(node_bin_dir) = std::path::Path::new(program).parent() {
// Ensure the Node.js bin directory is in PATH
let current_path = std::env::var("PATH").unwrap_or_default();
let node_bin_str = node_bin_dir.to_string_lossy();
if !current_path.contains(&node_bin_str.as_ref()) {
let new_path = format!("{}:{}", node_bin_str, current_path);
debug!("Adding NVM bin directory to PATH: {}", node_bin_str);
cmd.env("PATH", new_path);
}
}
}
// Add Homebrew support if the program is in a Homebrew directory
if program.contains("/homebrew/") || program.contains("/opt/homebrew/") {
if let Some(program_dir) = std::path::Path::new(program).parent() {
// Ensure the Homebrew bin directory is in PATH
let current_path = std::env::var("PATH").unwrap_or_default();
let homebrew_bin_str = program_dir.to_string_lossy();
if !current_path.contains(&homebrew_bin_str.as_ref()) {
let new_path = format!("{}:{}", homebrew_bin_str, current_path);
debug!(
"Adding Homebrew bin directory to PATH: {}",
homebrew_bin_str
);
cmd.env("PATH", new_path);
}
}
}
// Add asdf support if the program is in an asdf shims directory
// Also check if the program is a symlink pointing to asdf shims
let is_asdf_program = program.contains("/.asdf/shims/")
|| std::fs::read_link(program)
.map(|target| target.to_string_lossy().contains("/.asdf/shims/"))
.unwrap_or(false);
if is_asdf_program {
if let Ok(home) = std::env::var("HOME") {
let asdf_bin_dir = format!("{}/.asdf/bin", home);
let asdf_shims_dir = format!("{}/.asdf/shims", home);
let current_path = std::env::var("PATH").unwrap_or_default();
let mut new_path = current_path.clone();
// Add asdf bin directory if not already in PATH
if !current_path.contains(&asdf_bin_dir) {
new_path = format!("{}:{}", asdf_bin_dir, new_path);
debug!("Adding asdf bin directory to PATH: {}", asdf_bin_dir);
}
// Add asdf shims directory if not already in PATH
if !current_path.contains(&asdf_shims_dir) {
new_path = format!("{}:{}", asdf_shims_dir, new_path);
debug!("Adding asdf shims directory to PATH: {}", asdf_shims_dir);
}
if new_path != current_path {
cmd.env("PATH", new_path);
}
// Set ASDF_DIR if not already set
if std::env::var("ASDF_DIR").is_err() {
let asdf_dir = format!("{}/.asdf", home);
if std::path::Path::new(&asdf_dir).exists() {
debug!("Setting ASDF_DIR to: {}", asdf_dir);
cmd.env("ASDF_DIR", asdf_dir);
}
}
}
}
cmd
}