1
1
mirror of https://github.com/casey/just.git synced 2024-11-22 10:26:26 +03:00

Compare commits

...

16 Commits

Author SHA1 Message Date
Greg Shuflin
54c1cf722c
Merge 1379edc660 into 17350a603e 2024-11-18 13:35:42 -08:00
dependabot[bot]
17350a603e
Update softprops/action-gh-release (#2471) 2024-11-18 11:04:52 -08:00
Casey Rodarmor
1379edc660 Add newline 2024-11-11 15:56:42 -08:00
Casey Rodarmor
e439bdd9c7 Move AttributeSet into its own file 2024-11-11 15:48:49 -08:00
Casey Rodarmor
43d4e4586c Consolidate imports 2024-11-11 15:43:08 -08:00
Casey Rodarmor
a9e568f92d Merge remote-tracking branch 'origin/master' into attributeset 2024-11-11 15:39:46 -08:00
Casey Rodarmor
90537ca002 Implement FromIterator for AttributeSet 2024-11-11 15:39:32 -08:00
Greg Shuflin
c78467a171
Merge branch 'master' into attributeset 2024-11-05 16:54:45 -08:00
Greg Shuflin
ab3fcc41cf
Merge branch 'master' into attributeset 2024-11-03 20:26:47 -08:00
Greg Shuflin
90a1102ac1 tweak 2024-11-02 00:22:09 -07:00
Greg Shuflin
aca47c7229 fix 2024-11-01 21:24:32 -07:00
Greg Shuflin
0716e62761 use discriminant 2024-11-01 19:30:35 -07:00
Greg Shuflin
b64704592b More pr comments 2024-11-01 01:27:34 -07:00
Greg Shuflin
a452435052 WIP PR comments 2024-11-01 01:27:34 -07:00
Greg Shuflin
27648a97eb PR comments 2024-11-01 01:27:34 -07:00
Greg Shuflin
722a8776be AttributeSet type 2024-11-01 01:27:34 -07:00
9 changed files with 225 additions and 110 deletions

View File

@ -110,7 +110,7 @@ jobs:
shell: bash shell: bash
- name: Publish Archive - name: Publish Archive
uses: softprops/action-gh-release@v2.0.9 uses: softprops/action-gh-release@v2.1.0
if: ${{ startsWith(github.ref, 'refs/tags/') }} if: ${{ startsWith(github.ref, 'refs/tags/') }}
with: with:
draft: false draft: false
@ -120,7 +120,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Publish Changelog - name: Publish Changelog
uses: softprops/action-gh-release@v2.0.9 uses: softprops/action-gh-release@v2.1.0
if: >- if: >-
${{ ${{
startsWith(github.ref, 'refs/tags/') startsWith(github.ref, 'refs/tags/')
@ -157,7 +157,7 @@ jobs:
shasum -a 256 * > ../SHA256SUMS shasum -a 256 * > ../SHA256SUMS
- name: Publish Checksums - name: Publish Checksums
uses: softprops/action-gh-release@v2.0.9 uses: softprops/action-gh-release@v2.1.0
with: with:
draft: false draft: false
files: SHA256SUMS files: SHA256SUMS

View File

@ -3,7 +3,7 @@ use super::*;
/// An alias, e.g. `name := target` /// An alias, e.g. `name := target`
#[derive(Debug, PartialEq, Clone, Serialize)] #[derive(Debug, PartialEq, Clone, Serialize)]
pub(crate) struct Alias<'src, T = Rc<Recipe<'src>>> { pub(crate) struct Alias<'src, T = Rc<Recipe<'src>>> {
pub(crate) attributes: BTreeSet<Attribute<'src>>, pub(crate) attributes: AttributeSet<'src>,
pub(crate) name: Name<'src>, pub(crate) name: Name<'src>,
#[serde( #[serde(
bound(serialize = "T: Keyed<'src>"), bound(serialize = "T: Keyed<'src>"),
@ -26,7 +26,7 @@ impl<'src> Alias<'src, Name<'src>> {
impl Alias<'_> { impl Alias<'_> {
pub(crate) fn is_private(&self) -> bool { pub(crate) fn is_private(&self) -> bool {
self.name.lexeme().starts_with('_') || self.attributes.contains(&Attribute::Private) self.name.lexeme().starts_with('_') || self.attributes.contains(AttributeDiscriminant::Private)
} }
} }

View File

@ -72,17 +72,21 @@ impl<'run, 'src> Analyzer<'run, 'src> {
} => { } => {
let mut doc_attr: Option<&str> = None; let mut doc_attr: Option<&str> = None;
let mut groups = Vec::new(); let mut groups = Vec::new();
for attribute in attributes { attributes.ensure_valid_attributes(
if let Attribute::Doc(ref doc) = attribute { "Module",
**name,
&[AttributeDiscriminant::Doc, AttributeDiscriminant::Group],
)?;
for attribute in attributes.iter() {
match attribute {
Attribute::Doc(ref doc) => {
doc_attr = Some(doc.as_ref().map(|s| s.cooked.as_ref()).unwrap_or_default()); doc_attr = Some(doc.as_ref().map(|s| s.cooked.as_ref()).unwrap_or_default());
} else if let Attribute::Group(ref group) = attribute { }
Attribute::Group(ref group) => {
groups.push(group.cooked.clone()); groups.push(group.cooked.clone());
} else { }
return Err(name.token.error(InvalidAttribute { _ => unreachable!(),
item_kind: "Module",
item_name: name.lexeme(),
attribute: attribute.clone(),
}));
} }
} }
@ -170,13 +174,11 @@ impl<'run, 'src> Analyzer<'run, 'src> {
} }
for recipe in recipes.values() { for recipe in recipes.values() {
for attribute in &recipe.attributes { if recipe.attributes.contains(AttributeDiscriminant::Script) {
if let Attribute::Script(_) = attribute {
unstable_features.insert(UnstableFeature::ScriptAttribute); unstable_features.insert(UnstableFeature::ScriptAttribute);
break; break;
} }
} }
}
if settings.script_interpreter.is_some() { if settings.script_interpreter.is_some() {
unstable_features.insert(UnstableFeature::ScriptInterpreterSetting); unstable_features.insert(UnstableFeature::ScriptInterpreterSetting);
@ -284,11 +286,7 @@ impl<'run, 'src> Analyzer<'run, 'src> {
} }
if !recipe.is_script() { if !recipe.is_script() {
if let Some(attribute) = recipe if let Some(attribute) = recipe.attributes.get(AttributeDiscriminant::Extension) {
.attributes
.iter()
.find(|attribute| matches!(attribute, Attribute::Extension(_)))
{
return Err(recipe.name.error(InvalidAttribute { return Err(recipe.name.error(InvalidAttribute {
item_kind: "Recipe", item_kind: "Recipe",
item_name: recipe.name.lexeme(), item_name: recipe.name.lexeme(),
@ -301,16 +299,11 @@ impl<'run, 'src> Analyzer<'run, 'src> {
} }
fn analyze_alias(alias: &Alias<'src, Name<'src>>) -> CompileResult<'src> { fn analyze_alias(alias: &Alias<'src, Name<'src>>) -> CompileResult<'src> {
for attribute in &alias.attributes { alias.attributes.ensure_valid_attributes(
if *attribute != Attribute::Private { "Alias",
return Err(alias.name.token.error(InvalidAttribute { *alias.name,
item_kind: "Alias", &[AttributeDiscriminant::Private],
item_name: alias.name.lexeme(), )?;
attribute: attribute.clone(),
}));
}
}
Ok(()) Ok(())
} }

View File

@ -1,4 +1,4 @@
use super::*; use {super::*, std::collections};
#[derive( #[derive(
EnumDiscriminants, PartialEq, Debug, Clone, Serialize, Ord, PartialOrd, Eq, IntoStaticStr, EnumDiscriminants, PartialEq, Debug, Clone, Serialize, Ord, PartialOrd, Eq, IntoStaticStr,
@ -96,6 +96,10 @@ impl<'src> Attribute<'src> {
}) })
} }
pub(crate) fn discriminant(&self) -> AttributeDiscriminant {
self.into()
}
pub(crate) fn name(&self) -> &'static str { pub(crate) fn name(&self) -> &'static str {
self.into() self.into()
} }

60
src/attribute_set.rs Normal file
View File

@ -0,0 +1,60 @@
use {super::*, std::collections};
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub(crate) struct AttributeSet<'src>(BTreeSet<Attribute<'src>>);
impl<'src> AttributeSet<'src> {
pub(crate) fn len(&self) -> usize {
self.0.len()
}
pub(crate) fn contains(&self, target: AttributeDiscriminant) -> bool {
self.0.iter().any(|attr| attr.discriminant() == target)
}
pub(crate) fn get(&self, discriminant: AttributeDiscriminant) -> Option<&Attribute<'src>> {
self
.0
.iter()
.find(|attr| discriminant == attr.discriminant())
}
pub(crate) fn iter(&self) -> impl Iterator<Item = &Attribute<'src>> {
self.0.iter()
}
pub(crate) fn ensure_valid_attributes(
&self,
item_kind: &'static str,
item_token: Token<'src>,
valid: &[AttributeDiscriminant],
) -> Result<(), CompileError<'src>> {
for attribute in &self.0 {
let discriminant = attribute.discriminant();
if !valid.contains(&discriminant) {
return Err(item_token.error(CompileErrorKind::InvalidAttribute {
item_kind,
item_name: item_token.lexeme(),
attribute: attribute.clone(),
}));
}
}
Ok(())
}
}
impl<'src, 'a> FromIterator<Attribute<'src>> for AttributeSet<'src> {
fn from_iter<T: IntoIterator<Item = attribute::Attribute<'src>>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
impl<'src, 'a> IntoIterator for &'a AttributeSet<'src> {
type Item = &'a Attribute<'src>;
type IntoIter = collections::btree_set::Iter<'a, Attribute<'src>>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}

View File

@ -13,7 +13,7 @@ pub(crate) enum Item<'src> {
relative: StringLiteral<'src>, relative: StringLiteral<'src>,
}, },
Module { Module {
attributes: BTreeSet<Attribute<'src>>, attributes: AttributeSet<'src>,
absolute: Option<PathBuf>, absolute: Option<PathBuf>,
doc: Option<&'src str>, doc: Option<&'src str>,
name: Name<'src>, name: Name<'src>,

View File

@ -6,31 +6,96 @@
pub(crate) use { pub(crate) use {
crate::{ crate::{
alias::Alias, analyzer::Analyzer, argument_parser::ArgumentParser, assignment::Assignment, alias::Alias,
assignment_resolver::AssignmentResolver, ast::Ast, attribute::Attribute, binding::Binding, analyzer::Analyzer,
color::Color, color_display::ColorDisplay, command_color::CommandColor, argument_parser::ArgumentParser,
command_ext::CommandExt, compilation::Compilation, compile_error::CompileError, assignment::Assignment,
compile_error_kind::CompileErrorKind, compiler::Compiler, condition::Condition, assignment_resolver::AssignmentResolver,
conditional_operator::ConditionalOperator, config::Config, config_error::ConfigError, ast::Ast,
constants::constants, count::Count, delimiter::Delimiter, dependency::Dependency, attribute::{Attribute, AttributeDiscriminant},
dump_format::DumpFormat, enclosure::Enclosure, error::Error, evaluator::Evaluator, attribute_set::AttributeSet,
execution_context::ExecutionContext, executor::Executor, expression::Expression, binding::Binding,
fragment::Fragment, function::Function, interpreter::Interpreter, color::Color,
interrupt_guard::InterruptGuard, interrupt_handler::InterruptHandler, item::Item, color_display::ColorDisplay,
justfile::Justfile, keyed::Keyed, keyword::Keyword, lexer::Lexer, line::Line, list::List, command_color::CommandColor,
load_dotenv::load_dotenv, loader::Loader, module_path::ModulePath, name::Name, command_ext::CommandExt,
namepath::Namepath, ordinal::Ordinal, output::output, output_error::OutputError, compilation::Compilation,
parameter::Parameter, parameter_kind::ParameterKind, parser::Parser, platform::Platform, compile_error::CompileError,
platform_interface::PlatformInterface, position::Position, positional::Positional, ran::Ran, compile_error_kind::CompileErrorKind,
range_ext::RangeExt, recipe::Recipe, recipe_resolver::RecipeResolver, compiler::Compiler,
recipe_signature::RecipeSignature, scope::Scope, search::Search, search_config::SearchConfig, condition::Condition,
search_error::SearchError, set::Set, setting::Setting, settings::Settings, shebang::Shebang, conditional_operator::ConditionalOperator,
show_whitespace::ShowWhitespace, source::Source, string_delimiter::StringDelimiter, config::Config,
string_kind::StringKind, string_literal::StringLiteral, subcommand::Subcommand, config_error::ConfigError,
suggestion::Suggestion, table::Table, thunk::Thunk, token::Token, token_kind::TokenKind, constants::constants,
unresolved_dependency::UnresolvedDependency, unresolved_recipe::UnresolvedRecipe, count::Count,
unstable_feature::UnstableFeature, use_color::UseColor, variables::Variables, delimiter::Delimiter,
verbosity::Verbosity, warning::Warning, dependency::Dependency,
dump_format::DumpFormat,
enclosure::Enclosure,
error::Error,
evaluator::Evaluator,
execution_context::ExecutionContext,
executor::Executor,
expression::Expression,
fragment::Fragment,
function::Function,
interpreter::Interpreter,
interrupt_guard::InterruptGuard,
interrupt_handler::InterruptHandler,
item::Item,
justfile::Justfile,
keyed::Keyed,
keyword::Keyword,
lexer::Lexer,
line::Line,
list::List,
load_dotenv::load_dotenv,
loader::Loader,
module_path::ModulePath,
name::Name,
namepath::Namepath,
ordinal::Ordinal,
output::output,
output_error::OutputError,
parameter::Parameter,
parameter_kind::ParameterKind,
parser::Parser,
platform::Platform,
platform_interface::PlatformInterface,
position::Position,
positional::Positional,
ran::Ran,
range_ext::RangeExt,
recipe::Recipe,
recipe_resolver::RecipeResolver,
recipe_signature::RecipeSignature,
scope::Scope,
search::Search,
search_config::SearchConfig,
search_error::SearchError,
set::Set,
setting::Setting,
settings::Settings,
shebang::Shebang,
show_whitespace::ShowWhitespace,
source::Source,
string_delimiter::StringDelimiter,
string_kind::StringKind,
string_literal::StringLiteral,
subcommand::Subcommand,
suggestion::Suggestion,
table::Table,
thunk::Thunk,
token::Token,
token_kind::TokenKind,
unresolved_dependency::UnresolvedDependency,
unresolved_recipe::UnresolvedRecipe,
unstable_feature::UnstableFeature,
use_color::UseColor,
variables::Variables,
verbosity::Verbosity,
warning::Warning,
}, },
camino::Utf8Path, camino::Utf8Path,
clap::ValueEnum, clap::ValueEnum,
@ -113,6 +178,7 @@ mod assignment;
mod assignment_resolver; mod assignment_resolver;
mod ast; mod ast;
mod attribute; mod attribute;
mod attribute_set;
mod binding; mod binding;
mod color; mod color;
mod color_display; mod color_display;

View File

@ -462,7 +462,7 @@ impl<'run, 'src> Parser<'run, 'src> {
/// Parse an alias, e.g `alias name := target` /// Parse an alias, e.g `alias name := target`
fn parse_alias( fn parse_alias(
&mut self, &mut self,
attributes: BTreeSet<Attribute<'src>>, attributes: AttributeSet<'src>,
) -> CompileResult<'src, Alias<'src, Name<'src>>> { ) -> CompileResult<'src, Alias<'src, Name<'src>>> {
self.presume_keyword(Keyword::Alias)?; self.presume_keyword(Keyword::Alias)?;
let name = self.parse_name()?; let name = self.parse_name()?;
@ -480,24 +480,16 @@ impl<'run, 'src> Parser<'run, 'src> {
fn parse_assignment( fn parse_assignment(
&mut self, &mut self,
export: bool, export: bool,
attributes: BTreeSet<Attribute<'src>>, attributes: AttributeSet<'src>,
) -> CompileResult<'src, Assignment<'src>> { ) -> CompileResult<'src, Assignment<'src>> {
let name = self.parse_name()?; let name = self.parse_name()?;
self.presume(ColonEquals)?; self.presume(ColonEquals)?;
let value = self.parse_expression()?; let value = self.parse_expression()?;
self.expect_eol()?; self.expect_eol()?;
let private = attributes.contains(&Attribute::Private); let private = attributes.contains(AttributeDiscriminant::Private);
for attribute in attributes { attributes.ensure_valid_attributes("Assignment", *name, &[AttributeDiscriminant::Private])?;
if attribute != Attribute::Private {
return Err(name.error(CompileErrorKind::InvalidAttribute {
item_kind: "Assignment",
item_name: name.lexeme(),
attribute,
}));
}
}
Ok(Assignment { Ok(Assignment {
constant: false, constant: false,
@ -863,7 +855,7 @@ impl<'run, 'src> Parser<'run, 'src> {
&mut self, &mut self,
doc: Option<&'src str>, doc: Option<&'src str>,
quiet: bool, quiet: bool,
attributes: BTreeSet<Attribute<'src>>, attributes: AttributeSet<'src>,
) -> CompileResult<'src, UnresolvedRecipe<'src>> { ) -> CompileResult<'src, UnresolvedRecipe<'src>> {
let name = self.parse_name()?; let name = self.parse_name()?;
@ -924,9 +916,7 @@ impl<'run, 'src> Parser<'run, 'src> {
let body = self.parse_body()?; let body = self.parse_body()?;
let shebang = body.first().map_or(false, Line::is_shebang); let shebang = body.first().map_or(false, Line::is_shebang);
let script = attributes let script = attributes.contains(AttributeDiscriminant::Script);
.iter()
.any(|attribute| matches!(attribute, Attribute::Script(_)));
if shebang && script { if shebang && script {
return Err(name.error(CompileErrorKind::ShebangAndScriptAttribute { return Err(name.error(CompileErrorKind::ShebangAndScriptAttribute {
@ -934,7 +924,8 @@ impl<'run, 'src> Parser<'run, 'src> {
})); }));
} }
let private = name.lexeme().starts_with('_') || attributes.contains(&Attribute::Private); let private =
name.lexeme().starts_with('_') || attributes.contains(AttributeDiscriminant::Private);
let mut doc = doc.map(ToOwned::to_owned); let mut doc = doc.map(ToOwned::to_owned);
@ -1122,9 +1113,7 @@ impl<'run, 'src> Parser<'run, 'src> {
} }
/// Item attributes, i.e., `[macos]` or `[confirm: "warning!"]` /// Item attributes, i.e., `[macos]` or `[confirm: "warning!"]`
fn parse_attributes( fn parse_attributes(&mut self) -> CompileResult<'src, Option<(Token<'src>, AttributeSet<'src>)>> {
&mut self,
) -> CompileResult<'src, Option<(Token<'src>, BTreeSet<Attribute<'src>>)>> {
let mut attributes = BTreeMap::new(); let mut attributes = BTreeMap::new();
let mut token = None; let mut token = None;

View File

@ -19,7 +19,7 @@ fn error_from_signal(recipe: &str, line_number: Option<usize>, exit_status: Exit
/// A recipe, e.g. `foo: bar baz` /// A recipe, e.g. `foo: bar baz`
#[derive(PartialEq, Debug, Clone, Serialize)] #[derive(PartialEq, Debug, Clone, Serialize)]
pub(crate) struct Recipe<'src, D = Dependency<'src>> { pub(crate) struct Recipe<'src, D = Dependency<'src>> {
pub(crate) attributes: BTreeSet<Attribute<'src>>, pub(crate) attributes: AttributeSet<'src>,
pub(crate) body: Vec<Line<'src>>, pub(crate) body: Vec<Line<'src>>,
pub(crate) dependencies: Vec<D>, pub(crate) dependencies: Vec<D>,
pub(crate) doc: Option<String>, pub(crate) doc: Option<String>,
@ -66,8 +66,9 @@ impl<'src, D> Recipe<'src, D> {
} }
pub(crate) fn confirm(&self) -> RunResult<'src, bool> { pub(crate) fn confirm(&self) -> RunResult<'src, bool> {
for attribute in &self.attributes { if let Some(Attribute::Confirm(ref prompt)) =
if let Attribute::Confirm(prompt) = attribute { self.attributes.get(AttributeDiscriminant::Confirm)
{
if let Some(prompt) = prompt { if let Some(prompt) = prompt {
eprint!("{} ", prompt.cooked); eprint!("{} ", prompt.cooked);
} else { } else {
@ -80,7 +81,6 @@ impl<'src, D> Recipe<'src, D> {
let line = line.trim().to_lowercase(); let line = line.trim().to_lowercase();
return Ok(line == "y" || line == "yes"); return Ok(line == "y" || line == "yes");
} }
}
Ok(true) Ok(true)
} }
@ -97,7 +97,7 @@ impl<'src, D> Recipe<'src, D> {
} }
pub(crate) fn is_public(&self) -> bool { pub(crate) fn is_public(&self) -> bool {
!self.private && !self.attributes.contains(&Attribute::Private) !self.private && !self.attributes.contains(AttributeDiscriminant::Private)
} }
pub(crate) fn is_script(&self) -> bool { pub(crate) fn is_script(&self) -> bool {
@ -105,18 +105,21 @@ impl<'src, D> Recipe<'src, D> {
} }
pub(crate) fn takes_positional_arguments(&self, settings: &Settings) -> bool { pub(crate) fn takes_positional_arguments(&self, settings: &Settings) -> bool {
settings.positional_arguments || self.attributes.contains(&Attribute::PositionalArguments) settings.positional_arguments
|| self
.attributes
.contains(AttributeDiscriminant::PositionalArguments)
} }
pub(crate) fn change_directory(&self) -> bool { pub(crate) fn change_directory(&self) -> bool {
!self.attributes.contains(&Attribute::NoCd) !self.attributes.contains(AttributeDiscriminant::NoCd)
} }
pub(crate) fn enabled(&self) -> bool { pub(crate) fn enabled(&self) -> bool {
let windows = self.attributes.contains(&Attribute::Windows); let windows = self.attributes.contains(AttributeDiscriminant::Windows);
let linux = self.attributes.contains(&Attribute::Linux); let linux = self.attributes.contains(AttributeDiscriminant::Linux);
let macos = self.attributes.contains(&Attribute::Macos); let macos = self.attributes.contains(AttributeDiscriminant::Macos);
let unix = self.attributes.contains(&Attribute::Unix); let unix = self.attributes.contains(AttributeDiscriminant::Unix);
(!windows && !linux && !macos && !unix) (!windows && !linux && !macos && !unix)
|| (cfg!(target_os = "windows") && windows) || (cfg!(target_os = "windows") && windows)
@ -127,7 +130,9 @@ impl<'src, D> Recipe<'src, D> {
} }
fn print_exit_message(&self) -> bool { fn print_exit_message(&self) -> bool {
!self.attributes.contains(&Attribute::NoExitMessage) !self
.attributes
.contains(AttributeDiscriminant::NoExitMessage)
} }
fn working_directory<'a>(&'a self, context: &'a ExecutionContext) -> Option<PathBuf> { fn working_directory<'a>(&'a self, context: &'a ExecutionContext) -> Option<PathBuf> {
@ -139,7 +144,7 @@ impl<'src, D> Recipe<'src, D> {
} }
fn no_quiet(&self) -> bool { fn no_quiet(&self) -> bool {
self.attributes.contains(&Attribute::NoQuiet) self.attributes.contains(AttributeDiscriminant::NoQuiet)
} }
pub(crate) fn run<'run>( pub(crate) fn run<'run>(
@ -341,10 +346,8 @@ impl<'src, D> Recipe<'src, D> {
return Ok(()); return Ok(());
} }
let executor = if let Some(Attribute::Script(interpreter)) = self let executor = if let Some(Attribute::Script(interpreter)) =
.attributes self.attributes.get(AttributeDiscriminant::Script)
.iter()
.find(|attribute| matches!(attribute, Attribute::Script(_)))
{ {
Executor::Command( Executor::Command(
interpreter interpreter