jarvy 0.3.0

Jarvy is a fast, cross-platform CLI that installs and manages developer tools across macOS and Linux.
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
//! Proxy resolution with priority handling
//!
//! Priority order:
//! 1. Environment variables (HTTP_PROXY, HTTPS_PROXY, etc.)
//! 2. Tool-specific overrides in [network.overrides.<tool>]
//! 3. Global config in [network] section

#![allow(dead_code)] // Public API for proxy resolution

use super::config::{NetworkConfig, NetworkOverride};
use std::collections::HashMap;
use std::env;

/// Resolved proxy configuration for a specific tool
#[derive(Debug, Clone, Default)]
pub struct ResolvedProxy {
    pub http_proxy: Option<String>,
    pub https_proxy: Option<String>,
    pub socks_proxy: Option<String>,
    pub no_proxy: Option<String>,
    pub source: ProxySource,
}

/// Source of the resolved proxy configuration
#[derive(Debug, Clone, Default, PartialEq)]
pub enum ProxySource {
    #[default]
    None,
    Environment,
    ToolOverride(String),
    GlobalConfig,
}

/// Proxy resolver that combines environment, config, and tool-specific settings
pub struct ProxyResolver<'a> {
    config: Option<&'a NetworkConfig>,
}

impl<'a> ProxyResolver<'a> {
    /// Create a new proxy resolver
    pub fn new(config: Option<&'a NetworkConfig>) -> Self {
        Self { config }
    }

    /// Resolve proxy configuration for a specific tool
    pub fn resolve_for_tool(&self, tool_name: &str) -> ResolvedProxy {
        // Check environment variables first (highest priority)
        if let Some(proxy) = self.env_proxy() {
            return proxy;
        }

        // Check tool-specific override
        if let Some(config) = self.config {
            if let Some(override_config) = config.overrides.get(tool_name) {
                if override_config.no_proxy_all {
                    // Tool explicitly disables proxy
                    return ResolvedProxy {
                        source: ProxySource::ToolOverride(tool_name.to_string()),
                        ..Default::default()
                    };
                }

                let resolved = self.override_proxy(override_config, tool_name);
                if resolved.http_proxy.is_some() || resolved.https_proxy.is_some() {
                    return resolved;
                }
            }
        }

        // Fall back to global config
        self.global_proxy()
    }

    /// Get proxy from environment variables
    fn env_proxy(&self) -> Option<ResolvedProxy> {
        let http = env::var("HTTP_PROXY")
            .or_else(|_| env::var("http_proxy"))
            .ok();
        let https = env::var("HTTPS_PROXY")
            .or_else(|_| env::var("https_proxy"))
            .ok();
        let socks = env::var("SOCKS_PROXY")
            .or_else(|_| env::var("socks_proxy"))
            .or_else(|_| env::var("ALL_PROXY"))
            .or_else(|_| env::var("all_proxy"))
            .ok();
        let no_proxy = env::var("NO_PROXY").or_else(|_| env::var("no_proxy")).ok();

        if http.is_some() || https.is_some() || socks.is_some() {
            Some(ResolvedProxy {
                http_proxy: http,
                https_proxy: https,
                socks_proxy: socks,
                no_proxy,
                source: ProxySource::Environment,
            })
        } else {
            None
        }
    }

    /// Get proxy from tool-specific override
    fn override_proxy(&self, override_config: &NetworkOverride, tool_name: &str) -> ResolvedProxy {
        let global = self.config;

        ResolvedProxy {
            http_proxy: override_config
                .http_proxy
                .clone()
                .or_else(|| global.and_then(|c| c.http_proxy.clone())),
            https_proxy: override_config
                .https_proxy
                .clone()
                .or_else(|| global.and_then(|c| c.https_proxy.clone())),
            socks_proxy: override_config
                .socks_proxy
                .clone()
                .or_else(|| global.and_then(|c| c.socks_proxy.clone())),
            no_proxy: override_config
                .no_proxy
                .as_ref()
                .map(|np| np.to_env_string())
                .or_else(|| global.and_then(|c| c.no_proxy.as_ref().map(|np| np.to_env_string()))),
            source: ProxySource::ToolOverride(tool_name.to_string()),
        }
    }

    /// Get proxy from global config
    fn global_proxy(&self) -> ResolvedProxy {
        match self.config {
            Some(config) if config.has_proxy() => ResolvedProxy {
                http_proxy: config.http_proxy.clone(),
                https_proxy: config.https_proxy.clone(),
                socks_proxy: config.socks_proxy.clone(),
                no_proxy: config.no_proxy.as_ref().map(|np| np.to_env_string()),
                source: ProxySource::GlobalConfig,
            },
            _ => ResolvedProxy::default(),
        }
    }
}

impl ResolvedProxy {
    /// Check if any proxy is configured
    pub fn has_proxy(&self) -> bool {
        self.http_proxy.is_some() || self.https_proxy.is_some() || self.socks_proxy.is_some()
    }

    /// Convert to environment variable HashMap
    pub fn to_env_vars(&self) -> HashMap<String, String> {
        let mut vars = HashMap::new();

        if let Some(ref proxy) = self.http_proxy {
            vars.insert("HTTP_PROXY".to_string(), proxy.clone());
            vars.insert("http_proxy".to_string(), proxy.clone());
        }

        if let Some(ref proxy) = self.https_proxy {
            vars.insert("HTTPS_PROXY".to_string(), proxy.clone());
            vars.insert("https_proxy".to_string(), proxy.clone());
        }

        if let Some(ref proxy) = self.socks_proxy {
            vars.insert("SOCKS_PROXY".to_string(), proxy.clone());
            vars.insert("socks_proxy".to_string(), proxy.clone());
            vars.insert("ALL_PROXY".to_string(), proxy.clone());
            vars.insert("all_proxy".to_string(), proxy.clone());
        }

        if let Some(ref no_proxy) = self.no_proxy {
            vars.insert("NO_PROXY".to_string(), no_proxy.clone());
            vars.insert("no_proxy".to_string(), no_proxy.clone());
        }

        vars
    }
}

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

    #[test]
    #[serial_test::serial(proxy_env)]
    fn test_resolver_no_config() {
        // env_proxy() reads HTTP(S)_PROXY first; without an EnvGuard,
        // a CI runner (or a parallel test mutating proxy env vars)
        // can leak into this assertion. Guard + serial keep the test
        // hermetic.
        let _guard = EnvGuard::new(PROXY_ENV_VARS);
        let resolver = ProxyResolver::new(None);
        let resolved = resolver.resolve_for_tool("git");
        assert!(!resolved.has_proxy());
        assert_eq!(resolved.source, ProxySource::None);
    }

    #[test]
    #[serial_test::serial(proxy_env)]
    fn test_resolver_global_config() {
        let _guard = EnvGuard::new(PROXY_ENV_VARS);
        let config = NetworkConfig {
            https_proxy: Some("http://proxy:8080".to_string()),
            ..Default::default()
        };

        let resolver = ProxyResolver::new(Some(&config));
        let resolved = resolver.resolve_for_tool("git");

        assert!(resolved.has_proxy());
        assert_eq!(resolved.https_proxy, Some("http://proxy:8080".to_string()));
        assert_eq!(resolved.source, ProxySource::GlobalConfig);
    }

    #[test]
    #[serial_test::serial(proxy_env)]
    fn test_resolver_tool_override() {
        let _guard = EnvGuard::new(PROXY_ENV_VARS);
        let git_override = NetworkOverride {
            https_proxy: Some("http://git-proxy:8888".to_string()),
            ..Default::default()
        };
        let mut overrides = std::collections::HashMap::new();
        overrides.insert("git".to_string(), git_override);
        let config = NetworkConfig {
            https_proxy: Some("http://proxy:8080".to_string()),
            overrides,
            ..Default::default()
        };

        let resolver = ProxyResolver::new(Some(&config));
        let resolved = resolver.resolve_for_tool("git");

        assert_eq!(
            resolved.https_proxy,
            Some("http://git-proxy:8888".to_string())
        );
        assert_eq!(
            resolved.source,
            ProxySource::ToolOverride("git".to_string())
        );
    }

    #[test]
    #[serial_test::serial(proxy_env)]
    fn test_resolver_tool_no_proxy_all() {
        let _guard = EnvGuard::new(PROXY_ENV_VARS);
        let git_override = NetworkOverride {
            no_proxy_all: true,
            ..Default::default()
        };
        let mut overrides = std::collections::HashMap::new();
        overrides.insert("git".to_string(), git_override);
        let config = NetworkConfig {
            https_proxy: Some("http://proxy:8080".to_string()),
            overrides,
            ..Default::default()
        };

        let resolver = ProxyResolver::new(Some(&config));
        let resolved = resolver.resolve_for_tool("git");

        assert!(!resolved.has_proxy());
        assert_eq!(
            resolved.source,
            ProxySource::ToolOverride("git".to_string())
        );
    }

    /// RAII guard that snapshots the listed env vars on construction and
    /// restores them on drop. Pair with `#[serial(proxy_env)]` so concurrent
    /// tests do not race on the global env.
    struct EnvGuard {
        saved: Vec<(&'static str, Option<String>)>,
    }

    impl EnvGuard {
        fn new(vars: &[&'static str]) -> Self {
            let saved = vars.iter().map(|k| (*k, std::env::var(k).ok())).collect();
            // Wipe each so tests start from a known state.
            for k in vars {
                // SAFETY: tests run with #[serial(proxy_env)] so no other
                // thread is reading or writing these vars concurrently.
                unsafe { std::env::remove_var(k) };
            }
            Self { saved }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            for (k, v) in &self.saved {
                // SAFETY: see EnvGuard::new.
                unsafe {
                    match v {
                        Some(val) => std::env::set_var(k, val),
                        None => std::env::remove_var(k),
                    }
                }
            }
        }
    }

    const PROXY_ENV_VARS: &[&str] = &[
        "HTTP_PROXY",
        "http_proxy",
        "HTTPS_PROXY",
        "https_proxy",
        "SOCKS_PROXY",
        "socks_proxy",
        "ALL_PROXY",
        "all_proxy",
        "NO_PROXY",
        "no_proxy",
    ];

    #[test]
    #[serial_test::serial(proxy_env)]
    fn proxy_precedence_env_beats_tool_and_global() {
        let _guard = EnvGuard::new(PROXY_ENV_VARS);
        // SAFETY: serialized via #[serial(proxy_env)].
        unsafe { std::env::set_var("HTTPS_PROXY", "https://env.example/x") };

        let git_override = NetworkOverride {
            https_proxy: Some("https://tool.example/y".to_string()),
            ..Default::default()
        };
        let mut overrides = std::collections::HashMap::new();
        overrides.insert("git".to_string(), git_override);
        let config = NetworkConfig {
            https_proxy: Some("https://global.example/z".to_string()),
            overrides,
            ..Default::default()
        };

        let resolver = ProxyResolver::new(Some(&config));
        let resolved = resolver.resolve_for_tool("git");

        assert_eq!(resolved.source, ProxySource::Environment);
        assert_eq!(
            resolved.https_proxy.as_deref(),
            Some("https://env.example/x")
        );
    }

    #[test]
    #[serial_test::serial(proxy_env)]
    fn proxy_precedence_tool_beats_global_when_no_env() {
        let _guard = EnvGuard::new(PROXY_ENV_VARS);

        let git_override = NetworkOverride {
            https_proxy: Some("https://tool.example/y".to_string()),
            ..Default::default()
        };
        let mut overrides = std::collections::HashMap::new();
        overrides.insert("git".to_string(), git_override);
        let config = NetworkConfig {
            https_proxy: Some("https://global.example/z".to_string()),
            overrides,
            ..Default::default()
        };

        let resolver = ProxyResolver::new(Some(&config));
        let resolved = resolver.resolve_for_tool("git");

        assert_eq!(
            resolved.source,
            ProxySource::ToolOverride("git".to_string())
        );
        assert_eq!(
            resolved.https_proxy.as_deref(),
            Some("https://tool.example/y")
        );
    }

    #[test]
    #[serial_test::serial(proxy_env)]
    fn proxy_no_proxy_all_drops_global_proxy() {
        let _guard = EnvGuard::new(PROXY_ENV_VARS);

        let git_override = NetworkOverride {
            no_proxy_all: true,
            ..Default::default()
        };
        let mut overrides = std::collections::HashMap::new();
        overrides.insert("git".to_string(), git_override);
        let config = NetworkConfig {
            https_proxy: Some("https://global.example/z".to_string()),
            overrides,
            ..Default::default()
        };

        let resolver = ProxyResolver::new(Some(&config));
        let resolved = resolver.resolve_for_tool("git");

        assert!(!resolved.has_proxy());
        assert_eq!(
            resolved.source,
            ProxySource::ToolOverride("git".to_string())
        );
    }

    #[test]
    #[serial_test::serial(proxy_env)]
    fn proxy_unrelated_tool_falls_back_to_global() {
        let _guard = EnvGuard::new(PROXY_ENV_VARS);

        let git_override = NetworkOverride {
            https_proxy: Some("https://git.example/y".to_string()),
            ..Default::default()
        };
        let mut overrides = std::collections::HashMap::new();
        overrides.insert("git".to_string(), git_override);
        let config = NetworkConfig {
            https_proxy: Some("https://global.example/z".to_string()),
            overrides,
            ..Default::default()
        };

        let resolver = ProxyResolver::new(Some(&config));
        let resolved = resolver.resolve_for_tool("npm");

        assert_eq!(resolved.source, ProxySource::GlobalConfig);
        assert_eq!(
            resolved.https_proxy.as_deref(),
            Some("https://global.example/z")
        );
    }

    #[test]
    fn test_resolved_proxy_to_env_vars() {
        let proxy = ResolvedProxy {
            http_proxy: Some("http://proxy:8080".to_string()),
            https_proxy: Some("https://proxy:8443".to_string()),
            socks_proxy: None,
            no_proxy: Some("localhost,127.0.0.1".to_string()),
            source: ProxySource::GlobalConfig,
        };

        let vars = proxy.to_env_vars();
        assert_eq!(
            vars.get("HTTP_PROXY"),
            Some(&"http://proxy:8080".to_string())
        );
        assert_eq!(
            vars.get("http_proxy"),
            Some(&"http://proxy:8080".to_string())
        );
        assert_eq!(
            vars.get("HTTPS_PROXY"),
            Some(&"https://proxy:8443".to_string())
        );
        assert_eq!(
            vars.get("NO_PROXY"),
            Some(&"localhost,127.0.0.1".to_string())
        );
    }
}