Skip to content

Commit 3834e83

Browse files
committed
better error for image format id parsing
1 parent 93a2746 commit 3834e83

File tree

3 files changed

+25
-10
lines changed

3 files changed

+25
-10
lines changed

espflash/src/error.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use miette::{Diagnostic, SourceOffset, SourceSpan};
66
use slip_codec::Error as SlipError;
77
use std::fmt::{Display, Formatter};
88
use std::io;
9-
use strum::AsStaticRef;
9+
use strum::{AsStaticRef, VariantNames};
1010
use thiserror::Error;
1111

1212
#[derive(Error, Debug, Diagnostic)]
@@ -51,6 +51,12 @@ pub enum Error {
5151
#[error(transparent)]
5252
#[diagnostic(transparent)]
5353
UnsupportedImageFormat(#[from] UnsupportedImageFormatError),
54+
#[error("Unrecognized image format {0}")]
55+
#[diagnostic(
56+
code(espflash::unknown_format),
57+
help("The following image formats are {}", ImageFormatId::VARIANTS.join(", "))
58+
)]
59+
UnknownImageFormat(String),
5460
}
5561

5662
#[derive(Error, Debug, Diagnostic)]

espflash/src/image_format/mod.rs

+17-4
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ pub use esp32bootloader::*;
88
pub use esp32directboot::*;
99
pub use esp8266::*;
1010

11-
use strum_macros::{AsStaticStr, Display, EnumString};
11+
use crate::error::Error;
12+
use std::str::FromStr;
13+
use strum_macros::{AsStaticStr, Display, EnumVariantNames};
1214

1315
const ESP_MAGIC: u8 = 0xE9;
1416
const WP_PIN_DISABLED: u8 = 0xEE;
@@ -44,10 +46,21 @@ pub trait ImageFormat<'a> {
4446
'a: 'b;
4547
}
4648

47-
#[derive(Debug, Copy, Clone, Eq, PartialEq, Display, EnumString, AsStaticStr)]
49+
#[derive(Debug, Copy, Clone, Eq, PartialEq, Display, AsStaticStr, EnumVariantNames)]
50+
#[strum(serialize_all = "kebab-case")]
4851
pub enum ImageFormatId {
49-
#[strum(serialize = "bootloader")]
5052
Bootloader,
51-
#[strum(serialize = "direct-boot")]
5253
DirectBoot,
5354
}
55+
56+
impl FromStr for ImageFormatId {
57+
type Err = Error;
58+
59+
fn from_str(s: &str) -> Result<Self, Self::Err> {
60+
match s {
61+
"bootloader" => Ok(Self::Bootloader),
62+
"direct-boot" => Ok(Self::DirectBoot),
63+
_ => Err(Error::UnknownImageFormat(s.into())),
64+
}
65+
}
66+
}

espflash/src/main.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -90,11 +90,7 @@ fn main() -> Result<()> {
9090
let image_format = image_format_string
9191
.as_deref()
9292
.map(ImageFormatId::from_str)
93-
.transpose()
94-
.into_diagnostic()
95-
.wrap_err_with(|| {
96-
format!("Unrecognized image format {}", image_format_string.unwrap())
97-
})?;
93+
.transpose()?;
9894
let partition_table = partition_table_path
9995
.as_deref()
10096
.map(|path| {

0 commit comments

Comments
 (0)