Skip to content

Commit a4ae680

Browse files
committed
cleanup
1 parent 359a734 commit a4ae680

File tree

11 files changed

+116
-341
lines changed

11 files changed

+116
-341
lines changed

src/main/kotlin/com/lambda/loader/BaseMavenVersionController.kt

Lines changed: 31 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -19,46 +19,19 @@ abstract class BaseMavenVersionController(
1919
) {
2020
protected val logger: Logger = Logger.getLogger("Lambda-Loader")
2121

22-
/**
23-
* Override this to specify which release mode to use.
24-
* By default, uses the client release mode for backwards compatibility.
25-
*/
26-
protected open fun getReleaseMode(): ReleaseMode = ConfigManager.config.clientReleaseMode
27-
28-
/**
29-
* The base Maven repository URL
30-
*/
3122
abstract val mavenUrl: String
32-
33-
/**
34-
* URL to the releases maven-metadata.xml
35-
*/
36-
abstract val releasesMetaUrl: URL
37-
38-
/**
39-
* URL to the snapshots maven-metadata.xml
40-
*/
23+
abstract val stableMetaUrl: URL
4124
abstract val snapshotMetaUrl: URL
42-
43-
/**
44-
* The artifact group and name path (e.g., "com/lambda/lambda")
45-
*/
4625
abstract val artifactPath: String
47-
48-
/**
49-
* The artifact name (e.g., "lambda")
50-
*/
5126
abstract val artifactName: String
5227

53-
/**
54-
* Override this to provide version matching logic.
55-
* Return null to accept all versions (no filtering).
56-
*/
28+
protected open fun getReleaseMode(): ReleaseMode = ConfigManager.config.clientReleaseMode
29+
5730
protected open fun getVersionToMatch(): String? = null
5831

59-
protected fun checkReleasesVersion(): String? {
32+
protected fun checkStableVersion(): String? {
6033
return try {
61-
val xml = releasesMetaUrl.readText()
34+
val xml = stableMetaUrl.readText()
6235
parseLatestVersionForMinecraft(xml)
6336
} catch (e: Exception) {
6437
e.printStackTrace()
@@ -82,7 +55,6 @@ abstract class BaseMavenVersionController(
8255
val builder = factory.newDocumentBuilder()
8356
val document = builder.parse(xml.byteInputStream())
8457

85-
// Get all versions
8658
val versionNodes = document.getElementsByTagName("version")
8759
val versions = mutableListOf<String>()
8860

@@ -94,28 +66,20 @@ abstract class BaseMavenVersionController(
9466
val versionToMatch = getVersionToMatch()
9567

9668
if (ConfigManager.config.debug) {
97-
if (versionToMatch != null) {
98-
logger.info("Target version: $versionToMatch")
99-
}
69+
if (versionToMatch != null) logger.info("Target version: $versionToMatch")
10070
logger.info("Available Maven versions: ${versions.joinToString(", ")}")
10171
}
10272

10373
val matchingVersions = if (versionToMatch != null && versionMatchingEnabled) {
104-
// Filter versions for the target version
10574
versions.filter { version ->
106-
// Extract MC version from artifact version (after +, before - or end)
10775
val mcVersionInArtifact = version.substringAfter("+").substringBefore("-")
10876

109-
// Normalize both versions for comparison (remove extra dots)
11077
val normalizedArtifactVersion = mcVersionInArtifact.replace(".", "")
11178
val normalizedTargetVersion = versionToMatch.replace(".", "")
11279

11380
normalizedArtifactVersion == normalizedTargetVersion
11481
}
115-
} else {
116-
// No filtering, use all versions
117-
versions
118-
}
82+
} else versions
11983

12084
if (matchingVersions.isEmpty()) {
12185
if (ConfigManager.config.debug) {
@@ -126,7 +90,6 @@ abstract class BaseMavenVersionController(
12690
return null
12791
}
12892

129-
// Get the latest matching version (last in the list)
13093
val latestVersion = matchingVersions.last()
13194
if (ConfigManager.config.debug) {
13295
val versionMsg = versionToMatch?.let { "for version $it" } ?: ""
@@ -192,64 +155,58 @@ abstract class BaseMavenVersionController(
192155
return "$jarUrl.md5"
193156
}
194157

195-
protected fun getReleaseJarUrl(): String? {
196-
val version = checkReleasesVersion() ?: return null
158+
protected fun getStableJarUrl(): String? {
159+
val version = checkStableVersion() ?: return null
197160
return "$mavenUrl/releases/$artifactPath/$version/$artifactName-$version.jar"
198161
}
199162

200-
protected fun getReleaseChecksumUrl(): String? {
201-
val jarUrl = getReleaseJarUrl() ?: return null
163+
protected fun getStableChecksumUrl(): String? {
164+
val jarUrl = getStableJarUrl() ?: return null
202165
return "$jarUrl.md5"
203166
}
204167

205168
protected fun getJarUrl(): String? {
206169
return when (getReleaseMode()) {
207-
ReleaseMode.STABLE -> {
208-
val releaseUrl = getReleaseJarUrl()
170+
ReleaseMode.Stable -> {
171+
val releaseUrl = getStableJarUrl()
209172
if (releaseUrl == null) {
210173
val versionMsg = getVersionToMatch()?.let { "for version $it" } ?: ""
211174
logger.warning("No stable version found $versionMsg, falling back to snapshot")
212175
getSnapshotJarUrl()
213-
} else {
214-
releaseUrl
215-
}
176+
} else releaseUrl
216177
}
217-
ReleaseMode.SNAPSHOT -> getSnapshotJarUrl()
178+
ReleaseMode.Snapshot -> getSnapshotJarUrl()
218179
}
219180
}
220181

221182
protected fun getChecksumUrl(): String? {
222183
return when (getReleaseMode()) {
223-
ReleaseMode.STABLE -> {
224-
val releaseChecksumUrl = getReleaseChecksumUrl()
184+
ReleaseMode.Stable -> {
185+
val releaseChecksumUrl = getStableChecksumUrl()
225186
if (releaseChecksumUrl == null) {
226187
val versionMsg = getVersionToMatch()?.let { "for version $it" } ?: ""
227188
logger.warning("No stable version checksum found $versionMsg, falling back to snapshot")
228189
getSnapshotChecksumUrl()
229-
} else {
230-
releaseChecksumUrl
231-
}
190+
} else releaseChecksumUrl
232191
}
233-
ReleaseMode.SNAPSHOT -> getSnapshotChecksumUrl()
192+
ReleaseMode.Snapshot -> getSnapshotChecksumUrl()
234193
}
235194
}
236195

237196
protected fun getCacheFileName(): String? {
238197
return when (getReleaseMode()) {
239-
ReleaseMode.STABLE -> {
240-
val version = checkReleasesVersion()
198+
ReleaseMode.Stable -> {
199+
val version = checkStableVersion()
241200
if (version == null) {
242201
val versionMsg = getVersionToMatch()?.let { "for version $it" } ?: ""
243202
logger.warning("No stable cache filename found $versionMsg, falling back to snapshot")
244203
val snapshotInfo = getLatestSnapshotInfo() ?: return null
245204
val baseVersion = snapshotInfo.version.replace("-SNAPSHOT", "")
246205
"$artifactName-$baseVersion-${snapshotInfo.timestamp}-${snapshotInfo.buildNumber}.jar"
247-
} else {
248-
"$artifactName-$version.jar"
249-
}
206+
} else "$artifactName-$version.jar"
250207
}
251208

252-
ReleaseMode.SNAPSHOT -> {
209+
ReleaseMode.Snapshot -> {
253210
val snapshotInfo = getLatestSnapshotInfo() ?: return null
254211
val baseVersion = snapshotInfo.version.replace("-SNAPSHOT", "")
255212
"$artifactName-$baseVersion-${snapshotInfo.timestamp}-${snapshotInfo.buildNumber}.jar"
@@ -289,55 +246,38 @@ abstract class BaseMavenVersionController(
289246

290247
protected fun ensureLatestVersionCached(): Boolean {
291248
return try {
292-
// Check if already cached with valid checksum
293249
if (isLatestVersionCached()) {
294-
if (ConfigManager.config.debug) {
295-
logger.info("Latest version is already cached with valid checksum")
296-
}
250+
if (ConfigManager.config.debug) logger.info("Latest version is already cached with valid checksum")
297251
return true
298252
}
299253

300-
if (ConfigManager.config.debug) {
301-
logger.info("Latest version not cached or checksum invalid, downloading...")
302-
}
254+
if (ConfigManager.config.debug) logger.info("Latest version not cached or checksum invalid, downloading...")
303255

304-
// Get the file name for caching
305256
val fileName = getCacheFileName() ?: return false
306257

307-
// Download the JAR
308258
val jarData = downloadJar() ?: run {
309259
logger.severe("Failed to download JAR")
310260
return false
311261
}
312262

313-
// Download the expected checksum
314263
val expectedChecksum = downloadChecksum() ?: run {
315264
logger.severe("Failed to download checksum")
316265
return false
317266
}
318267

319-
// Verify downloaded data matches checksum
320268
val actualChecksum = cache.checksumBytes(jarData)
321269
if (actualChecksum != expectedChecksum) {
322270
logger.severe("Checksum mismatch! Expected: $expectedChecksum, Got: $actualChecksum")
323271
return false
324272
}
325273

326-
// Cache the verified JAR
327274
cache.cacheVersion(fileName, jarData)
328-
if (ConfigManager.config.debug) {
329-
logger.info("Successfully cached version: $fileName")
330-
}
275+
if (ConfigManager.config.debug) logger.info("Successfully cached version: $fileName")
331276

332-
// Verify it was cached correctly
333277
val verified = cache.checkVersionChecksum(fileName, expectedChecksum)
334-
if (ConfigManager.config.debug) {
335-
if (verified) {
336-
logger.fine("Cache verification successful")
337-
} else {
338-
logger.warning("Cache verification failed")
339-
}
340-
}
278+
if (ConfigManager.config.debug)
279+
if (verified) logger.fine("Cache verification successful")
280+
else logger.warning("Cache verification failed")
341281
verified
342282
} catch (e: Exception) {
343283
logger.severe("Error ensuring latest version cached: ${e.message}")
@@ -354,10 +294,8 @@ abstract class BaseMavenVersionController(
354294
*/
355295
fun getOrDownloadLatestVersion(): File? {
356296
return try {
357-
// Ensure the latest version is cached
358297
if (!ensureLatestVersionCached()) {
359-
// Check if both stable and snapshot versions are unavailable
360-
val stableVersion = checkReleasesVersion()
298+
val stableVersion = checkStableVersion()
361299
val snapshotVersion = checkSnapshotVersion()
362300

363301
if (stableVersion == null && snapshotVersion == null) {
@@ -379,23 +317,19 @@ abstract class BaseMavenVersionController(
379317
return null
380318
}
381319

382-
// Get the cached filename
383320
val fileName = getCacheFileName()
384321
if (fileName == null) {
385322
logger.severe("Failed to get cache filename after successful caching")
386323
return null
387324
}
388325

389-
// Get the cached version file
390326
val jarFile = cache.getCachedVersion(fileName)
391327
if (jarFile == null) {
392328
logger.severe("JAR file does not exist after caching: $fileName")
393329
exitProcess(1)
394330
}
395331

396-
if (ConfigManager.config.debug) {
397-
logger.info("Latest version ready: ${jarFile.absolutePath}")
398-
}
332+
if (ConfigManager.config.debug) logger.info("Latest version ready: ${jarFile.absolutePath}")
399333
jarFile
400334
} catch (e: Exception) {
401335
logger.severe("Failed to get or download latest version: ${e.message}")

src/main/kotlin/com/lambda/loader/Cache.kt

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,37 +23,28 @@ class Cache(baseDir: File = File("lambda")) {
2323
}
2424

2525
private fun clearOldVersions(currentFileName: String) {
26-
// Extract base name without version (e.g., "mod-1.0.0.jar" -> "mod")
2726
val baseName = currentFileName.substringBeforeLast("-").substringBeforeLast(".")
2827

2928
versionCacheDir.listFiles()?.forEach { file ->
3029
if (file.isFile && file.name.endsWith(".jar") && file.name != currentFileName) {
31-
// Check if this file is an older version of the same mod
3230
val fileBaseName = file.name.substringBeforeLast("-").substringBeforeLast(".")
3331
if (fileBaseName == baseName) {
3432
val deleted = file.delete()
35-
if (ConfigManager.config.debug) {
36-
if (deleted) {
37-
logger.info("Deleted old version: ${file.name}")
38-
} else {
39-
logger.warning("Failed to delete old version: ${file.name}")
40-
}
41-
}
33+
if (ConfigManager.config.debug)
34+
if (deleted) logger.info("Deleted old version: ${file.name}")
35+
else logger.warning("Failed to delete old version: ${file.name}")
4236
}
4337
}
4438
}
4539
}
4640

4741
fun cacheVersion(name: String, data: ByteArray) {
48-
// Clear old versions of this specific mod before caching new one
4942
clearOldVersions(name)
5043

5144
val cachedFile = File(versionCacheDir, name)
5245
cachedFile.writeBytes(data)
5346

54-
if (ConfigManager.config.debug) {
55-
logger.info("Cached new version: $name")
56-
}
47+
if (ConfigManager.config.debug) logger.info("Cached new version: $name")
5748
}
5849

5950

src/main/kotlin/com/lambda/loader/LambdaLoaderInitializer.kt

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,21 @@ import com.lambda.loader.config.ConfigManager
44
import com.lambda.loader.util.FabricUtil
55
import com.lambda.loader.util.SimpleLogFormatter
66
import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint
7+
import net.minecraft.client.MinecraftClient
78
import org.spongepowered.asm.mixin.Mixins
89
import java.util.logging.ConsoleHandler
910
import java.util.logging.Logger
10-
import kotlin.system.exitProcess
1111

12-
class LambdaLoaderInitializer : PreLaunchEntrypoint {
12+
class LoaderInitializer : PreLaunchEntrypoint {
1313
val logger: Logger = Logger.getLogger("Lambda-Loader").also {
14-
// Configure logger to use simple format
1514
it.useParentHandlers = false
1615
val handler = ConsoleHandler()
1716
handler.formatter = SimpleLogFormatter()
1817
it.addHandler(handler)
1918
}
2019

2120
override fun onPreLaunch() {
22-
// Check for loader self-updates first
2321
checkForLoaderUpdate()
24-
25-
// Then load Lambda Client
2622
loadClient()
2723
}
2824

@@ -39,7 +35,6 @@ class LambdaLoaderInitializer : PreLaunchEntrypoint {
3935
logger.info("Latest version: ${updateInfo.latestVersion}")
4036
logger.info("═══════════════════════════════════════════════════════════")
4137

42-
// Apply the update
4338
val applied = updater.applyUpdate(updateInfo)
4439

4540
if (applied) {
@@ -48,32 +43,26 @@ class LambdaLoaderInitializer : PreLaunchEntrypoint {
4843
logger.info("Please restart Minecraft to use the new version.")
4944
logger.info("═══════════════════════════════════════════════════════════")
5045

51-
// Exit to force restart with new loader
52-
// User will need to restart Minecraft manually
53-
exitProcess(0)
46+
MinecraftClient.getInstance().stop()
5447
} else {
5548
logger.warning("Failed to apply loader update, continuing with current version")
49+
updater.restoreFromBackup()
5650
}
57-
} else {
58-
if (ConfigManager.config.debug) {
59-
logger.info("Lambda-Loader is up to date (${updateInfo.currentVersion ?: "unknown"})")
60-
}
61-
}
51+
} else if (ConfigManager.config.debug) logger.info("Lambda-Loader is up to date (${updateInfo.currentVersion ?: "unknown"})")
6252
} catch (e: Exception) {
6353
logger.warning("Error checking for loader updates: ${e.message}")
64-
if (ConfigManager.config.debug) {
65-
e.printStackTrace()
66-
}
54+
if (ConfigManager.config.debug) e.printStackTrace()
6755
logger.info("Continuing with current loader version")
6856
}
6957
}
7058

7159
private fun loadClient() {
7260
logger.info("Loading Lambda Client...")
73-
val latestVersion = VersionController().getOrDownloadLatestVersion()
61+
val latestVersion = LambdaVersionController().getOrDownloadLatestVersion()
7462
if (latestVersion == null) {
7563
logger.severe("Failed to download latest lambda stopping!")
76-
exitProcess(0)
64+
MinecraftClient.getInstance().stop()
65+
return
7766
}
7867

7968
FabricUtil.addToClassPath(latestVersion)

0 commit comments

Comments
 (0)