From d01458dfeb499ef046c75ca681c4bb0cd1166651 Mon Sep 17 00:00:00 2001 From: Xiangda Li <102507799+im-xiangda-li@users.noreply.github.com> Date: Fri, 27 Nov 2026 09:36:44 +1000 Subject: [PATCH] Add scriptable output to contract alias ls --- FULL_HELP_DOCS.md | 12 +++ cmd/crates/soroban-test/tests/it/config.rs | 49 +++++++++ .../src/commands/contract/alias.rs | 2 +- .../src/commands/contract/alias/ls.rs | 102 +++++++++++++----- 4 files changed, 135 insertions(+), 30 deletions(-) diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index bf5d23c502..635413d2f9 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -266,6 +266,18 @@ List all aliases - `--config-dir ` — Location of config directory. By default, it uses `$XDG_CONFIG_HOME/stellar` if set, falling back to `~/.config/stellar` otherwise. Contains configuration files, aliases, and other persistent settings +###### **Options:** + +- `--network ` — Name of the configured network to list +- `--output ` — Format of the output + + Default value: `text` + + Possible values: + - `text`: Human-readable alias listing + - `json`: Compact JSON grouped by network passphrase + - `json-formatted`: Indented JSON grouped by network passphrase + ## `stellar contract bindings` Generate code client bindings for a contract diff --git a/cmd/crates/soroban-test/tests/it/config.rs b/cmd/crates/soroban-test/tests/it/config.rs index 328231216d..f514f19e4c 100644 --- a/cmd/crates/soroban-test/tests/it/config.rs +++ b/cmd/crates/soroban-test/tests/it/config.rs @@ -1121,6 +1121,55 @@ fn alias_ls_always_shows_builtin_native() { }); } +#[test] +fn alias_ls_json_is_sorted_and_can_filter_by_network() { + TestEnv::with_default(|sandbox| { + let contract = "CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE"; + for alias in ["z-token", "a-token"] { + sandbox + .new_assert_cmd("contract") + .args(["alias", "add", alias, "--id", contract]) + .assert() + .success(); + } + let list = |args: &[&str]| { + sandbox + .new_assert_cmd("contract") + .args(["alias", "ls", "--output", "json"]) + .args(args) + .assert() + .success() + .stdout_as_str() + }; + + let all = list(&[]); + assert_eq!(all, list(&[])); + let all: serde_json::Value = serde_json::from_str(&all).unwrap(); + let filtered = list(&["--network", "local"]); + let filtered: serde_json::Value = serde_json::from_str(&filtered).unwrap(); + assert!(all.get(MAINNET).is_some()); + assert_eq!( + filtered, + serde_json::json!({ (LOCAL_NETWORK_PASSPHRASE): all[LOCAL_NETWORK_PASSPHRASE] }) + ); + + let aliases = filtered[LOCAL_NETWORK_PASSPHRASE].as_array().unwrap(); + assert_eq!(aliases.len(), 3); + assert_eq!( + aliases[0], + serde_json::json!({ + "alias": "a-token", + "contract": contract, + "builtin": false, + "disabled": false + }) + ); + assert_eq!(aliases[1]["alias"], "native"); + assert_eq!(aliases[1]["builtin"], true); + assert_eq!(aliases[2]["alias"], "z-token"); + }); +} + #[test] fn alias_ls_marks_preexisting_native_alias_disabled() { TestEnv::with_default(|sandbox| { diff --git a/cmd/soroban-cli/src/commands/contract/alias.rs b/cmd/soroban-cli/src/commands/contract/alias.rs index e7969a0810..db6e4b346c 100644 --- a/cmd/soroban-cli/src/commands/contract/alias.rs +++ b/cmd/soroban-cli/src/commands/contract/alias.rs @@ -42,7 +42,7 @@ impl Cmd { Cmd::Rm(rm) => rm.run(global_args)?, Cmd::Add(add) => add.run(global_args)?, Cmd::Show(show) => show.run(global_args)?, - Cmd::Ls(ls) => ls.run()?, + Cmd::Ls(ls) => ls.run(global_args)?, } Ok(()) } diff --git a/cmd/soroban-cli/src/commands/contract/alias/ls.rs b/cmd/soroban-cli/src/commands/contract/alias/ls.rs index c27733c01e..377608b450 100644 --- a/cmd/soroban-cli/src/commands/contract/alias/ls.rs +++ b/cmd/soroban-cli/src/commands/contract/alias/ls.rs @@ -1,19 +1,50 @@ -use clap::Parser; -use std::collections::HashMap; +use clap::{Parser, ValueEnum}; +use serde::Serialize; +use std::collections::BTreeMap; use std::ffi::OsStr; use std::fmt::Debug; use std::fs; use std::path::Path; use crate::commands::config::network; +use crate::commands::global; use crate::config::locator::{print_deprecation_warning, Location}; use crate::config::{alias, locator}; +use crate::output::{Format, Output}; + +#[derive(Debug, Clone, Copy, ValueEnum)] +enum OutputFormat { + /// Human-readable alias listing + Text, + /// Compact JSON grouped by network passphrase + Json, + /// Indented JSON grouped by network passphrase + JsonFormatted, +} + +impl From for Format { + fn from(format: OutputFormat) -> Self { + match format { + OutputFormat::Text => Self::Readable, + OutputFormat::Json => Self::Json, + OutputFormat::JsonFormatted => Self::JsonFormatted, + } + } +} #[derive(Parser, Debug, Clone)] #[group(skip)] pub struct Cmd { #[command(flatten)] pub config_locator: locator::Args, + + /// Name of the configured network to list + #[arg(long)] + network: Option, + + /// Format of the output + #[arg(long, value_enum, default_value = "text")] + output: OutputFormat, } #[derive(thiserror::Error, Debug)] @@ -26,18 +57,23 @@ pub enum Error { #[error(transparent)] IoError(#[from] std::io::Error), + + #[error(transparent)] + Json(#[from] serde_json::Error), } -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Serialize)] struct AliasEntry { alias: String, contract: String, builtin: bool, + disabled: bool, } impl Cmd { - pub fn run(&self) -> Result<(), Error> { + pub fn run(&self, global_args: &global::Args) -> Result<(), Error> { let config_dirs = self.config_locator.local_and_global()?; + let output = Output::new(self.output.into(), global_args.quiet); for cfg in config_dirs { match cfg { @@ -46,16 +82,16 @@ impl Cmd { print_deprecation_warning(&config_dir); } } - Location::Global(config_dir) => self.read_from_config_dir(&config_dir)?, + Location::Global(config_dir) => self.read_from_config_dir(&config_dir, &output)?, } } Ok(()) } - fn collect_aliases(config_dir: &Path) -> Result>, Error> { + fn collect_aliases(config_dir: &Path) -> Result>, Error> { let contract_ids_dir = config_dir.join("contract-ids"); - let mut map: HashMap> = HashMap::new(); + let mut map: BTreeMap> = BTreeMap::new(); if !contract_ids_dir.is_dir() { return Ok(map); @@ -78,6 +114,7 @@ impl Cmd { alias: alias.clone(), contract: contract_id.clone(), builtin: false, + disabled: alias::is_reserved(&alias), }; map.entry(network_passphrase.clone()) @@ -90,14 +127,18 @@ impl Cmd { Ok(map) } - fn read_from_config_dir(&self, config_dir: &Path) -> Result<(), Error> { + fn read_from_config_dir(&self, config_dir: &Path, output: &Output) -> Result<(), Error> { let mut map = Self::collect_aliases(config_dir)?; - // The built-in `native` alias resolves to the native asset contract for - // a network, so make sure every known network is listed even when it has - // no stored aliases of its own. - for (_, network, _) in self.config_locator.list_networks_long()? { - map.entry(network.network_passphrase).or_default(); + if let Some(name) = &self.network { + let passphrase = self.config_locator.read_network(name)?.network_passphrase; + map.retain(|network, _| *network == passphrase); + map.entry(passphrase).or_default(); + } else { + // Include known networks even when they only have the built-in native alias. + for (_, network, _) in self.config_locator.list_networks_long()? { + map.entry(network.network_passphrase).or_default(); + } } for (network_passphrase, list) in &mut map { @@ -108,28 +149,31 @@ impl Cmd { alias: alias::NATIVE.to_string(), contract: format!("{contract}"), builtin: true, + disabled: false, }); } - println!("ℹ️ Aliases available for network '{network_passphrase}'"); - list.sort_by(|a, b| a.alias.cmp(&b.alias)); + } - for entry in list.iter() { - let note = if entry.builtin { - " (built-in)" - } else if alias::is_reserved(&entry.alias) { - // A user alias whose name is now reserved is shadowed by the - // built-in alias of the same name, so it no longer resolves. - " (disabled)" - } else { - "" - }; - println!("{}: {}{note}", entry.alias, entry.contract); - } + output.readable(|_| { + for (network_passphrase, list) in &map { + println!("ℹ️ Aliases available for network '{network_passphrase}'"); + for entry in list { + let note = if entry.builtin { + " (built-in)" + } else if entry.disabled { + " (disabled)" + } else { + "" + }; + println!("{}: {}{note}", entry.alias, entry.contract); + } - println!(); - } + println!(); + } + }); + output.json_value(&map)?; Ok(()) }