Skip to content

Commit

Permalink
core/config.rs: add context for I/O errors
Browse files Browse the repository at this point in the history
Signed-off-by: Manos Pitsidianakis <manos@pitsidianak.is>
  • Loading branch information
epilys committed Nov 2, 2023
1 parent c470a61 commit 632ec83
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
7 changes: 4 additions & 3 deletions cli/tests/basic_interfaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,10 @@ For more information, try '--help'."#,
output.code(255).stderr(predicates::str::is_empty()).stdout(
predicate::eq(
format!(
"[1] Could not read configuration file from path: {} Caused by:\n[2] Error \
returned from internal I/O operation: No such file or directory (os error 2)",
conf.display()
"[1] Could not read configuration file from path: {path} Caused by:\n[2] \
Configuration file {path} not found. Caused by:\n[3] Error returned from \
internal I/O operation: No such file or directory (os error 2)",
path = conf.display()
)
.as_str(),
)
Expand Down
32 changes: 21 additions & 11 deletions core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,18 @@ impl Configuration {
pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
let path = path.as_ref();
let mut s = String::new();
let mut file = std::fs::File::open(path)?;
file.read_to_string(&mut s)?;
let mut file = std::fs::File::open(path)
.with_context(|| format!("Configuration file {} not found.", path.display()))?;
file.read_to_string(&mut s)
.with_context(|| format!("Could not read from file {}.", path.display()))?;
let config: Self = toml::from_str(&s)
.map_err(anyhow::Error::from)
.context(format!(
"Could not parse configuration file `{}` successfully: ",
path.display()
))?;
.with_context(|| {
format!(
"Could not parse configuration file `{}` successfully: ",
path.display()
)
})?;

Ok(config)
}
Expand All @@ -106,14 +110,20 @@ impl Configuration {
}

debug_assert!(path != self.db_path());
let mut file = std::fs::File::create(&path)?;
let metadata = file.metadata()?;
let mut file = std::fs::File::create(&path)
.with_context(|| format!("Could not create file {}.", path.display()))?;
let metadata = file
.metadata()
.with_context(|| format!("Could not fstat file {}.", path.display()))?;
let mut permissions = metadata.permissions();

permissions.set_mode(0o600); // Read/write for owner only.
file.set_permissions(permissions)?;
file.write_all(msg.as_bytes())?;
file.flush()?;
file.set_permissions(permissions)
.with_context(|| format!("Could not chmod 600 file {}.", path.display()))?;
file.write_all(msg.as_bytes())
.with_context(|| format!("Could not write message to file {}.", path.display()))?;
file.flush()
.with_context(|| format!("Could not flush message I/O to file {}.", path.display()))?;
Ok(path)
}

Expand Down

0 comments on commit 632ec83

Please sign in to comment.