Skip to main content

hx_toolchain/
install.rs

1//! Toolchain installation.
2//!
3//! Provides smart installation that tries direct download first, then falls back to ghcup.
4
5use crate::cabal::{self, CabalDownloadOptions};
6use crate::ghc::{self, DownloadOptions, Platform};
7use hx_cache::toolchain_dir;
8use hx_core::{CommandRunner, Error, Fix, Result};
9use hx_ui::Spinner;
10use tracing::{info, warn};
11
12/// Install GHC via ghcup.
13pub async fn install_ghc(version: &str) -> Result<()> {
14    let runner = CommandRunner::new();
15    let spinner = Spinner::new(format!("Installing GHC {}", version));
16
17    info!("Installing GHC {} via ghcup", version);
18
19    let output = runner.run("ghcup", ["install", "ghc", version]).await?;
20
21    if output.success() {
22        // Set as default
23        let _ = runner.run("ghcup", ["set", "ghc", version]).await;
24        spinner.finish_success(format!("GHC {} installed", version));
25        Ok(())
26    } else {
27        spinner.finish_error(format!("Failed to install GHC {}", version));
28        Err(Error::CommandFailed {
29            command: format!("ghcup install ghc {}", version),
30            exit_code: Some(output.exit_code),
31            stdout: output.stdout,
32            stderr: output.stderr,
33            fixes: vec![],
34        })
35    }
36}
37
38/// Install Cabal via ghcup.
39pub async fn install_cabal(version: &str) -> Result<()> {
40    let runner = CommandRunner::new();
41    let spinner = Spinner::new(format!("Installing Cabal {}", version));
42
43    info!("Installing Cabal {} via ghcup", version);
44
45    let output = runner.run("ghcup", ["install", "cabal", version]).await?;
46
47    if output.success() {
48        let _ = runner.run("ghcup", ["set", "cabal", version]).await;
49        spinner.finish_success(format!("Cabal {} installed", version));
50        Ok(())
51    } else {
52        spinner.finish_error(format!("Failed to install Cabal {}", version));
53        Err(Error::CommandFailed {
54            command: format!("ghcup install cabal {}", version),
55            exit_code: Some(output.exit_code),
56            stdout: output.stdout,
57            stderr: output.stderr,
58            fixes: vec![],
59        })
60    }
61}
62
63/// Install HLS via ghcup.
64pub async fn install_hls(version: &str) -> Result<()> {
65    let runner = CommandRunner::new();
66    let spinner = Spinner::new(format!("Installing HLS {}", version));
67
68    info!("Installing HLS {} via ghcup", version);
69
70    let output = runner.run("ghcup", ["install", "hls", version]).await?;
71
72    if output.success() {
73        let _ = runner.run("ghcup", ["set", "hls", version]).await;
74        spinner.finish_success(format!("HLS {} installed", version));
75        Ok(())
76    } else {
77        spinner.finish_error(format!("Failed to install HLS {}", version));
78        Err(Error::CommandFailed {
79            command: format!("ghcup install hls {}", version),
80            exit_code: Some(output.exit_code),
81            stdout: output.stdout,
82            stderr: output.stderr,
83            fixes: vec![],
84        })
85    }
86}
87
88/// Set GHC version via ghcup (without installing).
89pub async fn set_ghc(version: &str) -> Result<()> {
90    let runner = CommandRunner::new();
91    info!("Setting GHC to {} via ghcup", version);
92
93    let output = runner.run("ghcup", ["set", "ghc", version]).await?;
94
95    if output.success() {
96        Ok(())
97    } else {
98        Err(Error::CommandFailed {
99            command: format!("ghcup set ghc {}", version),
100            exit_code: Some(output.exit_code),
101            stdout: output.stdout,
102            stderr: output.stderr,
103            fixes: vec![Fix::with_command(
104                format!("Install GHC {} first", version),
105                format!("hx toolchain install --ghc {}", version),
106            )],
107        })
108    }
109}
110
111/// Set Cabal version via ghcup (without installing).
112pub async fn set_cabal(version: &str) -> Result<()> {
113    let runner = CommandRunner::new();
114    info!("Setting Cabal to {} via ghcup", version);
115
116    let output = runner.run("ghcup", ["set", "cabal", version]).await?;
117
118    if output.success() {
119        Ok(())
120    } else {
121        Err(Error::CommandFailed {
122            command: format!("ghcup set cabal {}", version),
123            exit_code: Some(output.exit_code),
124            stdout: output.stdout,
125            stderr: output.stderr,
126            fixes: vec![Fix::with_command(
127                format!("Install Cabal {} first", version),
128                format!("hx toolchain install --cabal {}", version),
129            )],
130        })
131    }
132}
133
134/// Set HLS version via ghcup (without installing).
135pub async fn set_hls(version: &str) -> Result<()> {
136    let runner = CommandRunner::new();
137    info!("Setting HLS to {} via ghcup", version);
138
139    let output = runner.run("ghcup", ["set", "hls", version]).await?;
140
141    if output.success() {
142        Ok(())
143    } else {
144        Err(Error::CommandFailed {
145            command: format!("ghcup set hls {}", version),
146            exit_code: Some(output.exit_code),
147            stdout: output.stdout,
148            stderr: output.stderr,
149            fixes: vec![Fix::with_command(
150                format!("Install HLS {} first", version),
151                format!("hx toolchain install --hls {}", version),
152            )],
153        })
154    }
155}
156
157/// Get the ghcup install command for the current platform.
158pub fn ghcup_install_command() -> &'static str {
159    if cfg!(windows) {
160        "Set-ExecutionPolicy Bypass -Scope Process -Force;[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; try { Invoke-Command -ScriptBlock ([ScriptBlock]::Create((Invoke-WebRequest https://www.haskell.org/ghcup/sh/bootstrap-haskell.ps1 -UseBasicParsing))) -ArgumentList $true } catch { Write-Error $_ }"
161    } else {
162        "curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | sh"
163    }
164}
165
166/// Smart GHC installation strategy.
167#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
168pub enum InstallStrategy {
169    /// Try direct download first, fall back to ghcup.
170    #[default]
171    Smart,
172    /// Only use direct download (fail if not available).
173    Direct,
174    /// Only use ghcup.
175    Ghcup,
176}
177
178/// Options for smart GHC installation.
179#[derive(Debug, Clone)]
180pub struct SmartInstallOptions {
181    /// GHC version to install.
182    pub version: String,
183    /// Installation strategy.
184    pub strategy: InstallStrategy,
185    /// Whether to set as active after installation.
186    pub set_active: bool,
187    /// Force reinstall even if already installed.
188    pub force: bool,
189}
190
191impl SmartInstallOptions {
192    /// Create new options for a version.
193    pub fn new(version: impl Into<String>) -> Self {
194        Self {
195            version: version.into(),
196            strategy: InstallStrategy::default(),
197            set_active: false,
198            force: false,
199        }
200    }
201
202    /// Set the installation strategy.
203    pub fn with_strategy(mut self, strategy: InstallStrategy) -> Self {
204        self.strategy = strategy;
205        self
206    }
207
208    /// Set as active after installation.
209    pub fn with_set_active(mut self, set_active: bool) -> Self {
210        self.set_active = set_active;
211        self
212    }
213
214    /// Force reinstall.
215    pub fn with_force(mut self, force: bool) -> Self {
216        self.force = force;
217        self
218    }
219}
220
221/// Install GHC using smart strategy: direct download first, fallback to ghcup.
222///
223/// This is the preferred method for installing GHC as it:
224/// 1. Tries direct download from downloads.haskell.org (faster, no ghcup dependency)
225/// 2. Falls back to ghcup if direct download fails
226///
227/// Use `InstallStrategy::Direct` to disable ghcup fallback.
228/// Use `InstallStrategy::Ghcup` to skip direct download.
229pub async fn install_ghc_smart(options: &SmartInstallOptions) -> Result<()> {
230    match options.strategy {
231        InstallStrategy::Direct => install_ghc_direct(options).await,
232        InstallStrategy::Ghcup => install_ghc(&options.version).await,
233        InstallStrategy::Smart => {
234            // Check if platform is supported for direct download
235            if Platform::current().is_none() {
236                info!("Platform not supported for direct download, using ghcup");
237                return install_ghc(&options.version).await;
238            }
239
240            // Try direct download first
241            match install_ghc_direct(options).await {
242                Ok(()) => Ok(()),
243                Err(e) => {
244                    warn!(
245                        "Direct GHC installation failed, falling back to ghcup: {}",
246                        e
247                    );
248                    install_ghc(&options.version).await
249                }
250            }
251        }
252    }
253}
254
255/// Install GHC via direct download.
256async fn install_ghc_direct(options: &SmartInstallOptions) -> Result<()> {
257    let tc_dir = toolchain_dir()?;
258
259    let download_options = DownloadOptions {
260        version: options.version.clone(),
261        platform: Platform::current(),
262        toolchain_dir: tc_dir,
263        set_active: options.set_active,
264        force: options.force,
265        ..Default::default()
266    };
267
268    let result = ghc::download_and_install_ghc(&download_options).await?;
269
270    if result.was_cached {
271        info!("GHC {} was already installed", options.version);
272    } else {
273        info!("GHC {} installed successfully", options.version);
274    }
275
276    Ok(())
277}
278
279/// Options for smart Cabal installation.
280#[derive(Debug, Clone)]
281pub struct SmartCabalInstallOptions {
282    /// Cabal version to install.
283    pub version: String,
284    /// Installation strategy.
285    pub strategy: InstallStrategy,
286    /// Whether to set as active after installation.
287    pub set_active: bool,
288    /// Force reinstall even if already installed.
289    pub force: bool,
290}
291
292impl SmartCabalInstallOptions {
293    /// Create new options for a version.
294    pub fn new(version: impl Into<String>) -> Self {
295        Self {
296            version: version.into(),
297            strategy: InstallStrategy::default(),
298            set_active: false,
299            force: false,
300        }
301    }
302
303    /// Set the installation strategy.
304    pub fn with_strategy(mut self, strategy: InstallStrategy) -> Self {
305        self.strategy = strategy;
306        self
307    }
308
309    /// Set as active after installation.
310    pub fn with_set_active(mut self, set_active: bool) -> Self {
311        self.set_active = set_active;
312        self
313    }
314
315    /// Force reinstall.
316    pub fn with_force(mut self, force: bool) -> Self {
317        self.force = force;
318        self
319    }
320}
321
322/// Install Cabal using smart strategy: direct download first, fallback to ghcup.
323///
324/// This is the preferred method for installing Cabal as it:
325/// 1. Tries direct download from downloads.haskell.org (faster, no ghcup dependency)
326/// 2. Falls back to ghcup if direct download fails
327///
328/// Use `InstallStrategy::Direct` to disable ghcup fallback.
329/// Use `InstallStrategy::Ghcup` to skip direct download.
330pub async fn install_cabal_smart(options: &SmartCabalInstallOptions) -> Result<()> {
331    match options.strategy {
332        InstallStrategy::Direct => install_cabal_direct(options).await,
333        InstallStrategy::Ghcup => install_cabal(&options.version).await,
334        InstallStrategy::Smart => {
335            // Check if platform is supported for direct download
336            if Platform::current().is_none() {
337                info!("Platform not supported for direct download, using ghcup");
338                return install_cabal(&options.version).await;
339            }
340
341            // Try direct download first
342            match install_cabal_direct(options).await {
343                Ok(()) => Ok(()),
344                Err(e) => {
345                    warn!(
346                        "Direct Cabal installation failed, falling back to ghcup: {}",
347                        e
348                    );
349                    install_cabal(&options.version).await
350                }
351            }
352        }
353    }
354}
355
356/// Install Cabal via direct download.
357async fn install_cabal_direct(options: &SmartCabalInstallOptions) -> Result<()> {
358    let tc_dir = toolchain_dir()?;
359
360    let download_options = CabalDownloadOptions {
361        version: options.version.clone(),
362        platform: Platform::current(),
363        toolchain_dir: tc_dir,
364        set_active: options.set_active,
365        force: options.force,
366        ..Default::default()
367    };
368
369    let result = cabal::download_and_install_cabal(&download_options).await?;
370
371    if result.was_cached {
372        info!("Cabal {} was already installed", options.version);
373    } else {
374        info!("Cabal {} installed successfully", options.version);
375    }
376
377    Ok(())
378}