From 97bfe0afc3cb86f06a02560179dd7042a08775c7 Mon Sep 17 00:00:00 2001 From: Scott Lamb Date: Thu, 21 Oct 2021 09:07:06 -0700 Subject: [PATCH] fix nvr init error message on mkdir failure Before it would produce this incorrect message that told you to run the command you just ran: ``` $ nvr init --db-dir=/nonexistent/db E20211021 09:08:23.798 main moonfire_nvr] Exiting due to error: db dir /nonexistent/db not found; try running moonfire-nvr init caused by: ENOENT: No such file or directory ``` Now the same command produces the following: ``` $ nvr init --db-dir=/nonexistent/db E20211021 09:09:11.056 main moonfire_nvr] Exiting due to error: unable to create db dir /nonexistent/db caused by: ENOENT: No such file or directory ``` Add tests just for good measure. --- server/src/cmds/mod.rs | 44 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/server/src/cmds/mod.rs b/server/src/cmds/mod.rs index 56b7ff8..e746140 100644 --- a/server/src/cmds/mod.rs +++ b/server/src/cmds/mod.rs @@ -28,7 +28,9 @@ enum OpenMode { /// The returned `dir::Fd` holds the lock and should be kept open as long as the `Connection` is. fn open_dir(db_dir: &Path, mode: OpenMode) -> Result { let dir = dir::Fd::open(db_dir, mode == OpenMode::Create).map_err(|e| { - e.context(if e == nix::Error::ENOENT { + e.context(if mode == OpenMode::Create { + format!("unable to create db dir {}", db_dir.display()) + } else if e == nix::Error::ENOENT { format!( "db dir {} not found; try running moonfire-nvr init", db_dir.display() @@ -79,3 +81,43 @@ fn open_conn(db_dir: &Path, mode: OpenMode) -> Result<(dir::Fd, rusqlite::Connec )?; Ok((dir, conn)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn open_dir_error_msg() { + let tmpdir = tempfile::Builder::new() + .prefix("moonfire-nvr-test") + .tempdir() + .unwrap(); + let mut nonexistent_dir = tmpdir.path().to_path_buf(); + nonexistent_dir.push("nonexistent"); + let nonexistent_open = open_dir(&nonexistent_dir, OpenMode::ReadOnly).unwrap_err(); + assert!( + nonexistent_open + .to_string() + .contains("try running moonfire-nvr init"), + "unexpected error {}", + &nonexistent_open + ); + } + + #[test] + fn create_dir_error_msg() { + let tmpdir = tempfile::Builder::new() + .prefix("moonfire-nvr-test") + .tempdir() + .unwrap(); + let mut nonexistent_dir = tmpdir.path().to_path_buf(); + nonexistent_dir.push("nonexistent"); + nonexistent_dir.push("db"); + let nonexistent_create = open_dir(&nonexistent_dir, OpenMode::Create).unwrap_err(); + assert!( + nonexistent_create.to_string().contains("unable to create"), + "unexpected error {}", + &nonexistent_create + ); + } +}