Merge pull request #236 from AleoHQ/feat/login-cleanup

Cleans up login command
This commit is contained in:
Howard Wu 2020-08-15 02:18:51 -07:00 committed by GitHub
commit 77fbc6f66d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 79 additions and 57 deletions

View File

@ -1,19 +1,12 @@
//
// Usege:
// Usage:
//
// leo login <token>
// leo login -u username -p password
// leo login // not yet implemented
//
use crate::{
cli::CLI,
cli_types::*,
errors::{
CLIError::LoginError,
LoginError::{CannotGetToken, ConnectionUnavalaible, WrongLoginOrPassword},
},
};
use crate::{cli::CLI, cli_types::*, errors::LoginError};
use lazy_static::lazy_static;
use std::{
collections::HashMap,
@ -56,10 +49,15 @@ impl CLI for LoginCommand {
type Options = (Option<String>, Option<String>, Option<String>);
type Output = String;
const ABOUT: AboutType = "Login to the package manager (*)";
const ABOUT: AboutType = "Login to the Aleo Package Manager";
const ARGUMENTS: &'static [ArgumentType] = &[
// (name, description, required, index)
("NAME", "Sets token for login to the package manager", false, 1u64),
(
"NAME",
"Sets the authentication token for login to the package manager",
false,
1u64,
),
];
const FLAGS: &'static [FlagType] = &[];
const NAME: NameType = "login";
@ -91,7 +89,7 @@ impl CLI for LoginCommand {
fn output(options: Self::Options) -> Result<Self::Output, crate::errors::CLIError> {
let token = match options {
// Login using existing token
(Some(token), _, _) => token,
(Some(token), _, _) => Some(token),
// Login using username and password
(None, Some(username), Some(password)) => {
@ -107,37 +105,50 @@ impl CLI for LoginCommand {
Ok(json) => json,
Err(_error) => {
log::error!("Wrong login or password");
return Err(LoginError(WrongLoginOrPassword("Wrong login or password".into())));
return Err(LoginError::WrongLoginOrPassword("Wrong login or password".into()).into());
}
},
//Cannot connect to the server
Err(_error) => {
return Err(LoginError(ConnectionUnavalaible(
"Could not connect to the package manager".into(),
)));
return Err(
LoginError::NoConnectionFound("Could not connect to the package manager".into()).into(),
);
}
};
match response.get("token") {
Some(token) => token.clone(),
None => return Err(LoginError(CannotGetToken("There is no token".into()))),
Some(token) => Some(token.clone()),
None => {
return Err(LoginError::CannotGetToken("No token was provided in the response".into()).into());
}
}
}
// Login using JWT
(_, _, _) => {
// TODO JWT
unimplemented!()
None
}
};
// Create Leo credentials directory if it not exists
if !Path::new(LEO_CREDENTIALS_DIR).exists() {
create_dir(LEO_CREDENTIALS_DIR)?;
}
match token {
Some(token) => {
// Create Leo credentials directory if it not exists
if !Path::new(LEO_CREDENTIALS_DIR).exists() {
create_dir(LEO_CREDENTIALS_DIR)?;
}
LoginCommand::write_token(token.as_str())?;
log::info!("Successfully logged in");
Ok(token)
LoginCommand::write_token(token.as_str())?;
log::info!("Login successful.");
Ok(token)
}
_ => {
log::error!("Failed to login. Please run `leo login -h` for help.");
Err(LoginError::NoCredentialsProvided.into())
}
}
}
}

View File

@ -8,11 +8,12 @@ use crate::{
CLIError::PublishError,
},
};
use clap::ArgMatches;
use leo_package::{
outputs::OutputsDirectory,
root::{Manifest, ZipFile},
};
use clap::ArgMatches;
use reqwest::{
blocking::{multipart::Form, Client},
header::{HeaderMap, HeaderValue},
@ -36,16 +37,8 @@ impl CLI for PublishCommand {
type Options = ();
type Output = Option<String>;
const ABOUT: AboutType = "Publish the current package to the package manager (*)";
const ARGUMENTS: &'static [ArgumentType] = &[
// (name, description, required, index)
(
"NAME",
"Sets the resulting package name, defaults to the directory name",
true,
1u64,
),
];
const ABOUT: AboutType = "Publish the current package to the Aleo Package Manager";
const ARGUMENTS: &'static [ArgumentType] = &[];
const FLAGS: &'static [FlagType] = &[];
const NAME: NameType = "publish";
const OPTIONS: &'static [OptionType] = &[];
@ -53,17 +46,12 @@ impl CLI for PublishCommand {
#[cfg_attr(tarpaulin, skip)]
fn parse(_arguments: &ArgMatches) -> Result<Self::Options, CLIError> {
// match arguments.value_of("NAME") {
// Some(name) => Ok((Some(name.to_string()),)),
// None => Ok((None,)),
// }
Ok(())
}
#[cfg_attr(tarpaulin, skip)]
fn output(_options: Self::Options) -> Result<Self::Output, CLIError> {
// Build all program files.
// It's okay if there's just a lib.leo file here
// let _output = BuildCommand::output(options)?;
// Get the package name
@ -77,7 +65,9 @@ impl CLI for PublishCommand {
// Create zip file
let zip_file = ZipFile::new(&package_name);
if zip_file.exists_at(&path) {
log::info!("Existing package zip file found. Skipping compression.")
log::debug!("Existing package zip file found. Clearing it to regenerate.");
// Remove the existing package zip file
ZipFile::new(&package_name).remove(&path)?;
} else {
zip_file.write(&path)?;
}
@ -94,8 +84,8 @@ impl CLI for PublishCommand {
let token = match LoginCommand::read_token() {
Ok(token) => token,
// If not logged then try to login using JWT
Err(_errorr) => {
// If not logged in, then try logging in using JWT.
Err(_error) => {
log::warn!("You should be logged before publish the package");
log::info!("Trying to log in using JWT...");
let options = (None, None, None);
@ -133,7 +123,7 @@ impl CLI for PublishCommand {
}
};
log::info!("Packge published successfully");
log::info!("Package published successfully");
Ok(Some(result.package_id))
}
}

View File

@ -31,7 +31,7 @@ impl CLI for WatchCommand {
let mut watcher = watcher(tx, Duration::from_secs(INTERVAL)).unwrap();
watcher.watch(LEO_SOURCE_DIR, RecursiveMode::Recursive).unwrap();
log::info!("Watching leo's source files");
log::info!("Watching Leo source code");
loop {
match rx.recv() {
// See changes on the write event
@ -39,7 +39,7 @@ impl CLI for WatchCommand {
let options = ();
match BuildCommand::output(options) {
Ok(_output) => {
log::info!("Build successfully");
log::info!("Built successfully");
}
Err(e) => {
// Syntax error
@ -51,9 +51,11 @@ impl CLI for WatchCommand {
Ok(_event) => {}
// Watch error
Err(e) => println!("watch error: {:?}", e),
Err(e) => {
log::error!("watch error: {:?}", e)
// TODO (howardwu): Add graceful termination.
}
}
}
// Ok(())
}
}

View File

@ -5,9 +5,12 @@ pub enum LoginError {
#[error("{:?}", _0)]
CannotGetToken(OsString),
#[error("connectin unavalaible {:?}", _0)]
ConnectionUnavalaible(OsString),
#[error("No connection found {:?}", _0)]
NoConnectionFound(OsString),
#[error("wrong login or password {:?}", _0)]
#[error("No login credentials were provided")]
NoCredentialsProvided,
#[error("Wrong login or password {:?}", _0)]
WrongLoginOrPassword(OsString),
}

View File

@ -13,6 +13,9 @@ pub enum ZipFileError {
#[error("Cannot read from the provided file path - {:?}", _0)]
FileReadError(PathBuf),
#[error("Cannot remove the provided file - {:?}", _0)]
FileRemovalError(PathBuf),
#[error("writing: {}", _0)]
Writing(io::Error),

View File

@ -16,7 +16,7 @@ use crate::{
use serde::Deserialize;
use std::{
fs::File,
fs::{self, File},
io::{Read, Write},
path::{Path, PathBuf},
};
@ -80,7 +80,7 @@ impl ZipFile {
// write file or directory
if path.is_file() {
log::info!("\tadding file {:?} as {:?}", path, name);
log::info!("Adding file {:?} as {:?}", path, name);
zip.start_file_from_path(name, options)?;
let mut f = File::open(path)?;
@ -90,7 +90,7 @@ impl ZipFile {
} else if name.as_os_str().len() != 0 {
// Only if not root Avoids path spec / warning
// and mapname conversion failed error on unzip
log::info!("\tadding dir {:?} as {:?}", path, name);
log::info!("Adding directory {:?} as {:?}", path, name);
zip.add_directory_from_path(name, options)?;
}
}
@ -102,6 +102,18 @@ impl ZipFile {
Ok(())
}
/// Removes the zip file at the given path if it exists. Returns `true` on success,
/// `false` if the file doesn't exist, and `Error` if the file system fails during operation.
pub fn remove(&self, path: &PathBuf) -> Result<bool, ZipFileError> {
let path = self.setup_file_path(path);
if !path.exists() {
return Ok(false);
}
fs::remove_file(&path).map_err(|_| ZipFileError::FileRemovalError(path.clone()))?;
Ok(true)
}
fn setup_file_path(&self, path: &PathBuf) -> PathBuf {
let mut path = path.to_owned();
if path.is_dir() {
@ -115,11 +127,12 @@ impl ZipFile {
}
fn is_excluded(path: &Path) -> bool {
log::debug!("Checking if {:?} is excluded", path);
// excluded directories: `input`, `output`, `imports`
if path.ends_with(INPUTS_DIRECTORY_NAME.trim_end_matches("/"))
| path.ends_with(OUTPUTS_DIRECTORY_NAME.trim_end_matches("/"))
| path.ends_with(IMPORTS_DIRECTORY_NAME.trim_end_matches("/"))
| path.starts_with(INPUTS_DIRECTORY_NAME)
{
return true;
}