Skip to content

Commit

Permalink
Add custom exceptions to Project
Browse files Browse the repository at this point in the history
Add Settings for Define Env Plugin
Add a tool window to configure define_env for project
Fix Process Env
  • Loading branch information
ibrahim-mubarak committed Dec 21, 2022
1 parent 7e02275 commit 0fd4732
Show file tree
Hide file tree
Showing 19 changed files with 412 additions and 92 deletions.
10 changes: 7 additions & 3 deletions studio-plugin/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
plugins {
id("java")
id("org.jetbrains.kotlin.jvm") version "1.7.20"
id("org.jetbrains.intellij") version "1.10.1"
id("org.jetbrains.intellij") version "1.11.0"
}

group = "com.flrx.define_env"
version = "1.0-SNAPSHOT"
version = "0.4.2"

repositories {
mavenCentral()
Expand All @@ -31,10 +31,14 @@ tasks {
kotlinOptions.jvmTarget = "11"
}

buildSearchableOptions {
enabled = false
}

patchPluginXml {
sinceBuild.set("213")
untilBuild.set("213.*")
version.set("0.4.1")
version.set("$version")
}

signPlugin {
Expand Down
1 change: 1 addition & 0 deletions studio-plugin/gradle.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
kotlin.stdlib.default.dependency=false
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.flrx.define_env

import com.flrx.define_env.exceptions.DartSdkException
import com.flrx.define_env.exceptions.ProjectPathException
import com.flrx.define_env.model.DefineEnvModel
import com.flrx.define_env.settings.SettingsService
import com.flrx.define_env.utils.addPathToEnv
import com.flrx.define_env.utils.readError
import com.flrx.define_env.utils.readOutput
Expand All @@ -15,33 +19,52 @@ import com.jetbrains.lang.dart.sdk.DartSdk
import io.flutter.run.FlutterRunConfigurationType
import io.flutter.run.SdkRunConfig
import java.io.File
import kotlin.io.path.Path

class DefineEnvForProjectTask(
private val file: VirtualFile,
private val project: Project,
) : Task.Backgroundable(project, "Updating Dart Define") {
) : Task.Backgroundable(project, "Updating dart define configuration") {
private lateinit var indicator: ProgressIndicator

private val service = SettingsService.getInstance(project)
override fun run(indicator: ProgressIndicator) {
this.indicator = indicator


val filePathFromProjectRoot: String = file.path.replace(project.basePath + File.separator, "")

val properConfigs = service.state.envRunConfigs.filter {
return@filter it.file == filePathFromProjectRoot
}

println(properConfigs)

if (properConfigs.isEmpty()) {
return
}

if (!indicator.isRunning) {
indicator.start()
}
runDefineEnvForProject()

properConfigs.forEach {
runDefineEnvForConfig(it)
}
indicator.stop()
}

private fun runDefineEnvForProject(): Boolean {
indicator.text = "Starting Process"
private fun runDefineEnvForConfig(model: DefineEnvModel): Boolean {
indicator.text = "Starting process"
val pb = buildDefineEnvProcess()


// start the process
indicator.text = "Running Process"
indicator.text = "Running process"
val process = pb.start()

// read the output from the process
var processOutput = process.readOutput()
val processOutput = process.readOutput()

// wait for the process to finish
val finalCode = process.waitFor()
Expand All @@ -56,65 +79,65 @@ class DefineEnvForProjectTask(
}

else -> {
indicator.text = "Updating Configurations"
updateConfigurationsForProject(project, processOutput)
indicator.text = "Updating configurations"
updateConfigurations(model, processOutput)
true
}
}
}

private fun buildDefineEnvProcess(): ProcessBuilder {
/// Build Process
val pb = ProcessBuilder("dart", "pub", "global", "run", "define_env", "-f", file.path)
/// Add Dart SDK to PATH
val dartSdkPath = DartSdk.getDartSdk(project)?.homePath ?: throw DartSdkException()

/// Run in Project directory
println(file.path)
println(project.basePath)
pb.directory(File(project.basePath))
val dartSdkBinPath = dartSdkPath + File.separator + "bin"
val dartBinary = Path(dartSdkPath, "bin", "dart").toString()

/// Update Path Env
pb.addPathToEnv(System.getenv("PATH"))
val pb = ProcessBuilder(dartBinary, "pub", "global", "run", "define_env", "-f", file.path)

/// Add Dart SDK to PATH
val projectPath = project.basePath ?: throw ProjectPathException()

val dartSdkPath = DartSdk.getDartSdk(project)?.homePath
println(dartSdkPath ?: "No SDK Found for project")
/// Run in Project directory
pb.directory(File(projectPath))

val dartSdkBinPath = dartSdkPath + File.separator + "bin"
/// Update Path Env
pb.addPathToEnv(System.getenv("PATH"))
pb.addPathToEnv(dartSdkBinPath)

return pb
}


private fun updateConfigurationsForProject(project: Project, dartDefineString: String) {
private fun updateConfigurations(model: DefineEnvModel, dartDefineString: String) {
RunManagerEx.getInstanceEx(project).allSettings
.filter { it.configuration.type is FlutterRunConfigurationType }
.filter { model.runConfiguration!!.name == it.configuration.name }
.forEach { checkSettings(it, dartDefineString) }
}

private fun checkSettings(setting: RunnerAndConfigurationSettings, defineString: String) {
val configuration = setting.configuration as? SdkRunConfig
val fields = configuration!!.fields

var oldArgs = (fields.additionalArgs ?: "")
val oldArgs = (fields.additionalArgs ?: "")

var retainedArgs = oldArgs
val retainedArgs = oldArgs
.replace(""", "\"")
.replace(Regex("""--dart-define=[^ "]+(["\'])([^"\'])+(["\'])"""), "")
.replace(Regex("""--dart-define=[^ "]+"""), "")
.replace(Regex("\\s+"), " ")
.trim()

var args = mutableListOf<String>()
val args = mutableListOf<String>()

if (!retainedArgs.isNullOrBlank()) {
if (retainedArgs.isNotBlank()) {
args.add(retainedArgs)
}

args.add(defineString)

var finalArgs = Joiner.on(" ").join(args)
val finalArgs = Joiner.on(" ").join(args)
fields.additionalArgs = finalArgs
}
}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package com.flrx.define_env.exceptions

class DartSdkException : Exception()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package com.flrx.define_env.exceptions

class ProjectPathException : Exception()
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.flrx.define_env.listeners

import com.flrx.define_env.DefineEnvForProjectTask
import com.flrx.define_env.utils.getProjects
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vfs.AsyncFileListener
import com.intellij.openapi.vfs.AsyncFileListener.ChangeApplier
import com.intellij.openapi.vfs.newvfs.events.VFileEvent

class EnvFileListener : AsyncFileListener {
override fun prepareChange(events: MutableList<out VFileEvent>): AsyncFileListener.ChangeApplier {
val envFileEvents = events.filter { isValidEvent(it) }

return object : ChangeApplier {
override fun afterVfsChange() = envFileEvents
.mapNotNull { it.file }
.forEach { file ->
file.getProjects().forEach { project ->
ProgressManager.getInstance().run(DefineEnvForProjectTask(file, project))
}
}
}
}

private fun isValidEvent(event: VFileEvent): Boolean {
val file = event.file ?: return false
if (!file.exists()) return false
if (!event.isFromSave && !event.isFromRefresh) return false
if (!event.path.contains(".env")) return false


val openProjects = ProjectManager.getInstance().openProjects

val isInOpenProject = openProjects.fold(false) { prev, project ->
return prev || ProjectFileIndex.getInstance(project).isInContent(file)
}

return isInOpenProject
}
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.flrx.define_env.model

import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.xmlb.annotations.XMap
import io.flutter.run.SdkRunConfig
import java.io.File

data class DefineEnvModel(
var isEnabled: Boolean?,
var file: String?,
var runConfiguration: RunConfigDetails?
) {

constructor() : this(null, null, null)

constructor(project: Project, isEnabled: Boolean, file: VirtualFile, runConfiguration: SdkRunConfig) :
this(
isEnabled,
file.path.replace(project.basePath + File.separator, ""),
RunConfigDetails(runConfiguration.name, runConfiguration.type.displayName)
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.flrx.define_env.model

data class RunConfigDetails(var name: String? = null, var type: String? = null) {
override fun toString() = name ?: super.toString()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.flrx.define_env.settings

import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.project.Project

@Service
@State(name = "DefineEnvMap", storages = [Storage("define_env.xml")])
class SettingsService : PersistentStateComponent<SettingsState> {

companion object {
fun getInstance(project: Project): SettingsService = project.getService(SettingsService::class.java)
}

private var settingsState = SettingsState()

override fun getState() = settingsState

override fun loadState(state: SettingsState) {
settingsState = state
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.flrx.define_env.settings

import com.flrx.define_env.model.DefineEnvModel

data class SettingsState(var envRunConfigs: MutableList<DefineEnvModel> = mutableListOf())
Loading

0 comments on commit 0fd4732

Please sign in to comment.