diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..259a4a7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*.{kt,kts}] +indent_size = 4 +max_line_length = 160 +ktlint_function_naming_ignore_when_annotated_with = Composable +ktlint_standard_backing-property-naming = disabled +ktlint_standard_property-naming = disabled diff --git a/build.gradle.kts b/build.gradle.kts index d45a161..382d302 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -2,11 +2,14 @@ import org.jetbrains.changelog.Changelog import org.jetbrains.changelog.markdownToHTML fun properties(key: String) = providers.gradleProperty(key) + fun environment(key: String) = providers.environmentVariable(key) plugins { kotlin("jvm") version libs.versions.kotlin.get() - id("org.jetbrains.compose") version "1.10.0" // must align with jewel https://github.com/JetBrains/intellij-community/blob/master/platform/jewel/gradle/libs.versions.toml + // must align with jewel: + // https://github.com/JetBrains/intellij-community/blob/master/platform/jewel/gradle/libs.versions.toml + id("org.jetbrains.compose") version libs.versions.compose.get() alias(libs.plugins.gradleIntelliJPlugin) // IntelliJ Platform Gradle Plugin alias(libs.plugins.changelog) // Gradle Changelog Plugin alias(libs.plugins.compose) // Gradle Compose Compiler Plugin @@ -41,7 +44,7 @@ repositories { } apply( - from = "gradle/spotless.gradle" + from = "gradle/spotless.gradle", ) sourceSets { @@ -63,7 +66,7 @@ dependencies { "uiTestImplementation"(libs.junit) "uiTestImplementation"("com.squareup.okhttp3:okhttp:4.12.0") // The Compose compiler plugin applies to all source sets; uiTest needs the runtime on its classpath - "uiTestImplementation"("org.jetbrains.compose.runtime:runtime-desktop:1.7.3") + "uiTestImplementation"("org.jetbrains.compose.runtime:runtime-desktop:${libs.versions.compose.get()}") // IntelliJ Platform Gradle Plugin Dependencies Extension - read more: https://plugins.jetbrains.com/docs/intellij/tools-intellij-platform-gradle-plugin-dependencies-extension.html intellijPlatform { @@ -94,7 +97,11 @@ dependencies { } kotlin { - jvmToolchain(libs.versions.jdk.get().toInt()) + jvmToolchain( + libs.versions.jdk + .get() + .toInt(), + ) } // Configure Gradle Changelog Plugin - read more: https://github.com/JetBrains/gradle-changelog-plugin @@ -114,30 +121,32 @@ tasks { // untilBuild = properties("pluginUntilBuild").get() // Extract the section from README.md and provide for the plugin's manifest - pluginDescription = providers.fileContents(layout.projectDirectory.file("README.md")).asText.map { - val start = "" - val end = "" - - with(it.lines()) { - if (!containsAll(listOf(start, end))) { - throw GradleException("Plugin description section not found in README.md:\n$start ... $end") + pluginDescription = + providers.fileContents(layout.projectDirectory.file("README.md")).asText.map { + val start = "" + val end = "" + + with(it.lines()) { + if (!containsAll(listOf(start, end))) { + throw GradleException("Plugin description section not found in README.md:\n$start ... $end") + } + subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML) } - subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML) } - } val changelog = project.changelog // local variable for configuration cache compatibility // Get the latest available change notes from the changelog file - changeNotes = properties("pluginVersion").map { pluginVersion -> - with(changelog) { - renderItem( - (getOrNull(pluginVersion) ?: getUnreleased()) - .withHeader(false) - .withEmptySections(false), - Changelog.OutputType.HTML - ) + changeNotes = + properties("pluginVersion").map { pluginVersion -> + with(changelog) { + renderItem( + (getOrNull(pluginVersion) ?: getUnreleased()) + .withHeader(false) + .withEmptySections(false), + Changelog.OutputType.HTML, + ) + } } - } } signPlugin { @@ -169,29 +178,34 @@ intellijPlatformTesting { runIde { register("runIdeForUiTests") { task { - jvmArgumentProviders += CommandLineArgumentProvider { - listOf( - "-Drobot-server.port=8082", - "-Dide.mac.message.dialogs.as.sheets=false", - "-Djb.privacy.policy.text=", - "-Djb.consents.confirmation.enabled=false", - // Skip the "Trust Project?" dialog that blocks the IDE frame from appearing - "-Didea.trust.all.projects=true", - "-Didea.initially.ask.config=never", - // Suppress Tip of the Day, What's New, and other first-run dialogs - "-Dide.show.tips.on.startup.default.value=false", - "-Didea.is.internal=false", - "-Dide.no.platform.update=true", - // Skip import settings dialog - "-Didea.config.imported.in.current.session=true", - // Force the Swing menu bar so remote-robot can find menu items. - // Without this, macOS uses the native system menu bar which is - // invisible to the Swing component hierarchy that remote-robot inspects. - "-Dapple.laf.useScreenMenuBar=false" - ) - } + jvmArgumentProviders += + CommandLineArgumentProvider { + listOf( + "-Drobot-server.port=8082", + "-Dide.mac.message.dialogs.as.sheets=false", + "-Djb.privacy.policy.text=", + "-Djb.consents.confirmation.enabled=false", + // Skip the "Trust Project?" dialog that blocks the IDE frame from appearing + "-Didea.trust.all.projects=true", + "-Didea.initially.ask.config=never", + // Suppress Tip of the Day, What's New, and other first-run dialogs + "-Dide.show.tips.on.startup.default.value=false", + "-Didea.is.internal=false", + "-Dide.no.platform.update=true", + // Skip import settings dialog + "-Didea.config.imported.in.current.session=true", + // Force the Swing menu bar so remote-robot can find menu items. + // Without this, macOS uses the native system menu bar which is + // invisible to the Swing component hierarchy that remote-robot inspects. + "-Dapple.laf.useScreenMenuBar=false", + ) + } // Open the test project so settings.gradle.kts is available for module creation - args(layout.projectDirectory.dir("src/uiTest/testProject").asFile.absolutePath) + args( + layout.projectDirectory + .dir("src/uiTest/testProject") + .asFile.absolutePath, + ) } plugins { @@ -207,30 +221,32 @@ intellijPlatform { version = properties("pluginVersion").get() // Extract the section from README.md and provide for the plugin's manifest - description = providers.fileContents(layout.projectDirectory.file("README.md")).asText.map { - val start = "" - val end = "" - - with(it.lines()) { - if (!containsAll(listOf(start, end))) { - throw GradleException("Plugin description section not found in README.md:\n$start ... $end") + description = + providers.fileContents(layout.projectDirectory.file("README.md")).asText.map { + val start = "" + val end = "" + + with(it.lines()) { + if (!containsAll(listOf(start, end))) { + throw GradleException("Plugin description section not found in README.md:\n$start ... $end") + } + subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML) } - subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML) } - } val changelog = project.changelog // local variable for configuration cache compatibility // Get the latest available change notes from the changelog file - changeNotes = properties("pluginVersion").map { pluginVersion -> - with(changelog) { - renderItem( - (getOrNull(pluginVersion) ?: getUnreleased()) - .withHeader(false) - .withEmptySections(false), - Changelog.OutputType.HTML - ) + changeNotes = + properties("pluginVersion").map { pluginVersion -> + with(changelog) { + renderItem( + (getOrNull(pluginVersion) ?: getUnreleased()) + .withHeader(false) + .withEmptySections(false), + Changelog.OutputType.HTML, + ) + } } - } ideaVersion { sinceBuild = properties("pluginSinceBuild").get() @@ -249,8 +265,9 @@ intellijPlatform { // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release labels, like 2.1.7-alpha.3 // Specify pre-release label to publish the plugin in a custom Release Channel automatically. Read more: // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel - channels = properties("pluginVersion") - .map { listOf(it.substringAfter('-', "").substringBefore('.').ifEmpty { "default" }) } + channels = + properties("pluginVersion") + .map { listOf(it.substringAfter('-', "").substringBefore('.').ifEmpty { "default" }) } } pluginVerification { diff --git a/gradle.properties b/gradle.properties index 8bfec7e..7fa1908 100644 --- a/gradle.properties +++ b/gradle.properties @@ -16,7 +16,7 @@ pluginSinceBuild = 253 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension platformType = AI # AS version and patch at the end -platformVersion = 2025.3.1.1 +platformVersion = 2025.3.4.7 # Example: platformBundledPlugins = com.intellij.java platformBundledPlugins = com.intellij.java @@ -27,7 +27,7 @@ platformPlugins = # Gradle Releases -> https://github.com/gradle/gradle/releases # update gradle-wrapper.properties and run ./gradlew wrapper -gradleVersion = 8.13 +gradleVersion = 9.5.0 # Opt-out flag for bundling Kotlin standard library -> https://jb.gg/intellij-platform-kotlin-stdlib kotlin.stdlib.default.dependency = false diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 2b011c0..acf6064 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,12 +1,13 @@ [versions] -freemarker = "2.3.30" -serialization = "1.5.1" +freemarker = "2.3.34" +serialization = "1.11.0" jdk = "17" -kotlin = "2.2.20" -changelog = "2.0.0" -gradleIntelliJPlugin = "2.10.5" -spotless = "6.8.0" -segment = "1.13.2" +kotlin = "2.4.10" +compose = "1.10.3" +changelog = "2.5.0" +gradleIntelliJPlugin = "2.18.1" +spotless = "8.9.0" +segment = "1.26.0" junit = "4.13.2" remoteRobot = "0.11.23" diff --git a/gradle/spotless.gradle b/gradle/spotless.gradle index b2bee9e..2fa4a5f 100644 --- a/gradle/spotless.gradle +++ b/gradle/spotless.gradle @@ -2,31 +2,32 @@ apply plugin: "com.diffplug.spotless" spotless { java { - target '**/*.java' + target 'src/**/*.java' googleJavaFormat().aosp() removeUnusedImports() trimTrailingWhitespace() - indentWithSpaces() + leadingTabsToSpaces() endWithNewline() } kotlinGradle { - ktlint("0.46.0") + target '*.gradle.kts', 'settings.gradle.kts' + ktlint() trimTrailingWhitespace() endWithNewline() } kotlin { - target '**/*.kt' - ktlint("0.46.0") + target 'src/**/*.kt' + ktlint() trimTrailingWhitespace() - indentWithSpaces() + leadingTabsToSpaces() endWithNewline() } format 'misc', { - target '**/*.gradle', '**/*.md', '**/.gitignore' - indentWithSpaces() + target '*.gradle', '*.md', '.gitignore', 'gradle/**/*.gradle' + leadingTabsToSpaces() trimTrailingWhitespace() endWithNewline() } diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 37f853b..1a70468 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/src/main/kotlin/com/joetr/modulemaker/MessageDialogWrapper.kt b/src/main/kotlin/com/joetr/modulemaker/MessageDialogWrapper.kt index 4454590..ae90c42 100644 --- a/src/main/kotlin/com/joetr/modulemaker/MessageDialogWrapper.kt +++ b/src/main/kotlin/com/joetr/modulemaker/MessageDialogWrapper.kt @@ -12,8 +12,9 @@ import javax.swing.JTextArea private const val WINDOW_WIDTH = 100 private const val WINDOW_HEIGHT = 100 -class MessageDialogWrapper(private val message: String) : DialogWrapper(true) { - +class MessageDialogWrapper( + private val message: String, +) : DialogWrapper(true) { init { init() } @@ -30,12 +31,11 @@ class MessageDialogWrapper(private val message: String) : DialogWrapper(true) { return dialogPanel } - override fun createActions(): Array { - return arrayOf( + override fun createActions(): Array = + arrayOf( DialogWrapperExitAction( "Okay", - 2 - ) + 2, + ), ) - } } diff --git a/src/main/kotlin/com/joetr/modulemaker/ModuleMakerAction.kt b/src/main/kotlin/com/joetr/modulemaker/ModuleMakerAction.kt index 8ff28ce..e1579a4 100644 --- a/src/main/kotlin/com/joetr/modulemaker/ModuleMakerAction.kt +++ b/src/main/kotlin/com/joetr/modulemaker/ModuleMakerAction.kt @@ -17,7 +17,7 @@ class ModuleMakerAction : AnAction() { ModuleMakerDialogWrapper( project = project, - startingLocation = if (shouldUseStartingLocation) startingLocation else null + startingLocation = if (shouldUseStartingLocation) startingLocation else null, ).show() } } diff --git a/src/main/kotlin/com/joetr/modulemaker/ModuleMakerDialogWrapper.kt b/src/main/kotlin/com/joetr/modulemaker/ModuleMakerDialogWrapper.kt index 7f0472b..fd45045 100644 --- a/src/main/kotlin/com/joetr/modulemaker/ModuleMakerDialogWrapper.kt +++ b/src/main/kotlin/com/joetr/modulemaker/ModuleMakerDialogWrapper.kt @@ -71,14 +71,14 @@ private const val DEFAULT_SRC_VALUE = "EMPTY" class ModuleMakerDialogWrapper( private val project: Project, - private val startingLocation: VirtualFile? + private val startingLocation: VirtualFile?, ) : DialogWrapper(true) { - private val preferenceService = PreferenceServiceImpl.instance - private val fileWriter = FileWriter( - preferenceService = preferenceService - ) + private val fileWriter = + FileWriter( + preferenceService = preferenceService, + ) private var selectedSrcValue = mutableStateOf(DEFAULT_SRC_VALUE) private val threeModuleCreation = mutableStateOf(preferenceService.preferenceState.threeModuleCreationDefault) @@ -94,61 +94,69 @@ class ModuleMakerDialogWrapper( private val sourceSets = mutableStateListOf() // Segment's write key isn't really a secret - private var analytics: Analytics = Analytics("CNghGjhOHipwGB9YdWMBwkMTJbRFtizc") { - application = "ModuleMaker" - flushAt = 1 - } + private var analytics: Analytics = + Analytics("CNghGjhOHipwGB9YdWMBwkMTJbRFtizc") { + application = "ModuleMaker" + flushAt = 1 + } init { title = "Module Maker" init() - selectedSrcValue.value = if (startingLocation != null) { - // give default of starting location - File(startingLocation.path).absolutePath.removePrefix(rootDirectoryStringDropLast()) - .removePrefix(File.separator) - } else { - // give default value of the root project - File(rootDirectoryString()).absolutePath.removePrefix(rootDirectoryStringDropLast()) - .removePrefix(File.separator) - } + selectedSrcValue.value = + if (startingLocation != null) { + // give default of starting location + File(startingLocation.path) + .absolutePath + .removePrefix(rootDirectoryStringDropLast()) + .removePrefix(File.separator) + } else { + // give default value of the root project + File(rootDirectoryString()) + .absolutePath + .removePrefix(rootDirectoryStringDropLast()) + .removePrefix(File.separator) + } } @OptIn(ExperimentalJewelApi::class) @Nullable - override fun createCenterPanel(): JComponent { - return JewelComposeNoThemePanel(focusOnClickInside = true) { + override fun createCenterPanel(): JComponent = + JewelComposeNoThemePanel(focusOnClickInside = true) { WidgetTheme { Row { val startingHeight = remember { mutableStateOf(WINDOW_HEIGHT) } val fileTreeWidth = remember { mutableStateOf(FILE_TREE_WIDTH) } val configurationPanelWidth = remember { mutableStateOf(CONFIGURATION_PANEL_WIDTH) } FileTreeJPanel( - modifier = Modifier.height(startingHeight.value.dp).width(fileTreeWidth.value.dp) + modifier = Modifier.height(startingHeight.value.dp).width(fileTreeWidth.value.dp), ) ConfigurationPanel( - modifier = Modifier.height(startingHeight.value.dp) - .width(configurationPanelWidth.value.dp) + modifier = + Modifier + .height(startingHeight.value.dp) + .width(configurationPanelWidth.value.dp), ) } } } - } - override fun createLeftSideActions(): Array { - return arrayOf(object : AbstractAction("Settings") { - override fun actionPerformed(e: ActionEvent?) { - SettingsDialogWrapper( - project = project, - onSave = { - onSettingsSaved() - }, - isKtsCurrentlyChecked = useKtsExtension.value, - isAndroidChecked = moduleTypeSelection.value == ANDROID - ).show() - } - }) - } + override fun createLeftSideActions(): Array = + arrayOf( + object : AbstractAction("Settings") { + override fun actionPerformed(e: ActionEvent?) { + SettingsDialogWrapper( + project = project, + onSave = { + onSettingsSaved() + }, + isKtsCurrentlyChecked = useKtsExtension.value, + isAndroidChecked = moduleTypeSelection.value == ANDROID, + ).show() + } + }, + ) private fun onSettingsSaved() { packageName.value = TextFieldValue(preferenceService.preferenceState.packageName) @@ -159,11 +167,11 @@ class ModuleMakerDialogWrapper( addGitIgnore.value = preferenceService.preferenceState.addGitIgnore } - override fun createActions(): Array { - return arrayOf( + override fun createActions(): Array = + arrayOf( DialogWrapperExitAction( "Cancel", - 2 + 2, ), object : AbstractAction("Preview") { override fun actionPerformed(e: ActionEvent?) { @@ -182,26 +190,22 @@ class ModuleMakerDialogWrapper( MessageDialogWrapper("Please fill out required values").show() } } - } + }, ) - } private fun displayPreviewDialog() { val filesToBeCreated = create(previewMode = true) PreviewDialogWrapper(filesToBeCreated = filesToBeCreated, root = rootFromPath(rootDirectoryString())).show() } - private fun validateInput(): Boolean { - return packageName.value.text.isNotEmpty() && + private fun validateInput(): Boolean = + packageName.value.text.isNotEmpty() && selectedSrcValue.value != DEFAULT_SRC_VALUE && moduleName.value.text.isNotEmpty() && moduleName.value.text != DEFAULT_MODULE_NAME - } @Composable - private fun FileTreeJPanel( - modifier: Modifier = Modifier - ) { + private fun FileTreeJPanel(modifier: Modifier = Modifier) { val height = remember { mutableStateOf(WINDOW_HEIGHT) } val fileTree = remember { FileTree(root = File(rootDirectoryString()).toProjectFile()) } FileTreeView( @@ -227,15 +231,13 @@ class ModuleMakerDialogWrapper( if (fileTreeNode.file.isDirectory) { selectedSrcValue.value = relativePath } - } + }, ) } @OptIn(ExperimentalLayoutApi::class, ExperimentalJewelApi::class) @Composable - private fun ConfigurationPanel( - modifier: Modifier = Modifier - ) { + private fun ConfigurationPanel(modifier: Modifier = Modifier) { Column(modifier = modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(8.dp)) { val selectedRootState = remember { selectedSrcValue } Text("Selected root: ${selectedRootState.value}") @@ -249,22 +251,22 @@ class ModuleMakerDialogWrapper( checked = threeModuleCreationState.value, onCheckedChange = { threeModuleCreationState.value = it - } + }, ) IconButton(onClick = { MessageDialogWrapper( """ - The 3 module creation adds an api, glue, and impl module. + The 3 module creation adds an api, glue, and impl module. - More info can be found here https://www.droidcon.com/2019/11/15/android-at-scale-square/ - """.trimIndent() + More info can be found here https://www.droidcon.com/2019/11/15/android-at-scale-square/ + """.trimIndent(), ).show() }) { _ -> Icon( key = IntelliJIconKey.fromPlatformIcon(AllIcons.General.Information), contentDescription = "info", iconClass = AllIcons::class.java, - modifier = Modifier.padding(end = 4.dp) + modifier = Modifier.padding(end = 4.dp), ) } } @@ -277,7 +279,7 @@ class ModuleMakerDialogWrapper( checked = useKtsExtensionState.value, onCheckedChange = { useKtsExtensionState.value = it - } + }, ) Spacer(Modifier.height(8.dp)) @@ -288,7 +290,7 @@ class ModuleMakerDialogWrapper( checked = gradleFileNamedAfterModuleState.value, onCheckedChange = { gradleFileNamedAfterModuleState.value = it - } + }, ) Spacer(Modifier.height(8.dp)) @@ -299,7 +301,7 @@ class ModuleMakerDialogWrapper( checked = addReadmeState.value, onCheckedChange = { addReadmeState.value = it - } + }, ) Spacer(Modifier.height(8.dp)) @@ -310,7 +312,7 @@ class ModuleMakerDialogWrapper( checked = addGitIgnoreState.value, onCheckedChange = { addGitIgnoreState.value = it - } + }, ) Spacer(Modifier.height(8.dp)) @@ -325,7 +327,7 @@ class ModuleMakerDialogWrapper( text = text, selected = (text == moduleTypeSelectionState.value), onClick = { moduleTypeSelectionState.value = text }, - modifier = Modifier.padding(end = 16.dp) + modifier = Modifier.padding(end = 16.dp), ) Spacer(Modifier.height(8.dp)) } @@ -345,18 +347,19 @@ class ModuleMakerDialogWrapper( text = text, selected = (text == platformTypeRadioOptionsState.value), onClick = { platformTypeRadioOptionsState.value = text }, - modifier = Modifier.padding(end = 16.dp) + modifier = Modifier.padding(end = 16.dp), ) Spacer(Modifier.height(8.dp)) } - val selectedSourceSets = remember { - sourceSets - } + val selectedSourceSets = + remember { + sourceSets + } AnimatedVisibility( - platformTypeSelection.value == MULTIPLATFORM + platformTypeSelection.value == MULTIPLATFORM, ) { Spacer(Modifier.height(8.dp)) @@ -374,7 +377,7 @@ class ModuleMakerDialogWrapper( } else { selectedSourceSets.remove(sourceSet) } - } + }, ) } } @@ -396,7 +399,7 @@ class ModuleMakerDialogWrapper( } else { selectedSourceSets.remove(sourceSet) } - } + }, ) } } @@ -413,7 +416,7 @@ class ModuleMakerDialogWrapper( value = packageNameState.value, onValueChange = { packageNameState.value = it - } + }, ) Spacer(Modifier.height(8.dp)) @@ -428,7 +431,7 @@ class ModuleMakerDialogWrapper( value = moduleNameState.value, onValueChange = { moduleNameState.value = it - } + }, ) } } @@ -450,7 +453,7 @@ class ModuleMakerDialogWrapper( settingsGradleKtsCurrentlySelectedRoot, settingsGradleCurrentlySelectedRoot, settingsGradleKtsPath, - settingsGradlePath + settingsGradlePath, ).firstOrNull { it.exists() } ?: run { @@ -472,42 +475,43 @@ class ModuleMakerDialogWrapper( addGitIgnore = addGitIgnore.value, addReadme = addReadme.value, gradleNameToFollow = gradleFileNamedAfterModule.value, - useKts = useKtsExtension.value - ) - ) - val filesCreated = fileWriter.createModule( - // at this point, selectedSrcValue has a value of something like /root/module/module2/ - // - we want to remove the root of the project to use as the file path in settings.gradle - rootPathString = removeRootFromPath(selectedSrcValue.value), - settingsGradleFile = settingsGradleFile, - modulePathAsString = moduleName.value.text, - moduleType = moduleType, - showErrorDialog = { - analytics.track("module_creation_error", ModuleCreationErrorAnalytics(message = it)) - MessageDialogWrapper(it).show() - }, - showSuccessDialog = { - analytics.track("module_creation_success") - MessageDialogWrapper("Success").show() - refreshFileSystem( - settingsGradleFile = settingsGradleFile, - currentlySelectedFile = currentlySelectedFile - ) - if (preferenceService.preferenceState.refreshOnModuleAdd) { - syncProject() - } - }, - workingDirectory = currentlySelectedFile, - enhancedModuleCreationStrategy = threeModuleCreation.value, - useKtsBuildFile = useKtsExtension.value, - gradleFileFollowModule = gradleFileNamedAfterModule.value, - packageName = packageName.value.text, - addReadme = addReadme.value, - addGitIgnore = addGitIgnore.value, - previewMode = previewMode, - platformType = platformTypeSelection.value, - sourceSets = sourceSets.toList() + useKts = useKtsExtension.value, + ), ) + val filesCreated = + fileWriter.createModule( + // at this point, selectedSrcValue has a value of something like /root/module/module2/ + // - we want to remove the root of the project to use as the file path in settings.gradle + rootPathString = removeRootFromPath(selectedSrcValue.value), + settingsGradleFile = settingsGradleFile, + modulePathAsString = moduleName.value.text, + moduleType = moduleType, + showErrorDialog = { + analytics.track("module_creation_error", ModuleCreationErrorAnalytics(message = it)) + MessageDialogWrapper(it).show() + }, + showSuccessDialog = { + analytics.track("module_creation_success") + MessageDialogWrapper("Success").show() + refreshFileSystem( + settingsGradleFile = settingsGradleFile, + currentlySelectedFile = currentlySelectedFile, + ) + if (preferenceService.preferenceState.refreshOnModuleAdd) { + syncProject() + } + }, + workingDirectory = currentlySelectedFile, + enhancedModuleCreationStrategy = threeModuleCreation.value, + useKtsBuildFile = useKtsExtension.value, + gradleFileFollowModule = gradleFileNamedAfterModule.value, + packageName = packageName.value.text, + addReadme = addReadme.value, + addGitIgnore = addGitIgnore.value, + previewMode = previewMode, + platformType = platformTypeSelection.value, + sourceSets = sourceSets.toList(), + ) return filesCreated } else { @@ -522,43 +526,41 @@ class ModuleMakerDialogWrapper( ProjectSystemId("GRADLE"), rootDirectoryString(), false, - ProgressExecutionMode.START_IN_FOREGROUND_ASYNC + ProgressExecutionMode.START_IN_FOREGROUND_ASYNC, ) } /** * Refresh the settings gradle file and the root file */ - private fun refreshFileSystem(settingsGradleFile: File, currentlySelectedFile: File) { + private fun refreshFileSystem( + settingsGradleFile: File, + currentlySelectedFile: File, + ) { VfsUtil.markDirtyAndRefresh( false, true, true, settingsGradleFile, - currentlySelectedFile + currentlySelectedFile, ) } - private fun getCurrentlySelectedFile(): File { - return File(rootDirectoryStringDropLast() + File.separator + selectedSrcValue.value) - } + private fun getCurrentlySelectedFile(): File = File(rootDirectoryStringDropLast() + File.separator + selectedSrcValue.value) private fun rootDirectoryStringDropLast(): String { // rootDirectoryString() gives us back something like /Users/user/path/to/project // the first path element in the tree node starts with 'project' (last folder above) // so we remove it and join the nodes of the tree by our file separator - return project.basePath!!.split(File.separator).dropLast(1).joinToString(File.separator) - } - - private fun rootDirectoryString(): String { return project.basePath!! + .split(File.separator) + .dropLast(1) + .joinToString(File.separator) } - private fun removeRootFromPath(path: String): String { - return path.split(File.separator).drop(1).joinToString(File.separator) - } + private fun rootDirectoryString(): String = project.basePath!! - private fun rootFromPath(path: String): String { - return path.split(File.separator).last() - } + private fun removeRootFromPath(path: String): String = path.split(File.separator).drop(1).joinToString(File.separator) + + private fun rootFromPath(path: String): String = path.split(File.separator).last() } diff --git a/src/main/kotlin/com/joetr/modulemaker/MultiplatformSourceSets.kt b/src/main/kotlin/com/joetr/modulemaker/MultiplatformSourceSets.kt index 8f9f23d..a4ae8eb 100644 --- a/src/main/kotlin/com/joetr/modulemaker/MultiplatformSourceSets.kt +++ b/src/main/kotlin/com/joetr/modulemaker/MultiplatformSourceSets.kt @@ -4,63 +4,65 @@ package com.joetr.modulemaker -val kotlinMultiplatformSourceSets = listOf( - // Main Source Sets - "commonMain", - "androidMain", - "jvmMain", - "nativeMain", - "iosMain", - "jsMain", - "wasmJsMain", - "iosArm64Main", - "iosX64Main", - "iosSimulatorArm64Main", - "macosMain", - "macosX64Main", - "macosArm64Main", - "linuxMain", - "linuxX64Main", - "linuxArm64Main", - "mingwMain", - "mingwX64Main", - "tvosMain", - "tvosArm64Main", - "tvosX64Main", - "tvosSimulatorArm64Main", - "watchosMain", - "watchosArm32Main", - "watchosArm64Main", - "watchosX64Main", - "watchosSimulatorArm64Main" -) +val kotlinMultiplatformSourceSets = + listOf( + // Main Source Sets + "commonMain", + "androidMain", + "jvmMain", + "nativeMain", + "iosMain", + "jsMain", + "wasmJsMain", + "iosArm64Main", + "iosX64Main", + "iosSimulatorArm64Main", + "macosMain", + "macosX64Main", + "macosArm64Main", + "linuxMain", + "linuxX64Main", + "linuxArm64Main", + "mingwMain", + "mingwX64Main", + "tvosMain", + "tvosArm64Main", + "tvosX64Main", + "tvosSimulatorArm64Main", + "watchosMain", + "watchosArm32Main", + "watchosArm64Main", + "watchosX64Main", + "watchosSimulatorArm64Main", + ) -val kotlinMultiplatformTestSourceSets = listOf( - "commonTest", - "androidTest", - "jvmTest", - "nativeTest", - "iosTest", - "jsTest", - "wasmTest", - "iosArm64Test", - "iosX64Test", - "iosSimulatorArm64Test", - "macosTest", - "macosX64Test", - "macosArm64Test", - "linuxTest", - "linuxX64Test", - "linuxArm64Test", - "mingwTest", - "mingwX64Test", - "tvosTest", - "tvosArm64Test", - "tvosX64Test", - "tvosSimulatorArm64Test", - "watchosTest", - "watchosArm32Test", - "watchosArm64Test", - "watchosX64Test", - "watchosSimulatorArm64Test" -) +val kotlinMultiplatformTestSourceSets = + listOf( + "commonTest", + "androidTest", + "jvmTest", + "nativeTest", + "iosTest", + "jsTest", + "wasmTest", + "iosArm64Test", + "iosX64Test", + "iosSimulatorArm64Test", + "macosTest", + "macosX64Test", + "macosArm64Test", + "linuxTest", + "linuxX64Test", + "linuxArm64Test", + "mingwTest", + "mingwX64Test", + "tvosTest", + "tvosArm64Test", + "tvosX64Test", + "tvosSimulatorArm64Test", + "watchosTest", + "watchosArm32Test", + "watchosArm64Test", + "watchosX64Test", + "watchosSimulatorArm64Test", + ) diff --git a/src/main/kotlin/com/joetr/modulemaker/Notifications.kt b/src/main/kotlin/com/joetr/modulemaker/Notifications.kt index b1c2642..e605aa7 100644 --- a/src/main/kotlin/com/joetr/modulemaker/Notifications.kt +++ b/src/main/kotlin/com/joetr/modulemaker/Notifications.kt @@ -6,12 +6,13 @@ import com.intellij.openapi.project.Project object Notifications { fun showExportError(project: Project) { - val notification = Notification( - "ModuleMaker", - "Error", - "An error occurred while exporting your settings", - NotificationType.ERROR - ) + val notification = + Notification( + "ModuleMaker", + "Error", + "An error occurred while exporting your settings", + NotificationType.ERROR, + ) notification.notify(project) } diff --git a/src/main/kotlin/com/joetr/modulemaker/PreviewDialogWrapper.kt b/src/main/kotlin/com/joetr/modulemaker/PreviewDialogWrapper.kt index 67954b5..b5c5502 100644 --- a/src/main/kotlin/com/joetr/modulemaker/PreviewDialogWrapper.kt +++ b/src/main/kotlin/com/joetr/modulemaker/PreviewDialogWrapper.kt @@ -25,8 +25,10 @@ import javax.swing.JComponent private const val WINDOW_WIDTH = 400 private const val WINDOW_HEIGHT = 600 -class PreviewDialogWrapper(val filesToBeCreated: List, val root: String) : DialogWrapper(true) { - +class PreviewDialogWrapper( + val filesToBeCreated: List, + val root: String, +) : DialogWrapper(true) { private var tempRoot: File init { @@ -43,7 +45,7 @@ class PreviewDialogWrapper(val filesToBeCreated: List, val root: String) : // splice together the files to have a root of our temp folder File(pathToRoot, split.drop(1).joinToString(separator = "")) - } + }, ) } @@ -52,40 +54,39 @@ class PreviewDialogWrapper(val filesToBeCreated: List, val root: String) : tempRoot.parentFile.deleteRecursively() } - override fun createCenterPanel(): JComponent { - return ComposePanel().apply { + override fun createCenterPanel(): JComponent = + ComposePanel().apply { setBounds(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT) setContent { WidgetTheme { FileTreeJPanel( - modifier = Modifier.height(WINDOW_HEIGHT.dp).width(WINDOW_WIDTH.dp) + modifier = Modifier.height(WINDOW_HEIGHT.dp).width(WINDOW_WIDTH.dp), ) } } } - } @Composable - private fun FileTreeJPanel( - modifier: Modifier = Modifier - ) { + private fun FileTreeJPanel(modifier: Modifier = Modifier) { val height = remember { mutableStateOf(WINDOW_HEIGHT) } FileTreeView( modifier = modifier, model = FileTree(root = tempRoot.toProjectFile()), height = height.value.dp, - onClick = { } + onClick = { }, ) } - private fun List.root(): File { - return this.minBy { file -> + private fun List.root(): File = + this.minBy { file -> file.absolutePath.count { it.toString() == File.separator } } - } - private fun createFileStructure(root: File, structure: List) { + private fun createFileStructure( + root: File, + structure: List, + ) { root.mkdirs() structure.forEach { it.mkdirs() @@ -95,12 +96,11 @@ class PreviewDialogWrapper(val filesToBeCreated: List, val root: String) : } } - override fun createActions(): Array { - return arrayOf( + override fun createActions(): Array = + arrayOf( DialogWrapperExitAction( "Okay", - 2 - ) + 2, + ), ) - } } diff --git a/src/main/kotlin/com/joetr/modulemaker/SettingsDialogWrapper.kt b/src/main/kotlin/com/joetr/modulemaker/SettingsDialogWrapper.kt index de7e455..21284b4 100644 --- a/src/main/kotlin/com/joetr/modulemaker/SettingsDialogWrapper.kt +++ b/src/main/kotlin/com/joetr/modulemaker/SettingsDialogWrapper.kt @@ -82,9 +82,8 @@ class SettingsDialogWrapper( private val project: Project, private val onSave: () -> Unit, private val isKtsCurrentlyChecked: Boolean, - private val isAndroidChecked: Boolean + private val isAndroidChecked: Boolean, ) : DialogWrapper(true) { - private val preferenceService = PreferenceServiceImpl.instance private val refreshOnModuleAdd = mutableStateOf(preferenceService.preferenceState.refreshOnModuleAdd) @@ -118,53 +117,55 @@ class SettingsDialogWrapper( private val multiplatformTemplateTextArea = mutableStateOf(TextFieldValue(preferenceService.preferenceState.multiplatformTemplate)) + init { title = "Settings" init() } @Nullable - override fun createCenterPanel(): JComponent { - return ComposePanel().apply { + override fun createCenterPanel(): JComponent = + ComposePanel().apply { setBounds(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT) setContent { SettingsTab() } } - } @Composable fun SettingsTab() { var tabIndex by remember { mutableStateOf(0) } - val tabs = listOf( - "Module Template Defaults", - "Enhanced Template Defaults", - "Multiplatform Template Defaults", - ".gitignore Template Defaults", - "General" - ) + val tabs = + listOf( + "Module Template Defaults", + "Enhanced Template Defaults", + "Multiplatform Template Defaults", + ".gitignore Template Defaults", + "General", + ) WidgetTheme { Column(modifier = Modifier.width(WINDOW_WIDTH.dp).height(WINDOW_HEIGHT.dp)) { - val tabData = tabs.mapIndexed { index, title -> - TabData.Default( - selected = tabIndex == index, - content = { _ -> - SimpleTabContent( - label = title, - state = TabState.of(tabIndex == index) - ) - }, - closable = false, - onClose = {}, - onClick = { tabIndex = index } - ) - } + val tabData = + tabs.mapIndexed { index, title -> + TabData.Default( + selected = tabIndex == index, + content = { _ -> + SimpleTabContent( + label = title, + state = TabState.of(tabIndex == index), + ) + }, + closable = false, + onClose = {}, + onClick = { tabIndex = index }, + ) + } TabStrip( tabs = tabData, style = JewelTheme.defaultTabStyle, - interactionSource = MutableInteractionSource() + interactionSource = MutableInteractionSource(), ) when (tabIndex) { 0 -> TemplateDefaultComponent() @@ -182,14 +183,14 @@ class SettingsDialogWrapper( Column(modifier = Modifier.fillMaxSize().padding(8.dp)) { val settingExplanationText = """ - You can override the multiplatform gradle templates created with your own project specific defaults. + You can override the multiplatform gradle templates created with your own project specific defaults. - If nothing is specified here, a sensible default will be generated for you. + If nothing is specified here, a sensible default will be generated for you. """.trimIndent() Text( modifier = Modifier.padding(8.dp), - text = settingExplanationText + text = settingExplanationText, ) val multiplatformModuleTemplateState = remember { multiplatformTemplateTextArea } @@ -200,7 +201,7 @@ class SettingsDialogWrapper( onValueChange = { multiplatformModuleTemplateState.value = it }, - modifier = Modifier.fillMaxSize().padding(8.dp) + modifier = Modifier.fillMaxSize().padding(8.dp), ) } } @@ -210,11 +211,12 @@ class SettingsDialogWrapper( Column(modifier = Modifier.fillMaxSize().padding(8.dp)) { Text( modifier = Modifier.padding(8.dp), - text = """ + text = + """ You can override the .gitignore templates created with your own project specific default. If nothing is specified here, a sensible default will be generated for you. - """.trimIndent() + """.trimIndent(), ) Spacer(Modifier.height(16.dp)) @@ -226,7 +228,7 @@ class SettingsDialogWrapper( value = gitIgnoreTemplateState.value, onValueChange = { gitIgnoreTemplateState.value = it - } + }, ) } } @@ -234,7 +236,7 @@ class SettingsDialogWrapper( @Composable private fun GeneralPanel() { Column( - modifier = Modifier.fillMaxSize().padding(8.dp).verticalScroll(rememberScrollState()) + modifier = Modifier.fillMaxSize().padding(8.dp).verticalScroll(rememberScrollState()), ) { var basePackageName by remember { packageNameTextField } @@ -245,7 +247,7 @@ class SettingsDialogWrapper( basePackageName = newValue }, modifier = Modifier.padding(8.dp).fillMaxWidth(), - textStyle = TextStyle(fontFamily = FontFamily.SansSerif) + textStyle = TextStyle(fontFamily = FontFamily.SansSerif), ) Spacer(Modifier.height(8.dp)) @@ -259,7 +261,7 @@ class SettingsDialogWrapper( includeKeyword = newValue }, modifier = Modifier.padding(8.dp).fillMaxWidth(), - textStyle = TextStyle(fontFamily = FontFamily.SansSerif) + textStyle = TextStyle(fontFamily = FontFamily.SansSerif), ) Spacer(Modifier.height(8.dp)) @@ -270,7 +272,7 @@ class SettingsDialogWrapper( checked = refreshAfterModuleCreationState.value, onCheckedChange = { refreshAfterModuleCreationState.value = it - } + }, ) Spacer(Modifier.height(8.dp)) @@ -281,7 +283,7 @@ class SettingsDialogWrapper( checked = threeModuleState.value, onCheckedChange = { threeModuleState.value = it - } + }, ) Spacer(Modifier.height(8.dp)) @@ -292,7 +294,7 @@ class SettingsDialogWrapper( checked = useKtsState.value, onCheckedChange = { useKtsState.value = it - } + }, ) Spacer(Modifier.height(8.dp)) @@ -303,7 +305,7 @@ class SettingsDialogWrapper( checked = gradleFileNameState.value, onCheckedChange = { gradleFileNameState.value = it - } + }, ) Spacer(Modifier.height(8.dp)) @@ -314,7 +316,7 @@ class SettingsDialogWrapper( checked = readmeState.value, onCheckedChange = { readmeState.value = it - } + }, ) Spacer(Modifier.height(8.dp)) @@ -325,7 +327,7 @@ class SettingsDialogWrapper( checked = addGitignore.value, onCheckedChange = { gitIgnoreState.value = it - } + }, ) Spacer(Modifier.height(16.dp)) @@ -333,7 +335,7 @@ class SettingsDialogWrapper( DefaultButton( onClick = { importSettings() - } + }, ) { Text("Import Settings") } @@ -343,7 +345,7 @@ class SettingsDialogWrapper( DefaultButton( onClick = { exportSettings() - } + }, ) { Text("Export Settings") } @@ -353,7 +355,7 @@ class SettingsDialogWrapper( DefaultButton( onClick = { clearData() - } + }, ) { Text("Clear All Settings") } @@ -363,25 +365,26 @@ class SettingsDialogWrapper( @Composable private fun TemplateDefaultComponent() { Column( - modifier = Modifier.fillMaxSize().padding(8.dp).verticalScroll(rememberScrollState()) + modifier = Modifier.fillMaxSize().padding(8.dp).verticalScroll(rememberScrollState()), ) { val settingExplanationText = """ - You can override the gradle templates created with your own project specific defaults. + You can override the gradle templates created with your own project specific defaults. - If nothing is specified here, a sensible default will be generated for you. + If nothing is specified here, a sensible default will be generated for you. """.trimIndent() - val supportedVariablesString = TemplateVariable.values().joinToString("\n") { - it.templateVariable - } + val supportedVariablesString = + TemplateVariable.values().joinToString("\n") { + it.templateVariable + } val supportedVariablesLabel = """ - If you do have a custom template, there are some variable names that will be automatically replaced for you. + If you do have a custom template, there are some variable names that will be automatically replaced for you. - Supported variables are: + Supported variables are: - $supportedVariablesString + $supportedVariablesString """.trimIndent() Text(settingExplanationText) @@ -391,23 +394,29 @@ class SettingsDialogWrapper( val kotlinTemplateState = remember { kotlinTemplateTextArea } Text("Kotlin Template") TextArea( - modifier = Modifier.fillMaxWidth().padding(8.dp) - .defaultMinSize(minHeight = (WINDOW_HEIGHT / 3).dp), + modifier = + Modifier + .fillMaxWidth() + .padding(8.dp) + .defaultMinSize(minHeight = (WINDOW_HEIGHT / 3).dp), value = kotlinTemplateState.value, onValueChange = { kotlinTemplateState.value = it - } + }, ) val androidTemplateState = remember { androidTemplateTextArea } Text("Android Template") TextArea( - modifier = Modifier.fillMaxWidth().padding(8.dp) - .defaultMinSize(minHeight = (WINDOW_HEIGHT / 3).dp), + modifier = + Modifier + .fillMaxWidth() + .padding(8.dp) + .defaultMinSize(minHeight = (WINDOW_HEIGHT / 3).dp), value = androidTemplateState.value, onValueChange = { androidTemplateState.value = it - } + }, ) Text(supportedVariablesLabel) @@ -417,39 +426,48 @@ class SettingsDialogWrapper( @Composable private fun EnhancedTemplateDefaultComponent() { Column( - modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()) + modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()), ) { val apiTemplateState = remember { apiTemplateTextArea } Text("Api Template") TextArea( - modifier = Modifier.fillMaxWidth().padding(8.dp) - .defaultMinSize(minHeight = (WINDOW_HEIGHT / 3).dp), + modifier = + Modifier + .fillMaxWidth() + .padding(8.dp) + .defaultMinSize(minHeight = (WINDOW_HEIGHT / 3).dp), value = apiTemplateState.value, onValueChange = { apiTemplateState.value = it - } + }, ) val glueTemplateState = remember { glueTemplateTextArea } Text("Glue Template") TextArea( - modifier = Modifier.fillMaxWidth().padding(8.dp) - .defaultMinSize(minHeight = (WINDOW_HEIGHT / 3).dp), + modifier = + Modifier + .fillMaxWidth() + .padding(8.dp) + .defaultMinSize(minHeight = (WINDOW_HEIGHT / 3).dp), value = glueTemplateState.value, onValueChange = { glueTemplateState.value = it - } + }, ) val implTemplateState = remember { implTemplateTextArea } Text("Impl Template") TextArea( - modifier = Modifier.fillMaxWidth().padding(8.dp) - .defaultMinSize(minHeight = (WINDOW_HEIGHT / 3).dp), + modifier = + Modifier + .fillMaxWidth() + .padding(8.dp) + .defaultMinSize(minHeight = (WINDOW_HEIGHT / 3).dp), value = implTemplateState.value, onValueChange = { implTemplateState.value = it - } + }, ) val apiModuleNameState = remember { apiModuleNameTextArea } @@ -460,7 +478,7 @@ class SettingsDialogWrapper( value = apiModuleNameState.value, onValueChange = { apiModuleNameState.value = it - } + }, ) val glueModuleNameState = remember { glueModuleNameTextArea } @@ -471,7 +489,7 @@ class SettingsDialogWrapper( value = glueModuleNameState.value, onValueChange = { glueModuleNameState.value = it - } + }, ) val implModuleNameState = remember { implModuleNameTextArea } @@ -482,7 +500,7 @@ class SettingsDialogWrapper( value = implModuleNameState.value, onValueChange = { implModuleNameState.value = it - } + }, ) } } @@ -495,10 +513,10 @@ class SettingsDialogWrapper( false, false, false, - false + false, ), project, - null + null, ) { val path: Path = Paths.get(it.path) @@ -525,14 +543,15 @@ class SettingsDialogWrapper( } private fun exportSettings() { - val test = FileChooserFactory.getInstance().createSaveFileDialog( - FileSaverDescriptor( - "Select Location", - "", - ".json" - ), - project - ) + val test = + FileChooserFactory.getInstance().createSaveFileDialog( + FileSaverDescriptor( + "Select Location", + "", + ".json", + ), + project, + ) val wrapper = test.save("module_maker_settings.json") if (wrapper != null) { try { @@ -564,32 +583,33 @@ class SettingsDialogWrapper( val gitignoreTemplate = gitignoreTemplateTextArea.value.text // if more parameters get added, add support to import / export - val newState = PreferenceServiceImpl.Companion.State( - androidTemplate = androidTemplate, - kotlinTemplate = kotlinTemplate, - multiplatformTemplate = multiplatformTemplate, - apiTemplate = apiTemplate, - glueTemplate = glueTemplate, - implTemplate = implTemplate, - packageName = packageName, - includeProjectKeyword = includeProject, - refreshOnModuleAdd = shouldRefresh, - threeModuleCreationDefault = threeModuleCreationDefault, - useKtsFileExtension = useKtsFileExtension, - gradleFileNamedAfterModule = gradleFileNamedAfterModule, - addReadme = addReadme, - addGitIgnore = addGitignore, - gitignoreTemplate = gitignoreTemplate - ) + val newState = + PreferenceServiceImpl.Companion.State( + androidTemplate = androidTemplate, + kotlinTemplate = kotlinTemplate, + multiplatformTemplate = multiplatformTemplate, + apiTemplate = apiTemplate, + glueTemplate = glueTemplate, + implTemplate = implTemplate, + packageName = packageName, + includeProjectKeyword = includeProject, + refreshOnModuleAdd = shouldRefresh, + threeModuleCreationDefault = threeModuleCreationDefault, + useKtsFileExtension = useKtsFileExtension, + gradleFileNamedAfterModule = gradleFileNamedAfterModule, + addReadme = addReadme, + addGitIgnore = addGitignore, + gitignoreTemplate = gitignoreTemplate, + ) return Json.encodeToString(newState) } - override fun createActions(): Array { - return arrayOf( + override fun createActions(): Array = + arrayOf( DialogWrapperExitAction( "Cancel", - DEFAULT_EXIT_CODE + DEFAULT_EXIT_CODE, ), object : AbstractAction("Save") { override fun actionPerformed(e: ActionEvent?) { @@ -597,31 +617,31 @@ class SettingsDialogWrapper( onSave() close(DEFAULT_EXIT_CODE) } - } + }, ) - } private fun saveDate() { - preferenceService.preferenceState = preferenceService.preferenceState.copy( - androidTemplate = androidTemplateTextArea.value.text, - kotlinTemplate = kotlinTemplateTextArea.value.text, - multiplatformTemplate = multiplatformTemplateTextArea.value.text, - apiTemplate = apiTemplateTextArea.value.text, - implTemplate = implTemplateTextArea.value.text, - glueTemplate = glueTemplateTextArea.value.text, - packageName = packageNameTextField.value.text, - includeProjectKeyword = includeProjectKeywordTextField.value.text, - refreshOnModuleAdd = refreshOnModuleAdd.value, - threeModuleCreationDefault = threeModuleCreation.value, - useKtsFileExtension = ktsFileExtension.value, - gradleFileNamedAfterModule = gradleFileNamedAfterModule.value, - addReadme = addReadme.value, - addGitIgnore = addGitignore.value, - gitignoreTemplate = gitignoreTemplateTextArea.value.text, - apiModuleName = apiModuleNameTextArea.value.text, - glueModuleName = glueModuleNameTextArea.value.text, - implModuleName = implModuleNameTextArea.value.text - ) + preferenceService.preferenceState = + preferenceService.preferenceState.copy( + androidTemplate = androidTemplateTextArea.value.text, + kotlinTemplate = kotlinTemplateTextArea.value.text, + multiplatformTemplate = multiplatformTemplateTextArea.value.text, + apiTemplate = apiTemplateTextArea.value.text, + implTemplate = implTemplateTextArea.value.text, + glueTemplate = glueTemplateTextArea.value.text, + packageName = packageNameTextField.value.text, + includeProjectKeyword = includeProjectKeywordTextField.value.text, + refreshOnModuleAdd = refreshOnModuleAdd.value, + threeModuleCreationDefault = threeModuleCreation.value, + useKtsFileExtension = ktsFileExtension.value, + gradleFileNamedAfterModule = gradleFileNamedAfterModule.value, + addReadme = addReadme.value, + addGitIgnore = addGitignore.value, + gitignoreTemplate = gitignoreTemplateTextArea.value.text, + apiModuleName = apiModuleNameTextArea.value.text, + glueModuleName = glueModuleNameTextArea.value.text, + implModuleName = implModuleNameTextArea.value.text, + ) } private fun clearData() { @@ -646,7 +666,10 @@ class SettingsDialogWrapper( apiModuleNameTextArea.value = TextFieldValue(DEFAULT_API_MODULE_NAME) } - private fun getDefaultTemplate(isKotlin: Boolean = false, isMultiplatform: Boolean = false): String { + private fun getDefaultTemplate( + isKotlin: Boolean = false, + isMultiplatform: Boolean = false, + ): String { if (isMultiplatform) { return MultiplatformKtsTemplate.data } diff --git a/src/main/kotlin/com/joetr/modulemaker/data/ToProjectFile.kt b/src/main/kotlin/com/joetr/modulemaker/data/ToProjectFile.kt index d053266..a57aa4f 100644 --- a/src/main/kotlin/com/joetr/modulemaker/data/ToProjectFile.kt +++ b/src/main/kotlin/com/joetr/modulemaker/data/ToProjectFile.kt @@ -1,24 +1,26 @@ package com.joetr.modulemaker.data -fun java.io.File.toProjectFile(): File = object : File { - override val name: String - get() = this@toProjectFile.name +fun java.io.File.toProjectFile(): File = + object : File { + override val name: String + get() = this@toProjectFile.name - override val absolutePath: String - get() = this@toProjectFile.absolutePath + override val absolutePath: String + get() = this@toProjectFile.absolutePath - override val isDirectory: Boolean - get() = this@toProjectFile.isDirectory + override val isDirectory: Boolean + get() = this@toProjectFile.isDirectory - override val children: List - get() = this@toProjectFile - .listFiles { _, name -> !name.startsWith(".") } - .orEmpty() - .map { it.toProjectFile() } + override val children: List + get() = + this@toProjectFile + .listFiles { _, name -> !name.startsWith(".") } + .orEmpty() + .map { it.toProjectFile() } - private val numberOfFiles - get() = listFiles()?.size ?: 0 + private val numberOfFiles + get() = listFiles()?.size ?: 0 - override val hasChildren: Boolean - get() = isDirectory && numberOfFiles > 0 -} + override val hasChildren: Boolean + get() = isDirectory && numberOfFiles > 0 + } diff --git a/src/main/kotlin/com/joetr/modulemaker/data/analytics/ModuleCreationAnalytics.kt b/src/main/kotlin/com/joetr/modulemaker/data/analytics/ModuleCreationAnalytics.kt index 2f57d35..c788e71 100644 --- a/src/main/kotlin/com/joetr/modulemaker/data/analytics/ModuleCreationAnalytics.kt +++ b/src/main/kotlin/com/joetr/modulemaker/data/analytics/ModuleCreationAnalytics.kt @@ -9,5 +9,5 @@ data class ModuleCreationAnalytics( val addGitIgnore: Boolean, val addReadme: Boolean, val gradleNameToFollow: Boolean, - val useKts: Boolean + val useKts: Boolean, ) diff --git a/src/main/kotlin/com/joetr/modulemaker/data/analytics/ModuleCreationErrorAnalytics.kt b/src/main/kotlin/com/joetr/modulemaker/data/analytics/ModuleCreationErrorAnalytics.kt index e66afdc..66a6a9f 100644 --- a/src/main/kotlin/com/joetr/modulemaker/data/analytics/ModuleCreationErrorAnalytics.kt +++ b/src/main/kotlin/com/joetr/modulemaker/data/analytics/ModuleCreationErrorAnalytics.kt @@ -4,5 +4,5 @@ import kotlinx.serialization.Serializable @Serializable data class ModuleCreationErrorAnalytics( - val message: String + val message: String, ) diff --git a/src/main/kotlin/com/joetr/modulemaker/file/FileWriter.kt b/src/main/kotlin/com/joetr/modulemaker/file/FileWriter.kt index 20b300b..60a3533 100644 --- a/src/main/kotlin/com/joetr/modulemaker/file/FileWriter.kt +++ b/src/main/kotlin/com/joetr/modulemaker/file/FileWriter.kt @@ -21,12 +21,12 @@ const val IMPL_KEY = "key" * This class is responsible for writing files into the project */ class FileWriter( - private val preferenceService: PreferenceService + private val preferenceService: PreferenceService, ) { - - private val templateWriter = TemplateWriter( - preferenceService = preferenceService - ) + private val templateWriter = + TemplateWriter( + preferenceService = preferenceService, + ) fun createModule( settingsGradleFile: File, @@ -44,7 +44,7 @@ class FileWriter( rootPathString: String, previewMode: Boolean = false, platformType: String = ANDROID, - sourceSets: List = emptyList() + sourceSets: List = emptyList(), ): List { val filesCreated = mutableListOf() @@ -73,37 +73,39 @@ class FileWriter( modulePathAsString = modulePathAsString, settingsGradleFile = settingsGradleFile, enhancedModuleCreationStrategy = enhancedModuleCreationStrategy, - showErrorDialog = showErrorDialog + showErrorDialog = showErrorDialog, ) } if (enhancedModuleCreationStrategy) { - filesCreated += createEnhancedModuleStructure( - moduleFile = moduleFile, - moduleType = moduleType, - useKtsBuildFile = useKtsBuildFile, - gradleFileFollowModule = gradleFileFollowModule, - packageName = packageName, - addReadme = addReadme, - addGitIgnore = addGitIgnore, - previewMode = previewMode, - platformType = platformType, - sourceSets = sourceSets - ) + filesCreated += + createEnhancedModuleStructure( + moduleFile = moduleFile, + moduleType = moduleType, + useKtsBuildFile = useKtsBuildFile, + gradleFileFollowModule = gradleFileFollowModule, + packageName = packageName, + addReadme = addReadme, + addGitIgnore = addGitIgnore, + previewMode = previewMode, + platformType = platformType, + sourceSets = sourceSets, + ) } else { - filesCreated += createDefaultModuleStructure( - moduleFile = moduleFile, - moduleName = moduleName, - moduleType = moduleType, - useKtsBuildFile = useKtsBuildFile, - gradleFileFollowModule = gradleFileFollowModule, - packageName = packageName, - addReadme = addReadme, - addGitIgnore = addGitIgnore, - previewMode = previewMode, - platformType = platformType, - sourceSets = sourceSets - ) + filesCreated += + createDefaultModuleStructure( + moduleFile = moduleFile, + moduleName = moduleName, + moduleType = moduleType, + useKtsBuildFile = useKtsBuildFile, + gradleFileFollowModule = gradleFileFollowModule, + packageName = packageName, + addReadme = addReadme, + addGitIgnore = addGitIgnore, + previewMode = previewMode, + platformType = platformType, + sourceSets = sourceSets, + ) } if (previewMode.not()) { @@ -123,7 +125,7 @@ class FileWriter( addGitIgnore: Boolean, previewMode: Boolean, platformType: String, - sourceSets: List + sourceSets: List, ): List { val filesCreated = mutableListOf() @@ -133,33 +135,41 @@ class FileWriter( mkdirs() } // create the gradle file - filesCreated += templateWriter.createGradleFile( - moduleFile = this, - moduleName = moduleFile.path.split(File.separator).toList().last().plus("-") - .plus(preferenceService.preferenceState.glueModuleName), - moduleType = moduleType, - useKtsBuildFile = useKtsBuildFile, - defaultKey = GLUE_KEY, - gradleFileFollowModule = gradleFileFollowModule, - packageName = packageName.plus(".${preferenceService.preferenceState.glueModuleName}"), - previewMode = previewMode, - platformType = platformType - ) + filesCreated += + templateWriter.createGradleFile( + moduleFile = this, + moduleName = + moduleFile.path + .split(File.separator) + .toList() + .last() + .plus("-") + .plus(preferenceService.preferenceState.glueModuleName), + moduleType = moduleType, + useKtsBuildFile = useKtsBuildFile, + defaultKey = GLUE_KEY, + gradleFileFollowModule = gradleFileFollowModule, + packageName = packageName.plus(".${preferenceService.preferenceState.glueModuleName}"), + previewMode = previewMode, + platformType = platformType, + ) // create default packages - filesCreated += createDefaultPackages( - moduleFile = this, - packageName = packageName.plus(".${preferenceService.preferenceState.glueModuleName}"), - previewMode = previewMode, - platformType = platformType, - sourceSets = sourceSets - ) - - if (addGitIgnore) { - filesCreated += createGitIgnore( + filesCreated += + createDefaultPackages( moduleFile = this, - previewMode = previewMode + packageName = packageName.plus(".${preferenceService.preferenceState.glueModuleName}"), + previewMode = previewMode, + platformType = platformType, + sourceSets = sourceSets, ) + + if (addGitIgnore) { + filesCreated += + createGitIgnore( + moduleFile = this, + previewMode = previewMode, + ) } } @@ -167,33 +177,41 @@ class FileWriter( if (previewMode.not()) { mkdirs() } - filesCreated += templateWriter.createGradleFile( - moduleFile = this, - moduleName = moduleFile.path.split(File.separator).toList().last().plus("-") - .plus(preferenceService.preferenceState.implModuleName), - moduleType = moduleType, - useKtsBuildFile = useKtsBuildFile, - defaultKey = IMPL_KEY, - gradleFileFollowModule = gradleFileFollowModule, - packageName = packageName.plus(".${preferenceService.preferenceState.implModuleName}"), - previewMode = previewMode, - platformType = platformType - ) + filesCreated += + templateWriter.createGradleFile( + moduleFile = this, + moduleName = + moduleFile.path + .split(File.separator) + .toList() + .last() + .plus("-") + .plus(preferenceService.preferenceState.implModuleName), + moduleType = moduleType, + useKtsBuildFile = useKtsBuildFile, + defaultKey = IMPL_KEY, + gradleFileFollowModule = gradleFileFollowModule, + packageName = packageName.plus(".${preferenceService.preferenceState.implModuleName}"), + previewMode = previewMode, + platformType = platformType, + ) // create default packages - filesCreated += createDefaultPackages( - moduleFile = this, - packageName = packageName.plus(".${preferenceService.preferenceState.implModuleName}"), - previewMode = previewMode, - platformType = platformType, - sourceSets = sourceSets - ) - - if (addGitIgnore) { - filesCreated += createGitIgnore( + filesCreated += + createDefaultPackages( moduleFile = this, - previewMode = previewMode + packageName = packageName.plus(".${preferenceService.preferenceState.implModuleName}"), + previewMode = previewMode, + platformType = platformType, + sourceSets = sourceSets, ) + + if (addGitIgnore) { + filesCreated += + createGitIgnore( + moduleFile = this, + previewMode = previewMode, + ) } } @@ -201,42 +219,51 @@ class FileWriter( if (previewMode.not()) { mkdirs() } - filesCreated += templateWriter.createGradleFile( - moduleFile = this, - moduleName = moduleFile.path.split(File.separator).toList().last().plus("-") - .plus(preferenceService.preferenceState.apiModuleName), - moduleType = moduleType, - useKtsBuildFile = useKtsBuildFile, - defaultKey = API_KEY, - gradleFileFollowModule = gradleFileFollowModule, - packageName = packageName.plus(".${preferenceService.preferenceState.apiModuleName}"), - previewMode = previewMode, - platformType = platformType - ) + filesCreated += + templateWriter.createGradleFile( + moduleFile = this, + moduleName = + moduleFile.path + .split(File.separator) + .toList() + .last() + .plus("-") + .plus(preferenceService.preferenceState.apiModuleName), + moduleType = moduleType, + useKtsBuildFile = useKtsBuildFile, + defaultKey = API_KEY, + gradleFileFollowModule = gradleFileFollowModule, + packageName = packageName.plus(".${preferenceService.preferenceState.apiModuleName}"), + previewMode = previewMode, + platformType = platformType, + ) if (addReadme) { // create readme file for the api module - filesCreated += templateWriter.createReadmeFile( - moduleFile = this, - moduleName = preferenceService.preferenceState.apiModuleName, - previewMode = previewMode - ) + filesCreated += + templateWriter.createReadmeFile( + moduleFile = this, + moduleName = preferenceService.preferenceState.apiModuleName, + previewMode = previewMode, + ) } // create default packages - filesCreated += createDefaultPackages( - moduleFile = this, - packageName = packageName.plus(".${preferenceService.preferenceState.apiModuleName}"), - previewMode = previewMode, - platformType = platformType, - sourceSets = sourceSets - ) - - if (addGitIgnore) { - filesCreated += createGitIgnore( + filesCreated += + createDefaultPackages( moduleFile = this, - previewMode = previewMode + packageName = packageName.plus(".${preferenceService.preferenceState.apiModuleName}"), + previewMode = previewMode, + platformType = platformType, + sourceSets = sourceSets, ) + + if (addGitIgnore) { + filesCreated += + createGitIgnore( + moduleFile = this, + previewMode = previewMode, + ) } } @@ -254,52 +281,59 @@ class FileWriter( addGitIgnore: Boolean, previewMode: Boolean, platformType: String, - sourceSets: List + sourceSets: List, ): List { val filesCreated = mutableListOf() // create gradle files - filesCreated += templateWriter.createGradleFile( - moduleFile = moduleFile, - moduleName = moduleName, - moduleType = moduleType, - useKtsBuildFile = useKtsBuildFile, - defaultKey = null, - gradleFileFollowModule = gradleFileFollowModule, - packageName = packageName, - previewMode = previewMode, - platformType = platformType - ) - - if (addReadme) { - // create readme file - filesCreated += templateWriter.createReadmeFile( + filesCreated += + templateWriter.createGradleFile( moduleFile = moduleFile, moduleName = moduleName, - previewMode = previewMode + moduleType = moduleType, + useKtsBuildFile = useKtsBuildFile, + defaultKey = null, + gradleFileFollowModule = gradleFileFollowModule, + packageName = packageName, + previewMode = previewMode, + platformType = platformType, ) + + if (addReadme) { + // create readme file + filesCreated += + templateWriter.createReadmeFile( + moduleFile = moduleFile, + moduleName = moduleName, + previewMode = previewMode, + ) } // create default packages - filesCreated += createDefaultPackages( - moduleFile = moduleFile, - packageName = packageName, - previewMode = previewMode, - platformType = platformType, - sourceSets = sourceSets - ) - - if (addGitIgnore) { - filesCreated += createGitIgnore( + filesCreated += + createDefaultPackages( moduleFile = moduleFile, - previewMode = previewMode + packageName = packageName, + previewMode = previewMode, + platformType = platformType, + sourceSets = sourceSets, ) + + if (addGitIgnore) { + filesCreated += + createGitIgnore( + moduleFile = moduleFile, + previewMode = previewMode, + ) } return filesCreated } - private fun createGitIgnore(moduleFile: File, previewMode: Boolean): List { + private fun createGitIgnore( + moduleFile: File, + previewMode: Boolean, + ): List { val gitignoreFile = Paths.get(moduleFile.absolutePath).toFile() val filePath = Paths.get(gitignoreFile.absolutePath, ".gitignore").toFile() @@ -308,9 +342,10 @@ class FileWriter( val writer: Writer = java.io.FileWriter(filePath) val customPreferences = preferenceService.preferenceState.gitignoreTemplate - val dataToWrite = customPreferences.ifEmpty { - GitIgnoreTemplate.data - } + val dataToWrite = + customPreferences.ifEmpty { + GitIgnoreTemplate.data + } writer.write(dataToWrite) writer.flush() @@ -330,7 +365,7 @@ class FileWriter( packageName: String, previewMode: Boolean, platformType: String, - sourceSets: List + sourceSets: List, ): List { fun makePath(srcPath: File): File { val packagePath = Paths.get(srcPath.path, packageName.split(".").joinToString(File.separator)).toFile() @@ -344,21 +379,22 @@ class FileWriter( return packagePath } // create src/main - val packagePaths = if (platformType == ANDROID) { - val srcPath = Paths.get(moduleFile.absolutePath, "src/main/kotlin").toFile() - val packagePath = makePath(srcPath) - listOf(packagePath) - } else if (platformType == MULTIPLATFORM) { - val paths = mutableListOf() - sourceSets.forEach { - val srcPath = Paths.get(moduleFile.absolutePath, "src/$it/kotlin").toFile() + val packagePaths = + if (platformType == ANDROID) { + val srcPath = Paths.get(moduleFile.absolutePath, "src/main/kotlin").toFile() val packagePath = makePath(srcPath) - paths.add(packagePath) + listOf(packagePath) + } else if (platformType == MULTIPLATFORM) { + val paths = mutableListOf() + sourceSets.forEach { + val srcPath = Paths.get(moduleFile.absolutePath, "src/$it/kotlin").toFile() + val packagePath = makePath(srcPath) + paths.add(packagePath) + } + paths + } else { + throw IllegalArgumentException("Unknown platform type $platformType") } - paths - } else { - throw IllegalArgumentException("Unknown platform type $platformType") - } return packagePaths } @@ -373,53 +409,60 @@ class FileWriter( modulePathAsString: String, enhancedModuleCreationStrategy: Boolean, showErrorDialog: (String) -> Unit, - rootPathAsString: String + rootPathAsString: String, ) { val settingsFile = Files.readAllLines(Paths.get(settingsGradleFile.toURI())) // if the user has non-empty include keyword set, only check for that. - val includeKeywords = if (preferenceService.preferenceState.includeProjectKeyword.isNotEmpty()) { - listOf(preferenceService.preferenceState.includeProjectKeyword) - } else { - listOf( - "includeProject", - "includeBuild", - "include" - ) - } + val includeKeywords = + if (preferenceService.preferenceState.includeProjectKeyword.isNotEmpty()) { + listOf(preferenceService.preferenceState.includeProjectKeyword) + } else { + listOf( + "includeProject", + "includeBuild", + "include", + ) + } val twoParametersPattern = """\(".+", ".+"\)""".toRegex() - val lastNonEmptyLineInSettingsGradleFile = settingsFile.lastOrNull { settingsFileLine -> - settingsFileLine.isNotEmpty() && includeKeywords.any { - settingsFileLine.contains(it) + val lastNonEmptyLineInSettingsGradleFile = + settingsFile.lastOrNull { settingsFileLine -> + settingsFileLine.isNotEmpty() && + includeKeywords.any { + settingsFileLine.contains(it) + } + } + val projectIncludeKeyword = + includeKeywords.firstOrNull { includeKeyword -> + lastNonEmptyLineInSettingsGradleFile?.contains(includeKeyword) ?: false } - } - val projectIncludeKeyword = includeKeywords.firstOrNull { includeKeyword -> - lastNonEmptyLineInSettingsGradleFile?.contains(includeKeyword) ?: false - } if (projectIncludeKeyword == null) { showErrorDialog("Could not find any include statements in settings.gradle(.kts) file") return } - val usesTwoParameters = settingsFile.any { line -> - twoParametersPattern.containsMatchIn(line) - } + val usesTwoParameters = + settingsFile.any { line -> + twoParametersPattern.containsMatchIn(line) + } // get the last line numbers for an include statement - val lastLineNumberOfFirstIncludeProjectStatement = settingsFile.indexOfLast { - settingsFileContainsSpecialIncludeKeyword(it, projectIncludeKeyword) - } + val lastLineNumberOfFirstIncludeProjectStatement = + settingsFile.indexOfLast { + settingsFileContainsSpecialIncludeKeyword(it, projectIncludeKeyword) + } // traverse backwards from there to find the first instance var tempIndexForSettingsFile = lastLineNumberOfFirstIncludeProjectStatement while (tempIndexForSettingsFile >= 0) { val currentLine = settingsFile[tempIndexForSettingsFile] - if (currentLine.trim().isEmpty() || settingsFileContainsSpecialIncludeKeyword( + if (currentLine.trim().isEmpty() || + settingsFileContainsSpecialIncludeKeyword( currentLine, - projectIncludeKeyword + projectIncludeKeyword, ) ) { tempIndexForSettingsFile-- @@ -437,27 +480,29 @@ class FileWriter( } // sub list them and create a new list so we aren't modifying the original - val includeProjectStatements = settingsFile.subList( - firstLineNumberOfFirstIncludeProjectStatement, - lastLineNumberOfFirstIncludeProjectStatement + 1 - ) - .filter { - it.isNotEmpty() - } - .toMutableList() - - val textToWrite = constructTextToWrite( - enhancedModuleCreationStrategy = enhancedModuleCreationStrategy, - usesTwoParameters = usesTwoParameters, - projectIncludeKeyword = projectIncludeKeyword, - modulePathAsString = modulePathAsString, - rootPathAsString = rootPathAsString - ) + val includeProjectStatements = + settingsFile + .subList( + firstLineNumberOfFirstIncludeProjectStatement, + lastLineNumberOfFirstIncludeProjectStatement + 1, + ).filter { + it.isNotEmpty() + }.toMutableList() + + val textToWrite = + constructTextToWrite( + enhancedModuleCreationStrategy = enhancedModuleCreationStrategy, + usesTwoParameters = usesTwoParameters, + projectIncludeKeyword = projectIncludeKeyword, + modulePathAsString = modulePathAsString, + rootPathAsString = rootPathAsString, + ) // the spot we want to insert it is the first line we find that is after it alphabetically - val insertionIndex = includeProjectStatements.indexOfFirst { - it.isNotEmpty() && it.lowercase() >= textToWrite.lowercase() - } + val insertionIndex = + includeProjectStatements.indexOfFirst { + it.isNotEmpty() && it.lowercase() >= textToWrite.lowercase() + } if (insertionIndex < 0) { /** @@ -473,13 +518,16 @@ class FileWriter( * in the latter case, we don't really support that, but we also don't want to add it after the include statement to break * the current include, so we insert it just before */ - val offsetAmount = if (includeProjectStatements.size == 1 && includeProjectStatements.first() - .doesNotContainModule(projectIncludeKeyword) - ) { - 0 - } else { - 1 - } + val offsetAmount = + if (includeProjectStatements.size == 1 && + includeProjectStatements + .first() + .doesNotContainModule(projectIncludeKeyword) + ) { + 0 + } else { + 1 + } // insert it at the end as nothing is past it settingsFile.add(lastLineNumberOfFirstIncludeProjectStatement + offsetAmount, textToWrite) } else { @@ -492,38 +540,39 @@ class FileWriter( private fun settingsFileContainsSpecialIncludeKeyword( stringToCheck: String, - projectIncludeKeyword: String - ): Boolean { - return stringToCheck.contains("$projectIncludeKeyword(\"") || + projectIncludeKeyword: String, + ): Boolean = + stringToCheck.contains("$projectIncludeKeyword(\"") || stringToCheck.contains("$projectIncludeKeyword('") || stringToCheck.contains("$projectIncludeKeyword(") || stringToCheck.contains("$projectIncludeKeyword \"") || stringToCheck.contains("$projectIncludeKeyword '") - } private fun constructTextToWrite( enhancedModuleCreationStrategy: Boolean, usesTwoParameters: Boolean, projectIncludeKeyword: String, modulePathAsString: String, - rootPathAsString: String + rootPathAsString: String, ): String { fun buildText(path: String): String { - val parametersString = if (usesTwoParameters) { - val filePath = "$rootPathAsString${path.replace(":", File.separator)}".removePrefix("/") - "\"$path\", \"$filePath\"" - } else { - "\"$path\"" - } + val parametersString = + if (usesTwoParameters) { + val filePath = "$rootPathAsString${path.replace(":", File.separator)}".removePrefix("/") + "\"$path\", \"$filePath\"" + } else { + "\"$path\"" + } return "$projectIncludeKeyword($parametersString)" } return if (enhancedModuleCreationStrategy) { - val paths = arrayOf( - "$modulePathAsString:${preferenceService.preferenceState.apiModuleName}", - "$modulePathAsString:${preferenceService.preferenceState.implModuleName}", - "$modulePathAsString:${preferenceService.preferenceState.glueModuleName}" - ) + val paths = + arrayOf( + "$modulePathAsString:${preferenceService.preferenceState.apiModuleName}", + "$modulePathAsString:${preferenceService.preferenceState.implModuleName}", + "$modulePathAsString:${preferenceService.preferenceState.glueModuleName}", + ) paths.joinToString("\n") { buildText(it) } } else { buildText(modulePathAsString) @@ -531,6 +580,4 @@ class FileWriter( } } -private fun String.doesNotContainModule(includeKeyword: String): Boolean { - return this.replace(" ", "").replace("(", "") == includeKeyword -} +private fun String.doesNotContainModule(includeKeyword: String): Boolean = this.replace(" ", "").replace("(", "") == includeKeyword diff --git a/src/main/kotlin/com/joetr/modulemaker/persistence/PreferenceServiceImpl.kt b/src/main/kotlin/com/joetr/modulemaker/persistence/PreferenceServiceImpl.kt index fe31089..7dd9e45 100644 --- a/src/main/kotlin/com/joetr/modulemaker/persistence/PreferenceServiceImpl.kt +++ b/src/main/kotlin/com/joetr/modulemaker/persistence/PreferenceServiceImpl.kt @@ -20,8 +20,9 @@ import kotlinx.serialization.Serializable import org.jetbrains.annotations.Nullable @State(name = "PreferenceService", storages = [(Storage("module_maker_preferences.xml"))]) -class PreferenceServiceImpl : PersistentStateComponent, PreferenceService { - +class PreferenceServiceImpl : + PersistentStateComponent, + PreferenceService { private var state = State() override var preferenceState: State @@ -31,16 +32,13 @@ class PreferenceServiceImpl : PersistentStateComponent { try { // Build the data-model @@ -47,70 +47,99 @@ class TemplateWriter( data["packageName"] = packageName // load gradle file from template folder - val gradleTemplate: Template = when (moduleType) { - KOTLIN -> { - val customPreferences = getPreferenceFromKey(defaultKey, if (platformType == MULTIPLATFORM) MULTIPLATFORM else KOTLIN_KEY) - if (customPreferences.isNotEmpty()) { - Template( - null, - customPreferences, - cfg - ) - } else { - val template = if (useKtsBuildFile) { - KotlinModuleKtsTemplate.data + val gradleTemplate: Template = + when (moduleType) { + KOTLIN -> { + val customPreferences = + getPreferenceFromKey( + defaultKey, + if (platformType == + MULTIPLATFORM + ) { + MULTIPLATFORM + } else { + KOTLIN_KEY + }, + ) + if (customPreferences.isNotEmpty()) { + Template( + null, + customPreferences, + cfg, + ) } else { - KotlinModuleTemplate.data + val template = + if (useKtsBuildFile) { + KotlinModuleKtsTemplate.data + } else { + KotlinModuleTemplate.data + } + Template( + null, + template, + cfg, + ) } - Template( - null, - template, - cfg - ) } - } - ANDROID -> { - val customPreferences = getPreferenceFromKey(defaultKey, if (platformType == MULTIPLATFORM) MULTIPLATFORM else ANDROID_KEY) - - if (customPreferences.isNotEmpty()) { - Template( - null, - customPreferences, - cfg - ) - } else { - val template = if (platformType == ANDROID) { - if (useKtsBuildFile) { - AndroidModuleKtsTemplate.data - } else { - AndroidModuleTemplate.data - } - } else if (platformType == MULTIPLATFORM) { - MultiplatformKtsTemplate.data + + ANDROID -> { + val customPreferences = + getPreferenceFromKey( + defaultKey, + if (platformType == + MULTIPLATFORM + ) { + MULTIPLATFORM + } else { + ANDROID_KEY + }, + ) + + if (customPreferences.isNotEmpty()) { + Template( + null, + customPreferences, + cfg, + ) } else { - throw IllegalArgumentException("Unknown platform type $platformType") + val template = + if (platformType == ANDROID) { + if (useKtsBuildFile) { + AndroidModuleKtsTemplate.data + } else { + AndroidModuleTemplate.data + } + } else if (platformType == MULTIPLATFORM) { + MultiplatformKtsTemplate.data + } else { + throw IllegalArgumentException("Unknown platform type $platformType") + } + Template( + null, + template, + cfg, + ) } - Template( - null, - template, - cfg - ) + } + + else -> { + throw IllegalArgumentException("Unknown module type") } } - else -> throw IllegalArgumentException("Unknown module type") - } // File output - val extension = if (useKtsBuildFile) { - ".gradle.kts" - } else { - ".gradle" - } - val fileName = if (gradleFileFollowModule) { - moduleName.plus(extension) - } else { - "build".plus(extension) - } + val extension = + if (useKtsBuildFile) { + ".gradle.kts" + } else { + ".gradle" + } + val fileName = + if (gradleFileFollowModule) { + moduleName.plus(extension) + } else { + "build".plus(extension) + } val filePath = Paths.get(moduleFile.absolutePath, fileName).toFile() @@ -131,13 +160,18 @@ class TemplateWriter( return emptyList() } - fun createReadmeFile(moduleFile: File, moduleName: String, previewMode: Boolean): List { + fun createReadmeFile( + moduleFile: File, + moduleName: String, + previewMode: Boolean, + ): List { try { - val manifestTemplate = Template( - null, - ModuleReadMeTemplate.data, - cfg - ) + val manifestTemplate = + Template( + null, + ModuleReadMeTemplate.data, + cfg, + ) val data: MutableMap = HashMap() @@ -168,8 +202,11 @@ class TemplateWriter( return emptyList() } - private fun getPreferenceFromKey(key: String?, fallback: String): String { - return when (key ?: fallback) { + private fun getPreferenceFromKey( + key: String?, + fallback: String, + ): String = + when (key ?: fallback) { IMPL_KEY -> preferenceService.preferenceState.implTemplate API_KEY -> preferenceService.preferenceState.apiTemplate GLUE_KEY -> preferenceService.preferenceState.glueTemplate @@ -178,5 +215,4 @@ class TemplateWriter( KOTLIN_KEY -> preferenceService.preferenceState.kotlinTemplate else -> "" } - } } diff --git a/src/main/kotlin/com/joetr/modulemaker/ui/LabelledCheckbox.kt b/src/main/kotlin/com/joetr/modulemaker/ui/LabelledCheckbox.kt index 7d502b3..d9c931e 100644 --- a/src/main/kotlin/com/joetr/modulemaker/ui/LabelledCheckbox.kt +++ b/src/main/kotlin/com/joetr/modulemaker/ui/LabelledCheckbox.kt @@ -16,21 +16,23 @@ fun LabelledCheckbox( modifier: Modifier = Modifier, label: String, checked: Boolean, - onCheckedChange: (Boolean) -> Unit + onCheckedChange: (Boolean) -> Unit, ) { Row( - modifier = modifier.clickable { - onCheckedChange(checked.not()) - }.padding(end = 8.dp), + modifier = + modifier + .clickable { + onCheckedChange(checked.not()) + }.padding(end = 8.dp), horizontalArrangement = Arrangement.Start, - verticalAlignment = Alignment.CenterVertically + verticalAlignment = Alignment.CenterVertically, ) { Checkbox( checked = checked, onCheckedChange = { onCheckedChange(it) }, - enabled = true + enabled = true, ) Text(text = label) } diff --git a/src/main/kotlin/com/joetr/modulemaker/ui/file/FileTree.kt b/src/main/kotlin/com/joetr/modulemaker/ui/file/FileTree.kt index 8c0662c..c179e49 100644 --- a/src/main/kotlin/com/joetr/modulemaker/ui/file/FileTree.kt +++ b/src/main/kotlin/com/joetr/modulemaker/ui/file/FileTree.kt @@ -7,54 +7,70 @@ import com.joetr.modulemaker.data.File class ExpandableFile( val file: File, - val level: Int + val level: Int, ) { var children: List by mutableStateOf(emptyList()) val canExpand: Boolean get() = file.hasChildren fun toggleExpanded() { - children = if (children.isEmpty()) { - file.children - .map { ExpandableFile(it, level + 1) } - .sortedWith(compareBy({ it.file.isDirectory }, { it.file.name })) - .sortedBy { !it.file.isDirectory } - } else { - emptyList() - } + children = + if (children.isEmpty()) { + file.children + .map { ExpandableFile(it, level + 1) } + .sortedWith(compareBy({ it.file.isDirectory }, { it.file.name })) + .sortedBy { !it.file.isDirectory } + } else { + emptyList() + } } } -class FileTree(root: File) { - - private val expandableRoot = ExpandableFile(root, 0).apply { - toggleExpanded() - } +class FileTree( + root: File, +) { + private val expandableRoot = + ExpandableFile(root, 0).apply { + toggleExpanded() + } val items: List get() = expandableRoot.toItems() inner class Item( - internal val file: ExpandableFile + internal val file: ExpandableFile, ) { val name: String get() = file.file.name val level: Int get() = file.level val type: ItemType - get() = if (file.file.isDirectory) { - ItemType.Folder(isExpanded = file.children.isNotEmpty(), canExpand = file.canExpand) - } else { - ItemType.File(ext = file.file.name.substringAfterLast(".").lowercase()) - } + get() = + if (file.file.isDirectory) { + ItemType.Folder(isExpanded = file.children.isNotEmpty(), canExpand = file.canExpand) + } else { + ItemType.File( + ext = + file.file.name + .substringAfterLast(".") + .lowercase(), + ) + } - fun open() = when (type) { - is ItemType.Folder -> file.toggleExpanded() - is ItemType.File -> Unit - } + fun open() = + when (type) { + is ItemType.Folder -> file.toggleExpanded() + is ItemType.File -> Unit + } } sealed class ItemType { - class Folder(val isExpanded: Boolean, val canExpand: Boolean) : ItemType() - class File(val ext: String) : ItemType() + class Folder( + val isExpanded: Boolean, + val canExpand: Boolean, + ) : ItemType() + + class File( + val ext: String, + ) : ItemType() } private fun ExpandableFile.toItems(): List { diff --git a/src/main/kotlin/com/joetr/modulemaker/ui/file/FileTreeView.kt b/src/main/kotlin/com/joetr/modulemaker/ui/file/FileTreeView.kt index 6d0570f..f9eabc3 100644 --- a/src/main/kotlin/com/joetr/modulemaker/ui/file/FileTreeView.kt +++ b/src/main/kotlin/com/joetr/modulemaker/ui/file/FileTreeView.kt @@ -39,8 +39,13 @@ import org.jetbrains.jewel.ui.component.Text import org.jetbrains.jewel.ui.icon.IntelliJIconKey @Composable -fun FileTreeView(model: FileTree, height: Dp, onClick: (ExpandableFile) -> Unit, modifier: Modifier) = Box( - modifier = modifier.height(height) +fun FileTreeView( + model: FileTree, + height: Dp, + onClick: (ExpandableFile) -> Unit, + modifier: Modifier, +) = Box( + modifier = modifier.height(height), ) { with(LocalDensity.current) { Box { @@ -49,7 +54,7 @@ fun FileTreeView(model: FileTree, height: Dp, onClick: (ExpandableFile) -> Unit, LazyColumn( modifier = Modifier.fillMaxSize().horizontalScroll(scrollState), - state = lazyListState + state = lazyListState, ) { items(model.items.size) { FileTreeItemView( @@ -60,19 +65,19 @@ fun FileTreeView(model: FileTree, height: Dp, onClick: (ExpandableFile) -> Unit, // if it's the last one and the scrollbar is showing showBottomPadding = it == model.items.size - 1 && (lazyListState.canScrollForward || lazyListState.canScrollBackward), // if the scrollbar is showing - showEndPadding = scrollState.canScrollForward || scrollState.canScrollBackward + showEndPadding = scrollState.canScrollForward || scrollState.canScrollBackward, ) } } VerticalScrollbar( rememberScrollbarAdapter(lazyListState), - Modifier.align(Alignment.CenterEnd) + Modifier.align(Alignment.CenterEnd), ) HorizontalScrollbar( rememberScrollbarAdapter(scrollState), - Modifier.align(Alignment.BottomStart) + Modifier.align(Alignment.BottomStart), ) } } @@ -85,10 +90,10 @@ private fun FileTreeItemView( model: FileTree.Item, onClick: (ExpandableFile) -> Unit, showBottomPadding: Boolean, - showEndPadding: Boolean -) = - Row( - modifier = Modifier + showEndPadding: Boolean, +) = Row( + modifier = + Modifier .wrapContentHeight() .clickable { model.open() @@ -100,117 +105,158 @@ private fun FileTreeItemView( .padding( start = 24.dp * model.level, end = if (showEndPadding) 8.dp else 0.dp, - bottom = if (showBottomPadding) 8.dp else 0.dp - ) - .height(height) - .fillMaxWidth() - ) { - val interactionSource = remember { MutableInteractionSource() } - val active by interactionSource.collectIsHoveredAsState() - - FileItemIcon(Modifier.align(Alignment.CenterVertically), model) - Text( - text = model.name, - color = if (active) JewelTheme.contentColor.copy(alpha = 0.60f) else JewelTheme.contentColor, - modifier = Modifier + bottom = if (showBottomPadding) 8.dp else 0.dp, + ).height(height) + .fillMaxWidth(), +) { + val interactionSource = remember { MutableInteractionSource() } + val active by interactionSource.collectIsHoveredAsState() + + FileItemIcon(Modifier.align(Alignment.CenterVertically), model) + Text( + text = model.name, + color = if (active) JewelTheme.contentColor.copy(alpha = 0.60f) else JewelTheme.contentColor, + modifier = + Modifier .align(Alignment.CenterVertically) .clipToBounds() .hoverable(interactionSource), - softWrap = true, - fontSize = fontSize, - overflow = TextOverflow.Ellipsis, - maxLines = 1 - ) - } + softWrap = true, + fontSize = fontSize, + overflow = TextOverflow.Ellipsis, + maxLines = 1, + ) +} @Composable -private fun FileItemIcon(modifier: Modifier, model: FileTree.Item) = Box(modifier.size(24.dp).padding(4.dp)) { +private fun FileItemIcon( + modifier: Modifier, + model: FileTree.Item, +) = Box(modifier.size(24.dp).padding(4.dp)) { when (val type = model.type) { - is FileTree.ItemType.Folder -> when { - !type.canExpand -> Unit - type.isExpanded -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.General.ArrowDown), - contentDescription = null, - iconClass = AllIcons::class.java - ) + is FileTree.ItemType.Folder -> { + when { + !type.canExpand -> { + // Non-expandable folders have no disclosure icon. + } - else -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.General.ArrowRight), - contentDescription = null, - iconClass = AllIcons::class.java - ) + type.isExpanded -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.General.ArrowDown), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + + else -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.General.ArrowRight), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + } } - is FileTree.ItemType.File -> when (type.ext) { - in sourceCodeFileExtensions -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Java), - contentDescription = null, - iconClass = AllIcons::class.java - ) - "txt" -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Text), - contentDescription = null, - iconClass = AllIcons::class.java - ) - "md" -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Text), - contentDescription = null, - iconClass = AllIcons::class.java - ) - "gitignore" -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.Vcs.Ignore_file), - contentDescription = null, - iconClass = AllIcons::class.java - ) - "gradle" -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Config), - contentDescription = null, - iconClass = AllIcons::class.java - ) - "kts" -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Java), - contentDescription = null, - iconClass = AllIcons::class.java - ) - "properties" -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Properties), - contentDescription = null, - iconClass = AllIcons::class.java - ) - "bat" -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Custom), - contentDescription = null, - iconClass = AllIcons::class.java - ) - else -> Icon( - key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Unknown), - contentDescription = null, - iconClass = AllIcons::class.java - ) + is FileTree.ItemType.File -> { + when (type.ext) { + in sourceCodeFileExtensions -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Java), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + + "txt" -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Text), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + + "md" -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Text), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + + "gitignore" -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.Vcs.Ignore_file), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + + "gradle" -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Config), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + + "kts" -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Java), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + + "properties" -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Properties), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + + "bat" -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Custom), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + + else -> { + Icon( + key = IntelliJIconKey.fromPlatformIcon(AllIcons.FileTypes.Unknown), + contentDescription = null, + iconClass = AllIcons::class.java, + ) + } + } } } } -private val sourceCodeFileExtensions = listOf( - "java", - "kt", - "cpp", - "c", - "h", - "py", - "js", - "html", - "css", - "php", - "rb", - "swift", - "go", - "scala", - "rust", - "dart", - "lua", - "xml", - "pl", - "sh", - "sql" -) +private val sourceCodeFileExtensions = + listOf( + "java", + "kt", + "cpp", + "c", + "h", + "py", + "js", + "html", + "css", + "php", + "rb", + "swift", + "go", + "scala", + "rust", + "dart", + "lua", + "xml", + "pl", + "sh", + "sql", + ) diff --git a/src/main/kotlin/com/joetr/modulemaker/ui/theme/WidgetTheme.kt b/src/main/kotlin/com/joetr/modulemaker/ui/theme/WidgetTheme.kt index dcb88ca..0e561ff 100644 --- a/src/main/kotlin/com/joetr/modulemaker/ui/theme/WidgetTheme.kt +++ b/src/main/kotlin/com/joetr/modulemaker/ui/theme/WidgetTheme.kt @@ -6,7 +6,7 @@ import org.jetbrains.jewel.bridge.theme.SwingBridgeTheme @Composable fun WidgetTheme( darkTheme: Boolean = false, - content: @Composable () -> Unit + content: @Composable () -> Unit, ) { SwingBridgeTheme { content() diff --git a/src/main/kotlin/com/joetr/modulemaker/ui/theme/intellij/SwingColor.kt b/src/main/kotlin/com/joetr/modulemaker/ui/theme/intellij/SwingColor.kt index 77a5e5c..8aaf6f9 100644 --- a/src/main/kotlin/com/joetr/modulemaker/ui/theme/intellij/SwingColor.kt +++ b/src/main/kotlin/com/joetr/modulemaker/ui/theme/intellij/SwingColor.kt @@ -20,14 +20,15 @@ interface SwingColor { fun SwingColor(): SwingColor { val swingColor = remember { SwingColorImpl() } - val messageBus = remember { - ApplicationManager.getApplication().messageBus.connect() - } + val messageBus = + remember { + ApplicationManager.getApplication().messageBus.connect() + } remember(messageBus) { messageBus.subscribe( LafManagerListener.TOPIC, - ThemeChangeListener(swingColor::updateCurrentColors) + ThemeChangeListener(swingColor::updateCurrentColors), ) } @@ -56,6 +57,7 @@ private class SwingColorImpl : SwingColor { } private val AWTColor.asComposeColor: Color get() = Color(red, green, blue, alpha) + private fun getColor(key: String): Color = UIManager.getColor(key).asComposeColor companion object { diff --git a/src/main/kotlin/com/joetr/modulemaker/ui/theme/intellij/ThemeChangeListener.kt b/src/main/kotlin/com/joetr/modulemaker/ui/theme/intellij/ThemeChangeListener.kt index 2dbeffe..a4b9858 100644 --- a/src/main/kotlin/com/joetr/modulemaker/ui/theme/intellij/ThemeChangeListener.kt +++ b/src/main/kotlin/com/joetr/modulemaker/ui/theme/intellij/ThemeChangeListener.kt @@ -4,7 +4,7 @@ import com.intellij.ide.ui.LafManager import com.intellij.ide.ui.LafManagerListener internal class ThemeChangeListener( - val updateColors: () -> Unit + val updateColors: () -> Unit, ) : LafManagerListener { override fun lookAndFeelChanged(source: LafManager) { updateColors() diff --git a/src/test/kotlin/com/joetr/modulemaker/AndroidModuleMakerTest.kt b/src/test/kotlin/com/joetr/modulemaker/AndroidModuleMakerTest.kt index 7874c88..77dcc46 100644 --- a/src/test/kotlin/com/joetr/modulemaker/AndroidModuleMakerTest.kt +++ b/src/test/kotlin/com/joetr/modulemaker/AndroidModuleMakerTest.kt @@ -13,24 +13,25 @@ import org.junit.rules.TemporaryFolder import java.io.File class AndroidModuleMakerTest { - @JvmField @Rule var folder = TemporaryFolder() var testState = PreferenceServiceImpl.Companion.State() - private val fakePreferenceService = object : PreferenceService { - override var preferenceState: PreferenceServiceImpl.Companion.State - get() = testState - set(value) { - testState = value - } - } - - private val fileWriter = FileWriter( - preferenceService = fakePreferenceService - ) + private val fakePreferenceService = + object : PreferenceService { + override var preferenceState: PreferenceServiceImpl.Companion.State + get() = testState + set(value) { + testState = value + } + } + + private val fileWriter = + FileWriter( + preferenceService = fakePreferenceService, + ) private lateinit var settingsGradleFile: File @@ -62,41 +63,40 @@ class AndroidModuleMakerTest { addReadme = true, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert it was added to settings.gradle val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assert( - settingsGradleFileContents.contains("include(\":repository\")") + settingsGradleFileContents.contains("include(\":repository\")"), ) // assert readme was generated assert( // root/repository/README.md - File(folder.root.path + File.separator + modulePathAsFile + File.separator + readmeFile).exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + readmeFile).exists(), ) // assert build.gradle is generated val buildGradleFile = File(folder.root.path + File.separator + modulePathAsFile + File.separator + buildGradleFileName) assert( // root/repository/build.gradle - buildGradleFile.exists() + buildGradleFile.exists(), ) // assert package name is included in build.gradle val buildGradleFileContents = readFromFile(buildGradleFile) assert( buildGradleFileContents.contains( - " namespace = \"$testPackageName\"" - ) + " namespace = \"$testPackageName\"", + ), ) // assert the correct package structure is generated assert( // root/repository/build.gradle - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/main/kotlin/com/joetr/test").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/main/kotlin/com/joetr/test").exists(), ) } @@ -126,22 +126,22 @@ class AndroidModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false + previewMode = false, ) // assert build.gradle is generated val buildGradleFile = File(folder.root.path + File.separator + modulePathAsFile + File.separator + buildGradleFileName) assert( // root/repository/build.gradle - buildGradleFile.exists() + buildGradleFile.exists(), ) // assert package name is included in build.gradle val buildGradleFileContents = readFromFile(buildGradleFile) assert( buildGradleFileContents.contains( - template - ) + template, + ), ) } @@ -150,13 +150,14 @@ class AndroidModuleMakerTest { val modulePath = ":repository" val modulePathAsFile = "repository" - val template = """ + val template = + """ this is a custom template android { namespace = "${'$'}{packageName}" } - """.trimIndent() + """.trimIndent() fakePreferenceService.preferenceState.androidTemplate = template @@ -178,8 +179,7 @@ class AndroidModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert build.gradle file exists and contains the package name when using a custom template @@ -191,8 +191,8 @@ class AndroidModuleMakerTest { assert( buildGradleFileContents.contains( - " namespace = \"$testPackageName\"" - ) + " namespace = \"$testPackageName\"", + ), ) } @@ -219,41 +219,40 @@ class AndroidModuleMakerTest { addReadme = true, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert it was added to settings.gradle val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assert( - settingsGradleFileContents.contains("include(\":repository:database\")") + settingsGradleFileContents.contains("include(\":repository:database\")"), ) // assert readme was generated assert( // root/repository/database/README.md - File(folder.root.path + File.separator + modulePathAsFile + File.separator + readmeFile).exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + readmeFile).exists(), ) // assert build.gradle is generated val buildGradleFile = File(folder.root.path + File.separator + modulePathAsFile + File.separator + buildGradleFileName) assert( // root/repository/database/build.gradle - buildGradleFile.exists() + buildGradleFile.exists(), ) // assert package name is included in build.gradle val buildGradleFileContents = readFromFile(buildGradleFile) assert( buildGradleFileContents.contains( - " namespace = \"$testPackageName\"" - ) + " namespace = \"$testPackageName\"", + ), ) // assert the correct package structure is generated assert( // root/repository/build.gradle - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/main/kotlin/com/joetr/test").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/main/kotlin/com/joetr/test").exists(), ) } @@ -280,15 +279,14 @@ class AndroidModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert build.gradle.kts is generated val buildGradleFile = File(folder.root.path + File.separator + modulePathAsFile + File.separator + buildGradleKtsFileName) assert( // root/repository/database/build.gradle - buildGradleFile.exists() + buildGradleFile.exists(), ) } @@ -315,14 +313,13 @@ class AndroidModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert it was added to settings.gradle val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assert( - settingsGradleFileContents.contains("include(\":repository:database\")") + settingsGradleFileContents.contains("include(\":repository:database\")"), ) } @@ -350,14 +347,13 @@ class AndroidModuleMakerTest { addReadme = true, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert readme exists val buildGradleFile = File(folder.root.path + File.separator + modulePathAsFile + File.separator + "README.md") assert( - buildGradleFile.exists() + buildGradleFile.exists(), ) } @@ -385,14 +381,13 @@ class AndroidModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert readme does not exists val buildGradleFile = File(folder.root.path + File.separator + modulePathAsFile + File.separator + "README.md") assert( - buildGradleFile.exists().not() + buildGradleFile.exists().not(), ) } @@ -419,14 +414,14 @@ class AndroidModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert gitignore was not generated assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + File.separator + ".gitignore").exists() - .not() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + File.separator + ".gitignore") + .exists() + .not(), ) } @@ -453,8 +448,7 @@ class AndroidModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert gitignore was generated and has the expected contents @@ -462,7 +456,7 @@ class AndroidModuleMakerTest { val gitignoreFileContents = readFromFile(file = gitignoreFile) assertEquals( GitIgnoreTemplate.data, - gitignoreFileContents.joinToString("\n") + gitignoreFileContents.joinToString("\n"), ) } @@ -471,9 +465,10 @@ class AndroidModuleMakerTest { val modulePath = ":repository" val modulePathAsFile = "repository" - val template = """ + val template = + """ this is a custom template - """.trimIndent() + """.trimIndent() fakePreferenceService.preferenceState.gitignoreTemplate = template @@ -495,8 +490,7 @@ class AndroidModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert gitignore was generated and has the expected contents @@ -504,7 +498,7 @@ class AndroidModuleMakerTest { val gitignoreFileContents = readFromFile(file = gitignoreFile) assertEquals( template, - gitignoreFileContents.joinToString("\n") + gitignoreFileContents.joinToString("\n"), ) } } diff --git a/src/test/kotlin/com/joetr/modulemaker/EnhancedModuleMakerTest.kt b/src/test/kotlin/com/joetr/modulemaker/EnhancedModuleMakerTest.kt index 6163bec..cf6ba16 100644 --- a/src/test/kotlin/com/joetr/modulemaker/EnhancedModuleMakerTest.kt +++ b/src/test/kotlin/com/joetr/modulemaker/EnhancedModuleMakerTest.kt @@ -13,24 +13,25 @@ import org.junit.rules.TemporaryFolder import java.io.File class EnhancedModuleMakerTest { - @JvmField @Rule var folder = TemporaryFolder() var testState = PreferenceServiceImpl.Companion.State() - private val fakePreferenceService = object : PreferenceService { - override var preferenceState: PreferenceServiceImpl.Companion.State - get() = testState - set(value) { - testState = value - } - } + private val fakePreferenceService = + object : PreferenceService { + override var preferenceState: PreferenceServiceImpl.Companion.State + get() = testState + set(value) { + testState = value + } + } - private val fileWriter = FileWriter( - preferenceService = fakePreferenceService - ) + private val fileWriter = + FileWriter( + preferenceService = fakePreferenceService, + ) private lateinit var settingsGradleFile: File @@ -62,26 +63,25 @@ class EnhancedModuleMakerTest { addReadme = true, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert it was added to settings.gradle val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assert( - settingsGradleFileContents.contains("include(\":repository:api\")") + settingsGradleFileContents.contains("include(\":repository:api\")"), ) assert( - settingsGradleFileContents.contains("include(\":repository:glue\")") + settingsGradleFileContents.contains("include(\":repository:glue\")"), ) assert( - settingsGradleFileContents.contains("include(\":repository:impl\")") + settingsGradleFileContents.contains("include(\":repository:impl\")"), ) // assert readme was generated in the api module assert( // root/repository/api/README.md - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "api" + File.separator + readmeFile).exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "api" + File.separator + readmeFile).exists(), ) // assert build.gradle is generated for all 3 modules @@ -101,29 +101,29 @@ class EnhancedModuleMakerTest { val buildGradleImplFileContents = readFromFile(buildGradleFileImpl) assert( buildGradleApiFileContents.contains( - " namespace = \"$testPackageName.api\"" - ) + " namespace = \"$testPackageName.api\"", + ), ) assert( buildGradleGlueFileContents.contains( - " namespace = \"$testPackageName.glue\"" - ) + " namespace = \"$testPackageName.glue\"", + ), ) assert( buildGradleImplFileContents.contains( - " namespace = \"$testPackageName.impl\"" - ) + " namespace = \"$testPackageName.impl\"", + ), ) // assert the correct package structure is generated assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "api/src/main/kotlin/com/joetr/test/api").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "api/src/main/kotlin/com/joetr/test/api").exists(), ) assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "glue/src/main/kotlin/com/joetr/test/glue").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "glue/src/main/kotlin/com/joetr/test/glue").exists(), ) assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "impl/src/main/kotlin/com/joetr/test/impl").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "impl/src/main/kotlin/com/joetr/test/impl").exists(), ) } @@ -132,13 +132,14 @@ class EnhancedModuleMakerTest { val modulePath = ":repository" val modulePathAsFile = "repository" - val template = """ + val template = + """ this is a custom template android { namespace = "${'$'}{packageName}" } - """.trimIndent() + """.trimIndent() fakePreferenceService.preferenceState.apiTemplate = template fakePreferenceService.preferenceState.glueTemplate = template @@ -162,8 +163,7 @@ class EnhancedModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert build.gradle is generated for all 3 modules @@ -183,18 +183,18 @@ class EnhancedModuleMakerTest { val buildGradleImplFileContents = readFromFile(buildGradleFileImpl) assert( buildGradleApiFileContents.contains( - " namespace = \"$testPackageName.api\"" - ) + " namespace = \"$testPackageName.api\"", + ), ) assert( buildGradleGlueFileContents.contains( - " namespace = \"$testPackageName.glue\"" - ) + " namespace = \"$testPackageName.glue\"", + ), ) assert( buildGradleImplFileContents.contains( - " namespace = \"$testPackageName.impl\"" - ) + " namespace = \"$testPackageName.impl\"", + ), ) } @@ -227,8 +227,7 @@ class EnhancedModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert build.gradle is generated for all 3 modules @@ -248,18 +247,18 @@ class EnhancedModuleMakerTest { val buildGradleImplFileContents = readFromFile(buildGradleFileImpl) assert( buildGradleApiFileContents.contains( - template - ) + template, + ), ) assert( buildGradleGlueFileContents.contains( - template - ) + template, + ), ) assert( buildGradleImplFileContents.contains( - template - ) + template, + ), ) } @@ -286,14 +285,14 @@ class EnhancedModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert readme was not generated in the api module assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "api" + File.separator + readmeFile).exists() - .not() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "api" + File.separator + readmeFile) + .exists() + .not(), ) } @@ -320,22 +319,24 @@ class EnhancedModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert gitignore was not generated in any of the modules module assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "api" + File.separator + ".gitignore").exists() - .not() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "api" + File.separator + ".gitignore") + .exists() + .not(), ) assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "impl" + File.separator + ".gitignore").exists() - .not() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "impl" + File.separator + ".gitignore") + .exists() + .not(), ) assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "glue" + File.separator + ".gitignore").exists() - .not() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "glue" + File.separator + ".gitignore") + .exists() + .not(), ) } @@ -362,8 +363,7 @@ class EnhancedModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) val apiGitIgnore = File(folder.root.path + File.separator + modulePathAsFile + File.separator + "api" + File.separator + ".gitignore") @@ -375,17 +375,17 @@ class EnhancedModuleMakerTest { Assert.assertEquals( GitIgnoreTemplate.data, - apiGitignoreFileContents.joinToString("\n") + apiGitignoreFileContents.joinToString("\n"), ) Assert.assertEquals( GitIgnoreTemplate.data, - glueGitignoreFileContents.joinToString("\n") + glueGitignoreFileContents.joinToString("\n"), ) Assert.assertEquals( GitIgnoreTemplate.data, - implGitignoreFileContents.joinToString("\n") + implGitignoreFileContents.joinToString("\n"), ) } @@ -394,9 +394,10 @@ class EnhancedModuleMakerTest { val modulePath = ":repository" val modulePathAsFile = "repository" - val template = """ + val template = + """ this is a custom template - """.trimIndent() + """.trimIndent() fakePreferenceService.preferenceState.gitignoreTemplate = template @@ -418,8 +419,7 @@ class EnhancedModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) val apiGitIgnore = File(folder.root.path + File.separator + modulePathAsFile + File.separator + "api" + File.separator + ".gitignore") @@ -431,17 +431,17 @@ class EnhancedModuleMakerTest { Assert.assertEquals( template, - apiGitignoreFileContents.joinToString("\n") + apiGitignoreFileContents.joinToString("\n"), ) Assert.assertEquals( template, - glueGitignoreFileContents.joinToString("\n") + glueGitignoreFileContents.joinToString("\n"), ) Assert.assertEquals( template, - implGitignoreFileContents.joinToString("\n") + implGitignoreFileContents.joinToString("\n"), ) } @@ -471,22 +471,21 @@ class EnhancedModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) Assert.assertEquals( "include(\"$modulePath:api\", \"$rootPathString/$modulePathAsFile/api\")", - settingsGradleFileContents[56] + settingsGradleFileContents[56], ) Assert.assertEquals( "include(\"$modulePath:impl\", \"$rootPathString/$modulePathAsFile/impl\")", - settingsGradleFileContents[57] + settingsGradleFileContents[57], ) Assert.assertEquals( "include(\"$modulePath:glue\", \"$rootPathString/$modulePathAsFile/glue\")", - settingsGradleFileContents[58] + settingsGradleFileContents[58], ) } @@ -517,26 +516,25 @@ class EnhancedModuleMakerTest { addReadme = true, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert it was added to settings.gradle val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assert( - settingsGradleFileContents.contains("include(\":repository:customapi\")") + settingsGradleFileContents.contains("include(\":repository:customapi\")"), ) assert( - settingsGradleFileContents.contains("include(\":repository:customglue\")") + settingsGradleFileContents.contains("include(\":repository:customglue\")"), ) assert( - settingsGradleFileContents.contains("include(\":repository:customimpl\")") + settingsGradleFileContents.contains("include(\":repository:customimpl\")"), ) // assert readme was generated in the api module assert( // root/repository/api/README.md - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "customapi" + File.separator + readmeFile).exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "customapi" + File.separator + readmeFile).exists(), ) // assert build.gradle is generated for all 3 modules @@ -556,29 +554,29 @@ class EnhancedModuleMakerTest { val buildGradleImplFileContents = readFromFile(buildGradleFileImpl) assert( buildGradleApiFileContents.contains( - " namespace = \"$testPackageName.customapi\"" - ) + " namespace = \"$testPackageName.customapi\"", + ), ) assert( buildGradleGlueFileContents.contains( - " namespace = \"$testPackageName.customglue\"" - ) + " namespace = \"$testPackageName.customglue\"", + ), ) assert( buildGradleImplFileContents.contains( - " namespace = \"$testPackageName.customimpl\"" - ) + " namespace = \"$testPackageName.customimpl\"", + ), ) // assert the correct package structure is generated assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "customapi/src/main/kotlin/com/joetr/test/customapi").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "customapi/src/main/kotlin/com/joetr/test/customapi").exists(), ) assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "customglue/src/main/kotlin/com/joetr/test/customglue").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "customglue/src/main/kotlin/com/joetr/test/customglue").exists(), ) assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "customimpl/src/main/kotlin/com/joetr/test/customimpl").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "customimpl/src/main/kotlin/com/joetr/test/customimpl").exists(), ) } } diff --git a/src/test/kotlin/com/joetr/modulemaker/KotlinModuleMakerTest.kt b/src/test/kotlin/com/joetr/modulemaker/KotlinModuleMakerTest.kt index 30bddcb..504a532 100644 --- a/src/test/kotlin/com/joetr/modulemaker/KotlinModuleMakerTest.kt +++ b/src/test/kotlin/com/joetr/modulemaker/KotlinModuleMakerTest.kt @@ -13,24 +13,25 @@ import org.junit.rules.TemporaryFolder import java.io.File class KotlinModuleMakerTest { - @JvmField @Rule var folder = TemporaryFolder() var testState = PreferenceServiceImpl.Companion.State() - private val fakePreferenceService = object : PreferenceService { - override var preferenceState: PreferenceServiceImpl.Companion.State - get() = testState - set(value) { - testState = value - } - } + private val fakePreferenceService = + object : PreferenceService { + override var preferenceState: PreferenceServiceImpl.Companion.State + get() = testState + set(value) { + testState = value + } + } - private val fileWriter = FileWriter( - preferenceService = fakePreferenceService - ) + private val fileWriter = + FileWriter( + preferenceService = fakePreferenceService, + ) private lateinit var settingsGradleFile: File @@ -62,32 +63,31 @@ class KotlinModuleMakerTest { addReadme = true, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert it was added to settings.gradle val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assert( - settingsGradleFileContents.contains("include(\":repository\")") + settingsGradleFileContents.contains("include(\":repository\")"), ) // assert readme was generated assert( // root/repository/README.md - File(folder.root.path + File.separator + modulePathAsFile + File.separator + readmeFile).exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + readmeFile).exists(), ) // assert build.gradle is generated assert( // root/repository/build.gradle - File(folder.root.path + File.separator + modulePathAsFile + File.separator + buildGradleFileName).exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + buildGradleFileName).exists(), ) // assert the correct package structure is generated assert( // root/repository/build.gradle - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/main/kotlin/com/joetr/test").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/main/kotlin/com/joetr/test").exists(), ) } @@ -116,8 +116,7 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert build.gradle is generated @@ -125,15 +124,15 @@ class KotlinModuleMakerTest { File(folder.root.path + File.separator + modulePathAsFile + File.separator + buildGradleFileName) assert( // root/repository/build.gradle - buildGradleFile.exists() + buildGradleFile.exists(), ) // assert package name is included in build.gradle val buildGradleFileContents = readFromFile(buildGradleFile) assert( buildGradleFileContents.contains( - template - ) + template, + ), ) } @@ -160,8 +159,7 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert build.gradle.kts is generated @@ -169,7 +167,7 @@ class KotlinModuleMakerTest { File(folder.root.path + File.separator + modulePathAsFile + File.separator + "database.gradle.kts") assert( // root/repository/database/build.gradle - buildGradleFile.exists() + buildGradleFile.exists(), ) } @@ -196,8 +194,7 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert build.gradle.kts is generated @@ -205,7 +202,7 @@ class KotlinModuleMakerTest { File(folder.root.path + File.separator + modulePathAsFile + File.separator + "database.gradle") assert( // root/repository/database/build.gradle - buildGradleFile.exists() + buildGradleFile.exists(), ) } @@ -232,15 +229,14 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert readme is NOT generated val buildGradleFile = File(folder.root.path + File.separator + modulePathAsFile + File.separator + "README.md") assert( - buildGradleFile.exists().not() + buildGradleFile.exists().not(), ) } @@ -267,15 +263,14 @@ class KotlinModuleMakerTest { addReadme = true, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert readme is generated val buildGradleFile = File(folder.root.path + File.separator + modulePathAsFile + File.separator + "README.md") assert( - buildGradleFile.exists() + buildGradleFile.exists(), ) } @@ -302,14 +297,14 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = false, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert gitignore was not generated assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + File.separator + ".gitignore").exists() - .not() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + File.separator + ".gitignore") + .exists() + .not(), ) } @@ -336,8 +331,7 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert gitignore was generated and has the expected contents @@ -346,7 +340,7 @@ class KotlinModuleMakerTest { val gitignoreFileContents = readFromFile(file = gitignoreFile) assertEquals( GitIgnoreTemplate.data, - gitignoreFileContents.joinToString("\n") + gitignoreFileContents.joinToString("\n"), ) } @@ -355,9 +349,10 @@ class KotlinModuleMakerTest { val modulePath = ":repository" val modulePathAsFile = "repository" - val template = """ + val template = + """ this is a custom template - """.trimIndent() + """.trimIndent() fakePreferenceService.preferenceState.gitignoreTemplate = template @@ -379,8 +374,7 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) // assert gitignore was generated and has the expected contents @@ -389,7 +383,7 @@ class KotlinModuleMakerTest { val gitignoreFileContents = readFromFile(file = gitignoreFile) assertEquals( template, - gitignoreFileContents.joinToString("\n") + gitignoreFileContents.joinToString("\n"), ) } @@ -419,14 +413,13 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assertEquals( "include(\"$modulePath\", \"$rootPathString/$modulePathAsFile\")", - settingsGradleFileContents[56] + settingsGradleFileContents[56], ) } @@ -456,14 +449,13 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assertEquals( "includeBuild(\"$modulePath\", \"$rootPathString/$modulePathAsFile\")", - settingsGradleFileContents[56] + settingsGradleFileContents[56], ) } @@ -491,14 +483,13 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assertEquals( "include(\"$modulePath\")", - settingsGradleFileContents[45] + settingsGradleFileContents[45], ) } @@ -528,14 +519,13 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assertEquals( "testIncludeProject(\"$modulePath\")", - settingsGradleFileContents[45] + settingsGradleFileContents[45], ) } @@ -563,14 +553,13 @@ class KotlinModuleMakerTest { addReadme = false, addGitIgnore = true, rootPathString = folder.root.toString(), - previewMode = false - + previewMode = false, ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assertEquals( "include(\"$modulePath\")", - settingsGradleFileContents[16] + settingsGradleFileContents[16], ) } @@ -584,43 +573,43 @@ class KotlinModuleMakerTest { val settingsGradleFileContentsBefore = readFromFile(file = settingsGradleFile) - val filesToReturn = fileWriter.createModule( - settingsGradleFile = settingsGradleFile, - workingDirectory = folder.root, - modulePathAsString = modulePath, - moduleType = KOTLIN, - showErrorDialog = { - Assert.fail("No errors should be thrown") - }, - showSuccessDialog = { - assert(true) - }, - enhancedModuleCreationStrategy = false, - useKtsBuildFile = false, - gradleFileFollowModule = false, - packageName = testPackageName, - addReadme = false, - addGitIgnore = true, - rootPathString = folder.root.toString(), - previewMode = true - - ) + val filesToReturn = + fileWriter.createModule( + settingsGradleFile = settingsGradleFile, + workingDirectory = folder.root, + modulePathAsString = modulePath, + moduleType = KOTLIN, + showErrorDialog = { + Assert.fail("No errors should be thrown") + }, + showSuccessDialog = { + assert(true) + }, + enhancedModuleCreationStrategy = false, + useKtsBuildFile = false, + gradleFileFollowModule = false, + packageName = testPackageName, + addReadme = false, + addGitIgnore = true, + rootPathString = folder.root.toString(), + previewMode = true, + ) val settingsGradleFileContentsAfter = readFromFile(file = settingsGradleFile) assertEquals( settingsGradleFileContentsBefore, - settingsGradleFileContentsAfter + settingsGradleFileContentsAfter, ) assertEquals( filesToReturn.size, - 3 + 3, ) assertEquals( rootFiles!!.size, - folder.root.listFiles()!!.size + folder.root.listFiles()!!.size, ) } } diff --git a/src/test/kotlin/com/joetr/modulemaker/MultiplatformModuleMakerTest.kt b/src/test/kotlin/com/joetr/modulemaker/MultiplatformModuleMakerTest.kt index b647196..5415897 100644 --- a/src/test/kotlin/com/joetr/modulemaker/MultiplatformModuleMakerTest.kt +++ b/src/test/kotlin/com/joetr/modulemaker/MultiplatformModuleMakerTest.kt @@ -13,24 +13,25 @@ import org.junit.rules.TemporaryFolder import java.io.File class MultiplatformModuleMakerTest { - @JvmField @Rule var folder = TemporaryFolder() var testState = PreferenceServiceImpl.Companion.State() - private val fakePreferenceService = object : PreferenceService { - override var preferenceState: PreferenceServiceImpl.Companion.State - get() = testState - set(value) { - testState = value - } - } + private val fakePreferenceService = + object : PreferenceService { + override var preferenceState: PreferenceServiceImpl.Companion.State + get() = testState + set(value) { + testState = value + } + } - private val fileWriter = FileWriter( - preferenceService = fakePreferenceService - ) + private val fileWriter = + FileWriter( + preferenceService = fakePreferenceService, + ) private lateinit var settingsGradleFile: File @@ -64,37 +65,36 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") - + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) // assert it was added to settings.gradle val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assert( - settingsGradleFileContents.contains("include(\":multiplatform-module\")") + settingsGradleFileContents.contains("include(\":multiplatform-module\")"), ) // assert readme was generated assert( // root/repository/README.md - File(folder.root.path + File.separator + modulePathAsFile + File.separator + readmeFile).exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + readmeFile).exists(), ) // assert build.gradle is generated assert( // root/repository/build.gradle - File(folder.root.path + File.separator + modulePathAsFile + File.separator + buildGradleFileName).exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + buildGradleFileName).exists(), ) // assert the correct package structure is generated assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/androidMain/kotlin/com/joetr/test").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/androidMain/kotlin/com/joetr/test").exists(), ) assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/iosMain/kotlin/com/joetr/test").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/iosMain/kotlin/com/joetr/test").exists(), ) assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/jvmMain/kotlin/com/joetr/test").exists() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + "src/jvmMain/kotlin/com/joetr/test").exists(), ) } @@ -125,7 +125,7 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) // assert build.gradle is generated @@ -133,15 +133,15 @@ class MultiplatformModuleMakerTest { File(folder.root.path + File.separator + modulePathAsFile + File.separator + buildGradleFileName) assert( // root/repository/build.gradle - buildGradleFile.exists() + buildGradleFile.exists(), ) // assert package name is included in build.gradle val buildGradleFileContents = readFromFile(buildGradleFile) assert( buildGradleFileContents.contains( - template - ) + template, + ), ) } @@ -170,7 +170,7 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) // assert build.gradle.kts is generated @@ -178,7 +178,7 @@ class MultiplatformModuleMakerTest { File(folder.root.path + File.separator + modulePathAsFile + File.separator + "database.gradle.kts") assert( // root/repository/database/build.gradle - buildGradleFile.exists() + buildGradleFile.exists(), ) } @@ -207,7 +207,7 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) // assert build.gradle.kts is generated @@ -215,7 +215,7 @@ class MultiplatformModuleMakerTest { File(folder.root.path + File.separator + modulePathAsFile + File.separator + "database.gradle") assert( // root/repository/database/build.gradle - buildGradleFile.exists() + buildGradleFile.exists(), ) } @@ -244,14 +244,14 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) // assert readme is NOT generated val buildGradleFile = File(folder.root.path + File.separator + modulePathAsFile + File.separator + "README.md") assert( - buildGradleFile.exists().not() + buildGradleFile.exists().not(), ) } @@ -280,14 +280,14 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) // assert readme is generated val buildGradleFile = File(folder.root.path + File.separator + modulePathAsFile + File.separator + "README.md") assert( - buildGradleFile.exists() + buildGradleFile.exists(), ) } @@ -316,13 +316,14 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) // assert gitignore was not generated assert( - File(folder.root.path + File.separator + modulePathAsFile + File.separator + File.separator + ".gitignore").exists() - .not() + File(folder.root.path + File.separator + modulePathAsFile + File.separator + File.separator + ".gitignore") + .exists() + .not(), ) } @@ -351,7 +352,7 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) // assert gitignore was generated and has the expected contents @@ -360,7 +361,7 @@ class MultiplatformModuleMakerTest { val gitignoreFileContents = readFromFile(file = gitignoreFile) assertEquals( GitIgnoreTemplate.data, - gitignoreFileContents.joinToString("\n") + gitignoreFileContents.joinToString("\n"), ) } @@ -369,9 +370,10 @@ class MultiplatformModuleMakerTest { val modulePath = ":repository" val modulePathAsFile = "repository" - val template = """ + val template = + """ this is a custom template - """.trimIndent() + """.trimIndent() fakePreferenceService.preferenceState.gitignoreTemplate = template @@ -395,7 +397,7 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) // assert gitignore was generated and has the expected contents @@ -404,7 +406,7 @@ class MultiplatformModuleMakerTest { val gitignoreFileContents = readFromFile(file = gitignoreFile) assertEquals( template, - gitignoreFileContents.joinToString("\n") + gitignoreFileContents.joinToString("\n"), ) } @@ -436,13 +438,13 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assertEquals( "include(\"$modulePath\", \"$rootPathString/$modulePathAsFile\")", - settingsGradleFileContents[56] + settingsGradleFileContents[56], ) } @@ -474,13 +476,13 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assertEquals( "includeBuild(\"$modulePath\", \"$rootPathString/$modulePathAsFile\")", - settingsGradleFileContents[56] + settingsGradleFileContents[56], ) } @@ -510,13 +512,13 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assertEquals( "include(\"$modulePath\")", - settingsGradleFileContents[45] + settingsGradleFileContents[45], ) } @@ -548,13 +550,13 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assertEquals( "testIncludeProject(\"$modulePath\")", - settingsGradleFileContents[45] + settingsGradleFileContents[45], ) } @@ -584,13 +586,13 @@ class MultiplatformModuleMakerTest { rootPathString = folder.root.toString(), previewMode = false, platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), ) val settingsGradleFileContents = readFromFile(file = settingsGradleFile) assertEquals( "include(\"$modulePath\")", - settingsGradleFileContents[16] + settingsGradleFileContents[16], ) } @@ -604,44 +606,45 @@ class MultiplatformModuleMakerTest { val settingsGradleFileContentsBefore = readFromFile(file = settingsGradleFile) - val filesToReturn = fileWriter.createModule( - settingsGradleFile = settingsGradleFile, - workingDirectory = folder.root, - modulePathAsString = modulePath, - moduleType = KOTLIN, - showErrorDialog = { - Assert.fail("No errors should be thrown") - }, - showSuccessDialog = { - assert(true) - }, - enhancedModuleCreationStrategy = false, - useKtsBuildFile = false, - gradleFileFollowModule = false, - packageName = testPackageName, - addReadme = false, - addGitIgnore = true, - rootPathString = folder.root.toString(), - previewMode = true, - platformType = MULTIPLATFORM, - sourceSets = listOf("jvmMain", "iosMain", "androidMain") - ) + val filesToReturn = + fileWriter.createModule( + settingsGradleFile = settingsGradleFile, + workingDirectory = folder.root, + modulePathAsString = modulePath, + moduleType = KOTLIN, + showErrorDialog = { + Assert.fail("No errors should be thrown") + }, + showSuccessDialog = { + assert(true) + }, + enhancedModuleCreationStrategy = false, + useKtsBuildFile = false, + gradleFileFollowModule = false, + packageName = testPackageName, + addReadme = false, + addGitIgnore = true, + rootPathString = folder.root.toString(), + previewMode = true, + platformType = MULTIPLATFORM, + sourceSets = listOf("jvmMain", "iosMain", "androidMain"), + ) val settingsGradleFileContentsAfter = readFromFile(file = settingsGradleFile) assertEquals( settingsGradleFileContentsBefore, - settingsGradleFileContentsAfter + settingsGradleFileContentsAfter, ) assertEquals( filesToReturn.size, - 5 + 5, ) assertEquals( rootFiles!!.size, - folder.root.listFiles()!!.size + folder.root.listFiles()!!.size, ) } } diff --git a/src/test/kotlin/com/joetr/modulemaker/settings/DefaultTemplateSettingsGradle.kt b/src/test/kotlin/com/joetr/modulemaker/settings/DefaultTemplateSettingsGradle.kt index f6853e6..488c042 100644 --- a/src/test/kotlin/com/joetr/modulemaker/settings/DefaultTemplateSettingsGradle.kt +++ b/src/test/kotlin/com/joetr/modulemaker/settings/DefaultTemplateSettingsGradle.kt @@ -1,7 +1,8 @@ package com.joetr.modulemaker.settings object DefaultTemplateSettingsGradle { - val data = """ + val data = + """ pluginManagement { repositories { google() @@ -18,5 +19,5 @@ object DefaultTemplateSettingsGradle { } rootProject.name = "ModuleMakerTest" include ':app' - """.trimIndent() + """.trimIndent() } diff --git a/src/test/kotlin/com/joetr/modulemaker/settings/NowInAndroidSettingsGradleKts.kt b/src/test/kotlin/com/joetr/modulemaker/settings/NowInAndroidSettingsGradleKts.kt index a3aa0a2..cb3424a 100644 --- a/src/test/kotlin/com/joetr/modulemaker/settings/NowInAndroidSettingsGradleKts.kt +++ b/src/test/kotlin/com/joetr/modulemaker/settings/NowInAndroidSettingsGradleKts.kt @@ -1,7 +1,8 @@ package com.joetr.modulemaker.settings object NowInAndroidSettingsGradleKts { - val data = """ + val data = + """ /* * Copyright 2021 The Android Open Source Project * @@ -62,9 +63,10 @@ object NowInAndroidSettingsGradleKts { include(":sync:work") include(":sync:sync-test") include(":ui-test-hilt-manifest") - """.trimIndent() + """.trimIndent() - val filePathData = """ + val filePathData = + """ /* * Copyright 2021 The Android Open Source Project * @@ -125,9 +127,10 @@ object NowInAndroidSettingsGradleKts { include(":sync:work", "path/to") include(":sync:sync-test", "path/to") include(":ui-test-hilt-manifest", "path/to") - """.trimIndent() + """.trimIndent() - val filePathDataWithCustomIncludeBuildData = """ + val filePathDataWithCustomIncludeBuildData = + """ /* * Copyright 2021 The Android Open Source Project * @@ -188,5 +191,5 @@ object NowInAndroidSettingsGradleKts { includeBuild(":sync:work", "path/to") includeBuild(":sync:sync-test", "path/to") includeBuild(":ui-test-hilt-manifest", "path/to") - """.trimIndent() + """.trimIndent() } diff --git a/src/test/kotlin/com/joetr/modulemaker/settings/TiviSettingsGradleKts.kt b/src/test/kotlin/com/joetr/modulemaker/settings/TiviSettingsGradleKts.kt index 2817759..df519ea 100644 --- a/src/test/kotlin/com/joetr/modulemaker/settings/TiviSettingsGradleKts.kt +++ b/src/test/kotlin/com/joetr/modulemaker/settings/TiviSettingsGradleKts.kt @@ -1,7 +1,8 @@ package com.joetr.modulemaker.settings object TiviSettingsGradleKts { - val data = """ + val data = + """ // Copyright 2023, Christopher Banes and the Tivi project contributors // SPDX-License-Identifier: Apache-2.0 @@ -103,9 +104,10 @@ object TiviSettingsGradleKts { ":thirdparty:swipe", ":thirdparty:compose-material-dialogs:datetime", ) - """.trimIndent() + """.trimIndent() - val dataWithCustomIncludeProject = """ + val dataWithCustomIncludeProject = + """ // Copyright 2023, Christopher Banes and the Tivi project contributors // SPDX-License-Identifier: Apache-2.0 @@ -207,5 +209,5 @@ object TiviSettingsGradleKts { ":thirdparty:swipe", ":thirdparty:compose-material-dialogs:datetime", ) - """.trimIndent() + """.trimIndent() } diff --git a/src/uiTest/kotlin/com/joetr/modulemaker/ModuleMakerUiTest.kt b/src/uiTest/kotlin/com/joetr/modulemaker/ModuleMakerUiTest.kt index 7854fac..45b07f0 100644 --- a/src/uiTest/kotlin/com/joetr/modulemaker/ModuleMakerUiTest.kt +++ b/src/uiTest/kotlin/com/joetr/modulemaker/ModuleMakerUiTest.kt @@ -27,7 +27,6 @@ import java.time.Duration * ComposePanel forwards dispatched Swing events to the compose layer. */ class ModuleMakerUiTest { - private val robotPort = System.getProperty("robot-server.port", "8082") private val remoteRobot = RemoteRobot("http://127.0.0.1:$robotPort") @@ -39,28 +38,32 @@ class ModuleMakerUiTest { dismissBlockingDialogs() // Check if the project frame is open - val ideFrame = findAll( - byXpath("//div[@class='IdeFrameImpl']") - ) + val ideFrame = + findAll( + byXpath("//div[@class='IdeFrameImpl']"), + ) if (ideFrame.isNotEmpty()) { println("Found IdeFrameImpl") true } else { // Dump what top-level components exist so we can diagnose CI failures val allComponents = findAll(byXpath("//div")) - val classNames = allComponents.mapNotNull { fixture -> - try { - fixture.callJs("component.getClass().getName()") - } catch (_: Exception) { - null - } - }.distinct() + val classNames = + allComponents + .mapNotNull { fixture -> + try { + fixture.callJs("component.getClass().getName()") + } catch (_: Exception) { + null + } + }.distinct() println("Waiting for IdeFrameImpl... Found components: ${classNames.take(30)}") // If stuck on Welcome screen, the project didn't auto-open - val welcomeFrame = findAll( - byXpath("//div[@class='FlatWelcomeFrame']") - ) + val welcomeFrame = + findAll( + byXpath("//div[@class='FlatWelcomeFrame']"), + ) if (welcomeFrame.isNotEmpty()) { println("Detected Welcome screen - project did not auto-open") } @@ -88,7 +91,7 @@ class ModuleMakerUiTest { // Click the IDE frame to ensure it has focus find( byXpath("//div[@class='IdeFrameImpl']"), - Duration.ofSeconds(10) + Duration.ofSeconds(10), ).click() Thread.sleep(500) @@ -102,9 +105,10 @@ class ModuleMakerUiTest { Thread.sleep(2_000) // Check if Find Action popup appeared - val searchField = findAll( - byXpath("//div[@class='SearchEverywhereUI']") - ) + val searchField = + findAll( + byXpath("//div[@class='SearchEverywhereUI']"), + ) if (searchField.isEmpty()) { println("Find Action popup not found, retrying...") // Press Escape to clean up any partial state @@ -124,15 +128,16 @@ class ModuleMakerUiTest { step("Verify Module Maker dialog opened") { waitFor(duration = Duration.ofSeconds(30)) { findAll( - byXpath("//div[@title='Module Maker']") + byXpath("//div[@title='Module Maker']"), ).isNotEmpty() } } - val dialog = find( - byXpath("//div[@title='Module Maker']"), - Duration.ofSeconds(10) - ) + val dialog = + find( + byXpath("//div[@title='Module Maker']"), + Duration.ofSeconds(10), + ) val isMac = System.getProperty("os.name").contains("Mac", ignoreCase = true) @@ -143,10 +148,11 @@ class ModuleMakerUiTest { step("Focus Module Name via Shift+Tab from Create button") { // Focus (don't click!) the Create button as a stable tab-order anchor - dialog.find( - byXpath("//div[@text='Create']"), - Duration.ofSeconds(10) - ).callJs("component.requestFocusInWindow(); true") + dialog + .find( + byXpath("//div[@text='Create']"), + Duration.ofSeconds(10), + ).callJs("component.requestFocusInWindow(); true") Thread.sleep(500) // Shift+Tab from Create → lands on Module Name field @@ -178,27 +184,29 @@ class ModuleMakerUiTest { } step("Click Create button") { - dialog.find( - byXpath("//div[@text='Create']"), - Duration.ofSeconds(10) - ).click() + dialog + .find( + byXpath("//div[@text='Create']"), + Duration.ofSeconds(10), + ).click() } step("Dismiss any post-creation dialog") { Thread.sleep(3_000) // Try to dismiss success or error dialog findAll( - byXpath("//div[@text='Okay']") + byXpath("//div[@text='Okay']"), ).firstOrNull()?.click() findAll( - byXpath("//div[@class='JButton' and @text='OK']") + byXpath("//div[@class='JButton' and @text='OK']"), ).firstOrNull()?.click() Thread.sleep(500) } step("Verify module was created on disk") { - val testProjectDir = File(System.getProperty("user.dir")) - .resolve("src/uiTest/testProject") + val testProjectDir = + File(System.getProperty("user.dir")) + .resolve("src/uiTest/testProject") val repositoryDir = testProjectDir.resolve("repository") assert(repositoryDir.exists() && repositoryDir.isDirectory) { "Expected repository directory at ${repositoryDir.absolutePath}" @@ -226,7 +234,11 @@ class ModuleMakerUiTest { dialog.find(byXpath("//div[@class='ComposePanel']"), Duration.ofSeconds(10)) /** Dispatch a mouse click at (x, y) relative to the compose panel. */ - private fun dispatchClick(dialog: CommonContainerFixture, x: Int, y: Int) { + private fun dispatchClick( + dialog: CommonContainerFixture, + x: Int, + y: Int, + ) { findComposePanel(dialog).callJs( """ var target = component.getComponent(1); @@ -242,7 +254,7 @@ class ModuleMakerUiTest { target, java.awt.event.MouseEvent.MOUSE_CLICKED, now + 50, 0, $x, $y, 1, false, java.awt.event.MouseEvent.BUTTON1)); true - """ + """, ) } @@ -252,7 +264,7 @@ class ModuleMakerUiTest { keyCode: Int, ctrl: Boolean = false, meta: Boolean = false, - shift: Boolean = false + shift: Boolean = false, ) { val modifiers = mutableListOf() if (ctrl) modifiers.add("java.awt.event.InputEvent.CTRL_DOWN_MASK") @@ -271,31 +283,38 @@ class ModuleMakerUiTest { target, java.awt.event.KeyEvent.KEY_RELEASED, now + 30, $modExpr, $keyCode, java.awt.event.KeyEvent.CHAR_UNDEFINED)); true - """ + """, ) } /** Dispatch KEY_TYPED events for each character in [text]. */ - private fun dispatchText(dialog: CommonContainerFixture, text: String) { + private fun dispatchText( + dialog: CommonContainerFixture, + text: String, + ) { for (ch in text) { dispatchChar(dialog, ch) Thread.sleep(50) } } - private fun dispatchChar(dialog: CommonContainerFixture, ch: Char) { + private fun dispatchChar( + dialog: CommonContainerFixture, + ch: Char, + ) { // For typed characters, we need KEY_TYPED with the char value. // Some characters also need KEY_PRESSED/KEY_RELEASED for the compose layer. - val (keyCode, shift) = when { - ch in 'a'..'z' -> (KeyEvent.VK_A + (ch - 'a')) to false - ch in 'A'..'Z' -> (KeyEvent.VK_A + (ch - 'A')) to true - ch in '0'..'9' -> (KeyEvent.VK_0 + (ch - '0')) to false - ch == '.' -> KeyEvent.VK_PERIOD to false - ch == ':' -> KeyEvent.VK_SEMICOLON to true - ch == '-' -> KeyEvent.VK_MINUS to false - ch == '_' -> KeyEvent.VK_MINUS to true - else -> throw IllegalArgumentException("Unsupported character: '$ch'") - } + val (keyCode, shift) = + when { + ch in 'a'..'z' -> (KeyEvent.VK_A + (ch - 'a')) to false + ch in 'A'..'Z' -> (KeyEvent.VK_A + (ch - 'A')) to true + ch in '0'..'9' -> (KeyEvent.VK_0 + (ch - '0')) to false + ch == '.' -> KeyEvent.VK_PERIOD to false + ch == ':' -> KeyEvent.VK_SEMICOLON to true + ch == '-' -> KeyEvent.VK_MINUS to false + ch == '_' -> KeyEvent.VK_MINUS to true + else -> throw IllegalArgumentException("Unsupported character: '$ch'") + } val modExpr = if (shift) "java.awt.event.InputEvent.SHIFT_DOWN_MASK" else "0" @@ -313,7 +332,7 @@ class ModuleMakerUiTest { target, java.awt.event.KeyEvent.KEY_RELEASED, now + 30, $modExpr, $keyCode, '$ch')); true - """ + """, ) } @@ -344,15 +363,17 @@ class ModuleMakerUiTest { // Catch-all: if a DialogWrapper dialog is blocking, find buttons and click // a safe one. Skip "Cancel"/"No"/"Exit" to avoid killing legitimate operations. - val dialogButtons = findAll( - byXpath("//div[@class='MyDialog']//div[@class='JButton']") - ) + val dialogButtons = + findAll( + byXpath("//div[@class='MyDialog']//div[@class='JButton']"), + ) for (btn in dialogButtons) { - val btnText = try { - btn.callJs("component.getText()")?.trim() ?: "" - } catch (_: Exception) { - "" - } + val btnText = + try { + btn.callJs("component.getText()")?.trim() ?: "" + } catch (_: Exception) { + "" + } val lower = btnText.lowercase() if (lower in listOf("cancel", "no", "exit", "abort", "stop")) { println("Skipping dangerous dialog button: '$btnText'")