Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor run::run into Config::run #490

Merged
merged 1 commit into from
Oct 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 2 additions & 9 deletions src/assignment_evaluator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,10 @@ mod test {
use super::*;
use crate::testing::parse;

fn no_cwd_err() -> Result<PathBuf, String> {
Err(String::from("no cwd in tests"))
}

#[test]
fn backtick_code() {
match parse("a:\n echo {{`f() { return 100; }; f`}}")
.run(&no_cwd_err(), &["a"], &Default::default())
.run(&["a"], &Default::default())
.unwrap_err()
{
RuntimeError::Backtick {
Expand Down Expand Up @@ -202,10 +198,7 @@ recipe:
..Default::default()
};

match parse(text)
.run(&no_cwd_err(), &["recipe"], &config)
.unwrap_err()
{
match parse(text).run(&["recipe"], &config).unwrap_err() {
RuntimeError::Backtick {
token,
output_error: OutputError::Code(_),
Expand Down
24 changes: 14 additions & 10 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ pub(crate) use std::{
borrow::Cow,
cmp,
collections::{BTreeMap, BTreeSet},
convert::AsRef,
env,
ffi::OsStr,
fmt::{self, Display, Formatter},
fs, io, iter,
ops::{Range, RangeInclusive},
Expand All @@ -16,7 +18,7 @@ pub(crate) use std::{

// dependencies
pub(crate) use edit_distance::edit_distance;
pub(crate) use libc::{EXIT_FAILURE, EXIT_SUCCESS};
pub(crate) use libc::EXIT_FAILURE;
pub(crate) use log::warn;
pub(crate) use unicode_width::UnicodeWidthChar;

Expand All @@ -38,21 +40,23 @@ pub(crate) use crate::{
pub(crate) use crate::{
alias::Alias, alias_resolver::AliasResolver, assignment_evaluator::AssignmentEvaluator,
assignment_resolver::AssignmentResolver, color::Color, compilation_error::CompilationError,
compilation_error_kind::CompilationErrorKind, config::Config, expression::Expression,
fragment::Fragment, function::Function, function_context::FunctionContext, functions::Functions,
interrupt_guard::InterruptGuard, interrupt_handler::InterruptHandler, justfile::Justfile,
lexer::Lexer, output_error::OutputError, parameter::Parameter, parser::Parser,
platform::Platform, position::Position, recipe::Recipe, recipe_context::RecipeContext,
recipe_resolver::RecipeResolver, runtime_error::RuntimeError, search_error::SearchError,
shebang::Shebang, state::State, string_literal::StringLiteral, subcommand::Subcommand,
token::Token, token_kind::TokenKind, use_color::UseColor, variables::Variables,
verbosity::Verbosity, warning::Warning,
compilation_error_kind::CompilationErrorKind, config::Config, config_error::ConfigError,
expression::Expression, fragment::Fragment, function::Function,
function_context::FunctionContext, functions::Functions, interrupt_guard::InterruptGuard,
interrupt_handler::InterruptHandler, justfile::Justfile, lexer::Lexer, output_error::OutputError,
parameter::Parameter, parser::Parser, platform::Platform, position::Position, recipe::Recipe,
recipe_context::RecipeContext, recipe_resolver::RecipeResolver, runtime_error::RuntimeError,
search_error::SearchError, shebang::Shebang, state::State, string_literal::StringLiteral,
subcommand::Subcommand, token::Token, token_kind::TokenKind, use_color::UseColor,
variables::Variables, verbosity::Verbosity, warning::Warning,
};

pub(crate) type CompilationResult<'a, T> = Result<T, CompilationError<'a>>;

pub(crate) type RunResult<'a, T> = Result<T, RuntimeError<'a>>;

pub(crate) type ConfigResult<T> = Result<T, ConfigError>;

#[allow(unused_imports)]
pub(crate) use std::io::prelude::*;

Expand Down
65 changes: 46 additions & 19 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,24 @@ pub(crate) struct Config<'a> {
pub(crate) color: Color,
pub(crate) verbosity: Verbosity,
pub(crate) arguments: Vec<&'a str>,
pub(crate) justfile: Option<&'a Path>,
pub(crate) working_directory: Option<&'a Path>,
pub(crate) invocation_directory: Result<PathBuf, String>,
}

mod arg {
pub(crate) const EDIT: &str = "EDIT";
pub(crate) const SUMMARY: &str = "SUMMARY";
pub(crate) const DUMP: &str = "DUMP";
pub(crate) const COLOR: &str = "COLOR";
pub(crate) const EDIT: &str = "EDIT";
pub(crate) const LIST: &str = "LIST";
pub(crate) const SHOW: &str = "SHOW";
pub(crate) const SUMMARY: &str = "SUMMARY";
pub(crate) const WORKING_DIRECTORY: &str = "WORKING-DIRECTORY";

pub(crate) const COLOR_AUTO: &str = "auto";
pub(crate) const COLOR_ALWAYS: &str = "always";
pub(crate) const COLOR_NEVER: &str = "never";
pub(crate) const COLOR_VALUES: &[&str] = &[COLOR_AUTO, COLOR_ALWAYS, COLOR_NEVER];
}

impl<'a> Config<'a> {
Expand All @@ -38,11 +48,11 @@ impl<'a> Config<'a> {
.help("The recipe(s) to run, defaults to the first recipe in the justfile"),
)
.arg(
Arg::with_name("COLOR")
Arg::with_name(arg::COLOR)
.long("color")
.takes_value(true)
.possible_values(&["auto", "always", "never"])
.default_value("auto")
.possible_values(arg::COLOR_VALUES)
.default_value(arg::COLOR_AUTO)
.help("Print colorful output"),
)
.arg(
Expand Down Expand Up @@ -129,7 +139,7 @@ impl<'a> Config<'a> {
.help("Use verbose output"),
)
.arg(
Arg::with_name("WORKING-DIRECTORY")
Arg::with_name(arg::WORKING_DIRECTORY)
.short("d")
.long("working-directory")
.takes_value(true)
Expand Down Expand Up @@ -164,18 +174,28 @@ impl<'a> Config<'a> {
}
}

pub(crate) fn from_matches(matches: &'a ArgMatches<'a>) -> Config<'a> {
fn color_from_value(value: &str) -> ConfigResult<Color> {
match value {
arg::COLOR_AUTO => Ok(Color::auto()),
arg::COLOR_ALWAYS => Ok(Color::always()),
arg::COLOR_NEVER => Ok(Color::never()),
_ => Err(ConfigError::Internal {
message: format!("Invalid argument `{}` to --color.", value),
}),
}
}

pub(crate) fn from_matches(matches: &'a ArgMatches<'a>) -> ConfigResult<Config<'a>> {
let invocation_directory =
env::current_dir().map_err(|e| format!("Error getting current directory: {}", e));

let verbosity = Verbosity::from_flag_occurrences(matches.occurrences_of("VERBOSE"));

let color = match matches.value_of("COLOR").expect("`--color` had no value") {
"auto" => Color::auto(),
"always" => Color::always(),
"never" => Color::never(),
other => die!(
"Invalid argument `{}` to --color. This is a bug in just.",
other
),
};
let color = Self::color_from_value(
matches
.value_of(arg::COLOR)
.expect("`--color` had no value"),
)?;

let set_count = matches.occurrences_of("SET");
let mut overrides = BTreeMap::new();
Expand Down Expand Up @@ -216,7 +236,7 @@ impl<'a> Config<'a> {
.flat_map(|(i, argument)| {
if i == 0 {
if let Some(i) = argument.rfind('/') {
if matches.is_present("WORKING-DIRECTORY") {
if matches.is_present(arg::WORKING_DIRECTORY) {
die!("--working-directory and a path prefixed recipe may not be used together.");
}

Expand Down Expand Up @@ -252,18 +272,21 @@ impl<'a> Config<'a> {
Subcommand::Run
};

Config {
Ok(Config {
dry_run: matches.is_present("DRY-RUN"),
evaluate: matches.is_present("EVALUATE"),
highlight: matches.is_present("HIGHLIGHT"),
quiet: matches.is_present("QUIET"),
shell: matches.value_of("SHELL").unwrap(),
justfile: matches.value_of("JUSTFILE").map(Path::new),
working_directory: matches.value_of("WORKING-DIRECTORY").map(Path::new),
invocation_directory,
subcommand,
verbosity,
color,
overrides,
arguments,
}
})
}
}

Expand All @@ -280,6 +303,10 @@ impl<'a> Default for Config<'a> {
shell: DEFAULT_SHELL,
color: default(),
verbosity: Verbosity::from_flag_occurrences(0),
justfile: None,
working_directory: None,
invocation_directory: env::current_dir()
.map_err(|e| format!("Error getting current directory: {}", e)),
}
}
}
20 changes: 20 additions & 0 deletions src/config_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use crate::common::*;

pub(crate) enum ConfigError {
Internal { message: String },
}

impl Display for ConfigError {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
use ConfigError::*;

match self {
Internal { message } => write!(
f,
"Internal config error, this may indicate a bug in just: {} \
consider filing an issue: https://github.com/casey/just/issues/new",
message
),
}
}
}
47 changes: 14 additions & 33 deletions src/justfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,7 @@ impl<'a> Justfile<'a> {
None
}

pub(crate) fn run(
&'a self,
invocation_directory: &'a Result<PathBuf, String>,
arguments: &[&'a str],
config: &'a Config<'a>,
) -> RunResult<'a, ()> {
pub(crate) fn run(&'a self, arguments: &[&'a str], config: &'a Config<'a>) -> RunResult<'a, ()> {
let unknown_overrides = config
.overrides
.keys()
Expand All @@ -66,7 +61,7 @@ impl<'a> Justfile<'a> {

let scope = AssignmentEvaluator::evaluate_assignments(
&self.assignments,
invocation_directory,
&config.invocation_directory,
&dotenv,
&config.overrides,
config.quiet,
Expand Down Expand Up @@ -127,11 +122,7 @@ impl<'a> Justfile<'a> {
});
}

let context = RecipeContext {
invocation_directory,
config,
scope,
};
let context = RecipeContext { config, scope };

let mut ran = empty();
for (recipe, arguments) in grouped {
Expand Down Expand Up @@ -212,14 +203,10 @@ mod test {
use crate::runtime_error::RuntimeError::*;
use crate::testing::parse;

fn no_cwd_err() -> Result<PathBuf, String> {
Err(String::from("no cwd in tests"))
}

#[test]
fn unknown_recipes() {
match parse("a:\nb:\nc:")
.run(&no_cwd_err(), &["a", "x", "y", "z"], &Default::default())
.run(&["a", "x", "y", "z"], &Default::default())
.unwrap_err()
{
UnknownRecipes {
Expand Down Expand Up @@ -251,10 +238,7 @@ a:
x
";

match parse(text)
.run(&no_cwd_err(), &["a"], &Default::default())
.unwrap_err()
{
match parse(text).run(&["a"], &Default::default()).unwrap_err() {
Code {
recipe,
line_number,
Expand All @@ -271,7 +255,7 @@ a:
#[test]
fn code_error() {
match parse("fail:\n @exit 100")
.run(&no_cwd_err(), &["fail"], &Default::default())
.run(&["fail"], &Default::default())
.unwrap_err()
{
Code {
Expand All @@ -294,7 +278,7 @@ a return code:
@x() { {{return}} {{code + "0"}}; }; x"#;

match parse(text)
.run(&no_cwd_err(), &["a", "return", "15"], &Default::default())
.run(&["a", "return", "15"], &Default::default())
.unwrap_err()
{
Code {
Expand All @@ -313,7 +297,7 @@ a return code:
#[test]
fn missing_some_arguments() {
match parse("a b c d:")
.run(&no_cwd_err(), &["a", "b", "c"], &Default::default())
.run(&["a", "b", "c"], &Default::default())
.unwrap_err()
{
ArgumentCountMismatch {
Expand All @@ -337,7 +321,7 @@ a return code:
#[test]
fn missing_some_arguments_variadic() {
match parse("a b c +d:")
.run(&no_cwd_err(), &["a", "B", "C"], &Default::default())
.run(&["a", "B", "C"], &Default::default())
.unwrap_err()
{
ArgumentCountMismatch {
Expand All @@ -361,7 +345,7 @@ a return code:
#[test]
fn missing_all_arguments() {
match parse("a b c d:\n echo {{b}}{{c}}{{d}}")
.run(&no_cwd_err(), &["a"], &Default::default())
.run(&["a"], &Default::default())
.unwrap_err()
{
ArgumentCountMismatch {
Expand All @@ -385,7 +369,7 @@ a return code:
#[test]
fn missing_some_defaults() {
match parse("a b c d='hello':")
.run(&no_cwd_err(), &["a", "b"], &Default::default())
.run(&["a", "b"], &Default::default())
.unwrap_err()
{
ArgumentCountMismatch {
Expand All @@ -409,7 +393,7 @@ a return code:
#[test]
fn missing_all_defaults() {
match parse("a b c='r' d='h':")
.run(&no_cwd_err(), &["a"], &Default::default())
.run(&["a"], &Default::default())
.unwrap_err()
{
ArgumentCountMismatch {
Expand All @@ -436,7 +420,7 @@ a return code:
config.overrides.insert("foo", "bar");
config.overrides.insert("baz", "bob");
match parse("a:\n echo {{`f() { return 100; }; f`}}")
.run(&no_cwd_err(), &["a"], &config)
.run(&["a"], &config)
.unwrap_err()
{
UnknownOverrides { overrides } => {
Expand All @@ -463,10 +447,7 @@ wut:
..Default::default()
};

match parse(text)
.run(&no_cwd_err(), &["wut"], &config)
.unwrap_err()
{
match parse(text).run(&["wut"], &config).unwrap_err() {
Code {
code: _,
line_number,
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ mod common;
mod compilation_error;
mod compilation_error_kind;
mod config;
mod config_error;
mod expression;
mod fragment;
mod function;
Expand Down
4 changes: 3 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
fn main() {
just::run();
if let Err(code) = just::run() {
std::process::exit(code);
}
}
Loading