use super::netrc;
use std::fmt;
#[derive(Clone)]
pub struct NetrcStore {
entries: Vec<NetrcEntry>,
default_entry: Option<NetrcEntry>,
}
impl fmt::Debug for NetrcStore {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("NetrcStore")
.field("entry_count", &self.entries.len())
.field("has_default_entry", &self.default_entry.is_some())
.finish()
}
}
#[derive(Clone)]
pub struct NetrcEntry {
pub host: String,
pub login: String,
pub password: String,
}
impl fmt::Debug for NetrcEntry {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("NetrcEntry")
.field("host", &self.host)
.field("login", &"<redacted>")
.field("password", &"<redacted>")
.finish()
}
}
impl NetrcStore {
pub fn new() -> Self {
Self {
entries: Vec::new(),
default_entry: None,
}
}
pub fn from_entries(entries: Vec<NetrcEntry>) -> Self {
Self {
entries,
default_entry: None,
}
}
pub fn with_default(entries: Vec<NetrcEntry>, default: Option<NetrcEntry>) -> Self {
Self {
entries,
default_entry: default,
}
}
pub fn find(&self, host: &str) -> Option<&NetrcEntry> {
self.entries
.iter()
.find(|entry| netrc::no_proxy_domain_match(host, &entry.host))
}
pub fn find_with_fallback(&self, host: &str) -> Option<&NetrcEntry> {
self.find(host).or(self.default_entry.as_ref())
}
pub fn default_entry(&self) -> Option<&NetrcEntry> {
self.default_entry.as_ref()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty() && self.default_entry.is_none()
}
}
impl Default for NetrcStore {
fn default() -> Self {
Self::new()
}
}
impl From<netrc::NetrcParser> for NetrcStore {
fn from(parser: netrc::NetrcParser) -> Self {
let mut entries = Vec::with_capacity(parser.entries().len());
for entry in parser.entries() {
if let (Some(login), Some(password)) = (&entry.login, &entry.password) {
entries.push(NetrcEntry {
host: entry.machine.clone(),
login: login.clone(),
password: password.clone(),
});
}
}
let default_entry = parser.default_entry().and_then(|entry| {
if let (Some(login), Some(password)) = (&entry.login, &entry.password) {
Some(NetrcEntry {
host: String::new(),
login: login.clone(),
password: password.clone(),
})
} else {
None
}
});
Self {
entries,
default_entry,
}
}
}