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
extern crate serde_json;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::io::{BufRead,LineWriter,Write};
#[cfg(test)]
mod tests;
#[derive(Serialize, Deserialize, Debug)]
struct I3StatusItem {
name: String,
instance: Option<String>,
markup: String,
color: Option<String>,
full_text: String,
}
pub fn begin<R: BufRead, W: Write>( reader: &mut R, writer: &mut LineWriter<W> ) -> std::io::Result<()>{
let mut line = String::new();
reader.read_line(&mut line)?;
writer.write_all(line.as_bytes())?;
assert!(line == "{\"version\":1}\n");
line = String::new();
reader.read_line(&mut line)?;
writer.write_all(line.as_bytes())?;
assert!(line == "[\n");
Ok(())
}
pub fn update<R: BufRead, W: std::io::Write>( reader: &mut R, writer: &mut LineWriter<W>, name: &str, position: usize, reverse: bool, what: &str) -> std::io::Result<()> {
let mut line = String::new();
reader.read_line(&mut line)?;
assert!(line != "{\"version\":1}");
assert!(line != "[");
if line.chars().next().unwrap() == ',' {
line.remove(0);
writer.write_all(b",")?;
}
match serde_json::from_str(&line) {
Ok(i) => {
let mut items: Vec<I3StatusItem> = i;
let w: I3StatusItem = I3StatusItem {
full_text: what.to_string(),
markup: "none".to_string(),
name: name.to_string(),
instance: None,
color: None,
};
if reverse {
items.insert(items.len() - 1 - position, w);
} else {
items.insert(position, w);
}
writer.write_all(format_json(format!("{:?}", items)).as_bytes())?;
}
_ => writer.write_all(line.as_bytes())?,
}
writer.write_all(b"\n")?;
Ok(())
}
fn format_json(line: String) -> String {
let line = line
.replace("I3StatusItem", "")
.replace(", color: None", "")
.replace(", instance: None", "")
.replace(", full_text:", ",\"full_text\":")
.replace(", instance:", ",\"instance\":")
.replace(", color:", ",\"color\":")
.replace(", markup:", ",\"markup\":")
.replace("{ name:", "{\"name\":");
let re = Regex::new(r"Some\((?P<v>[^\)]*)\)").unwrap();
re.replace_all(&line, "$v").to_owned().to_string()
}