CLI state between calls (#175)

* add serialization

* add config

* change state

* final touches
This commit is contained in:
tyshko-rostyslav 2023-06-07 13:18:01 +02:00 committed by GitHub
parent 96497db7c5
commit ecd056884c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 53 additions and 1 deletions

2
Cargo.lock generated
View File

@ -2702,6 +2702,8 @@ dependencies = [
"clap_derive",
"color-eyre 0.6.2",
"rln",
"serde",
"serde_json",
]
[[package]]

View File

@ -8,3 +8,6 @@ rln = { path = "../rln" }
clap = { version = "4.2.7", features = ["cargo", "derive", "env"]}
clap_derive = { version = "=4.2.0" }
color-eyre = "=0.6.2"
# serialization
serde_json = "1.0.48"
serde = { version = "1.0.130", features = ["derive"] }

29
rln-cli/src/config.rs Normal file
View File

@ -0,0 +1,29 @@
use color_eyre::Result;
use serde::{Deserialize, Serialize};
use std::{fs::File, io::Read, path::PathBuf};
pub const RLN_STATE_PATH: &str = "RLN_STATE_PATH";
#[derive(Default, Serialize, Deserialize)]
pub(crate) struct Config {
pub inner: Option<InnerConfig>,
}
#[derive(Default, Serialize, Deserialize)]
pub(crate) struct InnerConfig {
pub file: PathBuf,
pub tree_height: usize,
}
impl Config {
pub(crate) fn load_config() -> Result<Config> {
let path = PathBuf::from(std::env::var(RLN_STATE_PATH)?);
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let state: Config = serde_json::from_str(&contents)?;
Ok(state)
}
}

View File

@ -7,6 +7,7 @@ use rln::public::RLN;
use state::State;
mod commands;
mod config;
mod state;
#[derive(Parser)]
@ -19,7 +20,7 @@ struct Cli {
fn main() -> Result<()> {
let cli = Cli::parse();
let mut state = State::default();
let mut state = State::load_state()?;
match &cli.command {
Some(Commands::New {

View File

@ -1,6 +1,23 @@
use color_eyre::Result;
use rln::public::RLN;
use std::fs::File;
use crate::config::{InnerConfig, Config};
#[derive(Default)]
pub(crate) struct State<'a> {
pub rln: Option<RLN<'a>>,
}
impl<'a> State<'a> {
pub(crate) fn load_state() -> Result<State<'a>> {
let config = Config::load_config()?;
let rln = if let Some(InnerConfig { file, tree_height }) = config.inner {
let resources = File::open(&file)?;
Some(RLN::new(tree_height, resources)?)
} else {
None
};
Ok(State { rln })
}
}