Groovy web console

subscribe to the feed Subscribe
to this
site

Code Generation From GString Templates

Published 2 months ago by zett42 with tags GString templates
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
String method2(String tier, String jobName) {
    indented """
        Map downstreamJobs = [:]
        stage ("${jobName}-${tier}-\${region}_${jobName}") {
            test
        }
    """
}

String simpleLog() {
    indented """\
        script {
           def user = env.BUILD_USER_ID
        }
    """
}

String method1() {
    indented """\
        import jenkins.model.Jenkins
        currentBuild.displayName = "name"
        
        ${simpleLog()}
    """
}

String generateFullDeploymentPipelineCode() {
    indented """\
        Text here
        ${method1()}
        ${method2("test1", "test2")}
    """
}

println generateFullDeploymentPipelineCode()

//---------- Move the following code into its own script ----------

String indented( GString templ ) {
    
    // Iterate over the interpolated values of the GString template.
    templ.values.eachWithIndex{ value, i ->

        // Get the string preceding the current value. Always defined, even
        // when the value is at the beginning of the template.
        def beforeValue = templ.strings[ i ]
        
        // RegEx to match any indent substring before the value.
        // Special case for the first string, which doesn't necessarily contain '\n'. 
        def regexIndent = i == 0
                          ? /(?:^|\n)([ \t]+)$/
                          : /\n([ \t]+)$/
        
        def matchIndent = ( beforeValue =~ regexIndent )
        if( matchIndent ) {
            def indent = matchIndent[ 0 ][ 1 ]
            def lines = value.readLines()
            def linesNew = [ lines.head() ]  // The 1st line is already indented.
            // Insert the indentation from the 1st line into all subsequent lines.
            linesNew += lines.tail().collect{ indent + it }
            // Finally replace the value with the reformatted lines.
            templ.values[ i ] = linesNew.join('\n')
        }
    }

    return templ.stripIndent()
}

String indented( String templ ) {
    return templ.stripIndent()  
}