Skip to content

Commit f65ea62

Browse files
committed
fix: handle missing element index in delete subcommand
1 parent b3d651c commit f65ea62

1 file changed

Lines changed: 23 additions & 15 deletions

File tree

src/arguments/delete.rs

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -29,28 +29,36 @@ pub struct DeleteArgs {
2929

3030
impl SubcommandExecutor for DeleteArgs {
3131
fn run_command(self, mut otp_database: OTPDatabase) -> color_eyre::Result<OTPDatabase> {
32+
if otp_database.elements_ref().is_empty() {
33+
return Err(eyre!("There are no elements to delete"));
34+
}
35+
3236
let index_to_delete = self
3337
.index
3438
.and_then(|i| i.checked_sub(1))
39+
// Match by issues or label if index filter is missing
3540
.or_else(|| get_first_matching_element(&otp_database, &self))
3641
.ok_or(eyre!("No code has been found using the given arguments"))?;
3742

38-
let element = otp_database.elements_ref().get(index_to_delete).unwrap();
39-
print!(
40-
"Are you sure you want to delete the {}th code ({}, {}) [Y,N]: ",
41-
index_to_delete + 1,
42-
element.issuer,
43-
element.label
44-
);
45-
io::stdout().flush()?;
46-
47-
let output = read_confirmation_line()?;
48-
49-
if output.trim().eq_ignore_ascii_case("y") {
50-
otp_database.delete_element(index_to_delete);
51-
Ok(otp_database)
43+
if let Some(element) = otp_database.elements_ref().get(index_to_delete) {
44+
print!(
45+
"Are you sure you want to delete the {}th code ({}, {}) [Y,N]: ",
46+
index_to_delete + 1,
47+
element.issuer,
48+
element.label
49+
);
50+
io::stdout().flush()?;
51+
52+
let output = read_confirmation_line()?;
53+
54+
if output.trim().eq_ignore_ascii_case("y") {
55+
otp_database.delete_element(index_to_delete);
56+
Ok(otp_database)
57+
} else {
58+
Err(eyre!("Operation interrupt by the user"))
59+
}
5260
} else {
53-
Err(eyre!("Operation interrupt by the user"))
61+
Err(eyre!("Missing {}th code to delete", index_to_delete + 1))
5462
}
5563
}
5664
}

0 commit comments

Comments
 (0)