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

cli: diff: add fileset-alias option #4962

Open
wants to merge 4 commits into
base: main
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
51 changes: 47 additions & 4 deletions cli/src/cli_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,11 @@ use jj_lib::config::ConfigGetResultExt as _;
use jj_lib::config::ConfigNamePathBuf;
use jj_lib::config::StackedConfig;
use jj_lib::conflicts::ConflictMarkerStyle;
use jj_lib::dsl_util::AliasDeclarationParser;
use jj_lib::dsl_util::AliasesMap;
use jj_lib::file_util;
use jj_lib::fileset;
use jj_lib::fileset::FilesetAliasesMap;
use jj_lib::fileset::FilesetDiagnostics;
use jj_lib::fileset::FilesetExpression;
use jj_lib::git;
Expand Down Expand Up @@ -704,6 +707,7 @@ pub struct WorkspaceCommandEnvironment {
command: CommandHelper,
revset_aliases_map: RevsetAliasesMap,
template_aliases_map: TemplateAliasesMap,
fileset_aliases_map: FilesetAliasesMap,
path_converter: RepoPathUiConverter,
workspace_id: WorkspaceId,
immutable_heads_expression: Rc<UserRevsetExpression>,
Expand All @@ -716,6 +720,7 @@ impl WorkspaceCommandEnvironment {
fn new(ui: &Ui, command: &CommandHelper, workspace: &Workspace) -> Result<Self, CommandError> {
let revset_aliases_map = revset_util::load_revset_aliases(ui, command.settings().config())?;
let template_aliases_map = command.load_template_aliases(ui)?;
let fileset_aliases_map = load_fileset_aliases(ui, command.settings().config())?;
let path_converter = RepoPathUiConverter::Fs {
cwd: command.cwd().to_owned(),
base: workspace.workspace_root().to_owned(),
Expand All @@ -724,6 +729,7 @@ impl WorkspaceCommandEnvironment {
command: command.clone(),
revset_aliases_map,
template_aliases_map,
fileset_aliases_map,
path_converter,
workspace_id: workspace.workspace_id().to_owned(),
immutable_heads_expression: RevsetExpression::root(),
Expand Down Expand Up @@ -765,6 +771,7 @@ impl WorkspaceCommandEnvironment {
now.into(),
self.command.revset_extensions(),
Some(workspace_context),
&self.fileset_aliases_map,
)
}

Expand Down Expand Up @@ -1263,7 +1270,14 @@ to the current parents may contain changes from multiple commits.
let mut diagnostics = FilesetDiagnostics::new();
let expressions: Vec<_> = file_args
.iter()
.map(|arg| fileset::parse_maybe_bare(&mut diagnostics, arg, self.path_converter()))
.map(|arg| {
fileset::parse_maybe_bare(
&mut diagnostics,
arg,
self.path_converter(),
self.fileset_aliases_map(),
)
})
.try_collect()?;
print_parse_diagnostics(ui, "In fileset expression", &diagnostics)?;
Ok(FilesetExpression::union_all(expressions))
Expand All @@ -1279,6 +1293,7 @@ to the current parents may contain changes from multiple commits.
cwd: "".into(),
base: "".into(),
},
self.fileset_aliases_map(),
)?;
print_parse_diagnostics(ui, "In `snapshot.auto-track`", &diagnostics)?;
Ok(expression.to_matcher())
Expand Down Expand Up @@ -1554,6 +1569,10 @@ to the current parents may contain changes from multiple commits.
&self.env.template_aliases_map
}

pub fn fileset_aliases_map(&self) -> &FilesetAliasesMap {
&self.env.fileset_aliases_map
}

/// Parses template of the given language into evaluation tree.
///
/// `wrap_self` specifies the type of the top-level property, which should
Expand Down Expand Up @@ -2684,11 +2703,31 @@ fn load_template_aliases(
stacked_config: &StackedConfig,
) -> Result<TemplateAliasesMap, CommandError> {
let table_name = ConfigNamePathBuf::from_iter(["template-aliases"]);
let mut aliases_map = TemplateAliasesMap::new();
load_aliases(ui, stacked_config, &table_name)
}

fn load_fileset_aliases(
ui: &Ui,
stacked_config: &StackedConfig,
) -> Result<FilesetAliasesMap, CommandError> {
let table_name = ConfigNamePathBuf::from_iter(["fileset-aliases"]);
load_aliases(ui, stacked_config, &table_name)
}

fn load_aliases<P>(
ui: &Ui,
stacked_config: &StackedConfig,
table_name: &ConfigNamePathBuf,
) -> Result<AliasesMap<P, String>, CommandError>
where
P: Default + AliasDeclarationParser,
P::Error: ToString,
{
let mut aliases_map = AliasesMap::new();
// Load from all config layers in order. 'f(x)' in default layer should be
// overridden by 'f(a)' in user.
for layer in stacked_config.layers() {
let table = match layer.look_up_table(&table_name) {
let table = match layer.look_up_table(table_name) {
Ok(Some(table)) => table,
Ok(None) => continue,
Err(item) => {
Expand All @@ -2708,7 +2747,11 @@ fn load_template_aliases(
.clone()
.into_string()
.map_err(|e| e.to_string())
.and_then(|v| aliases_map.insert(decl, v).map_err(|e| e.to_string()));
.and_then(|v| {
aliases_map
.insert(decl, v)
.map_err(|e: P::Error| e.to_string())
});
if let Err(s) = r {
writeln!(
ui.warning_default(),
Expand Down
3 changes: 3 additions & 0 deletions cli/src/command_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,9 @@ fn fileset_parse_error_hint(err: &FilesetParseError) -> Option<String> {
FilesetParseErrorKind::InvalidArguments { .. } | FilesetParseErrorKind::Expression(_) => {
find_source_parse_error_hint(&err)
}
FilesetParseErrorKind::InAliasExpansion(_)
| FilesetParseErrorKind::InParameterExpansion(_)
| FilesetParseErrorKind::RecursiveAlias(_) => None,
}
}

Expand Down
4 changes: 3 additions & 1 deletion cli/src/commands/debug/fileset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,11 @@ pub fn cmd_debug_fileset(
) -> Result<(), CommandError> {
let workspace_command = command.workspace_helper(ui)?;
let path_converter = workspace_command.path_converter();
let aliases_map = workspace_command.fileset_aliases_map();

let mut diagnostics = FilesetDiagnostics::new();
let expression = fileset::parse_maybe_bare(&mut diagnostics, &args.path, path_converter)?;
let expression =
fileset::parse_maybe_bare(&mut diagnostics, &args.path, path_converter, aliases_map)?;
print_parse_diagnostics(ui, "In fileset expression", &diagnostics)?;
writeln!(ui.stdout(), "-- Parsed:")?;
writeln!(ui.stdout(), "{expression:#?}")?;
Expand Down
11 changes: 9 additions & 2 deletions cli/src/commands/fix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ use tracing::instrument;

use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::cli_util::WorkspaceCommandHelper;
use crate::command_error::config_error;
use crate::command_error::print_parse_diagnostics;
use crate::command_error::CommandError;
Expand Down Expand Up @@ -145,7 +146,7 @@ pub(crate) fn cmd_fix(
args: &FixArgs,
) -> Result<(), CommandError> {
let mut workspace_command = command.workspace_helper(ui)?;
let tools_config = get_tools_config(ui, command.settings())?;
let tools_config = get_tools_config(ui, &workspace_command, command.settings())?;
let root_commits: Vec<CommitId> = if args.source.is_empty() {
let revs = command.settings().get_string("revsets.fix")?;
workspace_command.parse_revset(ui, &RevisionArg::from(revs))?
Expand Down Expand Up @@ -446,7 +447,11 @@ struct RawToolConfig {
/// Fails if any of the commands or patterns are obviously unusable, but does
/// not check for issues that might still occur later like missing executables.
/// This is a place where we could fail earlier in some cases, though.
fn get_tools_config(ui: &mut Ui, settings: &UserSettings) -> Result<ToolsConfig, CommandError> {
fn get_tools_config(
ui: &mut Ui,
workspace_command: &WorkspaceCommandHelper,
settings: &UserSettings,
) -> Result<ToolsConfig, CommandError> {
let mut tools_config = ToolsConfig { tools: Vec::new() };
// TODO: Remove this block of code and associated documentation after at least
// one release where the feature is marked deprecated.
Expand Down Expand Up @@ -475,6 +480,7 @@ fn get_tools_config(ui: &mut Ui, settings: &UserSettings) -> Result<ToolsConfig,
}
if let Ok(tools_table) = settings.get_table("fix.tools") {
// Convert the map into a sorted vector early so errors are deterministic.
let fileset_aliases_map = workspace_command.fileset_aliases_map();
let mut tools: Vec<ToolConfig> = tools_table
.into_iter()
.sorted_by(|a, b| a.0.cmp(&b.0))
Expand All @@ -492,6 +498,7 @@ fn get_tools_config(ui: &mut Ui, settings: &UserSettings) -> Result<ToolsConfig,
cwd: "".into(),
base: "".into(),
},
fileset_aliases_map,
)
})
.try_collect()?,
Expand Down
13 changes: 10 additions & 3 deletions cli/src/commit_templater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use jj_lib::copies::CopiesTreeDiffEntry;
use jj_lib::copies::CopyRecords;
use jj_lib::extensions_map::ExtensionsMap;
use jj_lib::fileset;
use jj_lib::fileset::FilesetAliasesMap;
use jj_lib::fileset::FilesetDiagnostics;
use jj_lib::fileset::FilesetExpression;
use jj_lib::id_prefix::IdPrefixContext;
Expand Down Expand Up @@ -806,7 +807,12 @@ fn builtin_commit_methods<'repo>() -> CommitTemplateBuildMethodFnMap<'repo, Comm
|language, diagnostics, _build_ctx, self_property, function| {
let ([], [files_node]) = function.expect_arguments()?;
let files = if let Some(node) = files_node {
expect_fileset_literal(diagnostics, node, language.path_converter)?
expect_fileset_literal(
diagnostics,
node,
language.path_converter,
language.revset_parse_context.fileset_aliases_map(),
)?
} else {
// TODO: defaults to CLI path arguments?
// https://github.com/martinvonz/jj/issues/2933#issuecomment-1925870731
Expand Down Expand Up @@ -851,11 +857,12 @@ fn expect_fileset_literal(
diagnostics: &mut TemplateDiagnostics,
node: &ExpressionNode,
path_converter: &RepoPathUiConverter,
aliases_map: &FilesetAliasesMap,
) -> Result<FilesetExpression, TemplateParseError> {
template_parser::expect_string_literal_with(node, |text, span| {
let mut inner_diagnostics = FilesetDiagnostics::new();
let expression =
fileset::parse(&mut inner_diagnostics, text, path_converter).map_err(|err| {
let expression = fileset::parse(&mut inner_diagnostics, text, path_converter, aliases_map)
.map_err(|err| {
TemplateParseError::expression("In fileset expression", span).with_source(err)
})?;
diagnostics.extend_with(inner_diagnostics, |diag| {
Expand Down
14 changes: 14 additions & 0 deletions docs/filesets.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ You can also specify patterns by using functions.
* `all()`: Matches everything.
* `none()`: Matches nothing.

## Aliases

New symbols can be defined in the config file, using predefined symbols/
functions and other aliases.

Unlike revsets, aliases currently cannot be functions.

For example:
```toml
[fileset-aliases]
LIB = "root-glob:lib/**"
NO_LOCK = "~root-glob:**/*.lock"
```

## Examples

Show diff excluding `Cargo.lock`.
Expand Down
2 changes: 2 additions & 0 deletions lib/src/fileset.pest
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,5 @@ program_or_bare_string = _{
| bare_string_pattern ~ EOI
| bare_string ~ EOI )
}

alias_declaration = _{ SOI ~ strict_identifier ~ EOI }
57 changes: 51 additions & 6 deletions lib/src/fileset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ use once_cell::sync::Lazy;
use thiserror::Error;

use crate::dsl_util::collect_similar;
use crate::dsl_util::AliasExpandError;
use crate::fileset_parser;
use crate::fileset_parser::BinaryOp;
use crate::fileset_parser::ExpressionKind;
use crate::fileset_parser::ExpressionNode;
pub use crate::fileset_parser::FilesetAliasesMap;
pub use crate::fileset_parser::FilesetDiagnostics;
pub use crate::fileset_parser::FilesetParseError;
pub use crate::fileset_parser::FilesetParseErrorKind;
Expand Down Expand Up @@ -465,6 +467,15 @@ fn resolve_expression(
ExpressionKind::FunctionCall(function) => {
resolve_function(diagnostics, path_converter, function)
}
ExpressionKind::AliasExpanded(id, subst) => {
let mut inner_diagnostics = FilesetDiagnostics::new();
let expression = resolve_expression(&mut inner_diagnostics, path_converter, subst)
.map_err(|e| e.within_alias_expansion(*id, node.span))?;
diagnostics.extend_with(inner_diagnostics, |diag| {
diag.within_alias_expansion(*id, node.span)
});
Ok(expression)
}
}
}

Expand All @@ -473,8 +484,9 @@ pub fn parse(
diagnostics: &mut FilesetDiagnostics,
text: &str,
path_converter: &RepoPathUiConverter,
aliases_map: &FilesetAliasesMap,
) -> FilesetParseResult<FilesetExpression> {
let node = fileset_parser::parse_program(text)?;
let node = fileset_parser::parse(text, aliases_map)?;
// TODO: add basic tree substitution pass to eliminate redundant expressions
resolve_expression(diagnostics, path_converter, &node)
}
Expand All @@ -487,8 +499,9 @@ pub fn parse_maybe_bare(
diagnostics: &mut FilesetDiagnostics,
text: &str,
path_converter: &RepoPathUiConverter,
aliases_map: &FilesetAliasesMap,
) -> FilesetParseResult<FilesetExpression> {
let node = fileset_parser::parse_program_or_bare_string(text)?;
let node = fileset_parser::parse_maybe_bare(text, aliases_map)?;
// TODO: add basic tree substitution pass to eliminate redundant expressions
resolve_expression(diagnostics, path_converter, &node)
}
Expand Down Expand Up @@ -529,7 +542,15 @@ mod tests {
cwd: PathBuf::from("/ws/cur"),
base: PathBuf::from("/ws"),
};
let parse = |text| parse_maybe_bare(&mut FilesetDiagnostics::new(), text, &path_converter);
let aliases_map = Default::default();
let parse = |text| {
parse_maybe_bare(
&mut FilesetDiagnostics::new(),
text,
&path_converter,
&aliases_map,
)
};

// cwd-relative patterns
insta::assert_debug_snapshot!(
Expand Down Expand Up @@ -574,7 +595,15 @@ mod tests {
cwd: PathBuf::from("/ws/cur*"),
base: PathBuf::from("/ws"),
};
let parse = |text| parse_maybe_bare(&mut FilesetDiagnostics::new(), text, &path_converter);
let aliases_map = Default::default();
let parse = |text| {
parse_maybe_bare(
&mut FilesetDiagnostics::new(),
text,
&path_converter,
&aliases_map,
)
};

// cwd-relative, without meta characters
insta::assert_debug_snapshot!(
Expand Down Expand Up @@ -747,7 +776,15 @@ mod tests {
cwd: PathBuf::from("/ws/cur"),
base: PathBuf::from("/ws"),
};
let parse = |text| parse_maybe_bare(&mut FilesetDiagnostics::new(), text, &path_converter);
let aliases_map = Default::default();
let parse = |text| {
parse_maybe_bare(
&mut FilesetDiagnostics::new(),
text,
&path_converter,
&aliases_map,
)
};

insta::assert_debug_snapshot!(parse("all()").unwrap(), @"All");
insta::assert_debug_snapshot!(parse("none()").unwrap(), @"None");
Expand Down Expand Up @@ -775,7 +812,15 @@ mod tests {
cwd: PathBuf::from("/ws/cur"),
base: PathBuf::from("/ws"),
};
let parse = |text| parse_maybe_bare(&mut FilesetDiagnostics::new(), text, &path_converter);
let aliases_map = Default::default();
let parse = |text| {
parse_maybe_bare(
&mut FilesetDiagnostics::new(),
text,
&path_converter,
&aliases_map,
)
};

insta::assert_debug_snapshot!(parse("~x").unwrap(), @r###"
Difference(
Expand Down
Loading
Loading