parent
ec82cc20d3
commit
3d67786aaf
@ -48,7 +48,7 @@ impl<'a, 'b> AssignmentEvaluator<'a, 'b> {
|
||||
pub fn evaluate_line(
|
||||
&mut self,
|
||||
line: &[Fragment<'a>],
|
||||
arguments: &Map<&str, Cow<str>>
|
||||
arguments: &Map<&str, Cow<str>>,
|
||||
) -> RunResult<'a, String> {
|
||||
let mut evaluated = String::new();
|
||||
for fragment in line {
|
||||
@ -76,7 +76,7 @@ impl<'a, 'b> AssignmentEvaluator<'a, 'b> {
|
||||
}
|
||||
} else {
|
||||
return Err(RuntimeError::Internal {
|
||||
message: format!("attempted to evaluated unknown assignment {}", name)
|
||||
message: format!("attempted to evaluated unknown assignment {}", name),
|
||||
});
|
||||
}
|
||||
|
||||
@ -86,7 +86,7 @@ impl<'a, 'b> AssignmentEvaluator<'a, 'b> {
|
||||
fn evaluate_expression(
|
||||
&mut self,
|
||||
expression: &Expression<'a>,
|
||||
arguments: &Map<&str, Cow<str>>
|
||||
arguments: &Map<&str, Cow<str>>,
|
||||
) -> RunResult<'a, String> {
|
||||
match *expression {
|
||||
Expression::Variable { name, .. } => {
|
||||
@ -101,14 +101,19 @@ impl<'a, 'b> AssignmentEvaluator<'a, 'b> {
|
||||
Ok(arguments[name].to_string())
|
||||
} else {
|
||||
Err(RuntimeError::Internal {
|
||||
message: format!("attempted to evaluate undefined variable `{}`", name)
|
||||
message: format!("attempted to evaluate undefined variable `{}`", name),
|
||||
})
|
||||
}
|
||||
}
|
||||
Expression::Call{name, arguments: ref call_arguments, ref token} => {
|
||||
let call_arguments = call_arguments.iter().map(|argument| {
|
||||
self.evaluate_expression(argument, arguments)
|
||||
}).collect::<Result<Vec<String>, RuntimeError>>()?;
|
||||
Expression::Call {
|
||||
name,
|
||||
arguments: ref call_arguments,
|
||||
ref token,
|
||||
} => {
|
||||
let call_arguments = call_arguments
|
||||
.iter()
|
||||
.map(|argument| self.evaluate_expression(argument, arguments))
|
||||
.collect::<Result<Vec<String>, RuntimeError>>()?;
|
||||
let context = FunctionContext {
|
||||
invocation_directory: &self.invocation_directory,
|
||||
dotenv: self.dotenv,
|
||||
@ -124,11 +129,7 @@ impl<'a, 'b> AssignmentEvaluator<'a, 'b> {
|
||||
}
|
||||
}
|
||||
Expression::Concatination { ref lhs, ref rhs } => {
|
||||
Ok(
|
||||
self.evaluate_expression(lhs, arguments)?
|
||||
+
|
||||
&self.evaluate_expression(rhs, arguments)?
|
||||
)
|
||||
Ok(self.evaluate_expression(lhs, arguments)? + &self.evaluate_expression(rhs, arguments)?)
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -143,8 +144,7 @@ impl<'a, 'b> AssignmentEvaluator<'a, 'b> {
|
||||
|
||||
cmd.export_environment_variables(self.scope, dotenv, self.exports)?;
|
||||
|
||||
cmd.arg("-cu")
|
||||
.arg(raw);
|
||||
cmd.arg("-cu").arg(raw);
|
||||
|
||||
cmd.stderr(if self.quiet {
|
||||
process::Stdio::null()
|
||||
@ -152,13 +152,15 @@ impl<'a, 'b> AssignmentEvaluator<'a, 'b> {
|
||||
process::Stdio::inherit()
|
||||
});
|
||||
|
||||
InterruptHandler::guard(|| brev::output(cmd)
|
||||
.map_err(|output_error| RuntimeError::Backtick{token: token.clone(), output_error})
|
||||
)
|
||||
InterruptHandler::guard(|| {
|
||||
brev::output(cmd).map_err(|output_error| RuntimeError::Backtick {
|
||||
token: token.clone(),
|
||||
output_error,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
@ -173,11 +175,16 @@ mod test {
|
||||
#[test]
|
||||
fn backtick_code() {
|
||||
match parse_success("a:\n echo {{`f() { return 100; }; f`}}")
|
||||
.run(&no_cwd_err(), &["a"], &Default::default()).unwrap_err() {
|
||||
RuntimeError::Backtick{token, output_error: OutputError::Code(code)} => {
|
||||
.run(&no_cwd_err(), &["a"], &Default::default())
|
||||
.unwrap_err()
|
||||
{
|
||||
RuntimeError::Backtick {
|
||||
token,
|
||||
output_error: OutputError::Code(code),
|
||||
} => {
|
||||
assert_eq!(code, 100);
|
||||
assert_eq!(token.lexeme, "`f() { return 100; }; f`");
|
||||
},
|
||||
}
|
||||
other => panic!("expected a code run error, but got: {}", other),
|
||||
}
|
||||
}
|
||||
@ -196,10 +203,16 @@ recipe:
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
match parse_success(text).run(&no_cwd_err(), &["recipe"], &configuration).unwrap_err() {
|
||||
RuntimeError::Backtick{token, output_error: OutputError::Code(_)} => {
|
||||
match parse_success(text)
|
||||
.run(&no_cwd_err(), &["recipe"], &configuration)
|
||||
.unwrap_err()
|
||||
{
|
||||
RuntimeError::Backtick {
|
||||
token,
|
||||
output_error: OutputError::Code(_),
|
||||
} => {
|
||||
assert_eq!(token.lexeme, "`echo $exported_variable`");
|
||||
},
|
||||
}
|
||||
other => panic!("expected a backtick code errror, but got: {}", other),
|
||||
}
|
||||
}
|
||||
|
@ -15,7 +15,6 @@ impl<'a: 'b, 'b> AssignmentResolver<'a, 'b> {
|
||||
assignments: &Map<&'a str, Expression<'a>>,
|
||||
assignment_tokens: &Map<&'a str, Token<'a>>,
|
||||
) -> CompilationResult<'a, ()> {
|
||||
|
||||
let mut resolver = AssignmentResolver {
|
||||
stack: empty(),
|
||||
seen: empty(),
|
||||
@ -50,14 +49,13 @@ impl<'a: 'b, 'b> AssignmentResolver<'a, 'b> {
|
||||
line: 0,
|
||||
column: 0,
|
||||
width: None,
|
||||
kind: Internal{message}
|
||||
kind: Internal { message },
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn resolve_expression(
|
||||
&mut self, expression: &Expression<'a>) -> CompilationResult<'a, ()> {
|
||||
fn resolve_expression(&mut self, expression: &Expression<'a>) -> CompilationResult<'a, ()> {
|
||||
match *expression {
|
||||
Expression::Variable { name, ref token } => {
|
||||
if self.evaluated.contains(name) {
|
||||
@ -75,9 +73,11 @@ impl<'a: 'b, 'b> AssignmentResolver<'a, 'b> {
|
||||
return Err(token.error(UndefinedVariable { variable: name }));
|
||||
}
|
||||
}
|
||||
Expression::Call{ref token, ref arguments, ..} => {
|
||||
resolve_function(token, arguments.len())?
|
||||
}
|
||||
Expression::Call {
|
||||
ref token,
|
||||
ref arguments,
|
||||
..
|
||||
} => resolve_function(token, arguments.len())?,
|
||||
Expression::Concatination { ref lhs, ref rhs } => {
|
||||
self.resolve_expression(lhs)?;
|
||||
self.resolve_expression(rhs)?;
|
||||
|
@ -3,8 +3,8 @@ extern crate atty;
|
||||
|
||||
use common::*;
|
||||
|
||||
use self::ansi_term::{Style, Prefix, Suffix, ANSIGenericString};
|
||||
use self::ansi_term::Color::*;
|
||||
use self::ansi_term::{ANSIGenericString, Prefix, Style, Suffix};
|
||||
use self::atty::is as is_atty;
|
||||
use self::atty::Stream;
|
||||
|
||||
@ -34,10 +34,7 @@ impl Default for Color {
|
||||
|
||||
impl Color {
|
||||
fn restyle(self, style: Style) -> Color {
|
||||
Color {
|
||||
style,
|
||||
..self
|
||||
}
|
||||
Color { style, ..self }
|
||||
}
|
||||
|
||||
fn redirect(self, stream: Stream) -> Color {
|
||||
|
@ -5,7 +5,7 @@ pub trait CommandExt {
|
||||
&mut self,
|
||||
scope: &Map<&'a str, String>,
|
||||
dotenv: &Map<String, String>,
|
||||
exports: &Set<&'a str>
|
||||
exports: &Set<&'a str>,
|
||||
) -> RunResult<'a, ()>;
|
||||
}
|
||||
|
||||
@ -14,7 +14,7 @@ impl CommandExt for Command {
|
||||
&mut self,
|
||||
scope: &Map<&'a str, String>,
|
||||
dotenv: &Map<String, String>,
|
||||
exports: &Set<&'a str>
|
||||
exports: &Set<&'a str>,
|
||||
) -> RunResult<'a, ()> {
|
||||
for (name, value) in dotenv {
|
||||
self.env(name, value);
|
||||
|
@ -6,7 +6,7 @@ pub use std::ops::Range;
|
||||
pub use std::path::{Path, PathBuf};
|
||||
pub use std::process::Command;
|
||||
pub use std::sync::{Mutex, MutexGuard};
|
||||
pub use std::{cmp, env, fs, fmt, io, iter, process, vec, usize};
|
||||
pub use std::{cmp, env, fmt, fs, io, iter, process, usize, vec};
|
||||
|
||||
pub use color::Color;
|
||||
pub use libc::{EXIT_FAILURE, EXIT_SUCCESS};
|
||||
@ -32,7 +32,7 @@ pub use parser::Parser;
|
||||
pub use range_ext::RangeExt;
|
||||
pub use recipe::{Recipe, RecipeContext};
|
||||
pub use recipe_resolver::RecipeResolver;
|
||||
pub use runtime_error::{RuntimeError, RunResult};
|
||||
pub use runtime_error::{RunResult, RuntimeError};
|
||||
pub use shebang::Shebang;
|
||||
pub use token::{Token, TokenKind};
|
||||
pub use verbosity::Verbosity;
|
||||
|
@ -1,6 +1,6 @@
|
||||
use common::*;
|
||||
|
||||
use misc::{Or, write_error_context, show_whitespace, maybe_s};
|
||||
use misc::{maybe_s, show_whitespace, write_error_context, Or};
|
||||
|
||||
pub type CompilationResult<'a, T> = Result<T, CompilationError<'a>>;
|
||||
|
||||
@ -16,27 +16,76 @@ pub struct CompilationError<'a> {
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum CompilationErrorKind<'a> {
|
||||
CircularRecipeDependency{recipe: &'a str, circle: Vec<&'a str>},
|
||||
CircularVariableDependency{variable: &'a str, circle: Vec<&'a str>},
|
||||
DependencyHasParameters{recipe: &'a str, dependency: &'a str},
|
||||
DuplicateDependency{recipe: &'a str, dependency: &'a str},
|
||||
DuplicateParameter{recipe: &'a str, parameter: &'a str},
|
||||
DuplicateRecipe{recipe: &'a str, first: usize},
|
||||
DuplicateVariable{variable: &'a str},
|
||||
CircularRecipeDependency {
|
||||
recipe: &'a str,
|
||||
circle: Vec<&'a str>,
|
||||
},
|
||||
CircularVariableDependency {
|
||||
variable: &'a str,
|
||||
circle: Vec<&'a str>,
|
||||
},
|
||||
DependencyHasParameters {
|
||||
recipe: &'a str,
|
||||
dependency: &'a str,
|
||||
},
|
||||
DuplicateDependency {
|
||||
recipe: &'a str,
|
||||
dependency: &'a str,
|
||||
},
|
||||
DuplicateParameter {
|
||||
recipe: &'a str,
|
||||
parameter: &'a str,
|
||||
},
|
||||
DuplicateRecipe {
|
||||
recipe: &'a str,
|
||||
first: usize,
|
||||
},
|
||||
DuplicateVariable {
|
||||
variable: &'a str,
|
||||
},
|
||||
ExtraLeadingWhitespace,
|
||||
FunctionArgumentCountMismatch{function: &'a str, found: usize, expected: usize},
|
||||
InconsistentLeadingWhitespace{expected: &'a str, found: &'a str},
|
||||
Internal{message: String},
|
||||
InvalidEscapeSequence{character: char},
|
||||
MixedLeadingWhitespace{whitespace: &'a str},
|
||||
FunctionArgumentCountMismatch {
|
||||
function: &'a str,
|
||||
found: usize,
|
||||
expected: usize,
|
||||
},
|
||||
InconsistentLeadingWhitespace {
|
||||
expected: &'a str,
|
||||
found: &'a str,
|
||||
},
|
||||
Internal {
|
||||
message: String,
|
||||
},
|
||||
InvalidEscapeSequence {
|
||||
character: char,
|
||||
},
|
||||
MixedLeadingWhitespace {
|
||||
whitespace: &'a str,
|
||||
},
|
||||
OuterShebang,
|
||||
ParameterFollowsVariadicParameter{parameter: &'a str},
|
||||
ParameterShadowsVariable{parameter: &'a str},
|
||||
RequiredParameterFollowsDefaultParameter{parameter: &'a str},
|
||||
UndefinedVariable{variable: &'a str},
|
||||
UnexpectedToken{expected: Vec<TokenKind>, found: TokenKind},
|
||||
UnknownDependency{recipe: &'a str, unknown: &'a str},
|
||||
UnknownFunction{function: &'a str},
|
||||
ParameterFollowsVariadicParameter {
|
||||
parameter: &'a str,
|
||||
},
|
||||
ParameterShadowsVariable {
|
||||
parameter: &'a str,
|
||||
},
|
||||
RequiredParameterFollowsDefaultParameter {
|
||||
parameter: &'a str,
|
||||
},
|
||||
UndefinedVariable {
|
||||
variable: &'a str,
|
||||
},
|
||||
UnexpectedToken {
|
||||
expected: Vec<TokenKind>,
|
||||
found: TokenKind,
|
||||
},
|
||||
UnknownDependency {
|
||||
recipe: &'a str,
|
||||
unknown: &'a str,
|
||||
},
|
||||
UnknownFunction {
|
||||
function: &'a str,
|
||||
},
|
||||
UnknownStartOfToken,
|
||||
UnterminatedInterpolation,
|
||||
UnterminatedString,
|
||||
@ -55,16 +104,27 @@ impl<'a> Display for CompilationError<'a> {
|
||||
if circle.len() == 2 {
|
||||
writeln!(f, "Recipe `{}` depends on itself", recipe)?;
|
||||
} else {
|
||||
writeln!(f, "Recipe `{}` has circular dependency `{}`",
|
||||
recipe, circle.join(" -> "))?;
|
||||
writeln!(
|
||||
f,
|
||||
"Recipe `{}` has circular dependency `{}`",
|
||||
recipe,
|
||||
circle.join(" -> ")
|
||||
)?;
|
||||
}
|
||||
}
|
||||
CircularVariableDependency{variable, ref circle} => {
|
||||
CircularVariableDependency {
|
||||
variable,
|
||||
ref circle,
|
||||
} => {
|
||||
if circle.len() == 2 {
|
||||
writeln!(f, "Variable `{}` is defined in terms of itself", variable)?;
|
||||
} else {
|
||||
writeln!(f, "Variable `{}` depends on its own value: `{}`",
|
||||
variable, circle.join(" -> "))?;
|
||||
writeln!(
|
||||
f,
|
||||
"Variable `{}` depends on its own value: `{}`",
|
||||
variable,
|
||||
circle.join(" -> ")
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
@ -79,36 +139,65 @@ impl<'a> Display for CompilationError<'a> {
|
||||
writeln!(f, "`\\{}` is not a valid escape sequence", representation)?;
|
||||
}
|
||||
DuplicateParameter { recipe, parameter } => {
|
||||
writeln!(f, "Recipe `{}` has duplicate parameter `{}`", recipe, parameter)?;
|
||||
writeln!(
|
||||
f,
|
||||
"Recipe `{}` has duplicate parameter `{}`",
|
||||
recipe, parameter
|
||||
)?;
|
||||
}
|
||||
DuplicateVariable { variable } => {
|
||||
writeln!(f, "Variable `{}` has multiple definitions", variable)?;
|
||||
}
|
||||
UnexpectedToken{ref expected, found} => {
|
||||
UnexpectedToken {
|
||||
ref expected,
|
||||
found,
|
||||
} => {
|
||||
writeln!(f, "Expected {}, but found {}", Or(expected), found)?;
|
||||
}
|
||||
DuplicateDependency { recipe, dependency } => {
|
||||
writeln!(f, "Recipe `{}` has duplicate dependency `{}`", recipe, dependency)?;
|
||||
writeln!(
|
||||
f,
|
||||
"Recipe `{}` has duplicate dependency `{}`",
|
||||
recipe, dependency
|
||||
)?;
|
||||
}
|
||||
DuplicateRecipe { recipe, first } => {
|
||||
writeln!(f, "Recipe `{}` first defined on line {} is redefined on line {}",
|
||||
recipe, first + 1, self.line + 1)?;
|
||||
writeln!(
|
||||
f,
|
||||
"Recipe `{}` first defined on line {} is redefined on line {}",
|
||||
recipe,
|
||||
first + 1,
|
||||
self.line + 1
|
||||
)?;
|
||||
}
|
||||
DependencyHasParameters { recipe, dependency } => {
|
||||
writeln!(f, "Recipe `{}` depends on `{}` which requires arguments. \
|
||||
Dependencies may not require arguments", recipe, dependency)?;
|
||||
writeln!(
|
||||
f,
|
||||
"Recipe `{}` depends on `{}` which requires arguments. \
|
||||
Dependencies may not require arguments",
|
||||
recipe, dependency
|
||||
)?;
|
||||
}
|
||||
ParameterShadowsVariable { parameter } => {
|
||||
writeln!(f, "Parameter `{}` shadows variable of the same name", parameter)?;
|
||||
writeln!(
|
||||
f,
|
||||
"Parameter `{}` shadows variable of the same name",
|
||||
parameter
|
||||
)?;
|
||||
}
|
||||
RequiredParameterFollowsDefaultParameter { parameter } => {
|
||||
writeln!(f, "Non-default parameter `{}` follows default parameter", parameter)?;
|
||||
writeln!(
|
||||
f,
|
||||
"Non-default parameter `{}` follows default parameter",
|
||||
parameter
|
||||
)?;
|
||||
}
|
||||
ParameterFollowsVariadicParameter { parameter } => {
|
||||
writeln!(f, "Parameter `{}` follows variadic parameter", parameter)?;
|
||||
}
|
||||
MixedLeadingWhitespace { whitespace } => {
|
||||
writeln!(f,
|
||||
writeln!(
|
||||
f,
|
||||
"Found a mix of tabs and spaces in leading whitespace: `{}`\n\
|
||||
Leading whitespace may consist of tabs or spaces, but not both",
|
||||
show_whitespace(whitespace)
|
||||
@ -117,25 +206,38 @@ impl<'a> Display for CompilationError<'a> {
|
||||
ExtraLeadingWhitespace => {
|
||||
writeln!(f, "Recipe line has extra leading whitespace")?;
|
||||
}
|
||||
FunctionArgumentCountMismatch{function, found, expected} => {
|
||||
FunctionArgumentCountMismatch {
|
||||
function,
|
||||
found,
|
||||
expected,
|
||||
} => {
|
||||
writeln!(
|
||||
f,
|
||||
"Function `{}` called with {} argument{} but takes {}",
|
||||
function, found, maybe_s(found), expected
|
||||
function,
|
||||
found,
|
||||
maybe_s(found),
|
||||
expected
|
||||
)?;
|
||||
}
|
||||
InconsistentLeadingWhitespace { expected, found } => {
|
||||
writeln!(f,
|
||||
writeln!(
|
||||
f,
|
||||
"Recipe line has inconsistent leading whitespace. \
|
||||
Recipe started with `{}` but found line with `{}`",
|
||||
show_whitespace(expected), show_whitespace(found)
|
||||
show_whitespace(expected),
|
||||
show_whitespace(found)
|
||||
)?;
|
||||
}
|
||||
OuterShebang => {
|
||||
writeln!(f, "`#!` is reserved syntax outside of recipes")?;
|
||||
}
|
||||
UnknownDependency { recipe, unknown } => {
|
||||
writeln!(f, "Recipe `{}` has unknown dependency `{}`", recipe, unknown)?;
|
||||
writeln!(
|
||||
f,
|
||||
"Recipe `{}` has unknown dependency `{}`",
|
||||
recipe, unknown
|
||||
)?;
|
||||
}
|
||||
UndefinedVariable { variable } => {
|
||||
writeln!(f, "Variable `{}` not defined", variable)?;
|
||||
@ -153,9 +255,12 @@ impl<'a> Display for CompilationError<'a> {
|
||||
writeln!(f, "Unterminated string")?;
|
||||
}
|
||||
Internal { ref message } => {
|
||||
writeln!(f, "Internal error, this may indicate a bug in just: {}\n\
|
||||
writeln!(
|
||||
f,
|
||||
"Internal error, this may indicate a bug in just: {}\n\
|
||||
consider filing an issue: https://github.com/casey/just/issues/new",
|
||||
message)?;
|
||||
message
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -11,7 +11,10 @@ impl<'a> CookedString<'a> {
|
||||
let raw = &token.lexeme[1..token.lexeme.len() - 1];
|
||||
|
||||
if let TokenKind::RawString = token.kind {
|
||||
Ok(CookedString{cooked: raw.to_string(), raw})
|
||||
Ok(CookedString {
|
||||
cooked: raw.to_string(),
|
||||
raw,
|
||||
})
|
||||
} else if let TokenKind::StringToken = token.kind {
|
||||
let mut cooked = String::new();
|
||||
let mut escape = false;
|
||||
@ -23,9 +26,11 @@ impl<'a> CookedString<'a> {
|
||||
't' => cooked.push('\t'),
|
||||
'\\' => cooked.push('\\'),
|
||||
'"' => cooked.push('"'),
|
||||
other => return Err(token.error(CompilationErrorKind::InvalidEscapeSequence {
|
||||
character: other,
|
||||
})),
|
||||
other => {
|
||||
return Err(
|
||||
token.error(CompilationErrorKind::InvalidEscapeSequence { character: other }),
|
||||
)
|
||||
}
|
||||
}
|
||||
escape = false;
|
||||
continue;
|
||||
@ -39,7 +44,7 @@ impl<'a> CookedString<'a> {
|
||||
Ok(CookedString { raw, cooked })
|
||||
} else {
|
||||
Err(token.error(CompilationErrorKind::Internal {
|
||||
message: "cook_string() called on non-string token".to_string()
|
||||
message: "cook_string() called on non-string token".to_string(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
@ -2,24 +2,35 @@ use common::*;
|
||||
|
||||
#[derive(PartialEq, Debug)]
|
||||
pub enum Expression<'a> {
|
||||
Backtick{raw: &'a str, token: Token<'a>},
|
||||
Call{name: &'a str, token: Token<'a>, arguments: Vec<Expression<'a>>},
|
||||
Concatination{lhs: Box<Expression<'a>>, rhs: Box<Expression<'a>>},
|
||||
String{cooked_string: CookedString<'a>},
|
||||
Variable{name: &'a str, token: Token<'a>},
|
||||
Backtick {
|
||||
raw: &'a str,
|
||||
token: Token<'a>,
|
||||
},
|
||||
Call {
|
||||
name: &'a str,
|
||||
token: Token<'a>,
|
||||
arguments: Vec<Expression<'a>>,
|
||||
},
|
||||
Concatination {
|
||||
lhs: Box<Expression<'a>>,
|
||||
rhs: Box<Expression<'a>>,
|
||||
},
|
||||
String {
|
||||
cooked_string: CookedString<'a>,
|
||||
},
|
||||
Variable {
|
||||
name: &'a str,
|
||||
token: Token<'a>,
|
||||
},
|
||||
}
|
||||
|
||||
impl<'a> Expression<'a> {
|
||||
pub fn variables(&'a self) -> Variables<'a> {
|
||||
Variables {
|
||||
stack: vec![self],
|
||||
}
|
||||
Variables { stack: vec![self] }
|
||||
}
|
||||
|
||||
pub fn functions(&'a self) -> Functions<'a> {
|
||||
Functions {
|
||||
stack: vec![self],
|
||||
}
|
||||
Functions { stack: vec![self] }
|
||||
}
|
||||
}
|
||||
|
||||
@ -30,7 +41,11 @@ impl<'a> Display for Expression<'a> {
|
||||
Expression::Concatination { ref lhs, ref rhs } => write!(f, "{} + {}", lhs, rhs)?,
|
||||
Expression::String { ref cooked_string } => write!(f, "\"{}\"", cooked_string.raw)?,
|
||||
Expression::Variable { name, .. } => write!(f, "{}", name)?,
|
||||
Expression::Call {name, ref arguments, ..} => {
|
||||
Expression::Call {
|
||||
name,
|
||||
ref arguments,
|
||||
..
|
||||
} => {
|
||||
write!(f, "{}(", name)?;
|
||||
for (i, argument) in arguments.iter().enumerate() {
|
||||
if i > 0 {
|
||||
@ -82,7 +97,11 @@ impl<'a> Iterator for Functions<'a> {
|
||||
| Some(&Expression::String { .. })
|
||||
| Some(&Expression::Backtick { .. })
|
||||
| Some(&Expression::Variable { .. }) => None,
|
||||
Some(&Expression::Call{ref token, ref arguments, ..}) => Some((token, arguments.len())),
|
||||
Some(&Expression::Call {
|
||||
ref token,
|
||||
ref arguments,
|
||||
..
|
||||
}) => Some((token, arguments.len())),
|
||||
Some(&Expression::Concatination { ref lhs, ref rhs }) => {
|
||||
self.stack.push(lhs);
|
||||
self.stack.push(rhs);
|
||||
|
@ -11,12 +11,17 @@ lazy_static! {
|
||||
("os_family", Function::Nullary(os_family)),
|
||||
("env_var", Function::Unary(env_var)),
|
||||
("env_var_or_default", Function::Binary(env_var_or_default)),
|
||||
("invocation_directory", Function::Nullary(invocation_directory)),
|
||||
].into_iter().collect();
|
||||
(
|
||||
"invocation_directory",
|
||||
Function::Nullary(invocation_directory)
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect();
|
||||
}
|
||||
|
||||
enum Function {
|
||||
Nullary(fn(&FunctionContext, ) -> Result<String, String>),
|
||||
Nullary(fn(&FunctionContext) -> Result<String, String>),
|
||||
Unary(fn(&FunctionContext, &str) -> Result<String, String>),
|
||||
Binary(fn(&FunctionContext, &str, &str) -> Result<String, String>),
|
||||
}
|
||||
@ -42,17 +47,19 @@ pub fn resolve_function<'a>(token: &Token<'a>, argc: usize) -> CompilationResult
|
||||
if let Some(function) = FUNCTIONS.get(&name) {
|
||||
use self::Function::*;
|
||||
match (function, argc) {
|
||||
(&Nullary(_), 0) |
|
||||
(&Unary(_), 1) |
|
||||
(&Binary(_), 2) => Ok(()),
|
||||
_ => {
|
||||
Err(token.error(CompilationErrorKind::FunctionArgumentCountMismatch{
|
||||
function: name, found: argc, expected: function.argc(),
|
||||
}))
|
||||
}
|
||||
(&Nullary(_), 0) | (&Unary(_), 1) | (&Binary(_), 2) => Ok(()),
|
||||
_ => Err(
|
||||
token.error(CompilationErrorKind::FunctionArgumentCountMismatch {
|
||||
function: name,
|
||||
found: argc,
|
||||
expected: function.argc(),
|
||||
}),
|
||||
),
|
||||
}
|
||||
} else {
|
||||
Err(token.error(CompilationErrorKind::UnknownFunction{function: token.lexeme}))
|
||||
Err(token.error(CompilationErrorKind::UnknownFunction {
|
||||
function: token.lexeme,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@ -60,27 +67,36 @@ pub fn evaluate_function<'a>(
|
||||
token: &Token<'a>,
|
||||
name: &'a str,
|
||||
context: &FunctionContext,
|
||||
arguments: &[String]
|
||||
arguments: &[String],
|
||||
) -> RunResult<'a, String> {
|
||||
if let Some(function) = FUNCTIONS.get(name) {
|
||||
use self::Function::*;
|
||||
let argc = arguments.len();
|
||||
match (function, argc) {
|
||||
(&Nullary(f), 0) => f(context)
|
||||
.map_err(|message| RuntimeError::FunctionCall{token: token.clone(), message}),
|
||||
(&Unary(f), 1) => f(context, &arguments[0])
|
||||
.map_err(|message| RuntimeError::FunctionCall{token: token.clone(), message}),
|
||||
(&Binary(f), 2) => f(context, &arguments[0], &arguments[1])
|
||||
.map_err(|message| RuntimeError::FunctionCall{token: token.clone(), message}),
|
||||
_ => {
|
||||
Err(RuntimeError::Internal {
|
||||
message: format!("attempted to evaluate function `{}` with {} arguments", name, argc)
|
||||
(&Nullary(f), 0) => f(context).map_err(|message| RuntimeError::FunctionCall {
|
||||
token: token.clone(),
|
||||
message,
|
||||
}),
|
||||
(&Unary(f), 1) => f(context, &arguments[0]).map_err(|message| RuntimeError::FunctionCall {
|
||||
token: token.clone(),
|
||||
message,
|
||||
}),
|
||||
(&Binary(f), 2) => {
|
||||
f(context, &arguments[0], &arguments[1]).map_err(|message| RuntimeError::FunctionCall {
|
||||
token: token.clone(),
|
||||
message,
|
||||
})
|
||||
}
|
||||
_ => Err(RuntimeError::Internal {
|
||||
message: format!(
|
||||
"attempted to evaluate function `{}` with {} arguments",
|
||||
name, argc
|
||||
),
|
||||
}),
|
||||
}
|
||||
} else {
|
||||
Err(RuntimeError::Internal {
|
||||
message: format!("attempted to evaluate unknown function: `{}`", name)
|
||||
message: format!("attempted to evaluate unknown function: `{}`", name),
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -98,9 +114,9 @@ pub fn os_family(_context: &FunctionContext) -> Result<String, String> {
|
||||
}
|
||||
|
||||
pub fn invocation_directory(context: &FunctionContext) -> Result<String, String> {
|
||||
context.invocation_directory.clone()
|
||||
.and_then(|s| Platform::to_shell_path(&s)
|
||||
.map_err(|e| format!("Error getting shell path: {}", e)))
|
||||
context.invocation_directory.clone().and_then(|s| {
|
||||
Platform::to_shell_path(&s).map_err(|e| format!("Error getting shell path: {}", e))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn env_var(context: &FunctionContext, key: &str) -> Result<String, String> {
|
||||
@ -112,8 +128,10 @@ pub fn env_var(context: &FunctionContext, key: &str) -> Result<String, String> {
|
||||
|
||||
match env::var(key) {
|
||||
Err(NotPresent) => Err(format!("environment variable `{}` not present", key)),
|
||||
Err(NotUnicode(os_string)) =>
|
||||
Err(format!("environment variable `{}` not unicode: {:?}", key, os_string)),
|
||||
Err(NotUnicode(os_string)) => Err(format!(
|
||||
"environment variable `{}` not unicode: {:?}",
|
||||
key, os_string
|
||||
)),
|
||||
Ok(value) => Ok(value),
|
||||
}
|
||||
}
|
||||
@ -130,8 +148,10 @@ pub fn env_var_or_default(
|
||||
use std::env::VarError::*;
|
||||
match env::var(key) {
|
||||
Err(NotPresent) => Ok(default.to_string()),
|
||||
Err(NotUnicode(os_string)) =>
|
||||
Err(format!("environment variable `{}` not unicode: {:?}", key, os_string)),
|
||||
Err(NotUnicode(os_string)) => Err(format!(
|
||||
"environment variable `{}` not unicode: {:?}",
|
||||
key, os_string
|
||||
)),
|
||||
Ok(value) => Ok(value),
|
||||
}
|
||||
}
|
||||
|
@ -126,17 +126,15 @@ impl<'a> Justfile<'a> where {
|
||||
});
|
||||
}
|
||||
|
||||
let context = RecipeContext{invocation_directory, configuration, scope};
|
||||
let context = RecipeContext {
|
||||
invocation_directory,
|
||||
configuration,
|
||||
scope,
|
||||
};
|
||||
|
||||
let mut ran = empty();
|
||||
for (recipe, arguments) in grouped {
|
||||
self.run_recipe(
|
||||
&context,
|
||||
recipe,
|
||||
arguments,
|
||||
&dotenv,
|
||||
&mut ran,
|
||||
)?
|
||||
self.run_recipe(&context, recipe, arguments, &dotenv, &mut ran)?
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@ -152,21 +150,10 @@ impl<'a> Justfile<'a> where {
|
||||
) -> RunResult<()> {
|
||||
for dependency_name in &recipe.dependencies {
|
||||
if !ran.contains(dependency_name) {
|
||||
self.run_recipe(
|
||||
context,
|
||||
&self.recipes[dependency_name],
|
||||
&[],
|
||||
dotenv,
|
||||
ran,
|
||||
)?;
|
||||
self.run_recipe(context, &self.recipes[dependency_name], &[], dotenv, ran)?;
|
||||
}
|
||||
}
|
||||
recipe.run(
|
||||
context,
|
||||
arguments,
|
||||
dotenv,
|
||||
&self.exports,
|
||||
)?;
|
||||
recipe.run(context, arguments, dotenv, &self.exports)?;
|
||||
ran.insert(recipe.name);
|
||||
Ok(())
|
||||
}
|
||||
@ -313,10 +300,7 @@ a return code:
|
||||
min,
|
||||
max,
|
||||
} => {
|
||||
let param_names = parameters
|
||||
.iter()
|
||||
.map(|p| p.name)
|
||||
.collect::<Vec<&str>>();
|
||||
let param_names = parameters.iter().map(|p| p.name).collect::<Vec<&str>>();
|
||||
assert_eq!(recipe, "a");
|
||||
assert_eq!(param_names, ["b", "c", "d"]);
|
||||
assert_eq!(found, 2);
|
||||
@ -340,10 +324,7 @@ a return code:
|
||||
min,
|
||||
max,
|
||||
} => {
|
||||
let param_names = parameters
|
||||
.iter()
|
||||
.map(|p| p.name)
|
||||
.collect::<Vec<&str>>();
|
||||
let param_names = parameters.iter().map(|p| p.name).collect::<Vec<&str>>();
|
||||
assert_eq!(recipe, "a");
|
||||
assert_eq!(param_names, ["b", "c", "d"]);
|
||||
assert_eq!(found, 2);
|
||||
@ -367,10 +348,7 @@ a return code:
|
||||
min,
|
||||
max,
|
||||
} => {
|
||||
let param_names = parameters
|
||||
.iter()
|
||||
.map(|p| p.name)
|
||||
.collect::<Vec<&str>>();
|
||||
let param_names = parameters.iter().map(|p| p.name).collect::<Vec<&str>>();
|
||||
assert_eq!(recipe, "a");
|
||||
assert_eq!(param_names, ["b", "c", "d"]);
|
||||
assert_eq!(found, 0);
|
||||
@ -394,10 +372,7 @@ a return code:
|
||||
min,
|
||||
max,
|
||||
} => {
|
||||
let param_names = parameters
|
||||
.iter()
|
||||
.map(|p| p.name)
|
||||
.collect::<Vec<&str>>();
|
||||
let param_names = parameters.iter().map(|p| p.name).collect::<Vec<&str>>();
|
||||
assert_eq!(recipe, "a");
|
||||
assert_eq!(param_names, ["b", "c", "d"]);
|
||||
assert_eq!(found, 1);
|
||||
@ -421,10 +396,7 @@ a return code:
|
||||
min,
|
||||
max,
|
||||
} => {
|
||||
let param_names = parameters
|
||||
.iter()
|
||||
.map(|p| p.name)
|
||||
.collect::<Vec<&str>>();
|
||||
let param_names = parameters.iter().map(|p| p.name).collect::<Vec<&str>>();
|
||||
assert_eq!(recipe, "a");
|
||||
assert_eq!(param_names, ["b", "c", "d"]);
|
||||
assert_eq!(found, 0);
|
||||
|
165
src/lexer.rs
165
src/lexer.rs
@ -1,7 +1,7 @@
|
||||
use common::*;
|
||||
|
||||
use TokenKind::*;
|
||||
use CompilationErrorKind::*;
|
||||
use TokenKind::*;
|
||||
|
||||
fn re(pattern: &str) -> Regex {
|
||||
Regex::new(pattern).unwrap()
|
||||
@ -80,19 +80,21 @@ impl<'a> Lexer<'a> {
|
||||
static ref INDENT: Regex = re(r"^([ \t]*)[^ \t\n\r]");
|
||||
}
|
||||
|
||||
let indentation = INDENT.captures(self.rest).map(|captures| captures.get(1).unwrap().as_str());
|
||||
let indentation = INDENT
|
||||
.captures(self.rest)
|
||||
.map(|captures| captures.get(1).unwrap().as_str());
|
||||
|
||||
if self.column == 0 {
|
||||
if let Some(kind) = match (self.state.last().unwrap(), indentation) {
|
||||
// ignore: was no indentation and there still isn't
|
||||
// or current line is blank
|
||||
(&State::Start, Some("")) | (_, None) => {
|
||||
None
|
||||
}
|
||||
(&State::Start, Some("")) | (_, None) => None,
|
||||
// indent: was no indentation, now there is
|
||||
(&State::Start, Some(current)) => {
|
||||
if mixed_whitespace(current) {
|
||||
return Err(self.error(MixedLeadingWhitespace{whitespace: current}));
|
||||
return Err(self.error(MixedLeadingWhitespace {
|
||||
whitespace: current,
|
||||
}));
|
||||
}
|
||||
//indent = Some(current);
|
||||
self.state.push(State::Indent(current));
|
||||
@ -109,7 +111,7 @@ impl<'a> Lexer<'a> {
|
||||
if !current.starts_with(previous) {
|
||||
return Err(self.error(InconsistentLeadingWhitespace {
|
||||
expected: previous,
|
||||
found: current
|
||||
found: current,
|
||||
}));
|
||||
}
|
||||
None
|
||||
@ -117,7 +119,7 @@ impl<'a> Lexer<'a> {
|
||||
// at column 0 in some other state: this should never happen
|
||||
(&State::Text, _) | (&State::Interpolation, _) => {
|
||||
return Err(self.error(Internal {
|
||||
message: "unexpected state at column 0".to_string()
|
||||
message: "unexpected state at column 0".to_string(),
|
||||
}));
|
||||
}
|
||||
} {
|
||||
@ -163,17 +165,25 @@ impl<'a> Lexer<'a> {
|
||||
self.tokens.push(token);
|
||||
}
|
||||
|
||||
let (prefix, lexeme, kind) =
|
||||
if let (0, &State::Indent(indent), Some(captures)) =
|
||||
(self.column, self.state.last().unwrap(), LINE.captures(self.rest)) {
|
||||
let (prefix, lexeme, kind) = if let (0, &State::Indent(indent), Some(captures)) = (
|
||||
self.column,
|
||||
self.state.last().unwrap(),
|
||||
LINE.captures(self.rest),
|
||||
) {
|
||||
let line = captures.get(0).unwrap().as_str();
|
||||
if !line.starts_with(indent) {
|
||||
return Err(self.error(Internal{message: "unexpected indent".to_string()}));
|
||||
return Err(self.error(Internal {
|
||||
message: "unexpected indent".to_string(),
|
||||
}));
|
||||
}
|
||||
self.state.push(State::Text);
|
||||
(&line[0..indent.len()], "", Line)
|
||||
} else if let Some(captures) = EOF.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), Eof)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
Eof,
|
||||
)
|
||||
} else if let State::Text = *self.state.last().unwrap() {
|
||||
if let Some(captures) = INTERPOLATION_START.captures(self.rest) {
|
||||
self.state.push(State::Interpolation);
|
||||
@ -184,46 +194,106 @@ impl<'a> Lexer<'a> {
|
||||
("", captures.get(1).unwrap().as_str(), Text)
|
||||
} else if let Some(captures) = EOL.captures(self.rest) {
|
||||
self.state.pop();
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), Eol)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
Eol,
|
||||
)
|
||||
} else {
|
||||
return Err(self.error(Internal {
|
||||
message: format!("Could not match token in text state: \"{}\"", self.rest)
|
||||
message: format!("Could not match token in text state: \"{}\"", self.rest),
|
||||
}));
|
||||
}
|
||||
} else if let Some(captures) = INTERPOLATION_START_TOKEN.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), InterpolationStart)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
InterpolationStart,
|
||||
)
|
||||
} else if let Some(captures) = INTERPOLATION_END.captures(self.rest) {
|
||||
if self.state.last().unwrap() == &State::Interpolation {
|
||||
self.state.pop();
|
||||
}
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), InterpolationEnd)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
InterpolationEnd,
|
||||
)
|
||||
} else if let Some(captures) = NAME.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), Name)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
Name,
|
||||
)
|
||||
} else if let Some(captures) = EOL.captures(self.rest) {
|
||||
if self.state.last().unwrap() == &State::Interpolation {
|
||||
return Err(self.error(UnterminatedInterpolation));
|
||||
}
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), Eol)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
Eol,
|
||||
)
|
||||
} else if let Some(captures) = BACKTICK.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), Backtick)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
Backtick,
|
||||
)
|
||||
} else if let Some(captures) = COLON.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), Colon)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
Colon,
|
||||
)
|
||||
} else if let Some(captures) = AT.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), At)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
At,
|
||||
)
|
||||
} else if let Some(captures) = COMMA.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), Comma)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
Comma,
|
||||
)
|
||||
} else if let Some(captures) = PAREN_L.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), ParenL)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
ParenL,
|
||||
)
|
||||
} else if let Some(captures) = PAREN_R.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), ParenR)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
ParenR,
|
||||
)
|
||||
} else if let Some(captures) = PLUS.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), Plus)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
Plus,
|
||||
)
|
||||
} else if let Some(captures) = EQUALS.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), Equals)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
Equals,
|
||||
)
|
||||
} else if let Some(captures) = COMMENT.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), Comment)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
Comment,
|
||||
)
|
||||
} else if let Some(captures) = RAW_STRING.captures(self.rest) {
|
||||
(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str(), RawString)
|
||||
(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
RawString,
|
||||
)
|
||||
} else if UNTERMINATED_RAW_STRING.is_match(self.rest) {
|
||||
return Err(self.error(UnterminatedString));
|
||||
} else if let Some(captures) = STRING.captures(self.rest) {
|
||||
@ -266,10 +336,12 @@ impl<'a> Lexer<'a> {
|
||||
if len == 0 {
|
||||
let last = self.tokens.last().unwrap();
|
||||
match last.kind {
|
||||
Eof => {},
|
||||
_ => return Err(last.error(Internal {
|
||||
message: format!("zero length token: {:?}", last)
|
||||
})),
|
||||
Eof => {}
|
||||
_ => {
|
||||
return Err(last.error(Internal {
|
||||
message: format!("zero length token: {:?}", last),
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -314,24 +386,32 @@ mod test {
|
||||
let input = $input;
|
||||
let expected = $expected;
|
||||
let tokens = ::Lexer::lex(input).unwrap();
|
||||
let roundtrip = tokens.iter().map(|t| {
|
||||
let roundtrip = tokens
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let mut s = String::new();
|
||||
s += t.prefix;
|
||||
s += t.lexeme;
|
||||
s
|
||||
}).collect::<Vec<_>>().join("");
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("");
|
||||
let actual = token_summary(&tokens);
|
||||
if actual != expected {
|
||||
panic!("token summary mismatch:\nexpected: {}\ngot: {}\n", expected, actual);
|
||||
panic!(
|
||||
"token summary mismatch:\nexpected: {}\ngot: {}\n",
|
||||
expected, actual
|
||||
);
|
||||
}
|
||||
assert_eq!(input, roundtrip);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn token_summary(tokens: &[Token]) -> String {
|
||||
tokens.iter().map(|t| {
|
||||
match t.kind {
|
||||
tokens
|
||||
.iter()
|
||||
.map(|t| match t.kind {
|
||||
At => "@",
|
||||
Backtick => "`",
|
||||
Colon => ":",
|
||||
@ -352,8 +432,9 @@ mod test {
|
||||
RawString => "'",
|
||||
StringToken => "\"",
|
||||
Text => "_",
|
||||
}
|
||||
}).collect::<Vec<_>>().join("")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("")
|
||||
}
|
||||
|
||||
macro_rules! error_test {
|
||||
@ -390,7 +471,7 @@ mod test {
|
||||
panic!("tokenize succeeded but expected: {}\n{}", expected, input);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
summary_test! {
|
||||
|
@ -8,10 +8,12 @@ pub fn load_dotenv() -> RunResult<'static, Map<String, String>> {
|
||||
let result: dotenv::Result<Map<String, String>> = iter.collect();
|
||||
result.map_err(|dotenv_error| RuntimeError::Dotenv { dotenv_error })
|
||||
}
|
||||
Err(dotenv_error) => if dotenv_error.not_found() {
|
||||
Err(dotenv_error) => {
|
||||
if dotenv_error.not_found() {
|
||||
Ok(Map::new())
|
||||
} else {
|
||||
Err(RuntimeError::Dotenv { dotenv_error })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
53
src/misc.rs
53
src/misc.rs
@ -3,7 +3,14 @@ use common::*;
|
||||
use unicode_width::UnicodeWidthChar;
|
||||
|
||||
pub fn show_whitespace(text: &str) -> String {
|
||||
text.chars().map(|c| match c { '\t' => '␉', ' ' => '␠', _ => c }).collect()
|
||||
text
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'\t' => '␉',
|
||||
' ' => '␠',
|
||||
_ => c,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn default<T: Default>() -> T {
|
||||
@ -32,10 +39,11 @@ pub fn conjoin<T: Display>(
|
||||
conjunction: &str,
|
||||
) -> Result<(), fmt::Error> {
|
||||
match values.len() {
|
||||
0 => {},
|
||||
0 => {}
|
||||
1 => write!(f, "{}", values[0])?,
|
||||
2 => write!(f, "{} {} {}", values[0], conjunction, values[1])?,
|
||||
_ => for (i, item) in values.iter().enumerate() {
|
||||
_ => {
|
||||
for (i, item) in values.iter().enumerate() {
|
||||
write!(f, "{}", item)?;
|
||||
if i == values.len() - 1 {
|
||||
} else if i == values.len() - 2 {
|
||||
@ -43,7 +51,8 @@ pub fn conjoin<T: Display>(
|
||||
} else {
|
||||
write!(f, ", ")?
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -76,7 +85,6 @@ pub fn write_error_context(
|
||||
} else {
|
||||
if i < column {
|
||||
space_column += UnicodeWidthChar::width(c).unwrap_or(0);
|
||||
|
||||
}
|
||||
if i >= column && i < column + width.unwrap_or(1) {
|
||||
space_width += UnicodeWidthChar::width(c).unwrap_or(0);
|
||||
@ -90,15 +98,36 @@ pub fn write_error_context(
|
||||
writeln!(f, "{} | {}", line_number, space_line)?;
|
||||
write!(f, "{0:1$} |", "", line_number_width)?;
|
||||
if width == None {
|
||||
write!(f, " {0:1$}{2}^{3}", "", space_column, red.prefix(), red.suffix())?;
|
||||
write!(
|
||||
f,
|
||||
" {0:1$}{2}^{3}",
|
||||
"",
|
||||
space_column,
|
||||
red.prefix(),
|
||||
red.suffix()
|
||||
)?;
|
||||
} else {
|
||||
write!(f, " {0:1$}{2}{3:^<4$}{5}", "", space_column,
|
||||
red.prefix(), "", space_width, red.suffix())?;
|
||||
write!(
|
||||
f,
|
||||
" {0:1$}{2}{3:^<4$}{5}",
|
||||
"",
|
||||
space_column,
|
||||
red.prefix(),
|
||||
"",
|
||||
space_width,
|
||||
red.suffix()
|
||||
)?;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if index != text.len() {
|
||||
write!(
|
||||
f,
|
||||
"internal error: Error has invalid line number: {}",
|
||||
line_number
|
||||
)?
|
||||
}
|
||||
}
|
||||
},
|
||||
None => if index != text.len() {
|
||||
write!(f, "internal error: Error has invalid line number: {}", line_number)?
|
||||
},
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
@ -16,7 +16,10 @@ impl<'a> Display for Parameter<'a> {
|
||||
}
|
||||
write!(f, "{}", color.parameter().paint(self.name))?;
|
||||
if let Some(ref default) = self.default {
|
||||
let escaped = default.chars().flat_map(char::escape_default).collect::<String>();;
|
||||
let escaped = default
|
||||
.chars()
|
||||
.flat_map(char::escape_default)
|
||||
.collect::<String>();;
|
||||
write!(f, r#"='{}'"#, color.string().paint(&escaped))?;
|
||||
}
|
||||
Ok(())
|
||||
|
@ -1,8 +1,8 @@
|
||||
use common::*;
|
||||
|
||||
use itertools;
|
||||
use TokenKind::*;
|
||||
use CompilationErrorKind::*;
|
||||
use TokenKind::*;
|
||||
|
||||
pub struct Parser<'a> {
|
||||
text: &'a str,
|
||||
@ -96,7 +96,7 @@ impl<'a> Parser<'a> {
|
||||
if let Some(recipe) = self.recipes.get(name.lexeme) {
|
||||
return Err(name.error(DuplicateRecipe {
|
||||
recipe: recipe.name,
|
||||
first: recipe.line_number
|
||||
first: recipe.line_number,
|
||||
}));
|
||||
}
|
||||
|
||||
@ -108,11 +108,13 @@ impl<'a> Parser<'a> {
|
||||
|
||||
let parameter = match self.accept(Name) {
|
||||
Some(parameter) => parameter,
|
||||
None => if let Some(plus) = plus {
|
||||
None => {
|
||||
if let Some(plus) = plus {
|
||||
return Err(self.unexpected_token(&plus, &[Name]));
|
||||
} else {
|
||||
break
|
||||
},
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let variadic = plus.is_some();
|
||||
@ -125,7 +127,8 @@ impl<'a> Parser<'a> {
|
||||
|
||||
if parameters.iter().any(|p| p.name == parameter.lexeme) {
|
||||
return Err(parameter.error(DuplicateParameter {
|
||||
recipe: name.lexeme, parameter: parameter.lexeme
|
||||
recipe: name.lexeme,
|
||||
parameter: parameter.lexeme,
|
||||
}));
|
||||
}
|
||||
|
||||
@ -174,7 +177,7 @@ impl<'a> Parser<'a> {
|
||||
if dependencies.contains(&dependency.lexeme) {
|
||||
return Err(dependency.error(DuplicateDependency {
|
||||
recipe: name.lexeme,
|
||||
dependency: dependency.lexeme
|
||||
dependency: dependency.lexeme,
|
||||
}));
|
||||
}
|
||||
dependencies.push(dependency.lexeme);
|
||||
@ -196,8 +199,8 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
if let Some(token) = self.expect(Line) {
|
||||
return Err(token.error(Internal {
|
||||
message: format!("Expected a line but got {}", token.kind)
|
||||
}))
|
||||
message: format!("Expected a line but got {}", token.kind),
|
||||
}));
|
||||
}
|
||||
let mut fragments = vec![];
|
||||
|
||||
@ -209,9 +212,13 @@ impl<'a> Parser<'a> {
|
||||
shebang = true;
|
||||
}
|
||||
} else if !shebang
|
||||
&& !lines.last().and_then(|line| line.last())
|
||||
.map(Fragment::continuation).unwrap_or(false)
|
||||
&& (token.lexeme.starts_with(' ') || token.lexeme.starts_with('\t')) {
|
||||
&& !lines
|
||||
.last()
|
||||
.and_then(|line| line.last())
|
||||
.map(Fragment::continuation)
|
||||
.unwrap_or(false)
|
||||
&& (token.lexeme.starts_with(' ') || token.lexeme.starts_with('\t'))
|
||||
{
|
||||
return Err(token.error(ExtraLeadingWhitespace));
|
||||
}
|
||||
}
|
||||
@ -220,7 +227,7 @@ impl<'a> Parser<'a> {
|
||||
return Err(self.unexpected_token(&token, &[Text, InterpolationStart, Eol]));
|
||||
} else {
|
||||
fragments.push(Fragment::Expression {
|
||||
expression: self.expression()?
|
||||
expression: self.expression()?,
|
||||
});
|
||||
|
||||
if let Some(token) = self.expect(InterpolationEnd) {
|
||||
@ -233,7 +240,9 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
self.recipes.insert(name.lexeme, Recipe {
|
||||
self.recipes.insert(
|
||||
name.lexeme,
|
||||
Recipe {
|
||||
line_number: name.line,
|
||||
name: name.lexeme,
|
||||
doc: doc.map(|t| t.lexeme[1..].trim()),
|
||||
@ -244,7 +253,8 @@ impl<'a> Parser<'a> {
|
||||
parameters,
|
||||
quiet,
|
||||
shebang,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@ -261,24 +271,34 @@ impl<'a> Parser<'a> {
|
||||
if let Some(token) = self.expect(ParenR) {
|
||||
return Err(self.unexpected_token(&token, &[Name, StringToken, ParenR]));
|
||||
}
|
||||
Expression::Call {name: first.lexeme, token: first, arguments}
|
||||
Expression::Call {
|
||||
name: first.lexeme,
|
||||
token: first,
|
||||
arguments,
|
||||
}
|
||||
} else {
|
||||
Expression::Variable {name: first.lexeme, token: first}
|
||||
Expression::Variable {
|
||||
name: first.lexeme,
|
||||
token: first,
|
||||
}
|
||||
}
|
||||
}
|
||||
Backtick => Expression::Backtick {
|
||||
raw: &first.lexeme[1..first.lexeme.len() - 1],
|
||||
token: first
|
||||
token: first,
|
||||
},
|
||||
RawString | StringToken => Expression::String {
|
||||
cooked_string: CookedString::new(&first)?,
|
||||
},
|
||||
RawString | StringToken => {
|
||||
Expression::String{cooked_string: CookedString::new(&first)?}
|
||||
}
|
||||
_ => return Err(self.unexpected_token(&first, &[Name, StringToken])),
|
||||
};
|
||||
|
||||
if self.accepted(Plus) {
|
||||
let rhs = self.expression()?;
|
||||
Ok(Expression::Concatination{lhs: Box::new(lhs), rhs: Box::new(rhs)})
|
||||
Ok(Expression::Concatination {
|
||||
lhs: Box::new(lhs),
|
||||
rhs: Box::new(rhs),
|
||||
})
|
||||
} else {
|
||||
Ok(lhs)
|
||||
}
|
||||
@ -304,7 +324,9 @@ impl<'a> Parser<'a> {
|
||||
|
||||
fn assignment(&mut self, name: Token<'a>, export: bool) -> CompilationResult<'a, ()> {
|
||||
if self.assignments.contains_key(name.lexeme) {
|
||||
return Err(name.error(DuplicateVariable {variable: name.lexeme}));
|
||||
return Err(name.error(DuplicateVariable {
|
||||
variable: name.lexeme,
|
||||
}));
|
||||
}
|
||||
if export {
|
||||
self.exports.insert(name.lexeme);
|
||||
@ -338,14 +360,17 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
doc = Some(token);
|
||||
}
|
||||
At => if let Some(name) = self.accept(Name) {
|
||||
At => {
|
||||
if let Some(name) = self.accept(Name) {
|
||||
self.recipe(&name, doc, true)?;
|
||||
doc = None;
|
||||
} else {
|
||||
let unexpected = &self.tokens.next().unwrap();
|
||||
return Err(self.unexpected_token(unexpected, &[Name]));
|
||||
},
|
||||
Name => if token.lexeme == "export" {
|
||||
}
|
||||
}
|
||||
Name => {
|
||||
if token.lexeme == "export" {
|
||||
let next = self.tokens.next().unwrap();
|
||||
if next.kind == Name && self.accepted(Equals) {
|
||||
self.assignment(next, true)?;
|
||||
@ -361,26 +386,32 @@ impl<'a> Parser<'a> {
|
||||
} else {
|
||||
self.recipe(&token, doc, false)?;
|
||||
doc = None;
|
||||
},
|
||||
}
|
||||
}
|
||||
_ => return Err(self.unexpected_token(&token, &[Name, At])),
|
||||
},
|
||||
None => return Err(CompilationError {
|
||||
None => {
|
||||
return Err(CompilationError {
|
||||
text: self.text,
|
||||
index: 0,
|
||||
line: 0,
|
||||
column: 0,
|
||||
width: None,
|
||||
kind: Internal {
|
||||
message: "unexpected end of token stream".to_string()
|
||||
message: "unexpected end of token stream".to_string(),
|
||||
},
|
||||
})
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(token) = self.tokens.next() {
|
||||
return Err(token.error(Internal {
|
||||
message: format!("unexpected token remaining after parsing completed: {:?}", token.kind)
|
||||
}))
|
||||
message: format!(
|
||||
"unexpected token remaining after parsing completed: {:?}",
|
||||
token.kind
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
RecipeResolver::resolve_recipes(&self.recipes, &self.assignments, self.text)?;
|
||||
@ -389,7 +420,7 @@ impl<'a> Parser<'a> {
|
||||
for parameter in &recipe.parameters {
|
||||
if self.assignments.contains_key(parameter.token.lexeme) {
|
||||
return Err(parameter.token.error(ParameterShadowsVariable {
|
||||
parameter: parameter.token.lexeme
|
||||
parameter: parameter.token.lexeme,
|
||||
}));
|
||||
}
|
||||
}
|
||||
@ -434,7 +465,7 @@ mod test {
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
summary_test! {
|
||||
|
@ -7,8 +7,11 @@ pub struct Platform;
|
||||
pub trait PlatformInterface {
|
||||
/// Construct a command equivelant to running the script at `path` with the
|
||||
/// shebang line `shebang`
|
||||
fn make_shebang_command(path: &Path, command: &str, argument: Option<&str>)
|
||||
-> Result<Command, brev::OutputError>;
|
||||
fn make_shebang_command(
|
||||
path: &Path,
|
||||
command: &str,
|
||||
argument: Option<&str>,
|
||||
) -> Result<Command, brev::OutputError>;
|
||||
|
||||
/// Set the execute permission on the file pointed to by `path`
|
||||
fn set_execute_permission(path: &Path) -> Result<(), io::Error>;
|
||||
@ -20,12 +23,13 @@ pub trait PlatformInterface {
|
||||
fn to_shell_path(path: &Path) -> Result<String, String>;
|
||||
}
|
||||
|
||||
|
||||
#[cfg(unix)]
|
||||
impl PlatformInterface for Platform {
|
||||
fn make_shebang_command(path: &Path, _command: &str, _argument: Option<&str>)
|
||||
-> Result<Command, brev::OutputError>
|
||||
{
|
||||
fn make_shebang_command(
|
||||
path: &Path,
|
||||
_command: &str,
|
||||
_argument: Option<&str>,
|
||||
) -> Result<Command, brev::OutputError> {
|
||||
// shebang scripts can be executed directly on unix
|
||||
Ok(Command::new(path))
|
||||
}
|
||||
@ -50,17 +54,20 @@ impl PlatformInterface for Platform {
|
||||
}
|
||||
|
||||
fn to_shell_path(path: &Path) -> Result<String, String> {
|
||||
path.to_str().map(str::to_string)
|
||||
.ok_or_else(|| String::from(
|
||||
"Error getting current directory: unicode decode error"))
|
||||
path
|
||||
.to_str()
|
||||
.map(str::to_string)
|
||||
.ok_or_else(|| String::from("Error getting current directory: unicode decode error"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl PlatformInterface for Platform {
|
||||
fn make_shebang_command(path: &Path, command: &str, argument: Option<&str>)
|
||||
-> Result<Command, brev::OutputError>
|
||||
{
|
||||
fn make_shebang_command(
|
||||
path: &Path,
|
||||
command: &str,
|
||||
argument: Option<&str>,
|
||||
) -> Result<Command, brev::OutputError> {
|
||||
// Translate path to the interpreter from unix style to windows style
|
||||
let mut cygpath = Command::new("cygpath");
|
||||
cygpath.arg("--windows");
|
||||
|
@ -4,7 +4,10 @@ pub trait RangeExt<T> {
|
||||
fn range_contains(&self, i: T) -> bool;
|
||||
}
|
||||
|
||||
impl<T> RangeExt<T> for Range<T> where T: PartialOrd + Copy {
|
||||
impl<T> RangeExt<T> for Range<T>
|
||||
where
|
||||
T: PartialOrd + Copy,
|
||||
{
|
||||
fn range_contains(&self, i: T) -> bool {
|
||||
i >= self.start && i < self.end
|
||||
}
|
||||
|
123
src/recipe.rs
123
src/recipe.rs
@ -1,6 +1,6 @@
|
||||
use common::*;
|
||||
|
||||
use std::process::{ExitStatus, Command, Stdio};
|
||||
use std::process::{Command, ExitStatus, Stdio};
|
||||
|
||||
use platform::{Platform, PlatformInterface};
|
||||
|
||||
@ -9,11 +9,18 @@ use platform::{Platform, PlatformInterface};
|
||||
fn error_from_signal(
|
||||
recipe: &str,
|
||||
line_number: Option<usize>,
|
||||
exit_status: ExitStatus
|
||||
exit_status: ExitStatus,
|
||||
) -> RuntimeError {
|
||||
match Platform::signal_from_exit_status(exit_status) {
|
||||
Some(signal) => RuntimeError::Signal{recipe, line_number, signal},
|
||||
None => RuntimeError::Unknown{recipe, line_number},
|
||||
Some(signal) => RuntimeError::Signal {
|
||||
recipe,
|
||||
line_number,
|
||||
signal,
|
||||
},
|
||||
None => RuntimeError::Unknown {
|
||||
recipe,
|
||||
line_number,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -43,7 +50,11 @@ impl<'a> Recipe<'a> {
|
||||
}
|
||||
|
||||
pub fn min_arguments(&self) -> usize {
|
||||
self.parameters.iter().filter(|p| p.default.is_none()).count()
|
||||
self
|
||||
.parameters
|
||||
.iter()
|
||||
.filter(|p| p.default.is_none())
|
||||
.count()
|
||||
}
|
||||
|
||||
pub fn max_arguments(&self) -> usize {
|
||||
@ -65,7 +76,12 @@ impl<'a> Recipe<'a> {
|
||||
|
||||
if configuration.verbosity.loquacious() {
|
||||
let color = configuration.color.stderr().banner();
|
||||
eprintln!("{}===> Running recipe `{}`...{}", color.prefix(), self.name, color.suffix());
|
||||
eprintln!(
|
||||
"{}===> Running recipe `{}`...{}",
|
||||
color.prefix(),
|
||||
self.name,
|
||||
color.suffix()
|
||||
);
|
||||
}
|
||||
|
||||
let mut argument_map = Map::new();
|
||||
@ -75,9 +91,11 @@ impl<'a> Recipe<'a> {
|
||||
let value = if rest.is_empty() {
|
||||
match parameter.default {
|
||||
Some(ref default) => Cow::Borrowed(default.as_str()),
|
||||
None => return Err(RuntimeError::Internal{
|
||||
message: "missing parameter without default".to_string()
|
||||
}),
|
||||
None => {
|
||||
return Err(RuntimeError::Internal {
|
||||
message: "missing parameter without default".to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
} else if parameter.variadic {
|
||||
let value = Cow::Owned(rest.to_vec().join(" "));
|
||||
@ -120,13 +138,17 @@ impl<'a> Recipe<'a> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let tmp = TempDir::new("just")
|
||||
.map_err(|error| RuntimeError::TmpdirIoError{recipe: self.name, io_error: error})?;
|
||||
let tmp = TempDir::new("just").map_err(|error| RuntimeError::TmpdirIoError {
|
||||
recipe: self.name,
|
||||
io_error: error,
|
||||
})?;
|
||||
let mut path = tmp.path().to_path_buf();
|
||||
path.push(self.name);
|
||||
{
|
||||
let mut f = fs::File::create(&path)
|
||||
.map_err(|error| RuntimeError::TmpdirIoError{recipe: self.name, io_error: error})?;
|
||||
let mut f = fs::File::create(&path).map_err(|error| RuntimeError::TmpdirIoError {
|
||||
recipe: self.name,
|
||||
io_error: error,
|
||||
})?;
|
||||
let mut text = String::new();
|
||||
// add the shebang
|
||||
text += &evaluated_lines[0];
|
||||
@ -147,44 +169,65 @@ impl<'a> Recipe<'a> {
|
||||
}
|
||||
|
||||
f.write_all(text.as_bytes())
|
||||
.map_err(|error| RuntimeError::TmpdirIoError{recipe: self.name, io_error: error})?;
|
||||
.map_err(|error| RuntimeError::TmpdirIoError {
|
||||
recipe: self.name,
|
||||
io_error: error,
|
||||
})?;
|
||||
}
|
||||
|
||||
// make the script executable
|
||||
Platform::set_execute_permission(&path)
|
||||
.map_err(|error| RuntimeError::TmpdirIoError{recipe: self.name, io_error: error})?;
|
||||
|
||||
let shebang_line = evaluated_lines.first()
|
||||
.ok_or_else(|| RuntimeError::Internal {
|
||||
message: "evaluated_lines was empty".to_string()
|
||||
Platform::set_execute_permission(&path).map_err(|error| RuntimeError::TmpdirIoError {
|
||||
recipe: self.name,
|
||||
io_error: error,
|
||||
})?;
|
||||
|
||||
let Shebang{interpreter, argument} = Shebang::new(shebang_line)
|
||||
let shebang_line = evaluated_lines
|
||||
.first()
|
||||
.ok_or_else(|| RuntimeError::Internal {
|
||||
message: format!("bad shebang line: {}", shebang_line)
|
||||
message: "evaluated_lines was empty".to_string(),
|
||||
})?;
|
||||
|
||||
let Shebang {
|
||||
interpreter,
|
||||
argument,
|
||||
} = Shebang::new(shebang_line).ok_or_else(|| RuntimeError::Internal {
|
||||
message: format!("bad shebang line: {}", shebang_line),
|
||||
})?;
|
||||
|
||||
// create a command to run the script
|
||||
let mut command = Platform::make_shebang_command(&path, interpreter, argument)
|
||||
.map_err(|output_error| RuntimeError::Cygpath{recipe: self.name, output_error})?;
|
||||
let mut command =
|
||||
Platform::make_shebang_command(&path, interpreter, argument).map_err(|output_error| {
|
||||
RuntimeError::Cygpath {
|
||||
recipe: self.name,
|
||||
output_error,
|
||||
}
|
||||
})?;
|
||||
|
||||
command.export_environment_variables(&context.scope, dotenv, exports)?;
|
||||
|
||||
// run it!
|
||||
match InterruptHandler::guard(|| command.status()) {
|
||||
Ok(exit_status) => if let Some(code) = exit_status.code() {
|
||||
Ok(exit_status) => {
|
||||
if let Some(code) = exit_status.code() {
|
||||
if code != 0 {
|
||||
return Err(RuntimeError::Code{recipe: self.name, line_number: None, code})
|
||||
return Err(RuntimeError::Code {
|
||||
recipe: self.name,
|
||||
line_number: None,
|
||||
code,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return Err(error_from_signal(self.name, None, exit_status))
|
||||
},
|
||||
Err(io_error) => return Err(RuntimeError::Shebang {
|
||||
return Err(error_from_signal(self.name, None, exit_status));
|
||||
}
|
||||
}
|
||||
Err(io_error) => {
|
||||
return Err(RuntimeError::Shebang {
|
||||
recipe: self.name,
|
||||
command: interpreter.to_string(),
|
||||
argument: argument.map(String::from),
|
||||
io_error,
|
||||
})
|
||||
}
|
||||
};
|
||||
} else {
|
||||
let mut lines = self.lines.iter().peekable();
|
||||
@ -219,8 +262,7 @@ impl<'a> Recipe<'a> {
|
||||
|
||||
if configuration.dry_run
|
||||
|| configuration.verbosity.loquacious()
|
||||
|| !((quiet_command ^ self.quiet)
|
||||
|| configuration.quiet)
|
||||
|| !((quiet_command ^ self.quiet) || configuration.quiet)
|
||||
{
|
||||
let color = if configuration.highlight {
|
||||
configuration.color.command()
|
||||
@ -246,19 +288,25 @@ impl<'a> Recipe<'a> {
|
||||
cmd.export_environment_variables(&context.scope, dotenv, exports)?;
|
||||
|
||||
match InterruptHandler::guard(|| cmd.status()) {
|
||||
Ok(exit_status) => if let Some(code) = exit_status.code() {
|
||||
Ok(exit_status) => {
|
||||
if let Some(code) = exit_status.code() {
|
||||
if code != 0 {
|
||||
return Err(RuntimeError::Code {
|
||||
recipe: self.name, line_number: Some(line_number), code,
|
||||
recipe: self.name,
|
||||
line_number: Some(line_number),
|
||||
code,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return Err(error_from_signal(self.name, Some(line_number), exit_status));
|
||||
},
|
||||
Err(io_error) => return Err(RuntimeError::IoError{
|
||||
}
|
||||
}
|
||||
Err(io_error) => {
|
||||
return Err(RuntimeError::IoError {
|
||||
recipe: self.name,
|
||||
io_error,
|
||||
}),
|
||||
})
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -290,8 +338,7 @@ impl<'a> Display for Recipe<'a> {
|
||||
}
|
||||
match *piece {
|
||||
Fragment::Text { ref text } => write!(f, "{}", text.lexeme)?,
|
||||
Fragment::Expression{ref expression, ..} =>
|
||||
write!(f, "{{{{{}}}}}", expression)?,
|
||||
Fragment::Expression { ref expression, .. } => write!(f, "{{{{{}}}}}", expression)?,
|
||||
}
|
||||
}
|
||||
if i + 1 < self.lines.len() {
|
||||
|
@ -83,29 +83,38 @@ impl<'a, 'b> RecipeResolver<'a, 'b> {
|
||||
|
||||
fn resolve_recipe(&mut self, recipe: &Recipe<'a>) -> CompilationResult<'a, ()> {
|
||||
if self.resolved.contains(recipe.name) {
|
||||
return Ok(())
|
||||
return Ok(());
|
||||
}
|
||||
self.stack.push(recipe.name);
|
||||
self.seen.insert(recipe.name);
|
||||
for dependency_token in &recipe.dependency_tokens {
|
||||
match self.recipes.get(dependency_token.lexeme) {
|
||||
Some(dependency) => if !self.resolved.contains(dependency.name) {
|
||||
Some(dependency) => {
|
||||
if !self.resolved.contains(dependency.name) {
|
||||
if self.seen.contains(dependency.name) {
|
||||
let first = self.stack[0];
|
||||
self.stack.push(first);
|
||||
return Err(dependency_token.error(CircularRecipeDependency {
|
||||
return Err(
|
||||
dependency_token.error(CircularRecipeDependency {
|
||||
recipe: recipe.name,
|
||||
circle: self.stack.iter()
|
||||
circle: self
|
||||
.stack
|
||||
.iter()
|
||||
.skip_while(|name| **name != dependency.name)
|
||||
.cloned().collect()
|
||||
}));
|
||||
.cloned()
|
||||
.collect(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
self.resolve_recipe(dependency)?;
|
||||
},
|
||||
None => return Err(dependency_token.error(UnknownDependency {
|
||||
}
|
||||
}
|
||||
None => {
|
||||
return Err(dependency_token.error(UnknownDependency {
|
||||
recipe: recipe.name,
|
||||
unknown: dependency_token.lexeme
|
||||
})),
|
||||
unknown: dependency_token.lexeme,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
self.resolved.insert(recipe.name);
|
||||
|
207
src/run.rs
207
src/run.rs
@ -1,23 +1,21 @@
|
||||
use common::*;
|
||||
|
||||
use std::{convert, ffi};
|
||||
use clap::{App, Arg, ArgGroup, AppSettings};
|
||||
use clap::{App, AppSettings, Arg, ArgGroup};
|
||||
use configuration::DEFAULT_SHELL;
|
||||
use misc::maybe_s;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
use env_logger;
|
||||
use interrupt_handler::InterruptHandler;
|
||||
use misc::maybe_s;
|
||||
use std::{convert, ffi};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
#[cfg(windows)]
|
||||
use ansi_term::enable_ansi_support;
|
||||
|
||||
fn edit<P: convert::AsRef<ffi::OsStr>>(path: P) -> ! {
|
||||
let editor = env::var_os("EDITOR")
|
||||
.unwrap_or_else(|| die!("Error getting EDITOR environment variable"));
|
||||
let editor =
|
||||
env::var_os("EDITOR").unwrap_or_else(|| die!("Error getting EDITOR environment variable"));
|
||||
|
||||
let error = Command::new(editor)
|
||||
.arg(path)
|
||||
.status();
|
||||
let error = Command::new(editor).arg(path).status();
|
||||
|
||||
match error {
|
||||
Ok(status) => process::exit(status.code().unwrap_or(EXIT_FAILURE)),
|
||||
@ -42,102 +40,151 @@ pub fn run() {
|
||||
enable_ansi_support().ok();
|
||||
|
||||
env_logger::Builder::from_env(
|
||||
env_logger::Env::new().filter("JUST_LOG").write_style("JUST_LOG_STYLE")
|
||||
).init();
|
||||
env_logger::Env::new()
|
||||
.filter("JUST_LOG")
|
||||
.write_style("JUST_LOG_STYLE"),
|
||||
)
|
||||
.init();
|
||||
|
||||
let invocation_directory = env::current_dir()
|
||||
.map_err(|e| format!("Error getting current directory: {}", e));
|
||||
let invocation_directory =
|
||||
env::current_dir().map_err(|e| format!("Error getting current directory: {}", e));
|
||||
|
||||
let matches = App::new(env!("CARGO_PKG_NAME"))
|
||||
.version(concat!("v", env!("CARGO_PKG_VERSION")))
|
||||
.author(env!("CARGO_PKG_AUTHORS"))
|
||||
.about(concat!(env!("CARGO_PKG_DESCRIPTION"), " - ", env!("CARGO_PKG_HOMEPAGE")))
|
||||
.about(concat!(
|
||||
env!("CARGO_PKG_DESCRIPTION"),
|
||||
" - ",
|
||||
env!("CARGO_PKG_HOMEPAGE")
|
||||
))
|
||||
.help_message("Print help information")
|
||||
.version_message("Print version information")
|
||||
.setting(AppSettings::ColoredHelp)
|
||||
.setting(AppSettings::TrailingVarArg)
|
||||
.arg(Arg::with_name("ARGUMENTS")
|
||||
.arg(
|
||||
Arg::with_name("ARGUMENTS")
|
||||
.multiple(true)
|
||||
.help("The recipe(s) to run, defaults to the first recipe in the justfile"))
|
||||
.arg(Arg::with_name("COLOR")
|
||||
.help("The recipe(s) to run, defaults to the first recipe in the justfile"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("COLOR")
|
||||
.long("color")
|
||||
.takes_value(true)
|
||||
.possible_values(&["auto", "always", "never"])
|
||||
.default_value("auto")
|
||||
.help("Print colorful output"))
|
||||
.arg(Arg::with_name("DRY-RUN")
|
||||
.help("Print colorful output"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("DRY-RUN")
|
||||
.long("dry-run")
|
||||
.help("Print what just would do without doing it")
|
||||
.conflicts_with("QUIET"))
|
||||
.arg(Arg::with_name("DUMP")
|
||||
.conflicts_with("QUIET"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("DUMP")
|
||||
.long("dump")
|
||||
.help("Print entire justfile"))
|
||||
.arg(Arg::with_name("EDIT")
|
||||
.help("Print entire justfile"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("EDIT")
|
||||
.short("e")
|
||||
.long("edit")
|
||||
.help("Open justfile with $EDITOR"))
|
||||
.arg(Arg::with_name("EVALUATE")
|
||||
.help("Open justfile with $EDITOR"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("EVALUATE")
|
||||
.long("evaluate")
|
||||
.help("Print evaluated variables"))
|
||||
.arg(Arg::with_name("HIGHLIGHT")
|
||||
.help("Print evaluated variables"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("HIGHLIGHT")
|
||||
.long("highlight")
|
||||
.help("Highlight echoed recipe lines in bold"))
|
||||
.arg(Arg::with_name("JUSTFILE")
|
||||
.help("Highlight echoed recipe lines in bold"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("JUSTFILE")
|
||||
.short("f")
|
||||
.long("justfile")
|
||||
.takes_value(true)
|
||||
.help("Use <JUSTFILE> as justfile. --working-directory must also be set")
|
||||
.requires("WORKING-DIRECTORY"))
|
||||
.arg(Arg::with_name("LIST")
|
||||
.requires("WORKING-DIRECTORY"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("LIST")
|
||||
.short("l")
|
||||
.long("list")
|
||||
.help("List available recipes and their arguments"))
|
||||
.arg(Arg::with_name("QUIET")
|
||||
.help("List available recipes and their arguments"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("QUIET")
|
||||
.short("q")
|
||||
.long("quiet")
|
||||
.help("Suppress all output")
|
||||
.conflicts_with("DRY-RUN"))
|
||||
.arg(Arg::with_name("SET")
|
||||
.conflicts_with("DRY-RUN"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("SET")
|
||||
.long("set")
|
||||
.takes_value(true)
|
||||
.number_of_values(2)
|
||||
.value_names(&["VARIABLE", "VALUE"])
|
||||
.multiple(true)
|
||||
.help("Set <VARIABLE> to <VALUE>"))
|
||||
.arg(Arg::with_name("SHELL")
|
||||
.help("Set <VARIABLE> to <VALUE>"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("SHELL")
|
||||
.long("shell")
|
||||
.takes_value(true)
|
||||
.default_value(DEFAULT_SHELL)
|
||||
.help("Invoke <SHELL> to run recipes"))
|
||||
.arg(Arg::with_name("SHOW")
|
||||
.help("Invoke <SHELL> to run recipes"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("SHOW")
|
||||
.short("s")
|
||||
.long("show")
|
||||
.takes_value(true)
|
||||
.value_name("RECIPE")
|
||||
.help("Show information about <RECIPE>"))
|
||||
.arg(Arg::with_name("SUMMARY")
|
||||
.help("Show information about <RECIPE>"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("SUMMARY")
|
||||
.long("summary")
|
||||
.help("List names of available recipes"))
|
||||
.arg(Arg::with_name("VERBOSE")
|
||||
.help("List names of available recipes"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("VERBOSE")
|
||||
.short("v")
|
||||
.long("verbose")
|
||||
.multiple(true)
|
||||
.help("Use verbose output"))
|
||||
.arg(Arg::with_name("WORKING-DIRECTORY")
|
||||
.help("Use verbose output"),
|
||||
)
|
||||
.arg(
|
||||
Arg::with_name("WORKING-DIRECTORY")
|
||||
.short("d")
|
||||
.long("working-directory")
|
||||
.takes_value(true)
|
||||
.help("Use <WORKING-DIRECTORY> as working directory. --justfile must also be set")
|
||||
.requires("JUSTFILE"))
|
||||
.group(ArgGroup::with_name("EARLY-EXIT")
|
||||
.args(&["DUMP", "EDIT", "LIST", "SHOW", "SUMMARY", "ARGUMENTS", "EVALUATE"]))
|
||||
.requires("JUSTFILE"),
|
||||
)
|
||||
.group(ArgGroup::with_name("EARLY-EXIT").args(&[
|
||||
"DUMP",
|
||||
"EDIT",
|
||||
"LIST",
|
||||
"SHOW",
|
||||
"SUMMARY",
|
||||
"ARGUMENTS",
|
||||
"EVALUATE",
|
||||
]))
|
||||
.get_matches();
|
||||
|
||||
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),
|
||||
other => die!(
|
||||
"Invalid argument `{}` to --color. This is a bug in just.",
|
||||
other
|
||||
),
|
||||
};
|
||||
|
||||
let set_count = matches.occurrences_of("SET");
|
||||
@ -151,15 +198,25 @@ pub fn run() {
|
||||
|
||||
let override_re = Regex::new("^([^=]+)=(.*)$").unwrap();
|
||||
|
||||
let raw_arguments = matches.values_of("ARGUMENTS").map(|values| values.collect::<Vec<_>>())
|
||||
let raw_arguments = matches
|
||||
.values_of("ARGUMENTS")
|
||||
.map(|values| values.collect::<Vec<_>>())
|
||||
.unwrap_or_default();
|
||||
|
||||
for argument in raw_arguments.iter().take_while(|arg| override_re.is_match(arg)) {
|
||||
for argument in raw_arguments
|
||||
.iter()
|
||||
.take_while(|arg| override_re.is_match(arg))
|
||||
{
|
||||
let captures = override_re.captures(argument).unwrap();
|
||||
overrides.insert(captures.get(1).unwrap().as_str(), captures.get(2).unwrap().as_str());
|
||||
overrides.insert(
|
||||
captures.get(1).unwrap().as_str(),
|
||||
captures.get(2).unwrap().as_str(),
|
||||
);
|
||||
}
|
||||
|
||||
let rest = raw_arguments.iter().skip_while(|arg| override_re.is_match(arg))
|
||||
let rest = raw_arguments
|
||||
.iter()
|
||||
.skip_while(|arg| override_re.is_match(arg))
|
||||
.enumerate()
|
||||
.flat_map(|(i, argument)| {
|
||||
if i == 0 {
|
||||
@ -208,10 +265,12 @@ pub fn run() {
|
||||
'outer: loop {
|
||||
for candidate in &["justfile", "Justfile"] {
|
||||
match fs::metadata(candidate) {
|
||||
Ok(metadata) => if metadata.is_file() {
|
||||
Ok(metadata) => {
|
||||
if metadata.is_file() {
|
||||
name = *candidate;
|
||||
break 'outer;
|
||||
},
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
if error.kind() != io::ErrorKind::NotFound {
|
||||
die!("Error fetching justfile metadata: {}", error)
|
||||
@ -221,7 +280,11 @@ pub fn run() {
|
||||
}
|
||||
|
||||
match env::current_dir() {
|
||||
Ok(pathbuf) => if pathbuf.as_os_str() == "/" { die!("No justfile found."); },
|
||||
Ok(pathbuf) => {
|
||||
if pathbuf.as_os_str() == "/" {
|
||||
die!("No justfile found.");
|
||||
}
|
||||
}
|
||||
Err(error) => die!("Error getting current dir: {}", error),
|
||||
}
|
||||
|
||||
@ -240,19 +303,21 @@ pub fn run() {
|
||||
.unwrap_or_else(|error| die!("Error reading justfile: {}", error));
|
||||
}
|
||||
|
||||
let justfile = Parser::parse(&text).unwrap_or_else(|error|
|
||||
let justfile = Parser::parse(&text).unwrap_or_else(|error| {
|
||||
if color.stderr().active() {
|
||||
die!("{:#}", error);
|
||||
} else {
|
||||
die!("{}", error);
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
if matches.is_present("SUMMARY") {
|
||||
if justfile.count() == 0 {
|
||||
eprintln!("Justfile contains no recipes.");
|
||||
} else {
|
||||
let summary = justfile.recipes.iter()
|
||||
let summary = justfile
|
||||
.recipes
|
||||
.iter()
|
||||
.filter(|&(_, recipe)| !recipe.private)
|
||||
.map(|(name, _)| name)
|
||||
.cloned()
|
||||
@ -305,10 +370,12 @@ pub fn run() {
|
||||
}
|
||||
if let Some(doc) = recipe.doc {
|
||||
print!(
|
||||
" {:padding$}{} {}", "", doc_color.paint("#"), doc_color.paint(doc),
|
||||
padding = max_line_width.saturating_sub(
|
||||
line_widths.get(name).cloned().unwrap_or(max_line_width)
|
||||
)
|
||||
" {:padding$}{} {}",
|
||||
"",
|
||||
doc_color.paint("#"),
|
||||
doc_color.paint(doc),
|
||||
padding =
|
||||
max_line_width.saturating_sub(line_widths.get(name).cloned().unwrap_or(max_line_width))
|
||||
);
|
||||
}
|
||||
println!();
|
||||
@ -337,8 +404,12 @@ pub fn run() {
|
||||
} else if let Some(recipe) = justfile.first() {
|
||||
let min_arguments = recipe.min_arguments();
|
||||
if min_arguments > 0 {
|
||||
die!("Recipe `{}` cannot be used as default recipe since it requires at least {} argument{}.",
|
||||
recipe.name, min_arguments, maybe_s(min_arguments));
|
||||
die!(
|
||||
"Recipe `{}` cannot be used as default recipe since it requires at least {} argument{}.",
|
||||
recipe.name,
|
||||
min_arguments,
|
||||
maybe_s(min_arguments)
|
||||
);
|
||||
}
|
||||
vec![recipe.name]
|
||||
} else {
|
||||
@ -362,11 +433,7 @@ pub fn run() {
|
||||
warn!("Failed to set CTRL-C handler: {}", error)
|
||||
}
|
||||
|
||||
if let Err(run_error) = justfile.run(
|
||||
&invocation_directory,
|
||||
&arguments,
|
||||
&configuration)
|
||||
{
|
||||
if let Err(run_error) = justfile.run(&invocation_directory, &arguments, &configuration) {
|
||||
if !configuration.quiet {
|
||||
if color.stderr().active() {
|
||||
eprintln!("{:#}", run_error);
|
||||
|
@ -4,7 +4,7 @@ use dotenv;
|
||||
|
||||
use brev::OutputError;
|
||||
|
||||
use misc::{And, Or, maybe_s, Tick, ticks, write_error_context};
|
||||
use misc::{maybe_s, ticks, write_error_context, And, Or, Tick};
|
||||
|
||||
use self::RuntimeError::*;
|
||||
|
||||
@ -17,7 +17,7 @@ fn write_token_error_context(f: &mut fmt::Formatter, token: &Token) -> Result<()
|
||||
token.index,
|
||||
token.line,
|
||||
token.column + token.prefix.len(),
|
||||
Some(token.lexeme.len())
|
||||
Some(token.lexeme.len()),
|
||||
)
|
||||
}
|
||||
|
||||
@ -30,25 +30,69 @@ pub enum RuntimeError<'a> {
|
||||
min: usize,
|
||||
max: usize,
|
||||
},
|
||||
Backtick{token: Token<'a>, output_error: OutputError},
|
||||
Code{recipe: &'a str, line_number: Option<usize>, code: i32},
|
||||
Cygpath{recipe: &'a str, output_error: OutputError},
|
||||
Dotenv{dotenv_error: dotenv::Error},
|
||||
FunctionCall{token: Token<'a>, message: String},
|
||||
Internal{message: String},
|
||||
IoError{recipe: &'a str, io_error: io::Error},
|
||||
Shebang{recipe: &'a str, command: String, argument: Option<String>, io_error: io::Error},
|
||||
Signal{recipe: &'a str, line_number: Option<usize>, signal: i32},
|
||||
TmpdirIoError{recipe: &'a str, io_error: io::Error},
|
||||
UnknownOverrides{overrides: Vec<&'a str>},
|
||||
UnknownRecipes{recipes: Vec<&'a str>, suggestion: Option<&'a str>},
|
||||
Unknown{recipe: &'a str, line_number: Option<usize>},
|
||||
Backtick {
|
||||
token: Token<'a>,
|
||||
output_error: OutputError,
|
||||
},
|
||||
Code {
|
||||
recipe: &'a str,
|
||||
line_number: Option<usize>,
|
||||
code: i32,
|
||||
},
|
||||
Cygpath {
|
||||
recipe: &'a str,
|
||||
output_error: OutputError,
|
||||
},
|
||||
Dotenv {
|
||||
dotenv_error: dotenv::Error,
|
||||
},
|
||||
FunctionCall {
|
||||
token: Token<'a>,
|
||||
message: String,
|
||||
},
|
||||
Internal {
|
||||
message: String,
|
||||
},
|
||||
IoError {
|
||||
recipe: &'a str,
|
||||
io_error: io::Error,
|
||||
},
|
||||
Shebang {
|
||||
recipe: &'a str,
|
||||
command: String,
|
||||
argument: Option<String>,
|
||||
io_error: io::Error,
|
||||
},
|
||||
Signal {
|
||||
recipe: &'a str,
|
||||
line_number: Option<usize>,
|
||||
signal: i32,
|
||||
},
|
||||
TmpdirIoError {
|
||||
recipe: &'a str,
|
||||
io_error: io::Error,
|
||||
},
|
||||
UnknownOverrides {
|
||||
overrides: Vec<&'a str>,
|
||||
},
|
||||
UnknownRecipes {
|
||||
recipes: Vec<&'a str>,
|
||||
suggestion: Option<&'a str>,
|
||||
},
|
||||
Unknown {
|
||||
recipe: &'a str,
|
||||
line_number: Option<usize>,
|
||||
},
|
||||
}
|
||||
|
||||
impl<'a> RuntimeError<'a> {
|
||||
pub fn code(&self) -> Option<i32> {
|
||||
match *self {
|
||||
Code{code, ..} | Backtick{output_error: OutputError::Code(code), ..} => Some(code),
|
||||
Code { code, .. }
|
||||
| Backtick {
|
||||
output_error: OutputError::Code(code),
|
||||
..
|
||||
} => Some(code),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@ -57,7 +101,11 @@ impl<'a> RuntimeError<'a> {
|
||||
impl<'a> Display for RuntimeError<'a> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
use RuntimeError::*;
|
||||
let color = if f.alternate() { Color::always() } else { Color::never() };
|
||||
let color = if f.alternate() {
|
||||
Color::always()
|
||||
} else {
|
||||
Color::never()
|
||||
};
|
||||
let error = color.error();
|
||||
let message = color.message();
|
||||
write!(f, "{} {}", error.paint("error:"), message.prefix())?;
|
||||
@ -65,30 +113,64 @@ impl<'a> Display for RuntimeError<'a> {
|
||||
let mut error_token = None;
|
||||
|
||||
match *self {
|
||||
UnknownRecipes{ref recipes, ref suggestion} => {
|
||||
write!(f, "Justfile does not contain recipe{} {}.",
|
||||
maybe_s(recipes.len()), Or(&ticks(recipes)))?;
|
||||
UnknownRecipes {
|
||||
ref recipes,
|
||||
ref suggestion,
|
||||
} => {
|
||||
write!(
|
||||
f,
|
||||
"Justfile does not contain recipe{} {}.",
|
||||
maybe_s(recipes.len()),
|
||||
Or(&ticks(recipes))
|
||||
)?;
|
||||
if let Some(suggestion) = *suggestion {
|
||||
write!(f, "\nDid you mean `{}`?", suggestion)?;
|
||||
}
|
||||
},
|
||||
}
|
||||
UnknownOverrides { ref overrides } => {
|
||||
write!(f, "Variable{} {} overridden on the command line but not present in justfile",
|
||||
write!(
|
||||
f,
|
||||
"Variable{} {} overridden on the command line but not present in justfile",
|
||||
maybe_s(overrides.len()),
|
||||
And(&overrides.iter().map(Tick).collect::<Vec<_>>()))?;
|
||||
},
|
||||
ArgumentCountMismatch{recipe, ref parameters, found, min, max} => {
|
||||
And(&overrides.iter().map(Tick).collect::<Vec<_>>())
|
||||
)?;
|
||||
}
|
||||
ArgumentCountMismatch {
|
||||
recipe,
|
||||
ref parameters,
|
||||
found,
|
||||
min,
|
||||
max,
|
||||
} => {
|
||||
if min == max {
|
||||
let expected = min;
|
||||
write!(f, "Recipe `{}` got {} argument{} but {}takes {}",
|
||||
recipe, found, maybe_s(found),
|
||||
if expected < found { "only " } else { "" }, expected)?;
|
||||
write!(
|
||||
f,
|
||||
"Recipe `{}` got {} argument{} but {}takes {}",
|
||||
recipe,
|
||||
found,
|
||||
maybe_s(found),
|
||||
if expected < found { "only " } else { "" },
|
||||
expected
|
||||
)?;
|
||||
} else if found < min {
|
||||
write!(f, "Recipe `{}` got {} argument{} but takes at least {}",
|
||||
recipe, found, maybe_s(found), min)?;
|
||||
write!(
|
||||
f,
|
||||
"Recipe `{}` got {} argument{} but takes at least {}",
|
||||
recipe,
|
||||
found,
|
||||
maybe_s(found),
|
||||
min
|
||||
)?;
|
||||
} else if found > max {
|
||||
write!(f, "Recipe `{}` got {} argument{} but takes at most {}",
|
||||
recipe, found, maybe_s(found), max)?;
|
||||
write!(
|
||||
f,
|
||||
"Recipe `{}` got {} argument{} but takes at most {}",
|
||||
recipe,
|
||||
found,
|
||||
maybe_s(found),
|
||||
max
|
||||
)?;
|
||||
}
|
||||
write!(f, "\nusage:\n just {}", recipe)?;
|
||||
for param in parameters {
|
||||
@ -98,89 +180,170 @@ impl<'a> Display for RuntimeError<'a> {
|
||||
write!(f, " {}", param)?;
|
||||
}
|
||||
}
|
||||
},
|
||||
Code{recipe, line_number, code} => {
|
||||
}
|
||||
Code {
|
||||
recipe,
|
||||
line_number,
|
||||
code,
|
||||
} => {
|
||||
if let Some(n) = line_number {
|
||||
write!(f, "Recipe `{}` failed on line {} with exit code {}", recipe, n, code)?;
|
||||
write!(
|
||||
f,
|
||||
"Recipe `{}` failed on line {} with exit code {}",
|
||||
recipe, n, code
|
||||
)?;
|
||||
} else {
|
||||
write!(f, "Recipe `{}` failed with exit code {}", recipe, code)?;
|
||||
}
|
||||
},
|
||||
Cygpath{recipe, ref output_error} => match *output_error {
|
||||
}
|
||||
Cygpath {
|
||||
recipe,
|
||||
ref output_error,
|
||||
} => match *output_error {
|
||||
OutputError::Code(code) => {
|
||||
write!(f, "Cygpath failed with exit code {} while translating recipe `{}` \
|
||||
shebang interpreter path", code, recipe)?;
|
||||
write!(
|
||||
f,
|
||||
"Cygpath failed with exit code {} while translating recipe `{}` \
|
||||
shebang interpreter path",
|
||||
code, recipe
|
||||
)?;
|
||||
}
|
||||
OutputError::Signal(signal) => {
|
||||
write!(f, "Cygpath terminated by signal {} while translating recipe `{}` \
|
||||
shebang interpreter path", signal, recipe)?;
|
||||
write!(
|
||||
f,
|
||||
"Cygpath terminated by signal {} while translating recipe `{}` \
|
||||
shebang interpreter path",
|
||||
signal, recipe
|
||||
)?;
|
||||
}
|
||||
OutputError::Unknown => {
|
||||
write!(f, "Cygpath experienced an unknown failure while translating recipe `{}` \
|
||||
shebang interpreter path", recipe)?;
|
||||
write!(
|
||||
f,
|
||||
"Cygpath experienced an unknown failure while translating recipe `{}` \
|
||||
shebang interpreter path",
|
||||
recipe
|
||||
)?;
|
||||
}
|
||||
OutputError::Io(ref io_error) => {
|
||||
match io_error.kind() {
|
||||
io::ErrorKind::NotFound => write!(
|
||||
f, "Could not find `cygpath` executable to translate recipe `{}` \
|
||||
shebang interpreter path:\n{}", recipe, io_error),
|
||||
f,
|
||||
"Could not find `cygpath` executable to translate recipe `{}` \
|
||||
shebang interpreter path:\n{}",
|
||||
recipe, io_error
|
||||
),
|
||||
io::ErrorKind::PermissionDenied => write!(
|
||||
f, "Could not run `cygpath` executable to translate recipe `{}` \
|
||||
shebang interpreter path:\n{}", recipe, io_error),
|
||||
f,
|
||||
"Could not run `cygpath` executable to translate recipe `{}` \
|
||||
shebang interpreter path:\n{}",
|
||||
recipe, io_error
|
||||
),
|
||||
_ => write!(f, "Could not run `cygpath` executable:\n{}", io_error),
|
||||
}?;
|
||||
}
|
||||
OutputError::Utf8(ref utf8_error) => {
|
||||
write!(f, "Cygpath successfully translated recipe `{}` shebang interpreter path, \
|
||||
but output was not utf8: {}", recipe, utf8_error)?;
|
||||
write!(
|
||||
f,
|
||||
"Cygpath successfully translated recipe `{}` shebang interpreter path, \
|
||||
but output was not utf8: {}",
|
||||
recipe, utf8_error
|
||||
)?;
|
||||
}
|
||||
},
|
||||
Dotenv { ref dotenv_error } => {
|
||||
writeln!(f, "Failed to load .env: {}", dotenv_error)?;
|
||||
}
|
||||
FunctionCall{ref token, ref message} => {
|
||||
FunctionCall {
|
||||
ref token,
|
||||
ref message,
|
||||
} => {
|
||||
writeln!(f, "Call to function `{}` failed: {}", token.lexeme, message)?;
|
||||
error_token = Some(token);
|
||||
}
|
||||
Shebang{recipe, ref command, ref argument, ref io_error} => {
|
||||
Shebang {
|
||||
recipe,
|
||||
ref command,
|
||||
ref argument,
|
||||
ref io_error,
|
||||
} => {
|
||||
if let Some(ref argument) = *argument {
|
||||
write!(f, "Recipe `{}` with shebang `#!{} {}` execution error: {}",
|
||||
recipe, command, argument, io_error)?;
|
||||
write!(
|
||||
f,
|
||||
"Recipe `{}` with shebang `#!{} {}` execution error: {}",
|
||||
recipe, command, argument, io_error
|
||||
)?;
|
||||
} else {
|
||||
write!(f, "Recipe `{}` with shebang `#!{}` execution error: {}",
|
||||
recipe, command, io_error)?;
|
||||
write!(
|
||||
f,
|
||||
"Recipe `{}` with shebang `#!{}` execution error: {}",
|
||||
recipe, command, io_error
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Signal{recipe, line_number, signal} => {
|
||||
Signal {
|
||||
recipe,
|
||||
line_number,
|
||||
signal,
|
||||
} => {
|
||||
if let Some(n) = line_number {
|
||||
write!(f, "Recipe `{}` was terminated on line {} by signal {}", recipe, n, signal)?;
|
||||
write!(
|
||||
f,
|
||||
"Recipe `{}` was terminated on line {} by signal {}",
|
||||
recipe, n, signal
|
||||
)?;
|
||||
} else {
|
||||
write!(f, "Recipe `{}` was terminated by signal {}", recipe, signal)?;
|
||||
}
|
||||
}
|
||||
Unknown{recipe, line_number} => {
|
||||
Unknown {
|
||||
recipe,
|
||||
line_number,
|
||||
} => {
|
||||
if let Some(n) = line_number {
|
||||
write!(f, "Recipe `{}` failed on line {} for an unknown reason", recipe, n)?;
|
||||
write!(
|
||||
f,
|
||||
"Recipe `{}` failed on line {} for an unknown reason",
|
||||
recipe, n
|
||||
)?;
|
||||
} else {
|
||||
}
|
||||
},
|
||||
IoError{recipe, ref io_error} => {
|
||||
}
|
||||
IoError {
|
||||
recipe,
|
||||
ref io_error,
|
||||
} => {
|
||||
match io_error.kind() {
|
||||
io::ErrorKind::NotFound => writeln!(f,
|
||||
io::ErrorKind::NotFound => writeln!(
|
||||
f,
|
||||
"Recipe `{}` could not be run because just could not find `sh`:{}",
|
||||
recipe, io_error),
|
||||
recipe, io_error
|
||||
),
|
||||
io::ErrorKind::PermissionDenied => writeln!(
|
||||
f, "Recipe `{}` could not be run because just could not run `sh`:{}",
|
||||
recipe, io_error),
|
||||
_ => writeln!(f, "Recipe `{}` could not be run because of an IO error while \
|
||||
launching `sh`:{}", recipe, io_error),
|
||||
f,
|
||||
"Recipe `{}` could not be run because just could not run `sh`:{}",
|
||||
recipe, io_error
|
||||
),
|
||||
_ => writeln!(
|
||||
f,
|
||||
"Recipe `{}` could not be run because of an IO error while \
|
||||
launching `sh`:{}",
|
||||
recipe, io_error
|
||||
),
|
||||
}?;
|
||||
},
|
||||
TmpdirIoError{recipe, ref io_error} =>
|
||||
writeln!(f, "Recipe `{}` could not be run because of an IO error while trying \
|
||||
}
|
||||
TmpdirIoError {
|
||||
recipe,
|
||||
ref io_error,
|
||||
} => writeln!(
|
||||
f,
|
||||
"Recipe `{}` could not be run because of an IO error while trying \
|
||||
to create a temporary directory or write a file to that directory`:{}",
|
||||
recipe, io_error)?,
|
||||
Backtick{ref token, ref output_error} => match *output_error {
|
||||
recipe, io_error
|
||||
)?,
|
||||
Backtick {
|
||||
ref token,
|
||||
ref output_error,
|
||||
} => match *output_error {
|
||||
OutputError::Code(code) => {
|
||||
writeln!(f, "Backtick failed with exit code {}", code)?;
|
||||
error_token = Some(token);
|
||||
@ -196,24 +359,40 @@ impl<'a> Display for RuntimeError<'a> {
|
||||
OutputError::Io(ref io_error) => {
|
||||
match io_error.kind() {
|
||||
io::ErrorKind::NotFound => write!(
|
||||
f, "Backtick could not be run because just could not find `sh`:\n{}",
|
||||
io_error),
|
||||
f,
|
||||
"Backtick could not be run because just could not find `sh`:\n{}",
|
||||
io_error
|
||||
),
|
||||
io::ErrorKind::PermissionDenied => write!(
|
||||
f, "Backtick could not be run because just could not run `sh`:\n{}", io_error),
|
||||
_ => write!(f, "Backtick could not be run because of an IO \
|
||||
error while launching `sh`:\n{}", io_error),
|
||||
f,
|
||||
"Backtick could not be run because just could not run `sh`:\n{}",
|
||||
io_error
|
||||
),
|
||||
_ => write!(
|
||||
f,
|
||||
"Backtick could not be run because of an IO \
|
||||
error while launching `sh`:\n{}",
|
||||
io_error
|
||||
),
|
||||
}?;
|
||||
error_token = Some(token);
|
||||
}
|
||||
OutputError::Utf8(ref utf8_error) => {
|
||||
writeln!(f, "Backtick succeeded but stdout was not utf8: {}", utf8_error)?;
|
||||
writeln!(
|
||||
f,
|
||||
"Backtick succeeded but stdout was not utf8: {}",
|
||||
utf8_error
|
||||
)?;
|
||||
error_token = Some(token);
|
||||
}
|
||||
},
|
||||
Internal { ref message } => {
|
||||
write!(f, "Internal error, this may indicate a bug in just: {} \
|
||||
write!(
|
||||
f,
|
||||
"Internal error, this may indicate a bug in just: {} \
|
||||
consider filing an issue: https://github.com/casey/just/issues/new",
|
||||
message)?;
|
||||
message
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -23,7 +23,10 @@ impl<'a> Shebang<'a> {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Shebang{interpreter, argument})
|
||||
Some(Shebang {
|
||||
interpreter,
|
||||
argument,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@ -35,26 +38,59 @@ mod test {
|
||||
fn split_shebang() {
|
||||
fn check(text: &str, expected_split: Option<(&str, Option<&str>)>) {
|
||||
let shebang = Shebang::new(text);
|
||||
assert_eq!(shebang.map(|shebang| (shebang.interpreter, shebang.argument)), expected_split);
|
||||
assert_eq!(
|
||||
shebang.map(|shebang| (shebang.interpreter, shebang.argument)),
|
||||
expected_split
|
||||
);
|
||||
}
|
||||
|
||||
check("#! ", None);
|
||||
check("#!", None);
|
||||
check("#!/bin/bash", Some(("/bin/bash", None)));
|
||||
check("#!/bin/bash ", Some(("/bin/bash", None)));
|
||||
check("#!/usr/bin/env python", Some(("/usr/bin/env", Some("python" ))));
|
||||
check("#!/usr/bin/env python ", Some(("/usr/bin/env", Some("python" ))));
|
||||
check("#!/usr/bin/env python -x", Some(("/usr/bin/env", Some("python -x" ))));
|
||||
check("#!/usr/bin/env python -x", Some(("/usr/bin/env", Some("python -x"))));
|
||||
check("#!/usr/bin/env python \t-x\t", Some(("/usr/bin/env", Some("python \t-x"))));
|
||||
check(
|
||||
"#!/usr/bin/env python",
|
||||
Some(("/usr/bin/env", Some("python"))),
|
||||
);
|
||||
check(
|
||||
"#!/usr/bin/env python ",
|
||||
Some(("/usr/bin/env", Some("python"))),
|
||||
);
|
||||
check(
|
||||
"#!/usr/bin/env python -x",
|
||||
Some(("/usr/bin/env", Some("python -x"))),
|
||||
);
|
||||
check(
|
||||
"#!/usr/bin/env python -x",
|
||||
Some(("/usr/bin/env", Some("python -x"))),
|
||||
);
|
||||
check(
|
||||
"#!/usr/bin/env python \t-x\t",
|
||||
Some(("/usr/bin/env", Some("python \t-x"))),
|
||||
);
|
||||
check("#/usr/bin/env python \t-x\t", None);
|
||||
check("#! /bin/bash", Some(("/bin/bash", None)));
|
||||
check("#!\t\t/bin/bash ", Some(("/bin/bash", None)));
|
||||
check("#! \t\t/usr/bin/env python", Some(("/usr/bin/env", Some("python" ))));
|
||||
check("#! /usr/bin/env python ", Some(("/usr/bin/env", Some("python" ))));
|
||||
check("#! /usr/bin/env python -x", Some(("/usr/bin/env", Some("python -x" ))));
|
||||
check("#! /usr/bin/env python -x", Some(("/usr/bin/env", Some("python -x"))));
|
||||
check("#! /usr/bin/env python \t-x\t", Some(("/usr/bin/env", Some("python \t-x"))));
|
||||
check(
|
||||
"#! \t\t/usr/bin/env python",
|
||||
Some(("/usr/bin/env", Some("python"))),
|
||||
);
|
||||
check(
|
||||
"#! /usr/bin/env python ",
|
||||
Some(("/usr/bin/env", Some("python"))),
|
||||
);
|
||||
check(
|
||||
"#! /usr/bin/env python -x",
|
||||
Some(("/usr/bin/env", Some("python -x"))),
|
||||
);
|
||||
check(
|
||||
"#! /usr/bin/env python -x",
|
||||
Some(("/usr/bin/env", Some("python -x"))),
|
||||
);
|
||||
check(
|
||||
"#! /usr/bin/env python \t-x\t",
|
||||
Some(("/usr/bin/env", Some("python \t-x"))),
|
||||
);
|
||||
check("# /usr/bin/env python \t-x\t", None);
|
||||
}
|
||||
}
|
||||
|
@ -45,5 +45,5 @@ macro_rules! compilation_error_test {
|
||||
panic!("parse succeeded but expected: {}\n{}", expected, input);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
@ -51,7 +51,10 @@ pub enum TokenKind {
|
||||
impl Display for TokenKind {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||
use TokenKind::*;
|
||||
write!(f, "{}", match *self {
|
||||
write!(
|
||||
f,
|
||||
"{}",
|
||||
match *self {
|
||||
Backtick => "backtick",
|
||||
Colon => "':'",
|
||||
Comma => "','",
|
||||
@ -72,6 +75,7 @@ impl Display for TokenKind {
|
||||
StringToken => "string",
|
||||
RawString => "raw string",
|
||||
Text => "command text",
|
||||
})
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
@ -48,9 +48,12 @@ fn integration_test(
|
||||
expected_stderr: &str,
|
||||
expected_status: i32,
|
||||
) {
|
||||
let tmp = TempDir::new("just-integration")
|
||||
.unwrap_or_else(
|
||||
|err| panic!("integration test: failed to create temporary directory: {}", err));
|
||||
let tmp = TempDir::new("just-integration").unwrap_or_else(|err| {
|
||||
panic!(
|
||||
"integration test: failed to create temporary directory: {}",
|
||||
err
|
||||
)
|
||||
});
|
||||
|
||||
let mut justfile_path = tmp.path().to_path_buf();
|
||||
justfile_path.push("justfile");
|
||||
@ -77,13 +80,19 @@ fn integration_test(
|
||||
|
||||
let stdout = str::from_utf8(&output.stdout).unwrap();
|
||||
if stdout != expected_stdout {
|
||||
println!("bad stdout:\ngot:\n{}\n\nexpected:\n{}", stdout, expected_stdout);
|
||||
println!(
|
||||
"bad stdout:\ngot:\n{}\n\nexpected:\n{}",
|
||||
stdout, expected_stdout
|
||||
);
|
||||
failure = true;
|
||||
}
|
||||
|
||||
let stderr = str::from_utf8(&output.stderr).unwrap();
|
||||
if stderr != expected_stderr {
|
||||
println!("bad stderr:\ngot:\n{}\n\nexpected:\n{}", stderr, expected_stderr);
|
||||
println!(
|
||||
"bad stderr:\ngot:\n{}\n\nexpected:\n{}",
|
||||
stderr, expected_stderr
|
||||
);
|
||||
failure = true;
|
||||
}
|
||||
|
||||
@ -591,7 +600,6 @@ wut:
|
||||
status: EXIT_FAILURE,
|
||||
}
|
||||
|
||||
|
||||
integration_test! {
|
||||
name: export_shebang,
|
||||
justfile: r#"
|
||||
@ -929,7 +937,6 @@ integration_test! {
|
||||
status: EXIT_FAILURE,
|
||||
}
|
||||
|
||||
|
||||
integration_test! {
|
||||
name: required_after_default,
|
||||
justfile: "bar:\nhello baz arg='foo' bar:",
|
||||
@ -969,7 +976,6 @@ hello baz arg="XYZ\t\" ":
|
||||
status: EXIT_SUCCESS,
|
||||
}
|
||||
|
||||
|
||||
integration_test! {
|
||||
name: use_raw_string_default,
|
||||
justfile: r#"
|
||||
@ -1228,7 +1234,6 @@ foo:
|
||||
status: EXIT_SUCCESS,
|
||||
}
|
||||
|
||||
|
||||
integration_test! {
|
||||
name: env_var_failure,
|
||||
justfile: "a:\n echo {{env_var('ZADDY')}}",
|
||||
@ -1500,7 +1505,6 @@ a:"#,
|
||||
status: EXIT_FAILURE,
|
||||
}
|
||||
|
||||
|
||||
integration_test! {
|
||||
name: multiline_raw_string,
|
||||
justfile: "
|
||||
|
@ -4,8 +4,12 @@ extern crate libc;
|
||||
extern crate tempdir;
|
||||
|
||||
use executable_path::executable_path;
|
||||
use std::{
|
||||
process::Command,
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tempdir::TempDir;
|
||||
use std::{process::Command, time::{Duration, Instant}, thread};
|
||||
|
||||
#[cfg(unix)]
|
||||
fn kill(process_id: u32) {
|
||||
@ -16,9 +20,12 @@ fn kill(process_id: u32) {
|
||||
|
||||
#[cfg(unix)]
|
||||
fn interrupt_test(justfile: &str) {
|
||||
let tmp = TempDir::new("just-interrupts")
|
||||
.unwrap_or_else(
|
||||
|err| panic!("integration test: failed to create temporary directory: {}", err));
|
||||
let tmp = TempDir::new("just-interrupts").unwrap_or_else(|err| {
|
||||
panic!(
|
||||
"integration test: failed to create temporary directory: {}",
|
||||
err
|
||||
)
|
||||
});
|
||||
|
||||
let mut justfile_path = tmp.path().to_path_buf();
|
||||
justfile_path.push("justfile");
|
||||
@ -53,29 +60,35 @@ fn interrupt_test(justfile: &str) {
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn interrupt_shebang() {
|
||||
interrupt_test("
|
||||
interrupt_test(
|
||||
"
|
||||
default:
|
||||
#!/usr/bin/env sh
|
||||
sleep 2
|
||||
");
|
||||
",
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn interrupt_line() {
|
||||
interrupt_test("
|
||||
interrupt_test(
|
||||
"
|
||||
default:
|
||||
@sleep 2
|
||||
");
|
||||
",
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn interrupt_backtick() {
|
||||
interrupt_test("
|
||||
interrupt_test(
|
||||
"
|
||||
foo = `sleep 2`
|
||||
|
||||
default:
|
||||
@echo hello
|
||||
");
|
||||
",
|
||||
);
|
||||
}
|
||||
|
@ -4,16 +4,19 @@ extern crate target;
|
||||
extern crate tempdir;
|
||||
|
||||
use executable_path::executable_path;
|
||||
use std::path::Path;
|
||||
use std::process;
|
||||
use std::str;
|
||||
use std::path::Path;
|
||||
use tempdir::TempDir;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn to_shell_path(path: &Path) -> String {
|
||||
use std::fs;
|
||||
fs::canonicalize(path).expect("canonicalize failed")
|
||||
.to_str().map(str::to_string).expect("unicode decode failed")
|
||||
fs::canonicalize(path)
|
||||
.expect("canonicalize failed")
|
||||
.to_str()
|
||||
.map(str::to_string)
|
||||
.expect("unicode decode failed")
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
@ -27,13 +30,19 @@ fn to_shell_path(path: &Path) -> String {
|
||||
|
||||
#[test]
|
||||
fn test_invocation_directory() {
|
||||
let tmp = TempDir::new("just-integration")
|
||||
.unwrap_or_else(
|
||||
|err| panic!("integration test: failed to create temporary directory: {}", err));
|
||||
let tmp = TempDir::new("just-integration").unwrap_or_else(|err| {
|
||||
panic!(
|
||||
"integration test: failed to create temporary directory: {}",
|
||||
err
|
||||
)
|
||||
});
|
||||
|
||||
let mut justfile_path = tmp.path().to_path_buf();
|
||||
justfile_path.push("justfile");
|
||||
brev::dump(justfile_path, "default:\n @cd {{invocation_directory()}}\n @echo {{invocation_directory()}}");
|
||||
brev::dump(
|
||||
justfile_path,
|
||||
"default:\n @cd {{invocation_directory()}}\n @echo {{invocation_directory()}}",
|
||||
);
|
||||
|
||||
let mut subdir = tmp.path().to_path_buf();
|
||||
subdir.push("subdir");
|
||||
@ -48,8 +57,7 @@ fn test_invocation_directory() {
|
||||
let mut failure = false;
|
||||
|
||||
let expected_status = 0;
|
||||
let expected_stdout =
|
||||
to_shell_path(&subdir) + "\n";
|
||||
let expected_stdout = to_shell_path(&subdir) + "\n";
|
||||
let expected_stderr = "";
|
||||
|
||||
let status = output.status.code().unwrap();
|
||||
@ -60,13 +68,19 @@ fn test_invocation_directory() {
|
||||
|
||||
let stdout = str::from_utf8(&output.stdout).unwrap();
|
||||
if stdout != expected_stdout {
|
||||
println!("bad stdout:\ngot:\n{:?}\n\nexpected:\n{:?}", stdout, expected_stdout);
|
||||
println!(
|
||||
"bad stdout:\ngot:\n{:?}\n\nexpected:\n{:?}",
|
||||
stdout, expected_stdout
|
||||
);
|
||||
failure = true;
|
||||
}
|
||||
|
||||
let stderr = str::from_utf8(&output.stderr).unwrap();
|
||||
if stderr != expected_stderr {
|
||||
println!("bad stderr:\ngot:\n{:?}\n\nexpected:\n{:?}", stderr, expected_stderr);
|
||||
println!(
|
||||
"bad stderr:\ngot:\n{:?}\n\nexpected:\n{:?}",
|
||||
stderr, expected_stderr
|
||||
);
|
||||
failure = true;
|
||||
}
|
||||
|
||||
|
@ -2,9 +2,9 @@ extern crate brev;
|
||||
extern crate executable_path;
|
||||
extern crate tempdir;
|
||||
|
||||
use tempdir::TempDir;
|
||||
use std::{path, str, fs, process};
|
||||
use executable_path::executable_path;
|
||||
use std::{fs, path, process, str};
|
||||
use tempdir::TempDir;
|
||||
|
||||
fn search_test<P: AsRef<path::Path>>(path: P, args: &[&str]) {
|
||||
let binary = executable_path("just");
|
||||
|
Loading…
Reference in New Issue
Block a user