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
use std::ffi::{OsStr, OsString};
use std::fmt::Display;
use std::path::PathBuf;

use clap::{Arg, Command, Error};
use color_eyre::eyre::Result;
use regex::Regex;

use crate::plugins::PluginName;
use crate::toolset::{ToolVersion, ToolVersionType};

#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct RuntimeArg {
    pub plugin: PluginName,
    pub version: RuntimeArgVersion,
}

/// The type of runtime argument
/// Generally, these are in the form of `plugin@version` that's "Version"
/// but there are some alternatives like `plugin@ref:sha` or `plugin@path:/path/to/runtime`
#[derive(Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum RuntimeArgVersion {
    /// Nothing was specified, e.g.: `nodejs`
    None,
    /// references a version, version prefix, or alias
    /// e.g.: `nodejs@18`, `nodejs@latest`, `nodejs@lts`
    Version(String),
    /// use the system runtime already on PATH
    /// e.g.: `nodejs@system`
    System,
    /// build runtime from source at this VCS sha
    Ref(String),
    /// runtime is in a local directory, not managed by rtx
    Path(PathBuf),
    Prefix(String),
}

impl RuntimeArg {
    pub fn parse(input: &str) -> Self {
        match input.split_once('@') {
            Some((plugin, "system")) => Self {
                plugin: plugin.into(),
                version: RuntimeArgVersion::System,
            },
            Some((plugin, version)) => match version.split_once(':') {
                Some(("path", path)) => Self {
                    plugin: plugin.into(),
                    version: RuntimeArgVersion::Path(path.into()),
                },
                Some(("ref", ref_)) => Self {
                    plugin: plugin.into(),
                    version: RuntimeArgVersion::Ref(ref_.into()),
                },
                Some(("prefix", prefix)) => Self {
                    plugin: plugin.into(),
                    version: RuntimeArgVersion::Prefix(prefix.into()),
                },
                _ => Self {
                    plugin: plugin.into(),
                    version: RuntimeArgVersion::Version(version.into()),
                },
            },
            None => Self {
                plugin: input.into(),
                version: RuntimeArgVersion::None,
            },
        }
    }

    /// this handles the case where the user typed in:
    /// rtx local nodejs 18.0.0
    /// instead of
    /// rtx local nodejs@18.0.0
    ///
    /// We can detect this, and we know what they meant, so make it work the way
    /// they expected.
    pub fn double_runtime_condition(runtimes: &[RuntimeArg]) -> Vec<RuntimeArg> {
        let mut runtimes = runtimes.to_vec();
        if runtimes.len() == 2 {
            let re: &Regex = regex!(r"^\d+(\.\d+)?(\.\d+)?$");
            let a = runtimes[0].clone();
            let b = runtimes[1].clone();
            if matches!(a.version, RuntimeArgVersion::None)
                && matches!(b.version, RuntimeArgVersion::None)
                && re.is_match(&b.plugin)
            {
                runtimes[1].version = RuntimeArgVersion::Version(b.plugin);
                runtimes[1].plugin = a.plugin;
                runtimes.remove(0);
            }
        }
        runtimes
    }

    pub fn with_version(self, version: RuntimeArgVersion) -> Self {
        Self { version, ..self }
    }

    pub fn to_tool_version(&self) -> Option<ToolVersion> {
        match self.version {
            RuntimeArgVersion::Version(ref v) => Some(ToolVersion::new(
                self.plugin.clone(),
                ToolVersionType::Version(v.clone()),
            )),
            RuntimeArgVersion::Ref(ref v) => Some(ToolVersion::new(
                self.plugin.clone(),
                ToolVersionType::Ref(v.clone()),
            )),
            RuntimeArgVersion::Path(ref v) => Some(ToolVersion::new(
                self.plugin.clone(),
                ToolVersionType::Path(v.clone()),
            )),
            RuntimeArgVersion::Prefix(ref v) => Some(ToolVersion::new(
                self.plugin.clone(),
                ToolVersionType::Prefix(v.clone()),
            )),
            RuntimeArgVersion::System => Some(ToolVersion::new(
                self.plugin.clone(),
                ToolVersionType::System,
            )),
            RuntimeArgVersion::None => None,
        }
    }
}

impl Display for RuntimeArg {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}@{}", self.plugin, self.version)
    }
}

impl Display for RuntimeArgVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RuntimeArgVersion::System => write!(f, "system"),
            RuntimeArgVersion::Version(version) => write!(f, "{version}"),
            RuntimeArgVersion::Path(path) => write!(f, "path:{}", path.display()),
            RuntimeArgVersion::Ref(ref_) => write!(f, "ref:{ref_}"),
            RuntimeArgVersion::Prefix(prefix) => write!(f, "prefix:{prefix}"),
            RuntimeArgVersion::None => write!(f, "current"),
        }
    }
}

#[derive(Debug, Clone)]
pub struct RuntimeArgParser;

impl clap::builder::TypedValueParser for RuntimeArgParser {
    type Value = RuntimeArg;

    fn parse_ref(
        &self,
        cmd: &Command,
        arg: Option<&Arg>,
        value: &OsStr,
    ) -> Result<Self::Value, Error> {
        self.parse(cmd, arg, value.to_os_string())
    }

    fn parse(
        &self,
        _cmd: &Command,
        _arg: Option<&Arg>,
        value: OsString,
    ) -> Result<Self::Value, Error> {
        Ok(RuntimeArg::parse(&value.to_string_lossy()))
    }
}