Skip to content

Commit

Permalink
format; help max_term_width=80 for readability
Browse files Browse the repository at this point in the history
  • Loading branch information
tuna-f1sh committed Jan 10, 2023
1 parent e80c532 commit ca58f37
Show file tree
Hide file tree
Showing 10 changed files with 116 additions and 75 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description = "List system USB buses and devices; a modern and compatible `lsusb
repository = "https://github.com/tuna-f1sh/cyme"
readme = "README.md"
license = "GPL-3.0-or-later"
version = "1.2.2"
version = "1.2.3"
edition = "2021"
keywords = ["usb", "lsusb", "system_profiler", "macos", "libusb"]
categories = ["command-line-utilities"]
Expand Down
14 changes: 9 additions & 5 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ use std::io;
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};

use crate::colour;
use crate::display;
use crate::display::Block;
use crate::colour;
use crate::icon;

const CONF_DIR: &'static str = "cyme";
Expand Down Expand Up @@ -73,17 +73,21 @@ impl Config {
let path = p.join(CONF_NAME);
log::info!("Looking for cyme system config {:?}", &path);
return match Self::from_file(&path) {
Ok(c) => {
Ok(c) => {
log::info!("Loaded cyme system config {:?}", c);
c
},
}
Err(e) => {
if e.kind() != io::ErrorKind::NotFound {
log::warn!("Failed to read cyme system config {:?}: Error({})", &path, e);
log::warn!(
"Failed to read cyme system config {:?}: Error({})",
&path,
e
);
}
Self::new()
}
}
};
}
Self::new()
}
Expand Down
35 changes: 21 additions & 14 deletions src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
use clap::ValueEnum;
use colored::*;
use itertools::Itertools;
use rand::{distributions::Alphanumeric, seq::IteratorRandom, Rng};
use serde::{Deserialize, Serialize};
use std::cmp;
use std::collections::HashMap;
use rand::{distributions::Alphanumeric, seq::IteratorRandom, Rng};

use crate::colour;
use crate::icon;
Expand Down Expand Up @@ -959,8 +959,7 @@ impl Block<InterfaceBlocks, USBInterface> for InterfaceBlocks {
InterfaceBlocks::Driver => ct.driver.map_or(s.normal(), |c| s.color(c)),
InterfaceBlocks::AltSetting | InterfaceBlocks::NumEndpoints => {
ct.number.map_or(s.normal(), |c| s.color(c))
}
// _ => s.normal(),
} // _ => s.normal(),
}
}

Expand Down Expand Up @@ -1199,8 +1198,7 @@ impl Block<EndpointBlocks, USBEndpoint> for EndpointBlocks {
}
EndpointBlocks::UsageType => {
format!("{:^pad$}", "UsageT", pad = pad.get(self).unwrap_or(&0))
}
// _ => "",
} // _ => "",
}
}
}
Expand Down Expand Up @@ -2034,19 +2032,28 @@ pub fn mask_serial(device: &mut system_profiler::USBDevice, hide: &MaskSerial, r
if let Some(serial) = device.serial_num.as_mut() {
*serial = match hide {
MaskSerial::Hide => serial.chars().map(|_| '*').collect::<String>(),
MaskSerial::Scramble =>
serial.chars().map(|_| serial.chars().choose(&mut rand::thread_rng()).unwrap_or('*')).collect::<String>(),
MaskSerial::Replace =>
rand::thread_rng()
.sample_iter(Alphanumeric)
.take(serial.chars().count())
.map(char::from)
.collect::<String>().to_uppercase(),
MaskSerial::Scramble => serial
.chars()
.map(|_| {
serial
.chars()
.choose(&mut rand::thread_rng())
.unwrap_or('*')
})
.collect::<String>(),
MaskSerial::Replace => rand::thread_rng()
.sample_iter(Alphanumeric)
.take(serial.chars().count())
.map(char::from)
.collect::<String>()
.to_uppercase(),
};
}

if recursive {
device.devices.as_mut().map_or((), |dd| dd.iter_mut().for_each(|d| mask_serial(d, hide, recursive)));
device.devices.as_mut().map_or((), |dd| {
dd.iter_mut().for_each(|d| mask_serial(d, hide, recursive))
});
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/icon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,10 @@ pub fn example() -> HashMap<Icon, String> {

/// Returns example theme with [`Icon`] types and default tree
pub fn example_theme() -> IconTheme {
let tree_strings: HashMap<Icon, String> = DEFAULT_TREE.iter().map(|(k, v)| (k.to_owned(), v.to_string())).collect();
let tree_strings: HashMap<Icon, String> = DEFAULT_TREE
.iter()
.map(|(k, v)| (k.to_owned(), v.to_string()))
.collect();

IconTheme {
user: Some(example()),
Expand Down
23 changes: 14 additions & 9 deletions src/lsusb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ pub mod profiler {
//! ```
//!
//! See [`system_profiler`] docs for what can be done with returned data, such as [`system_profiler::USBFilter`]
use std::collections::HashMap;
use std::time::Duration;
use itertools::Itertools;
use rusb as libusb;
use std::collections::HashMap;
use std::time::Duration;
use usb_ids::{self, FromId};

use crate::{system_profiler, types::NumericalUnit, usb};
#[cfg(all(target_os = "linux", feature = "udev"))]
use crate::udev;
use crate::{system_profiler, types::NumericalUnit, usb};

struct UsbDevice<T: libusb::UsbContext> {
handle: libusb::DeviceHandle<T>,
Expand Down Expand Up @@ -574,9 +574,7 @@ pub mod profiler {
/// Fills a passed mutable `spusb` reference to fill using `get_spusb`. Will replace existing [`system_profiler::USBDevice`]s found in the libusb build but leave others and the buses.
///
/// The main use case for this is to merge with macOS `system_profiler` data, so that [`usb::USBDeviceExtra`] can be obtained but internal buses kept. One could also use it to update a static .json dump.
pub fn fill_spusb(
spusb: &mut system_profiler::SPUSBDataType,
) -> Result<(), libusb::Error> {
pub fn fill_spusb(spusb: &mut system_profiler::SPUSBDataType) -> Result<(), libusb::Error> {
let libusb_spusb = get_spusb_with_extra()?;

// merge if passed has any buses
Expand Down Expand Up @@ -719,8 +717,12 @@ pub mod display {
.expect("Cannot print verbose without extra data");

println!("Device Descriptor:");
println!(" bcdUSB {}",
device.bcd_usb.as_ref().map_or(String::new(), |v| v.to_string())
println!(
" bcdUSB {}",
device
.bcd_usb
.as_ref()
.map_or(String::new(), |v| v.to_string())
);
println!(
" bDeviceClass {:3} {}",
Expand All @@ -745,7 +747,10 @@ pub mod display {
);
println!(
" bcdDevice {}",
device.bcd_device.as_ref().map_or(String::new(), |v| v.to_string())
device
.bcd_device
.as_ref()
.map_or(String::new(), |v| v.to_string())
);
println!(
" iManufacturer {:3} {}",
Expand Down
20 changes: 12 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use cyme::usb::ClassCode;

#[derive(Parser, Debug, Default, Serialize, Deserialize)]
#[skip_serializing_none]
#[command(author, version, about, long_about = None)]
#[command(author, version, about, long_about = None, max_term_width=80)]
struct Args {
/// Attempt to maintain compatibility with lsusb output
#[arg(short, long, default_value_t = false)]
Expand Down Expand Up @@ -284,15 +284,19 @@ fn get_libusb_spusb(_args: &Args) -> system_profiler::SPUSBDataType {
#[cfg(feature = "libusb")]
fn get_libusb_spusb(args: &Args) -> system_profiler::SPUSBDataType {
if args.verbose > 0
|| args.tree
|| args.device.is_some()
|| args.lsusb
|| args.json
|| args.more {
|| args.tree
|| args.device.is_some()
|| args.lsusb
|| args.json
|| args.more
{
lsusb::profiler::get_spusb_with_extra().unwrap_or_else(|e| {
eprintexit!(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Failed to gather system USB data with extra from libusb: Error({})", e)
format!(
"Failed to gather system USB data with extra from libusb: Error({})",
e
)
));
})
} else {
Expand Down Expand Up @@ -341,10 +345,10 @@ fn print_lsusb(
#[cfg(feature = "cli_generate")]
#[cold]
fn print_man() -> Result<(), Error> {
use std::fs;
use clap::CommandFactory;
use clap_complete::generate_to;
use clap_complete::shells::*;
use std::fs;
use std::path::PathBuf;

let outdir = std::env::var_os("BUILD_SCRIPT_DIR")
Expand Down
56 changes: 32 additions & 24 deletions src/system_profiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@
//!
//! let spusb = system_profiler::get_spusb_with_extra().unwrap();
//! ```
use colored::*;
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use serde_with::{skip_serializing_none, DeserializeFromStr, SerializeDisplay};
use std::fmt;
use std::io;
use std::fs;
use std::io;
use std::io::Read;
use std::process::Command;
use std::str::FromStr;
use std::io::Read;
use serde::de::{self, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use serde_with::{skip_serializing_none, DeserializeFromStr, SerializeDisplay};
use colored::*;

use crate::types::NumericalUnit;
use crate::usb::*;
Expand Down Expand Up @@ -666,10 +666,18 @@ pub struct USBDevice {
pub serial_num: Option<String>,
/// The device manufacturer as provided in descriptor or using usb_ids if None
pub manufacturer: Option<String>,
#[serde(default, serialize_with = "version_serializer", deserialize_with = "deserialize_option_version_from_string")]
#[serde(
default,
serialize_with = "version_serializer",
deserialize_with = "deserialize_option_version_from_string"
)]
/// The device release number set by the developer as a [`Version`]
pub bcd_device: Option<Version>,
#[serde(default, serialize_with = "version_serializer", deserialize_with = "deserialize_option_version_from_string")]
#[serde(
default,
serialize_with = "version_serializer",
deserialize_with = "deserialize_option_version_from_string"
)]
/// The highest version of USB the device supports as a [`Version`]
pub bcd_usb: Option<Version>,
#[serde(default, deserialize_with = "deserialize_option_number_from_string")]
Expand Down Expand Up @@ -710,9 +718,10 @@ impl USBDevice {
/// Does the device have an interface with `class`
pub fn has_interface_class(&self, c: &ClassCode) -> bool {
if let Some(extra) = self.extra.as_ref() {
extra.configurations.iter().any(|conf| {
conf.interfaces.iter().any(|i| i.class == *c)
})
extra
.configurations
.iter()
.any(|conf| conf.interfaces.iter().any(|i| i.class == *c))
} else {
false
}
Expand Down Expand Up @@ -990,12 +999,12 @@ impl USBDevice {

/// Generate a String from self like lsusb default list device
/// ```
/// let d = cyme::system_profiler::USBDevice{
/// name: String::from("Test device"),
/// manufacturer: Some(String::from("Test Devices Inc.")),
/// let d = cyme::system_profiler::USBDevice{
/// name: String::from("Test device"),
/// manufacturer: Some(String::from("Test Devices Inc.")),
/// vendor_id: Some(0x1234),
/// product_id: Some(0x4321),
/// location_id: cyme::system_profiler::DeviceLocation { bus: 1, number: 4, tree_positions: vec![1, 2, 3] },
/// location_id: cyme::system_profiler::DeviceLocation { bus: 1, number: 4, tree_positions: vec![1, 2, 3] },
/// ..Default::default()
/// };
/// assert_eq!(d.to_lsusb_string(), "Bus 001 Device 004: ID 1234:4321 Test Devices Inc. Test device");
Expand Down Expand Up @@ -1285,13 +1294,10 @@ impl USBFilter {
.map_or(false, |s| s.contains(n.as_str()))
}))
&& (self.class.as_ref().map_or(true, |fc| {
device
.class
.as_ref()
.map_or(false, |c| c == fc) || device.has_interface_class(fc)
device.class.as_ref().map_or(false, |c| c == fc) || device.has_interface_class(fc)
}))
&& !(self.exclude_empty_hub && device.is_hub() && !device.has_devices())
&& (!device.is_root_hub() || self.no_exclude_root_hub)
&& (!device.is_root_hub() || self.no_exclude_root_hub)
}

/// Recursively retain only `USBBus` in `buses` with `USBDevice` matching filter
Expand Down Expand Up @@ -1385,13 +1391,13 @@ pub fn get_spusb_with_extra() -> Result<SPUSBDataType, io::Error> {
let mut spusb = get_spusb().map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("Failed to parse system_profiler output: Error({})", e)
format!("Failed to parse system_profiler output: Error({})", e),
)
})?;
crate::lsusb::profiler::fill_spusb(&mut spusb).map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("Failed to gather system USB data from libusb: Error({})", e)
format!("Failed to gather system USB data from libusb: Error({})", e),
)
})?;

Expand All @@ -1403,7 +1409,7 @@ pub fn get_spusb_with_extra() -> Result<SPUSBDataType, io::Error> {
pub fn get_spusb_with_extra() -> Result<SPUSBDataType, io::Error> {
Err(io::Error::new(
io::ErrorKind::Other,
"libusb feature is required to do this, install with `cargo install --features libusb`"
"libusb feature is required to do this, install with `cargo install --features libusb`",
))
}

Expand Down Expand Up @@ -1455,7 +1461,9 @@ where
}
}

fn deserialize_option_version_from_string<'de, D>(deserializer: D) -> Result<Option<Version>, D::Error>
fn deserialize_option_version_from_string<'de, D>(
deserializer: D,
) -> Result<Option<Version>, D::Error>
where
D: Deserializer<'de>,
{
Expand Down
Loading

0 comments on commit ca58f37

Please sign in to comment.