airmux 0.1.0

Just another tmux session manager
Documentation
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use crate::command::{de_command_list, process_command, process_command_list};
use crate::pane::Pane;
use crate::utils::valid_tmux_identifier;
use crate::working_dir::{de_working_dir, home_working_dir, process_working_dir};

use de::Visitor;
use serde::{de, Deserialize, Serialize};

use std::error::Error;
use std::fmt;
use std::path::PathBuf;

#[derive(Serialize, Debug, PartialEq, Clone)]
pub struct Window {
    pub name: Option<String>,
    pub working_dir: Option<PathBuf>,
    pub layout: Option<String>,
    pub on_create: Vec<String>,
    pub post_create: Vec<String>,
    pub on_pane_create: Vec<String>,
    pub post_pane_create: Vec<String>,
    pub pane_commands: Vec<String>,
    pub panes: Vec<Pane>,
}

impl Window {
    pub fn check(&self, base_pane_index: usize) -> Result<(), Box<dyn Error>> {
        // Make sure the window's name is valid
        if let Some(name) = &self.name {
            valid_tmux_identifier(name)?;
        }

        // Check that split_from for each pane points to an existing pane
        for pane in &self.panes {
            pane.check()?;

            if self.layout.is_some() && (pane.split.is_some() || pane.split_size.is_some()) {
                return Err(
                    "layout: cannot use layout when sub-panes use split or split_size".into(),
                );
            }

            if let Some(split_from) = pane.split_from {
                if split_from < base_pane_index || split_from >= base_pane_index + self.panes.len()
                {
                    return Err(format!(
                        "split_from: there is no pane with index {} (pane indexes always start at pane_base_index)",
                        split_from
                    ).into());
                }
            }
        }

        // Make sure working_dir exists and is a directory
        if let Some(path) = &self.working_dir {
            if !path.is_dir() {
                return Err(format!(
                    "window working_dir {:?} is not a directory or does not exist",
                    path
                )
                .into());
            }
        }

        // Run check for each pane
        for pane in &self.panes {
            pane.check()?;
        }

        Ok(())
    }

    pub fn default_panes() -> Vec<Pane> {
        vec![Pane::default()]
    }

    fn de_panes<'de, D>(deserializer: D) -> Result<Vec<Pane>, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        #[derive(Deserialize, Debug)]
        #[serde(untagged)]
        enum PaneList {
            Empty,
            List(Vec<Pane>),
            Single(Pane),
        };

        let pane_list: PaneList = de::Deserialize::deserialize(deserializer)?;

        Ok(match pane_list {
            PaneList::List(panes) => panes,
            PaneList::Single(pane) => vec![pane],
            PaneList::Empty => Self::default_panes(),
        })
    }
}

impl From<&str> for Window {
    fn from(command: &str) -> Self {
        Self::from(command.to_string())
    }
}

impl From<String> for Window {
    fn from(command: String) -> Self {
        Self {
            panes: vec![Pane::from(command)],
            ..Self::default()
        }
    }
}

impl From<Vec<String>> for Window {
    fn from(commands: Vec<String>) -> Self {
        Self {
            panes: commands.into_iter().map(Pane::from).collect(),
            ..Self::default()
        }
    }
}

impl Default for Window {
    fn default() -> Self {
        Self {
            name: None,
            working_dir: None,
            layout: None,
            on_create: vec![],
            post_create: vec![],
            on_pane_create: vec![],
            post_pane_create: vec![],
            pane_commands: vec![],
            panes: Self::default_panes(),
        }
    }
}

struct WindowVisitor;
impl<'de> Visitor<'de> for WindowVisitor {
    type Value = Window;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a window definition")
    }

    fn visit_none<E>(self) -> Result<Self::Value, E>
    where
        E: Error,
    {
        Ok(Window::default())
    }

    fn visit_unit<E>(self) -> Result<Self::Value, E>
    where
        E: Error,
    {
        Ok(Window::default())
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: Error,
    {
        Ok(Window::from(v))
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: de::SeqAccess<'de>,
    {
        let mut commands: Vec<String> = Vec::with_capacity(seq.size_hint().unwrap_or(0));

        while let Some(command) = seq.next_element::<String>()? {
            commands.push(command);
        }

        Ok(Window::from(commands))
    }

    fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
    where
        M: de::MapAccess<'de>,
    {
        type WindowKeyType = Option<String>;

        #[derive(Deserialize, Debug)]
        #[serde(deny_unknown_fields)]
        struct WindowDef {
            #[serde(default, alias = "root", deserialize_with = "de_working_dir")]
            working_dir: Option<PathBuf>,
            #[serde(default)]
            layout: Option<String>,
            #[serde(default, deserialize_with = "de_command_list")]
            on_create: Vec<String>,
            #[serde(default, deserialize_with = "de_command_list")]
            post_create: Vec<String>,
            #[serde(default, deserialize_with = "de_command_list")]
            on_pane_create: Vec<String>,
            #[serde(default, deserialize_with = "de_command_list")]
            post_pane_create: Vec<String>,
            #[serde(
                default,
                alias = "pre",
                alias = "pane_command",
                deserialize_with = "de_command_list"
            )]
            pane_commands: Vec<String>,
            #[serde(
                default = "Window::default_panes",
                alias = "pane",
                deserialize_with = "Window::de_panes"
            )]
            panes: Vec<Pane>,
        }

        #[derive(Deserialize, Debug)]
        #[serde(deny_unknown_fields)]
        struct WindowDefWithName {
            #[serde(alias = "title")]
            name: Option<String>,
            #[serde(default, alias = "root", deserialize_with = "de_working_dir")]
            working_dir: Option<PathBuf>,
            #[serde(default)]
            layout: Option<String>,
            #[serde(default, deserialize_with = "de_command_list")]
            on_create: Vec<String>,
            #[serde(default, deserialize_with = "de_command_list")]
            post_create: Vec<String>,
            #[serde(default, deserialize_with = "de_command_list")]
            on_pane_create: Vec<String>,
            #[serde(default, deserialize_with = "de_command_list")]
            post_pane_create: Vec<String>,
            #[serde(
                default,
                alias = "pre",
                alias = "pane_command",
                deserialize_with = "de_command_list"
            )]
            pane_commands: Vec<String>,
            #[serde(
                default = "Window::default_panes",
                alias = "pane",
                deserialize_with = "Window::de_panes"
            )]
            panes: Vec<Pane>,
        }

        #[derive(Deserialize, Debug)]
        #[serde(untagged)]
        enum WindowOption {
            None,
            String(String),
            CommandList(Vec<String>),
            PaneList(Vec<Pane>),
            Definition(WindowDef),
            DefinitionWithName(WindowDefWithName),
        }

        let mut first_entry = true;
        let mut window = Self::Value::default();
        while let Some((key, value)) = map.next_entry::<WindowKeyType, WindowOption>()? {
            match key {
                None => {
                    if !first_entry {
                        return Err(de::Error::custom(
                            "null name can only be set as first element of the map",
                        ));
                    }

                    match value {
                        WindowOption::None => {}
                        WindowOption::String(string) => window.panes = vec![Pane::from(string)],
                        WindowOption::CommandList(commands) => {
                            window.panes = commands.into_iter().map(Pane::from).collect()
                        }
                        WindowOption::DefinitionWithName(def) => {
                            window.name = def.name;
                            window.working_dir = def.working_dir;
                            window.layout = def.layout;
                            window.on_create = def.on_create;
                            window.post_create = def.post_create;
                            window.on_pane_create = def.on_pane_create;
                            window.post_pane_create = def.post_pane_create;
                            window.pane_commands = def.pane_commands;
                            window.panes = def.panes;
                        }
                        WindowOption::Definition(def) => {
                            window.working_dir = def.working_dir;
                            window.layout = def.layout;
                            window.on_create = def.on_create;
                            window.post_create = def.post_create;
                            window.on_pane_create = def.on_pane_create;
                            window.post_pane_create = def.post_pane_create;
                            window.pane_commands = def.pane_commands;
                            window.panes = def.panes;
                        }
                        WindowOption::PaneList(panes) => window.panes = panes,
                    }
                }
                Some(key) => match value {
                    WindowOption::None => match key.as_str() {
                        "name" | "title" => window.name = None,
                        "working_dir" | "root" => window.working_dir = Some(home_working_dir()),
                        "layout" => window.layout = None,
                        "on_create" => window.on_create = vec![],
                        "post_create" => window.post_create = vec![],
                        "on_pane_create" => window.on_pane_create = vec![],
                        "post_pane_create" => window.post_pane_create = vec![],
                        "pane_commands" | "pane_command" | "pre" => window.pane_commands = vec![],
                        "panes" | "pane" => window.panes = vec![Pane::default()],
                        _ => {
                            if !first_entry {
                                return Err(de::Error::custom(format!(
                                    "window field {:?} cannot be null",
                                    key
                                )));
                            }

                            window.name = Some(key);
                        }
                    },
                    WindowOption::String(val) => match key.as_str() {
                        "name" | "title" => window.name = Some(val),
                        "working_dir" | "root" => {
                            window.working_dir = Some(process_working_dir(val.as_str()))
                        }
                        "layout" => window.layout = Some(val),
                        "on_create" => window.on_create = vec![process_command(val)],
                        "post_create" => window.post_create = vec![process_command(val)],
                        "on_pane_create" => window.on_pane_create = vec![process_command(val)],
                        "post_pane_create" => window.post_pane_create = vec![process_command(val)],
                        "pane_commands" | "pane_command" | "pre" => {
                            window.pane_commands = vec![process_command(val)]
                        }
                        "panes" | "pane" => window.panes = vec![Pane::from(val)],
                        _ => {
                            if !first_entry {
                                return Err(de::Error::custom(format!(
                                    "window field {:?} cannot be a string",
                                    key
                                )));
                            }

                            window.name = Some(key);
                            window.panes = vec![Pane::from(val)]
                        }
                    },
                    WindowOption::CommandList(commands) => match key.as_str() {
                        "on_create" => window.on_create = process_command_list(commands),
                        "post_create" => window.post_create = process_command_list(commands),
                        "on_pane_create" => window.on_pane_create = process_command_list(commands),
                        "post_pane_create" => {
                            window.post_pane_create = process_command_list(commands)
                        }
                        "pane_commands" | "pane_command" | "pre" => {
                            window.pane_commands = process_command_list(commands)
                        }
                        "panes" | "pane" => {
                            window.panes = commands.into_iter().map(Pane::from).collect()
                        }
                        _ => {
                            if !first_entry {
                                return Err(de::Error::custom(format!(
                                    "window field {:?} cannot be a command list",
                                    key
                                )));
                            }

                            window.name = Some(key);
                            window.panes = commands.into_iter().map(Pane::from).collect()
                        }
                    },
                    WindowOption::Definition(def) => {
                        if !first_entry {
                            return Err(de::Error::custom(format!(
                                "window field {:?} cannot be a window definition",
                                key
                            )));
                        }

                        window.name = Some(key);
                        window.working_dir = def.working_dir;
                        window.layout = def.layout;
                        window.on_create = def.on_create;
                        window.post_create = def.post_create;
                        window.on_pane_create = def.on_pane_create;
                        window.post_pane_create = def.post_pane_create;
                        window.pane_commands = def.pane_commands;
                        window.panes = def.panes;
                    }
                    WindowOption::DefinitionWithName(def) => {
                        if !first_entry {
                            return Err(de::Error::custom(format!(
                                "window field {:?} cannot be a window definition",
                                key
                            )));
                        }

                        window.name = def.name;
                        window.working_dir = def.working_dir;
                        window.layout = def.layout;
                        window.on_create = def.on_create;
                        window.post_create = def.post_create;
                        window.on_pane_create = def.on_pane_create;
                        window.post_pane_create = def.post_pane_create;
                        window.pane_commands = def.pane_commands;
                        window.panes = def.panes;
                    }
                    WindowOption::PaneList(panes) => match key.as_str() {
                        "panes" | "pane" => window.panes = panes,
                        _ => {
                            if !first_entry {
                                return Err(de::Error::custom(format!(
                                    "window field {:?} cannot be a pane list",
                                    key
                                )));
                            }

                            window.name = Some(key);
                            window.panes = panes
                        }
                    },
                },
            }

            first_entry = false;
        }

        Ok(window)
    }
}

impl<'de> Deserialize<'de> for Window {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        deserializer.deserialize_any(WindowVisitor)
    }
}

#[cfg(test)]
#[path = "test/window.rs"]
mod tests;