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

Show aliases in suggestions #624

Merged
merged 4 commits into from
Apr 26, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
77 changes: 60 additions & 17 deletions src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,66 @@ pub(crate) use crate::{

// structs and enums
pub(crate) use crate::{
alias::Alias, analyzer::Analyzer, assignment::Assignment,
Celeo marked this conversation as resolved.
Show resolved Hide resolved
assignment_resolver::AssignmentResolver, binding::Binding, color::Color,
compilation_error::CompilationError, compilation_error_kind::CompilationErrorKind,
compiler::Compiler, config::Config, config_error::ConfigError, count::Count,
dependency::Dependency, enclosure::Enclosure, evaluator::Evaluator, expression::Expression,
fragment::Fragment, function::Function, function_context::FunctionContext,
interrupt_guard::InterruptGuard, interrupt_handler::InterruptHandler, item::Item,
justfile::Justfile, lexer::Lexer, line::Line, list::List, load_error::LoadError, module::Module,
name::Name, output_error::OutputError, parameter::Parameter, parser::Parser, platform::Platform,
position::Position, positional::Positional, recipe::Recipe, recipe_context::RecipeContext,
recipe_resolver::RecipeResolver, runtime_error::RuntimeError, scope::Scope, search::Search,
search_config::SearchConfig, search_error::SearchError, set::Set, setting::Setting,
settings::Settings, shebang::Shebang, show_whitespace::ShowWhitespace,
string_literal::StringLiteral, subcommand::Subcommand, table::Table, thunk::Thunk, token::Token,
token_kind::TokenKind, unresolved_dependency::UnresolvedDependency,
unresolved_recipe::UnresolvedRecipe, use_color::UseColor, variables::Variables,
verbosity::Verbosity, warning::Warning,
alias::Alias,
analyzer::Analyzer,
assignment::Assignment,
assignment_resolver::AssignmentResolver,
binding::Binding,
color::Color,
compilation_error::CompilationError,
compilation_error_kind::CompilationErrorKind,
compiler::Compiler,
config::Config,
config_error::ConfigError,
count::Count,
dependency::Dependency,
enclosure::Enclosure,
evaluator::Evaluator,
expression::Expression,
fragment::Fragment,
function::Function,
function_context::FunctionContext,
interrupt_guard::InterruptGuard,
interrupt_handler::InterruptHandler,
item::Item,
justfile::{Justfile, Suggestion},
lexer::Lexer,
line::Line,
list::List,
load_error::LoadError,
module::Module,
name::Name,
output_error::OutputError,
parameter::Parameter,
parser::Parser,
platform::Platform,
position::Position,
positional::Positional,
recipe::Recipe,
recipe_context::RecipeContext,
recipe_resolver::RecipeResolver,
runtime_error::RuntimeError,
scope::Scope,
search::Search,
search_config::SearchConfig,
search_error::SearchError,
set::Set,
setting::Setting,
settings::Settings,
shebang::Shebang,
show_whitespace::ShowWhitespace,
string_literal::StringLiteral,
subcommand::Subcommand,
table::Table,
thunk::Thunk,
token::Token,
token_kind::TokenKind,
unresolved_dependency::UnresolvedDependency,
unresolved_recipe::UnresolvedRecipe,
use_color::UseColor,
variables::Variables,
verbosity::Verbosity,
warning::Warning,
};

// type aliases
Expand Down
2 changes: 1 addition & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,7 @@ impl Config {
} else {
eprintln!("Justfile does not contain recipe `{}`.", name);
if let Some(suggestion) = justfile.suggest(name) {
eprintln!("Did you mean `{}`?", suggestion);
eprintln!("{}", suggestion);
}
Err(EXIT_FAILURE)
}
Expand Down
69 changes: 60 additions & 9 deletions src/justfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,31 @@ impl<'src> Justfile<'src> {
self.recipes.len()
}

pub(crate) fn suggest(&self, name: &str) -> Option<&'src str> {
pub(crate) fn suggest(&self, name: &str) -> Option<Suggestion> {
Celeo marked this conversation as resolved.
Show resolved Hide resolved
let mut suggestions = self
.recipes
.keys()
.map(|suggestion| (edit_distance(suggestion, name), suggestion))
.collect::<Vec<_>>();
suggestions.sort();
if let Some(&(distance, suggestion)) = suggestions.first() {
if distance < 3 {
return Some(suggestion);
}
.map(|recipe_name| {
(edit_distance(recipe_name, name), Suggestion {
name: recipe_name,
target: None,
})
})
.chain(self.aliases.iter().map(|(alias_name, alias)| {
(edit_distance(alias_name, name), Suggestion {
name: alias_name,
target: Some(alias.target.name.lexeme()),
})
}))
.filter(|(distance, _suggestion)| distance < &3)
.collect::<Vec<(usize, Suggestion)>>();
suggestions.sort_by_key(|(distance, _suggestion)| *distance);

if let Some((_distance, suggestion)) = suggestions.first() {
Celeo marked this conversation as resolved.
Show resolved Hide resolved
Some(*suggestion)
} else {
None
}
None
}

pub(crate) fn run<'run>(
Expand Down Expand Up @@ -280,6 +292,22 @@ impl<'src> Display for Justfile<'src> {
}
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Suggestion<'src> {
pub(crate) name: &'src str,
pub(crate) target: Option<&'src str>,
}

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, "?")
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -301,6 +329,29 @@ mod tests {
}
}

run_error! {
name: unknown_recipes_show_alias_suggestion,
src: "
foo:
echo foo

alias z := foo
",
args: ["zz"],
error: UnknownRecipes {
recipes,
suggestion,
},
check: {
assert_eq!(recipes, &["zz"]);
assert_eq!(suggestion, Some(Suggestion {
name: "z",
target: Some("foo"),
}
));
}
}

// This test exists to make sure that shebang recipes run correctly. Although
// this script is still executed by a shell its behavior depends on the value of
// a variable and continuing even though a command fails, whereas in plain
Expand Down
4 changes: 2 additions & 2 deletions src/runtime_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub(crate) enum RuntimeError<'src> {
},
UnknownRecipes {
recipes: Vec<&'src str>,
suggestion: Option<&'src str>,
suggestion: Option<Suggestion<'src>>,
},
Unknown {
recipe: &'src str,
Expand Down Expand Up @@ -117,7 +117,7 @@ impl<'src> Display for RuntimeError<'src> {
List::or_ticked(recipes),
)?;
if let Some(suggestion) = *suggestion {
write!(f, "\nDid you mean `{}`?", suggestion)?;
write!(f, "\n{}", suggestion)?;
}
},
UnknownOverrides { overrides } => {
Expand Down