Skip to content
This repository has been archived by the owner on Aug 3, 2023. It is now read-only.

Commit

Permalink
add script-format field, remove Option<T> from builder config
Browse files Browse the repository at this point in the history
  • Loading branch information
xortive committed Dec 17, 2020
1 parent 193ba02 commit a271ffc
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 66 deletions.
3 changes: 2 additions & 1 deletion src/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ pub fn build_target(target: &Target) -> Result<String, failure::Error> {
Ok(msg)
}
Some(config) => {
if config.build_command().spawn()?.wait()?.success() {
if let Some(mut command) = config.build_command() {
command.spawn()?.wait()?.success();
Ok(String::from("Build completed successfully!"))
} else {
Ok(String::from("No build command specified, skipping build."))
Expand Down
106 changes: 43 additions & 63 deletions src/settings/toml/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,84 +4,64 @@ use std::process::Command;

use serde::{Deserialize, Serialize};

use crate::terminal::emoji;
use crate::terminal::message::{Message, StdOut};

use super::ScriptFormat;

const OUTPUT_DIR: &str = "dist";
const SRC_DIR: &str = "src";
const BUILD_COMMAND: &str = "npm run build";

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Builder {
// are these renames necessary? I'm not super well versed in serde
// so i'm not sure how the annotations work
#[serde(rename = "build_command")]
#[serde(alias = "build-command")]
build_command: Option<String>,
#[serde(rename = "output_dir")]
output_dir: Option<PathBuf>,
#[serde(rename = "src_dir")]
src_dir: Option<PathBuf>,
#[serde(default = "output_dir")]
pub output_dir: PathBuf,
pub upload_format: ScriptFormat,
#[serde(default = "src_dir")]
pub src_dir: PathBuf,
}

impl Builder {
fn dir_or_default(dir: &Option<PathBuf>, default: &str, dirname: &str) -> PathBuf {
match dir {
Some(path) => path.to_owned(),
None => {
StdOut::warn(&format!(
"{} {} not specified, falling back to {}",
emoji::WARN,
dirname,
default
));
PathBuf::from(default)
}
}
}
fn default_warning(field: &str, default: &str) {
StdOut::warn(&format!(
"{} not specified, falling back to {}",
field, default
));
}

pub fn output_dir(&self) -> Result<PathBuf, std::io::Error> {
let current_dir = env::current_dir()?;
let output_dir = current_dir.join(Builder::dir_or_default(
&self.output_dir,
OUTPUT_DIR,
"output dir",
));
Ok(output_dir)
}
fn output_dir() -> PathBuf {
default_warning("output dir", OUTPUT_DIR);
let current_dir = env::current_dir().unwrap();
current_dir.join(OUTPUT_DIR)
}

pub fn src_dir(&self) -> Result<PathBuf, std::io::Error> {
let current_dir = env::current_dir()?;
let src_dir = current_dir.join(Builder::dir_or_default(&self.src_dir, SRC_DIR, "src dir"));
Ok(src_dir)
}
fn src_dir() -> PathBuf {
default_warning("src dir", SRC_DIR);
let current_dir = env::current_dir().unwrap();
current_dir.join(SRC_DIR)
}

impl Builder {
pub fn build_command(&self) -> Option<Command> {
if let Some(cmd) = &self.build_command {
let args: Vec<&str> = cmd.split_whitespace().collect();

pub fn build_command(&self) -> Command {
let args_string = match &self.build_command {
Some(cmd) => cmd.to_owned(),
None => {
StdOut::warn(&format!(
"{} build command not specified, falling back to {}",
emoji::WARN,
BUILD_COMMAND
));
BUILD_COMMAND.to_string()
}
};
let args: Vec<&str> = args_string.split_whitespace().collect();
let command = if cfg!(target_os = "windows") {
let mut c = Command::new("cmd");
c.arg("/C").args(args.as_slice());
c
} else {
let mut c = Command::new(args[0]);
if args.len() > 1 {
c.args(&args[1..]);
}
c
};

let command = if cfg!(target_os = "windows") {
let mut c = Command::new("cmd");
c.arg("/C").args(args.as_slice());
c
Some(command)
} else {
let mut c = Command::new(args[0]);
if args.len() > 1 {
c.args(&args[1..]);
}
c
};

command
None
}
}
}
2 changes: 2 additions & 0 deletions src/settings/toml/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use serde_with::rust::string_empty_as_none;

use crate::settings::toml::builder::Builder;
use crate::settings::toml::kv_namespace::ConfigKvNamespace;
use crate::settings::toml::route::RouteConfig;
use crate::settings::toml::site::Site;
Expand All @@ -20,6 +21,7 @@ pub struct Environment {
#[serde(default, with = "string_empty_as_none")]
pub zone_id: Option<String>,
pub webpack_config: Option<String>,
pub builder_config: Option<Builder>,
pub private: Option<bool>,
pub site: Option<Site>,
#[serde(alias = "kv-namespaces")]
Expand Down
5 changes: 4 additions & 1 deletion src/settings/toml/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,13 +292,13 @@ impl Manifest {
target_type, // Top level
account_id: self.account_id.clone(), // Inherited
webpack_config: self.webpack_config.clone(), // Inherited
builder_config: self.builder_config.clone(), // Inherited
// importantly, the top level name will be modified
// to include the name of the environment
name: self.name.clone(), // Inherited
kv_namespaces: get_namespaces(self.kv_namespaces.clone(), preview)?, // Not inherited
site: self.site.clone(), // Inherited
vars: self.vars.clone(), // Not inherited
builder_config: self.builder_config.clone(), // lol idk what this inherit stuff means
};

let environment = self.get_environment(environment_name)?;
Expand All @@ -311,6 +311,9 @@ impl Manifest {
if let Some(webpack_config) = &environment.webpack_config {
target.webpack_config = Some(webpack_config.clone());
}
if let Some(builder_config) = &environment.builder_config {
target.builder_config = Some(builder_config.clone());
}

// don't inherit kv namespaces because it is an anti-pattern to use the same namespaces across multiple environments
target.kv_namespaces = get_namespaces(environment.kv_namespaces.clone(), preview)?;
Expand Down
2 changes: 2 additions & 0 deletions src/settings/toml/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod environment;
mod kv_namespace;
mod manifest;
mod route;
mod script_format;
mod site;
mod target;
mod target_type;
Expand All @@ -14,6 +15,7 @@ pub use environment::Environment;
pub use kv_namespace::{ConfigKvNamespace, KvNamespace};
pub use manifest::Manifest;
pub use route::{Route, RouteConfig};
pub use script_format::ScriptFormat;
pub use site::Site;
pub use target::Target;
pub use target_type::TargetType;
Expand Down
34 changes: 34 additions & 0 deletions src/settings/toml/script_format.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
pub enum ScriptFormat {
#[serde(rename = "service-worker")]
ServiceWorker,
#[serde(rename = "modules")]
Modules,
}

impl fmt::Display for ScriptFormat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let printable = match *self {
Self::ServiceWorker => "service-worker",
Self::Modules => "modules",
};
write!(f, "{}", printable)
}
}

impl FromStr for ScriptFormat {
type Err = failure::Error;

fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"service-worker" => Ok(Self::ServiceWorker),
"modules" => Ok(Self::Modules),
_ => failure::bail!("{} is not a valid script format!", s),
}
}
}
2 changes: 1 addition & 1 deletion src/watch/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ pub fn watch_and_build(
}
Some(config) => {
watcher
.watch(config.src_dir()?, notify::RecursiveMode::Recursive)
.watch(config.src_dir, notify::RecursiveMode::Recursive)
.unwrap();

let mut is_first = true;
Expand Down

0 comments on commit a271ffc

Please sign in to comment.