Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reorder ports so that known ports appear first in CLI #324

Merged
merged 1 commit into from
Dec 19, 2022
Merged
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
29 changes: 23 additions & 6 deletions espflash/src/cli/serial.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::cmp::Ordering;
#[cfg(not(target_os = "windows"))]
use std::fs;

Expand Down Expand Up @@ -176,28 +177,44 @@ const KNOWN_DEVICES: &[UsbDevice] = &[
];

fn select_serial_port(
ports: Vec<SerialPortInfo>,
mut ports: Vec<SerialPortInfo>,
config: &Config,
) -> Result<(SerialPortInfo, bool), Error> {
let device_matches = |info| {
fn device_matches(config: &Config, info: &UsbPortInfo) -> bool {
config
.usb_device
.iter()
.chain(KNOWN_DEVICES.iter())
.any(|dev| dev.matches(info))
};
}

if ports.len() > 1 {
// Multiple serial ports detected
info!("Detected {} serial ports", ports.len());
info!("Ports which match a known common dev board are highlighted");
info!("Please select a port");

ports.sort_by(|a, b| {
let a_matches = match &a.port_type {
SerialPortType::UsbPort(info) => device_matches(config, info),
_ => false,
};
let b_matches = match &b.port_type {
SerialPortType::UsbPort(info) => device_matches(config, info),
_ => false,
};
match (a_matches, b_matches) {
(true, true) | (false, false) => Ordering::Equal,
(true, false) => Ordering::Less,
(false, true) => Ordering::Greater,
}
});

let port_names = ports
.iter()
.map(|port_info| match &port_info.port_type {
SerialPortType::UsbPort(info) => {
let formatted = if device_matches(info) {
let formatted = if device_matches(config, info) {
port_info.port_name.as_str().bold()
} else {
port_info.port_name.as_str().reset()
Expand All @@ -222,7 +239,7 @@ fn select_serial_port(
match ports.get(index) {
Some(port_info) => {
let matches = if let SerialPortType::UsbPort(usb_info) = &port_info.port_type {
device_matches(usb_info)
device_matches(config, usb_info)
} else {
false
};
Expand All @@ -248,7 +265,7 @@ fn select_serial_port(
_ => unreachable!(),
};

if device_matches(port_info) {
if device_matches(config, port_info) {
Ok((port.to_owned(), true))
} else if confirm_port(&port_name, port_info)? {
Ok((port.to_owned(), false))
Expand Down