Skip to content

Commit d0c726a

Browse files
committed
Changed many unwraps to more meaningful errors
1 parent 74c214a commit d0c726a

14 files changed

Lines changed: 118 additions & 77 deletions

File tree

crates/common/src/attachment.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ pub fn write_attachment(conductor: ConductorHandle, filepath: PathBuf) -> Result
1717
} else { "__no_filename_found_".to_string() };
1818
let mut file = std::fs::File::open(filepath.clone())?;
1919
/// Get metadata and check size
20-
let file_meta = file.metadata().unwrap();
20+
let file_meta = file.metadata().expect("File should always have metadata");
2121
if file_meta.len() > FILE_MAX_SIZE as u64 {
2222
return Err(std::io::Error::new(std::io::ErrorKind::Other, "Attachment too big!"));
2323
}
@@ -57,7 +57,8 @@ pub fn write_attachment(conductor: ConductorHandle, filepath: PathBuf) -> Result
5757
chunk_index: i,
5858
chunk: chunk_b64,
5959
};
60-
let hh = snapmail_write_chunk(conductor.clone(), WriteChunkInput(chunk_input)).unwrap();
60+
let hh = snapmail_write_chunk(conductor.clone(), WriteChunkInput(chunk_input))
61+
.map_err(|_err| std::io::Error::from(std::io::ErrorKind::Other))?;
6162
chunk_hh_list.push(hh);
6263
i += 1;
6364
}
@@ -70,13 +71,15 @@ pub fn write_attachment(conductor: ConductorHandle, filepath: PathBuf) -> Result
7071
orig_filesize: file_meta.len() as usize,
7172
chunks: chunk_hh_list,
7273
};
73-
let res = snapmail_write_manifest(conductor, input).unwrap();
74+
let res = snapmail_write_manifest(conductor, input)
75+
.map_err(|_err| std::io::Error::from(std::io::ErrorKind::Other))?;
7476
Ok(res)
7577
}
7678

7779
///
7880
pub fn get_attachment(conductor: ConductorHandle, eh: EntryHash, path: PathBuf) -> std::io::Result<PathBuf> {
79-
let manifest = snapmail_get_manifest(conductor.clone(), AnyDhtHash::from(eh)).unwrap();
81+
let manifest = snapmail_get_manifest(conductor.clone(), AnyDhtHash::from(eh))
82+
.map_err(|_err| std::io::Error::from(std::io::ErrorKind::Other))?;
8083

8184
// /// Print
8285
// msg!(" Filename: {}", manifest.filename);

crates/common/src/conductor.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@ pub async fn start_conductor_or_abort(sid: String) -> (ConductorHandle, DnaHash)
3333
/// - Get UID
3434
let path = CONFIG_PATH.as_path().join(sid.clone());
3535
let app_filepath = path.join(APP_CONFIG_FILENAME);
36-
let uid = std::fs::read_to_string(app_filepath).unwrap();
36+
let uid = std::fs::read_to_string(app_filepath).expect("Should have config folder");
3737
let expected_hash = load_dna_from_rs(uid).await.dna_hash().clone();
3838
/// - Get Installed DNAs
39-
let dnas = conductor.list_dnas().await.unwrap();
39+
let dnas = conductor.list_dnas().await.expect("Conductor should not fail");
4040
/// - Check
4141
if dnas.len() != 1 {
4242
err_msg!("No installed DNA found ({})", dnas.len());
@@ -137,7 +137,7 @@ pub async fn install_app(sid: String, uid: String) -> ConductorResult<DnaHash> {
137137
/// Activate app
138138
conductor.activate_app(SNAPMAIL_APP_ID.to_string()).await?;
139139
/// Done
140-
let dnas = conductor.list_dnas().await.unwrap();
140+
let dnas = conductor.list_dnas().await.expect("Conductor should not fail");
141141
msg!("Installed DNAs: {:?}", dnas);
142142
Ok(dna_file.dna_hash().clone())
143143
}
@@ -148,7 +148,9 @@ pub fn dump_state(conductor: ConductorHandle) -> usize {
148148
//let p2p = conductor.holochain_p2p();
149149
//let broadcaster = conductor.signal_broadcaster();
150150

151-
let cell_id = &conductor.list_cell_ids().await.unwrap()[0];
151+
let cell_id = &conductor.list_cell_ids().await
152+
.expect("Conductor should not fail")
153+
[0];
152154

153155
// let cell = conductor.cell_by_id(cell_id).unwrap();
154156
// let arc = cell.env();
@@ -159,7 +161,7 @@ pub fn dump_state(conductor: ConductorHandle) -> usize {
159161
let peer_dump = p2p_store::dump_state(
160162
conductor.get_p2p_env().await.clone().into(),
161163
Some(cell_id.clone()),
162-
).unwrap();
164+
).expect("p2p_store should not fail");
163165

164166
//let state = conductor.dump_cell_state(&cell_ids[0]).await.unwrap();
165167
//msg!(" {}", state);
@@ -169,5 +171,5 @@ pub fn dump_state(conductor: ConductorHandle) -> usize {
169171
// msg!(" - Peers: {}", peer_dump.peers.len());
170172
peer_dump.peers.len()
171173
}, std::time::Duration::from_secs(9));
172-
result.unwrap()
174+
result.expect("dump_state() should not fail")
173175
}

crates/common/src/config.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ pub fn create_config(environment_path: PathBuf) -> ConductorConfig {
1919
/// Write [`ConductorConfig`] to [`CONDUCTOR_CONFIG`]
2020
pub fn write_config(mut path: PathBuf, config: &ConductorConfig) -> PathBuf {
2121
path.push(CONDUCTOR_CONFIG_FILENAME);
22-
std::fs::write(path.clone(), serde_yaml::to_string(&config).unwrap()).unwrap();
22+
std::fs::write(path.clone(), serde_yaml::to_string(&config).unwrap())
23+
.expect("CONDUCTOR_CONFIG_FILENAME should be writable");
2324
path
2425
}
2526

crates/snapmail-cli/src/cli.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ impl SnapSubcommand {
8181
match self {
8282
Self::Setup(cmd)=> {
8383
msg!("Setup!");
84-
cmd.run(sid).await;
84+
cmd.run(sid).await?;
8585
},
8686
Self::Info => {
8787
msg!("{} Info:", sid_str);
@@ -105,7 +105,8 @@ impl SnapSubcommand {
105105
Self::ListSessions => {
106106
msg!("ListSessions: ");
107107
let root = CONFIG_PATH.as_path().to_path_buf();
108-
let paths = std::fs::read_dir(root).unwrap();
108+
let paths = std::fs::read_dir(root)
109+
.expect("Missing config folder");
109110
for path in paths {
110111
msg!(" - {}", path.unwrap().path().display())
111112
}
@@ -184,7 +185,8 @@ impl SnapSubcommand {
184185
let handle_list = snapmail_get_all_handles(conductor.clone(), ())?;
185186
msg!(" {} mail(s) found:", all_mail_list.len());
186187
for item in all_mail_list.iter() {
187-
let username = get_name(&handle_list, &item.author).unwrap();
188+
let username = get_name(&handle_list, &item.author)
189+
.expect("DHT incoherent state as author's handle should publicly available");
188190
msg!("- {:?} | {} | {} | {}", item.state, username, item.mail.subject, item.address);
189191
}
190192
dump_state(conductor);

crates/snapmail-cli/src/subcommands/change.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ impl ChangeCommand {
3636
fn update_uid(&self, sid: PathBuf, uid: &str) {
3737
let config_path = Path::new(&*CONFIG_PATH).join(sid.clone());
3838
let app_filepath = config_path.join(APP_CONFIG_FILENAME);
39-
std::fs::write(app_filepath, uid.as_bytes()).unwrap();
39+
std::fs::write(app_filepath, uid.as_bytes())
40+
.expect("APP_CONFIG_FILENAME should be writable");
4041
}
4142

4243
///
@@ -64,6 +65,7 @@ impl ChangeCommand {
6465
}
6566
/// Write config
6667
msg!("New config:\n{}", file_str);
67-
std::fs::write(config_filepath.clone(), file_str).unwrap();
68+
std::fs::write(config_filepath.clone(), file_str)
69+
.expect("CONDUCTOR_CONFIG_FILENAME should be writable");
6870
}
6971
}

crates/snapmail-cli/src/subcommands/listen.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,10 @@ use tokio::time::{Duration};
1717
pub async fn listen(conductor: ConductorHandle, loop_interval_sec: u64) -> anyhow::Result<()> {
1818

1919
/// Add app interface so we can get signals
20-
let mut interfaces = conductor.list_app_interfaces().await.unwrap();
20+
let mut interfaces = conductor.list_app_interfaces().await?;
2121
if interfaces.is_empty() {
22-
let _port = conductor.clone().add_app_interface(0).await.unwrap();
23-
interfaces = conductor.list_app_interfaces().await.unwrap();
22+
let _port = conductor.clone().add_app_interface(0).await?;
23+
interfaces = conductor.list_app_interfaces().await?;
2424
}
2525
msg!("App Interfaces: {:?}", interfaces);
2626

@@ -75,7 +75,12 @@ fn print_snapmail_signal(conductor: ConductorHandle, handle_list: &GetAllHandles
7575
}
7676
SignalProtocol::ReceivedAck(ack) => {
7777
let name = get_name(handle_list, &ack.from).unwrap_or("<unknown>".to_string());
78-
let maybe_mail = snapmail_get_mail(conductor.clone(), ack.for_mail.clone()).unwrap();
78+
let maybe_mail = snapmail_get_mail(conductor.clone(), ack.for_mail.clone());
79+
if let Err(err) = maybe_mail {
80+
msg!("snapmail_get_mail() failed during print_snapmail_signal(): {:?}", err);
81+
return;
82+
}
83+
let maybe_mail = maybe_mail.unwrap();
7984
let subject = if let Some(mail) = maybe_mail.0 {
8085
match mail {
8186
Ok(inmail) => inmail.mail.subject,
@@ -94,7 +99,12 @@ fn print_snapmail_signal(conductor: ConductorHandle, handle_list: &GetAllHandles
9499
/// Get username from AgentPubKey
95100
/// Update Handle list if necessary
96101
pub fn try_get_name(conductor: ConductorHandle, candidate: &AgentPubKey) -> Result<String, ()> {
97-
let handle_list = snapmail_get_all_handles(conductor.clone(), ()).unwrap().0;
102+
let handle_list = snapmail_get_all_handles(conductor.clone(), ());
103+
if let Err(err) = handle_list {
104+
msg!("snapmail_get_all_handles() failed during try_get_name(): {:?}", err);
105+
return Err(());
106+
}
107+
let handle_list = handle_list.unwrap().0;
98108
for pair in handle_list.iter() {
99109
if &pair.1 == candidate {
100110
return Ok(pair.0.clone());

crates/snapmail-cli/src/subcommands/open.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,16 @@ fn print_mail(handle_list: &GetAllHandlesOutput, mail: Mail, from: String, bcc:
1313
/// Get all CCs
1414
let mut cc_all = String::new();
1515
for cc in mail.cc.iter() {
16-
cc_all = format!("{}, {}", cc_all, get_name(&handle_list, &cc).unwrap());
16+
let name = get_name(&handle_list, &cc)
17+
.expect("Should have found cc handle in DHT");
18+
cc_all = format!("{}, {}", cc_all, name);
1719
}
1820
/// Get all BCCs
1921
let mut bcc_all = String::new();
2022
for bcc in bcc.iter() {
21-
bcc_all = format!("{}, {}",bcc_all, get_name(&handle_list, &bcc).unwrap());
23+
let name = get_name(&handle_list, &bcc)
24+
.expect("Should have found bcc handle in DHT");
25+
bcc_all = format!("{}, {}",bcc_all, name);
2226
}
2327
///
2428
let date: DateTime<Local> = Local.timestamp(mail.date_sent as i64, 0);
@@ -44,7 +48,8 @@ pub async fn open(uid: String, hh: HeaderHash) -> anyhow::Result<()> {
4448
msg!(" - mail: {:?}", mail);
4549
match mail {
4650
Ok(inmail) => {
47-
let from = get_name(&handle_list, &inmail.from).unwrap();
51+
let from = get_name(&handle_list, &inmail.from)
52+
.ok_or(anyhow::Error::msg("Handle not found"))?;
4853
print_mail(&handle_list, inmail.mail, from, vec![]);
4954
msg!("Acknowledging...");
5055
let maybe_hash = snapmail_acknowledge_mail(conductor, hh);

crates/snapmail-cli/src/subcommands/send.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ impl SendCommand {
4545
let mut manifest_address_list: Vec<HeaderHash> = Vec::new();
4646
if let Some(attachment) = self.maybe_attachment {
4747
msg!("Reading attachment file: {:?}", attachment);
48-
let hh = write_attachment(conductor.clone(), attachment).unwrap();
48+
let hh = write_attachment(conductor.clone(), attachment)?;
4949
manifest_address_list.push(hh);
5050
}
5151
// Form MailInput
@@ -59,7 +59,7 @@ impl SendCommand {
5959
};
6060
let send_count = mail.to.len() + mail.cc.len() + mail.bcc.len();
6161
// Send
62-
let output = snapmail_send_mail(conductor, mail).unwrap();
62+
let output = snapmail_send_mail(conductor, mail)?;
6363
// Show results
6464
let pending_count = output.to_pendings.len() + output.cc_pendings.len() + output.bcc_pendings.len();
6565
msg!("Send done: {:?}", output.outmail);

crates/snapmail-cli/src/subcommands/setup.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,6 @@ pub struct SetupCommand {
2323
/// Network ID that this session will use
2424
uid: String,
2525

26-
// #[structopt(name = "mdns")]
27-
// maybe_can_mdns: Option<bool>,
28-
2926
// Set a root directory for the app's storage data to be placed into.
3027
// Defaults to the system's temp directory.
3128
// This directory must already exist.
@@ -35,7 +32,7 @@ pub struct SetupCommand {
3532

3633
impl SetupCommand {
3734
///
38-
pub async fn run(&self, sid: PathBuf) {
35+
pub async fn run(&self, sid: PathBuf) -> anyhow::Result<()> {
3936
let sid_str = sid.to_string_lossy().to_string();
4037
//let root = self.maybe_root.clone().unwrap_or(CONFIG_PATH.as_path().to_path_buf());
4138
let root = CONFIG_PATH.as_path().to_path_buf();
@@ -46,11 +43,12 @@ impl SetupCommand {
4643
).expect("Generate config failed. Maybe Invalid params.");
4744

4845

49-
let _dna_hash = install_app(sid.to_string_lossy().to_string(), self.uid.clone()).await.unwrap();
46+
let _dna_hash = install_app(sid.to_string_lossy().to_string(), self.uid.clone()).await?;
5047
// msg!(" Using DNA: {}", dna_hash);
5148
let conductor = start_conductor(sid_str.clone()).await;
52-
let hash = snapmail_set_handle(conductor, sid_str.clone()).unwrap();
49+
let hash = snapmail_set_handle(conductor, sid_str.clone())?;
5350
msg!(" handle set: {} - {:?}", sid_str, hash);
51+
Ok(())
5452
}
5553
}
5654

crates/snapmail-tui/src/app.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -142,12 +142,13 @@ impl App {
142142

143143
///
144144
pub fn show_selected_contact(&mut self) {
145-
let selected = self.contacts_table.state.selected();
146-
if selected.is_none() {
147-
self.feedback(&format!("No selection"));
148-
return;
149-
}
150-
let index = selected.unwrap();
145+
let index = match self.contacts_table.state.selected() {
146+
None => {
147+
self.feedback(&format!("No selection"));
148+
return;
149+
}
150+
Some(s) => s,
151+
};
151152
let key = self.contacts_table.agent_index_map.get(&index).unwrap();
152153
let msg = format!("({}) Selected agent: {}", index, key);
153154
self.feedback(&msg);

0 commit comments

Comments
 (0)