Skip to content

Commit e9a0ea4

Browse files
committed
config: write: better error handling and code
1 parent e031676 commit e9a0ea4

File tree

2 files changed

+15
-19
lines changed

2 files changed

+15
-19
lines changed

Cargo.lock

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/config.rs

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use anyhow::Result;
1+
use anyhow::{Context, Result};
22
use serde::{Deserialize, Serialize};
33
use std::{fs, path::Path};
44

@@ -81,23 +81,19 @@ impl ConfigOptions {
8181
{
8282
// I dont think this can panic so i simply unwrapped it
8383
let contents = toml::to_string(&self).unwrap();
84-
match fs::create_dir_all(&path.as_ref().parent().unwrap_or(Path::new("/"))) {
85-
Ok(_) => match fs::write(&path, &contents) {
86-
Ok(_) => {
87-
let path = path.as_ref().display();
88-
println!("Config config file created at: {path}")
89-
}
90-
Err(e) => {
91-
let path = path.as_ref().display();
92-
eprintln!("Failed to write config file at {path}: {e}")
93-
}
94-
},
95-
Err(e) => {
96-
let path = path.as_ref().display();
97-
eprintln!("Failed to create config directory {path}: {e}");
98-
}
84+
let dir = path
85+
.as_ref()
86+
.parent()
87+
.with_context(|| format!("'{}' is not a path!", path.as_ref().display()));
88+
fs::create_dir_all(dir?)?;
89+
match fs::write(&path, contents) {
90+
Ok(_) => println!("Created default config at {}", path.as_ref().display()),
91+
Err(e) => eprintln!(
92+
"Failed to write default config at {}: {}",
93+
path.as_ref().display(),
94+
e
95+
),
9996
}
100-
// Im not sure it should return simple Ok(())?
10197
Ok(())
10298
}
10399
}

0 commit comments

Comments
 (0)