zv 0.10.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
//! Sync command and centralized zv binary update functionality
//!
//! This module provides:
//! - `zv sync` command to refresh Zig indices, mirrors, and zv binary
//! - `check_and_update_zv_binary()` - centralized function for updating zv binary
//!   across different commands (sync, setup, use)
//!
//! The binary update logic includes:
//! - Checksum comparison
//! - Version comparison (with optional downgrade prompts)
//! - Automatic shim regeneration when binary is updated

use crate::Shim;
use std::path::Path;

pub async fn sync(app: &mut crate::App) -> crate::Result<()> {
    use yansi::Paint;

    println!("{}", "Syncing zv...".cyan());

    // Ensure data/config/cache directories exist
    ensure_directories(app).await?;

    // Check and update zv binary (self-install to internal bin)
    println!("  {} Checking zv binary...", "".blue());
    let binary_updated = check_and_update_zv_binary(app, false).await?;

    // Create public bin symlinks (belt-and-suspenders)
    #[cfg(unix)]
    if let Some(pub_bin) = app.public_bin_path() {
        create_public_bin_symlinks(app.bin_path(), pub_bin).await?;
    }

    // Run migrations if binary was actually updated
    if binary_updated
        && let Err(e) = crate::app::migrations::migrate(app.path(), &app.paths.config_file).await
    {
        eprintln!("  {} Warning: Migration failed: {}", "".yellow(), e);
    }

    // Fetch zig index
    println!("  {} Refreshing Zig index...", "".blue());
    app.sync_zig_index().await?;
    println!("  {} Zig index synced successfully", "".green());

    // Fetch mirrors list
    println!("  {} Refreshing community mirrors...", "".blue());
    let mirror_count = app.sync_mirrors().await?;
    println!(
        "  {} Community mirrors synced successfully ({} mirrors)",
        "".green(),
        mirror_count
    );

    println!("{}", "Sync completed successfully!".green().bold());

    // On Tier 2/3 (macOS Library or ZV_DIR), warn if PATH not configured
    if !app.source_set {
        #[cfg(target_os = "linux")]
        {
            // Linux Tier 1: should never happen since ~/.local/bin is in PATH
            let target = app
                .public_bin_path()
                .map(|p| p.display().to_string())
                .unwrap_or_else(|| app.bin_path().display().to_string());
            println!(
                "{} {} is not in your PATH. This is unusual on Linux.",
                "".yellow(),
                Paint::cyan(&target)
            );
        }
        #[cfg(target_os = "macos")]
        {
            if app.paths.tier == 2 {
                println!(
                    "{} PATH not configured. Run {} to add zv to your PATH.",
                    "".yellow(),
                    Paint::blue("zv setup")
                );
            }
        }
        #[cfg(windows)]
        {
            println!(
                "{} PATH not configured. Run {} to add zv to your PATH.",
                "".yellow(),
                Paint::blue("zv setup")
            );
        }
    }

    Ok(())
}

async fn ensure_directories(app: &crate::App) -> crate::Result<()> {
    use std::path::Path;

    async fn ensure(dir: &Path) -> crate::Result<()> {
        if !dir.try_exists().unwrap_or(false)
            && let Some(parent) = dir.parent()
            && parent.exists()
        {
            tokio::fs::create_dir_all(dir).await?;
        }
        Ok(())
    }

    ensure(&app.paths.data_dir).await?;
    ensure(&app.paths.config_dir).await?;
    ensure(&app.paths.cache_dir).await?;
    ensure(app.bin_path()).await?;

    if let Some(ref pub_dir) = app.paths.public_bin_dir {
        ensure(pub_dir).await?;
    }

    Ok(())
}

/// Public API for checking and updating zv binary
/// This can be called from setup, sync, or other commands
/// Returns true if binary was updated, false if it was already up to date
pub async fn check_and_update_zv_binary(app: &crate::App, quiet: bool) -> crate::Result<bool> {
    tracing::debug!(target: "zv::cli::sync", "Checking for zv binary updates");
    check_and_update_zv_binary_impl(app, quiet, true).await
}

async fn check_and_update_zv_binary_impl(
    app: &crate::App,
    quiet: bool,
    prompt_on_downgrade: bool,
) -> crate::Result<bool> {
    use crate::tools::files_have_same_hash;
    use color_eyre::eyre::Context;

    use yansi::Paint;

    let zv_dir_bin = app.bin_path();
    let target_exe = zv_dir_bin.join(Shim::Zv.executable_name());

    let current_exe = std::env::current_exe().wrap_err("Failed to get current executable path")?;

    // If target doesn't exist, copy current binary
    if !target_exe.exists() {
        if !quiet {
            tracing::info!(
                "zv binary not found in {}, installing...",
                zv_dir_bin.display()
            );
        }
        copy_binary_and_regenerate_shims(&current_exe, &target_exe, app, quiet).await?;
        if !quiet {
            tracing::info!("zv binary installed");
        }
        return Ok(true);
    }

    // Compare checksums
    match files_have_same_hash(&current_exe, &target_exe) {
        Ok(true) => {
            // Checksums match, versions are the same - no update
            if !quiet {
                println!("  {} zv binary is up to date", "".green());
            }
            Ok(false)
        }
        Ok(false) => {
            // Checksums differ - need to compare versions
            let current_version = env!("CARGO_PKG_VERSION");

            // Try to get and compare versions
            match get_binary_version(&target_exe) {
                Ok(target_version) => {
                    let current_version = semver::Version::parse(current_version)
                        .expect("CARGO_PKG_VERSION should always be valid semver");

                    use std::cmp::Ordering;
                    match current_version.cmp(&target_version) {
                        Ordering::Greater => {
                            // Current is newer - update target
                            if !quiet {
                                println!(
                                    "  {} Updating zv binary ({} -> {})",
                                    "".blue(),
                                    Paint::yellow(&target_version),
                                    Paint::green(&current_version)
                                );
                            }
                            copy_binary_and_regenerate_shims(&current_exe, &target_exe, app, quiet)
                                .await?;
                            if !quiet {
                                println!("  {} zv binary updated", "".green());
                            }
                            Ok(true)
                        }
                        Ordering::Less => {
                            // Target is newer than current
                            if !quiet {
                                println!(
                                    "  {} Warning: ZV_DIR/bin/zv is newer ({}) than current binary ({})",
                                    "".yellow(),
                                    Paint::green(&target_version),
                                    Paint::yellow(&current_version)
                                );
                            }

                            // Prompt user with default NO (only if prompt_on_downgrade is true)
                            if prompt_on_downgrade && !prompt_user_to_downgrade()? {
                                if !quiet {
                                    println!("  {} Skipping zv binary update", "".blue());
                                }
                                return Ok(false);
                            }

                            if !quiet {
                                println!(
                                    "  {} {} zv binary ({} -> {})",
                                    "".blue(),
                                    if prompt_on_downgrade {
                                        "Downgrading"
                                    } else {
                                        "Updating"
                                    },
                                    Paint::green(&target_version),
                                    Paint::yellow(&current_version)
                                );
                            }
                            copy_binary_and_regenerate_shims(&current_exe, &target_exe, app, quiet)
                                .await?;
                            if !quiet {
                                println!(
                                    "  {} zv binary {}",
                                    "".green(),
                                    if prompt_on_downgrade {
                                        "downgraded"
                                    } else {
                                        "updated"
                                    }
                                );
                            }
                            Ok(true)
                        }
                        Ordering::Equal => {
                            // Same version but different checksum - update
                            if !quiet {
                                println!(
                                    "  {} Updating zv binary (checksum mismatch for version {})",
                                    "".blue(),
                                    current_version
                                );
                            }
                            copy_binary_and_regenerate_shims(&current_exe, &target_exe, app, quiet)
                                .await?;
                            if !quiet {
                                println!("  {} zv binary updated", "".green());
                            }
                            Ok(true)
                        }
                    }
                }
                Err(e) => {
                    // Failed to get version - assume we need to replace
                    tracing::error!(
                        target: "zv::cli::sync",
                        error = %e,
                        "Failed to get version from target binary, will update anyway"
                    );
                    if !quiet {
                        println!(
                            "  {} Warning: failed to get target version, updating anyway",
                            "".yellow()
                        );
                    }
                    copy_binary_and_regenerate_shims(&current_exe, &target_exe, app, quiet).await?;
                    if !quiet {
                        println!("  {} zv binary updated", "".green());
                    }
                    Ok(true)
                }
            }
        }
        Err(e) => {
            // Checksum comparison failed - update anyway
            if !quiet {
                println!(
                    "  {} Warning: checksum comparison failed: {}, updating anyway",
                    "".yellow(),
                    e
                );
            }
            copy_binary_and_regenerate_shims(&current_exe, &target_exe, app, quiet).await?;
            if !quiet {
                println!("  {} zv binary updated", "".green());
            }
            Ok(true)
        }
    }
}

/// Get version from a zv binary by running it with --version
fn get_binary_version(binary_path: &std::path::Path) -> crate::Result<semver::Version> {
    use color_eyre::eyre::eyre;

    let output = std::process::Command::new(binary_path)
        .arg("--version")
        .output()
        .map_err(|e| {
            eyre!(
                "Failed to execute binary at {}: {}",
                binary_path.display(),
                e
            )
        })?;

    if !output.status.success() {
        return Err(eyre!(
            "Binary at {} failed to run --version",
            binary_path.display()
        ));
    }

    let version_output = String::from_utf8_lossy(&output.stdout);
    // Parse "zv X.Y.Z" format - extract version number
    let version_str = version_output
        .split_whitespace()
        .nth(1)
        .ok_or_else(|| eyre!("Failed to parse version from: {}", version_output))?
        .trim();

    // Parse as semver
    semver::Version::parse(version_str)
        .map_err(|e| eyre!("Failed to parse version '{}' as semver: {}", version_str, e))
}

/// Prompt user whether to proceed with downgrade (default: NO)
fn prompt_user_to_downgrade() -> crate::Result<bool> {
    use dialoguer::Confirm;

    // If not in a TTY or in CI, default to NO
    if !crate::tools::is_tty() || std::env::var("CI").is_ok() {
        return Ok(false);
    }

    // Default is NO (false) for downgrades
    let proceed = Confirm::new()
        .with_prompt("  Do you want to replace it with an older version?")
        .default(false)
        .interact()
        .unwrap_or(false);

    Ok(proceed)
}

/// Copy zv binary and regenerate shims
/// This ensures that shims point to the correct binary
async fn copy_binary_and_regenerate_shims(
    source: &Path,
    target: &Path,
    app: &crate::App,
    quiet: bool,
) -> crate::Result<()> {
    use color_eyre::eyre::Context;

    // Ensure internal bin directory exists
    tokio::fs::create_dir_all(app.bin_path())
        .await
        .with_context(|| format!("Failed to create directory {}", app.bin_path().display()))?;

    // Remove the target first to avoid ETXTBSY on Linux when the binary is running
    if target.exists() {
        tokio::fs::remove_file(target).await.with_context(|| {
            format!("Failed to remove existing binary at {}", target.display())
        })?;
    }

    tokio::fs::copy(source, target).await.with_context(|| {
        format!(
            "Failed to copy zv binary from {} to {}",
            source.display(),
            target.display()
        )
    })?;

    // Regenerate shims to ensure they point to the correct zv binary
    let toolchain_manager = &app.toolchain_manager;
    if let Some(install) = toolchain_manager.get_active_install() {
        toolchain_manager
            .deploy_shims(install, true, quiet)
            .await
            .with_context(|| "Failed to regenerate shims after updating zv binary")?;
    }

    // On XDG systems, keep public symlinks in ~/.local/bin up to date
    #[cfg(unix)]
    if let Some(pub_bin) = app.public_bin_path() {
        create_public_bin_symlinks(app.bin_path(), pub_bin)
            .await
            .with_context(|| {
                format!(
                    "Failed to create public bin symlinks in {}",
                    pub_bin.display()
                )
            })?;
    }

    Ok(())
}

/// Create (or refresh) symlinks in the public bin dir (`~/.local/bin`) pointing at
/// the internal bin dir (`ZV_DIR/bin`).  Only called on XDG-capable systems.
///
/// Layout produced:
/// ```text
/// ~/.local/bin/zv  → ZV_DIR/bin/zv
/// ~/.local/bin/zig → ZV_DIR/bin/zig   (only if shim exists)
/// ```
#[cfg(unix)]
async fn create_public_bin_symlinks(internal_bin: &Path, public_bin: &Path) -> crate::Result<()> {
    use color_eyre::eyre::Context;
    use crate::Shim;

    tokio::fs::create_dir_all(public_bin)
        .await
        .with_context(|| format!("Failed to create public bin dir {}", public_bin.display()))?;

    // Helper: create / replace a symlink link → target
    async fn place_symlink(target: &Path, link: &Path) -> crate::Result<()> {
        if link.exists() || link.is_symlink() {
            tokio::fs::remove_file(link).await?;
        }
        tokio::fs::symlink(target, link).await?;
        Ok(())
    }

    let zv_name = Shim::Zv.executable_name();
    let zv_src = internal_bin.join(zv_name);
    let zv_dst = public_bin.join(zv_name);
    if zv_src.exists() {
        place_symlink(&zv_src, &zv_dst)
            .await
            .with_context(|| format!("Failed to symlink zv in {}", public_bin.display()))?;
        tracing::debug!("Linked {} → {}", zv_dst.display(), zv_src.display());
    }

    let zig_name = Shim::Zig.executable_name();
    let zig_src = internal_bin.join(zig_name);
    let zig_dst = public_bin.join(zig_name);
    if zig_src.exists() {
        place_symlink(&zig_src, &zig_dst)
            .await
            .with_context(|| format!("Failed to symlink zig in {}", public_bin.display()))?;
        tracing::debug!("Linked {} → {}", zig_dst.display(), zig_src.display());
    }

    Ok(())
}