Add config file support

This commit is contained in:
2026-07-08 14:22:40 +05:30
parent cf408c1088
commit 7ba49e4e49
3 changed files with 342 additions and 20 deletions
+57 -20
View File
@@ -1,25 +1,22 @@
mod config;
mod error;
use std::env::args;
use std::net::UdpSocket;
fn get_magic_pkt(mac: &str, magic_bytes: &mut [u8; 102]) {
let mut mac_bytes = [0u8; 6];
for (i, part) in mac.split(':').enumerate() {
mac_bytes[i] = u8::from_str_radix(part, 16)
.expect(&format!("'{}' is not a valid hex between 00-ff", part));
}
use crate::config::{Config, Mac};
use crate::error::EResult;
magic_bytes[..6].fill(0xFF);
for i in 0..16 {
let start = 6 + i * 6;
magic_bytes[start..start + 6].copy_from_slice(&mac_bytes);
}
}
fn main() -> EResult<()> {
let config = Config::create()?;
fn main() {
let mac = args()
.nth(1)
.expect("no mac given; Usage woly aa:bb:cc:dd:ee:ff");
let arg_1 = args().nth(1);
let Some(arg_1) = arg_1 else {
print_usage();
return Ok(());
};
let mac = config.get_mac(&arg_1)?;
let mut magic_bytes = [0u8; 102];
get_magic_pkt(&mac, &mut magic_bytes);
@@ -28,17 +25,54 @@ fn main() {
socket
.send_to(&magic_bytes, "255.255.255.255:9")
.expect("couldn't send data");
println!("Magic packet sent to 255.255.255.255:9 for Mac {:?}", mac);
println!("Magic packet sent to 255.255.255.255:9 for Mac {:}", mac);
Ok(())
}
fn get_magic_pkt(mac: &Mac, magic_bytes: &mut [u8; 102]) {
magic_bytes[..6].fill(0xFF);
for i in 0..16 {
let start = 6 + i * 6;
magic_bytes[start..start + 6].copy_from_slice(&mac.mac_bytes);
}
}
fn print_usage() {
println!(
"{}",
r#"usage: woly ARG
Options:
ARG Either the mac address of the device to send the wol magic
packet to, or a nickname specified in woly.conf to lookup
the mac.
Eg: woly aa:bb:cc:dd:ee:ff
Eg: woly potato
where potato is configured in the woly.conf file as
potato=aa:bb:cc:dd:ee:ff
Config file:
Filename woly.conf
Location $WOLY_CONFIG_DIR/woly.conf, then $XDG_CONFIG_DIR/woly.conf,
then $HOME/woly.conf
Format one KEY=VALUE per line without spaces
Example potato=aa:bb:cc:dd:ee:ff
idly=12:34:23:e2:3d:ff
"#
);
}
#[cfg(test)]
mod tests {
use crate::get_magic_pkt;
use crate::{config::Mac, get_magic_pkt};
#[test]
fn test_magic_bytes_for_mac() {
let mut magic_bytes = [0u8; 102];
get_magic_pkt("32:1a:ff:3e:10:ef", &mut magic_bytes);
let mac = Mac::create("32:1a:ff:3e:10:ef").expect("Test data is curated to be valid");
get_magic_pkt(&mac, &mut magic_bytes);
#[rustfmt::skip]
let expected = [
255, 255, 255, 255, 255, 255,
50, 26, 255, 62, 16, 239,
@@ -59,6 +93,9 @@ mod tests {
50, 26, 255, 62, 16, 239,
];
assert_eq!(magic_bytes, expected, "Magic bytes are not created correctly");
assert_eq!(
magic_bytes, expected,
"Magic bytes are not created correctly"
);
}
}