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
#![allow(clippy::borrowed_box)]

use crate::errors::ProtoError;
use crate::helpers::{is_alias_name, remove_v_prefix};
use crate::manifest::{Manifest, MANIFEST_NAME};
use crate::tool::Tool;
use crate::tools_config::{ToolsConfig, TOOLS_CONFIG_NAME};
use human_sort::compare;
use lenient_semver::Version;
use starbase_utils::fs;
use std::{env, path::Path};
use tracing::debug;

#[async_trait::async_trait]
pub trait Detector<'tool>: Send + Sync {
    /// Attempt to detect an applicable version from the provided working directory.
    async fn detect_version_from(&self, _working_dir: &Path) -> Result<Option<String>, ProtoError> {
        Ok(None)
    }
}

pub fn load_version_file(path: &Path) -> Result<String, ProtoError> {
    Ok(fs::read_file(path)?.trim().to_owned())
}

#[tracing::instrument(skip_all)]
pub async fn detect_version<'l, T: Tool<'l> + ?Sized>(
    tool: &Box<T>,
    forced_version: Option<String>,
) -> Result<String, ProtoError> {
    let mut version = forced_version;
    let env_var = format!("PROTO_{}_VERSION", tool.get_id().to_uppercase());

    // Env var takes highest priority
    if version.is_none() {
        if let Ok(session_version) = env::var(&env_var) {
            debug!(
                env_var,
                version = session_version,
                "Detected version from environment variable",
            );

            version = Some(session_version);
        }
    } else {
        debug!(
            version = version.as_ref().unwrap(),
            "Using explicit version passed on the command line",
        );
    }

    // Traverse upwards and attempt to detect a local version
    if let Ok(working_dir) = env::current_dir() {
        debug!("Attempting to find local version");

        let mut current_dir: Option<&Path> = Some(&working_dir);

        while let Some(dir) = &current_dir {
            debug!(dir = %dir.display(), "Checking in directory");

            // We already found a version, so exit
            if version.is_some() {
                break;
            }

            // Detect from our config file
            debug!("Checking proto configuration file ({})", TOOLS_CONFIG_NAME);

            let config = ToolsConfig::load_from(dir)?;

            if let Some(local_version) = config.tools.get(tool.get_id()) {
                debug!(
                    version = local_version,
                    file = %config.path.display(),
                    "Detected version from configuration file",
                );

                version = Some(local_version.to_owned());
                break;
            }

            // Detect using the tool
            debug!("Detecting from the tool's ecosystem");

            if let Some(eco_version) = tool.detect_version_from(dir).await? {
                if let Some(eco_version) =
                    expand_detected_version(&eco_version, tool.get_manifest()?)?
                {
                    debug!(
                        version = eco_version,
                        "Detected version from tool's ecosystem"
                    );

                    version = Some(eco_version);
                    break;
                }
            }

            current_dir = dir.parent();
        }
    }

    // If still no version, load the global version
    if version.is_none() {
        debug!(
            "Attempting to find global version in manifest ({})",
            MANIFEST_NAME
        );

        let manifest = tool.get_manifest()?;

        if let Some(global_version) = &manifest.default_version {
            debug!(
                version = global_version,
                file = %manifest.path.display(),
                "Detected global version from manifest",
            );

            version = Some(global_version.to_owned());
        }
    }

    // We didn't find anything!
    match version {
        Some(ver) => Ok(ver),
        None => Err(ProtoError::VersionDetectFailed(tool.get_id().to_owned())),
    }
}

#[tracing::instrument(skip_all)]
pub fn expand_detected_version(
    version: &str,
    manifest: &Manifest,
) -> Result<Option<String>, ProtoError> {
    if is_alias_name(version) {
        return Ok(Some(version.to_owned()));
    }

    let version = remove_v_prefix(&version.replace(".*", ""));
    let mut fully_qualified = false;
    let mut maybe_version = String::new();

    // Sort the installed versions in descending order, so that v20
    // is preferred over v2, and v19 for a requirement like >=15.
    let mut installed_versions = manifest
        .installed_versions
        .iter()
        .map(|v| v.to_owned())
        .collect::<Vec<String>>();

    installed_versions.sort_by(|a, d| compare(d, a));

    let mut check_manifest = |check_version: String| -> Result<bool, ProtoError> {
        let req =
            semver::VersionReq::parse(&check_version).map_err(|error| ProtoError::Semver {
                version: check_version.to_owned(),
                error,
            })?;

        for installed_version in &installed_versions {
            let version_inst =
                semver::Version::parse(installed_version).map_err(|error| ProtoError::Semver {
                    version: installed_version.to_owned(),
                    error,
                })?;

            if req.matches(&version_inst) {
                fully_qualified = true;
                maybe_version = installed_version.to_owned();

                return Ok(true);
            }
        }

        Ok(false)
    };

    // ^18 || ^20
    if version.contains("||") {
        for split_version in version.split("||") {
            if let Some(matched_version) = expand_detected_version(split_version.trim(), manifest)?
            {
                return Ok(Some(matched_version));
            }
        }

        // >=18, <20
    } else if version.contains(", ") {
        check_manifest(version.clone())?;

        // >=18 <20
    } else if version.contains(' ') {
        // Node.js doesn't require the comma, but Rust does
        check_manifest(version.replace(' ', ", "))?;

        // ^18, ~17, >16, ...
    } else {
        match &version[0..1] {
            "^" | "~" | ">" | "<" | "*" => {
                check_manifest(version.clone())?;
            }
            "=" => {
                maybe_version = version[1..].to_owned();
            }
            _ => {
                // Only use an exact match when fully qualified,
                // otherwise check the manifest against the partial.
                let dot_count = version.match_indices('.').collect::<Vec<_>>().len();

                if dot_count == 2 || !check_manifest(format!("^{version}"))? {
                    maybe_version = version.clone();
                }
            }
        };
    }

    if maybe_version.is_empty() {
        if version == "*" {
            return Ok(Some("latest".to_owned()));
        }

        return Ok(None);
    }

    let semver = Version::parse(&maybe_version).map_err(|e| ProtoError::Message(e.to_string()))?;

    let version_parts = version.split('.').collect::<Vec<_>>();
    let mut matched_version = semver.major.to_string();

    if version_parts.get(1).is_some() || fully_qualified {
        matched_version = format!("{matched_version}.{}", semver.minor);

        if version_parts.get(2).is_some() || fully_qualified {
            matched_version = format!("{matched_version}.{}", semver.patch);
        }
    }

    Ok(Some(matched_version))
}