Skip to content
This repository has been archived by the owner on Oct 31, 2023. It is now read-only.

fix/feat: add cfg module to get or create the .wash directory #216

Merged
merged 4 commits into from
Dec 13, 2021
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@
*.par.gz
*.gz
flake.lock
.vscode
27 changes: 27 additions & 0 deletions src/cfg.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use crate::util::Result;
use std::{
fs,
io::{Error, ErrorKind},
path::PathBuf,
};

const WASH_DIR: &str = ".wash";

/// Get the path to the `.wash` configuration directory.
/// Creates the directory if it does not exist.
pub fn cfg_dir() -> Result<PathBuf> {
let home = dirs::home_dir().ok_or_else(|| {
Error::new(
ErrorKind::NotFound,
"No home directory found. Please set $HOME.",
)
})?;

let wash = home.join(WASH_DIR);

if !wash.exists() {
fs::create_dir_all(&wash)?;
}

Ok(wash)
}
21 changes: 7 additions & 14 deletions src/ctx/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{
cfg::cfg_dir,
generate::{
interactive::{prompt_for_choice, user_question},
project_variables::StringEntry,
Expand All @@ -21,9 +22,9 @@ use structopt::{clap::AppSettings, StructOpt};
pub mod context;
use context::{DefaultContext, WashContext};

const CTX_DIR: &str = ".wash/contexts";
const CTX_DIR_NAME: &str = "contexts";
const INDEX_JSON: &str = "index.json";
const HOST_CONFIG_PATH: &str = ".wash/host_config.json";
const HOST_CONFIG_FILE: &str = "host_config.json";
const HOST_CONFIG_NAME: &str = "host_config";

#[derive(Debug, StructOpt, Clone)]
Expand Down Expand Up @@ -348,7 +349,7 @@ fn ensure_host_config_context(context_dir: &Path) -> Result<()> {

/// Load the host configuration file and create a context called `host_config` from it
fn create_host_config_context(context_dir: &Path) -> Result<()> {
let host_config_path = home_dir()?.join(HOST_CONFIG_PATH);
let host_config_path = cfg_dir()?.join(HOST_CONFIG_FILE);
let host_config_ctx = WashContext {
name: HOST_CONFIG_NAME.to_string(),
..load_context(&host_config_path)?
Expand Down Expand Up @@ -406,24 +407,16 @@ pub(crate) fn context_dir(cmd_dir: Option<PathBuf>) -> Result<PathBuf> {
let dir = if let Some(dir) = cmd_dir {
dir
} else {
home_dir()?.join(CTX_DIR)
This conversation was marked as resolved.
Show resolved Hide resolved
cfg_dir()?.join(CTX_DIR_NAME)
};

// Ensure user supplied context exists
if std::fs::metadata(&dir).is_err() {
let _ = std::fs::create_dir(&dir);
let _ = std::fs::create_dir_all(&dir);
}
Ok(dir)
}

fn home_dir() -> Result<PathBuf> {
Ok(dirs::home_dir().ok_or_else(|| {
Error::new(
ErrorKind::NotFound,
"Context directory not found, please set $HOME or $WASH_CONTEXTS for managed contexts",
)
})?)
}

/// Helper function to properly format the path to a context JSON file
fn context_path_from_name(dir: &Path, name: &str) -> PathBuf {
dir.join(format!("{}.json", name))
Expand Down
35 changes: 11 additions & 24 deletions src/keys.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use crate::util::{format_output, Output, OutputKind};
use crate::{
cfg::cfg_dir,
util::{format_output, Output, OutputKind, Result},
};
use nkeys::{KeyPair, KeyPairType};
use serde_json::json;
use std::{
fs,
fs::File,
io::{prelude::*, Error},
io::prelude::*,
path::{Path, PathBuf},
};
use structopt::StructOpt;
Expand Down Expand Up @@ -62,9 +65,7 @@ pub(crate) enum KeysCliCommand {
},
}

pub(crate) fn handle_command(
command: KeysCliCommand,
) -> Result<String, Box<dyn ::std::error::Error>> {
pub(crate) fn handle_command(command: KeysCliCommand) -> Result<String> {
match command {
KeysCliCommand::GenCommand { keytype, output } => Ok(generate(&keytype, &output.kind)),
KeysCliCommand::GetCommand {
Expand Down Expand Up @@ -94,11 +95,7 @@ pub(crate) fn generate(kt: &KeyPairType, output: &OutputKind) -> String {
}

/// Retrieves a keypair by name in a specified directory, or $WASH_KEYS ($HOME/.wash/keys) if directory is not specified
pub(crate) fn get(
keyname: &str,
directory: Option<PathBuf>,
output: &Output,
) -> Result<String, Box<dyn ::std::error::Error>> {
pub(crate) fn get(keyname: &str, directory: Option<PathBuf>, output: &Output) -> Result<String> {
let keyfile = determine_directory(directory)?.join(keyname);
let mut f = File::open(&keyfile)
.map_err(|e| format!("{}.\nPlease ensure {} exists.", e, keyfile.display()))?;
Expand All @@ -119,10 +116,7 @@ pub(crate) fn get(
}

/// Lists all keypairs (file extension .nk) in a specified directory or $WASH_KEYS($HOME/.wash/keys) if directory is not specified
pub(crate) fn list(
directory: Option<PathBuf>,
output: &Output,
) -> Result<String, Box<dyn ::std::error::Error>> {
pub(crate) fn list(directory: Option<PathBuf>, output: &Output) -> Result<String> {
let dir = determine_directory(directory)?;

let mut keys = vec![];
Expand Down Expand Up @@ -152,18 +146,11 @@ pub(crate) fn list(
))
}

fn determine_directory(directory: Option<PathBuf>) -> Result<PathBuf, Error> {
fn determine_directory(directory: Option<PathBuf>) -> Result<PathBuf> {
if let Some(d) = directory {
Ok(d)
} else {
let d = dirs::home_dir()
.ok_or_else(|| {
Error::new(
std::io::ErrorKind::NotFound,
"$HOME not found, please set $HOME or $WASH_KEYS for autogenerated keys",
)
})?
.join(".wash/keys");
let d = cfg_dir()?.join("keys");
Ok(d)
}
}
Expand All @@ -176,7 +163,7 @@ pub(crate) fn extract_keypair(
directory: Option<PathBuf>,
keygen_type: KeyPairType,
disable_keygen: bool,
) -> Result<KeyPair, Box<dyn std::error::Error>> {
) -> Result<KeyPair> {
let seed = if let Some(input_str) = input {
match File::open(input_str.clone()) {
// User provided file path to seed as argument
Expand Down
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use smithy::{GenerateCli, LintCli, ValidateCli};
use structopt::{clap::AppSettings, StructOpt};

mod call;
mod cfg;
mod claims;
mod ctl;
mod ctx;
Expand Down