Jonke
Jonke

Reputation: 6533

Setting an upstreamproject in Jenkins using groovy

I would like to copy a FreeStyleProject to a new job and then set a new upstreamproject to this new job using groovy. I can't find any method on Class FreeStyleProject that let me do that: set a new upstreamproject. Is there some other method or trick that can accomplish this?

def x = "testproj"
def hi=hi.getItem(x)
hi.copy(x, "Copy"+x); 
def newjob=hi.getItem("Copy"+x)
//newjob.setUpstreamProject("bar") //<<--?
  def di = newjob.getUpstreamProjects()

     for ( y in di ) {

      println(y.name)
}

Update: For clarification:

Job A ====> Job B (A is upstream)

I want to copy Both jobs so i get i

Job A' and Job B' and then set A' or B' so I get A' =====> Job B' (A' is upstream)

I think I need to remove a build trigger and create a new build trigger (that is what creates the upstream/downstream concept it seems)

Upvotes: 1

Views: 1478

Answers (1)

Jonke
Jonke

Reputation: 6533

With a sample of Two FreeStyle projects and one downstream, this snip will found the TestTop and set them to the existing TopTest2. The concept is to get the buildtriggers with the help of getPublishersList on a project and then get the hudson.tasks.BuildTrigger.class of these.

For each of these do a
publishlist.remove(aa) publishlist.add( new hudson.tasks.BuildTrigger("TestTop2", false))

def hudsonInstance = hudson.model.Hudson.instance 
hudsonInstance.getItems(hudson.model.Project).each {project ->

  if (project.displayName== "TestTop"){
    println(project.displayName)
    def di = project.getUpstreamProjects()
    def triggers=project.getBuildTriggerUpstreamProjects()
    for (z in triggers){
      println("triggers " + z.getDisplayName())

      def pubList = z.getPublishersList()
      for(w in pubList){

        println(w)

        def buildTrigger = w.grep(hudson.tasks.BuildTrigger.class) 

        println("BT " + buildTrigger)
        for(aa in buildTrigger){
          println("aa " + aa.getChildProjectsValue())
          def newtop =  hudsonInstance.getItem("TestTop2")
          pubList.remove(aa)
          pubList.add( new hudson.tasks.BuildTrigger("TestTop2", false)) 
        }               
      }
    }   
  }
}
hudsonInstance.rebuildDependencyGraph()

Upvotes: 2

Related Questions