Intellij Idea 是否可以从外部调用Intellij IDE脚本,例如通过命令行?

yhuiod9q  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(155)

我正在尝试使用Intellij IDE scripting console编写一个脚本,并使用命令行启动器(例如Intellij IDEA的idea)在外部调用它。
它看起来像是在2021.1中添加的支持(参见YouTrack ticket],但它可能已经从(?)
我试着用下面的命令调用脚本,但是什么也没有发生;脚本似乎未执行,并且未记录任何错误。

# following command in YouTrack ticket referenced above
idea ideScript /path/to/script

这些是脚本的内容,在IDE中运行时可以正常工作。

# ide_script.kts
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.ActionCallback

val project = ProjectManager.getInstance().defaultProject
val actionManager: ActionManager = ActionManager.getInstance()
val action: AnAction = actionManager.getAction("NextTab")
val actionResult: ActionCallback = actionManager.tryToExecute(action, null, null, null, true)

Messages.showInfoMessage(project, actionResult.error ?: "Action success", "Action Result")

理想情况下,我也想(如果可能的话)参数化脚本,例如,在行动的名称。

n53p2ov0

n53p2ov01#

你没有定义你的旗帜
试试这个:

idea --ideScript /path/to/script

import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.ActionCallback

val projectName = args[0]
val actionName = args[1]

val project = ProjectManager.getInstance().defaultProject
val actionManager: ActionManager = ActionManager.getInstance()
val action: AnAction = actionManager.getAction(actionName)
val actionResult: ActionCallback = actionManager.tryToExecute(action, null, null, null, true)

Messages.showInfoMessage(project, actionResult.error ?: "Action success", "Action Result: $projectName")

idea --ideScript /path/to/script myProject myAction

或者,您可以尝试:

import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.ActionCallback

val projectName = System.getenv("PROJECT_NAME")
val actionName = System.getenv("ACTION_NAME")

val project = ProjectManager.getInstance().defaultProject
val actionManager: ActionManager = ActionManager.getInstance()
val action: AnAction = actionManager.getAction(actionName)
val actionResult: ActionCallback = actionManager.tryToExecute(action, null, null, null, true)

Messages.showInfoMessage(project, actionResult.error ?: "Action success", "Action Result: $projectName")

export PROJECT_NAME=myProject
export ACTION_NAME=myAction
idea --ideScript /path/to/script

这样,脚本将读取'PROJECT_NAME'和'ACTION_NAME'环境变量,并在脚本中使用它们。这种方法允许您将参数传递给脚本,而无需修改其内容。

相关问题