Skip to content

Commit

Permalink
revset: extract helper that formats remote symbol
Browse files Browse the repository at this point in the history
I'll add a few more callers.
  • Loading branch information
yuja committed Feb 3, 2025
1 parent ce123a6 commit 5877eea
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
7 changes: 3 additions & 4 deletions cli/src/commands/git/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,14 +124,13 @@ fn write_repository_level_trunk_alias(
branch: &str,
) -> Result<(), CommandError> {
let mut file = ConfigFile::load_or_empty(ConfigSource::Repo, repo_path.join("config.toml"))?;
let branch = revset::format_symbol(branch);
let remote = revset::format_symbol(remote);
file.set_value(["revset-aliases", "trunk()"], format!("{branch}@{remote}"))
let expr = revset::format_remote_symbol(branch, remote);
file.set_value(["revset-aliases", "trunk()"], &expr)
.expect("initial repo config shouldn't have invalid values");
file.save()?;
writeln!(
ui.status(),
"Setting the revset alias `trunk()` to `{branch}@{remote}`",
"Setting the revset alias `trunk()` to `{expr}`",
)?;
Ok(())
}
29 changes: 27 additions & 2 deletions lib/src/revset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2686,15 +2686,31 @@ pub struct RevsetWorkspaceContext<'a> {
pub workspace_id: &'a WorkspaceId,
}

/// Formats a string as symbol by quoting and escaping it if necessary
/// Formats a string as symbol by quoting and escaping it if necessary.
///
/// Note that symbols may be substituted to user aliases. Use
/// [`format_string()`] to ensure that the provided string is resolved as a
/// tag/bookmark name, commit/change ID prefix, etc.
pub fn format_symbol(literal: &str) -> String {
if revset_parser::is_identifier(literal) {
literal.to_string()
} else {
format!(r#""{}""#, dsl_util::escape_string(literal))
format_string(literal)
}
}

/// Formats a string by quoting and escaping it.
pub fn format_string(literal: &str) -> String {
format!(r#""{}""#, dsl_util::escape_string(literal))
}

/// Formats a `name@remote` symbol, applies quoting and escaping if necessary.
pub fn format_remote_symbol(name: &str, remote: &str) -> String {
let name = format_symbol(name);
let remote = format_symbol(remote);
format!("{name}@{remote}")
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;
Expand Down Expand Up @@ -4363,4 +4379,13 @@ mod tests {
assert_eq!(format_symbol("foo\\\"bar"), r#""foo\\\"bar""#);
assert_eq!(format_symbol("foo \x01 bar"), r#""foo \x01 bar""#);
}

#[test]
fn test_escape_remote_symbol() {
assert_eq!(format_remote_symbol("foo", "bar"), "foo@bar");
assert_eq!(
format_remote_symbol(" foo ", "bar:baz"),
r#"" foo "@"bar:baz""#
);
}
}

0 comments on commit 5877eea

Please sign in to comment.