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 global config for default network and identity. #1690

Merged
merged 7 commits into from
Nov 6, 2024
Merged
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
50 changes: 50 additions & 0 deletions FULL_HELP_DOCS.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Anything after the `--` double dash (the "slop") is parsed as arguments to the c

* `contract` — Tools for smart contract developers
* `events` — Watch the network for contract events
* `env` — Prints the current environment variables or defaults to the stdout, in a format that can be used as .env file. Environment variables have precedency over defaults
* `keys` — Create and manage identities including keys and addresses
* `network` — Start and configure networks
* `snapshot` — Download a snapshot of a ledger from an archive
Expand Down Expand Up @@ -897,6 +898,19 @@ Watch the network for contract events



## `stellar env`

Prints the current environment variables or defaults to the stdout, in a format that can be used as .env file. Environment variables have precedency over defaults

**Usage:** `stellar env [OPTIONS]`

###### **Options:**

* `--global` — Use global config
* `--config-dir <CONFIG_DIR>` — Location of config directory, default is "."



## `stellar keys`

Create and manage identities including keys and addresses
Expand All @@ -912,6 +926,7 @@ Create and manage identities including keys and addresses
* `ls` — List identities
* `rm` — Remove an identity
* `show` — Given an identity return its private key
* `use` — Set the default identity that will be used on all commands. This allows you to skip `--source-account` or setting a environment variable, while reusing this value in all commands that require it



Expand Down Expand Up @@ -1052,6 +1067,23 @@ Given an identity return its private key



## `stellar keys use`

Set the default identity that will be used on all commands. This allows you to skip `--source-account` or setting a environment variable, while reusing this value in all commands that require it

**Usage:** `stellar keys use [OPTIONS] <NAME>`

###### **Arguments:**

* `<NAME>` — Set the default network name

###### **Options:**

* `--global` — Use global config
* `--config-dir <CONFIG_DIR>` — Location of config directory, default is "."



## `stellar network`

Start and configure networks
Expand All @@ -1065,6 +1097,7 @@ Start and configure networks
* `ls` — List networks
* `start` — ⚠️ Deprecated: use `stellar container start` instead
* `stop` — ⚠️ Deprecated: use `stellar container stop` instead
* `use` — Set the default network that will be used on all commands. This allows you to skip `--network` or setting a environment variable, while reusing this value in all commands that require it
* `container` — Commands to start, stop and get logs for a quickstart container


Expand Down Expand Up @@ -1174,6 +1207,23 @@ Stop a network started with `network start`. For example, if you ran `stellar ne



## `stellar network use`

Set the default network that will be used on all commands. This allows you to skip `--network` or setting a environment variable, while reusing this value in all commands that require it

**Usage:** `stellar network use [OPTIONS] <NAME>`

###### **Arguments:**

* `<NAME>` — Set the default network name

###### **Options:**

* `--global` — Use global config
* `--config-dir <CONFIG_DIR>` — Location of config directory, default is "."



## `stellar network container`

Commands to start, stop and get logs for a quickstart container
Expand Down
53 changes: 53 additions & 0 deletions cmd/crates/soroban-test/tests/it/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,3 +340,56 @@ fn config_dirs_precedence() {
))
.stdout("SAQMV6P3OWM2SKCK3OEWNXSRYWK5RNNUL5CPHQGIJF2WVT4EI2BZ63GG\n");
}

#[test]
fn set_default_identity() {
let sandbox = TestEnv::default();

sandbox
.new_assert_cmd("keys")
.env(
"SOROBAN_SECRET_KEY",
"SC4ZPYELVR7S7EE7KZDZN3ETFTNQHHLTUL34NUAAWZG5OK2RGJ4V2U3Z",
)
.arg("add")
.arg("alice")
.assert()
.success();

sandbox
.new_assert_cmd("keys")
.arg("use")
.arg("alice")
.assert()
.stderr(predicate::str::contains(
"The default source account is set to `alice`",
))
.success();

sandbox
.new_assert_cmd("env")
.assert()
.stdout(predicate::str::contains("STELLAR_ACCOUNT=alice"))
.success();
}

#[test]
fn set_default_network() {
let sandbox = TestEnv::default();

sandbox
.new_assert_cmd("network")
.arg("use")
.arg("testnet")
.assert()
.stderr(predicate::str::contains(
"The default network is set to `testnet`",
))
.success();

sandbox
.new_assert_cmd("env")
.assert()
.stdout(predicate::str::contains("STELLAR_NETWORK=testnet"))
.success();
}
64 changes: 64 additions & 0 deletions cmd/soroban-cli/src/commands/env/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use crate::{
commands::global,
config::{
locator::{self},
Config,
},
print::Print,
};
use clap::Parser;

#[derive(Debug, Parser)]
pub struct Cmd {
#[command(flatten)]
pub config_locator: locator::Args,
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
Locator(#[from] locator::Error),
}

impl Cmd {
pub fn run(&self, global_args: &global::Args) -> Result<(), Error> {
let print = Print::new(global_args.quiet);
let config = Config::new()?;
let mut lines: Vec<(String, String)> = Vec::new();

if let Some(data) = get("STELLAR_NETWORK", config.defaults.network) {
lines.push(data);
}

if let Some(data) = get("STELLAR_ACCOUNT", config.defaults.identity) {
lines.push(data);
}

if lines.is_empty() {
print.warnln("No defaults or environment variables set".to_string());
return Ok(());
}

let max_len = lines.iter().map(|l| l.0.len()).max().unwrap_or(0);

lines.sort();

for (value, source) in lines {
println!("{value:max_len$} # {source}");
}

Ok(())
}
}

fn get(env_var: &str, default_value: Option<String>) -> Option<(String, String)> {
if let Ok(value) = std::env::var(env_var) {
return Some((format!("{env_var}={value}"), "env".to_string()));
}

if let Some(value) = default_value {
return Some((format!("{env_var}={value}"), "default".to_string()));
}

None
}
35 changes: 35 additions & 0 deletions cmd/soroban-cli/src/commands/keys/default.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use clap::command;

use crate::{commands::global, config::locator, print::Print};

#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
Config(#[from] locator::Error),
}

#[derive(Debug, clap::Parser, Clone)]
#[group(skip)]
pub struct Cmd {
/// Set the default network name.
pub name: String,

#[command(flatten)]
pub config_locator: locator::Args,
}

impl Cmd {
pub fn run(&self, global_args: &global::Args) -> Result<(), Error> {
let printer = Print::new(global_args.quiet);
let _ = self.config_locator.read_identity(&self.name)?;

self.config_locator.write_default_identity(&self.name)?;

printer.infoln(format!(
"The default source account is set to `{}`",
self.name,
));

Ok(())
}
}
20 changes: 20 additions & 0 deletions cmd/soroban-cli/src/commands/keys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use clap::Parser;

pub mod add;
pub mod address;
pub mod default;
pub mod fund;
pub mod generate;
pub mod ls;
Expand All @@ -13,18 +14,30 @@ pub mod show;
pub enum Cmd {
/// Add a new identity (keypair, ledger, macOS keychain)
Add(add::Cmd),

/// Given an identity return its address (public key)
Address(address::Cmd),

/// Fund an identity on a test network
Fund(fund::Cmd),

/// Generate a new identity with a seed phrase, currently 12 words
Generate(generate::Cmd),

/// List identities
Ls(ls::Cmd),

/// Remove an identity
Rm(rm::Cmd),

/// Given an identity return its private key
Show(show::Cmd),

/// Set the default identity that will be used on all commands.
/// This allows you to skip `--source-account` or setting a environment
/// variable, while reusing this value in all commands that require it.
#[command(name = "use")]
Default(default::Cmd),
}

#[derive(thiserror::Error, Debug)]
Expand All @@ -34,18 +47,24 @@ pub enum Error {

#[error(transparent)]
Address(#[from] address::Error),

#[error(transparent)]
Fund(#[from] fund::Error),

#[error(transparent)]
Generate(#[from] generate::Error),

#[error(transparent)]
Rm(#[from] rm::Error),

#[error(transparent)]
Ls(#[from] ls::Error),

#[error(transparent)]
Show(#[from] show::Error),

#[error(transparent)]
Default(#[from] default::Error),
}

impl Cmd {
Expand All @@ -58,6 +77,7 @@ impl Cmd {
Cmd::Ls(cmd) => cmd.run()?,
Cmd::Rm(cmd) => cmd.run()?,
Cmd::Show(cmd) => cmd.run()?,
Cmd::Default(cmd) => cmd.run(global_args)?,
};
Ok(())
}
Expand Down
Loading
Loading