Skip to main content

hx_toolchain/ghc/
activate.rs

1//! GHC version activation and resolution.
2//!
3//! Provides utilities for resolving which GHC to use and setting up
4//! the environment for builds.
5
6use crate::ghc::{InstalledGhc, ToolchainManifest};
7use hx_cache::{toolchain_bin_dir, toolchain_dir};
8use hx_core::{Error, Result};
9use std::fs;
10use std::path::{Path, PathBuf};
11use tracing::{debug, info};
12
13/// Source of a resolved GHC version.
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum GhcSource {
16    /// GHC installed by hx (in ~/.hx/toolchains).
17    HxManaged,
18    /// GHC from ghcup.
19    Ghcup,
20    /// GHC from system PATH.
21    System,
22}
23
24/// A resolved GHC installation.
25#[derive(Debug, Clone)]
26pub struct ResolvedGhc {
27    /// Version string.
28    pub version: String,
29    /// Path to the bin directory containing ghc.
30    pub bin_dir: PathBuf,
31    /// Source of this GHC.
32    pub source: GhcSource,
33}
34
35impl ResolvedGhc {
36    /// Get the path to the ghc binary.
37    pub fn ghc_path(&self) -> PathBuf {
38        self.bin_dir.join(ghc_binary_name())
39    }
40
41    /// Get the path to ghc-pkg.
42    pub fn ghc_pkg_path(&self) -> PathBuf {
43        self.bin_dir.join(ghc_pkg_binary_name())
44    }
45}
46
47/// Version resolution priority.
48#[derive(Debug, Clone, Default)]
49pub struct ResolutionConfig {
50    /// Explicit version from CLI flag.
51    pub cli_version: Option<String>,
52    /// Version from project hx.toml.
53    pub project_version: Option<String>,
54}
55
56/// Resolve which GHC to use based on priority:
57/// 1. CLI flag version
58/// 2. Project hx.toml version
59/// 3. hx-managed active version
60/// 4. System PATH
61pub fn resolve_ghc(config: &ResolutionConfig) -> Result<Option<ResolvedGhc>> {
62    let tc_dir = toolchain_dir()?;
63
64    // Check CLI override first
65    if let Some(ref version) = config.cli_version {
66        debug!("Resolving GHC from CLI flag: {}", version);
67        if let Some(resolved) = resolve_version_from_hx(version, &tc_dir)? {
68            return Ok(Some(resolved));
69        }
70        // CLI flag specified but version not found in hx-managed
71        return Err(Error::config(format!(
72            "GHC {} not found. Install with: hx toolchain install {}",
73            version, version
74        )));
75    }
76
77    // Check project config
78    if let Some(ref version) = config.project_version {
79        debug!("Resolving GHC from project config: {}", version);
80        if let Some(resolved) = resolve_version_from_hx(version, &tc_dir)? {
81            return Ok(Some(resolved));
82        }
83        // Project specifies a version but it's not installed
84        return Err(Error::config(format!(
85            "Project requires GHC {} but it's not installed. Install with: hx toolchain install {}",
86            version, version
87        )));
88    }
89
90    // Check hx-managed active version
91    let manifest = ToolchainManifest::load(&tc_dir)?;
92    if let Some(active) = manifest.active() {
93        debug!("Using hx-managed active GHC: {}", active.version);
94        return Ok(Some(ResolvedGhc {
95            version: active.version.clone(),
96            bin_dir: active.bin_dir(),
97            source: GhcSource::HxManaged,
98        }));
99    }
100
101    // Fall back to system PATH
102    if let Some(resolved) = resolve_from_path()? {
103        debug!("Using system GHC: {}", resolved.version);
104        return Ok(Some(resolved));
105    }
106
107    Ok(None)
108}
109
110/// Try to resolve a specific version from hx-managed installations.
111fn resolve_version_from_hx(version: &str, tc_dir: &Path) -> Result<Option<ResolvedGhc>> {
112    let manifest = ToolchainManifest::load(tc_dir)?;
113
114    // Check for exact match
115    if let Some(installed) = manifest.get_ghc(version) {
116        return Ok(Some(ResolvedGhc {
117            version: installed.version.clone(),
118            bin_dir: installed.bin_dir(),
119            source: GhcSource::HxManaged,
120        }));
121    }
122
123    // Check for major.minor match (e.g., "9.8" matches "9.8.2")
124    for installed in &manifest.ghc {
125        if installed.version.starts_with(version)
126            && installed.version.chars().nth(version.len()) == Some('.')
127        {
128            return Ok(Some(ResolvedGhc {
129                version: installed.version.clone(),
130                bin_dir: installed.bin_dir(),
131                source: GhcSource::HxManaged,
132            }));
133        }
134    }
135
136    Ok(None)
137}
138
139/// Try to find GHC in system PATH.
140fn resolve_from_path() -> Result<Option<ResolvedGhc>> {
141    let ghc_path = match which::which("ghc") {
142        Ok(p) => p,
143        Err(_) => return Ok(None),
144    };
145
146    // Get version from ghc --numeric-version
147    let output = std::process::Command::new(&ghc_path)
148        .arg("--numeric-version")
149        .output()
150        .map_err(|e| Error::Io {
151            message: "Failed to run ghc --numeric-version".into(),
152            path: Some(ghc_path.clone()),
153            source: e,
154        })?;
155
156    if !output.status.success() {
157        return Ok(None);
158    }
159
160    let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
161    let bin_dir = ghc_path.parent().unwrap_or(&ghc_path).to_path_buf();
162
163    // Determine source (ghcup or system)
164    let source = if bin_dir.to_string_lossy().contains(".ghcup") {
165        GhcSource::Ghcup
166    } else {
167        GhcSource::System
168    };
169
170    Ok(Some(ResolvedGhc {
171        version,
172        bin_dir,
173        source,
174    }))
175}
176
177/// Get the PATH string with hx-managed GHC bin directory prepended.
178pub fn get_path_with_ghc(ghc: &ResolvedGhc) -> String {
179    let current_path = std::env::var("PATH").unwrap_or_default();
180    let bin_dir = ghc.bin_dir.to_string_lossy();
181
182    #[cfg(windows)]
183    let separator = ";";
184    #[cfg(not(windows))]
185    let separator = ":";
186
187    format!("{}{}{}", bin_dir, separator, current_path)
188}
189
190/// Create symlinks in ~/.hx/bin for the active GHC.
191///
192/// This allows users to add ~/.hx/bin to their PATH for easy access.
193pub fn create_symlinks(ghc: &InstalledGhc) -> Result<()> {
194    let bin_dir = toolchain_bin_dir()?;
195    fs::create_dir_all(&bin_dir).map_err(|e| Error::Io {
196        message: "Failed to create bin directory".into(),
197        path: Some(bin_dir.clone()),
198        source: e,
199    })?;
200
201    let tools = ["ghc", "ghci", "ghc-pkg", "runghc", "runhaskell", "haddock"];
202
203    for tool in tools {
204        let source = ghc.bin_dir().join(tool_binary_name(tool));
205        let target = bin_dir.join(tool_binary_name(tool));
206
207        if source.exists() {
208            // Remove existing symlink/file
209            let _ = fs::remove_file(&target);
210
211            #[cfg(unix)]
212            {
213                std::os::unix::fs::symlink(&source, &target).map_err(|e| Error::Io {
214                    message: format!("Failed to create symlink for {}", tool),
215                    path: Some(target.clone()),
216                    source: e,
217                })?;
218            }
219
220            #[cfg(windows)]
221            {
222                // On Windows, create a .cmd wrapper instead of symlink
223                let content = format!("@echo off\n\"{}\" %*", source.display());
224                let target_cmd = bin_dir.join(format!("{}.cmd", tool));
225                fs::write(&target_cmd, content).map_err(|e| Error::Io {
226                    message: format!("Failed to create wrapper for {}", tool),
227                    path: Some(target_cmd),
228                    source: e,
229                })?;
230            }
231
232            debug!(
233                "Created symlink: {} -> {}",
234                target.display(),
235                source.display()
236            );
237        }
238    }
239
240    info!("Symlinks created in {}", bin_dir.display());
241    Ok(())
242}
243
244/// Remove symlinks from ~/.hx/bin.
245pub fn remove_symlinks() -> Result<()> {
246    let bin_dir = toolchain_bin_dir()?;
247
248    if !bin_dir.exists() {
249        return Ok(());
250    }
251
252    let tools = ["ghc", "ghci", "ghc-pkg", "runghc", "runhaskell", "haddock"];
253
254    for tool in tools {
255        let target = bin_dir.join(tool_binary_name(tool));
256        if target.exists() || target.is_symlink() {
257            let _ = fs::remove_file(&target);
258        }
259
260        #[cfg(windows)]
261        {
262            let target_cmd = bin_dir.join(format!("{}.cmd", tool));
263            let _ = fs::remove_file(&target_cmd);
264        }
265    }
266
267    Ok(())
268}
269
270fn ghc_binary_name() -> &'static str {
271    if cfg!(windows) { "ghc.exe" } else { "ghc" }
272}
273
274fn ghc_pkg_binary_name() -> &'static str {
275    if cfg!(windows) {
276        "ghc-pkg.exe"
277    } else {
278        "ghc-pkg"
279    }
280}
281
282fn tool_binary_name(name: &str) -> String {
283    if cfg!(windows) {
284        format!("{}.exe", name)
285    } else {
286        name.to_string()
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn test_resolution_config_default() {
296        let config = ResolutionConfig::default();
297        assert!(config.cli_version.is_none());
298        assert!(config.project_version.is_none());
299    }
300
301    #[test]
302    fn test_ghc_source_equality() {
303        assert_eq!(GhcSource::HxManaged, GhcSource::HxManaged);
304        assert_ne!(GhcSource::HxManaged, GhcSource::Ghcup);
305    }
306
307    #[test]
308    fn test_resolved_ghc_paths() {
309        let resolved = ResolvedGhc {
310            version: "9.8.2".to_string(),
311            bin_dir: PathBuf::from("/path/to/ghc/bin"),
312            source: GhcSource::HxManaged,
313        };
314
315        let ghc_path = resolved.ghc_path();
316        assert!(ghc_path.ends_with("ghc") || ghc_path.ends_with("ghc.exe"));
317
318        let pkg_path = resolved.ghc_pkg_path();
319        assert!(pkg_path.ends_with("ghc-pkg") || pkg_path.ends_with("ghc-pkg.exe"));
320    }
321
322    #[test]
323    fn test_get_path_with_ghc() {
324        let resolved = ResolvedGhc {
325            version: "9.8.2".to_string(),
326            bin_dir: PathBuf::from("/path/to/ghc/bin"),
327            source: GhcSource::HxManaged,
328        };
329
330        let path = get_path_with_ghc(&resolved);
331        assert!(path.starts_with("/path/to/ghc/bin"));
332    }
333}