ModSync/For developers/Library API

Library API

The modsync crate contains the engine behind the desktop app and the modsync command. Use it to build your own installer, guide checker or guide tool. The examples here call the same public functions the command line calls.

Adding the dependency

Add the crate from its Git repository and turn off the default desktop feature. That feature brings in the graphical app and its toolkit, which a library does not need.

[dependencies]
modsync = { git = "https://github.com/kolto-labs/ModSync.rs", default-features = false }

The examples assume a function that returns anyhow::Result, so ? works throughout. The project builds with and without the desktop feature.

Crate layout

The public modules are declared in src/lib.rs. The most useful ones are:

ModuleWhat it is for
modelGuide and Component types. Loads, parses, renders and saves instruction files, and puts components in install order.
selectionSelection actions (select, deselect, by tier or category, options) and the dependency rules that go with them.
engineEngine for validating and installing, with Settings and Event. These are also re-exported at the crate root.
validationReport and its stage results, returned by validation.
install_progressPhase and Progress values reported while an install runs.
recoveryThe recovery snapshot: restoring folders after a stopped install and reading the saved completion summary.
downloadFetches one archive over HTTPS, with an optional SHA-256 check.
archiveOptions for archive handling (scratch folder, size limit), used by downloads and installs.
profilesSaved selections and folder settings, in a Store.
draftDrafts instructions from prose in a Markdown guide.
conflictsReports of game files written by more than one component.
pathsRoots, the pair of mod folder and game folder.
gameDetects the game in a folder and resolves the install root.
download_planWorks out which offered filename a component would use from a download page.
phasePrepares a guide for one install phase, as the --phase option does.

These modules serve players' apps such as the desktop app:

ModuleWhat it is for
buildsThe mod build Catalog: the KOTOR Community builds (builds::community()) plus links players add, each fetched over HTTPS and kept in a local cache with Catalog::fetch.
importTurns a loose mod archive into a one-mod guide: import::prepare places it in the mod folder, inspects it read-only, and returns a Prepared guide. archives_in lists the archives in a folder.
pausePausing a download, check or install at its next safe point, with a shared Arc<AtomicBool> flag like the cancel flag. follow_file makes a flag that follows whether a file exists.
mod_infoA mod page's title, description, author and screenshots, from DeadlyStream or the Nexus Mods API. image_data_url fetches a screenshot as a data: URL.
app_updateChecks a GitHub repository's releases for a newer version, downloads this platform's build, and reads one version's notes from a changelog.
deadlystream_accountSigns in to DeadlyStream and returns a Session to keep in place of the password; check_session tells whether a kept session still works.
game_locatorfind_installs lists KOTOR installs in Steam, GOG and Origin/EA folders. Read-only.
deploymentBesides deploying, Service::duplicates lists deployed mods that share a name, and Service::remove_from_library deletes a staged mod that is not deployed.
download_orchestratorDownloads a whole guide. RunSettings::paused holds downloads between reads, RunSettings::deadlystream_session reads DeadlyStream pages signed in, and nxm_target turns a Nexus nxm:// link into a download for the matching mod.

Checkpoints, managed deployment, peer sharing and torrents also live in the crate (checkpoint, deployment, p2p, peer_sharing). They are advanced features and are not covered on this page.

Loading a guide

Guide::load_for_install_preserving_selection reads a TOML, JSON, YAML, XML or Markdown guide and keeps the selection the file records. Markdown guides are drafted when they are read. The command line then puts the components in install order with sort_for_install, except for Markdown guides, which do not carry the install-before and install-after data that ordering uses.

use std::path::Path;
use modsync::Guide;

fn load(path: &Path) -> anyhow::Result<Guide> {
    let mut guide = Guide::load_for_install_preserving_selection(path)?;
    if !guide.ordering.markdown {
        guide.sort_for_install()?;
    }
    Ok(guide)
}

Guide::load is similar, but selects every component when the file selects none. Guide::parse(text, "auto") reads guide text that is already in memory. Use Guide::ordered() to get the components in install order without changing the guide.

Choosing components and options

Use Engine::select_available to change the selection, as the command line and desktop app do. It applies one selection::Action and checks archive availability first. It returns an Outcome that lists what was selected or deselected, and any warnings.

use modsync::{Engine, Settings, game};
use modsync::selection::{Action, Filter};
use std::path::Path;

fn choose_defaults(guide: &mut modsync::Guide, mods: &Path, game_dir: &Path) -> anyhow::Result<()> {
    let engine = Engine::new(Settings::new(mods, game_dir)?)?;
    let detected = game::detect(&game::resolve_install_root(game_dir));
    let (outcome, _availability) = engine.select_available(
        &mut guide.components,
        Some(detected),
        Action::SelectVisible(Filter::default()),
    )?;
    for warning in &outcome.warnings {
        eprintln!("Selection warning: {warning}");
    }
    Ok(())
}

The main actions are:

  • Action::SetComponent { guid, selected } and Action::SetOption { guid, selected }, for one component or option. The cascade rules apply.
  • Action::SelectVisible(Filter), which selects the base components that match the filter, with their dependencies. This is the command line's default when you pass no selection flags.
  • Action::ResetFromSelectors(Vec<String>), the reset behavior of --select.
  • Action::SelectThroughTier(String), Action::SelectCategories(Vec<String>) and Action::DeselectBase.
  • Action::SetWidescreen { guid, selected } and Action::EnforceGame, which handle widescreen-only components and game-specific exclusions.

If you have only a guide and no folders yet, selection::apply(components, game, action) applies the same actions without the archive checks. For selectors written the way --select takes them, selection::apply_cli_selection(&mut guide.components, &selectors) returns warnings as a Vec<String>.

Saved profiles

A profiles::Store keeps named profiles, each with the selections and folders. Use Store::new with a folder you choose, or Store::from_settings_directory(None) for the default location.

use std::path::Path;
use modsync::profiles::Store;

let store = Store::new(Path::new("/path/to/settings"))?;
store.capture("Full Build", &guide, Some(input), Some(game_dir), Some(mods))?;
store.apply("Full Build", &mut guide)?;
store.activate("Full Build")?;

Validating without touching files

Engine::validate_report runs the same checks as the command line's validate command. It returns a validation::Report instead of failing on the first problem. Validation never writes to the mod or game folder and never runs external programs.

let engine = Engine::new(Settings::new(mods, game_dir)?)?;
let report = engine.validate_report(&guide, |event| {
    println!("{}: {}", event.component, event.message);
});
if !report.success {
    eprintln!("{} error(s), {} warning(s)", report.error_count, report.warning_count);
}

The report also has stages, one StageResult per check, with passed, summary and messages. Engine::validate takes the same guide and returns a Result instead, for callers who want an error rather than a report. To see which game files each component would write, call engine.analyze_conflicts(&guide), which returns a conflicts::Report and also changes neither folder.

Installing with progress and cancellation

Engine::install_observed_report installs the guide and returns an InstallReport. It takes two callbacks. The first receives an Event for each step, with the same text the command line prints. The second receives an install_progress::Progress at each real stage of the install, with the Phase, the active component and its index, and whether a recovery snapshot is pending. Progress reports real boundaries, not byte counts.

use modsync::{Engine, Settings};
use modsync::install_progress::Phase;

let settings = Settings::new(mods, game_dir)?;
let cancel = settings.cancelled.clone();
// From another thread, set it to stop: cancel.store(true, std::sync::atomic::Ordering::Relaxed);
let engine = Engine::new(settings)?;

let report = engine.install_observed_report(
    &guide,
    |event| println!("{}: {}", event.component, event.message),
    |progress| {
        if progress.phase == Phase::InstallingComponent {
            println!(
                "Installing {} of {}: {}",
                progress.component_index, progress.component_total, progress.message
            );
        }
    },
)?;

The engine checks the cancel flag between steps. A cancelled or failed install returns an error. Once it has started changing files, it leaves the recovery snapshot in place, so restore before you try again (see the next section). If you do not need progress, engine.install(&guide, |event| ...) does the same work and returns Result<()>.

Settings::new selects the linked OdyPatcher library with patcher = None and patcher_engine = PatcherEngine::OdyPatcher. It runs within ModSync. Its source lives in the OdyPatcher repository, at the exact Git revision pinned in Cargo.toml and Cargo.lock. To select an external executable, set settings.patcher to its path, settings.patcher_engine to its backend, and settings.allow_processes = true. Execute and Run steps also require this permission.

Restoring after a failure

A stopped install leaves the game and mod folders partly changed. Restore them before doing anything else. recovery::restore checks the saved snapshot, puts both folders back as they were before the install, and clears the unfinished-install marker. It refuses to run if the snapshot no longer matches what was recorded.

use modsync::{Settings, recovery};

let settings = Settings::new(mods, game_dir)?;
recovery::restore(&settings.roots)?;
// The folders match the snapshot again. Start the install from the beginning to retry.

recovery::completion_summary reads the saved result of the last completed install without checking the game files. It returns Ok(None) when there is no saved result.

if let Some(summary) = recovery::completion_summary(&settings.roots)? {
    println!("{} components recorded", summary.components.len());
}

Pausing and resuming

Settings::paused is a shared flag, like Settings::cancelled. While it is set, checks and installs hold at the next boundary between components, never inside one. Clearing it carries on from there in the same process. Cancelling still stops a held run, and then recovery works as usual.

use std::sync::atomic::Ordering;
use modsync::{Engine, Settings};

let settings = Settings::new(mods, game_dir)?;
let paused = settings.paused.clone();
let engine = Engine::new(settings)?;
// From another thread:
//   paused.store(true, Ordering::Release);   // hold at the next component boundary
//   paused.store(false, Ordering::Release);  // carry on
engine.install(&guide, |event| println!("{}: {}", event.component, event.message))?;

For a command-line tool, modsync::pause::follow_file(path) returns a flag that is set while the file exists, which is how install --pause-file works. Downloads take the same kind of flag in download_orchestrator::RunSettings::paused. Your own long-running work can wait on a flag with pause::hold(&paused, &cancelled).

Importing a loose archive

import::prepare copies an archive into the mod folder (never replacing a different file with the same name), inspects it without changing anything, and returns a one-mod guide that installs it. It returns Ok(None) for an archive with no game files or TSLPatcher data. Validate and install the guide like any other.

use std::path::Path;
use std::sync::atomic::AtomicBool;
use modsync::{archive, import, Engine, Settings};

let cancelled = AtomicBool::new(false);
let Some(prepared) = import::prepare(
    Path::new("/downloads/SomeMod.7z"),
    mods,
    Some("Some Mod"),
    &archive::Options::default(),
    &cancelled,
)? else {
    anyhow::bail!("Install this archive by hand");
};
println!("{} ({:?})", prepared.archive.display(), prepared.method);

// validate and install each take the engine by value, so make one per call.
Engine::new(Settings::new(mods, game_dir)?)?.validate(&prepared.guide, |_| {})?;
Engine::new(Settings::new(mods, game_dir)?)?
    .install(&prepared.guide, |event| println!("{}", event.message))?;

To import a folder, call import::archives_in(folder, &cancelled) and prepare each archive on its own.

Converting between formats

Load a guide in one format and render it as another. The format names are toml, json, yaml, xml and md, plus common aliases such as yml. save writes the file atomically and picks the format from the file extension, using TOML when there is none. The command line's convert command also orders components by their dependencies first, and can draft instructions from prose with draft::generate.

use modsync::Guide;
use std::path::Path;

let mut guide = Guide::load(Path::new("guide.toml"))?;
for warning in guide.sort_like_dependency_resolver(false)? {
    eprintln!("{warning}");
}
let json = guide.render("json")?;
guide.save(Path::new("guide.yaml"))?;

Tip. save replaces the file at the path you give it. Write converted output to a new file name so the original guide is kept.

Downloading archives

download::fetch_with_options downloads one direct archive URL over HTTPS. It checks the archive (ZIP, 7z, RAR, TAR and GZip are supported) and the SHA-256 when you give one, then saves it. It never overwrites an existing file. Host landing pages, such as Nexus Mods pages and MEGA links, are not fetched. They remain browser downloads.

use modsync::{archive, download};
use std::path::Path;
use std::sync::atomic::AtomicBool;

let cancelled = AtomicBool::new(false);
download::fetch_with_options(
    "https://example.org/mod.zip",
    Path::new("/path/to/mods/mod.zip"),
    Some("EXPECTED_SHA256_HEX"),
    &cancelled,
    &archive::Options::default(),
)?;

To download into a folder and let the server name the file, use download::fetch_to with download::Destination::Directory. It returns a Fetched value with the saved path and its SHA-256. To find which selected components have downloads, call selection::download_candidates(&guide.components, selection::Scope::Base).

Errors

Most functions in the crate return anyhow::Result, so you can propagate errors with ? and add context with anyhow::Context. Download failures also carry a class. download::classify returns it, so your tool can retry a temporary failure, send a web page to the browser, or stop.

use modsync::download::{self, FailureClass};

match download::fetch_with_options(url, dest, Some(sha), &cancelled, &options) {
    Ok(()) => {}
    Err(error) => {
        let class = download::classify(&error).cloned();
        match class {
            Some(FailureClass::Transient { retry_after_secs }) => {
                println!("Try again later (retry after {retry_after_secs:?} seconds)");
            }
            Some(FailureClass::ManualRequired { url, .. }) => {
                println!("Download this one in a browser: {url}");
            }
            _ => return Err(error),
        }
    }
}

Safety rules every caller must keep

These rules come from the engine's design. A tool that follows them is as safe as the command line. Breaking them can damage a player's game.

  1. Validation never changes files. When you only want to check a guide, call validate_report or validate, never install.

    let report = Engine::new(Settings::new(mods, game_dir)?)?
        .validate_report(&guide, |_| {});
  2. Keep guide order. Show and run components in the order Guide::ordered returns. Do not sort them yourself.

    for component in guide.ordered()? {
        println!("{}", component.name);
    }
  3. Stop on failure. When an install returns an error, stop. Do not skip the failed component, move on to the next one, or retry it in place. Propagating the error with ? does this.

    engine.install(&guide, |_| {})?; // an error ends the run here
  4. Restore before retrying. Restore the verified snapshot first, then install from the beginning. Never add a skipped mod to the end of an install.

    recovery::restore(&settings.roots)?;
    Engine::new(settings)?.install(&guide, |_| {})?;
  5. Test in isolated folders. Install tests should use temporary folders, never a real game or mod folder. The example uses the tempfile crate, which you add as a dev-dependency.

    let scratch = tempfile::tempdir()?;
    let mods = scratch.path().join("mods");
    let game = scratch.path().join("game");
    std::fs::create_dir_all(&mods)?;
    std::fs::create_dir_all(&game)?;
    let settings = Settings::new(&mods, &game)?;