Skip to content

Commit

Permalink
fix error in pipelineDef
Browse files Browse the repository at this point in the history
  • Loading branch information
Rubentxu committed Nov 8, 2023
1 parent 7c28753 commit f9b60e9
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 18 deletions.
17 changes: 10 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,28 +25,28 @@ El argumento `--class-path` especifica la ruta al archivo JAR que se va a compil
#### Ejecutar

```bash
$ java -jar pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar -c pipeline-cli/src/test/resources/config.yaml -s pipeline-cli/src/test/resources/HelloWorld.pipeline.kts
$ java -jar pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar -c pipeline-cli/testData/config.yaml -s pipeline-cli/testData/HelloWorld.pipeline.kts
```
Este comando ejecuta el archivo JAR generado utilizando el comando `java -jar`. Los argumentos `-c` y `-s` son probablemente opciones específicas de la aplicación, que especifican la ubicación de un archivo de configuración y un script, respectivamente.

---

```bash
$ java -cp pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar dev.rubentxu.pipeline.cli.PipelineCliKt -c pipeline-cli/src/test/resources/config.yaml -s pipeline-cli/src/test/resources/HelloWorld.pipeline.kts
$ java -cp pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar dev.rubentxu.pipeline.cli.PipelineCliKt -c pipeline-cli/testData/config.yaml -s pipeline-cli/testData/HelloWorld.pipeline.kts
```
Este comando es similar al anterior, pero en lugar de usar `-jar`, usa `-cp` (classpath) para especificar el archivo JAR y luego proporciona la clase principal que se debe ejecutar. Los argumentos `-c` y `-s` funcionan de la misma manera que en el comando anterior.

---

```bash
$ ./pipeline-kts -c pipeline-cli/src/test/resources/config.yaml -s pipeline-cli/src/test/resources/HelloWorld.pipeline.kts
$ ./pipeline-kts -c pipeline-cli/testData/config.yaml -s pipeline-cli/testData/HelloWorld.pipeline.kts
```
Este comando ejecuta la imagen nativa generada por el comando `native-image`. Nuevamente, los argumentos `-c` y `-s` especifican la ubicación de un archivo de configuración y un script, respectivamente.

---

```bash
$ kotlinc -script pipeline-cli/src/test/resources/HelloWorld.pipeline.kts -classpath pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar
$ kotlinc -script pipeline-cli/testData/HelloWorld.pipeline.kts -classpath pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar
```
Este comando utiliza el compilador de Kotlin `kotlinc` para ejecutar un script de Kotlin. El argumento `-script` especifica la ubicación del script que se va a ejecutar, y `-classpath` especifica la ruta al archivo JAR que contiene las clases y recursos necesarios para ejecutar el script.

Expand Down Expand Up @@ -82,19 +82,22 @@ The `--class-path` argument specifies the path to the JAR file to be compiled. `
#### Run

```bash
$ java -jar pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar -c pipeline-cli/src/test/resources/config.yaml -s pipeline-cli/src/test/resources/HelloWorld.pipeline.kts
$ java -jar pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar -c pipeline-cli/testData/config.yaml -s pipeline-cli/testData/HelloWorld.pipeline.kts
```
This command runs the generated JAR file using the `java -jar` command. The `-c` and `-s` arguments are likely application-specific options, specifying the location of a configuration file and a script, respectively.

---

```bash
$ java -cp pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar dev.rubentxu.pipeline.cli.PipelineCliKt -c pipeline-cli/src/test/resources/config.yaml -s pipeline-cli/src/test/resources/HelloWorld.pipeline.kts
$ java -cp pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar dev.rubentxu.pipeline.cli.PipelineCliCommand -c pipeline-cli/testData/config.yaml -s pipeline-cli/testData/HelloWorld.pipeline.kts
```
This command is similar to the previous one, but instead of using `-jar`, it uses `-cp` (classpath) to specify the JAR file and then provides the main class to be run. The `-c` and `-s` arguments work in the same way as in the previous command.

---

```bash
$ ./pipeline-kts -c pipeline-cli/testData/config.yaml -s pipeline-cli/testData/HelloWorld.pipeline.kts
```
```bash
$ ./pipeline-kts -c pipeline-cli/src/test/resources/config.yaml -s pipeline-cli/src/test/resources/HelloWorld.pipeline.kts
```
Expand All @@ -103,6 +106,6 @@ This command runs the native image generated by the `native-image` command. Agai
---

```bash
$ kotlinc -script pipeline-cli/src/test/resources/HelloWorld.pipeline.kts -classpath pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar
$ kotlinc -script pipeline-cli/testData/HelloWorld.pipeline.kts -classpath pipeline-cli/build/libs/pipeline-cli-1.0-SNAPSHOT-all.jar
```
This command uses the Kotlin compiler `kotlinc` to run a Kotlin script. The `-script` argument specifies the location of the script to be run, and `-classpath` specifies the path to the JAR file containing the classes and resources necessary to run the script.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import org.slf4j.LoggerFactory
*/
class PipelineLogger(
private var logLevel: LogLevel,
private val logConfigurationStrategy: LogConfigurationStrategy = ConsoleLogConfigurationStrategy()
val logConfigurationStrategy: LogConfigurationStrategy = ConsoleLogConfigurationStrategy()
) : IPipelineLogger {

private val logger = LoggerFactory.getLogger(PipelineLogger::class.java)
Expand Down Expand Up @@ -242,10 +242,17 @@ class PipelineLogger(
}

private fun createBanner(msgs: List<String>): String {
val messageLines = msgFlatten(mutableListOf(), msgs.filter { it.isNotEmpty() })
// Obtener la longitud de la línea más larga
val maxLength = messageLines.maxOf { it.length }
// Crear la línea de '=' multiplicada
val separator = "=".repeat(maxLength+7)
return """
|===========================================
|${msgFlatten(mutableListOf(), msgs.filter { it.isNotEmpty() }).joinToString("\n")}
|===========================================
|
| $separator
| ${messageLines.joinToString("\n ")}
| $separator
|
""".trimMargin()
}

Expand Down
1 change: 1 addition & 0 deletions pipeline-cli/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dependencies {
implementation("io.micronaut.kotlin:micronaut-kotlin-runtime")
implementation("io.micronaut.picocli:micronaut-picocli")
implementation("io.micronaut.serde:micronaut-serde-jackson")
implementation("ch.qos.logback:logback-classic:1.4.11")

implementation("org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlinVersion")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package dev.rubentxu.pipeline.cli


import ch.qos.logback.classic.Logger
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.kotlin.readValue
import io.micronaut.configuration.picocli.PicocliRunner
import org.slf4j.LoggerFactory
import picocli.CommandLine.Command
import picocli.CommandLine.Option
import java.io.File
import java.nio.file.Path
import ch.qos.logback.classic.LoggerContext

@Command(name = "pipeline-cli", description = ["..."], mixinStandardHelpOptions = true)
class PipelineCliCommand : Runnable {
Expand Down Expand Up @@ -36,6 +39,16 @@ class PipelineCliCommand : Runnable {
val configuration = readConfigFile(normalizeAndAbsolutePath(configPath))

evalWithScriptEngineManager(File(normalizeAndAbsolutePath(scriptPath)))


detachAndStopAllAppenders()
}

private fun detachAndStopAllAppenders() {
// Stop all appenders from showing micronaut related traces
val loggerContext = LoggerFactory.getILoggerFactory() as LoggerContext
val rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME)
rootLogger.detachAndStopAllAppenders()
}

fun readConfigFile(configFilePath: String): Config {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,33 @@ package dev.rubentxu.pipeline.cli

import dev.rubentxu.pipeline.dsl.PipelineDefinition
import dev.rubentxu.pipeline.dsl.PipelineExecutor
import dev.rubentxu.pipeline.logger.LogLevel
import dev.rubentxu.pipeline.logger.PipelineLogger
import java.io.File

fun evalWithScriptEngineManager(scriptFile: File): Any? {
val logger = PipelineLogger(LogLevel.TRACE)
val engine = javax.script.ScriptEngineManager().getEngineByExtension("kts")!!
val pipelineDef = engine.eval(scriptFile.reader())
if (pipelineDef is PipelineDefinition) {
return PipelineExecutor().execute(pipelineDef)
try {

val pipelineDef = engine.eval(scriptFile.reader())
if (pipelineDef is PipelineDefinition) {
return PipelineExecutor(logger).execute(pipelineDef)
}

return pipelineDef
} catch (e: Exception) {
val regex = """ERROR (.*) expected \(ScriptingHost.*.kts:(\d+):(\d+)\)""".toRegex()

val match = regex.find(e.message?:"")
if (match == null) {
logger.error("Error in Pipeline definition ::: ${e.message}")
}
val (error, line, space) = match!!.destructured

logger.errorBanner(listOf("Error in Pipeline definition: $error","Line: $line","Space: $space"))
return null
}
return pipelineDef


}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import io.micronaut.context.env.Environment
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.PrintStream
import kotlin.script.experimental.jvm.util.isError

class PipelineScriptRunnerKtTest : StringSpec({

Expand All @@ -25,7 +24,7 @@ class PipelineScriptRunnerKtTest : StringSpec({
}
//
"eval script pipeline dsl" {
val scriptFile = File("testData/HelloWorld.pipeline.kts")
val scriptFile = File("src/test/resources/HelloWorld.pipeline.kts")
val result = evalWithScriptEngineManager(scriptFile) as PipelineResult

println("result: $result")
Expand All @@ -35,6 +34,27 @@ class PipelineScriptRunnerKtTest : StringSpec({

}

"eval regex" {

val errorMessage = """
javax.script.ScriptException: ERROR Function invocation 'any(...)' expected (ScriptingHost474821de_Line_0.kts:9:11)
"""

// El resto del código es igual

val regex = """ERROR (.*) expected \(ScriptingHost.*.kts:(\d+):(\d+)\)""".toRegex()

val match = regex.find(errorMessage) ?: throw RuntimeException("No se pudo parsear el error")

val (error, line, space) = match.destructured

println("Error in Pipeline definition: $error")
println("Line: $line")
println("Space: $space")


}

"eval with script manager pipeline dsl" {
val scriptFile = File("testData/HelloWorld.pipeline.kts")

Expand Down
25 changes: 24 additions & 1 deletion pipeline-cli/testData/HelloWorld.pipeline.kts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import kotlinx.coroutines.delay
println("HOLA MUNDO..................................................")

pipeline {
agent(any)

environment {
"DISABLE_AUTH" += "true"
"DB_ENGINE" += "sqlite"
Expand All @@ -27,13 +27,36 @@ pipeline {
sh("pwd", returnStdout=true)
echo("Variable de entorno para DB_ENGINE es ${env["DB_ENGINE"]}")
}
post {
always {
echo("This is the post section always in stage Test")
}

failure {
echo("This is the post section failure in stage Test")
}
}
}
stage("Test") {
steps {
sh("ls -la", returnStdout=true)
echo("Tests complete")
sh("ls -la /home", returnStdout=true)
}

}
}
post {
always {
echo("This is the post section always")
}

success {
echo("This is the post section success")
}

failure {
echo("This is the post section failure")
}
}
}

0 comments on commit f9b60e9

Please sign in to comment.