zv 0.9.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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
pub mod constants;
pub(crate) mod migrations;
pub(crate) mod network;
pub(crate) mod toolchain;
pub(crate) mod utils;
use crate::app::network::{ZigDownload, ZigRelease};
use crate::app::utils::{remove_files, zig_tarball};
use crate::types::*;
mod minisign;
use crate::path_utils;
use color_eyre::eyre::{Context as _, eyre};
pub use network::CacheStrategy;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::LazyLock;
use toolchain::ToolchainManager;

/// 21 days default TTL for index
pub static INDEX_TTL_DAYS: LazyLock<i64> = LazyLock::new(|| {
    std::env::var("ZV_INDEX_TTL_DAYS")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(21)
});
/// 21 days default TTL for mirrors list
pub static MIRRORS_TTL_DAYS: LazyLock<i64> = LazyLock::new(|| {
    std::env::var("ZV_MIRRORS_TTL_DAYS")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(21)
});
/// Network timeout in seconds for operations
pub static FETCH_TIMEOUT_SECS: LazyLock<u64> = LazyLock::new(|| {
    std::env::var("ZV_FETCH_TIMEOUT_SECS")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(4)
});
/// Maximum number of retry attempts for downloads
pub static MAX_RETRIES: LazyLock<u32> = LazyLock::new(|| {
    std::env::var("ZV_MAX_RETRIES")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(3)
});

impl App {
    pub fn download_cache(&self) -> &Path {
        &self.download_cache
    }
}

/// Zv App State
#[derive(Debug, Clone)]
pub struct App {
    /// <ZV_DIR> - Home for zv
    zv_base_path: PathBuf,
    /// <ZV_DIR>/bin - Binary symlink location
    bin_path: PathBuf,
    /// <ZV_DIR>/downloads -  Download cache path
    download_cache: PathBuf,
    /// <ZV_DIR>/bin/zig - Zv managed zig executable if any
    zig: Option<PathBuf>,
    /// <ZV_DIR>/bin/zls - Zv managed zls executable if any
    #[allow(dead_code)]
    zls: Option<PathBuf>,
    /// <ZV_DIR>/versions - Installed versions
    pub(crate) versions_path: PathBuf,
    /// <ZV_DIR>/env for *nix. For powershell/cmd prompt we rely on direct PATH variable manipulation.
    env_path: PathBuf,
    /// Network client
    network: Option<network::ZvNetwork>,
    /// Toolchain manager
    pub(crate) toolchain_manager: ToolchainManager,
    /// <ZV_DIR>/bin in $PATH? If not prompt user to run `setup` or add `source <ZV_DIR>/env to their shell profile`
    pub(crate) source_set: bool,
    /// Current detected shell
    pub(crate) shell: Option<crate::Shell>,
    /// ZigRelease to install - set during resolution phase
    pub(crate) to_install: Option<Either>,
}
impl From<ZigRelease> for Either {
    fn from(release: ZigRelease) -> Self {
        Either::Release(release)
    }
}
impl From<ResolvedZigVersion> for Either {
    fn from(rzv: ResolvedZigVersion) -> Self {
        Either::Version(rzv)
    }
}
impl Either {
    /// Convert to ZigRelease if possible
    pub fn into_release(self) -> Option<ZigRelease> {
        match self {
            Either::Release(r) => Some(r),
            Either::Version(_) => None,
        }
    }
    /// Convert to ResolvedZigVersion if possible
    pub fn into_version(self) -> Option<ResolvedZigVersion> {
        match self {
            Either::Version(v) => Some(v),
            Either::Release(_) => None,
        }
    }
}
#[derive(Debug, Clone)]
pub enum Either {
    Version(ResolvedZigVersion),
    Release(ZigRelease),
}

impl App {
    /// Minimal App path initialization & directory creation
    pub async fn init(
        UserConfig {
            zv_base_path,
            shell,
        }: UserConfig,
    ) -> Result<Self, ZvError> {
        /* path is canonicalized in tools::fetch_zv_dir() so we don't need to do that here */
        let bin_path = zv_base_path.join("bin");
        let download_cache = zv_base_path.as_path().join("downloads");

        if !bin_path.try_exists().unwrap_or_default() {
            std::fs::create_dir_all(&bin_path)
                .map_err(ZvError::Io)
                .wrap_err("Creation of bin directory failed")?;
        }
        let toolchain_manager = ToolchainManager::new(&zv_base_path).await?;
        // Check for existing ZV zig/zls shims in bin directory
        let zig = toolchain_manager
            .get_active_install()
            .map(|zig_install| zig_install.path.join(Shim::Zig.executable_name()));
        let zls = utils::detect_shim(&bin_path, Shim::Zls);

        let versions_path = zv_base_path.join("versions");
        if !versions_path.try_exists().unwrap_or(false) {
            std::fs::create_dir_all(&versions_path)
                .map_err(ZvError::Io)
                .wrap_err("Creation of versions directory failed")?;
        }

        // Run migrations if needed
        if let Err(e) = migrations::migrate(&zv_base_path).await {
            tracing::warn!("Migration failed: {}", e);
        }

        let env_path = if let Some(ref shell_type) = shell {
            zv_base_path.join(shell_type.env_file_name())
        } else {
            // In non-shell mode, it doesn't really matter what the file is
            zv_base_path.join("env")
        };

        let app = App {
            network: None,
            zig,
            zls,
            source_set: if let Some(ref shell_type) = shell {
                path_utils::check_dir_in_path_for_shell(shell_type, &bin_path)
            } else {
                path_utils::check_dir_in_path(&bin_path)
            },
            bin_path,
            download_cache,
            env_path,
            toolchain_manager,
            zv_base_path,
            versions_path,
            shell,
            to_install: None,
        };
        Ok(app)
    }

    /// Set the active Zig version. Optionally provide the installed path to skip re-checking installation
    pub async fn set_active_version<'b>(
        &mut self,
        version: &'b ResolvedZigVersion,
        installed_path: Option<PathBuf>,
    ) -> crate::Result<()> {
        // Copy zv binary to bin directory if needed and regenerate shims
        crate::cli::sync::check_and_update_zv_binary(self, true)
            .await
            .wrap_err("Failed to update zv binary")?;

        if let Some(p) = installed_path {
            return self
                .toolchain_manager
                .set_active_version_with_path(version, p)
                .await;
        }
        self.toolchain_manager.set_active_version(version).await
    }

    /// Initialize network client if not already done
    pub async fn ensure_network(&mut self) -> Result<(), ZvError> {
        if self.network.is_none() {
            self.network = Some(
                network::ZvNetwork::new(self.zv_base_path.as_path(), self.download_cache.clone())
                    .await?,
            );
        }
        Ok(())
    }
    /// Initialize network client with mirror manager if not already done
    pub async fn ensure_network_with_mirrors(&mut self) -> Result<(), ZvError> {
        if self.network.is_none() {
            let mut net =
                network::ZvNetwork::new(self.zv_base_path.as_path(), self.download_cache.clone())
                    .await?;
            net.ensure_mirror_manager().await?;
            self.network = Some(net);
        } else if self.network.is_some() {
            self.network
                .as_mut()
                .unwrap()
                .ensure_mirror_manager()
                .await?;
        }
        Ok(())
    }
    /// Fetch a handle to IndexManger
    pub async fn index_manager(&mut self) -> Result<&mut network::IndexManager, ZvError> {
        self.ensure_network().await?;
        Ok(&mut self.network.as_mut().unwrap().index_manager)
    }
    /// Fetch a handle to MirrorManager
    pub async fn mirror_manager(&mut self) -> Result<&mut network::mirror::MirrorManager, ZvError> {
        self.ensure_network_with_mirrors().await?;
        Ok(self
            .network
            .as_mut()
            .unwrap()
            .mirror_manager
            .as_mut()
            .unwrap())
    }
    /// Force refresh the Zig index from network
    pub async fn sync_zig_index(&mut self) -> Result<(), ZvError> {
        self.ensure_network().await?;

        if let Some(network) = self.network.as_mut() {
            network.sync_zig_index().await?;
        }

        Ok(())
    }

    /// Force refresh the community mirrors list from network
    pub async fn sync_mirrors(&mut self) -> Result<usize, ZvError> {
        self.ensure_network_with_mirrors().await?;

        if let Some(network) = self.network.as_mut() {
            return network.sync_mirrors().await;
        }

        Ok(0)
    }

    /// Get the current active Zig version
    pub fn get_active_version(&self) -> Option<ZigVersion> {
        self.toolchain_manager.get_active_install().map(|zi| {
            if zi.is_master {
                ZigVersion::Master(Some(zi.version.clone()))
            } else {
                ZigVersion::Semver(zi.version.clone())
            }
        })
    }

    /// Get the app's base path
    pub fn path(&self) -> &PathBuf {
        &self.zv_base_path
    }

    /// Get the app's bin path
    pub fn bin_path(&self) -> &PathBuf {
        &self.bin_path
    }

    /// Get the environment file path
    pub fn env_path(&self) -> &PathBuf {
        &self.env_path
    }

    /// Path to zv zig binary
    pub fn zv_zig(&self) -> Option<PathBuf> {
        self.zig.clone()
    }

    /// Spawn a zig process with recursion guard management
    /// Only bumps the recursion count if we're spawning our own shim
    pub(crate) fn spawn_zig_with_guard(
        &self,
        zig_path: &Path,
        args: &[&str],
        current_dir: Option<&Path>,
    ) -> Result<Output, ZvError> {
        // No need for canonicalization here, just a quick check
        let is_our_shim = zig_path.parent() == Some(self.bin_path.as_path());

        let new_count = if is_our_shim {
            let count = std::env::var("ZV_RECURSION_COUNT")
                .ok()
                .and_then(|s| s.parse::<u32>().ok())
                .unwrap_or(0);

            let new_count = count + 1;
            tracing::trace!(
                "Spawning ZV shim zig process at {:?} with ZV_RECURSION_COUNT: {} -> {}",
                zig_path,
                count,
                new_count
            );
            Some(new_count)
        } else {
            tracing::trace!(
                "Spawning external zig process at {:?} (no recursion guard needed)",
                zig_path
            );
            None
        };

        let mut cmd = Command::new(zig_path);
        cmd.args(args);

        if let Some(dir) = current_dir {
            cmd.current_dir(dir);
        }

        if let Some(count) = new_count {
            cmd.env("ZV_RECURSION_COUNT", count.to_string());
        }

        cmd.output().map_err(|e| {
            tracing::error!(
                "Failed to execute zig at path: {:?}, error: {}",
                zig_path,
                e
            );
            ZvError::ZigExecuteError {
                source: eyre!("Failed to execute zig: {}", e),
                command: "zig ".to_string() + &args.join(" "),
            }
        })
    }

    /// Fetch a compatible ZLS version for the given Zig version
    /// This is a placeholder implementation that will be expanded with proper compatibility logic
    pub fn fetch_compatible_zls(&mut self, zig_version: &ZigVersion) -> Result<PathBuf, ZvError> {
        tracing::info!("Fetching compatible ZLS for Zig version: {:?}", zig_version);

        // Determine compatible ZLS version
        todo!()
    }

    /// Fetch latest master and returns a [ZigRelease]
    pub async fn fetch_master_version(&mut self) -> Result<ZigRelease, ZvError> {
        self.ensure_network().await?;
        let zig_release = self
            .network
            .as_mut()
            .unwrap()
            .fetch_master_version()
            .await?;

        // Update master file with the fetched version
        let version_str = zig_release.resolved_version().version().to_string();
        crate::app::migrations::update_master_file(&self.zv_base_path, &version_str).await;

        Ok(zig_release)
    }
    /// Fetch latest stable and returns a [ZigRelease]
    pub async fn fetch_latest_version(
        &mut self,
        cache_strategy: CacheStrategy,
    ) -> Result<ZigRelease, ZvError> {
        self.ensure_network().await?;
        let zig_release = self
            .network
            .as_mut()
            .unwrap()
            .fetch_latest_stable_version(cache_strategy)
            .await?;
        Ok(zig_release)
    }
    /// Validate if a semver version exists in the index and returns a [ZigRelease] or [ResolvedZigVersion]
    pub async fn validate_semver(&mut self, version: &semver::Version) -> Result<Either, ZvError> {
        // todo!("Implement semver validation against installed versions and return early or else");
        self.ensure_network().await?;
        let zig_release = self
            .network
            .as_mut()
            .unwrap()
            .validate_semver(version)
            .await;
        match zig_release {
            Ok(release) => Ok(Either::Release(release)),
            Err(_) => Ok(Either::Version(ResolvedZigVersion::Semver(version.clone()))),
        }
    }

    /// Check if version is installed returning Some(path) to zig binary if so
    #[inline]
    pub fn check_installed(&self, rzv: &ResolvedZigVersion) -> Option<PathBuf> {
        self.toolchain_manager.is_version_installed(rzv)
    }
    /// Install the current loaded `to_install` ZigVersion directly without index resolution
    pub async fn install_direct(&mut self, force_ziglang: bool) -> Result<PathBuf, ZvError> {
        const TARGET: &str = "zv::app::install_direct";

        let resolved_version = self
            .to_install
            .take()
            .and_then(|z| z.into_version())
            .ok_or_else(|| {
                ZvError::ZigVersionResolveError(eyre!(
                    "No ResolvedZigVersion is currently loaded for installation"
                ))
            })?;

        let semver_version = resolved_version.version();
        let is_master = resolved_version.is_master();
        tracing::debug!(
            target: TARGET,
            version = %semver_version,
            is_master,
            "Starting direct installation"
        );

        let zig_tarball = zig_tarball(semver_version, None).ok_or_else(|| {
            eyre!(
                "Could not determine tarball name for Zig version {}",
                semver_version
            )
        })?;
        tracing::debug!(target: TARGET, tarball = %zig_tarball, "Determined tarball name");

        let ext = if zig_tarball.ends_with(".zip") {
            ArchiveExt::Zip
        } else if zig_tarball.ends_with(".tar.xz") {
            ArchiveExt::TarXz
        } else {
            unreachable!("Unknown archive extension for tarball: {}", zig_tarball)
        };
        tracing::debug!(target: TARGET, ?ext, "Detected archive format");

        // Initialize network based on force_ziglang flag
        if !force_ziglang {
            self.ensure_network_with_mirrors().await?;
        } else {
            self.ensure_network().await?;
        }

        let host_target = utils::host_target().ok_or_else(|| {
            eyre!(
                "Could not determine host target for Zig version {}",
                semver_version
            )
        })?;
        tracing::debug!(target: TARGET, %host_target, "Resolved host target");

        let ZigDownload {
            tarball_path,
            minisig_path,
            mirror_used,
        } = if !force_ziglang {
            // Use mirrors with optional artifact info (None since we don't have index data)
            self.network
                .as_mut()
                .unwrap()
                .download_version(semver_version, &zig_tarball, None)
                .await?
        } else {
            // Generate ziglang.org URLs directly
            let ziglang_org_tarball = if !semver_version.pre.is_empty() {
                format!("https://ziglang.org/builds/{zig_tarball}")
            } else {
                format!(
                    "https://ziglang.org/download/{}/{zig_tarball}",
                    semver_version.to_string()
                )
            };
            let ziglang_org_minisig = format!("{}.minisig", ziglang_org_tarball);

            tracing::trace!(target: "zv", "Using ziglang.org as download source");
            self.network
                .as_mut()
                .unwrap()
                .direct_download(
                    &ziglang_org_tarball,
                    &ziglang_org_minisig,
                    &zig_tarball,
                    None, // No expected shasum
                    None, // No expected size
                )
                .await?
        };
        tracing::debug!(
            target: TARGET,
            tarball = %tarball_path.display(),
            minisig = %minisig_path.display(),
            ?mirror_used,
            "Download completed"
        );

        let zig_exe = self
            .toolchain_manager
            .install_version(&tarball_path, semver_version, ext, is_master)
            .await?;
        tracing::info!(
            target: TARGET,
            version = %semver_version,
            "Toolchain installation succeeded"
        );

        remove_files(&[tarball_path.as_path(), minisig_path.as_path()]).await;
        tracing::debug!(target: TARGET, "Cleaned up temporary download files");

        Ok(zig_exe)
    }
    /// Install the current loaded `to_install` ZigRelease
    pub async fn install_release(&mut self, force_ziglang: bool) -> Result<PathBuf, ZvError> {
        const TARGET: &str = "zv::app::install_release";

        let zig_release = self
            .to_install
            .take()
            .and_then(|z| z.into_release())
            .ok_or_else(|| {
                ZvError::ZigVersionResolveError(eyre!(
                    "No ZigRelease is currently loaded for installation"
                ))
            })?;

        let semver_version = zig_release.resolved_version().version();
        let is_master = zig_release.resolved_version().is_master();
        tracing::debug!(
            target: TARGET,
            version = %semver_version,
            is_master,
            "Starting installation"
        );

        let zig_tarball = zig_tarball(semver_version, None).ok_or_else(|| {
            eyre!(
                "Could not determine tarball name for Zig version {}",
                zig_release.version_string()
            )
        })?;
        tracing::debug!(target: TARGET, tarball = %zig_tarball, "Determined tarball name");

        let ext = if zig_tarball.ends_with(".zip") {
            ArchiveExt::Zip
        } else if zig_tarball.ends_with(".tar.xz") {
            ArchiveExt::TarXz
        } else {
            unreachable!("Unknown archive extension for tarball: {}", zig_tarball)
        };
        tracing::debug!(target: TARGET, ?ext, "Detected archive format");
        if !force_ziglang {
            self.ensure_network_with_mirrors().await?;
        } else {
            self.ensure_network().await?;
        }
        let host_target = utils::host_target().ok_or_else(|| {
            eyre!(
                "Could not determine host target for Zig version {}",
                zig_release.version_string()
            )
        })?;
        tracing::debug!(target: TARGET, %host_target, "Resolved host target");

        let download_artifact = zig_release
            .target_artifact(&host_target)
            .ok_or_else(|| {
                eyre!(
                    "No download artifact found for target <{}> in release {}",
                    host_target,
                    zig_release.version_string()
                )
            })
            .map_err(ZvError::ZigNotFound)?;
        tracing::debug!(
            target: TARGET,
            artifact_url = %download_artifact.ziglang_org_tarball,
            "Selected download artifact"
        );

        let ZigDownload {
            tarball_path,
            minisig_path,
            mirror_used,
        } = if !force_ziglang {
            self.network
                .as_mut()
                .unwrap()
                .download_version(semver_version, &zig_tarball, Some(download_artifact))
                .await?
        } else {
            tracing::trace!(target: "zv", "Using ziglang.org as download source");
            self.network
                .as_mut()
                .unwrap()
                .direct_download(
                    &download_artifact.ziglang_org_tarball,
                    &format!("{}.minisig", &download_artifact.ziglang_org_tarball),
                    &zig_tarball,
                    Some(&download_artifact.shasum),
                    Some(download_artifact.size),
                )
                .await?
        };
        tracing::debug!(
            target: TARGET,
            tarball = %tarball_path.display(),
            minisig = %minisig_path.display(),
            ?mirror_used,
            "Download completed"
        );

        let zig_exe = self
            .toolchain_manager
            .install_version(&tarball_path, semver_version, ext, is_master)
            .await?;
        tracing::info!(
            target: TARGET,
            version = %semver_version,
            "Toolchain installation succeeded"
        );

        remove_files(&[tarball_path.as_path(), minisig_path.as_path()]).await;
        tracing::debug!(target: TARGET, "Cleaned up temporary download files");

        Ok(zig_exe)
    }
}