Skip to content

Commit

Permalink
cli: Refactor workspace root directory creation
Browse files Browse the repository at this point in the history
* Add file_util::create_or_reuse_dir() which is needed by all init
  functionality regardless of the backend.
  • Loading branch information
essiene committed Feb 2, 2024
1 parent 42c85b3 commit b284701
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
15 changes: 5 additions & 10 deletions cli/src/commands/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 _;
Expand Down Expand Up @@ -51,16 +51,11 @@ 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_with_message("Failed to create workspace", e)),
}
let wc_path = wc_path
.canonicalize()
.map_err(|e| user_error_with_message("Failed to create workspace", e))?; // raced?
let cwd = command.cwd().canonicalize().unwrap();
let wc_path = cwd.join(&args.destination);
let wc_path = file_util::create_or_reuse_dir(&wc_path)
.and_then(|p| p.canonicalize())
.map_err(|e| user_error_with_message("Failed to create workspace", e))?;
let relative_wc_path = file_util::relative_path(&cwd, &wc_path);

if let Some(git_store_str) = &args.git_repo {
Expand Down
18 changes: 17 additions & 1 deletion lib/src/file_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -42,6 +42,22 @@ impl<T> IoResultExt<T> for io::Result<T> {
}
}

/// Creates a directory or does nothing if the directory already exists.
///
/// Returns the &Path if successful, so it can be chained with .and_then() and
/// friends which take a closure with a single param.
///
/// 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) -> io::Result<&Path> {
match fs::create_dir(dirname) {
Ok(()) => Ok(dirname),
Err(_) if dirname.is_dir() => Ok(dirname),
Err(e) => Err(e),
}
}

/// 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
Expand Down

0 comments on commit b284701

Please sign in to comment.