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
use std::path::{Path, PathBuf};

use serde::{de::Error, Deserialize, Serialize};
use strum_macros::{Display, EnumIter};

use crate::{
    enums::{unit_enum_deserialize, unit_enum_from_str},
    util::normalize_path,
};

#[derive(Debug, Serialize)]
pub struct Shell {
    program: PathBuf,
    #[serde(skip_serializing_if = "Option::is_none")]
    kind: Option<ShellKind>,
}

impl Shell {
    pub fn new(program: &Path, kind: Option<ShellKind>) -> Self {
        Self {
            program: program.to_owned(),
            kind,
        }
    }

    pub fn program(&self) -> &Path {
        &self.program
    }

    pub fn kind(&self) -> Option<ShellKind> {
        self.kind
    }
}

impl std::fmt::Display for Shell {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.program.display().to_string())
    }
}

impl<'de> Deserialize<'de> for Shell {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(remote = "Shell")]
        struct ShellObject {
            program: PathBuf,
            kind: Option<ShellKind>,
        }

        #[derive(Deserialize)]
        #[serde(untagged)]
        enum ShellDeserializationMode {
            Path(PathBuf),
            #[serde(with = "ShellObject")]
            Object(Shell),
        }

        Ok(match ShellDeserializationMode::deserialize(deserializer)? {
            ShellDeserializationMode::Object(mut shell) => {
                shell.program = normalize_path(&shell.program).map_err(D::Error::custom)?;
                shell
            }
            ShellDeserializationMode::Path(program) => Shell {
                program: normalize_path(program).map_err(D::Error::custom)?,
                kind: None,
            },
        })
    }
}

#[derive(Debug, Display, Serialize, EnumIter, Clone, Copy)]
pub enum ShellKind {
    Posix,
    Cmd,
    Powershell,
}

unit_enum_from_str!(ShellKind);
unit_enum_deserialize!(ShellKind);