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
use std::{cell::RefCell, error::Error};
mod parser;
#[derive(Debug)]
pub struct Config<'a> {
contents: RefCell<Vec<&'a str>>,
}
impl<'a> Config<'a> {
pub fn load(contents: Vec<&'a str>) -> Config {
Config {
contents: RefCell::new(contents),
}
}
pub fn get_config(&self) -> String {
self.contents
.borrow()
.iter()
.map(|c| c.to_string())
.collect::<Vec<String>>()
.join("\n")
}
pub fn list_contexts(&self) -> Result<String, Box<dyn Error>> {
Ok(self
.get_contexts()?
.iter()
.map(|c| c.to_string())
.collect::<Vec<String>>()
.join("\n"))
}
pub fn check_context(&self, context: &str) -> Result<bool, &'static str> {
let contexts = self.get_contexts()?;
Ok(contexts.iter().any(|c| *c == context))
}
pub fn get_current_context(&self) -> Result<&str, &'static str> {
let contents = self.contents.borrow();
let iter = contents.iter();
for line in iter {
if let Some(current_context) = parser::match_literal(line, "current-context: ") {
return Ok(current_context);
}
}
Err("current-context is not set")
}
pub fn set_current_context(&'a self, new_context: &'a str) -> Result<(), &'static str> {
let mut contents = self.contents.borrow_mut();
let iter = contents.iter();
for (index, line) in iter.enumerate() {
if parser::match_literal(line, "current-context:").is_some() {
contents.push(new_context);
contents.swap_remove(index);
return Ok(());
}
}
contents.push(new_context);
Ok(())
}
pub fn unset_current_context(&'a self) -> Result<(), &'static str> {
let mut contents = self.contents.borrow_mut();
let iter = contents.iter();
for (index, line) in iter.enumerate() {
if parser::match_literal(line, "current-context:").is_some() {
contents.remove(index);
return Ok(());
}
}
Ok(())
}
fn get_contexts(&self) -> Result<Vec<&str>, &'static str> {
let mut contexts = Vec::<&str>::new();
let contents = self.contents.borrow();
let mut input = contents.iter().peekable();
while let Some(line) = input.next() {
if parser::match_literal(line, "contexts:").is_some() {
while parser::is_in_mapping(input.peek().ok_or("Reached the end of contexts.")?)
.is_ok()
{
if let Some(line) = input.next() {
if let Some(name) = parser::match_literal(line, " name: ") {
contexts.push(name);
}
}
}
break;
}
}
if contexts.is_empty() {
return Err("Cannot get contexts!");
}
Ok(contexts)
}
}