jenkinsci / ghprb-plugin

github pull requests builder plugin for Jenkins
https://plugins.jenkins.io/ghprb/
MIT License
506 stars 612 forks source link

Example init.groovy script uses wrong type for Secret #753

Open SpComb opened 5 years ago

SpComb commented 5 years ago

The following groovy script example from the README is broken: https://github.com/jenkinsci/ghprb-plugin/blob/master/README.md#using-groovy

...
String secret = null
githubAuths.add(new GhprbGitHubAuth(serverAPIUrl, jenkinsUrl, credentialsId, description, id, secret))
jenkins_1                | WARNING: Failed to run script file:/var/jenkins_home/init.groovy.d/21-ghprb.groovy
jenkins_1                | groovy.lang.GroovyRuntimeException: Could not find matching constructor for: org.jenkinsci.plugins.ghprb.GhprbGitHubAuth(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)

The secret param needs to be a hudson.util.Secret instead:

import hudson.util.Secret

...
Secret secret = Secret.fromString(...)
SpComb commented 5 years ago

Here's a complete example for configuring a GhprbGitHubAuth from envs. A new auth is added for the JENKINS_GHPRB_AUTH_ID if it doesn't yet exist, but it's not updated if the envs change. #701 CaC support would be ideal.

import java.util.logging.Logger
import jenkins.model.Jenkins
import hudson.util.Secret
import org.jenkinsci.plugins.ghprb.*

def env = System.getenv()
def logger = Logger.getLogger("init-ghprb")
def instance = Jenkins.getInstance()

def descriptor = instance.getDescriptorByType(org.jenkinsci.plugins.ghprb.GhprbTrigger.DescriptorImpl.class)

if (env.JENKINS_GHPRB_AUTH_ID) {
  String serverAPIUrl = ""
  String jenkinsUrl = ""
  String credentialsId = env.JENKINS_GITHUB_CREDENTIALS
  String description = 'GitHub'
  String id = env.JENKINS_GHPRB_AUTH_ID
  Secret secret = env.JENKINS_GHPRB_HOOK_SECRET ? Secret.fromString(env.JENKINS_GHPRB_HOOK_SECRET) : null

  // find matching
  githubAuths = descriptor.getGithubAuth()
  githubAuth = null;

  for (a in githubAuths) {
    if (a.id == id) {
      githubAuth = a;
    }
  }

  logger.info("Find GitHub PR Builder auth " + id + ": " + githubAuth)

  // add if missing
  if (!githubAuth) {
    logger.info("Configure GitHub PR Builder auth " + id + ": credentialsId=" + credentialsId)

    githubAuth = new GhprbGitHubAuth(serverAPIUrl, jenkinsUrl, credentialsId, description, id, secret)

    githubAuths.add(githubAuth)

    descriptor.save()
  }
}