diff --git a/README.md b/README.md index 2b68943..89465cc 100644 --- a/README.md +++ b/README.md @@ -77,8 +77,20 @@ hytale-runner run --java-path /path/to/java # Run without auto-restart on updates hytale-runner run --no-restart + +# Download from the pre-release patchline if server files are missing +hytale-runner run --patchline pre-release + +# Pin the server to a specific version +hytale-runner run --server-version 0.7.2 ``` +`--server-version` keeps the server on the given version: if it is not installed, the runner downloads it, +and staged updates are not applied. `hytale-downloader` can only download the latest version of a patchline, +so a version that is no longer the latest can only be used if it is already installed. +If `.hytale-runner.yaml` pins a different `server_version`, it is updated to the version from the flag +once that version is installed (the same applies to `download --server-version`). + ### Download Command ```bash @@ -90,6 +102,9 @@ hytale-runner download --force # Download pre-release version hytale-runner download --patchline pre-release + +# Download only if the latest version matches +hytale-runner download --server-version 0.7.2 ``` ### Install Command @@ -154,6 +169,7 @@ port: 5520 memory_max: "8G" assets: Assets.zip patchline: release +# server_version: 0.7.2 java: path: "" @@ -184,6 +200,10 @@ The Hytale server uses exit code 8 to signal that an update is ready. When this Use `--no-restart` to disable this behavior and exit instead. +When the server version is pinned (`--server-version` or `server_version` in config), staged updates are skipped +and left in `updater/staging/`. Downloading server files removes `updater/staging/`, since a staged update +is older than the downloaded version. + ## Building for Multiple Platforms ```bash diff --git a/src/cli/download.rs b/src/cli/download.rs index bd89422..bb8a35d 100644 --- a/src/cli/download.rs +++ b/src/cli/download.rs @@ -1,5 +1,5 @@ use anyhow::Result; -use tracing::info; +use tracing::{info, warn}; use crate::cli::{Cli, DownloadArgs}; use crate::config::AppConfig; @@ -17,15 +17,29 @@ pub async fn execute(args: &DownloadArgs, cli: &Cli) -> Result<()> { // Load configuration let config = AppConfig::load(cli.config.as_ref(), &server_dir)?; + let patchline = args.patchline.as_deref().or(config.patchline.as_deref()); + let server_version = args + .server_version + .as_deref() + .or(config.server_version.as_deref()); + // Create downloader - let downloader = ServerDownloader::new(&config)?; + let downloader = ServerDownloader::new(&config, patchline)?; // Download server files info!( "Downloading Hytale server files (patchline: {})...", - args.patchline + patchline.unwrap_or("default") ); - downloader.download_all(&server_dir, args.force).await?; + downloader + .download_all(&server_dir, args.force, server_version) + .await?; + + if let Some(ref version) = args.server_version { + if let Err(e) = AppConfig::update_server_version(&server_dir, version) { + warn!("Failed to update server_version in config: {:#}", e); + } + } info!("Download complete!"); Ok(()) diff --git a/src/cli/mod.rs b/src/cli/mod.rs index 667cd4b..45aab4e 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -30,6 +30,7 @@ pub struct Cli { } #[derive(Subcommand, Debug)] +#[allow(clippy::large_enum_variant)] pub enum Commands { /// Download (if needed) and run the Hytale server Run(RunArgs), @@ -89,6 +90,14 @@ pub struct RunArgs { #[arg(long)] pub aot_path: Option, + /// Patchline to download from: release, pre-release (default: release) + #[arg(long)] + pub patchline: Option, + + /// Pin the server to a specific version (staged updates are not applied) + #[arg(long)] + pub server_version: Option, + /// Additional JVM arguments #[arg(long)] pub jvm_args: Option, @@ -121,8 +130,12 @@ pub struct RunArgs { #[derive(Parser, Debug)] pub struct DownloadArgs { /// Patchline: release (default), pre-release - #[arg(long, default_value = "release")] - pub patchline: String, + #[arg(long)] + pub patchline: Option, + + /// Download only this server version + #[arg(long)] + pub server_version: Option, /// Re-download even if files exist #[arg(long)] diff --git a/src/cli/run.rs b/src/cli/run.rs index a4ec667..27a013b 100644 --- a/src/cli/run.rs +++ b/src/cli/run.rs @@ -38,11 +38,32 @@ pub async fn execute(args: &RunArgs, cli: &Cli) -> Result<()> { let java_path = ensure_java(args, &config).await?; info!("Using Java: {}", java_path.display()); + let patchline = args.patchline.as_deref().or(config.patchline.as_deref()); + let server_version = args + .server_version + .as_deref() + .or(config.server_version.as_deref()); + // Ensure server files are available - ensure_server_files(&server_dir, &jar_path, &config).await?; + ensure_server_files(&server_dir, &jar_path, &config, patchline, server_version).await?; + + if let Some(ref version) = args.server_version { + if let Err(e) = AppConfig::update_server_version(&server_dir, version) { + warn!("Failed to update server_version in config: {:#}", e); + } + } // Run the server with auto-update loop - run_server_loop(args, &config, &server_dir, &java_path, &jar_path, &aot_path).await + run_server_loop( + args, + &config, + &server_dir, + &java_path, + &jar_path, + &aot_path, + server_version, + ) + .await } /// Ensure Java is available, installing if necessary @@ -82,17 +103,41 @@ async fn ensure_java(args: &RunArgs, config: &AppConfig) -> Result { } /// Ensure server files are available, downloading if necessary -async fn ensure_server_files(server_dir: &Path, jar_path: &Path, config: &AppConfig) -> Result<()> { +async fn ensure_server_files( + server_dir: &Path, + jar_path: &Path, + config: &AppConfig, + patchline: Option<&str>, + server_version: Option<&str>, +) -> Result<()> { let assets_path = server_dir.join("Assets.zip"); + let installed = jar_path.exists() && assets_path.exists(); + + if let Some(version) = server_version { + if installed && ServerDownloader::get_local_version(server_dir).as_deref() == Some(version) + { + info!("Server files found (version {})", version); + return Ok(()); + } - if jar_path.exists() && assets_path.exists() { + info!( + "Server version {} is not installed, downloading...", + version + ); + let downloader = ServerDownloader::new(config, patchline)?; + return downloader + .download_all(server_dir, true, Some(version)) + .await; + } + + if installed { info!("Server files found"); return Ok(()); } info!("Server files not found, downloading..."); - let downloader = ServerDownloader::new(config)?; - downloader.download_all(server_dir, false).await?; + let downloader = ServerDownloader::new(config, patchline)?; + downloader.download_all(server_dir, false, None).await?; Ok(()) } @@ -106,6 +151,7 @@ async fn run_server_loop( java_path: &Path, jar_path: &Path, aot_path: &Path, + server_version: Option<&str>, ) -> Result<()> { let updater = ServerUpdater::new(server_dir.to_path_buf(), config); let runner = ServerRunner::new( @@ -119,11 +165,18 @@ async fn run_server_loop( loop { // Apply staged update if present if updater.has_staged_update() { - info!("Applying staged update..."); - updater - .apply_staged_update() - .context("Failed to apply staged update")?; - info!("Update applied successfully"); + if let Some(version) = server_version { + warn!( + "Skipping staged update: server version is pinned to {}", + version + ); + } else { + info!("Applying staged update..."); + updater + .apply_staged_update() + .context("Failed to apply staged update")?; + info!("Update applied successfully"); + } } // Build JVM arguments diff --git a/src/config/app_config.rs b/src/config/app_config.rs index c0187fd..6691921 100644 --- a/src/config/app_config.rs +++ b/src/config/app_config.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use tracing::debug; +use tracing::{debug, info}; /// Global configuration file name const GLOBAL_CONFIG_FILE: &str = "config.yaml"; @@ -22,6 +22,10 @@ pub struct AppConfig { pub update: UpdateConfig, /// Path to hytale-downloader binary pub downloader_path: Option, + /// Patchline to download from (release, pre-release) + pub patchline: Option, + /// Pinned server version + pub server_version: Option, } /// Default server settings @@ -148,6 +152,53 @@ impl AppConfig { Ok(config) } + + /// Replace `server_version` in the per-server config if it is set there to a different version. + /// The file is edited line by line to keep comments and formatting. + pub fn update_server_version(server_dir: &Path, version: &str) -> Result<()> { + let path = server_dir.join(SERVER_CONFIG_FILE); + if !path.exists() { + return Ok(()); + } + + let current = match load_config_file(&path)?.server_version { + Some(current) if current != version => current, + _ => return Ok(()), + }; + + let content = std::fs::read_to_string(&path) + .with_context(|| format!("Failed to read config file: {}", path.display()))?; + + let updated: String = content + .split_inclusive('\n') + .map(|line| { + if line.starts_with("server_version:") { + let eol = &line[line.trim_end_matches(['\r', '\n']).len()..]; + format!("server_version: \"{}\"{}", version, eol) + } else { + line.to_string() + } + }) + .collect(); + + if updated == content { + anyhow::bail!( + "Failed to find top-level 'server_version' in {}", + path.display() + ); + } + + std::fs::write(&path, updated) + .with_context(|| format!("Failed to write config file: {}", path.display()))?; + + info!( + "Updated server_version in {}: {} -> {}", + path.display(), + current, + version + ); + Ok(()) + } } /// Get the global configuration directory @@ -236,5 +287,74 @@ fn merge_configs(base: AppConfig, overlay: AppConfig) -> AppConfig { }, update: overlay.update, downloader_path: overlay.downloader_path.or(base.downloader_path), + patchline: overlay.patchline.or(base.patchline), + server_version: overlay.server_version.or(base.server_version), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::TempDir; + + fn write_server_config(dir: &TempDir, content: &str) -> PathBuf { + let path = dir.path().join(SERVER_CONFIG_FILE); + std::fs::write(&path, content).unwrap(); + path + } + + #[test] + fn test_update_server_version_replaces_value() { + let dir = TempDir::new().unwrap(); + let path = write_server_config( + &dir, + "# pinned\r\npatchline: release\r\nserver_version: 0.7.2\r\ndownloader_path: /bin/dl\r\n", + ); + + AppConfig::update_server_version(dir.path(), "0.7.3").unwrap(); + + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "# pinned\r\npatchline: release\r\nserver_version: \"0.7.3\"\r\ndownloader_path: /bin/dl\r\n" + ); + assert_eq!( + load_config_file(&path).unwrap().server_version.as_deref(), + Some("0.7.3") + ); + } + + #[test] + fn test_update_server_version_same_version() { + let dir = TempDir::new().unwrap(); + let path = write_server_config(&dir, "server_version: 0.7.3 # keep\n"); + + AppConfig::update_server_version(dir.path(), "0.7.3").unwrap(); + + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "server_version: 0.7.3 # keep\n" + ); + } + + #[test] + fn test_update_server_version_not_pinned() { + let dir = TempDir::new().unwrap(); + let path = write_server_config(&dir, "patchline: release\n# server_version: 0.7.2\n"); + + AppConfig::update_server_version(dir.path(), "0.7.3").unwrap(); + + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "patchline: release\n# server_version: 0.7.2\n" + ); + } + + #[test] + fn test_update_server_version_no_config() { + let dir = TempDir::new().unwrap(); + + AppConfig::update_server_version(dir.path(), "0.7.3").unwrap(); + + assert!(!dir.path().join(SERVER_CONFIG_FILE).exists()); } } diff --git a/src/java/detector.rs b/src/java/detector.rs index cffa536..7df3f25 100644 --- a/src/java/detector.rs +++ b/src/java/detector.rs @@ -145,16 +145,10 @@ fn parse_java_version_output(output: &str, path: PathBuf) -> Option { let first_line = lines[0]; // Extract version string between quotes - let version = if let Some(start) = first_line.find('"') { - let rest = &first_line[start + 1..]; - if let Some(end) = rest.find('"') { - rest[..end].to_string() - } else { - return None; - } - } else { - return None; - }; + let start = first_line.find('"')?; + let rest = &first_line[start + 1..]; + let end = rest.find('"')?; + let version = rest[..end].to_string(); // Try to extract vendor from second line let vendor = lines.get(1).and_then(|line| { diff --git a/src/server/downloader.rs b/src/server/downloader.rs index d005138..37e951c 100644 --- a/src/server/downloader.rs +++ b/src/server/downloader.rs @@ -12,21 +12,46 @@ const HYTALE_DOWNLOADER_BIN: &str = "hytale-downloader"; /// Downloads Hytale server files using hytale-downloader pub struct ServerDownloader { downloader_path: PathBuf, + patchline: Option, } impl ServerDownloader { - pub fn new(config: &AppConfig) -> Result { + pub fn new(config: &AppConfig, patchline: Option<&str>) -> Result { let downloader_path = find_hytale_downloader(config)?; - Ok(Self { downloader_path }) + Ok(Self { + downloader_path, + patchline: patchline.map(str::to_string), + }) } - /// Download all server files using hytale-downloader - pub async fn download_all(&self, server_dir: &Path, force: bool) -> Result<()> { + /// Download all server files using hytale-downloader. + /// With `required_version`, only that version is accepted: hytale-downloader + /// can only fetch the latest version of a patchline, so any other version is an error. + pub async fn download_all( + &self, + server_dir: &Path, + force: bool, + required_version: Option<&str>, + ) -> Result<()> { std::fs::create_dir_all(server_dir).context("Failed to create server directory")?; - // Check if download is needed - if !force { + if let Some(required_version) = required_version { + if !force && Self::get_local_version(server_dir).as_deref() == Some(required_version) { + info!("Server version {} is already installed", required_version); + return Ok(()); + } + + let remote_version = self.get_remote_version().await?; + if remote_version != required_version { + anyhow::bail!( + "Server version {} is not available for download (latest available: {}). \ + hytale-downloader can only download the latest version of a patchline", + required_version, + remote_version + ); + } + } else if !force { if let Some(local_version) = Self::get_local_version(server_dir) { // Only check remote version if we have a local version to compare let remote_version = self.get_remote_version().await?; @@ -44,7 +69,7 @@ impl ServerDownloader { // Download to temp zip file let zip_path = server_dir.join("server-download.zip"); - let mut cmd = Command::new(&self.downloader_path); + let mut cmd = self.command(); cmd.arg("-download-path") .arg(&zip_path) .stdin(Stdio::inherit()) @@ -71,6 +96,13 @@ impl ServerDownloader { let version = self.get_remote_version().await?; Self::save_version(server_dir, &version)?; + // A staged update is older than freshly downloaded files and would downgrade the server + let staging_dir = server_dir.join("updater").join("staging"); + if staging_dir.exists() { + info!("Removing outdated staged update: {}", staging_dir.display()); + std::fs::remove_dir_all(&staging_dir).context("Failed to remove staging directory")?; + } + // Clean up zip file std::fs::remove_file(&zip_path).ok(); @@ -100,7 +132,8 @@ impl ServerDownloader { /// Get the remote version from hytale-downloader async fn get_remote_version(&self) -> Result { - let output = Command::new(&self.downloader_path) + let output = self + .command() .arg("-print-version") .output() .await @@ -115,8 +148,17 @@ impl ServerDownloader { Ok(version) } + /// Build a hytale-downloader command with the selected patchline + fn command(&self) -> Command { + let mut cmd = Command::new(&self.downloader_path); + if let Some(ref patchline) = self.patchline { + cmd.arg("-patchline").arg(patchline); + } + cmd + } + /// Get the local installed version from version.txt - fn get_local_version(server_dir: &Path) -> Option { + pub fn get_local_version(server_dir: &Path) -> Option { let version_file = server_dir.join("version.txt"); std::fs::read_to_string(version_file) .ok() diff --git a/src/server/updater.rs b/src/server/updater.rs index 5187367..b176bd7 100644 --- a/src/server/updater.rs +++ b/src/server/updater.rs @@ -29,7 +29,7 @@ pub struct ServerUpdater { impl ServerUpdater { pub fn new(server_dir: PathBuf, config: &AppConfig) -> Self { - let downloader = ServerDownloader::new(config).ok(); + let downloader = ServerDownloader::new(config, config.patchline.as_deref()).ok(); Self { server_dir, downloader,