Skip to main content

hx_toolchain/
check.rs

1//! Toolchain version checking and auto-installation.
2
3use crate::detect::{ToolStatus, Toolchain};
4use crate::install::{self, SmartCabalInstallOptions, SmartInstallOptions};
5use hx_core::{Error, Fix, Result, Version};
6use std::io::{self, IsTerminal, Write};
7use tracing::info;
8
9/// Result of checking toolchain requirements.
10#[derive(Debug, Clone)]
11pub struct ToolchainCheck {
12    /// GHC version mismatch (expected, found)
13    pub ghc_mismatch: Option<(String, Option<String>)>,
14    /// Cabal version mismatch (expected, found)
15    pub cabal_mismatch: Option<(String, Option<String>)>,
16    /// Whether ghcup is available (for fallback)
17    pub has_ghcup: bool,
18}
19
20impl ToolchainCheck {
21    /// Check if there are any mismatches.
22    pub fn has_mismatch(&self) -> bool {
23        self.ghc_mismatch.is_some() || self.cabal_mismatch.is_some()
24    }
25
26    /// Check if mismatches can be auto-fixed.
27    ///
28    /// We can always auto-fix via direct download, ghcup is optional fallback.
29    pub fn can_auto_fix(&self) -> bool {
30        self.has_mismatch()
31    }
32
33    /// Get a description of the mismatches.
34    pub fn mismatch_summary(&self) -> String {
35        let mut parts = Vec::new();
36
37        if let Some((expected, found)) = &self.ghc_mismatch {
38            let found_str = found
39                .as_ref()
40                .map(|v| v.as_str())
41                .unwrap_or("not installed");
42            parts.push(format!("GHC {} (found: {})", expected, found_str));
43        }
44
45        if let Some((expected, found)) = &self.cabal_mismatch {
46            let found_str = found
47                .as_ref()
48                .map(|v| v.as_str())
49                .unwrap_or("not installed");
50            parts.push(format!("Cabal {} (found: {})", expected, found_str));
51        }
52
53        parts.join(", ")
54    }
55}
56
57/// Check toolchain requirements against detected versions.
58pub fn check_requirements(
59    toolchain: &Toolchain,
60    required_ghc: Option<&str>,
61    required_cabal: Option<&str>,
62) -> ToolchainCheck {
63    let ghc_mismatch = required_ghc.and_then(|required| {
64        check_version_match(&toolchain.ghc.status, required)
65            .map(|found| (required.to_string(), found))
66    });
67
68    let cabal_mismatch = required_cabal.and_then(|required| {
69        check_version_match(&toolchain.cabal.status, required)
70            .map(|found| (required.to_string(), found))
71    });
72
73    ToolchainCheck {
74        ghc_mismatch,
75        cabal_mismatch,
76        has_ghcup: toolchain.has_ghcup(),
77    }
78}
79
80/// Check if a tool version matches the requirement.
81/// Returns Some(found_version) if there's a mismatch, None if it matches.
82fn check_version_match(status: &ToolStatus, required: &str) -> Option<Option<String>> {
83    match status {
84        ToolStatus::Found { version, .. } => {
85            // Parse required version
86            let required_ver: Version = required.parse().ok()?;
87
88            // Check if major.minor match, and patch if specified in required
89            // If required is "9.8" (patch=0), match any 9.8.x
90            // If required is "9.8.2", match exactly 9.8.2
91            let patch_matches = if required.matches('.').count() < 2 {
92                // Only major.minor specified (e.g., "9.8")
93                true
94            } else {
95                version.patch == required_ver.patch
96            };
97
98            if version.major == required_ver.major
99                && version.minor == required_ver.minor
100                && patch_matches
101            {
102                None // Matches
103            } else {
104                Some(Some(version.to_string())) // Mismatch
105            }
106        }
107        ToolStatus::NotFound => Some(None), // Not installed
108        ToolStatus::VersionUnknown { .. } => None, // Can't check, assume ok
109    }
110}
111
112/// Policy for auto-installation.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
114pub enum AutoInstallPolicy {
115    /// Never auto-install, just warn
116    Never,
117    /// Prompt the user for confirmation
118    #[default]
119    Prompt,
120    /// Automatically install without prompting
121    Always,
122}
123
124/// Ensure the toolchain matches requirements, optionally installing missing versions.
125///
126/// When `required_ghc` or `required_cabal` are specified (from hx.toml), the effective
127/// policy defaults to `Always` unless explicitly set to `Never`. This enables seamless
128/// project-specific toolchain bootstrapping - just `hx build` in a project with hx.toml
129/// and the correct toolchain versions will be downloaded automatically.
130pub async fn ensure_toolchain(
131    toolchain: &Toolchain,
132    required_ghc: Option<&str>,
133    required_cabal: Option<&str>,
134    policy: AutoInstallPolicy,
135) -> Result<()> {
136    let check = check_requirements(toolchain, required_ghc, required_cabal);
137
138    if !check.has_mismatch() {
139        return Ok(());
140    }
141
142    info!("Toolchain mismatch detected: {}", check.mismatch_summary());
143
144    // If project specifies versions, default to auto-install
145    // This enables seamless bootstrapping: `hx build` just works
146    let effective_policy = if required_ghc.is_some() || required_cabal.is_some() {
147        match policy {
148            AutoInstallPolicy::Never => AutoInstallPolicy::Never,
149            _ => AutoInstallPolicy::Always,
150        }
151    } else {
152        policy
153    };
154
155    match effective_policy {
156        AutoInstallPolicy::Never => {
157            return Err(Error::ToolchainMismatch {
158                tool: "toolchain".to_string(),
159                expected: check.mismatch_summary(),
160                found: "auto-install disabled".to_string(),
161                fixes: build_install_fixes(&check),
162            });
163        }
164        AutoInstallPolicy::Prompt => {
165            if !confirm_install(&check)? {
166                return Err(Error::ToolchainMismatch {
167                    tool: "toolchain".to_string(),
168                    expected: check.mismatch_summary(),
169                    found: "installation declined".to_string(),
170                    fixes: build_install_fixes(&check),
171                });
172            }
173        }
174        AutoInstallPolicy::Always => {
175            // Proceed with installation
176        }
177    }
178
179    // Install missing/mismatched tools using smart installation
180    // This tries direct download first, then falls back to ghcup
181    if let Some((version, _)) = &check.ghc_mismatch {
182        let options = SmartInstallOptions::new(version).with_set_active(true);
183        install::install_ghc_smart(&options).await?;
184    }
185
186    if let Some((version, _)) = &check.cabal_mismatch {
187        let options = SmartCabalInstallOptions::new(version).with_set_active(true);
188        install::install_cabal_smart(&options).await?;
189    }
190
191    Ok(())
192}
193
194/// Build fix suggestions for a toolchain check.
195fn build_install_fixes(check: &ToolchainCheck) -> Vec<Fix> {
196    let mut fixes = Vec::new();
197
198    if let Some((version, _)) = &check.ghc_mismatch {
199        fixes.push(Fix::with_command(
200            format!("Install GHC {}", version),
201            format!("hx toolchain install --ghc {}", version),
202        ));
203    }
204
205    if let Some((version, _)) = &check.cabal_mismatch {
206        fixes.push(Fix::with_command(
207            format!("Install Cabal {}", version),
208            format!("hx toolchain install --cabal {}", version),
209        ));
210    }
211
212    fixes
213}
214
215/// Prompt the user to confirm installation.
216fn confirm_install(check: &ToolchainCheck) -> Result<bool> {
217    // Check if we're in a non-interactive environment
218    if std::env::var("CI").is_ok() || !io::stdin().is_terminal() {
219        // Non-interactive: don't prompt, just fail
220        return Ok(false);
221    }
222
223    eprint!(
224        "\nToolchain mismatch: {}\nInstall missing toolchain components? [Y/n] ",
225        check.mismatch_summary()
226    );
227    io::stderr().flush().map_err(|e| Error::Io {
228        message: "failed to flush stderr".to_string(),
229        path: None,
230        source: e,
231    })?;
232
233    let mut input = String::new();
234    io::stdin().read_line(&mut input).map_err(|e| Error::Io {
235        message: "failed to read input".to_string(),
236        path: None,
237        source: e,
238    })?;
239
240    let input = input.trim().to_lowercase();
241    Ok(input.is_empty() || input == "y" || input == "yes")
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    use crate::detect::DetectedTool;
248    use std::path::PathBuf;
249
250    fn make_tool(name: &str, version: Option<&str>) -> DetectedTool {
251        let status = match version {
252            Some(v) => ToolStatus::Found {
253                version: v.parse().unwrap(),
254                path: PathBuf::from("/usr/bin").join(name),
255            },
256            None => ToolStatus::NotFound,
257        };
258        DetectedTool {
259            name: name.to_string(),
260            status,
261            source: None,
262        }
263    }
264
265    #[test]
266    fn test_check_requirements_match() {
267        let toolchain = Toolchain {
268            ghc: make_tool("ghc", Some("9.8.2")),
269            cabal: make_tool("cabal", Some("3.12.1.0")),
270            ghcup: make_tool("ghcup", Some("0.1.30.0")),
271            hls: make_tool("hls", Some("2.9.0.0")),
272        };
273
274        let check = check_requirements(&toolchain, Some("9.8.2"), Some("3.12.1.0"));
275        assert!(!check.has_mismatch());
276    }
277
278    #[test]
279    fn test_check_requirements_ghc_mismatch() {
280        let toolchain = Toolchain {
281            ghc: make_tool("ghc", Some("9.6.4")),
282            cabal: make_tool("cabal", Some("3.12.1.0")),
283            ghcup: make_tool("ghcup", Some("0.1.30.0")),
284            hls: make_tool("hls", Some("2.9.0.0")),
285        };
286
287        let check = check_requirements(&toolchain, Some("9.8.2"), None);
288        assert!(check.has_mismatch());
289        assert!(check.ghc_mismatch.is_some());
290        assert!(check.cabal_mismatch.is_none());
291    }
292
293    #[test]
294    fn test_check_requirements_not_installed() {
295        let toolchain = Toolchain {
296            ghc: make_tool("ghc", None),
297            cabal: make_tool("cabal", Some("3.12.1.0")),
298            ghcup: make_tool("ghcup", Some("0.1.30.0")),
299            hls: make_tool("hls", None),
300        };
301
302        let check = check_requirements(&toolchain, Some("9.8.2"), None);
303        assert!(check.has_mismatch());
304        assert!(check.ghc_mismatch.is_some());
305        let (expected, found) = check.ghc_mismatch.unwrap();
306        assert_eq!(expected, "9.8.2");
307        assert!(found.is_none());
308    }
309
310    #[test]
311    fn test_check_requirements_minor_version_mismatch() {
312        let toolchain = Toolchain {
313            ghc: make_tool("ghc", Some("9.8.1")),
314            cabal: make_tool("cabal", Some("3.12.1.0")),
315            ghcup: make_tool("ghcup", Some("0.1.30.0")),
316            hls: make_tool("hls", Some("2.9.0.0")),
317        };
318
319        // 9.8.1 should match 9.8 (no patch specified)
320        let check = check_requirements(&toolchain, Some("9.8"), None);
321        assert!(!check.has_mismatch());
322
323        // 9.8.1 should NOT match 9.8.2 (patch mismatch)
324        let check = check_requirements(&toolchain, Some("9.8.2"), None);
325        assert!(check.has_mismatch());
326    }
327}