♻️ refactor: move more Windows-only code behind cfg flags

main
_ 2021-12-09 00:11:47 +00:00
parent dbedc6083e
commit ee51bb7d3d
2 changed files with 87 additions and 55 deletions

View File

@ -6,6 +6,10 @@ use std::{
use crate::AppError; use crate::AppError;
#[cfg(target_os = "linux")]
pub mod linux {
use super::*;
pub fn get_ip_addr_output () -> Result <String, AppError> { pub fn get_ip_addr_output () -> Result <String, AppError> {
let output = Command::new ("ip") let output = Command::new ("ip")
.arg ("addr") .arg ("addr")
@ -25,6 +29,11 @@ pub fn parse_ip_addr_output (output: &str) -> Vec <Ipv4Addr> {
.filter_map (|l| Ipv4Addr::from_str (l).ok ()) .filter_map (|l| Ipv4Addr::from_str (l).ok ())
.collect () .collect ()
} }
}
#[cfg(target_os = "windows")]
pub mod windows {
use super::*;
pub fn get_ip_config_output () -> Result <String, AppError> { pub fn get_ip_config_output () -> Result <String, AppError> {
let output = Command::new ("ipconfig") let output = Command::new ("ipconfig")
@ -60,3 +69,26 @@ pub fn parse_ip_config_output (output: &str) -> Vec <Ipv4Addr> {
addrs addrs
} }
#[cfg (test)]
mod test {
use super::*;
#[test]
fn test () {
for (input, expected) in [
(
r"
IPv4 Address . . .. . . . : 192.168.1.1
",
vec! [
Ipv4Addr::new (192, 168, 1, 1),
]
),
] {
let actual = parse_ip_config_output (input);
assert_eq! (actual, expected);
}
}
}
}

View File

@ -111,9 +111,9 @@ async fn async_main () -> Result <(), AppError> {
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
fn my_ips () -> Result <(), AppError> { fn my_ips () -> Result <(), AppError> {
let output = ip::get_ip_addr_output ()?; let output = ip::linux::get_ip_addr_output ()?;
for addr in ip::parse_ip_addr_output (&output) for addr in ip::linux::parse_ip_addr_output (&output)
.iter () .iter ()
.filter (|a| ! a.is_loopback ()) .filter (|a| ! a.is_loopback ())
{ {
@ -131,9 +131,9 @@ fn my_ips () -> Result <(), AppError> {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
fn my_ips () -> Result <(), AppError> { fn my_ips () -> Result <(), AppError> {
let output = ip::get_ip_config_output ()?; let output = ip::windows::get_ip_config_output ()?;
for addr in ip::parse_ip_config_output (&output) { for addr in ip::windows::parse_ip_config_output (&output) {
println! ("{:?}", addr); println! ("{:?}", addr);
} }