1use 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#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum GhcSource {
16 HxManaged,
18 Ghcup,
20 System,
22}
23
24#[derive(Debug, Clone)]
26pub struct ResolvedGhc {
27 pub version: String,
29 pub bin_dir: PathBuf,
31 pub source: GhcSource,
33}
34
35impl ResolvedGhc {
36 pub fn ghc_path(&self) -> PathBuf {
38 self.bin_dir.join(ghc_binary_name())
39 }
40
41 pub fn ghc_pkg_path(&self) -> PathBuf {
43 self.bin_dir.join(ghc_pkg_binary_name())
44 }
45}
46
47#[derive(Debug, Clone, Default)]
49pub struct ResolutionConfig {
50 pub cli_version: Option<String>,
52 pub project_version: Option<String>,
54}
55
56pub fn resolve_ghc(config: &ResolutionConfig) -> Result<Option<ResolvedGhc>> {
62 let tc_dir = toolchain_dir()?;
63
64 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 return Err(Error::config(format!(
72 "GHC {} not found. Install with: hx toolchain install {}",
73 version, version
74 )));
75 }
76
77 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 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 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 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
110fn resolve_version_from_hx(version: &str, tc_dir: &Path) -> Result<Option<ResolvedGhc>> {
112 let manifest = ToolchainManifest::load(tc_dir)?;
113
114 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 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
139fn 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 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 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
177pub 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
190pub 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 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 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
244pub 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}