From 6fc1ac8d66f5b7d5b29c498f49bd561457ce377a Mon Sep 17 00:00:00 2001 From: Essien Ita Essien Date: Mon, 8 Jan 2024 10:41:07 +0000 Subject: [PATCH] cli: Refactor workspace root directory creation * Add Workspace::create_workspace_root() which is needed by all init functionality regardless of the backend. --- cli/src/commands/init.rs | 13 +++---------- lib/src/file_util.rs | 21 ++++++++++++++++++++- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/cli/src/commands/init.rs b/cli/src/commands/init.rs index 906ba8531d..dd12e75d06 100644 --- a/cli/src/commands/init.rs +++ b/cli/src/commands/init.rs @@ -12,8 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +use std::io; use std::io::Write; -use std::{fs, io}; use clap::ArgGroup; use itertools::Itertools as _; @@ -53,15 +53,8 @@ pub(crate) fn cmd_init( command: &CommandHelper, args: &InitArgs, ) -> Result<(), CommandError> { - let wc_path = command.cwd().join(&args.destination); - match fs::create_dir(&wc_path) { - Ok(()) => {} - Err(_) if wc_path.is_dir() => {} - Err(e) => return Err(user_error(format!("Failed to create workspace: {e}"))), - } - let wc_path = wc_path - .canonicalize() - .map_err(|e| user_error(format!("Failed to create workspace: {e}")))?; // raced? + let wc_path = file_util::create_or_reuse_dir(&command.cwd().join(&args.destination)) + .map_err(|e| user_error(format!("Failed to create workspace: {e}")))?; let cwd = command.cwd().canonicalize().unwrap(); let relative_wc_path = file_util::relative_path(&cwd, &wc_path); diff --git a/lib/src/file_util.rs b/lib/src/file_util.rs index d2b6c4820a..7609b64226 100644 --- a/lib/src/file_util.rs +++ b/lib/src/file_util.rs @@ -14,7 +14,7 @@ #![allow(missing_docs)] -use std::fs::File; +use std::fs::{self, File}; use std::path::{Component, Path, PathBuf}; use std::{io, iter}; @@ -42,6 +42,25 @@ impl IoResultExt for io::Result { } } +/// Creates a directory and returns it's canonicalized path. +/// +/// If the directory already exists, will only return it's canonicalized path +/// without doing anything. +/// +/// Returns the underlying error if the directory can't be created. +/// The function will also fail if intermediate directories on the path do not +/// already exist. +pub fn create_or_reuse_dir(dirname: &Path) -> std::io::Result { + match fs::create_dir(dirname) { + Ok(()) => {} + Err(_) if dirname.is_dir() => {} + Err(e) => return Err(e), + } + + // if it fails, race condition? + dirname.canonicalize() +} + /// Turns the given `to` path into relative path starting from the `from` path. /// /// Both `from` and `to` paths are supposed to be absolute and normalized in the