shellfish/app.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
//! # App
//!
//! Apps allow you to create commamd line argument parsing for your shellfish
//! commands. Basically, you define your commands as normal and call
//! [`.run_args`](App::run_args) on app. State is also saved, and only
//! deleted when given `exit` or `quit`.
//!
//! **Note: Normal handlers won't work as they MUST assume that
//! the first argument is that of the binaries name.**
use std::collections::HashMap;
use std::convert::TryFrom;
use std::env;
use std::error::Error;
use std::fmt::Display;
use std::fs;
use std::io::{Read, Write};
#[cfg(feature = "async-std")]
use async_std::prelude::*;
use serde::{Deserialize, Serialize};
pub use crate::handler::app::{CommandLineHandler, DefaultCommandLineHandler};
#[cfg(feature = "async")]
use crate::handler::async_app::DefaultAsyncCLIHandler;
use crate::*;
/// See the module level dicumentation. Note `App` closely mirrors state and
/// so can be created from it (given the right trait bounds)
pub struct App<
'b,
T: Serialize + for<'a> Deserialize<'a>,
H: CommandLineHandler,
> {
pub commands: HashMap<&'b str, Command<T>>,
pub state: T,
pub handler: H,
pub description: String,
}
impl<
'f: 't,
't,
T: Serialize + for<'a> Deserialize<'a>,
M: Display,
H: Handler<T>,
I: InputHandler,
> TryFrom<Shell<'f, T, M, H, I>> for App<'t, T, DefaultCommandLineHandler>
{
type Error = Box<dyn Error>;
fn try_from(shell: Shell<'f, T, M, H, I>) -> Result<Self, Box<dyn Error>> {
let mut this = Self {
commands: shell.commands,
state: shell.state,
handler: DefaultCommandLineHandler { proj_name: None },
description: shell.description,
};
this.load_cache()?;
Ok(this)
}
}
#[cfg(feature = "async")]
impl<'f: 't, 't, T: Serialize + for<'a> Deserialize<'a> + Send>
App<'t, T, DefaultAsyncCLIHandler>
{
pub fn try_from_async<M: Display, H: AsyncHandler<T>, I: InputHandler>(
shell: Shell<'f, T, M, H, I>,
) -> Result<Self, Box<dyn Error>> {
let mut this = Self {
commands: shell.commands,
state: shell.state,
handler: DefaultAsyncCLIHandler { proj_name: None },
description: shell.description,
};
this.load_cache()?;
Ok(this)
}
}
impl<T: Serialize + for<'a> Deserialize<'a>>
App<'_, T, DefaultCommandLineHandler>
{
/// Creates a new shell
pub fn new(state: T, project_name: String) -> Result<Self, Box<dyn Error>> {
let mut this = Self {
commands: HashMap::new(),
state,
handler: DefaultCommandLineHandler {
proj_name: Some(project_name),
},
description: String::new(),
};
this.load_cache()?;
Ok(this)
}
}
impl<T: Serialize + for<'a> Deserialize<'a>, H: CommandLineHandler>
App<'_, T, H>
{
/// Creates a new shell with the given handler.
///
/// **Note that this should be a handler which can deal with cli
/// arguments, as in the FIRST ARGUMENT is the BINARY name.**
pub fn new_with_handler(
state: T,
handler: H,
) -> Result<Self, Box<dyn Error>> {
let mut this = Self {
commands: HashMap::new(),
state,
handler,
description: String::new(),
};
this.load_cache()?;
Ok(this)
}
/// Loads the state from cache.
pub fn load_cache(&mut self) -> Result<(), Box<dyn Error>> {
if let Some(cache) = self.handler.get_cache() {
// Try and open the file
if let Ok(mut file) = fs::File::open(cache) {
// Get the string
let mut string = String::new();
file.read_to_string(&mut string)?;
// Parse it with serde json
self.state = serde_json::from_str(&string)?;
}
}
Ok(())
}
}
impl<
T: Serialize + for<'a> Deserialize<'a>,
H: CommandLineHandler + Handler<T>,
> App<'_, T, H>
{
/// Handles an vec of strings, like environment arguments.
///
/// Returns a bool on wether we have 'quit' or not
pub fn run_vec(&mut self, vec: Vec<String>) -> std::io::Result<bool> {
let result = self.handler.handle(
vec,
&self.commands,
&mut self.state,
&self.description,
);
// Do stuff with the cache
match result {
// Delete the cache
true => {
if let Some(cache) = self.handler.get_cache() {
fs::remove_file(cache)?;
}
}
// Write the cache
false => {
if let Some(cache) = self.handler.get_cache() {
// Create the dir
if let Some(dir) = cache.parent() {
fs::create_dir_all(dir)?;
}
// Create the file
let mut file = fs::File::create(cache)?;
file.write_all(
serde_json::to_string(&self.state)?.as_bytes(),
)?;
}
}
}
Ok(result)
}
/// Runs from the env args
pub fn run_args(&mut self) -> std::io::Result<bool> {
self.run_vec(env::args().collect())
}
}
#[cfg(feature = "async")]
impl<
T: Serialize + for<'a> Deserialize<'a> + Send,
H: CommandLineHandler + AsyncHandler<T>,
> App<'_, T, H>
{
/// Handles an vec of strings, like environment arguments.
///
/// Returns a bool on wether we have 'quit' or not
pub async fn run_vec_async(
&mut self,
vec: Vec<String>,
) -> std::io::Result<bool> {
let result = self
.handler
.handle_async(
vec,
&self.commands,
&mut self.state,
&self.description,
)
.await;
// Do stuff with the cache
match result {
// Delete the cache
true => {
if let Some(cache) = self.handler.get_cache() {
cfg_if::cfg_if! {
if #[cfg(feature = "async-std")] {
async_std::fs::remove_file(cache).await?;
} else if #[cfg(feature = "tokio")] {
tokio::fs::remove_file(cache).await?;
} else {
fs::remove_file(cache)?;
}
}
}
}
// Write the cache
false => {
if let Some(cache) = self.handler.get_cache() {
cfg_if::cfg_if! {
if #[cfg(feature = "async-std")] {
// Create the dir
if let Some(dir) = cache.parent() {
async_std::fs::create_dir_all(dir).await?;
}
// Create the file
let mut file = async_std::fs::File::create(cache).await?;
file.write_all(
serde_json::to_string(&self.state)?.as_bytes(),
).await?;
} else if #[cfg(feature = "tokio")] {
// Create the dir
if let Some(dir) = cache.parent() {
tokio::fs::create_dir_all(dir).await?;
}
// Create the file
let mut file = tokio::fs::File::create(cache).await?;
file.write_all(
serde_json::to_string(&self.state)?.as_bytes(),
).await?;
} else {
// Create the dir
if let Some(dir) = cache.parent() {
fs::create_dir_all(dir)?;
}
// Create the file
let mut file = fs::File::create(cache)?;
file.write_all(
serde_json::to_string(&self.state)?.as_bytes(),
)?;
}
}
}
}
}
Ok(result)
}
/// Runs from the env args
pub async fn run_args_async(&mut self) -> std::io::Result<bool> {
self.run_vec_async(env::args().collect()).await
}
}