如何使用 Groovy 访问 Jenkins 服务器的用户特定视图的作业?

How can I access the jobs of a user-specific view of a Jenkins Server using Groovy?

我目前的情况是我需要在 Jenkins 服务器上触发状态为 "icon-red" 的所有作业,这些作业由给定的 user 特定视图选择(我的观点)。问题是列表很长,我们不想全部手动触发。 这就是为什么我想到使用 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()),但显然我没有掌握它。

知道如何访问与特定于用户的列表视图关联的项目列表吗?

我想我自己找到了:

  • Jenkins 中用户的个人观点是给定用户 UserProperties 的一部分。
  • 每个用户可能有多个 UserProperty - 正确的 UserProperty 是 MyViewProperty

假设变量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())
}