-
Notifications
You must be signed in to change notification settings - Fork 390
Expand file tree
/
Copy pathinner.rs
More file actions
295 lines (262 loc) · 8.65 KB
/
inner.rs
File metadata and controls
295 lines (262 loc) · 8.65 KB
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
use crate::{Command, ListNode, Tab};
use ego_tree::{NodeMut, Tree};
use include_dir::{include_dir, Dir};
use serde::Deserialize;
use std::{
fs::File,
io::{BufRead, BufReader, Read},
ops::{Deref, DerefMut},
os::unix::fs::PermissionsExt,
path::{Path, PathBuf},
rc::Rc,
};
use temp_dir::TempDir;
const TAB_DATA: Dir = include_dir!("$CARGO_MANIFEST_DIR/tabs");
// Allow the unused TempDir to be stored for later destructor call
#[allow(dead_code)]
pub struct TabList(pub Vec<Tab>, TempDir);
// Implement deref to allow Vec<Tab> methods to be called on TabList
impl Deref for TabList {
type Target = Vec<Tab>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for TabList {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl IntoIterator for TabList {
type Item = Tab;
type IntoIter = std::vec::IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
pub fn get_tabs(validate: bool) -> TabList {
let (temp_dir, tab_files) = TabDirectories::get_tabs();
let tabs: Vec<_> = tab_files
.into_iter()
.map(|path| {
let directory = path.parent().unwrap().to_owned();
let data = std::fs::read_to_string(path).expect("Failed to read tab data");
let mut tab_data: TabEntry = toml::from_str(&data).expect("Failed to parse tab data");
if validate {
filter_entries(&mut tab_data.data);
}
(tab_data, directory)
})
.collect();
let tabs: Vec<Tab> = tabs
.into_iter()
.map(|(TabEntry { name, data }, directory)| {
let mut tree = Tree::new(Rc::new(ListNode {
name: "root".to_string(),
description: String::new(),
command: Command::None,
task_list: String::new(),
multi_select: false,
}));
let mut root = tree.root_mut();
create_directory(data, &mut root, &directory, validate, true);
Tab { name, tree }
})
.collect();
if tabs.is_empty() {
panic!("No tabs found");
}
TabList(tabs, temp_dir)
}
#[derive(Deserialize)]
struct TabDirectories {
directories: Vec<PathBuf>,
}
#[derive(Deserialize)]
struct TabEntry {
name: String,
data: Vec<Entry>,
}
#[derive(Deserialize)]
struct Entry {
name: String,
#[allow(dead_code)]
#[serde(default)]
description: String,
#[serde(default)]
preconditions: Option<Vec<Precondition>>,
#[serde(flatten)]
entry_type: EntryType,
#[serde(default)]
task_list: String,
#[serde(default = "default_true")]
multi_select: bool,
}
fn default_true() -> bool {
true
}
#[derive(Deserialize)]
enum EntryType {
#[serde(rename = "entries")]
Entries(Vec<Entry>),
#[serde(rename = "command")]
Command(String),
#[serde(rename = "script")]
Script(PathBuf),
}
impl Entry {
fn is_supported(&self) -> bool {
self.preconditions.as_deref().map_or(true, |preconditions| {
preconditions.iter().all(
|Precondition {
matches,
data,
values,
}| {
match data {
SystemDataType::Environment(var_name) => std::env::var(var_name)
.is_ok_and(|var| values.contains(&var) == *matches),
SystemDataType::File(path) => path.exists() == *matches,
SystemDataType::CommandExists => values
.iter()
.all(|command| which::which(command).is_ok() == *matches),
SystemDataType::FileContains { file, contains } => {
std::fs::read_to_string(file)
.map(|content| content.contains(contains) == *matches)
.unwrap_or(false)
}
}
},
)
})
}
}
#[derive(Deserialize)]
struct Precondition {
// If true, the data must be contained within the list of values.
// Otherwise, the data must not be contained within the list of values
matches: bool,
data: SystemDataType,
values: Vec<String>,
}
#[derive(Deserialize)]
enum SystemDataType {
#[serde(rename = "environment")]
Environment(String),
#[serde(rename = "file")]
File(PathBuf),
#[serde(rename = "command_exists")]
CommandExists,
#[serde(untagged)]
FileContains {
file: PathBuf,
contains: String,
},
}
fn filter_entries(entries: &mut Vec<Entry>) {
entries.retain_mut(|entry| {
if !entry.is_supported() {
return false;
}
if let EntryType::Entries(entries) = &mut entry.entry_type {
filter_entries(entries);
!entries.is_empty()
} else {
true
}
});
}
fn create_directory(
data: Vec<Entry>,
node: &mut NodeMut<Rc<ListNode>>,
command_dir: &Path,
validate: bool,
parent_multi_select: bool,
) {
for entry in data {
let multi_select = parent_multi_select && entry.multi_select;
match entry.entry_type {
EntryType::Entries(entries) => {
let mut node = node.append(Rc::new(ListNode {
name: entry.name,
description: entry.description,
command: Command::None,
task_list: String::new(),
multi_select,
}));
create_directory(entries, &mut node, command_dir, validate, multi_select);
}
EntryType::Command(command) => {
node.append(Rc::new(ListNode {
name: entry.name,
description: entry.description,
command: Command::Raw(command),
task_list: String::new(),
multi_select,
}));
}
EntryType::Script(script) => {
let script = command_dir.join(script);
if !script.exists() {
panic!("Script {} does not exist", script.display());
}
if let Some((executable, args)) = get_shebang(&script, validate) {
node.append(Rc::new(ListNode {
name: entry.name,
description: entry.description,
command: Command::LocalFile {
executable,
args,
file: script,
},
task_list: entry.task_list,
multi_select,
}));
}
}
}
}
}
fn get_shebang(script_path: &Path, validate: bool) -> Option<(String, Vec<String>)> {
let default_executable = || Some(("/bin/sh".into(), vec!["-e".into()]));
let script = File::open(script_path).expect("Failed to open script file");
let mut reader = BufReader::new(script);
// Take the first 2 characters from the reader; check whether it's a shebang
let mut two_chars = [0; 2];
if reader.read_exact(&mut two_chars).is_err() || two_chars != *b"#!" {
return default_executable();
}
let first_line = reader.lines().next().unwrap().unwrap();
let mut parts = first_line.split_whitespace();
let Some(executable) = parts.next() else {
return default_executable();
};
let is_valid = !validate || is_executable(Path::new(executable));
is_valid.then(|| {
let mut args: Vec<String> = parts.map(ToString::to_string).collect();
args.push(script_path.to_string_lossy().to_string());
(executable.to_string(), args)
})
}
fn is_executable(path: &Path) -> bool {
path.metadata()
.map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0)
.unwrap_or(false)
}
impl TabDirectories {
fn get_tabs() -> (TempDir, Vec<PathBuf>) {
let temp_dir = TempDir::with_prefix("linutil_scripts").unwrap();
TAB_DATA
.extract(&temp_dir)
.expect("Failed to extract the saved directory");
let tab_files = std::fs::read_to_string(temp_dir.path().join("tabs.toml"))
.expect("Failed to read tabs.toml");
let data: Self = toml::from_str(&tab_files).expect("Failed to parse tabs.toml");
let tab_paths = data
.directories
.iter()
.map(|path| temp_dir.path().join(path).join("tab_data.toml"))
.collect();
(temp_dir, tab_paths)
}
}