Skip to content

Commit

Permalink
refactor: remove something redundant
Browse files Browse the repository at this point in the history
  • Loading branch information
pplmx committed Dec 12, 2023
1 parent d5f5908 commit 6e8c7ef
Showing 1 changed file with 28 additions and 29 deletions.
57 changes: 28 additions & 29 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,54 +1,53 @@
// lib.rs
#[cfg(windows)]
pub const NPM: &str = "npm.cmd";

#[cfg(not(windows))]
pub const NPM: &str = "npm";

pub mod proxy_manager {
use std::env;
use std::process::Command;

use crate::NPM;

pub fn enable_proxy(proxy_url: &str) {
git_config("http.proxy", Some(proxy_url));
npm_config("proxy", Some(proxy_url));
set_config("http.proxy", Some(proxy_url), "git");
set_config("proxy", Some(proxy_url), NPM);

std::env::set_var("all_proxy", proxy_url);
std::env::set_var("http_proxy", proxy_url);
std::env::set_var("https_proxy", proxy_url);
std::env::set_var("no_proxy", "localhost, 127.0.0.1, ::1, .local, .internal, 192.168.0.0/16, 10.0.0.0/8, 172.16.0.0/12");
let proxies = ["all_proxy", "http_proxy", "https_proxy"];
let no_proxy = "localhost, 127.0.0.1, ::1, .local, .internal, 192.168.0.0/16, 10.0.0.0/8, 172.16.0.0/12";
for proxy in proxies.iter() {
env::set_var(proxy, proxy_url);
}
env::set_var("no_proxy", no_proxy);
println!("Proxy enabled");
}

pub fn disable_proxy() {
git_config("http.proxy", None);
npm_config("proxy", None);
set_config("http.proxy", None, "git");
set_config("proxy", None, NPM);

std::env::remove_var("all_proxy");
std::env::remove_var("http_proxy");
std::env::remove_var("https_proxy");
std::env::remove_var("no_proxy");
let proxies = ["all_proxy", "http_proxy", "https_proxy", "no_proxy"];
for proxy in proxies.iter() {
env::remove_var(proxy);
}
println!("Proxy disabled");
}

// git global config. if value is None, unset the key
fn git_config(key: &str, value: Option<&str>) {
let mut args = vec!["config", "--global"];
match value {
Some(v) => args.extend_from_slice(&[key, v]),
None => args.extend_from_slice(&["--unset", key]),
// Set or unset a configuration for a given tool.
fn set_config(key: &str, value: Option<&str>, tool: &str) {
let mut args = match value {
Some(v) => vec!["config", "--global", key, v],
None => vec!["config", "--global", "--unset", key],
};
if tool == NPM {
args = match value {
Some(v) => vec!["config", "set", key, v],
None => vec!["config", "delete", key],
};
}
Command::new("git").args(&args).output().ok();
}

// npm config. if value is None, unset the key
fn npm_config(key: &str, value: Option<&str>) {
let mut args = vec!["config"];
match value {
Some(v) => args.extend_from_slice(&["set", key, v]),
None => args.extend_from_slice(&["delete", key]),
if let Err(e) = Command::new(tool).args(&args).output() {
eprintln!("Failed to set config for {}: {}", tool, e);
}
Command::new(NPM).args(&args).output().ok();
}
}

0 comments on commit 6e8c7ef

Please sign in to comment.