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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
use crate::command::de_command_list;
use crate::config::Config;
use crate::pane::Pane;
use crate::pane_split::PaneSplit;
use crate::startup_window::StartupWindow;
use crate::utils::{is_default, parse_command, valid_tmux_identifier};
use crate::window::Window;
use crate::working_dir::{de_working_dir, ser_working_dir};

use serde::ser::{SerializeSeq, Serializer};
use serde::{de, Deserialize, Serialize};
use shell_words::{join, split};

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

#[derive(Serialize, Debug, PartialEq, Clone)]
pub struct Project {
    pub session_name: Option<String>,
    pub tmux_command: Option<String>,
    pub tmux_options: Option<String>,
    pub tmux_socket: Option<String>,
    pub working_dir: Option<PathBuf>,
    pub window_base_index: usize,
    pub pane_base_index: usize,
    pub startup_window: StartupWindow,
    pub startup_pane: Option<usize>,
    pub on_start: Vec<String>,
    pub on_first_start: Vec<String>,
    pub on_restart: Vec<String>,
    pub on_exit: Vec<String>,
    pub on_stop: 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 clear_panes: bool,
    pub attach: bool,
    pub windows: Vec<Window>,
}

impl Project {
    pub fn prepare(self, config: &Config, project_name: &str, force_attach: Option<bool>) -> Self {
        let mut project = Self {
            session_name: self.session_name.or_else(|| Some(project_name.to_string())),
            ..self
        };

        if let Some(attach) = force_attach {
            project.attach = attach;
        }

        if let Some(tmux_command) = &config.tmux_command {
            project.tmux_command = Some(tmux_command.to_owned());
        } else if project.tmux_command.is_none() {
            project.tmux_command = Some(String::from("tmux"));
        }

        project
    }

    pub fn check(&self) -> Result<(), Box<dyn Error>> {
        // Make sure session name is valid
        if let Some(session_name) = &self.session_name {
            valid_tmux_identifier(session_name)?;
        }

        // Make sure start up window exists
        match &self.startup_window {
            StartupWindow::Index(index) => {
                if *index >= self.window_base_index + self.windows.len()
                    || *index < self.window_base_index
                {
                    return Err(
                        format!("startup_window: there is no window with index {}", index).into(),
                    );
                }
            }
            StartupWindow::Name(name) => {
                if self
                    .windows
                    .iter()
                    .find(|window| match &window.name {
                        Some(window_name) => window_name == name,
                        _ => false,
                    })
                    .is_none()
                {
                    return Err(
                        format!("startup_window: there is no window with name {:?}", name).into(),
                    );
                }
            }
            _ => {}
        }

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

        // Run checks for each window
        for window in &self.windows {
            window.check(self.pane_base_index)?;
        }

        Ok(())
    }

    // Separates tmux_command into the command itself + an array of arguments
    // The arguments are then merged with the passed arguments
    // Also appends tmux_socket and tmux_options as arguments while at it
    pub fn tmux_command(&self, args: &[&str]) -> Result<(String, Vec<String>), Box<dyn Error>> {
        let command = self.tmux_command.as_ref().ok_or("tmux command not set")?;

        let mut full_args = vec![];

        // Add tmux_socket arguments
        if let Some(tmux_socket) = &self.tmux_socket {
            full_args.extend_from_slice(&["-L", tmux_socket]);
        }

        // Add tmux_options as individual argument
        let tmux_options_split;
        if let Some(tmux_options) = &self.tmux_options {
            tmux_options_split = split(tmux_options)?;
            let mut tmux_options_split: Vec<&str> =
                tmux_options_split.iter().map(|x| x.as_str()).collect();
            full_args.append(&mut tmux_options_split);
        }

        // Add passed arguments
        full_args.extend_from_slice(args);

        // Use utiliy to split command and append args to the split arguments
        parse_command(&command, &full_args)
    }

    // Sanitizes tmux_command for use in the template file
    pub fn tmux<'a, I, S>(&self, args: I) -> Result<String, Box<dyn Error>>
    where
        I: IntoIterator<Item = &'a S>,
        S: AsRef<str> + 'a,
    {
        let args: Vec<&str> = args.into_iter().map(AsRef::as_ref).collect();
        let (command, args) = self.tmux_command(&args)?;

        Ok(join(iter::once(command).chain(args.into_iter())))
    }

    fn default_window_base_index() -> usize {
        1
    }

    fn is_default_window_base_index(value: &usize) -> bool {
        value == &Self::default_window_base_index()
    }

    fn default_pane_base_index() -> usize {
        1
    }

    fn is_default_pane_base_index(value: &usize) -> bool {
        value == &Self::default_pane_base_index()
    }

    fn default_windows() -> Vec<Window> {
        vec![Window::default()]
    }

    fn default_attach() -> bool {
        true
    }

    fn is_default_attach(attach: &bool) -> bool {
        *attach == Self::default_attach()
    }

    fn de_window_base_index<'de, D>(deserializer: D) -> Result<usize, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        let opt: Option<usize> = de::Deserialize::deserialize(deserializer)?;
        Ok(opt.unwrap_or_else(Self::default_window_base_index))
    }

    fn de_pane_base_index<'de, D>(deserializer: D) -> Result<usize, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        let opt: Option<usize> = de::Deserialize::deserialize(deserializer)?;
        Ok(opt.unwrap_or_else(Self::default_pane_base_index))
    }

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

        let window_list: WindowList = de::Deserialize::deserialize(deserializer)?;

        Ok(match window_list {
            WindowList::List(windows) => windows,
            WindowList::Single(window) => vec![window],
            WindowList::Empty => Self::default_windows(),
        })
    }

    pub fn serialize_compact(&self, json: bool) -> Result<String, Box<dyn Error>> {
        fn is_default_windows(windows: &[CompactWindow]) -> bool {
            Project::default_windows()
                .into_iter()
                .map(CompactWindow::from)
                .eq(windows.to_owned())
        }

        fn is_default_panes(panes: &[CompactPane]) -> bool {
            Window::default_panes()
                .into_iter()
                .map(CompactPane::from)
                .eq(panes.to_owned())
        }

        #[derive(Serialize, PartialEq, Clone)]
        struct CompactProject {
            #[serde(skip_serializing_if = "is_default")]
            session_name: Option<String>,
            #[serde(skip_serializing_if = "is_default")]
            tmux_command: Option<String>,
            #[serde(skip_serializing_if = "is_default")]
            tmux_options: Option<String>,
            #[serde(skip_serializing_if = "is_default")]
            tmux_socket: Option<String>,
            #[serde(skip_serializing_if = "is_default", serialize_with = "ser_working_dir")]
            working_dir: Option<PathBuf>,
            #[serde(skip_serializing_if = "Project::is_default_window_base_index")]
            window_base_index: usize,
            #[serde(skip_serializing_if = "Project::is_default_pane_base_index")]
            pane_base_index: usize,
            #[serde(skip_serializing_if = "is_default")]
            startup_window: StartupWindow,
            #[serde(skip_serializing_if = "is_default")]
            startup_pane: Option<usize>,
            #[serde(skip_serializing_if = "is_default")]
            on_start: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            on_first_start: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            on_restart: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            on_exit: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            on_stop: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            post_create: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            on_pane_create: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            post_pane_create: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            pane_commands: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            clear_panes: bool,
            #[serde(skip_serializing_if = "Project::is_default_attach")]
            attach: bool,
            #[serde(skip_serializing_if = "is_default_windows")]
            windows: Vec<CompactWindow>,
        }

        impl From<Project> for CompactProject {
            fn from(copy: Project) -> Self {
                Self {
                    session_name: copy.session_name,
                    tmux_command: copy.tmux_command,
                    tmux_options: copy.tmux_options,
                    tmux_socket: copy.tmux_socket,
                    working_dir: copy.working_dir,
                    window_base_index: copy.window_base_index,
                    pane_base_index: copy.pane_base_index,
                    startup_window: copy.startup_window,
                    startup_pane: copy.startup_pane,
                    on_start: copy.on_start,
                    on_first_start: copy.on_first_start,
                    on_restart: copy.on_restart,
                    on_exit: copy.on_exit,
                    on_stop: copy.on_stop,
                    post_create: copy.post_create,
                    on_pane_create: copy.on_pane_create,
                    post_pane_create: copy.post_pane_create,
                    pane_commands: copy.pane_commands,
                    clear_panes: copy.clear_panes,
                    attach: copy.attach,
                    windows: copy.windows.into_iter().map(CompactWindow::from).collect(),
                }
            }
        }

        #[derive(Serialize, PartialEq, Clone)]
        struct CompactWindow {
            name: Option<String>,
            #[serde(skip_serializing_if = "is_default", serialize_with = "ser_working_dir")]
            working_dir: Option<PathBuf>,
            #[serde(skip_serializing_if = "is_default")]
            layout: Option<String>,
            #[serde(skip_serializing_if = "is_default")]
            on_create: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            post_create: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            on_pane_create: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            post_pane_create: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            pane_commands: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            clear_panes: bool,
            #[serde(skip_serializing_if = "is_default_panes", serialize_with = "ser_panes")]
            panes: Vec<CompactPane>,
        }

        impl From<Window> for CompactWindow {
            fn from(copy: Window) -> Self {
                Self {
                    name: copy.name,
                    working_dir: copy.working_dir,
                    layout: copy.layout,
                    on_create: copy.on_create,
                    post_create: copy.post_create,
                    on_pane_create: copy.on_pane_create,
                    post_pane_create: copy.post_pane_create,
                    pane_commands: copy.pane_commands,
                    clear_panes: copy.clear_panes,
                    panes: copy.panes.into_iter().map(CompactPane::from).collect(),
                }
            }
        }

        #[derive(Serialize, PartialEq, Clone)]
        struct CompactPane {
            #[serde(skip_serializing_if = "is_default")]
            name: Option<String>,
            #[serde(skip_serializing_if = "is_default", serialize_with = "ser_working_dir")]
            working_dir: Option<PathBuf>,
            #[serde(skip_serializing_if = "is_default")]
            split: Option<PaneSplit>,
            #[serde(skip_serializing_if = "is_default")]
            split_from: Option<usize>,
            #[serde(skip_serializing_if = "is_default")]
            split_size: Option<String>,
            #[serde(skip_serializing_if = "is_default")]
            clear: bool,
            #[serde(skip_serializing_if = "is_default")]
            on_create: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            post_create: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            commands: Vec<String>,
            #[serde(skip_serializing_if = "is_default")]
            send_keys: Vec<String>,
        }

        impl From<Pane> for CompactPane {
            fn from(copy: Pane) -> Self {
                Self {
                    name: copy.name,
                    working_dir: copy.working_dir,
                    split: copy.split,
                    split_from: copy.split_from,
                    split_size: copy.split_size,
                    clear: copy.clear,
                    on_create: copy.on_create,
                    post_create: copy.post_create,
                    commands: copy.commands,
                    send_keys: copy.send_keys,
                }
            }
        }

        fn ser_panes<S>(panes: &[CompactPane], serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut seq = serializer.serialize_seq(Some(panes.len()))?;
            for pane in panes {
                if pane.commands.len() <= 1
                    && is_default(&pane.name)
                    && is_default(&pane.working_dir)
                    && is_default(&pane.split)
                    && is_default(&pane.split_from)
                    && is_default(&pane.split_size)
                    && is_default(&pane.clear)
                    && is_default(&pane.on_create)
                    && is_default(&pane.post_create)
                    && is_default(&pane.send_keys)
                {
                    if pane.commands.is_empty() {
                        seq.serialize_element(&None as &Option<&str>)?;
                    } else {
                        seq.serialize_element(&pane.commands[0])?;
                    }
                } else {
                    seq.serialize_element(pane)?;
                }
            }
            seq.end()
        }

        let project = CompactProject::from(self.to_owned());

        Ok(if json {
            serde_json::to_string_pretty(&project)?
        } else {
            serde_yaml::to_string(&project)?
        })
    }
}

impl Default for Project {
    fn default() -> Self {
        Self {
            session_name: None,
            tmux_command: None,
            tmux_options: None,
            tmux_socket: None,
            working_dir: None,
            window_base_index: Self::default_window_base_index(),
            pane_base_index: Self::default_pane_base_index(),
            startup_window: StartupWindow::default(),
            startup_pane: None,
            on_start: vec![],
            on_first_start: vec![],
            on_restart: vec![],
            on_exit: vec![],
            on_stop: vec![],
            post_create: vec![],
            on_pane_create: vec![],
            post_pane_create: vec![],
            pane_commands: vec![],
            clear_panes: false,
            attach: true,
            windows: Self::default_windows(),
        }
    }
}

impl From<Option<Project>> for Project {
    fn from(project: Option<Project>) -> Self {
        project.unwrap_or_default()
    }
}

impl<'de> Deserialize<'de> for Project {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        #[derive(Deserialize, Debug)]
        #[serde(deny_unknown_fields)]
        struct ProjectProxy {
            #[serde(default, alias = "name")]
            session_name: Option<String>,
            #[serde(default)]
            tmux_command: Option<String>,
            #[serde(default)]
            tmux_options: Option<String>,
            #[serde(default, alias = "socket_name")]
            tmux_socket: Option<String>,
            #[serde(default, alias = "root", deserialize_with = "de_working_dir")]
            working_dir: Option<PathBuf>,
            #[serde(
                default = "Project::default_window_base_index",
                deserialize_with = "Project::de_window_base_index"
            )]
            window_base_index: usize,
            #[serde(
                default = "Project::default_pane_base_index",
                deserialize_with = "Project::de_pane_base_index"
            )]
            pane_base_index: usize,
            #[serde(default)]
            startup_window: StartupWindow,
            #[serde(default)]
            startup_pane: Option<usize>,
            #[serde(
                default,
                alias = "on_project_start",
                deserialize_with = "de_command_list"
            )]
            on_start: Vec<String>,
            #[serde(
                default,
                alias = "on_project_first_start",
                alias = "on_create",
                deserialize_with = "de_command_list"
            )]
            on_first_start: Vec<String>,
            #[serde(
                default,
                alias = "on_project_restart",
                deserialize_with = "de_command_list"
            )]
            on_restart: Vec<String>,
            #[serde(
                default,
                alias = "on_project_exit",
                deserialize_with = "de_command_list"
            )]
            on_exit: Vec<String>,
            #[serde(
                default,
                alias = "on_project_stop",
                deserialize_with = "de_command_list"
            )]
            on_stop: 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_window",
                alias = "pane_command",
                deserialize_with = "de_command_list"
            )]
            pane_commands: Vec<String>,
            #[serde(default)]
            clear_panes: bool,
            #[serde(default, alias = "tmux_attached")]
            attach: Option<bool>,
            #[serde(default, alias = "tmux_detached")]
            detached: Option<bool>,
            #[serde(
                default = "Project::default_windows",
                alias = "window",
                deserialize_with = "Project::de_windows"
            )]
            windows: Vec<Window>,
        }

        let opt: Option<ProjectProxy> = de::Deserialize::deserialize(deserializer)?;

        Ok(match opt {
            None => Self::default(),
            Some(project) => {
                let attach = match project.attach {
                    Some(attach) => match project.detached {
                        None => attach,
                        Some(_) => {
                            return Err(de::Error::custom(
                                "cannot set both 'attach' and 'detached' fields",
                            ))
                        }
                    },
                    None => match project.detached {
                        Some(detached) => !detached,
                        None => Self::default_attach(),
                    },
                };

                Self {
                    session_name: project.session_name,
                    tmux_command: project.tmux_command,
                    tmux_options: project.tmux_options,
                    tmux_socket: project.tmux_socket,
                    working_dir: project.working_dir,
                    window_base_index: project.window_base_index,
                    pane_base_index: project.pane_base_index,
                    startup_window: project.startup_window,
                    startup_pane: project.startup_pane,
                    on_start: project.on_start,
                    on_first_start: project.on_first_start,
                    on_restart: project.on_restart,
                    on_exit: project.on_exit,
                    on_stop: project.on_stop,
                    post_create: project.post_create,
                    on_pane_create: project.on_pane_create,
                    post_pane_create: project.post_pane_create,
                    pane_commands: project.pane_commands,
                    clear_panes: project.clear_panes,
                    attach,
                    windows: project.windows,
                }
            }
        })
    }
}

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