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

use anyhow::{anyhow,Context};
use std::ops::Deref;
use std::convert::AsRef;
use std::fmt::Debug;
use std::sync::Arc;
use std::fs;
use serde::de::Deserialize;
use tokio::process::Command;

use crate::local::CollarKey;

type E = anyhow::Error;

pub struct ParsedConfig {
  t : toml::Value,
  filename : String,
}

pub type Config = Arc<ParsedConfig>;

impl Deref for ParsedConfig {
  type Target = toml::Value;
  fn deref(&self) -> &toml::Value { &self.t }
}

pub const NO_MORE : [&str;0] = [];

const DEFAULT_KEY_FILE : &str = "/etc/tau.key";

pub trait Key : Debug {
  fn get<'t>(&self, t : &'t toml::Value) -> Option<&'t toml::value::Value>;
}
impl Key for str {
  fn get<'t>(&self, t : &'t toml::Value) -> Option<&'t toml::value::Value> {
    t.get(self)
  }
}
impl<K> Key for [&K] where K : Key + ?Sized {
  fn get<'t>(&self, t0 : &'t toml::Value) -> Option<&'t toml::value::Value> {
    let mut t = t0;
    for k in self { t = k.get(t)? }
    Some(t)
  }
}
impl<'s, R : Debug + AsRef<[&'s str]>> Key for R {
  fn get<'t>(&self, t : &'t toml::Value) -> Option<&'t toml::value::Value> {
    Key::get(self.as_ref(), t)
  }
}

//impl Key for [&str] {
//}

impl ParsedConfig {
  pub fn lookup<'l, K : Key + ?Sized, T : Deserialize<'l>>
    (&self, k : &K, def : T) -> Result<T,E>
  {
    let s = k.get(self);
    if s.is_none() { return Ok(def) }
    Ok( s.unwrap().clone().try_into()
        .context(format!("config key {:?}",k))? )
  }

  pub fn need<'l, K : Key + ?Sized, T : Deserialize<'l>>
    (&self, k : &K) -> Result<T,E>
  {
    Ok((||{
      let s = k.get(self).ok_or_else(|| anyhow!("missing config"))?;
      <Result<T,E>>::Ok(s.clone().try_into()?)
    })().context(format!("config key {:?}",&k))?)
  }

  fn command_from_strs<K : Key + ?Sized,
                       S : Debug + AsRef<str>, M : Debug + AsRef<str>>
                       (k : &K, cmd : &[S], more : &[M])
     -> Result<Command,E>
  {
    let l : Vec<&str> =
      cmd.iter().map(|s| s.as_ref())
      .chain( more.iter().map(|s| <M as AsRef<str>>::as_ref(s)) )
      .collect();
    println!("config: command for {:?}: {:?}", k, l);
    let mut c : Command = Command::new(
      l.first().ok_or_else(|| anyhow!("missing command") )?
    );
    c.args(l.iter().skip(1));
    <Result<Command,E>>::Ok(c)
  }

  pub fn command_general<K : Key + ?Sized,
                        S : Debug + AsRef<str>, M : Debug + AsRef<str>>
                        (&self, k : &K, def : &[S], more_args : &[M])
     -> Result<Command,E>
  {
    let c = (||{
      let l = k.get(self);
      if l.is_some() {
        let l : Vec<String> = l.unwrap().clone().try_into()?;
        Self::command_from_strs(k, &l,   more_args)
      } else {
        Self::command_from_strs(k, &def, more_args)
      }
    })().context(format!("command from config key {:?}",k))?;
    Ok(c)
  }

  pub fn command_simple<K : Key + ?Sized,
                        M : Debug + AsRef<str>>
                        (&self, k : &K, def : &str, more : &[M])
                         -> Result<Command,E> {
    self.command_general(k, &[def, &self.filename], more)
  }

  pub fn collar_key(&self) -> Result<CollarKey,E> {
    let key_file = self.lookup::<str, String>("key_file", DEFAULT_KEY_FILE.to_owned())?;
    let key = (||{
      let content = fs::read_to_string(&key_file)?;
      let key = content.trim().parse().context("parse key")?;
      <Result<CollarKey,E>>::Ok(key)
    })().context(format!("read key file {:?}",key_file))?;
    Ok(key)
  }
}

pub fn read() -> Result<Config, E> {
  let filename = std::env::args().nth(1)
    .ok_or_else(|| anyhow!("need config file arg"))?;
  let content = fs::read_to_string(&filename).context("config file")?;
  parse(&content, filename)
}

pub fn parse(content : &str, filename : String) -> Result<Config, E> {
  Ok(Arc::new( ParsedConfig{ t : content.parse()?, filename } ))
}