Skip to content

Commit

Permalink
fix: restructured the configuration file (#85)
Browse files Browse the repository at this point in the history
Signed-off-by: Berend Sliedrecht <[email protected]>
  • Loading branch information
berendsliedrecht authored Mar 9, 2022
1 parent 3f398c2 commit 7c62338
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 66 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,12 @@ cargo install --path .

## Configuration

In order to easily use the aries-cli, you can setup a configuration that allows you to set some default values. the configuration can be initialised with the following command:
In order to easily use the aries-cli, you can setup a configuration that allows you to set some default values. the configuration can be initialized with the following command:

```sh
aries-cli init
# or
aries-cli config --initialise
aries-cli config --initialize
```

This will create a file at `~/.config/aries-cli/config.ini` for \*NIX systems and `TODO` for Windows. It will set a default endpoint to `https://agent.community.animo.id`.
Expand Down
2 changes: 0 additions & 2 deletions cli/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ pub enum Error {
OsUnknown,
RequiredAttributes,
NoSubcommandSupplied(String),
NoFlagSupplied(String),
}

impl std::error::Error for Error {}
Expand All @@ -30,7 +29,6 @@ impl Display for Error {
Error::ConfigExists => write!(f, "Configuration file already exists."),
Error::OsUnknown => write!(f, "Unknown operating system. Failed to detect OS as windows or unix."),
Error::NoSubcommandSupplied(subcommand) => write!(f, "No subcommand supplied for {}. Check `aries-cli {} --help for the available options.", subcommand, subcommand),
Error::NoFlagSupplied(subcommand) => write!(f, "The subcommand {} requires atleast one flag. Check `aries-cli {} --help for the available options.", subcommand, subcommand),
Error::RequiredAttributes => write!(f, "Creating a schema requires at least one attribute. Please supply them via the --attributes flag."),
Error::InvalidConfigurationStructure => write!(f, "Invalid configuration structure. Please make sure you have a valid configuration file."),
}
Expand Down
49 changes: 22 additions & 27 deletions cli/src/modules/configuration.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,33 @@
use std::fs;
use std::path::Path;

use clap::Args;
use log::info;

use crate::error;
use crate::error::Result;
use crate::utils::config::{get_config_path, Configuration};
use colored::*;
use crate::utils::config::{get_config_path, Configurations};
use clap::{Args, Subcommand};
use log::info;
use std::fs;
use std::path::Path;

#[derive(Args)]
pub struct ConfigurationOptions {
#[clap(short, long, conflicts_with = "view")]
initialize: bool,
#[clap(subcommand)]
pub commands: ConfigurationSubcommands,
}

#[clap(short, long, conflicts_with = "initialize")]
view: bool,
#[derive(Subcommand, Debug)]
pub enum ConfigurationSubcommands {
Initialize,
View,
}

pub async fn parse_configuration_args(options: &ConfigurationOptions) -> Result<()> {
let config_path = get_config_path()?;
if options.initialize {
initialise(&config_path)?;
info!("{} the configuration", "Initialised".cyan());
return Ok(());
}
if options.view {
return view(&config_path);
match options.commands {
ConfigurationSubcommands::Initialize => {
initialize(&config_path)?;
info!("Initialized the configuration!");
return Ok(());
}
ConfigurationSubcommands::View => view(&config_path),
}

Err(error::Error::NoFlagSupplied("configuration".to_string()).into())
}

fn view(path: &Path) -> Result<()> {
Expand All @@ -38,9 +36,8 @@ fn view(path: &Path) -> Result<()> {
Ok(())
}

fn initialise(path: &Path) -> Result<()> {
let config = Configuration::default();

fn initialize(path: &Path) -> Result<()> {
// Check if the path exists and stop so we do not override the existing configuration file
if path.exists() {
return Err(error::Error::ConfigExists.into());
}
Expand All @@ -54,10 +51,8 @@ fn initialise(path: &Path) -> Result<()> {
// Create the configuration file
fs::File::create(&path)?;

let initial_configuration = format!("configurations:\n{}", config);

// Write the default configuration to the file
fs::write(path, initial_configuration)?;
fs::write(path, serde_yaml::to_string(&Configurations::default())?)?;

Ok(())
}
21 changes: 10 additions & 11 deletions cli/src/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,33 +34,33 @@ pub async fn register() -> Result<()> {
Commands::Configuration(options) => parse_configuration_args(options).await,
Commands::Schema(options) => {
let agent =
initialise_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
initialize_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
parse_schema_args(options, agent).await
}
Commands::Features(_) => {
let agent =
initialise_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
initialize_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
parse_features_args(agent).await
}
Commands::Message(options) => {
let agent =
initialise_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
initialize_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
parse_message_args(options, agent).await
}
Commands::CredentialDefinition(options) => {
let agent =
initialise_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
initialize_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
parse_credential_definition_args(options, agent).await
}
Commands::Connections(options) => {
let agent =
initialise_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
initialize_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
// TODO: refactor cli.copy
parse_connection_args(options, agent, cli.copy).await
}
Commands::Credentials(options) => {
let agent =
initialise_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
initialize_agent_from_cli(cli.config, cli.environment, cli.endpoint, cli.api_key)?;
parse_credentials_args(&options.commands, agent).await
}
}?;
Expand All @@ -69,7 +69,7 @@ pub async fn register() -> Result<()> {
Ok(())
}

fn initialise_agent_from_cli(
fn initialize_agent_from_cli(
config: Option<PathBuf>,
environment: String,
endpoint: Option<String>,
Expand Down Expand Up @@ -97,11 +97,10 @@ fn initialise_agent_from_cli(
let configurations = get_config_from_path(cp)?;
let configuration = configurations
.configurations
.into_iter()
.find(|c| c.name == environment)
.get_key_value(&environment)
.ok_or(Error::InvalidEnvironment)?;
let endpoint = endpoint.unwrap_or(configuration.endpoint);
let api_key = api_key.or(configuration.api_key);
let endpoint = endpoint.unwrap_or(configuration.1.endpoint.to_owned());
let api_key = api_key.or(configuration.1.api_key.to_owned());
(endpoint, api_key)
}
None => {
Expand Down
31 changes: 11 additions & 20 deletions cli/src/utils/config.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,18 @@
use std::fmt;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Configuration {
pub name: String,
pub endpoint: String,
pub api_key: Option<String>,
}

impl fmt::Display for Configuration {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
" - name: {}\n endpoint: {}\n{}",
self.name,
self.endpoint,
self.api_key
.as_ref()
.map(|val| format!(" apiKey: {}\n", val))
.unwrap_or_else(|| "".to_string())
)
}
}

impl Default for Configuration {
fn default() -> Self {
Configuration {
name: String::from("default"),
Self {
endpoint: String::from("https://agent.community.animo.id"),
api_key: None,
}
Expand All @@ -38,7 +21,15 @@ impl Default for Configuration {

#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Configurations {
pub configurations: Vec<Configuration>,
pub configurations: BTreeMap<String, Configuration>,
}

impl Default for Configurations {
fn default() -> Self {
let mut configurations = BTreeMap::<String, Configuration>::new();
configurations.insert(String::from("default"), Configuration::default());
Self { configurations }
}
}

pub fn get_config_from_path(config_path: PathBuf) -> Result<Configurations> {
Expand Down
4 changes: 2 additions & 2 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ aries-cli --config ./project/cli/config.ini --environment ENVIRONMENT invite

## Default configuration file

The default can be initialised with one of the two commands: `aries-cli init` and `aries-cli config --initialise`. These two commands create a default configuration file. On any \*NIX system it uses the following location: `~/.config/aries-cli/config.ini` and for Windows systems it uses `TODO` as the location.
The default can be initialized with one of the two commands: `aries-cli init` and `aries-cli config --initialize`. These two commands create a default configuration file. On any \*NIX system it uses the following location: `~/.config/aries-cli/config.ini` and for Windows systems it uses `TODO` as the location.

The configuration is initialised with the following structure:
The configuration is initialized with the following structure:

```ini
[Default]
Expand Down
4 changes: 2 additions & 2 deletions example/config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
configurations:
- name: Default
default:
endpoint: agent.community.animo.id
apiKey: Hello-world
- name: test
test:
endpoint: https://agent.community.animo.id

0 comments on commit 7c62338

Please sign in to comment.