Documentation
¶
Index ¶
- func ApplyProfileOverrides(game *domain.Game, profile *domain.Profile) error
- func CompareVersions(v1, v2 string) int
- func DetectModName(extractedPath, archiveFilename string) string
- func IsNewerVersion(currentVersion, newVersion string) bool
- type AggregateSearchResult
- type BatchOptions
- type BatchResult
- type Conflict
- type DependencyResolver
- type DeployOptions
- type DeployPhase
- type DeployProgress
- type DeployResult
- type DeployedFile
- type DisableResult
- type DownloadModResult
- type DownloadProgress
- type DownloadResult
- type Downloader
- type EnableResult
- type Extractor
- type HookContext
- type HookResult
- type HookRunner
- type ImportOptions
- type ImportResult
- type Importer
- func (i *Importer) FindDuplicateMod(modName string, installedMods []domain.InstalledMod) *domain.InstalledMod
- func (i *Importer) Import(ctx context.Context, archivePath string, game *domain.Game, opts ImportOptions) (result *ImportResult, err error)
- func (i *Importer) ScanModPath(ctx context.Context, game *domain.Game, installedMods []domain.InstalledMod, ...) ([]ScanResult, error)
- type InstallOptions
- type InstallPlan
- type InstallResult
- type InstalledModResult
- type Installer
- func (i *Installer) GetConflicts(ctx context.Context, game *domain.Game, mod *domain.Mod, profileName string) ([]Conflict, error)
- func (i *Installer) GetDeployedFiles(game *domain.Game, mod *domain.Mod) ([]string, error)
- func (i *Installer) Install(ctx context.Context, game *domain.Game, mod *domain.Mod, profileName string) error
- func (i *Installer) InstallBatch(ctx context.Context, game *domain.Game, mods []*domain.Mod, versions []string, ...) (*BatchResult, error)
- func (i *Installer) IsInstalled(game *domain.Game, mod *domain.Mod) (bool, error)
- func (i *Installer) Replace(ctx context.Context, game *domain.Game, oldMod, newMod *domain.Mod, ...) error
- func (i *Installer) ReplaceWithCaches(ctx context.Context, game *domain.Game, oldCache, newCache *cache.Cache, ...) error
- func (i *Installer) ReplaceWithOldCache(ctx context.Context, game *domain.Game, oldCache *cache.Cache, ...) error
- func (i *Installer) Uninstall(ctx context.Context, game *domain.Game, mod *domain.Mod, profileName string) error
- func (i *Installer) UninstallBatch(ctx context.Context, game *domain.Game, mods []*domain.InstalledMod, ...) (*BatchResult, error)
- type ParsedFilename
- type ProfileManager
- func (pm *ProfileManager) AddMod(gameID, profileName string, mod domain.ModReference) error
- func (pm *ProfileManager) Create(gameID, name string) (*domain.Profile, error)
- func (pm *ProfileManager) Delete(gameID, name string) error
- func (pm *ProfileManager) Export(gameID, profileName string) ([]byte, error)
- func (pm *ProfileManager) Get(gameID, name string) (*domain.Profile, error)
- func (pm *ProfileManager) GetDefault(gameID string) (*domain.Profile, error)
- func (pm *ProfileManager) Import(data []byte) (*domain.Profile, error)
- func (pm *ProfileManager) ImportWithOptions(data []byte, force bool) (*domain.Profile, error)
- func (pm *ProfileManager) List(gameID string) ([]*domain.Profile, error)
- func (pm *ProfileManager) ParseProfile(data []byte) (*domain.Profile, error)
- func (pm *ProfileManager) RemoveMod(gameID, profileName, sourceID, modID string) error
- func (pm *ProfileManager) ReorderMods(gameID, profileName string, mods []domain.ModReference) error
- func (pm *ProfileManager) SetDefault(gameID, name string) error
- func (pm *ProfileManager) Switch(ctx context.Context, game *domain.Game, newProfileName string) error
- func (pm *ProfileManager) UpsertMod(gameID, profileName string, mod domain.ModReference) error
- type ProgressFunc
- type ResolvedHooks
- func (h *ResolvedHooks) GetInstallAfterAll() string
- func (h *ResolvedHooks) GetInstallAfterEach() string
- func (h *ResolvedHooks) GetInstallBeforeAll() string
- func (h *ResolvedHooks) GetInstallBeforeEach() string
- func (h *ResolvedHooks) GetUninstallAfterAll() string
- func (h *ResolvedHooks) GetUninstallAfterEach() string
- func (h *ResolvedHooks) GetUninstallBeforeAll() string
- func (h *ResolvedHooks) GetUninstallBeforeEach() string
- type ScanOptions
- type ScanResult
- type Service
- func (s *Service) AddGame(game *domain.Game) error
- func (s *Service) ApplyInstall(ctx context.Context, game *domain.Game, plan *InstallPlan, opts InstallOptions, ...) (*InstallResult, error)
- func (s *Service) ApplyModUpdate(sourceID, modID, gameID, profileName, newVersion string, fileIDs []string) error
- func (s *Service) ApplyProfileSwitch(ctx context.Context, game *domain.Game, plan *SwitchPlan, ...) (*SwitchResult, error)
- func (s *Service) ApplyUpdate(ctx context.Context, game *domain.Game, profileName string, upd domain.Update, ...) (*UpdateApplyResult, error)
- func (s *Service) Cache() *cache.Cache
- func (s *Service) Close() error
- func (s *Service) ConfigDir() string
- func (s *Service) DeleteInstalledMod(sourceID, modID, gameID, profileName string) error
- func (s *Service) DeleteSourceToken(sourceID string) error
- func (s *Service) DeployProfile(ctx context.Context, game *domain.Game, profileName string, opts DeployOptions, ...) (*DeployResult, error)
- func (s *Service) DisableMod(ctx context.Context, game *domain.Game, profileName, sourceID, modID string) (*DisableResult, error)
- func (s *Service) DownloadMod(ctx context.Context, sourceID string, game *domain.Game, mod *domain.Mod, ...) (result *DownloadModResult, err error)
- func (s *Service) DownloadModToCache(ctx context.Context, gameCache *cache.Cache, sourceID string, ...) (result *DownloadModResult, err error)
- func (s *Service) EnableMod(ctx context.Context, game *domain.Game, profileName, sourceID, modID string) (*EnableResult, error)
- func (s *Service) GetDefaultLinkMethod() domain.LinkMethod
- func (s *Service) GetDependencies(ctx context.Context, sourceID string, mod *domain.Mod) ([]domain.ModReference, error)
- func (s *Service) GetDeployedFilesForMod(gameID, profileName, sourceID, modID string) ([]string, error)
- func (s *Service) GetDownloadURL(ctx context.Context, sourceID string, mod *domain.Mod, fileID string) (string, error)
- func (s *Service) GetFileOwner(gameID, profileName, relativePath string) (sourceID, modID string, found bool, err error)
- func (s *Service) GetFilesWithChecksums(gameID, profileName string) ([]DeployedFile, error)
- func (s *Service) GetGame(gameID string) (*domain.Game, error)
- func (s *Service) GetGameCache(game *domain.Game) *cache.Cache
- func (s *Service) GetGameCachePath(game *domain.Game) string
- func (s *Service) GetGameLinkMethod(game *domain.Game) domain.LinkMethod
- func (s *Service) GetInstalledMod(sourceID, modID, gameID, profileName string) (*domain.InstalledMod, error)
- func (s *Service) GetInstalledMods(gameID, profileName string) ([]domain.InstalledMod, error)
- func (s *Service) GetInstalledModsInProfileOrder(gameID, profileName string) ([]domain.InstalledMod, error)
- func (s *Service) GetInstaller(game *domain.Game) *Installer
- func (s *Service) GetLinker(method domain.LinkMethod) linker.Linker
- func (s *Service) GetMod(ctx context.Context, sourceID, gameID, modID string) (*domain.Mod, error)
- func (s *Service) GetModFiles(ctx context.Context, sourceID string, mod *domain.Mod) ([]domain.DownloadableFile, error)
- func (s *Service) GetSource(id string) (source.ModSource, error)
- func (s *Service) GetSourceToken(sourceID string) (*db.StoredToken, error)
- func (s *Service) IsSourceAuthenticated(sourceID string) bool
- func (s *Service) ListGames() []*domain.Game
- func (s *Service) ListSourceTokens() ([]db.StoredToken, error)
- func (s *Service) ListSources() []source.ModSource
- func (s *Service) NewInstallerWithLinker(game *domain.Game, lnk linker.Linker) *Installer
- func (s *Service) NewProfileManager() *ProfileManager
- func (s *Service) NewUpdater() *Updater
- func (s *Service) PlanInstall(ctx context.Context, game *domain.Game, profileName, sourceID, modID string, ...) (*InstallPlan, error)
- func (s *Service) PlanProfileSwitch(ctx context.Context, game *domain.Game, target string) (*SwitchPlan, error)
- func (s *Service) RegisterSource(src source.ModSource)
- func (s *Service) RollbackModVersion(sourceID, modID, gameID, profileName string) error
- func (s *Service) SaveFileChecksum(sourceID, modID, gameID, profileName, fileID, checksum string) error
- func (s *Service) SaveInstalledMod(mod *domain.InstalledMod) error
- func (s *Service) SaveSourceToken(sourceID, apiKey string) error
- func (s *Service) SearchAllSources(ctx context.Context, gameID, query, category string, tags []string, ...) (AggregateSearchResult, error)
- func (s *Service) SearchMods(ctx context.Context, sourceID, gameID, query string, category string, ...) (source.SearchResult, error)
- func (s *Service) SetModDeployed(sourceID, modID, gameID, profileName string, deployed bool) error
- func (s *Service) SetModEnabled(sourceID, modID, gameID, profileName string, enabled bool) error
- func (s *Service) SetModFileIDs(sourceID, modID, gameID, profileName string, fileIDs []string) error
- func (s *Service) SetModLinkMethod(sourceID, modID, gameID, profileName string, linkMethod domain.LinkMethod) error
- func (s *Service) SetModUpdatePolicy(sourceID, modID, gameID, profileName string, policy domain.UpdatePolicy) error
- func (s *Service) UninstallMod(ctx context.Context, game *domain.Game, profileName, sourceID, modID string, ...) (*UninstallResult, error)
- func (s *Service) UpdateModVersion(sourceID, modID, gameID, profileName, newVersion string) error
- type ServiceConfig
- type SkippedMod
- type SourceWarning
- type SwitchPlan
- type SwitchResult
- type UninstallOptions
- type UninstallResult
- type UninstalledModResult
- type UpdateApplyResult
- type UpdateOptions
- type Updater
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApplyProfileOverrides ¶ added in v1.1.0
ApplyProfileOverrides writes a profile's configuration overrides to the game install directory. Each key in profile.Overrides is a path relative to game.InstallPath; the value is written as file content. Used on deploy and profile switch so INI tweaks and other overrides are applied. Paths that escape the game install directory (e.g. ../../../etc/passwd) are rejected to prevent abuse.
func CompareVersions ¶
CompareVersions delegates to domain.CompareVersions. Kept for backward compatibility with existing callers.
func DetectModName ¶ added in v0.10.0
DetectModName determines a display name for an imported mod. It checks for a single top-level directory in the extracted content, falling back to the archive basename if not found.
func IsNewerVersion ¶
IsNewerVersion delegates to domain.IsNewerVersion. Kept for backward compatibility with existing callers.
Types ¶
type AggregateSearchResult ¶ added in v1.10.0
type AggregateSearchResult struct {
Mods []domain.Mod // merged, ranked; each Mod carries its SourceID
TotalCount int // sum of per-source totals (sources reporting 0/unknown contribute 0)
Warnings []SourceWarning // per-source failures (design §5: warnings, not errors)
}
AggregateSearchResult is the merged outcome of searching every source configured for a game.
type BatchOptions ¶ added in v0.12.0
type BatchOptions struct {
Hooks *ResolvedHooks // Hooks to run during batch operation
HookRunner *HookRunner // Runner for executing hooks
HookContext HookContext // Base context for hooks (mod-specific fields added per-mod)
Force bool // If true, bypass before_* hook failures
}
BatchOptions configures batch install/uninstall operations
type BatchResult ¶ added in v0.12.0
type BatchResult struct {
Installed []InstalledModResult // Successfully installed mods (for InstallBatch)
Uninstalled []UninstalledModResult // Successfully uninstalled mods (for UninstallBatch)
Skipped []SkippedMod // Mods skipped due to hook failure or error
Errors []error // Non-fatal errors (after_* hook failures)
}
BatchResult contains the results of a batch install/uninstall operation
type Conflict ¶ added in v0.9.0
Conflict represents a file that would be overwritten by installing a mod
type DependencyResolver ¶
type DependencyResolver struct{}
DependencyResolver resolves mod dependencies and detects cycles
func NewDependencyResolver ¶
func NewDependencyResolver() *DependencyResolver
NewDependencyResolver creates a new dependency resolver
func (*DependencyResolver) GetDependencyTree ¶
func (r *DependencyResolver) GetDependencyTree(mod *domain.Mod, modMap map[string]*domain.Mod) ([]domain.Mod, error)
GetDependencyTree returns all dependencies for a mod (including transitive)
func (*DependencyResolver) Resolve ¶
Resolve returns mods in dependency order (dependencies first) Returns ErrDependencyLoop if a circular dependency is detected
func (*DependencyResolver) ValidateDependencies ¶
func (r *DependencyResolver) ValidateDependencies(mods []domain.Mod) error
ValidateDependencies checks if all dependencies are satisfied
type DeployOptions ¶ added in v1.11.0
type DeployOptions struct {
Purge bool // --purge: undeploy every installed mod (regardless of ModID/All) before deploying, remembering which were enabled beforehand for the profile-wide selection below.
// LinkMethod overrides the link method used for this deploy (--method).
// nil (the zero value) means "use the game's effective link method" via
// Service.GetGameLinkMethod. A pointer is used, rather than a bare
// domain.LinkMethod with its zero value as the "unset" sentinel, because
// domain.LinkMethod's zero value (LinkSymlink) is itself a valid,
// explicit choice - it cannot double as "no override" without losing
// the ability to explicitly request symlink. See the task report.
LinkMethod *domain.LinkMethod
// ModID/SourceID restrict the deploy to a single mod (`lmm deploy
// <mod-id>`). Both empty (the default) deploys every mod in profile
// order, subject to All. SourceID selects which source's copy of ModID
// to deploy - the CLI's --source flag, default "nexusmods".
ModID string
SourceID string
All bool // --all: include disabled mods in a full-profile deploy, or allow deploying a disabled ModID.
// Hook plumbing, mirroring UninstallOptions. Hooks and/or HookRunner may
// be nil to skip hook execution entirely (e.g. --no-hooks). The deploy
// pass runs install.* hooks; the purge pass (when Purge is set) runs
// uninstall.* hooks, matching the pre-extraction CLI's doDeploy/
// purgeDeployedMods split.
Hooks *ResolvedHooks
HookRunner *HookRunner
HookContext HookContext
Force bool // continue past a failing before_* hook (warn instead of fail)
}
DeployOptions configures DeployProfile.
type DeployPhase ¶ added in v1.11.0
type DeployPhase int
DeployPhase identifies what DeployProfile is doing for the mod named in a DeployProgress event (or, for DeployPurging, for the purge pass as a whole), letting callers (CLI, TUI) render phase-appropriate UI without needing to know how a deploy is actually carried out.
const ( // DeployPurging fires once, before any purge-phase mod is touched, when // Purge is set and there is at least one installed mod to purge. Total // is the number of mods being purged; Index and ModName are zero/empty. DeployPurging DeployPhase = iota // DeployBeforeEachSkipped: install.before_each failed for ModName: the // mod is skipped (added to DeployResult.Skipped). Detail is the reason. DeployBeforeEachSkipped // DeployRedownloading: ModName's cache entry is missing; DeployProfile // is re-fetching it from source. DeployRedownloading // DeployFallbackUsed: ModName's stored file IDs were not found on the // source; falling back to the primary file. DeployFallbackUsed // DeployDownloading: a file for ModName is downloading. Percent is the // 0-100 completion (only reported once the source declares a total // size, matching the pre-extraction CLI's progress callback gating). DeployDownloading // DeployDownloadFailed: a file for ModName failed to download; the mod // is skipped. Detail is the reason. DeployDownloadFailed // DeployDownloadDone fires once, after a cache-miss mod's redownload // loop finishes without error, mirroring the pre-extraction CLI's // unconditional `fmt.Println() // Clear progress line` immediately // after the download loop (git show b2ad559:cmd/lmm/deploy.go) - it // terminates DeployDownloading's carriage-returned progress line with a // real newline before the mod's own DeployDeployed line prints. Unlike // its ApplyProfileSwitch analog (SwitchDownloadDone), which fires on // both success and failure since doProfileSwitch's equivalent Println // sat unconditionally after its own loop, redeployFromSource's failure // path returns immediately via a DeployDownloadFailed event instead (see // below) without reaching this point - so this phase covers the // success path only. DeployDownloadDone // DeploySkipped: ModName was skipped for a reason other than a hook or // download failure (fetch failure, no files available, file-selection // failure, or an outright deploy/install failure). Detail is the reason. DeploySkipped // DeployDeployed: ModName was (re)deployed successfully. DeployDeployed // DeployBeforeAllForced fires once, immediately, when install.before_all // (a deploy) or uninstall.before_all (a --purge pass) fails and Force is // set: the pre-extraction CLI printed this warning as the very first // line of output, before anything else (the "Purging..."/"Deploying..." // header included) - so this event always precedes DeployPurging and // any other event. No mod is in scope (Index/Total/ModName/ModID are // zero); Detail matches the DeployResult.Warnings entry verbatim. DeployBeforeAllForced // DeployNote fires wherever DeployProfile appends an entry to // DeployResult.Notes for a specific mod during the main deploy loop // (a failed undeploy-before-redeploy, a failed SetModLinkMethod, or a // failed SetModDeployed), at the exact point it happens - always // before that same mod's own DeployDeployed event, matching the // pre-extraction CLI's inline ordering. ModName/ModID identify the // mod; for the latter two diagnostics, whose historical text carries // no mod identity at all, the event's ModName/ModID are the ONLY way // to attribute the diagnostic to a mod. DeployNote // DeployWarning fires wherever DeployProfile appends an entry to // DeployResult.Warnings other than a DeployBeforeAllForced one: a // failed install.after_each hook (ModName/ModID set), a failed // install.after_all hook, or a failed ApplyProfileOverrides (neither // has a mod in scope). The pre-extraction CLI printed the overrides // warning immediately once computed, then its batched hook warnings // (after_each in mod order, then after_all) right after - so // DeployProfile emits the overrides DeployWarning (if any) first, then // the after_each/after_all ones, reproducing that print order without // changing when each check actually runs (see DeployProfile's body). DeployWarning // PurgeWarning fires wherever a --purge pass appends an entry to // DeployResult.Warnings: a skipped uninstall.before_each mod (fires // inline, per mod, as it happens), or a failed uninstall.after_each/ // after_all hook (fires after the whole purge loop has finished, in // mod order then after_all - mirroring the pre-extraction // purgeDeployedMods, which accumulated these and printed them // together, after every per-mod line, via printHookWarnings). PurgeWarning // PurgeNote fires wherever a --purge pass appends an entry to // DeployResult.Notes for a specific mod (a failed undeploy, or a // failed SetModDeployed(false)), inline, immediately after that // operation - mirroring the pre-extraction purgeDeployedMods's // --verbose-gated "⚠ " lines. PurgeNote // PurgeComplete fires once, after a non-empty --purge pass has // finished everything (including its own hook warnings) but before // DeployProfile moves on to gathering mods to deploy. It carries no // data; a caller wanting byte-identical pre-extraction output prints // exactly one blank line here - purgeDeployedMods's own final // `fmt.Println()`, which the initial extraction had misplaced // immediately after the purge header instead of at the end of the // purge phase. PurgeComplete // SwitchDisableNote fires for each of the disable loop's two possible // per-mod diagnostics (a failed Uninstall, then a failed SetModEnabled), // mirroring doProfileSwitch's " Warning: failed to undeploy %s: %v" / // " Warning: failed to update %s: %v" - both --verbose-gated stdout // prints. Detail carries the historical "Warning: " prefix baked in; a // caller wanting byte-identical output prints // `if verbose { fmt.Printf(" %s\n", p.Detail) }`. SwitchDisableNote // SwitchDisabled fires once a mod's disable step has finished // (regardless of whether SwitchDisableNote fired for it) - // doProfileSwitch always disables the DB row and always prints // " ✓ Disabled: %s" even when the undeploy/DB update above it failed. // ModName is set. SwitchDisabled // SwitchEnableNote mirrors SwitchDisableNote for the enable loop's two // diagnostics (a failed Install, then a failed SetModEnabled). Unlike // the disable loop, a failed Install is fatal FOR THAT MOD ONLY: the mod // is skipped (no SwitchEnabled event follows) - see doProfileSwitch's // `continue` after the Install failure branch. SwitchEnableNote // SwitchEnabled fires once a mod has been successfully deployed (and // enabled, or deployed but its SetModEnabled bookkeeping failed - see // SwitchEnableNote), mirroring " ✓ Enabled: %s". SwitchEnabled // SwitchInstalling fires once, before the install loop, only when there // is at least one mod to install (Total = len(SwitchPlan.ToInstall)), // mirroring doProfileSwitch's "\nInstalling missing mods...". SwitchInstalling // SwitchInstallingMod fires once per mod to install, before it is even // fetched - SourceID/ModID are the only identity available at this // point, mirroring " Installing %s:%s...". SwitchInstallingMod // SwitchInstallError fires for any of the install loop's mod-fatal-only // failure reasons (fetch, get-files, no-files, file-selection, deploy, // or save), each already worded to match its historical text exactly // (Detail is printed verbatim as " Error: %s"). Unlike // DeployProfile's DeploySkipped, these are NOT accumulated into any // SwitchResult slice - doProfileSwitch never printed a final // skipped-count summary for profile switch, so there is nothing to // accumulate beyond the live event. SwitchInstallError // SwitchFallbackUsed fires when a to-be-installed mod's stored file IDs // were not found on the source and the primary file was used instead, // mirroring doProfileSwitch's unconditional (NOT --verbose-gated) // " Warning: stored file IDs not found, using primary". SwitchFallbackUsed // SwitchDownloading mirrors DeployDownloading for the install loop's // download progress (Percent set, gated the same way: only once the // source declares a total size). SwitchDownloading // SwitchDownloadFailed fires when a file download fails; Detail is // "download failed: %v". A caller wanting byte-identical output prints a // blank line then " Error: %s" with Detail - see SwitchDownloadDone's // doc comment for why the blank line isn't included here. SwitchDownloadFailed // SwitchDownloadDone fires once per install-loop mod after its download // loop finishes, on both success and failure - doProfileSwitch's // `fmt.Println()` after the loop runs unconditionally either way. A // caller wanting byte-identical output prints a bare blank line here; // combined with SwitchDownloadFailed's own leading blank line, a failed // download reproduces the original's blank/error/blank sequence, and a // successful one reproduces its single trailing blank line. SwitchDownloadDone // SwitchInstalled fires once a to-be-installed mod has been fetched, // downloaded, deployed, and saved to the DB, mirroring " ✓ Installed: // %s". ModName is set (mod.Name, now known). SwitchInstalled // SwitchInstallNote fires when UpsertMod (recording the profile's // FileIDs) fails after a successful install - the sole --verbose-gated // diagnostic in the install loop, mirroring " Warning: could not // update profile: %v" (4-space indent, one level deeper than // SwitchDisableNote/SwitchEnableNote's 2-space Notes). SwitchInstallNote // --- Phase 5b Task 2: ApplyInstall progress events, restored to // byte-for-byte per-path fidelity in Fix wave 1 (see // task-2-report.md's "Fix wave 1 (dep-path fidelity)" entry for the full // review trace). ApplyInstall reproduces the pre-extraction CLI's own // TWO divergent execution engines EXACTLY, gated on // len(plan.Dependencies): // // - Empty (the STRICT/no-deps path): the primary uses doInstall's own // single-mod code unchanged from Task 2 - Force-gated // before_all/before_each, Install-or-Replace (incl. the // reinstall-cache-transaction for a same-version reinstall), // interactive/--file file selection and the blocking // conflict-confirm prompt are the CALLER's job (plan.Files/ // plan.Conflicts), SaveFileChecksum, --skip-verify. See // InstallDownload*/InstallChecksumComputed/InstallExtracting/ // InstallDeploying/InstallDone below. // - Non-empty (the BATCH path): EVERY mod in [Dependencies..., // primary] uses batchInstallMods' lenient mechanics IDENTICALLY - // the primary is NOT special-cased at all here, matching the // pre-extraction CLI's own behavior of delegating the WHOLE list, // target included, to batchInstallMods whenever there were // dependencies to install (doInstall's "if len(modsToInstall) > 1" // early return, before any single-mod code - including file // selection and the conflict prompt - ever ran). before_each is // NEVER Force-gated (a failure always just skips that one mod and // continues, primary included), no Replace path (always a fresh // Install; a same-key existing mod is uninstalled+cache-deleted // first), no interactive file selection (always the // primary-or-first file, re-resolved per mod - plan.Files is never // consulted), conflicts are a non-blocking inline warning (never a // prompt). See InstallDepInstalling below onward. InstallBeforeAllForced // InstallBeforeEachForced fires when the PRIMARY mod's install.before_each // hook fails and Force is set (a forced warning, not a fatal error) - // mirrors doInstall's own before_each Force-gate exactly. ModName/ModID // identify the primary. ONLY fires in the STRICT (no-deps) path - in the // BATCH path the primary's before_each is never Force-gated at all (see // InstallDepSkipped), matching batchInstallMods exactly. InstallBeforeEachForced // InstallDepInstalling fires once per mod in the BATCH path's combined // [Dependencies..., primary] list - dependency OR primary alike - // before before_each even runs, mirroring batchInstallMods' own // "\n[%d/%d] Installing: %s v%s\n" byte-for-byte (Fix wave 1 restored // the exact text and the primary's participation; Task 2's original // design fired this for dependencies only, with different wording - // see task-2-report.md). Index/Total count across the WHOLE combined // list (len(plan.Dependencies)+1), matching batchInstallMods' shared // counter; ModVersion carries the version for the restored "v%s" text. InstallDepInstalling // InstallDepReinstalling fires, unconditionally (not verbose-gated), // when a BATCH-path mod (dependency or primary) already has an existing // installed row for (SourceID, ID, Profile) - mirroring // batchInstallMods' unconditional " Removing previous installation...". // The existing install is then uninstalled and its cache entry deleted // - never a Replace/reinstall-cache-transaction (that mechanism is // STRICT-path only). InstallDepReinstalling // InstallDepFileSelected fires once a BATCH-path mod's downloadable // files have been fetched, filtered/sorted, and reduced to the // primary-or-first file (never interactive, never --file) - mirroring // batchInstallMods' " File: %s\n". File identifies which, for the // CLI's own displayFileLabel call. InstallDepFileSelected // InstallDepDownloading mirrors batchInstallMods' per-mod download // progress readout (Percent only, gated on a known total size - no // byte-count fallback line, unlike the STRICT path's // InstallDownloading). Fires for a dependency OR the primary alike. InstallDepDownloading // InstallDepSkipped fires whenever ANY BATCH-path mod (dependency or // primary alike) is skipped for any reason (hook failure, fetch/files/ // download/deploy/save failure) - unconditional, never Force-gated, // matching batchInstallMods exactly. Detail already carries the // restored, failure-type-specific, fully-prefixed line text verbatim // ("Skipped: install.before_each hook failed: %v" for a hook failure; // "Error: <reason>" for every other failure type - batchInstallMods // used different wording per failure type, never a uniform "Skipped: // <name>: <reason>" - see task-2-report.md's Fix wave 1 for the // before/after); a caller wanting byte-identical output prints // `fmt.Printf(" %s\n", p.Detail)`. Index/Total count across the whole // combined list, matching InstallDepInstalling. InstallDepSkipped // InstallDepDownloadDone fires, unconditionally (success OR failure // alike), immediately after a BATCH-path mod's DownloadMod call // returns - mirroring batchInstallMods' unconditional `fmt.Println()` // right after the download call, which precedes InstallDepSkipped's // own restored "\n Error: download failed: %v\n" leading blank line // on failure. A caller wanting byte-identical output prints a bare // `fmt.Println()` here. InstallDepDownloadDone // InstallDepConflictWarning fires when a BATCH-path mod's files // (already downloaded/cached at this point) would overwrite files from // another installed mod and Force is NOT set - a non-blocking, // informational warning only (batchInstallMods never prompts in the // BATCH path, primary included - the blocking plan.Conflicts prompt is // STRICT-path only). Detail is "%d file conflict(s) - will overwrite". InstallDepConflictWarning // InstallDepInstalled fires once a BATCH-path mod (dependency or // primary) has been fully installed (downloaded, deployed, saved, // profile-upserted) - mirroring batchInstallMods' restored // " ✓ Installed (%d files)\n" (Fix wave 1: Task 2's original design // used the mod's name instead of its file count - see // task-2-report.md). FilesExtracted carries the count. InstallDepInstalled // InstallDownloadStarted fires once per one of the PRIMARY's selected // files (plan.Files) in the STRICT (no-deps) path only, before it // begins downloading - mirrors downloadSelectedFiles' // "\n[%d/%d] Downloading %s...\n" (or, for a single file, // "\nDownloading %s...\n"). File identifies which (for the CLI's own // displayFileLabel call); Index/Total count among plan.Files. The BATCH // path has no equivalent "starting" event - its download progress // begins directly at InstallDepDownloading. InstallDownloadStarted // InstallDownloading mirrors the STRICT path's primary per-tick // download progress - Downloaded/TotalBytes/Percent carry the raw // numbers so the CLI can reproduce its exact byte-count/percent // readout (see DeployProgress's doc comment on those fields). The // BATCH path's per-mod download progress fires InstallDepDownloading // instead (Percent only, no byte-count fallback). InstallDownloading // InstallDownloadDone fires once a STRICT-path file's download attempt // finishes - success OR failure alike, mirroring downloadSelectedFiles' // `fmt.Println()` that runs unconditionally right after the download // call returns, before branching on its error. The BATCH path's // equivalent is InstallDepDownloadDone. InstallDownloadDone // InstallDownloadFailed fires when a STRICT-path (primary) file // download fails; Detail carries "download failed: %v" (the CLI checks // Detail for the "third-party downloads" substring itself, mirroring // doInstall's own check, to print the manual-install notice using the // plan's own Mod.SourceURL/ID - already in the CLI's enclosing scope, // so it isn't duplicated onto the event). Always fatal - the BATCH // path's equivalent (InstallDepSkipped) never is. InstallDownloadFailed // InstallChecksumComputed fires once a checksum has been computed and // !SkipVerify, for BOTH paths: the STRICT path's primary file(s) // (Index/Total/File populated, matching InstallDownloadStarted) and // the BATCH path's per-mod checksum (Index/Total/ModName populated // instead, File unset - mirroring batchInstallMods' own // " Checksum: %s\n", fired once per mod right after its download // succeeds). Detail carries the full (untruncated) checksum either // way; the CLI applies its own truncateChecksum. InstallChecksumComputed // InstallExtracting mirrors doInstall's unconditional "Extracting to // cache..." status line, fired once after the STRICT-path primary's // download(s) finish, before Install/Replace. The BATCH path never // prints this (batchInstallMods had no equivalent status line). InstallExtracting // InstallDeploying mirrors "Deploying to game directory...", fired once // right before the STRICT-path primary's Install/Replace. The BATCH // path never prints this. InstallDeploying // InstallDone fires once the STRICT-path primary has been fully // installed (deployed, saved, checksum stored, profile upserted). The // BATCH path's equivalent (for every mod, primary included) is // InstallDepInstalled. InstallDone // InstallNote fires wherever ApplyInstall appends an entry to // InstallResult.Notes (a failed profile-create, UpsertMod, // reinstall-cache-transaction commit, old-cache cleanup, or - BATCH // path only - a failed Uninstall/cache-Delete while removing a // mod's previous installation, see InstallDepReinstalling) - the // --verbose-gated stdout bucket, mirroring DeployNote/SwitchInstallNote. // Detail equals the Notes entry verbatim; ModName/ModID identify the // mod when relevant. InstallNote // InstallWarning fires wherever ApplyInstall appends an entry to // InstallResult.Warnings other than an InstallBeforeAllForced/ // InstallBeforeEachForced one: a failed SaveFileChecksum (unconditional // stderr, matching doInstall exactly - NOT verbose-gated), or an // install.after_each/after_all hook failure (deferred - see // ApplyInstall's doc comment - emitted after the whole run, mirroring // DeployWarning/printHookWarnings' batched timing). InstallWarning // UpdateDownloading mirrors applyUpdate's own download-progress readout // ("\r Downloading: %.1f%%", verbose-gated in the pre-extraction CLI) - // Percent only, gated on a known total size, matching // DeployDownloading/InstallDepDownloading's own gating (no raw // byte-count fallback - applyUpdate never printed one). UpdateDownloading // UpdateDownloadDone fires once, only after EVERY file in the update's // download step has downloaded successfully - mirroring applyUpdate's // own `if verbose { fmt.Println() }`, which terminates the // carriage-returned UpdateDownloading progress line. A download failure // returns immediately instead (see ApplyUpdate's doc comment), so - // like DeployDownloadDone, and unlike InstallDownloadDone - this covers // the success path only. A caller wanting byte-identical pre-extraction // output prints this ONLY under --verbose (the historical gate lived on // the print itself, not just the progress ticks). UpdateDownloadDone // UpdateBeforeEachForced fires when EITHER of the update's two // Force-gated hooks - uninstall.before_each (old version) or // install.before_each (new version) - fails with Force set, mirroring // applyUpdate's own two, textually-near-identical (only the hook name // differs) "Warning: %s hook failed (forced): %v" unconditional stderr // prints. Detail already carries the full, hook-specific message // verbatim. UpdateBeforeEachForced // UpdateWarning fires for either of the update's two after_each hook // failures - uninstall.after_each (old version) or install.after_each // (new version) - mirroring applyUpdate's own hookErrors/ // printHookWarnings pair, fired right after both hooks have run // (Replace already succeeded), in hook-run order (uninstall.after_each, // then install.after_each) - unlike DeployWarning/InstallWarning's // end-of-whole-run deferral, since applyUpdate itself prints these // immediately, well before its own DB-update steps below. UpdateWarning // UpdateNote fires when SetModLinkMethod fails after a successful // update - the sole --verbose-gated diagnostic in applyUpdate, // mirroring " Warning: could not update link method: %v" (2-space // indent, prefix baked into Detail, matching SwitchDisableNote/ // SwitchEnableNote's own convention). UpdateNote )
type DeployProgress ¶ added in v1.11.0
type DeployProgress struct {
Index, Total int
ModName string
ModID string
// SourceID is populated by ApplyProfileSwitch's install-loop events
// (SwitchInstallingMod onward), where a mod's SourceID:ModID pair is the
// only identity known before it has even been fetched (no ModName yet).
// DeployProfile's own events never set it (zero value, ignored).
SourceID string
Phase DeployPhase
Detail string
Percent float64
// Downloaded and TotalBytes carry the raw byte counts behind Percent for
// the primary mod's own download phases (InstallDownloading) - unlike
// DeployDownloading (gated on TotalBytes > 0 and Percent-only),
// doInstall's downloadSelectedFiles prints a byte-count readout even
// when the total size is unknown ("Downloaded %s" vs "%.1f%% (%s /
// %s)"), so the CLI needs the raw numbers, not just Percent, to
// reproduce that byte-identically. Zero for every other phase.
Downloaded int64
TotalBytes int64
// File identifies which of the primary mod's selected files an
// InstallDownload* event concerns, so the CLI can call its own
// displayFileLabel(*File) to reproduce doInstall's exact file-name
// formatting without core duplicating that cosmetic, CLI-only helper.
// Populated only for InstallDownloadStarted/InstallDownloading/
// InstallDownloadDone/InstallDownloadFailed/InstallChecksumComputed.
File *domain.DownloadableFile
// ModVersion carries the mod's version for InstallDepInstalling's
// restored "Installing: %s v%s" header text (batchInstallMods printed
// the version; the strict/no-deps path's own headers are printed
// CLI-side from data already in doInstall's scope, so this is a
// batch-only field). Zero for every other phase.
ModVersion string
// FilesExtracted carries the batch-mode mod's own extracted-file count
// for InstallDepInstalled's restored " ✓ Installed (%d files)" text
// (batchInstallMods' downloadResult.FilesExtracted) - distinct from
// InstallResult.FilesDeployed, which only ever tracks the STRICT path's
// primary. Zero for every other phase.
FilesExtracted int
}
DeployProgress reports incremental status during DeployProfile. Index and Total describe ModName's position among the mods being deployed (both zero for phases with no mod/count in scope - see each DeployPhase constant's doc comment). ModID accompanies ModName wherever a specific mod is in scope; for phases whose historical text carries no mod name at all (DeployNote's link-method/mark-deployed cases), it is the only attribution available. Detail and Percent are populated only for the phases documented on DeployPhase's constants; both are zero otherwise.
type DeployResult ¶ added in v1.11.0
DeployResult reports the outcome of DeployProfile. As with UninstallResult (see its doc comment), every entry below is always recorded - there is no verbosity concept in core - but Warnings and Notes carry the same two display contracts Task 2 established:
- Warnings holds diagnostics the pre-extraction CLI printed unconditionally to stderr: install.before_all/uninstall.before_all (when forced), a skipped uninstall.before_each during purge, install/uninstall after_each/after_all hook failures, and a profile-overrides application failure. Callers should print each entry to stderr, unconditionally, e.g. `fmt.Fprintf(os.Stderr, "Warning: %v\n", w)`.
- Notes holds operational diagnostics the pre-extraction CLI only printed under --verbose: a failed undeploy-before-redeploy, a failed SetModLinkMethod, and a failed SetModDeployed, all per mod, plus (for a --purge pass) the equivalent per-mod undeploy/SetModDeployed failures from purging. Each entry already carries its historical prefix ("Warning: " for the deploy-loop trio, "⚠ " for the purge trio) baked into the text, matching each one's pre-extraction wording; a caller wanting byte-identical pre-extraction output should print each entry to stdout ONLY under --verbose, verbatim, e.g. `fmt.Printf(" %s\n", n)`.
Every entry in both slices is ALSO reported via the progress callback at the exact point it is appended (DeployBeforeAllForced/DeployNote/ DeployWarning/PurgeWarning/PurgeNote - see each DeployPhase constant's doc comment for which), with Detail equal to the slice entry verbatim and the phase itself indicating which display contract above applies. A caller driving its console output entirely from progress events (as cmd/lmm's doDeploy does) gets pre-extraction-accurate positioning; the slices remain here, unconditionally, for callers that only want the final, order-independent summary.
Skipped carries one "<mod name>: <reason>" entry per mod that did not deploy, for any reason (hook failure, download failure, install failure); the pre-extraction CLI printed each of these unconditionally as it happened; DeployProgress's DeployBeforeEachSkipped/ DeployDownloadFailed/DeploySkipped events carry the same reason text in real time for callers that want to print them as they occur instead of (or in addition to) at the end.
On error, the returned result carries any diagnostics accumulated before the failure; callers should surface them alongside the error.
type DeployedFile ¶ added in v1.3.7
DeployedFile is a service-boundary view of a tracked mod file with its checksum.
type DisableResult ¶ added in v1.12.0
DisableResult reports the outcome of DisableMod. Changed mirrors EnableResult.Changed. Notes carries the sole diagnostic DisableMod can produce — a non-fatal undeploy failure (see DisableMod's doc comment) — using the same historical-prefix-baked-into-the-text convention UninstallResult's doc comment documents: a caller wanting byte-identical pre-5a output should print each entry to stdout ONLY under --verbose, verbatim, e.g. `fmt.Printf(" %s\n", n)`.
type DownloadModResult ¶ added in v0.8.0
type DownloadModResult struct {
FilesExtracted int // Number of files extracted
Checksum string // MD5 hash of downloaded archive
}
DownloadModResult contains the outcome of downloading a mod file
type DownloadProgress ¶
type DownloadProgress struct {
TotalBytes int64 // Total size in bytes (0 if unknown)
Downloaded int64 // Bytes downloaded so far
Percentage float64 // Completion percentage (0-100)
}
DownloadProgress represents the current state of a download
type DownloadResult ¶ added in v0.8.0
type DownloadResult struct {
Path string // Final file path
Size int64 // Bytes downloaded
Checksum string // MD5 hash of downloaded file (recorded in the DB)
SHA256 string // SHA-256 of downloaded file (compared against source-declared checksums)
}
DownloadResult contains the outcome of a download
type Downloader ¶
type Downloader struct {
// contains filtered or unexported fields
}
Downloader handles HTTP file downloads with progress tracking
func NewDownloader ¶
func NewDownloader(httpClient *http.Client) *Downloader
NewDownloader creates a new Downloader with the given HTTP client If httpClient is nil, http.DefaultClient is used
func (*Downloader) Download ¶
func (d *Downloader) Download(ctx context.Context, url, destPath string, progressFn ProgressFunc) (*DownloadResult, error)
Download fetches a file from the URL and saves it to destPath, with retries on transient failures (exponential backoff). Progress updates are sent to the optional progressFn callback.
func (*Downloader) DownloadWithHeaders ¶ added in v1.7.0
func (d *Downloader) DownloadWithHeaders(ctx context.Context, url, destPath string, headers map[string]string, progressFn ProgressFunc) (*DownloadResult, error)
DownloadWithHeaders is Download with extra request headers applied to every attempt — used for authenticated file downloads from custom sources.
type EnableResult ¶ added in v1.12.0
EnableResult reports the outcome of EnableMod. Changed is true iff the mod was actually deployed and flipped to enabled — false (not an error) when it was already enabled, mirroring EnableMod's pre-Task-6 (bool, error) return. Notes carries operational diagnostics using the same display-contract convention as UninstallResult/DeployResult (Task 2's convention, extended here in Task 6 item a for result-struct convergence): always empty today — EnableMod has no diagnostic-producing step — kept for parity with DisableResult and so a future EnableMod diagnostic wouldn't need another signature change.
type Extractor ¶
type Extractor struct{}
Extractor handles archive extraction for mod files
func (*Extractor) CanExtract ¶
CanExtract returns true if the extractor can handle the given filename
func (*Extractor) DetectFormat ¶
DetectFormat returns the archive format based on filename extension
type HookContext ¶ added in v0.12.0
type HookContext struct {
GameID string
GamePath string
ModPath string
ModID string // Empty for *_all hooks
ModName string // Empty for *_all hooks
ModVersion string // Empty for *_all hooks
HookName string // e.g., "install.before_all"
}
HookContext provides environment information for hook scripts
type HookResult ¶ added in v0.12.0
HookResult contains the output from running a hook
type HookRunner ¶ added in v0.12.0
type HookRunner struct {
// contains filtered or unexported fields
}
HookRunner executes hook scripts with timeout and environment
func NewHookRunner ¶ added in v0.12.0
func NewHookRunner(timeout time.Duration) *HookRunner
NewHookRunner creates a new hook runner with the given timeout
func (*HookRunner) Run ¶ added in v0.12.0
func (r *HookRunner) Run(ctx context.Context, scriptPath string, hc HookContext) (*HookResult, error)
Run executes a hook script and returns its output
type ImportOptions ¶ added in v0.10.0
type ImportOptions struct {
SourceID string // Explicit source (empty = auto-detect or "local")
ModID string // Explicit mod ID (empty = auto-detect or generate)
ProfileName string // Target profile
}
ImportOptions configures the import operation
type ImportResult ¶ added in v0.10.0
type ImportResult struct {
Mod *domain.Mod
FilesExtracted int
LinkedSource string // "nexusmods", "local", etc.
AutoDetected bool // true if source/ID was parsed from filename
}
ImportResult contains the outcome of importing a local mod
type Importer ¶ added in v0.10.0
type Importer struct {
// contains filtered or unexported fields
}
Importer handles importing mods from local archive files
func NewImporter ¶ added in v0.10.0
NewImporter creates a new Importer
func (*Importer) FindDuplicateMod ¶ added in v1.1.0
func (i *Importer) FindDuplicateMod(modName string, installedMods []domain.InstalledMod) *domain.InstalledMod
findDuplicateMod checks if a mod with similar name already exists (for duplicate prevention)
func (*Importer) Import ¶ added in v0.10.0
func (i *Importer) Import(ctx context.Context, archivePath string, game *domain.Game, opts ImportOptions) (result *ImportResult, err error)
Import imports a mod from a local archive file
func (*Importer) ScanModPath ¶ added in v1.1.0
func (i *Importer) ScanModPath(ctx context.Context, game *domain.Game, installedMods []domain.InstalledMod, opts ScanOptions) ([]ScanResult, error)
ScanModPath scans the game's mod_path for untracked mods
type InstallOptions ¶ added in v1.12.0
type InstallOptions struct {
// SkipVerify mirrors doInstall's --skip-verify: when true, a downloaded
// file's checksum is neither saved (SaveFileChecksum) nor reported via
// an InstallChecksumComputed event, matching downloadSelectedFiles' "if
// !skipVerify && checksum != ..." gate exactly for every mod (primary
// and dependencies alike - batchInstallMods honors the same flag).
SkipVerify bool
// Hook plumbing, mirroring UninstallOptions/DeployOptions. Hooks and/or
// HookRunner may be nil to skip hook execution entirely (e.g.
// --no-hooks).
//
// Force gates install.before_all (once, always) and, in the STRICT
// (no-deps) path ONLY, the primary's own install.before_each - matching
// doInstall's own single-mod code exactly (a failure aborts with an
// error unless Force is set, in which case it is recorded as a Warning
// and the install proceeds). In the BATCH (Dependencies-present) path,
// NO mod's before_each - dependency or primary alike - is EVER
// Force-gated: it unconditionally skips that one mod and continues,
// matching batchInstallMods exactly (Fix wave 1 - see
// task-2-report.md's "Fix wave 1" entry - restored this for the primary
// too; pre-extraction doInstall delegated the WHOLE list, target
// included, to batchInstallMods whenever Dependencies was non-empty).
Hooks *ResolvedHooks
HookRunner *HookRunner
HookContext HookContext
Force bool
// ConfirmConflicts gates the STRICT (no-deps) path's deploy step
// (applyInstallPrimary), restoring the pre-extraction CLI's blocking
// conflict prompt at its ORIGINAL position: AFTER the primary is
// downloaded and extracted to cache and BEFORE it is deployed - the
// exact point confirmInstallConflicts occupied in doInstall
// (cmd/lmm/install.go), since installer.GetConflicts can only inspect a
// mod's cache once something has actually been downloaded into it (see
// InstallPlan.Conflicts' doc comment for why a pre-download PlanInstall
// call can't do this for a mod that has never been cached before - the
// C1 review finding this field fixes: conflicts had regressed into
// PlanInstall alone, which silently missed every uncached mod's
// conflicts and, for an already-cached one, prompted at the wrong
// position).
//
// Called with the freshly-computed, non-empty conflict list ONLY when
// !Force and ConfirmConflicts is non-nil - Force skips the check
// entirely without ever calling it (matching doInstall's own "if
// !installForce" gate), and a nil ConfirmConflicts likewise skips it
// (proceeds silently), for a caller that doesn't want the STRICT path's
// blocking behavior at all (the BATCH path - applyInstallBatchMod - has
// its own separate, always-non-blocking inline warning and never
// consults this field).
//
// Returning false aborts the install with the exact error
// confirmInstallConflicts' decline produced ("installation cancelled"),
// leaving the same state a decline left in doInstall: before_all/
// before_each hooks already ran, the download is already cached (a
// fresh/upgrade install's cache entry is left in place; a same-version
// reinstall's staged reinstall-cache-transaction is rolled back via its
// existing deferred Rollback, restoring the live cache/deployed files
// exactly as they were), and nothing is deployed or saved to the DB/
// profile.
ConfirmConflicts func(conflicts []Conflict) bool
}
InstallOptions configures ApplyInstall.
type InstallPlan ¶ added in v1.12.0
type InstallPlan struct {
SourceID, GameID, Profile string
Mod domain.Mod // the mod that would be installed, freshly fetched via GetMod
// Files is the file(s) that WOULD be downloaded: GetModFiles' result
// after filterAndSortInstallFiles (doInstall's filterAndSortFiles,
// ported - strips ARCHIVED/OLD_VERSION/DELETED unless showArchived, sorts
// MAIN>OPTIONAL>UPDATE>MISCELLANEOUS>other), then the same non-interactive
// default cmd/lmm/install.go's selectInstallFiles falls back to (the
// primary file, or the sole/first file) absent --file or an interactive
// choice - reusing selectDeployFiles rather than porting
// selectInstallFiles verbatim, since selectInstallFiles's --file flag and
// interactive prompt both consume a plan rather than being part of one
// (see the task report). Always exactly one file in practice: neither
// selectDeployFiles nor this non-interactive default ever picks more
// than one without a stored/explicit multi-file selection.
Files []domain.DownloadableFile
// Dependencies is target's resolved, not-yet-installed dependency chain,
// deepest dependency first (install order) - target itself is excluded
// (it's Mod, above). Mirrors cmd/lmm/install.go's resolveDependencies
// exactly, including one quirk worth calling out: every dependency is
// fetched using the TOP-LEVEL SourceID field above, not each
// ModReference's own SourceID - a dependency listed for a different
// source therefore always ends up in MissingDependencies unless that
// source happens to stamp the same SourceID onto the Mod it returns (see
// resolveInstallDependencies). Empty (with a nil error) whenever the
// source lacks the Dependencies capability, returns
// source.ErrNotSupported, or Mod is a local (domain.SourceLocal) mod -
// resolveDependencies swallows ANY GetDependencies error the same way,
// degrading to "no dependencies" rather than failing the plan.
Dependencies []domain.Mod
// MissingDependencies records dependency references resolveDependencies
// found but couldn't resolve (source fetch failure, or a SourceID
// mismatch - see Dependencies) - the pre-extraction CLI's showInstallPlan
// printed these as a warning, never a failure. Not part of the task
// brief's directional API struct; added because the brief's own framing
// ("output contains everything the CLI's pre-install prompts... need to
// display") requires it to reproduce that warning - see the task report.
MissingDependencies []domain.ModReference
// CycleDetected mirrors resolveDependencies' cycleDetected: a circular
// reference was found while resolving Dependencies (install order is
// best-effort). Same rationale as MissingDependencies.
CycleDetected bool
// Conflicts lists files installing Mod would overwrite from OTHER
// installed mods, exactly as installer.GetConflicts reports them - but
// ONLY when Mod's exact (SourceID, ID, Version) is already cached:
// GetConflicts inspects the cache's extracted file list, and PlanInstall
// must never download to populate it (see the function doc comment). A
// mod that has never been downloaded before therefore always reports
// empty Conflicts here; this mirrors the pre-extraction CLI's own
// confirmInstallConflicts, which likewise treats ANY GetConflicts error
// (a cache-miss included) as "no conflicts, continue" rather than an
// install-blocking failure - see the task report.
Conflicts []Conflict
// Replaces is the currently-installed row for (SourceID, Mod.ID,
// Profile), if any - non-nil means installing this plan would use
// Installer.Replace (or its reinstall-cache-transaction variants, an
// Apply-time concern) rather than Installer.Install. Mirrors doInstall's
// existingMod exactly: populated regardless of whether the installed
// version matches Mod.Version, so both a same-version reinstall and a
// version upgrade set this.
Replaces *domain.InstalledMod
// TotalDownloadBytes is the sum of Files' declared sizes, or -1 if any
// selected file's size is unreported (Size <= 0, matching the
// DownloadProgress convention used elsewhere in this file: only a
// positive TotalBytes/Size is treated as "known").
TotalDownloadBytes int64
// ShowArchived is the showArchived value PlanInstall was called with -
// stored on the plan (Phase 5b Task 2) so ApplyInstall can resolve each
// Dependencies entry's own downloadable files (at apply time - see
// Dependencies' doc comment) using the identical filter the CLI showed
// the user at plan time, without a second, possibly-inconsistent
// parameter on InstallOptions. "The plan is the contract."
ShowArchived bool
}
InstallPlan is the pure, displayable result of PlanInstall: everything the pre-extraction CLI's pre-install prompts (dependency tree, conflict warnings, "already installed" notice) and the TUI's future install modal need to render before a caller decides whether to proceed (Phase 5b Task 2 adds ApplyInstall to actually execute one of these). Computed with zero side effects - see PlanInstall's doc comment.
type InstallResult ¶ added in v1.12.0
type InstallResult struct {
// Installed holds display names in install order: dependencies first,
// then the primary. In the STRICT (no-deps) path, a primary failure is
// FATAL - it returns an error instead of appending here. In the BATCH
// (Dependencies-present) path, the primary follows the exact same
// skip-and-continue semantics as every dependency (Fix wave 1 - see
// task-2-report.md's "Fix wave 1" entry) - a primary failure there
// populates Failed/Skipped below instead of returning an error.
Installed []string
// Skipped holds "<name>: <reason>" entries for any mod that failed in
// the BATCH (Dependencies-present) path - dependency OR primary alike
// (Fix wave 1 restored the primary's participation; see InstallOptions'
// Force doc comment). Always empty in the STRICT (no-deps) path, since
// a primary failure there returns an error instead.
Skipped []string
// Failed holds JUST the display names (no reason - see Skipped for
// that) of every BATCH-path mod that failed, dependency or primary
// alike, in the SAME order Skipped uses - mirrors batchInstallMods' own
// `failed []string` accumulator, which the pre-extraction CLI's
// restored terminal "--- Summary ---\nInstalled: %d\nFailed: %d (%s)\n"
// block joins verbatim (task-2-report.md's Fix wave 1). Always empty
// in the STRICT (no-deps) path.
Failed []string
// FilesDeployed is the number of files extracted for the STRICT path's
// PRIMARY mod across all of plan.Files - mirrors doInstall's
// totalFileCount / the pre-extraction CLI's final "Files deployed: %d"
// line. Always 0 in the BATCH path (batchInstallMods' terminal summary
// never printed a file count, only Installed/Failed - see Failed).
FilesDeployed int
Warnings []string
Notes []string
}
InstallResult reports the outcome of ApplyInstall. As with DeployResult/ UninstallResult/SwitchResult, every entry below is always recorded - there is no verbosity concept in core.
- Warnings holds diagnostics doInstall/batchInstallMods printed unconditionally: install.before_all/before_each (STRICT-path primary only, when forced), a failed SaveFileChecksum (note: unconditional, NOT --verbose-gated - doInstall/batchInstallMods print this one to stderr regardless), and install.after_each/after_all hook failures. Callers should print each entry to stderr, unconditionally, e.g. `fmt.Fprintf(os.Stderr, "Warning: %v\n", w)`.
- Notes holds diagnostics doInstall/batchInstallMods only printed under --verbose: a failed profile-create, a failed UpsertMod, a failed reinstall-cache-transaction commit, a failed old-cache cleanup after a version upgrade (all STRICT-path), or - BATCH path only - a failed Uninstall/cache-Delete while removing a mod's previous installation
- each already carrying its historical "Warning: " prefix baked into the text, matching the pre-extraction CLI's exact wording; a caller wanting byte-identical output should print each entry to stdout ONLY under --verbose, e.g. `fmt.Printf(" %s\n", n)`.
Every entry in both slices is ALSO reported via the progress callback at the exact point it is appended (InstallBeforeAllForced/ InstallBeforeEachForced/InstallWarning/InstallNote - see each DeployPhase constant's doc comment), with Detail equal to the slice entry verbatim.
On error, the returned result carries any diagnostics/counts accumulated before the failure; callers should surface them alongside the error.
type InstalledModResult ¶ added in v0.12.0
InstalledModResult is a successfully installed mod (wraps domain.Mod for batch result)
type Installer ¶
type Installer struct {
// contains filtered or unexported fields
}
Installer handles mod installation and uninstallation
func NewInstaller ¶
NewInstaller creates a new installer The db parameter is optional - if nil, file tracking is disabled
func (*Installer) GetConflicts ¶ added in v0.9.0
func (i *Installer) GetConflicts(ctx context.Context, game *domain.Game, mod *domain.Mod, profileName string) ([]Conflict, error)
GetConflicts checks if installing a mod would overwrite files from other mods. Returns conflicts for files owned by OTHER mods (not the mod being installed).
func (*Installer) GetDeployedFiles ¶
GetDeployedFiles returns the list of files deployed for a mod
func (*Installer) Install ¶
func (i *Installer) Install(ctx context.Context, game *domain.Game, mod *domain.Mod, profileName string) error
Install deploys a mod to the game directory. If DB tracking is enabled and a SaveDeployedFile fails, only the file that failed to track is rolled back so the filesystem stays consistent with the database (previously deployed+tracked files are left in place).
func (*Installer) InstallBatch ¶ added in v0.12.0
func (i *Installer) InstallBatch(ctx context.Context, game *domain.Game, mods []*domain.Mod, versions []string, profileName string, opts BatchOptions) (*BatchResult, error)
InstallBatch installs multiple mods with hook support Hook behavior: - install.before_all: If fails, return error immediately (unless Force) - install.before_each: If fails, skip that mod, continue others - install.after_each: If fails, warn (add to Errors), continue - install.after_all: If fails, warn (add to Errors)
func (*Installer) IsInstalled ¶
IsInstalled checks if a mod is currently deployed. Returns true only if every cached file is deployed (partial installs report as not installed).
func (*Installer) Replace ¶ added in v1.3.3
func (i *Installer) Replace(ctx context.Context, game *domain.Game, oldMod, newMod *domain.Mod, profileName string) error
Replace swaps an existing deployment with a new cached version and restores the old files if the replacement fails.
func (*Installer) ReplaceWithCaches ¶ added in v1.3.3
func (i *Installer) ReplaceWithCaches(ctx context.Context, game *domain.Game, oldCache, newCache *cache.Cache, oldMod, newMod *domain.Mod, profileName string) error
ReplaceWithCaches swaps an existing deployment using explicit old and new caches.
func (*Installer) ReplaceWithOldCache ¶ added in v1.3.3
func (i *Installer) ReplaceWithOldCache(ctx context.Context, game *domain.Game, oldCache *cache.Cache, oldMod, newMod *domain.Mod, profileName string) error
ReplaceWithOldCache swaps an existing deployment using an alternate cache snapshot for the old version.
func (*Installer) Uninstall ¶
func (i *Installer) Uninstall(ctx context.Context, game *domain.Game, mod *domain.Mod, profileName string) error
Uninstall removes a mod from the game directory
func (*Installer) UninstallBatch ¶ added in v0.12.0
func (i *Installer) UninstallBatch(ctx context.Context, game *domain.Game, mods []*domain.InstalledMod, profileName string, opts BatchOptions) (*BatchResult, error)
UninstallBatch uninstalls multiple mods with hook support Hook behavior: - uninstall.before_all: If fails, return error immediately (unless Force) - uninstall.before_each: If fails, skip that mod, continue others - uninstall.after_each: If fails, warn (add to Errors), continue - uninstall.after_all: If fails, warn (add to Errors)
type ParsedFilename ¶ added in v0.10.0
type ParsedFilename struct {
ModID string // NexusMods mod ID
Version string // Mod version (normalized)
BaseName string // Mod name portion before the ID
}
ParsedFilename contains extracted info from a NexusMods-style filename
func ParseNexusModsFilename ¶ added in v0.10.0
func ParseNexusModsFilename(filename string) *ParsedFilename
ParseNexusModsFilename attempts to extract mod ID and version from a NexusMods-style filename like "SkyUI-12604-5-2SE.zip". Returns nil if the filename doesn't match the expected pattern.
type ProfileManager ¶
type ProfileManager struct {
// contains filtered or unexported fields
}
ProfileManager handles profile CRUD operations and switching
func NewProfileManager ¶
func NewProfileManager(configDir string, database *db.DB, cache *cache.Cache, lnk linker.Linker) *ProfileManager
NewProfileManager creates a new profile manager
func (*ProfileManager) AddMod ¶
func (pm *ProfileManager) AddMod(gameID, profileName string, mod domain.ModReference) error
AddMod adds a mod reference to a profile
func (*ProfileManager) Create ¶
func (pm *ProfileManager) Create(gameID, name string) (*domain.Profile, error)
Create creates a new profile for a game
func (*ProfileManager) Delete ¶
func (pm *ProfileManager) Delete(gameID, name string) error
Delete removes a profile
func (*ProfileManager) Export ¶
func (pm *ProfileManager) Export(gameID, profileName string) ([]byte, error)
Export exports a profile to a portable format
func (*ProfileManager) Get ¶
func (pm *ProfileManager) Get(gameID, name string) (*domain.Profile, error)
Get retrieves a specific profile
func (*ProfileManager) GetDefault ¶
func (pm *ProfileManager) GetDefault(gameID string) (*domain.Profile, error)
GetDefault returns the default profile for a game
func (*ProfileManager) Import ¶
func (pm *ProfileManager) Import(data []byte) (*domain.Profile, error)
Import imports a profile from portable format
func (*ProfileManager) ImportWithOptions ¶
ImportWithOptions imports a profile with optional force overwrite
func (*ProfileManager) List ¶
func (pm *ProfileManager) List(gameID string) ([]*domain.Profile, error)
List returns all profiles for a game
func (*ProfileManager) ParseProfile ¶
func (pm *ProfileManager) ParseProfile(data []byte) (*domain.Profile, error)
ParseProfile parses profile data without saving (for preview)
func (*ProfileManager) RemoveMod ¶
func (pm *ProfileManager) RemoveMod(gameID, profileName, sourceID, modID string) error
RemoveMod removes a mod reference from a profile
func (*ProfileManager) ReorderMods ¶
func (pm *ProfileManager) ReorderMods(gameID, profileName string, mods []domain.ModReference) error
ReorderMods updates the load order of mods in a profile
func (*ProfileManager) SetDefault ¶
func (pm *ProfileManager) SetDefault(gameID, name string) error
SetDefault sets a profile as the default for a game
func (*ProfileManager) Switch ¶
func (pm *ProfileManager) Switch(ctx context.Context, game *domain.Game, newProfileName string) error
Switch switches to a different profile, undeploying the current profile's mods and deploying the new profile's mods. It fails fast on any error and rolls back to the previous state (game dir and default profile) so the system is never left in a mixed old/new state.
func (*ProfileManager) UpsertMod ¶ added in v0.7.5
func (pm *ProfileManager) UpsertMod(gameID, profileName string, mod domain.ModReference) error
UpsertMod adds or updates a mod reference in a profile. If the mod exists, it updates Version and FileIDs while preserving position. If the mod doesn't exist, it appends to the end. This is the preferred method for install/update operations.
type ProgressFunc ¶
type ProgressFunc func(DownloadProgress)
ProgressFunc is called periodically during download with progress updates
type ResolvedHooks ¶ added in v0.12.0
type ResolvedHooks struct {
Install domain.HookConfig
Uninstall domain.HookConfig
}
ResolvedHooks contains the final merged hooks for an operation
func ResolveHooks ¶ added in v0.12.0
func ResolveHooks(game *domain.Game, profile *domain.Profile) *ResolvedHooks
ResolveHooks merges game-level hooks with profile-level overrides
func (*ResolvedHooks) GetInstallAfterAll ¶ added in v1.3.1
func (h *ResolvedHooks) GetInstallAfterAll() string
GetInstallAfterAll returns the install.after_all command, or "" if not set.
func (*ResolvedHooks) GetInstallAfterEach ¶ added in v1.3.1
func (h *ResolvedHooks) GetInstallAfterEach() string
GetInstallAfterEach returns the install.after_each command, or "" if not set.
func (*ResolvedHooks) GetInstallBeforeAll ¶ added in v1.3.1
func (h *ResolvedHooks) GetInstallBeforeAll() string
GetInstallBeforeAll returns the install.before_all command, or "" if not set. Nil-safe: returns "" when the receiver is nil.
func (*ResolvedHooks) GetInstallBeforeEach ¶ added in v1.3.1
func (h *ResolvedHooks) GetInstallBeforeEach() string
GetInstallBeforeEach returns the install.before_each command, or "" if not set.
func (*ResolvedHooks) GetUninstallAfterAll ¶ added in v1.3.1
func (h *ResolvedHooks) GetUninstallAfterAll() string
GetUninstallAfterAll returns the uninstall.after_all command, or "" if not set.
func (*ResolvedHooks) GetUninstallAfterEach ¶ added in v1.3.1
func (h *ResolvedHooks) GetUninstallAfterEach() string
GetUninstallAfterEach returns the uninstall.after_each command, or "" if not set.
func (*ResolvedHooks) GetUninstallBeforeAll ¶ added in v1.3.1
func (h *ResolvedHooks) GetUninstallBeforeAll() string
GetUninstallBeforeAll returns the uninstall.before_all command, or "" if not set.
func (*ResolvedHooks) GetUninstallBeforeEach ¶ added in v1.3.1
func (h *ResolvedHooks) GetUninstallBeforeEach() string
GetUninstallBeforeEach returns the uninstall.before_each command, or "" if not set.
type ScanOptions ¶ added in v1.1.0
type ScanOptions struct {
ProfileName string
DryRun bool // If true, don't actually import, just report what would be done
}
ScanOptions configures the scan operation
type ScanResult ¶ added in v1.1.0
type ScanResult struct {
FilePath string // Original path in mod_path
FileName string // Base filename
Mod *domain.Mod // Detected/created mod info
MatchedSource string // "curseforge", "nexusmods", or "local"
AlreadyTracked bool // True if already in lmm database
Error error // Any error during processing
}
ScanResult contains the outcome of scanning a single mod file
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the main orchestrator for mod management operations
func NewService ¶
func NewService(cfg ServiceConfig) (*Service, error)
NewService creates a new core service instance
func (*Service) ApplyInstall ¶ added in v1.12.0
func (s *Service) ApplyInstall(ctx context.Context, game *domain.Game, plan *InstallPlan, opts InstallOptions, progress func(DeployProgress)) (*InstallResult, error)
ApplyInstall executes a plan produced by PlanInstall, gated on len(plan.Dependencies) - see the DeployPhase Install* constants' doc comments (starting at InstallBeforeAllForced) for the full restored- fidelity design this reproduces, and task-2-report.md's "Fix wave 1 (dep-path fidelity)" entry for the review trace that drove it:
- Empty: the STRICT (no-deps) path - only plan.Mod installs, via applyInstallPrimary's doInstall-derived single-mod mechanics (Force-gated hooks, Install-or-Replace, SaveFileChecksum; interactive/--file selection is the CALLER's job, applied to plan.Files before this is ever called - but the blocking conflict prompt is NOT: it fires INSIDE applyInstallPrimary itself, post- download/pre-deploy, via opts.ConfirmConflicts - see that field's doc comment for why a caller-side, plan.Conflicts-driven prompt can never detect an uncached mod's conflicts, the C1 review finding this restores fidelity for).
- Non-empty: the BATCH path - plan.Dependencies (in plan order) THEN plan.Mod all install via applyInstallBatchMod, IDENTICALLY, matching batchInstallMods' own "every mod in the list is treated the same" design byte-for-byte - the primary is NOT special-cased here at all (no Replace, no interactive selection, no blocking conflict prompt - see applyInstallBatchMod's own doc comment).
install.before_all runs once, before any mod is touched, in EITHER path (matching both doInstall's own single-mod code and batchInstallMods, which each had their own, functionally-identical, Force-gated install.before_all call). install.after_all runs once, at the very end: in the STRICT path, only if the primary's own install fully succeeded (an early return skips it entirely, matching doInstall's single-mod code); in the BATCH path, unconditionally once the loop finishes, since no per-mod failure there is ever fatal (matching batchInstallMods, which always reaches its own install.after_all call regardless of how many mods in its list failed). progress may be nil.
On error, the returned result carries any diagnostics/Installed entries accumulated before the failure - callers should surface them alongside the error (see InstallResult's doc comment).
func (*Service) ApplyModUpdate ¶ added in v1.3.3
func (s *Service) ApplyModUpdate(sourceID, modID, gameID, profileName, newVersion string, fileIDs []string) error
ApplyModUpdate updates version and file IDs atomically, preserving rollback state.
func (*Service) ApplyProfileSwitch ¶ added in v1.11.0
func (s *Service) ApplyProfileSwitch(ctx context.Context, game *domain.Game, plan *SwitchPlan, progress func(DeployProgress)) (*SwitchResult, error)
ApplyProfileSwitch executes a plan produced by PlanProfileSwitch: disables every ToDisable mod, then enables every ToEnable mod, then downloads and installs every ToInstall mod, and finally calls ProfileManager.SetDefault to make plan.To the active profile - in that order, matching doProfileSwitch exactly. progress may be nil.
doProfileSwitch runs no install/uninstall hooks at all (unlike DeployProfile/UninstallMod), so ApplyProfileSwitch doesn't either - there is deliberately no hook plumbing in its signature or DeployOptions-style options struct, since profile switch takes no CLI flags beyond the target profile name.
plan is executed EXACTLY as given - this method never re-plans or re-validates it against current state. A caller that computed plan some time ago (e.g. to show a user a preview) and only calls this later, after showing that preview, accepts whatever has changed in the interim as already baked into plan; PlanProfileSwitch's own doc comment documents why speculative plans are cheap enough to discard and recompute instead. The TUI's coreProvider.ApplyProfileSwitch (Task 6 item e) is exactly this caller: it re-plans immediately before calling this method, which is a SEPARATE PlanProfileSwitch call from whichever one built the confirmation modal the user actually saw - see that method's own doc comment for the resulting preview/apply drift this can introduce.
func (*Service) ApplyUpdate ¶ added in v1.12.0
func (s *Service) ApplyUpdate(ctx context.Context, game *domain.Game, profileName string, upd domain.Update, opts UpdateOptions, progress func(DeployProgress)) (*UpdateApplyResult, error)
ApplyUpdate applies upd to the installed mod it references (upd.InstalledMod), following cmd/lmm/update.go's pre-extraction applyUpdate ordering exactly: GetMod (the new version) -> GetModFiles -> resolve FileIDReplacements -> download -> hooks -> installer.Replace -> ApplyModUpdate -> SetModLinkMethod -> UpsertMod. This is a behavior-preserving extraction - see the task report for the full mapping.
FileIDReplacements resolution mirrors applyUpdate exactly: each of the installed mod's own FileIDs is looked up in upd.FileIDReplacements; a hit substitutes the new (superseding) file ID, a miss retains the ORIGINAL id verbatim (never silently dropped) - selectDeployFiles' own primary-file fallback only kicks in afterward, if NONE of the resulting IDs are found among the new version's available files at all.
A download failure returns immediately - before any hook runs, before Replace, before any DB/profile write - so the old version is left deployed and every row untouched, matching applyUpdate's own bare early return. Installer.Replace never touches the cache (only the game directory and deployed-file tracking - see installer.go), so the OLD version's cache entry always survives an update; ApplyModUpdate records PreviousVersion/PreviousFileIDs before overwriting version/FileIDs - both preconditions `lmm update rollback` (doUpdateRollback, NOT extracted by this task - see the task report) depends on.
Hook failure semantics mirror applyUpdate's own two, independently Force-gated before_each hooks (uninstall.before_each for the OLD mod, install.before_each for the NEW mod: fatal unless Force is set, in which case a Warning is recorded and the update proceeds) and its two always- non-fatal after_each hooks (uninstall.after_each, install.after_each - both recorded as Warnings regardless of Force, printed immediately after Replace, well before the DB/profile writes below - see UpdateWarning's doc comment).
A failure to write ApplyModUpdate or UpsertMod triggers the same best-effort compensating actions applyUpdate itself performed (a reverse Installer.Replace to restore the old deployment, plus - for UpsertMod - a RollbackModVersion to undo the DB version swap first); a failure to write SetModLinkMethod is NOT rolled back, matching applyUpdate exactly (it only ever produced a --verbose-gated Note).
progress may be nil. On error, the returned result carries any diagnostics accumulated before the failure - callers should surface them alongside the error (see UpdateApplyResult's doc comment).
func (*Service) DeleteInstalledMod ¶ added in v1.3.7
DeleteInstalledMod removes the installed-mod record from the active profile.
func (*Service) DeleteSourceToken ¶
DeleteSourceToken removes an API token for a source
func (*Service) DeployProfile ¶ added in v1.11.0
func (s *Service) DeployProfile(ctx context.Context, game *domain.Game, profileName string, opts DeployOptions, progress func(DeployProgress)) (*DeployResult, error)
DeployProfile redeploys the mods of a profile in profile order: an optional --purge pass first (undeploying every installed mod), then for each mod to deploy - re-downloading from source if its cache entry is missing - an undeploy-then-install cycle recording the effective link method and deployed state, and finally applying any profile overrides. This is a behavior-preserving extraction of the pre-extraction CLI's doDeploy (cmd/lmm/deploy.go) and purgeDeployedMods (cmd/lmm/purge.go, the --purge-before-deploy call only - the standalone `lmm purge` command is untouched by this extraction); see the task report for the exact mapping.
progress may be nil. When non-nil, it is called synchronously from this function for every notable event - see DeployPhase's constants for what each one means and what Detail/Percent carry.
func (*Service) DisableMod ¶ added in v1.11.0
func (s *Service) DisableMod(ctx context.Context, game *domain.Game, profileName, sourceID, modID string) (*DisableResult, error)
DisableMod undeploys the mod's files from the game directory — the cache entry is kept so the mod can be re-enabled later without downloading again — and marks it disabled in the database. Returns a result with Changed false — not an error — if the mod was already disabled.
Undeploy failures are treated as non-fatal: the game files may already have been removed manually, and refusing to record the user's intent to disable the mod would leave it stuck. This mirrors the pre-extraction CLI, which warned (under --verbose) but always continued to flip the DB state — DisableResult.Notes (Task 6 item a) restores that diagnostic for callers that want it, rather than discarding it as the (bool, error) signature this replaces was forced to.
func (*Service) DownloadMod ¶
func (s *Service) DownloadMod(ctx context.Context, sourceID string, game *domain.Game, mod *domain.Mod, file *domain.DownloadableFile, progressFn ProgressFunc) (result *DownloadModResult, err error)
DownloadMod downloads a mod file, extracts it, and stores it in the cache Returns the download result including files extracted and checksum. Multiple files from the same mod can be downloaded to the same cache location.
func (*Service) DownloadModToCache ¶ added in v1.3.3
func (s *Service) DownloadModToCache(ctx context.Context, gameCache *cache.Cache, sourceID string, game *domain.Game, mod *domain.Mod, file *domain.DownloadableFile, progressFn ProgressFunc) (result *DownloadModResult, err error)
DownloadModToCache downloads a mod file, extracts it, and stores it in the provided cache.
func (*Service) EnableMod ¶ added in v1.11.0
func (s *Service) EnableMod(ctx context.Context, game *domain.Game, profileName, sourceID, modID string) (*EnableResult, error)
EnableMod deploys an installed-but-disabled mod's files from the cache to the game directory and marks it enabled in the database. Returns a result with Changed false — not an error — if the mod was already enabled.
func (*Service) GetDefaultLinkMethod ¶
func (s *Service) GetDefaultLinkMethod() domain.LinkMethod
GetDefaultLinkMethod returns the default link method from config
func (*Service) GetDependencies ¶ added in v0.11.0
func (s *Service) GetDependencies(ctx context.Context, sourceID string, mod *domain.Mod) ([]domain.ModReference, error)
GetDependencies returns dependencies for a mod from the specified source
func (*Service) GetDeployedFilesForMod ¶ added in v1.3.7
func (s *Service) GetDeployedFilesForMod(gameID, profileName, sourceID, modID string) ([]string, error)
GetDeployedFilesForMod returns the relative paths the given mod has deployed in the named profile.
func (*Service) GetDownloadURL ¶
func (s *Service) GetDownloadURL(ctx context.Context, sourceID string, mod *domain.Mod, fileID string) (string, error)
GetDownloadURL gets the download URL for a specific mod file
func (*Service) GetFileOwner ¶ added in v1.3.7
func (s *Service) GetFileOwner(gameID, profileName, relativePath string) (sourceID, modID string, found bool, err error)
GetFileOwner reports which mod currently owns a deployed file. The bool is false when no record exists; err is non-nil only on storage errors.
func (*Service) GetFilesWithChecksums ¶ added in v1.3.7
func (s *Service) GetFilesWithChecksums(gameID, profileName string) ([]DeployedFile, error)
GetFilesWithChecksums returns every tracked file in the profile with its recorded checksum (empty when none has been computed yet).
func (*Service) GetGameCache ¶
GetGameCache returns a cache manager for the specified game. Uses the game's cache_path if configured (game-scoped: paths omit gameID), otherwise the global cache.
func (*Service) GetGameCachePath ¶
GetGameCachePath returns the effective cache path for a game. Uses the game's cache_path if configured, otherwise falls back to global cache.
func (*Service) GetGameLinkMethod ¶
func (s *Service) GetGameLinkMethod(game *domain.Game) domain.LinkMethod
GetGameLinkMethod returns the effective link method for a game. Uses the game's explicit setting if configured, otherwise falls back to global default.
func (*Service) GetInstalledMod ¶
func (s *Service) GetInstalledMod(sourceID, modID, gameID, profileName string) (*domain.InstalledMod, error)
GetInstalledMod retrieves a single installed mod
func (*Service) GetInstalledMods ¶
func (s *Service) GetInstalledMods(gameID, profileName string) ([]domain.InstalledMod, error)
GetInstalledMods returns all installed mods for a game/profile (DB order: installed_at).
func (*Service) GetInstalledModsInProfileOrder ¶ added in v1.1.0
func (s *Service) GetInstalledModsInProfileOrder(gameID, profileName string) ([]domain.InstalledMod, error)
GetInstalledModsInProfileOrder returns installed mods in profile load order (first = lowest priority). Mods not present in the profile are omitted. Use this for deploy/switch so deployment order matches load order.
func (*Service) GetInstaller ¶ added in v0.7.8
GetInstaller returns an Installer configured for the given game
func (*Service) GetLinker ¶
func (s *Service) GetLinker(method domain.LinkMethod) linker.Linker
GetLinker returns a linker for the given method
func (*Service) GetModFiles ¶
func (s *Service) GetModFiles(ctx context.Context, sourceID string, mod *domain.Mod) ([]domain.DownloadableFile, error)
GetModFiles retrieves available download files for a mod
func (*Service) GetSourceToken ¶
func (s *Service) GetSourceToken(sourceID string) (*db.StoredToken, error)
GetSourceToken retrieves an API token for a source
func (*Service) IsSourceAuthenticated ¶
IsSourceAuthenticated checks if a source has a stored API token
func (*Service) ListSourceTokens ¶ added in v1.8.0
func (s *Service) ListSourceTokens() ([]db.StoredToken, error)
ListSourceTokens returns every stored API token, including ones whose source is no longer registered (e.g. the custom-source definition file was removed) — used by `lmm auth status` to surface orphaned credentials.
func (*Service) ListSources ¶
ListSources returns all registered sources
func (*Service) NewInstallerWithLinker ¶ added in v1.3.7
NewInstallerWithLinker returns an Installer for the given game using a caller-supplied linker — used when the CLI overrides the game's default link method (e.g. `lmm deploy --method`).
func (*Service) NewProfileManager ¶ added in v1.3.7
func (s *Service) NewProfileManager() *ProfileManager
NewProfileManager returns a ProfileManager wired to this service's storage, so callers do not need direct access to the database or registry.
func (*Service) NewUpdater ¶ added in v1.3.7
NewUpdater returns an Updater wired to this service's source registry.
func (*Service) PlanInstall ¶ added in v1.12.0
func (s *Service) PlanInstall(ctx context.Context, game *domain.Game, profileName, sourceID, modID string, showArchived bool) (*InstallPlan, error)
PlanInstall computes what installing (sourceID, modID) into profileName would do - the pure, read-only half of the pre-extraction CLI's doInstall (cmd/lmm/install.go), extracted with zero mutations so a caller (the CLI, or the TUI's future install modal) can render it and decide whether to proceed before Phase 5b Task 2's ApplyInstall executes it. See InstallPlan's doc comment for what each field means, and the task report for the exact mapping back to doInstall.
Deliberately NOT reproduced here (both consume a plan rather than being part of one, matching PlanProfileSwitch's precedent):
- doInstall's interactive file picking / --file flag (selectInstallFiles) and its "Install N mod(s)? Y/n" dependency confirm prompt - Files always reflects the same non-interactive default cmd/lmm's own --yes flag would pick; a CLI/TUI caller that resolves a different selection overrides plan.Files before calling ApplyInstall.
- --no-deps: a caller that wants to skip Dependencies can simply ignore or clear them before calling ApplyInstall.
showArchived mirrors doInstall's --show-archived flag exactly: it is threaded straight into filterAndSortInstallFiles (the faithful port of cmd/lmm/install.go's filterAndSortFiles - same ARCHIVED/OLD_VERSION/DELETED filter set, same MAIN>OPTIONAL>UPDATE>MISCELLANEOUS>other sort), which runs BEFORE the "no downloadable files" check and BEFORE selectDeployFiles - so a mod whose files are all archived reports the CLI's exact error instead of a plan, and the no-IsPrimary fallback picks the CLI's post-sort file, not GetModFiles' raw-order first. This parameter exists so Task 2's CLI refit can pass installShowArchived straight through without re-porting filterAndSortFiles into cmd/lmm a second time - see the task report's Fix wave 1 for why a parameter (rather than a hardcoded false, or a separate options type/overload) is the shape picked here.
Network reads (GetMod, GetDependencies, GetModFiles) are expected; no DB write, filesystem write, cache write, hook execution, or download ever happens here - see TestService_PlanInstall_PerformsZeroMutations.
func (*Service) PlanProfileSwitch ¶ added in v1.11.0
func (s *Service) PlanProfileSwitch(ctx context.Context, game *domain.Game, target string) (*SwitchPlan, error)
PlanProfileSwitch computes the diff between game's currently-active default profile and target, without mutating anything (no DB writes, no filesystem changes, no deploys) - callers may call this speculatively (to render a confirmation modal) and discard the result without consequence. See SwitchPlan's doc comment; ctx is accepted for API consistency with the rest of Service's methods and future-proofing, even though today's algorithm performs no I/O that needs it.
func (*Service) RegisterSource ¶
RegisterSource adds a mod source to the registry
func (*Service) RollbackModVersion ¶
RollbackModVersion reverts a mod to its previous version
func (*Service) SaveFileChecksum ¶ added in v1.3.7
func (s *Service) SaveFileChecksum(sourceID, modID, gameID, profileName, fileID, checksum string) error
SaveFileChecksum records the verified checksum for a downloaded mod file.
func (*Service) SaveInstalledMod ¶ added in v1.3.7
func (s *Service) SaveInstalledMod(mod *domain.InstalledMod) error
SaveInstalledMod persists an installed-mod record (insert or update).
func (*Service) SaveSourceToken ¶
SaveSourceToken saves an API token for a source
func (*Service) SearchAllSources ¶ added in v1.10.0
func (s *Service) SearchAllSources(ctx context.Context, gameID, query, category string, tags []string, page, pageSize int) (AggregateSearchResult, error)
SearchAllSources searches every source configured for a game concurrently and merges the results (design §5). Per-source failures become Warnings — one flaky API must not hide local modlets; only all-sources-failed is an error. Sources without search capability are skipped silently. Pagination is per-source: page N requests page N from each source and merges.
func (*Service) SearchMods ¶
func (s *Service) SearchMods(ctx context.Context, sourceID, gameID, query string, category string, tags []string, page, pageSize int) (source.SearchResult, error)
SearchMods searches for mods in a source
func (*Service) SetModDeployed ¶ added in v1.3.7
SetModDeployed records whether a mod's files are currently deployed.
func (*Service) SetModEnabled ¶ added in v1.3.7
SetModEnabled toggles the enabled flag for an installed mod.
func (*Service) SetModFileIDs ¶ added in v0.7.3
func (s *Service) SetModFileIDs(sourceID, modID, gameID, profileName string, fileIDs []string) error
SetModFileIDs updates the file IDs for an installed mod
func (*Service) SetModLinkMethod ¶
func (s *Service) SetModLinkMethod(sourceID, modID, gameID, profileName string, linkMethod domain.LinkMethod) error
SetModLinkMethod sets the deployment method for an installed mod
func (*Service) SetModUpdatePolicy ¶
func (s *Service) SetModUpdatePolicy(sourceID, modID, gameID, profileName string, policy domain.UpdatePolicy) error
SetModUpdatePolicy sets the update policy for an installed mod
func (*Service) UninstallMod ¶ added in v1.11.0
func (s *Service) UninstallMod(ctx context.Context, game *domain.Game, profileName, sourceID, modID string, opts UninstallOptions) (*UninstallResult, error)
UninstallMod removes a mod from the profile: runs uninstall hooks, undeploys files, deletes the cache entry (unless KeepCache), removes the DB row, and removes the mod from the profile YAML.
Hook failure semantics (matching the pre-extraction CLI's doUninstall):
- uninstall.before_all / uninstall.before_each: a failure aborts the operation with an error, unless Force is set, in which case it is recorded in Warnings and the uninstall proceeds.
- uninstall.after_each / uninstall.after_all: always non-fatal; a failure is recorded in Warnings after every other step has already committed.
Undeploy failures, cache-delete failures, and a failure to remove the mod from the profile (e.g. the DB and profile have drifted out of sync) are all non-fatal and always recorded in Notes; the operation still completes. See UninstallResult's doc comment for the Warnings/Notes display contract.
func (*Service) UpdateModVersion ¶
UpdateModVersion updates the version of an installed mod, preserving the previous version for rollback
type ServiceConfig ¶
type ServiceConfig struct {
ConfigDir string // Directory for configuration files
DataDir string // Directory for database and persistent data
CacheDir string // Directory for mod file cache
}
ServiceConfig holds configuration for the core service
type SkippedMod ¶ added in v0.12.0
SkippedMod represents a mod that was skipped during batch operation
type SourceWarning ¶ added in v1.10.0
SourceWarning reports a per-source failure during an aggregate operation.
type SwitchPlan ¶ added in v1.11.0
type SwitchPlan struct {
GameID, From, To string
ToEnable []domain.InstalledMod // installed+disabled (or installed under a different profile) -> enable, deployed under To
ToDisable []domain.InstalledMod // enabled under From but absent from To -> disable, undeployed under From
ToInstall []domain.ModReference // in To but not installed anywhere -> download+install (FileIDs preserved from the installed mod's own record when this is really a cache-miss redeploy - see PlanProfileSwitch)
NoChanges bool // To's mod set matches From's content-wise; only SetDefault is needed
AlreadyActive bool // To is already the active default profile; nothing to plan
}
SwitchPlan is the pure, displayable diff between the currently-active default profile and a target profile - computed by PlanProfileSwitch with zero side effects, so a caller (the CLI, or eventually the TUI) can render it (in a print block or a confirmation modal) before deciding whether to call ApplyProfileSwitch. This is a behavior-preserving extraction of cmd/lmm/profile.go's doProfileSwitch's diff computation (through its "Show changes" print block) - see the task report for the exact mapping.
CRITICAL: this mirrors the CLI's OWN diff algorithm, which is distinct from (and does not call) ProfileManager.Switch - see the task report for why both exist.
type SwitchResult ¶ added in v1.11.0
SwitchResult reports the outcome of ApplyProfileSwitch. As with DeployResult/UninstallResult, every Notes entry is always recorded - there is no verbosity concept in core.
- Notes holds every diagnostic doProfileSwitch only printed under --verbose: failed Uninstall/SetModEnabled during the disable loop, failed Install/SetModEnabled during the enable loop, and a failed UpsertMod during the install loop. Each entry already carries its historical "Warning: " prefix, matching doProfileSwitch's exact wording; a caller wanting byte-identical output should print each entry to stdout ONLY under --verbose, e.g. `fmt.Printf(" %s\n", n)` (disable/enable loop notes) or `fmt.Printf(" %s\n", n)` (the install loop's profile-update note, one indent level deeper).
Every Notes entry is ALSO reported via the progress callback at the exact point it is appended (SwitchDisableNote/SwitchEnableNote/SwitchInstallNote - see each DeployPhase constant's doc comment), with Detail equal to the slice entry verbatim.
On error, the returned result carries any diagnostics/counts accumulated before the failure; callers should surface them alongside the error.
type UninstallOptions ¶ added in v1.11.0
type UninstallOptions struct {
KeepCache bool // --keep-cache: skip deleting the mod's cache entry
// Hook plumbing, mirroring BatchOptions. Hooks and/or HookRunner may be
// nil to skip hook execution entirely (e.g. --no-hooks).
Hooks *ResolvedHooks
HookRunner *HookRunner
HookContext HookContext
Force bool // continue past a failing uninstall.before_* hook (warn instead of fail)
}
UninstallOptions configures UninstallMod.
type UninstallResult ¶ added in v1.11.0
type UninstallResult struct {
Warnings []string // unconditional, stderr, audience: operator/always-visible
Notes []string // --verbose-gated, stdout, audience: diagnostic detail
}
UninstallResult reports the outcome of UninstallMod. Every entry in both slices below is always recorded — UninstallMod has no verbosity concept — but the two slices carry different display contracts for callers to honor (this is the convention Tasks 3-4 should follow too):
- Warnings holds diagnostics the pre-extraction CLI printed unconditionally to stderr regardless of --verbose (hook failures: uninstall.before_* when Force is set, and uninstall.after_*, which is always non-fatal). Callers should print each entry to stderr, unconditionally, e.g. `fmt.Fprintf(os.Stderr, "Warning: %v\n", w)`.
- Notes holds operational diagnostics the pre-extraction CLI only printed under --verbose (undeploy failure, cache-delete failure, and a failure to remove the mod from the profile). Each entry already carries its historical prefix word baked into the text ("Warning: " for undeploy/cache-delete, "Note: " for the profile-removal message, matching the pre-extraction CLI's exact wording for each), so a caller that wants byte-identical pre-extraction output should print each entry to stdout ONLY under --verbose, verbatim, e.g. `fmt.Printf(" %s\n", n)`.
On error, the returned result carries any diagnostics accumulated before the failure; callers should surface them alongside the error.
type UninstalledModResult ¶ added in v0.12.0
UninstalledModResult is a successfully uninstalled mod (wraps domain.Mod for batch result)
type UpdateApplyResult ¶ added in v1.12.0
UpdateApplyResult reports the outcome of ApplyUpdate. As with DeployResult/UninstallResult/SwitchResult/InstallResult, every entry below is always recorded - there is no verbosity concept in core.
- Applied holds a single "<name> <old version> → <new version>" entry (matching what the CLI prints, e.g. "SkyUI 5.1 → 5.2") once the WHOLE sequence - download, hooks, Replace, and all three DB/profile writes - has succeeded. Empty on any failure; ApplyUpdate applies exactly one domain.Update per call (the CLI's own update loop calls it once per mod), so this is never more than a single entry.
- Warnings holds diagnostics applyUpdate printed unconditionally: uninstall.before_each/install.before_each (when forced), and uninstall.after_each/install.after_each hook failures (always non-fatal). Callers should print each entry to stderr, unconditionally, e.g. `fmt.Fprintf(os.Stderr, "Warning: %v\n", w)`.
- Notes holds the sole diagnostic applyUpdate only printed under --verbose: a failed SetModLinkMethod, with the historical "Warning: " prefix baked into the text already (matching applyUpdate's exact wording); a caller wanting byte-identical output should print it to stdout ONLY under --verbose, e.g. `fmt.Printf(" %s\n", n)`.
Every entry in both slices is ALSO reported via the progress callback at the exact point it is appended (UpdateBeforeEachForced/UpdateWarning/ UpdateNote - see each DeployPhase constant's doc comment), with Detail equal to the slice entry verbatim.
On error, the returned result carries any diagnostics accumulated before the failure; callers should surface them alongside the error.
type UpdateOptions ¶ added in v1.12.0
type UpdateOptions struct {
// Hook plumbing, mirroring UninstallOptions/DeployOptions/InstallOptions.
// Hooks and/or HookRunner may be nil to skip hook execution entirely
// (e.g. --no-hooks).
Hooks *ResolvedHooks
HookRunner *HookRunner
HookContext HookContext
// Force: continue past a failing uninstall.before_each/install.before_each
// hook (warn instead of fail), matching applyUpdate's own --force gate.
Force bool
}
UpdateOptions configures ApplyUpdate. Unlike InstallOptions/DeployOptions, there is no before_all/after_all hook plumbing at all - applyUpdate never ran that pair (see ApplyUpdate's doc comment) - so Force here gates ONLY the two before_each hooks (uninstall.before_each for the old version, install.before_each for the new one), matching applyUpdate's own near-identical Force checks exactly.
type Updater ¶
type Updater struct {
// contains filtered or unexported fields
}
Updater checks for and applies mod updates
func NewUpdater ¶
NewUpdater creates a new updater
func (*Updater) CheckUpdates ¶
func (u *Updater) CheckUpdates(ctx context.Context, game *domain.Game, installed []domain.InstalledMod) ([]domain.Update, error)
CheckUpdates checks for available updates for installed mods. game supplies the source-ID mapping: installed rows persist the lmm game ID, but sources like NexusMods address games by their own domain, so each source's batch is translated via game.SourceIDs before the call (empty mapping = keep the lmm id, matching the search-side semantics in Service.SearchMods/GetMod).
func (*Updater) GetAutoUpdateMods ¶
func (u *Updater) GetAutoUpdateMods(installed []domain.InstalledMod) []domain.InstalledMod
GetAutoUpdateMods filters installed mods to those with auto-update enabled