From cee463943ab2d623949946f566de18fd594f37fb Mon Sep 17 00:00:00 2001 From: Ellet Date: Wed, 10 Jul 2024 17:07:26 +0300 Subject: [PATCH 1/3] feat(common): basic support for logger, development mode --- common/build.gradle.kts | 2 ++ common/src/main/kotlin/utils/Logger.kt | 46 ++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 common/src/main/kotlin/utils/Logger.kt diff --git a/common/build.gradle.kts b/common/build.gradle.kts index 9e1baa0..169c86c 100644 --- a/common/build.gradle.kts +++ b/common/build.gradle.kts @@ -33,12 +33,14 @@ val generateBuildConfig = tasks.register("generateBuildConfig") { // To allow overriding the current project version val projectVersion: String? by project + val developmentMode: String? by project val buildConfigDirectory = project.layout.buildDirectory.dir("generated") classFullyQualifiedName.set("generated.BuildConfig") generatedOutputDirectory.set(buildConfigDirectory) fieldsToGenerate.put("PROJECT_VERSION", projectVersion ?: libs.versions.project.get()) + fieldsToGenerate.put("DEVELOPMENT_MODE", developmentMode?.toBooleanStrictOrNull() ?: false) } sourceSets.main.configure { diff --git a/common/src/main/kotlin/utils/Logger.kt b/common/src/main/kotlin/utils/Logger.kt new file mode 100644 index 0000000..503c870 --- /dev/null +++ b/common/src/main/kotlin/utils/Logger.kt @@ -0,0 +1,46 @@ +package utils + +import generated.BuildConfig + +/** + * A simple logger that doesn't require additional dependencies and is not compatible + * with known logging solutions. Most of the messages will be shown to the user + * in case they run the application in CLI mode either in command-line or using the launcher, + * which is why don't use something like `[main] INFO Main - The log message` in production mode. + * */ +object Logger { + fun error(lazyMessage: () -> String) { + logMessage(lazyMessage = lazyMessage, logLevel = "Error") + } + + fun debug(lazyMessage: () -> String) { + if (!BuildConfig.DEVELOPMENT_MODE) return + logMessage(lazyMessage = lazyMessage, logLevel = "Debug") + } + + fun info(lazyMessage: () -> String) { + logMessage(lazyMessage = lazyMessage, logLevel = "Info") + } + + fun warning(lazyMessage: () -> String) { + logMessage(lazyMessage = lazyMessage, logLevel = "Warning") + } + + fun trace(lazyMessage: () -> String) { + logMessage(lazyMessage = lazyMessage, logLevel = "Trace") + } + + private fun logMessage( + lazyMessage: () -> String, + logLevel: String, + ) { + val message = + buildString { + if (BuildConfig.DEVELOPMENT_MODE) { + append("$logLevel - ") + } + append(lazyMessage()) + } + println(message) + } +} From da8aa25bf4fb138866edea0f926ee13a49a5b88b Mon Sep 17 00:00:00 2001 From: Ellet Date: Wed, 10 Jul 2024 18:39:20 +0300 Subject: [PATCH 2/3] chore: use the 'Logger' class to log messages instead of using println directly --- .../data/RemoteCurseForgeDataSource.kt | 5 ++- common/src/main/kotlin/gui/utils/GuiUtils.kt | 13 +++--- .../main/kotlin/gui/utils/ThemeDetector.kt | 11 ++--- common/src/main/kotlin/utils/CommandLine.kt | 12 ++++-- common/src/main/kotlin/utils/Logger.kt | 18 +++++++- sync-script/src/main/kotlin/Main.kt | 41 ++++++++++--------- .../kotlin/services/updater/JarAutoUpdater.kt | 32 ++++++++------- .../syncInfo/data/RemoteSyncInfoDataSource.kt | 3 +- .../kotlin/syncService/ModsSyncService.kt | 34 +++++++-------- .../syncService/ResourcePacksSyncService.kt | 41 ++++++++++++------- .../kotlin/syncService/ServersSyncService.kt | 9 ++-- .../syncService/common/AssetSyncService.kt | 3 +- sync-script/src/main/kotlin/utils/Utils.kt | 2 +- 13 files changed, 136 insertions(+), 88 deletions(-) diff --git a/admin/src/main/kotlin/minecraftAssetProviders/curseForge/data/RemoteCurseForgeDataSource.kt b/admin/src/main/kotlin/minecraftAssetProviders/curseForge/data/RemoteCurseForgeDataSource.kt index 615400e..ed96e12 100644 --- a/admin/src/main/kotlin/minecraftAssetProviders/curseForge/data/RemoteCurseForgeDataSource.kt +++ b/admin/src/main/kotlin/minecraftAssetProviders/curseForge/data/RemoteCurseForgeDataSource.kt @@ -5,6 +5,7 @@ import minecraftAssetProviders.curseForge.models.CurseForgeModFileDownloadUrlRes import minecraftAssetProviders.curseForge.models.CurseForgeModFileResponse import services.HttpClient import services.HttpResponse +import utils.Logger class RemoteCurseForgeDataSource : CurseForgeDataSource { companion object { @@ -28,7 +29,7 @@ class RemoteCurseForgeDataSource : CurseForgeDataSource { ) ) { is HttpResponse.Success -> { - println("ℹ\uFE0F Curse Forge Mod ($modId) File ($fileId) Json Response: ${response.body}") + Logger.info { "ℹ\uFE0F Curse Forge Mod ($modId) File ($fileId) Json Response: ${response.body}" } Result.success(response.decodeJson()) } @@ -52,7 +53,7 @@ class RemoteCurseForgeDataSource : CurseForgeDataSource { ) return when (response) { is HttpResponse.Success -> { - println("ℹ\uFE0F Curse Forge Mod ($modId) File ($fileId) Download URL Json Response: ${response.body}") + Logger.info { "ℹ\uFE0F Curse Forge Mod ($modId) File ($fileId) Download URL Json Response: ${response.body}" } Result.success(response.decodeJson()) } diff --git a/common/src/main/kotlin/gui/utils/GuiUtils.kt b/common/src/main/kotlin/gui/utils/GuiUtils.kt index 3ca8579..3c1e276 100644 --- a/common/src/main/kotlin/gui/utils/GuiUtils.kt +++ b/common/src/main/kotlin/gui/utils/GuiUtils.kt @@ -11,6 +11,7 @@ import com.formdev.flatlaf.themes.FlatMacLightLaf import constants.SharedAssetConstants import gui.theme.Theme import gui.theme.ThemeMode +import utils.Logger import utils.getResourceAsURLOrThrow import utils.os.OperatingSystem import java.awt.Component @@ -152,14 +153,14 @@ object GuiUtils { e.printStackTrace() if (e is UnsupportedLookAndFeelException) { - println( - "⚠️ Couldn't switch to the selected theme \uD83C\uDFA8. It looks like this theme is not supported on your system.", - ) + Logger.error { + "⚠️ Couldn't switch to the selected theme \uD83C\uDFA8. It looks like this theme is not supported on your system." + } return } - println( - "❌ Failed to switch to the selected theme \uD83C\uDFA8: ${e.message}", - ) + Logger.error { + "❌ Failed to switch to the selected theme \uD83C\uDFA8: ${e.message}" + } } } diff --git a/common/src/main/kotlin/gui/utils/ThemeDetector.kt b/common/src/main/kotlin/gui/utils/ThemeDetector.kt index 87595e5..9403a37 100644 --- a/common/src/main/kotlin/gui/utils/ThemeDetector.kt +++ b/common/src/main/kotlin/gui/utils/ThemeDetector.kt @@ -1,5 +1,6 @@ package gui.utils +import utils.Logger import utils.SystemInfoProvider import utils.commandLine import utils.os.LinuxDesktopEnvironment @@ -48,20 +49,20 @@ object ThemeDetector { SystemInfoProvider.getUserHomeDirectoryPath(), ".config/kdeglobals", ) - println( + Logger.info { "\uD83D\uDCC4 Reading the following file to check if the KDE Plasma desktop environment " + - "is in dark mode: ${kdeGlobalsFile.pathString}", - ) + "is in dark mode: ${kdeGlobalsFile.pathString}" + } return try { val lookAndFeelPackageName = kdeGlobalsFile.bufferedReader().useLines { line -> line.firstOrNull { it.startsWith("LookAndFeelPackage=") }?.substringAfter('=') } - println("✨ The KDE Plasma look and feel package name: 🎨 $lookAndFeelPackageName") + Logger.info { "✨ The KDE Plasma look and feel package name: 🎨 $lookAndFeelPackageName" } Result.success(lookAndFeelPackageName) } catch (e: Exception) { e.printStackTrace() - println("❌ Error while reading the file ${kdeGlobalsFile.name}: ${e.message}") + Logger.error { "❌ Error while reading the file ${kdeGlobalsFile.name}: ${e.message}" } Result.failure(e) } } diff --git a/common/src/main/kotlin/utils/CommandLine.kt b/common/src/main/kotlin/utils/CommandLine.kt index 7d3a1ea..ae7e2ec 100644 --- a/common/src/main/kotlin/utils/CommandLine.kt +++ b/common/src/main/kotlin/utils/CommandLine.kt @@ -27,7 +27,7 @@ fun commandLine( } append(": ${args.joinToString(" ")}") } - println(message) + Logger.info { message } } return try { val process = @@ -39,18 +39,22 @@ fun commandLine( process.destroy() val errorMessage = "⏰ Process timed out for the command: ${args.joinToString(" ")}" if (isLoggingEnabled) { - println("❌ $errorMessage") + Logger.error { "❌ $errorMessage" } } return Result.failure(RuntimeException(errorMessage)) } val result = process.inputStream.bufferedReader().use { it.readText() } if (isLoggingEnabled) { - println("✅ Command executed successfully: '${args.joinToString(" ")}'. " + "📜 Output: ${result.trim()}") + Logger.info { + "✅ Command executed successfully: '${args.joinToString(" ")}'. " + "📜 Output: ${result.trim()}" + } } Result.success(result) } catch (e: Exception) { if (isLoggingEnabled) { - println("❌ Error executing command `${args.joinToString(" ")}`: ${e.message}") + Logger.error { + "❌ Error executing command `${args.joinToString(" ")}`: ${e.message}" + } } e.printStackTrace() Result.failure(e) diff --git a/common/src/main/kotlin/utils/Logger.kt b/common/src/main/kotlin/utils/Logger.kt index 503c870..e36d8f5 100644 --- a/common/src/main/kotlin/utils/Logger.kt +++ b/common/src/main/kotlin/utils/Logger.kt @@ -18,8 +18,15 @@ object Logger { logMessage(lazyMessage = lazyMessage, logLevel = "Debug") } - fun info(lazyMessage: () -> String) { - logMessage(lazyMessage = lazyMessage, logLevel = "Info") + fun info( + extraLine: Boolean = false, + lazyMessage: () -> String, + ) { + logMessage( + extraLine = extraLine, + lazyMessage = lazyMessage, + logLevel = "Info", + ) } fun warning(lazyMessage: () -> String) { @@ -31,11 +38,18 @@ object Logger { } private fun logMessage( + /** + * Add an extra new line before printing the message + * */ + extraLine: Boolean = false, lazyMessage: () -> String, logLevel: String, ) { val message = buildString { + if (extraLine) { + append("\n") + } if (BuildConfig.DEVELOPMENT_MODE) { append("$logLevel - ") } diff --git a/sync-script/src/main/kotlin/Main.kt b/sync-script/src/main/kotlin/Main.kt index c369260..9148a87 100644 --- a/sync-script/src/main/kotlin/Main.kt +++ b/sync-script/src/main/kotlin/Main.kt @@ -25,6 +25,7 @@ import syncService.ResourcePacksSyncService import syncService.ServersSyncService import syncService.SyncService import utils.ExecutionTimer +import utils.Logger import utils.SystemInfoProvider import utils.createFileWithParentDirectoriesOrTerminate import utils.deleteRecursivelyWithLegacyJavaIo @@ -49,8 +50,8 @@ suspend fun main(args: Array) { passedArgs = args - println("📋 Current project version: ${BuildConfig.PROJECT_VERSION}") - println("\uD83D\uDCC1 Current working directory: ${SystemInfoProvider.getCurrentWorkingDirectoryPath()}") + Logger.info { "📋 Current project version: ${BuildConfig.PROJECT_VERSION}" } + Logger.info { "\uD83D\uDCC1 Current working directory: ${SystemInfoProvider.getCurrentWorkingDirectoryPath()}" } logSystemInfo() handleTemporaryDirectory(isStart = true) @@ -79,7 +80,7 @@ suspend fun main(args: Array) { GuiState.updateIsGuiEnabled() - println("ℹ\uFE0F Script Configuration: ${ScriptConfig.instance}") + Logger.info { "ℹ\uFE0F Script Configuration: ${ScriptConfig.instance}" } // Switch to the themes specified by config if (GuiState.isGuiEnabled) { @@ -108,28 +109,28 @@ private fun logSystemInfo() { OperatingSystem.MacOS -> "\uD83C\uDF4F You are using macOS \uF8FF. Welcome to the world of Apple \uD83C\uDF4E." OperatingSystem.Windows -> "\uD83E\uDE9F You are using Windows. Be safe!" OperatingSystem.Unknown -> "❓Your operating system couldn't be identified. Let's hope everything works smoothly." - }.also { println(it) } + }.also { Logger.info { it } } if (!GraphicsEnvironment.isHeadless()) { if (GuiUtils.isSystemInDarkMode) { "🌙 Welcome to the dark side! Your system is in dark mode. Enjoy the soothing darkness! 🌃" } else { "☀️ Brighten up your day! Your system is in the light mode. Embrace the light! 🌅" - }.also { println(it) } + }.also { Logger.info { it } } } } private fun handleTemporaryDirectory(isStart: Boolean) { SyncScriptDotMinecraftFiles.SyncScriptData.Temp.path.apply { if (exists()) { - println( + Logger.info { if (isStart) { "ℹ\uFE0F The temporary folder: $pathString exist. " + "The script might not finished last time. Removing the folder." } else { "\uD83D\uDEAB Deleting the temporary folder: '$pathString' (no longer needed)." - }, - ) + } + } deleteRecursivelyWithLegacyJavaIo() } } @@ -139,10 +140,10 @@ private suspend fun loadScriptConfig(): ScriptConfig { val scriptConfigFile = SyncScriptDotMinecraftFiles.SyncScriptData.ScriptConfig.path if (!scriptConfigFile.exists()) { if (GuiState.isGuiEnabled) { - println( - "Configuration Missing! ⚠\uFE0F. Since you're in GUI mode, we'll launch a quick " + - "dialog to gather the necessary information", - ) + Logger.info { + "ℹ\uFE0F Configuration Missing. Since you're in GUI mode, we'll launch a quick " + + "dialog to gather the necessary information" + } val scriptConfig = CreateScriptConfigDialog().showDialog() runBlocking { scriptConfigDataSource.replaceConfig(scriptConfig) } @@ -248,6 +249,8 @@ private suspend fun fetchSyncInfo() { return } + Logger.debug { "\uD83D\uDC1E Sync Info: ${SyncInfo.instance}" } + LoadingIndicatorDialog.instance?.updateComponentProperties( title = "Synchronization", infoText = "Performing initial checks and configurations...", @@ -275,10 +278,10 @@ private suspend fun handleAdminTrustCheck() { // If the user doesn't say he/she trusts the admin yet, then we will ask him val doesUserTrustThisSource = TrustAdminDialog.showDialog() if (!doesUserTrustThisSource) { - println( + Logger.info { "\uD83D\uDD12 Script is closing because trust in the administration is lacking. " + - "Feel free to reach out if you have any concerns.", - ) + "Feel free to reach out if you have any concerns." + } terminateWithOrWithoutError() } runBlocking { @@ -315,9 +318,9 @@ private fun finalize(applicationExecutionTimer: ExecutionTimer) { // after finish syncing the contents successfully, we don't need it anymore. handleTemporaryDirectory(isStart = false) - println( - "\n\uD83C\uDF89 The script has successfully completed in " + - "(${applicationExecutionTimer.getRunningUntilNowDuration().inWholeMilliseconds}ms)! \uD83D\uDE80", - ) + Logger.info(extraLine = true) { + "\uD83C\uDF89 The script has successfully completed in " + + "(${applicationExecutionTimer.getRunningUntilNowDuration().inWholeMilliseconds}ms)! \uD83D\uDE80" + } exitProcess(0) } diff --git a/sync-script/src/main/kotlin/services/updater/JarAutoUpdater.kt b/sync-script/src/main/kotlin/services/updater/JarAutoUpdater.kt index 777519a..4b75b48 100644 --- a/sync-script/src/main/kotlin/services/updater/JarAutoUpdater.kt +++ b/sync-script/src/main/kotlin/services/updater/JarAutoUpdater.kt @@ -9,6 +9,7 @@ import kotlinx.coroutines.withContext import services.HttpClient import services.HttpResponse import utils.FileDownloader +import utils.Logger import utils.SystemInfoProvider import utils.buildHtml import utils.commandLineNonBlocking @@ -40,7 +41,7 @@ object JarAutoUpdater { ) } val latestJarFileDownloadUrl = ProjectInfoConstants.LATEST_SYNC_SCRIPT_JAR_FILE_URL - println("\uD83D\uDD3D Downloading the new JAR file from: $latestJarFileDownloadUrl") + Logger.info { "\uD83D\uDD3D Downloading the new JAR file from: $latestJarFileDownloadUrl" } LoadingIndicatorDialog.instance?.updateComponentProperties( title = "Updating...", @@ -78,7 +79,9 @@ object JarAutoUpdater { private suspend fun getLatestProjectVersion(): Result { val url = ProjectInfoConstants.LIBS_VERSIONS_TOML_FILE_URL - println("\uD83D\uDCE5 Sending GET request to: $url") + + Logger.info { "\uD83D\uDCE5 Sending GET request to: $url" } + return when (val response = HttpClient.get(url = url)) { is HttpResponse.Success -> { val projectVersionRegex = Regex("""project\s*=\s*"(.+?)"""") @@ -106,14 +109,14 @@ object JarAutoUpdater { ) val latestProjectVersionString = getLatestProjectVersion().getOrElse { - println("❌ We couldn't get the latest project version: ${it.message}") + Logger.error { "❌ We couldn't get the latest project version: ${it.message}" } return false } if (latestProjectVersionString == null) { - println( + Logger.error { "⚠\uFE0F It seems that the project version is missing, it could have been moved somewhere else. " + - "Consider updating manually.", - ) + "Consider updating manually." + } return false } @@ -121,23 +124,23 @@ object JarAutoUpdater { val latestProjectSemanticVersion: SemanticVersion = SemanticVersion.parse(latestProjectVersionString).getOrElse { - println("❌ Failed to parse the latest project version to SemanticVersion: ${it.message}") + Logger.error { "❌ Failed to parse the latest project version to SemanticVersion: ${it.message}" } return false } val currentSemanticVersion: SemanticVersion = SemanticVersion.parse(currentVersionString).getOrElse { - println("❌ Failed to parse the current application version to SemanticVersion: ${it.message}") + Logger.error { "❌ Failed to parse the current application version to SemanticVersion: ${it.message}" } return false } return when { currentSemanticVersion == latestProjectSemanticVersion -> { - println("✨ You're using the latest version of the project.") + Logger.info { "✨ You're using the latest version of the project." } false } currentSemanticVersion > latestProjectSemanticVersion -> { - println("✨ You're using a version that's newer than the latest.") + Logger.info { "✨ You're using a version that's newer than the latest." } false } @@ -149,7 +152,7 @@ object JarAutoUpdater { val currentRunningJarFilePath = getRunningJarFilePath() .getOrElse { - println("⚠\uFE0F Auto update feature is only supported when running using JAR.") + Logger.warning { "⚠\uFE0F Auto update feature is only supported when running using JAR." } return } @@ -161,10 +164,10 @@ object JarAutoUpdater { } val newJarFile = downloadLatestJarFile().getOrElse { - println("❌ An error occurred while downloading the latest version: ${it.message}") + Logger.error { "❌ An error occurred while downloading the latest version: ${it.message}" } return } - println("ℹ\uFE0F The new update has been downloaded, will close the application.") + Logger.info { "ℹ\uFE0F The new update has been downloaded, will close the application." } updateApplication( currentRunningJarFilePath = currentRunningJarFilePath, newJarFilePath = newJarFile, @@ -203,6 +206,7 @@ object JarAutoUpdater { "--msgbox", message, ) + else -> arrayOf( "zenity", @@ -273,7 +277,7 @@ object JarAutoUpdater { } OperatingSystem.Unknown -> { - println("⚠\uFE0F Auto update feature is not supported on ${SystemInfoProvider.getOperatingSystemName()}.") + Logger.error { "⚠\uFE0F Auto update feature is not supported on ${SystemInfoProvider.getOperatingSystemName()}." } } } // Will require the user to launch once again after the update. diff --git a/sync-script/src/main/kotlin/syncInfo/data/RemoteSyncInfoDataSource.kt b/sync-script/src/main/kotlin/syncInfo/data/RemoteSyncInfoDataSource.kt index 964c55a..63ff427 100644 --- a/sync-script/src/main/kotlin/syncInfo/data/RemoteSyncInfoDataSource.kt +++ b/sync-script/src/main/kotlin/syncInfo/data/RemoteSyncInfoDataSource.kt @@ -3,11 +3,12 @@ package syncInfo.data import services.HttpClient import services.HttpResponse import syncInfo.models.SyncInfo +import utils.Logger // TODO: I might add an option for caching the data/response or disable it. Similar to Next Js class RemoteSyncInfoDataSource : SyncInfoDataSource { override suspend fun fetchSyncInfo(url: String): Result { - println("\uD83D\uDCE5 Sending GET request to: $url") + Logger.info { "\uD83D\uDCE5 Sending GET request to: $url" } return when (val response = HttpClient.get(url = url)) { is HttpResponse.Success -> Result.success(response.decodeJson()) is HttpResponse.HttpFailure -> diff --git a/sync-script/src/main/kotlin/syncService/ModsSyncService.kt b/sync-script/src/main/kotlin/syncService/ModsSyncService.kt index 2e8d048..f5e2741 100644 --- a/sync-script/src/main/kotlin/syncService/ModsSyncService.kt +++ b/sync-script/src/main/kotlin/syncService/ModsSyncService.kt @@ -14,6 +14,7 @@ import syncInfo.models.shouldVerifyFileIntegrity import syncService.common.AssetSyncService import utils.ExecutionTimer import utils.FileDownloader +import utils.Logger import utils.calculateProgressByIndex import utils.convertBytesToReadableMegabytesAsString import utils.deleteExistingOrTerminate @@ -41,17 +42,17 @@ class ModsSyncService : withContext(Dispatchers.IO) { val executionTimer = ExecutionTimer() executionTimer.setStartTime() - println("\n\uD83D\uDD04 Syncing mods...") + Logger.info(extraLine = true) { "\uD83D\uDD04 Syncing mods..." } // Mods from the remote val mods = modSyncInfo.mods - println("📥 Total received mods from server: ${mods.size}") + Logger.info { "📥 Total received mods from server: ${mods.size}" } validateAssetDirectory() deleteUnSyncedLocalModFiles(mods = mods) val currentEnvironmentModsOrAll = getCurrentEnvironmentModsOrAll(mods = mods) - println("📥 Current environment mods: ${currentEnvironmentModsOrAll.size}") + Logger.info { "📥 Current environment mods: ${currentEnvironmentModsOrAll.size}" } LoadingIndicatorDialog.instance?.updateComponentProperties( title = "Syncing Mods...", @@ -66,14 +67,16 @@ class ModsSyncService : getModsForDownloadAndValidateIfRequired( mods = currentEnvironmentModsOrAll, ) - println("\n🔍 Mods to download: ${modsToDownload.size}") + Logger.info(extraLine = true) { "🔍 Mods to download: ${modsToDownload.size}" } downloadMods( modsToDownload = modsToDownload, totalMods = currentEnvironmentModsOrAll, ) - println("\uD83D\uDD52 Finished syncing the mods in ${executionTimer.getRunningUntilNowDuration().inWholeMilliseconds}ms.") + Logger.info { + "\uD83D\uDD52 Finished syncing the mods in ${executionTimer.getRunningUntilNowDuration().inWholeMilliseconds}ms." + } } private suspend fun deleteUnSyncedLocalModFiles(mods: List) { @@ -87,7 +90,7 @@ class ModsSyncService : val remoteModFileNames: List = mods.map { getModFilePath(it).name } for (localModFilePath in localModFilePathsToProcess) { if (localModFilePath.name !in remoteModFileNames) { - println("\uD83D\uDEAB Deleting the mod '${localModFilePath.name}' as it's no longer on the server.") + Logger.info { "\uD83D\uDEAB Deleting the mod '${localModFilePath.name}' as it's no longer on the server." } localModFilePath.deleteExistingOrTerminate( fileEntityType = "mod", reasonOfDelete = "it's no longer on the server", @@ -109,7 +112,7 @@ class ModsSyncService : val modFilePath = getModFilePath(mod) if (modFilePath.exists()) { - println("❌ Deleting the mod '${modFilePath.name}' as it's not needed on the current environment.") + Logger.info { "\uD83D\uDEAB Deleting the mod '${modFilePath.name}' as it's not needed on the current environment." } modFilePath.deleteExistingOrTerminate( fileEntityType = "mod", reasonOfDelete = "it's not required on the current environment", @@ -127,7 +130,7 @@ class ModsSyncService : val modFilePath = getModFilePath(mod) if (modFilePath.exists()) { if (!mod.shouldVerifyFileIntegrity()) { - println("ℹ️ The mod: '$modFileName' is set to not be verified. Skipping to the next mod.") + Logger.info { "ℹ️ The mod: '$modFileName' is set to not be verified. Skipping to the next mod." } return@filter false } @@ -142,17 +145,16 @@ class ModsSyncService : ) val hasValidModFileIntegrity = mod.hasValidFileIntegrityOrError(modFilePath) if (hasValidModFileIntegrity == null) { - println("❓ The mod: '$modFileName' has an unknown integrity. Skipping to the next mod.") + Logger.info { "❓ The mod: '$modFileName' has an unknown integrity. Skipping to the next mod." } return@filter false } if (hasValidModFileIntegrity) { - println("✅ The mod: '$modFileName' has valid file integrity. Skipping to the next mod.") + Logger.info { "✅ The mod: '$modFileName' has valid file integrity. Skipping to the next mod." } return@filter false } - println( - "❌ The mod: '$modFileName' has invalid integrity. Deleting the mod " + - "and downloading it again.", - ) + Logger.info { + "\uD83D\uDEAB The mod: '$modFileName' has invalid integrity. Deleting the mod and downloading it again." + } modFilePath.deleteExistingOrTerminate( fileEntityType = "mod", reasonOfDelete = "it has invalid file integrity", @@ -172,10 +174,10 @@ class ModsSyncService : val modFileName = getFileNameFromUrlOrError(mod.downloadUrl) val modFilePath = getModFilePath(mod) if (modFilePath.exists()) { - println("⚠\uFE0F The mod: '$modFileName' already exists.") + Logger.info { "⚠\uFE0F The mod: '$modFileName' already exists." } } - println("\uD83D\uDD3D Downloading mod '$modFileName' from ${mod.downloadUrl}") + Logger.info { "\uD83D\uDD3D Downloading mod '$modFileName' from ${mod.downloadUrl}" } FileDownloader( downloadUrl = mod.downloadUrl, diff --git a/sync-script/src/main/kotlin/syncService/ResourcePacksSyncService.kt b/sync-script/src/main/kotlin/syncService/ResourcePacksSyncService.kt index 57297fe..0f8a626 100644 --- a/sync-script/src/main/kotlin/syncService/ResourcePacksSyncService.kt +++ b/sync-script/src/main/kotlin/syncService/ResourcePacksSyncService.kt @@ -12,6 +12,7 @@ import syncInfo.models.shouldVerifyFileIntegrity import syncService.common.AssetSyncService import utils.ExecutionTimer import utils.FileDownloader +import utils.Logger import utils.calculateProgressByIndex import utils.convertBytesToReadableMegabytesAsString import utils.deleteExistingOrTerminate @@ -37,11 +38,11 @@ class ResourcePacksSyncService : val executionTimer = ExecutionTimer() executionTimer.setStartTime() - println("\n\uD83D\uDD04 Syncing resource-packs...") + Logger.info(extraLine = true) { "\uD83D\uDD04 Syncing resource-packs..." } // Resource packs from the remote val resourcePacks = resourcePackSyncInfo.resourcePacks - println("📥 Total received resource-packs from server: ${resourcePacks.size}") + Logger.info { "📥 Total received resource-packs from server: ${resourcePacks.size}" } validateAssetDirectory() deleteUnSyncedLocalResourcePackFiles(resourcePacks = resourcePacks) @@ -57,7 +58,7 @@ class ResourcePacksSyncService : getResourcePacksForDownloadAndValidateIfRequired( resourcePacks = resourcePacks, ) - println("\n🔍 Resource Packs to download: ${resourcePacksToDownload.size}") + Logger.info(extraLine = true) { "🔍 Resource Packs to download: ${resourcePacksToDownload.size}" } downloadResourcePacks( resourcePacksToDownload = resourcePacksToDownload, @@ -68,7 +69,9 @@ class ResourcePacksSyncService : applyResourcePacks() } - println("\uD83D\uDD52 Finished syncing the resource-packs in ${executionTimer.getRunningUntilNowDuration().inWholeMilliseconds}ms.") + Logger.info { + "\uD83D\uDD52 Finished syncing the resource-packs in ${executionTimer.getRunningUntilNowDuration().inWholeMilliseconds}ms." + } } private suspend fun deleteUnSyncedLocalResourcePackFiles(resourcePacks: List) { @@ -82,7 +85,9 @@ class ResourcePacksSyncService : val remoteResourcePackFileNames: List = resourcePacks.map { getResourcePackFilePath(it).name } for (localResourcePackFilePath in localResourcePackFilePathsToProcess) { if (localResourcePackFilePath.name !in remoteResourcePackFileNames) { - println("\uD83D\uDEAB Deleting the resource-pack '${localResourcePackFilePath.name}' as it's no longer on the server.") + Logger.info { + "\uD83D\uDEAB Deleting the resource-pack '${localResourcePackFilePath.name}' as it's no longer on the server." + } localResourcePackFilePath.deleteExistingOrTerminate( fileEntityType = "resource-pack", reasonOfDelete = "it's no longer on the server", @@ -97,7 +102,9 @@ class ResourcePacksSyncService : val resourcePackFilePath = getResourcePackFilePath(resourcePack) if (resourcePackFilePath.exists()) { if (!resourcePack.shouldVerifyFileIntegrity()) { - println("ℹ️ The resource-pack: '$resourcePackFileName' is set to not be verified. Skipping to the next resource-pack.") + Logger.info { + "ℹ️ The resource-pack: '$resourcePackFileName' is set to not be verified. Skipping to the next resource-pack." + } return@filter false } @@ -112,17 +119,21 @@ class ResourcePacksSyncService : ) val hasValidResourcePackFileIntegrity = resourcePack.hasValidFileIntegrityOrError(resourcePackFilePath) if (hasValidResourcePackFileIntegrity == null) { - println("❓ The resource-pack: '$resourcePackFileName' has an unknown integrity. Skipping to the next resource-pack.") + Logger.info { + "❓ The resource-pack: '$resourcePackFileName' has an unknown integrity. Skipping to the next resource-pack." + } return@filter false } if (hasValidResourcePackFileIntegrity) { - println("✅ The resource-pack: '$resourcePackFileName' has valid file integrity. Skipping to the next resource-pack.") + Logger.info { + "✅ The resource-pack: '$resourcePackFileName' has valid file integrity. Skipping to the next resource-pack." + } return@filter false } - println( - "❌ The resource-pack: '$resourcePackFileName' has invalid integrity. Deleting the resource-pack " + - "and downloading it again.", - ) + Logger.info { + "\uD83D\uDEAB The resource-pack: '$resourcePackFileName' has invalid integrity. Deleting the resource-pack " + + "and downloading it again." + } resourcePackFilePath.deleteExistingOrTerminate( fileEntityType = "resource-pack", reasonOfDelete = "it has invalid file integrity", @@ -141,10 +152,12 @@ class ResourcePacksSyncService : val resourcePackFileName = getFileNameFromUrlOrError(resourcePack.downloadUrl) val resourcePackFilePath = getResourcePackFilePath(resourcePack) if (resourcePackFilePath.exists()) { - println("⚠\uFE0F The resource-pack: '$resourcePackFileName' already exists.") + Logger.warning { + "⚠\uFE0F The resource-pack: '$resourcePackFileName' already exists." + } } - println("\uD83D\uDD3D Downloading resource-pack '$resourcePackFileName' from ${resourcePack.downloadUrl}") + Logger.info { "\uD83D\uDD3D Downloading resource-pack '$resourcePackFileName' from ${resourcePack.downloadUrl}" } FileDownloader( downloadUrl = resourcePack.downloadUrl, diff --git a/sync-script/src/main/kotlin/syncService/ServersSyncService.kt b/sync-script/src/main/kotlin/syncService/ServersSyncService.kt index 75c2575..bb9dc93 100644 --- a/sync-script/src/main/kotlin/syncService/ServersSyncService.kt +++ b/sync-script/src/main/kotlin/syncService/ServersSyncService.kt @@ -17,6 +17,7 @@ import net.benwoodworth.knbt.put import syncInfo.models.SyncInfo import syncInfo.models.instance import utils.ExecutionTimer +import utils.Logger import utils.buildHtml import utils.isFileEmpty import utils.showErrorMessageAndTerminate @@ -47,7 +48,7 @@ class ServersSyncService : SyncService { val executionTimer = ExecutionTimer() executionTimer.setStartTime() - println("\n\uD83D\uDD04 Syncing server list...") + Logger.info(extraLine = true) { "\uD83D\uDD04 Syncing server list..." } val currentRootCompound = loadServersDatFile().getOrElse { @@ -105,7 +106,9 @@ class ServersSyncService : SyncService { return } - println("\uD83D\uDD52 Finished syncing the server list in ${executionTimer.getRunningUntilNowDuration().inWholeMilliseconds}ms.") + Logger.info { + "\uD83D\uDD52 Finished syncing the server list in ${executionTimer.getRunningUntilNowDuration().inWholeMilliseconds}ms." + } } private fun loadServersDatFile(): Result { @@ -121,7 +124,7 @@ class ServersSyncService : SyncService { exitProcess(1) } if (serversDatFilePath.isFileEmpty()) { - println("ℹ️ The file '${serversDatFilePath.name}' exists and is currently empty.") + Logger.info { "ℹ️ The file '${serversDatFilePath.name}' exists and is currently empty." } return Result.success(createEmptyServerCompound()) } return Result.success( diff --git a/sync-script/src/main/kotlin/syncService/common/AssetSyncService.kt b/sync-script/src/main/kotlin/syncService/common/AssetSyncService.kt index e893c8b..5f2e77d 100644 --- a/sync-script/src/main/kotlin/syncService/common/AssetSyncService.kt +++ b/sync-script/src/main/kotlin/syncService/common/AssetSyncService.kt @@ -1,6 +1,7 @@ package syncService.common import syncService.SyncService +import utils.Logger import utils.buildHtml import utils.getFileNameFromUrlOrError import utils.listFilteredPaths @@ -25,7 +26,7 @@ abstract class AssetSyncService( ) : SyncService { protected fun validateAssetDirectory() { if (!assetDirectory.exists()) { - println("\uD83D\uDCC1 The '${assetDirectory.name}' folder doesn't exist, creating it..") + Logger.info { "\uD83D\uDCC1 The '${assetDirectory.name}' folder doesn't exist, creating it..\n" } assetDirectory.createDirectories() } diff --git a/sync-script/src/main/kotlin/utils/Utils.kt b/sync-script/src/main/kotlin/utils/Utils.kt index 873190b..a3fe1b2 100644 --- a/sync-script/src/main/kotlin/utils/Utils.kt +++ b/sync-script/src/main/kotlin/utils/Utils.kt @@ -35,7 +35,7 @@ fun showErrorMessageAndTerminate( parentComponent = guiParentComponent, ) } else { - println("❌ $title: $message") + Logger.error { "❌ $title: $message" } } terminateWithOrWithoutError() } From 09ab5f851192d2e18935ba929d2b35fc78e71d1c Mon Sep 17 00:00:00 2001 From: Ellet Date: Wed, 10 Jul 2024 18:52:56 +0300 Subject: [PATCH 3/3] chore: log 'The mod already exists.' message as warning in ModsSyncService to be consistent with ResourcePacksSyncService --- sync-script/src/main/kotlin/syncService/ModsSyncService.kt | 2 +- .../src/main/kotlin/syncService/ResourcePacksSyncService.kt | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/sync-script/src/main/kotlin/syncService/ModsSyncService.kt b/sync-script/src/main/kotlin/syncService/ModsSyncService.kt index f5e2741..b30255a 100644 --- a/sync-script/src/main/kotlin/syncService/ModsSyncService.kt +++ b/sync-script/src/main/kotlin/syncService/ModsSyncService.kt @@ -174,7 +174,7 @@ class ModsSyncService : val modFileName = getFileNameFromUrlOrError(mod.downloadUrl) val modFilePath = getModFilePath(mod) if (modFilePath.exists()) { - Logger.info { "⚠\uFE0F The mod: '$modFileName' already exists." } + Logger.warning { "⚠\uFE0F The mod: '$modFileName' already exists." } } Logger.info { "\uD83D\uDD3D Downloading mod '$modFileName' from ${mod.downloadUrl}" } diff --git a/sync-script/src/main/kotlin/syncService/ResourcePacksSyncService.kt b/sync-script/src/main/kotlin/syncService/ResourcePacksSyncService.kt index 0f8a626..9b77d3f 100644 --- a/sync-script/src/main/kotlin/syncService/ResourcePacksSyncService.kt +++ b/sync-script/src/main/kotlin/syncService/ResourcePacksSyncService.kt @@ -152,9 +152,7 @@ class ResourcePacksSyncService : val resourcePackFileName = getFileNameFromUrlOrError(resourcePack.downloadUrl) val resourcePackFilePath = getResourcePackFilePath(resourcePack) if (resourcePackFilePath.exists()) { - Logger.warning { - "⚠\uFE0F The resource-pack: '$resourcePackFileName' already exists." - } + Logger.warning { "⚠\uFE0F The resource-pack: '$resourcePackFileName' already exists." } } Logger.info { "\uD83D\uDD3D Downloading resource-pack '$resourcePackFileName' from ${resourcePack.downloadUrl}" }