annoying_journal/src/config.rs

64 lines
1.4 KiB
Rust

use std::{
str::FromStr,
};
type Result <T> = std::result::Result <T, crate::error::Error>;
pub struct Config {
pub interval_secs: u64,
pub prompt: String,
// Open dev tools in a web browser and run `Math.random () * 2225`
pub offset_secs: u64,
}
impl Default for Config {
fn default () -> Self {
Self {
interval_secs: 2225,
prompt: "Write a journal entry, then hit Tab, Enter to submit it.".into (),
offset_secs: 0,
}
}
}
impl Config {
pub fn from_args <I: Iterator <Item=String>> (mut args: I) -> Result <Self> {
use crate::error::Error::{
CannotParseArg,
ParamNeedsArg,
};
let mut that = Self::default ();
// Finally found the difference: https://stackoverflow.com/questions/1788923/parameter-vs-argument
while let Some (arg) = args.next () {
if arg == "--interval-secs" {
let val = args.next ().ok_or (ParamNeedsArg ("--interval-secs"))?;
let val = u64::from_str (&val).map_err (|_| CannotParseArg ("--interval-secs <u64>"))?;
that.interval_secs = val;
}
else if arg == "--offset-secs" {
let val = args.next ().ok_or (ParamNeedsArg ("--offset-secs"))?;
let val = u64::from_str (&val).map_err (|_| CannotParseArg ("--offset-secs <u64>"))?;
that.offset_secs = val;
}
else if arg == "--prompt" {
let val = args.next ().ok_or (ParamNeedsArg ("--prompt"))?;
that.prompt = val;
}
}
Ok (that)
}
}
#[cfg (test)]
mod test {
#[test]
fn parse () {
}
}