mirror of
https://github.com/Corfirean/coa-server-manager.git
synced 2026-11-23 03:25:56 +00:00
Realmlist switcher next to PLAY, and a Modules page
- Named realmlists (e.g. Solo, PTR): a drop-down by the PLAY button switches the game client by writing the chosen text into every locale's realmlist.wtf (the replaced file is saved first); add / edit / remove with a name and the realmlist text (or just an address). First use offers 'Solo' (127.0.0.1) and, if the client held another realmlist, 'Previous'. - Modules page: bundled catalog (modules/catalog.json) of the optional modules built into the server; switch each on or off (its Enable setting), open its page on GitHub, edit its configuration with the module's own documentation. Nine modules to start with. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a79c26ed49
commit
81aacdf5bb
17 files changed
+1208
-5
No files matched your search
@@ -189,6 +189,32 @@ pub fn set_realmlist(client: &Path, meta: &Path, host: &str) -> Result<Vec<Strin
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// Replace the text of every locale's realmlist with `content` (a named realmlist chosen by the player). Each changed file
|
||||
/// is saved to the backup folder first; files that already hold the same lines are left alone. A client without one gets a
|
||||
/// file for each installed locale. Returns the files that changed.
|
||||
pub fn write_realmlist(client: &Path, meta: &Path, content: &str) -> Result<Vec<String>> {
|
||||
let compact = |t: &str| t.lines().map(|l| l.trim().to_ascii_lowercase()).filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n");
|
||||
let mut files = realmlist_files(client);
|
||||
if files.is_empty() {
|
||||
files = installed_locales(client).into_iter().map(|loc| client.join("Data").join(loc).join("realmlist.wtf")).collect();
|
||||
}
|
||||
let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S").to_string();
|
||||
let mut changed = Vec::new();
|
||||
for file in files {
|
||||
let old = fs::read(&file).ok();
|
||||
if let Some(old) = &old {
|
||||
if compact(&String::from_utf8_lossy(old)) == compact(content) {
|
||||
continue;
|
||||
}
|
||||
let locale = file.parent().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
fsx::atomic_write(&backup_dir(meta).join(format!("realmlist-{locale}-{stamp}.wtf")), old)?;
|
||||
}
|
||||
fsx::atomic_write(&file, content.as_bytes())?;
|
||||
changed.push(file.to_string_lossy().into_owned());
|
||||
}
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// Copy the addon into the client. If a different version is there, that one folder is backed up first;
|
||||
/// files in it that the package does not contain are left alone.
|
||||
pub fn install_addon(client: &Path, meta: &Path, source: &Path) -> Result<()> {
|
||||
|
||||
@@ -26,6 +26,8 @@ pub mod migrations;
|
||||
pub mod net;
|
||||
pub mod package;
|
||||
pub mod ra;
|
||||
pub mod modules;
|
||||
pub mod realmlist;
|
||||
pub mod registry;
|
||||
pub mod release;
|
||||
pub mod update;
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
//! Optional server modules. They are compiled into the server; what the owner decides is whether each one is on and how it is
|
||||
//! configured, which lives in `Core/configs/modules/<module>.conf` (the documented defaults are in the `.dist` beside it).
|
||||
//! The list of known modules is a bundled catalog, so a module is added to the Manager by adding a few lines to it.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::config::parser::ConfFile;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
static CATALOG: &str = include_str!("../../../modules/catalog.json");
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Entry {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// language code -> text; "en" is always there.
|
||||
pub description: BTreeMap<String, String>,
|
||||
pub repo: String,
|
||||
/// File in `Core/configs/modules` that holds this module's settings.
|
||||
pub conf: String,
|
||||
/// The setting that switches the whole module on or off (1 / 0).
|
||||
pub enable_key: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Catalog {
|
||||
modules: Vec<Entry>,
|
||||
}
|
||||
|
||||
pub fn catalog() -> Vec<Entry> {
|
||||
serde_json::from_str::<Catalog>(CATALOG).map(|c| c.modules).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn entry(id: &str) -> Result<Entry> {
|
||||
catalog().into_iter().find(|e| e.id == id).ok_or_else(|| Error::Invalid("That module is not known to the Manager.".into()))
|
||||
}
|
||||
|
||||
fn dir(root: &Path) -> PathBuf {
|
||||
root.join("Core/configs/modules")
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Option<ConfFile> {
|
||||
fs::read(path).ok().and_then(|b| ConfFile::parse_bytes(&b).ok())
|
||||
}
|
||||
|
||||
fn truthy(v: &str) -> bool {
|
||||
matches!(v.trim().trim_matches('"').to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ModuleView {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: BTreeMap<String, String>,
|
||||
pub repo: String,
|
||||
/// The module's configuration is present on this server (otherwise it is not part of this server build).
|
||||
pub installed: bool,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
pub fn list(root: &Path) -> Vec<ModuleView> {
|
||||
catalog()
|
||||
.into_iter()
|
||||
.map(|e| {
|
||||
let conf = dir(root).join(&e.conf);
|
||||
let dist = dir(root).join(format!("{}.dist", e.conf));
|
||||
let installed = conf.is_file() || dist.is_file();
|
||||
// the active file decides; without one the documented default is what the server will use
|
||||
let enabled = read(&conf).or_else(|| read(&dist)).and_then(|c| c.get(&e.enable_key).map(truthy)).unwrap_or(false);
|
||||
ModuleView { id: e.id, name: e.name, description: e.description, repo: e.repo, installed, enabled }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The active file, created from its `.dist` when it does not exist yet.
|
||||
fn active_file(root: &Path, e: &Entry) -> Result<PathBuf> {
|
||||
let conf = dir(root).join(&e.conf);
|
||||
if !conf.is_file() {
|
||||
let dist = dir(root).join(format!("{}.dist", e.conf));
|
||||
if !dist.is_file() {
|
||||
return Err(Error::Invalid("This module is not part of this server.".into()));
|
||||
}
|
||||
fsx::atomic_write(&conf, &fs::read(&dist)?)?;
|
||||
}
|
||||
Ok(conf)
|
||||
}
|
||||
|
||||
fn backup(meta: &Path, conf: &Path) -> Result<()> {
|
||||
let name = conf.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let to = meta.join("backups").join("modules").join(format!("{name}-{}", chrono::Utc::now().format("%Y%m%d-%H%M%S")));
|
||||
fsx::atomic_write(&to, &fs::read(conf)?)
|
||||
}
|
||||
|
||||
pub fn set_enabled(root: &Path, meta: &Path, id: &str, on: bool) -> Result<()> {
|
||||
let e = entry(id)?;
|
||||
let conf = active_file(root, &e)?;
|
||||
let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?;
|
||||
if file.get(&e.enable_key).map(truthy) == Some(on) {
|
||||
return Ok(());
|
||||
}
|
||||
backup(meta, &conf)?;
|
||||
file.set(&e.enable_key, if on { "1" } else { "0" }, &["Changed by CoA Server Manager"]);
|
||||
fsx::atomic_write(&conf, file.to_text().as_bytes())?;
|
||||
tracing::info!(module = id, on, "module switched");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, PartialEq, Eq)]
|
||||
pub struct Setting {
|
||||
pub key: String,
|
||||
pub value: String,
|
||||
pub default: Option<String>,
|
||||
/// The documentation the module ships above the setting.
|
||||
pub doc: String,
|
||||
}
|
||||
|
||||
/// Every active setting of the module with its current value, its documented default and its description.
|
||||
pub fn settings(root: &Path, id: &str) -> Result<Vec<Setting>> {
|
||||
let e = entry(id)?;
|
||||
let conf = dir(root).join(&e.conf);
|
||||
let dist = read(&dir(root).join(format!("{}.dist", e.conf)));
|
||||
let active = read(&conf).or_else(|| dist.clone()).ok_or_else(|| Error::Invalid("This module is not part of this server.".into()))?;
|
||||
Ok(active
|
||||
.entries()
|
||||
.map(|(k, v)| Setting {
|
||||
key: k.to_string(),
|
||||
value: v.to_string(),
|
||||
default: dist.as_ref().and_then(|d| d.get(k)).map(str::to_string),
|
||||
doc: dist.as_ref().map(|d| d.doc_for(k)).filter(|d| !d.is_empty()).unwrap_or_else(|| active.doc_for(k)).join(" "),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Change values of settings the module already has. A value is one line of at most 500 characters.
|
||||
pub fn save_settings(root: &Path, meta: &Path, id: &str, changes: &BTreeMap<String, String>) -> Result<Vec<String>> {
|
||||
let e = entry(id)?;
|
||||
let conf = active_file(root, &e)?;
|
||||
let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?;
|
||||
let mut changed = Vec::new();
|
||||
for (key, value) in changes {
|
||||
let value = value.trim();
|
||||
if file.get(key).is_none() {
|
||||
return Err(Error::Invalid(format!("{key} is not a setting of this module.")));
|
||||
}
|
||||
if value.is_empty() || value.len() > 500 || value.chars().any(char::is_control) {
|
||||
return Err(Error::Invalid(format!("The value of {key} must be one line of text.")));
|
||||
}
|
||||
if file.get(key).map(str::trim) != Some(value) {
|
||||
changed.push((key.clone(), value.to_string()));
|
||||
}
|
||||
}
|
||||
if changed.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
backup(meta, &conf)?;
|
||||
for (k, v) in &changed {
|
||||
file.set(k, v, &[]);
|
||||
}
|
||||
fsx::atomic_write(&conf, file.to_text().as_bytes())?;
|
||||
Ok(changed.into_iter().map(|(k, _)| k).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn server(d: &Path) -> (PathBuf, PathBuf) {
|
||||
let (root, meta) = (d.join("srv"), d.join("meta"));
|
||||
let m = dir(&root);
|
||||
fs::create_dir_all(&m).unwrap();
|
||||
fs::create_dir_all(&meta).unwrap();
|
||||
fs::write(m.join("war_games.conf.dist"), "# Turns War Games on.\r\n# Second line.\r\nWarGames.Enable = 1\r\n\r\n# How long a challenge stays open.\r\nWarGames.ChallengeSeconds = 60\r\n").unwrap();
|
||||
(root, meta)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bundled_catalog_is_complete() {
|
||||
let c = catalog();
|
||||
assert!(c.len() >= 5);
|
||||
for e in &c {
|
||||
assert!(e.description.contains_key("en") && e.description.len() == 5, "{} has all five descriptions", e.id);
|
||||
assert!(e.repo.starts_with("https://github.com/Corfirean/") && e.conf.ends_with(".conf") && e.enable_key.ends_with(".Enable"), "{}", e.id);
|
||||
}
|
||||
let mut ids: Vec<_> = c.iter().map(|e| e.id.as_str()).collect();
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
assert_eq!(ids.len(), c.len(), "ids are unique");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_is_listed_as_installed_with_its_documented_default_until_a_file_exists() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (root, _) = server(d.path());
|
||||
let wg = list(&root).into_iter().find(|m| m.id == "war-games").unwrap();
|
||||
assert!(wg.installed && wg.enabled, "the .dist says 1");
|
||||
assert!(!list(&root).into_iter().find(|m| m.id == "spellbook").unwrap().installed, "no configuration of that module on this server");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_a_module_creates_its_file_saves_the_old_one_and_changes_only_that_line() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (root, meta) = server(d.path());
|
||||
set_enabled(&root, &meta, "war-games", false).unwrap();
|
||||
let conf = fs::read_to_string(dir(&root).join("war_games.conf")).unwrap();
|
||||
assert!(conf.contains("WarGames.Enable = 0") && conf.contains("WarGames.ChallengeSeconds = 60"), "{conf}");
|
||||
assert!(!list(&root).into_iter().find(|m| m.id == "war-games").unwrap().enabled);
|
||||
set_enabled(&root, &meta, "war-games", false).unwrap();
|
||||
assert_eq!(fs::read_dir(meta.join("backups/modules")).unwrap().count(), 1, "no change, no backup");
|
||||
set_enabled(&root, &meta, "war-games", true).unwrap();
|
||||
assert!(fs::read_to_string(dir(&root).join("war_games.conf")).unwrap().contains("WarGames.Enable = 1"));
|
||||
assert!(set_enabled(&root, &meta, "spellbook", true).is_err(), "not part of this server");
|
||||
assert!(set_enabled(&root, &meta, "nonsense", true).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_show_the_documentation_and_only_known_keys_with_one_line_values_can_be_saved() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (root, meta) = server(d.path());
|
||||
let s = settings(&root, "war-games").unwrap();
|
||||
assert_eq!(s.len(), 2);
|
||||
assert_eq!(s[1], Setting { key: "WarGames.ChallengeSeconds".into(), value: "60".into(), default: Some("60".into()), doc: "How long a challenge stays open.".into() });
|
||||
assert_eq!(s[0].doc, "Turns War Games on. Second line.");
|
||||
|
||||
let ok = BTreeMap::from([("WarGames.ChallengeSeconds".to_string(), "90".to_string())]);
|
||||
assert_eq!(save_settings(&root, &meta, "war-games", &ok).unwrap(), ["WarGames.ChallengeSeconds"]);
|
||||
assert!(settings(&root, "war-games").unwrap()[1].value == "90");
|
||||
assert!(save_settings(&root, &meta, "war-games", &ok).unwrap().is_empty(), "same value: nothing to do");
|
||||
for bad in [("Other.Key", "1"), ("WarGames.ChallengeSeconds", ""), ("WarGames.ChallengeSeconds", "1\nInjected = 1")] {
|
||||
let c = BTreeMap::from([(bad.0.to_string(), bad.1.to_string())]);
|
||||
assert!(save_settings(&root, &meta, "war-games", &c).is_err(), "{bad:?}");
|
||||
}
|
||||
assert!(!fs::read_to_string(dir(&root).join("war_games.conf")).unwrap().contains("Injected"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Named realmlists for the game client ("Solo" for your own server, "PTR" for the shared one, ...). Choosing one writes its
|
||||
//! text into the client's `Data/<locale>/realmlist.wtf` files; the file that was there is saved first. The profiles live
|
||||
//! in the Manager's folder for the server, never in the client.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::client;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsx;
|
||||
|
||||
const FILE: &str = "realmlists.json";
|
||||
const MAX_PROFILES: usize = 24;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct Profile {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// The text of `realmlist.wtf` (normalised: `set <name> <value>` lines).
|
||||
pub data: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
struct Store {
|
||||
profiles: Vec<Profile>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct View {
|
||||
pub profiles: Vec<Profile>,
|
||||
/// The profile whose text every realmlist file of the client currently holds.
|
||||
pub active: Option<String>,
|
||||
}
|
||||
|
||||
fn compact(text: &str) -> String {
|
||||
text.lines().map(|l| l.trim().to_ascii_lowercase()).filter(|l| !l.is_empty()).collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
|
||||
/// Accept either the whole file text or just an address ("play.example.com", "192.168.0.5:3724"), and make sure that
|
||||
/// what is written into the client is nothing but `set <name> <value>` lines.
|
||||
pub fn normalize(data: &str) -> Result<String> {
|
||||
let bad = |m: &str| Err(Error::Invalid(m.into()));
|
||||
let text = data.trim();
|
||||
if text.is_empty() {
|
||||
return bad("Enter the realmlist text or an address.");
|
||||
}
|
||||
if text.len() > 2000 {
|
||||
return bad("That text is too long for a realmlist.");
|
||||
}
|
||||
let lines: Vec<String> = if !text.contains(char::is_whitespace) {
|
||||
vec![format!("set realmlist {text}")]
|
||||
} else {
|
||||
text.lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect()
|
||||
};
|
||||
for line in &lines {
|
||||
let mut parts = line.splitn(3, char::is_whitespace);
|
||||
let (set, key, value) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""), parts.next().unwrap_or("").trim());
|
||||
if !set.eq_ignore_ascii_case("set") || key.is_empty() || value.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
|
||||
return bad("Each line must look like: set realmlist 127.0.0.1");
|
||||
}
|
||||
if !value.chars().all(|c| c.is_ascii_graphic() || c == ' ') {
|
||||
return bad("The realmlist may only use plain letters, digits and punctuation.");
|
||||
}
|
||||
if key.eq_ignore_ascii_case("realmlist") && !value.trim_matches('"').chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | ':' | '_')) {
|
||||
return bad("That address is not valid.");
|
||||
}
|
||||
}
|
||||
Ok(lines.join("\r\n") + "\r\n")
|
||||
}
|
||||
|
||||
fn slug(name: &str) -> String {
|
||||
let s: String = name.to_ascii_lowercase().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect();
|
||||
let s = s.trim_matches('-').to_string();
|
||||
if s.is_empty() { "realm".into() } else { s }
|
||||
}
|
||||
|
||||
fn load(meta: &Path, client_dir: Option<&Path>) -> Store {
|
||||
let mut store: Store = fsx::read_json(&meta.join(FILE)).unwrap_or_default();
|
||||
if store.profiles.is_empty() {
|
||||
// First use: "Solo" for this computer, and what the client held before so that it can be switched back to.
|
||||
store.profiles.push(Profile { id: "solo".into(), name: "Solo".into(), data: "set realmlist 127.0.0.1\r\n".into() });
|
||||
if let Some(files) = client_dir.map(client::realmlist_files) {
|
||||
if let Some(text) = files.iter().find_map(|f| fs::read_to_string(f).ok()) {
|
||||
if let Ok(data) = normalize(&text) {
|
||||
if compact(&data) != compact(&store.profiles[0].data) {
|
||||
store.profiles.push(Profile { id: "previous".into(), name: "Previous".into(), data });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = fsx::atomic_write_json(&meta.join(FILE), &store);
|
||||
}
|
||||
store
|
||||
}
|
||||
|
||||
fn save_store(meta: &Path, store: &Store) -> Result<()> {
|
||||
fsx::atomic_write_json(&meta.join(FILE), store)
|
||||
}
|
||||
|
||||
pub fn view(meta: &Path, client_dir: Option<&Path>) -> View {
|
||||
let store = load(meta, client_dir);
|
||||
let active = client_dir.and_then(|c| {
|
||||
let files = client::realmlist_files(c);
|
||||
let texts: Vec<String> = files.iter().filter_map(|f| fs::read_to_string(f).ok()).map(|t| compact(&t)).collect();
|
||||
let first = texts.first()?;
|
||||
if texts.iter().any(|t| t != first) {
|
||||
return None;
|
||||
}
|
||||
store.profiles.iter().find(|p| compact(&p.data) == *first).map(|p| p.id.clone())
|
||||
});
|
||||
View { profiles: store.profiles, active }
|
||||
}
|
||||
|
||||
/// Add a profile (`id` None) or change one. Names are 1-32 characters and unique regardless of capitals.
|
||||
pub fn save_profile(meta: &Path, client_dir: Option<&Path>, id: Option<&str>, name: &str, data: &str) -> Result<Profile> {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || name.chars().count() > 32 || name.chars().any(char::is_control) {
|
||||
return Err(Error::Invalid("The name must be 1 to 32 characters.".into()));
|
||||
}
|
||||
let data = normalize(data)?;
|
||||
let mut store = load(meta, client_dir);
|
||||
if store.profiles.iter().any(|p| p.name.eq_ignore_ascii_case(name) && Some(p.id.as_str()) != id) {
|
||||
return Err(Error::Invalid("A realmlist with that name already exists.".into()));
|
||||
}
|
||||
let profile = match id {
|
||||
Some(id) => {
|
||||
let p = store.profiles.iter_mut().find(|p| p.id == id).ok_or_else(|| Error::Invalid("That realmlist does not exist.".into()))?;
|
||||
p.name = name.to_string();
|
||||
p.data = data;
|
||||
p.clone()
|
||||
}
|
||||
None => {
|
||||
if store.profiles.len() >= MAX_PROFILES {
|
||||
return Err(Error::Invalid("There are too many realmlists; remove one first.".into()));
|
||||
}
|
||||
let mut new_id = slug(name);
|
||||
while store.profiles.iter().any(|p| p.id == new_id) {
|
||||
new_id.push('-');
|
||||
}
|
||||
let p = Profile { id: new_id, name: name.to_string(), data };
|
||||
store.profiles.push(p.clone());
|
||||
p
|
||||
}
|
||||
};
|
||||
save_store(meta, &store)?;
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
pub fn delete_profile(meta: &Path, client_dir: Option<&Path>, id: &str) -> Result<()> {
|
||||
let mut store = load(meta, client_dir);
|
||||
if store.profiles.len() <= 1 {
|
||||
return Err(Error::Invalid("The last realmlist cannot be removed.".into()));
|
||||
}
|
||||
store.profiles.retain(|p| p.id != id);
|
||||
save_store(meta, &store)
|
||||
}
|
||||
|
||||
/// Write the profile into the client; returns the files that changed (each was saved to the backup folder first).
|
||||
pub fn activate(meta: &Path, client_dir: &Path, id: &str) -> Result<Vec<String>> {
|
||||
let store = load(meta, Some(client_dir));
|
||||
let profile = store.profiles.iter().find(|p| p.id == id).ok_or_else(|| Error::Invalid("That realmlist does not exist.".into()))?;
|
||||
client::write_realmlist(client_dir, meta, &profile.data)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn fake_client(d: &Path, host: &str) -> std::path::PathBuf {
|
||||
let c = d.join("wow");
|
||||
for loc in ["enUS", "ruRU"] {
|
||||
fs::create_dir_all(c.join("Data").join(loc)).unwrap();
|
||||
fs::write(c.join("Data").join(loc).join("realmlist.wtf"), format!("set realmlist {host}\r\nset patchlist x.example\r\n")).unwrap();
|
||||
}
|
||||
fs::write(c.join("Ascension.exe"), b"exe").unwrap();
|
||||
c
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_or_whole_lines_are_accepted_and_anything_else_is_not() {
|
||||
assert_eq!(normalize("play.example.com").unwrap(), "set realmlist play.example.com\r\n");
|
||||
assert_eq!(normalize("SET realmlist 192.168.0.5:3724\nset patchlist x.example\n").unwrap(), "SET realmlist 192.168.0.5:3724\r\nset patchlist x.example\r\n");
|
||||
for bad in ["", " ", "rm -rf /", "set realmlist bad host;calc", "set realmlist", "x\ny", "set realmlist a\"b", &"a".repeat(2100)] {
|
||||
assert!(normalize(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_use_offers_solo_and_what_the_client_had_and_the_active_one_is_recognised() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (c, meta) = (fake_client(d.path(), "ptr.example.org"), d.path().join("meta"));
|
||||
fs::create_dir_all(&meta).unwrap();
|
||||
let v = view(&meta, Some(&c));
|
||||
assert_eq!(v.profiles.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Solo", "Previous"]);
|
||||
assert_eq!(v.active.as_deref(), Some("previous"), "the files hold exactly what was captured");
|
||||
assert!(activate(&meta, &c, "previous").unwrap().is_empty(), "already what the files hold");
|
||||
assert_eq!(fs::read_to_string(c.join("Data/enUS/realmlist.wtf")).unwrap(), "set realmlist ptr.example.org\r\nset patchlist x.example\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_writes_every_locale_saves_the_old_file_and_changes_nothing_else() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let (c, meta) = (fake_client(d.path(), "ptr.example.org"), d.path().join("meta"));
|
||||
fs::create_dir_all(&meta).unwrap();
|
||||
fs::write(c.join("WTF.txt"), b"mine").unwrap();
|
||||
let ptr = save_profile(&meta, Some(&c), None, "PTR", "ptr.example.org").unwrap();
|
||||
let changed = activate(&meta, &c, "solo").unwrap();
|
||||
assert_eq!(changed.len(), 2);
|
||||
for loc in ["enUS", "ruRU"] {
|
||||
assert_eq!(fs::read_to_string(c.join("Data").join(loc).join("realmlist.wtf")).unwrap(), "set realmlist 127.0.0.1\r\n");
|
||||
}
|
||||
assert_eq!(view(&meta, Some(&c)).active.as_deref(), Some("solo"));
|
||||
assert_eq!(fs::read_dir(meta.join("backups/client")).unwrap().count(), 2, "each replaced file was saved");
|
||||
activate(&meta, &c, &ptr.id).unwrap();
|
||||
assert_eq!(view(&meta, Some(&c)).active.as_deref(), Some(ptr.id.as_str()));
|
||||
assert_eq!(fs::read(c.join("WTF.txt")).unwrap(), b"mine");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_unique_profiles_can_be_edited_and_the_last_one_stays() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let meta = d.path().join("meta");
|
||||
fs::create_dir_all(&meta).unwrap();
|
||||
let a = save_profile(&meta, None, None, "PTR", "ptr.example.org").unwrap();
|
||||
assert!(save_profile(&meta, None, None, "ptr", "other.example.org").is_err(), "names are unique regardless of capitals");
|
||||
let edited = save_profile(&meta, None, Some(&a.id), "PTR 2", "ptr2.example.org").unwrap();
|
||||
assert_eq!((edited.id.as_str(), edited.data.as_str()), (a.id.as_str(), "set realmlist ptr2.example.org\r\n"));
|
||||
assert!(save_profile(&meta, None, None, "", "x.example.org").is_err());
|
||||
delete_profile(&meta, None, &a.id).unwrap();
|
||||
assert!(delete_profile(&meta, None, "solo").is_err(), "one profile must remain");
|
||||
assert_eq!(view(&meta, None).profiles.len(), 1);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user