Eliminate lazy_static (#1442)

This commit is contained in:
Cameron Steffen 2022-12-15 18:53:21 -06:00 committed by GitHub
parent c35b131971
commit 216df31543
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
46 changed files with 202 additions and 227 deletions

View File

@ -26,7 +26,7 @@ jobs:
uses: actions-rs/toolchain@v1
with:
components: clippy, rustfmt
toolchain: 1.56.0
toolchain: stable
- uses: Swatinem/rust-cache@v1
@ -63,7 +63,7 @@ jobs:
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: 1.56.0
toolchain: stable
- uses: Swatinem/rust-cache@v1
@ -123,7 +123,7 @@ jobs:
with:
components: clippy, rustfmt
override: true
toolchain: 1.56.0
toolchain: stable
- uses: Swatinem/rust-cache@v1

1
Cargo.lock generated
View File

@ -317,7 +317,6 @@ dependencies = [
"env_logger",
"executable-path",
"heck 0.4.0",
"lazy_static",
"lexiclean",
"libc",
"log",

View File

@ -27,7 +27,6 @@ dotenvy = "0.15"
edit-distance = "2.0.0"
env_logger = "0.9.3"
heck = "0.4.0"
lazy_static = "1.0.0"
lexiclean = "0.0.1"
libc = "0.2.0"
log = "0.4.4"

View File

@ -2421,7 +2421,7 @@ Before merging a particularly large or gruesome change, Janus should be run to m
### Minimum Supported Rust Version
The minimum supported Rust version, or MSRV, is Rust 1.56.0.
The minimum supported Rust version, or MSRV, is current stable Rust. It may build on older versions of Rust, but this is not guaranteed.
### New Releases

View File

@ -165,7 +165,7 @@ fn main() -> Result {
for chapter in chapters {
let path = format!("{}/chapter_{}.md", src, chapter.number());
fs::write(&path, &chapter.markdown()?)?;
fs::write(path, chapter.markdown()?)?;
let indent = match chapter.level {
HeadingLevel::H1 => 0,
HeadingLevel::H2 => 1,

View File

@ -36,7 +36,7 @@ impl<'src: 'run, 'run> AssignmentResolver<'src, 'run> {
self.resolve_expression(&assignment.value)?;
self.evaluated.insert(name);
} else {
let message = format!("attempted to resolve unknown assignment `{}`", name);
let message = format!("attempted to resolve unknown assignment `{name}`");
let token = Token {
src: "",
offset: 0,

View File

@ -16,7 +16,7 @@ impl<'src> Display for Ast<'src> {
let mut iter = self.items.iter().peekable();
while let Some(item) = iter.next() {
writeln!(f, "{}", item)?;
writeln!(f, "{item}")?;
if let Some(next_item) = iter.peek() {
if matches!(item, Item::Recipe(_))

View File

@ -39,7 +39,7 @@ impl Display for CompileError<'_> {
}
CircularRecipeDependency { recipe, ref circle } => {
if circle.len() == 2 {
write!(f, "Recipe `{}` depends on itself", recipe)?;
write!(f, "Recipe `{recipe}` depends on itself")?;
} else {
write!(
f,
@ -54,7 +54,7 @@ impl Display for CompileError<'_> {
ref circle,
} => {
if circle.len() == 2 {
write!(f, "Variable `{}` is defined in terms of itself", variable)?;
write!(f, "Variable `{variable}` is defined in terms of itself")?;
} else {
write!(
f,
@ -80,11 +80,11 @@ impl Display for CompileError<'_> {
if min == max {
let expected = min;
write!(f, "{} {}", expected, Count("argument", *expected))?;
write!(f, "{expected} {}", Count("argument", *expected))?;
} else if found < min {
write!(f, "at least {} {}", min, Count("argument", *min))?;
write!(f, "at least {min} {}", Count("argument", *min))?;
} else {
write!(f, "at most {} {}", max, Count("argument", *max))?;
write!(f, "at most {max} {}", Count("argument", *max))?;
}
}
DuplicateAlias { alias, first } => {
@ -131,7 +131,7 @@ impl Display for CompileError<'_> {
)?;
}
DuplicateVariable { variable } => {
write!(f, "Variable `{}` has multiple definitions", variable)?;
write!(f, "Variable `{variable}` has multiple definitions")?;
}
ExpectedKeyword { expected, found } => {
if found.kind == TokenKind::Identifier {
@ -192,7 +192,7 @@ impl Display for CompileError<'_> {
'"' => r#"""#.to_owned(),
_ => character.escape_default().collect(),
};
write!(f, "`\\{}` is not a valid escape sequence", representation)?;
write!(f, "`\\{representation}` is not a valid escape sequence")?;
}
MismatchedClosingDelimiter {
open,
@ -216,13 +216,12 @@ impl Display for CompileError<'_> {
)?;
}
ParameterFollowsVariadicParameter { parameter } => {
write!(f, "Parameter `{}` follows variadic parameter", parameter)?;
write!(f, "Parameter `{parameter}` follows variadic parameter")?;
}
ParameterShadowsVariable { parameter } => {
write!(
f,
"Parameter `{}` shadows variable of the same name",
parameter
"Parameter `{parameter}` shadows variable of the same name",
)?;
}
ParsingRecursionDepthExceeded => {
@ -236,41 +235,37 @@ impl Display for CompileError<'_> {
)?;
}
UndefinedVariable { variable } => {
write!(f, "Variable `{}` not defined", variable)?;
write!(f, "Variable `{variable}` not defined")?;
}
UnexpectedCharacter { expected } => {
write!(f, "Expected character `{}`", expected)?;
write!(f, "Expected character `{expected}`")?;
}
UnexpectedClosingDelimiter { close } => {
write!(f, "Unexpected closing delimiter `{}`", close.close())?;
}
UnexpectedEndOfToken { expected } => {
write!(f, "Expected character `{}` but found end-of-file", expected)?;
write!(f, "Expected character `{expected}` but found end-of-file")?;
}
UnexpectedToken {
ref expected,
found,
} => {
write!(f, "Expected {}, but found {}", List::or(expected), found)?;
write!(f, "Expected {}, but found {found}", List::or(expected))?;
}
UnknownAliasTarget { alias, target } => {
write!(f, "Alias `{}` has an unknown target `{}`", alias, target)?;
write!(f, "Alias `{alias}` has an unknown target `{target}`")?;
}
UnknownAttribute { attribute } => {
write!(f, "Unknown attribute `{}`", attribute)?;
write!(f, "Unknown attribute `{attribute}`")?;
}
UnknownDependency { recipe, unknown } => {
write!(
f,
"Recipe `{}` has unknown dependency `{}`",
recipe, unknown
)?;
write!(f, "Recipe `{recipe}` has unknown dependency `{unknown}`",)?;
}
UnknownFunction { function } => {
write!(f, "Call to unknown function `{}`", function)?;
write!(f, "Call to unknown function `{function}`")?;
}
UnknownSetting { setting } => {
write!(f, "Unknown setting `{}`", setting)?;
write!(f, "Unknown setting `{setting}`")?;
}
UnknownStartOfToken => {
write!(f, "Unknown start of token:")?;

View File

@ -388,7 +388,7 @@ impl Config {
arg::COLOR_ALWAYS => Ok(Color::always()),
arg::COLOR_NEVER => Ok(Color::never()),
_ => Err(ConfigError::Internal {
message: format!("Invalid argument `{}` to --color.", value),
message: format!("Invalid argument `{value}` to --color."),
}),
}
}
@ -404,7 +404,7 @@ impl Config {
arg::DUMP_FORMAT_JSON => Ok(DumpFormat::Json),
arg::DUMP_FORMAT_JUST => Ok(DumpFormat::Just),
_ => Err(ConfigError::Internal {
message: format!("Invalid argument `{}` to --dump-format.", value),
message: format!("Invalid argument `{value}` to --dump-format."),
}),
}
}

View File

@ -28,7 +28,7 @@ pub(crate) enum ConfigError {
#[snafu(display(
"`--{}` used with unexpected overrides: {}",
subcommand.to_lowercase(),
List::and_ticked(overrides.iter().map(|(key, value)| format!("{}={}", key, value))),
List::and_ticked(overrides.iter().map(|(key, value)| format!("{key}={value}"))),
))]
SubcommandOverrides {
subcommand: &'static str,
@ -37,7 +37,7 @@ pub(crate) enum ConfigError {
#[snafu(display(
"`--{}` used with unexpected overrides: {}; and arguments: {}",
subcommand.to_lowercase(),
List::and_ticked(overrides.iter().map(|(key, value)| format!("{}={}", key, value))),
List::and_ticked(overrides.iter().map(|(key, value)| format!("{key}={value}"))),
List::and_ticked(arguments)))
]
SubcommandOverridesAndArguments {

View File

@ -15,7 +15,7 @@ impl<'src> Display for Dependency<'src> {
write!(f, "({}", self.recipe.name())?;
for argument in &self.arguments {
write!(f, " {}", argument)?;
write!(f, " {argument}")?;
}
write!(f, ")")

View File

@ -256,10 +256,10 @@ impl<'src> ColorDisplay for Error<'src> {
}
Backtick { output_error, .. } => match output_error {
OutputError::Code(code) => {
write!(f, "Backtick failed with exit code {}", code)?;
write!(f, "Backtick failed with exit code {code}")?;
}
OutputError::Signal(signal) => {
write!(f, "Backtick was terminated by signal {}", signal)?;
write!(f, "Backtick was terminated by signal {signal}")?;
}
OutputError::Unknown => {
write!(f, "Backtick failed for an unknown reason")?;
@ -343,7 +343,7 @@ impl<'src> ColorDisplay for Error<'src> {
recipe, n, code
)?;
} else {
write!(f, "Recipe `{}` failed with exit code {}", recipe, code)?;
write!(f, "Recipe `{recipe}` failed with exit code {code}")?;
}
}
CommandInvoke {
@ -422,7 +422,7 @@ impl<'src> ColorDisplay for Error<'src> {
path:\n{}",
recipe, io_error
),
_ => write!(f, "Could not run `cygpath` executable:\n{}", io_error),
_ => write!(f, "Could not run `cygpath` executable:\n{io_error}"),
}?;
}
OutputError::Utf8(utf8_error) => {
@ -447,34 +447,28 @@ impl<'src> ColorDisplay for Error<'src> {
)?;
}
Dotenv { dotenv_error } => {
write!(f, "Failed to load environment file: {}", dotenv_error)?;
write!(f, "Failed to load environment file: {dotenv_error}")?;
}
DumpJson { serde_json_error } => {
write!(f, "Failed to dump JSON to stdout: {}", serde_json_error)?;
write!(f, "Failed to dump JSON to stdout: {serde_json_error}")?;
}
EditorInvoke { editor, io_error } => {
write!(
f,
"Editor `{}` invocation failed: {}",
"Editor `{}` invocation failed: {io_error}",
editor.to_string_lossy(),
io_error
)?;
}
EditorStatus { editor, status } => {
write!(
f,
"Editor `{}` failed: {}",
editor.to_string_lossy(),
status
)?;
write!(f, "Editor `{}` failed: {status}", editor.to_string_lossy(),)?;
}
EvalUnknownVariable {
variable,
suggestion,
} => {
write!(f, "Justfile does not contain variable `{}`.", variable,)?;
write!(f, "Justfile does not contain variable `{variable}`.")?;
if let Some(suggestion) = *suggestion {
write!(f, "\n{}", suggestion)?;
write!(f, "\n{suggestion}")?;
}
}
FormatCheckFoundDiff => {
@ -533,7 +527,7 @@ impl<'src> ColorDisplay for Error<'src> {
write!(f, "Justfile contains no recipes.")?;
}
RegexCompile { source } => {
write!(f, "{}", source)?;
write!(f, "{source}")?;
}
Search { search_error } => Display::fmt(search_error, f)?,
Shebang {
@ -545,14 +539,12 @@ impl<'src> ColorDisplay for Error<'src> {
if let Some(argument) = argument {
write!(
f,
"Recipe `{}` with shebang `#!{} {}` execution error: {}",
recipe, command, argument, io_error
"Recipe `{recipe}` with shebang `#!{command} {argument}` execution error: {io_error}",
)?;
} else {
write!(
f,
"Recipe `{}` with shebang `#!{}` execution error: {}",
recipe, command, io_error
"Recipe `{recipe}` with shebang `#!{command}` execution error: {io_error}",
)?;
}
}
@ -564,18 +556,16 @@ impl<'src> ColorDisplay for Error<'src> {
if let Some(n) = line_number {
write!(
f,
"Recipe `{}` was terminated on line {} by signal {}",
recipe, n, signal
"Recipe `{recipe}` was terminated on line {n} by signal {signal}",
)?;
} else {
write!(f, "Recipe `{}` was terminated by signal {}", recipe, signal)?;
write!(f, "Recipe `{recipe}` was terminated by signal {signal}")?;
}
}
TmpdirIo { recipe, io_error } => write!(
f,
"Recipe `{}` could not be run because of an IO error while trying to create a temporary \
directory or write a file to that directory`:{}",
recipe, io_error
"Recipe `{recipe}` could not be run because of an IO error while trying to create a temporary \
directory or write a file to that directory`:{io_error}",
)?,
Unknown {
recipe,
@ -584,11 +574,10 @@ impl<'src> ColorDisplay for Error<'src> {
if let Some(n) = line_number {
write!(
f,
"Recipe `{}` failed on line {} for an unknown reason",
recipe, n
"Recipe `{recipe}` failed on line {n} for an unknown reason",
)?;
} else {
write!(f, "Recipe `{}` failed for an unknown reason", recipe)?;
write!(f, "Recipe `{recipe}` failed for an unknown reason")?;
}
}
UnknownOverrides { overrides } => {
@ -610,7 +599,7 @@ impl<'src> ColorDisplay for Error<'src> {
List::or_ticked(recipes),
)?;
if let Some(suggestion) = *suggestion {
write!(f, "\n{}", suggestion)?;
write!(f, "\n{suggestion}")?;
}
}
Unstable { message } => {

View File

@ -61,7 +61,7 @@ impl<'src, 'run> Evaluator<'src, 'run> {
Ok(self.evaluate_assignment(assignment)?.to_owned())
} else {
Err(Error::Internal {
message: format!("attempted to evaluate undefined variable `{}`", variable),
message: format!("attempted to evaluate undefined variable `{variable}`"),
})
}
}
@ -145,7 +145,7 @@ impl<'src, 'run> Evaluator<'src, 'run> {
Expression::StringLiteral { string_literal } => Ok(string_literal.cooked.clone()),
Expression::Backtick { contents, token } => {
if self.config.dry_run {
Ok(format!("`{}`", contents))
Ok(format!("`{contents}`"))
} else {
Ok(self.run_backtick(contents, token)?)
}

View File

@ -51,12 +51,12 @@ impl<'src> Display for Expression<'src> {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
match self {
Expression::Backtick { token, .. } => write!(f, "{}", token.lexeme()),
Expression::Join { lhs: None, rhs } => write!(f, "/ {}", rhs),
Expression::Join { lhs: None, rhs } => write!(f, "/ {rhs}"),
Expression::Join {
lhs: Some(lhs),
rhs,
} => write!(f, "{} / {}", lhs, rhs),
Expression::Concatenation { lhs, rhs } => write!(f, "{} + {}", lhs, rhs),
} => write!(f, "{lhs} / {rhs}"),
Expression::Concatenation { lhs, rhs } => write!(f, "{lhs} + {rhs}"),
Expression::Conditional {
lhs,
rhs,
@ -68,10 +68,10 @@ impl<'src> Display for Expression<'src> {
"if {} {} {} {{ {} }} else {{ {} }}",
lhs, operator, rhs, then, otherwise
),
Expression::StringLiteral { string_literal } => write!(f, "{}", string_literal),
Expression::StringLiteral { string_literal } => write!(f, "{string_literal}"),
Expression::Variable { name } => write!(f, "{}", name.lexeme()),
Expression::Call { thunk } => write!(f, "{}", thunk),
Expression::Group { contents } => write!(f, "({})", contents),
Expression::Call { thunk } => write!(f, "{thunk}"),
Expression::Group { contents } => write!(f, "({contents})"),
}
}
}

View File

@ -9,6 +9,7 @@ use heck::{
};
use Function::*;
pub(crate) enum Function {
Nullary(fn(&FunctionContext) -> Result<String, String>),
Unary(fn(&FunctionContext, &str) -> Result<String, String>),
@ -17,53 +18,53 @@ pub(crate) enum Function {
Ternary(fn(&FunctionContext, &str, &str, &str) -> Result<String, String>),
}
lazy_static! {
pub(crate) static ref TABLE: BTreeMap<&'static str, Function> = vec![
("absolute_path", Unary(absolute_path)),
("arch", Nullary(arch)),
("capitalize", Unary(capitalize)),
("clean", Unary(clean)),
("env_var", Unary(env_var)),
("env_var_or_default", Binary(env_var_or_default)),
("error", Unary(error)),
("extension", Unary(extension)),
("file_name", Unary(file_name)),
("file_stem", Unary(file_stem)),
("invocation_directory", Nullary(invocation_directory)),
("join", BinaryPlus(join)),
("just_executable", Nullary(just_executable)),
("justfile", Nullary(justfile)),
("justfile_directory", Nullary(justfile_directory)),
("kebabcase", Unary(kebabcase)),
("lowercamelcase", Unary(lowercamelcase)),
("lowercase", Unary(lowercase)),
("os", Nullary(os)),
("os_family", Nullary(os_family)),
("parent_directory", Unary(parent_directory)),
("path_exists", Unary(path_exists)),
("quote", Unary(quote)),
("replace", Ternary(replace)),
("replace_regex", Ternary(replace_regex)),
("sha256", Unary(sha256)),
("sha256_file", Unary(sha256_file)),
("shoutykebabcase", Unary(shoutykebabcase)),
("shoutysnakecase", Unary(shoutysnakecase)),
("snakecase", Unary(snakecase)),
("titlecase", Unary(titlecase)),
("trim", Unary(trim)),
("trim_end", Unary(trim_end)),
("trim_end_match", Binary(trim_end_match)),
("trim_end_matches", Binary(trim_end_matches)),
("trim_start", Unary(trim_start)),
("trim_start_match", Binary(trim_start_match)),
("trim_start_matches", Binary(trim_start_matches)),
("uppercamelcase", Unary(uppercamelcase)),
("uppercase", Unary(uppercase)),
("uuid", Nullary(uuid)),
("without_extension", Unary(without_extension)),
]
.into_iter()
.collect();
pub(crate) fn get(name: &str) -> Option<Function> {
let function = match name {
"absolute_path" => Unary(absolute_path),
"arch" => Nullary(arch),
"capitalize" => Unary(capitalize),
"clean" => Unary(clean),
"env_var" => Unary(env_var),
"env_var_or_default" => Binary(env_var_or_default),
"error" => Unary(error),
"extension" => Unary(extension),
"file_name" => Unary(file_name),
"file_stem" => Unary(file_stem),
"invocation_directory" => Nullary(invocation_directory),
"join" => BinaryPlus(join),
"just_executable" => Nullary(just_executable),
"justfile" => Nullary(justfile),
"justfile_directory" => Nullary(justfile_directory),
"kebabcase" => Unary(kebabcase),
"lowercamelcase" => Unary(lowercamelcase),
"lowercase" => Unary(lowercase),
"os" => Nullary(os),
"os_family" => Nullary(os_family),
"parent_directory" => Unary(parent_directory),
"path_exists" => Unary(path_exists),
"quote" => Unary(quote),
"replace" => Ternary(replace),
"replace_regex" => Ternary(replace_regex),
"sha256" => Unary(sha256),
"sha256_file" => Unary(sha256_file),
"shoutykebabcase" => Unary(shoutykebabcase),
"shoutysnakecase" => Unary(shoutysnakecase),
"snakecase" => Unary(snakecase),
"titlecase" => Unary(titlecase),
"trim" => Unary(trim),
"trim_end" => Unary(trim_end),
"trim_end_match" => Binary(trim_end_match),
"trim_end_matches" => Binary(trim_end_matches),
"trim_start" => Unary(trim_start),
"trim_start_match" => Binary(trim_start_match),
"trim_start_matches" => Binary(trim_start_matches),
"uppercamelcase" => Unary(uppercamelcase),
"uppercase" => Unary(uppercase),
"uuid" => Nullary(uuid),
"without_extension" => Unary(without_extension),
_ => return None,
};
Some(function)
}
impl Function {
@ -117,7 +118,7 @@ fn env_var(context: &FunctionContext, key: &str) -> Result<String, String> {
}
match env::var(key) {
Err(NotPresent) => Err(format!("environment variable `{}` not present", key)),
Err(NotPresent) => Err(format!("environment variable `{key}` not present")),
Err(NotUnicode(os_string)) => Err(format!(
"environment variable `{}` not unicode: {:?}",
key, os_string
@ -155,21 +156,21 @@ fn extension(_context: &FunctionContext, path: &str) -> Result<String, String> {
Utf8Path::new(path)
.extension()
.map(str::to_owned)
.ok_or_else(|| format!("Could not extract extension from `{}`", path))
.ok_or_else(|| format!("Could not extract extension from `{path}`"))
}
fn file_name(_context: &FunctionContext, path: &str) -> Result<String, String> {
Utf8Path::new(path)
.file_name()
.map(str::to_owned)
.ok_or_else(|| format!("Could not extract file name from `{}`", path))
.ok_or_else(|| format!("Could not extract file name from `{path}`"))
}
fn file_stem(_context: &FunctionContext, path: &str) -> Result<String, String> {
Utf8Path::new(path)
.file_stem()
.map(str::to_owned)
.ok_or_else(|| format!("Could not extract file stem from `{}`", path))
.ok_or_else(|| format!("Could not extract file stem from `{path}`"))
}
fn invocation_directory(context: &FunctionContext) -> Result<String, String> {
@ -177,7 +178,7 @@ fn invocation_directory(context: &FunctionContext) -> Result<String, String> {
&context.search.working_directory,
context.invocation_directory,
)
.map_err(|e| format!("Error getting shell path: {}", e))
.map_err(|e| format!("Error getting shell path: {e}"))
}
fn join(
@ -195,7 +196,7 @@ fn join(
fn just_executable(_context: &FunctionContext) -> Result<String, String> {
let exe_path =
std::env::current_exe().map_err(|e| format!("Error getting current executable: {}", e))?;
std::env::current_exe().map_err(|e| format!("Error getting current executable: {e}"))?;
exe_path.to_str().map(str::to_owned).ok_or_else(|| {
format!(
@ -262,7 +263,7 @@ fn parent_directory(_context: &FunctionContext, path: &str) -> Result<String, St
Utf8Path::new(path)
.parent()
.map(Utf8Path::to_string)
.ok_or_else(|| format!("Could not extract parent directory from `{}`", path))
.ok_or_else(|| format!("Could not extract parent directory from `{path}`"))
}
fn path_exists(context: &FunctionContext, path: &str) -> Result<String, String> {
@ -303,7 +304,7 @@ fn sha256(_context: &FunctionContext, s: &str) -> Result<String, String> {
let mut hasher = Sha256::new();
hasher.update(s);
let hash = hasher.finalize();
Ok(format!("{:x}", hash))
Ok(format!("{hash:x}"))
}
fn sha256_file(context: &FunctionContext, path: &str) -> Result<String, String> {
@ -311,11 +312,11 @@ fn sha256_file(context: &FunctionContext, path: &str) -> Result<String, String>
let justpath = context.search.working_directory.join(path);
let mut hasher = Sha256::new();
let mut file = std::fs::File::open(&justpath)
.map_err(|err| format!("Failed to open file at `{:?}`: {}", &justpath.to_str(), err))?;
.map_err(|err| format!("Failed to open file at `{:?}`: {err}", &justpath.to_str()))?;
std::io::copy(&mut file, &mut hasher)
.map_err(|err| format!("Failed to read file at `{:?}`: {}", &justpath.to_str(), err))?;
.map_err(|err| format!("Failed to read file at `{:?}`: {err}", &justpath.to_str()))?;
let hash = hasher.finalize();
Ok(format!("{:x}", hash))
Ok(format!("{hash:x}"))
}
fn shoutykebabcase(_context: &FunctionContext, s: &str) -> Result<String, String> {
@ -377,11 +378,11 @@ fn uuid(_context: &FunctionContext) -> Result<String, String> {
fn without_extension(_context: &FunctionContext, path: &str) -> Result<String, String> {
let parent = Utf8Path::new(path)
.parent()
.ok_or_else(|| format!("Could not extract parent from `{}`", path))?;
.ok_or_else(|| format!("Could not extract parent from `{path}`"))?;
let file_stem = Utf8Path::new(path)
.file_stem()
.ok_or_else(|| format!("Could not extract file stem from `{}`", path))?;
.ok_or_else(|| format!("Could not extract file stem from `{path}`"))?;
Ok(parent.join(file_stem).to_string())
}

View File

@ -14,9 +14,7 @@ impl InterruptHandler {
}
pub(crate) fn instance() -> MutexGuard<'static, Self> {
lazy_static! {
static ref INSTANCE: Mutex<InterruptHandler> = Mutex::new(InterruptHandler::new());
}
static INSTANCE: Mutex<InterruptHandler> = Mutex::new(InterruptHandler::new());
match INSTANCE.lock() {
Ok(guard) => guard,
@ -24,7 +22,7 @@ impl InterruptHandler {
eprintln!(
"{}",
Error::Internal {
message: format!("interrupt handler mutex poisoned: {}", poison_error),
message: format!("interrupt handler mutex poisoned: {poison_error}"),
}
.color_display(Color::auto().stderr())
);
@ -33,7 +31,7 @@ impl InterruptHandler {
}
}
fn new() -> Self {
const fn new() -> Self {
Self {
blocks: 0,
interrupted: false,

View File

@ -13,11 +13,11 @@ pub(crate) enum Item<'src> {
impl<'src> Display for Item<'src> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Item::Alias(alias) => write!(f, "{}", alias),
Item::Assignment(assignment) => write!(f, "{}", assignment),
Item::Comment(comment) => write!(f, "{}", comment),
Item::Alias(alias) => write!(f, "{alias}"),
Item::Assignment(assignment) => write!(f, "{assignment}"),
Item::Comment(comment) => write!(f, "{comment}"),
Item::Recipe(recipe) => write!(f, "{}", recipe.color_display(Color::never())),
Item::Set(set) => write!(f, "{}", set),
Item::Set(set) => write!(f, "{set}"),
}
}
}

View File

@ -161,7 +161,7 @@ impl<'src> Justfile<'src> {
Subcommand::Evaluate { variable, .. } => {
if let Some(variable) = variable {
if let Some(value) = scope.value(variable) {
print!("{}", value);
print!("{value}");
} else {
return Err(Error::EvalUnknownVariable {
suggestion: self.suggest_variable(variable),
@ -373,14 +373,14 @@ impl<'src> ColorDisplay for Justfile<'src> {
if assignment.export {
write!(f, "export ")?;
}
write!(f, "{} := {}", name, assignment.value)?;
write!(f, "{name} := {}", assignment.value)?;
items -= 1;
if items != 0 {
write!(f, "\n\n")?;
}
}
for alias in self.aliases.values() {
write!(f, "{}", alias)?;
write!(f, "{alias}")?;
items -= 1;
if items != 0 {
write!(f, "\n\n")?;

View File

@ -121,7 +121,7 @@ impl<'src> Lexer<'src> {
fn presume(&mut self, c: char) -> CompileResult<'src, ()> {
if !self.next_is(c) {
return Err(self.internal_error(format!("Lexer presumed character `{}`", c)));
return Err(self.internal_error(format!("Lexer presumed character `{c}`")));
}
self.advance()?;
@ -948,7 +948,7 @@ mod tests {
// Variable lexemes
Text | StringToken | Backtick | Identifier | Comment | Unspecified => {
panic!("Token {:?} has no default lexeme", kind)
panic!("Token {kind:?} has no default lexeme")
}
}
}

View File

@ -88,9 +88,6 @@ pub(crate) type ConfigResult<T> = Result<T, ConfigError>;
pub(crate) type RunResult<'a, T> = Result<T, Error<'a>>;
pub(crate) type SearchResult<T> = Result<T, SearchError>;
#[macro_use]
extern crate lazy_static;
#[cfg(test)]
#[macro_use]
pub mod testing;

View File

@ -41,7 +41,7 @@ impl<T: Display, I: Iterator<Item = T> + Clone> Display for List<T, I> {
let mut values = self.values.clone().fuse();
if let Some(first) = values.next() {
write!(f, "{}", first)?;
write!(f, "{first}")?;
} else {
return Ok(());
}
@ -55,7 +55,7 @@ impl<T: Display, I: Iterator<Item = T> + Clone> Display for List<T, I> {
let third = values.next();
if let (Some(second), None) = (second.as_ref(), third.as_ref()) {
write!(f, " {} {}", self.conjunction, second)?;
write!(f, " {} {second}", self.conjunction)?;
return Ok(());
}
@ -65,12 +65,12 @@ impl<T: Display, I: Iterator<Item = T> + Clone> Display for List<T, I> {
loop {
match (current, next) {
(Some(c), Some(n)) => {
write!(f, ", {}", c)?;
write!(f, ", {c}")?;
current = Some(n);
next = values.next();
}
(Some(c), None) => {
write!(f, ", {} {}", self.conjunction, c)?;
write!(f, ", {} {c}", self.conjunction)?;
return Ok(());
}
_ => unreachable!("Iterator was fused, but returned Some after None"),

View File

@ -25,7 +25,7 @@ pub(crate) fn load_dotenv(
.to_owned();
for directory in working_directory.ancestors() {
let path = directory.join(&filename);
let path = directory.join(filename.as_str());
if path.is_file() {
return load_from_file(&path);
}

View File

@ -17,11 +17,11 @@ pub(crate) enum OutputError {
impl Display for OutputError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
Self::Code(code) => write!(f, "Process exited with status code {}", code),
Self::Io(ref io_error) => write!(f, "Error executing process: {}", io_error),
Self::Signal(signal) => write!(f, "Process terminated by signal {}", signal),
Self::Code(code) => write!(f, "Process exited with status code {code}"),
Self::Io(ref io_error) => write!(f, "Error executing process: {io_error}"),
Self::Signal(signal) => write!(f, "Process terminated by signal {signal}"),
Self::Unknown => write!(f, "Process experienced an unknown failure"),
Self::Utf8(ref err) => write!(f, "Could not convert process stdout to UTF-8: {}", err),
Self::Utf8(ref err) => write!(f, "Could not convert process stdout to UTF-8: {err}"),
}
}
}

View File

@ -894,10 +894,10 @@ mod tests {
let justfile = Parser::parse(&tokens).expect("parsing failed");
let have = justfile.tree();
if have != want {
println!("parsed text: {}", unindented);
println!("expected: {}", want);
println!("but got: {}", have);
println!("tokens: {:?}", tokens);
println!("parsed text: {unindented}");
println!("expected: {want}");
println!("but got: {have}");
println!("tokens: {tokens:?}");
panic!();
}
}

View File

@ -257,7 +257,7 @@ impl<'src, D> Recipe<'src, D> {
if config.verbosity.loud() && (config.dry_run || self.quiet) {
for line in &evaluated_lines {
eprintln!("{}", line);
eprintln!("{line}");
}
}
@ -270,7 +270,7 @@ impl<'src, D> Recipe<'src, D> {
})?;
let shebang = Shebang::new(shebang_line).ok_or_else(|| Error::Internal {
message: format!("bad shebang line: {}", shebang_line),
message: format!("bad shebang line: {shebang_line}"),
})?;
let mut tempdir_builder = tempfile::Builder::new();
@ -378,7 +378,7 @@ impl<'src, D> Recipe<'src, D> {
impl<'src, D: Display> ColorDisplay for Recipe<'src, D> {
fn fmt(&self, f: &mut Formatter, color: Color) -> Result<(), fmt::Error> {
if let Some(doc) = self.doc {
writeln!(f, "# {}", doc)?;
writeln!(f, "# {doc}")?;
}
for attribute in &self.attributes {
@ -401,7 +401,7 @@ impl<'src, D: Display> ColorDisplay for Recipe<'src, D> {
write!(f, " &&")?;
}
write!(f, " {}", dependency)?;
write!(f, " {dependency}")?;
}
for (i, line) in self.body.iter().enumerate() {
@ -414,7 +414,7 @@ impl<'src, D: Display> ColorDisplay for Recipe<'src, D> {
}
match fragment {
Fragment::Text { token } => write!(f, "{}", token.lexeme())?,
Fragment::Interpolation { expression, .. } => write!(f, "{{{{ {} }}}}", expression)?,
Fragment::Interpolation { expression, .. } => write!(f, "{{{{ {expression} }}}}")?,
}
}
if i + 1 < self.body.len() {

View File

@ -238,7 +238,7 @@ mod tests {
fs::write(&path, "default:\n\techo ok").unwrap();
path.pop();
if let Err(err) = Search::justfile(path.as_path()) {
panic!("No errors were expected: {}", err);
panic!("No errors were expected: {err}");
}
}
@ -261,7 +261,7 @@ mod tests {
fs::write(&path, "default:\n\techo ok").unwrap();
path.pop();
if let Err(err) = Search::justfile(path.as_path()) {
panic!("No errors were expected: {}", err);
panic!("No errors were expected: {err}");
}
}
@ -277,7 +277,7 @@ mod tests {
path.push("b");
fs::create_dir(&path).expect("test justfile search: failed to create intermediary directory");
if let Err(err) = Search::justfile(path.as_path()) {
panic!("No errors were expected: {}", err);
panic!("No errors were expected: {err}");
}
}
@ -301,7 +301,7 @@ mod tests {
path.push(DEFAULT_JUSTFILE_NAME);
assert_eq!(found_path, path);
}
Err(err) => panic!("No errors were expected: {}", err),
Err(err) => panic!("No errors were expected: {err}"),
}
}
@ -317,7 +317,7 @@ mod tests {
let justfile = sub.join("justfile");
#[cfg(unix)]
std::os::unix::fs::symlink(&src, &justfile).unwrap();
std::os::unix::fs::symlink(src, &justfile).unwrap();
#[cfg(windows)]
std::os::windows::fs::symlink_file(&src, &justfile).unwrap();
@ -335,7 +335,9 @@ mod tests {
let cases = &[
("/", "foo", "/foo"),
("/bar", "/foo", "/foo"),
("//foo", "bar//baz", "/foo/bar/baz"),
#[cfg(windows)]
("//foo", "bar//baz", "//foo\\bar\\baz"),
#[cfg(not(windows))]
("/", "..", "/"),
("/", "/..", "/"),
("/..", "", "/"),

View File

@ -23,10 +23,10 @@ impl<'src> Display for Setting<'src> {
| Setting::Fallback(value)
| Setting::IgnoreComments(value)
| Setting::PositionalArguments(value)
| Setting::WindowsPowerShell(value) => write!(f, "{}", value),
Setting::Shell(shell) | Setting::WindowsShell(shell) => write!(f, "{}", shell),
| Setting::WindowsPowerShell(value) => write!(f, "{value}"),
Setting::Shell(shell) | Setting::WindowsShell(shell) => write!(f, "{shell}"),
Setting::Tempdir(tempdir) => {
write!(f, "{:?}", tempdir)
write!(f, "{tempdir:?}")
}
}
}

View File

@ -40,8 +40,8 @@ impl<'line> Shebang<'line> {
pub(crate) fn script_filename(&self, recipe: &str) -> String {
match self.interpreter_filename() {
"cmd" | "cmd.exe" => format!("{}.bat", recipe),
"powershell" | "powershell.exe" | "pwsh" | "pwsh.exe" => format!("{}.ps1", recipe),
"cmd" | "cmd.exe" => format!("{recipe}.bat"),
"powershell" | "powershell.exe" | "pwsh" | "pwsh.exe" => format!("{recipe}.ps1"),
_ => recipe.to_owned(),
}
}

View File

@ -11,7 +11,7 @@ impl<'src> Display for Shell<'src> {
write!(f, "[{}", self.command)?;
for argument in &self.arguments {
write!(f, ", {}", argument)?;
write!(f, ", {argument}")?;
}
write!(f, "]")

View File

@ -9,7 +9,7 @@ impl<'str> Display for ShowWhitespace<'str> {
match c {
'\t' => write!(f, "")?,
' ' => write!(f, "")?,
_ => write!(f, "{}", c)?,
_ => write!(f, "{c}")?,
};
}

View File

@ -338,7 +338,7 @@ impl Subcommand {
.map_err(|serde_json_error| Error::DumpJson { serde_json_error })?;
println!();
}
DumpFormat::Just => print!("{}", ast),
DumpFormat::Just => print!("{ast}"),
}
Ok(())
}
@ -388,7 +388,7 @@ impl Subcommand {
ChangeTag::Insert => ("+", config.color.stderr().diff_added()),
};
eprint!("{}{}{}{}", color.prefix(), symbol, change, color.suffix());
eprint!("{}{symbol}{change}{}", color.prefix(), color.suffix());
}
}
@ -478,7 +478,7 @@ impl Subcommand {
.chain(recipe_aliases.get(name).unwrap_or(&Vec::new()))
.enumerate()
{
print!("{}{}", config.list_prefix, name);
print!("{}{name}", config.list_prefix);
for parameter in &recipe.parameters {
print!(" {}", parameter.color_display(config.color.stdout()));
}
@ -513,7 +513,7 @@ impl Subcommand {
fn show<'src>(config: &Config, name: &str, justfile: Justfile<'src>) -> Result<(), Error<'src>> {
if let Some(alias) = justfile.get_alias(name) {
let recipe = justfile.get_recipe(alias.target.name.lexeme()).unwrap();
println!("{}", alias);
println!("{alias}");
println!("{}", recipe.color_display(config.color.stdout()));
Ok(())
} else if let Some(recipe) = justfile.get_recipe(name) {
@ -539,7 +539,7 @@ impl Subcommand {
.map(|recipe| recipe.name())
.collect::<Vec<&str>>()
.join(" ");
println!("{}", summary);
println!("{summary}");
}
}

View File

@ -10,7 +10,7 @@ impl<'src> Display for Suggestion<'src> {
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, ", an alias for `{target}`")?;
}
write!(f, "?")
}

View File

@ -6,7 +6,7 @@ use pretty_assertions::assert_eq;
pub(crate) fn compile(text: &str) -> Justfile {
match Compiler::compile(text) {
Ok(justfile) => justfile,
Err(error) => panic!("Expected successful compilation but got error:\n {}", error),
Err(error) => panic!("Expected successful compilation but got error:\n {error}"),
}
}

View File

@ -49,17 +49,14 @@ impl<'src> Thunk<'src> {
name: Name<'src>,
mut arguments: Vec<Expression<'src>>,
) -> CompileResult<'src, Thunk<'src>> {
crate::function::TABLE.get(&name.lexeme()).map_or(
crate::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: *function,
name,
}),
(Function::Nullary(function), 0) => Ok(Thunk::Nullary { function, name }),
(Function::Unary(function), 1) => Ok(Thunk::Unary {
function: *function,
function,
arg: Box::new(arguments.pop().unwrap()),
name,
}),
@ -67,7 +64,7 @@ impl<'src> Thunk<'src> {
let b = Box::new(arguments.pop().unwrap());
let a = Box::new(arguments.pop().unwrap());
Ok(Thunk::Binary {
function: *function,
function,
args: [a, b],
name,
})
@ -77,7 +74,7 @@ impl<'src> Thunk<'src> {
let b = Box::new(arguments.pop().unwrap());
let a = Box::new(arguments.pop().unwrap());
Ok(Thunk::BinaryPlus {
function: *function,
function,
args: ([a, b], rest),
name,
})
@ -87,12 +84,12 @@ impl<'src> Thunk<'src> {
let b = Box::new(arguments.pop().unwrap());
let a = Box::new(arguments.pop().unwrap());
Ok(Thunk::Ternary {
function: *function,
function,
args: [a, b, c],
name,
})
}
_ => Err(name.error(CompileErrorKind::FunctionArgumentCountMismatch {
(function, _) => Err(name.error(CompileErrorKind::FunctionArgumentCountMismatch {
function: name.lexeme(),
found: arguments.len(),
expected: function.argc(),
@ -107,18 +104,18 @@ impl Display for Thunk<'_> {
use Thunk::*;
match self {
Nullary { name, .. } => write!(f, "{}()", name.lexeme()),
Unary { name, arg, .. } => write!(f, "{}({})", name.lexeme(), arg),
Unary { name, arg, .. } => write!(f, "{}({arg})", name.lexeme()),
Binary {
name, args: [a, b], ..
} => write!(f, "{}({}, {})", name.lexeme(), a, b),
} => write!(f, "{}({a}, {b})", name.lexeme()),
BinaryPlus {
name,
args: ([a, b], rest),
..
} => {
write!(f, "{}({}, {}", name.lexeme(), a, b)?;
write!(f, "{}({a}, {b}", name.lexeme())?;
for arg in rest {
write!(f, ", {}", arg)?;
write!(f, ", {arg}")?;
}
write!(f, ")")
}
@ -126,7 +123,7 @@ impl Display for Thunk<'_> {
name,
args: [a, b, c],
..
} => write!(f, "{}({}, {}, {})", name.lexeme(), a, b, c),
} => write!(f, "{}({a}, {b}, {c})", name.lexeme()),
}
}
}

View File

@ -53,7 +53,7 @@ impl<'src> ColorDisplay for Token<'src> {
}
let line_number_width = line_number.to_string().len();
writeln!(f, "{0:1$} |", "", line_number_width)?;
writeln!(f, "{} | {}", line_number, space_line)?;
writeln!(f, "{line_number} | {space_line}")?;
write!(f, "{0:1$} |", "", line_number_width)?;
write!(
f,

View File

@ -133,12 +133,12 @@ impl Display for Tree<'_> {
if i > 0 {
write!(f, " ")?;
}
write!(f, "{}", child)?;
write!(f, "{child}")?;
}
write!(f, ")")
}
Tree::Atom(text) => write!(f, "{}", text),
Tree::Atom(text) => write!(f, "{text}"),
}
}
}

View File

@ -14,7 +14,7 @@ impl<'src> Display for UnresolvedDependency<'src> {
write!(f, "({}", self.recipe)?;
for argument in &self.arguments {
write!(f, " {}", argument)?;
write!(f, " {argument}")?;
}
write!(f, ")")

View File

@ -38,10 +38,8 @@ impl Verbosity {
Grandiloquent => true,
}
}
}
impl Default for Verbosity {
fn default() -> Self {
pub const fn default() -> Self {
Self::Taciturn
}
}

View File

@ -105,7 +105,7 @@ fn working_directory_is_correct() {
fs::write(tmp.path().join("bar"), "baz").unwrap();
fs::create_dir(tmp.path().join("foo")).unwrap();
let output = Command::new(&executable_path("just"))
let output = Command::new(executable_path("just"))
.args(["--command", "cat", "bar"])
.current_dir(tmp.path().join("foo"))
.output()
@ -124,7 +124,7 @@ fn command_not_found() {
fs::write(tmp.path().join("justfile"), "").unwrap();
let output = Command::new(&executable_path("just"))
let output = Command::new(executable_path("just"))
.args(["--command", "asdfasdfasdfasdfadfsadsfadsf", "bar"])
.output()
.unwrap();

View File

@ -49,7 +49,7 @@ fn invoke_error() {
assert_eq!(
String::from_utf8_lossy(&output.stderr),
if cfg!(windows) {
"error: Editor `/` invocation failed: Access is denied. (os error 5)\n"
"error: Editor `/` invocation failed: program path has no file name\n"
} else {
"error: Editor `/` invocation failed: Permission denied (os error 13)\n"
}

View File

@ -42,7 +42,7 @@ fn write_error() {
let justfile_path = test.justfile_path();
fs::create_dir(&justfile_path).unwrap();
fs::create_dir(justfile_path).unwrap();
test
.no_justfile()

View File

@ -16,8 +16,8 @@ fn interrupt_test(arguments: &[&str], justfile: &str) {
let start = Instant::now();
let mut child = Command::new(&executable_path("just"))
.current_dir(&tmp)
let mut child = Command::new(executable_path("just"))
.current_dir(tmp)
.args(arguments)
.spawn()
.expect("just invocation failed");

View File

@ -48,7 +48,7 @@ fn test_invocation_directory() {
subdir.push("subdir");
fs::create_dir(&subdir).unwrap();
let output = Command::new(&executable_path("just"))
let output = Command::new(executable_path("just"))
.current_dir(&subdir)
.args(["--shell", "sh"])
.output()

View File

@ -25,7 +25,7 @@ fn readme() {
let path = tmp.path().join("justfile");
fs::write(&path, &justfile).unwrap();
fs::write(path, justfile).unwrap();
let output = Command::new(executable_path("just"))
.current_dir(tmp.path())

View File

@ -59,8 +59,8 @@ fn test_upwards_path_argument() {
},
};
search_test(&tmp.path().join("a"), &["../"]);
search_test(&tmp.path().join("a"), &["../default"]);
search_test(tmp.path().join("a"), &["../"]);
search_test(tmp.path().join("a"), &["../default"]);
}
#[test]
@ -140,7 +140,7 @@ fn single_upwards() {
let path = tmp.path().join("child");
search_test(&path, &["../"]);
search_test(path, &["../"]);
}
#[test]

View File

@ -176,7 +176,7 @@ impl Test {
dotenv_path.push(".env");
fs::write(dotenv_path, "DOTENV_KEY=dotenv-value").unwrap();
let mut command = Command::new(&executable_path("just"));
let mut command = Command::new(executable_path("just"));
if self.shell {
command.args(["--shell", "bash"]);
@ -258,7 +258,7 @@ struct Output<'a> {
fn test_round_trip(tmpdir: &Path) {
println!("Reparsing...");
let output = Command::new(&executable_path("just"))
let output = Command::new(executable_path("just"))
.current_dir(tmpdir)
.arg("--dump")
.output()
@ -274,7 +274,7 @@ fn test_round_trip(tmpdir: &Path) {
fs::write(&reparsed_path, &dumped).unwrap();
let output = Command::new(&executable_path("just"))
let output = Command::new(executable_path("just"))
.current_dir(tmpdir)
.arg("--justfile")
.arg(&reparsed_path)