Skip to content

Commit

Permalink
Merge pull request cardano-foundation#2 from cardano-foundation/feat/…
Browse files Browse the repository at this point in the history
…configure-installation-path

Feat/configure installation path
  • Loading branch information
fabianbormann authored Nov 30, 2024
2 parents 4380459 + e9f8f18 commit ab25075
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 41 deletions.
29 changes: 19 additions & 10 deletions cli/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,36 @@ pub struct YaciDevkit {
}

impl Config {
fn default() -> Self {
fn default(path: String) -> Self {
Config {
yaci_devkit: YaciDevkit {
path: format!("{}/yaci-devkit", get_devkit_root()),
services_path: format!("{}/services", get_devkit_root()),
path: Path::new(&path)
.join("yaci-devkit")
.to_string_lossy()
.to_string(),
services_path: Path::new(&path)
.join("services")
.to_string_lossy()
.to_string(),
version: "0.9.3-beta".to_string(),
},
}
}

fn load() -> Self {
let config_path = format!("{}/config.json", get_devkit_root());
fn load(path: Option<String>) -> Self {
let config_path = Path::new(&get_devkit_root())
.join("config.json")
.to_string_lossy()
.to_string();
if Path::new(&config_path).exists() {
let file_content =
fs::read_to_string(config_path).expect("Failed to read config file.");
serde_json::from_str(&file_content).unwrap_or_else(|_| {
eprintln!("Failed to parse config file, using default config.");
Config::default()
Config::default(path.unwrap_or(get_devkit_root()))
})
} else {
let default_config = Config::default();
let default_config = Config::default(path.unwrap_or(get_devkit_root()));
log(&format!("🚀 Looks like it's your first time using the Cardano DevKit. Let's set up a config for you at: {}", config_path));

let parent_dir = Path::new(&config_path).parent().unwrap();
Expand All @@ -64,7 +73,7 @@ impl Config {
}

lazy_static! {
static ref CONFIG: Mutex<Config> = Mutex::new(Config::default());
static ref CONFIG: Mutex<Config> = Mutex::new(Config::default(get_devkit_root()));
}

pub fn get_devkit_root() -> String {
Expand All @@ -75,9 +84,9 @@ pub fn get_devkit_root() -> String {
}
}

pub fn init() {
pub fn init(path: Option<String>) {
let mut config = CONFIG.lock().unwrap();
*config = Config::load();
*config = Config::load(path);
}

pub fn get_config() -> Config {
Expand Down
57 changes: 31 additions & 26 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::path::Path;
use std::process::Command;

use clap::CommandFactory;
use clap::Parser;
use clap::Subcommand;
use logger::error;
use logger::log;
use utils::default_config_path;

mod config;
mod logger;
Expand All @@ -18,10 +18,13 @@ mod utils;
struct Args {
/// Subcommand to execute
#[command(subcommand)]
command: Option<Commands>,
command: Commands,
/// Verbosity level (0 = quite, 1 = standard, 2 = warning, 3 = error, 4 = info, 5 = verbose)
#[arg(long, default_value_t = 1)]
verbose: usize,
/// Configuration file name. It should be in the root directory of the project
#[arg(short, long, default_value = default_config_path().into_os_string())]
config: String,
}

#[derive(Subcommand)]
Expand All @@ -32,26 +35,31 @@ enum Commands {
Start,
/// Stops the local cardano development environment
Stop,
/// Runs a yaci-cli command
Run {
/// yaci-cli arguments to run
args: Vec<String>,
},
}

#[tokio::main]
async fn main() {
let os = std::env::consts::OS;
let arch = std::env::consts::ARCH;

if !(os == "linux" && arch == "x86") && !(os == "macos" && arch == "aarch64") {
if !(os == "linux" && arch.contains("x86")) && !(os == "macos" && arch == "aarch64") {
eprintln!(
"Unfortunately, your operating system ({}, {}) is not currently supported. Please feel free to submit a feature request at: https://github.com/cardano-foundation/cardano-devkit/issues/new/choose",
os, arch
);
std::process::exit(1);
}

let parsed_args = Args::try_parse();
utils::print_header();
logger::init(parsed_args.as_ref().map(|args| args.verbose).unwrap_or(1));
config::init();
let parsed_args = Args::parse();
config::init(Some(parsed_args.config));

utils::print_header();
logger::init(parsed_args.verbose);
utils::check_setup().await.unwrap_or_else(|e| {
logger::error(&format!(
"Failed to check your Yaci DevKit and services setup: {}",
Expand All @@ -60,34 +68,31 @@ async fn main() {
std::process::exit(1);
});

match parsed_args {
Ok(args) => match args.command {
Some(Commands::Init) => logger::log("Init command not implemented yet"),
Some(Commands::Start) => match start::start_devkit() {
Ok(_) => logger::log("Cardano DevKit started successfully"),
Err(e) => {
logger::error(&format!("Failed to start Cardano DevKit: {}", e));
std::process::exit(1);
}
},
Some(Commands::Stop) => logger::log("Stop command not implemented yet"),
None => {
error("Please provide a subcommand to execute.");
log(&format!(
"{}",
Args::command().render_long_help().to_string()
match parsed_args.command {
Commands::Init => {
utils::check_setup().await.unwrap_or_else(|e| {
logger::error(&format!(
"Failed to check your Yaci DevKit and services setup: {}",
e
));
std::process::exit(1);
});
}
Commands::Start => match start::start_devkit() {
Ok(_) => logger::log("Cardano DevKit started successfully"),
Err(e) => {
logger::error(&format!("Failed to start Cardano DevKit: {}", e));
std::process::exit(1);
}
},
Err(_) => {
let cli_args: Vec<String> = std::env::args().skip(1).collect();
Commands::Stop => logger::log("Stop command not implemented yet"),
Commands::Run { args } => {
let configuration = config::get_config();
let yaci_devkit_path = Path::new(&configuration.yaci_devkit.path);

let output = Command::new(yaci_devkit_path.join("yaci-cli"))
.current_dir(yaci_devkit_path)
.args(cli_args)
.args(args)
.output()
.map_err(|yaci_cli_error| {
error(&format!(
Expand Down
7 changes: 7 additions & 0 deletions cli/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,13 @@ pub fn resolve_home_symbol(path: &str) -> String {
path.to_string()
}

pub fn default_config_path() -> PathBuf {
let mut config_path = home_dir().unwrap_or_else(|| PathBuf::from("~"));
config_path.push(".cardano-devkit");
config_path.push("config.json");
config_path
}

pub async fn check_setup() -> Result<(), Box<dyn std::error::Error>> {
let config = config::get_config();
let yaci_devkit_root = resolve_home_symbol(&config.yaci_devkit.path);
Expand Down
6 changes: 1 addition & 5 deletions cli/tests/main_tests.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
use assert_cmd::Command;
use predicates::str::contains;

#[test]
fn test_init_command() {
let mut cmd = Command::cargo_bin("cardano-devkit").unwrap();
cmd.arg("init")
.assert()
.success()
.stdout(contains("Init command not implemented yet"));
cmd.arg("init").assert().success();
}

0 comments on commit ab25075

Please sign in to comment.