proxy_x/
lib.rs

1use std::io;
2use std::net::UdpSocket;
3use std::process::Command;
4
5#[cfg(windows)]
6pub const NPM: &str = "npm.cmd";
7
8#[cfg(not(windows))]
9pub const NPM: &str = "npm";
10
11pub fn enable_proxy(proxy_url: &str) {
12    set_config("http.proxy", Some(proxy_url), "git");
13    set_config("proxy", Some(proxy_url), NPM);
14    println!("Proxy enabled");
15}
16
17pub fn disable_proxy() {
18    set_config("http.proxy", None, "git");
19    set_config("proxy", None, NPM);
20    println!("Proxy disabled");
21}
22
23pub fn get_agent_ip() -> io::Result<String> {
24    let socket = UdpSocket::bind("0.0.0.0:0")?;
25    socket.connect("8.8.8.8:53")?;
26
27    let local_addr = socket.local_addr()?;
28    Ok(local_addr.ip().to_string())
29}
30
31// Set or unset a configuration for a given tool.
32fn set_config(key: &str, value: Option<&str>, tool: &str) {
33    let mut args = match value {
34        Some(v) => vec!["config", "--global", key, v],
35        None => vec!["config", "--global", "--unset", key],
36    };
37    if tool == NPM {
38        args = match value {
39            Some(v) => vec!["config", "set", key, v],
40            None => vec!["config", "delete", key],
41        };
42    }
43    if let Err(e) = Command::new(tool).args(&args).output() {
44        eprintln!("Failed to set config for {}: {}", tool, e);
45    }
46}