|
| 1 | +use crate::network; |
| 2 | +use anyhow::{Context, Result}; |
| 3 | +use clap::Parser; |
| 4 | +use colored::Colorize; |
| 5 | +use serde::Deserialize; |
| 6 | +use std::io::Write; |
| 7 | + |
| 8 | +const GITHUB_REPO: &str = "WebProject-xyz/php-version-manager"; |
| 9 | + |
| 10 | +/// Check for and apply pvm updates |
| 11 | +#[derive(Parser, Debug)] |
| 12 | +pub struct SelfUpdate { |
| 13 | + /// Apply the update if a newer version is available (asks for confirmation, default yes) |
| 14 | + #[arg(long)] |
| 15 | + pub apply: bool, |
| 16 | +} |
| 17 | + |
| 18 | +#[derive(Deserialize)] |
| 19 | +struct GhRelease { |
| 20 | + tag_name: String, |
| 21 | +} |
| 22 | + |
| 23 | +fn current_version() -> Result<semver::Version> { |
| 24 | + let raw = env!("PVM_VERSION"); |
| 25 | + let token = raw.split_whitespace().next().unwrap_or(raw); |
| 26 | + let trimmed = token.trim_start_matches('v'); |
| 27 | + // git-describe extras (e.g. "-2-gabc") are not valid semver; drop them. |
| 28 | + let core = trimmed.split('-').next().unwrap_or(trimmed); |
| 29 | + semver::Version::parse(core).with_context(|| { |
| 30 | + format!( |
| 31 | + "Failed to parse current pvm version '{}' from '{}'", |
| 32 | + core, raw |
| 33 | + ) |
| 34 | + }) |
| 35 | +} |
| 36 | + |
| 37 | +fn parse_remote_version(tag: &str) -> Result<semver::Version> { |
| 38 | + let trimmed = tag.trim_start_matches('v'); |
| 39 | + semver::Version::parse(trimmed) |
| 40 | + .with_context(|| format!("Failed to parse remote release tag '{}'", tag)) |
| 41 | +} |
| 42 | + |
| 43 | +async fn fetch_latest_release() -> Result<GhRelease> { |
| 44 | + let url = format!( |
| 45 | + "https://api.github.com/repos/{}/releases/latest", |
| 46 | + GITHUB_REPO |
| 47 | + ); |
| 48 | + let release = network::http_client()? |
| 49 | + .get(&url) |
| 50 | + .header("Accept", "application/vnd.github+json") |
| 51 | + .send() |
| 52 | + .await |
| 53 | + .context("Failed to query GitHub releases API")? |
| 54 | + .error_for_status() |
| 55 | + .context("GitHub releases API returned an error")? |
| 56 | + .json::<GhRelease>() |
| 57 | + .await |
| 58 | + .context("Failed to parse GitHub release JSON")?; |
| 59 | + Ok(release) |
| 60 | +} |
| 61 | + |
| 62 | +async fn download_and_replace(tag: &str) -> Result<()> { |
| 63 | + let target = network::get_target_triple()?; |
| 64 | + let asset = format!("pvm-{}.tar.gz", target); |
| 65 | + let url = format!( |
| 66 | + "https://github.com/{}/releases/download/{}/{}", |
| 67 | + GITHUB_REPO, tag, asset |
| 68 | + ); |
| 69 | + |
| 70 | + let current_exe = |
| 71 | + std::env::current_exe().context("Failed to determine current executable path")?; |
| 72 | + let exe_dir = current_exe |
| 73 | + .parent() |
| 74 | + .context("Current executable has no parent directory")?; |
| 75 | + |
| 76 | + println!("{} Downloading {}...", "↻".blue(), url); |
| 77 | + |
| 78 | + let response = network::http_client()? |
| 79 | + .get(&url) |
| 80 | + .send() |
| 81 | + .await |
| 82 | + .context("Failed to download release archive")? |
| 83 | + .error_for_status() |
| 84 | + .context("Server returned an error when downloading release")?; |
| 85 | + |
| 86 | + let pb = network::build_download_progress_bar(response.content_length())?; |
| 87 | + let tmp = network::stream_to_tempfile(response, &pb).await?; |
| 88 | + pb.finish_and_clear(); |
| 89 | + |
| 90 | + // Stage the new binary in the same directory as the current exe so the rename is atomic |
| 91 | + // (cross-filesystem renames would fail otherwise). |
| 92 | + let mut staged = tempfile::Builder::new() |
| 93 | + .prefix(".pvm-update-") |
| 94 | + .tempfile_in(exe_dir) |
| 95 | + .context("Failed to create staging file next to current executable")?; |
| 96 | + |
| 97 | + { |
| 98 | + let tar = flate2::read::GzDecoder::new(tmp); |
| 99 | + let mut archive = tar::Archive::new(tar); |
| 100 | + let mut found = false; |
| 101 | + for entry in archive |
| 102 | + .entries() |
| 103 | + .context("Failed to read archive entries")? |
| 104 | + { |
| 105 | + let mut entry = entry.context("Failed to read archive entry")?; |
| 106 | + let path = entry.path().context("Invalid entry path")?.into_owned(); |
| 107 | + let name = path.file_name().and_then(|s| s.to_str()).unwrap_or(""); |
| 108 | + if name == "pvm" { |
| 109 | + std::io::copy(&mut entry, staged.as_file_mut()) |
| 110 | + .context("Failed to extract pvm binary from archive")?; |
| 111 | + staged |
| 112 | + .as_file_mut() |
| 113 | + .flush() |
| 114 | + .context("Failed to flush staged binary")?; |
| 115 | + found = true; |
| 116 | + break; |
| 117 | + } |
| 118 | + } |
| 119 | + if !found { |
| 120 | + anyhow::bail!("Release archive did not contain a `pvm` binary"); |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + #[cfg(unix)] |
| 125 | + { |
| 126 | + use std::os::unix::fs::PermissionsExt; |
| 127 | + std::fs::set_permissions(staged.path(), std::fs::Permissions::from_mode(0o755)) |
| 128 | + .context("Failed to set permissions on staged binary")?; |
| 129 | + } |
| 130 | + |
| 131 | + // Atomic rename. On Unix this is safe even while the current binary is executing — the |
| 132 | + // kernel keeps the old inode alive through open fds until the process exits. |
| 133 | + staged |
| 134 | + .persist(¤t_exe) |
| 135 | + .with_context(|| format!("Failed to replace current executable {:?}", current_exe))?; |
| 136 | + |
| 137 | + Ok(()) |
| 138 | +} |
| 139 | + |
| 140 | +impl SelfUpdate { |
| 141 | + pub async fn call(self) -> Result<()> { |
| 142 | + let current = current_version()?; |
| 143 | + let current_str = current.to_string(); |
| 144 | + println!("{} Current version: {}", "↻".blue(), current_str.bold()); |
| 145 | + println!("{} Checking GitHub for the latest release...", "↻".blue()); |
| 146 | + |
| 147 | + let release = fetch_latest_release().await?; |
| 148 | + let remote = parse_remote_version(&release.tag_name)?; |
| 149 | + |
| 150 | + if remote <= current { |
| 151 | + println!("{} pvm is up to date ({})", "✓".green(), current_str.bold()); |
| 152 | + return Ok(()); |
| 153 | + } |
| 154 | + |
| 155 | + let remote_str = remote.to_string(); |
| 156 | + println!( |
| 157 | + "{} New version available: {} → {}", |
| 158 | + "💡".yellow(), |
| 159 | + current_str.bold(), |
| 160 | + remote_str.bold() |
| 161 | + ); |
| 162 | + |
| 163 | + if !self.apply { |
| 164 | + println!( |
| 165 | + "{} Run `{}` to install it.", |
| 166 | + "💡".yellow(), |
| 167 | + "pvm self-update --apply".bold() |
| 168 | + ); |
| 169 | + return Ok(()); |
| 170 | + } |
| 171 | + |
| 172 | + let theme = dialoguer::theme::ColorfulTheme::default(); |
| 173 | + let confirmed = dialoguer::Confirm::with_theme(&theme) |
| 174 | + .with_prompt(format!("Update pvm to {}?", remote_str).bold().to_string()) |
| 175 | + .default(true) |
| 176 | + .interact_opt() |
| 177 | + .unwrap_or(Some(false)) |
| 178 | + .unwrap_or(false); |
| 179 | + |
| 180 | + if !confirmed { |
| 181 | + println!("{} Update cancelled.", "✗".red()); |
| 182 | + return Ok(()); |
| 183 | + } |
| 184 | + |
| 185 | + download_and_replace(&release.tag_name).await?; |
| 186 | + println!( |
| 187 | + "{} Successfully updated pvm to {}", |
| 188 | + "✓".green(), |
| 189 | + remote_str.bold() |
| 190 | + ); |
| 191 | + println!( |
| 192 | + "{} Restart your shell or re-run `{}` to pick up the new binary.", |
| 193 | + "💡".yellow(), |
| 194 | + "pvm env".bold() |
| 195 | + ); |
| 196 | + |
| 197 | + Ok(()) |
| 198 | + } |
| 199 | +} |
0 commit comments