Rename arguments to parameters.

This commit is contained in:
Casey Rodarmor 2016-10-31 19:11:27 -07:00
parent 0127986bce
commit 7f6a74af24
4 changed files with 156 additions and 115 deletions

107
README.md
View File

@ -3,73 +3,60 @@ just
[![crates.io version](https://img.shields.io/crates/v/just.svg)](https://crates.io/crates/just) [![crates.io version](https://img.shields.io/crates/v/just.svg)](https://crates.io/crates/just)
`just` is a handy way to run project-specific commands. `just` is a handy way to save and run commands.
Commands are stored in a file called `justfile` with a syntax inspired by `make`:
```make
# test everything. must build first
test-all: build
test --all
# run a specific test by passing it as an argument: `just test server-test`
test TEST: build
test --test {{TEST}}
# build the binary
build:
cc *.c -o main
version = "0.2.0"
tardir = "awesomesauce-" + version
tarball = tardir + ".tar.gz"
build-tarball:
rm -f {{tarball}}
mkdir {{tardir}}
cp README.md *.c {{tardir}}
tar zcvf {{tarball}} {{tardir}}
rm -rf {{tardir}}
publish: test build-tarball
scp {{tarball}} me@server.com:release/
# recipes can be written in any language
serve-docs:
#!/usr/bin/env python3
import os, http.server, socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
os.chdir('docs')
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
```
`just` avoids `make`'s idiosyncrasies and produces excellent error messages, so debugging a `justfile` is easier and less suprising than debugging a makefile.
getting started getting started
--------------- ---------------
Get `just` from cargo, the [rust language](https://www.rust-lang.org) package manager: `just` should run on any system with a reasonable `sh`, and can be installed with `cargo`, the [rust language](https://www.rust-lang.org) package manager:
1. Get rust and cargo from [rustup.rs](https://www.rustup.rs) 1. Get rust and cargo from [rustup.rs](https://www.rustup.rs)
2. Run `cargo install just` 2. Run `cargo install just`
3. Add `~/.cargo/bin` to your PATH 3. Add `~/.cargo/bin` to your PATH
`just` depends on `make` or `gmake` to actually run commands, but if you're using unix, a make is probably already installed on your system. If not, you can get it from your friendly local package manager. Then, create a file called `justfile` in the root of your project and start adding recipes to it.
Unfortunately, the dependency on `make` makes `just` difficult to run on windows. A possible future goal is to stop depending on make and use a custom file format, discussed in [issue #1](https://github.com/casey/just/issues/1). Optionally, you can `alias j=just` for lighting fast command running.
Once you can run `just`, create a file called `justfile` in the root of your project, and start adding recipes to it. See an example `justfile` [here](https://github.com/casey/j/blob/master/justfile).
The first recipe in the `justfile` will be run when `just` is called with no arguments, which makes it a good candidate for the command that you run most often, for example building and testing your project. Other recipes can be run by supplying their name as an argument, for example `just build` to run the `build` recipe.
After that, the sky is the limit!
Ideas for recipes include:
* Deploying/publishing the project
* Building in release mode vs debug mode
* Running in debug mode/with logging enabled
* Complex git workflows
* Updating dependencies
* Running different sets of tests, for example fast tests vs slow tests
* Any complex set of commands that you really should write down somewhere, if only to be able to remember them
how it works
------------
`just` looks upward from the current directory for a file called `justfile` and then runs `make` with that file as the makefile. `just` also sets the current working directory to where it found the justfile, so your commands are executed from the root of your project and not from whatever subdirectory you happen to be in.
Makefile targets are called "recipes", and are simply lists of commands to run in sequence, making them very concise. Recipes stop if a command fails, like if you do `set -e` in a shell script. Recipes also print each command before running it. If you would like to supress this, you can prepend a line in a recipe with `@`.
With no arguments `just` runs the default recipe:
`just`
Adding one argument specifies the recipe:
`just compile`
Multiple recipes can be run in order:
`just lint compile test`
Arguments after `--` are exported to environment variables`ARG0`, `ARG1`, ..., `ARGN`, which can be used in the justfile. To run recipe `compile` and export `ARG0=bar` and `ARG1=baz`:
`just compile -- bar baz`
further ramblings
-----------------
`just` is a trivial program, but I personally find it enormously useful and write a `justfile` for almost every project, big or small.
For one, `just` is a full 5 characters shorter than `./main`, and 3 characters shorter than `make`.
On a big project with multiple contributers, it's very useful to have a file with all the commands needed to work on the project. There are probably different commands to test, build, lint, deploy, and the like, and having them all in one place is useful and cuts down on the time you have to spend telling people which commands to run and how to type them. And, with an easy place to put commands, it's likely that you'll come up with other useful things which are part of the project's collective wisdom, but which aren't written down anywhere, like the arcane commands needed for your project's revision control workflow, for updating dependencies, or all the random flags you might need to pass to the build system.
Even for small, personal projects, it's nice to be able to go into an old project written in some random language with some mysterious build system and know that all the commands you need to do whatever you need to do are in the justfile, and that if you type `just` something useful will probably happen.
If you have a feature request, do open an issue and let me know.
I hope you enjoy using `just`, and find great success and satisfaction in all your computational endeavors!
😸

58
notes
View File

@ -1,12 +1,23 @@
todo todo
---- ----
should justfile recipes have arguments or parameters?
After that, the sky is the limit!
Ideas for recipes include:
* Deploying/publishing the project
* Building in release mode vs debug mode
* Running in debug mode/with logging enabled
* Complex git workflows
* Updating dependencies
* Running different sets of tests, for example fast tests vs slow tests
* Any complex set of commands that you really should write down somewhere, if only to be able to remember them
. start with an short example justfile . start with an short example justfile
. recipes, dependencies, assignments, backticks . recipes, dependencies, assignments, backticks
. make this justfile runnable as a test . make this justfile runnable as a test
. suggest j as alias
. users can email me or open an issue for help, bowing emoji . users can email me or open an issue for help, bowing emoji
open issue for feature requests open issue for feature requests
. ask users to contribute their justfiles as tests . ask users to contribute their justfiles as tests
@ -46,3 +57,46 @@ todo
. irc . irc
. r/rust . r/rust
. hacker news . hacker news
how it works
------------
`just` can then be invoked from any subdirectory of your project.
The first recipe in the `justfile` will be run when `just` is invoked with no arguments, which makes it a good candidate for the command that you run most often, for example building and testing your project. Other recipes can be run by supplying their name as an argument, for example `just build` to run the `build` recipe.
- recipes stop if a command fails
- commands are printed before running unless prepended with @
With no arguments `just` runs the default recipe:
`just`
Adding one argument specifies the recipe:
`just compile`
Multiple recipes can be run in order:
`just lint compile test`
Arguments after `--` are exported to environment variables`ARG0`, `ARG1`, ..., `ARGN`, which can be used in the justfile. To run recipe `compile` and export `ARG0=bar` and `ARG1=baz`:
`just compile -- bar baz`
further ramblings
-----------------
`just` is a trivial program, but I personally find it enormously useful and write a `justfile` for almost every project, big or small.
For one, `just` is a full 5 characters shorter than `./main`, and 3 characters shorter than `make`.
On a big project with multiple contributers, it's very useful to have a file with all the commands needed to work on the project. There are probably different commands to test, build, lint, deploy, and the like, and having them all in one place is useful and cuts down on the time you have to spend telling people which commands to run and how to type them. And, with an easy place to put commands, it's likely that you'll come up with other useful things which are part of the project's collective wisdom, but which aren't written down anywhere, like the arcane commands needed for your project's revision control workflow, for updating dependencies, or all the random flags you might need to pass to the build system.
Even for small, personal projects, it's nice to be able to go into an old project written in some random language with some mysterious build system and know that all the commands you need to do whatever you need to do are in the justfile, and that if you type `just` something useful will probably happen.
If you have a feature request, do open an issue and let me know.
I hope you enjoy using `just`, and find great success and satisfaction in all your computational endeavors!
😸

View File

@ -62,8 +62,8 @@ struct Recipe<'a> {
lines: Vec<Vec<Fragment<'a>>>, lines: Vec<Vec<Fragment<'a>>>,
dependencies: Vec<&'a str>, dependencies: Vec<&'a str>,
dependency_tokens: Vec<Token<'a>>, dependency_tokens: Vec<Token<'a>>,
arguments: Vec<&'a str>, parameters: Vec<&'a str>,
argument_tokens: Vec<Token<'a>>, parameter_tokens: Vec<Token<'a>>,
shebang: bool, shebang: bool,
} }
@ -219,7 +219,7 @@ impl<'a> Recipe<'a> {
dry_run: bool, dry_run: bool,
) -> Result<(), RunError<'a>> { ) -> Result<(), RunError<'a>> {
let argument_map = arguments .iter().enumerate() let argument_map = arguments .iter().enumerate()
.map(|(i, argument)| (self.arguments[i], *argument)).collect(); .map(|(i, argument)| (self.parameters[i], *argument)).collect();
let mut evaluator = Evaluator { let mut evaluator = Evaluator {
evaluated: Map::new(), evaluated: Map::new(),
@ -343,8 +343,8 @@ impl<'a> Recipe<'a> {
impl<'a> Display for Recipe<'a> { impl<'a> Display for Recipe<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(write!(f, "{}", self.name)); try!(write!(f, "{}", self.name));
for argument in &self.arguments { for parameter in &self.parameters {
try!(write!(f, " {}", argument)); try!(write!(f, " {}", parameter));
} }
try!(write!(f, ":")); try!(write!(f, ":"));
for dependency in &self.dependencies { for dependency in &self.dependencies {
@ -394,7 +394,7 @@ fn resolve_recipes<'a>(
if let Fragment::Expression{ref expression, ..} = *fragment { if let Fragment::Expression{ref expression, ..} = *fragment {
for variable in expression.variables() { for variable in expression.variables() {
let name = variable.lexeme; let name = variable.lexeme;
if !(assignments.contains_key(name) || recipe.arguments.contains(&name)) { if !(assignments.contains_key(name) || recipe.parameters.contains(&name)) {
// There's a borrow issue here that seems too difficult to solve. // There's a borrow issue here that seems too difficult to solve.
// The error derived from the variable token has too short a lifetime, // The error derived from the variable token has too short a lifetime,
// so we create a new error from its contents, which do live long // so we create a new error from its contents, which do live long
@ -653,12 +653,11 @@ struct Error<'a> {
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
enum ErrorKind<'a> { enum ErrorKind<'a> {
ArgumentShadowsVariable{argument: &'a str},
CircularRecipeDependency{recipe: &'a str, circle: Vec<&'a str>}, CircularRecipeDependency{recipe: &'a str, circle: Vec<&'a str>},
CircularVariableDependency{variable: &'a str, circle: Vec<&'a str>}, CircularVariableDependency{variable: &'a str, circle: Vec<&'a str>},
DependencyHasArguments{recipe: &'a str, dependency: &'a str}, DependencyHasParameters{recipe: &'a str, dependency: &'a str},
DuplicateArgument{recipe: &'a str, argument: &'a str},
DuplicateDependency{recipe: &'a str, dependency: &'a str}, DuplicateDependency{recipe: &'a str, dependency: &'a str},
DuplicateParameter{recipe: &'a str, parameter: &'a str},
DuplicateRecipe{recipe: &'a str, first: usize}, DuplicateRecipe{recipe: &'a str, first: usize},
DuplicateVariable{variable: &'a str}, DuplicateVariable{variable: &'a str},
ExtraLeadingWhitespace, ExtraLeadingWhitespace,
@ -667,10 +666,11 @@ enum ErrorKind<'a> {
InvalidEscapeSequence{character: char}, InvalidEscapeSequence{character: char},
MixedLeadingWhitespace{whitespace: &'a str}, MixedLeadingWhitespace{whitespace: &'a str},
OuterShebang, OuterShebang,
ParameterShadowsVariable{parameter: &'a str},
UndefinedVariable{variable: &'a str},
UnexpectedToken{expected: Vec<TokenKind>, found: TokenKind}, UnexpectedToken{expected: Vec<TokenKind>, found: TokenKind},
UnknownDependency{recipe: &'a str, unknown: &'a str}, UnknownDependency{recipe: &'a str, unknown: &'a str},
UnknownStartOfToken, UnknownStartOfToken,
UndefinedVariable{variable: &'a str},
UnterminatedString, UnterminatedString,
} }
@ -750,8 +750,8 @@ impl<'a> Display for Error<'a> {
ErrorKind::InvalidEscapeSequence{character} => { ErrorKind::InvalidEscapeSequence{character} => {
try!(writeln!(f, "`\\{}` is not a valid escape sequence", character.escape_default().collect::<String>())); try!(writeln!(f, "`\\{}` is not a valid escape sequence", character.escape_default().collect::<String>()));
} }
ErrorKind::DuplicateArgument{recipe, argument} => { ErrorKind::DuplicateParameter{recipe, parameter} => {
try!(writeln!(f, "recipe `{}` has duplicate argument `{}`", recipe, argument)); try!(writeln!(f, "recipe `{}` has duplicate parameter `{}`", recipe, parameter));
} }
ErrorKind::DuplicateVariable{variable} => { ErrorKind::DuplicateVariable{variable} => {
try!(writeln!(f, "variable `{}` is has multiple definitions", variable)); try!(writeln!(f, "variable `{}` is has multiple definitions", variable));
@ -767,11 +767,11 @@ impl<'a> Display for Error<'a> {
recipe, first, self.line)); recipe, first, self.line));
return Ok(()); return Ok(());
} }
ErrorKind::DependencyHasArguments{recipe, dependency} => { ErrorKind::DependencyHasParameters{recipe, dependency} => {
try!(writeln!(f, "recipe `{}` depends on `{}` which takes arguments. dependencies may not take arguments", recipe, dependency)); try!(writeln!(f, "recipe `{}` depends on `{}` which requires arguments. dependencies may not require arguments", recipe, dependency));
} }
ErrorKind::ArgumentShadowsVariable{argument} => { ErrorKind::ParameterShadowsVariable{parameter} => {
try!(writeln!(f, "argument `{}` shadows variable of the same name", argument)); try!(writeln!(f, "parameter `{}` shadows variable of the same name", parameter));
} }
ErrorKind::MixedLeadingWhitespace{whitespace} => { ErrorKind::MixedLeadingWhitespace{whitespace} => {
try!(writeln!(f, try!(writeln!(f,
@ -881,16 +881,16 @@ impl<'a, 'b> Justfile<'a> where 'a: 'b {
for (i, argument) in arguments.iter().enumerate() { for (i, argument) in arguments.iter().enumerate() {
if let Some(recipe) = self.recipes.get(argument) { if let Some(recipe) = self.recipes.get(argument) {
if !recipe.arguments.is_empty() { if !recipe.parameters.is_empty() {
if i != 0 { if i != 0 {
return Err(RunError::NonLeadingRecipeWithArguments{recipe: recipe.name}); return Err(RunError::NonLeadingRecipeWithParameters{recipe: recipe.name});
} }
let rest = &arguments[1..]; let rest = &arguments[1..];
if recipe.arguments.len() != rest.len() { if recipe.parameters.len() != rest.len() {
return Err(RunError::ArgumentCountMismatch { return Err(RunError::ArgumentCountMismatch {
recipe: recipe.name, recipe: recipe.name,
found: rest.len(), found: rest.len(),
expected: recipe.arguments.len(), expected: recipe.parameters.len(),
}); });
} }
try!(self.run_recipe(recipe, rest, &scope, &mut ran, dry_run)); try!(self.run_recipe(recipe, rest, &scope, &mut ran, dry_run));
@ -969,7 +969,7 @@ enum RunError<'a> {
Code{recipe: &'a str, code: i32}, Code{recipe: &'a str, code: i32},
InternalError{message: String}, InternalError{message: String},
IoError{recipe: &'a str, io_error: io::Error}, IoError{recipe: &'a str, io_error: io::Error},
NonLeadingRecipeWithArguments{recipe: &'a str}, NonLeadingRecipeWithParameters{recipe: &'a str},
Signal{recipe: &'a str, signal: i32}, Signal{recipe: &'a str, signal: i32},
TmpdirIoError{recipe: &'a str, io_error: io::Error}, TmpdirIoError{recipe: &'a str, io_error: io::Error},
UnknownFailure{recipe: &'a str}, UnknownFailure{recipe: &'a str},
@ -996,7 +996,7 @@ impl<'a> Display for RunError<'a> {
try!(write!(f, "{} set on the command line but not present in justfile", try!(write!(f, "{} set on the command line but not present in justfile",
And(overrides))) And(overrides)))
}, },
RunError::NonLeadingRecipeWithArguments{recipe} => { RunError::NonLeadingRecipeWithParameters{recipe} => {
try!(write!(f, "Recipe `{}` takes arguments and so must be the first and only recipe specified on the command line", recipe)); try!(write!(f, "Recipe `{}` takes arguments and so must be the first and only recipe specified on the command line", recipe));
}, },
RunError::ArgumentCountMismatch{recipe, found, expected} => { RunError::ArgumentCountMismatch{recipe, found, expected} => {
@ -1466,22 +1466,22 @@ impl<'a> Parser<'a> {
})); }));
} }
let mut arguments = vec![]; let mut parameters = vec![];
let mut argument_tokens = vec![]; let mut parameter_tokens = vec![];
while let Some(argument) = self.accept(Name) { while let Some(parameter) = self.accept(Name) {
if arguments.contains(&argument.lexeme) { if parameters.contains(&parameter.lexeme) {
return Err(argument.error(ErrorKind::DuplicateArgument{ return Err(parameter.error(ErrorKind::DuplicateParameter {
recipe: name.lexeme, argument: argument.lexeme recipe: name.lexeme, parameter: parameter.lexeme
})); }));
} }
arguments.push(argument.lexeme); parameters.push(parameter.lexeme);
argument_tokens.push(argument); parameter_tokens.push(parameter);
} }
if let Some(token) = self.expect(Colon) { if let Some(token) = self.expect(Colon) {
// if we haven't accepted any arguments, an equals // if we haven't accepted any parameters, an equals
// would have been fine as part of an assignment // would have been fine as part of an assignment
if arguments.is_empty() { if parameters.is_empty() {
return Err(self.unexpected_token(&token, &[Name, Colon, Equals])); return Err(self.unexpected_token(&token, &[Name, Colon, Equals]));
} else { } else {
return Err(self.unexpected_token(&token, &[Name, Colon])); return Err(self.unexpected_token(&token, &[Name, Colon]));
@ -1553,8 +1553,8 @@ impl<'a> Parser<'a> {
name: name.lexeme, name: name.lexeme,
dependencies: dependencies, dependencies: dependencies,
dependency_tokens: dependency_tokens, dependency_tokens: dependency_tokens,
arguments: arguments, parameters: parameters,
argument_tokens: argument_tokens, parameter_tokens: parameter_tokens,
lines: lines, lines: lines,
shebang: shebang, shebang: shebang,
}); });
@ -1680,17 +1680,17 @@ impl<'a> Parser<'a> {
try!(resolve_recipes(&self.recipes, &self.assignments, self.text)); try!(resolve_recipes(&self.recipes, &self.assignments, self.text));
for recipe in self.recipes.values() { for recipe in self.recipes.values() {
for argument in &recipe.argument_tokens { for parameter in &recipe.parameter_tokens {
if self.assignments.contains_key(argument.lexeme) { if self.assignments.contains_key(parameter.lexeme) {
return Err(argument.error(ErrorKind::ArgumentShadowsVariable { return Err(parameter.error(ErrorKind::ParameterShadowsVariable {
argument: argument.lexeme parameter: parameter.lexeme
})); }));
} }
} }
for dependency in &recipe.dependency_tokens { for dependency in &recipe.dependency_tokens {
if !self.recipes[dependency.lexeme].arguments.is_empty() { if !self.recipes[dependency.lexeme].parameters.is_empty() {
return Err(dependency.error(ErrorKind::DependencyHasArguments { return Err(dependency.error(ErrorKind::DependencyHasParameters {
recipe: recipe.name, recipe: recipe.name,
dependency: dependency.lexeme, dependency: dependency.lexeme,
})); }));

View File

@ -372,7 +372,7 @@ fn eof_test() {
} }
#[test] #[test]
fn duplicate_argument() { fn duplicate_parameter() {
let text = "a b b:"; let text = "a b b:";
parse_error(text, Error { parse_error(text, Error {
text: text, text: text,
@ -380,12 +380,12 @@ fn duplicate_argument() {
line: 0, line: 0,
column: 4, column: 4,
width: Some(1), width: Some(1),
kind: ErrorKind::DuplicateArgument{recipe: "a", argument: "b"} kind: ErrorKind::DuplicateParameter{recipe: "a", parameter: "b"}
}); });
} }
#[test] #[test]
fn argument_shadows_varible() { fn parameter_shadows_varible() {
let text = "foo = \"h\"\na foo:"; let text = "foo = \"h\"\na foo:";
parse_error(text, Error { parse_error(text, Error {
text: text, text: text,
@ -393,12 +393,12 @@ fn argument_shadows_varible() {
line: 1, line: 1,
column: 2, column: 2,
width: Some(3), width: Some(3),
kind: ErrorKind::ArgumentShadowsVariable{argument: "foo"} kind: ErrorKind::ParameterShadowsVariable{parameter: "foo"}
}); });
} }
#[test] #[test]
fn dependency_with_arguments() { fn dependency_has_parameters() {
let text = "foo arg:\nb: foo"; let text = "foo arg:\nb: foo";
parse_error(text, Error { parse_error(text, Error {
text: text, text: text,
@ -406,7 +406,7 @@ fn dependency_with_arguments() {
line: 1, line: 1,
column: 3, column: 3,
width: Some(3), width: Some(3),
kind: ErrorKind::DependencyHasArguments{recipe: "b", dependency: "foo"} kind: ErrorKind::DependencyHasParameters{recipe: "b", dependency: "foo"}
}); });
} }
@ -518,7 +518,7 @@ fn string_escapes() {
} }
#[test] #[test]
fn arguments() { fn parameters() {
parse_summary( parse_summary(
"a b c: "a b c:
{{b}} {{c}}", {{b}} {{c}}",