repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/executor.rs | src/executor.rs | use super::*;
pub(crate) enum Executor<'a> {
Command(Interpreter<String>),
Shebang(Shebang<'a>),
}
impl Executor<'_> {
pub(crate) fn command<'src>(
&self,
config: &Config,
path: &Path,
recipe: &'src str,
working_directory: Option<&Path>,
) -> RunResult<'src, Command> {
match self {
Self::Command(interpreter) => {
let mut command = Command::new(&interpreter.command);
if let Some(working_directory) = working_directory {
command.current_dir(working_directory);
}
for arg in &interpreter.arguments {
command.arg(arg);
}
command.arg(path);
Ok(command)
}
Self::Shebang(shebang) => {
// make script executable
Platform::set_execute_permission(path).map_err(|error| Error::TempdirIo {
recipe,
io_error: error,
})?;
// create command to run script
Platform::make_shebang_command(config, path, *shebang, working_directory).map_err(
|output_error| Error::Cygpath {
recipe,
output_error,
},
)
}
}
}
pub(crate) fn script_filename(&self, recipe: &str, extension: Option<&str>) -> String {
let extension = extension.unwrap_or_else(|| {
let interpreter = match self {
Self::Command(interpreter) => &interpreter.command,
Self::Shebang(shebang) => shebang.interpreter_filename(),
};
match interpreter {
"cmd" | "cmd.exe" => ".bat",
"powershell" | "powershell.exe" | "pwsh" | "pwsh.exe" => ".ps1",
_ => "",
}
});
format!("{recipe}{extension}")
}
pub(crate) fn error<'src>(&self, io_error: io::Error, recipe: &'src str) -> Error<'src> {
match self {
Self::Command(Interpreter { command, arguments }) => {
let mut command = command.clone();
for arg in arguments {
command.push(' ');
command.push_str(arg);
}
Error::Script {
command,
io_error,
recipe,
}
}
Self::Shebang(shebang) => Error::Shebang {
argument: shebang.argument.map(String::from),
command: shebang.interpreter.to_owned(),
io_error,
recipe,
},
}
}
// Script text for `recipe` given evaluated `lines` including blanks so line
// numbers in errors from generated script match justfile source lines.
pub(crate) fn script<D>(&self, recipe: &Recipe<D>, lines: &[String]) -> String {
let mut script = String::new();
let mut n = 0;
let shebangs = recipe
.body
.iter()
.take_while(|line| line.is_shebang())
.count();
if let Self::Shebang(shebang) = self {
for shebang_line in &lines[..shebangs] {
if shebang.include_shebang_line() {
script.push_str(shebang_line);
}
script.push('\n');
n += 1;
}
}
for (line, text) in recipe.body.iter().zip(lines).skip(n) {
while n < line.number {
script.push('\n');
n += 1;
}
script.push_str(text);
script.push('\n');
n += 1;
}
script
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shebang_script_filename() {
#[track_caller]
fn case(interpreter: &str, recipe: &str, extension: Option<&str>, expected: &str) {
assert_eq!(
Executor::Shebang(Shebang::new(&format!("#!{interpreter}")).unwrap())
.script_filename(recipe, extension),
expected
);
assert_eq!(
Executor::Command(Interpreter {
command: interpreter.into(),
arguments: Vec::new()
})
.script_filename(recipe, extension),
expected
);
}
case("bar", "foo", Some(".sh"), "foo.sh");
case("pwsh.exe", "foo", Some(".sh"), "foo.sh");
case("cmd.exe", "foo", Some(".sh"), "foo.sh");
case("powershell", "foo", None, "foo.ps1");
case("pwsh", "foo", None, "foo.ps1");
case("powershell.exe", "foo", None, "foo.ps1");
case("pwsh.exe", "foo", None, "foo.ps1");
case("cmd", "foo", None, "foo.bat");
case("cmd.exe", "foo", None, "foo.bat");
case("bar", "foo", None, "foo");
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/format_string_part.rs | src/format_string_part.rs | #[derive(PartialEq, Debug, Clone, Ord, Eq, PartialOrd)]
pub(crate) enum FormatStringPart {
Continue,
End,
Single,
Start,
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/testing.rs | src/testing.rs | use {super::*, pretty_assertions::assert_eq};
pub(crate) fn compile(src: &str) -> Justfile {
Compiler::test_compile(src).expect("expected successful compilation")
}
pub(crate) fn config(args: &[&str]) -> Config {
let mut args = Vec::from(args);
args.insert(0, "just");
let app = Config::app();
let matches = app.try_get_matches_from(args).unwrap();
Config::from_matches(&matches).unwrap()
}
pub(crate) fn search(config: &Config) -> Search {
let working_directory = config.invocation_directory.clone();
let justfile = working_directory.join("justfile");
Search {
justfile,
working_directory,
}
}
pub(crate) fn tempdir() -> tempfile::TempDir {
tempfile::Builder::new()
.prefix("just-test-tempdir")
.tempdir()
.expect("failed to create temporary directory")
}
macro_rules! analysis_error {
(
name: $name:ident,
input: $input:expr,
offset: $offset:expr,
line: $line:expr,
column: $column:expr,
width: $width:expr,
kind: $kind:expr,
) => {
#[test]
fn $name() {
$crate::testing::analysis_error($input, $offset, $line, $column, $width, $kind);
}
};
}
pub(crate) fn analysis_error(
src: &str,
offset: usize,
line: usize,
column: usize,
length: usize,
kind: CompileErrorKind,
) {
let tokens = Lexer::test_lex(src).expect("Lexing failed in parse test...");
let ast = Parser::parse(0, &[], None, &tokens, &PathBuf::new())
.expect("Parsing failed in analysis test...");
let root = PathBuf::from("justfile");
let mut asts: HashMap<PathBuf, Ast> = HashMap::new();
asts.insert(root.clone(), ast);
let mut paths: HashMap<PathBuf, PathBuf> = HashMap::new();
paths.insert("justfile".into(), "justfile".into());
match Analyzer::analyze(
&asts,
&Config::default(),
None,
&[],
&[],
None,
&paths,
false,
&root,
) {
Ok(_) => panic!("Analysis unexpectedly succeeded"),
Err(have) => {
let Error::Compile { compile_error } = have else {
panic!(
"unexpected non-compile analysis error: {}",
have.color_display(Color::never()),
);
};
let want = CompileError {
token: Token {
kind: compile_error.token.kind,
src,
offset,
line,
column,
length,
path: "justfile".as_ref(),
},
kind: kind.into(),
};
assert_eq!(compile_error, want);
}
}
}
macro_rules! run_error {
{
name: $name:ident,
src: $src:expr,
args: $args:expr,
error: $error:pat,
check: $check:block $(,)?
} => {
#[test]
fn $name() {
let config = $crate::testing::config(&$args);
let search = $crate::testing::search(&config);
if let Subcommand::Run{ arguments } = &config.subcommand {
match $crate::testing::compile(&$crate::unindent::unindent($src))
.run(
&config,
&search,
&arguments,
).expect_err("Expected runtime error") {
$error => $check
other => {
panic!("Unexpected run error: {other:?}");
}
}
} else {
panic!("Unexpected subcommand: {:?}", config.subcommand);
}
}
};
}
macro_rules! assert_matches {
($expression:expr, $( $pattern:pat_param )|+ $( if $guard:expr )? $(,)?) => {
match $expression {
$( $pattern )|+ $( if $guard )? => {}
left => panic!(
"assertion failed: (left ~= right)\n left: `{:?}`\n right: `{}`",
left,
stringify!($($pattern)|+ $(if $guard)?)
),
}
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/compile_error_kind.rs | src/compile_error_kind.rs | use super::*;
#[derive(Debug, PartialEq)]
pub(crate) enum CompileErrorKind<'src> {
ArgAttributeValueRequiresOption,
ArgumentPatternRegex {
source: regex::Error,
},
AttributeArgumentCountMismatch {
attribute: Name<'src>,
found: usize,
min: usize,
max: usize,
},
AttributeKeyMissingValue {
key: Name<'src>,
},
AttributePositionalFollowsKeyword,
BacktickShebang,
CircularRecipeDependency {
recipe: &'src str,
circle: Vec<&'src str>,
},
CircularVariableDependency {
variable: &'src str,
circle: Vec<&'src str>,
},
DependencyArgumentCountMismatch {
dependency: Namepath<'src>,
found: usize,
min: usize,
max: usize,
},
DuplicateArgAttribute {
arg: String,
first: usize,
},
DuplicateAttribute {
attribute: &'src str,
first: usize,
},
DuplicateDefault {
recipe: &'src str,
},
DuplicateOption {
recipe: &'src str,
option: Switch,
},
DuplicateParameter {
recipe: &'src str,
parameter: &'src str,
},
DuplicateSet {
setting: &'src str,
first: usize,
},
DuplicateUnexport {
variable: &'src str,
},
DuplicateVariable {
variable: &'src str,
},
ExitMessageAndNoExitMessageAttribute {
recipe: &'src str,
},
ExpectedKeyword {
expected: Vec<Keyword>,
found: Token<'src>,
},
ExportUnexported {
variable: &'src str,
},
ExtraLeadingWhitespace,
ExtraneousAttributes {
count: usize,
},
FunctionArgumentCountMismatch {
function: &'src str,
found: usize,
expected: RangeInclusive<usize>,
},
Include,
InconsistentLeadingWhitespace {
expected: &'src str,
found: &'src str,
},
Internal {
message: String,
},
InvalidAttribute {
item_kind: &'static str,
item_name: &'src str,
attribute: Box<Attribute<'src>>,
},
InvalidEscapeSequence {
character: char,
},
MismatchedClosingDelimiter {
close: Delimiter,
open: Delimiter,
open_line: usize,
},
MixedLeadingWhitespace {
whitespace: &'src str,
},
NoCdAndWorkingDirectoryAttribute {
recipe: &'src str,
},
OptionNameContainsEqualSign {
parameter: String,
},
OptionNameEmpty {
parameter: String,
},
ParameterFollowsVariadicParameter {
parameter: &'src str,
},
ParsingRecursionDepthExceeded,
Redefinition {
first: usize,
first_type: &'static str,
name: &'src str,
second_type: &'static str,
},
RequiredParameterFollowsDefaultParameter {
parameter: &'src str,
},
ShellExpansion {
err: shellexpand::LookupError<env::VarError>,
},
ShortOptionWithMultipleCharacters {
parameter: String,
},
UndefinedArgAttribute {
argument: String,
},
UndefinedVariable {
variable: &'src str,
},
UnexpectedCharacter {
expected: Vec<char>,
},
UnexpectedClosingDelimiter {
close: Delimiter,
},
UnexpectedEndOfToken {
expected: Vec<char>,
},
UnexpectedToken {
expected: Vec<TokenKind>,
found: TokenKind,
},
UnicodeEscapeCharacter {
character: char,
},
UnicodeEscapeDelimiter {
character: char,
},
UnicodeEscapeEmpty,
UnicodeEscapeLength {
hex: String,
},
UnicodeEscapeRange {
hex: String,
},
UnicodeEscapeUnterminated,
UnknownAliasTarget {
alias: &'src str,
target: Namepath<'src>,
},
UnknownAttribute {
attribute: &'src str,
},
UnknownAttributeKeyword {
attribute: &'src str,
keyword: &'src str,
},
UnknownDependency {
recipe: &'src str,
unknown: Namepath<'src>,
},
UnknownFunction {
function: &'src str,
},
UnknownSetting {
setting: &'src str,
},
UnknownStartOfToken {
start: char,
},
UnpairedCarriageReturn,
UnterminatedBacktick,
UnterminatedInterpolation,
UnterminatedString,
VariadicParameterWithOption,
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/compilation.rs | src/compilation.rs | use super::*;
#[derive(Debug)]
pub(crate) struct Compilation<'src> {
pub(crate) asts: HashMap<PathBuf, Ast<'src>>,
pub(crate) justfile: Justfile<'src>,
pub(crate) root: PathBuf,
pub(crate) srcs: HashMap<PathBuf, &'src str>,
}
impl<'src> Compilation<'src> {
pub(crate) fn root_ast(&self) -> &Ast<'src> {
self.asts.get(&self.root).unwrap()
}
pub(crate) fn root_src(&self) -> &'src str {
self.srcs.get(&self.root).unwrap()
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/verbosity.rs | src/verbosity.rs | #[allow(clippy::arbitrary_source_item_ordering)]
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
pub(crate) enum Verbosity {
Quiet,
Taciturn,
Loquacious,
Grandiloquent,
}
impl Verbosity {
pub(crate) fn from_flag_occurrences(flag_occurrences: u8) -> Self {
match flag_occurrences {
0 => Self::Taciturn,
1 => Self::Loquacious,
_ => Self::Grandiloquent,
}
}
pub(crate) fn quiet(self) -> bool {
self == Self::Quiet
}
pub(crate) fn loud(self) -> bool {
!self.quiet()
}
pub(crate) fn loquacious(self) -> bool {
self >= Self::Loquacious
}
pub(crate) fn grandiloquent(self) -> bool {
self >= Self::Grandiloquent
}
pub const fn default() -> Self {
Self::Taciturn
}
}
impl Default for Verbosity {
fn default() -> Self {
Self::default()
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/run.rs | src/run.rs | use super::*;
/// Main entry point into `just`. Parse arguments from `args` and run.
#[allow(clippy::missing_errors_doc)]
pub fn run(args: impl Iterator<Item = impl Into<OsString> + Clone>) -> Result<(), i32> {
#[cfg(windows)]
ansi_term::enable_ansi_support().ok();
let app = Config::app();
let matches = app.try_get_matches_from(args).map_err(|err| {
err.print().ok();
err.exit_code()
})?;
let config = Config::from_matches(&matches).map_err(Error::from);
let (color, verbosity) = config
.as_ref()
.map(|config| (config.color, config.verbosity))
.unwrap_or_default();
let loader = Loader::new();
config
.and_then(|config| {
SignalHandler::install(config.verbosity)?;
config.subcommand.execute(&config, &loader)
})
.map_err(|error| {
if !verbosity.quiet() && error.print_message() {
eprintln!("{}", error.color_display(color.stderr()));
}
error.code().unwrap_or(EXIT_FAILURE)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_can_be_called_more_than_once() {
let tmp = testing::tempdir();
fs::write(tmp.path().join("justfile"), "foo:").unwrap();
let search_directory = format!("{}/", tmp.path().to_str().unwrap());
run(["just", &search_directory].iter()).unwrap();
run(["just", &search_directory].iter()).unwrap();
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/alias.rs | src/alias.rs | use super::*;
/// An alias, e.g. `alias name := target`
#[derive(Debug, PartialEq, Clone, Serialize)]
pub(crate) struct Alias<'src, T = Arc<Recipe<'src>>> {
pub(crate) attributes: AttributeSet<'src>,
pub(crate) name: Name<'src>,
#[serde(
bound(serialize = "T: Keyed<'src>"),
serialize_with = "keyed::serialize"
)]
pub(crate) target: T,
}
impl<'src> Alias<'src, Namepath<'src>> {
pub(crate) fn resolve(self, target: Arc<Recipe<'src>>) -> Alias<'src> {
assert!(self.target.last().lexeme() == target.name());
Alias {
attributes: self.attributes,
name: self.name,
target,
}
}
}
impl Alias<'_> {
pub(crate) fn is_public(&self) -> bool {
!self.name.lexeme().starts_with('_')
&& !self.attributes.contains(AttributeDiscriminant::Private)
}
}
impl<'src, T> Keyed<'src> for Alias<'src, T> {
fn key(&self) -> &'src str {
self.name.lexeme()
}
}
impl<'src> Display for Alias<'src, Namepath<'src>> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "alias {} := {}", self.name.lexeme(), self.target)
}
}
impl Display for Alias<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
"alias {} := {}",
self.name.lexeme(),
self.target.name.lexeme()
)
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/condition.rs | src/condition.rs | use super::*;
#[derive(PartialEq, Debug, Clone)]
pub(crate) struct Condition<'src> {
pub(crate) lhs: Box<Expression<'src>>,
pub(crate) operator: ConditionalOperator,
pub(crate) rhs: Box<Expression<'src>>,
}
impl Display for Condition<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{} {} {}", self.lhs, self.operator, self.rhs)
}
}
impl Serialize for Condition<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None)?;
seq.serialize_element(&self.operator.to_string())?;
seq.serialize_element(&self.lhs)?;
seq.serialize_element(&self.rhs)?;
seq.end()
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/completions.rs | src/completions.rs | use super::*;
#[derive(ValueEnum, Debug, Clone, Copy, PartialEq)]
pub(crate) enum Shell {
Bash,
Elvish,
Fish,
#[value(alias = "nu")]
Nushell,
Powershell,
Zsh,
}
impl Shell {
pub(crate) fn script(self) -> &'static str {
match self {
Self::Bash => include_str!("../completions/just.bash"),
Self::Elvish => include_str!("../completions/just.elvish"),
Self::Fish => include_str!("../completions/just.fish"),
Self::Nushell => include_str!("../completions/just.nu"),
Self::Powershell => include_str!("../completions/just.powershell"),
Self::Zsh => include_str!("../completions/just.zsh"),
}
}
}
#[cfg(test)]
mod tests {
use {
super::*,
pretty_assertions::assert_eq,
std::io::{Read, Seek},
tempfile::tempfile,
};
#[test]
fn scripts() {
fs::create_dir_all("tmp/completions").unwrap();
let bash = clap(clap_complete::Shell::Bash);
fs::write("tmp/completions/just.bash", &bash).unwrap();
let elvish = clap(clap_complete::Shell::Elvish);
fs::write("tmp/completions/just.elvish", &elvish).unwrap();
let fish = clap(clap_complete::Shell::Fish);
fs::write("tmp/completions/just.fish", &fish).unwrap();
let powershell = clap(clap_complete::Shell::PowerShell);
fs::write("tmp/completions/just.powershell", &powershell).unwrap();
let zsh = clap(clap_complete::Shell::Zsh);
fs::write("tmp/completions/just.zsh", &zsh).unwrap();
assert_eq!(Shell::Bash.script(), bash);
assert_eq!(Shell::Elvish.script(), elvish);
assert_eq!(Shell::Fish.script(), fish);
assert_eq!(Shell::Powershell.script(), powershell);
assert_eq!(Shell::Zsh.script(), zsh);
}
fn clap(shell: clap_complete::Shell) -> String {
fn replace(haystack: &mut String, needle: &str, replacement: &str) {
if let Some(index) = haystack.find(needle) {
haystack.replace_range(index..index + needle.len(), replacement);
} else {
panic!("Failed to find text:\n{needle}\n…in completion script:\n{haystack}")
}
}
let mut script = {
let mut tempfile = tempfile().unwrap();
clap_complete::generate(
shell,
&mut crate::config::Config::app(),
env!("CARGO_PKG_NAME"),
&mut tempfile,
);
tempfile.rewind().unwrap();
let mut buffer = String::new();
tempfile.read_to_string(&mut buffer).unwrap();
buffer
};
match shell {
clap_complete::Shell::Bash => {
for (needle, replacement) in BASH_COMPLETION_REPLACEMENTS {
replace(&mut script, needle, replacement);
}
}
clap_complete::Shell::Fish => {
script.insert_str(0, FISH_RECIPE_COMPLETIONS);
}
clap_complete::Shell::PowerShell => {
for (needle, replacement) in POWERSHELL_COMPLETION_REPLACEMENTS {
replace(&mut script, needle, replacement);
}
}
clap_complete::Shell::Zsh => {
for (needle, replacement) in ZSH_COMPLETION_REPLACEMENTS {
replace(&mut script, needle, replacement);
}
}
_ => {}
}
let mut script = script.trim().to_string();
script.push('\n');
script
}
const FISH_RECIPE_COMPLETIONS: &str = r#"function __fish_just_complete_recipes
if string match -rq '(-f|--justfile)\s*=?(?<justfile>[^\s]+)' -- (string split -- ' -- ' (commandline -pc))[1]
set -fx JUST_JUSTFILE "$justfile"
end
printf "%s\n" (string split " " (just --summary))
end
# don't suggest files right off
complete -c just -n "__fish_is_first_arg" --no-files
# complete recipes
complete -c just -a '(__fish_just_complete_recipes)'
# autogenerated completions
"#;
const ZSH_COMPLETION_REPLACEMENTS: &[(&str, &str)] = &[
(
r#" _arguments "${_arguments_options[@]}" : \"#,
r" local common=(",
),
(
r"'*--set=[Override <VARIABLE> with <VALUE>]:VARIABLE:_default:VARIABLE:_default' \",
r"'*--set=[Override <VARIABLE> with <VALUE>]: :(_just_variables)' \",
),
(
r"'()-s+[Show recipe at <PATH>]:PATH:_default' \
'()--show=[Show recipe at <PATH>]:PATH:_default' \",
r"'-s+[Show recipe at <PATH>]: :(_just_commands)' \
'--show=[Show recipe at <PATH>]: :(_just_commands)' \",
),
(
"'*::ARGUMENTS -- Overrides and recipe(s) to run, defaulting to the first recipe in the \
justfile:_default' \\
&& ret=0",
r#")
_arguments "${_arguments_options[@]}" $common \
'1: :_just_commands' \
'*: :->args' \
&& ret=0
case $state in
args)
curcontext="${curcontext%:*}-${words[2]}:"
local lastarg=${words[${#words}]}
local recipe
local cmds; cmds=(
${(s: :)$(_call_program commands just --summary)}
)
# Find first recipe name
for ((i = 2; i < $#words; i++ )) do
if [[ ${cmds[(I)${words[i]}]} -gt 0 ]]; then
recipe=${words[i]}
break
fi
done
if [[ $lastarg = */* ]]; then
# Arguments contain slash would be recognised as a file
_arguments -s -S $common '*:: :_files'
elif [[ $lastarg = *=* ]]; then
# Arguments contain equal would be recognised as a variable
_message "value"
elif [[ $recipe ]]; then
# Show usage message
_message "`just --show $recipe`"
# Or complete with other commands
#_arguments -s -S $common '*:: :_just_commands'
else
_arguments -s -S $common '*:: :_just_commands'
fi
;;
esac
return ret
"#,
),
(
" local commands; commands=()",
r#" [[ $PREFIX = -* ]] && return 1
integer ret=1
local variables; variables=(
${(s: :)$(_call_program commands just --variables)}
)
local commands; commands=(
${${${(M)"${(f)$(_call_program commands just --list)}":# *}/ ##/}/ ##/:Args: }
)
"#,
),
(
r#" _describe -t commands 'just commands' commands "$@""#,
r#" if compset -P '*='; then
case "${${words[-1]%=*}#*=}" in
*) _message 'value' && ret=0 ;;
esac
else
_describe -t variables 'variables' variables -qS "=" && ret=0
_describe -t commands 'just commands' commands "$@"
fi
"#,
),
(
r#"_just "$@""#,
r#"(( $+functions[_just_variables] )) ||
_just_variables() {
[[ $PREFIX = -* ]] && return 1
integer ret=1
local variables; variables=(
${(s: :)$(_call_program commands just --variables)}
)
if compset -P '*='; then
case "${${words[-1]%=*}#*=}" in
*) _message 'value' && ret=0 ;;
esac
else
_describe -t variables 'variables' variables && ret=0
fi
return ret
}
_just "$@""#,
),
];
const POWERSHELL_COMPLETION_REPLACEMENTS: &[(&str, &str)] = &[(
r#"$completions.Where{ $_.CompletionText -like "$wordToComplete*" } |
Sort-Object -Property ListItemText"#,
r#"function Get-JustFileRecipes([string[]]$CommandElements) {
$justFileIndex = $commandElements.IndexOf("--justfile");
if ($justFileIndex -ne -1 -and $justFileIndex + 1 -le $commandElements.Length) {
$justFileLocation = $commandElements[$justFileIndex + 1]
}
$justArgs = @("--summary")
if (Test-Path $justFileLocation) {
$justArgs += @("--justfile", $justFileLocation)
}
$recipes = $(just @justArgs) -split ' '
return $recipes | ForEach-Object { [CompletionResult]::new($_) }
}
$elementValues = $commandElements | Select-Object -ExpandProperty Value
$recipes = Get-JustFileRecipes -CommandElements $elementValues
$completions += $recipes
$completions.Where{ $_.CompletionText -like "$wordToComplete*" } |
Sort-Object -Property ListItemText"#,
)];
const BASH_COMPLETION_REPLACEMENTS: &[(&str, &str)] = &[
(
r#" if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
fi"#,
r#" if [[ ${cur} == -* ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
elif [[ ${COMP_CWORD} -eq 1 ]]; then
local recipes=$(just --summary 2> /dev/null)
if echo "${cur}" | \grep -qF '/'; then
local path_prefix=$(echo "${cur}" | sed 's/[/][^/]*$/\//')
local recipes=$(just --summary 2> /dev/null -- "${path_prefix}")
local recipes=$(printf "${path_prefix}%s\t" $recipes)
fi
if [[ $? -eq 0 ]]; then
COMPREPLY=( $(compgen -W "${recipes}" -- "${cur}") )
return 0
fi
fi"#,
),
(
r"local i cur prev opts cmd",
r"local i cur prev words cword opts cmd",
),
(
r#" cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}""#,
r#"
# Modules use "::" as the separator, which is considered a wordbreak character in bash.
# The _get_comp_words_by_ref function is a hack to allow for exceptions to this rule without
# modifying the global COMP_WORDBREAKS environment variable.
if type _get_comp_words_by_ref &>/dev/null; then
_get_comp_words_by_ref -n : cur prev words cword
else
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
words=$COMP_WORDS
cword=$COMP_CWORD
fi
"#,
),
(r"for i in ${COMP_WORDS[@]}", r"for i in ${words[@]}"),
(r"elif [[ ${COMP_CWORD} -eq 1 ]]; then", r"else"),
(
r#"COMPREPLY=( $(compgen -W "${recipes}" -- "${cur}") )"#,
r#"COMPREPLY=( $(compgen -W "${recipes}" -- "${cur}") )
if type __ltrim_colon_completions &>/dev/null; then
__ltrim_colon_completions "$cur"
fi"#,
),
];
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/loader.rs | src/loader.rs | use super::*;
pub(crate) struct Loader {
paths: Arena<PathBuf>,
srcs: Arena<String>,
}
impl Loader {
pub(crate) fn new() -> Self {
Self {
srcs: Arena::new(),
paths: Arena::new(),
}
}
pub(crate) fn load<'src>(
&'src self,
root: &Path,
path: &Path,
) -> RunResult<'src, (&'src Path, &'src str)> {
let src = fs::read_to_string(path).map_err(|io_error| Error::Load {
path: path.into(),
io_error,
})?;
let relative = path.strip_prefix(root.parent().unwrap()).unwrap_or(path);
Ok((self.paths.alloc(relative.into()), self.srcs.alloc(src)))
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/enclosure.rs | src/enclosure.rs | use super::*;
pub struct Enclosure<T: Display> {
enclosure: &'static str,
value: T,
}
impl<T: Display> Enclosure<T> {
pub fn tick(value: T) -> Enclosure<T> {
Self {
enclosure: "`",
value,
}
}
}
impl<T: Display> Display for Enclosure<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}{}{}", self.enclosure, self.value, self.enclosure)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tick() {
assert_eq!(Enclosure::tick("foo").to_string(), "`foo`");
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/shebang.rs | src/shebang.rs | #[derive(Copy, Clone)]
pub(crate) struct Shebang<'line> {
pub(crate) argument: Option<&'line str>,
pub(crate) interpreter: &'line str,
}
impl<'line> Shebang<'line> {
pub(crate) fn new(line: &'line str) -> Option<Self> {
if !line.starts_with("#!") {
return None;
}
let mut pieces = line[2..]
.lines()
.next()
.unwrap_or("")
.trim()
.splitn(2, [' ', '\t']);
let interpreter = pieces.next().unwrap_or("");
let argument = pieces.next();
if interpreter.is_empty() {
return None;
}
Some(Self {
argument,
interpreter,
})
}
pub fn interpreter_filename(&self) -> &str {
self
.interpreter
.split(['/', '\\'])
.next_back()
.unwrap_or(self.interpreter)
}
pub(crate) fn include_shebang_line(&self) -> bool {
!(cfg!(windows) || matches!(self.interpreter_filename(), "cmd" | "cmd.exe"))
}
}
#[cfg(test)]
mod tests {
use super::Shebang;
#[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
);
}
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 \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("# /usr/bin/env python \t-x\t", None);
}
#[test]
fn interpreter_filename_with_forward_slash() {
assert_eq!(
Shebang::new("#!/foo/bar/baz")
.unwrap()
.interpreter_filename(),
"baz"
);
}
#[test]
fn interpreter_filename_with_backslash() {
assert_eq!(
Shebang::new("#!\\foo\\bar\\baz")
.unwrap()
.interpreter_filename(),
"baz"
);
}
#[test]
fn dont_include_shebang_line_cmd() {
assert!(!Shebang::new("#!cmd").unwrap().include_shebang_line());
}
#[test]
fn dont_include_shebang_line_cmd_exe() {
assert!(!Shebang::new("#!cmd.exe /C").unwrap().include_shebang_line());
}
#[test]
#[cfg(not(windows))]
fn include_shebang_line_other_not_windows() {
assert!(Shebang::new("#!foo -c").unwrap().include_shebang_line());
}
#[test]
#[cfg(windows)]
fn include_shebang_line_other_windows() {
assert!(!Shebang::new("#!foo -c").unwrap().include_shebang_line());
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/namepath.rs | src/namepath.rs | use super::*;
#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
pub(crate) struct Namepath<'src>(Vec<Name<'src>>);
impl<'src> Namepath<'src> {
pub(crate) fn join(&self, name: Name<'src>) -> Self {
Self(self.0.iter().copied().chain(iter::once(name)).collect())
}
pub(crate) fn push(&mut self, name: Name<'src>) {
self.0.push(name);
}
pub(crate) fn last(&self) -> &Name<'src> {
self.0.last().unwrap()
}
pub(crate) fn split_last(&self) -> (&Name<'src>, &[Name<'src>]) {
self.0.split_last().unwrap()
}
#[cfg(test)]
pub(crate) fn iter(&self) -> slice::Iter<'_, Name<'src>> {
self.0.iter()
}
pub(crate) fn components(&self) -> usize {
self.0.len()
}
}
impl Display for Namepath<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
for (i, name) in self.0.iter().enumerate() {
if i > 0 {
write!(f, "::")?;
}
write!(f, "{name}")?;
}
Ok(())
}
}
impl<'src> From<Name<'src>> for Namepath<'src> {
fn from(name: Name<'src>) -> Self {
Self(vec![name])
}
}
impl Serialize for Namepath<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{self}"))
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/range_ext.rs | src/range_ext.rs | use super::*;
pub(crate) trait RangeExt<T> {
fn display(&self) -> DisplayRange<&Self> {
DisplayRange(self)
}
}
pub(crate) struct DisplayRange<T>(T);
impl Display for DisplayRange<&RangeInclusive<usize>> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.0.start() == self.0.end() {
write!(f, "{}", self.0.start())?;
} else if *self.0.end() == usize::MAX {
write!(f, "{} or more", self.0.start())?;
} else {
write!(f, "{} to {}", self.0.start(), self.0.end())?;
}
Ok(())
}
}
impl<T> RangeExt<T> for RangeInclusive<T> where T: PartialOrd {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display() {
assert!(!(1..1).contains(&1));
assert!((1..1).is_empty());
assert!((5..5).is_empty());
assert_eq!((0..=0).display().to_string(), "0");
assert_eq!((1..=1).display().to_string(), "1");
assert_eq!((5..=5).display().to_string(), "5");
assert_eq!((5..=9).display().to_string(), "5 to 9");
assert_eq!((1..=usize::MAX).display().to_string(), "1 or more");
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/arg_attribute.rs | src/arg_attribute.rs | use super::*;
pub(crate) struct ArgAttribute<'src> {
pub(crate) help: Option<String>,
pub(crate) long: Option<String>,
pub(crate) name: Token<'src>,
pub(crate) pattern: Option<Pattern<'src>>,
pub(crate) short: Option<char>,
pub(crate) value: Option<String>,
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/name.rs | src/name.rs | use super::*;
/// A name. This is just a `Token` of kind `Identifier`, but we give it its own
/// type for clarity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
pub(crate) struct Name<'src> {
pub(crate) token: Token<'src>,
}
impl<'src> Name<'src> {
pub(crate) fn from_identifier(token: Token<'src>) -> Self {
assert_eq!(token.kind, TokenKind::Identifier);
Self { token }
}
}
impl<'src> Deref for Name<'src> {
type Target = Token<'src>;
fn deref(&self) -> &Self::Target {
&self.token
}
}
impl Display for Name<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.lexeme())
}
}
impl<'src> Keyed<'src> for Name<'src> {
fn key(&self) -> &'src str {
self.lexeme()
}
}
impl Serialize for Name<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.lexeme())
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/interpreter.rs | src/interpreter.rs | use super::*;
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub(crate) struct Interpreter<T> {
pub(crate) arguments: Vec<T>,
pub(crate) command: T,
}
impl Interpreter<String> {
pub(crate) fn default_script_interpreter() -> &'static Self {
static INSTANCE: LazyLock<Interpreter<String>> = LazyLock::new(|| Interpreter::<String> {
arguments: vec!["-eu".into()],
command: "sh".into(),
});
&INSTANCE
}
}
impl<T: Display> Display for Interpreter<T> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self.command)?;
for argument in &self.arguments {
write!(f, ", {argument}")?;
}
Ok(())
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/unresolved_recipe.rs | src/unresolved_recipe.rs | use super::*;
pub(crate) type UnresolvedRecipe<'src> = Recipe<'src, UnresolvedDependency<'src>>;
impl<'src> UnresolvedRecipe<'src> {
pub(crate) fn resolve(
self,
module_path: &str,
resolved: Vec<Arc<Recipe<'src>>>,
) -> CompileResult<'src, Recipe<'src>> {
assert_eq!(
self.dependencies.len(),
resolved.len(),
"UnresolvedRecipe::resolve: dependency count not equal to resolved count: {} != {}",
self.dependencies.len(),
resolved.len()
);
for (unresolved, resolved) in self.dependencies.iter().zip(&resolved) {
assert_eq!(unresolved.recipe.last().lexeme(), resolved.name.lexeme());
if !resolved
.argument_range()
.contains(&unresolved.arguments.len())
{
return Err(unresolved.recipe.last().error(
CompileErrorKind::DependencyArgumentCountMismatch {
dependency: unresolved.recipe.clone(),
found: unresolved.arguments.len(),
min: resolved.min_arguments(),
max: resolved.max_arguments(),
},
));
}
}
let dependencies = self
.dependencies
.into_iter()
.zip(resolved)
.map(|(unresolved, resolved)| Dependency {
arguments: resolved.group_arguments(&unresolved.arguments),
recipe: resolved,
})
.collect();
let mut namepath = String::from(module_path);
if !namepath.is_empty() {
namepath.push_str("::");
}
namepath.push_str(self.name.lexeme());
Ok(Recipe {
attributes: self.attributes,
body: self.body,
dependencies,
doc: self.doc,
file_depth: self.file_depth,
import_offsets: self.import_offsets,
name: self.name,
namepath: Some(namepath),
parameters: self.parameters,
priors: self.priors,
private: self.private,
quiet: self.quiet,
shebang: self.shebang,
})
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/main.rs | src/main.rs | fn main() {
if let Err(code) = just::run(std::env::args_os()) {
std::process::exit(code);
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/constants.rs | src/constants.rs | use super::*;
const CONSTANTS: &[(&str, &str, Option<&str>, &str)] = &[
("HEX", "0123456789abcdef", None, "1.27.0"),
("HEXLOWER", "0123456789abcdef", None, "1.27.0"),
("HEXUPPER", "0123456789ABCDEF", None, "1.27.0"),
("PATH_SEP", "/", Some("\\"), "1.41.0"),
("PATH_VAR_SEP", ":", Some(";"), "1.41.0"),
("CLEAR", "\x1bc", None, "1.37.0"),
("NORMAL", "\x1b[0m", None, "1.37.0"),
("BOLD", "\x1b[1m", None, "1.37.0"),
("ITALIC", "\x1b[3m", None, "1.37.0"),
("UNDERLINE", "\x1b[4m", None, "1.37.0"),
("INVERT", "\x1b[7m", None, "1.37.0"),
("HIDE", "\x1b[8m", None, "1.37.0"),
("STRIKETHROUGH", "\x1b[9m", None, "1.37.0"),
("BLACK", "\x1b[30m", None, "1.37.0"),
("RED", "\x1b[31m", None, "1.37.0"),
("GREEN", "\x1b[32m", None, "1.37.0"),
("YELLOW", "\x1b[33m", None, "1.37.0"),
("BLUE", "\x1b[34m", None, "1.37.0"),
("MAGENTA", "\x1b[35m", None, "1.37.0"),
("CYAN", "\x1b[36m", None, "1.37.0"),
("WHITE", "\x1b[37m", None, "1.37.0"),
("BG_BLACK", "\x1b[40m", None, "1.37.0"),
("BG_RED", "\x1b[41m", None, "1.37.0"),
("BG_GREEN", "\x1b[42m", None, "1.37.0"),
("BG_YELLOW", "\x1b[43m", None, "1.37.0"),
("BG_BLUE", "\x1b[44m", None, "1.37.0"),
("BG_MAGENTA", "\x1b[45m", None, "1.37.0"),
("BG_CYAN", "\x1b[46m", None, "1.37.0"),
("BG_WHITE", "\x1b[47m", None, "1.37.0"),
];
pub(crate) fn constants() -> &'static HashMap<&'static str, &'static str> {
static MAP: LazyLock<HashMap<&str, &str>> = LazyLock::new(|| {
CONSTANTS
.iter()
.copied()
.map(|(name, unix, windows, _version)| {
(
name,
if cfg!(windows) {
windows.unwrap_or(unix)
} else {
unix
},
)
})
.collect()
});
&MAP
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn readme_table() {
let mut table = Vec::<String>::new();
table.push("| Name | Value | Value on Windows |".into());
table.push("|---|---|---|".into());
for (name, unix, windows, version) in CONSTANTS {
table.push(format!(
"| `{name}`<sup>{version}</sup> | `\"{}\"` | {} |",
unix.replace('\x1b', "\\e"),
windows
.map(|value| format!("`\"{value}\"`"))
.unwrap_or_default(),
));
}
let table = table.join("\n");
let readme = fs::read_to_string("README.md").unwrap();
assert!(
readme.contains(&table),
"could not find table in readme:\n{table}",
);
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/ordinal.rs | src/ordinal.rs | pub(crate) trait Ordinal {
/// Convert an index starting at 0 to an ordinal starting at 1
fn ordinal(self) -> Self;
}
impl Ordinal for usize {
fn ordinal(self) -> Self {
self + 1
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/binding.rs | src/binding.rs | use super::*;
/// A binding of `name` to `value`
#[derive(Debug, Clone, PartialEq, Serialize)]
pub(crate) struct Binding<'src, V = String> {
pub(crate) export: bool,
#[serde(skip)]
pub(crate) file_depth: u32,
pub(crate) name: Name<'src>,
#[serde(skip)]
pub(crate) prelude: bool,
pub(crate) private: bool,
pub(crate) value: V,
}
impl<'src, V> Keyed<'src> for Binding<'src, V> {
fn key(&self) -> &'src str {
self.name.lexeme()
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/request.rs | src/request.rs | use super::*;
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(rename_all = "kebab-case")]
pub enum Request {
EnvironmentVariable(String),
#[cfg(not(windows))]
Signal,
}
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Response {
EnvironmentVariable(Option<OsString>),
#[cfg(not(windows))]
Signal(String),
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/line.rs | src/line.rs | use super::*;
/// A single line in a recipe body, consisting of any number of `Fragment`s.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(transparent)]
pub(crate) struct Line<'src> {
pub(crate) fragments: Vec<Fragment<'src>>,
#[serde(skip)]
pub(crate) number: usize,
}
impl Line<'_> {
fn first(&self) -> Option<&str> {
if let Fragment::Text { token } = self.fragments.first()? {
Some(token.lexeme())
} else {
None
}
}
pub(crate) fn is_comment(&self) -> bool {
self.first().is_some_and(|text| text.starts_with('#'))
}
pub(crate) fn is_continuation(&self) -> bool {
matches!(
self.fragments.last(),
Some(Fragment::Text { token }) if token.lexeme().ends_with('\\'),
)
}
pub(crate) fn is_empty(&self) -> bool {
self.fragments.is_empty()
}
pub(crate) fn is_infallible(&self) -> bool {
self
.first()
.is_some_and(|text| text.starts_with('-') || text.starts_with("@-"))
}
pub(crate) fn is_quiet(&self) -> bool {
self
.first()
.is_some_and(|text| text.starts_with('@') || text.starts_with("-@"))
}
pub(crate) fn is_shebang(&self) -> bool {
self.first().is_some_and(|text| text.starts_with("#!"))
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/item.rs | src/item.rs | use super::*;
/// A single top-level item
#[derive(Debug, Clone)]
pub(crate) enum Item<'src> {
Alias(Alias<'src, Namepath<'src>>),
Assignment(Assignment<'src>),
Comment(&'src str),
Import {
absolute: Option<PathBuf>,
optional: bool,
relative: StringLiteral<'src>,
},
Module {
absolute: Option<PathBuf>,
doc: Option<String>,
groups: Vec<StringLiteral<'src>>,
name: Name<'src>,
optional: bool,
private: bool,
relative: Option<StringLiteral<'src>>,
},
Recipe(UnresolvedRecipe<'src>),
Set(Set<'src>),
Unexport {
name: Name<'src>,
},
}
impl Display for Item<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Alias(alias) => write!(f, "{alias}"),
Self::Assignment(assignment) => write!(f, "{assignment}"),
Self::Comment(comment) => write!(f, "{comment}"),
Self::Import {
relative, optional, ..
} => {
write!(f, "import")?;
if *optional {
write!(f, "?")?;
}
write!(f, " {relative}")
}
Self::Module {
doc,
groups,
name,
optional,
relative,
..
} => {
if let Some(doc) = doc {
writeln!(f, "# {doc}")?;
}
for group in groups {
writeln!(f, "[group: {group}]")?;
}
write!(f, "mod")?;
if *optional {
write!(f, "?")?;
}
write!(f, " {name}")?;
if let Some(path) = relative {
write!(f, " {path}")?;
}
Ok(())
}
Self::Recipe(recipe) => write!(f, "{}", recipe.color_display(Color::never())),
Self::Set(set) => write!(f, "{set}"),
Self::Unexport { name } => write!(f, "unexport {name}"),
}
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/position.rs | src/position.rs | /// Source position
#[derive(Copy, Clone, PartialEq, Debug)]
pub(crate) struct Position {
pub(crate) column: usize,
pub(crate) line: usize,
pub(crate) offset: usize,
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/setting.rs | src/setting.rs | use super::*;
#[derive(Debug, Clone)]
pub(crate) enum Setting<'src> {
AllowDuplicateRecipes(bool),
AllowDuplicateVariables(bool),
DotenvFilename(Expression<'src>),
DotenvLoad(bool),
DotenvOverride(bool),
DotenvPath(Expression<'src>),
DotenvRequired(bool),
Export(bool),
Fallback(bool),
IgnoreComments(bool),
NoExitMessage(bool),
PositionalArguments(bool),
Quiet(bool),
ScriptInterpreter(Interpreter<Expression<'src>>),
Shell(Interpreter<Expression<'src>>),
Tempdir(Expression<'src>),
Unstable(bool),
WindowsPowerShell(bool),
WindowsShell(Interpreter<Expression<'src>>),
WorkingDirectory(Expression<'src>),
}
impl<'src> Setting<'src> {
pub(crate) fn expressions(&self) -> impl Iterator<Item = &Expression<'src>> {
let first = match self {
Self::DotenvFilename(value)
| Self::DotenvPath(value)
| Self::Tempdir(value)
| Self::WorkingDirectory(value) => Some(value),
Self::ScriptInterpreter(value) | Self::Shell(value) | Self::WindowsShell(value) => {
Some(&value.command)
}
_ => None,
};
let rest = match self {
Self::ScriptInterpreter(value) | Self::Shell(value) | Self::WindowsShell(value) => {
value.arguments.as_slice()
}
_ => &[],
};
first.into_iter().chain(rest)
}
}
impl Display for Setting<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::AllowDuplicateRecipes(value)
| Self::AllowDuplicateVariables(value)
| Self::DotenvLoad(value)
| Self::DotenvOverride(value)
| Self::DotenvRequired(value)
| Self::Export(value)
| Self::Fallback(value)
| Self::IgnoreComments(value)
| Self::NoExitMessage(value)
| Self::PositionalArguments(value)
| Self::Quiet(value)
| Self::Unstable(value)
| Self::WindowsPowerShell(value) => write!(f, "{value}"),
Self::DotenvFilename(value)
| Self::DotenvPath(value)
| Self::Tempdir(value)
| Self::WorkingDirectory(value) => {
write!(f, "{value}")
}
Self::ScriptInterpreter(value) | Self::Shell(value) | Self::WindowsShell(value) => {
write!(f, "[{value}]")
}
}
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/thunk.rs | src/thunk.rs | use super::*;
#[allow(clippy::arbitrary_source_item_ordering)]
#[derive_where(Debug, PartialEq)]
#[derive(Clone)]
pub(crate) enum Thunk<'src> {
Nullary {
name: Name<'src>,
#[derive_where(skip(Debug, EqHashOrd))]
function: fn(function::Context) -> FunctionResult,
},
Unary {
name: Name<'src>,
#[derive_where(skip(Debug, EqHashOrd))]
function: fn(function::Context, &str) -> FunctionResult,
arg: Box<Expression<'src>>,
},
UnaryOpt {
name: Name<'src>,
#[derive_where(skip(Debug, EqHashOrd))]
function: fn(function::Context, &str, Option<&str>) -> FunctionResult,
args: (Box<Expression<'src>>, Box<Option<Expression<'src>>>),
},
UnaryPlus {
name: Name<'src>,
#[derive_where(skip(Debug, EqHashOrd))]
function: fn(function::Context, &str, &[String]) -> FunctionResult,
args: (Box<Expression<'src>>, Vec<Expression<'src>>),
},
Binary {
name: Name<'src>,
#[derive_where(skip(Debug, EqHashOrd))]
function: fn(function::Context, &str, &str) -> FunctionResult,
args: [Box<Expression<'src>>; 2],
},
BinaryPlus {
name: Name<'src>,
#[derive_where(skip(Debug, EqHashOrd))]
function: fn(function::Context, &str, &str, &[String]) -> FunctionResult,
args: ([Box<Expression<'src>>; 2], Vec<Expression<'src>>),
},
Ternary {
name: Name<'src>,
#[derive_where(skip(Debug, EqHashOrd))]
function: fn(function::Context, &str, &str, &str) -> FunctionResult,
args: [Box<Expression<'src>>; 3],
},
}
impl<'src> Thunk<'src> {
pub(crate) fn name(&self) -> Name<'src> {
match self {
Self::Nullary { name, .. }
| Self::Unary { name, .. }
| Self::UnaryOpt { name, .. }
| Self::UnaryPlus { name, .. }
| Self::Binary { name, .. }
| Self::BinaryPlus { name, .. }
| Self::Ternary { name, .. } => *name,
}
}
pub(crate) fn resolve(
name: Name<'src>,
mut arguments: Vec<Expression<'src>>,
) -> CompileResult<'src, Thunk<'src>> {
function::get(name.lexeme()).map_or(
Err(name.error(CompileErrorKind::UnknownFunction {
function: name.lexeme(),
})),
|function| match (function, arguments.len()) {
(Function::Nullary(function), 0) => Ok(Thunk::Nullary { function, name }),
(Function::Unary(function), 1) => Ok(Thunk::Unary {
function,
arg: arguments.pop().unwrap().into(),
name,
}),
(Function::UnaryOpt(function), 1..=2) => {
let a = arguments.remove(0).into();
let b = match arguments.pop() {
Some(value) => Some(value).into(),
None => None.into(),
};
Ok(Thunk::UnaryOpt {
function,
args: (a, b),
name,
})
}
(Function::UnaryPlus(function), 1..=usize::MAX) => {
let rest = arguments.drain(1..).collect();
let a = Box::new(arguments.pop().unwrap());
Ok(Thunk::UnaryPlus {
function,
args: (a, rest),
name,
})
}
(Function::Binary(function), 2) => {
let b = arguments.pop().unwrap().into();
let a = arguments.pop().unwrap().into();
Ok(Thunk::Binary {
function,
args: [a, b],
name,
})
}
(Function::BinaryPlus(function), 2..=usize::MAX) => {
let rest = arguments.drain(2..).collect();
let b = arguments.pop().unwrap().into();
let a = arguments.pop().unwrap().into();
Ok(Thunk::BinaryPlus {
function,
args: ([a, b], rest),
name,
})
}
(Function::Ternary(function), 3) => {
let c = arguments.pop().unwrap().into();
let b = arguments.pop().unwrap().into();
let a = arguments.pop().unwrap().into();
Ok(Thunk::Ternary {
function,
args: [a, b, c],
name,
})
}
(function, _) => Err(name.error(CompileErrorKind::FunctionArgumentCountMismatch {
function: name.lexeme(),
found: arguments.len(),
expected: function.argc(),
})),
},
)
}
}
impl Display for Thunk<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
use Thunk::*;
match self {
Nullary { name, .. } => write!(f, "{}()", name.lexeme()),
Unary { name, arg, .. } => write!(f, "{}({arg})", name.lexeme()),
UnaryOpt {
name, args: (a, b), ..
} => {
if let Some(b) = b.as_ref() {
write!(f, "{}({a}, {b})", name.lexeme())
} else {
write!(f, "{}({a})", name.lexeme())
}
}
UnaryPlus {
name,
args: (a, rest),
..
} => {
write!(f, "{}({a}", name.lexeme())?;
for arg in rest {
write!(f, ", {arg}")?;
}
write!(f, ")")
}
Binary {
name, args: [a, b], ..
} => write!(f, "{}({a}, {b})", name.lexeme()),
BinaryPlus {
name,
args: ([a, b], rest),
..
} => {
write!(f, "{}({a}, {b}", name.lexeme())?;
for arg in rest {
write!(f, ", {arg}")?;
}
write!(f, ")")
}
Ternary {
name,
args: [a, b, c],
..
} => write!(f, "{}({a}, {b}, {c})", name.lexeme()),
}
}
}
impl Serialize for Thunk<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None)?;
seq.serialize_element("call")?;
seq.serialize_element(&self.name())?;
match self {
Self::Nullary { .. } => {}
Self::Unary { arg, .. } => seq.serialize_element(&arg)?,
Self::UnaryOpt {
args: (a, opt_b), ..
} => {
seq.serialize_element(a)?;
if let Some(b) = opt_b.as_ref() {
seq.serialize_element(b)?;
}
}
Self::UnaryPlus {
args: (a, rest), ..
} => {
seq.serialize_element(a)?;
for arg in rest {
seq.serialize_element(arg)?;
}
}
Self::Binary { args, .. } => {
for arg in args {
seq.serialize_element(arg)?;
}
}
Self::BinaryPlus { args, .. } => {
for arg in args.0.iter().map(Box::as_ref).chain(&args.1) {
seq.serialize_element(arg)?;
}
}
Self::Ternary { args, .. } => {
for arg in args {
seq.serialize_element(arg)?;
}
}
}
seq.end()
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/evaluator.rs | src/evaluator.rs | use super::*;
pub(crate) struct Evaluator<'src: 'run, 'run> {
assignments: Option<&'run Table<'src, Assignment<'src>>>,
context: Option<ExecutionContext<'src, 'run>>,
is_dependency: bool,
non_const_assignments: Table<'src, Name<'src>>,
scope: Scope<'src, 'run>,
}
impl<'src, 'run> Evaluator<'src, 'run> {
fn context(
&self,
const_error: ConstError<'src>,
) -> Result<&ExecutionContext<'src, 'run>, ConstError<'src>> {
self.context.as_ref().ok_or(const_error)
}
pub(crate) fn evaluate_settings(
assignments: &'run Table<'src, Assignment<'src>>,
config: &Config,
name: Option<Name>,
sets: Table<'src, Set<'src>>,
scope: &'run Scope<'src, 'run>,
) -> RunResult<'src, Settings> {
let mut scope = scope.child();
if name.is_none() {
let mut unknown_overrides = Vec::new();
for (name, value) in &config.overrides {
if let Some(assignment) = assignments.get(name) {
scope.bind(Binding {
export: assignment.export,
file_depth: 0,
name: assignment.name,
prelude: false,
private: assignment.private,
value: value.clone(),
});
} else {
unknown_overrides.push(name.clone());
}
}
if !unknown_overrides.is_empty() {
return Err(Error::UnknownOverrides {
overrides: unknown_overrides,
});
}
}
let mut evaluator = Self {
assignments: Some(assignments),
context: None,
is_dependency: false,
non_const_assignments: Table::new(),
scope,
};
for assignment in assignments.values() {
match evaluator.evaluate_assignment(assignment) {
Err(Error::Const { .. }) => evaluator.non_const_assignments.insert(assignment.name),
Err(err) => return Err(err),
Ok(_) => {}
}
}
evaluator.evaluate_sets(sets)
}
fn evaluate_sets(&mut self, sets: Table<'src, Set<'src>>) -> RunResult<'src, Settings> {
let mut settings = Settings::default();
for (_name, set) in sets {
match set.value {
Setting::AllowDuplicateRecipes(value) => {
settings.allow_duplicate_recipes = value;
}
Setting::AllowDuplicateVariables(value) => {
settings.allow_duplicate_variables = value;
}
Setting::DotenvFilename(value) => {
settings.dotenv_filename = Some(self.evaluate_expression(&value)?);
}
Setting::DotenvLoad(value) => {
settings.dotenv_load = value;
}
Setting::DotenvPath(value) => {
settings.dotenv_path = Some(self.evaluate_expression(&value)?.into());
}
Setting::DotenvOverride(value) => {
settings.dotenv_override = value;
}
Setting::DotenvRequired(value) => {
settings.dotenv_required = value;
}
Setting::Export(value) => {
settings.export = value;
}
Setting::Fallback(value) => {
settings.fallback = value;
}
Setting::IgnoreComments(value) => {
settings.ignore_comments = value;
}
Setting::NoExitMessage(value) => {
settings.no_exit_message = value;
}
Setting::PositionalArguments(value) => {
settings.positional_arguments = value;
}
Setting::Quiet(value) => {
settings.quiet = value;
}
Setting::ScriptInterpreter(value) => {
settings.script_interpreter = Some(self.evaluate_intepreter(&value)?);
}
Setting::Shell(value) => {
settings.shell = Some(self.evaluate_intepreter(&value)?);
}
Setting::Unstable(value) => {
settings.unstable = value;
}
Setting::WindowsPowerShell(value) => {
settings.windows_powershell = value;
}
Setting::WindowsShell(value) => {
settings.windows_shell = Some(self.evaluate_intepreter(&value)?);
}
Setting::Tempdir(value) => {
settings.tempdir = Some(self.evaluate_expression(&value)?);
}
Setting::WorkingDirectory(value) => {
settings.working_directory = Some(self.evaluate_expression(&value)?.into());
}
}
}
Ok(settings)
}
pub(crate) fn evaluate_intepreter(
&mut self,
interpreter: &Interpreter<Expression<'src>>,
) -> RunResult<'src, Interpreter<String>> {
Ok(Interpreter {
command: self.evaluate_expression(&interpreter.command)?,
arguments: interpreter
.arguments
.iter()
.map(|argument| self.evaluate_expression(argument))
.collect::<RunResult<Vec<String>>>()?,
})
}
pub(crate) fn evaluate_assignments(
config: &'run Config,
dotenv: &'run BTreeMap<String, String>,
module: &'run Justfile<'src>,
parent: &'run Scope<'src, 'run>,
search: &'run Search,
) -> RunResult<'src, Scope<'src, 'run>>
where
'src: 'run,
{
let context = ExecutionContext {
config,
dotenv,
module,
search,
};
let mut scope = parent.child();
if !module.is_submodule() {
let mut unknown_overrides = Vec::new();
for (name, value) in &config.overrides {
if let Some(assignment) = module.assignments.get(name) {
scope.bind(Binding {
export: assignment.export,
file_depth: 0,
name: assignment.name,
prelude: false,
private: assignment.private,
value: value.clone(),
});
} else {
unknown_overrides.push(name.clone());
}
}
if !unknown_overrides.is_empty() {
return Err(Error::UnknownOverrides {
overrides: unknown_overrides,
});
}
}
let mut evaluator = Self {
assignments: Some(&module.assignments),
context: Some(context),
is_dependency: false,
non_const_assignments: Table::new(),
scope,
};
for assignment in module.assignments.values() {
evaluator.evaluate_assignment(assignment)?;
}
Ok(evaluator.scope)
}
fn evaluate_assignment(&mut self, assignment: &Assignment<'src>) -> RunResult<'src, &str> {
let name = assignment.name.lexeme();
if !self.scope.bound(name) {
let value = self.evaluate_expression(&assignment.value)?;
self.scope.bind(Binding {
export: assignment.export,
file_depth: 0,
name: assignment.name,
prelude: false,
private: assignment.private,
value,
});
}
Ok(self.scope.value(name).unwrap())
}
fn function_context(&self, thunk: &Thunk<'src>) -> RunResult<'src, function::Context> {
Ok(function::Context {
execution_context: self.context(ConstError::FunctionCall(thunk.name()))?,
is_dependency: self.is_dependency,
name: thunk.name(),
scope: &self.scope,
})
}
pub(crate) fn evaluate_expression(
&mut self,
expression: &Expression<'src>,
) -> RunResult<'src, String> {
match expression {
Expression::And { lhs, rhs } => {
let lhs = self.evaluate_expression(lhs)?;
if lhs.is_empty() {
return Ok(String::new());
}
self.evaluate_expression(rhs)
}
Expression::Assert {
condition,
error,
name,
} => {
if self.evaluate_condition(condition)? {
Ok(String::new())
} else {
Err(Error::Assert {
message: self.evaluate_expression(error)?,
name: *name,
})
}
}
Expression::Backtick { contents, token } => {
let context = self.context(ConstError::Backtick(*token))?;
if context.config.dry_run {
return Ok(format!("`{contents}`"));
}
Self::run_command(context, &self.scope, contents, &[]).map_err(|output_error| {
Error::Backtick {
token: *token,
output_error,
}
})
}
Expression::Call { thunk } => {
use Thunk::*;
match thunk {
Nullary { function, .. } => function(self.function_context(thunk)?),
Unary { function, arg, .. } => {
let arg = self.evaluate_expression(arg)?;
function(self.function_context(thunk)?, &arg)
}
UnaryOpt {
function,
args: (a, b),
..
} => {
let a = self.evaluate_expression(a)?;
let b = match b.as_ref() {
Some(b) => Some(self.evaluate_expression(b)?),
None => None,
};
function(self.function_context(thunk)?, &a, b.as_deref())
}
UnaryPlus {
function,
args: (a, rest),
..
} => {
let a = self.evaluate_expression(a)?;
let mut rest_evaluated = Vec::new();
for arg in rest {
rest_evaluated.push(self.evaluate_expression(arg)?);
}
function(self.function_context(thunk)?, &a, &rest_evaluated)
}
Binary {
function,
args: [a, b],
..
} => {
let a = self.evaluate_expression(a)?;
let b = self.evaluate_expression(b)?;
function(self.function_context(thunk)?, &a, &b)
}
BinaryPlus {
function,
args: ([a, b], rest),
..
} => {
let a = self.evaluate_expression(a)?;
let b = self.evaluate_expression(b)?;
let mut rest_evaluated = Vec::new();
for arg in rest {
rest_evaluated.push(self.evaluate_expression(arg)?);
}
function(self.function_context(thunk)?, &a, &b, &rest_evaluated)
}
Ternary {
function,
args: [a, b, c],
..
} => {
let a = self.evaluate_expression(a)?;
let b = self.evaluate_expression(b)?;
let c = self.evaluate_expression(c)?;
function(self.function_context(thunk)?, &a, &b, &c)
}
}
.map_err(|message| Error::FunctionCall {
function: thunk.name(),
message,
})
}
Expression::Concatenation { lhs, rhs } => {
let lhs = self.evaluate_expression(lhs)?;
let rhs = self.evaluate_expression(rhs)?;
Ok(lhs + &rhs)
}
Expression::Conditional {
condition,
then,
otherwise,
} => {
if self.evaluate_condition(condition)? {
self.evaluate_expression(then)
} else {
self.evaluate_expression(otherwise)
}
}
Expression::FormatString { start, expressions } => {
let mut value = start.cooked.clone();
for (expression, string) in expressions {
value.push_str(&self.evaluate_expression(expression)?);
value.push_str(&string.cooked);
}
if start.kind.indented {
Ok(unindent(&value))
} else {
Ok(value)
}
}
Expression::Group { contents } => self.evaluate_expression(contents),
Expression::Join { lhs: None, rhs } => Ok("/".to_string() + &self.evaluate_expression(rhs)?),
Expression::Join {
lhs: Some(lhs),
rhs,
} => {
let lhs = self.evaluate_expression(lhs)?;
let rhs = self.evaluate_expression(rhs)?;
Ok(lhs + "/" + &rhs)
}
Expression::Or { lhs, rhs } => {
let lhs = self.evaluate_expression(lhs)?;
if !lhs.is_empty() {
return Ok(lhs);
}
self.evaluate_expression(rhs)
}
Expression::StringLiteral { string_literal } => Ok(string_literal.cooked.clone()),
Expression::Variable { name, .. } => {
let variable = name.lexeme();
if let Some(value) = self.scope.value(variable) {
Ok(value.to_owned())
} else if self.non_const_assignments.contains_key(name.lexeme()) {
Err(ConstError::Variable(*name).into())
} else if let Some(assignment) = self
.assignments
.and_then(|assignments| assignments.get(variable))
{
Ok(self.evaluate_assignment(assignment)?.to_owned())
} else {
Err(Error::internal(format!(
"attempted to evaluate undefined variable `{variable}`"
)))
}
}
}
}
fn evaluate_condition(&mut self, condition: &Condition<'src>) -> RunResult<'src, bool> {
let lhs_value = self.evaluate_expression(&condition.lhs)?;
let rhs_value = self.evaluate_expression(&condition.rhs)?;
let condition = match condition.operator {
ConditionalOperator::Equality => lhs_value == rhs_value,
ConditionalOperator::Inequality => lhs_value != rhs_value,
ConditionalOperator::RegexMatch => Regex::new(&rhs_value)
.map_err(|source| Error::RegexCompile { source })?
.is_match(&lhs_value),
ConditionalOperator::RegexMismatch => !Regex::new(&rhs_value)
.map_err(|source| Error::RegexCompile { source })?
.is_match(&lhs_value),
};
Ok(condition)
}
pub(crate) fn run_command(
context: &ExecutionContext,
scope: &Scope,
command: &str,
args: &[&str],
) -> Result<String, OutputError> {
let mut cmd = context.module.settings.shell_command(context.config);
cmd
.arg(command)
.args(args)
.current_dir(context.working_directory())
.export(
&context.module.settings,
context.dotenv,
scope,
&context.module.unexports,
)
.stdin(Stdio::inherit())
.stderr(if context.config.verbosity.quiet() {
Stdio::null()
} else {
Stdio::inherit()
})
.stdout(Stdio::piped());
cmd.output_guard_stdout()
}
pub(crate) fn evaluate_line(
&mut self,
line: &Line<'src>,
continued: bool,
) -> RunResult<'src, String> {
let mut evaluated = String::new();
for (i, fragment) in line.fragments.iter().enumerate() {
match fragment {
Fragment::Text { token } => {
let lexeme = token
.lexeme()
.replace(Lexer::INTERPOLATION_ESCAPE, Lexer::INTERPOLATION_START);
if i == 0 && continued {
evaluated += lexeme.trim_start();
} else {
evaluated += &lexeme;
}
}
Fragment::Interpolation { expression } => {
evaluated += &self.evaluate_expression(expression)?;
}
}
}
Ok(evaluated)
}
pub(crate) fn evaluate_parameters(
arguments: &[Vec<String>],
context: &ExecutionContext<'src, 'run>,
is_dependency: bool,
parameters: &[Parameter<'src>],
recipe: &Recipe<'src>,
scope: &'run Scope<'src, 'run>,
) -> RunResult<'src, (Scope<'src, 'run>, Vec<String>)> {
let mut evaluator = Self::new(context, is_dependency, scope);
let mut positional = Vec::new();
if arguments.len() != parameters.len() {
return Err(Error::internal("arguments do not match parameter count"));
}
for (parameter, group) in parameters.iter().zip(arguments) {
let values = if group.is_empty() {
if let Some(ref default) = parameter.default {
let value = evaluator.evaluate_expression(default)?;
positional.push(value.clone());
vec![value]
} else if parameter.kind == ParameterKind::Star {
Vec::new()
} else {
return Err(Error::internal("missing parameter without default"));
}
} else if parameter.kind.is_variadic() {
positional.extend_from_slice(group);
group.clone()
} else {
if group.len() != 1 {
return Err(Error::internal(
"multiple values for non-variadic parameter",
));
}
let value = group[0].clone();
positional.push(value.clone());
vec![value]
};
for value in &values {
parameter.check_pattern_match(recipe, value)?;
}
evaluator.scope.bind(Binding {
export: parameter.export,
file_depth: 0,
name: parameter.name,
prelude: false,
private: false,
value: values.join(" "),
});
}
Ok((evaluator.scope, positional))
}
pub(crate) fn new(
context: &ExecutionContext<'src, 'run>,
is_dependency: bool,
scope: &'run Scope<'src, 'run>,
) -> Self {
Self {
assignments: None,
context: Some(*context),
is_dependency,
non_const_assignments: Table::new(),
scope: scope.child(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
run_error! {
name: backtick_code,
src: "
a:
echo {{`f() { return 100; }; f`}}
",
args: ["a"],
error: Error::Backtick {
token,
output_error: OutputError::Code(code),
},
check: {
assert_eq!(code, 100);
assert_eq!(token.lexeme(), "`f() { return 100; }; f`");
}
}
run_error! {
name: export_assignment_backtick,
src: r#"
export exported_variable := "A"
b := `echo $exported_variable`
recipe:
echo {{b}}
"#,
args: ["--quiet", "recipe"],
error: Error::Backtick {
token,
output_error: OutputError::Code(_),
},
check: {
assert_eq!(token.lexeme(), "`echo $exported_variable`");
}
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/module_path.rs | src/module_path.rs | use super::*;
#[derive(Debug, PartialEq, Clone)]
pub(crate) struct ModulePath {
pub(crate) path: Vec<String>,
pub(crate) spaced: bool,
}
impl TryFrom<&[&str]> for ModulePath {
type Error = ();
fn try_from(path: &[&str]) -> Result<Self, Self::Error> {
let spaced = path.len() > 1;
let path = if path.len() == 1 {
let first = path[0];
if first.starts_with(':') || first.ends_with(':') || first.contains(":::") {
return Err(());
}
first
.split("::")
.map(str::to_string)
.collect::<Vec<String>>()
} else {
path.iter().map(|s| (*s).to_string()).collect()
};
for name in &path {
if name.is_empty() {
return Err(());
}
for (i, c) in name.chars().enumerate() {
if i == 0 {
if !Lexer::is_identifier_start(c) {
return Err(());
}
} else if !Lexer::is_identifier_continue(c) {
return Err(());
}
}
}
Ok(Self { path, spaced })
}
}
impl Display for ModulePath {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
for (i, name) in self.path.iter().enumerate() {
if i > 0 {
if self.spaced {
write!(f, " ")?;
} else {
write!(f, "::")?;
}
}
write!(f, "{name}")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn try_from_ok() {
#[track_caller]
fn case(path: &[&str], expected: &[&str], display: &str) {
let actual = ModulePath::try_from(path).unwrap();
assert_eq!(actual.path, expected);
assert_eq!(actual.to_string(), display);
}
case(&[], &[], "");
case(&["foo"], &["foo"], "foo");
case(&["foo0"], &["foo0"], "foo0");
case(&["foo", "bar"], &["foo", "bar"], "foo bar");
case(&["foo::bar"], &["foo", "bar"], "foo::bar");
}
#[test]
fn try_from_err() {
#[track_caller]
fn case(path: &[&str]) {
assert!(ModulePath::try_from(path).is_err());
}
case(&[":foo"]);
case(&["foo:"]);
case(&["foo:::bar"]);
case(&["0foo"]);
case(&["f$oo"]);
case(&[""]);
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/color.rs | src/color.rs | use {
super::*,
ansi_term::{ANSIGenericString, Color::*, Prefix, Style, Suffix},
std::io::{self, IsTerminal},
};
#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) struct Color {
is_terminal: bool,
style: Style,
use_color: UseColor,
}
impl Color {
pub(crate) fn active(&self) -> bool {
match self.use_color {
UseColor::Always => true,
UseColor::Never => false,
UseColor::Auto => self.is_terminal,
}
}
pub(crate) fn alias(self) -> Self {
self.restyle(Style::new().fg(Purple))
}
pub(crate) fn always() -> Self {
Self {
use_color: UseColor::Always,
..Self::default()
}
}
pub(crate) fn annotation(self) -> Self {
self.restyle(Style::new().fg(Purple))
}
pub(crate) fn auto() -> Self {
Self::default()
}
pub(crate) fn banner(self) -> Self {
self.restyle(Style::new().fg(Cyan).bold())
}
pub(crate) fn command(self, foreground: Option<ansi_term::Color>) -> Self {
self.restyle(Style {
foreground,
is_bold: true,
..Style::default()
})
}
pub(crate) fn context(self) -> Self {
self.restyle(Style::new().fg(Blue).bold())
}
pub(crate) fn diff_added(self) -> Self {
self.restyle(Style::new().fg(Green))
}
pub(crate) fn diff_deleted(self) -> Self {
self.restyle(Style::new().fg(Red))
}
pub(crate) fn doc(self) -> Self {
self.restyle(Style::new().fg(Blue))
}
pub(crate) fn doc_backtick(self) -> Self {
self.restyle(Style::new().fg(Cyan))
}
fn effective_style(&self) -> Style {
if self.active() {
self.style
} else {
Style::new()
}
}
pub(crate) fn error(self) -> Self {
self.restyle(Style::new().fg(Red).bold())
}
pub(crate) fn group(self) -> Self {
self.restyle(Style::new().fg(Yellow).bold())
}
pub(crate) fn message(self) -> Self {
self.restyle(Style::new().bold())
}
pub(crate) fn never() -> Self {
Self {
use_color: UseColor::Never,
..Self::default()
}
}
pub(crate) fn paint<'a>(&self, text: &'a str) -> ANSIGenericString<'a, str> {
self.effective_style().paint(text)
}
pub(crate) fn parameter(self) -> Self {
self.restyle(Style::new().fg(Cyan))
}
pub(crate) fn prefix(&self) -> Prefix {
self.effective_style().prefix()
}
fn redirect(self, stream: impl IsTerminal) -> Self {
Self {
is_terminal: stream.is_terminal(),
..self
}
}
fn restyle(self, style: Style) -> Self {
Self { style, ..self }
}
pub(crate) fn stderr(self) -> Self {
self.redirect(io::stderr())
}
pub(crate) fn stdout(self) -> Self {
self.redirect(io::stdout())
}
pub(crate) fn string(self) -> Self {
self.restyle(Style::new().fg(Green))
}
pub(crate) fn suffix(&self) -> Suffix {
self.effective_style().suffix()
}
pub(crate) fn warning(self) -> Self {
self.restyle(Style::new().fg(Yellow).bold())
}
pub(crate) fn heading(self) -> Self {
self.restyle(Style::new().fg(Yellow).bold())
}
pub(crate) fn option(self) -> Self {
self.restyle(Style::new().fg(Green))
}
pub(crate) fn argument(self) -> Self {
self.restyle(Style::new().fg(Cyan))
}
}
impl From<UseColor> for Color {
fn from(use_color: UseColor) -> Self {
Self {
use_color,
..Default::default()
}
}
}
impl Default for Color {
fn default() -> Self {
Self {
is_terminal: false,
style: Style::new(),
use_color: UseColor::Auto,
}
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/positional.rs | src/positional.rs | use super::*;
/// A struct containing the parsed representation of positional command-line
/// arguments, i.e. arguments that are not flags, options, or the subcommand.
///
/// The DSL of positional arguments is fairly complex and mostly accidental.
/// There are three possible components: overrides, a search directory, and the
/// rest:
///
/// - Overrides are of the form `NAME=.*`
///
/// - After overrides comes a single optional search directory argument. This is
/// either '.', '..', or an argument that contains a `/`.
///
/// If the argument contains a `/`, everything before and including the slash
/// is the search directory, and everything after is added to the rest.
///
/// - Everything else is an argument.
///
/// Overrides set the values of top-level variables in the justfile being
/// invoked and are a convenient way to override settings.
///
/// For modes that do not take other arguments, the search directory argument
/// determines where to begin searching for the justfile. This allows command
/// lines like `just -l ..` and `just ../build` to find the same justfile.
///
/// For modes that do take other arguments, the search argument is simply
/// prepended to rest.
#[cfg_attr(test, derive(PartialEq, Eq, Debug))]
pub struct Positional {
/// Everything else
pub arguments: Vec<String>,
/// Overrides from values of the form `[a-zA-Z_][a-zA-Z0-9_-]*=.*`
pub overrides: Vec<(String, String)>,
/// An argument equal to '.', '..', or ending with `/`
pub search_directory: Option<String>,
}
impl Positional {
pub fn from_values<'values>(values: Option<impl IntoIterator<Item = &'values str>>) -> Self {
let mut overrides = Vec::new();
let mut search_directory = None;
let mut arguments = Vec::new();
if let Some(values) = values {
for value in values {
if search_directory.is_none() && arguments.is_empty() {
if let Some(o) = Self::override_from_value(value) {
overrides.push(o);
} else if value == "." || value == ".." {
search_directory = Some(value.to_owned());
} else if let Some(i) = value.rfind('/') {
let (dir, tail) = value.split_at(i + 1);
search_directory = Some(dir.to_owned());
if !tail.is_empty() {
arguments.push(tail.to_owned());
}
} else {
arguments.push(value.to_owned());
}
} else {
arguments.push(value.to_owned());
}
}
}
Self {
arguments,
overrides,
search_directory,
}
}
/// Parse an override from a value of the form `NAME=.*`.
fn override_from_value(value: &str) -> Option<(String, String)> {
let equals = value.find('=')?;
let (identifier, equals_value) = value.split_at(equals);
// exclude `=` from value
let value = &equals_value[1..];
if Lexer::is_identifier(identifier) {
Some((identifier.to_owned(), value.to_owned()))
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
macro_rules! test {
{
name: $name:ident,
values: $vals:expr,
overrides: $overrides:expr,
search_directory: $search_directory:expr,
arguments: $arguments:expr,
} => {
#[test]
fn $name() {
assert_eq! (
Positional::from_values(Some($vals.iter().cloned())),
Positional {
overrides: $overrides
.iter()
.cloned()
.map(|(key, value): (&str, &str)| (key.to_owned(), value.to_owned()))
.collect(),
search_directory: $search_directory.map(str::to_owned),
arguments: $arguments.iter().cloned().map(str::to_owned).collect(),
},
)
}
}
}
test! {
name: no_values,
values: [],
overrides: [],
search_directory: None,
arguments: [],
}
test! {
name: arguments_only,
values: ["foo", "bar"],
overrides: [],
search_directory: None,
arguments: ["foo", "bar"],
}
test! {
name: all_overrides,
values: ["foo=bar", "bar=foo"],
overrides: [("foo", "bar"), ("bar", "foo")],
search_directory: None,
arguments: [],
}
test! {
name: override_not_name,
values: ["foo=bar", "bar.=foo"],
overrides: [("foo", "bar")],
search_directory: None,
arguments: ["bar.=foo"],
}
test! {
name: no_overrides,
values: ["the-dir/", "baz", "bzzd"],
overrides: [],
search_directory: Some("the-dir/"),
arguments: ["baz", "bzzd"],
}
test! {
name: no_search_directory,
values: ["foo=bar", "bar=foo", "baz", "bzzd"],
overrides: [("foo", "bar"), ("bar", "foo")],
search_directory: None,
arguments: ["baz", "bzzd"],
}
test! {
name: no_arguments,
values: ["foo=bar", "bar=foo", "the-dir/"],
overrides: [("foo", "bar"), ("bar", "foo")],
search_directory: Some("the-dir/"),
arguments: [],
}
test! {
name: all_dot,
values: ["foo=bar", "bar=foo", ".", "garnor"],
overrides: [("foo", "bar"), ("bar", "foo")],
search_directory: Some("."),
arguments: ["garnor"],
}
test! {
name: all_dot_dot,
values: ["foo=bar", "bar=foo", "..", "garnor"],
overrides: [("foo", "bar"), ("bar", "foo")],
search_directory: Some(".."),
arguments: ["garnor"],
}
test! {
name: all_slash,
values: ["foo=bar", "bar=foo", "/", "garnor"],
overrides: [("foo", "bar"), ("bar", "foo")],
search_directory: Some("/"),
arguments: ["garnor"],
}
test! {
name: search_directory_after_argument,
values: ["foo=bar", "bar=foo", "baz", "bzzd", "bar/"],
overrides: [("foo", "bar"), ("bar", "foo")],
search_directory: None,
arguments: ["baz", "bzzd", "bar/"],
}
test! {
name: override_after_search_directory,
values: ["..", "a=b"],
overrides: [],
search_directory: Some(".."),
arguments: ["a=b"],
}
test! {
name: override_after_argument,
values: ["a", "a=b"],
overrides: [],
search_directory: None,
arguments: ["a", "a=b"],
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/command_color.rs | src/command_color.rs | use super::*;
#[derive(Copy, Clone, ValueEnum)]
pub(crate) enum CommandColor {
Black,
Blue,
Cyan,
Green,
Purple,
Red,
Yellow,
}
impl From<CommandColor> for ansi_term::Color {
fn from(command_color: CommandColor) -> Self {
match command_color {
CommandColor::Black => Self::Black,
CommandColor::Blue => Self::Blue,
CommandColor::Cyan => Self::Cyan,
CommandColor::Green => Self::Green,
CommandColor::Purple => Self::Purple,
CommandColor::Red => Self::Red,
CommandColor::Yellow => Self::Yellow,
}
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/string_delimiter.rs | src/string_delimiter.rs | #[derive(Debug, PartialEq, Clone, Copy, Ord, PartialOrd, Eq)]
pub(crate) enum StringDelimiter {
Backtick,
QuoteDouble,
QuoteSingle,
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/assignment.rs | src/assignment.rs | use super::*;
/// An assignment, e.g `foo := bar`
pub(crate) type Assignment<'src> = Binding<'src, Expression<'src>>;
impl Display for Assignment<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if self.private {
writeln!(f, "[private]")?;
}
if self.export {
write!(f, "export ")?;
}
write!(f, "{} := {}", self.name, self.value)
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/set.rs | src/set.rs | use super::*;
#[derive(Debug, Clone)]
pub(crate) struct Set<'src> {
pub(crate) name: Name<'src>,
pub(crate) value: Setting<'src>,
}
impl<'src> Keyed<'src> for Set<'src> {
fn key(&self) -> &'src str {
self.name.lexeme()
}
}
impl Display for Set<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "set {} := {}", self.name, self.value)
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/signals.rs | src/signals.rs | use {
super::*,
nix::{
errno::Errno,
fcntl::{FcntlArg, FdFlag},
sys::signal::{SaFlags, SigAction, SigHandler, SigSet},
},
std::{
fs::File,
io::Read,
os::fd::{BorrowedFd, IntoRawFd, OwnedFd},
sync::atomic::{self, AtomicI32},
},
};
const INVALID_FILENO: i32 = -1;
static WRITE: AtomicI32 = AtomicI32::new(INVALID_FILENO);
fn die(message: &str) -> ! {
// SAFETY:
//
// Standard error is open for the duration of the program.
const STDERR: BorrowedFd = unsafe { BorrowedFd::borrow_raw(libc::STDERR_FILENO) };
let mut i = 0;
let mut buffer = [0; 512];
let mut append = |s: &str| {
let remaining = buffer.len() - i;
let n = s.len().min(remaining);
let end = i + n;
buffer[i..end].copy_from_slice(&s.as_bytes()[0..n]);
i = end;
};
append("error: ");
append(message);
append("\n");
nix::unistd::write(STDERR, &buffer[0..i]).ok();
process::abort();
}
extern "C" fn handler(signal: libc::c_int) {
let errno = Errno::last();
let Ok(signal) = u8::try_from(signal) else {
die("unexpected signal");
};
// SAFETY:
//
// `WRITE` is initialized before the signal handler can run and remains open
// for the duration of the program.
let fd = unsafe { BorrowedFd::borrow_raw(WRITE.load(atomic::Ordering::Relaxed)) };
if let Err(err) = nix::unistd::write(fd, &[signal]) {
die(err.desc());
}
errno.set();
}
fn fcntl(fd: &OwnedFd, arg: FcntlArg) -> RunResult<'static, libc::c_int> {
nix::fcntl::fcntl(fd, arg).map_err(|errno| Error::SignalHandlerPipeCloexec {
io_error: errno.into(),
})
}
fn set_cloexec(fd: &OwnedFd) -> RunResult<'static> {
// It would be better to use pipe2(O_CLOEXEC) rather than pipe-then-fcntl,
// but it isn't supported on all platforms (most notably, not macos) and in
// the atomicity guarantees that pipe2 provides aren't needed.
let existing_flags = fcntl(fd, FcntlArg::F_GETFD)?;
let combined_flags = FdFlag::from_bits_retain(existing_flags) | FdFlag::FD_CLOEXEC;
fcntl(fd, FcntlArg::F_SETFD(combined_flags))?;
Ok(())
}
pub(crate) struct Signals(File);
impl Signals {
pub(crate) fn new() -> RunResult<'static, Self> {
let (read, write) = nix::unistd::pipe().map_err(|errno| Error::SignalHandlerPipeOpen {
io_error: errno.into(),
})?;
set_cloexec(&read)?;
set_cloexec(&write)?;
if WRITE
.compare_exchange(
INVALID_FILENO,
write.into_raw_fd(),
atomic::Ordering::Relaxed,
atomic::Ordering::Relaxed,
)
.is_err()
{
panic!("signal iterator cannot be initialized twice");
}
let sa = SigAction::new(
SigHandler::Handler(handler),
SaFlags::SA_RESTART,
SigSet::empty(),
);
for &signal in Signal::ALL {
// SAFETY:
//
// This is the only place we modify signal handlers, and
// `nix::sys::signal::sigaction` is unsafe only if an invalid signal
// handler has already been installed.
unsafe {
nix::sys::signal::sigaction(signal.into(), &sa).map_err(|errno| {
Error::SignalHandlerSigaction {
signal,
io_error: errno.into(),
}
})?;
}
}
Ok(Self(File::from(read)))
}
}
impl Iterator for Signals {
type Item = io::Result<Signal>;
fn next(&mut self) -> Option<Self::Item> {
let mut signal = [0];
Some(
self
.0
.read_exact(&mut signal)
.and_then(|()| Signal::try_from(signal[0])),
)
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/suggestion.rs | src/suggestion.rs | use super::*;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Suggestion<'src> {
pub(crate) name: &'src str,
pub(crate) target: Option<&'src str>,
}
impl Display for Suggestion<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "Did you mean `{}`", self.name)?;
if let Some(target) = self.target {
write!(f, ", an alias for `{target}`")?;
}
write!(f, "?")
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/switch.rs | src/switch.rs | use super::*;
#[derive(Debug, PartialEq)]
pub(crate) enum Switch {
Long(String),
Short(char),
}
impl Display for Switch {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match &self {
Self::Long(long) => write!(f, "--{long}"),
Self::Short(short) => write!(f, "-{short}"),
}
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/invocation_parser.rs | src/invocation_parser.rs | use super::*;
#[allow(clippy::doc_markdown)]
/// The invocation parser is responsible for grouping command-line positional
/// arguments into invocations, which consist of a recipe and its arguments.
///
/// Invocation parsing is substantially complicated by the fact that recipe
/// paths can be given on the command line as multiple arguments, i.e., "foo"
/// "bar" baz", or as a single "::"-separated argument.
///
/// Error messages produced by the invocation parser should use the format of
/// the recipe path as passed on the command line.
///
/// Additionally, if a recipe is specified with a "::"-separated path, extra
/// components of that path after a valid recipe must not be used as arguments,
/// whereas arguments after multiple argument path may be used as arguments. As
/// an example, `foo bar baz` may refer to recipe `foo::bar` with argument
/// `baz`, but `foo::bar::baz` is an error, since `bar` is a recipe, not a
/// module.
pub(crate) struct InvocationParser<'src: 'run, 'run> {
arguments: &'run [&'run str],
next: usize,
root: &'run Justfile<'src>,
}
impl<'src: 'run, 'run> InvocationParser<'src, 'run> {
pub(crate) fn parse_invocations(
root: &'run Justfile<'src>,
arguments: &'run [&'run str],
) -> RunResult<'src, Vec<Invocation<'src, 'run>>> {
let mut invocations = Vec::new();
let mut invocation_parser = Self {
arguments,
next: 0,
root,
};
loop {
invocations.push(invocation_parser.parse_invocation()?);
if invocation_parser.next == arguments.len() {
break;
}
}
Ok(invocations)
}
fn parse_invocation(&mut self) -> RunResult<'src, Invocation<'src, 'run>> {
let recipe = if let Some(next) = self.next() {
if next.contains(':') {
let module_path =
ModulePath::try_from([next].as_slice()).map_err(|()| Error::UnknownRecipe {
recipe: next.into(),
suggestion: None,
})?;
let (recipe, _) = self.resolve_recipe(true, &module_path.path)?;
self.next += 1;
recipe
} else {
let (recipe, consumed) = self.resolve_recipe(false, self.rest())?;
self.next += consumed;
recipe
}
} else {
let (recipe, consumed) = self.resolve_recipe(false, self.rest())?;
assert_eq!(consumed, 0);
recipe
};
let mut arguments = vec![Vec::<String>::new(); recipe.parameters.len()];
let long = recipe
.parameters
.iter()
.enumerate()
.filter_map(|(i, parameter)| parameter.long.as_ref().map(|name| (name.as_str(), i)))
.collect::<BTreeMap<&str, usize>>();
let short = recipe
.parameters
.iter()
.enumerate()
.filter_map(|(i, parameter)| parameter.short.map(|name| (name, i)))
.collect::<BTreeMap<char, usize>>();
let positional = recipe
.parameters
.iter()
.enumerate()
.filter_map(|(i, parameter)| (!parameter.is_option()).then_some(i))
.collect::<Vec<usize>>();
let mut end_of_options = long.is_empty() && short.is_empty();
let rest = self.rest();
let mut i = 0;
let mut positional_index = 0;
let mut positional_accepted = 0;
loop {
let Some(argument) = rest.get(i) else {
break;
};
if !end_of_options && *argument == "--" {
end_of_options = true;
i += 1;
} else if !end_of_options && argument.starts_with('-') && *argument != "-" {
let mut name = argument
.strip_prefix("--")
.or_else(|| argument.strip_prefix('-'))
.unwrap();
let value = if let Some((left, right)) = name.split_once('=') {
name = left;
Some(right)
} else {
None
};
let switch = if argument.starts_with("--") {
Switch::Long(name.into())
} else {
if name.chars().count() != 1 {
return Err(Error::MultipleShortOptions {
options: name.into(),
});
}
Switch::Short(name.chars().next().unwrap())
};
let index = match &switch {
Switch::Long(name) => long.get(name.as_str()),
Switch::Short(name) => short.get(name),
};
let Some(&index) = index else {
return Err(Error::UnknownOption {
recipe: recipe.name(),
option: switch,
});
};
let value = if let Some(flag_value) = &recipe.parameters[index].value {
if value.is_some() {
return Err(Error::FlagWithValue {
recipe: recipe.name(),
option: switch,
});
}
i += 1;
flag_value
} else if let Some(value) = value {
i += 1;
value
} else {
let Some(&value) = rest.get(i + 1) else {
return Err(Error::OptionMissingValue {
recipe: recipe.name(),
option: switch,
});
};
i += 2;
value
};
let group = &mut arguments[index];
if !group.is_empty() {
return Err(Error::DuplicateOption {
recipe: recipe.name(),
option: switch,
});
}
group.push((*value).into());
} else {
let Some(&index) = positional.get(positional_index) else {
break;
};
let group = &mut arguments[index];
group.push((*argument).into());
if !recipe.parameters[index].kind.is_variadic() {
positional_index += 1;
}
positional_accepted += 1;
i += 1;
}
}
let mut missing_positional = 0;
for (parameter, group) in recipe.parameters.iter().zip(&arguments) {
if !group.is_empty() {
continue;
}
if parameter.default.is_some() || parameter.kind == ParameterKind::Star {
continue;
}
if let Some(name) = ¶meter.long {
return Err(Error::MissingOption {
recipe: recipe.name(),
option: Switch::Long(name.into()),
});
}
if let Some(name) = ¶meter.short {
return Err(Error::MissingOption {
recipe: recipe.name(),
option: Switch::Short(*name),
});
}
missing_positional += 1;
}
if missing_positional > 0 {
return Err(Error::PositionalArgumentCountMismatch {
recipe: Box::new(recipe.clone()),
found: positional_accepted,
min: recipe
.parameters
.iter()
.filter(|p| p.is_required() && !p.is_option())
.count(),
max: if recipe.parameters.iter().any(|p| p.kind.is_variadic()) {
usize::MAX - 1
} else {
recipe.parameters.iter().filter(|p| !p.is_option()).count()
},
});
}
for (group, parameter) in arguments.iter().zip(&recipe.parameters) {
for argument in group {
parameter.check_pattern_match(recipe, argument)?;
}
}
self.next += i;
Ok(Invocation { arguments, recipe })
}
fn resolve_recipe(
&self,
module_path: bool,
args: &[impl AsRef<str>],
) -> RunResult<'src, (&'run Recipe<'src>, usize)> {
let mut current = self.root;
let mut path = Vec::new();
for (i, arg) in args.iter().enumerate() {
let arg = arg.as_ref();
path.push(arg.to_string());
if let Some(module) = current.modules.get(arg) {
current = module;
} else if let Some(recipe) = current.get_recipe(arg) {
if module_path && i + 1 < args.len() {
return Err(Error::ExpectedSubmoduleButFoundRecipe {
path: path.join("::"),
});
}
return Ok((recipe, i + 1));
} else {
if module_path && i + 1 < args.len() {
return Err(Error::UnknownSubmodule {
path: path.join("::"),
});
}
return Err(Error::UnknownRecipe {
recipe: if module_path {
path.join("::")
} else {
path.join(" ")
},
suggestion: current.suggest_recipe(arg),
});
}
}
if let Some(recipe) = ¤t.default {
recipe.check_can_be_default_recipe()?;
Ok((recipe, args.len()))
} else if current.recipes.is_empty() {
Err(Error::NoRecipes)
} else {
Err(Error::NoDefaultRecipe)
}
}
fn next(&self) -> Option<&'run str> {
self.arguments.get(self.next).copied()
}
fn rest(&self) -> &[&'run str] {
&self.arguments[self.next..]
}
}
#[cfg(test)]
mod tests {
use {super::*, tempfile::TempDir};
trait TempDirExt {
fn write(&self, path: &str, content: &str);
}
impl TempDirExt for TempDir {
fn write(&self, path: &str, content: &str) {
let path = self.path().join(path);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, content).unwrap();
}
}
#[test]
fn single_no_arguments() {
let justfile = testing::compile("foo:");
let invocations = InvocationParser::parse_invocations(&justfile, &["foo"]).unwrap();
assert_eq!(invocations.len(), 1);
assert_eq!(invocations[0].recipe.namepath(), "foo");
assert!(invocations[0].arguments.is_empty());
}
#[test]
fn single_with_argument() {
let justfile = testing::compile("foo bar:");
let invocations = InvocationParser::parse_invocations(&justfile, &["foo", "baz"]).unwrap();
assert_eq!(invocations.len(), 1);
assert_eq!(invocations[0].recipe.namepath(), "foo");
assert_eq!(invocations[0].arguments, vec![vec![String::from("baz")]]);
}
#[test]
fn single_argument_count_mismatch() {
let justfile = testing::compile("foo bar:");
assert_matches!(
InvocationParser::parse_invocations(&justfile, &["foo"]).unwrap_err(),
Error::PositionalArgumentCountMismatch {
recipe: _,
found: 0,
min: 1,
max: 1,
..
},
);
}
#[test]
fn single_unknown() {
let justfile = testing::compile("foo:");
assert_matches!(
InvocationParser::parse_invocations(&justfile, &["bar"]).unwrap_err(),
Error::UnknownRecipe {
recipe,
suggestion: None
} if recipe == "bar",
);
}
#[test]
fn multiple_unknown() {
let justfile = testing::compile("foo:");
assert_matches!(
InvocationParser::parse_invocations(&justfile, &["bar", "baz"]).unwrap_err(),
Error::UnknownRecipe {
recipe,
suggestion: None
} if recipe == "bar",
);
}
#[test]
fn recipe_in_submodule() {
let loader = Loader::new();
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("justfile");
fs::write(&path, "mod foo").unwrap();
fs::create_dir(tempdir.path().join("foo")).unwrap();
fs::write(tempdir.path().join("foo/mod.just"), "bar:").unwrap();
let compilation = Compiler::compile(&Config::default(), &loader, &path).unwrap();
let invocations =
InvocationParser::parse_invocations(&compilation.justfile, &["foo", "bar"]).unwrap();
assert_eq!(invocations.len(), 1);
assert_eq!(invocations[0].recipe.namepath(), "foo::bar");
assert!(invocations[0].arguments.is_empty());
}
#[test]
fn recipe_in_submodule_unknown() {
let loader = Loader::new();
let tempdir = tempfile::tempdir().unwrap();
let path = tempdir.path().join("justfile");
fs::write(&path, "mod foo").unwrap();
fs::create_dir(tempdir.path().join("foo")).unwrap();
fs::write(tempdir.path().join("foo/mod.just"), "bar:").unwrap();
let compilation = Compiler::compile(&Config::default(), &loader, &path).unwrap();
assert_matches!(
InvocationParser::parse_invocations(&compilation.justfile, &["foo", "zzz"]).unwrap_err(),
Error::UnknownRecipe {
recipe,
suggestion: None
} if recipe == "foo zzz",
);
}
#[test]
fn recipe_in_submodule_path_unknown() {
let tempdir = tempfile::tempdir().unwrap();
tempdir.write("justfile", "mod foo");
tempdir.write("foo.just", "bar:");
let loader = Loader::new();
let compilation = Compiler::compile(
&Config::default(),
&loader,
&tempdir.path().join("justfile"),
)
.unwrap();
assert_matches!(
InvocationParser::parse_invocations(&compilation.justfile, &["foo::zzz"]).unwrap_err(),
Error::UnknownRecipe {
recipe,
suggestion: None
} if recipe == "foo::zzz",
);
}
#[test]
fn module_path_not_consumed() {
let tempdir = tempfile::tempdir().unwrap();
tempdir.write("justfile", "mod foo");
tempdir.write("foo.just", "bar:");
let loader = Loader::new();
let compilation = Compiler::compile(
&Config::default(),
&loader,
&tempdir.path().join("justfile"),
)
.unwrap();
assert_matches!(
InvocationParser::parse_invocations(&compilation.justfile, &["foo::bar::baz"]).unwrap_err(),
Error::ExpectedSubmoduleButFoundRecipe {
path,
} if path == "foo::bar",
);
}
#[test]
fn no_recipes() {
let tempdir = tempfile::tempdir().unwrap();
tempdir.write("justfile", "");
let loader = Loader::new();
let compilation = Compiler::compile(
&Config::default(),
&loader,
&tempdir.path().join("justfile"),
)
.unwrap();
assert_matches!(
InvocationParser::parse_invocations(&compilation.justfile, &[]).unwrap_err(),
Error::NoRecipes,
);
}
#[test]
fn default_recipe_requires_arguments() {
let tempdir = tempfile::tempdir().unwrap();
tempdir.write("justfile", "foo bar:");
let loader = Loader::new();
let compilation = Compiler::compile(
&Config::default(),
&loader,
&tempdir.path().join("justfile"),
)
.unwrap();
assert_matches!(
InvocationParser::parse_invocations(&compilation.justfile, &[]).unwrap_err(),
Error::DefaultRecipeRequiresArguments {
recipe: "foo",
min_arguments: 1,
},
);
}
#[test]
fn no_default_recipe() {
let tempdir = tempfile::tempdir().unwrap();
tempdir.write("justfile", "import 'foo.just'");
tempdir.write("foo.just", "bar:");
let loader = Loader::new();
let compilation = Compiler::compile(
&Config::default(),
&loader,
&tempdir.path().join("justfile"),
)
.unwrap();
assert_matches!(
InvocationParser::parse_invocations(&compilation.justfile, &[]).unwrap_err(),
Error::NoDefaultRecipe,
);
}
#[test]
fn complex_grouping() {
let justfile = testing::compile(
"
FOO A B='blarg':
echo foo: {{A}} {{B}}
BAR X:
echo bar: {{X}}
BAZ +Z:
echo baz: {{Z}}
",
);
let invocations = InvocationParser::parse_invocations(
&justfile,
&["BAR", "0", "FOO", "1", "2", "BAZ", "3", "4", "5"],
)
.unwrap();
assert_eq!(invocations.len(), 3);
assert_eq!(invocations[0].recipe.namepath(), "BAR");
assert_eq!(invocations[0].arguments, vec![vec![String::from("0")]]);
assert_eq!(invocations[1].recipe.namepath(), "FOO");
assert_eq!(
invocations[1].arguments,
vec![vec![String::from("1")], vec![String::from("2")]]
);
assert_eq!(invocations[2].recipe.namepath(), "BAZ");
assert_eq!(
invocations[2].arguments,
vec![vec![
String::from("3"),
String::from("4"),
String::from("5")
]]
);
}
#[test]
fn long_argument() {
let justfile = testing::compile(
"
[arg('bar', long='bar')]
foo bar:
",
);
let invocations =
InvocationParser::parse_invocations(&justfile, &["foo", "--bar", "baz"]).unwrap();
assert_eq!(invocations.len(), 1);
assert_eq!(invocations[0].recipe.namepath(), "foo");
assert_eq!(invocations[0].arguments, vec![vec![String::from("baz")]]);
}
#[test]
fn long_argument_with_positional() {
let justfile = testing::compile(
"
[arg('bar', long='bar')]
foo baz bar:
",
);
let invocations =
InvocationParser::parse_invocations(&justfile, &["foo", "qux", "--bar", "baz"]).unwrap();
assert_eq!(invocations.len(), 1);
assert_eq!(invocations[0].recipe.namepath(), "foo");
assert_eq!(
invocations[0].arguments,
vec![vec![String::from("qux")], vec![String::from("baz")]]
);
}
#[test]
fn long_argument_terminator() {
let justfile = testing::compile(
"
[arg('bar', long='bar')]
foo baz qux='qux' bar='bar':
",
);
let invocations =
InvocationParser::parse_invocations(&justfile, &["foo", "--", "--bar"]).unwrap();
assert_eq!(invocations.len(), 1);
assert_eq!(invocations[0].recipe.namepath(), "foo");
assert_eq!(
invocations[0].arguments,
vec![vec![String::from("--bar")], Vec::new(), Vec::new()]
);
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/usage.rs | src/usage.rs | use super::*;
pub(crate) struct Usage<'a, D> {
pub(crate) long: bool,
pub(crate) path: &'a ModulePath,
pub(crate) recipe: &'a Recipe<'a, D>,
}
impl<D> ColorDisplay for Usage<'_, D> {
fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result {
write!(
f,
"{}{}{} {}",
color
.heading()
.paint(if self.long { "Usage:" } else { "usage:" }),
if self.long { " " } else { "\n " },
color.argument().paint("just"),
color.argument().paint(&self.path.to_string()),
)?;
let options = self.recipe.parameters.iter().any(Parameter::is_option);
let arguments = self.recipe.parameters.iter().any(|p| !p.is_option());
if options {
write!(f, " {}", color.argument().paint("[OPTIONS]"))?;
}
for parameter in &self.recipe.parameters {
if parameter.is_option() {
continue;
}
write!(f, " ")?;
write!(
f,
"{}",
UsageParameter {
parameter,
long: false,
}
.color_display(color),
)?;
}
if !self.long {
return Ok(());
}
if arguments {
writeln!(f)?;
writeln!(f)?;
writeln!(f, "{}", color.heading().paint("Arguments:"))?;
for (i, parameter) in self
.recipe
.parameters
.iter()
.filter(|p| !p.is_option())
.enumerate()
{
if i > 0 {
writeln!(f)?;
}
write!(f, " ")?;
write!(
f,
"{}",
UsageParameter {
parameter,
long: true,
}
.color_display(color),
)?;
}
}
if options {
if arguments {
writeln!(f)?;
}
writeln!(f)?;
writeln!(f, "{}", color.heading().paint("Options:"))?;
for (i, parameter) in self
.recipe
.parameters
.iter()
.filter(|p| p.is_option())
.enumerate()
{
if i > 0 {
writeln!(f)?;
}
write!(f, " ")?;
write!(
f,
"{}",
UsageParameter {
parameter,
long: true,
}
.color_display(color),
)?;
}
}
Ok(())
}
}
struct UsageParameter<'a> {
long: bool,
parameter: &'a Parameter<'a>,
}
impl ColorDisplay for UsageParameter<'_> {
fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result {
if self.parameter.is_option() {
if let Some(short) = self.parameter.short {
write!(f, "{}", color.option().paint(&format!("-{short}")))?;
} else {
write!(f, " ")?;
}
if let Some(long) = &self.parameter.long {
if self.parameter.short.is_some() {
write!(f, ", ")?;
} else {
write!(f, " ")?;
}
write!(f, "{}", color.option().paint(&format!("--{long}")))?;
}
if self.parameter.value.is_none() {
write!(
f,
" {}",
color.argument().paint(self.parameter.name.lexeme()),
)?;
}
} else {
if !self.parameter.is_required() {
write!(f, "{}", color.argument().paint("["))?;
}
write!(
f,
"{}",
color.argument().paint(self.parameter.name.lexeme()),
)?;
if self.parameter.kind.is_variadic() {
write!(f, "{}", color.argument().paint("..."))?;
}
if !self.parameter.is_required() {
write!(f, "{}", color.argument().paint("]"))?;
}
}
if !self.long {
return Ok(());
}
if let Some(help) = &self.parameter.help {
write!(f, " {help}")?;
}
if let Some(default) = &self.parameter.default {
if self.parameter.value.is_none() {
write!(f, " [default: {default}]")?;
}
}
if let Some(pattern) = &self.parameter.pattern {
write!(f, " [pattern: '{}']", pattern.original())?;
}
Ok(())
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/parameter.rs | src/parameter.rs | use super::*;
#[derive(PartialEq, Debug, Clone, Serialize)]
pub(crate) struct Parameter<'src> {
pub(crate) default: Option<Expression<'src>>,
pub(crate) export: bool,
pub(crate) help: Option<String>,
pub(crate) kind: ParameterKind,
pub(crate) long: Option<String>,
pub(crate) name: Name<'src>,
pub(crate) pattern: Option<Pattern<'src>>,
pub(crate) short: Option<char>,
pub(crate) value: Option<String>,
}
impl<'src> Parameter<'src> {
pub(crate) fn is_option(&self) -> bool {
self.long.is_some() || self.short.is_some()
}
pub(crate) fn is_required(&self) -> bool {
self.default.is_none() && self.kind != ParameterKind::Star
}
pub(crate) fn check_pattern_match(
&self,
recipe: &Recipe<'src>,
value: &str,
) -> Result<(), Error<'src>> {
let Some(pattern) = &self.pattern else {
return Ok(());
};
if pattern.is_match(value) {
return Ok(());
}
Err(Error::ArgumentPatternMismatch {
argument: value.into(),
parameter: self.name.lexeme(),
pattern: Box::new(pattern.clone()),
recipe: recipe.name(),
})
}
}
impl ColorDisplay for Parameter<'_> {
fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result {
if let Some(prefix) = self.kind.prefix() {
write!(f, "{}", color.annotation().paint(prefix))?;
}
if self.export {
write!(f, "$")?;
}
write!(f, "{}", color.parameter().paint(self.name.lexeme()))?;
if let Some(ref default) = self.default {
write!(f, "={}", color.string().paint(&default.to_string()))?;
}
Ok(())
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/token.rs | src/token.rs | use super::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
pub(crate) struct Token<'src> {
pub(crate) column: usize,
pub(crate) kind: TokenKind,
pub(crate) length: usize,
pub(crate) line: usize,
pub(crate) offset: usize,
pub(crate) path: &'src Path,
pub(crate) src: &'src str,
}
impl<'src> Token<'src> {
pub(crate) fn lexeme(&self) -> &'src str {
&self.src[self.offset..self.offset + self.length]
}
pub(crate) fn error(&self, kind: CompileErrorKind<'src>) -> CompileError<'src> {
CompileError::new(*self, kind)
}
}
impl ColorDisplay for Token<'_> {
fn fmt(&self, f: &mut Formatter, color: Color) -> fmt::Result {
let width = if self.length == 0 { 1 } else { self.length };
let line_number = self.line.ordinal();
match self.src.lines().nth(self.line) {
Some(line) => {
let mut i = 0;
let mut space_column = 0;
let mut space_line = String::new();
let mut space_width = 0;
for c in line.chars() {
if c == '\t' {
space_line.push_str(" ");
if i < self.column {
space_column += 4;
}
if i >= self.column && i < self.column + width {
space_width += 4;
}
} else {
if i < self.column {
space_column += UnicodeWidthChar::width(c).unwrap_or(0);
}
if i >= self.column && i < self.column + width {
space_width += UnicodeWidthChar::width(c).unwrap_or(0);
}
space_line.push(c);
}
i += c.len_utf8();
}
let line_number_width = line_number.to_string().len();
writeln!(
f,
"{:width$}{} {}:{}:{}",
"",
color.context().paint("——▶"),
self.path.display(),
line_number,
self.column.ordinal(),
width = line_number_width
)?;
writeln!(
f,
"{:width$} {}",
"",
color.context().paint("│"),
width = line_number_width
)?;
writeln!(
f,
"{} {space_line}",
color.context().paint(&format!("{line_number} │"))
)?;
write!(
f,
"{:width$} {}",
"",
color.context().paint("│"),
width = line_number_width
)?;
write!(
f,
" {0:1$}{2}{3:^<4$}{5}",
"",
space_column,
color.prefix(),
"",
space_width.max(1),
color.suffix()
)?;
}
None => {
if self.offset != self.src.len() {
write!(
f,
"internal error: Error has invalid line number: {line_number}"
)?;
}
}
}
Ok(())
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/compiler.rs | src/compiler.rs | use super::*;
pub(crate) struct Compiler;
impl Compiler {
pub(crate) fn compile<'src>(
config: &Config,
loader: &'src Loader,
root: &Path,
) -> RunResult<'src, Compilation<'src>> {
let mut asts = HashMap::<PathBuf, Ast>::new();
let mut loaded = Vec::new();
let mut paths = HashMap::<PathBuf, PathBuf>::new();
let mut srcs = HashMap::<PathBuf, &str>::new();
let mut stack = Vec::new();
stack.push(Source::root(root));
while let Some(current) = stack.pop() {
if paths.contains_key(¤t.path) {
continue;
}
let (relative, src) = loader.load(root, ¤t.path)?;
loaded.push(relative.into());
let tokens = Lexer::lex(relative, src)?;
let mut ast = Parser::parse(
current.file_depth,
¤t.import_offsets,
current.namepath.as_ref(),
&tokens,
¤t.working_directory,
)?;
paths.insert(current.path.clone(), relative.into());
srcs.insert(current.path.clone(), src);
for item in &mut ast.items {
match item {
Item::Module {
absolute,
name,
optional,
relative,
..
} => {
let parent = current.path.parent().unwrap();
let relative = relative
.as_ref()
.map(|relative| Self::expand_tilde(&relative.cooked))
.transpose()?;
let import = Self::find_module_file(parent, *name, relative.as_deref())?;
if let Some(import) = import {
if current.file_path.contains(&import) {
return Err(Error::CircularImport {
current: current.path,
import,
});
}
*absolute = Some(import.clone());
stack.push(current.module(*name, import));
} else if !*optional {
return Err(Error::MissingModuleFile { module: *name });
}
}
Item::Import {
relative,
absolute,
optional,
} => {
let import = current
.path
.parent()
.unwrap()
.join(Self::expand_tilde(&relative.cooked)?)
.lexiclean();
if import.is_file() {
if current.file_path.contains(&import) {
return Err(Error::CircularImport {
current: current.path,
import,
});
}
*absolute = Some(import.clone());
stack.push(current.import(import, relative.token.offset));
} else if !*optional {
return Err(Error::MissingImportFile {
path: relative.token,
});
}
}
_ => {}
}
}
asts.insert(current.path, ast.clone());
}
let justfile = Analyzer::analyze(&asts, config, None, &[], &loaded, None, &paths, false, root)?;
Ok(Compilation {
asts,
justfile,
root: root.into(),
srcs,
})
}
fn find_module_file<'src>(
parent: &Path,
module: Name<'src>,
path: Option<&Path>,
) -> RunResult<'src, Option<PathBuf>> {
let mut candidates = Vec::new();
if let Some(path) = path {
let full = parent.join(path);
if full.is_file() {
return Ok(Some(full));
}
candidates.push((path.join("mod.just"), true));
for name in search::JUSTFILE_NAMES {
candidates.push((path.join(name), false));
}
} else {
candidates.push((format!("{module}.just").into(), true));
candidates.push((format!("{module}/mod.just").into(), true));
for name in search::JUSTFILE_NAMES {
candidates.push((format!("{module}/{name}").into(), false));
}
}
let mut grouped = BTreeMap::<PathBuf, Vec<(PathBuf, bool)>>::new();
for (candidate, case_sensitive) in candidates {
let candidate = parent.join(candidate).lexiclean();
grouped
.entry(candidate.parent().unwrap().into())
.or_default()
.push((candidate, case_sensitive));
}
let mut found = Vec::new();
for (directory, candidates) in grouped {
let entries = match fs::read_dir(&directory) {
Ok(entries) => entries,
Err(io_error) => {
if io_error.kind() == io::ErrorKind::NotFound {
continue;
}
return Err(
SearchError::Io {
io_error,
directory,
}
.into(),
);
}
};
for entry in entries {
let entry = entry.map_err(|io_error| SearchError::Io {
io_error,
directory: directory.clone(),
})?;
if let Some(name) = entry.file_name().to_str() {
for (candidate, case_sensitive) in &candidates {
let candidate_name = candidate.file_name().unwrap().to_str().unwrap();
let eq = if *case_sensitive {
name == candidate_name
} else {
name.eq_ignore_ascii_case(candidate_name)
};
if eq {
found.push(candidate.parent().unwrap().join(name));
}
}
}
}
}
if found.len() > 1 {
found.sort();
Err(Error::AmbiguousModuleFile {
found: found
.into_iter()
.map(|found| found.strip_prefix(parent).unwrap().into())
.collect(),
module,
})
} else {
Ok(found.into_iter().next())
}
}
fn expand_tilde(path: &str) -> RunResult<'static, PathBuf> {
Ok(if let Some(path) = path.strip_prefix("~/") {
dirs::home_dir()
.ok_or(Error::Homedir)?
.join(path.trim_start_matches('/'))
} else {
PathBuf::from(path)
})
}
#[cfg(test)]
pub(crate) fn test_compile(src: &str) -> RunResult<Justfile> {
let tokens = Lexer::test_lex(src)?;
let ast = Parser::parse(0, &[], None, &tokens, &PathBuf::new())?;
let root = PathBuf::from("justfile");
let mut asts: HashMap<PathBuf, Ast> = HashMap::new();
asts.insert(root.clone(), ast);
let mut paths: HashMap<PathBuf, PathBuf> = HashMap::new();
paths.insert(root.clone(), root.clone());
Analyzer::analyze(
&asts,
&Config::default(),
None,
&[],
&[],
None,
&paths,
false,
&root,
)
}
}
#[cfg(test)]
mod tests {
use {super::*, temptree::temptree};
#[test]
fn include_justfile() {
let justfile_a = r#"
# A comment at the top of the file
import "./justfile_b"
#some_recipe: recipe_b
some_recipe:
echo "some recipe"
"#;
let justfile_b = r#"import "./subdir/justfile_c"
recipe_b: recipe_c
echo "recipe b"
"#;
let justfile_c = r#"recipe_c:
echo "recipe c"
"#;
let tmp = temptree! {
justfile: justfile_a,
justfile_b: justfile_b,
subdir: {
justfile_c: justfile_c
}
};
let loader = Loader::new();
let justfile_a_path = tmp.path().join("justfile");
let compilation = Compiler::compile(&Config::default(), &loader, &justfile_a_path).unwrap();
assert_eq!(compilation.root_src(), justfile_a);
}
#[test]
fn recursive_includes_fail() {
let tmp = temptree! {
justfile: "import './subdir/b'\na: b",
subdir: {
b: "import '../justfile'\nb:"
}
};
let loader = Loader::new();
let justfile_a_path = tmp.path().join("justfile");
let loader_output =
Compiler::compile(&Config::default(), &loader, &justfile_a_path).unwrap_err();
assert_matches!(loader_output, Error::CircularImport { current, import }
if current == tmp.path().join("subdir").join("b").lexiclean() &&
import == tmp.path().join("justfile").lexiclean()
);
}
#[test]
fn find_module_file() {
#[track_caller]
fn case(path: Option<&str>, files: &[&str], expected: Result<Option<&str>, &[&str]>) {
let module = Name {
token: Token {
column: 0,
kind: TokenKind::Identifier,
length: 3,
line: 0,
offset: 0,
path: Path::new(""),
src: "foo",
},
};
let tempdir = tempfile::tempdir().unwrap();
for file in files {
if let Some(parent) = Path::new(file).parent() {
fs::create_dir_all(tempdir.path().join(parent)).unwrap();
}
fs::write(tempdir.path().join(file), "").unwrap();
}
let actual = Compiler::find_module_file(tempdir.path(), module, path.map(Path::new));
match expected {
Err(expected) => match actual.unwrap_err() {
Error::AmbiguousModuleFile { found, .. } => {
assert_eq!(
found,
expected
.iter()
.map(|expected| expected.replace('/', std::path::MAIN_SEPARATOR_STR).into())
.collect::<Vec<PathBuf>>()
);
}
_ => panic!("unexpected error"),
},
Ok(Some(expected)) => assert_eq!(
actual.unwrap().unwrap(),
tempdir
.path()
.join(expected.replace('/', std::path::MAIN_SEPARATOR_STR))
),
Ok(None) => assert_eq!(actual.unwrap(), None),
}
}
case(None, &["foo.just"], Ok(Some("foo.just")));
case(None, &["FOO.just"], Ok(None));
case(None, &["foo/mod.just"], Ok(Some("foo/mod.just")));
case(None, &["foo/MOD.just"], Ok(None));
case(None, &["foo/justfile"], Ok(Some("foo/justfile")));
case(None, &["foo/JUSTFILE"], Ok(Some("foo/JUSTFILE")));
case(None, &["foo/.justfile"], Ok(Some("foo/.justfile")));
case(None, &["foo/.JUSTFILE"], Ok(Some("foo/.JUSTFILE")));
case(
None,
&["foo/.justfile", "foo/justfile"],
Err(&["foo/.justfile", "foo/justfile"]),
);
case(None, &["foo/JUSTFILE"], Ok(Some("foo/JUSTFILE")));
case(Some("bar"), &["bar"], Ok(Some("bar")));
case(Some("bar"), &["bar/mod.just"], Ok(Some("bar/mod.just")));
case(Some("bar"), &["bar/justfile"], Ok(Some("bar/justfile")));
case(Some("bar"), &["bar/JUSTFILE"], Ok(Some("bar/JUSTFILE")));
case(Some("bar"), &["bar/.justfile"], Ok(Some("bar/.justfile")));
case(Some("bar"), &["bar/.JUSTFILE"], Ok(Some("bar/.JUSTFILE")));
case(
Some("bar"),
&["bar/justfile", "bar/mod.just"],
Err(&["bar/justfile", "bar/mod.just"]),
);
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/platform/unix.rs | src/platform/unix.rs | use super::*;
impl PlatformInterface for Platform {
fn make_shebang_command(
_config: &Config,
path: &Path,
_shebang: Shebang,
working_directory: Option<&Path>,
) -> Result<Command, OutputError> {
// shebang scripts can be executed directly on unix
let mut command = Command::new(path);
if let Some(working_directory) = working_directory {
command.current_dir(working_directory);
}
Ok(command)
}
fn set_execute_permission(path: &Path) -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
// get current permissions
let mut permissions = fs::metadata(path)?.permissions();
// set the execute bit
let current_mode = permissions.mode();
permissions.set_mode(current_mode | 0o100);
// set the new permissions
fs::set_permissions(path, permissions)
}
fn signal_from_exit_status(exit_status: ExitStatus) -> Option<i32> {
use std::os::unix::process::ExitStatusExt;
exit_status.signal()
}
fn convert_native_path(
_config: &Config,
_working_directory: &Path,
path: &Path,
) -> FunctionResult {
path
.to_str()
.map(str::to_string)
.ok_or_else(|| String::from("Error getting current directory: unicode decode error"))
}
fn install_signal_handler<T: Fn(Signal) + Send + 'static>(handler: T) -> RunResult<'static> {
let signals = crate::signals::Signals::new()?;
std::thread::Builder::new()
.name("signal handler".into())
.spawn(move || {
for signal in signals {
match signal {
Ok(signal) => handler(signal),
Err(io_error) => eprintln!("warning: I/O error reading from signal pipe: {io_error}"),
}
}
})
.map_err(|io_error| Error::SignalHandlerSpawnThread { io_error })?;
Ok(())
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/src/platform/windows.rs | src/platform/windows.rs | use super::*;
impl PlatformInterface for Platform {
fn make_shebang_command(
config: &Config,
path: &Path,
shebang: Shebang,
working_directory: Option<&Path>,
) -> Result<Command, OutputError> {
use std::borrow::Cow;
// If the path contains forward slashes…
let command = if shebang.interpreter.contains('/') {
// …translate path to the interpreter from unix style to windows style.
let mut cygpath = Command::new(&config.cygpath);
if let Some(working_directory) = working_directory {
cygpath.current_dir(working_directory);
}
cygpath
.arg("--windows")
.arg(shebang.interpreter)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
Cow::Owned(cygpath.output_guard_stdout()?)
} else {
// …otherwise use it as-is.
Cow::Borrowed(shebang.interpreter)
};
let mut cmd = Command::new(command.as_ref());
if let Some(working_directory) = working_directory {
cmd.current_dir(working_directory);
}
if let Some(argument) = shebang.argument {
cmd.arg(argument);
}
cmd.arg(path);
Ok(cmd)
}
fn set_execute_permission(_path: &Path) -> io::Result<()> {
// it is not necessary to set an execute permission on a script on windows, so
// this is a nop
Ok(())
}
fn signal_from_exit_status(_exit_status: process::ExitStatus) -> Option<i32> {
// The rust standard library does not expose a way to extract a signal from a
// windows process exit status, so just return None
None
}
fn convert_native_path(config: &Config, working_directory: &Path, path: &Path) -> FunctionResult {
// Translate path from windows style to unix style
let mut cygpath = Command::new(&config.cygpath);
cygpath
.current_dir(working_directory)
.arg("--unix")
.arg(path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
match cygpath.output_guard_stdout() {
Ok(shell_path) => Ok(shell_path),
Err(_) => path
.to_str()
.map(str::to_string)
.ok_or_else(|| String::from("Error getting current directory: unicode decode error")),
}
}
fn install_signal_handler<T: Fn(Signal) + Send + 'static>(handler: T) -> RunResult<'static> {
ctrlc::set_handler(move || handler(Signal::Interrupt))
.map_err(|source| Error::SignalHandlerInstall { source })
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/allow_duplicate_recipes.rs | tests/allow_duplicate_recipes.rs | use super::*;
#[test]
fn allow_duplicate_recipes() {
Test::new()
.justfile(
"
b:
echo foo
b:
echo bar
set allow-duplicate-recipes
",
)
.stdout("bar\n")
.stderr("echo bar\n")
.run();
}
#[test]
fn allow_duplicate_recipes_with_args() {
Test::new()
.justfile(
"
b a:
echo foo
b c d:
echo bar {{c}} {{d}}
set allow-duplicate-recipes
",
)
.args(["b", "one", "two"])
.stdout("bar one two\n")
.stderr("echo bar one two\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/quiet.rs | tests/quiet.rs | use super::*;
#[test]
fn no_stdout() {
Test::new()
.arg("--quiet")
.justfile(
r"
default:
@echo hello
",
)
.run();
}
#[test]
fn stderr() {
Test::new()
.arg("--quiet")
.justfile(
r"
default:
@echo hello 1>&2
",
)
.run();
}
#[test]
fn command_echoing() {
Test::new()
.arg("--quiet")
.justfile(
r"
default:
exit
",
)
.run();
}
#[test]
fn error_messages() {
Test::new()
.arg("--quiet")
.justfile(
r"
default:
exit 100
",
)
.status(100)
.run();
}
#[test]
fn assignment_backtick_stderr() {
Test::new()
.arg("--quiet")
.justfile(
r"
a := `echo hello 1>&2`
default:
exit 100
",
)
.status(100)
.run();
}
#[test]
fn interpolation_backtick_stderr() {
Test::new()
.arg("--quiet")
.justfile(
r"
default:
echo `echo hello 1>&2`
exit 100
",
)
.status(100)
.run();
}
#[test]
fn choose_none() {
Test::new()
.arg("--choose")
.arg("--quiet")
.justfile("")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn choose_invocation() {
Test::new()
.arg("--choose")
.arg("--quiet")
.arg("--shell")
.arg("asdfasdfasfdasdfasdfadsf")
.justfile("foo:")
.shell(false)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn choose_status() {
Test::new()
.arg("--choose")
.arg("--quiet")
.arg("--chooser")
.arg("/usr/bin/env false")
.justfile("foo:")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn edit_invocation() {
Test::new()
.arg("--edit")
.arg("--quiet")
.env("VISUAL", "adsfasdfasdfadsfadfsaf")
.justfile("foo:")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn edit_status() {
Test::new()
.arg("--edit")
.arg("--quiet")
.env("VISUAL", "false")
.justfile("foo:")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn init_exists() {
Test::new()
.arg("--init")
.arg("--quiet")
.justfile("foo:")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn show_missing() {
Test::new()
.arg("--show")
.arg("bar")
.arg("--quiet")
.justfile("foo:")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn quiet_shebang() {
Test::new()
.arg("--quiet")
.justfile(
"
@foo:
#!/bin/sh
",
)
.run();
}
#[test]
fn no_quiet_setting() {
Test::new()
.justfile(
"
foo:
echo FOO
",
)
.stdout("FOO\n")
.stderr("echo FOO\n")
.run();
}
#[test]
fn quiet_setting() {
Test::new()
.justfile(
"
set quiet
foo:
echo FOO
",
)
.stdout("FOO\n")
.run();
}
#[test]
fn quiet_setting_with_no_quiet_attribute() {
Test::new()
.justfile(
"
set quiet
[no-quiet]
foo:
echo FOO
",
)
.stdout("FOO\n")
.stderr("echo FOO\n")
.run();
}
#[test]
fn quiet_setting_with_quiet_recipe() {
Test::new()
.justfile(
"
set quiet
@foo:
echo FOO
",
)
.stdout("FOO\n")
.run();
}
#[test]
fn quiet_setting_with_quiet_line() {
Test::new()
.justfile(
"
set quiet
foo:
@echo FOO
",
)
.stdout("FOO\n")
.run();
}
#[test]
fn quiet_setting_with_no_quiet_attribute_and_quiet_recipe() {
Test::new()
.justfile(
"
set quiet
[no-quiet]
@foo:
echo FOO
",
)
.stdout("FOO\n")
.run();
}
#[test]
fn quiet_setting_with_no_quiet_attribute_and_quiet_line() {
Test::new()
.justfile(
"
set quiet
[no-quiet]
foo:
@echo FOO
",
)
.stdout("FOO\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/byte_order_mark.rs | tests/byte_order_mark.rs | use super::*;
#[test]
fn ignore_leading_byte_order_mark() {
Test::new()
.justfile(
"
\u{feff}foo:
echo bar
",
)
.stderr("echo bar\n")
.stdout("bar\n")
.run();
}
#[test]
fn non_leading_byte_order_mark_produces_error() {
Test::new()
.justfile(
"
foo:
echo bar
\u{feff}
",
)
.stderr(
"
error: Expected \'@\', \'[\', comment, end of file, end of line, or identifier, but found byte order mark
——▶ justfile:3:1
│
3 │ \u{feff}
│ ^
")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn dont_mention_byte_order_mark_in_errors() {
Test::new()
.justfile("{")
.stderr(
"
error: Expected '@', '[', comment, end of file, end of line, or identifier, but found '{'
——▶ justfile:1:1
│
1 │ {
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/misc.rs | tests/misc.rs | use super::*;
#[test]
fn alias_listing() {
Test::new()
.arg("--list")
.justfile(
"
foo:
echo foo
alias f := foo
",
)
.stdout(
"
Available recipes:
foo # [alias: f]
",
)
.run();
}
#[test]
fn alias_listing_with_doc() {
Test::new()
.justfile(
"
# foo command
foo:
echo foo
alias f := foo
",
)
.arg("--list")
.stdout(
"
Available recipes:
foo # foo command [alias: f]
",
)
.run();
}
#[test]
fn alias_listing_multiple_aliases() {
Test::new()
.arg("--list")
.justfile("foo:\n echo foo\nalias f := foo\nalias fo := foo")
.stdout(
"
Available recipes:
foo # [aliases: f, fo]
",
)
.run();
}
#[test]
fn alias_listing_parameters() {
Test::new()
.args(["--list"])
.justfile("foo PARAM='foo':\n echo {{PARAM}}\nalias f := foo")
.stdout(
"
Available recipes:
foo PARAM='foo' # [alias: f]
",
)
.run();
}
#[test]
fn alias_listing_private() {
Test::new()
.arg("--list")
.justfile("foo PARAM='foo':\n echo {{PARAM}}\nalias _f := foo")
.stdout(
"
Available recipes:
foo PARAM='foo'
",
)
.run();
}
#[test]
fn alias() {
Test::new()
.arg("f")
.justfile("foo:\n echo foo\nalias f := foo")
.stdout("foo\n")
.stderr("echo foo\n")
.run();
}
#[test]
fn alias_with_parameters() {
Test::new()
.arg("f")
.arg("bar")
.justfile("foo value='foo':\n echo {{value}}\nalias f := foo")
.stdout("bar\n")
.stderr("echo bar\n")
.run();
}
#[test]
fn bad_setting() {
Test::new()
.justfile(
"
set foo
",
)
.stderr(
"
error: Unknown setting `foo`
——▶ justfile:1:5
│
1 │ set foo
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn bad_setting_with_keyword_name() {
Test::new()
.justfile(
"
set if := 'foo'
",
)
.stderr(
"
error: Unknown setting `if`
——▶ justfile:1:5
│
1 │ set if := 'foo'
│ ^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn alias_with_dependencies() {
Test::new()
.arg("b")
.justfile("foo:\n echo foo\nbar: foo\nalias b := bar")
.stdout("foo\n")
.stderr("echo foo\n")
.run();
}
#[test]
fn duplicate_alias() {
Test::new()
.justfile("alias foo := bar\nalias foo := baz\n")
.stderr(
"
error: Alias `foo` first defined on line 1 is redefined on line 2
——▶ justfile:2:7
│
2 │ alias foo := baz
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unknown_alias_target() {
Test::new()
.justfile("alias foo := bar\n")
.stderr(
"
error: Alias `foo` has an unknown target `bar`
——▶ justfile:1:7
│
1 │ alias foo := bar
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn alias_shadows_recipe() {
Test::new()
.justfile("bar:\n echo bar\nalias foo := bar\nfoo:\n echo foo")
.stderr(
"
error: Alias `foo` defined on line 3 is redefined as a recipe on line 4
——▶ justfile:4:1
│
4 │ foo:
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn default() {
Test::new()
.justfile("default:\n echo hello\nother: \n echo bar")
.stdout("hello\n")
.stderr("echo hello\n")
.run();
}
#[test]
fn quiet() {
Test::new()
.justfile("default:\n @echo hello")
.stdout("hello\n")
.run();
}
#[test]
fn verbose() {
Test::new()
.arg("--verbose")
.justfile("default:\n @echo hello")
.stdout("hello\n")
.stderr("===> Running recipe `default`...\necho hello\n")
.run();
}
#[test]
fn order() {
Test::new()
.arg("a")
.arg("d")
.justfile(
"
b: a
echo b
@mv a b
a:
echo a
@touch F
@touch a
d: c
echo d
@rm c
c: b
echo c
@mv b c",
)
.stdout("a\nb\nc\nd\n")
.stderr("echo a\necho b\necho c\necho d\n")
.run();
}
#[test]
fn select() {
Test::new()
.arg("d")
.arg("c")
.justfile("b:\n @echo b\na:\n @echo a\nd:\n @echo d\nc:\n @echo c")
.stdout("d\nc\n")
.run();
}
#[test]
fn print() {
Test::new()
.arg("d")
.arg("c")
.justfile("b:\n echo b\na:\n echo a\nd:\n echo d\nc:\n echo c")
.stdout("d\nc\n")
.stderr("echo d\necho c\n")
.run();
}
#[test]
fn status_passthrough() {
Test::new()
.arg("recipe")
.justfile(
"
hello:
recipe:
@exit 100",
)
.stderr("error: Recipe `recipe` failed on line 5 with exit code 100\n")
.status(100)
.run();
}
#[test]
fn unknown_dependency() {
Test::new()
.justfile("bar:\nhello:\nfoo: bar baaaaaaaz hello")
.stderr(
"
error: Recipe `foo` has unknown dependency `baaaaaaaz`
——▶ justfile:3:10
│
3 │ foo: bar baaaaaaaz hello
│ ^^^^^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn backtick_success() {
Test::new()
.justfile("a := `printf Hello,`\nbar:\n printf '{{a + `printf ' world.'`}}'")
.stdout("Hello, world.")
.stderr("printf 'Hello, world.'\n")
.run();
}
#[test]
fn backtick_trimming() {
Test::new()
.justfile("a := `echo Hello,`\nbar:\n echo '{{a + `echo ' world.'`}}'")
.stdout("Hello, world.\n")
.stderr("echo 'Hello, world.'\n")
.run();
}
#[test]
fn backtick_code_assignment() {
Test::new()
.justfile("b := a\na := `exit 100`\nbar:\n echo '{{`exit 200`}}'")
.stderr(
"
error: Backtick failed with exit code 100
——▶ justfile:2:6
│
2 │ a := `exit 100`
│ ^^^^^^^^^^
",
)
.status(100)
.run();
}
#[test]
fn backtick_code_interpolation() {
Test::new()
.justfile("b := a\na := `echo hello`\nbar:\n echo '{{`exit 200`}}'")
.stderr(
"
error: Backtick failed with exit code 200
——▶ justfile:4:10
│
4 │ echo '{{`exit 200`}}'
│ ^^^^^^^^^^
",
)
.status(200)
.run();
}
#[test]
fn backtick_code_interpolation_mod() {
Test::new()
.justfile("f:\n 無{{`exit 200`}}")
.stderr(
"
error: Backtick failed with exit code 200
——▶ justfile:2:7
│
2 │ 無{{`exit 200`}}
│ ^^^^^^^^^^
",
)
.status(200)
.run();
}
#[test]
fn backtick_code_interpolation_tab() {
Test::new()
.justfile(
"
backtick-fail:
\techo {{`exit 200`}}
",
)
.stderr(
" error: Backtick failed with exit code 200
——▶ justfile:2:9
│
2 │ echo {{`exit 200`}}
│ ^^^^^^^^^^
",
)
.status(200)
.run();
}
#[test]
fn backtick_code_interpolation_tabs() {
Test::new()
.justfile(
"
backtick-fail:
\techo {{\t`exit 200`}}
",
)
.stderr(
"error: Backtick failed with exit code 200
——▶ justfile:2:10
│
2 │ echo {{ `exit 200`}}
│ ^^^^^^^^^^
",
)
.status(200)
.run();
}
#[test]
fn backtick_code_interpolation_inner_tab() {
Test::new()
.justfile(
"
backtick-fail:
\techo {{\t`exit\t\t200`}}
",
)
.stderr(
"
error: Backtick failed with exit code 200
——▶ justfile:2:10
│
2 │ echo {{ `exit 200`}}
│ ^^^^^^^^^^^^^^^^^
",
)
.status(200)
.run();
}
#[test]
fn backtick_code_interpolation_leading_emoji() {
Test::new()
.justfile(
"
backtick-fail:
\techo 😬{{`exit 200`}}
",
)
.stderr(
"
error: Backtick failed with exit code 200
——▶ justfile:2:13
│
2 │ echo 😬{{`exit 200`}}
│ ^^^^^^^^^^
",
)
.status(200)
.run();
}
#[test]
fn backtick_code_interpolation_unicode_hell() {
Test::new()
.justfile(
"
backtick-fail:
\techo \t\t\t😬鎌鼬{{\t\t`exit 200 # \t\t\tabc`}}\t\t\t😬鎌鼬
",
)
.stderr(
"
error: Backtick failed with exit code 200
——▶ justfile:2:24
│
2 │ echo 😬鎌鼬{{ `exit 200 # abc`}} 😬鎌鼬
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
",
)
.status(200)
.run();
}
#[test]
fn backtick_code_long() {
Test::new()
.justfile(
"
b := a
a := `echo hello`
bar:
echo '{{`exit 200`}}'
",
)
.stderr(
"
error: Backtick failed with exit code 200
——▶ justfile:10:10
│
10 │ echo '{{`exit 200`}}'
│ ^^^^^^^^^^
",
)
.status(200)
.run();
}
#[test]
fn shebang_backtick_failure() {
Test::new()
.justfile(
"foo:
#!/bin/sh
echo hello
echo {{`exit 123`}}",
)
.stderr(
"
error: Backtick failed with exit code 123
——▶ justfile:4:9
│
4 │ echo {{`exit 123`}}
│ ^^^^^^^^^^
",
)
.status(123)
.run();
}
#[test]
fn command_backtick_failure() {
Test::new()
.justfile(
"foo:
echo hello
echo {{`exit 123`}}",
)
.stdout("hello\n")
.stderr(
"
echo hello
error: Backtick failed with exit code 123
——▶ justfile:3:9
│
3 │ echo {{`exit 123`}}
│ ^^^^^^^^^^
",
)
.status(123)
.run();
}
#[test]
fn assignment_backtick_failure() {
Test::new()
.justfile(
"foo:
echo hello
echo {{`exit 111`}}
a := `exit 222`",
)
.stderr(
"
error: Backtick failed with exit code 222
——▶ justfile:4:6
│
4 │ a := `exit 222`
│ ^^^^^^^^^^
",
)
.status(222)
.run();
}
#[test]
fn unknown_override_options() {
Test::new()
.arg("--set")
.arg("foo")
.arg("bar")
.arg("--set")
.arg("baz")
.arg("bob")
.arg("--set")
.arg("a")
.arg("b")
.arg("a")
.arg("b")
.justfile(
"foo:
echo hello
echo {{`exit 111`}}
a := `exit 222`",
)
.status(EXIT_FAILURE)
.stderr(
"error: Variables `baz` and `foo` overridden on the command line but not present \
in justfile\n",
)
.run();
}
#[test]
fn unknown_override_args() {
Test::new()
.arg("foo=bar")
.arg("baz=bob")
.arg("a=b")
.arg("a")
.arg("b")
.justfile(
"foo:
echo hello
echo {{`exit 111`}}
a := `exit 222`",
)
.stderr(
"error: Variables `baz` and `foo` overridden on the command line but not present \
in justfile\n",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unknown_override_arg() {
Test::new()
.arg("foo=bar")
.arg("a=b")
.arg("a")
.arg("b")
.justfile(
"foo:
echo hello
echo {{`exit 111`}}
a := `exit 222`",
)
.stderr("error: Variable `foo` overridden on the command line but not present in justfile\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn overrides_first() {
Test::new()
.arg("foo=bar")
.arg("a=b")
.arg("recipe")
.arg("baz=bar")
.justfile(
r#"
foo := "foo"
a := "a"
baz := "baz"
recipe arg:
echo arg={{arg}}
echo {{foo + a + baz}}"#,
)
.stdout("arg=baz=bar\nbarbbaz\n")
.stderr("echo arg=baz=bar\necho barbbaz\n")
.run();
}
#[test]
fn overrides_not_evaluated() {
Test::new()
.arg("foo=bar")
.arg("a=b")
.arg("recipe")
.arg("baz=bar")
.justfile(
r#"
foo := `exit 1`
a := "a"
baz := "baz"
recipe arg:
echo arg={{arg}}
echo {{foo + a + baz}}"#,
)
.stdout("arg=baz=bar\nbarbbaz\n")
.stderr("echo arg=baz=bar\necho barbbaz\n")
.run();
}
#[test]
fn dry_run() {
Test::new()
.arg("--dry-run")
.arg("shebang")
.arg("command")
.justfile(
r"
var := `echo stderr 1>&2; echo backtick`
command:
@touch /this/is/not/a/file
{{var}}
echo {{`echo command interpolation`}}
shebang:
#!/bin/sh
touch /this/is/not/a/file
{{var}}
echo {{`echo shebang interpolation`}}",
)
.stderr(
"#!/bin/sh
touch /this/is/not/a/file
`echo stderr 1>&2; echo backtick`
echo `echo shebang interpolation`
touch /this/is/not/a/file
`echo stderr 1>&2; echo backtick`
echo `echo command interpolation`
",
)
.run();
}
#[test]
fn line_error_spacing() {
Test::new()
.justfile(
r"
^^^
",
)
.stderr(
"error: Unknown start of token '^'
——▶ justfile:10:1
│
10 │ ^^^
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn argument_single() {
Test::new()
.arg("foo")
.arg("ARGUMENT")
.justfile(
"
foo A:
echo {{A}}
",
)
.stdout("ARGUMENT\n")
.stderr("echo ARGUMENT\n")
.run();
}
#[test]
fn argument_multiple() {
Test::new()
.arg("foo")
.arg("ONE")
.arg("TWO")
.justfile(
"
foo A B:
echo A:{{A}} B:{{B}}
",
)
.stdout("A:ONE B:TWO\n")
.stderr("echo A:ONE B:TWO\n")
.run();
}
#[test]
fn argument_mismatch_more() {
Test::new()
.arg("foo")
.arg("ONE")
.arg("TWO")
.arg("THREE")
.stderr("error: Justfile does not contain recipe `THREE`\n")
.status(EXIT_FAILURE)
.justfile(
"
foo A B:
echo A:{{A}} B:{{B}}
",
)
.run();
}
#[test]
fn argument_mismatch_fewer() {
Test::new()
.arg("foo")
.arg("ONE")
.justfile(
"
foo A B:
echo A:{{A}} B:{{B}}
",
)
.stderr("error: Recipe `foo` got 1 positional argument but takes 2\nusage:\n just foo A B\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn argument_mismatch_more_with_default() {
Test::new()
.arg("foo")
.arg("ONE")
.arg("TWO")
.arg("THREE")
.justfile(
"
foo A B='B':
echo A:{{A}} B:{{B}}
",
)
.stderr("error: Justfile does not contain recipe `THREE`\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn argument_mismatch_fewer_with_default() {
Test::new()
.arg("foo")
.arg("bar")
.justfile(
"
foo A B C='C':
echo A:{{A}} B:{{B}} C:{{C}}
",
)
.stderr(
"
error: Recipe `foo` got 1 positional argument but takes at least 2
usage:
just foo A B [C]
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unknown_recipe() {
Test::new()
.arg("foo")
.justfile("hello:")
.stderr("error: Justfile does not contain recipe `foo`\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unknown_recipes() {
Test::new()
.arg("foo")
.arg("bar")
.justfile("hello:")
.stderr("error: Justfile does not contain recipe `foo`\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn color_always() {
Test::new()
.arg("--color")
.arg("always")
.justfile("b := a\na := `exit 100`\nbar:\n echo '{{`exit 200`}}'")
.status(100)
.stderr("\u{1b}[1;31merror\u{1b}[0m: \u{1b}[1mBacktick failed with exit code 100\u{1b}[0m\n \u{1b}[1;34m——▶\u{1b}[0m justfile:2:6\n \u{1b}[1;34m│\u{1b}[0m\n\u{1b}[1;34m2 │\u{1b}[0m a := `exit 100`\n \u{1b}[1;34m│\u{1b}[0m \u{1b}[1;31m^^^^^^^^^^\u{1b}[0m\n")
.run();
}
#[test]
fn color_never() {
Test::new()
.arg("--color")
.arg("never")
.justfile("b := a\na := `exit 100`\nbar:\n echo '{{`exit 200`}}'")
.stderr(
"error: Backtick failed with exit code 100
——▶ justfile:2:6
│
2 │ a := `exit 100`
│ ^^^^^^^^^^
",
)
.status(100)
.run();
}
#[test]
fn color_auto() {
Test::new()
.arg("--color")
.arg("auto")
.justfile("b := a\na := `exit 100`\nbar:\n echo '{{`exit 200`}}'")
.stderr(
"error: Backtick failed with exit code 100
——▶ justfile:2:6
│
2 │ a := `exit 100`
│ ^^^^^^^^^^
",
)
.status(100)
.run();
}
#[test]
fn colors_no_context() {
Test::new()
.arg("--color=always")
.stderr(
"\u{1b}[1;31merror\u{1b}[0m: \u{1b}[1m\
Recipe `recipe` failed on line 2 with exit code 100\u{1b}[0m\n",
)
.status(100)
.justfile(
"
recipe:
@exit 100",
)
.run();
}
#[test]
fn dump() {
Test::new()
.arg("--dump")
.justfile(
r"
# this recipe does something
recipe a b +d:
@exit 100",
)
.stdout(
"# this recipe does something
recipe a b +d:
@exit 100
",
)
.run();
}
#[test]
fn mixed_whitespace() {
Test::new()
.justfile("bar:\n\t echo hello")
.stderr(
"error: Found a mix of tabs and spaces in leading whitespace: `␉␠`
Leading whitespace may consist of tabs or spaces, but not both
——▶ justfile:2:1
│
2 │ echo hello
│ ^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn extra_leading_whitespace() {
Test::new()
.justfile("bar:\n\t\techo hello\n\t\t\techo goodbye")
.stderr(
"error: Recipe line has extra leading whitespace
——▶ justfile:3:3
│
3 │ echo goodbye
│ ^^^^^^^^^^^^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn inconsistent_leading_whitespace() {
Test::new()
.justfile("bar:\n\t\techo hello\n\t echo goodbye")
.stderr(
"error: Recipe line has inconsistent leading whitespace. \
Recipe started with `␉␉` but found line with `␉␠`
——▶ justfile:3:1
│
3 │ echo goodbye
│ ^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn required_after_default() {
Test::new()
.justfile("bar:\nhello baz arg='foo' bar:")
.stderr(
"error: Non-default parameter `bar` follows default parameter
——▶ justfile:2:21
│
2 │ hello baz arg='foo' bar:
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn required_after_plus_variadic() {
Test::new()
.justfile("bar:\nhello baz +arg bar:")
.stderr(
"error: Parameter `bar` follows variadic parameter
——▶ justfile:2:16
│
2 │ hello baz +arg bar:
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn required_after_star_variadic() {
Test::new()
.justfile("bar:\nhello baz *arg bar:")
.stderr(
"error: Parameter `bar` follows variadic parameter
——▶ justfile:2:16
│
2 │ hello baz *arg bar:
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn use_string_default() {
Test::new()
.arg("hello")
.arg("ABC")
.justfile(
r#"
bar:
hello baz arg="XYZ\t\" ":
echo '{{baz}}...{{arg}}'
"#,
)
.stdout("ABC...XYZ\t\"\t\n")
.stderr("echo 'ABC...XYZ\t\"\t'\n")
.run();
}
#[test]
fn use_raw_string_default() {
Test::new()
.arg("hello")
.arg("ABC")
.justfile(
r#"
bar:
hello baz arg='XYZ" ':
printf '{{baz}}...{{arg}}'
"#,
)
.stdout("ABC...XYZ\"\t")
.stderr("printf 'ABC...XYZ\"\t'\n")
.run();
}
#[test]
fn supply_use_default() {
Test::new()
.arg("hello")
.arg("0")
.arg("1")
.justfile(
r"
hello a b='B' c='C':
echo {{a}} {{b}} {{c}}
",
)
.stdout("0 1 C\n")
.stderr("echo 0 1 C\n")
.run();
}
#[test]
fn supply_defaults() {
Test::new()
.arg("hello")
.arg("0")
.arg("1")
.arg("2")
.justfile(
r"
hello a b='B' c='C':
echo {{a}} {{b}} {{c}}
",
)
.stdout("0 1 2\n")
.stderr("echo 0 1 2\n")
.run();
}
#[test]
fn list() {
Test::new()
.arg("--list")
.justfile(
r#"
# this does a thing
hello a b='B ' c='C':
echo {{a}} {{b}} {{c}}
# this comment will be ignored
a Z="\t z":
# this recipe will not appear
_private-recipe:
"#,
)
.stdout(
r#"
Available recipes:
a Z="\t z"
hello a b='B ' c='C' # this does a thing
"#,
)
.run();
}
#[test]
fn list_alignment() {
Test::new()
.arg("--list")
.justfile(
r#"
# this does a thing
hello a b='B ' c='C':
echo {{a}} {{b}} {{c}}
# something else
a Z="\t z":
# this recipe will not appear
_private-recipe:
"#,
)
.stdout(
r#"
Available recipes:
a Z="\t z" # something else
hello a b='B ' c='C' # this does a thing
"#,
)
.run();
}
#[test]
fn list_alignment_long() {
Test::new()
.arg("--list")
.justfile(
r#"
# this does a thing
hello a b='B ' c='C':
echo {{a}} {{b}} {{c}}
# this does another thing
x a b='B ' c='C':
echo {{a}} {{b}} {{c}}
# something else
this-recipe-is-very-very-very-very-very-very-very-very-important Z="\t z":
# this recipe will not appear
_private-recipe:
"#,
)
.stdout(
r#"
Available recipes:
hello a b='B ' c='C' # this does a thing
this-recipe-is-very-very-very-very-very-very-very-very-important Z="\t z" # something else
x a b='B ' c='C' # this does another thing
"#,
)
.run();
}
#[test]
fn list_sorted() {
Test::new()
.arg("--list")
.justfile(
r"
alias c := b
b:
a:
",
)
.stdout(
r"
Available recipes:
a
b # [alias: c]
",
)
.run();
}
#[test]
fn list_unsorted() {
Test::new()
.arg("--list")
.arg("--unsorted")
.justfile(
r"
alias c := b
b:
a:
",
)
.stdout(
r"
Available recipes:
b # [alias: c]
a
",
)
.run();
}
#[test]
fn list_heading() {
Test::new()
.arg("--list")
.arg("--list-heading")
.arg("Cool stuff…\n")
.justfile(
r"
a:
b:
",
)
.stdout(
r"
Cool stuff…
a
b
",
)
.run();
}
#[test]
fn list_prefix() {
Test::new()
.arg("--list")
.arg("--list-prefix")
.arg("····")
.justfile(
r"
a:
b:
",
)
.stdout(
r"
Available recipes:
····a
····b
",
)
.run();
}
#[test]
fn list_empty_prefix_and_heading() {
Test::new()
.arg("--list")
.arg("--list-heading")
.arg("")
.arg("--list-prefix")
.arg("")
.justfile(
r"
a:
b:
",
)
.stdout(
r"
a
b
",
)
.run();
}
#[test]
fn run_suggestion() {
Test::new()
.arg("hell")
.justfile("hello:")
.stderr("error: Justfile does not contain recipe `hell`\nDid you mean `hello`?\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn private_recipes_are_not_suggested() {
Test::new()
.arg("hell")
.justfile(
"
[private]
hello:
",
)
.stderr("error: Justfile does not contain recipe `hell`\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn alias_suggestion() {
Test::new()
.arg("hell")
.justfile(
"
alias hello := bar
bar:
",
)
.stderr(
"error: Justfile does not contain recipe `hell`\nDid you mean `hello`, an alias for `bar`?\n",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn private_aliases_are_not_suggested() {
Test::new()
.arg("hell")
.justfile(
"
[private]
alias hello := bar
bar:
",
)
.stderr("error: Justfile does not contain recipe `hell`\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn line_continuation_with_space() {
Test::new()
.justfile(
r"
foo:
echo a\
b \
c
",
)
.stdout("ab c\n")
.stderr("echo ab c\n")
.run();
}
#[test]
fn line_continuation_with_quoted_space() {
Test::new()
.justfile(
r"
foo:
echo 'a\
b \
c'
",
)
.stdout("ab c\n")
.stderr("echo 'ab c'\n")
.run();
}
#[test]
fn line_continuation_no_space() {
Test::new()
.justfile(
r"
foo:
echo a\
b\
c
",
)
.stdout("abc\n")
.stderr("echo abc\n")
.run();
}
#[test]
fn infallible_command() {
Test::new()
.justfile(
r"
infallible:
-exit 101
",
)
.stderr("exit 101\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn infallible_with_failing() {
Test::new()
.justfile(
r"
infallible:
-exit 101
exit 202
",
)
.stderr(
r"exit 101
exit 202
error: Recipe `infallible` failed on line 3 with exit code 202
",
)
.status(202)
.run();
}
#[test]
fn quiet_recipe() {
Test::new()
.justfile(
r"
@quiet:
# a
# b
@echo c
",
)
.stdout("c\n")
.stderr("echo c\n")
.run();
}
#[test]
fn quiet_shebang_recipe() {
Test::new()
.justfile(
r"
@quiet:
#!/bin/sh
echo hello
",
)
.stdout("hello\n")
.stderr("#!/bin/sh\necho hello\n")
.run();
}
#[test]
fn complex_dependencies() {
Test::new()
.arg("b")
.justfile(
r"
a: b
b:
c: b a
",
)
.run();
}
#[test]
fn unknown_function_in_assignment() {
Test::new()
.arg("bar")
.justfile(
r#"foo := foo() + "hello"
bar:"#,
)
.stderr(
r#"error: Call to unknown function `foo`
——▶ justfile:1:8
│
1 │ foo := foo() + "hello"
│ ^^^
"#,
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn dependency_takes_arguments_exact() {
Test::new()
.arg("b")
.justfile(
"
a FOO:
b: a
",
)
.stderr(
"error: Dependency `a` got 0 arguments but takes 1 argument
——▶ justfile:2:4
│
2 │ b: a
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn dependency_takes_arguments_at_least() {
Test::new()
.arg("b")
.justfile(
"
a FOO LUZ='hello':
b: a
",
)
.stderr(
"error: Dependency `a` got 0 arguments but takes at least 1 argument
——▶ justfile:2:4
│
2 │ b: a
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn dependency_takes_arguments_at_most() {
Test::new()
.arg("b")
.justfile(
"
a FOO LUZ='hello':
b: (a '0' '1' '2')
",
)
.stderr(
"error: Dependency `a` got 3 arguments but takes at most 2 arguments
——▶ justfile:2:5
│
2 │ b: (a '0' '1' '2')
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn duplicate_parameter() {
Test::new()
.arg("a")
.justfile("a foo foo:")
.stderr(
"error: Recipe `a` has duplicate parameter `foo`
——▶ justfile:1:7
│
1 │ a foo foo:
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn duplicate_recipe() {
Test::new()
.arg("b")
.justfile("b:\nb:")
.stderr(
"error: Recipe `b` first defined on line 1 is redefined on line 2
——▶ justfile:2:1
│
2 │ b:
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn duplicate_variable() {
Test::new()
.arg("foo")
.justfile("a := 'hello'\na := 'hello'\nfoo:")
.status(EXIT_FAILURE)
.stderr(
"error: Variable `a` has multiple definitions
——▶ justfile:2:1
│
2 │ a := 'hello'
│ ^
",
)
.run();
}
#[test]
fn unexpected_token_in_dependency_position() {
Test::new()
.arg("foo")
.justfile("foo: 'bar'")
.stderr(
"error: Expected '&&', comment, end of file, end of line, \
identifier, or '(', but found string
——▶ justfile:1:6
│
1 │ foo: 'bar'
│ ^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unexpected_token_after_name() {
Test::new()
.arg("foo")
.justfile("foo 'bar'")
.stderr(
"error: Expected '*', ':', '$', identifier, or '+', but found string
——▶ justfile:1:5
│
1 │ foo 'bar'
│ ^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn self_dependency() {
Test::new()
.arg("a")
.justfile("a: a")
.stderr(
"error: Recipe `a` depends on itself
——▶ justfile:1:4
│
1 │ a: a
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn long_circular_recipe_dependency() {
Test::new()
.arg("a")
.justfile("a: b\nb: c\nc: d\nd: a")
.stderr(
"error: Recipe `d` has circular dependency `a -> b -> c -> d -> a`
——▶ justfile:4:4
│
4 │ d: a
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn variable_self_dependency() {
Test::new()
.arg("a")
.justfile("z := z\na:")
.stderr(
"error: Variable `z` is defined in terms of itself
——▶ justfile:1:1
│
1 │ z := z
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn variable_circular_dependency() {
Test::new()
.arg("a")
.justfile("x := y\ny := z\nz := x\na:")
.status(EXIT_FAILURE)
.stderr(
"error: Variable `x` depends on its own value: `x -> y -> z -> x`
——▶ justfile:1:1
│
1 │ x := y
│ ^
",
)
.run();
}
#[test]
fn variable_circular_dependency_with_additional_variable() {
Test::new()
.arg("a")
.justfile(
"
a := ''
x := y
y := x
a:
",
)
.stderr(
"error: Variable `x` depends on its own value: `x -> y -> x`
——▶ justfile:2:1
│
2 │ x := y
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn plus_variadic_recipe() {
Test::new()
.arg("a")
.arg("0")
.arg("1")
.arg("2")
.arg("3")
.arg(" 4 ")
.justfile(
"
a x y +z:
echo {{x}} {{y}} {{z}}
",
)
.stdout("0 1 2 3 4\n")
.stderr("echo 0 1 2 3 4 \n")
.run();
}
#[test]
fn plus_variadic_ignore_default() {
Test::new()
.arg("a")
.arg("0")
.arg("1")
.arg("2")
.arg("3")
.arg(" 4 ")
.justfile(
"
a x y +z='HELLO':
echo {{x}} {{y}} {{z}}
",
)
.stdout("0 1 2 3 4\n")
.stderr("echo 0 1 2 3 4 \n")
.run();
}
#[test]
fn plus_variadic_use_default() {
Test::new()
.arg("a")
.arg("0")
.arg("1")
.justfile(
"
a x y +z='HELLO':
echo {{x}} {{y}} {{z}}
",
)
.stdout("0 1 HELLO\n")
.stderr("echo 0 1 HELLO\n")
.run();
}
#[test]
fn plus_variadic_too_few() {
Test::new()
.arg("a")
.arg("0")
.arg("1")
.justfile(
"
a x y +z:
echo {{x}} {{y}} {{z}}
",
)
.stderr(
"
error: Recipe `a` got 2 positional arguments but takes at least 3
usage:
just a x y z...
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn star_variadic_recipe() {
Test::new()
.arg("a")
.arg("0")
.arg("1")
.arg("2")
.arg("3")
.arg(" 4 ")
.justfile(
"
a x y *z:
echo {{x}} {{y}} {{z}}
",
)
.stdout("0 1 2 3 4\n")
.stderr("echo 0 1 2 3 4 \n")
.run();
}
#[test]
fn star_variadic_none() {
Test::new()
.arg("a")
.arg("0")
.arg("1")
.justfile(
"
a x y *z:
echo {{x}} {{y}} {{z}}
",
)
.stdout("0 1\n")
.stderr("echo 0 1 \n")
.run();
}
#[test]
fn star_variadic_ignore_default() {
Test::new()
.arg("a")
.arg("0")
.arg("1")
.arg("2")
.arg("3")
.arg(" 4 ")
.justfile(
"
a x y *z='HELLO':
echo {{x}} {{y}} {{z}}
",
)
.stdout("0 1 2 3 4\n")
.stderr("echo 0 1 2 3 4 \n")
.run();
}
#[test]
fn star_variadic_use_default() {
Test::new()
.arg("a")
.arg("0")
.arg("1")
.justfile(
"
a x y *z='HELLO':
echo {{x}} {{y}} {{z}}
",
)
.stdout("0 1 HELLO\n")
.stderr("echo 0 1 HELLO\n")
.run();
}
#[test]
fn star_then_plus_variadic() {
Test::new()
.justfile(
"
foo *a +b:
echo {{a}} {{b}}
",
)
.stderr(
"error: Expected \':\' or \'=\', but found \'+\'
——▶ justfile:1:8
│
1 │ foo *a +b:
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn plus_then_star_variadic() {
Test::new()
.justfile(
"
foo +a *b:
echo {{a}} {{b}}
",
)
.stderr(
"error: Expected \':\' or \'=\', but found \'*\'
——▶ justfile:1:8
│
1 │ foo +a *b:
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn argument_grouping() {
Test::new()
.arg("BAR")
.arg("0")
.arg("FOO")
.arg("1")
.arg("2")
.arg("BAZ")
.arg("3")
.arg("4")
.arg("5")
.justfile(
"
FOO A B='blarg':
echo foo: {{A}} {{B}}
BAR X:
echo bar: {{X}}
BAZ +Z:
echo baz: {{Z}}
",
)
.stdout("bar: 0\nfoo: 1 2\nbaz: 3 4 5\n")
.stderr("echo bar: 0\necho foo: 1 2\necho baz: 3 4 5\n")
.run();
}
#[test]
fn missing_second_dependency() {
Test::new()
.justfile(
"
x:
a: x y
",
)
.stderr(
"error: Recipe `a` has unknown dependency `y`
——▶ justfile:3:6
│
3 │ a: x y
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn list_colors() {
Test::new()
.arg("--color")
.arg("always")
.arg("--list")
.justfile(
"
# comment
a B C +D='hello':
echo {{B}} {{C}} {{D}}
",
)
.stdout(
"
Available recipes:
a \
\u{1b}[36mB\u{1b}[0m \u{1b}[36mC\u{1b}[0m \u{1b}[35m+\
\u{1b}[0m\u{1b}[36mD\u{1b}[0m=\u{1b}[32m'hello'\u{1b}[0m \
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | true |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/multibyte_char.rs | tests/multibyte_char.rs | use super::*;
#[test]
fn bugfix() {
Test::new().justfile("foo:\nx := '''ǩ'''").run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/ignore_comments.rs | tests/ignore_comments.rs | use super::*;
#[test]
fn ignore_comments_in_recipe() {
Test::new()
.justfile(
"
set ignore-comments
some_recipe:
# A recipe-internal comment
echo something-useful
",
)
.stdout("something-useful\n")
.stderr("echo something-useful\n")
.run();
}
#[test]
fn dont_ignore_comments_in_recipe_by_default() {
Test::new()
.justfile(
"
some_recipe:
# A recipe-internal comment
echo something-useful
",
)
.stdout("something-useful\n")
.stderr("# A recipe-internal comment\necho something-useful\n")
.run();
}
#[test]
fn ignore_recipe_comments_with_shell_setting() {
Test::new()
.justfile(
"
set shell := ['echo', '-n']
set ignore-comments
some_recipe:
# Alternate shells still ignore comments
echo something-useful
",
)
.stdout("something-useful\n")
.stderr("echo something-useful\n")
.run();
}
#[test]
fn continuations_with_echo_comments_false() {
Test::new()
.justfile(
"
set ignore-comments
some_recipe:
# Comment lines ignore line continuations \\
echo something-useful
",
)
.stdout("something-useful\n")
.stderr("echo something-useful\n")
.run();
}
#[test]
fn continuations_with_echo_comments_true() {
Test::new()
.justfile(
"
set ignore-comments := false
some_recipe:
# comment lines can be continued \\
echo something-useful
",
)
.stderr("# comment lines can be continued echo something-useful\n")
.run();
}
#[test]
fn dont_evaluate_comments() {
Test::new()
.justfile(
"
set ignore-comments
some_recipe:
# {{ error('foo') }}
",
)
.run();
}
#[test]
fn dont_analyze_comments() {
Test::new()
.justfile(
"
set ignore-comments
some_recipe:
# {{ bar }}
",
)
.run();
}
#[test]
fn comments_still_must_be_parsable_when_ignored() {
Test::new()
.justfile(
"
set ignore-comments
some_recipe:
# {{ foo bar }}
",
)
.stderr(
"
error: Expected '&&', '||', '}}', '(', '+', or '/', but found identifier
——▶ justfile:4:12
│
4 │ # {{ foo bar }}
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/test.rs | tests/test.rs | use {
super::*,
pretty_assertions::{assert_eq, StrComparison},
};
pub(crate) struct Output {
pub(crate) pid: u32,
pub(crate) stdout: String,
pub(crate) tempdir: TempDir,
}
#[must_use]
pub(crate) struct Test {
pub(crate) args: Vec<String>,
pub(crate) current_dir: PathBuf,
pub(crate) env: BTreeMap<String, String>,
pub(crate) expected_files: BTreeMap<PathBuf, Vec<u8>>,
pub(crate) justfile: Option<String>,
pub(crate) response: Option<Response>,
pub(crate) shell: bool,
pub(crate) status: i32,
pub(crate) stderr: String,
pub(crate) stderr_regex: Option<Regex>,
pub(crate) stdin: String,
pub(crate) stdout: String,
pub(crate) stdout_regex: Option<Regex>,
pub(crate) tempdir: TempDir,
pub(crate) test_round_trip: bool,
pub(crate) unindent_stdout: bool,
}
impl Test {
pub(crate) fn new() -> Self {
Self::with_tempdir(tempdir())
}
pub(crate) fn with_tempdir(tempdir: TempDir) -> Self {
Self {
args: Vec::new(),
current_dir: PathBuf::new(),
env: BTreeMap::new(),
expected_files: BTreeMap::new(),
justfile: Some(String::new()),
response: None,
shell: true,
status: EXIT_SUCCESS,
stderr: String::new(),
stderr_regex: None,
stdin: String::new(),
stdout: String::new(),
stdout_regex: None,
tempdir,
test_round_trip: true,
unindent_stdout: true,
}
}
pub(crate) fn arg(mut self, val: &str) -> Self {
self.args.push(val.to_owned());
self
}
pub(crate) fn args<'a>(mut self, args: impl AsRef<[&'a str]>) -> Self {
for arg in args.as_ref() {
self = self.arg(arg);
}
self
}
pub(crate) fn create_dir(self, path: impl AsRef<Path>) -> Self {
fs::create_dir_all(self.tempdir.path().join(path)).unwrap();
self
}
pub(crate) fn current_dir(mut self, path: impl AsRef<Path>) -> Self {
path.as_ref().clone_into(&mut self.current_dir);
self
}
pub(crate) fn env(mut self, key: &str, val: &str) -> Self {
self.env.insert(key.to_string(), val.to_string());
self
}
pub(crate) fn justfile(mut self, justfile: impl Into<String>) -> Self {
self.justfile = Some(justfile.into());
self
}
pub(crate) fn justfile_path(&self) -> PathBuf {
self.tempdir.path().join("justfile")
}
#[cfg(unix)]
#[track_caller]
pub(crate) fn symlink(self, original: &str, link: &str) -> Self {
std::os::unix::fs::symlink(
self.tempdir.path().join(original),
self.tempdir.path().join(link),
)
.unwrap();
self
}
pub(crate) fn no_justfile(mut self) -> Self {
self.justfile = None;
self
}
pub(crate) fn response(mut self, response: Response) -> Self {
self.response = Some(response);
self.stdout_regex(".*")
}
pub(crate) fn shell(mut self, shell: bool) -> Self {
self.shell = shell;
self
}
pub(crate) fn status(mut self, exit_status: i32) -> Self {
self.status = exit_status;
self
}
pub(crate) fn stderr(mut self, stderr: impl Into<String>) -> Self {
self.stderr = stderr.into();
self
}
pub(crate) fn stderr_regex(mut self, stderr_regex: impl AsRef<str>) -> Self {
self.stderr_regex = Some(Regex::new(&format!("^(?s){}$", stderr_regex.as_ref())).unwrap());
self
}
pub(crate) fn stdin(mut self, stdin: impl Into<String>) -> Self {
self.stdin = stdin.into();
self
}
pub(crate) fn stdout(mut self, stdout: impl Into<String>) -> Self {
self.stdout = stdout.into();
self
}
pub(crate) fn stdout_regex(mut self, stdout_regex: impl AsRef<str>) -> Self {
self.stdout_regex = Some(Regex::new(&format!("(?s)^{}$", stdout_regex.as_ref())).unwrap());
self
}
pub(crate) fn test_round_trip(mut self, test_round_trip: bool) -> Self {
self.test_round_trip = test_round_trip;
self
}
pub(crate) fn tree(self, mut tree: Tree) -> Self {
tree.map(|_name, content| unindent(content));
tree.instantiate(self.tempdir.path()).unwrap();
self
}
pub(crate) fn unindent_stdout(mut self, unindent_stdout: bool) -> Self {
self.unindent_stdout = unindent_stdout;
self
}
pub(crate) fn write(self, path: impl AsRef<Path>, content: impl AsRef<[u8]>) -> Self {
let path = self.tempdir.path().join(path);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, content).unwrap();
self
}
pub(crate) fn make_executable(self, path: impl AsRef<Path>) -> Self {
let file = self.tempdir.path().join(path);
// Make sure it exists first, as a sanity check.
assert!(file.exists(), "file does not exist: {}", file.display());
// Windows uses file extensions to determine whether a file is executable.
// Other systems don't care. To keep these tests cross-platform, just make
// sure all executables end with ".exe" suffix.
assert!(
file.extension() == Some("exe".as_ref()),
"executable file does not end with .exe: {}",
file.display()
);
#[cfg(unix)]
{
let perms = std::os::unix::fs::PermissionsExt::from_mode(0o755);
fs::set_permissions(file, perms).unwrap();
}
self
}
pub(crate) fn expect_file(mut self, path: impl AsRef<Path>, content: impl AsRef<[u8]>) -> Self {
let path = path.as_ref();
self
.expected_files
.insert(path.into(), content.as_ref().into());
self
}
}
impl Test {
#[track_caller]
pub(crate) fn run(self) -> Output {
fn compare<T: PartialEq + Debug>(name: &str, have: T, want: T) -> bool {
let equal = have == want;
if !equal {
eprintln!("Bad {name}: {}", Comparison::new(&have, &want));
}
equal
}
fn compare_string(name: &str, have: &str, want: &str) -> bool {
let equal = have == want;
if !equal {
eprintln!("Bad {name}: {}", StrComparison::new(&have, &want));
}
equal
}
if let Some(justfile) = &self.justfile {
let justfile = unindent(justfile);
fs::write(self.justfile_path(), justfile).unwrap();
}
let stdout = if self.unindent_stdout {
unindent(&self.stdout)
} else {
self.stdout.clone()
};
let stderr = unindent(&self.stderr);
let mut command = Command::new(executable_path("just"));
if self.shell {
command.args(["--shell", "bash"]);
}
let mut child = command
.args(&self.args)
.envs(&self.env)
.current_dir(self.tempdir.path().join(&self.current_dir))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("just invocation failed");
let pid = child.id();
{
let mut stdin_handle = child.stdin.take().expect("failed to unwrap stdin handle");
stdin_handle
.write_all(self.stdin.as_bytes())
.expect("failed to write stdin to just process");
}
let output = child
.wait_with_output()
.expect("failed to wait for just process");
let output_stdout = str::from_utf8(&output.stdout).unwrap();
let output_stderr = str::from_utf8(&output.stderr).unwrap();
if let Some(ref stdout_regex) = self.stdout_regex {
assert!(
stdout_regex.is_match(output_stdout),
"Stdout regex mismatch:\n{output_stdout:?}\n!~=\n/{stdout_regex:?}/",
);
}
if let Some(ref stderr_regex) = self.stderr_regex {
assert!(
stderr_regex.is_match(output_stderr),
"Stderr regex mismatch:\n{output_stderr:?}\n!~=\n/{stderr_regex:?}/",
);
}
if !compare("status", output.status.code(), Some(self.status))
| (self.stdout_regex.is_none() && !compare_string("stdout", output_stdout, &stdout))
| (self.stderr_regex.is_none() && !compare_string("stderr", output_stderr, &stderr))
{
panic!("Output mismatch.");
}
if let Some(ref response) = self.response {
assert_eq!(
&serde_json::from_str::<Response>(output_stdout)
.expect("failed to deserialize stdout as response"),
response,
"response mismatch"
);
}
for (path, expected) in &self.expected_files {
let actual = fs::read(self.tempdir.path().join(path)).unwrap();
assert_eq!(
actual,
expected.as_slice(),
"mismatch for expected file at path {}",
path.display(),
);
}
if self.test_round_trip && self.status == EXIT_SUCCESS {
self.round_trip();
}
Output {
pid,
stdout: output_stdout.into(),
tempdir: self.tempdir,
}
}
fn round_trip(&self) {
let output = Command::new(executable_path("just"))
.current_dir(self.tempdir.path())
.arg("--dump")
.envs(&self.env)
.output()
.expect("just invocation failed");
assert!(
output.status.success(),
"dump failed: {} {:?}",
output.status,
output,
);
let dumped = String::from_utf8(output.stdout).unwrap();
let reparsed_path = self.tempdir.path().join("reparsed.just");
fs::write(&reparsed_path, &dumped).unwrap();
let output = Command::new(executable_path("just"))
.current_dir(self.tempdir.path())
.arg("--justfile")
.arg(&reparsed_path)
.arg("--dump")
.envs(&self.env)
.output()
.expect("just invocation failed");
assert!(output.status.success(), "reparse failed: {}", output.status);
let reparsed = String::from_utf8(output.stdout).unwrap();
assert_eq!(reparsed, dumped, "reparse mismatch");
}
}
pub fn assert_eval_eq(expression: &str, result: &str) {
Test::new()
.justfile(format!("x := {expression}"))
.args(["--evaluate", "x"])
.stdout(result)
.unindent_stdout(false)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/settings.rs | tests/settings.rs | use super::*;
#[test]
fn all_settings_allow_expressions() {
Test::new()
.justfile(
"
foo := 'hello'
set dotenv-filename := foo
set dotenv-path := foo
set script-interpreter := [foo, foo, foo]
set shell := [foo, foo, foo]
set tempdir := foo
set windows-shell := [foo, foo, foo]
set working-directory := foo
",
)
.arg("--summary")
.stdout(
"
",
)
.stderr("Justfile contains no recipes.\n")
.run();
}
#[test]
fn undefined_variable_in_working_directory() {
Test::new()
.justfile(
"
set working-directory := foo
",
)
.stderr(
"
error: Variable `foo` not defined
——▶ justfile:1:26
│
1 │ set working-directory := foo
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn undefined_variable_in_dotenv_filename() {
Test::new()
.justfile(
"
set dotenv-filename := foo
",
)
.stderr(
"
error: Variable `foo` not defined
——▶ justfile:1:24
│
1 │ set dotenv-filename := foo
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn undefined_variable_in_dotenv_path() {
Test::new()
.justfile(
"
set dotenv-path := foo
",
)
.stderr(
"
error: Variable `foo` not defined
——▶ justfile:1:20
│
1 │ set dotenv-path := foo
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn undefined_variable_in_tempdir() {
Test::new()
.justfile(
"
set tempdir := foo
",
)
.stderr(
"
error: Variable `foo` not defined
——▶ justfile:1:16
│
1 │ set tempdir := foo
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn undefined_variable_in_script_interpreter_command() {
Test::new()
.justfile(
"
set script-interpreter := [foo]
",
)
.stderr(
"
error: Variable `foo` not defined
——▶ justfile:1:28
│
1 │ set script-interpreter := [foo]
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn undefined_variable_in_script_interpreter_argument() {
Test::new()
.justfile(
"
set script-interpreter := ['foo', bar]
",
)
.stderr(
"
error: Variable `bar` not defined
——▶ justfile:1:35
│
1 │ set script-interpreter := ['foo', bar]
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn undefined_variable_in_shell_command() {
Test::new()
.justfile(
"
set shell := [foo]
",
)
.stderr(
"
error: Variable `foo` not defined
——▶ justfile:1:15
│
1 │ set shell := [foo]
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn undefined_variable_in_shell_argument() {
Test::new()
.justfile(
"
set shell := ['foo', bar]
",
)
.stderr(
"
error: Variable `bar` not defined
——▶ justfile:1:22
│
1 │ set shell := ['foo', bar]
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn undefined_variable_in_windows_shell_command() {
Test::new()
.justfile(
"
set windows-shell := [foo]
",
)
.stderr(
"
error: Variable `foo` not defined
——▶ justfile:1:23
│
1 │ set windows-shell := [foo]
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn undefined_variable_in_windows_shell_argument() {
Test::new()
.justfile(
"
set windows-shell := ['foo', bar]
",
)
.stderr(
"
error: Variable `bar` not defined
——▶ justfile:1:30
│
1 │ set windows-shell := ['foo', bar]
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn built_in_constant() {
Test::new()
.justfile(
"
set working-directory := HEX
@foo:
cat file.txt
",
)
.write("0123456789abcdef/file.txt", "bar")
.stdout("bar")
.run();
}
#[test]
fn variable() {
Test::new()
.justfile(
"
dir := 'bar'
set working-directory := dir
@foo:
cat file.txt
",
)
.write("bar/file.txt", "baz")
.arg("foo")
.stdout("baz")
.run();
}
#[test]
fn unused_non_const_assignments() {
Test::new()
.justfile(
"
baz := `pwd`
dir := 'bar'
set working-directory := dir
@foo:
cat file.txt
",
)
.write("bar/file.txt", "baz")
.arg("foo")
.stdout("baz")
.run();
}
#[test]
fn variable_with_override() {
Test::new()
.justfile(
"
dir := 'bar'
set working-directory := dir
@foo:
cat file.txt
",
)
.arg("dir=bob")
.write("bob/file.txt", "baz")
.arg("foo")
.stdout("baz")
.run();
}
#[test]
fn expression() {
Test::new()
.justfile(
"
dir := 'bar'
set working-directory := dir + '-bob'
@foo:
cat file.txt
",
)
.write("bar-bob/file.txt", "baz")
.arg("foo")
.stdout("baz")
.run();
}
#[test]
fn expression_with_override() {
Test::new()
.justfile(
"
dir := 'bar'
set working-directory := dir + '-bob'
@foo:
cat file.txt
",
)
.write("bob-bob/file.txt", "baz")
.args(["dir=bob", "foo"])
.stdout("baz")
.run();
}
#[test]
fn backtick() {
Test::new()
.justfile(
"
set working-directory := `pwd`
",
)
.stderr(
"
error: Cannot call backticks in const context
——▶ justfile:1:26
│
1 │ set working-directory := `pwd`
│ ^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn function_call() {
Test::new()
.justfile(
"
set working-directory := arch()
",
)
.stderr(
"
error: Cannot call functions in const context
——▶ justfile:1:26
│
1 │ set working-directory := arch()
│ ^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn non_const_variable() {
Test::new()
.justfile(
"
foo := `pwd`
set working-directory := foo
",
)
.stderr(
"
error: Cannot access non-const variable `foo` in const context
——▶ justfile:3:26
│
3 │ set working-directory := foo
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn assert() {
Test::new()
.justfile(
"
set working-directory := assert('foo' == 'bar', 'fail')
",
)
.stderr(
"
error: Assert failed: fail
——▶ justfile:1:26
│
1 │ set working-directory := assert('foo' == 'bar', 'fail')
│ ^^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn bad_regex() {
Test::new()
.justfile(
"
set working-directory := if '' =~ '(' {
'a'
} else {
'b'
}
",
)
.stderr(
"
error: regex parse error:
(
^
error: unclosed group
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn backtick_override() {
Test::new()
.justfile(
"
bar := `pwd`
set working-directory := bar
@foo:
cat file.txt
",
)
.test_round_trip(false)
.arg("bar=foo")
.write("foo/file.txt", "baz")
.arg("foo")
.stdout("baz")
.run();
}
#[test]
fn submodule_expression() {
Test::new()
.write(
"foo/mod.just",
"
dir := 'bar'
set working-directory := dir + '-baz'
foo:
@cat file.txt
",
)
.justfile(
"
dir := 'hello'
mod foo
",
)
.write("foo/bar-baz/file.txt", "ok")
.args(["foo", "foo"])
.stdout("ok")
.run();
}
#[test]
fn overrides_are_ignored_in_submodules() {
Test::new()
.write(
"foo.just",
"
dir := 'bar'
set working-directory := dir
foo:
@cat file.txt
",
)
.justfile(
"
mod foo
dir := 'root'
bob := 'baz'
",
)
.args(["dir=bob", "bob=foo", "foo::foo"])
.write("bar/file.txt", "ok")
.stdout("ok")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/dotenv.rs | tests/dotenv.rs | use super::*;
#[test]
fn dotenv() {
Test::new()
.write(".env", "KEY=ROOT")
.write("sub/.env", "KEY=SUB")
.write("sub/justfile", "default:\n\techo KEY=${KEY:-unset}")
.args(["sub/default"])
.stdout("KEY=unset\n")
.stderr("echo KEY=${KEY:-unset}\n")
.run();
}
#[test]
fn set_false() {
Test::new()
.justfile(
r#"
set dotenv-load := false
@foo:
if [ -n "${DOTENV_KEY+1}" ]; then echo defined; else echo undefined; fi
"#,
)
.write(".env", "DOTENV_KEY=dotenv-value")
.stdout("undefined\n")
.run();
}
#[test]
fn set_implicit() {
Test::new()
.justfile(
"
set dotenv-load
foo:
echo $DOTENV_KEY
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.stdout("dotenv-value\n")
.stderr("echo $DOTENV_KEY\n")
.run();
}
#[test]
fn set_true() {
Test::new()
.justfile(
"
set dotenv-load := true
foo:
echo $DOTENV_KEY
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.stdout("dotenv-value\n")
.stderr("echo $DOTENV_KEY\n")
.run();
}
#[test]
fn no_warning() {
Test::new()
.justfile(
"
foo:
echo ${DOTENV_KEY:-unset}
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.stdout("unset\n")
.stderr("echo ${DOTENV_KEY:-unset}\n")
.run();
}
#[test]
fn dotenv_required() {
Test::new()
.justfile(
"
set dotenv-required
foo:
",
)
.stderr("error: Dotenv file not found\n")
.status(1)
.run();
}
#[test]
fn path_resolves() {
Test::new()
.justfile(
"
foo:
@echo $JUST_TEST_VARIABLE
",
)
.tree(tree! {
subdir: {
".env": "JUST_TEST_VARIABLE=bar"
}
})
.args(["--dotenv-path", "subdir/.env"])
.stdout("bar\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn filename_resolves() {
Test::new()
.justfile(
"
foo:
@echo $JUST_TEST_VARIABLE
",
)
.tree(tree! {
".env.special": "JUST_TEST_VARIABLE=bar"
})
.args(["--dotenv-filename", ".env.special"])
.stdout("bar\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn filename_flag_overwrites_no_load() {
Test::new()
.justfile(
"
set dotenv-load := false
foo:
@echo $JUST_TEST_VARIABLE
",
)
.tree(tree! {
".env.special": "JUST_TEST_VARIABLE=bar"
})
.args(["--dotenv-filename", ".env.special"])
.stdout("bar\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn path_flag_overwrites_no_load() {
Test::new()
.justfile(
"
set dotenv-load := false
foo:
@echo $JUST_TEST_VARIABLE
",
)
.tree(tree! {
subdir: {
".env": "JUST_TEST_VARIABLE=bar"
}
})
.args(["--dotenv-path", "subdir/.env"])
.stdout("bar\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn can_set_dotenv_filename_from_justfile() {
Test::new()
.justfile(
r#"
set dotenv-filename := ".env.special"
foo:
@echo $JUST_TEST_VARIABLE
"#,
)
.tree(tree! {
".env.special": "JUST_TEST_VARIABLE=bar"
})
.stdout("bar\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn can_set_dotenv_path_from_justfile() {
Test::new()
.justfile(
r#"
set dotenv-path := "subdir/.env"
foo:
@echo $JUST_TEST_VARIABLE
"#,
)
.tree(tree! {
subdir: {
".env": "JUST_TEST_VARIABLE=bar"
}
})
.stdout("bar\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn program_argument_has_priority_for_dotenv_filename() {
Test::new()
.justfile(
r#"
set dotenv-filename := ".env.special"
foo:
@echo $JUST_TEST_VARIABLE
"#,
)
.tree(tree! {
".env.special": "JUST_TEST_VARIABLE=bar",
".env.superspecial": "JUST_TEST_VARIABLE=baz"
})
.args(["--dotenv-filename", ".env.superspecial"])
.stdout("baz\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn program_argument_has_priority_for_dotenv_path() {
Test::new()
.justfile(
"
set dotenv-path := 'subdir/.env'
foo:
@echo $JUST_TEST_VARIABLE
",
)
.tree(tree! {
subdir: {
".env": "JUST_TEST_VARIABLE=bar",
".env.special": "JUST_TEST_VARIABLE=baz"
}
})
.args(["--dotenv-path", "subdir/.env.special"])
.stdout("baz\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn dotenv_path_is_relative_to_working_directory() {
Test::new()
.justfile(
"
set dotenv-path := '.env'
foo:
@echo $DOTENV_KEY
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.tree(tree! { subdir: { } })
.current_dir("subdir")
.stdout("dotenv-value\n")
.run();
}
#[test]
fn dotenv_variable_in_recipe() {
Test::new()
.justfile(
"
set dotenv-load
echo:
echo $DOTENV_KEY
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.stdout("dotenv-value\n")
.stderr("echo $DOTENV_KEY\n")
.run();
}
#[test]
fn dotenv_variable_in_backtick() {
Test::new()
.justfile(
"
set dotenv-load
X:=`echo $DOTENV_KEY`
echo:
echo {{X}}
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.stdout("dotenv-value\n")
.stderr("echo dotenv-value\n")
.run();
}
#[test]
fn dotenv_variable_in_function_in_recipe() {
Test::new()
.justfile(
"
set dotenv-load
echo:
echo {{env_var_or_default('DOTENV_KEY', 'foo')}}
echo {{env_var('DOTENV_KEY')}}
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.stdout("dotenv-value\ndotenv-value\n")
.stderr("echo dotenv-value\necho dotenv-value\n")
.run();
}
#[test]
fn dotenv_variable_in_function_in_backtick() {
Test::new()
.justfile(
"
set dotenv-load
X:=env_var_or_default('DOTENV_KEY', 'foo')
Y:=env_var('DOTENV_KEY')
echo:
echo {{X}}
echo {{Y}}
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.stdout("dotenv-value\ndotenv-value\n")
.stderr("echo dotenv-value\necho dotenv-value\n")
.run();
}
#[test]
fn no_dotenv() {
Test::new()
.justfile(
"
X:=env_var_or_default('DOTENV_KEY', 'DEFAULT')
echo:
echo {{X}}
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.arg("--no-dotenv")
.stdout("DEFAULT\n")
.stderr("echo DEFAULT\n")
.run();
}
#[test]
fn dotenv_env_var_default_no_override() {
Test::new()
.justfile(
"
echo:
echo $DOTENV_KEY
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.env("DOTENV_KEY", "not-the-dotenv-value")
.stdout("not-the-dotenv-value\n")
.stderr("echo $DOTENV_KEY\n")
.run();
}
#[test]
fn dotenv_env_var_override() {
Test::new()
.justfile(
"
set dotenv-load
set dotenv-override := true
echo:
echo $DOTENV_KEY
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.env("DOTENV_KEY", "not-the-dotenv-value")
.stdout("dotenv-value\n")
.stderr("echo $DOTENV_KEY\n")
.run();
}
#[test]
fn dotenv_env_var_override_no_load() {
Test::new()
.justfile(
"
set dotenv-override := true
echo:
echo $DOTENV_KEY
",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.env("DOTENV_KEY", "not-the-dotenv-value")
.stdout("dotenv-value\n")
.stderr("echo $DOTENV_KEY\n")
.run();
}
#[test]
fn dotenv_path_usable_from_subdir() {
Test::new()
.justfile(
"
set dotenv-path := '.custom-env'
@echo:
echo $DOTENV_KEY
",
)
.create_dir("sub")
.current_dir("sub")
.write(".custom-env", "DOTENV_KEY=dotenv-value")
.stdout("dotenv-value\n")
.run();
}
#[test]
fn dotenv_path_does_not_override_dotenv_file() {
Test::new()
.write(".env", "KEY=ROOT")
.write(
"sub/justfile",
"set dotenv-path := '.'\n@foo:\n echo ${KEY}",
)
.current_dir("sub")
.stdout("ROOT\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/no_exit_message.rs | tests/no_exit_message.rs | use super::*;
#[test]
fn recipe_exit_message_suppressed() {
Test::new()
.justfile(
"
# This is a doc comment
[no-exit-message]
hello:
@echo 'Hello, World!'
@exit 100
",
)
.stdout("Hello, World!\n")
.status(100)
.run();
}
#[test]
fn silent_recipe_exit_message_suppressed() {
Test::new()
.justfile(
"
# This is a doc comment
[no-exit-message]
@hello:
echo 'Hello, World!'
exit 100
",
)
.stdout("Hello, World!\n")
.status(100)
.run();
}
#[test]
fn recipe_has_doc_comment() {
Test::new()
.justfile(
"
# This is a doc comment
[no-exit-message]
hello:
@exit 100
",
)
.arg("--list")
.stdout(
"
Available recipes:
hello # This is a doc comment
",
)
.run();
}
#[test]
fn unknown_attribute() {
Test::new()
.justfile(
"
# This is a doc comment
[unknown-attribute]
hello:
@exit 100
",
)
.stderr(
"
error: Unknown attribute `unknown-attribute`
——▶ justfile:2:2
│
2 │ [unknown-attribute]
│ ^^^^^^^^^^^^^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn empty_attribute() {
Test::new()
.justfile(
"
# This is a doc comment
[]
hello:
@exit 100
",
)
.stderr(
"
error: Expected identifier, but found ']'
——▶ justfile:2:2
│
2 │ []
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn extraneous_attribute_before_comment() {
Test::new()
.justfile(
"
[no-exit-message]
# This is a doc comment
hello:
@exit 100
",
)
.stderr(
"
error: Extraneous attribute
——▶ justfile:1:1
│
1 │ [no-exit-message]
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn extraneous_attribute_before_empty_line() {
Test::new()
.justfile(
"
[no-exit-message]
hello:
@exit 100
",
)
.stderr(
"
error: Extraneous attribute
——▶ justfile:1:1
│
1 │ [no-exit-message]
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn shebang_exit_message_suppressed() {
Test::new()
.justfile(
"
[no-exit-message]
hello:
#!/usr/bin/env bash
echo 'Hello, World!'
exit 100
",
)
.stdout("Hello, World!\n")
.status(100)
.run();
}
#[test]
fn no_exit_message() {
Test::new()
.justfile(
"
[no-exit-message]
@hello:
echo 'Hello, World!'
exit 100
",
)
.stdout("Hello, World!\n")
.status(100)
.run();
}
#[test]
fn exit_message() {
Test::new()
.justfile(
"
[exit-message]
@hello:
echo 'Hello, World!'
exit 100
",
)
.stdout("Hello, World!\n")
.status(100)
.stderr("error: Recipe `hello` failed on line 4 with exit code 100\n")
.run();
}
#[test]
fn recipe_exit_message_setting_suppressed() {
Test::new()
.justfile(
"
set no-exit-message
# This is a doc comment
hello:
@echo 'Hello, World!'
@exit 100
",
)
.stdout("Hello, World!\n")
.status(100)
.run();
}
#[test]
fn shebang_exit_message_setting_suppressed() {
Test::new()
.justfile(
"
set no-exit-message
hello:
#!/usr/bin/env bash
echo 'Hello, World!'
exit 100
",
)
.stdout("Hello, World!\n")
.status(100)
.run();
}
#[test]
fn exit_message_override_no_exit_setting() {
Test::new()
.justfile(
"
set no-exit-message
[exit-message]
fail:
@exit 100
",
)
.status(100)
.stderr("error: Recipe `fail` failed on line 5 with exit code 100\n")
.run();
}
#[test]
fn exit_message_and_no_exit_message_compile_forbidden() {
Test::new()
.justfile(
"
[exit-message, no-exit-message]
bar:
",
)
.stderr(
"
error: Recipe `bar` has both `[exit-message]` and `[no-exit-message]` attributes
——▶ justfile:2:1
│
2 │ bar:
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/search_arguments.rs | tests/search_arguments.rs | use super::*;
#[test]
fn argument_with_different_path_prefix_is_allowed() {
Test::new()
.justfile("foo bar:")
.args(["./foo", "../bar"])
.run();
}
#[test]
fn passing_dot_as_argument_is_allowed() {
Test::new()
.justfile(
"
say ARG:
echo {{ARG}}
",
)
.write(
"child/justfile",
"say ARG:\n '{{just_executable()}}' ../say {{ARG}}",
)
.current_dir("child")
.args(["say", "."])
.stdout(".\n")
.stderr_regex("'.*' ../say .\necho .\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/delimiters.rs | tests/delimiters.rs | use super::*;
#[test]
fn mismatched_delimiter() {
Test::new()
.justfile("(]")
.stderr(
"
error: Mismatched closing delimiter `]`. (Did you mean to close the `(` on line 1?)
——▶ justfile:1:2
│
1 │ (]
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unexpected_delimiter() {
Test::new()
.justfile("]")
.stderr(
"
error: Unexpected closing delimiter `]`
——▶ justfile:1:1
│
1 │ ]
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn paren_continuation() {
Test::new()
.justfile(
"
x := (
'a'
+
'b'
)
foo:
echo {{x}}
",
)
.stdout("ab\n")
.stderr("echo ab\n")
.run();
}
#[test]
fn brace_continuation() {
Test::new()
.justfile(
"
x := if '' == '' {
'a'
} else {
'b'
}
foo:
echo {{x}}
",
)
.stdout("a\n")
.stderr("echo a\n")
.run();
}
#[test]
fn bracket_continuation() {
Test::new()
.justfile(
"
set shell := [
'sh',
'-cu',
]
foo:
echo foo
",
)
.stdout("foo\n")
.stderr("echo foo\n")
.run();
}
#[test]
fn dependency_continuation() {
Test::new()
.justfile(
"
foo: (
bar 'bar'
)
echo foo
bar x:
echo {{x}}
",
)
.stdout("bar\nfoo\n")
.stderr("echo bar\necho foo\n")
.run();
}
#[test]
fn interpolation_continuation() {
Test::new()
.justfile(
"
foo:
echo {{ (
'a' + 'b')}}
",
)
.stderr("echo ab\n")
.stdout("ab\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/imports.rs | tests/imports.rs | use super::*;
#[test]
fn import_succeeds() {
Test::new()
.tree(tree! {
"import.justfile": "
b:
@echo B
",
})
.justfile(
"
import './import.justfile'
a: b
@echo A
",
)
.arg("a")
.stdout("B\nA\n")
.run();
}
#[test]
fn missing_import_file_error() {
Test::new()
.justfile(
"
import './import.justfile'
a:
@echo A
",
)
.arg("a")
.status(EXIT_FAILURE)
.stderr(
"
error: Could not find source file for import.
——▶ justfile:1:8
│
1 │ import './import.justfile'
│ ^^^^^^^^^^^^^^^^^^^
",
)
.run();
}
#[test]
fn missing_optional_imports_are_ignored() {
Test::new()
.justfile(
"
import? './import.justfile'
a:
@echo A
",
)
.arg("a")
.stdout("A\n")
.run();
}
#[test]
fn trailing_spaces_after_import_are_ignored() {
Test::new()
.tree(tree! {
"import.justfile": "",
})
.justfile(
"
import './import.justfile'\x20
a:
@echo A
",
)
.stdout("A\n")
.run();
}
#[test]
fn import_after_recipe() {
Test::new()
.tree(tree! {
"import.justfile": "
a:
@echo A
",
})
.justfile(
"
b: a
import './import.justfile'
",
)
.stdout("A\n")
.run();
}
#[test]
fn circular_import() {
Test::new()
.justfile("import 'a'")
.tree(tree! {
a: "import 'b'",
b: "import 'a'",
})
.status(EXIT_FAILURE)
.stderr_regex(path_for_regex(
"error: Import `.*/a` in `.*/b` is circular\n",
))
.run();
}
#[test]
fn import_recipes_are_not_default() {
Test::new()
.tree(tree! {
"import.justfile": "bar:",
})
.justfile("import './import.justfile'")
.status(EXIT_FAILURE)
.stderr("error: Justfile contains no default recipe.\n")
.run();
}
#[test]
fn listed_recipes_in_imports_are_in_load_order() {
Test::new()
.justfile(
"
import './import.justfile'
foo:
",
)
.write("import.justfile", "bar:")
.args(["--list", "--unsorted"])
.stdout(
"
Available recipes:
foo
bar
",
)
.run();
}
#[test]
fn include_error() {
Test::new()
.justfile("!include foo")
.status(EXIT_FAILURE)
.stderr(
"
error: The `!include` directive has been stabilized as `import`
——▶ justfile:1:1
│
1 │ !include foo
│ ^
",
)
.run();
}
#[test]
fn recipes_in_import_are_overridden_by_recipes_in_parent() {
Test::new()
.tree(tree! {
"import.justfile": "
a:
@echo IMPORT
",
})
.justfile(
"
a:
@echo ROOT
import './import.justfile'
set allow-duplicate-recipes
",
)
.arg("a")
.stdout("ROOT\n")
.run();
}
#[test]
fn variables_in_import_are_overridden_by_variables_in_parent() {
Test::new()
.tree(tree! {
"import.justfile": "
f := 'foo'
",
})
.justfile(
"
f := 'bar'
import './import.justfile'
set allow-duplicate-variables
a:
@echo {{f}}
",
)
.arg("a")
.stdout("bar\n")
.run();
}
#[cfg(not(windows))]
#[test]
fn import_paths_beginning_with_tilde_are_expanded_to_homdir() {
Test::new()
.write("foobar/mod.just", "foo:\n @echo FOOBAR")
.justfile(
"
import '~/mod.just'
",
)
.arg("foo")
.stdout("FOOBAR\n")
.env("HOME", "foobar")
.run();
}
#[test]
fn imports_dump_correctly() {
Test::new()
.write("import.justfile", "")
.justfile(
"
import './import.justfile'
",
)
.arg("--dump")
.stdout("import './import.justfile'\n")
.run();
}
#[test]
fn optional_imports_dump_correctly() {
Test::new()
.write("import.justfile", "")
.justfile(
"
import? './import.justfile'
",
)
.arg("--dump")
.stdout("import? './import.justfile'\n")
.run();
}
#[test]
fn imports_in_root_run_in_justfile_directory() {
Test::new()
.write("foo/import.justfile", "bar:\n @cat baz")
.write("baz", "BAZ")
.justfile(
"
import 'foo/import.justfile'
",
)
.arg("bar")
.stdout("BAZ")
.run();
}
#[test]
fn imports_in_submodules_run_in_submodule_directory() {
Test::new()
.justfile("mod foo")
.write("foo/mod.just", "import 'import.just'")
.write("foo/import.just", "bar:\n @cat baz")
.write("foo/baz", "BAZ")
.arg("foo")
.arg("bar")
.stdout("BAZ")
.run();
}
#[test]
fn nested_import_paths_are_relative_to_containing_submodule() {
Test::new()
.justfile("import 'foo/import.just'")
.write("foo/import.just", "import 'bar.just'")
.write("foo/bar.just", "bar:\n @echo BAR")
.arg("bar")
.stdout("BAR\n")
.run();
}
#[test]
fn recipes_in_nested_imports_run_in_parent_module() {
Test::new()
.justfile("import 'foo/import.just'")
.write("foo/import.just", "import 'bar/import.just'")
.write("foo/bar/import.just", "bar:\n @cat baz")
.write("baz", "BAZ")
.arg("bar")
.stdout("BAZ")
.run();
}
#[test]
fn shebang_recipes_in_imports_in_root_run_in_justfile_directory() {
Test::new()
.write(
"foo/import.justfile",
"bar:\n #!/usr/bin/env bash\n cat baz",
)
.write("baz", "BAZ")
.justfile(
"
import 'foo/import.justfile'
",
)
.arg("bar")
.stdout("BAZ")
.run();
}
#[test]
fn recipes_imported_in_root_run_in_command_line_provided_working_directory() {
Test::new()
.write("subdir/b.justfile", "@b:\n cat baz")
.write("subdir/a.justfile", "import 'b.justfile'\n@a: b\n cat baz")
.write("baz", "BAZ")
.args([
"--working-directory",
".",
"--justfile",
"subdir/a.justfile",
])
.stdout("BAZBAZ")
.run();
}
#[test]
fn reused_import_are_allowed() {
Test::new()
.justfile(
"
import 'a'
import 'b'
bar:
",
)
.tree(tree! {
a: "import 'c'",
b: "import 'c'",
c: "",
})
.run();
}
#[test]
fn multiply_imported_items_do_not_conflict() {
Test::new()
.justfile(
"
import 'a.just'
import 'a.just'
foo: bar
",
)
.write(
"a.just",
"
x := 'y'
@bar:
echo hello
",
)
.stdout("hello\n")
.run();
}
#[test]
fn nested_multiply_imported_items_do_not_conflict() {
Test::new()
.justfile(
"
import 'a.just'
import 'b.just'
foo: bar
",
)
.write("a.just", "import 'c.just'")
.write("b.just", "import 'c.just'")
.write(
"c.just",
"
x := 'y'
@bar:
echo hello
",
)
.stdout("hello\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/parameters.rs | tests/parameters.rs | use super::*;
#[test]
fn parameter_default_values_may_use_earlier_parameters() {
Test::new()
.justfile(
"
@foo a b=a:
echo {{ b }}
",
)
.args(["foo", "bar"])
.stdout("bar\n")
.run();
}
#[test]
fn parameter_default_values_may_not_use_later_parameters() {
Test::new()
.justfile(
"
@foo a b=c c='':
echo {{ b }}
",
)
.args(["foo", "bar"])
.stderr(
"
error: Variable `c` not defined
——▶ justfile:1:10
│
1 │ @foo a b=c c='':
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn star_may_follow_default() {
Test::new()
.justfile(
"
foo bar='baz' *bob:
@echo {{bar}} {{bob}}
",
)
.args(["foo", "hello", "goodbye"])
.stdout("hello goodbye\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/global.rs | tests/global.rs | use super::*;
#[test]
#[cfg(target_os = "macos")]
fn macos() {
let tempdir = tempdir();
let path = tempdir.path().to_owned();
Test::with_tempdir(tempdir)
.no_justfile()
.test_round_trip(false)
.write(
"Library/Application Support/just/justfile",
"@default:\n echo foo",
)
.env("HOME", path.to_str().unwrap())
.args(["--global-justfile"])
.stdout("foo\n")
.run();
}
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn not_macos() {
let tempdir = tempdir();
let path = tempdir.path().to_owned();
Test::with_tempdir(tempdir)
.no_justfile()
.test_round_trip(false)
.write("just/justfile", "@default:\n echo foo")
.env("XDG_CONFIG_HOME", path.to_str().unwrap())
.args(["--global-justfile"])
.stdout("foo\n")
.run();
}
#[test]
#[cfg(unix)]
fn unix() {
let tempdir = tempdir();
let path = tempdir.path().to_owned();
let tempdir = Test::with_tempdir(tempdir)
.no_justfile()
.test_round_trip(false)
.write("justfile", "@default:\n echo foo")
.env("HOME", path.to_str().unwrap())
.args(["--global-justfile"])
.stdout("foo\n")
.run()
.tempdir;
Test::with_tempdir(tempdir)
.no_justfile()
.test_round_trip(false)
.write(".config/just/justfile", "@default:\n echo bar")
.env("HOME", path.to_str().unwrap())
.args(["--global-justfile"])
.stdout("bar\n")
.run();
}
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn case_insensitive() {
let tempdir = tempdir();
let path = tempdir.path().to_owned();
Test::with_tempdir(tempdir)
.no_justfile()
.test_round_trip(false)
.write("just/JUSTFILE", "@default:\n echo foo")
.env("XDG_CONFIG_HOME", path.to_str().unwrap())
.args(["--global-justfile"])
.stdout("foo\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/lib.rs | tests/lib.rs | use {
crate::{
assert_stdout::assert_stdout,
assert_success::assert_success,
tempdir::tempdir,
test::{assert_eval_eq, Output, Test},
},
executable_path::executable_path,
just::{unindent, Response},
libc::{EXIT_FAILURE, EXIT_SUCCESS},
pretty_assertions::Comparison,
regex::Regex,
serde::{Deserialize, Serialize},
serde_json::{json, Value},
std::{
collections::BTreeMap,
env::{self, consts::EXE_SUFFIX},
error::Error,
fmt::Debug,
fs,
io::Write,
iter,
path::{Path, PathBuf, MAIN_SEPARATOR, MAIN_SEPARATOR_STR},
process::{Command, Stdio},
str,
time::{Duration, Instant},
},
tempfile::TempDir,
temptree::{temptree, tree, Tree},
which::which,
};
#[cfg(not(windows))]
use std::thread;
fn default<T: Default>() -> T {
Default::default()
}
#[macro_use]
mod test;
mod alias;
mod alias_style;
mod allow_duplicate_recipes;
mod allow_duplicate_variables;
mod allow_missing;
mod arg_attribute;
mod assert_stdout;
mod assert_success;
mod assertions;
mod assignment;
mod attributes;
mod backticks;
mod byte_order_mark;
mod ceiling;
mod changelog;
mod choose;
mod command;
mod completions;
mod conditional;
mod confirm;
mod constants;
mod datetime;
mod default;
mod delimiters;
mod dependencies;
mod directories;
mod dotenv;
mod edit;
mod equals;
mod error_messages;
mod evaluate;
mod examples;
mod explain;
mod export;
mod fallback;
mod format;
mod format_string;
mod functions;
#[cfg(unix)]
mod global;
mod groups;
mod ignore_comments;
mod imports;
mod init;
mod interpolation;
mod invocation_directory;
mod json;
mod line_prefixes;
mod list;
mod logical_operators;
mod man;
mod misc;
mod modules;
mod multibyte_char;
mod newline_escape;
mod no_aliases;
mod no_cd;
mod no_dependencies;
mod no_exit_message;
mod options;
mod os_attributes;
mod parallel;
mod parameters;
mod parser;
mod positional_arguments;
mod private;
mod quiet;
mod quote;
mod readme;
mod recursion_limit;
mod regexes;
mod request;
mod run;
mod scope;
mod script;
mod search;
mod search_arguments;
mod settings;
mod shadowing_parameters;
mod shebang;
mod shell;
mod shell_expansion;
mod show;
#[cfg(unix)]
mod signals;
mod slash_operator;
mod string;
mod subsequents;
mod summary;
mod tempdir;
mod timestamps;
mod undefined_variables;
mod unexport;
mod unstable;
mod usage;
mod which_function;
#[cfg(windows)]
mod windows;
#[cfg(target_family = "windows")]
mod windows_shell;
mod working_directory;
fn path(s: &str) -> String {
if cfg!(windows) {
s.replace('/', "\\")
} else {
s.into()
}
}
fn path_for_regex(s: &str) -> String {
if cfg!(windows) {
s.replace('/', "\\\\")
} else {
s.into()
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/allow_duplicate_variables.rs | tests/allow_duplicate_variables.rs | use super::*;
#[test]
fn allow_duplicate_variables() {
Test::new()
.justfile(
"
a := 'foo'
a := 'bar'
set allow-duplicate-variables
b:
echo {{a}}
",
)
.arg("b")
.stdout("bar\n")
.stderr("echo bar\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/command.rs | tests/command.rs | use super::*;
#[test]
fn long() {
Test::new()
.arg("--command")
.arg("printf")
.arg("foo")
.justfile(
"
x:
echo XYZ
",
)
.stdout("foo")
.run();
}
#[test]
fn short() {
Test::new()
.arg("-c")
.arg("printf")
.arg("foo")
.justfile(
"
x:
echo XYZ
",
)
.stdout("foo")
.run();
}
#[test]
fn command_color() {
Test::new()
.arg("--color")
.arg("always")
.arg("--command-color")
.arg("cyan")
.justfile(
"
x:
echo XYZ
",
)
.stdout("XYZ\n")
.stderr("\u{1b}[1;36mecho XYZ\u{1b}[0m\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn no_binary() {
Test::new()
.arg("--command")
.justfile(
"
x:
echo XYZ
",
)
.stderr(
"
error: a value is required for '--command <COMMAND>...' but none was supplied
For more information, try '--help'.
",
)
.status(2)
.run();
}
#[test]
fn env_is_loaded() {
Test::new()
.justfile(
"
set dotenv-load
x:
echo XYZ
",
)
.args(["--command", "sh", "-c", "printf $DOTENV_KEY"])
.write(".env", "DOTENV_KEY=dotenv-value")
.stdout("dotenv-value")
.run();
}
#[test]
fn exports_are_available() {
Test::new()
.arg("--command")
.arg("sh")
.arg("-c")
.arg("printf $FOO")
.justfile(
"
export FOO := 'bar'
x:
echo XYZ
",
)
.stdout("bar")
.run();
}
#[test]
fn set_overrides_work() {
Test::new()
.arg("--set")
.arg("FOO")
.arg("baz")
.arg("--command")
.arg("sh")
.arg("-c")
.arg("printf $FOO")
.justfile(
"
export FOO := 'bar'
x:
echo XYZ
",
)
.stdout("baz")
.run();
}
#[test]
fn run_in_shell() {
Test::new()
.arg("--shell-command")
.arg("--command")
.arg("bar baz")
.justfile(
"
set shell := ['printf']
",
)
.stdout("bar baz")
.shell(false)
.run();
}
#[test]
fn exit_status() {
Test::new()
.arg("--command")
.arg("false")
.justfile(
"
x:
echo XYZ
",
)
.stderr_regex("error: Command `false` failed: exit (code|status): 1\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn working_directory_is_correct() {
let tmp = tempdir();
fs::write(tmp.path().join("justfile"), "").unwrap();
fs::write(tmp.path().join("bar"), "baz").unwrap();
fs::create_dir(tmp.path().join("foo")).unwrap();
let output = Command::new(executable_path("just"))
.args(["--command", "cat", "bar"])
.current_dir(tmp.path().join("foo"))
.output()
.unwrap();
assert_eq!(str::from_utf8(&output.stderr).unwrap(), "");
assert!(output.status.success());
assert_eq!(str::from_utf8(&output.stdout).unwrap(), "baz");
}
#[test]
fn command_not_found() {
let tmp = tempdir();
fs::write(tmp.path().join("justfile"), "").unwrap();
let output = Command::new(executable_path("just"))
.args(["--command", "asdfasdfasdfasdfadfsadsfadsf", "bar"])
.output()
.unwrap();
assert!(str::from_utf8(&output.stderr)
.unwrap()
.starts_with("error: Failed to invoke `asdfasdfasdfasdfadfsadsfadsf` `bar`:"));
assert!(!output.status.success());
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/unstable.rs | tests/unstable.rs | use super::*;
#[test]
fn set_unstable_true_with_env_var() {
for val in ["true", "some-arbitrary-string"] {
Test::new()
.justfile("# hello")
.args(["--fmt"])
.env("JUST_UNSTABLE", val)
.status(EXIT_SUCCESS)
.stderr_regex("Wrote justfile to `.*`\n")
.run();
}
}
#[test]
fn set_unstable_false_with_env_var() {
for val in ["0", "", "false"] {
Test::new()
.justfile("")
.args(["--fmt"])
.env("JUST_UNSTABLE", val)
.status(EXIT_FAILURE)
.stderr_regex("error: The `--fmt` command is currently unstable.*")
.run();
}
}
#[test]
fn set_unstable_false_with_env_var_unset() {
Test::new()
.justfile("")
.args(["--fmt"])
.status(EXIT_FAILURE)
.stderr_regex("error: The `--fmt` command is currently unstable.*")
.run();
}
#[test]
fn set_unstable_with_setting() {
Test::new()
.justfile("set unstable")
.arg("--fmt")
.stderr_regex("Wrote justfile to .*")
.run();
}
// This test should be re-enabled if we get a new unstable feature which is
// encountered in source files. (As opposed to, for example, the unstable
// `--fmt` subcommand, which is encountered on the command line.)
#[cfg(any())]
#[test]
fn unstable_setting_does_not_affect_submodules() {
Test::new()
.justfile(
"
set unstable
mod foo
",
)
.write("foo.just", "mod bar")
.write("bar.just", "baz:\n echo hello")
.args(["foo", "bar"])
.stderr_regex("error: Modules are currently unstable.*")
.status(EXIT_FAILURE)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/unexport.rs | tests/unexport.rs | use super::*;
#[test]
fn unexport_environment_variable_linewise() {
Test::new()
.justfile(
"
unexport JUST_TEST_VARIABLE
@recipe:
echo ${JUST_TEST_VARIABLE:-unset}
",
)
.env("JUST_TEST_VARIABLE", "foo")
.stdout("unset\n")
.run();
}
#[test]
fn unexport_environment_variable_shebang() {
Test::new()
.justfile(
"
unexport JUST_TEST_VARIABLE
recipe:
#!/usr/bin/env bash
echo ${JUST_TEST_VARIABLE:-unset}
",
)
.env("JUST_TEST_VARIABLE", "foo")
.stdout("unset\n")
.run();
}
#[test]
fn duplicate_unexport_fails() {
Test::new()
.justfile(
"
unexport JUST_TEST_VARIABLE
recipe:
echo \"variable: $JUST_TEST_VARIABLE\"
unexport JUST_TEST_VARIABLE
",
)
.env("JUST_TEST_VARIABLE", "foo")
.stderr(
"
error: Variable `JUST_TEST_VARIABLE` is unexported multiple times
——▶ justfile:6:10
│
6 │ unexport JUST_TEST_VARIABLE
│ ^^^^^^^^^^^^^^^^^^
",
)
.status(1)
.run();
}
#[test]
fn export_unexport_conflict() {
Test::new()
.justfile(
"
unexport JUST_TEST_VARIABLE
recipe:
echo variable: $JUST_TEST_VARIABLE
export JUST_TEST_VARIABLE := 'foo'
",
)
.stderr(
"
error: Variable JUST_TEST_VARIABLE is both exported and unexported
——▶ justfile:6:8
│
6 │ export JUST_TEST_VARIABLE := 'foo'
│ ^^^^^^^^^^^^^^^^^^
",
)
.status(1)
.run();
}
#[test]
fn unexport_doesnt_override_local_recipe_export() {
Test::new()
.justfile(
"
unexport JUST_TEST_VARIABLE
recipe $JUST_TEST_VARIABLE:
@echo \"variable: $JUST_TEST_VARIABLE\"
",
)
.args(["recipe", "value"])
.stdout("variable: value\n")
.run();
}
#[test]
fn unexport_does_not_conflict_with_recipe_syntax() {
Test::new()
.justfile(
"
unexport foo:
@echo {{foo}}
",
)
.args(["unexport", "bar"])
.stdout("bar\n")
.run();
}
#[test]
fn unexport_does_not_conflict_with_assignment_syntax() {
Test::new()
.justfile("unexport := 'foo'")
.args(["--evaluate", "unexport"])
.stdout("foo")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/slash_operator.rs | tests/slash_operator.rs | use super::*;
#[test]
fn once() {
Test::new()
.justfile("x := 'a' / 'b'")
.args(["--evaluate", "x"])
.stdout("a/b")
.run();
}
#[test]
fn twice() {
Test::new()
.justfile("x := 'a' / 'b' / 'c'")
.args(["--evaluate", "x"])
.stdout("a/b/c")
.run();
}
#[test]
fn no_lhs_once() {
Test::new()
.justfile("x := / 'a'")
.args(["--evaluate", "x"])
.stdout("/a")
.run();
}
#[test]
fn no_lhs_twice() {
Test::new()
.justfile("x := / 'a' / 'b'")
.args(["--evaluate", "x"])
.stdout("/a/b")
.run();
Test::new()
.justfile("x := // 'a'")
.args(["--evaluate", "x"])
.stdout("//a")
.run();
}
#[test]
fn no_rhs_once() {
Test::new()
.justfile("x := 'a' /")
.stderr(
"
error: Expected backtick, identifier, '(', '/', or string, but found end of file
——▶ justfile:1:11
│
1 │ x := 'a' /
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn default_un_parenthesized() {
Test::new()
.justfile(
"
foo x='a' / 'b':
echo {{x}}
",
)
.stderr(
"
error: Expected '*', ':', '$', identifier, or '+', but found '/'
——▶ justfile:1:11
│
1 │ foo x='a' / 'b':
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn no_lhs_un_parenthesized() {
Test::new()
.justfile(
"
foo x=/ 'a' / 'b':
echo {{x}}
",
)
.stderr(
"
error: Expected backtick, identifier, '(', or string, but found '/'
——▶ justfile:1:7
│
1 │ foo x=/ 'a' / 'b':
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn default_parenthesized() {
Test::new()
.justfile(
"
foo x=('a' / 'b'):
echo {{x}}
",
)
.stderr("echo a/b\n")
.stdout("a/b\n")
.run();
}
#[test]
fn no_lhs_parenthesized() {
Test::new()
.justfile(
"
foo x=(/ 'a' / 'b'):
echo {{x}}
",
)
.stderr("echo /a/b\n")
.stdout("/a/b\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/man.rs | tests/man.rs | use super::*;
#[test]
fn output() {
Test::new()
.arg("--man")
.stdout_regex("(?s).*.TH just 1.*")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/no_aliases.rs | tests/no_aliases.rs | use super::*;
#[test]
fn skip_alias() {
Test::new()
.justfile(
"
alias t := test1
test1:
@echo 'test1'
test2:
@echo 'test2'
",
)
.args(["--no-aliases", "--list"])
.stdout("Available recipes:\n test1\n test2\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/datetime.rs | tests/datetime.rs | use super::*;
#[test]
fn datetime() {
Test::new()
.justfile(
"
x := datetime('%Y-%m-%d %z')
",
)
.args(["--eval", "x"])
.stdout_regex(r"\d\d\d\d-\d\d-\d\d [+-]\d\d\d\d")
.run();
}
#[test]
fn datetime_utc() {
Test::new()
.justfile(
"
x := datetime_utc('%Y-%m-%d %Z')
",
)
.args(["--eval", "x"])
.stdout_regex(r"\d\d\d\d-\d\d-\d\d UTC")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/shadowing_parameters.rs | tests/shadowing_parameters.rs | use super::*;
#[test]
fn parameter_may_shadow_variable() {
Test::new()
.arg("a")
.arg("bar")
.justfile("FOO := 'hello'\na FOO:\n echo {{FOO}}\n")
.stdout("bar\n")
.stderr("echo bar\n")
.run();
}
#[test]
fn shadowing_parameters_do_not_change_environment() {
Test::new()
.arg("a")
.arg("bar")
.justfile("export FOO := 'hello'\na FOO:\n echo $FOO\n")
.stdout("hello\n")
.stderr("echo $FOO\n")
.run();
}
#[test]
fn exporting_shadowing_parameters_does_change_environment() {
Test::new()
.arg("a")
.arg("bar")
.justfile("export FOO := 'hello'\na $FOO:\n echo $FOO\n")
.stdout("bar\n")
.stderr("echo $FOO\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/string.rs | tests/string.rs | use super::*;
#[test]
fn raw_string() {
Test::new()
.justfile(
r#"
export EXPORTED_VARIABLE := '\z'
recipe:
printf "$EXPORTED_VARIABLE"
"#,
)
.stdout("\\z")
.stderr("printf \"$EXPORTED_VARIABLE\"\n")
.run();
}
#[test]
fn multiline_raw_string() {
Test::new()
.arg("a")
.justfile(
"
string := 'hello
whatever'
a:
echo '{{string}}'
",
)
.stdout(
"hello
whatever
",
)
.stderr(
"echo 'hello
whatever'
",
)
.run();
}
#[test]
fn multiline_backtick() {
Test::new()
.arg("a")
.justfile(
"
string := `echo hello
echo goodbye
`
a:
echo '{{string}}'
",
)
.stdout("hello\ngoodbye\n")
.stderr(
"echo 'hello
goodbye'
",
)
.run();
}
#[test]
fn multiline_cooked_string() {
Test::new()
.arg("a")
.justfile(
r#"
string := "hello
whatever"
a:
echo '{{string}}'
"#,
)
.stdout(
"hello
whatever
",
)
.stderr(
"echo 'hello
whatever'
",
)
.run();
}
#[test]
fn cooked_string_suppress_newline() {
Test::new()
.justfile(
r#"
a := """
foo\
bar
"""
@default:
printf %s '{{a}}'
"#,
)
.stdout(
"
foobar
",
)
.run();
}
#[test]
fn invalid_escape_sequence() {
Test::new()
.arg("a")
.justfile(
r#"x := "\q"
a:"#,
)
.stderr(
"error: `\\q` is not a valid escape sequence
——▶ justfile:1:6
│
1 │ x := \"\\q\"
│ ^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn error_line_after_multiline_raw_string() {
Test::new()
.arg("a")
.justfile(
"
string := 'hello
whatever' + 'yo'
a:
echo '{{foo}}'
",
)
.stderr(
"error: Variable `foo` not defined
——▶ justfile:6:11
│
6 │ echo '{{foo}}'
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn error_column_after_multiline_raw_string() {
Test::new()
.arg("a")
.justfile(
"
string := 'hello
whatever' + bar
a:
echo '{{string}}'
",
)
.stderr(
"error: Variable `bar` not defined
——▶ justfile:3:13
│
3 │ whatever' + bar
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn multiline_raw_string_in_interpolation() {
Test::new()
.arg("a")
.justfile(
r#"
a:
echo '{{"a" + '
' + "b"}}'
"#,
)
.stdout(
"
a
b
",
)
.stderr(
"
echo 'a
b'
",
)
.run();
}
#[test]
fn error_line_after_multiline_raw_string_in_interpolation() {
Test::new()
.arg("a")
.justfile(
r#"
a:
echo '{{"a" + '
' + "b"}}'
echo {{b}}
"#,
)
.stderr(
"error: Variable `b` not defined
——▶ justfile:5:10
│
5 │ echo {{b}}
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unterminated_raw_string() {
Test::new()
.arg("a")
.justfile(
"
a b= ':
",
)
.stderr(
"
error: Unterminated string
——▶ justfile:1:6
│
1 │ a b= ':
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unterminated_string() {
Test::new()
.arg("a")
.justfile(
r#"
a b= ":
"#,
)
.stderr(
r#"
error: Unterminated string
——▶ justfile:1:6
│
1 │ a b= ":
│ ^
"#,
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unterminated_backtick() {
Test::new()
.justfile(
"
foo a=\t`echo blaaaaaah:
echo {{a}}
",
)
.stderr(
r"
error: Unterminated backtick
——▶ justfile:1:8
│
1 │ foo a= `echo blaaaaaah:
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unterminated_indented_raw_string() {
Test::new()
.arg("a")
.justfile(
"
a b= ''':
",
)
.stderr(
"
error: Unterminated string
——▶ justfile:1:6
│
1 │ a b= ''':
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unterminated_indented_string() {
Test::new()
.arg("a")
.justfile(
r#"
a b= """:
"#,
)
.stderr(
r#"
error: Unterminated string
——▶ justfile:1:6
│
1 │ a b= """:
│ ^^^
"#,
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unterminated_indented_backtick() {
Test::new()
.justfile(
"
foo a=\t```echo blaaaaaah:
echo {{a}}
",
)
.stderr(
r"
error: Unterminated backtick
——▶ justfile:1:8
│
1 │ foo a= ```echo blaaaaaah:
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn indented_raw_string_contents_indentation_removed() {
Test::new()
.justfile(
"
a := '''
foo
bar
'''
@default:
printf '{{a}}'
",
)
.stdout(
"
foo
bar
",
)
.run();
}
#[test]
fn indented_cooked_string_contents_indentation_removed() {
Test::new()
.justfile(
r#"
a := """
foo
bar
"""
@default:
printf '{{a}}'
"#,
)
.stdout(
"
foo
bar
",
)
.run();
}
#[test]
fn indented_backtick_string_contents_indentation_removed() {
Test::new()
.justfile(
r"
a := ```
printf '
foo
bar
'
```
@default:
printf '{{a}}'
",
)
.stdout("\n\nfoo\nbar")
.run();
}
#[test]
fn indented_raw_string_escapes() {
Test::new()
.justfile(
r"
a := '''
foo\n
bar
'''
@default:
printf %s '{{a}}'
",
)
.stdout(
r"
foo\n
bar
",
)
.run();
}
#[test]
fn indented_cooked_string_escapes() {
Test::new()
.justfile(
r#"
a := """
foo\n
bar
"""
@default:
printf %s '{{a}}'
"#,
)
.stdout(
"
foo
bar
",
)
.run();
}
#[test]
fn indented_backtick_string_escapes() {
Test::new()
.justfile(
r"
a := ```
printf %s '
foo\n
bar
'
```
@default:
printf %s '{{a}}'
",
)
.stdout("\n\nfoo\\n\nbar")
.run();
}
#[test]
fn shebang_backtick() {
Test::new()
.justfile(
"
x := `#!/usr/bin/env sh`
",
)
.stderr(
"
error: Backticks may not start with `#!`
——▶ justfile:1:6
│
1 │ x := `#!/usr/bin/env sh`
│ ^^^^^^^^^^^^^^^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn valid_unicode_escape() {
Test::new()
.justfile(r#"x := "\u{1f916}\u{1F916}""#)
.args(["--evaluate", "x"])
.stdout("🤖🤖")
.run();
}
#[test]
fn unicode_escapes_with_all_hex_digits() {
Test::new()
.justfile(r#"x := "\u{012345}\u{6789a}\u{bcdef}\u{ABCDE}\u{F}""#)
.args(["--evaluate", "x"])
.stdout("\u{012345}\u{6789a}\u{bcdef}\u{ABCDE}\u{F}")
.run();
}
#[test]
fn maximum_valid_unicode_escape() {
Test::new()
.justfile(r#"x := "\u{10FFFF}""#)
.args(["--evaluate", "x"])
.stdout("\u{10FFFF}")
.run();
}
#[test]
fn unicode_escape_no_braces() {
Test::new()
.justfile("x := \"\\u1234\"")
.args(["--evaluate", "x"])
.status(1)
.stderr(
r#"
error: expected unicode escape sequence delimiter `{` but found `1`
——▶ justfile:1:6
│
1 │ x := "\u1234"
│ ^^^^^^^^
"#,
)
.run();
}
#[test]
fn unicode_escape_empty() {
Test::new()
.justfile("x := \"\\u{}\"")
.args(["--evaluate", "x"])
.status(1)
.stderr(
r#"
error: unicode escape sequences must not be empty
——▶ justfile:1:6
│
1 │ x := "\u{}"
│ ^^^^^^
"#,
)
.run();
}
#[test]
fn unicode_escape_requires_immediate_opening_brace() {
Test::new()
.justfile("x := \"\\u {1f916}\"")
.args(["--evaluate", "x"])
.status(1)
.stderr(
r#"
error: expected unicode escape sequence delimiter `{` but found ` `
——▶ justfile:1:6
│
1 │ x := "\u {1f916}"
│ ^^^^^^^^^^^^
"#,
)
.run();
}
#[test]
fn unicode_escape_non_hex() {
Test::new()
.justfile("x := \"\\u{foo}\"")
.args(["--evaluate", "x"])
.status(1)
.stderr(
r#"
error: expected hex digit [0-9A-Fa-f] but found `o`
——▶ justfile:1:6
│
1 │ x := "\u{foo}"
│ ^^^^^^^^^
"#,
)
.run();
}
#[test]
fn unicode_escape_invalid_character() {
Test::new()
.justfile("x := \"\\u{BadBad}\"")
.args(["--evaluate", "x"])
.status(1)
.stderr(
r#"
error: unicode escape sequence value `BadBad` greater than maximum valid code point `10FFFF`
——▶ justfile:1:6
│
1 │ x := "\u{BadBad}"
│ ^^^^^^^^^^^^
"#,
)
.run();
}
#[test]
fn unicode_escape_too_long() {
Test::new()
.justfile("x := \"\\u{FFFFFFFFFF}\"")
.args(["--evaluate", "x"])
.status(1)
.stderr(
r#"
error: unicode escape sequence starting with `\u{FFFFFFF` longer than six hex digits
——▶ justfile:1:6
│
1 │ x := "\u{FFFFFFFFFF}"
│ ^^^^^^^^^^^^^^^^
"#,
)
.run();
}
#[test]
fn unicode_escape_unterminated() {
Test::new()
.justfile("x := \"\\u{1f917\"")
.args(["--evaluate", "x"])
.status(1)
.stderr(
r#"
error: unterminated unicode escape sequence
——▶ justfile:1:6
│
1 │ x := "\u{1f917"
│ ^^^^^^^^^^
"#,
)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/parser.rs | tests/parser.rs | use super::*;
#[test]
fn dont_run_duplicate_recipes() {
Test::new()
.justfile(
"
set dotenv-load # foo
bar:
",
)
.run();
}
#[test]
fn invalid_bang_operator() {
Test::new()
.justfile(
"
x := if '' !! '' { '' } else { '' }
",
)
.status(1)
.stderr(
r"
error: Expected character `=` or `~`
——▶ justfile:1:13
│
1 │ x := if '' !! '' { '' } else { '' }
│ ^
",
)
.run();
}
#[test]
fn truncated_bang_operator() {
Test::new()
.justfile("x := if '' !")
.status(1)
.stderr(
r"
error: Expected character `=` or `~` but found end-of-file
——▶ justfile:1:13
│
1 │ x := if '' !
│ ^
",
)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/assert_success.rs | tests/assert_success.rs | #[track_caller]
pub(crate) fn assert_success(output: &std::process::Output) {
if !output.status.success() {
eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
panic!("{}", output.status);
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/equals.rs | tests/equals.rs | use super::*;
#[test]
fn export_recipe() {
Test::new()
.justfile(
"
export foo='bar':
echo {{foo}}
",
)
.stdout("bar\n")
.stderr("echo bar\n")
.run();
}
#[test]
fn alias_recipe() {
Test::new()
.justfile(
"
alias foo='bar':
echo {{foo}}
",
)
.stdout("bar\n")
.stderr("echo bar\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/alias_style.rs | tests/alias_style.rs | use super::*;
#[test]
fn default() {
Test::new()
.justfile(
"
alias f := foo
# comment
foo:
bar:
",
)
.args(["--list"])
.stdout(
"
Available recipes:
bar
foo # comment [alias: f]
",
)
.run();
}
#[test]
fn multiple() {
Test::new()
.justfile(
"
alias a := foo
alias b := foo
# comment
foo:
bar:
",
)
.args(["--list"])
.stdout(
"
Available recipes:
bar
foo # comment [aliases: a, b]
",
)
.run();
}
#[test]
fn right() {
Test::new()
.justfile(
"
alias f := foo
# comment
foo:
bar:
",
)
.args(["--alias-style=right", "--list"])
.stdout(
"
Available recipes:
bar
foo # comment [alias: f]
",
)
.run();
}
#[test]
fn left() {
Test::new()
.justfile(
"
alias f := foo
# comment
foo:
bar:
",
)
.args(["--alias-style=left", "--list"])
.stdout(
"
Available recipes:
bar
foo # [alias: f] comment
",
)
.run();
}
#[test]
fn separate() {
Test::new()
.justfile(
"
alias f := foo
# comment
foo:
bar:
",
)
.args(["--alias-style=separate", "--list"])
.stdout(
"
Available recipes:
bar
foo # comment
f # alias for `foo`
",
)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/readme.rs | tests/readme.rs | use super::*;
#[test]
fn readme() {
let mut justfiles = Vec::new();
let mut current = None;
for line in fs::read_to_string("README.md").unwrap().lines() {
if let Some(mut justfile) = current {
if line == "```" {
justfiles.push(justfile);
current = None;
} else {
justfile += line;
justfile += "\n";
current = Some(justfile);
}
} else if line == "```just" {
current = Some(String::new());
}
}
for justfile in justfiles {
let tmp = tempdir();
let path = tmp.path().join("justfile");
fs::write(path, justfile).unwrap();
let output = Command::new(executable_path("just"))
.current_dir(tmp.path())
.arg("--dump")
.output()
.unwrap();
assert_success(&output);
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/format_string.rs | tests/format_string.rs | use super::*;
#[test]
fn empty() {
Test::new()
.justfile(
"
foo := f''
@baz:
echo {{foo}}
",
)
.stdout("\n")
.unindent_stdout(false)
.run();
}
#[test]
fn simple() {
Test::new()
.justfile(
"
foo := f'bar'
@baz:
echo {{foo}}
",
)
.stdout("bar\n")
.run();
}
#[test]
fn compound() {
Test::new()
.justfile(
"
bar := 'BAR'
foo := f'FOO{{ bar }}BAZ'
@baz:
echo {{foo}}
",
)
.stdout("FOOBARBAZ\n")
.run();
}
#[test]
fn newline() {
Test::new()
.justfile(
"
bar := 'BAR'
foo := f'FOO{{
bar + 'XYZ'
}}BAZ'
@baz:
echo {{foo}}
",
)
.stdout("FOOBARXYZBAZ\n")
.run();
}
#[test]
fn conditional() {
Test::new()
.justfile(
"
foo := f'FOO{{
if 'a' == 'b' { 'c' } else { 'd' }
}}BAZ'
@baz:
echo {{foo}}
",
)
.stdout("FOOdBAZ\n")
.run();
}
#[test]
fn conditional_no_whitespace() {
Test::new()
.justfile(
"
foo := f'FOO{{if 'a' == 'b' { 'c' } else { 'd' }}}BAZ'
@baz:
echo {{foo}}
",
)
.stdout("FOOdBAZ\n")
.run();
}
#[test]
fn inner_delimiter() {
Test::new()
.justfile(
"
bar := 'BAR'
foo := f'FOO{{(bar)}}BAZ'
@baz:
echo {{foo}}
",
)
.stdout("FOOBARBAZ\n")
.run();
}
#[test]
fn nested() {
Test::new()
.justfile(
"
bar := 'BAR'
foo := f'FOO{{f'[{{bar}}]'}}BAZ'
@baz:
echo {{foo}}
",
)
.stdout("FOO[BAR]BAZ\n")
.run();
}
#[test]
fn recipe_body() {
Test::new()
.justfile(
"
bar := 'BAR'
@baz:
echo {{f'FOO{{f'[{{bar}}]'}}BAZ'}}
",
)
.stdout("FOO[BAR]BAZ\n")
.run();
}
#[test]
fn unclosed() {
Test::new()
.justfile("foo := f'FOO{{")
.stderr(
"
error: Expected backtick, identifier, '(', '/', or string, but found end of file
——▶ justfile:1:15
│
1 │ foo := f'FOO{{
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unmatched_close_is_ignored() {
Test::new()
.justfile(
"
foo := f'}}'
@baz:
echo {{foo}}
",
)
.stdout("}}\n")
.unindent_stdout(false)
.run();
}
#[test]
fn delimiter_may_be_escaped_in_double_quoted_strings() {
Test::new()
.justfile(
r#"
foo := f"{{{{"
"#,
)
.args(["--evaluate", "foo"])
.stdout("{{")
.run();
}
#[test]
fn delimiter_may_be_escaped_in_single_quoted_strings() {
Test::new()
.justfile(
"
foo := f'{{{{'
",
)
.args(["--evaluate", "foo"])
.stdout("{{")
.run();
}
#[test]
fn escaped_delimiter_is_ignored_in_normal_strings() {
Test::new()
.justfile(
"
foo := '{{{{'
",
)
.args(["--evaluate", "foo"])
.stdout("{{{{")
.run();
}
#[test]
fn escaped_delimiter_in_single_quoted_format_string() {
Test::new()
.justfile(
r"
foo := f'\{{{{'
",
)
.args(["--evaluate", "foo"])
.stdout("\\{{")
.run();
}
#[test]
fn escaped_delimiter_in_double_quoted_format_string() {
Test::new()
.justfile(
r#"
foo := f"\{{{{"
"#,
)
.args(["--evaluate", "foo"])
.status(EXIT_FAILURE)
.stderr(
r#"
error: `\{` is not a valid escape sequence
——▶ justfile:1:9
│
1 │ foo := f"\{{{{"
│ ^^^^^^^
"#,
)
.run();
}
#[test]
fn double_quotes_process_escapes() {
Test::new()
.justfile(
r#"
foo := f"\u{61}{{"b"}}\u{63}{{"d"}}\u{65}"
"#,
)
.args(["--evaluate", "foo"])
.stdout("abcde")
.run();
}
#[test]
fn single_quotes_do_not_process_escapes() {
Test::new()
.justfile(
r#"
foo := f'\n{{"a"}}\n{{"b"}}\n'
"#,
)
.args(["--evaluate", "foo"])
.stdout(r"\na\nb\n")
.run();
}
#[test]
fn indented_format_strings() {
Test::new()
.justfile(
r#"
foo := f'''
a
{{"b"}}
c
'''
"#,
)
.args(["--evaluate", "foo"])
.stdout("a\nb\nc\n")
.run();
}
#[test]
fn un_indented_format_strings() {
Test::new()
.justfile(
r#"
foo := f'
a
{{"b"}}
c
'
"#,
)
.args(["--evaluate", "foo"])
.stdout("\n a\n b\n c\n")
.unindent_stdout(false)
.run();
}
#[test]
fn dump() {
#[track_caller]
fn case(string: &str) {
Test::new()
.justfile(format!(
"
foo := {string}
"
))
.arg("--dump")
.stdout(format!("foo := {string}\n"))
.run();
}
case("f''");
case("f''''''");
case(r#"f"""#);
case(r#"f"""""""#);
case("f'{{'a'}}b{{'c'}}d'");
case("f'''{{'a'}}b{{'c'}}d'''");
case(r#"f"""{{'a'}}b{{'c'}}d""""#);
}
#[test]
fn undefined_variable_error() {
Test::new()
.justfile(
"
foo := f'{{bar}}'
",
)
.status(EXIT_FAILURE)
.stderr(
"
error: Variable `bar` not defined
——▶ justfile:1:12
│
1 │ foo := f'{{bar}}'
│ ^^^
",
)
.run();
}
#[test]
fn format_string_followed_by_recipe() {
Test::new()
.justfile(
"
foo := f'{{'foo'}}{{'bar'}}'
bar:
",
)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/modules.rs | tests/modules.rs | use super::*;
#[test]
fn modules_are_stable() {
Test::new()
.justfile(
"
mod foo
",
)
.write("foo.just", "@bar:\n echo ok")
.args(["foo", "bar"])
.stdout("ok\n")
.run();
}
#[test]
fn default_recipe_in_submodule_must_have_no_arguments() {
Test::new()
.write("foo.just", "foo bar:\n @echo FOO")
.justfile(
"
mod foo
",
)
.arg("foo")
.stderr("error: Recipe `foo` cannot be used as default recipe since it requires at least 1 argument.\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn module_recipes_can_be_run_as_subcommands() {
Test::new()
.write("foo.just", "foo:\n @echo FOO")
.justfile(
"
mod foo
",
)
.arg("foo")
.arg("foo")
.stdout("FOO\n")
.run();
}
#[test]
fn module_recipes_can_be_run_with_path_syntax() {
Test::new()
.write("foo.just", "foo:\n @echo FOO")
.justfile(
"
mod foo
",
)
.arg("foo::foo")
.stdout("FOO\n")
.run();
}
#[test]
fn nested_module_recipes_can_be_run_with_path_syntax() {
Test::new()
.write("foo.just", "mod bar")
.write("bar.just", "baz:\n @echo BAZ")
.justfile(
"
mod foo
",
)
.arg("foo::bar::baz")
.stdout("BAZ\n")
.run();
}
#[test]
fn invalid_path_syntax() {
Test::new()
.arg(":foo::foo")
.stderr("error: Justfile does not contain recipe `:foo::foo`\n")
.status(EXIT_FAILURE)
.run();
Test::new()
.arg("foo::foo:")
.stderr("error: Justfile does not contain recipe `foo::foo:`\n")
.status(EXIT_FAILURE)
.run();
Test::new()
.arg("foo:::foo")
.stderr("error: Justfile does not contain recipe `foo:::foo`\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn missing_recipe_after_invalid_path() {
Test::new()
.arg(":foo::foo")
.arg("bar")
.stderr("error: Justfile does not contain recipe `:foo::foo`\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn assignments_are_evaluated_in_modules() {
Test::new()
.write("foo.just", "bar := 'CHILD'\nfoo:\n @echo {{bar}}")
.justfile(
"
mod foo
bar := 'PARENT'
",
)
.arg("foo")
.arg("foo")
.stdout("CHILD\n")
.run();
}
#[test]
fn module_subcommand_runs_default_recipe() {
Test::new()
.write("foo.just", "foo:\n @echo FOO")
.justfile(
"
mod foo
",
)
.arg("foo")
.stdout("FOO\n")
.run();
}
#[test]
fn modules_can_contain_other_modules() {
Test::new()
.write("bar.just", "baz:\n @echo BAZ")
.write("foo.just", "mod bar")
.justfile(
"
mod foo
",
)
.arg("foo")
.arg("bar")
.arg("baz")
.stdout("BAZ\n")
.run();
}
#[test]
fn circular_module_imports_are_detected() {
Test::new()
.write("bar.just", "mod foo")
.write("foo.just", "mod bar")
.justfile(
"
mod foo
",
)
.arg("foo")
.arg("bar")
.arg("baz")
.stderr_regex(path_for_regex(
"error: Import `.*/foo.just` in `.*/bar.just` is circular\n",
))
.status(EXIT_FAILURE)
.run();
}
#[test]
fn modules_use_module_settings() {
Test::new()
.write(
"foo.just",
"set allow-duplicate-recipes
foo:
foo:
@echo FOO
",
)
.justfile(
"
mod foo
",
)
.arg("foo")
.arg("foo")
.stdout("FOO\n")
.run();
Test::new()
.write(
"foo.just",
"foo:
foo:
@echo FOO
",
)
.justfile(
"
mod foo
set allow-duplicate-recipes
",
)
.status(EXIT_FAILURE)
.arg("foo")
.arg("foo")
.stderr(
"
error: Recipe `foo` first defined on line 1 is redefined on line 2
——▶ foo.just:2:1
│
2 │ foo:
│ ^^^
",
)
.run();
}
#[test]
fn modules_conflict_with_recipes() {
Test::new()
.write("foo.just", "")
.justfile(
"
mod foo
foo:
",
)
.stderr(
"
error: Module `foo` defined on line 1 is redefined as a recipe on line 2
——▶ justfile:2:1
│
2 │ foo:
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn modules_conflict_with_aliases() {
Test::new()
.write("foo.just", "")
.justfile(
"
mod foo
bar:
alias foo := bar
",
)
.stderr(
"
error: Module `foo` defined on line 1 is redefined as an alias on line 3
——▶ justfile:3:7
│
3 │ alias foo := bar
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn modules_conflict_with_other_modules() {
Test::new()
.write("foo.just", "")
.justfile(
"
mod foo
mod foo
bar:
",
)
.status(EXIT_FAILURE)
.stderr(
"
error: Module `foo` first defined on line 1 is redefined on line 2
——▶ justfile:2:5
│
2 │ mod foo
│ ^^^
",
)
.run();
}
#[test]
fn modules_are_dumped_correctly() {
Test::new()
.write("foo.just", "foo:\n @echo FOO")
.justfile(
"
mod foo
",
)
.arg("--dump")
.stdout("mod foo\n")
.run();
}
#[test]
fn optional_modules_are_dumped_correctly() {
Test::new()
.write("foo.just", "foo:\n @echo FOO")
.justfile(
"
mod? foo
",
)
.arg("--dump")
.stdout("mod? foo\n")
.run();
}
#[test]
fn modules_can_be_in_subdirectory() {
Test::new()
.write("foo/mod.just", "foo:\n @echo FOO")
.justfile(
"
mod foo
",
)
.arg("foo")
.arg("foo")
.stdout("FOO\n")
.run();
}
#[test]
fn modules_in_subdirectory_can_be_named_justfile() {
Test::new()
.write("foo/justfile", "foo:\n @echo FOO")
.justfile(
"
mod foo
",
)
.arg("foo")
.arg("foo")
.stdout("FOO\n")
.run();
}
#[test]
fn modules_in_subdirectory_can_be_named_justfile_with_any_case() {
Test::new()
.write("foo/JUSTFILE", "foo:\n @echo FOO")
.justfile(
"
mod foo
",
)
.arg("foo")
.arg("foo")
.stdout("FOO\n")
.run();
}
#[test]
fn modules_in_subdirectory_can_have_leading_dot() {
Test::new()
.write("foo/.justfile", "foo:\n @echo FOO")
.justfile(
"
mod foo
",
)
.arg("foo")
.arg("foo")
.stdout("FOO\n")
.run();
}
#[test]
fn modules_require_unambiguous_file() {
Test::new()
.write("foo/justfile", "foo:\n @echo FOO")
.write("foo.just", "foo:\n @echo FOO")
.justfile(
"
mod foo
",
)
.status(EXIT_FAILURE)
.stderr(
"
error: Found multiple source files for module `foo`: `foo/justfile` and `foo.just`
——▶ justfile:1:5
│
1 │ mod foo
│ ^^^
"
.replace('/', MAIN_SEPARATOR_STR),
)
.run();
}
#[test]
fn missing_module_file_error() {
Test::new()
.justfile(
"
mod foo
",
)
.status(EXIT_FAILURE)
.stderr(
"
error: Could not find source file for module `foo`.
——▶ justfile:1:5
│
1 │ mod foo
│ ^^^
",
)
.run();
}
#[test]
fn missing_optional_modules_do_not_trigger_error() {
Test::new()
.justfile(
"
mod? foo
bar:
@echo BAR
",
)
.stdout("BAR\n")
.run();
}
#[test]
fn missing_optional_modules_do_not_conflict() {
Test::new()
.justfile(
"
mod? foo
mod? foo
mod foo 'baz.just'
",
)
.write("baz.just", "baz:\n @echo BAZ")
.arg("foo")
.arg("baz")
.stdout("BAZ\n")
.run();
}
#[test]
fn root_dotenv_is_available_to_submodules() {
Test::new()
.justfile(
"
set dotenv-load
mod foo
",
)
.write("foo.just", "foo:\n @echo $DOTENV_KEY")
.write(".env", "DOTENV_KEY=dotenv-value")
.args(["foo", "foo"])
.stdout("dotenv-value\n")
.run();
}
#[test]
fn dotenv_settings_in_submodule_are_ignored() {
Test::new()
.justfile(
"
set dotenv-load
mod foo
",
)
.write(
"foo.just",
"set dotenv-load := false\nfoo:\n @echo $DOTENV_KEY",
)
.write(".env", "DOTENV_KEY=dotenv-value")
.args(["foo", "foo"])
.stdout("dotenv-value\n")
.run();
}
#[test]
fn modules_may_specify_path() {
Test::new()
.write("commands/foo.just", "foo:\n @echo FOO")
.justfile(
"
mod foo 'commands/foo.just'
",
)
.arg("foo")
.arg("foo")
.stdout("FOO\n")
.run();
}
#[test]
fn modules_may_specify_path_to_directory() {
Test::new()
.write("commands/bar/mod.just", "foo:\n @echo FOO")
.justfile(
"
mod foo 'commands/bar'
",
)
.arg("foo")
.arg("foo")
.stdout("FOO\n")
.run();
}
#[test]
fn modules_with_paths_are_dumped_correctly() {
Test::new()
.write("commands/foo.just", "foo:\n @echo FOO")
.justfile(
"
mod foo 'commands/foo.just'
",
)
.arg("--dump")
.stdout("mod foo 'commands/foo.just'\n")
.run();
}
#[test]
fn optional_modules_with_paths_are_dumped_correctly() {
Test::new()
.write("commands/foo.just", "foo:\n @echo FOO")
.justfile(
"
mod? foo 'commands/foo.just'
",
)
.arg("--dump")
.stdout("mod? foo 'commands/foo.just'\n")
.run();
}
#[test]
fn recipes_may_be_named_mod() {
Test::new()
.justfile(
"
mod foo:
@echo FOO
",
)
.arg("mod")
.arg("bar")
.stdout("FOO\n")
.run();
}
#[test]
fn submodule_linewise_recipes_run_in_submodule_directory() {
Test::new()
.write("foo/bar", "BAR")
.write("foo/mod.just", "foo:\n @cat bar")
.justfile(
"
mod foo
",
)
.arg("foo")
.arg("foo")
.stdout("BAR")
.run();
}
#[test]
fn submodule_shebang_recipes_run_in_submodule_directory() {
Test::new()
.write("foo/bar", "BAR")
.write("foo/mod.just", "foo:\n #!/bin/sh\n cat bar")
.justfile(
"
mod foo
",
)
.arg("foo")
.arg("foo")
.stdout("BAR")
.run();
}
#[test]
fn cross_module_dependency_runs_in_submodule_directory() {
Test::new()
.write("foo/bar", "BAR")
.write("foo/mod.just", "foo:\n @cat bar")
.justfile(
"
mod foo
main: foo::foo
",
)
.arg("main")
.stdout("BAR")
.run();
}
#[test]
fn cross_module_dependency_with_no_cd_runs_in_invocation_directory() {
Test::new()
.write("root_file", "ROOT")
.write(
"foo/mod.just",
"
[no-cd]
foo:
@cat root_file
",
)
.justfile(
"
mod foo
main: foo::foo
",
)
.arg("main")
.stdout("ROOT")
.run();
}
#[test]
fn nested_cross_module_dependency_runs_in_correct_directory() {
Test::new()
.write("outer/inner/file", "NESTED")
.write("outer/inner/mod.just", "task:\n @cat file")
.write("outer/mod.just", "mod inner")
.justfile(
"
mod outer
main: outer::inner::task
",
)
.arg("main")
.stdout("NESTED")
.run();
}
#[cfg(not(windows))]
#[test]
fn module_paths_beginning_with_tilde_are_expanded_to_homdir() {
Test::new()
.write("foobar/mod.just", "foo:\n @echo FOOBAR")
.justfile(
"
mod foo '~/mod.just'
",
)
.arg("foo")
.arg("foo")
.stdout("FOOBAR\n")
.env("HOME", "foobar")
.run();
}
#[test]
fn recipes_with_same_name_are_both_run() {
Test::new()
.write("foo.just", "bar:\n @echo MODULE")
.justfile(
"
mod foo
bar:
@echo ROOT
",
)
.arg("foo::bar")
.arg("bar")
.stdout("MODULE\nROOT\n")
.run();
}
#[test]
fn submodule_recipe_not_found_error_message() {
Test::new()
.args(["foo::bar"])
.stderr("error: Justfile does not contain submodule `foo`\n")
.status(1)
.run();
}
#[test]
fn submodule_recipe_not_found_spaced_error_message() {
Test::new()
.write("foo.just", "bar:\n @echo MODULE")
.justfile(
"
mod foo
",
)
.args(["foo", "baz"])
.stderr("error: Justfile does not contain recipe `foo baz`\nDid you mean `bar`?\n")
.status(1)
.run();
}
#[test]
fn submodule_recipe_not_found_colon_separated_error_message() {
Test::new()
.write("foo.just", "bar:\n @echo MODULE")
.justfile(
"
mod foo
",
)
.args(["foo::baz"])
.stderr("error: Justfile does not contain recipe `foo::baz`\nDid you mean `bar`?\n")
.status(1)
.run();
}
#[test]
fn colon_separated_path_does_not_run_recipes() {
Test::new()
.justfile(
"
foo:
@echo FOO
bar:
@echo BAR
",
)
.args(["foo::bar"])
.stderr("error: Expected submodule at `foo` but found recipe.\n")
.status(1)
.run();
}
#[test]
fn expected_submodule_but_found_recipe_in_root_error() {
Test::new()
.justfile("foo:")
.arg("foo::baz")
.stderr("error: Expected submodule at `foo` but found recipe.\n")
.status(1)
.run();
}
#[test]
fn expected_submodule_but_found_recipe_in_submodule_error() {
Test::new()
.justfile("mod foo")
.write("foo.just", "bar:")
.args(["foo::bar::baz"])
.stderr("error: Expected submodule at `foo::bar` but found recipe.\n")
.status(1)
.run();
}
#[test]
fn colon_separated_path_components_are_not_used_as_arguments() {
Test::new()
.justfile("foo bar:")
.args(["foo::bar"])
.stderr("error: Expected submodule at `foo` but found recipe.\n")
.status(1)
.run();
}
#[test]
fn comments_can_follow_modules() {
Test::new()
.write("foo.just", "foo:\n @echo FOO")
.justfile(
"
mod foo # this is foo
",
)
.args(["foo", "foo"])
.stdout("FOO\n")
.run();
}
#[test]
fn doc_comment_on_module() {
Test::new()
.write("foo.just", "")
.justfile(
"
# Comment
mod foo
",
)
.test_round_trip(false)
.arg("--list")
.stdout("Available recipes:\n foo ... # Comment\n")
.run();
}
#[test]
fn doc_attribute_on_module() {
Test::new()
.write("foo.just", "")
.justfile(
r#"
# Suppressed comment
[doc: "Comment"]
mod foo
"#,
)
.test_round_trip(false)
.arg("--list")
.stdout("Available recipes:\n foo ... # Comment\n")
.run();
}
#[test]
fn group_attribute_on_module() {
Test::new()
.write("foo.just", "")
.write("bar.just", "")
.write("zee.just", "")
.justfile(
r"
[group('alpha')]
mod zee
[group('alpha')]
mod foo
[group('alpha')]
a:
[group('beta')]
b:
[group('beta')]
mod bar
c:
",
)
.test_round_trip(false)
.arg("--list")
.stdout(
"
Available recipes:
c
[alpha]
a
foo ...
zee ...
[beta]
b
bar ...
",
)
.run();
}
#[test]
fn group_attribute_on_module_unsorted() {
Test::new()
.write("foo.just", "")
.write("bar.just", "")
.write("zee.just", "")
.justfile(
r"
[group('alpha')]
mod zee
[group('alpha')]
mod foo
[group('alpha')]
a:
[group('beta')]
b:
[group('beta')]
mod bar
c:
",
)
.test_round_trip(false)
.arg("--list")
.arg("--unsorted")
.stdout(
"
Available recipes:
c
[alpha]
a
zee ...
foo ...
[beta]
b
bar ...
",
)
.run();
}
#[test]
fn group_attribute_on_module_list_submodule() {
Test::new()
.write("foo.just", "d:")
.write("bar.just", "e:")
.write("zee.just", "f:")
.justfile(
r"
[group('alpha')]
mod zee
[group('alpha')]
mod foo
[group('alpha')]
a:
[group('beta')]
b:
[group('beta')]
mod bar
c:
",
)
.test_round_trip(false)
.arg("--list")
.arg("--list-submodules")
.stdout(
"
Available recipes:
c
[alpha]
a
foo:
d
zee:
f
[beta]
b
bar:
e
",
)
.run();
}
#[test]
fn group_attribute_on_module_list_submodule_unsorted() {
Test::new()
.write("foo.just", "d:")
.write("bar.just", "e:")
.write("zee.just", "f:")
.justfile(
r"
[group('alpha')]
mod zee
[group('alpha')]
mod foo
[group('alpha')]
a:
[group('beta')]
b:
[group('beta')]
mod bar
c:
",
)
.test_round_trip(false)
.arg("--list")
.arg("--list-submodules")
.arg("--unsorted")
.stdout(
"
Available recipes:
c
[alpha]
a
zee:
f
foo:
d
[beta]
b
bar:
e
",
)
.run();
}
#[test]
fn bad_module_attribute_fails() {
Test::new()
.write("foo.just", "")
.justfile(
r"
[no-cd]
mod foo
",
)
.test_round_trip(false)
.arg("--list")
.stderr("error: Module `foo` has invalid attribute `no-cd`\n ——▶ justfile:2:5\n │\n2 │ mod foo\n │ ^^^\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn empty_doc_attribute_on_module() {
Test::new()
.write("foo.just", "")
.justfile(
"
# Suppressed comment
[doc]
mod foo
",
)
.test_round_trip(false)
.arg("--list")
.stdout("Available recipes:\n foo ...\n")
.run();
}
#[test]
fn overrides_work_when_submodule_is_present() {
Test::new()
.write("bar.just", "")
.justfile(
"
mod bar
x := 'a'
foo:
@echo {{ x }}
",
)
.test_round_trip(false)
.arg("x=b")
.stdout("b\n")
.run();
}
#[test]
fn exported_variables_are_available_in_submodules() {
Test::new()
.write("foo.just", "bar:\n @echo $x")
.justfile(
"
mod foo
export x := 'a'
",
)
.test_round_trip(false)
.arg("foo::bar")
.stdout("a\n")
.run();
}
#[test]
fn exported_variables_can_be_unexported_in_submodules() {
Test::new()
.write("foo.just", "unexport x\nbar:\n @echo ${x:-default}")
.justfile(
"
mod foo
export x := 'a'
",
)
.test_round_trip(false)
.arg("foo::bar")
.stdout("default\n")
.run();
}
#[test]
fn exported_variables_can_be_overridden_in_submodules() {
Test::new()
.write("foo.just", "export x := 'b'\nbar:\n @echo $x")
.justfile(
"
mod foo
export x := 'a'
",
)
.test_round_trip(false)
.arg("foo::bar")
.stdout("b\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/list.rs | tests/list.rs | use super::*;
#[test]
fn modules_unsorted() {
Test::new()
.write("foo.just", "foo:")
.write("bar.just", "bar:")
.justfile(
"
mod foo
mod bar
",
)
.args(["--list", "--unsorted"])
.stdout(
"
Available recipes:
foo ...
bar ...
",
)
.run();
}
#[test]
fn unsorted_list_order() {
Test::new()
.write("a.just", "a:")
.write("b.just", "b:")
.write("c.just", "c:")
.write("d.just", "d:")
.justfile(
"
import 'a.just'
import 'b.just'
import 'c.just'
import 'd.just'
x:
y:
z:
",
)
.args(["--list", "--unsorted"])
.stdout(
"
Available recipes:
x
y
z
a
b
c
d
",
)
.run();
Test::new()
.write("a.just", "a:")
.write("b.just", "b:")
.write("c.just", "c:")
.write("d.just", "d:")
.justfile(
"
x:
y:
z:
import 'd.just'
import 'c.just'
import 'b.just'
import 'a.just'
",
)
.args(["--list", "--unsorted"])
.stdout(
"
Available recipes:
x
y
z
d
c
b
a
",
)
.run();
Test::new()
.write("a.just", "a:\nimport 'e.just'")
.write("b.just", "b:\nimport 'f.just'")
.write("c.just", "c:\nimport 'g.just'")
.write("d.just", "d:\nimport 'h.just'")
.write("e.just", "e:")
.write("f.just", "f:")
.write("g.just", "g:")
.write("h.just", "h:")
.justfile(
"
x:
y:
z:
import 'd.just'
import 'c.just'
import 'b.just'
import 'a.just'
",
)
.args(["--list", "--unsorted"])
.stdout(
"
Available recipes:
x
y
z
d
h
c
g
b
f
a
e
",
)
.run();
Test::new()
.write("task1.just", "task1:")
.write("task2.just", "task2:")
.justfile(
"
import 'task1.just'
import 'task2.just'
",
)
.args(["--list", "--unsorted"])
.stdout(
"
Available recipes:
task1
task2
",
)
.run();
}
#[test]
fn list_submodule() {
Test::new()
.write("foo.just", "bar:")
.justfile(
"
mod foo
",
)
.args(["--list", "foo"])
.stdout(
"
Available recipes:
bar
",
)
.run();
}
#[test]
fn list_nested_submodule() {
Test::new()
.write("foo.just", "mod bar")
.write("bar.just", "baz:")
.justfile(
"
mod foo
",
)
.args(["--list", "foo", "bar"])
.stdout(
"
Available recipes:
baz
",
)
.run();
Test::new()
.write("foo.just", "mod bar")
.write("bar.just", "baz:")
.justfile(
"
mod foo
",
)
.args(["--list", "foo::bar"])
.stdout(
"
Available recipes:
baz
",
)
.run();
}
#[test]
fn list_invalid_path() {
Test::new()
.args(["--list", "$hello"])
.stderr("error: Invalid module path `$hello`\n")
.status(1)
.run();
}
#[test]
fn list_unknown_submodule() {
Test::new()
.args(["--list", "hello"])
.stderr("error: Justfile does not contain submodule `hello`\n")
.status(1)
.run();
}
#[test]
fn list_with_groups_in_modules() {
Test::new()
.justfile(
"
[group('FOO')]
foo:
mod bar
",
)
.write("bar.just", "[group('BAZ')]\nbaz:")
.args(["--list", "--list-submodules"])
.stdout(
"
Available recipes:
bar:
[BAZ]
baz
[FOO]
foo
",
)
.run();
}
#[test]
fn list_displays_recipes_in_submodules() {
Test::new()
.write("foo.just", "bar:\n @echo FOO")
.justfile(
"
mod foo
",
)
.args(["--list", "--list-submodules"])
.stdout(
"
Available recipes:
foo:
bar
",
)
.run();
}
#[test]
fn modules_are_space_separated_in_output() {
Test::new()
.write("foo.just", "foo:")
.write("bar.just", "bar:")
.justfile(
"
mod foo
mod bar
",
)
.args(["--list", "--list-submodules"])
.stdout(
"
Available recipes:
bar:
bar
foo:
foo
",
)
.run();
}
#[test]
fn module_recipe_list_alignment_ignores_private_recipes() {
Test::new()
.write(
"foo.just",
"
# foos
foo:
@echo FOO
[private]
barbarbar:
@echo BAR
@_bazbazbaz:
@echo BAZ
",
)
.justfile("mod foo")
.args(["--list", "--list-submodules"])
.stdout(
"
Available recipes:
foo:
foo # foos
",
)
.run();
}
#[test]
fn nested_modules_are_properly_indented() {
Test::new()
.write("foo.just", "mod bar")
.write("bar.just", "baz:\n @echo FOO")
.justfile(
"
mod foo
",
)
.args(["--list", "--list-submodules"])
.stdout(
"
Available recipes:
foo:
bar:
baz
",
)
.run();
}
#[test]
fn module_doc_rendered() {
Test::new()
.write("foo.just", "")
.justfile(
"
# Module foo
mod foo
",
)
.args(["--list"])
.stdout(
"
Available recipes:
foo ... # Module foo
",
)
.run();
}
#[test]
fn module_doc_aligned() {
Test::new()
.write("foo.just", "")
.write("bar.just", "")
.justfile(
"
# Module foo
mod foo
# comment
mod very_long_name_for_module \"bar.just\" # comment
# will change your world
recipe:
@echo Hi
",
)
.args(["--list"])
.stdout(
"
Available recipes:
recipe # will change your world
foo ... # Module foo
very_long_name_for_module ... # comment
",
)
.run();
}
#[test]
fn submodules_without_groups() {
Test::new()
.write("foo.just", "")
.justfile(
"
mod foo
[group: 'baz']
bar:
",
)
.args(["--list"])
.stdout(
"
Available recipes:
foo ...
[baz]
bar
",
)
.run();
}
#[test]
fn no_space_before_submodules_not_following_groups() {
Test::new()
.write("foo.just", "")
.justfile(
"
mod foo
",
)
.args(["--list"])
.stdout(
"
Available recipes:
foo ...
",
)
.run();
}
#[test]
fn backticks_highlighted() {
Test::new()
.justfile(
"
# Comment `` `with backticks` and trailing text
recipe:
",
)
.args(["--list", "--color=always"])
.stdout(
"
Available recipes:
recipe \u{1b}[34m#\u{1b}[0m \u{1b}[34mComment \u{1b}[0m\u{1b}[36m``\u{1b}[0m\u{1b}[34m \u{1b}[0m\u{1b}[36m`with backticks`\u{1b}[0m\u{1b}[34m and trailing text\u{1b}[0m
")
.run();
}
#[test]
fn unclosed_backticks() {
Test::new()
.justfile(
"
# Comment `with unclosed backick
recipe:
",
)
.args(["--list", "--color=always"])
.stdout(
"
Available recipes:
recipe \u{1b}[34m#\u{1b}[0m \u{1b}[34mComment \u{1b}[0m\u{1b}[36m`with unclosed backick\u{1b}[0m
")
.run();
}
#[test]
fn list_submodules_requires_list() {
Test::new()
.arg("--list-submodules")
.stderr_regex("error: the following required arguments were not provided:\n --list .*")
.status(2)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/backticks.rs | tests/backticks.rs | use super::*;
#[test]
fn trailing_newlines_are_stripped() {
Test::new()
.shell(false)
.args(["--evaluate", "foos"])
.justfile(
"
set shell := ['python3', '-c']
foos := `print('foo' * 4)`
",
)
.stdout("foofoofoofoo")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/ceiling.rs | tests/ceiling.rs | use super::*;
#[test]
fn justfile_run_search_stops_at_ceiling_dir() {
let tempdir = tempdir();
let ceiling = tempdir.path().join("foo");
fs::create_dir(&ceiling).unwrap();
#[cfg(not(windows))]
let ceiling = ceiling.canonicalize().unwrap();
Test::with_tempdir(tempdir)
.justfile(
"
foo:
echo bar
",
)
.create_dir("foo/bar")
.current_dir("foo/bar")
.args(["--ceiling", ceiling.to_str().unwrap()])
.stderr("error: No justfile found\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn ceiling_can_be_passed_as_environment_variable() {
let tempdir = tempdir();
let ceiling = tempdir.path().join("foo");
fs::create_dir(&ceiling).unwrap();
#[cfg(not(windows))]
let ceiling = ceiling.canonicalize().unwrap();
Test::with_tempdir(tempdir)
.justfile(
"
foo:
echo bar
",
)
.create_dir("foo/bar")
.current_dir("foo/bar")
.env("JUST_CEILING", ceiling.to_str().unwrap())
.stderr("error: No justfile found\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn justfile_init_search_stops_at_ceiling_dir() {
let tempdir = tempdir();
let ceiling = tempdir.path().join("foo");
fs::create_dir(&ceiling).unwrap();
#[cfg(not(windows))]
let ceiling = ceiling.canonicalize().unwrap();
let Output { tempdir, .. } = Test::with_tempdir(tempdir)
.no_justfile()
.test_round_trip(false)
.create_dir(".git")
.create_dir("foo/bar")
.current_dir("foo/bar")
.args(["--init", "--ceiling", ceiling.to_str().unwrap()])
.stderr_regex(if cfg!(windows) {
r"Wrote justfile to `.*\\foo\\bar\\justfile`\n"
} else {
"Wrote justfile to `.*/foo/bar/justfile`\n"
})
.run();
assert_eq!(
fs::read_to_string(tempdir.path().join("foo/bar/justfile")).unwrap(),
just::INIT_JUSTFILE
);
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/subsequents.rs | tests/subsequents.rs | use super::*;
#[test]
fn success() {
Test::new()
.justfile(
"
foo: && bar
echo foo
bar:
echo bar
",
)
.stdout(
"
foo
bar
",
)
.stderr(
"
echo foo
echo bar
",
)
.run();
}
#[test]
fn failure() {
Test::new()
.justfile(
"
foo: && bar
echo foo
false
bar:
echo bar
",
)
.stdout(
"
foo
",
)
.stderr(
"
echo foo
false
error: Recipe `foo` failed on line 3 with exit code 1
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn circular_dependency() {
Test::new()
.justfile(
"
foo: && foo
",
)
.stderr(
"
error: Recipe `foo` depends on itself
——▶ justfile:1:9
│
1 │ foo: && foo
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unknown() {
Test::new()
.justfile(
"
foo: && bar
",
)
.stderr(
"
error: Recipe `foo` has unknown dependency `bar`
——▶ justfile:1:9
│
1 │ foo: && bar
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unknown_argument() {
Test::new()
.justfile(
"
bar x:
foo: && (bar y)
",
)
.stderr(
"
error: Variable `y` not defined
——▶ justfile:3:14
│
3 │ foo: && (bar y)
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn argument() {
Test::new()
.justfile(
"
foo: && (bar 'hello')
bar x:
echo {{ x }}
",
)
.stdout(
"
hello
",
)
.stderr(
"
echo hello
",
)
.run();
}
#[test]
fn duplicate_subsequents_dont_run() {
Test::new()
.justfile(
"
a: && b c
echo a
b: d
echo b
c: d
echo c
d:
echo d
",
)
.stdout(
"
a
d
b
c
",
)
.stderr(
"
echo a
echo d
echo b
echo c
",
)
.run();
}
#[test]
fn subsequents_run_even_if_already_ran_as_prior() {
Test::new()
.justfile(
"
a: b && b
echo a
b:
echo b
",
)
.stdout(
"
b
a
b
",
)
.stderr(
"
echo b
echo a
echo b
",
)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/positional_arguments.rs | tests/positional_arguments.rs | use super::*;
#[test]
fn linewise() {
Test::new()
.arg("foo")
.arg("hello")
.arg("goodbye")
.justfile(
r#"
set positional-arguments
foo bar baz:
echo $0
echo $1
echo $2
echo "$@"
"#,
)
.stdout(
"
foo
hello
goodbye
hello goodbye
",
)
.stderr(
r#"
echo $0
echo $1
echo $2
echo "$@"
"#,
)
.run();
}
#[test]
fn linewise_with_attribute() {
Test::new()
.arg("foo")
.arg("hello")
.arg("goodbye")
.justfile(
r#"
[positional-arguments]
foo bar baz:
echo $0
echo $1
echo $2
echo "$@"
"#,
)
.stdout(
"
foo
hello
goodbye
hello goodbye
",
)
.stderr(
r#"
echo $0
echo $1
echo $2
echo "$@"
"#,
)
.run();
}
#[test]
fn variadic_linewise() {
Test::new()
.args(["foo", "a", "b", "c"])
.justfile(
r#"
set positional-arguments
foo *bar:
echo $1
echo "$@"
"#,
)
.stdout("a\na b c\n")
.stderr("echo $1\necho \"$@\"\n")
.run();
}
#[test]
fn shebang() {
Test::new()
.arg("foo")
.arg("hello")
.justfile(
"
set positional-arguments
foo bar:
#!/bin/sh
echo $1
",
)
.stdout("hello\n")
.run();
}
#[test]
fn shebang_with_attribute() {
Test::new()
.arg("foo")
.arg("hello")
.justfile(
"
[positional-arguments]
foo bar:
#!/bin/sh
echo $1
",
)
.stdout("hello\n")
.run();
}
#[test]
fn variadic_shebang() {
Test::new()
.arg("foo")
.arg("a")
.arg("b")
.arg("c")
.justfile(
r#"
set positional-arguments
foo *bar:
#!/bin/sh
echo $1
echo "$@"
"#,
)
.stdout("a\na b c\n")
.run();
}
#[test]
fn default_arguments() {
Test::new()
.justfile(
r"
set positional-arguments
foo bar='baz':
echo $1
",
)
.stdout("baz\n")
.stderr("echo $1\n")
.run();
}
#[test]
fn empty_variadic_is_undefined() {
Test::new()
.justfile(
r#"
set positional-arguments
foo *bar:
if [ -n "${1+1}" ]; then echo defined; else echo undefined; fi
"#,
)
.stdout("undefined\n")
.stderr("if [ -n \"${1+1}\" ]; then echo defined; else echo undefined; fi\n")
.run();
}
#[test]
fn variadic_arguments_are_separate() {
Test::new()
.arg("foo")
.arg("a")
.arg("b")
.justfile(
r"
set positional-arguments
foo *bar:
echo $1
echo $2
",
)
.stdout("a\nb\n")
.stderr("echo $1\necho $2\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/regexes.rs | tests/regexes.rs | use super::*;
#[test]
fn match_succeeds_evaluates_to_first_branch() {
Test::new()
.justfile(
"
foo := if 'abbbc' =~ 'ab+c' {
'yes'
} else {
'no'
}
default:
echo {{ foo }}
",
)
.stderr("echo yes\n")
.stdout("yes\n")
.run();
}
#[test]
fn match_fails_evaluates_to_second_branch() {
Test::new()
.justfile(
"
foo := if 'abbbc' =~ 'ab{4}c' {
'yes'
} else {
'no'
}
default:
echo {{ foo }}
",
)
.stderr("echo no\n")
.stdout("no\n")
.run();
}
#[test]
fn bad_regex_fails_at_runtime() {
Test::new()
.justfile(
"
default:
echo before
echo {{ if '' =~ '(' { 'a' } else { 'b' } }}
echo after
",
)
.stderr(
"
echo before
error: regex parse error:
(
^
error: unclosed group
",
)
.stdout("before\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn mismatch() {
Test::new()
.justfile(
"
foo := if 'Foo' !~ '^ab+c' {
'mismatch'
} else {
'match'
}
bar := if 'Foo' !~ 'Foo' {
'mismatch'
} else {
'match'
}
@default:
echo {{ foo }} {{ bar }}
",
)
.stdout("mismatch match\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/evaluate.rs | tests/evaluate.rs | use super::*;
#[test]
fn evaluate() {
Test::new()
.arg("--evaluate")
.justfile(
r#"
foo := "a\t"
hello := "c"
bar := "b\t"
ab := foo + bar + hello
wut:
touch /this/is/not/a/file
"#,
)
.stdout(
r#"ab := "a b c"
bar := "b "
foo := "a "
hello := "c"
"#,
)
.run();
}
#[test]
fn evaluate_empty() {
Test::new()
.arg("--evaluate")
.justfile(
"
a := 'foo'
",
)
.stdout(
r#"
a := "foo"
"#,
)
.run();
}
#[test]
fn evaluate_multiple() {
Test::new()
.arg("--evaluate")
.arg("a")
.arg("c")
.justfile(
"
a := 'x'
b := 'y'
c := 'z'
",
)
.stderr("error: `--evaluate` used with unexpected argument: `c`\n")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn evaluate_single_free() {
Test::new()
.arg("--evaluate")
.arg("b")
.justfile(
"
a := 'x'
b := 'y'
c := 'z'
",
)
.stdout("y")
.run();
}
#[test]
fn evaluate_no_suggestion() {
Test::new()
.arg("--evaluate")
.arg("aby")
.justfile(
"
abc := 'x'
",
)
.status(EXIT_FAILURE)
.stderr(
"
error: Justfile does not contain variable `aby`.
Did you mean `abc`?
",
)
.run();
}
#[test]
fn evaluate_suggestion() {
Test::new()
.arg("--evaluate")
.arg("goodbye")
.justfile(
"
hello := 'x'
",
)
.status(EXIT_FAILURE)
.stderr(
"
error: Justfile does not contain variable `goodbye`.
",
)
.run();
}
#[test]
fn evaluate_private() {
Test::new()
.arg("--evaluate")
.justfile(
"
[private]
foo := 'one'
bar := 'two'
_baz := 'three'
",
)
.stdout("bar := \"two\"\n")
.status(EXIT_SUCCESS)
.run();
}
#[test]
fn evaluate_single_private() {
Test::new()
.arg("--evaluate")
.arg("foo")
.justfile(
"
[private]
foo := 'one'
bar := 'two'
_baz := 'three'
",
)
.stdout("one")
.status(EXIT_SUCCESS)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/which_function.rs | tests/which_function.rs | use super::*;
const HELLO_SCRIPT: &str = "#!/usr/bin/env bash
echo hello
";
#[test]
fn finds_executable() {
let tmp = tempdir();
let path = PathBuf::from(tmp.path());
Test::with_tempdir(tmp)
.justfile("p := which('hello.exe')")
.args(["--evaluate", "p"])
.write("hello.exe", HELLO_SCRIPT)
.make_executable("hello.exe")
.env("PATH", path.to_str().unwrap())
.env("JUST_UNSTABLE", "1")
.stdout(path.join("hello.exe").display().to_string())
.run();
}
#[test]
fn prints_empty_string_for_missing_executable() {
let tmp = tempdir();
let path = PathBuf::from(tmp.path());
Test::with_tempdir(tmp)
.justfile("p := which('goodbye.exe')")
.args(["--evaluate", "p"])
.write("hello.exe", HELLO_SCRIPT)
.make_executable("hello.exe")
.env("PATH", path.to_str().unwrap())
.env("JUST_UNSTABLE", "1")
.run();
}
#[test]
fn skips_non_executable_files() {
let tmp = tempdir();
let path = PathBuf::from(tmp.path());
Test::with_tempdir(tmp)
.justfile("p := which('hi')")
.args(["--evaluate", "p"])
.write("hello.exe", HELLO_SCRIPT)
.make_executable("hello.exe")
.write("hi", "just some regular file")
.env("PATH", path.to_str().unwrap())
.env("JUST_UNSTABLE", "1")
.run();
}
#[test]
fn supports_multiple_paths() {
let tmp = tempdir();
let path = PathBuf::from(tmp.path());
let path_var = env::join_paths([
path.join("subdir1").to_str().unwrap(),
path.join("subdir2").to_str().unwrap(),
])
.unwrap();
Test::with_tempdir(tmp)
.justfile("p := which('hello1.exe') + '+' + which('hello2.exe')")
.args(["--evaluate", "p"])
.write("subdir1/hello1.exe", HELLO_SCRIPT)
.make_executable("subdir1/hello1.exe")
.write("subdir2/hello2.exe", HELLO_SCRIPT)
.make_executable("subdir2/hello2.exe")
.env("PATH", path_var.to_str().unwrap())
.env("JUST_UNSTABLE", "1")
.stdout(format!(
"{}+{}",
path.join("subdir1").join("hello1.exe").display(),
path.join("subdir2").join("hello2.exe").display(),
))
.run();
}
#[test]
fn supports_shadowed_executables() {
enum Variation {
Dir1Dir2, // PATH=/tmp/.../dir1:/tmp/.../dir2
Dir2Dir1, // PATH=/tmp/.../dir2:/tmp/.../dir1
}
for variation in [Variation::Dir1Dir2, Variation::Dir2Dir1] {
let tmp = tempdir();
let path = PathBuf::from(tmp.path());
let path_var = match variation {
Variation::Dir1Dir2 => env::join_paths([
path.join("dir1").to_str().unwrap(),
path.join("dir2").to_str().unwrap(),
]),
Variation::Dir2Dir1 => env::join_paths([
path.join("dir2").to_str().unwrap(),
path.join("dir1").to_str().unwrap(),
]),
}
.unwrap();
let stdout = match variation {
Variation::Dir1Dir2 => format!("{}", path.join("dir1").join("shadowed.exe").display()),
Variation::Dir2Dir1 => format!("{}", path.join("dir2").join("shadowed.exe").display()),
};
Test::with_tempdir(tmp)
.justfile("p := which('shadowed.exe')")
.args(["--evaluate", "p"])
.write("dir1/shadowed.exe", HELLO_SCRIPT)
.make_executable("dir1/shadowed.exe")
.write("dir2/shadowed.exe", HELLO_SCRIPT)
.make_executable("dir2/shadowed.exe")
.env("PATH", path_var.to_str().unwrap())
.env("JUST_UNSTABLE", "1")
.stdout(stdout)
.run();
}
}
#[test]
fn ignores_nonexecutable_candidates() {
let tmp = tempdir();
let path = PathBuf::from(tmp.path());
let path_var = env::join_paths([
path.join("dummy").to_str().unwrap(),
path.join("subdir").to_str().unwrap(),
path.join("dummy").to_str().unwrap(),
])
.unwrap();
let dummy_exe = if cfg!(windows) {
"dummy/foo"
} else {
"dummy/foo.exe"
};
Test::with_tempdir(tmp)
.justfile("p := which('foo.exe')")
.args(["--evaluate", "p"])
.write("subdir/foo.exe", HELLO_SCRIPT)
.make_executable("subdir/foo.exe")
.write(dummy_exe, HELLO_SCRIPT)
.env("PATH", path_var.to_str().unwrap())
.env("JUST_UNSTABLE", "1")
.stdout(path.join("subdir").join("foo.exe").display().to_string())
.run();
}
#[test]
fn handles_absolute_path() {
let tmp = tempdir();
let path = PathBuf::from(tmp.path());
let abspath = path.join("subdir").join("foo.exe");
Test::with_tempdir(tmp)
.justfile(format!("p := which('{}')", abspath.display()))
.write("subdir/foo.exe", HELLO_SCRIPT)
.make_executable("subdir/foo.exe")
.write("pathdir/foo.exe", HELLO_SCRIPT)
.make_executable("pathdir/foo.exe")
.env("PATH", path.join("pathdir").to_str().unwrap())
.env("JUST_UNSTABLE", "1")
.args(["--evaluate", "p"])
.stdout(abspath.display().to_string())
.run();
}
#[test]
fn handles_dotslash() {
let tmp = tempdir();
let path = if cfg!(windows) {
tmp.path().into()
} else {
// canonicalize() is necessary here to account for the justfile prepending
// the canonicalized working directory to 'subdir/foo.exe'.
tmp.path().canonicalize().unwrap()
};
Test::with_tempdir(tmp)
.justfile("p := which('./foo.exe')")
.args(["--evaluate", "p"])
.write("foo.exe", HELLO_SCRIPT)
.make_executable("foo.exe")
.write("pathdir/foo.exe", HELLO_SCRIPT)
.make_executable("pathdir/foo.exe")
.env("PATH", path.join("pathdir").to_str().unwrap())
.env("JUST_UNSTABLE", "1")
.stdout(path.join("foo.exe").display().to_string())
.run();
}
#[test]
fn handles_dir_slash() {
let tmp = tempdir();
let path = if cfg!(windows) {
tmp.path().into()
} else {
// canonicalize() is necessary here to account for the justfile prepending
// the canonicalized working directory to 'subdir/foo.exe'.
tmp.path().canonicalize().unwrap()
};
Test::with_tempdir(tmp)
.justfile("p := which('subdir/foo.exe')")
.args(["--evaluate", "p"])
.write("subdir/foo.exe", HELLO_SCRIPT)
.make_executable("subdir/foo.exe")
.write("pathdir/foo.exe", HELLO_SCRIPT)
.make_executable("pathdir/foo.exe")
.env("PATH", path.join("pathdir").to_str().unwrap())
.env("JUST_UNSTABLE", "1")
.stdout(path.join("subdir").join("foo.exe").display().to_string())
.run();
}
#[test]
fn is_unstable() {
let tmp = tempdir();
let path = PathBuf::from(tmp.path());
Test::with_tempdir(tmp)
.justfile("p := which('hello.exe')")
.args(["--evaluate", "p"])
.write("hello.exe", HELLO_SCRIPT)
.make_executable("hello.exe")
.env("PATH", path.to_str().unwrap())
.stderr_regex(r".*The `which\(\)` function is currently unstable\..*")
.status(EXIT_FAILURE)
.run();
}
#[test]
fn require_error() {
Test::new()
.justfile("p := require('asdfasdf')")
.args(["--evaluate", "p"])
.stderr(
"
error: Call to function `require` failed: could not find executable `asdfasdf`
——▶ justfile:1:6
│
1 │ p := require('asdfasdf')
│ ^^^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn require_success() {
let tmp = tempdir();
let path = PathBuf::from(tmp.path());
Test::with_tempdir(tmp)
.justfile("p := require('hello.exe')")
.args(["--evaluate", "p"])
.write("hello.exe", HELLO_SCRIPT)
.make_executable("hello.exe")
.env("PATH", path.to_str().unwrap())
.stdout(path.join("hello.exe").display().to_string())
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/error_messages.rs | tests/error_messages.rs | use super::*;
#[test]
fn invalid_alias_attribute() {
Test::new()
.justfile("[private]\n[linux]\nalias t := test\n\ntest:\n")
.stderr(
"
error: Alias `t` has invalid attribute `linux`
——▶ justfile:3:7
│
3 │ alias t := test
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn expected_keyword() {
Test::new()
.justfile("foo := if '' == '' { '' } arlo { '' }")
.stderr(
"
error: Expected keyword `else` but found identifier `arlo`
——▶ justfile:1:27
│
1 │ foo := if '' == '' { '' } arlo { '' }
│ ^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn unexpected_character() {
Test::new()
.justfile("&~")
.stderr(
"
error: Expected character `&`
——▶ justfile:1:2
│
1 │ &~
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn argument_count_mismatch() {
Test::new()
.justfile("foo a b:")
.args(["foo"])
.stderr(
"
error: Recipe `foo` got 0 positional arguments but takes 2
usage:
just foo a b
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn file_path_is_indented_if_justfile_is_long() {
Test::new()
.justfile("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfoo")
.status(EXIT_FAILURE)
.stderr(
"
error: Expected '*', ':', '$', identifier, or '+', but found end of file
——▶ justfile:20:4
│
20 │ foo
│ ^
",
)
.run();
}
#[test]
fn file_paths_are_relative() {
Test::new()
.justfile("import 'foo/bar.just'")
.write("foo/bar.just", "baz")
.status(EXIT_FAILURE)
.stderr(format!(
"
error: Expected '*', ':', '$', identifier, or '+', but found end of file
——▶ foo{MAIN_SEPARATOR}bar.just:1:4
│
1 │ baz
│ ^
",
))
.run();
}
#[test]
#[cfg(not(windows))]
fn file_paths_not_in_subdir_are_absolute() {
Test::new()
.write("foo/justfile", "import '../bar.just'")
.write("bar.just", "baz")
.no_justfile()
.args(["--justfile", "foo/justfile"])
.status(EXIT_FAILURE)
.stderr_regex(
r"error: Expected '\*', ':', '\$', identifier, or '\+', but found end of file
——▶ /.*/bar.just:1:4
│
1 │ baz
│ \^
",
)
.run();
}
#[test]
fn redefinition_errors_properly_swap_types() {
Test::new()
.write("foo.just", "foo:")
.justfile("foo:\n echo foo\n\nmod foo 'foo.just'")
.status(EXIT_FAILURE)
.stderr(
"
error: Recipe `foo` defined on line 1 is redefined as a module on line 4
——▶ justfile:4:5
│
4 │ mod foo 'foo.just'
│ ^^^
",
)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/functions.rs | tests/functions.rs | use super::*;
#[test]
fn test_os_arch_functions_in_interpolation() {
Test::new()
.justfile(
r"
foo:
echo {{arch()}} {{os()}} {{os_family()}} {{num_cpus()}}
",
)
.stdout(
format!(
"{} {} {} {}\n",
target::arch(),
target::os(),
target::family(),
num_cpus::get()
)
.as_str(),
)
.stderr(
format!(
"echo {} {} {} {}\n",
target::arch(),
target::os(),
target::family(),
num_cpus::get()
)
.as_str(),
)
.run();
}
#[test]
fn test_os_arch_functions_in_expression() {
Test::new()
.justfile(
r"
a := arch()
o := os()
f := os_family()
n := num_cpus()
foo:
echo {{a}} {{o}} {{f}} {{n}}
",
)
.stdout(
format!(
"{} {} {} {}\n",
target::arch(),
target::os(),
target::family(),
num_cpus::get()
)
.as_str(),
)
.stderr(
format!(
"echo {} {} {} {}\n",
target::arch(),
target::os(),
target::family(),
num_cpus::get()
)
.as_str(),
)
.run();
}
#[cfg(not(windows))]
#[test]
fn env_var_functions() {
Test::new()
.justfile(
r"
p := env_var('USER')
b := env_var_or_default('ZADDY', 'HTAP')
x := env_var_or_default('XYZ', 'ABC')
foo:
/usr/bin/env echo '{{p}}' '{{b}}' '{{x}}'
",
)
.stdout(format!("{} HTAP ABC\n", env::var("USER").unwrap()).as_str())
.stderr(
format!(
"/usr/bin/env echo '{}' 'HTAP' 'ABC'\n",
env::var("USER").unwrap()
)
.as_str(),
)
.run();
}
#[cfg(not(windows))]
#[test]
fn path_functions() {
Test::new()
.justfile(
r"
we := without_extension('/foo/bar/baz.hello')
fs := file_stem('/foo/bar/baz.hello')
fn := file_name('/foo/bar/baz.hello')
dir := parent_directory('/foo/bar/baz.hello')
ext := extension('/foo/bar/baz.hello')
jn := join('a', 'b')
foo:
/usr/bin/env echo '{{we}}' '{{fs}}' '{{fn}}' '{{dir}}' '{{ext}}' '{{jn}}'
",
)
.stdout("/foo/bar/baz baz baz.hello /foo/bar hello a/b\n")
.stderr("/usr/bin/env echo '/foo/bar/baz' 'baz' 'baz.hello' '/foo/bar' 'hello' 'a/b'\n")
.run();
}
#[cfg(not(windows))]
#[test]
fn path_functions2() {
Test::new()
.justfile(
r"
we := without_extension('/foo/bar/baz')
fs := file_stem('/foo/bar/baz.hello.ciao')
fn := file_name('/bar/baz.hello.ciao')
dir := parent_directory('/foo/')
ext := extension('/foo/bar/baz.hello.ciao')
foo:
/usr/bin/env echo '{{we}}' '{{fs}}' '{{fn}}' '{{dir}}' '{{ext}}'
",
)
.stdout("/foo/bar/baz baz.hello baz.hello.ciao / ciao\n")
.stderr("/usr/bin/env echo '/foo/bar/baz' 'baz.hello' 'baz.hello.ciao' '/' 'ciao'\n")
.run();
}
#[cfg(not(windows))]
#[test]
fn broken_without_extension_function() {
Test::new()
.justfile(
r"
we := without_extension('')
foo:
/usr/bin/env echo '{{we}}'
",
)
.stderr(
format!(
"{} {}\n{}\n{}\n{}\n{}\n",
"error: Call to function `without_extension` failed:",
"Could not extract parent from ``",
" ——▶ justfile:1:8",
" │",
"1 │ we := without_extension(\'\')",
" │ ^^^^^^^^^^^^^^^^^"
)
.as_str(),
)
.status(EXIT_FAILURE)
.run();
}
#[cfg(not(windows))]
#[test]
fn broken_extension_function() {
Test::new()
.justfile(
r"
we := extension('')
foo:
/usr/bin/env echo '{{we}}'
",
)
.stderr(
format!(
"{}\n{}\n{}\n{}\n{}\n",
"error: Call to function `extension` failed: Could not extract extension from ``",
" ——▶ justfile:1:8",
" │",
"1 │ we := extension(\'\')",
" │ ^^^^^^^^^"
)
.as_str(),
)
.status(EXIT_FAILURE)
.run();
}
#[cfg(not(windows))]
#[test]
fn broken_extension_function2() {
Test::new()
.justfile(
r"
we := extension('foo')
foo:
/usr/bin/env echo '{{we}}'
",
)
.stderr(
format!(
"{}\n{}\n{}\n{}\n{}\n",
"error: Call to function `extension` failed: Could not extract extension from `foo`",
" ——▶ justfile:1:8",
" │",
"1 │ we := extension(\'foo\')",
" │ ^^^^^^^^^"
)
.as_str(),
)
.status(EXIT_FAILURE)
.run();
}
#[cfg(not(windows))]
#[test]
fn broken_file_stem_function() {
Test::new()
.justfile(
r"
we := file_stem('')
foo:
/usr/bin/env echo '{{we}}'
",
)
.stderr(
format!(
"{}\n{}\n{}\n{}\n{}\n",
"error: Call to function `file_stem` failed: Could not extract file stem from ``",
" ——▶ justfile:1:8",
" │",
"1 │ we := file_stem(\'\')",
" │ ^^^^^^^^^"
)
.as_str(),
)
.status(EXIT_FAILURE)
.run();
}
#[cfg(not(windows))]
#[test]
fn broken_file_name_function() {
Test::new()
.justfile(
r"
we := file_name('')
foo:
/usr/bin/env echo '{{we}}'
",
)
.stderr(
format!(
"{}\n{}\n{}\n{}\n{}\n",
"error: Call to function `file_name` failed: Could not extract file name from ``",
" ——▶ justfile:1:8",
" │",
"1 │ we := file_name(\'\')",
" │ ^^^^^^^^^"
)
.as_str(),
)
.status(EXIT_FAILURE)
.run();
}
#[cfg(not(windows))]
#[test]
fn broken_directory_function() {
Test::new()
.justfile(
r"
we := parent_directory('')
foo:
/usr/bin/env echo '{{we}}'
",
)
.stderr(
format!(
"{} {}\n{}\n{}\n{}\n{}\n",
"error: Call to function `parent_directory` failed:",
"Could not extract parent directory from ``",
" ——▶ justfile:1:8",
" │",
"1 │ we := parent_directory(\'\')",
" │ ^^^^^^^^^^^^^^^^"
)
.as_str(),
)
.status(EXIT_FAILURE)
.run();
}
#[cfg(not(windows))]
#[test]
fn broken_directory_function2() {
Test::new()
.justfile(
r"
we := parent_directory('/')
foo:
/usr/bin/env echo '{{we}}'
",
)
.stderr(
format!(
"{} {}\n{}\n{}\n{}\n{}\n",
"error: Call to function `parent_directory` failed:",
"Could not extract parent directory from `/`",
" ——▶ justfile:1:8",
" │",
"1 │ we := parent_directory(\'/\')",
" │ ^^^^^^^^^^^^^^^^"
)
.as_str(),
)
.status(EXIT_FAILURE)
.run();
}
#[cfg(windows)]
#[test]
fn env_var_functions() {
Test::new()
.justfile(
r#"
p := env_var('USERNAME')
b := env_var_or_default('ZADDY', 'HTAP')
x := env_var_or_default('XYZ', 'ABC')
foo:
/usr/bin/env echo '{{p}}' '{{b}}' '{{x}}'
"#,
)
.stdout(format!("{} HTAP ABC\n", env::var("USERNAME").unwrap()).as_str())
.stderr(
format!(
"/usr/bin/env echo '{}' 'HTAP' 'ABC'\n",
env::var("USERNAME").unwrap()
)
.as_str(),
)
.run();
}
#[test]
fn env_var_failure() {
Test::new()
.arg("a")
.justfile("a:\n echo {{env_var('ZADDY')}}")
.status(EXIT_FAILURE)
.stderr(
"error: Call to function `env_var` failed: environment variable `ZADDY` not present
——▶ justfile:2:10
│
2 │ echo {{env_var('ZADDY')}}
│ ^^^^^^^
",
)
.run();
}
#[test]
fn test_just_executable_function() {
Test::new()
.arg("a")
.justfile(
"
a:
@printf 'Executable path is: %s\\n' '{{ just_executable() }}'
",
)
.status(EXIT_SUCCESS)
.stdout(
format!(
"Executable path is: {}\n",
executable_path("just").to_str().unwrap()
)
.as_str(),
)
.run();
}
#[test]
fn test_os_arch_functions_in_default() {
Test::new()
.justfile(
r"
foo a=arch() o=os() f=os_family() n=num_cpus():
echo {{a}} {{o}} {{f}} {{n}}
",
)
.stdout(
format!(
"{} {} {} {}\n",
target::arch(),
target::os(),
target::family(),
num_cpus::get()
)
.as_str(),
)
.stderr(
format!(
"echo {} {} {} {}\n",
target::arch(),
target::os(),
target::family(),
num_cpus::get()
)
.as_str(),
)
.run();
}
#[test]
fn clean() {
Test::new()
.justfile(
"
foo:
echo {{ clean('a/../b') }}
",
)
.stdout("b\n")
.stderr("echo b\n")
.run();
}
#[test]
fn uppercase() {
Test::new()
.justfile(
"
foo:
echo {{ uppercase('bar') }}
",
)
.stdout("BAR\n")
.stderr("echo BAR\n")
.run();
}
#[test]
fn lowercase() {
Test::new()
.justfile(
"
foo:
echo {{ lowercase('BAR') }}
",
)
.stdout("bar\n")
.stderr("echo bar\n")
.run();
}
#[test]
fn uppercamelcase() {
Test::new()
.justfile(
"
foo:
echo {{ uppercamelcase('foo bar') }}
",
)
.stdout("FooBar\n")
.stderr("echo FooBar\n")
.run();
}
#[test]
fn lowercamelcase() {
Test::new()
.justfile(
"
foo:
echo {{ lowercamelcase('foo bar') }}
",
)
.stdout("fooBar\n")
.stderr("echo fooBar\n")
.run();
}
#[test]
fn snakecase() {
Test::new()
.justfile(
"
foo:
echo {{ snakecase('foo bar') }}
",
)
.stdout("foo_bar\n")
.stderr("echo foo_bar\n")
.run();
}
#[test]
fn kebabcase() {
Test::new()
.justfile(
"
foo:
echo {{ kebabcase('foo bar') }}
",
)
.stdout("foo-bar\n")
.stderr("echo foo-bar\n")
.run();
}
#[test]
fn shoutysnakecase() {
Test::new()
.justfile(
"
foo:
echo {{ shoutysnakecase('foo bar') }}
",
)
.stdout("FOO_BAR\n")
.stderr("echo FOO_BAR\n")
.run();
}
#[test]
fn titlecase() {
Test::new()
.justfile(
"
foo:
echo {{ titlecase('foo bar') }}
",
)
.stdout("Foo Bar\n")
.stderr("echo Foo Bar\n")
.run();
}
#[test]
fn shoutykebabcase() {
Test::new()
.justfile(
"
foo:
echo {{ shoutykebabcase('foo bar') }}
",
)
.stdout("FOO-BAR\n")
.stderr("echo FOO-BAR\n")
.run();
}
#[test]
fn trim() {
Test::new()
.justfile(
"
foo:
echo {{ trim(' bar ') }}
",
)
.stdout("bar\n")
.stderr("echo bar\n")
.run();
}
#[test]
fn replace() {
Test::new()
.justfile(
"
foo:
echo {{ replace('barbarbar', 'bar', 'foo') }}
",
)
.stdout("foofoofoo\n")
.stderr("echo foofoofoo\n")
.run();
}
#[test]
fn replace_regex() {
Test::new()
.justfile(
"
foo:
echo {{ replace_regex('123bar123bar123bar', '\\d+bar', 'foo') }}
",
)
.stdout("foofoofoo\n")
.stderr("echo foofoofoo\n")
.run();
}
#[test]
fn invalid_replace_regex() {
Test::new()
.justfile(
"
foo:
echo {{ replace_regex('barbarbar', 'foo\\', 'foo') }}
",
)
.stderr(
"error: Call to function `replace_regex` failed: regex parse error:
foo\\
^
error: incomplete escape sequence, reached end of pattern prematurely
——▶ justfile:2:11
│
2 │ echo {{ replace_regex('barbarbar', 'foo\\', 'foo') }}
│ ^^^^^^^^^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn capitalize() {
Test::new()
.justfile(
"
foo:
echo {{ capitalize('BAR') }}
",
)
.stdout("Bar\n")
.stderr("echo Bar\n")
.run();
}
#[test]
fn semver_matches() {
Test::new()
.justfile(
"
foo:
echo {{ semver_matches('0.1.0', '>=0.1.0') }}
echo {{ semver_matches('0.1.0', '=0.0.1') }}
",
)
.stdout("true\nfalse\n")
.stderr("echo true\necho false\n")
.run();
}
#[test]
fn trim_end_matches() {
assert_eval_eq("trim_end_matches('foo', 'o')", "f");
assert_eval_eq("trim_end_matches('fabab', 'ab')", "f");
assert_eval_eq("trim_end_matches('fbaabab', 'ab')", "fba");
}
#[test]
fn trim_end_match() {
assert_eval_eq("trim_end_match('foo', 'o')", "fo");
assert_eval_eq("trim_end_match('fabab', 'ab')", "fab");
}
#[test]
fn trim_start_matches() {
assert_eval_eq("trim_start_matches('oof', 'o')", "f");
assert_eval_eq("trim_start_matches('ababf', 'ab')", "f");
assert_eval_eq("trim_start_matches('ababbaf', 'ab')", "baf");
}
#[test]
fn trim_start_match() {
assert_eval_eq("trim_start_match('oof', 'o')", "of");
assert_eval_eq("trim_start_match('ababf', 'ab')", "abf");
}
#[test]
fn trim_start() {
assert_eval_eq("trim_start(' f ')", "f ");
}
#[test]
fn trim_end() {
assert_eval_eq("trim_end(' f ')", " f");
}
#[test]
fn append() {
assert_eval_eq("append('8', 'r s t')", "r8 s8 t8");
assert_eval_eq("append('.c', 'main sar x11')", "main.c sar.c x11.c");
assert_eval_eq("append('-', 'c v h y')", "c- v- h- y-");
assert_eval_eq(
"append('0000', '11 10 01 00')",
"110000 100000 010000 000000",
);
assert_eval_eq(
"append('tion', '
Determina
Acquisi
Motiva
Conjuc
')",
"Determination Acquisition Motivation Conjuction",
);
}
#[test]
fn prepend() {
assert_eval_eq("prepend('8', 'r s t\n \n ')", "8r 8s 8t");
assert_eval_eq(
"prepend('src/', 'main sar x11')",
"src/main src/sar src/x11",
);
assert_eval_eq("prepend('-', 'c\tv h\ny')", "-c -v -h -y");
assert_eval_eq(
"prepend('0000', '11 10 01 00')",
"000011 000010 000001 000000",
);
assert_eval_eq(
"prepend('April-', '
1st,
17th,
20th,
')",
"April-1st, April-17th, April-20th,",
);
}
#[test]
#[cfg(not(windows))]
fn join() {
assert_eval_eq("join('a', 'b', 'c', 'd')", "a/b/c/d");
assert_eval_eq("join('a', '/b', 'c', 'd')", "/b/c/d");
assert_eval_eq("join('a', '/b', '/c', 'd')", "/c/d");
assert_eval_eq("join('a', '/b', '/c', '/d')", "/d");
}
#[test]
#[cfg(windows)]
fn join() {
assert_eval_eq("join('a', 'b', 'c', 'd')", "a\\b\\c\\d");
assert_eval_eq("join('a', '\\b', 'c', 'd')", "\\b\\c\\d");
assert_eval_eq("join('a', '\\b', '\\c', 'd')", "\\c\\d");
assert_eval_eq("join('a', '\\b', '\\c', '\\d')", "\\d");
}
#[test]
fn join_argument_count_error() {
Test::new()
.justfile("x := join('a')")
.args(["--evaluate"])
.stderr(
"
error: Function `join` called with 1 argument but takes 2 or more
——▶ justfile:1:6
│
1 │ x := join(\'a\')
│ ^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn test_path_exists_filepath_exist() {
Test::new()
.tree(tree! {
testfile: ""
})
.justfile("x := path_exists('testfile')")
.args(["--evaluate", "x"])
.stdout("true")
.run();
}
#[test]
fn test_path_exists_filepath_doesnt_exist() {
Test::new()
.justfile("x := path_exists('testfile')")
.args(["--evaluate", "x"])
.stdout("false")
.run();
}
#[test]
fn error_errors_with_message() {
Test::new()
.justfile("x := error ('Thing Not Supported')")
.args(["--evaluate"])
.status(1)
.stderr(
"
error: Call to function `error` failed: Thing Not Supported
——▶ justfile:1:6
│
1 │ x := error ('Thing Not Supported')
│ ^^^^^
",
)
.run();
}
#[test]
fn test_absolute_path_resolves() {
let test_object = Test::new()
.justfile("path := absolute_path('./test_file')")
.args(["--evaluate", "path"]);
let mut tempdir = test_object.tempdir.path().to_owned();
// Just retrieves the current directory via env::current_dir(), which
// does the moral equivalent of canonicalize, which will remove symlinks.
// So, we have to canonicalize here, so that we can match it.
if cfg!(unix) {
tempdir = tempdir.canonicalize().unwrap();
}
test_object
.stdout(tempdir.join("test_file").to_str().unwrap().to_owned())
.run();
}
#[test]
fn test_absolute_path_resolves_parent() {
let test_object = Test::new()
.justfile("path := absolute_path('../test_file')")
.args(["--evaluate", "path"]);
let mut tempdir = test_object.tempdir.path().to_owned();
// Just retrieves the current directory via env::current_dir(), which
// does the moral equivalent of canonicalize, which will remove symlinks.
// So, we have to canonicalize here, so that we can match it.
if cfg!(unix) {
tempdir = tempdir.canonicalize().unwrap();
}
test_object
.stdout(
tempdir
.parent()
.unwrap()
.join("test_file")
.to_str()
.unwrap()
.to_owned(),
)
.run();
}
#[test]
fn path_exists_subdir() {
Test::new()
.tree(tree! {
foo: "",
bar: {
}
})
.justfile("x := path_exists('foo')")
.current_dir("bar")
.args(["--evaluate", "x"])
.stdout("true")
.run();
}
#[test]
fn uuid() {
Test::new()
.justfile("x := uuid()")
.args(["--evaluate", "x"])
.stdout_regex("........-....-....-....-............")
.run();
}
#[test]
fn choose() {
Test::new()
.justfile(r"x := choose('10', 'xXyYzZ')")
.args(["--evaluate", "x"])
.stdout_regex("^[X-Zx-z]{10}$")
.run();
}
#[test]
fn choose_bad_alphabet_empty() {
Test::new()
.justfile("x := choose('10', '')")
.args(["--evaluate"])
.status(1)
.stderr(
"
error: Call to function `choose` failed: empty alphabet
——▶ justfile:1:6
│
1 │ x := choose('10', '')
│ ^^^^^^
",
)
.run();
}
#[test]
fn choose_bad_alphabet_repeated() {
Test::new()
.justfile("x := choose('10', 'aa')")
.args(["--evaluate"])
.status(1)
.stderr(
"
error: Call to function `choose` failed: alphabet contains repeated character `a`
——▶ justfile:1:6
│
1 │ x := choose('10', 'aa')
│ ^^^^^^
",
)
.run();
}
#[test]
fn choose_bad_length() {
Test::new()
.justfile("x := choose('foo', HEX)")
.args(["--evaluate"])
.status(1)
.stderr(
"
error: Call to function `choose` failed: failed to parse `foo` as positive integer: invalid digit found in string
——▶ justfile:1:6
│
1 │ x := choose('foo', HEX)
│ ^^^^^^
",
)
.run();
}
#[test]
fn sha256() {
Test::new()
.justfile("x := sha256('5943ee37-0000-1000-8000-010203040506')")
.args(["--evaluate", "x"])
.stdout("2330d7f5eb94a820b54fed59a8eced236f80b633a504289c030b6a65aef58871")
.run();
}
#[test]
fn sha256_file() {
Test::new()
.justfile("x := sha256_file('sub/shafile')")
.tree(tree! {
sub: {
shafile: "just is great\n",
}
})
.current_dir("sub")
.args(["--evaluate", "x"])
.stdout("177b3d79aaafb53a7a4d7aaba99a82f27c73370e8cb0295571aade1e4fea1cd2")
.run();
}
#[test]
fn just_pid() {
let Output { stdout, pid, .. } = Test::new()
.args(["--evaluate", "x"])
.justfile("x := just_pid()")
.stdout_regex(r"\d+")
.run();
assert_eq!(stdout.parse::<u32>().unwrap(), pid);
}
#[test]
fn shell_no_argument() {
Test::new()
.justfile("var := shell()")
.args(["--evaluate"])
.stderr(
"
error: Function `shell` called with 0 arguments but takes 1 or more
——▶ justfile:1:8
│
1 │ var := shell()
│ ^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn shell_minimal() {
assert_eval_eq("shell('echo $1 $2', 'justice', 'legs')", "justice legs");
}
#[test]
fn shell_args() {
assert_eval_eq("shell('echo $@', 'justice', 'legs')", "justice legs");
}
#[test]
fn shell_first_arg() {
assert_eval_eq("shell('echo $0')", "echo $0");
}
#[test]
fn shell_error() {
Test::new()
.justfile("var := shell('exit 1')")
.args(["--evaluate"])
.stderr(
"
error: Call to function `shell` failed: Process exited with status code 1
——▶ justfile:1:8
│
1 │ var := shell('exit 1')
│ ^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn blake3() {
Test::new()
.justfile("x := blake3('5943ee37-0000-1000-8000-010203040506')")
.args(["--evaluate", "x"])
.stdout("026c9f740a793ff536ddf05f8915ea4179421f47f0fa9545476076e9ba8f3f2b")
.run();
}
#[test]
fn blake3_file() {
Test::new()
.justfile("x := blake3_file('sub/blakefile')")
.tree(tree! {
sub: {
blakefile: "just is great\n",
}
})
.current_dir("sub")
.args(["--evaluate", "x"])
.stdout("8379241877190ca4b94076a8c8f89fe5747f95c62f3e4bf41f7408a0088ae16d")
.run();
}
#[cfg(unix)]
#[test]
fn canonicalize() {
Test::new()
.args(["--evaluate", "x"])
.justfile("x := canonicalize('foo')")
.symlink("justfile", "foo")
.stdout_regex(".*/justfile")
.run();
}
#[test]
fn encode_uri_component() {
Test::new()
.justfile("x := encode_uri_component(\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~ \\t\\r\\n🌐\")")
.args(["--evaluate", "x"])
.stdout("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!%22%23%24%25%26'()*%2B%2C-.%2F%3A%3B%3C%3D%3E%3F%40%5B%5C%5D%5E_%60%7B%7C%7D~%20%09%0D%0A%F0%9F%8C%90")
.run();
}
#[test]
fn source_file() {
Test::new()
.args(["--evaluate", "x"])
.justfile("x := source_file()")
.stdout_regex(r".*[/\\]justfile")
.run();
Test::new()
.args(["--evaluate", "x"])
.justfile(
"
import 'foo.just'
",
)
.write("foo.just", "x := source_file()")
.stdout_regex(r".*[/\\]foo.just")
.run();
Test::new()
.args(["foo", "bar"])
.justfile(
"
mod foo
",
)
.write("foo.just", "x := source_file()\nbar:\n @echo '{{x}}'")
.stdout_regex(r".*[/\\]foo.just\n")
.run();
}
#[test]
fn source_directory() {
Test::new()
.args(["foo", "bar"])
.justfile(
"
mod foo
",
)
.write(
"foo/mod.just",
"x := source_directory()\nbar:\n @echo '{{x}}'",
)
.stdout_regex(r".*[/\\]foo\n")
.run();
}
#[test]
fn module_paths() {
Test::new()
.write(
"foo/bar.just",
"
imf := module_file()
imd := module_directory()
import-outer: import-inner
@import-inner pmf=module_file() pmd=module_directory():
echo import
echo '{{ imf }}'
echo '{{ imd }}'
echo '{{ pmf }}'
echo '{{ pmd }}'
echo '{{ module_file() }}'
echo '{{ module_directory() }}'
",
)
.write(
"baz/mod.just",
"
import 'foo/bar.just'
mmf := module_file()
mmd := module_directory()
outer: inner
@inner pmf=module_file() pmd=module_directory():
echo module
echo '{{ mmf }}'
echo '{{ mmd }}'
echo '{{ pmf }}'
echo '{{ pmd }}'
echo '{{ module_file() }}'
echo '{{ module_directory() }}'
",
)
.write(
"baz/foo/bar.just",
"
imf := module_file()
imd := module_directory()
import-outer: import-inner
@import-inner pmf=module_file() pmd=module_directory():
echo import
echo '{{ imf }}'
echo '{{ imd }}'
echo '{{ pmf }}'
echo '{{ pmd }}'
echo '{{ module_file() }}'
echo '{{ module_directory() }}'
",
)
.justfile(
"
import 'foo/bar.just'
mod baz
rmf := module_file()
rmd := module_directory()
outer: inner
@inner pmf=module_file() pmd=module_directory():
echo root
echo '{{ rmf }}'
echo '{{ rmd }}'
echo '{{ pmf }}'
echo '{{ pmd }}'
echo '{{ module_file() }}'
echo '{{ module_directory() }}'
",
)
.args([
"outer",
"import-outer",
"baz",
"outer",
"baz",
"import-outer",
])
.stdout_regex(
r"root
.*[/\\]just-test-tempdir......[/\\]justfile
.*[/\\]just-test-tempdir......
.*[/\\]just-test-tempdir......[/\\]justfile
.*[/\\]just-test-tempdir......
.*[/\\]just-test-tempdir......[/\\]justfile
.*[/\\]just-test-tempdir......
import
.*[/\\]just-test-tempdir......[/\\]justfile
.*[/\\]just-test-tempdir......
.*[/\\]just-test-tempdir......[/\\]justfile
.*[/\\]just-test-tempdir......
.*[/\\]just-test-tempdir......[/\\]justfile
.*[/\\]just-test-tempdir......
module
.*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just
.*[/\\]just-test-tempdir......[/\\]baz
.*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just
.*[/\\]just-test-tempdir......[/\\]baz
.*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just
.*[/\\]just-test-tempdir......[/\\]baz
import
.*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just
.*[/\\]just-test-tempdir......[/\\]baz
.*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just
.*[/\\]just-test-tempdir......[/\\]baz
.*[/\\]just-test-tempdir......[/\\]baz[/\\]mod.just
.*[/\\]just-test-tempdir......[/\\]baz
",
)
.run();
}
#[test]
fn is_dependency() {
let justfile = "
alpha: beta
@echo 'alpha {{is_dependency()}}'
beta: && gamma
@echo 'beta {{is_dependency()}}'
gamma:
@echo 'gamma {{is_dependency()}}'
";
Test::new()
.args(["alpha"])
.justfile(justfile)
.stdout("beta true\ngamma true\nalpha false\n")
.run();
Test::new()
.args(["beta"])
.justfile(justfile)
.stdout("beta false\ngamma true\n")
.run();
}
#[test]
fn unary_argument_count_mismamatch_error_message() {
Test::new()
.justfile("x := datetime()")
.args(["--evaluate"])
.stderr(
"
error: Function `datetime` called with 0 arguments but takes 1
——▶ justfile:1:6
│
1 │ x := datetime()
│ ^^^^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn dir_abbreviations_are_accepted() {
Test::new()
.justfile(
"
abbreviated := justfile_dir()
unabbreviated := justfile_directory()
@foo:
# {{ assert(abbreviated == unabbreviated, 'fail') }}
",
)
.run();
}
#[test]
fn invocation_dir_native_abbreviation_is_accepted() {
Test::new()
.justfile(
"
abbreviated := invocation_directory_native()
unabbreviated := invocation_dir_native()
@foo:
# {{ assert(abbreviated == unabbreviated, 'fail') }}
",
)
.run();
}
#[test]
fn absolute_path_argument_is_relative_to_submodule_working_directory() {
Test::new()
.justfile("mod foo")
.write("foo/baz", "")
.write(
"foo/mod.just",
r#"
bar:
@echo "{{ absolute_path('baz') }}"
"#,
)
.stdout_regex(r".*[/\\]foo[/\\]baz\n")
.args(["foo", "bar"])
.run();
}
#[test]
fn blake3_file_argument_is_relative_to_submodule_working_directory() {
Test::new()
.justfile("mod foo")
.write("foo/baz", "")
.write(
"foo/mod.just",
"
bar:
@echo {{ blake3_file('baz') }}
",
)
.stdout("af1349b9f5f9a1a6a0404dea36dcc9499bcb25c9adc112b7cc9a93cae41f3262\n")
.args(["foo", "bar"])
.run();
}
#[test]
fn canonicalize_argument_is_relative_to_submodule_working_directory() {
Test::new()
.justfile("mod foo")
.write("foo/baz", "")
.write(
"foo/mod.just",
r#"
bar:
@echo "{{ canonicalize('baz') }}"
"#,
)
.stdout_regex(r".*[/\\]foo[/\\]baz\n")
.args(["foo", "bar"])
.run();
}
#[test]
fn path_exists_argument_is_relative_to_submodule_working_directory() {
Test::new()
.justfile("mod foo")
.write("foo/baz", "")
.write(
"foo/mod.just",
"
bar:
@echo {{ path_exists('baz') }}
",
)
.stdout_regex("true\n")
.args(["foo", "bar"])
.run();
}
#[test]
fn sha256_file_argument_is_relative_to_submodule_working_directory() {
Test::new()
.justfile("mod foo")
.write("foo/baz", "")
.write(
"foo/mod.just",
"
bar:
@echo {{ sha256_file('baz') }}
",
)
.stdout_regex("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\n")
.args(["foo", "bar"])
.run();
}
#[test]
fn style_command_default() {
Test::new()
.justfile(
r#"
foo:
@echo '{{ style("command") }}foo{{NORMAL}}'
"#,
)
.stdout("\x1b[1mfoo\x1b[0m\n")
.run();
}
#[test]
fn style_command_non_default() {
Test::new()
.justfile(
r#"
foo:
@echo '{{ style("command") }}foo{{NORMAL}}'
"#,
)
.args(["--command-color", "red"])
.stdout("\x1b[1;31mfoo\x1b[0m\n")
.run();
}
#[test]
fn style_error() {
Test::new()
.justfile(
r#"
foo:
@echo '{{ style("error") }}foo{{NORMAL}}'
"#,
)
.stdout("\x1b[1;31mfoo\x1b[0m\n")
.run();
}
#[test]
fn style_warning() {
Test::new()
.justfile(
r#"
foo:
@echo '{{ style("warning") }}foo{{NORMAL}}'
"#,
)
.stdout("\x1b[1;33mfoo\x1b[0m\n")
.run();
}
#[test]
fn style_unknown() {
Test::new()
.justfile(
r#"
foo:
@echo '{{ style("hippo") }}foo{{NORMAL}}'
"#,
)
.stderr(
r#"
error: Call to function `style` failed: unknown style: `hippo`
——▶ justfile:2:13
│
2 │ @echo '{{ style("hippo") }}foo{{NORMAL}}'
│ ^^^^^
"#,
)
.status(EXIT_FAILURE)
.run();
}
#[test]
fn read() {
Test::new()
.justfile("foo := read('bar')")
.write("bar", "baz")
.args(["--evaluate", "foo"])
.stdout("baz")
.run();
}
#[test]
fn read_file_not_found() {
Test::new()
.justfile("foo := read('bar')")
.args(["--evaluate", "foo"])
.stderr_regex(r"error: Call to function `read` failed: I/O error reading `bar`: .*")
.status(EXIT_FAILURE)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/no_dependencies.rs | tests/no_dependencies.rs | use super::*;
#[test]
fn skip_normal_dependency() {
Test::new()
.justfile(
"
a:
@echo 'a'
b: a
@echo 'b'
",
)
.args(["--no-deps", "b"])
.stdout("b\n")
.run();
}
#[test]
fn skip_prior_dependency() {
Test::new()
.justfile(
"
a:
@echo 'a'
b: && a
@echo 'b'
",
)
.args(["--no-deps", "b"])
.stdout("b\n")
.run();
}
#[test]
fn skip_dependency_multi() {
Test::new()
.justfile(
"
a:
@echo 'a'
b: && a
@echo 'b'
",
)
.args(["--no-deps", "b", "a"])
.stdout("b\na\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/shell.rs | tests/shell.rs | use super::*;
const JUSTFILE: &str = "
expression := `EXPRESSION`
recipe default=`DEFAULT`:
{{expression}}
{{default}}
RECIPE
";
/// Test that --shell correctly sets the shell
#[test]
#[cfg_attr(windows, ignore)]
fn flag() {
let tmp = temptree! {
justfile: JUSTFILE,
shell: "#!/usr/bin/env bash\necho \"$@\"",
};
let shell = tmp.path().join("shell");
#[cfg(not(windows))]
{
let permissions = std::os::unix::fs::PermissionsExt::from_mode(0o700);
fs::set_permissions(&shell, permissions).unwrap();
}
let output = Command::new(executable_path("just"))
.current_dir(tmp.path())
.arg("--shell")
.arg(shell)
.output()
.unwrap();
let stdout = "-cu -cu EXPRESSION\n-cu -cu DEFAULT\n-cu RECIPE\n";
assert_stdout(&output, stdout);
}
/// Test that we can use `set shell` to use cmd.exe on windows
#[test]
#[cfg(windows)]
fn cmd() {
let tmp = temptree! {
justfile: r#"
set shell := ["cmd.exe", "/C"]
x := `Echo`
recipe:
REM foo
Echo "{{x}}"
"#,
};
let output = Command::new(executable_path("just"))
.current_dir(tmp.path())
.output()
.unwrap();
let stdout = "\\\"ECHO is on.\\\"\r\n";
assert_stdout(&output, stdout);
}
/// Test that we can use `set shell` to use cmd.exe on windows
#[test]
#[cfg(windows)]
fn powershell() {
let tmp = temptree! {
justfile: r#"
set shell := ["powershell.exe", "-c"]
x := `Write-Host "Hello, world!"`
recipe:
For ($i=0; $i -le 10; $i++) { Write-Host $i }
Write-Host "{{x}}"
"#
,
};
let output = Command::new(executable_path("just"))
.current_dir(tmp.path())
.output()
.unwrap();
let stdout = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\nHello, world!\n";
assert_stdout(&output, stdout);
}
#[test]
fn shell_args() {
Test::new()
.arg("--shell-arg")
.arg("-c")
.justfile(
"
default:
echo A${foo}A
",
)
.shell(false)
.stdout("AA\n")
.stderr("echo A${foo}A\n")
.run();
}
#[test]
fn shell_override() {
Test::new()
.arg("--shell")
.arg("bash")
.justfile(
"
set shell := ['foo-bar-baz']
default:
echo hello
",
)
.shell(false)
.stdout("hello\n")
.stderr("echo hello\n")
.run();
}
#[test]
fn shell_arg_override() {
Test::new()
.arg("--shell-arg")
.arg("-cu")
.justfile(
"
set shell := ['foo-bar-baz']
default:
echo hello
",
)
.stdout("hello\n")
.stderr("echo hello\n")
.shell(false)
.run();
}
#[test]
fn set_shell() {
Test::new()
.justfile(
"
set shell := ['echo', '-n']
x := `bar`
foo:
echo {{x}}
echo foo
",
)
.stdout("echo barecho foo")
.stderr("echo bar\necho foo\n")
.shell(false)
.run();
}
#[test]
fn recipe_shell_not_found_error_message() {
Test::new()
.justfile(
"
foo:
@echo bar
",
)
.shell(false)
.args(["--shell", "NOT_A_REAL_SHELL"])
.stderr_regex(
"error: Recipe `foo` could not be run because just could not find the shell: .*\n",
)
.status(1)
.run();
}
#[test]
fn backtick_recipe_shell_not_found_error_message() {
Test::new()
.justfile(
"
bar := `echo bar`
foo:
echo {{bar}}
",
)
.shell(false)
.args(["--shell", "NOT_A_REAL_SHELL"])
.stderr_regex("(?s)error: Backtick could not be run because just could not find the shell:.*")
.status(1)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/invocation_directory.rs | tests/invocation_directory.rs | use super::*;
#[cfg(unix)]
fn convert_native_path(path: &Path) -> String {
fs::canonicalize(path)
.expect("canonicalize failed")
.to_str()
.map(str::to_string)
.expect("unicode decode failed")
}
#[cfg(windows)]
fn convert_native_path(path: &Path) -> String {
// Translate path from windows style to unix style
let mut cygpath = Command::new(env::var_os("JUST_CYGPATH").unwrap_or("cygpath".into()));
cygpath.arg("--unix");
cygpath.arg(path);
let output = cygpath.output().expect("executing cygpath failed");
assert!(output.status.success());
let stdout = str::from_utf8(&output.stdout).expect("cygpath output was not utf8");
if stdout.ends_with('\n') {
&stdout[0..stdout.len() - 1]
} else if stdout.ends_with("\r\n") {
&stdout[0..stdout.len() - 2]
} else {
stdout
}
.to_owned()
}
#[test]
fn test_invocation_directory() {
let tmp = tempdir();
let mut justfile_path = tmp.path().to_path_buf();
justfile_path.push("justfile");
fs::write(
justfile_path,
"default:\n @cd {{invocation_directory()}}\n @echo {{invocation_directory()}}",
)
.unwrap();
let mut subdir = tmp.path().to_path_buf();
subdir.push("subdir");
fs::create_dir(&subdir).unwrap();
let output = Command::new(executable_path("just"))
.current_dir(&subdir)
.args(["--shell", "sh"])
.output()
.expect("just invocation failed");
let mut failure = false;
let expected_status = 0;
let expected_stdout = convert_native_path(&subdir) + "\n";
let expected_stderr = "";
let status = output.status.code().unwrap();
if status != expected_status {
println!("bad status: {status} != {expected_status}");
failure = true;
}
let stdout = str::from_utf8(&output.stdout).unwrap();
if stdout != expected_stdout {
println!("bad stdout:\ngot:\n{stdout:?}\n\nexpected:\n{expected_stdout:?}");
failure = true;
}
let stderr = str::from_utf8(&output.stderr).unwrap();
if stderr != expected_stderr {
println!("bad stderr:\ngot:\n{stderr:?}\n\nexpected:\n{expected_stderr:?}");
failure = true;
}
assert!(!failure, "test failed");
}
#[test]
fn invocation_directory_native() {
let Output {
stdout, tempdir, ..
} = Test::new()
.justfile("x := invocation_directory_native()")
.args(["--evaluate", "x"])
.stdout_regex(".*")
.run();
if cfg!(windows) {
assert_eq!(Path::new(&stdout), tempdir.path());
} else {
assert_eq!(Path::new(&stdout), tempdir.path().canonicalize().unwrap());
}
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/default.rs | tests/default.rs | use super::*;
#[test]
fn default_attribute_overrides_first_recipe() {
Test::new()
.justfile(
"
foo:
@echo FOO
[default]
bar:
@echo BAR
",
)
.stdout("BAR\n")
.run();
}
#[test]
fn default_attribute_may_only_appear_once_per_justfile() {
Test::new()
.justfile(
"
[default]
foo:
[default]
bar:
",
)
.stderr(
"
error: Recipe `foo` has duplicate `[default]` attribute, which may only appear once per module
——▶ justfile:2:1
│
2 │ foo:
│ ^^^
"
)
.status(EXIT_FAILURE)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/search.rs | tests/search.rs | use super::*;
fn search_test<P: AsRef<Path>>(path: P, args: &[&str]) {
let binary = executable_path("just");
let output = Command::new(binary)
.current_dir(path)
.args(args)
.output()
.expect("just invocation failed");
assert_eq!(output.status.code().unwrap(), 0);
let stdout = str::from_utf8(&output.stdout).unwrap();
assert_eq!(stdout, "ok\n");
let stderr = str::from_utf8(&output.stderr).unwrap();
assert_eq!(stderr, "echo ok\n");
}
#[test]
fn test_justfile_search() {
let tmp = temptree! {
justfile: "default:\n\techo ok",
a: {
b: {
c: {
d: {},
},
},
},
};
search_test(tmp.path().join("a/b/c/d"), &[]);
}
#[test]
fn test_capitalized_justfile_search() {
let tmp = temptree! {
Justfile: "default:\n\techo ok",
a: {
b: {
c: {
d: {},
},
},
},
};
search_test(tmp.path().join("a/b/c/d"), &[]);
}
#[test]
fn test_upwards_path_argument() {
let tmp = temptree! {
justfile: "default:\n\techo ok",
a: {
justfile: "default:\n\techo bad",
},
};
search_test(tmp.path().join("a"), &["../"]);
search_test(tmp.path().join("a"), &["../default"]);
}
#[test]
fn test_downwards_path_argument() {
let tmp = temptree! {
justfile: "default:\n\techo bad",
a: {
justfile: "default:\n\techo ok",
},
};
let path = tmp.path();
search_test(path, &["a/"]);
search_test(path, &["a/default"]);
search_test(path, &["./a/"]);
search_test(path, &["./a/default"]);
search_test(path, &["./a/"]);
search_test(path, &["./a/default"]);
}
#[test]
fn test_upwards_multiple_path_argument() {
let tmp = temptree! {
justfile: "default:\n\techo ok",
a: {
b: {
justfile: "default:\n\techo bad",
},
},
};
let path = tmp.path().join("a").join("b");
search_test(&path, &["../../"]);
search_test(&path, &["../../default"]);
}
#[test]
fn test_downwards_multiple_path_argument() {
let tmp = temptree! {
justfile: "default:\n\techo bad",
a: {
b: {
justfile: "default:\n\techo ok",
},
},
};
let path = tmp.path();
search_test(path, &["a/b/"]);
search_test(path, &["a/b/default"]);
search_test(path, &["./a/b/"]);
search_test(path, &["./a/b/default"]);
search_test(path, &["./a/b/"]);
search_test(path, &["./a/b/default"]);
}
#[test]
fn single_downwards() {
let tmp = temptree! {
justfile: "default:\n\techo ok",
child: {},
};
let path = tmp.path();
search_test(path, &["child/"]);
}
#[test]
fn single_upwards() {
let tmp = temptree! {
justfile: "default:\n\techo ok",
child: {},
};
let path = tmp.path().join("child");
search_test(path, &["../"]);
}
#[test]
fn double_upwards() {
let tmp = temptree! {
justfile: "default:\n\techo ok",
foo: {
bar: {
justfile: "default:\n\techo foo",
},
},
};
let path = tmp.path().join("foo/bar");
search_test(path, &["../default"]);
}
#[test]
fn find_dot_justfile() {
Test::new()
.justfile(
"
foo:
echo bad
",
)
.tree(tree! {
dir: {
".justfile": "
foo:
echo ok
"
}
})
.current_dir("dir")
.stderr("echo ok\n")
.stdout("ok\n")
.run();
}
#[test]
fn dot_justfile_conflicts_with_justfile() {
Test::new()
.justfile(
"
foo:
",
)
.tree(tree! {
".justfile": "
foo:
",
})
.stderr_regex("error: Multiple candidate justfiles found in `.*`: `.justfile` and `justfile`\n")
.status(EXIT_FAILURE)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/json.rs | tests/json.rs | use super::*;
#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct Alias<'a> {
attributes: Vec<&'a str>,
name: &'a str,
target: &'a str,
}
#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct Assignment<'a> {
export: bool,
name: &'a str,
private: bool,
value: serde_json::Value,
}
#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct Dependency<'a> {
arguments: Vec<Value>,
recipe: &'a str,
}
#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct Interpreter<'a> {
arguments: Vec<&'a str>,
command: &'a str,
}
#[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Module<'a> {
aliases: BTreeMap<&'a str, Alias<'a>>,
assignments: BTreeMap<&'a str, Assignment<'a>>,
doc: Option<&'a str>,
first: Option<&'a str>,
groups: Vec<&'a str>,
modules: BTreeMap<&'a str, Module<'a>>,
recipes: BTreeMap<&'a str, Recipe<'a>>,
settings: Settings<'a>,
source: PathBuf,
unexports: Vec<&'a str>,
warnings: Vec<&'a str>,
}
#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct Parameter<'a> {
default: Option<&'a str>,
export: bool,
help: Option<&'a str>,
kind: &'a str,
long: Option<&'a str>,
name: &'a str,
pattern: Option<&'a str>,
short: Option<char>,
value: Option<&'a str>,
}
#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct Recipe<'a> {
attributes: Vec<Value>,
body: Vec<Value>,
dependencies: Vec<Dependency<'a>>,
doc: Option<&'a str>,
name: &'a str,
namepath: &'a str,
parameters: Vec<Parameter<'a>>,
priors: u32,
private: bool,
quiet: bool,
shebang: bool,
}
#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct Settings<'a> {
allow_duplicate_recipes: bool,
allow_duplicate_variables: bool,
dotenv_filename: Option<&'a str>,
dotenv_load: bool,
dotenv_override: bool,
dotenv_path: Option<&'a str>,
dotenv_required: bool,
export: bool,
fallback: bool,
ignore_comments: bool,
no_exit_message: bool,
positional_arguments: bool,
quiet: bool,
shell: Option<Interpreter<'a>>,
tempdir: Option<&'a str>,
unstable: bool,
windows_powershell: bool,
windows_shell: Option<&'a str>,
working_directory: Option<&'a str>,
}
#[track_caller]
fn case(justfile: &str, expected: Module) {
case_with_submodule(justfile, None, expected);
}
fn fix_source(dir: &Path, module: &mut Module) {
let filename = if module.source.as_os_str().is_empty() {
Path::new("justfile")
} else {
&module.source
};
module.source = if cfg!(target_os = "macos") {
dir.canonicalize().unwrap().join(filename)
} else {
dir.join(filename)
};
for module in module.modules.values_mut() {
fix_source(dir, module);
}
}
#[track_caller]
fn case_with_submodule(justfile: &str, submodule: Option<(&str, &str)>, mut expected: Module) {
let mut test = Test::new()
.justfile(justfile)
.args(["--dump", "--dump-format", "json"])
.stdout_regex(".*");
if let Some((path, source)) = submodule {
test = test.write(path, source);
}
fix_source(test.tempdir.path(), &mut expected);
let actual = test.run().stdout;
let actual: Module = serde_json::from_str(actual.as_str()).unwrap();
pretty_assertions::assert_eq!(actual, expected);
}
#[test]
fn alias() {
case(
"
alias f := foo
foo:
",
Module {
aliases: [(
"f",
Alias {
name: "f",
target: "foo",
..default()
},
)]
.into(),
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn assignment() {
case(
"foo := 'bar'",
Module {
assignments: [(
"foo",
Assignment {
name: "foo",
value: "bar".into(),
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn private_assignment() {
case(
"
_foo := 'foo'
[private]
bar := 'bar'
",
Module {
assignments: [
(
"_foo",
Assignment {
name: "_foo",
value: "foo".into(),
private: true,
..default()
},
),
(
"bar",
Assignment {
name: "bar",
value: "bar".into(),
private: true,
..default()
},
),
]
.into(),
..default()
},
);
}
#[test]
fn body() {
case(
"
foo:
bar
abc{{ 'xyz' }}def
",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
body: [json!(["bar"]), json!(["abc", ["xyz"], "def"])].into(),
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn dependencies() {
case(
"
foo:
bar: foo
",
Module {
first: Some("foo"),
recipes: [
(
"foo",
Recipe {
name: "foo",
namepath: "foo",
..default()
},
),
(
"bar",
Recipe {
name: "bar",
namepath: "bar",
dependencies: [Dependency {
recipe: "foo",
..default()
}]
.into(),
priors: 1,
..default()
},
),
]
.into(),
..default()
},
);
}
#[test]
fn dependency_argument() {
case(
"
x := 'foo'
foo *args:
bar: (
foo
'baz'
('baz')
('a' + 'b')
`echo`
x
if 'a' == 'b' { 'c' } else { 'd' }
arch()
env_var('foo')
join('a', 'b')
replace('a', 'b', 'c')
)
",
Module {
assignments: [(
"x",
Assignment {
name: "x",
value: "foo".into(),
..default()
},
)]
.into(),
first: Some("foo"),
recipes: [
(
"foo",
Recipe {
name: "foo",
namepath: "foo",
parameters: [Parameter {
kind: "star",
name: "args",
..default()
}]
.into(),
..default()
},
),
(
"bar",
Recipe {
name: "bar",
namepath: "bar",
dependencies: [Dependency {
recipe: "foo",
arguments: [
json!("baz"),
json!("baz"),
json!(["concatenate", "a", "b"]),
json!(["evaluate", "echo"]),
json!(["variable", "x"]),
json!(["if", ["==", "a", "b"], "c", "d"]),
json!(["call", "arch"]),
json!(["call", "env_var", "foo"]),
json!(["call", "join", "a", "b"]),
json!(["call", "replace", "a", "b", "c"]),
]
.into(),
}]
.into(),
priors: 1,
..default()
},
),
]
.into(),
..default()
},
);
}
#[test]
fn duplicate_recipes() {
case(
"
set allow-duplicate-recipes
alias f := foo
foo:
foo bar:
",
Module {
aliases: [(
"f",
Alias {
name: "f",
target: "foo",
..default()
},
)]
.into(),
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
parameters: [Parameter {
kind: "singular",
name: "bar",
..default()
}]
.into(),
..default()
},
)]
.into(),
settings: Settings {
allow_duplicate_recipes: true,
..default()
},
..default()
},
);
}
#[test]
fn duplicate_variables() {
case(
"
set allow-duplicate-variables
x := 'foo'
x := 'bar'
",
Module {
assignments: [(
"x",
Assignment {
name: "x",
value: "bar".into(),
..default()
},
)]
.into(),
settings: Settings {
allow_duplicate_variables: true,
..default()
},
..default()
},
);
}
#[test]
fn doc_comment() {
case(
"# hello\nfoo:",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
doc: Some("hello"),
name: "foo",
namepath: "foo",
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn empty_justfile() {
case("", Module::default());
}
#[test]
fn parameters() {
case(
"
a:
b x:
c x='y':
d +x:
e *x:
f $x:
",
Module {
first: Some("a"),
recipes: [
(
"a",
Recipe {
name: "a",
namepath: "a",
..default()
},
),
(
"b",
Recipe {
name: "b",
namepath: "b",
parameters: [Parameter {
kind: "singular",
name: "x",
..default()
}]
.into(),
..default()
},
),
(
"c",
Recipe {
name: "c",
namepath: "c",
parameters: [Parameter {
default: Some("y"),
kind: "singular",
name: "x",
..default()
}]
.into(),
..default()
},
),
(
"d",
Recipe {
name: "d",
namepath: "d",
parameters: [Parameter {
kind: "plus",
name: "x",
..default()
}]
.into(),
..default()
},
),
(
"e",
Recipe {
name: "e",
namepath: "e",
parameters: [Parameter {
kind: "star",
name: "x",
..default()
}]
.into(),
..default()
},
),
(
"f",
Recipe {
name: "f",
namepath: "f",
parameters: [Parameter {
export: true,
kind: "singular",
name: "x",
..default()
}]
.into(),
..default()
},
),
]
.into(),
..default()
},
);
}
#[test]
fn priors() {
case(
"
a:
b: a && c
c:
",
Module {
first: Some("a"),
recipes: [
(
"a",
Recipe {
name: "a",
namepath: "a",
..default()
},
),
(
"b",
Recipe {
dependencies: [
Dependency {
recipe: "a",
..default()
},
Dependency {
recipe: "c",
..default()
},
]
.into(),
name: "b",
namepath: "b",
priors: 1,
..default()
},
),
(
"c",
Recipe {
name: "c",
namepath: "c",
..default()
},
),
]
.into(),
..default()
},
);
}
#[test]
fn private() {
case(
"_foo:",
Module {
first: Some("_foo"),
recipes: [(
"_foo",
Recipe {
name: "_foo",
namepath: "_foo",
private: true,
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn quiet() {
case(
"@foo:",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
quiet: true,
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn settings() {
case(
"
set allow-duplicate-recipes
set dotenv-filename := \"filename\"
set dotenv-load
set dotenv-path := \"path\"
set export
set fallback
set ignore-comments
set positional-arguments
set quiet
set shell := ['a', 'b', 'c']
foo:
#!bar
",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
shebang: true,
body: [json!(["#!bar"])].into(),
..default()
},
)]
.into(),
settings: Settings {
allow_duplicate_recipes: true,
dotenv_filename: Some("filename"),
dotenv_path: Some("path"),
dotenv_load: true,
export: true,
fallback: true,
ignore_comments: true,
positional_arguments: true,
quiet: true,
shell: Some(Interpreter {
arguments: ["b", "c"].into(),
command: "a",
}),
..default()
},
..default()
},
);
}
#[test]
fn shebang() {
case(
"
foo:
#!bar
",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
shebang: true,
body: [json!(["#!bar"])].into(),
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn simple() {
case(
"foo:",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn attribute() {
case(
"
[no-exit-message]
foo:
",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
attributes: [json!("no-exit-message")].into(),
name: "foo",
namepath: "foo",
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn single_metadata_attribute() {
case(
"
[metadata('example')]
foo:
",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
attributes: [json!({"metadata": ["example"]})].into(),
name: "foo",
namepath: "foo",
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn multiple_metadata_attributes() {
case(
"
[metadata('example')]
[metadata('sample')]
foo:
",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
attributes: [
json!({"metadata": ["example"]}),
json!({"metadata": ["sample"]}),
]
.into(),
name: "foo",
namepath: "foo",
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn multiple_metadata_attributes_with_multiple_arguments() {
case(
"
[metadata('example', 'arg1')]
[metadata('sample', 'argument')]
foo:
",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
attributes: [
json!({"metadata": ["example", "arg1"]}),
json!({"metadata": ["sample", "argument"]}),
]
.into(),
name: "foo",
namepath: "foo",
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn module() {
case_with_submodule(
"
# hello
mod foo
",
Some(("foo.just", "bar:")),
Module {
modules: [(
"foo",
Module {
doc: Some("hello"),
first: Some("bar"),
source: "foo.just".into(),
recipes: [(
"bar",
Recipe {
name: "bar",
namepath: "foo::bar",
..default()
},
)]
.into(),
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn module_group() {
case_with_submodule(
"
[group('alpha')]
mod foo
",
Some(("foo.just", "bar:")),
Module {
modules: [(
"foo",
Module {
first: Some("bar"),
groups: ["alpha"].into(),
source: "foo.just".into(),
recipes: [(
"bar",
Recipe {
name: "bar",
namepath: "foo::bar",
..default()
},
)]
.into(),
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn recipes_with_private_attribute_are_private() {
case(
"
[private]
foo:
",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
attributes: [json!("private")].into(),
name: "foo",
namepath: "foo",
private: true,
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn doc_attribute_overrides_comment() {
case(
"
# COMMENT
[doc('ATTRIBUTE')]
foo:
",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
attributes: [json!({"doc": "ATTRIBUTE"})].into(),
doc: Some("ATTRIBUTE"),
name: "foo",
namepath: "foo",
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn format_string() {
case(
"
foo := f'abc'
",
Module {
assignments: [(
"foo",
Assignment {
name: "foo",
value: json!(["format", "abc"]),
..default()
},
)]
.into(),
..default()
},
);
case(
"
foo := f'abc{{'bar'}}xyz'
",
Module {
assignments: [(
"foo",
Assignment {
name: "foo",
value: json!(["format", "abc", "bar", "xyz"]),
..default()
},
)]
.into(),
..default()
},
);
case(
"
foo := f'abc{{'bar'}}xyz{{'baz' + 'buzz'}}123'
",
Module {
assignments: [(
"foo",
Assignment {
name: "foo",
value: json!([
"format",
"abc",
"bar",
"xyz",
["concatenate", "baz", "buzz"],
"123"
]),
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn arg_pattern() {
case(
"[arg('bar', pattern='BAR')]\nfoo bar:",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
attributes: [json!({
"arg": {
"help": null,
"long": null,
"name": "bar",
"pattern": "BAR",
"short": null,
"value": null,
}
})]
.into(),
parameters: [Parameter {
kind: "singular",
name: "bar",
pattern: Some("BAR"),
..default()
}]
.into(),
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn arg_long() {
case(
"[arg('bar', long='BAR')]\nfoo bar:",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
attributes: [json!({
"arg": {
"help": null,
"long": "BAR",
"name": "bar",
"pattern": null,
"short": null,
"value": null,
}
})]
.into(),
parameters: [Parameter {
kind: "singular",
name: "bar",
long: Some("BAR"),
..default()
}]
.into(),
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn arg_short() {
case(
"[arg('bar', short='B')]\nfoo bar:",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
attributes: [json!({
"arg": {
"help": null,
"long": null,
"name": "bar",
"pattern": null,
"short": "B",
"value": null,
}
})]
.into(),
parameters: [Parameter {
kind: "singular",
name: "bar",
short: Some('B'),
..default()
}]
.into(),
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn arg_value() {
case(
"[arg('bar', short='B', value='hello')]\nfoo bar:",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
attributes: [json!({
"arg": {
"help": null,
"long": null,
"name": "bar",
"pattern": null,
"short": "B",
"value": "hello",
}
})]
.into(),
parameters: [Parameter {
kind: "singular",
name: "bar",
short: Some('B'),
value: Some("hello"),
..default()
}]
.into(),
..default()
},
)]
.into(),
..default()
},
);
}
#[test]
fn arg_help() {
case(
"[arg('bar', help='hello')]\nfoo bar:",
Module {
first: Some("foo"),
recipes: [(
"foo",
Recipe {
name: "foo",
namepath: "foo",
attributes: [json!({
"arg": {
"help": "hello",
"long": null,
"name": "bar",
"pattern": null,
"short": null,
"value": null,
}
})]
.into(),
parameters: [Parameter {
help: Some("hello"),
kind: "singular",
name: "bar",
..default()
}]
.into(),
..default()
},
)]
.into(),
..default()
},
);
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/os_attributes.rs | tests/os_attributes.rs | use super::*;
#[test]
fn os_family() {
Test::new()
.justfile(
"
[unix]
foo:
echo bar
[windows]
foo:
echo baz
",
)
.stdout(if cfg!(unix) {
"bar\n"
} else if cfg!(windows) {
"baz\n"
} else {
panic!("unexpected os family")
})
.stderr(if cfg!(unix) {
"echo bar\n"
} else if cfg!(windows) {
"echo baz\n"
} else {
panic!("unexpected os family")
})
.run();
}
#[test]
fn os() {
Test::new()
.justfile(
"
[macos]
foo:
echo bar
[windows]
foo:
echo baz
[linux]
foo:
echo quxx
[openbsd]
foo:
echo bob
",
)
.stdout(if cfg!(target_os = "macos") {
"bar\n"
} else if cfg!(windows) {
"baz\n"
} else if cfg!(target_os = "linux") {
"quxx\n"
} else if cfg!(target_os = "openbsd") {
"bob\n"
} else {
panic!("unexpected os family")
})
.stderr(if cfg!(target_os = "macos") {
"echo bar\n"
} else if cfg!(windows) {
"echo baz\n"
} else if cfg!(target_os = "linux") {
"echo quxx\n"
} else if cfg!(target_os = "openbsd") {
"echo bob\n"
} else {
panic!("unexpected os family")
})
.run();
}
#[test]
fn all() {
Test::new()
.justfile(
"
[linux]
[macos]
[openbsd]
[unix]
[windows]
foo:
echo bar
",
)
.stdout("bar\n")
.stderr("echo bar\n")
.run();
}
#[test]
fn none() {
Test::new()
.justfile(
"
foo:
echo bar
",
)
.stdout("bar\n")
.stderr("echo bar\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/no_cd.rs | tests/no_cd.rs | use super::*;
#[test]
fn linewise() {
Test::new()
.justfile(
"
[no-cd]
foo:
cat bar
",
)
.current_dir("foo")
.tree(tree! {
foo: {
bar: "hello",
}
})
.stderr("cat bar\n")
.stdout("hello")
.run();
}
#[test]
fn shebang() {
Test::new()
.justfile(
"
[no-cd]
foo:
#!/bin/sh
cat bar
",
)
.current_dir("foo")
.tree(tree! {
foo: {
bar: "hello",
}
})
.stdout("hello")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/explain.rs | tests/explain.rs | use super::*;
#[test]
fn explain_recipe() {
Test::new()
.justfile(
"
# List some fruits
fruits:
echo 'apple peach dragonfruit'
",
)
.args(["--explain", "fruits"])
.stdout("apple peach dragonfruit\n")
.stderr(
"
#### List some fruits
echo 'apple peach dragonfruit'
",
)
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
casey/just | https://github.com/casey/just/blob/5732ee083a58c534804d184acbdede11d1bbaac5/tests/windows_shell.rs | tests/windows_shell.rs | use super::*;
#[test]
fn windows_shell_setting() {
Test::new()
.justfile(
r#"
set windows-shell := ["pwsh.exe", "-NoLogo", "-Command"]
set shell := ["asdfasdfasdfasdf"]
foo:
Write-Output bar
"#,
)
.shell(false)
.stdout("bar\r\n")
.stderr("Write-Output bar\n")
.run();
}
#[test]
fn windows_powershell_setting_uses_powershell_set_shell() {
Test::new()
.justfile(
r#"
set windows-powershell
set shell := ["asdfasdfasdfasdf"]
foo:
Write-Output bar
"#,
)
.shell(false)
.stdout("bar\r\n")
.stderr("Write-Output bar\n")
.run();
}
#[test]
fn windows_powershell_setting_uses_powershell() {
Test::new()
.justfile(
r#"
set windows-powershell
foo:
Write-Output bar
"#,
)
.shell(false)
.stdout("bar\r\n")
.stderr("Write-Output bar\n")
.run();
}
| rust | CC0-1.0 | 5732ee083a58c534804d184acbdede11d1bbaac5 | 2026-01-04T15:34:07.853244Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.