-1

我目前的情况是,我需要在 Jenkins 服务器上触发状态为“icon-red”的所有作业,这些作业由给定的用户特定视图(my-views)选择。问题是列表很长,我们不想手动触发它们。这就是为什么我想到使用 Groovy 脚本(Jenkins 的脚本控制台)的原因。

我可以使用如下编码触发给定全局视图的所有红色作业:

def viewName = "globalviewname"
def jobsToBuild = Jenkins.instance.getView(viewName).items.findAll { job ->
    job.getBuildStatusIconClassName() == "icon-red"
}

jobsToBuild.each { job ->
    println "Scheduling matching job ${job.name}"
    job.scheduleBuild(new Cause.UserIdCause())
}

但是,我缺乏访问当前用户视图的方法(稍后将成为参数):调用

Jenkins.instance.getViews()

仅提供所有全局视图的列表。我目前正在玩

Jenkins.instance.getMyViewsTabBar()

(另见http://javadoc.jenkins-ci.org/jenkins/model/Jenkins.html#getMyViewsTabBar()),但显然我没有掌握它。

任何线索如何访问与用户特定列表视图关联的项目列表?

4

1 回答 1

0

我想我自己设法找到了:

假设该变量username包含我们想要获取的视图的用户名,并且该变量viewname包含我们想要检索的视图的名称,那么下面的 Groovy 原型代码就可以为我解决问题:

def user = User.get(username, false, null)
if (user == null) {
  throw new Error("User does not exists")
}
println "Reading data from user "+user.toString()

// retrieve all UserProperties of this user and filter on the MyViewsProperty
def allMyViewsProperties = user.getAllProperties().findAll { 
  uprop -> (uprop instanceof hudson.model.MyViewsProperty) 
}
if (allMyViewsProperties.size() == 0) {
  throw new Error("MyViewsProperties does not exists")
}

// retrieve all views which are assigned to the MyViewsProperty.
// note that there also is a AllViewsProperty
def allPersonalViewsOfUser = allMyViewsProperties[0].getViews()

// further narrow down only to ListViews (special use case for me)
def allPersonalListViews = allPersonalViewsOfUser.findAll { 
  view -> view instanceof hudson.model.ListView 
}

// based on its name, filter on the view we want to retrieve
def listView = allPersonalListViews.findAll { view -> viewname.equals(view.getViewName()) }
if (listView.size() != 1) {
  throw new Error("selected view does not exist");
}

// get the view now
def view = listView[0]

鉴于这一切,现在很容易通过运行来触发此视图的状态为红色的所有作业

def jobsToBuild = view.items.findAll { job ->
    job.getBuildStatusIconClassName() == "icon-red"
}

jobsToBuild.each { job ->
    println "Scheduling matching job ${job.name}"
    job.scheduleBuild(new Cause.UserIdCause())
}
于 2016-05-21T20:57:48.253 回答