Compare commits

...

14 Commits

Author SHA1 Message Date
amrbashir c61b224564 try with sudo 2024-11-21 14:23:49 +02:00
amrbashir 719cd9398e try with /NS 2024-11-19 03:24:59 +02:00
amrbashir 84bfcea116 quiet 2024-11-19 02:23:36 +02:00
amrbashir 021547be1c skip uninstalling in CI 2024-11-19 01:43:28 +02:00
amrbashir eb5c600eda try with passive one more time 2024-11-19 01:42:08 +02:00
amrbashir ee5332fa84 enabe nsis 2024-11-17 17:09:21 +02:00
amrbashir 802e416a51 try with slient and longer wait between runs 2024-11-17 17:07:26 +02:00
amrbashir e0da7a8b8d try with passive 2024-11-17 16:46:57 +02:00
amrbashir e9937b2220 fix appimage 2024-11-17 16:14:16 +02:00
amrbashir 4dfbb13520 fix compilation 2024-11-17 04:54:07 +02:00
amrbashir 60728ea22a fix appimage 2024-11-17 04:48:40 +02:00
amrbashir 7dee8ab6e2 appimage test 2024-11-17 04:38:08 +02:00
amrbashir 30dd3f8b45 fix tests in CI 2024-11-17 02:12:56 +02:00
amrbashir 49a4f78806 refactor: simplify updater tests 2024-11-16 03:14:34 +02:00
8 changed files with 264 additions and 295 deletions
Generated
+2
View File
@@ -239,6 +239,7 @@ dependencies = [
name = "app-updater" name = "app-updater"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"dunce",
"serde", "serde",
"serde_json", "serde_json",
"tauri", "tauri",
@@ -6701,6 +6702,7 @@ version = "2.0.2"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"dirs 5.0.1", "dirs 5.0.1",
"dunce",
"flate2", "flate2",
"futures-util", "futures-util",
"http", "http",
+3
View File
@@ -63,6 +63,9 @@ flate2 = { version = "1", optional = true }
tar = "0.4" tar = "0.4"
flate2 = "1" flate2 = "1"
[dev-dependencies]
dunce = { workspace = true }
[features] [features]
default = ["rustls-tls", "zip"] default = ["rustls-tls", "zip"]
zip = ["dep:zip", "dep:tar", "dep:flate2"] zip = ["dep:zip", "dep:tar", "dep:flate2"]
+6 -2
View File
@@ -616,12 +616,16 @@ impl Update {
.chain(self.installer_args()) .chain(self.installer_args())
.collect(), .collect(),
WindowsUpdaterType::Msi { path, .. } => { WindowsUpdaterType::Msi { path, .. } => {
msi_args = if !current_args.is_empty() {
let escaped_args = current_args let escaped_args = current_args
.iter() .iter()
.map(escape_msi_property_arg) .map(escape_msi_property_arg)
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(" "); .join(" ");
msi_args = OsString::from(format!("LAUNCHAPPARGS=\"{escaped_args}\"")); OsString::from(format!("LAUNCHAPPARGS=\"{escaped_args}\""))
} else {
OsString::new()
};
[OsStr::new("/i"), path.as_os_str()] [OsStr::new("/i"), path.as_os_str()]
.into_iter() .into_iter()
@@ -629,7 +633,7 @@ impl Update {
.chain(once(OsStr::new("/promptrestart"))) .chain(once(OsStr::new("/promptrestart")))
.chain(self.installer_args()) .chain(self.installer_args())
.chain(once(OsStr::new("AUTOLAUNCHAPP=True"))) .chain(once(OsStr::new("AUTOLAUNCHAPP=True")))
.chain(once(msi_args.as_os_str())) .chain(once(msi_args.as_os_str()).filter(|a| !a.is_empty()))
.collect() .collect()
} }
}; };
@@ -0,0 +1,5 @@
[target.'cfg(windows)']
runner = "powershell -Command Start-Process -Verb runAs -FilePath"
[target.x86_64-unknown-linux-gnu]
runner = 'sudo -E'
@@ -14,5 +14,8 @@ tauri-plugin-updater = { path = "../.." }
tiny_http = "0.12" tiny_http = "0.12"
time = { version = "0.3", features = ["formatting"] } time = { version = "0.3", features = ["formatting"] }
[target."cfg(windows)".dependencies]
dunce = { workspace = true }
[features] [features]
prod = ["tauri/custom-protocol"] prod = ["tauri/custom-protocol"]
+19 -17
View File
@@ -14,29 +14,31 @@ fn main() {
.plugin(tauri_plugin_updater::Builder::new().build()) .plugin(tauri_plugin_updater::Builder::new().build())
.setup(|app| { .setup(|app| {
let handle = app.handle().clone(); let handle = app.handle().clone();
eprintln!("app version: {}", app.package_info().version);
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
#[allow(unused_mut)]
let mut builder = handle.updater_builder(); let mut builder = handle.updater_builder();
if std::env::var("TARGET").unwrap_or_default() == "nsis" {
// /D sets the default installation directory ($INSTDIR), // Overriding installation directory for integration tests on Windows
// overriding InstallDir and InstallDirRegKey. #[cfg(windows)]
// It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. {
// Only absolute paths are supported. let target = std::env::var("TARGET").unwrap_or_default();
// NOTE: we only need this because this is an integration test and we don't want to install the app in the programs folder let exe = tauri::utils::platform::current_exe().unwrap();
builder = builder.installer_args(vec![format!( let dir = dunce::simplified(exe.parent().unwrap()).display();
"/D={}", if target == "nsis" {
tauri::utils::platform::current_exe() builder = builder.installer_arg(format!("/D=\"{dir}\"",));
.unwrap() } else if target == "msi" {
.parent() builder = builder.installer_arg(format!("INSTALLDIR=\"{dir}\""));
.unwrap()
.display()
)]);
} }
}
let updater = builder.build().unwrap(); let updater = builder.build().unwrap();
match updater.check().await { match updater.check().await {
Ok(Some(update)) => { Ok(Some(update)) => {
if let Err(e) = update.download_and_install(|_, _| {}, || {}).await { if let Err(e) = update.download_and_install(|_, _| {}, || {}).await {
println!("{e}"); eprintln!("{e}");
std::process::exit(1); std::process::exit(1);
} }
std::process::exit(0); std::process::exit(0);
@@ -45,8 +47,8 @@ fn main() {
std::process::exit(2); std::process::exit(2);
} }
Err(e) => { Err(e) => {
println!("{e}"); eprintln!("{e}");
std::process::exit(1); std::process::exit(3);
} }
} }
}); });
@@ -5,8 +5,7 @@
"endpoints": ["http://localhost:3007"], "endpoints": ["http://localhost:3007"],
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEUwNDRGMjkwRjg2MDhCRDAKUldUUWkyRDRrUEpFNEQ4SmdwcU5PaXl6R2ZRUUNvUnhIaVkwVUltV0NMaEx6VTkrWVhpT0ZqeEEK", "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEUwNDRGMjkwRjg2MDhCRDAKUldUUWkyRDRrUEpFNEQ4SmdwcU5PaXl6R2ZRUUNvUnhIaVkwVUltV0NMaEx6VTkrWVhpT0ZqeEEK",
"windows": { "windows": {
"installMode": "quiet", "installMode": "quiet"
"installerArgs": ["/NS"]
} }
} }
}, },
+194 -243
View File
@@ -19,55 +19,65 @@ const UPDATER_PRIVATE_KEY: &str = "dW50cnVzdGVkIGNvbW1lbnQ6IHJzaWduIGVuY3J5cHRlZ
const UPDATED_EXIT_CODE: i32 = 0; const UPDATED_EXIT_CODE: i32 = 0;
const UP_TO_DATE_EXIT_CODE: i32 = 2; const UP_TO_DATE_EXIT_CODE: i32 = 2;
#[derive(Serialize)] #[derive(Serialize, Clone)]
struct Config { struct Config {
version: &'static str, version: &'static str,
bundle: BundleConfig, bundle: BundleConfig,
} }
#[derive(Serialize)] #[derive(Serialize, Clone)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct BundleConfig { struct BundleConfig {
create_updater_artifacts: Updater, create_updater_artifacts: Updater,
} }
#[derive(Serialize)]
struct PlatformUpdate {
signature: String,
url: &'static str,
with_elevated_task: bool,
}
#[derive(Serialize)] #[derive(Serialize)]
struct Update { struct Update {
version: &'static str, version: &'static str,
date: String, date: String,
platforms: HashMap<String, PlatformUpdate>, signature: String,
url: &'static str,
} }
fn build_app(cwd: &Path, config: &Config, bundle_updater: bool, target: BundleTarget) { fn setup_test() -> (PathBuf, PathBuf, Config, Config) {
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let target_dir = std::env::var("CARGO_TARGET_DIR")
.or_else(|_| std::env::var("CARGO_BUILD_TARGET_DIR"))
.map(PathBuf::from)
.unwrap_or_else(|_| manifest_dir.join("../../../../target"));
let base_config = Config {
version: "0.1.0",
bundle: BundleConfig {
create_updater_artifacts: Updater::Bool(true),
},
};
let config = Config {
version: "1.0.0",
bundle: BundleConfig {
create_updater_artifacts: Updater::Bool(true),
},
};
(manifest_dir, target_dir, base_config, config)
}
fn build_app(cwd: &Path, config: &Config, bundle_updater: bool, target: &str) {
let mut command = Command::new("cargo"); let mut command = Command::new("cargo");
command command
.args(["tauri", "build", "--debug", "--verbose"]) .args(["tauri", "build", "--debug"])
.arg("--config") .arg("--config")
.arg(serde_json::to_string(config).unwrap()) .arg(serde_json::to_string(config).unwrap())
.env("TAURI_SIGNING_PRIVATE_KEY", UPDATER_PRIVATE_KEY) .env("TAURI_SIGNING_PRIVATE_KEY", UPDATER_PRIVATE_KEY)
.env("TAURI_SIGNING_PRIVATE_KEY_PASSWORD", "") .env("TAURI_SIGNING_PRIVATE_KEY_PASSWORD", "")
.current_dir(cwd); .current_dir(cwd);
#[cfg(target_os = "linux")]
command.args(["--bundles", target.name()]);
#[cfg(target_os = "macos")]
command.args(["--bundles", target.name()]);
if bundle_updater { if bundle_updater {
#[cfg(windows)] command.args(["--bundles", target, "updater"]);
command.args(["--bundles", "msi", "nsis"]);
command.args(["--bundles", "updater"]);
} else { } else {
#[cfg(windows)] command.arg("--no-bundle");
command.args(["--bundles", target.name()]);
} }
let status = command let status = command
@@ -79,193 +89,31 @@ fn build_app(cwd: &Path, config: &Config, bundle_updater: bool, target: BundleTa
} }
} }
#[derive(Copy, Clone)] fn start_server(update_bundle: PathBuf, signature: PathBuf) -> Arc<tiny_http::Server> {
enum BundleTarget { let server = tiny_http::Server::http("localhost:3007").expect("failed to start updater server");
AppImage, let server = Arc::new(server);
App,
Msi,
Nsis,
}
impl BundleTarget {
fn name(self) -> &'static str {
match self {
Self::AppImage => "appimage",
Self::App => "app",
Self::Msi => "msi",
Self::Nsis => "nsis",
}
}
}
impl Default for BundleTarget {
fn default() -> Self {
#[cfg(any(target_os = "macos", target_os = "ios"))]
return Self::App;
#[cfg(target_os = "linux")]
return Self::AppImage;
#[cfg(windows)]
return Self::Nsis;
}
}
#[cfg(target_os = "linux")]
fn bundle_paths(root_dir: &Path, version: &str) -> Vec<(BundleTarget, PathBuf)> {
vec![(
BundleTarget::AppImage,
root_dir.join(format!(
"target/debug/bundle/appimage/app-updater_{version}_amd64.AppImage"
)),
)]
}
#[cfg(target_os = "macos")]
fn bundle_paths(root_dir: &Path, _version: &str) -> Vec<(BundleTarget, PathBuf)> {
vec![(
BundleTarget::App,
root_dir.join("target/debug/bundle/macos/app-updater.app"),
)]
}
#[cfg(target_os = "ios")]
fn bundle_paths(root_dir: &Path, _version: &str) -> Vec<(BundleTarget, PathBuf)> {
vec![(
BundleTarget::App,
root_dir.join("target/debug/bundle/ios/app-updater.ipa"),
)]
}
#[cfg(target_os = "android")]
fn bundle_path(root_dir: &Path, _version: &str) -> PathBuf {
root_dir.join("target/debug/bundle/android/app-updater.apk")
}
#[cfg(windows)]
fn bundle_paths(root_dir: &Path, version: &str) -> Vec<(BundleTarget, PathBuf)> {
vec![
(
BundleTarget::Nsis,
root_dir.join(format!(
"target/debug/bundle/nsis/app-updater_{version}_x64-setup.exe"
)),
),
(
BundleTarget::Msi,
root_dir.join(format!(
"target/debug/bundle/msi/app-updater_{version}_x64_en-US.msi"
)),
),
]
}
#[test]
#[ignore]
fn update_app() {
let target =
tauri_plugin_updater::target().expect("running updater test in an unsupported platform");
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let root_dir = manifest_dir.join("../../../..");
for mut config in [
Config {
version: "1.0.0",
bundle: BundleConfig {
create_updater_artifacts: Updater::Bool(true),
},
},
Config {
version: "1.0.0",
bundle: BundleConfig {
create_updater_artifacts: Updater::String(V1Compatible::V1Compatible),
},
},
] {
let v1_compatible = matches!(
config.bundle.create_updater_artifacts,
Updater::String(V1Compatible::V1Compatible)
);
// bundle app update
build_app(&manifest_dir, &config, true, Default::default());
let updater_zip_ext = if v1_compatible {
if cfg!(windows) {
Some("zip")
} else {
Some("tar.gz")
}
} else if cfg!(target_os = "macos") {
Some("tar.gz")
} else {
None
};
for (bundle_target, out_bundle_path) in bundle_paths(&root_dir, "1.0.0") {
let bundle_updater_ext = if v1_compatible {
out_bundle_path
.extension()
.unwrap()
.to_str()
.unwrap()
.replace("exe", "nsis")
} else {
out_bundle_path
.extension()
.unwrap()
.to_str()
.unwrap()
.to_string()
};
let updater_extension = if let Some(updater_zip_ext) = updater_zip_ext {
format!("{bundle_updater_ext}.{updater_zip_ext}")
} else {
bundle_updater_ext
};
let signature_extension = format!("{updater_extension}.sig");
let signature_path = out_bundle_path.with_extension(signature_extension);
let signature = std::fs::read_to_string(&signature_path).unwrap_or_else(|_| {
panic!("failed to read signature file {}", signature_path.display())
});
let out_updater_path = out_bundle_path.with_extension(updater_extension);
let updater_path = root_dir.join(format!(
"target/debug/{}",
out_updater_path.file_name().unwrap().to_str().unwrap()
));
std::fs::rename(&out_updater_path, &updater_path).expect("failed to rename bundle");
let target = target.clone();
// start the updater server
let server = Arc::new(
tiny_http::Server::http("localhost:3007").expect("failed to start updater server"),
);
let server_ = server.clone(); let server_ = server.clone();
std::thread::spawn(move || { std::thread::spawn(move || {
for request in server_.incoming_requests() { for request in server_.incoming_requests() {
match request.url() { match request.url() {
"/" => { "/" => {
let mut platforms = HashMap::new(); let signature =
std::fs::read_to_string(&signature).expect("failed to read signature");
let now = time::OffsetDateTime::now_utc()
.format(&time::format_description::well_known::Rfc3339)
.unwrap();
platforms.insert(
target.clone(),
PlatformUpdate {
signature: signature.clone(),
url: "http://localhost:3007/download",
with_elevated_task: false,
},
);
let body = serde_json::to_vec(&Update { let body = serde_json::to_vec(&Update {
version: "1.0.0", version: "1.0.0",
date: time::OffsetDateTime::now_utc() date: now,
.format(&time::format_description::well_known::Rfc3339) signature,
.unwrap(), url: "http://localhost:3007/download",
platforms,
}) })
.unwrap(); .unwrap();
let len = body.len(); let len = body.len();
let response = tiny_http::Response::new( let response = tiny_http::Response::new(
tiny_http::StatusCode(200), tiny_http::StatusCode(200),
Vec::new(), Vec::new(),
@@ -273,74 +121,177 @@ fn update_app() {
Some(len), Some(len),
None, None,
); );
let _ = request.respond(response); let _ = request.respond(response);
} }
"/download" => { "/download" => {
let _ = request.respond(tiny_http::Response::from_file( let file = File::open(&update_bundle).unwrap_or_else(|_| {
File::open(&updater_path).unwrap_or_else(|_| { panic!("failed to open updater bundle {}", update_bundle.display())
panic!( });
"failed to open updater bundle {}",
updater_path.display() let _ = request.respond(tiny_http::Response::from_file(file));
)
}),
));
} }
_ => (), _ => (),
} }
} }
}); });
config.version = "0.1.0"; server
}
// bundle initial app version fn test_update(app: &Path, update_bundle: PathBuf, signature: PathBuf, target: &str) {
build_app(&manifest_dir, &config, false, bundle_target); // start the updater server
let server = start_server(update_bundle, signature);
let status_checks = if matches!(bundle_target, BundleTarget::Msi) { // run app
// for msi we can't really check if the app was updated, because we can't change the install path let mut app_cmd = Command::new(app);
vec![UPDATED_EXIT_CODE] #[cfg(target_os = "linux")]
} else { if std::env::var("CI").map(|v| v == "true").unwrap_or_default() {
vec![UPDATED_EXIT_CODE, UP_TO_DATE_EXIT_CODE] app_cmd = Command::new("xvfb-run");
app_cmd.arg("--auto-servernum").arg(app);
}; };
app_cmd.env("TARGET", target);
let output = app_cmd.output().expect("failed to run app");
for expected_exit_code in status_checks { // check if updated, or failed during update
let mut binary_cmd = if cfg!(windows) { let code = output.status.code().unwrap_or(-1);
Command::new(root_dir.join("target/debug/app-updater.exe")) if code != UPDATED_EXIT_CODE {
} else if cfg!(target_os = "macos") { let stderr = String::from_utf8_lossy(&output.stderr);
Command::new( panic!("app failed while updating, expected exit code {UPDATED_EXIT_CODE}, got {code}\n{stderr}");
bundle_paths(&root_dir, "0.1.0") }
.first()
.unwrap()
.1
.join("Contents/MacOS/app-updater"),
)
} else if std::env::var("CI").map(|v| v == "true").unwrap_or_default() {
let mut c = Command::new("xvfb-run");
c.arg("--auto-servernum")
.arg(&bundle_paths(&root_dir, "0.1.0").first().unwrap().1);
c
} else {
Command::new(&bundle_paths(&root_dir, "0.1.0").first().unwrap().1)
};
binary_cmd.env("TARGET", bundle_target.name()); // wait for the update to finish
std::thread::sleep(std::time::Duration::from_secs(20));
let status = binary_cmd.status().expect("failed to run app"); // run again
let status = app_cmd.status().expect("failed to run new app");
// check if new version is up to date
let code = status.code().unwrap_or(-1); let code = status.code().unwrap_or(-1);
if code != UP_TO_DATE_EXIT_CODE {
if code != expected_exit_code { let stderr = String::from_utf8_lossy(&output.stderr);
panic!( panic!(
"failed to run app, expected exit code {expected_exit_code}, got {code}" "app failed to update, expected exit code {UP_TO_DATE_EXIT_CODE}, got {code}\n{stderr}"
); );
} }
// shutdown the server
server.unblock();
}
#[cfg(windows)] #[cfg(windows)]
if code == UPDATED_EXIT_CODE { fn nsis() {
// wait for the update to finish let (manifest_dir, target_dir, base_config, config) = setup_test();
// build update bundles
build_app(&manifest_dir, &config, true, "nsis");
// bundle base app
build_app(&manifest_dir, &base_config, false, "nsis");
let app = target_dir.join("debug/app-updater.exe");
// test nsis installer updates
let update_bundle = target_dir.join(format!(
"debug/bundle/nsis/app-updater_{}_x64-setup.exe",
config.version,
));
let signature = update_bundle.with_extension("exe.sig");
test_update(&app, update_bundle, signature, "nsis");
// cleanup the installed application
if !std::env::var("CI").map(|v| v == "true").unwrap_or_default() {
let _ = Command::new(target_dir.join("debug/uninstall.exe"))
.arg("/S")
.status()
.expect("failed to run nsis uninstaller");
std::thread::sleep(std::time::Duration::from_secs(5)); std::thread::sleep(std::time::Duration::from_secs(5));
} }
} }
// graceful shutdown #[cfg(windows)]
server.unblock(); fn msi() {
let (manifest_dir, target_dir, base_config, config) = setup_test();
// build update bundles
build_app(&manifest_dir, &config, true, "msi");
// bundle base app
build_app(&manifest_dir, &base_config, false, "msi");
let app = target_dir.join("debug/app-updater.exe");
// test msi installer updates
let update_bundle = target_dir.join(format!(
"debug/bundle/msi/app-updater_{}_x64_en-US.msi",
config.version,
));
let signature = update_bundle.with_extension("msi.sig");
test_update(&app, update_bundle, signature, "msi");
// cleanup the installed application
if !std::env::var("CI").map(|v| v == "true").unwrap_or_default() {
let uninstall = target_dir.join("debug/Uninstall app-updater.lnk");
let _ = Command::new("cmd")
.arg("/c")
.arg(&uninstall)
.arg("/quiet")
.status()
.expect("failed to run msi uninstaller");
std::thread::sleep(std::time::Duration::from_secs(5));
} }
} }
#[cfg(target_os = "linux")]
fn appimage() {
let (manifest_dir, target_dir, base_config, config) = setup_test();
// build update bundles
build_app(&manifest_dir, &config, true, "appimage");
let update_bundle = target_dir.join(format!(
"debug/bundle/appimage/app-updater_{}_amd64.AppImage",
config.version,
));
let signature = update_bundle.with_extension("AppImage.sig");
// backup update bundles files because next build will override them
let appimage_backup = target_dir.join("debug/bundle/test-appimage.AppImage");
let signature_backup = target_dir.join("debug/bundle/test-appimage.AppImage.sig");
std::fs::rename(&update_bundle, &appimage_backup);
std::fs::rename(&signature, &signature_backup);
// bundle base app
build_app(&manifest_dir, &base_config, true, "appimage");
// restore backup
std::fs::rename(&appimage_backup, &update_bundle);
std::fs::rename(&signature_backup, &signature);
let app = target_dir.join(format!(
"debug/bundle/appimage/app-updater_{}_amd64.AppImage",
base_config.version
));
// test appimage updates
test_update(&app, update_bundle, signature, "appimage");
}
#[cfg(target_os = "macos")]
fn app() {
let (manifest_dir, target_dir, base_config, config) = setup_test();
}
#[test]
#[ignore]
fn it_updates() {
#[cfg(windows)]
nsis();
// MSI test should be the last one
#[cfg(windows)]
msi();
#[cfg(target_os = "linux")]
appimage();
#[cfg(target_os = "macos")]
app();
} }