Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add dotenv-load setting #778

Merged
merged 2 commits into from
Mar 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion GRAMMAR.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,12 @@ assignment : NAME ':=' expression eol

export : 'export' assignment

setting : 'set' 'export'
setting : 'set' 'dotenv-load' boolean?
| 'set' 'export' boolean?
| 'set' 'shell' ':=' '[' string (',' string)* ','? ']'

boolean : ':=' ('true' | 'false')

expression : 'if' condition '{' expression '}' else '{' expression '}'
| value '+' expression
| value
Expand Down
43 changes: 30 additions & 13 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -388,29 +388,30 @@ foo:
[options="header"]
|=================
| Name | Value | Description
| `export` | | Export all variables as environment variables
| `dotenv-load` | `true` or `false` | Load a `.env` file, if present.
| `export` | `true` or `false` | Export all variables as environment variables.
|`shell` | `[COMMAND, ARGS...]` | Set the command used to invoke recipes and evaluate backticks.
|=================

==== Shell

The `shell` setting controls the command used to invoke recipe lines and backticks. Shebang recipes are unaffected.
Boolean settings can be written as:

```make
# use python3 to execute recipe lines and backticks
set shell := ["python3", "-c"]
```
set NAME
```

# use print to capture result of evaluation
foos := `print("foo" * 4)`
Which is equivalent to:

foo:
print("Snake snake snake snake.")
print("{{foos}}")
```
set NAME := true
```

==== Dotenv Load

If `dotenv-load` is `true`, a `.env` file will be loaded if present. Defaults to `true`.

==== Export

The `export` setting causes all Just variables to be exported as environment variables.
The `export` setting causes all Just variables to be exported as environment variables. Defaults to `false`.

```make
set export
Expand All @@ -428,6 +429,22 @@ hello
goodbye
```

==== Shell

The `shell` setting controls the command used to invoke recipe lines and backticks. Shebang recipes are unaffected.

```make
# use python3 to execute recipe lines and backticks
set shell := ["python3", "-c"]

# use print to capture result of evaluation
foos := `print("foo" * 4)`

foo:
print("Snake snake snake snake.")
print("{{foos}}")
```

=== Documentation Comments

Comments immediately preceding a recipe will appear in `just --list`:
Expand Down
9 changes: 6 additions & 3 deletions src/analyzer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,16 @@ impl<'src> Analyzer<'src> {

for (_, set) in self.sets {
match set.value {
Setting::DotenvLoad(dotenv_load) => {
settings.dotenv_load = dotenv_load;
},
Setting::Export(export) => {
settings.export = export;
},
Setting::Shell(shell) => {
assert!(settings.shell.is_none());
settings.shell = Some(shell);
},
Setting::Export => {
settings.export = true;
},
}
}

Expand Down
17 changes: 9 additions & 8 deletions src/compilation_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ impl Display for CompilationError<'_> {

write!(f, "{}", message.prefix())?;

match self.kind {
match &self.kind {
AliasShadowsRecipe { alias, recipe_line } => {
writeln!(
f,
Expand Down Expand Up @@ -116,22 +116,23 @@ impl Display for CompilationError<'_> {
"Dependency `{}` got {} {} but takes ",
dependency,
found,
Count("argument", found),
Count("argument", *found),
)?;

if min == max {
let expected = min;
writeln!(f, "{} {}", expected, Count("argument", expected))?;
writeln!(f, "{} {}", expected, Count("argument", *expected))?;
} else if found < min {
writeln!(f, "at least {} {}", min, Count("argument", min))?;
writeln!(f, "at least {} {}", min, Count("argument", *min))?;
} else {
writeln!(f, "at most {} {}", max, Count("argument", max))?;
writeln!(f, "at most {} {}", max, Count("argument", *max))?;
}
},
ExpectedKeyword { expected, found } => writeln!(
f,
"Expected keyword `{}` but found identifier `{}`",
expected, found
"Expected keyword {} but found identifier `{}`",
List::or_ticked(expected),
found
)?,
ParameterShadowsVariable { parameter } => {
writeln!(
Expand Down Expand Up @@ -171,7 +172,7 @@ impl Display for CompilationError<'_> {
"Function `{}` called with {} {} but takes {}",
function,
found,
Count("argument", found),
Count("argument", *found),
expected
)?;
},
Expand Down
2 changes: 1 addition & 1 deletion src/compilation_error_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub(crate) enum CompilationErrorKind<'src> {
first: usize,
},
ExpectedKeyword {
expected: Keyword,
expected: Vec<Keyword>,
found: &'src str,
},
ExtraLeadingWhitespace,
Expand Down
2 changes: 1 addition & 1 deletion src/justfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl<'src> Justfile<'src> {
}

let dotenv = if config.load_dotenv {
load_dotenv(&search.working_directory)?
load_dotenv(&search.working_directory, &self.settings)?
} else {
BTreeMap::new()
};
Expand Down
3 changes: 3 additions & 0 deletions src/keyword.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ pub(crate) enum Keyword {
Alias,
Else,
Export,
DotenvLoad,
True,
False,
If,
Set,
Shell,
Expand Down
6 changes: 6 additions & 0 deletions src/load_dotenv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@ use crate::common::*;

pub(crate) fn load_dotenv(
working_directory: &Path,
settings: &Settings,
) -> RunResult<'static, BTreeMap<String, String>> {
// `dotenv::from_path_iter` should eventually be un-deprecated, see:
// https://github.com/dotenv-rs/dotenv/issues/13
#![allow(deprecated)]

if !settings.dotenv_load {
return Ok(BTreeMap::new());
}

for directory in working_directory.ancestors() {
let path = directory.join(".env");

Expand Down
4 changes: 2 additions & 2 deletions src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,17 +187,17 @@ impl<'src> Node<'src> for Set<'src> {
fn tree(&self) -> Tree<'src> {
let mut set = Tree::atom(Keyword::Set.lexeme());

set.push_mut(self.name.lexeme());
set.push_mut(self.name.lexeme().replace('-', "_"));

use Setting::*;
match &self.value {
DotenvLoad(value) | Export(value) => set.push_mut(value.to_string()),
Shell(setting::Shell { command, arguments }) => {
set.push_mut(Tree::string(&command.cooked));
for argument in arguments {
set.push_mut(Tree::string(&argument.cooked));
}
},
Export => {},
}

set
Expand Down
79 changes: 75 additions & 4 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,10 @@ impl<'tokens, 'src> Parser<'tokens, 'src> {
if expected == found {
Ok(())
} else {
Err(identifier.error(CompilationErrorKind::ExpectedKeyword { expected, found }))
Err(identifier.error(CompilationErrorKind::ExpectedKeyword {
expected: vec![expected],
found,
}))
}
}

Expand Down Expand Up @@ -347,6 +350,7 @@ impl<'tokens, 'src> Parser<'tokens, 'src> {
Some(Keyword::Set) =>
if self.next_are(&[Identifier, Identifier, ColonEquals])
|| self.next_are(&[Identifier, Identifier, Eol])
|| self.next_are(&[Identifier, Identifier, Eof])
{
items.push(Item::Set(self.parse_set()?));
} else {
Expand Down Expand Up @@ -678,19 +682,50 @@ impl<'tokens, 'src> Parser<'tokens, 'src> {
Ok(lines)
}

/// Parse a boolean setting value
fn parse_set_bool(&mut self) -> CompilationResult<'src, bool> {
if !self.accepted(ColonEquals)? {
return Ok(true);
}

let identifier = self.expect(Identifier)?;

let value = if Keyword::True == identifier.lexeme() {
true
} else if Keyword::False == identifier.lexeme() {
false
} else {
return Err(identifier.error(CompilationErrorKind::ExpectedKeyword {
expected: vec![Keyword::True, Keyword::False],
found: identifier.lexeme(),
}));
};

Ok(value)
}

/// Parse a setting
fn parse_set(&mut self) -> CompilationResult<'src, Set<'src>> {
self.presume_keyword(Keyword::Set)?;
let name = Name::from_identifier(self.presume(Identifier)?);
let lexeme = name.lexeme();

if name.lexeme() == Keyword::Export.lexeme() {
if Keyword::DotenvLoad == lexeme {
let value = self.parse_set_bool()?;
return Ok(Set {
value: Setting::DotenvLoad(value),
name,
});
} else if Keyword::Export == lexeme {
let value = self.parse_set_bool()?;
return Ok(Set {
value: Setting::Export,
value: Setting::Export(value),
name,
});
}

self.presume(ColonEquals)?;
self.expect(ColonEquals)?;

if name.lexeme() == Keyword::Shell.lexeme() {
self.expect(BracketL)?;

Expand Down Expand Up @@ -1541,6 +1576,42 @@ mod tests {
tree: (justfile (recipe a (body ("foo"))) (recipe b)),
}

test! {
name: set_export_implicit,
text: "set export",
tree: (justfile (set export true)),
}

test! {
name: set_export_true,
text: "set export := true",
tree: (justfile (set export true)),
}

test! {
name: set_export_false,
text: "set export := false",
tree: (justfile (set export false)),
}

test! {
name: set_dotenv_load_implicit,
text: "set dotenv-load",
tree: (justfile (set dotenv_load true)),
}

test! {
name: set_dotenv_load_true,
text: "set dotenv-load := true",
tree: (justfile (set dotenv_load true)),
}

test! {
name: set_dotenv_load_false,
text: "set dotenv-load := false",
tree: (justfile (set dotenv_load false)),
}

test! {
name: set_shell_no_arguments,
text: "set shell := ['tclsh']",
Expand Down
3 changes: 2 additions & 1 deletion src/setting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use crate::common::*;
#[derive(Debug)]
pub(crate) enum Setting<'src> {
Shell(Shell<'src>),
Export,
Export(bool),
DotenvLoad(bool),
}

#[derive(Debug, PartialEq)]
Expand Down
10 changes: 6 additions & 4 deletions src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ use crate::common::*;

#[derive(Debug, PartialEq)]
pub(crate) struct Settings<'src> {
pub(crate) shell: Option<setting::Shell<'src>>,
pub(crate) export: bool,
pub(crate) dotenv_load: bool,
pub(crate) export: bool,
pub(crate) shell: Option<setting::Shell<'src>>,
}

impl<'src> Settings<'src> {
pub(crate) fn new() -> Settings<'src> {
Settings {
shell: None,
export: false,
dotenv_load: true,
export: false,
shell: None,
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl<'src> Token<'src> {
space_column,
color.prefix(),
"",
space_width,
space_width.max(1),
color.suffix()
)?;
},
Expand Down
4 changes: 2 additions & 2 deletions src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use crate::common::*;
use std::mem;

/// Construct a `Tree` from a symbolic expression literal. This macro, and the
/// Tree type, are only used in the Parser unit tests, as a concise notation
/// representing the expected results of parsing a given string.
/// Tree type, are only used in the Parser unit tests, providing a concise
/// notation for representing the expected results of parsing a given string.
macro_rules! tree {
{
($($child:tt)*)
Expand Down
Loading