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

fix: quite some patches #138

Merged
merged 9 commits into from
Apr 4, 2022
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,14 @@ pub struct CredentialOfferResponse {
pub updated_at: String,
}

pub struct CredentialsOfferOptions {
pub struct CredentialOfferOptions {
pub connection_id: String,
pub cred_def_id: String,
pub keys: Vec<String>,
pub values: Vec<String>,
}

pub struct SendProposalOptions {}

#[async_trait]
pub trait CredentialsModule {
async fn send_offer(&self, options: CredentialsOfferOptions)
-> Result<CredentialOfferResponse>;
async fn send_proposal(&self, options: SendProposalOptions) -> Result<Value>;
pub trait CredentialModule {
async fn send_offer(&self, options: CredentialOfferOptions) -> Result<CredentialOfferResponse>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub struct Protocol {
}

#[async_trait]
pub trait FeaturesModule {
pub trait FeatureModule {
/// Requests all the features from the cloudagent
async fn discover_features(&self) -> Result<DiscoverFeaturesResponse>;
}
6 changes: 3 additions & 3 deletions agent/src/modules/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub mod connections;
pub mod connection;
pub mod credential;
pub mod credential_definition;
pub mod credentials;
pub mod features;
pub mod feature;
pub mod message;
pub mod schema;
18 changes: 9 additions & 9 deletions cli/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use crate::help_strings::HelpStrings;

use crate::modules::workflow::WorkflowOptions;
use crate::modules::{
configuration::ConfigurationOptions, connections::ConnectionOptions,
credential_definition::CredentialDefinitionOptions, credentials::CredentialOptions,
features::FeaturesOptions, message::MessageOptions, schema::SchemaOptions,
configuration::ConfigurationOptions, connection::ConnectionOptions,
credential::CredentialOptions, credential_definition::CredentialDefinitionOptions,
feature::FeaturesOptions, message::MessageOptions, schema::SchemaOptions,
};

#[derive(Parser)]
Expand All @@ -33,7 +33,7 @@ pub struct Cli {
#[clap(long, short = 'o', help = HelpStrings::Config)]
pub config: Option<PathBuf>,

#[clap(long, short = 'e', default_value = "default", help = HelpStrings::Environment)]
#[clap(long, short, default_value = "default", help = HelpStrings::Environment)]
pub environment: String,

#[clap(long, short='v', help = HelpStrings::Verbose, parse(from_occurrences), conflicts_with = "quiet")]
Expand All @@ -45,12 +45,12 @@ pub struct Cli {

#[derive(Subcommand)]
pub enum Commands {
Connections(ConnectionOptions),
Features(FeaturesOptions),
Schemas(SchemaOptions),
CredentialDefinitions(CredentialDefinitionOptions),
Connection(ConnectionOptions),
Feature(FeaturesOptions),
Schema(SchemaOptions),
CredentialDefinition(CredentialDefinitionOptions),
Message(MessageOptions),
Credentials(CredentialOptions),
Credential(CredentialOptions),
Configuration(ConfigurationOptions),
Automate(WorkflowOptions),
}
4 changes: 2 additions & 2 deletions cli/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ pub enum Error {
InvalidEnvironment,
InactiveConnection,
NoAgentURLSupplied,
NoEnvironmentSupplied,
InvalidAgentInvitation,
UnqualAmountKeyValue,
HomeNotFound,
ConfigExists(String),
OsUnknown,
RequiredAttributes,
_NoSubcommandSupplied(String),
Expand All @@ -28,9 +28,9 @@ impl Display for Error {
Error::InvalidConfigurationPath => write!(f, "Invalid configuration path."),
Error::InvalidEnvironment => write!(f, "Invalid environment."),
Error::NoAgentURLSupplied => write!(f, "No agent URL supplied. Supply an agent URL either via `--agent-url` or see `aries-cli configuration --help` to learn about setting up an environment."),
Error::NoEnvironmentSupplied => write!(f, "No Environment supplied. Supply the environment either via `--environment` or see `aries-cli configuration --help` to learn about setting up an environment."),
Error::UnqualAmountKeyValue => write!(f, "Supplies keys and values are not equal in size."),
Error::HomeNotFound => write!(f, "Unable to find home directory."),
Error::ConfigExists(path) => write!(f, "Configuration file already exists at {}", path),
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::RequiredAttributes => write!(f, "Creating a schema requires at least one attribute. Please supply them via the --attributes flag."),
Expand Down
26 changes: 19 additions & 7 deletions cli/src/help_strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub enum HelpStrings {

// Configuration
Configuration,
ConfigurationInitialize,
ConfigurationDefault,
ConfigurationView,
ConfigurationInitializeToken,

Expand All @@ -28,12 +28,17 @@ pub enum HelpStrings {
ConnectionsInviteMultiUse,
ConnectionsInviteQr,
ConnectionsInviteToolbox,
ConnectionsList,
ConnectionsListId,
ConnectionsReceive,
ConnectionsReceiveUrl,

// Credential Definitions
CredentialDefinition,
CredentialDefinitionId,
CredentialDefinitionCreate,
CredentialDefinitionCreateSchemaId,
CredentialDefinitionList,

// Credentials
Credentials,
Expand All @@ -56,6 +61,7 @@ pub enum HelpStrings {
// Schema
Schema,
SchemaId,
SchemaList,
SchemaCreate,
SchemaCreateName,
SchemaCreateVersion,
Expand All @@ -81,12 +87,12 @@ impl HelpStrings {
HelpStrings::Copy => "Copy output to your clipboard",
HelpStrings::Quiet => "Suppresses most output",
HelpStrings::Verbose => "Print debug logs",
HelpStrings::Config => "Path to your configuration file",
HelpStrings::Config => "Supply a path to your configuration file to use that instead of the default",
HelpStrings::Environment => "Specify your current environment",

HelpStrings::Configuration => "Initialize or view current configuration",
HelpStrings::ConfigurationInitialize => {
"Initialize a new configuration file with a default environment"
HelpStrings::Configuration => "Add agents to your configuration or view your current configuration. To quickly get started run the following command: aries-cli configuration add --default",
HelpStrings::ConfigurationDefault => {
"Add the default agent to the configuration (can be combined with --token)"
}
HelpStrings::ConfigurationView => "Print your current configuration file",
HelpStrings::ConfigurationInitializeToken => "Authentication token for a multi tenancy agent",
Expand All @@ -105,11 +111,16 @@ impl HelpStrings {
"Print a QR code, convenient for use with mobile apps"
}
HelpStrings::ConnectionsInviteToolbox => HELP_STRING_CONNECTIONS_INVITE_TOOLBOX,
HelpStrings::ConnectionsList => "List all your current connections",
HelpStrings::ConnectionsListId => "Get a connection by id",
HelpStrings::ConnectionsReceive => "Receive an invitation via url",
HelpStrings::ConnectionsReceiveUrl => "The url that contains the invitation",

HelpStrings::CredentialDefinition => "Retrieve or create credential definitions",
HelpStrings::CredentialDefinitionId => "ID of a credential definition to retrieve",
HelpStrings::CredentialDefinitionCreate => "Create a new credential definition",
HelpStrings::CredentialDefinitionCreateSchemaId => "Schema ID to use in the definition",
HelpStrings::CredentialDefinitionList => "List all your credential definitions",

HelpStrings::Credentials => "Offer or propose credentials",
HelpStrings::CredentialsOffer => "Offer a new credential to an existing connection",
Expand All @@ -126,7 +137,7 @@ impl HelpStrings {

HelpStrings::Features => "List all available features",

HelpStrings::Message => "Send a secure message to an exist connection",
HelpStrings::Message => "Send a secure message to an existing connection",
HelpStrings::MessageId => "Connection ID to send the message to",
HelpStrings::MessageMessage => "Contents of the message",

Expand All @@ -135,7 +146,8 @@ impl HelpStrings {
HelpStrings::SchemaCreate => "Create a new schema",
HelpStrings::SchemaCreateName => "Name of the schema",
HelpStrings::SchemaCreateVersion => "Version of of the schema, useful to be able to specify multiple versions of the same schema",
HelpStrings::SchemaCreateAttributes => "Keys that describe the structure of the schema - for example \"age\"",
HelpStrings::SchemaCreateAttributes => "Keys that describe the structure of the schema - for example \"age\". Given in the following format: -a foo -a bar -a baz",
HelpStrings::SchemaList => "List all your current schemas",

HelpStrings::Workflow => "Automated actions that combine multiple functions",
HelpStrings::WorkflowCredentialOffer => "Simple credential offer workflow to offer a premade credential to any agent",
Expand Down
115 changes: 62 additions & 53 deletions cli/src/modules/configuration.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use crate::error;
use crate::error::Result;
use crate::error::{self, Error};
use crate::help_strings::HelpStrings;
use crate::utils::config::{get_config_path, Configurations};
use crate::utils::config::{get_config_path, Configuration, Environment};
use clap::{Args, Subcommand};
use colored::*;
use log::{debug, info, trace};
use log::{debug, info};
use std::fs;
use std::path::Path;

#[derive(Args)]
pub struct ConfigurationOptions {
Expand All @@ -17,69 +16,79 @@ pub struct ConfigurationOptions {
#[derive(Subcommand, Debug)]
#[clap(about = HelpStrings::Configuration)]
pub enum ConfigurationSubcommands {
#[clap(about = HelpStrings::ConfigurationInitialize)]
Initialize {
#[clap(short, long, help= HelpStrings::ConfigurationInitializeToken)]
token: Option<String>,
},
#[clap(about = HelpStrings::ConfigurationView)]
View,
Add {
#[clap(short, long, help = HelpStrings::ConfigurationDefault)]
default: bool,

#[clap(long, short, help = HelpStrings::Environment, conflicts_with = "default")]
environment: Option<String>,

#[clap(long, short='u', help = HelpStrings::AgentURL, conflicts_with = "default")]
agent_url: Option<String>,

#[clap(long, short, help = HelpStrings::ApiKey, conflicts_with = "default")]
api_key: Option<String>,

#[clap(long, short='t', help = HelpStrings::ConfigurationInitializeToken)]
token: Option<String>,
},
}

pub async fn parse_configuration_args(options: &ConfigurationOptions) -> Result<()> {
let config_path = get_config_path()?;
match &options.commands {
ConfigurationSubcommands::Initialize { token } => {
initialize(&config_path, token.to_owned())?;
println!(
"{} configuration file at {}.",
"Initialised".cyan(),
config_path.display()
);
Ok(())
}
ConfigurationSubcommands::View => {
debug!(
"Loaded configuration from {}",
String::from(config_path.to_str().unwrap()).bold()
);

view(&config_path).map_err(|err| {
let output = fs::read_to_string(&config_path).map_err(|err| {
debug!("Failed to read config file: {}", err);
error::Error::CannotReadConfigurationFile.into()
})
Box::<dyn std::error::Error>::from(error::Error::CannotReadConfigurationFile)
})?;
println!("Configuration path: {:?}", config_path);
println!("{}", output);
Ok(())
}
}
}

fn view(path: &Path) -> Result<()> {
let output = fs::read_to_string(path)?;
info!("{}", output);
Ok(())
}
ConfigurationSubcommands::Add {
default,
environment,
agent_url,
api_key,
token,
} => {
if *default {
let (environment, configuration) = Configuration::init(token.to_owned());
Configuration::add(environment, configuration)?;
println!(
"{} the default agent at {}.",
"Added".cyan(),
config_path.display()
);
return Ok(());
}
debug!("{} a new entry to the configuration file", "Adding".cyan());
let path = get_config_path()?;
let endpoint = agent_url.to_owned().ok_or(Error::NoAgentURLSupplied)?;
let environment = environment.to_owned().ok_or(Error::NoEnvironmentSupplied)?;
let env = Environment {
endpoint,
api_key: api_key.to_owned(),
auth_token: token.to_owned(),
};
info!(
"{} {}, {:#?} to {:#?}",
"Writing".cyan(),
environment,
env,
path
);
Configuration::add(environment.to_owned(), env)?;

fn initialize(path: &Path, token: Option<String>) -> 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(path.to_str().unwrap().into()).into());
debug!("{} a new entry to the configuration", "Written".green());
Ok(())
}
}

// Get the directories
let prefix = path.parent().unwrap();

// create all the required directories
fs::create_dir_all(prefix)?;

// Create the configuration file
fs::File::create(&path)?;

// Content
let content = serde_yaml::to_string(&Configurations::init(token))?;

trace!("{} {:#?} to {:#?}", "Writing".cyan(), content, path);

// Write the default configuration to the file
fs::write(path, content)?;

Ok(())
}
Loading