반응형

Basic

Closure closure = {
    append("I'm inside a closure")
}

StringBuilder sb = new StringBuilder()
closure.delegate = sb
closure.call()

// success
assert sb.toString() == "I'm inside a closure"

No DELEGATE_FIRST

void append(String text) {
    println text
}

Closure closure = {
    append("I'm inside a closure")
}

StringBuilder sb = new StringBuilder()
closure.delegate = sb
closure.call()

assert sb.toString() == ""

DELEGATE_FIRST

void append(String text) {
    println text
}

Closure closure = {
    append("I'm inside a closure")
}

StringBuilder sb = new StringBuilder()
closure.delegate = sb
closure.resolveStrategy = Closure.DELEGATE_FIRST
closure.call()

assert sb.toString() == "I'm inside a closure"

Custom

  • Triggers.groovy
    package jenkins
    
    class Triggers {
        String cron
    
        void cron(cron) {
            this.cron = cron
        }
    }
  • Stage.groovy
    package jenkins
    
    class Stage {
        String desc
        Closure func
    
        Stage(desc, func) {
            this.desc = desc
            this.func = func
        }
    }
  • Pipeline.groovy
    package jenkins
    
    class Pipeline {
        String agent
        Triggers triggers
        List<Stage> stages = []
    
        def agent(agent) {
            this.agent = agent
        }
    
        def triggers(closure) {
            closure.rehydrate(triggers = new Triggers(), this, this)()
        }
    
        def stages(Closure closure) {
            closure.rehydrate(this, this, this)()
        }
    
        def stage(desc, closure) {
            stages << new Stage(desc, closure)
        }
    }
  • test.groovy
    import jenkins.Pipeline
    
    def pipeline(closure) {
        def pipeline = new Pipeline()
        closure.rehydrate(pipeline, this, this)()
        pipeline
    }
    
    def pipeline = pipeline {
        agent "any"
    
        triggers {
            cron "* * * * *"
        }
    
        stages {
            stage("test-1") {
                println "zzzz"
            }
    
            stage("test-2") {
                println "ffff"
            }
        }
    }
    
    pipeline.stages.each { stage ->
        println stage.desc
        stage.func()
    }

참고

반응형

'Development > Groovy' 카테고리의 다른 글

[Groovy] 자바에서 groovy script 실행  (0) 2020.12.28
[Groovy] DSL 공식문서 코드  (0) 2020.12.28
[Groovy] 기본 문법  (0) 2020.12.28
[Groovy] 설치  (0) 2020.12.28

+ Recent posts