zv 0.4.0

Ziglang Version Manager and Project Starter
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! These models represent the runtime layer of the three-layer architecture:
//! 1. Network Layer (NetworkZigIndex, NetworkZigRelease, NetworkArtifact) - for JSON deserialization
//! 2. Runtime Layer (ZigIndex, ZigRelease, ArtifactInfo) - for in-memory operations
//! 3. Cache Layer (CacheZigIndex, CacheZigRelease, CacheArtifact) - for TOML serialization

use crate::app::INDEX_TTL_DAYS;
use crate::app::utils::host_target;
use crate::types::{ResolvedZigVersion, TargetTriple};
use chrono::{DateTime, Utc};
use serde::{
    Deserialize, Deserializer, Serialize,
    de::{self, MapAccess, Visitor},
};
use std::collections::{BTreeMap, HashMap};
use std::fmt;

/// Raw JSON representation from ziglang.org
#[derive(Debug, Deserialize)]
pub struct NetworkZigIndex {
    #[serde(flatten)]
    pub releases: HashMap<String, NetworkZigRelease>,
}

/// Represents a Zig release from the network JSON
#[derive(Debug)]
pub struct NetworkZigRelease {
    pub date: String,
    pub version: Option<String>, // Only present for master
    pub targets: HashMap<String, NetworkArtifact>,
}

/// Represents a download artifact from the network JSON
#[derive(Debug, Deserialize)]
pub struct NetworkArtifact {
    #[serde(rename = "tarball")]
    pub ziglang_org_tarball: String,
    pub shasum: String,
    #[serde(deserialize_with = "deserialize_str_to_u64")]
    pub size: u64,
}

/// Custom deserializer to convert string to u64 for size field
fn deserialize_str_to_u64<'de, D>(deserializer: D) -> Result<u64, D::Error>
where
    D: Deserializer<'de>,
{
    let s: String = String::deserialize(deserializer)?;
    s.parse::<u64>().map_err(de::Error::custom)
}

impl<'de> Deserialize<'de> for NetworkZigRelease {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct NetworkZigReleaseVisitor;

        impl<'de> Visitor<'de> for NetworkZigReleaseVisitor {
            type Value = NetworkZigRelease;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a NetworkZigRelease object")
            }

            fn visit_map<V>(self, mut map: V) -> Result<NetworkZigRelease, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut date = None;
                let mut version = None;
                let mut targets = HashMap::new();

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "date" => {
                            date = Some(map.next_value()?);
                        }
                        "version" => {
                            // Capture version field if present (for master)
                            version = Some(map.next_value()?);
                        }
                        // Skip documentation, bootstrap, source, and other non-platform fields
                        "docs" | "stdDocs" | "langRef" | "notes" | "bootstrap" | "src" => {
                            let _: serde_json::Value = map.next_value()?;
                        }
                        // Everything else should be a platform target
                        _ => {
                            // Try to deserialize as NetworkArtifact, skip if it fails
                            match map.next_value::<NetworkArtifact>() {
                                Ok(artifact) => {
                                    targets.insert(key, artifact);
                                }
                                Err(_) => {
                                    // Skip fields that don't deserialize as NetworkArtifact
                                    // This handles cases where the value is a string or other type
                                }
                            }
                        }
                    }
                }

                let date = date.ok_or_else(|| de::Error::missing_field("date"))?;

                Ok(NetworkZigRelease {
                    date,
                    version,
                    targets,
                })
            }
        }

        deserializer.deserialize_map(NetworkZigReleaseVisitor)
    }
}

// ============================================================================
// Cache Layer Models for TOML Serialization
// ============================================================================

/// Simplified TOML representation of the Zig index for local caching
#[derive(Debug, Serialize, Deserialize)]
pub struct CacheZigIndex {
    /// List of releases using array structure for clean TOML output
    pub releases: Vec<CacheZigRelease>,
    /// Timestamp of when this index was last synced
    pub last_synced: Option<DateTime<Utc>>,
}

/// Simplified TOML representation of a Zig release
#[derive(Debug, Serialize, Deserialize)]
pub struct CacheZigRelease {
    /// Version string (e.g., "0.11.0", "master")
    pub version: String,
    /// Release date
    pub date: String,
    /// List of artifacts using array structure for clean TOML output
    pub artifacts: Vec<CacheArtifact>,
}

/// Simplified TOML representation of a download artifact
#[derive(Debug, Serialize, Deserialize)]
pub struct CacheArtifact {
    /// Target triple in "arch-os" format
    pub target: String,
    /// Tarball download URL
    pub tarball_url: String,
    /// SHA-256 checksum
    pub shasum: String,
    /// Size in bytes
    pub size: u64,
}

/// Clean artifact data optimized for runtime operations
#[derive(Debug, Clone)]
pub struct ArtifactInfo {
    /// Tarball download URL from ziglang.org
    pub ziglang_org_tarball: String,
    /// SHA-256 checksum
    pub shasum: String,
    /// Size in bytes
    pub size: u64,
}

/// Runtime representation of a Zig release optimized for fast lookups
#[derive(Debug, Clone)]
pub struct ZigRelease {
    /// Version information
    version: ResolvedZigVersion,
    /// Release date
    date: String,
    /// Map of target triples to artifact information
    artifacts: HashMap<TargetTriple, ArtifactInfo>,
}

impl ZigRelease {
    /// Is the version a master variant?
    pub fn is_master(&self) -> bool {
        self.version.is_master()
    }
    /// Create a new ZigRelease
    pub fn new(
        version: ResolvedZigVersion,
        date: String,
        artifacts: HashMap<TargetTriple, ArtifactInfo>,
    ) -> Self {
        Self {
            version,
            date,
            artifacts,
        }
    }

    /// Get the version of this release
    pub fn resolved_version(&self) -> &ResolvedZigVersion {
        &self.version
    }

    /// Get the release date
    pub fn date(&self) -> &str {
        &self.date
    }

    /// Get all available artifacts
    pub fn artifacts(&self) -> &HashMap<TargetTriple, ArtifactInfo> {
        &self.artifacts
    }

    /// Generate tarball URL for the current host system
    /// Returns None if the target is not supported or no artifact is available
    pub fn zig_tarball_for_current_host(&self) -> Option<String> {
        let host_target_str = host_target()?;
        let target_triple = TargetTriple::from_key(&host_target_str)?;
        self.zig_tarball_for_target(&target_triple)
    }

    /// Generate tarball URL for a specific target
    /// Returns None if the target is not supported or no artifact is available
    pub fn zig_tarball_for_target(&self, target: &TargetTriple) -> Option<String> {
        // Check if we have an artifact for this target
        if !self.artifacts.contains_key(target) {
            return None;
        }

        // Extract semver::Version from our ResolvedZigVersion
        let semver_version = match &self.version {
            ResolvedZigVersion::Semver(v) => v,
            ResolvedZigVersion::Master(v) => v,
        };

        // Generate tarball name for the specific target
        // Use the same logic as zig_tarball but with the provided target
        self.zig_tarball_for_target_and_version(&target.arch, &target.os, semver_version)
    }

    /// Helper function to generate tarball name for a specific arch, os, and version
    /// This follows the same logic as the existing zig_tarball utility but for arbitrary targets
    fn zig_tarball_for_target_and_version(
        &self,
        arch: &str,
        os: &str,
        semver_version: &semver::Version,
    ) -> Option<String> {
        // Determine the appropriate file extension based on the OS
        let ext = if os == "windows" { "zip" } else { "tar.xz" };

        // Handle the naming convention change in Zig 0.14.1
        if semver_version.le(&semver::Version::new(0, 14, 0)) {
            Some(format!("zig-{os}-{arch}-{semver_version}.{ext}"))
        } else {
            Some(format!("zig-{arch}-{os}-{semver_version}.{ext}"))
        }
    }
}

/// Runtime representation of the Zig index optimized for fast lookups
#[derive(Debug, Clone)]
pub struct ZigIndex {
    /// Map of versions to releases, sorted by version
    releases: BTreeMap<ResolvedZigVersion, ZigRelease>,
    /// Timestamp of when this index was last synced
    last_synced: Option<DateTime<Utc>>,
}

impl ZigIndex {
    /// Create a new empty ZigIndex
    pub fn new() -> Self {
        Self {
            releases: BTreeMap::new(),
            last_synced: None,
        }
    }

    /// Create a new ZigIndex with releases and sync timestamp
    pub fn with_releases(
        releases: BTreeMap<ResolvedZigVersion, ZigRelease>,
        last_synced: Option<DateTime<Utc>>,
    ) -> Self {
        Self {
            releases,
            last_synced,
        }
    }

    /// Get all releases
    pub fn releases(&self) -> &BTreeMap<ResolvedZigVersion, ZigRelease> {
        &self.releases
    }

    /// Get the last sync timestamp
    pub fn last_synced(&self) -> Option<DateTime<Utc>> {
        self.last_synced
    }

    /// Get the latest stable version
    /// Returns the highest semantic version that is not a pre-release
    pub fn get_latest_stable(&self) -> Option<&ResolvedZigVersion> {
        self.releases
            .keys()
            .rev() // Start from highest versions
            .find(|version| {
                match version {
                    ResolvedZigVersion::Semver(v) => {
                        // Only consider stable releases (no pre-release or build metadata)
                        v.pre.is_empty() && v.build.is_empty()
                    }
                    _ => false, // Master variants are not considered stable
                }
            })
    }
}

// Backward compatibility wrapper for ZigIndex
impl ZigIndex {
    /// Check if a semver is in index (backward compatibility)
    pub fn contains_version(&self, version: &semver::Version) -> Option<&ZigRelease> {
        let resolved_version = ResolvedZigVersion::Semver(version.clone());
        self.releases().get(&resolved_version)
    }

    /// Get the latest stable release version (backward compatibility)
    pub fn get_latest_stable_release(&self) -> Option<&ZigRelease> {
        if let Some(latest_version) = self.get_latest_stable() {
            self.releases().get(latest_version)
        } else {
            None
        }
    }

    /// Get master version info (backward compatibility)
    pub fn get_master_version(&self) -> Option<&ZigRelease> {
        // Look for any master version in the index
        for (version, release) in self.releases() {
            if version.is_master() {
                return Some(release);
            }
        }

        None
    }

    /// Cache expired? (backward compatibility)
    pub fn is_expired(&self) -> bool {
        if let Some(last_synced) = self.last_synced() {
            let age = Utc::now() - last_synced;
            age.num_days() >= *INDEX_TTL_DAYS
        } else {
            true // If never synced, consider it expired
        }
    }
    /// Find the highest stable version in the index
    #[allow(unused)]
    fn find_highest_stable_version(&self) -> Option<ResolvedZigVersion> {
        self.releases()
            .keys()
            .filter_map(|resolved_version| {
                match resolved_version {
                    ResolvedZigVersion::Semver(v) => {
                        // Only consider stable releases (no pre-release or build metadata)
                        if v.pre.is_empty() && v.build.is_empty() {
                            Some(resolved_version.clone())
                        } else {
                            None
                        }
                    }
                    // Master variants are not considered stable
                    _ => None,
                }
            })
            .max() // BTreeMap keys are ordered, so max() gives us the highest version
    }
}

impl Default for ZigIndex {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Conversion Methods Between Layers
// ============================================================================

impl From<NetworkZigIndex> for ZigIndex {
    fn from(network_index: NetworkZigIndex) -> Self {
        let mut releases = BTreeMap::new();

        for (version_key, network_release) in network_index.releases {
            // Parse the version key to determine the ResolvedZigVersion
            let resolved_version = if version_key == "master" {
                // For master, use the version field if available
                if let Some(version_str) = &network_release.version {
                    match semver::Version::parse(version_str) {
                        Ok(version) => ResolvedZigVersion::Master(version),
                        Err(err) => {
                            tracing::warn!(
                                "Failed to parse master version: {}, {}",
                                version_str,
                                err
                            );
                            continue; // Skip this release
                        }
                    }
                } else {
                    tracing::warn!("Master release found without concrete version, skipping");
                    continue; // Skip master releases without concrete versions
                }
            } else {
                // Try to parse as semver version
                match semver::Version::parse(&version_key) {
                    Ok(version) => ResolvedZigVersion::Semver(version),
                    Err(err) => {
                        tracing::warn!("Failed to parse version key: {}, {}", version_key, err);
                        continue; // Skip this release
                    }
                }
            };

            // Convert network artifacts to runtime artifacts
            let mut runtime_artifacts = HashMap::new();
            for (target_key, network_artifact) in network_release.targets {
                if let Some(target_triple) = TargetTriple::from_key(&target_key) {
                    let artifact_info = ArtifactInfo {
                        ziglang_org_tarball: network_artifact.ziglang_org_tarball,
                        shasum: network_artifact.shasum,
                        size: network_artifact.size,
                    };
                    runtime_artifacts.insert(target_triple, artifact_info);
                } else {
                    tracing::warn!("Failed to parse target key: {}", target_key);
                }
            }

            let runtime_release = ZigRelease::new(
                resolved_version.clone(),
                network_release.date,
                runtime_artifacts,
            );

            releases.insert(resolved_version, runtime_release);
        }

        ZigIndex::with_releases(releases, Some(chrono::Utc::now()))
    }
}

impl From<&ZigIndex> for CacheZigIndex {
    fn from(runtime_index: &ZigIndex) -> Self {
        let mut cache_releases = Vec::new();

        for (resolved_version, runtime_release) in runtime_index.releases.iter() {
            // Convert ResolvedZigVersion to string for cache storage
            let version_string = match resolved_version {
                ResolvedZigVersion::Semver(v) => v.to_string(),
                ResolvedZigVersion::Master(v) => format!("master@{}", v),
            };

            // Convert runtime artifacts to cache artifacts
            let mut cache_artifacts = Vec::new();
            for (target_triple, artifact_info) in runtime_release.artifacts.iter() {
                let cache_artifact = CacheArtifact {
                    target: target_triple.to_key(),
                    tarball_url: artifact_info.ziglang_org_tarball.clone(),
                    shasum: artifact_info.shasum.clone(),
                    size: artifact_info.size,
                };
                cache_artifacts.push(cache_artifact);
            }

            // Sort artifacts by target for consistent output
            cache_artifacts.sort_by(|a, b| a.target.cmp(&b.target));

            let cache_release = CacheZigRelease {
                version: version_string,
                date: runtime_release.date.clone(),
                artifacts: cache_artifacts,
            };

            cache_releases.push(cache_release);
        }

        // Sort releases by version for consistent output
        cache_releases.sort_by(|a, b| a.version.cmp(&b.version));

        CacheZigIndex {
            releases: cache_releases,
            last_synced: runtime_index.last_synced,
        }
    }
}

impl From<CacheZigIndex> for ZigIndex {
    fn from(cache_index: CacheZigIndex) -> Self {
        let mut releases = BTreeMap::new();

        for cache_release in cache_index.releases {
            // Parse the version string back to ResolvedZigVersion
            let resolved_version =
                if let Some(version_str) = cache_release.version.strip_prefix("master@") {
                    match semver::Version::parse(version_str) {
                        Ok(version) => ResolvedZigVersion::Master(version),
                        Err(e) => {
                            tracing::warn!(
                                "Failed to parse cached master version '{}': {}",
                                version_str,
                                e
                            );
                            continue; // Skip this release
                        }
                    }
                } else {
                    // Try to parse as semver version
                    match semver::Version::parse(&cache_release.version) {
                        Ok(version) => ResolvedZigVersion::Semver(version),
                        Err(e) => {
                            tracing::warn!(
                                "Failed to parse cached version '{}': {}",
                                cache_release.version,
                                e
                            );
                            continue; // Skip this release
                        }
                    }
                };

            // Convert cache artifacts to runtime artifacts
            let mut runtime_artifacts = HashMap::new();
            for cache_artifact in cache_release.artifacts {
                if let Some(target_triple) = TargetTriple::from_key(&cache_artifact.target) {
                    let artifact_info = ArtifactInfo {
                        ziglang_org_tarball: cache_artifact.tarball_url,
                        shasum: cache_artifact.shasum,
                        size: cache_artifact.size,
                    };
                    runtime_artifacts.insert(target_triple, artifact_info);
                } else {
                    tracing::warn!(
                        "Failed to parse cached target key: {}",
                        cache_artifact.target
                    );
                }
            }

            let runtime_release = ZigRelease::new(
                resolved_version.clone(),
                cache_release.date,
                runtime_artifacts,
            );

            releases.insert(resolved_version, runtime_release);
        }

        ZigIndex::with_releases(releases, cache_index.last_synced)
    }
}