Skip to main content

thunderstore_engine/profile/
layout.rs

1//! Directory layout and profile lifecycle.
2//!
3//! Profiles live at `<base>/<game>/profiles/<name>/`, matching r2modman so a
4//! profile directory produced here works when copied into r2modman's data dir.
5//! The caller owns `base` (platform/path discovery stays outside the engine).
6//!
7//! # Errors
8//!
9//! A refused or missing profile name is
10//! [`Error::BadProfile`](crate::Error::BadProfile); every other failure is
11//! [`Error::Profile`](crate::Error::Profile). Underlying IO failures are wrapped
12//! with the offending path rather than surfaced as
13//! [`Error::Io`](crate::Error::Io), so a caller can render the message directly
14//! and does not need to prepend a path itself.
15//!
16//! A name for a new profile (`create`, and the destination of `rename` and
17//! `duplicate`) goes through
18//! [`validate_name`](crate::profile::layout::validate_name), so a name that
19//! could escape the profiles directory, or that Windows cannot hold, is refused
20//! before the filesystem is touched. A name for an existing profile is refused
21//! only if it could escape the profiles directory, so a profile named under
22//! older, looser rules stays usable. Individual functions document only the
23//! conditions beyond that shared contract.
24
25#![deny(missing_docs)]
26
27#[cfg(feature = "io")]
28use crate::error::{Error, Result};
29#[cfg(feature = "io")]
30use std::fs;
31use std::path::{Path, PathBuf};
32
33/// The profiles directory for a game: `<base>/<game>/profiles`.
34pub fn profiles_dir(base: &Path, game: &str) -> PathBuf {
35  base.join(game).join("profiles")
36}
37
38/// A single profile directory: `<base>/<game>/profiles/<name>`.
39pub fn profile_dir(base: &Path, game: &str, name: &str) -> PathBuf {
40  profiles_dir(base, game).join(name)
41}
42
43/// Refuses a profile name that could escape the profiles directory or that
44/// Windows cannot hold as a folder name, with the reason as a [`BadName`].
45///
46/// The Windows rules apply on every OS so a profile stays portable. The error
47/// is always [`BadProfile::InvalidName`].
48///
49/// # Examples
50///
51/// ```
52/// use thunderstore_engine::profile::layout::{BadName, BadProfile, validate_name};
53///
54/// assert!(validate_name("Main").is_ok());
55/// assert!(matches!(
56///   validate_name("CON.txt"),
57///   Err(BadProfile::InvalidName { reason: BadName::Reserved, .. })
58/// ));
59/// ```
60pub fn validate_name(name: &str) -> std::result::Result<(), BadProfile> {
61  refuse_if(
62    name,
63    escape_problem(name).or_else(|| portability_problem(name)),
64  )
65}
66
67/// Refuses the name of an existing profile only when it could escape the
68/// profiles directory, so a profile named under older, looser rules can still
69/// be used, renamed, and deleted.
70#[cfg(feature = "io")]
71pub(crate) fn validate_existing_name(name: &str) -> std::result::Result<(), BadProfile> {
72  refuse_if(name, escape_problem(name))
73}
74
75fn refuse_if(name: &str, problem: Option<BadName>) -> std::result::Result<(), BadProfile> {
76  match problem {
77    Some(reason) => Err(BadProfile::InvalidName {
78      name: name.to_string(),
79      reason,
80    }),
81    None => Ok(()),
82  }
83}
84
85/// Why `name` could resolve outside the profiles directory, if it could.
86fn escape_problem(name: &str) -> Option<BadName> {
87  if name.is_empty() {
88    return Some(BadName::Empty);
89  }
90
91  // Windows drops trailing dots and spaces from a path's last component, so
92  // `" "` or `"..."` would resolve to the profiles directory itself.
93  let resolved = name.trim_end_matches(['.', ' ']);
94
95  if matches!(resolved, "" | "." | "..") || name.contains(['/', '\\']) {
96    return Some(BadName::Escapes);
97  }
98
99  let mut chars = name.chars();
100
101  if matches!((chars.next(), chars.next()), (Some(drive), Some(':')) if drive.is_ascii_alphabetic())
102  {
103    return Some(BadName::DrivePrefix);
104  }
105
106  None
107}
108
109/// The first Windows folder-name rule `name` breaks, checked from most to least
110/// specific.
111fn portability_problem(name: &str) -> Option<BadName> {
112  if let Some(found) = name
113    .chars()
114    .find(|c| c.is_ascii_control() || matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*'))
115  {
116    return Some(BadName::ForbiddenChar(found));
117  }
118
119  if name.ends_with(['.', ' ']) {
120    return Some(BadName::TrailingDotOrSpace);
121  }
122
123  if is_reserved_device(name) {
124    return Some(BadName::Reserved);
125  }
126
127  None
128}
129
130/// Whether the part of `name` before its first `.` is a Windows device name,
131/// per Microsoft's "Naming Files, Paths, and Namespaces", which also reserves
132/// `COM` and `LPT` followed by 0 or a superscript 1, 2, or 3.
133fn is_reserved_device(name: &str) -> bool {
134  let stem = name
135    .split('.')
136    .next()
137    .unwrap_or(name)
138    .trim_end_matches(' ')
139    .to_ascii_uppercase();
140
141  match stem.as_str() {
142    "CON" | "PRN" | "AUX" | "NUL" => true,
143    _ => {
144      let numbered = stem
145        .strip_prefix("COM")
146        .or_else(|| stem.strip_prefix("LPT"));
147
148      matches!(
149        numbered,
150        Some(
151          "0"
152            | "1"
153            | "2"
154            | "3"
155            | "4"
156            | "5"
157            | "6"
158            | "7"
159            | "8"
160            | "9"
161            | "\u{b9}"
162            | "\u{b2}"
163            | "\u{b3}"
164        )
165      )
166    }
167  }
168}
169
170/// Lists profile names (immediate subdirectories) for a game, sorted. A missing
171/// profiles directory yields an empty list.
172#[cfg(feature = "io")]
173pub fn list(base: &Path, game: &str) -> Result<Vec<String>> {
174  let dir = profiles_dir(base, game);
175
176  if !dir.is_dir() {
177    return Ok(Vec::new());
178  }
179
180  let mut names = Vec::new();
181
182  for entry in
183    fs::read_dir(&dir).map_err(|e| Error::Profile(format!("reading {}: {}", dir.display(), e)))?
184  {
185    let entry = entry.map_err(|e| Error::Profile(format!("reading an entry: {e}")))?;
186
187    if entry.path().is_dir()
188      && let Some(name) = entry.file_name().to_str()
189    {
190      names.push(name.to_string());
191    }
192  }
193
194  names.sort();
195
196  Ok(names)
197}
198
199/// Creates a new, empty profile directory. Errors if it already exists so a
200/// create never silently adopts an existing profile.
201#[cfg(feature = "io")]
202pub fn create(base: &Path, game: &str, name: &str) -> Result<PathBuf> {
203  validate_name(name)?;
204
205  let dir = profile_dir(base, game, name);
206
207  if dir.exists() {
208    return Err(Error::Profile(format!("profile {name:?} already exists")));
209  }
210
211  fs::create_dir_all(&dir)
212    .map_err(|e| Error::Profile(format!("creating {}: {}", dir.display(), e)))?;
213
214  Ok(dir)
215}
216
217/// Removes a profile directory and everything under it, and clears the stored
218/// selection if it named this profile.
219///
220/// # Errors
221///
222/// [`BadProfile::Missing`] if the profile does not exist, so deleting an
223/// already-deleted profile is reported rather than treated as success.
224#[cfg(feature = "io")]
225pub fn delete(base: &Path, game: &str, name: &str) -> Result<()> {
226  let dir = require_profile(base, game, name)?;
227
228  fs::remove_dir_all(&dir)
229    .map_err(|e| Error::Profile(format!("deleting {}: {}", dir.display(), e)))?;
230
231  if read_selection(base, game).as_deref() == Some(name) {
232    clear_selection(base, game)?;
233  }
234
235  Ok(())
236}
237
238/// Renames a profile, carrying the stored selection across if it named `from`.
239///
240/// # Errors
241///
242/// [`BadProfile::Missing`] if `from` does not exist. Errors if `to` already
243/// exists, so a rename never clobbers another profile.
244///
245/// Not transactional: the rename can succeed and the selection update then fail,
246/// leaving the selection naming a profile that no longer exists. Callers that
247/// care can re-read it with [`read_selection`].
248#[cfg(feature = "io")]
249pub fn rename(base: &Path, game: &str, from: &str, to: &str) -> Result<()> {
250  let src = require_profile(base, game, from)?;
251
252  validate_name(to)?;
253
254  let dst = profile_dir(base, game, to);
255
256  if dst.exists() {
257    return Err(Error::Profile(format!("profile {to:?} already exists")));
258  }
259
260  fs::rename(&src, &dst).map_err(|e| {
261    Error::Profile(format!(
262      "renaming {} to {}: {}",
263      src.display(),
264      dst.display(),
265      e
266    ))
267  })?;
268
269  // Carry the selection across, or it is left naming a directory that no longer
270  // exists. Not transactional: a failed write here leaves that dangling state.
271  // The window is narrow and accepted rather than missed.
272  if read_selection(base, game).as_deref() == Some(from) {
273    write_selection(base, game, to)?;
274  }
275
276  Ok(())
277}
278
279/// Duplicates a profile directory (recursive copy) under a new name.
280///
281/// Symlinks are skipped rather than followed or recreated, so the copy cannot be
282/// made to write outside `to`.
283///
284/// # Errors
285///
286/// [`BadProfile::Missing`] if `from` does not exist. Errors if `to` already
287/// exists. A failed copy can leave `to` partially written; it is not cleaned
288/// up.
289#[cfg(feature = "io")]
290pub fn duplicate(base: &Path, game: &str, from: &str, to: &str) -> Result<PathBuf> {
291  let src = require_profile(base, game, from)?;
292
293  validate_name(to)?;
294
295  let dst = profile_dir(base, game, to);
296
297  if dst.exists() {
298    return Err(Error::Profile(format!("profile {to:?} already exists")));
299  }
300
301  copy_tree(&src, &dst)?;
302
303  Ok(dst)
304}
305
306/// Recursively copies a directory tree, creating `dst`. Skips symlinks (never
307/// follows them out of the tree), like the install layer's `walk_files`.
308#[cfg(feature = "io")]
309fn copy_tree(src: &Path, dst: &Path) -> Result<()> {
310  fs::create_dir_all(dst)
311    .map_err(|e| Error::Profile(format!("creating {}: {}", dst.display(), e)))?;
312
313  for entry in
314    fs::read_dir(src).map_err(|e| Error::Profile(format!("reading {}: {}", src.display(), e)))?
315  {
316    let entry = entry.map_err(|e| Error::Profile(format!("reading an entry: {e}")))?;
317    let metadata = fs::symlink_metadata(entry.path())
318      .map_err(|e| Error::Profile(format!("inspecting {}: {}", entry.path().display(), e)))?;
319
320    if metadata.file_type().is_symlink() {
321      continue;
322    }
323
324    let target = dst.join(entry.file_name());
325
326    if metadata.is_dir() {
327      copy_tree(&entry.path(), &target)?;
328    } else {
329      // `duplicate`'s src and dst are both `profile_dir(base, game, <name>)`
330      // siblings under one parent, and `dst.exists()` refuses the equal case
331      // before this ever runs, so an overlapping source and target cannot
332      // reach here today. The skip is added anyway: a future caller of
333      // `copy_tree` reaching it another way could otherwise truncate a file by
334      // copying it onto itself, the same failure mode `same_file` guards
335      // against in the portability layer's `copy_tree` and in
336      // `stage_one_file`.
337      if crate::util::same_file(&entry.path(), &target) {
338        continue;
339      }
340
341      fs::copy(entry.path(), &target)
342        .map_err(|e| Error::Profile(format!("copying to {}: {}", target.display(), e)))?;
343    }
344  }
345
346  Ok(())
347}
348
349/// The file under `<base>/<game>/` recording which profile is active.
350const SELECTION_FILE: &str = "selected_profile";
351
352/// The path of the persisted profile selection.
353///
354/// Public because two clients sharing one base directory must agree on this path
355/// or they silently stop seeing each other's active profile.
356pub fn selection_path(base: &Path, game: &str) -> PathBuf {
357  base.join(game).join(SELECTION_FILE)
358}
359
360/// The persisted selection, or `None` when absent, empty, or unreadable.
361#[cfg(feature = "io")]
362pub fn read_selection(base: &Path, game: &str) -> Option<String> {
363  let text = fs::read_to_string(selection_path(base, game)).ok()?;
364  let name = text.trim();
365
366  match name.is_empty() {
367    true => None,
368    false => Some(name.to_string()),
369  }
370}
371
372/// Persists `name` as the selected profile.
373#[cfg(feature = "io")]
374pub fn write_selection(base: &Path, game: &str, name: &str) -> Result<()> {
375  let path = selection_path(base, game);
376
377  if let Some(parent) = path.parent() {
378    fs::create_dir_all(parent)
379      .map_err(|e| Error::Profile(format!("creating {}: {}", parent.display(), e)))?;
380  }
381
382  fs::write(&path, name).map_err(|e| Error::Profile(format!("writing {}: {}", path.display(), e)))
383}
384
385/// Removes the persisted selection, returning to game-directory mode. Absent is
386/// not an error.
387#[cfg(feature = "io")]
388pub fn clear_selection(base: &Path, game: &str) -> Result<()> {
389  let path = selection_path(base, game);
390
391  if !path.exists() {
392    return Ok(());
393  }
394
395  fs::remove_file(&path).map_err(|e| Error::Profile(format!("removing {}: {}", path.display(), e)))
396}
397
398/// Why a profile name cannot be used.
399///
400/// Returned rather than flattened into a message so a caller wording the refusal
401/// itself, e.g. to offer to create the profile, gets the reason and the path it
402/// would go at instead of a sentence it would have to re-derive both from.
403/// Travels inside [`Error::BadProfile`] out of operations that have other ways
404/// to fail, so no such operation has to give up its single error type or its
405/// composition to keep the reason intact.
406///
407/// Deliberately **not** `#[non_exhaustive]`, matching [`super::NotRemovable`]: a
408/// caller that words each refusal should stop compiling when a new reason
409/// appears, rather than printing a generic fallback for a case nobody worded.
410/// [`Error`] being `#[non_exhaustive]` does not weaken that: the wildcard arm a
411/// client needs there is for other kinds of failure, not for other refusals.
412#[derive(Debug, Clone, PartialEq, Eq)]
413pub enum BadProfile {
414  /// The name is refused by [`validate_name`] or, for an existing profile,
415  /// could escape the profiles directory.
416  InvalidName {
417    /// The name as given.
418    name: String,
419    /// Which rule the name breaks.
420    reason: BadName,
421  },
422  /// No profile directory exists at `dir`.
423  Missing {
424    /// The name as given.
425    name: String,
426    /// Where the profile was expected.
427    dir: PathBuf,
428  },
429}
430
431impl std::fmt::Display for BadProfile {
432  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433    match self {
434      Self::InvalidName { name, .. } => write!(f, "invalid profile name {name:?}"),
435      Self::Missing { name, .. } => write!(f, "there is no profile named {name:?}"),
436    }
437  }
438}
439
440impl std::error::Error for BadProfile {}
441
442/// Why [`validate_name`] refuses a profile name.
443///
444/// Not `#[non_exhaustive]`, for the reason [`BadProfile`] gives.
445#[derive(Debug, Clone, PartialEq, Eq)]
446pub enum BadName {
447  /// The name is empty.
448  Empty,
449  /// The name is `.` or `..`, or contains `/` or `\`, so it could resolve
450  /// outside the profiles directory.
451  Escapes,
452  /// The name starts with a drive letter and a colon (`C:foo`), which Windows
453  /// resolves on that drive instead of under the profiles directory.
454  DrivePrefix,
455  /// A Windows device name (`CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`,
456  /// `LPT1`-`LPT9`, and `COM`/`LPT` with a superscript `¹`, `²`, or `³`), in
457  /// any case, alone or followed by an extension.
458  Reserved,
459  /// A character Windows forbids in a folder name: `< > : " | ? *` or a
460  /// control character.
461  ForbiddenChar(char),
462  /// The name ends with `.` or a space, which Windows strips.
463  TrailingDotOrSpace,
464}
465
466impl std::fmt::Display for BadName {
467  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
468    match self {
469      Self::Empty => write!(f, "the name is empty"),
470      Self::Escapes => write!(f, "the name is a path, not a single folder name"),
471      Self::DrivePrefix => write!(f, "the name starts with a drive letter"),
472      Self::Reserved => write!(f, "the name is reserved by Windows"),
473      Self::ForbiddenChar(found) => write!(f, "the name contains {found:?}"),
474      Self::TrailingDotOrSpace => write!(f, "the name ends with a dot or a space"),
475    }
476  }
477}
478
479/// The directory of an existing profile, classifying why not when there is none.
480///
481/// The single place that decides "is this a usable profile name": both
482/// [`use_profile`] and [`crate::profile::target::InstallTarget::resolve`] go
483/// through it, so they cannot drift apart, and a caller that wants to word the
484/// refusal itself gets the reason rather than a sentence.
485///
486/// Only a name that could escape the profiles directory is refused as
487/// [`BadProfile::InvalidName`]; the stricter [`validate_name`] rules apply to
488/// new names, so a profile named under older rules can still be found here.
489#[cfg(feature = "io")]
490pub fn require_profile(
491  base: &Path,
492  game: &str,
493  name: &str,
494) -> std::result::Result<PathBuf, BadProfile> {
495  validate_existing_name(name)?;
496
497  let dir = profile_dir(base, game, name);
498
499  if !dir.is_dir() {
500    return Err(BadProfile::Missing {
501      name: name.to_string(),
502      dir,
503    });
504  }
505
506  Ok(dir)
507}
508
509/// Selects `name` as the active profile, refusing one that does not exist.
510#[cfg(feature = "io")]
511pub fn use_profile(base: &Path, game: &str, name: &str) -> Result<()> {
512  require_profile(base, game, name)?;
513
514  write_selection(base, game, name)
515}
516
517/// Chooses the active profile from a caller's override and the persisted
518/// selection. Pure, so the precedence is testable without touching disk.
519///
520/// An explicit `flag` wins. `no_profile` opts out of a persisted selection.
521/// Otherwise the persisted selection applies, and its absence means
522/// game-directory mode.
523pub fn select_profile(
524  flag: Option<&str>,
525  no_profile: bool,
526  persisted: Option<&str>,
527) -> Option<String> {
528  if let Some(name) = flag {
529    return Some(name.to_string());
530  }
531
532  if no_profile {
533    return None;
534  }
535
536  persisted.map(|name| name.to_string())
537}
538
539#[cfg(test)]
540mod tests {
541  use super::*;
542  #[cfg(feature = "io")]
543  use std::fs;
544  #[cfg(feature = "io")]
545  use tempfile::tempdir;
546
547  #[test]
548  fn paths_follow_r2modman_layout() {
549    let base = Path::new("/base");
550
551    assert_eq!(
552      profiles_dir(base, "valheim"),
553      Path::new("/base/valheim/profiles")
554    );
555    assert_eq!(
556      profile_dir(base, "valheim", "Main"),
557      Path::new("/base/valheim/profiles/Main")
558    );
559  }
560
561  #[test]
562  fn validate_name_rejects_unsafe() {
563    assert!(validate_name("Main").is_ok());
564    assert!(validate_name("").is_err());
565    assert!(validate_name("..").is_err());
566    assert!(validate_name("a/b").is_err());
567    assert!(validate_name("a\\b").is_err());
568  }
569
570  fn refusal(name: &str) -> Option<BadName> {
571    match validate_name(name) {
572      Ok(()) => None,
573      Err(BadProfile::InvalidName { reason, .. }) => Some(reason),
574      Err(other) => panic!("{name:?} must be refused as a name; got: {other:?}"),
575    }
576  }
577
578  #[test]
579  fn names_windows_cannot_hold_are_refused_on_every_os() {
580    let cases = [
581      ("", BadName::Empty),
582      (".", BadName::Escapes),
583      ("..", BadName::Escapes),
584      ("a/b", BadName::Escapes),
585      ("a\\b", BadName::Escapes),
586      ("/abs", BadName::Escapes),
587      ("C:foo", BadName::DrivePrefix),
588      ("c:", BadName::DrivePrefix),
589      ("CON", BadName::Reserved),
590      ("con", BadName::Reserved),
591      ("Nul.txt", BadName::Reserved),
592      ("aux.tar.gz", BadName::Reserved),
593      ("NUL .txt", BadName::Reserved),
594      ("PRN", BadName::Reserved),
595      ("COM1", BadName::Reserved),
596      ("com9.log", BadName::Reserved),
597      ("LPT5", BadName::Reserved),
598      ("COM0", BadName::Reserved),
599      ("lpt0.bak", BadName::Reserved),
600      ("COM\u{b9}", BadName::Reserved),
601      ("com\u{b2}.log", BadName::Reserved),
602      ("COM\u{b3}", BadName::Reserved),
603      ("LPT\u{b9}", BadName::Reserved),
604      ("lpt\u{b2}", BadName::Reserved),
605      ("LPT\u{b3}.txt", BadName::Reserved),
606      ("a:b", BadName::DrivePrefix),
607      ("ab:c", BadName::ForbiddenChar(':')),
608      ("why?", BadName::ForbiddenChar('?')),
609      ("a*b", BadName::ForbiddenChar('*')),
610      ("a<b", BadName::ForbiddenChar('<')),
611      ("a>b", BadName::ForbiddenChar('>')),
612      ("a|b", BadName::ForbiddenChar('|')),
613      ("say \"hi\"", BadName::ForbiddenChar('"')),
614      ("tab\there", BadName::ForbiddenChar('\t')),
615      ("nul\0byte", BadName::ForbiddenChar('\0')),
616      ("trailing.", BadName::TrailingDotOrSpace),
617      ("trailing ", BadName::TrailingDotOrSpace),
618      ("...", BadName::Escapes),
619    ];
620
621    for (name, expected) in cases {
622      assert_eq!(refusal(name), Some(expected), "for {name:?}");
623    }
624  }
625
626  #[test]
627  fn names_that_only_resemble_reserved_ones_are_allowed() {
628    for name in [
629      "Main",
630      "work profile",
631      "CONSOLE",
632      "COM10",
633      "COM\u{2074}",
634      "LPT\u{b9}\u{b2}",
635      "nul-run",
636      "my.profile",
637      ".hidden",
638      "1.0",
639    ] {
640      assert_eq!(refusal(name), None, "for {name:?}");
641    }
642  }
643
644  #[test]
645  fn a_refused_name_keeps_its_message_and_carries_the_reason() {
646    let error = crate::Error::from(validate_name("CON").unwrap_err());
647
648    assert_eq!(
649      error.to_string(),
650      "Profile error: invalid profile name \"CON\""
651    );
652    assert!(matches!(
653      error,
654      crate::Error::BadProfile(BadProfile::InvalidName {
655        reason: BadName::Reserved,
656        ..
657      })
658    ));
659  }
660
661  #[test]
662  #[cfg(feature = "io")]
663  fn create_list_rename_duplicate_delete() {
664    let dir = tempdir().unwrap();
665    let base = dir.path();
666
667    assert_eq!(list(base, "valheim").unwrap(), Vec::<String>::new());
668
669    create(base, "valheim", "Main").unwrap();
670
671    assert!(profile_dir(base, "valheim", "Main").is_dir());
672    assert!(create(base, "valheim", "Main").is_err()); // already exists
673
674    fs::write(profile_dir(base, "valheim", "Main").join("mods.yml"), "[]").unwrap();
675
676    duplicate(base, "valheim", "Main", "Copy").unwrap();
677
678    assert!(
679      profile_dir(base, "valheim", "Copy")
680        .join("mods.yml")
681        .exists()
682    );
683
684    rename(base, "valheim", "Copy", "Renamed").unwrap();
685
686    let mut names = list(base, "valheim").unwrap();
687    names.sort();
688
689    assert_eq!(names, vec!["Main".to_string(), "Renamed".to_string()]);
690
691    delete(base, "valheim", "Main").unwrap();
692
693    assert_eq!(list(base, "valheim").unwrap(), vec!["Renamed".to_string()]);
694  }
695
696  #[test]
697  #[cfg(feature = "io")]
698  fn delete_rename_and_duplicate_refuse_a_missing_profile_by_reason() {
699    let base = tempdir().unwrap();
700    let root = base.path();
701    let expected = profile_dir(root, "valheim", "ghost");
702    let is_missing = |error: Error| {
703      matches!(error, Error::BadProfile(BadProfile::Missing { name, dir })
704        if name == "ghost" && dir == expected)
705    };
706
707    assert!(is_missing(delete(root, "valheim", "ghost").unwrap_err()));
708    assert!(is_missing(
709      rename(root, "valheim", "ghost", "other").unwrap_err()
710    ));
711    assert!(is_missing(
712      duplicate(root, "valheim", "ghost", "other").unwrap_err()
713    ));
714    assert!(
715      !profile_dir(root, "valheim", "other").exists(),
716      "a refused duplicate must not leave a target behind"
717    );
718  }
719
720  #[test]
721  #[cfg(feature = "io")]
722  fn create_rename_and_duplicate_refuse_a_name_windows_cannot_hold() {
723    let base = tempdir().unwrap();
724    let root = base.path();
725
726    create(root, "valheim", "Main").unwrap();
727
728    for error in [
729      create(root, "valheim", "C:evil").unwrap_err(),
730      rename(root, "valheim", "Main", "CON").unwrap_err(),
731      duplicate(root, "valheim", "Main", "copy.").unwrap_err(),
732    ] {
733      assert!(
734        matches!(error, Error::BadProfile(BadProfile::InvalidName { .. })),
735        "got: {error:?}"
736      );
737    }
738
739    assert_eq!(list(root, "valheim").unwrap(), vec!["Main".to_string()]);
740  }
741
742  #[test]
743  #[cfg(all(unix, feature = "io"))]
744  fn a_profile_named_under_the_old_rules_stays_usable() {
745    let base = tempdir().unwrap();
746    let root = base.path();
747    let legacy = ["Modded.", "v2: test", "aux"];
748
749    for name in legacy {
750      fs::create_dir_all(profile_dir(root, "valheim", name)).unwrap();
751    }
752
753    assert_eq!(
754      list(root, "valheim").unwrap(),
755      vec!["Modded.", "aux", "v2: test"]
756    );
757
758    use_profile(root, "valheim", "Modded.").unwrap();
759    rename(root, "valheim", "Modded.", "Modded").unwrap();
760
761    assert_eq!(read_selection(root, "valheim"), Some("Modded".to_string()));
762
763    duplicate(root, "valheim", "v2: test", "v2 copy").unwrap();
764    delete(root, "valheim", "aux").unwrap();
765    delete(root, "valheim", "v2: test").unwrap();
766
767    assert_eq!(list(root, "valheim").unwrap(), vec!["Modded", "v2 copy"]);
768
769    let resolved = crate::profile::target::InstallTarget::resolve(
770      root.to_path_buf(),
771      root.join("game"),
772      "valheim",
773      Some("v2 copy"),
774    )
775    .unwrap();
776
777    assert_eq!(resolved.dir, profile_dir(root, "valheim", "v2 copy"));
778  }
779
780  #[test]
781  #[cfg(all(unix, feature = "io"))]
782  fn an_existing_profile_still_cannot_be_renamed_to_a_name_windows_cannot_hold() {
783    let base = tempdir().unwrap();
784    let root = base.path();
785
786    fs::create_dir_all(profile_dir(root, "valheim", "aux")).unwrap();
787
788    for error in [
789      rename(root, "valheim", "aux", "nul").unwrap_err(),
790      duplicate(root, "valheim", "aux", "copy.").unwrap_err(),
791    ] {
792      assert!(
793        matches!(error, Error::BadProfile(BadProfile::InvalidName { .. })),
794        "got: {error:?}"
795      );
796    }
797  }
798
799  #[test]
800  #[cfg(feature = "io")]
801  fn an_existing_profile_name_that_escapes_is_still_refused() {
802    let base = tempdir().unwrap();
803    let root = base.path();
804
805    for (name, expected) in [
806      ("", BadName::Empty),
807      (".", BadName::Escapes),
808      ("..", BadName::Escapes),
809      (" ", BadName::Escapes),
810      ("...", BadName::Escapes),
811      (". .", BadName::Escapes),
812      (".. ", BadName::Escapes),
813      ("../escape", BadName::Escapes),
814      ("a\\b", BadName::Escapes),
815      ("C:evil", BadName::DrivePrefix),
816    ] {
817      let refused = require_profile(root, "valheim", name).unwrap_err();
818
819      assert_eq!(
820        refused,
821        BadProfile::InvalidName {
822          name: name.to_string(),
823          reason: expected,
824        },
825        "for {name:?}"
826      );
827    }
828  }
829
830  #[test]
831  #[cfg(feature = "io")]
832  fn the_selection_follows_a_rename_and_clears_on_delete() {
833    let base = tempdir().unwrap();
834    let root = base.path();
835
836    create(root, "valheim", "one").unwrap();
837    create(root, "valheim", "two").unwrap();
838
839    assert_eq!(read_selection(root, "valheim"), None);
840
841    use_profile(root, "valheim", "one").unwrap();
842
843    assert_eq!(read_selection(root, "valheim"), Some("one".to_string()));
844
845    // Renaming the selected profile must carry the selection with it, or the
846    // selection is left naming a directory that no longer exists.
847    rename(root, "valheim", "one", "renamed").unwrap();
848
849    assert_eq!(read_selection(root, "valheim"), Some("renamed".to_string()));
850
851    // Renaming a profile that is not selected must not disturb the selection.
852    rename(root, "valheim", "two", "other").unwrap();
853
854    assert_eq!(read_selection(root, "valheim"), Some("renamed".to_string()));
855
856    // Deleting a profile that is not selected leaves the selection alone.
857    delete(root, "valheim", "other").unwrap();
858
859    assert_eq!(read_selection(root, "valheim"), Some("renamed".to_string()));
860
861    // Deleting the selected one clears it, returning to game-directory mode.
862    delete(root, "valheim", "renamed").unwrap();
863
864    assert_eq!(read_selection(root, "valheim"), None);
865
866    // Selecting something that does not exist is refused.
867    assert!(use_profile(root, "valheim", "ghost").is_err());
868    // Clearing an already-absent selection is not an error.
869    clear_selection(root, "valheim").unwrap();
870  }
871
872  #[test]
873  #[cfg(feature = "io")]
874  fn require_profile_classifies_why_a_name_is_unusable() {
875    let base = tempdir().unwrap();
876    let root = base.path();
877
878    create(root, "valheim", "one").unwrap();
879
880    assert_eq!(
881      require_profile(root, "valheim", "one").unwrap(),
882      profile_dir(root, "valheim", "one")
883    );
884
885    let unsafe_name = require_profile(root, "valheim", "../escape").unwrap_err();
886
887    assert!(
888      matches!(&unsafe_name, BadProfile::InvalidName { name, .. } if name == "../escape"),
889      "an unsafe name must be told apart from an absent one; got: {unsafe_name:?}"
890    );
891
892    let missing = require_profile(root, "valheim", "ghost").unwrap_err();
893
894    // The expected directory comes back with the refusal, so a caller offering
895    // to create the profile does not have to recompute where it would go.
896    assert!(
897      matches!(&missing, BadProfile::Missing { name, dir }
898        if name == "ghost" && dir == &profile_dir(root, "valheim", "ghost")),
899      "a missing profile must carry its name and expected directory; got: {missing:?}"
900    );
901  }
902
903  #[test]
904  #[cfg(feature = "io")]
905  fn use_profile_and_resolve_refuse_a_missing_profile_identically() {
906    let base = tempdir().unwrap();
907    let root = base.path();
908    let game_dir = tempdir().unwrap();
909
910    // Both entry points classify through `require_profile`, so neither can drift
911    // into wording the same refusal differently.
912    let selecting = use_profile(root, "valheim", "ghost").unwrap_err();
913    let resolving = crate::profile::target::InstallTarget::resolve(
914      root.to_path_buf(),
915      game_dir.path().to_path_buf(),
916      "valheim",
917      Some("ghost"),
918    )
919    .unwrap_err();
920
921    assert_eq!(selecting.to_string(), resolving.to_string());
922    assert_eq!(
923      selecting.to_string(),
924      "Profile error: there is no profile named \"ghost\""
925    );
926
927    // Not just the same sentence: the same matchable reason, so a caller wording
928    // it does not have to care which entry point refused.
929    assert!(
930      matches!(selecting, Error::BadProfile(BadProfile::Missing { .. }))
931        && matches!(resolving, Error::BadProfile(BadProfile::Missing { .. })),
932      "both must carry the reason, not a flattened message"
933    );
934
935    let selecting = use_profile(root, "valheim", "a/b").unwrap_err();
936    let resolving = crate::profile::target::InstallTarget::resolve(
937      root.to_path_buf(),
938      game_dir.path().to_path_buf(),
939      "valheim",
940      Some("a/b"),
941    )
942    .unwrap_err();
943
944    assert_eq!(selecting.to_string(), resolving.to_string());
945    assert_eq!(
946      selecting.to_string(),
947      "Profile error: invalid profile name \"a/b\""
948    );
949  }
950
951  #[test]
952  fn select_profile_precedence() {
953    // An explicit flag wins over everything.
954    assert_eq!(
955      select_profile(Some("experiment"), false, Some("saved")),
956      Some("experiment".to_string())
957    );
958    // Opting out ignores a persisted selection.
959    assert_eq!(select_profile(None, true, Some("saved")), None);
960    // A persisted selection applies when nothing overrides it.
961    assert_eq!(
962      select_profile(None, false, Some("saved")),
963      Some("saved".to_string())
964    );
965    // Nothing set at all means game-directory mode.
966    assert_eq!(select_profile(None, false, None), None);
967  }
968}