1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
//! Types and functions for the command-line interface
//!
//! The contents of this module are intended for use with the [cargo-espflash]
//! and [espflash] command-line applications, and are likely not of much use
//! otherwise.
//!
//! Important note: The cli module DOES NOT provide SemVer guarantees,
//! feel free to opt-out by disabling the default `cli` feature.
//!
//! [cargo-espflash]: https://crates.io/crates/cargo-espflash
//! [espflash]: https://crates.io/crates/espflash

use std::{
    collections::HashMap,
    fs,
    io::Write,
    num::ParseIntError,
    path::{Path, PathBuf},
};

use clap::Args;
use clap_complete::Shell;
use comfy_table::{modifiers, presets::UTF8_FULL, Attribute, Cell, Color, Table};
use esp_idf_part::{DataType, Partition, PartitionTable};
use indicatif::{style::ProgressStyle, HumanCount, ProgressBar};
use log::{debug, info, warn};
use miette::{IntoDiagnostic, Result, WrapErr};
use serialport::{FlowControl, SerialPortType, UsbPortInfo};

use self::{
    config::Config,
    monitor::{monitor, LogFormat},
    serial::get_serial_port_info,
};
use crate::{
    connection::reset::{ResetAfterOperation, ResetBeforeOperation},
    elf::ElfFirmwareImage,
    error::{Error, MissingPartition, MissingPartitionTable},
    flasher::{
        parse_partition_table, FlashData, FlashFrequency, FlashMode, FlashSettings, FlashSize,
        Flasher, ProgressCallbacks,
    },
    targets::{Chip, XtalFrequency},
};

pub mod config;
pub mod monitor;

mod serial;

/// Establish a connection with a target device
#[derive(Debug, Args)]
#[non_exhaustive]
pub struct ConnectArgs {
    /// Reset operation to perform after connecting to the target
    #[arg(short = 'a', long, default_value = "hard-reset")]
    pub after: ResetAfterOperation,
    /// Baud rate at which to communicate with target device
    #[arg(short = 'B', long, env = "ESPFLASH_BAUD")]
    pub baud: Option<u32>,
    /// Reset operation to perform before connecting to the target
    #[arg(short = 'b', long, default_value = "default-reset")]
    pub before: ResetBeforeOperation,
    /// Target device
    #[arg(short = 'c', long)]
    pub chip: Option<Chip>,
    /// Require confirmation before auto-connecting to a recognized device.
    #[arg(short = 'C', long)]
    pub confirm_port: bool,
    /// List all available ports.
    #[arg(long)]
    pub list_all_ports: bool,
    /// Do not use the RAM stub for loading
    #[arg(long)]
    pub no_stub: bool,
    /// Serial port connected to target device
    #[arg(short = 'p', long, env = "ESPFLASH_PORT")]
    pub port: Option<String>,
}

/// Generate completions for the given shell
#[derive(Debug, Args)]
#[non_exhaustive]
pub struct CompletionsArgs {
    /// Shell to generate completions for.
    pub shell: Shell,
}

/// Erase entire flash of target device
#[derive(Debug, Args)]
#[non_exhaustive]
pub struct EraseFlashArgs {
    /// Connection configuration
    #[clap(flatten)]
    pub connect_args: ConnectArgs,
}

/// Erase specified region of flash
#[derive(Debug, Args)]
#[non_exhaustive]
pub struct EraseRegionArgs {
    /// Connection configuration
    #[clap(flatten)]
    pub connect_args: ConnectArgs,
    /// Offset to start erasing from
    #[arg(value_name = "OFFSET", value_parser = parse_uint32)]
    pub addr: u32,
    /// Size of the region to erase
    #[arg(value_name = "SIZE", value_parser = parse_uint32)]
    pub size: u32,
}

/// Configure communication with the target device's flash
#[derive(Debug, Args)]
#[non_exhaustive]
pub struct FlashConfigArgs {
    /// Flash frequency
    #[arg(short = 'f', long, value_name = "FREQ", value_enum)]
    pub flash_freq: Option<FlashFrequency>,
    /// Flash mode to use
    #[arg(short = 'm', long, value_name = "MODE", value_enum)]
    pub flash_mode: Option<FlashMode>,
    /// Flash size of the target
    #[arg(short = 's', long, value_name = "SIZE", value_enum)]
    pub flash_size: Option<FlashSize>,
}

/// Flash an application to a target device
#[derive(Debug, Args)]
#[non_exhaustive]
#[group(skip)]
pub struct FlashArgs {
    /// Erase partitions by label
    #[arg(long, value_name = "LABELS", value_delimiter = ',')]
    pub erase_parts: Option<Vec<String>>,
    /// Erase specified data partitions
    #[arg(long, value_name = "PARTS", value_enum, value_delimiter = ',')]
    pub erase_data_parts: Option<Vec<DataType>>,
    /// Logging format.
    #[arg(long, short = 'L', default_value = "serial", requires = "monitor")]
    pub log_format: LogFormat,
    /// Open a serial monitor after flashing
    #[arg(short = 'M', long)]
    pub monitor: bool,
    /// Baud rate at which to read console output
    #[arg(long, requires = "monitor", value_name = "BAUD")]
    pub monitor_baud: Option<u32>,
    /// Load the application to RAM instead of Flash
    #[arg(long)]
    pub ram: bool,
    /// Don't verify the flash contents after flashing
    #[arg(long)]
    pub no_verify: bool,
    /// Don't skip flashing of parts with matching checksum
    #[arg(long)]
    pub no_skip: bool,
    #[clap(flatten)]
    pub image: ImageArgs,
}

/// Operations for partitions tables
#[derive(Debug, Args)]
#[non_exhaustive]
pub struct PartitionTableArgs {
    /// Optional output file name, if unset will output to stdout
    #[arg(short = 'o', long, value_name = "FILE")]
    output: Option<PathBuf>,
    /// Input partition table
    #[arg(value_name = "FILE")]
    partition_table: PathBuf,
    /// Convert CSV partition table to binary representation
    #[arg(long, conflicts_with = "to_csv")]
    to_binary: bool,
    /// Convert binary partition table to CSV representation
    #[arg(long, conflicts_with = "to_binary")]
    to_csv: bool,
}

/// Reads the content of flash memory and saves it to a file
#[derive(Debug, Args)]
#[non_exhaustive]
pub struct ReadFlashArgs {
    /// Offset to start reading from
    #[arg(value_name = "OFFSET", value_parser = parse_uint32)]
    pub addr: u32,
    /// Size of each individual packet of data
    ///
    /// Defaults to 0x1000 (FLASH_SECTOR_SIZE)
    #[arg(long, default_value = "0x1000", value_parser = parse_uint32)]
    pub block_size: u32,
    /// Connection configuration
    #[clap(flatten)]
    connect_args: ConnectArgs,
    /// Size of the region to read
    #[arg(value_name = "SIZE", value_parser = parse_uint32)]
    pub size: u32,
    /// Name of binary dump
    #[arg(value_name = "FILE")]
    pub file: PathBuf,
    /// Maximum number of un-acked packets
    #[arg(long, default_value = "64", value_parser = parse_uint32)]
    pub max_in_flight: u32,
}

/// Save the image to disk instead of flashing to device
#[derive(Debug, Args)]
#[non_exhaustive]
#[group(skip)]
pub struct SaveImageArgs {
    /// Chip to create an image for
    #[arg(long, value_enum)]
    pub chip: Chip,
    /// File name to save the generated image to
    pub file: PathBuf,
    /// Boolean flag to merge binaries into single binary
    #[arg(long)]
    pub merge: bool,
    /// Don't pad the image to the flash size
    #[arg(long, short = 'P', requires = "merge")]
    pub skip_padding: bool,
    /// Cristal frequency of the target
    #[arg(long, short = 'x')]
    pub xtal_freq: Option<XtalFrequency>,
    #[clap(flatten)]
    pub image: ImageArgs,
}

#[derive(Debug, Args)]
#[non_exhaustive]
#[group(skip)]
pub struct ImageArgs {
    /// Path to a binary (.bin) bootloader file
    #[arg(long, value_name = "FILE")]
    pub bootloader: Option<PathBuf>,
    /// Path to a CSV file containing partition table
    #[arg(long, short = 'T', value_name = "FILE")]
    pub partition_table: Option<PathBuf>,
    /// Partition table offset
    #[arg(long, value_name = "OFFSET")]
    pub partition_table_offset: Option<u32>,
    /// Label of target app partition
    #[arg(long, value_name = "LABEL")]
    pub target_app_partition: Option<String>,
    /// Minimum chip revision supported by image, in format: major.minor
    #[arg(long, default_value = "0.0", value_parser = parse_chip_rev)]
    pub min_chip_rev: u16,
}

/// Open the serial monitor without flashing
#[derive(Debug, Args)]
#[non_exhaustive]
pub struct MonitorArgs {
    /// Connection configuration
    #[clap(flatten)]
    connect_args: ConnectArgs,
    /// Optional file name of the ELF image to load the symbols from
    #[arg(short = 'e', long, value_name = "FILE")]
    elf: Option<PathBuf>,
    /// Avoids asking the user for interactions like resetting the device
    #[arg(long)]
    non_interactive: bool,
    /// Logging format.
    #[arg(long, short = 'L', default_value = "serial", requires = "elf")]
    pub log_format: LogFormat,
}

#[derive(Debug, Args)]
#[non_exhaustive]
pub struct ChecksumMd5Args {
    /// Start address
    #[clap(short, long, value_parser=parse_u32)]
    address: u32,
    /// Length
    #[clap(short, long, value_parser=parse_u32)]
    length: u32,
    /// Connection configuration
    #[clap(flatten)]
    connect_args: ConnectArgs,
}

pub fn parse_u32(input: &str) -> Result<u32, ParseIntError> {
    parse_int::parse(input)
}

/// Select a serial port and establish a connection with a target device
pub fn connect(
    args: &ConnectArgs,
    config: &Config,
    no_verify: bool,
    no_skip: bool,
) -> Result<Flasher> {
    if args.before == ResetBeforeOperation::NoReset
        || args.before == ResetBeforeOperation::NoResetNoSync
    {
        warn!(
            "Pre-connection option '{:#?}' was selected. Connection may fail if the chip is not in bootloader or flasher stub mode.",
            args.before
        );
    }

    let port_info = get_serial_port_info(args, config)?;

    // Attempt to open the serial port and set its initial baud rate.
    info!("Serial port: '{}'", port_info.port_name);
    info!("Connecting...");

    let serial_port = serialport::new(&port_info.port_name, 115_200)
        .flow_control(FlowControl::None)
        .open_native()
        .map_err(Error::from)
        .wrap_err_with(|| format!("Failed to open serial port {}", port_info.port_name))?;

    // NOTE: since `get_serial_port_info` filters out all PCI Port and Bluetooth
    //       serial ports, we can just pretend these types don't exist here.
    let port_info = match port_info.port_type {
        SerialPortType::UsbPort(info) => info,
        SerialPortType::PciPort | SerialPortType::Unknown => {
            debug!("Matched `SerialPortType::PciPort or ::Unknown`");
            UsbPortInfo {
                vid: 0,
                pid: 0,
                serial_number: None,
                manufacturer: None,
                product: None,
            }
        }
        _ => unreachable!(),
    };

    Ok(Flasher::connect(
        *Box::new(serial_port),
        port_info,
        args.baud.or(config.baudrate),
        !args.no_stub,
        !no_verify,
        !no_skip,
        args.chip,
        args.after,
        args.before,
    )?)
}

/// Connect to a target device and print information about its chip
pub fn board_info(args: &ConnectArgs, config: &Config) -> Result<()> {
    let mut flasher = connect(args, config, true, true)?;
    print_board_info(&mut flasher)?;

    Ok(())
}

/// Connect to a target device and calculate the checksum of the given region
pub fn checksum_md5(args: &ChecksumMd5Args, config: &Config) -> Result<()> {
    let mut flasher = connect(&args.connect_args, config, true, true)?;

    let checksum = flasher.checksum_md5(args.address, args.length)?;
    println!("0x{:x}", checksum);

    Ok(())
}

/// Generate shell completions for the given shell
pub fn completions(args: &CompletionsArgs, app: &mut clap::Command, bin_name: &str) -> Result<()> {
    clap_complete::generate(args.shell, app, bin_name, &mut std::io::stdout());

    Ok(())
}

/// Parses chip revision from string to major * 100 + minor format
pub fn parse_chip_rev(chip_rev: &str) -> Result<u16> {
    let mut split = chip_rev.split('.');

    let parse_or_error = |value: Option<&str>| {
        value
            .ok_or_else(|| Error::ParseChipRevError {
                chip_rev: chip_rev.to_string(),
            })
            .and_then(|v| {
                v.parse::<u16>().map_err(|_| Error::ParseChipRevError {
                    chip_rev: chip_rev.to_string(),
                })
            })
            .into_diagnostic()
    };

    let major = parse_or_error(split.next())?;
    let minor = parse_or_error(split.next())?;

    if split.next().is_some() {
        return Err(Error::ParseChipRevError {
            chip_rev: chip_rev.to_string(),
        })
        .into_diagnostic();
    }

    Ok(major * 100 + minor)
}

/// Print information about a chip
pub fn print_board_info(flasher: &mut Flasher) -> Result<()> {
    let info = flasher.device_info()?;

    print!("Chip type:         {}", info.chip);
    if let Some((major, minor)) = info.revision {
        println!(" (revision v{major}.{minor})");
    } else {
        println!();
    }
    println!("Crystal frequency: {}", info.crystal_frequency);
    println!("Flash size:        {}", info.flash_size);
    println!("Features:          {}", info.features.join(", "));
    println!("MAC address:       {}", info.mac_address);

    Ok(())
}

/// Open a serial monitor
pub fn serial_monitor(args: MonitorArgs, config: &Config) -> Result<()> {
    let mut flasher = connect(&args.connect_args, config, true, true)?;
    let pid = flasher.get_usb_pid()?;

    let elf = if let Some(elf_path) = args.elf {
        let path = fs::canonicalize(elf_path).into_diagnostic()?;
        let data = fs::read(path).into_diagnostic()?;

        Some(data)
    } else {
        None
    };

    let chip = flasher.chip();
    let target = chip.into_target();

    // The 26MHz ESP32-C2's need to be treated as a special case.
    let default_baud = if chip == Chip::Esp32c2
        && target.crystal_freq(flasher.connection())? == XtalFrequency::_26Mhz
    {
        // 115_200 * 26 MHz / 40 MHz = 74_880
        74_880
    } else {
        115_200
    };

    monitor(
        flasher.into_serial(),
        elf.as_deref(),
        pid,
        args.connect_args.baud.unwrap_or(default_baud),
        args.log_format,
        !args.non_interactive,
    )
}

/// Convert the provided firmware image from ELF to binary
pub fn save_elf_as_image(
    elf_data: &[u8],
    chip: Chip,
    image_path: PathBuf,
    flash_data: FlashData,
    merge: bool,
    skip_padding: bool,
    xtal_freq: XtalFrequency,
) -> Result<()> {
    let image = ElfFirmwareImage::try_from(elf_data)?;

    if merge {
        // To get a chip revision, the connection is needed
        // For simplicity, the revision None is used
        let image =
            chip.into_target()
                .get_flash_image(&image, flash_data.clone(), None, xtal_freq)?;

        display_image_size(image.app_size(), image.part_size());

        let mut file = fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(image_path)
            .into_diagnostic()?;

        for segment in image.flash_segments() {
            let padding_bytes = vec![
                0xffu8;
                segment.addr as usize
                    - file.metadata().into_diagnostic()?.len() as usize
            ];
            file.write_all(&padding_bytes).into_diagnostic()?;
            file.write_all(&segment.data).into_diagnostic()?;
        }

        if !skip_padding {
            // Take flash_size as input parameter, if None, use default value of 4Mb
            let padding_bytes = vec![
                0xffu8;
                flash_data.flash_settings.size.unwrap_or_default().size()
                    as usize
                    - file.metadata().into_diagnostic()?.len() as usize
            ];
            file.write_all(&padding_bytes).into_diagnostic()?;
        }
    } else {
        let image = chip
            .into_target()
            .get_flash_image(&image, flash_data, None, xtal_freq)?;

        display_image_size(image.app_size(), image.part_size());

        let parts = image.ota_segments().collect::<Vec<_>>();
        match parts.as_slice() {
            [single] => fs::write(&image_path, &single.data).into_diagnostic()?,
            parts => {
                for part in parts {
                    let part_path = format!("{:#x}_{}", part.addr, image_path.display());
                    fs::write(part_path, &part.data).into_diagnostic()?
                }
            }
        }
    }

    info!("Image successfully saved!");

    Ok(())
}

/// Displays the image or app size
pub(crate) fn display_image_size(app_size: u32, part_size: Option<u32>) {
    if let Some(part_size) = part_size {
        let percent = app_size as f32 / part_size as f32 * 100.0;
        println!(
            "App/part. size:    {}/{} bytes, {:.2}%",
            HumanCount(app_size as u64),
            HumanCount(part_size as u64),
            percent
        );
    } else {
        println!("App size:          {} bytes", HumanCount(app_size as u64));
    }
}

/// Progress callback implementations for use in `cargo-espflash` and `espflash`
#[derive(Default)]
pub struct EspflashProgress {
    pb: Option<ProgressBar>,
}

impl ProgressCallbacks for EspflashProgress {
    /// Initialize the progress bar
    fn init(&mut self, addr: u32, len: usize) {
        let pb = ProgressBar::new(len as u64)
            .with_message(format!("{addr:#X}"))
            .with_style(
                ProgressStyle::default_bar()
                    .template("[{elapsed_precise}] [{bar:40}] {pos:>7}/{len:7} {msg}")
                    .unwrap()
                    .progress_chars("=> "),
            );

        self.pb = Some(pb);
    }

    /// Update the progress bar
    fn update(&mut self, current: usize) {
        if let Some(ref pb) = self.pb {
            pb.set_position(current as u64);
        }
    }

    /// End the progress bar
    fn finish(&mut self) {
        if let Some(ref pb) = self.pb {
            pb.finish();
        }
    }
}

pub fn erase_flash(args: EraseFlashArgs, config: &Config) -> Result<()> {
    if args.connect_args.no_stub {
        return Err(Error::StubRequired.into());
    }

    let mut flasher = connect(&args.connect_args, config, true, true)?;
    info!("Erasing Flash...");

    flasher.erase_flash()?;
    flasher
        .connection()
        .reset_after(!args.connect_args.no_stub)?;

    info!("Flash has been erased!");

    Ok(())
}

pub fn erase_region(args: EraseRegionArgs, config: &Config) -> Result<()> {
    if args.connect_args.no_stub {
        return Err(Error::StubRequired).into_diagnostic();
    }

    let mut flasher = connect(&args.connect_args, config, true, true)?;

    info!(
        "Erasing region at 0x{:08x} ({} bytes)",
        args.addr, args.size
    );

    flasher.erase_region(args.addr, args.size)?;
    flasher
        .connection()
        .reset_after(!args.connect_args.no_stub)?;

    Ok(())
}

/// Write an ELF image to a target device's flash
pub fn flash_elf_image(
    flasher: &mut Flasher,
    elf_data: &[u8],
    flash_data: FlashData,
    xtal_freq: XtalFrequency,
) -> Result<()> {
    // Load the ELF data, optionally using the provider bootloader/partition
    // table/image format, to the device's flash memory.
    flasher.load_elf_to_flash(
        elf_data,
        flash_data,
        Some(&mut EspflashProgress::default()),
        xtal_freq,
    )?;
    info!("Flashing has completed!");

    Ok(())
}

/// Erase one or more partitions by label or [DataType]
pub fn erase_partitions(
    flasher: &mut Flasher,
    partition_table: Option<PartitionTable>,
    erase_parts: Option<Vec<String>>,
    erase_data_parts: Option<Vec<DataType>>,
) -> Result<()> {
    let partition_table = match &partition_table {
        Some(partition_table) => partition_table,
        None => return Err(MissingPartitionTable.into()),
    };

    // Using a hashmap to deduplicate entries
    let mut parts_to_erase = None;

    // Look for any partitions with specific labels
    if let Some(part_labels) = erase_parts {
        for label in part_labels {
            let part = partition_table
                .find(label.as_str())
                .ok_or_else(|| MissingPartition::from(label))?;

            parts_to_erase
                .get_or_insert(HashMap::new())
                .insert(part.offset(), part);
        }
    }

    // Look for any data partitions with specific data subtype
    // There might be multiple partition of the same subtype, e.g. when using
    // multiple FAT partitions
    if let Some(partition_types) = erase_data_parts {
        for ty in partition_types {
            for part in partition_table.partitions() {
                if part.ty() == esp_idf_part::Type::Data
                    && part.subtype() == esp_idf_part::SubType::Data(ty)
                {
                    parts_to_erase
                        .get_or_insert(HashMap::new())
                        .insert(part.offset(), part);
                }
            }
        }
    }

    if let Some(parts) = parts_to_erase {
        parts
            .iter()
            .try_for_each(|(_, p)| erase_partition(flasher, p))?;
    }

    Ok(())
}

/// Erase a single partition
fn erase_partition(flasher: &mut Flasher, part: &Partition) -> Result<()> {
    log::info!("Erasing {} ({:?})...", part.name(), part.subtype());

    let offset = part.offset();
    let size = part.size();

    flasher.erase_region(offset, size).into_diagnostic()
}

/// Read flash content and write it to a file
pub fn read_flash(args: ReadFlashArgs, config: &Config) -> Result<()> {
    if args.connect_args.no_stub {
        return Err(Error::StubRequired.into());
    }

    let mut flasher = connect(&args.connect_args, config, false, false)?;
    print_board_info(&mut flasher)?;
    flasher.read_flash(
        args.addr,
        args.size,
        args.block_size,
        args.max_in_flight,
        args.file,
    )?;

    Ok(())
}

/// Convert and display CSV and binary partition tables
pub fn partition_table(args: PartitionTableArgs) -> Result<()> {
    if args.to_binary {
        let table = parse_partition_table(&args.partition_table)?;

        // Use either stdout or a file if provided for the output.
        let mut writer: Box<dyn Write> = if let Some(output) = args.output {
            Box::new(fs::File::create(output).into_diagnostic()?)
        } else {
            Box::new(std::io::stdout())
        };

        writer
            .write_all(&table.to_bin().into_diagnostic()?)
            .into_diagnostic()?;
    } else if args.to_csv {
        let input = fs::read(&args.partition_table).into_diagnostic()?;
        let table = PartitionTable::try_from_bytes(input).into_diagnostic()?;

        // Use either stdout or a file if provided for the output.
        let mut writer: Box<dyn Write> = if let Some(output) = args.output {
            Box::new(fs::File::create(output).into_diagnostic()?)
        } else {
            Box::new(std::io::stdout())
        };

        writer
            .write_all(table.to_csv().into_diagnostic()?.as_bytes())
            .into_diagnostic()?;
    } else {
        let input = fs::read(&args.partition_table).into_diagnostic()?;
        let table = PartitionTable::try_from(input).into_diagnostic()?;

        pretty_print(table);
    }

    Ok(())
}

/// Pretty print a partition table
fn pretty_print(table: PartitionTable) {
    let mut pretty = Table::new();

    pretty
        .load_preset(UTF8_FULL)
        .apply_modifier(modifiers::UTF8_ROUND_CORNERS)
        .set_header(vec![
            Cell::new("Name")
                .fg(Color::Green)
                .add_attribute(Attribute::Bold),
            Cell::new("Type")
                .fg(Color::Cyan)
                .add_attribute(Attribute::Bold),
            Cell::new("SubType")
                .fg(Color::Magenta)
                .add_attribute(Attribute::Bold),
            Cell::new("Offset")
                .fg(Color::Red)
                .add_attribute(Attribute::Bold),
            Cell::new("Size")
                .fg(Color::Yellow)
                .add_attribute(Attribute::Bold),
            Cell::new("Encrypted")
                .fg(Color::DarkCyan)
                .add_attribute(Attribute::Bold),
        ]);

    for p in table.partitions() {
        pretty.add_row(vec![
            Cell::new(p.name()).fg(Color::Green),
            Cell::new(p.ty().to_string()).fg(Color::Cyan),
            Cell::new(p.subtype().to_string()).fg(Color::Magenta),
            Cell::new(format!("{:#x}", p.offset())).fg(Color::Red),
            Cell::new(format!("{:#x} ({}KiB)", p.size(), p.size() / 1024)).fg(Color::Yellow),
            Cell::new(p.encrypted()).fg(Color::DarkCyan),
        ]);
    }

    println!("{pretty}");
}

/// Parses a string as a 32-bit unsigned integer.
pub fn parse_uint32(input: &str) -> Result<u32, ParseIntError> {
    parse_int::parse(input)
}

pub fn make_flash_settings(flash_config_args: &FlashConfigArgs, config: &Config) -> FlashSettings {
    FlashSettings::new(
        flash_config_args.flash_mode.or(config.flash.mode),
        flash_config_args.flash_size.or(config.flash.size),
        flash_config_args.flash_freq.or(config.flash.freq),
    )
}

pub fn make_flash_data(
    image_args: ImageArgs,
    flash_config_args: &FlashConfigArgs,
    config: &Config,
    default_bootloader: Option<&Path>,
    default_partition_table: Option<&Path>,
) -> Result<FlashData, Error> {
    let bootloader = image_args
        .bootloader
        .as_deref()
        .or(config.bootloader.as_deref())
        .or(default_bootloader);
    let partition_table = image_args
        .partition_table
        .as_deref()
        .or(config.partition_table.as_deref())
        .or(default_partition_table);

    if let Some(path) = &bootloader {
        println!("Bootloader:        {}", path.display());
    }
    if let Some(path) = &partition_table {
        println!("Partition table:   {}", path.display());
    }

    let flash_settings = make_flash_settings(flash_config_args, config);
    FlashData::new(
        bootloader,
        partition_table,
        image_args.partition_table_offset,
        image_args.target_app_partition,
        flash_settings,
        image_args.min_chip_rev,
    )
}