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
use crate::config::{last_modified, read, Conf, Status}; use indexmap::IndexMap; use nu_protocol::Value; use nu_source::Tag; use std::fmt::Debug; #[derive(Debug, Clone, Default)] pub struct NuConfig { pub vars: IndexMap<String, Value>, pub modified_at: Status, } impl Conf for NuConfig { fn is_modified(&self) -> Result<bool, Box<dyn std::error::Error>> { self.is_modified() } fn var(&self, key: &str) -> Option<Value> { self.var(key) } fn env(&self) -> Option<Value> { self.env() } fn path(&self) -> Option<Value> { self.path() } fn reload(&mut self) { let vars = &mut self.vars; if let Ok(variables) = read(Tag::unknown(), &None) { vars.extend(variables); self.modified_at = if let Ok(status) = last_modified(&None) { status } else { Status::Unavailable }; } } fn clone_box(&self) -> Box<dyn Conf> { Box::new(self.clone()) } } impl NuConfig { pub fn with(config_file: Option<std::path::PathBuf>) -> NuConfig { match &config_file { None => NuConfig::new(), Some(_) => { let vars = if let Ok(variables) = read(Tag::unknown(), &config_file) { variables } else { IndexMap::default() }; NuConfig { vars, modified_at: NuConfig::get_last_modified(&config_file), } } } } pub fn new() -> NuConfig { let vars = if let Ok(variables) = read(Tag::unknown(), &None) { variables } else { IndexMap::default() }; NuConfig { vars, modified_at: NuConfig::get_last_modified(&None), } } pub fn get_last_modified(config_file: &Option<std::path::PathBuf>) -> Status { if let Ok(status) = last_modified(config_file) { status } else { Status::Unavailable } } pub fn is_modified(&self) -> Result<bool, Box<dyn std::error::Error>> { let modified_at = &self.modified_at; Ok(match (NuConfig::get_last_modified(&None), modified_at) { (Status::LastModified(left), Status::LastModified(right)) => { let left = left.duration_since(std::time::UNIX_EPOCH)?; let right = (*right).duration_since(std::time::UNIX_EPOCH)?; left != right } (_, _) => false, }) } pub fn var(&self, key: &str) -> Option<Value> { let vars = &self.vars; if let Some(value) = vars.get(key) { return Some(value.clone()); } None } pub fn env(&self) -> Option<Value> { let vars = &self.vars; if let Some(env_vars) = vars.get("env") { return Some(env_vars.clone()); } None } pub fn path(&self) -> Option<Value> { let vars = &self.vars; if let Some(env_vars) = vars.get("path") { return Some(env_vars.clone()); } None } }