From 767b239776c23d9aa31c5d0b594ba200c430a8bb Mon Sep 17 00:00:00 2001 From: Daniel Schadt Date: Sat, 14 Jan 2023 19:07:30 +0100 Subject: add a cli option for the output directory --- src/main.rs | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 9c3250e..f4a7aa7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,11 @@ -use std::{fs, io, path::PathBuf}; +use std::{ + fs, + io::{self, ErrorKind}, + path::{Path, PathBuf}, +}; use clap::Parser; -use color_eyre::eyre::{bail, Result}; +use color_eyre::eyre::{bail, Context, Result}; use indicatif::{MultiProgress, ProgressBar, ProgressDrawTarget, ProgressStyle}; use is_terminal::IsTerminal; use rayon::ThreadPoolBuilder; @@ -28,6 +32,10 @@ struct Args { /// Number of threads to use. Set to 0 to use all available CPU cores. #[arg(long, short, default_value_t = 0)] threads: usize, + + /// The output directory. Will be created if it does not exist. + #[arg(long, short, default_value = "tiles")] + output_directory: PathBuf, } fn main() -> Result<()> { @@ -68,6 +76,8 @@ fn main() -> Result<()> { } bar.finish(); + ensure_output_directory(&args.output_directory)?; + let multibar = MultiProgress::new(); if !use_progress_bars { multibar.set_draw_target(ProgressDrawTarget::hidden()) @@ -85,7 +95,9 @@ fn main() -> Result<()> { bar.finish(); multibar.remove(&bar); - let target = ["tiles", &zoom.to_string()].iter().collect::(); + let target = [&args.output_directory, &zoom.to_string().into()] + .iter() + .collect::(); fs::create_dir(&target)?; let bar = @@ -101,3 +113,19 @@ fn main() -> Result<()> { Ok(()) } + +fn ensure_output_directory>(path: P) -> Result<()> { + let path = path.as_ref(); + let metadata = fs::metadata(path); + match metadata { + Err(e) if e.kind() == ErrorKind::NotFound => { + let parent = path.parent().unwrap_or(Path::new("/")); + fs::create_dir(path) + .context(format!("Could not create output directory at {parent:?}"))? + } + Err(e) => Err(e).context("Error while checking output directory")?, + Ok(m) if m.is_dir() => (), + Ok(_) => bail!("Output directory is not a directory"), + } + Ok(()) +} -- cgit v1.2.3