Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions apps/bosunctl/src/listing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
//! Argument parsing and rendering for `bosunctl device list`.
//!
//! Kept free of `clap` and of any HID backend so it can be unit-tested on its
//! own.

use bosun_hid::DeviceInfo;

/// Parse a 16-bit identifier written in decimal or `0x`-prefixed hex.
pub fn parse_u16(raw: &str) -> Result<u16, String> {
let text = raw.trim();
let parsed = match text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
Some(hex) => u16::from_str_radix(hex, 16),
None => text.parse::<u16>(),
};

parsed.map_err(|_| format!("expected a decimal or 0x-prefixed hex 16-bit value, got `{raw}`"))
}

/// True when an unset filter accepts everything and a set one must match.
pub fn accepts(filter: Option<u16>, actual: u16) -> bool {
match filter {
Some(expected) => expected == actual,
None => true,
}
}

/// One device rendered as two lines: identity, then the path used to open it.
pub fn format_device(info: &DeviceInfo) -> String {
let manufacturer = info.manufacturer.as_deref().unwrap_or("<unknown>");
let product = info.product.as_deref().unwrap_or("<unnamed>");

format!(
"{:04x}:{:04x} usage_page={:04x} usage={:04x} iface={} {manufacturer} {product}\n path={}",
info.vendor_id, info.product_id, info.usage_page, info.usage, info.interface_number, info.path
)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn identifiers_parse_in_hex_and_decimal() {
assert_eq!(parse_u16("0x046D"), Ok(0x046D));
assert_eq!(parse_u16("0X046d"), Ok(0x046D));
assert_eq!(parse_u16("1133"), Ok(0x046D));
assert_eq!(parse_u16(" 0xff00 "), Ok(0xFF00));
assert_eq!(parse_u16("0"), Ok(0));
assert_eq!(parse_u16("65535"), Ok(0xFFFF));
}

#[test]
fn out_of_range_and_malformed_identifiers_are_rejected() {
// 0x10000 and 65536 do not fit in a u16; silently truncating either
// would match the wrong device.
assert!(parse_u16("0x10000").is_err());
assert!(parse_u16("65536").is_err());
assert!(parse_u16("").is_err());
assert!(parse_u16("nonsense").is_err());
assert!(parse_u16("-1").is_err());
assert!(
parse_u16("046D").is_err(),
"bare hex must not parse as decimal"
);
}

#[test]
fn an_unset_filter_accepts_every_value() {
assert!(accepts(None, 0x046D));
assert!(accepts(None, 0));
}

#[test]
fn a_set_filter_accepts_only_its_own_value() {
assert!(accepts(Some(0x046D), 0x046D));
assert!(!accepts(Some(0x046D), 0x046E));
}

#[test]
fn a_device_renders_with_its_open_path_and_padded_identifiers() {
let info = DeviceInfo {
path: "/dev/hidraw3".to_owned(),
vendor_id: 0x046D,
product_id: 0xC21C,
usage_page: 0xFF00,
usage: 0x0001,
interface_number: 0,
manufacturer: Some("Logitech".to_owned()),
product: Some("G13".to_owned()),
serial_number: None,
};

assert_eq!(
format_device(&info),
"046d:c21c usage_page=ff00 usage=0001 iface=0 Logitech G13\n path=/dev/hidraw3"
);
}

#[test]
fn missing_strings_render_as_placeholders_rather_than_blanks() {
let rendered = format_device(&DeviceInfo::default());

assert!(rendered.contains("<unknown> <unnamed>"), "{rendered}");
assert!(rendered.contains("0000:0000"), "{rendered}");
}
}
179 changes: 177 additions & 2 deletions apps/bosunctl/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,178 @@
fn main() {
println!("bosunctl: M1 implementation has not started; see docs/PLAN-REVIEW.md");
//! `bosunctl` — the Bosun control CLI.
//!
//! M1 scope. The CLI names devices by match criteria on the command line; no
//! product identifiers are compiled in.

mod listing;

use anyhow::{Context, Result};
use bosun_hid::{DeviceInfo, HidTransport};
use clap::{Args, Parser, Subcommand};
use tracing_subscriber::EnvFilter;

use crate::listing::{accepts, format_device, parse_u16};

#[derive(Debug, Parser)]
#[command(name = "bosunctl", version, about = "Bosun control CLI")]
struct Cli {
#[command(subcommand)]
command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
/// Inspect HID devices.
Device {
#[command(subcommand)]
command: DeviceCommand,
},
}

#[derive(Debug, Subcommand)]
enum DeviceCommand {
/// List enumerated HID interfaces, optionally filtered.
List(ListArgs),
}

#[derive(Debug, Args)]
struct ListArgs {
/// Vendor ID, decimal or 0x-prefixed hex.
#[arg(long, value_parser = parse_u16)]
vid: Option<u16>,

/// Product ID, decimal or 0x-prefixed hex.
#[arg(long, value_parser = parse_u16)]
pid: Option<u16>,

/// HID usage page, decimal or 0x-prefixed hex.
#[arg(long = "usage-page", value_parser = parse_u16)]
usage_page: Option<u16>,
}

impl ListArgs {
fn selects(&self, info: &DeviceInfo) -> bool {
accepts(self.vid, info.vendor_id)
&& accepts(self.pid, info.product_id)
&& accepts(self.usage_page, info.usage_page)
}
}

fn main() -> Result<()> {
// Logs go to stderr so stdout stays a clean, pipeable listing.
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
)
.with_writer(std::io::stderr)
.init();

let cli = Cli::parse();

match cli.command {
Command::Device { command } => match command {
DeviceCommand::List(args) => device_list(&args),
},
}
}

fn device_list(args: &ListArgs) -> Result<()> {
let api = HidTransport::api().context("could not initialise the HID backend")?;
let devices = HidTransport::enumerate(&api);
let matched: Vec<&DeviceInfo> = devices.iter().filter(|info| args.selects(info)).collect();

if matched.is_empty() {
println!("No HID interface matched. {} enumerated.", devices.len());
return Ok(());
}

for info in matched {
println!("{}", format_device(info));
}

Ok(())
}

#[cfg(test)]
mod tests {
use super::*;

use clap::CommandFactory;

/// Parse an argv into the `device list` arguments it produces.
fn list_args<const N: usize>(argv: [&str; N]) -> ListArgs {
match Cli::parse_from(argv).command {
Command::Device {
command: DeviceCommand::List(args),
} => args,
}
}

fn g13_vendor_collection() -> DeviceInfo {
DeviceInfo {
path: "vendor".to_owned(),
vendor_id: 0x046D,
product_id: 0xC21C,
usage_page: 0xFF00,
..DeviceInfo::default()
}
}

#[test]
fn the_cli_definition_is_valid() {
Cli::command().debug_assert();
}

#[test]
fn identifiers_accept_hex_on_the_command_line() {
let args = list_args([
"bosunctl",
"device",
"list",
"--vid",
"0x046D",
"--pid",
"0xC21C",
"--usage-page",
"0xFF00",
]);

assert_eq!(args.vid, Some(0x046D));
assert_eq!(args.pid, Some(0xC21C));
assert_eq!(args.usage_page, Some(0xFF00));
}

#[test]
fn an_unfiltered_list_selects_everything() {
let args = list_args(["bosunctl", "device", "list"]);

assert!(args.selects(&g13_vendor_collection()));
assert!(args.selects(&DeviceInfo::default()));
}

#[test]
fn a_usage_page_filter_excludes_the_other_collections_of_one_device() {
let args = list_args([
"bosunctl",
"device",
"list",
"--vid",
"0x046D",
"--pid",
"0xC21C",
"--usage-page",
"0xFF00",
]);

assert!(args.selects(&g13_vendor_collection()));
assert!(!args.selects(&DeviceInfo {
usage_page: 0x0001,
..g13_vendor_collection()
}));
}

#[test]
fn a_malformed_identifier_is_rejected_rather_than_ignored() {
assert!(Cli::try_parse_from(["bosunctl", "device", "list", "--vid", "zzz"]).is_err());
assert!(Cli::try_parse_from(["bosunctl", "device", "list", "--vid", "0x10000"]).is_err());
}
}
Loading
Loading