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 alias attribute #2615

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion src/alias.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::*;

/// An alias, e.g. `name := target`
#[derive(Debug, PartialEq, Clone, Serialize)]
#[derive(Debug, PartialEq, Ord, PartialOrd, Eq, Clone, Serialize)]
pub(crate) struct Alias<'src, T = Rc<Recipe<'src>>> {
pub(crate) attributes: AttributeSet<'src>,
pub(crate) name: Name<'src>,
Expand Down
11 changes: 11 additions & 0 deletions src/analyzer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,17 @@ impl<'run, 'src> Analyzer<'run, 'src> {
if recipe.enabled() {
Self::analyze_recipe(recipe)?;
self.recipes.push(recipe);

for attribute in &recipe.attributes {
if let Attribute::Alias(name, _) = attribute {
Self::define(&mut definitions, *name, "alias", false)?;
self.aliases.insert(Alias {
name: *name,
target: recipe.name,
attributes: AttributeSet::new(),
});
}
}
}
}
Item::Set(set) => {
Expand Down
56 changes: 42 additions & 14 deletions src/attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use super::*;
#[strum_discriminants(derive(EnumString, Ord, PartialOrd))]
#[strum_discriminants(strum(serialize_all = "kebab-case"))]
pub(crate) enum Attribute<'src> {
Alias(Name<'src>, StringLiteral<'src>),
Confirm(Option<StringLiteral<'src>>),
Doc(Option<StringLiteral<'src>>),
ExitMessage,
Expand All @@ -32,7 +33,7 @@ impl AttributeDiscriminant {
fn argument_range(self) -> RangeInclusive<usize> {
match self {
Self::Confirm | Self::Doc => 0..=1,
Self::Group | Self::Extension | Self::WorkingDirectory => 1..=1,
Self::Alias | Self::Group | Self::Extension | Self::WorkingDirectory => 1..=1,
Self::ExitMessage
| Self::Linux
| Self::Macos
Expand All @@ -52,7 +53,7 @@ impl AttributeDiscriminant {
impl<'src> Attribute<'src> {
pub(crate) fn new(
name: Name<'src>,
arguments: Vec<StringLiteral<'src>>,
arguments: Vec<(Token<'src>, StringLiteral<'src>)>,
) -> CompileResult<'src, Self> {
let discriminant = name
.lexeme()
Expand All @@ -77,12 +78,41 @@ impl<'src> Attribute<'src> {
);
}

let mut arguments = arguments.into_iter();
let (token, argument) = arguments
.next()
.map(|(token, arg)| (Some(token), Some(arg)))
.unwrap_or_default();

Ok(match discriminant {
AttributeDiscriminant::Confirm => Self::Confirm(arguments.into_iter().next()),
AttributeDiscriminant::Doc => Self::Doc(arguments.into_iter().next()),
AttributeDiscriminant::Alias => {
let string_literal = argument.unwrap();
let delim = string_literal.kind.delimiter_len();
let token = token.unwrap();
let token = Token {
kind: TokenKind::Identifier,
column: token.column + delim,
length: token.length - (delim * 2),
offset: token.offset + delim,
..token
};

let alias = token.lexeme();
let valid_alias = alias.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');

if alias.is_empty() || !valid_alias {
return Err(token.error(CompileErrorKind::InvalidAliasName {
name: token.lexeme(),
}));
}

Self::Alias(Name::from_identifier(token), string_literal)
}
AttributeDiscriminant::Confirm => Self::Confirm(argument),
AttributeDiscriminant::Doc => Self::Doc(argument),
AttributeDiscriminant::ExitMessage => Self::ExitMessage,
AttributeDiscriminant::Extension => Self::Extension(arguments.into_iter().next().unwrap()),
AttributeDiscriminant::Group => Self::Group(arguments.into_iter().next().unwrap()),
AttributeDiscriminant::Extension => Self::Extension(argument.unwrap()),
AttributeDiscriminant::Group => Self::Group(argument.unwrap()),
AttributeDiscriminant::Linux => Self::Linux,
AttributeDiscriminant::Macos => Self::Macos,
AttributeDiscriminant::NoCd => Self::NoCd,
Expand All @@ -92,17 +122,14 @@ impl<'src> Attribute<'src> {
AttributeDiscriminant::PositionalArguments => Self::PositionalArguments,
AttributeDiscriminant::Private => Self::Private,
AttributeDiscriminant::Script => Self::Script({
let mut arguments = arguments.into_iter();
arguments.next().map(|command| Interpreter {
argument.map(|command| Interpreter {
command,
arguments: arguments.collect(),
arguments: arguments.map(|(_, arg)| arg).collect(),
})
}),
AttributeDiscriminant::Unix => Self::Unix,
AttributeDiscriminant::Windows => Self::Windows,
AttributeDiscriminant::WorkingDirectory => {
Self::WorkingDirectory(arguments.into_iter().next().unwrap())
}
AttributeDiscriminant::WorkingDirectory => Self::WorkingDirectory(argument.unwrap()),
})
}

Expand All @@ -115,7 +142,7 @@ impl<'src> Attribute<'src> {
}

pub(crate) fn repeatable(&self) -> bool {
matches!(self, Attribute::Group(_))
matches!(self, Attribute::Group(_) | Attribute::Alias(_, _))
}
}

Expand All @@ -124,7 +151,8 @@ impl Display for Attribute<'_> {
write!(f, "{}", self.name())?;

match self {
Self::Confirm(Some(argument))
Self::Alias(_, argument)
| Self::Confirm(Some(argument))
| Self::Doc(Some(argument))
| Self::Extension(argument)
| Self::Group(argument)
Expand Down
6 changes: 5 additions & 1 deletion src/attribute_set.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
use {super::*, std::collections};

#[derive(Default, Debug, Clone, PartialEq, Serialize)]
#[derive(Default, Debug, Clone, PartialEq, PartialOrd, Ord, Eq, Serialize)]
pub(crate) struct AttributeSet<'src>(BTreeSet<Attribute<'src>>);

impl<'src> AttributeSet<'src> {
pub(crate) fn new() -> Self {
Self(BTreeSet::new())
}

pub(crate) fn len(&self) -> usize {
self.0.len()
}
Expand Down
4 changes: 4 additions & 0 deletions src/compile_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ impl Display for CompileError<'_> {
"Internal error, this may indicate a bug in just: {message}\n\
consider filing an issue: https://github.com/casey/just/issues/new"
),
InvalidAliasName { name } => write!(
f,
"`{name}` is not a valid alias. Aliases must only contain alphanumeric characters and underscores."
),
InvalidAttribute {
item_name,
item_kind,
Expand Down
3 changes: 3 additions & 0 deletions src/compile_error_kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ pub(crate) enum CompileErrorKind<'src> {
Internal {
message: String,
},
InvalidAliasName {
name: &'src str,
},
InvalidAttribute {
item_kind: &'static str,
item_name: &'src str,
Expand Down
4 changes: 2 additions & 2 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1181,10 +1181,10 @@ impl<'run, 'src> Parser<'run, 'src> {
let mut arguments = Vec::new();

if self.accepted(Colon)? {
arguments.push(self.parse_string_literal()?);
arguments.push(self.parse_string_literal_token()?);
} else if self.accepted(ParenL)? {
loop {
arguments.push(self.parse_string_literal()?);
arguments.push(self.parse_string_literal_token()?);

if !self.accepted(Comma)? {
break;
Expand Down
162 changes: 162 additions & 0 deletions tests/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,3 +254,165 @@ fn duplicate_non_repeatable_attributes_are_forbidden() {
.status(EXIT_FAILURE)
.run();
}

#[test]
fn aliases_can_be_defined_as_attributes() {
Test::new()
.justfile(
"
[alias('bar')]
baz:
",
)
.arg("bar")
.status(EXIT_SUCCESS)
.run();
}

#[test]
fn multiple_aliases_can_be_defined_as_attributes() {
Test::new()
.justfile(
"
[alias('bar')]
[alias('foo')]
baz:
",
)
.arg("foo")
.status(EXIT_SUCCESS)
.run();
}

#[test]
fn duplicate_alias_attributes_are_forbidden() {
Test::new()
.justfile(
"
[alias('foo')]
[alias('foo')]
baz:
",
)
.arg("foo")
.stderr(
"
error: Alias `foo` first defined on line 1 is redefined on line 2
——▶ justfile:2:9
2 │ [alias('foo')]
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}

#[test]
fn alias_attributes_duplicating_alias_definition_is_forbidden() {
Test::new()
.justfile(
"
alias foo := baz
[alias('foo')]
baz:
",
)
.arg("foo")
.stderr(
"
error: Alias `foo` first defined on line 1 is redefined on line 2
——▶ justfile:2:9
2 │ [alias('foo')]
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}

#[test]
fn alias_definitions_duplicating_alias_attributes_is_forbidden() {
Test::new()
.justfile(
"
[alias('foo')]
baz:

alias foo := baz
",
)
.arg("foo")
.stderr(
"
error: Alias `foo` first defined on line 1 is redefined on line 4
——▶ justfile:4:7
4 │ alias foo := baz
│ ^^^
",
)
.status(EXIT_FAILURE)
.run();
}

#[test]
fn alphanumeric_and_underscores_are_valid_alias_attributes() {
Test::new()
.justfile(
"
[alias('alpha_numeric_123')]
baz:
",
)
.arg("alpha_numeric_123")
.status(EXIT_SUCCESS)
.run();
}

#[test]
fn nonalphanumeric_alias_attribute_is_forbidden() {
Test::new()
.justfile(
"
[alias('invalid name!')]
baz:
",
)
.arg("foo")
.stderr(
"
error: `invalid name!` is not a valid alias. Aliases must only contain alphanumeric characters and underscores.
——▶ justfile:1:9
1 │ [alias('invalid name!')]
│ ^^^^^^^^^^^^^
",
)
.status(EXIT_FAILURE)
.run();
}

#[test]
fn empty_alias_attribute_is_forbidden() {
Test::new()
.justfile(
"
[alias('')]
baz:
",
)
.arg("baz")
.stderr(
"
error: `` is not a valid alias. Aliases must only contain alphanumeric characters and underscores.
——▶ justfile:1:9
1 │ [alias('')]
│ ^
",
)
.status(EXIT_FAILURE)
.run();
}