#![deny(clippy::all, clippy::pedantic, warnings)]
mod cache;
mod config;
mod docker;
mod failure;
mod format;
mod runner;
mod schedule;
mod spinner;
mod tar;
mod toastfile;
use {
crate::{failure::Failure, format::CodeStr},
atty::Stream,
clap::{App, AppSettings, Arg},
env_logger::{fmt::Color, Builder},
log::{Level, LevelFilter},
std::{
collections::{HashMap, HashSet},
convert::AsRef,
default::Default,
env,
env::current_dir,
fs,
io::{stdout, Write},
mem::drop,
path::Path,
path::PathBuf,
process::exit,
str::FromStr,
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
},
},
toastfile::{default_task_mount_readonly, location, user, DEFAULT_USER},
};
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate scopeguard;
const VERSION: &str = env!("CARGO_PKG_VERSION");
const TOASTFILE_DEFAULT_NAME: &str = "toast.yml";
const CONFIG_FILE_XDG_PATH: &str = "toast/toast.yml";
const DEFAULT_LOG_LEVEL: LevelFilter = LevelFilter::Info;
const TOASTFILE_OPTION: &str = "file";
const CONFIG_FILE_OPTION: &str = "config-file";
const READ_LOCAL_CACHE_OPTION: &str = "read-local-cache";
const WRITE_LOCAL_CACHE_OPTION: &str = "write-local-cache";
const READ_REMOTE_CACHE_OPTION: &str = "read-remote-cache";
const WRITE_REMOTE_CACHE_OPTION: &str = "write-remote-cache";
const DOCKER_CLI_OPTION: &str = "docker-cli";
const DOCKER_REPO_OPTION: &str = "docker-repo";
const LIST_OPTION: &str = "list";
const SHELL_OPTION: &str = "shell";
const TASKS_OPTION: &str = "tasks";
const FORCE_OPTION: &str = "force";
fn set_up_logging() {
Builder::new()
.filter_module(
module_path!(),
LevelFilter::from_str(
&env::var("LOG_LEVEL").unwrap_or_else(|_| DEFAULT_LOG_LEVEL.to_string()),
)
.unwrap_or(DEFAULT_LOG_LEVEL),
)
.format(|buf, record| {
let mut style = buf.style();
style.set_bold(true);
match record.level() {
Level::Error => {
style.set_color(Color::Red);
}
Level::Warn => {
style.set_color(Color::Yellow);
}
Level::Info => {
style.set_color(Color::Green);
}
Level::Debug | Level::Trace => {
style.set_color(Color::Blue);
}
}
writeln!(
buf,
"{} {}",
style.value(format!("[{}]", record.level())),
record.args(),
)
})
.init();
}
fn set_up_signal_handlers(
docker_cli: String,
interrupted: Arc<AtomicBool>,
active_containers: Arc<Mutex<HashSet<String>>>,
) -> Result<(), Failure> {
ctrlc::set_handler(move || {
if interrupted.swap(true, Ordering::SeqCst) {
for container in &*active_containers.lock().unwrap() {
if let Err(e) = docker::stop_container(&docker_cli, container, &interrupted) {
error!("{}", e);
}
}
drop(stdout().write(b"\n"));
}
})
.map_err(failure::system("Error installing signal handler."))
}
fn parse_bool(s: &str) -> Result<bool, Failure> {
let normalized = s.trim().to_lowercase();
match normalized.as_ref() {
"true" | "yes" => Ok(true),
"false" | "no" => Ok(false),
_ => Err(Failure::User(
format!("{} is not a Boolean.", s.code_str()),
None,
)),
}
}
#[allow(clippy::struct_excessive_bools)]
pub struct Settings {
toastfile_path: PathBuf,
docker_cli: String,
docker_repo: String,
read_local_cache: bool,
write_local_cache: bool,
read_remote_cache: bool,
write_remote_cache: bool,
list: bool,
spawn_shell: bool,
tasks: Option<Vec<String>>,
forced_tasks: Vec<String>,
}
#[allow(clippy::too_many_lines)]
fn settings() -> Result<Settings, Failure> {
let matches = App::new("Toast")
.version(VERSION)
.version_short("v")
.author("Stephan Boyer <stephan@stephanboyer.com>")
.about("Toast is a containerized build system.")
.setting(AppSettings::ColoredHelp)
.setting(AppSettings::NextLineHelp)
.setting(AppSettings::UnifiedHelpMessage)
.arg(
Arg::with_name(TOASTFILE_OPTION)
.value_name("PATH")
.short("f")
.long(TOASTFILE_OPTION)
.help("Sets the path to the toastfile"),
)
.arg(
Arg::with_name(CONFIG_FILE_OPTION)
.value_name("PATH")
.short("c")
.long(CONFIG_FILE_OPTION)
.help("Sets the path of the config file"),
)
.arg(
Arg::with_name(READ_LOCAL_CACHE_OPTION)
.value_name("BOOL")
.long(READ_LOCAL_CACHE_OPTION)
.help("Sets whether local cache reading is enabled"),
)
.arg(
Arg::with_name(WRITE_LOCAL_CACHE_OPTION)
.value_name("BOOL")
.long(WRITE_LOCAL_CACHE_OPTION)
.help("Sets whether local cache writing is enabled"),
)
.arg(
Arg::with_name(READ_REMOTE_CACHE_OPTION)
.value_name("BOOL")
.long(READ_REMOTE_CACHE_OPTION)
.help("Sets whether remote cache reading is enabled"),
)
.arg(
Arg::with_name(WRITE_REMOTE_CACHE_OPTION)
.value_name("BOOL")
.long(WRITE_REMOTE_CACHE_OPTION)
.help("Sets whether remote cache writing is enabled"),
)
.arg(
Arg::with_name(DOCKER_REPO_OPTION)
.value_name("REPO")
.short("r")
.long(DOCKER_REPO_OPTION)
.help("Sets the Docker repository"),
)
.arg(
Arg::with_name(DOCKER_CLI_OPTION)
.value_name("CLI")
.long(DOCKER_CLI_OPTION)
.help("Sets the Docker CLI binary"),
)
.arg(
Arg::with_name(LIST_OPTION)
.short("l")
.long(LIST_OPTION)
.help("Lists the tasks that have a description"),
)
.arg(
Arg::with_name(SHELL_OPTION)
.short("s")
.long(SHELL_OPTION)
.help("Drops you into a shell after the tasks are finished"),
)
.arg(
Arg::with_name(FORCE_OPTION)
.value_name("TASK")
.long(FORCE_OPTION)
.help("Runs a task unconditionally, even if it\u{2019}s cached")
.multiple(true),
)
.arg(
Arg::with_name(TASKS_OPTION)
.value_name("TASKS")
.help("Sets the tasks to run")
.multiple(true),
)
.get_matches();
let toastfile_path = matches.value_of(TOASTFILE_OPTION).map_or_else(
|| {
let mut candidate_dir =
current_dir().map_err(failure::system("Unable to determine working directory."))?;
loop {
let candidate_path = candidate_dir.join(TOASTFILE_DEFAULT_NAME);
if let Ok(metadata) = fs::metadata(&candidate_path) {
if metadata.file_type().is_file() {
return Ok(candidate_path);
}
}
if !candidate_dir.pop() {
return Err(Failure::User(
format!(
"Unable to locate file {}.",
TOASTFILE_DEFAULT_NAME.code_str(),
),
None,
));
}
}
},
|x| Ok(Path::new(x).to_owned()),
)?;
let default_config_file_path = dirs::config_dir().map(|path| path.join(CONFIG_FILE_XDG_PATH));
let config_file_path = matches.value_of(CONFIG_FILE_OPTION).map_or_else(
|| default_config_file_path,
|path| Some(PathBuf::from(path)),
);
let config_data = config_file_path
.as_ref()
.and_then(|path| {
debug!(
"Attempting to load configuration file {}\u{2026}",
path.to_string_lossy().code_str(),
);
fs::read_to_string(path).ok()
})
.map_or_else(
|| {
debug!("Configuration file not found. Using the default configuration.");
config::EMPTY_CONFIG.to_owned()
},
|data| {
debug!("Found it.");
data
},
);
let config = config::parse(&config_data).map_err(failure::user(format!(
"Unable to parse file {}.",
config_file_path
.as_ref()
.unwrap() .to_string_lossy()
.code_str(),
)))?;
let read_local_cache = matches
.value_of(READ_LOCAL_CACHE_OPTION)
.map_or(Ok(config.read_local_cache), parse_bool)?;
let write_local_cache = matches
.value_of(WRITE_LOCAL_CACHE_OPTION)
.map_or(Ok(config.write_local_cache), parse_bool)?;
let read_remote_cache = matches
.value_of(READ_REMOTE_CACHE_OPTION)
.map_or(Ok(config.read_remote_cache), parse_bool)?;
let write_remote_cache = matches
.value_of(WRITE_REMOTE_CACHE_OPTION)
.map_or(Ok(config.write_remote_cache), parse_bool)?;
let docker_repo = matches
.value_of(DOCKER_REPO_OPTION)
.unwrap_or(&config.docker_repo)
.to_owned();
let docker_cli = matches
.value_of(DOCKER_CLI_OPTION)
.unwrap_or(&config.docker_cli)
.to_owned();
let list = matches.is_present(LIST_OPTION);
let spawn_shell = matches.is_present(SHELL_OPTION);
let tasks = matches.values_of(TASKS_OPTION).map(|tasks| {
tasks
.map(std::borrow::ToOwned::to_owned)
.collect::<Vec<_>>()
});
let forced_tasks = matches
.values_of(FORCE_OPTION)
.map_or_else(Vec::new, |tasks| {
tasks
.map(std::borrow::ToOwned::to_owned)
.collect::<Vec<_>>()
});
Ok(Settings {
toastfile_path,
docker_cli,
docker_repo,
read_local_cache,
write_local_cache,
read_remote_cache,
write_remote_cache,
list,
spawn_shell,
tasks,
forced_tasks,
})
}
fn parse_toastfile(toastfile_path: &Path) -> Result<toastfile::Toastfile, Failure> {
let toastfile_data = fs::read_to_string(toastfile_path).map_err(failure::user(format!(
"Unable to read file {}.",
toastfile_path.to_string_lossy().code_str(),
)))?;
toastfile::parse(&toastfile_data).map_err(failure::user(format!(
"Unable to parse file {}.",
toastfile_path.to_string_lossy().code_str(),
)))
}
fn get_roots<'a>(
settings: &'a Settings,
toastfile: &'a toastfile::Toastfile,
) -> Result<Vec<&'a str>, Failure> {
let mut roots: Vec<&'a str> = settings
.tasks
.as_ref()
.map_or_else(Vec::new, |tasks| tasks.iter().map(AsRef::as_ref).collect());
roots.extend(
settings
.forced_tasks
.iter()
.map(AsRef::as_ref)
.collect::<Vec<&'a str>>(),
);
if roots.is_empty() {
if let Some(default) = &toastfile.default {
Ok(vec![default.as_ref()])
} else {
Ok(toastfile
.tasks
.keys()
.map(AsRef::as_ref)
.collect::<Vec<_>>())
}
} else {
for task in &roots {
if !toastfile.tasks.contains_key(*task) {
return Err(Failure::User(
format!(
"No task named {} in {}.",
task.code_str(),
settings.toastfile_path.to_string_lossy().code_str(),
),
None,
));
}
}
Ok(roots)
}
}
fn fetch_environment(
schedule: &[&str],
tasks: &HashMap<String, toastfile::Task>,
) -> Result<HashMap<String, String>, Failure> {
let mut env = HashMap::new();
let mut violations = HashMap::new();
for task in schedule {
match toastfile::environment(&tasks[*task]) {
Ok(env_for_task) => {
env.extend(env_for_task);
}
Err(vars) => {
violations.insert((*task).to_owned(), vars);
}
}
}
if !violations.is_empty() {
return Err(Failure::User(
format!(
"The following tasks use variables which are missing from the environment: {}.",
format::series(
violations
.iter()
.map(|(task_name, vars)| {
format!(
"{} ({})",
task_name.code_str(),
format::series(
vars.iter()
.map(|var| format!("{}", var.code_str()))
.collect::<Vec<_>>()
.as_ref(),
),
)
})
.collect::<Vec<_>>()
.as_ref(),
),
),
None,
));
}
Ok(env)
}
#[allow(clippy::too_many_arguments)]
fn run_tasks(
schedule: &[&str],
settings: &Settings,
toastfile: &toastfile::Toastfile,
environment: &HashMap<String, String>,
need_context: bool,
interrupted: &Arc<AtomicBool>,
active_containers: &Arc<Mutex<HashSet<String>>>,
) -> (Result<(), Failure>, Option<runner::Context>, Option<String>) {
let mut caching_enabled = true;
let mut context = Some(runner::Context {
image: toastfile.image.clone(),
persist: true,
interrupted: interrupted.clone(),
docker_cli: settings.docker_cli.clone(),
});
for (i, task_name) in schedule.iter().enumerate() {
let task_data = &toastfile.tasks[*task_name];
caching_enabled = caching_enabled
&& task_data.cache
&& !settings
.forced_tasks
.iter()
.any(|forced_task| task_name == forced_task);
if interrupted.load(Ordering::SeqCst) {
return (
Err(Failure::Interrupted),
context,
Some((*task_name).to_owned()),
);
}
info!("Running task {}\u{2026}", task_name.code_str());
let (result, new_context) = runner::run(
settings,
environment,
interrupted,
active_containers,
toastfile,
task_data,
caching_enabled,
context.unwrap(), need_context || i != schedule.len() - 1, );
context = new_context;
if let Err(e) = result {
return (Err(e), context, Some((*task_name).to_owned()));
}
}
(
Ok(()),
context,
schedule.last().map(|task_name| (*task_name).to_owned()),
)
}
#[allow(clippy::too_many_lines)]
fn entry() -> Result<(), Failure> {
colored::control::set_override(atty::is(Stream::Stderr));
set_up_logging();
let interrupted = Arc::new(AtomicBool::new(false));
let active_containers = Arc::new(Mutex::new(HashSet::<String>::new()));
let settings = settings()?;
set_up_signal_handlers(
settings.docker_cli.clone(),
interrupted.clone(),
active_containers.clone(),
)?;
let toastfile = parse_toastfile(&settings.toastfile_path)?;
if settings.list {
info!("Here are the tasks that have a description:");
let mut task_names = toastfile
.tasks
.iter()
.filter(|(_, t)| t.description.is_some())
.map(|(k, _)| k)
.collect::<Vec<_>>();
task_names.sort();
for task_name in task_names {
let task_data = &toastfile.tasks[task_name];
println!(
"* {} \u{2014} {}",
task_name.code_str(),
task_data.description.as_ref().unwrap(),
);
for (variable, optional_default) in &task_data.environment {
if let Some(default) = optional_default {
println!(" {}: {}", variable.code_str(), default.code_str());
} else {
println!(" {}: (no default provided)", variable.code_str());
}
}
}
return Ok(());
}
let root_tasks = get_roots(&settings, &toastfile)?;
let schedule = schedule::compute(&toastfile, &root_tasks);
if !schedule.is_empty() {
info!(
"Ready to run {}: {}.",
format::number(schedule.len(), "task"),
format::series(
schedule
.iter()
.map(|task| task.code_str().to_string())
.collect::<Vec<_>>()
.as_ref(),
),
);
}
let environment = fetch_environment(&schedule, &toastfile.tasks)?;
let (result, context, last_task) = run_tasks(
&schedule,
&settings,
&toastfile,
&environment,
settings.spawn_shell, &interrupted,
&active_containers,
);
match result {
Ok(_) | Err(Failure::User(_, _)) => {
}
Err(Failure::Interrupted | Failure::System(_, _)) => {
return result;
}
};
if settings.spawn_shell {
if let Err(e) = &result {
error!("{}", e);
}
info!("Preparing a shell\u{2026}");
let (task_environment, location, mount_paths, mount_readonly, ports, user, extra_args) =
if let Some(last_task) = last_task {
let last_task = &toastfile.tasks[&last_task];
let mut task_environment = HashMap::<String, String>::new();
for variable in last_task.environment.keys() {
task_environment.insert(variable.clone(), environment[variable].clone());
}
(
task_environment,
location(&toastfile, last_task),
last_task.mount_paths.clone(),
last_task.mount_readonly,
last_task.ports.clone(),
user(&toastfile, last_task),
last_task.extra_docker_arguments.clone(),
)
} else {
(
HashMap::default(), Path::new("/").to_owned(), Vec::default(), default_task_mount_readonly(),
Vec::default(), DEFAULT_USER.to_owned(),
Vec::default(),
)
};
let mut toastfile_dir = PathBuf::from(&settings.toastfile_path);
toastfile_dir.pop();
docker::spawn_shell(
&settings.docker_cli,
&context.unwrap().image, &toastfile_dir,
&task_environment,
&location,
&mount_paths,
mount_readonly,
&ports,
&user,
&extra_args,
&interrupted,
)?;
}
result
}
fn main() {
if let Err(e) = entry() {
error!("{}", e);
exit(1);
}
}