Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 | import { XMLParser } from 'fast-xml-parser'; import path from 'path'; import fs from 'fs/promises'; import { ConfigManager } from './config-manager.js'; import { RepositoryManager } from './repository-manager.js'; import type { Mod, ModInstallation, UpdateResult, ModFilter, InstallationReport } from '../types/mod'; /** * Result from scanning a directory for mods */ export interface ScanResult { /** Mods found in directory */ found: Array<{ name: string; remote: string; versions: string[]; isNew: boolean; // Not in config yet }>; /** Mods in config but missing from disk */ missing: ModInstallation[]; /** Directories on disk that aren't recognized mods */ unknown: string[]; } /** * Service for managing mod operations * Orchestrates between repository operations and configuration */ export class ModManager { private xmlParser: XMLParser; constructor( private config: ConfigManager, private repository: RepositoryManager, private modsRegistry: Mod[] ) { this.xmlParser = new XMLParser(); } /** * Install a mod by name */ async installMod(modName: string, installDir: string): Promise<ModInstallation> { // Find mod in registry const mod = this.findMod(modName); if (!mod) { throw new Error(`Mod '${modName}' is not a known mod and cannot be installed`); } // Check if already installed if (this.isModInstalled(mod.remote)) { throw new Error(`Mod '${modName}' is already installed`); } // Clone repository const modPath = path.join(installDir, modName); await this.repository.cloneRepository(mod.remote, modPath); // Extract version info let supportedVersions: string[] = []; try { supportedVersions = await this.extractModVersions(modPath); } catch (error) { // Version extraction is optional - don't fail installation } // Create installation record const installation: ModInstallation = { modId: mod.id, name: modName, directory: modPath, remote: mod.remote, supportedVersions, installedAt: new Date(), lastUpdated: new Date(), }; // Save to config this.config.addOrUpdateInstalledMod(installation); return installation; } /** * Update a single mod */ async updateMod(mod: ModInstallation): Promise<UpdateResult> { const startTime = Date.now(); try { // Get current commit before update const beforeCommit = await this.repository.getCurrentCommit(mod.directory); // Perform update const pullResult = await this.repository.updateRepository(mod.directory); // Get commit after update const afterCommit = await this.repository.getCurrentCommit(mod.directory); // Update last checked time mod.lastChecked = new Date(); if (pullResult.hasChanges) { mod.lastUpdated = new Date(); mod.installedVersion = afterCommit; } this.config.addOrUpdateInstalledMod(mod); return { modId: mod.modId, success: pullResult.success, hasChanges: pullResult.hasChanges, previousVersion: beforeCommit, newVersion: afterCommit, duration: Date.now() - startTime, }; } catch (error) { return { modId: mod.modId, success: false, hasChanges: false, error: error as Error, duration: Date.now() - startTime, }; } } /** * Update all installed mods */ async updateAllMods(): Promise<UpdateResult[]> { const installed = this.config.getInstalledMods() .sort((a, b) => a.name.localeCompare(b.name)); // Run all updates in parallel - Git will handle its own concurrency return Promise.all(installed.map(mod => this.updateMod(mod))); } /** * Uninstall a mod */ async uninstallMod(modName: string): Promise<void> { // Find mod in registry const mod = this.findMod(modName); if (!mod) { throw new Error(`Mod '${modName}' is not a known mod and cannot be uninstalled`); } // Check if installed const installation = this.config.findInstalledModByRemote(mod.remote); if (!installation) { throw new Error(`Mod '${modName}' is not installed`); } // Remove directory try { // Remove .git directory first await fs.rm(path.join(installation.directory, '.git'), { recursive: true, force: true }); // Then remove the mod directory await fs.rm(installation.directory, { recursive: true, force: true }); } catch (error) { throw new Error( `Failed to remove mod directory: ${(error as Error).message}\n` + `Please manually remove:\n` + ` rm -rf ${installation.directory}/.git\n` + ` rm -rf ${installation.directory}` ); } // Remove from config this.config.removeInstalledMod(modName); } /** * Scan a directory for installed mods and sync with config */ async scanDirectory(installDir: string): Promise<ScanResult> { const result: ScanResult = { found: [], missing: [], unknown: [], }; // Get current config state const configuredMods = this.config.getInstalledMods(); // Read directory let files: string[]; try { files = await fs.readdir(installDir); } catch (error) { throw new Error(`Cannot read installation directory: ${installDir}`); } // Filter out hidden files and non-directories const directories = files.filter(f => !f.startsWith('.') && f !== 'Icon\r' && !f.includes('.txt') ); // Check each directory const scanPromises = directories.map(async (dir) => { const fullPath = path.join(installDir, dir); // Check if it's a Git repository const status = await this.repository.getRepositoryStatus(fullPath); if (!status.isValidRepo || !status.remoteUrl) { result.unknown.push(dir); return; } // Check if it's a known mod const mod = this.modsRegistry.find(m => m.remote === status.remoteUrl || m.remote.replace('.git', '') === status.remoteUrl?.replace('.git', '') ); if (!mod) { result.unknown.push(dir); return; } // Extract versions let versions: string[] = []; try { versions = await this.extractModVersions(fullPath); } catch (error) { // Version extraction is optional } // Check if it's already in config const isNew = !this.isModInstalled(mod.remote); result.found.push({ name: mod.name, remote: mod.remote, versions, isNew, }); }); await Promise.all(scanPromises); // Find mods that are in config but not on disk const foundRemotes = result.found.map(f => f.remote); result.missing = configuredMods.filter(m => !foundRemotes.includes(m.remote) && !foundRemotes.includes(m.remote.replace('.git', '')) ); return result; } /** * Sync configuration with disk state after scanning */ async syncConfigWithDisk(installDir: string): Promise<void> { const scanResult = await this.scanDirectory(installDir); // Build new installed mods list const updatedMods: ModInstallation[] = []; // Add all found mods for (const found of scanResult.found) { const mod = this.modsRegistry.find(m => m.remote === found.remote)!; const existing = this.config.findInstalledModByRemote(found.remote); if (existing) { // Update existing entry existing.supportedVersions = found.versions; updatedMods.push(existing); } else { // Create new entry updatedMods.push({ modId: mod.id, name: found.name, directory: path.join(installDir, found.name), remote: found.remote, supportedVersions: found.versions, installedAt: new Date(), lastUpdated: new Date(), }); } } // Update config with new state this.config.setInstallationDir(installDir); this.config.setInstalledMods(updatedMods); } /** * Find a mod by name or label */ findMod(nameOrLabel: string): Mod | undefined { return this.modsRegistry.find(m => m.name === nameOrLabel || m.label === nameOrLabel ); } /** * Search for mods by term */ searchMods(term: string, filter?: ModFilter): Mod[] { const lowerTerm = term.toLowerCase(); return this.modsRegistry.filter(mod => { // Apply search term const matchesTerm = mod.name.toLowerCase().includes(lowerTerm) || mod.label.toLowerCase().includes(lowerTerm) || (mod.remark && mod.remark.toLowerCase().includes(lowerTerm)); if (!matchesTerm) return false; // Apply filters if (filter?.includeDeprecated === false && mod.deprecated) return false; if (filter?.installed === true && !this.isModInstalled(mod.remote)) return false; if (filter?.installed === false && this.isModInstalled(mod.remote)) return false; return true; }); } /** * List mods with optional filter */ listMods(filter?: ModFilter): Mod[] { return this.modsRegistry.filter(mod => { if (filter?.includeDeprecated === false && mod.deprecated) return false; if (filter?.installed === true && !this.isModInstalled(mod.remote)) return false; if (filter?.installed === false && this.isModInstalled(mod.remote)) return false; if (filter?.searchTerm && !this.searchMods(filter.searchTerm).includes(mod)) return false; return true; }); } /** * Get all installed mods */ getInstalledMods(): ModInstallation[] { return this.config.getInstalledMods(); } /** * Check if a mod is installed */ isModInstalled(nameOrRemote: string): boolean { // Check by name const mod = this.findMod(nameOrRemote); if (mod) { return this.config.isModInstalled(mod.remote); } // Check by remote URL directly return this.config.isModInstalled(nameOrRemote); } /** * Extract supported versions from About.xml */ async extractModVersions(modPath: string): Promise<string[]> { try { const aboutPath = path.join(modPath, 'About', 'About.xml'); const xmlContent = await fs.readFile(aboutPath, 'utf-8'); const parsed = this.xmlParser.parse(xmlContent); const versions = parsed.ModMetaData?.supportedVersions?.li; if (!versions) return []; return Array.isArray(versions) ? versions : [versions]; } catch (error) { // If About.xml doesn't exist or can't be parsed, return empty array return []; } } /** * Get recent commits for a mod (for changelog display) */ async getModChangelog(mod: ModInstallation, limit: number = 5): Promise<Array<{ hash: string; message: string }>> { return this.repository.getRecentCommits(mod.directory, limit); } /** * Generate an installation report */ async generateInstallationReport(installDir: string): Promise<InstallationReport> { const scanResult = await this.scanDirectory(installDir); const configuredMods = this.config.getInstalledMods(); return { totalMods: this.modsRegistry.length, installedMods: configuredMods.length, corruptedMods: [], // We don't detect corrupted mods currently missingMods: scanResult.missing.map(m => m.name), unknownMods: scanResult.unknown, recommendations: [ ...scanResult.missing.length > 0 ? [`${scanResult.missing.length} mod(s) are in config but missing from disk`] : [], ...scanResult.unknown.length > 0 ? [`${scanResult.unknown.length} unknown folder(s) found in mods directory`] : [], ...scanResult.found.filter(f => f.isNew).length > 0 ? [`${scanResult.found.filter(f => f.isNew).length} new mod(s) found that can be added to config`] : [], ], }; } } |