如何在 GitHub Actions 上运行 Kotlin 脚本?

Lou*_*CAD 5 kotlin github-actions kotlin-script

我想在不依赖 Gradle 项目的情况下在 CI 中运行 Kotlin 脚本,这样我就可以轻松地执行使用 shell/bash/batch 难以编程的操作,并且在需要时可以使用库。

让 Kotlin 脚本仅在 Ubuntu/Linux 上运行很好,但理想情况下,有一种方法可以让它在 Windows 和 macOS 目标以及特定于平台的项目上运行。

Lou*_*CAD 6

TL;DR:在尝试运行 Kotlin 脚本之前在脚本中运行的重要命令如下: sudo snap install --classic kotlin

首先,确保您有一个正确的 Kotlin 脚本,以.kts或更好的结尾,.main.kts因为后者会被 IDE(例如 IntelliJ IDEA、Android Studio)更好地识别,尤其是在涉及自动完成和类型分析时。

其次,确保它的第一行是指向正确位置的shebang:

#!/usr/bin/env kotlin
Run Code Online (Sandbox Code Playgroud)

这将有助于在 CI 中运行之前在本地测试脚本,因为 IDE 将在 shebang 旁边的 gutter 中显示一个运行按钮。如果您为文件添加了执行权限(chmod +x YouScript.main.kts在 Linux/macOS 上),您还可以像运行任何其他脚本一样运行它,而无需kotlinc -script之前输入,这也适用于 GitHub Actions。

最后,这是一个示例手动 GitHub 操作(又名工作流文件),它会args在安装 Kotlin 后接受输入并将其传递给您的 Kotlin 脚本(可在属性/参数中使用):

name: Run Kotlin script

on:
  workflow_dispatch:
    inputs:
      awesome-input:
        description: 'Awesome parameter'
        default: 'You'
        required: true

jobs:
  awesome-action:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Install Kotlin
      run: sudo snap install --classic kotlin
    - name: Run Kotlin script
      run: kotlinc -script ./YourScript.main.kts ${{ github.event.inputs.awesome-input }}
Run Code Online (Sandbox Code Playgroud)

用于将 Kotlin 安装为 snap 包的命令取自 Kotlin 官网:https : //kotlinlang.org/docs/command-line.html#snap-package

请注意,如果脚本具有执行 ( x) 权限,正如我之前所说,您可以删除该kotlinc -script部分,它仍然会运行。


Mah*_*zad 5

Kotlin 运行器现已预安装在 GitHub Actions 环境中(GitHub 问题YouTube 视频)。
请参阅GitHub Actions 运行程序图像1以查看所有已安装的软件。

因此,您可以轻松运行.main.kts脚本,如下所示:

name: Example

on:
  push:
    branches:
      - main

jobs:
  example-action:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Run the script
        run: kotlin /path/in/repo/to/my-script.main.kts
Run Code Online (Sandbox Code Playgroud)

这是my-script.main.kts文件的示例:

@file:JvmName("MyScript")
@file:CompilerOptions("-jvm-target", "11")
@file:Repository("https://repo.maven.apache.org/maven2")
// @file:DependsOn("com.example:library:1.2.3")

import java.io.File

val input = File("README.md") // Assuming you ran checkout before
val output = File("result.txt")
val readmeFirstLine = input.readLines().first()
output.writeText(readmeFirstLine)
Run Code Online (Sandbox Code Playgroud)

还有一个名为setup-kotlin的 GitHub 操作,可让您安装所需版本的 Kotlin,并提供更多功能。看看这个问题

...
  - uses: actions/checkout@v3
  - uses: fwilhe2/setup-kotlin@main
    with:
      version: 1.7.0
  - name: Run the script
    run: kotlin /path/in/repo/to/my-script.main.kts
Run Code Online (Sandbox Code Playgroud)
  1. 它以前被称为虚拟环境

  • 使用 shebang `#!/usr/bin/env kotlin` 我敢打赌,您甚至可以将其简化为 `run: /path/in/repo/to/my-script.main.kts` (2认同)