Skip to content

Commit

Permalink
Refactor: Switch arg parsing to clap-derive (#110)
Browse files Browse the repository at this point in the history
* Switch arg parsing to clap-derive

* Fix default "." paths breaking glob paterns
  • Loading branch information
tranzystorekk authored Jan 25, 2022
1 parent 917e0fc commit d351615
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 92 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.48"
serde_yaml = "0.8"
anyhow = "1.0"
clap = "3.0.0-rc.11"
clap = { version = "3.0", features = ["derive"] }
glob = "0.3.0"
rayon = "1.5"
chrono = "0.4"
Expand Down
11 changes: 4 additions & 7 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub struct Config<'a> {
pub global_logbook: Vec<OrgMetadata<'a>>,
pub global_attachments: Vec<String>,
pub tera: tera::Tera,
pub verbosity: i8,
pub verbosity: u8,
// Data specifically for templates / user interaction:
pub user_config: UserConfig,
pub sitemap: Vec<LinkData>,
Expand All @@ -110,7 +110,7 @@ fn build_paths(cwd: &PathBuf) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
}

impl<'a> Config<'a> {
pub fn new(cwd: PathBuf, verbosity: i8) -> Result<Config<'a>, anyhow::Error> {
pub fn new(cwd: PathBuf, verbosity: u8) -> Result<Config<'a>, anyhow::Error> {
let (dir_firn, dir_templates, dir_site_out, config_file) = build_paths(&cwd);
Config::check_site_exists(&dir_firn);

Expand Down Expand Up @@ -449,11 +449,8 @@ impl<'a> Config<'a> {
}
}

pub fn setup_for_serve(&mut self, port: &str) {
let port_int = port
.parse::<u16>()
.expect("Failed to parse port to an integer");
self.serve_port = port_int;
pub fn setup_for_serve(&mut self, port: u16) {
self.serve_port = port;
self.user_config.site.url = format!("http://localhost:{}", port);
self.base_url.base_url = format!("http://localhost:{}", port);
}
Expand Down
145 changes: 62 additions & 83 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::env;
use std::path::PathBuf;
pub mod config;
pub mod errors;
pub mod front_matter;
Expand All @@ -10,98 +8,79 @@ pub mod serve;
pub mod templates;
pub mod user_config;
pub mod util;

use std::env;
use std::path::PathBuf;

use anyhow::Result;
use clap::{Parser, Subcommand};

/// Org Mode static site generator
#[derive(Parser)]
#[clap(name = "Firn", version = "0.15", author = "The Ice Shelf")]
struct Cli {
/// Set the level of verbosity, e.g. -v => verbose, -vv => very verbose
#[clap(short, long, global = true, parse(from_occurrences))]
verbose: u8,

#[clap(subcommand)]
command: Command,
}

#[derive(Subcommand)]
enum Command {
/// Scaffold files and folders needed to start a new site
New {
/// The target directory for a new site, defaults to cwd
path: Option<PathBuf>,
},

/// Build a static site
Build {
/// Directory containing files to be built, defaults to cwd
path: Option<PathBuf>,
},

extern crate clap;
use clap::{App, AppSettings, Arg};
/// Run a development server for processed org files
Serve {
/// The port for the development server to run on
#[clap(short, long, default_value_t = 8080)]
port: u16,

/// Directory containing files to be built and served, defaults to cwd
path: Option<PathBuf>,
},
}

fn main() -> Result<()> {
let matches = App::new("Firn")
.setting(AppSettings::ArgRequiredElseHelp)
.version("0.15")
.author("The Ice Shelf")
.about("Org Mode Static Site Generator")
.arg(
Arg::new("directory")
.short('d')
.long("dir")
.help("filesystem path to operate new/build/serve from")
.global(true)
.takes_value(true),
)
.arg(
Arg::new("verbose")
.short('v')
.long("verbose")
.multiple_occurrences(true)
.global(true)
.help("Sets the level of verbosity"),
)
.subcommand(
App::new("new")
.about("Scaffolds files & folders needed to start a new site."),
)
.subcommand(
App::new("build")
.about("Build a static site in a directory with org files."),
)
.subcommand(
App::new("serve")
.about("Runs a development server for processed org files.")
.arg(
Arg::new("port")
.short('p')
.help("set the port for the development server to run on.")
.long("port")
.takes_value(true),
),
)
.get_matches();
let cli = Cli::parse();

let get_dir = || -> PathBuf {
let dir: PathBuf;
if matches.is_present("directory") {
let dir_str = matches
.value_of("directory")
.expect("Failed to get directory value when running 'firn new'");
dir = PathBuf::from(dir_str);
} else {
dir = env::current_dir().expect("Failed to get cwd");
match cli.command {
Command::New { path } => {
let path = path_or_cwd(path);
new_site::init(path);
}
dir
};

let get_verbosity = || -> i8 {
match matches.occurrences_of("verbose") {
0 => 0,
1 => 1,
_ => 2,
Command::Build { path } => {
let path = path_or_cwd(path);
let mut config = unwrap_config(path, cli.verbose);
config.build(true)?;
}
Command::Serve { port, path } => {
let path = path_or_cwd(path);
let mut config = unwrap_config(path, cli.verbose);
config.setup_for_serve(port);
config.build(true)?;
serve::start_server(&mut config);
}
};
// Command: new ------------------------------------------------------------
if let Some(_matches) = matches.subcommand_matches("new") {
let dir = get_dir();
new_site::init(dir);
}
// Command: build ----------------------------------------------------------
if let Some(_matches) = matches.subcommand_matches("build") {
let dir = get_dir();
let mut config = unwrap_config(dir, get_verbosity());
config.build(true)?;
}

if let Some(serve_match) = matches.subcommand_matches("serve") {
let port = serve_match.value_of("port").unwrap_or("8080");
let dir = get_dir();
let mut config = unwrap_config(dir, get_verbosity());
config.setup_for_serve(port);
config.build(true)?;
serve::start_server(&mut config);
}
Ok(())
}

fn unwrap_config(cwd_as_path: PathBuf, verbosity: i8) -> config::Config<'static> {
fn path_or_cwd(path: Option<PathBuf>) -> PathBuf {
path.unwrap_or_else(|| env::current_dir().expect("Failed to get cwd"))
}

fn unwrap_config(cwd_as_path: PathBuf, verbosity: u8) -> config::Config<'static> {
let config = match config::Config::new(cwd_as_path, verbosity) {
Ok(cfg) => cfg,
Err(_e) => {
Expand Down
2 changes: 1 addition & 1 deletion src/templates/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub struct Render {
base_url: BaseUrl,
file_path: PathBuf,
front_matter: front_matter::FrontMatter,
verbosity: i8,
verbosity: u8,
user_config: user_config::UserConfig,
}

Expand Down

0 comments on commit d351615

Please sign in to comment.