hx-toolchain 0.11.0

Toolchain detection and management for hx
Documentation
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Toolchain manifest for tracking installed versions.

use chrono::{DateTime, Utc};
use hx_core::{Error, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use tracing::debug;

/// Manifest tracking installed toolchains.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ToolchainManifest {
    /// Schema version for future compatibility.
    #[serde(default = "default_schema_version")]
    pub schema_version: u32,
    /// Installed GHC versions.
    #[serde(default)]
    pub ghc: Vec<InstalledGhc>,
    /// Currently active GHC version (global default).
    pub active_ghc: Option<String>,
    /// Installed Cabal versions.
    #[serde(default)]
    pub cabal: Vec<InstalledCabal>,
    /// Currently active Cabal version (global default).
    pub active_cabal: Option<String>,
}

fn default_schema_version() -> u32 {
    1
}

/// An installed GHC entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstalledGhc {
    /// Version string (e.g., "9.8.2").
    pub version: String,
    /// Installation path.
    pub install_path: PathBuf,
    /// When this version was installed.
    pub installed_at: DateTime<Utc>,
    /// How the toolchain was installed.
    pub source: InstallSource,
}

/// An installed Cabal entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InstalledCabal {
    /// Version string (e.g., "3.12.1.0").
    pub version: String,
    /// Installation path.
    pub install_path: PathBuf,
    /// When this version was installed.
    pub installed_at: DateTime<Utc>,
    /// How the toolchain was installed.
    pub source: InstallSource,
}

/// How the toolchain was installed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InstallSource {
    /// Direct download from haskell.org via hx.
    Direct,
    /// Installed via ghcup.
    Ghcup,
    /// System package manager or manual installation.
    System,
}

impl std::fmt::Display for InstallSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Direct => write!(f, "hx"),
            Self::Ghcup => write!(f, "ghcup"),
            Self::System => write!(f, "system"),
        }
    }
}

impl ToolchainManifest {
    /// Create a new empty manifest.
    pub fn new() -> Self {
        Self::default()
    }

    /// Load manifest from the toolchain directory.
    ///
    /// Returns an empty manifest if the file doesn't exist.
    pub fn load(toolchain_dir: &Path) -> Result<Self> {
        let manifest_path = toolchain_dir.join("manifest.json");

        if !manifest_path.exists() {
            debug!(
                "No manifest found at {}, using empty",
                manifest_path.display()
            );
            return Ok(Self::new());
        }

        let content = std::fs::read_to_string(&manifest_path).map_err(|e| Error::Io {
            message: format!("Failed to read manifest: {}", e),
            path: Some(manifest_path.clone()),
            source: e,
        })?;

        let manifest: Self = serde_json::from_str(&content).map_err(|e| {
            Error::config(format!(
                "Failed to parse manifest at {}: {}",
                manifest_path.display(),
                e
            ))
        })?;

        Ok(manifest)
    }

    /// Save manifest to the toolchain directory.
    pub fn save(&self, toolchain_dir: &Path) -> Result<()> {
        std::fs::create_dir_all(toolchain_dir).map_err(|e| Error::Io {
            message: format!("Failed to create toolchain directory: {}", e),
            path: Some(toolchain_dir.to_path_buf()),
            source: e,
        })?;

        let manifest_path = toolchain_dir.join("manifest.json");
        let content = serde_json::to_string_pretty(self)
            .map_err(|e| Error::config(format!("Failed to serialize manifest: {}", e)))?;

        std::fs::write(&manifest_path, content).map_err(|e| Error::Io {
            message: format!("Failed to write manifest: {}", e),
            path: Some(manifest_path),
            source: e,
        })?;

        Ok(())
    }

    /// Add an installed GHC version.
    pub fn add_ghc(&mut self, ghc: InstalledGhc) {
        // Remove any existing entry with the same version
        self.ghc.retain(|g| g.version != ghc.version);
        self.ghc.push(ghc);
        // Sort by version (newest first)
        self.ghc.sort_by(|a, b| b.version.cmp(&a.version));
    }

    /// Remove an installed GHC version.
    pub fn remove_ghc(&mut self, version: &str) -> Option<InstalledGhc> {
        if let Some(pos) = self.ghc.iter().position(|g| g.version == version) {
            let removed = self.ghc.remove(pos);
            // Clear active if we removed the active version
            if self.active_ghc.as_deref() == Some(version) {
                self.active_ghc = None;
            }
            Some(removed)
        } else {
            None
        }
    }

    /// Get an installed GHC by version.
    pub fn get_ghc(&self, version: &str) -> Option<&InstalledGhc> {
        self.ghc.iter().find(|g| g.version == version)
    }

    /// Check if a version is installed.
    pub fn is_installed(&self, version: &str) -> bool {
        self.ghc.iter().any(|g| g.version == version)
    }

    /// Get the active GHC installation.
    pub fn active(&self) -> Option<&InstalledGhc> {
        self.active_ghc.as_ref().and_then(|v| self.get_ghc(v))
    }

    /// Set the active GHC version.
    pub fn set_active(&mut self, version: &str) -> Result<()> {
        if !self.is_installed(version) {
            return Err(Error::config(format!("GHC {} is not installed", version)));
        }
        self.active_ghc = Some(version.to_string());
        Ok(())
    }

    /// Get all installed versions.
    pub fn installed_versions(&self) -> Vec<&str> {
        self.ghc.iter().map(|g| g.version.as_str()).collect()
    }

    // ---- Cabal management methods ----

    /// Add an installed Cabal version.
    pub fn add_cabal(&mut self, cabal: InstalledCabal) {
        // Remove any existing entry with the same version
        self.cabal.retain(|c| c.version != cabal.version);
        self.cabal.push(cabal);
        // Sort by version (newest first)
        self.cabal.sort_by(|a, b| b.version.cmp(&a.version));
    }

    /// Remove an installed Cabal version.
    pub fn remove_cabal(&mut self, version: &str) -> Option<InstalledCabal> {
        if let Some(pos) = self.cabal.iter().position(|c| c.version == version) {
            let removed = self.cabal.remove(pos);
            // Clear active if we removed the active version
            if self.active_cabal.as_deref() == Some(version) {
                self.active_cabal = None;
            }
            Some(removed)
        } else {
            None
        }
    }

    /// Get an installed Cabal by version.
    pub fn get_cabal(&self, version: &str) -> Option<&InstalledCabal> {
        self.cabal.iter().find(|c| c.version == version)
    }

    /// Check if a Cabal version is installed.
    pub fn is_cabal_installed(&self, version: &str) -> bool {
        self.cabal.iter().any(|c| c.version == version)
    }

    /// Get the active Cabal installation.
    pub fn active_cabal(&self) -> Option<&InstalledCabal> {
        self.active_cabal.as_ref().and_then(|v| self.get_cabal(v))
    }

    /// Set the active Cabal version.
    pub fn set_active_cabal(&mut self, version: &str) -> Result<()> {
        if !self.is_cabal_installed(version) {
            return Err(Error::config(format!("Cabal {} is not installed", version)));
        }
        self.active_cabal = Some(version.to_string());
        Ok(())
    }

    /// Get all installed Cabal versions.
    pub fn installed_cabal_versions(&self) -> Vec<&str> {
        self.cabal.iter().map(|c| c.version.as_str()).collect()
    }
}

impl InstalledGhc {
    /// Create a new InstalledGhc entry.
    pub fn new(version: impl Into<String>, install_path: impl Into<PathBuf>) -> Self {
        Self {
            version: version.into(),
            install_path: install_path.into(),
            installed_at: Utc::now(),
            source: InstallSource::Direct,
        }
    }

    /// Set the installation source.
    pub fn with_source(mut self, source: InstallSource) -> Self {
        self.source = source;
        self
    }

    /// Get the path to the ghc binary.
    pub fn ghc_path(&self) -> PathBuf {
        self.install_path.join("bin").join(ghc_binary_name())
    }

    /// Get the path to the bin directory.
    pub fn bin_dir(&self) -> PathBuf {
        self.install_path.join("bin")
    }
}

impl InstalledCabal {
    /// Create a new InstalledCabal entry.
    pub fn new(version: impl Into<String>, install_path: impl Into<PathBuf>) -> Self {
        Self {
            version: version.into(),
            install_path: install_path.into(),
            installed_at: Utc::now(),
            source: InstallSource::Direct,
        }
    }

    /// Set the installation source.
    pub fn with_source(mut self, source: InstallSource) -> Self {
        self.source = source;
        self
    }

    /// Get the path to the cabal binary.
    pub fn cabal_path(&self) -> PathBuf {
        self.install_path.join("bin").join(cabal_binary_name())
    }

    /// Get the path to the bin directory.
    pub fn bin_dir(&self) -> PathBuf {
        self.install_path.join("bin")
    }
}

/// Get the GHC binary name for the current platform.
fn ghc_binary_name() -> &'static str {
    if cfg!(windows) { "ghc.exe" } else { "ghc" }
}

/// Get the Cabal binary name for the current platform.
fn cabal_binary_name() -> &'static str {
    if cfg!(windows) { "cabal.exe" } else { "cabal" }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn test_manifest_new() {
        let manifest = ToolchainManifest::new();
        assert!(manifest.ghc.is_empty());
        assert!(manifest.active_ghc.is_none());
    }

    #[test]
    fn test_manifest_add_ghc() {
        let mut manifest = ToolchainManifest::new();
        manifest.add_ghc(InstalledGhc::new("9.8.2", "/path/to/9.8.2"));
        manifest.add_ghc(InstalledGhc::new("9.6.4", "/path/to/9.6.4"));

        assert_eq!(manifest.ghc.len(), 2);
        assert!(manifest.is_installed("9.8.2"));
        assert!(manifest.is_installed("9.6.4"));
    }

    #[test]
    fn test_manifest_remove_ghc() {
        let mut manifest = ToolchainManifest::new();
        manifest.add_ghc(InstalledGhc::new("9.8.2", "/path/to/9.8.2"));
        manifest.active_ghc = Some("9.8.2".to_string());

        let removed = manifest.remove_ghc("9.8.2");
        assert!(removed.is_some());
        assert!(!manifest.is_installed("9.8.2"));
        assert!(manifest.active_ghc.is_none()); // Should be cleared
    }

    #[test]
    fn test_manifest_set_active() {
        let mut manifest = ToolchainManifest::new();
        manifest.add_ghc(InstalledGhc::new("9.8.2", "/path/to/9.8.2"));

        assert!(manifest.set_active("9.8.2").is_ok());
        assert_eq!(manifest.active_ghc, Some("9.8.2".to_string()));

        // Can't set active to non-installed version
        assert!(manifest.set_active("9.6.4").is_err());
    }

    #[test]
    fn test_manifest_save_load() {
        let temp = tempdir().unwrap();
        let toolchain_dir = temp.path();

        let mut manifest = ToolchainManifest::new();
        manifest.add_ghc(InstalledGhc::new("9.8.2", "/path/to/9.8.2"));
        manifest.active_ghc = Some("9.8.2".to_string());

        manifest.save(toolchain_dir).unwrap();

        let loaded = ToolchainManifest::load(toolchain_dir).unwrap();
        assert_eq!(loaded.ghc.len(), 1);
        assert_eq!(loaded.ghc[0].version, "9.8.2");
        assert_eq!(loaded.active_ghc, Some("9.8.2".to_string()));
    }

    #[test]
    fn test_installed_ghc_paths() {
        let ghc = InstalledGhc::new("9.8.2", "/home/user/.hx/toolchains/ghc/9.8.2");

        let bin_dir = ghc.bin_dir();
        assert!(bin_dir.ends_with("bin"));

        let ghc_path = ghc.ghc_path();
        assert!(ghc_path.ends_with("ghc") || ghc_path.ends_with("ghc.exe"));
    }

    // ---- Cabal tests ----

    #[test]
    fn test_manifest_add_cabal() {
        let mut manifest = ToolchainManifest::new();
        manifest.add_cabal(InstalledCabal::new("3.12.1.0", "/path/to/3.12.1.0"));
        manifest.add_cabal(InstalledCabal::new("3.10.3.0", "/path/to/3.10.3.0"));

        assert_eq!(manifest.cabal.len(), 2);
        assert!(manifest.is_cabal_installed("3.12.1.0"));
        assert!(manifest.is_cabal_installed("3.10.3.0"));
    }

    #[test]
    fn test_manifest_remove_cabal() {
        let mut manifest = ToolchainManifest::new();
        manifest.add_cabal(InstalledCabal::new("3.12.1.0", "/path/to/3.12.1.0"));
        manifest.active_cabal = Some("3.12.1.0".to_string());

        let removed = manifest.remove_cabal("3.12.1.0");
        assert!(removed.is_some());
        assert!(!manifest.is_cabal_installed("3.12.1.0"));
        assert!(manifest.active_cabal.is_none()); // Should be cleared
    }

    #[test]
    fn test_manifest_set_active_cabal() {
        let mut manifest = ToolchainManifest::new();
        manifest.add_cabal(InstalledCabal::new("3.12.1.0", "/path/to/3.12.1.0"));

        assert!(manifest.set_active_cabal("3.12.1.0").is_ok());
        assert_eq!(manifest.active_cabal, Some("3.12.1.0".to_string()));

        // Can't set active to non-installed version
        assert!(manifest.set_active_cabal("3.10.3.0").is_err());
    }

    #[test]
    fn test_installed_cabal_paths() {
        let cabal = InstalledCabal::new("3.12.1.0", "/home/user/.hx/toolchains/cabal/3.12.1.0");

        let bin_dir = cabal.bin_dir();
        assert!(bin_dir.ends_with("bin"));

        let cabal_path = cabal.cabal_path();
        assert!(cabal_path.ends_with("cabal") || cabal_path.ends_with("cabal.exe"));
    }
}