Skip to content

Commit bfbdece

Browse files
matoushybljessebraham
authored andcommitted
Reorder ports so that known ports appear first in CLI
1 parent 89d8836 commit bfbdece

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

espflash/src/cli/serial.rs

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use std::cmp::Ordering;
12
#[cfg(not(target_os = "windows"))]
23
use std::fs;
34

@@ -176,28 +177,44 @@ const KNOWN_DEVICES: &[UsbDevice] = &[
176177
];
177178

178179
fn select_serial_port(
179-
ports: Vec<SerialPortInfo>,
180+
mut ports: Vec<SerialPortInfo>,
180181
config: &Config,
181182
) -> Result<(SerialPortInfo, bool), Error> {
182-
let device_matches = |info| {
183+
fn device_matches(config: &Config, info: &UsbPortInfo) -> bool {
183184
config
184185
.usb_device
185186
.iter()
186187
.chain(KNOWN_DEVICES.iter())
187188
.any(|dev| dev.matches(info))
188-
};
189+
}
189190

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

197+
ports.sort_by(|a, b| {
198+
let a_matches = match &a.port_type {
199+
SerialPortType::UsbPort(info) => device_matches(config, info),
200+
_ => false,
201+
};
202+
let b_matches = match &b.port_type {
203+
SerialPortType::UsbPort(info) => device_matches(config, info),
204+
_ => false,
205+
};
206+
match (a_matches, b_matches) {
207+
(true, true) | (false, false) => Ordering::Equal,
208+
(true, false) => Ordering::Less,
209+
(false, true) => Ordering::Greater,
210+
}
211+
});
212+
196213
let port_names = ports
197214
.iter()
198215
.map(|port_info| match &port_info.port_type {
199216
SerialPortType::UsbPort(info) => {
200-
let formatted = if device_matches(info) {
217+
let formatted = if device_matches(config, info) {
201218
port_info.port_name.as_str().bold()
202219
} else {
203220
port_info.port_name.as_str().reset()
@@ -222,7 +239,7 @@ fn select_serial_port(
222239
match ports.get(index) {
223240
Some(port_info) => {
224241
let matches = if let SerialPortType::UsbPort(usb_info) = &port_info.port_type {
225-
device_matches(usb_info)
242+
device_matches(config, usb_info)
226243
} else {
227244
false
228245
};
@@ -248,7 +265,7 @@ fn select_serial_port(
248265
_ => unreachable!(),
249266
};
250267

251-
if device_matches(port_info) {
268+
if device_matches(config, port_info) {
252269
Ok((port.to_owned(), true))
253270
} else if confirm_port(&port_name, port_info)? {
254271
Ok((port.to_owned(), false))

0 commit comments

Comments
 (0)