Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
221 changes: 209 additions & 12 deletions src/commands/self_update.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use crate::interaction::{Interaction, TtyInteraction};
use crate::network;
use anyhow::{Context, Result};
use clap::Parser;
use colored::Colorize;
use serde::Deserialize;
use std::fmt::Write as _;
use std::fs::File;
use std::future::Future;
use std::io::{Read, Seek, SeekFrom, Write};

const GITHUB_REPO: &str = "WebProject-xyz/php-version-manager";
Expand All @@ -15,6 +17,10 @@ pub struct SelfUpdate {
/// Apply the update if a newer version is available (asks for confirmation, default yes)
#[arg(long)]
pub apply: bool,

/// Auto-approve the update without prompting
#[arg(short = 'y', long = "yes")]
pub yes: bool,
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -215,13 +221,36 @@ async fn download_and_replace(tag: &str) -> Result<()> {

impl SelfUpdate {
pub async fn call(self) -> Result<()> {
let mut io = TtyInteraction;
let current = current_version()?;
self.run_with(
&mut io,
current,
|| async { fetch_latest_release().await.map(|r| r.tag_name) },
|tag| async move { download_and_replace(&tag).await },
)
.await
}

async fn run_with<F, FutF, D, FutD>(
self,
io: &mut dyn Interaction,
current: semver::Version,
fetch_latest_tag: F,
apply_update: D,
) -> Result<()>
where
F: FnOnce() -> FutF,
FutF: Future<Output = Result<String>>,
D: FnOnce(String) -> FutD,
FutD: Future<Output = Result<()>>,
{
let current_str = current.to_string();
println!("{} Current version: {}", "↻".blue(), current_str.bold());
println!("{} Checking GitHub for the latest release...", "↻".blue());

let release = fetch_latest_release().await?;
let remote = parse_remote_version(&release.tag_name)?;
let tag_name = fetch_latest_tag().await?;
let remote = parse_remote_version(&tag_name)?;

if remote <= current {
println!("{} pvm is up to date ({})", "✓".green(), current_str.bold());
Expand All @@ -245,20 +274,13 @@ impl SelfUpdate {
return Ok(());
}

let theme = dialoguer::theme::ColorfulTheme::default();
let confirmed = dialoguer::Confirm::with_theme(&theme)
.with_prompt(format!("Update pvm to {}?", remote_str).bold().to_string())
.default(true)
.interact_opt()
.context("Failed to read update confirmation from terminal")?
.unwrap_or(false);

if !confirmed {
let question = format!("Update pvm to {}?", remote_str).bold().to_string();
if !io.confirm(&question, true, self.yes)? {
println!("{} Update cancelled.", "✗".red());
return Ok(());
}

download_and_replace(&release.tag_name).await?;
apply_update(tag_name).await?;
println!(
"{} Successfully updated pvm to {}",
"✓".green(),
Expand Down Expand Up @@ -383,4 +405,179 @@ mod tests {
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
}

#[tokio::test]
async fn self_update_apply_confirmed_applies_update() {
let mut io = crate::interaction::ScriptedInteraction::interactive().with_confirm(true);
let mut applied_tag = None;

SelfUpdate {
apply: true,
yes: false,
}
.run_with(
&mut io,
v(2, 0, 0),
|| async { Ok("v2.1.0".to_string()) },
|tag| {
applied_tag = Some(tag);
async { Ok(()) }
},
)
.await
.unwrap();

assert_eq!(applied_tag.as_deref(), Some("v2.1.0"));
assert_eq!(io.remaining_responses(), 0);
}

#[tokio::test]
async fn self_update_apply_declined_cancels_update() {
let mut io = crate::interaction::ScriptedInteraction::interactive().with_confirm(false);
let mut applied = false;

SelfUpdate {
apply: true,
yes: false,
}
.run_with(
&mut io,
v(2, 0, 0),
|| async { Ok("v2.1.0".to_string()) },
|_| {
applied = true;
async { Ok(()) }
},
)
.await
.unwrap();

assert!(!applied);
assert_eq!(io.remaining_responses(), 0);
}

#[tokio::test]
async fn self_update_apply_cancel_key_cancels_update() {
let mut io = crate::interaction::ScriptedInteraction::interactive().with_confirm_cancel();
let mut applied = false;

SelfUpdate {
apply: true,
yes: false,
}
.run_with(
&mut io,
v(2, 0, 0),
|| async { Ok("v2.1.0".to_string()) },
|_| {
applied = true;
async { Ok(()) }
},
)
.await
.unwrap();

assert!(!applied);
assert_eq!(io.remaining_responses(), 0);
}

#[tokio::test]
async fn self_update_apply_with_yes_skips_prompt() {
let mut io = crate::interaction::ScriptedInteraction::interactive();
let mut applied_tag = None;

SelfUpdate {
apply: true,
yes: true,
}
.run_with(
&mut io,
v(2, 0, 0),
|| async { Ok("v2.1.0".to_string()) },
|tag| {
applied_tag = Some(tag);
async { Ok(()) }
},
)
.await
.unwrap();

assert_eq!(applied_tag.as_deref(), Some("v2.1.0"));
assert!(io.seen_prompts.is_empty());
}

#[tokio::test]
async fn self_update_apply_non_tty_uses_default_without_prompting() {
let mut io = crate::interaction::ScriptedInteraction::non_interactive();
let mut applied_tag = None;

SelfUpdate {
apply: true,
yes: false,
}
.run_with(
&mut io,
v(2, 0, 0),
|| async { Ok("v2.1.0".to_string()) },
|tag| {
applied_tag = Some(tag);
async { Ok(()) }
},
)
.await
.unwrap();

assert_eq!(applied_tag.as_deref(), Some("v2.1.0"));
assert!(io.seen_prompts.is_empty());
}

#[tokio::test]
async fn self_update_without_apply_does_not_prompt_or_apply() {
let mut io = crate::interaction::ScriptedInteraction::interactive();
let mut applied = false;

SelfUpdate {
apply: false,
yes: false,
}
.run_with(
&mut io,
v(2, 0, 0),
|| async { Ok("v2.1.0".to_string()) },
|_| {
applied = true;
async { Ok(()) }
},
)
.await
.unwrap();

assert!(!applied);
assert!(io.seen_prompts.is_empty());
}

#[tokio::test]
async fn self_update_already_up_to_date_does_not_prompt_or_apply() {
let mut io = crate::interaction::ScriptedInteraction::interactive();
let mut applied = false;

SelfUpdate {
apply: true,
yes: false,
}
.run_with(
&mut io,
v(2, 1, 0),
|| async { Ok("v2.1.0".to_string()) },
|_| {
applied = true;
async { Ok(()) }
},
)
.await
.unwrap();

assert!(!applied);
assert!(io.seen_prompts.is_empty());
}
}
Loading