Skip to content

Instantly share code, notes, and snippets.

@rmcgibbo
Created August 23, 2012 07:22
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save rmcgibbo/3433798 to your computer and use it in GitHub Desktop.
Save rmcgibbo/3433798 to your computer and use it in GitHub Desktop.
Jenkins setup to automatically comment on github commits with build status
// Using the Jenkins Groovy Post build plugin to execute the following after every build
// https://wiki.jenkins-ci.org/display/JENKINS/Groovy+Postbuild+Plugin
// It would be nice not to have to specify these here... the repo name should be available within the hudson
// api somehow, but I didn't know how to get it. The access token should maybe be saved in a config file, and
// read in at runtime?
GITHUB_REPO_NAME = 'myusername/myreponame'
GITHUB_ACCESS_TOKEN = 'my_github_api_v3_access_token'
env = manager.build.getEnvironment(manager.listener)
if(manager.build.result == hudson.model.Result.SUCCESS) {
COMMENT = "This commit <a href=${env.BUILD_URL}>passes</a>"
} else {
COMMENT = "This commit <a href=${env.BUILD_URL}>fails</a>"
}
pb = new ProcessBuilder('python', '/var/lib/jenkins/github_comment_on_commit.py')
pb.environment().put('GITHUB_ACCESS_TOKEN', GITHUB_ACCESS_TOKEN)
pb.environment().put('GITHUB_REPO_NAME', GITHUB_REPO_NAME)
pb.environment().put('GIT_COMMIT', env.GIT_COMMIT)
pb.environment().put('COMMENT', COMMENT)
p = pb.start()
p.waitFor()
manager.listener.logger.println p.text
# /var/lib/jenkins/github_comment_on_commit.py
import sys, os
sys.stderr = sys.stdout # helpful for debugging groovy calling, so we dont have to check stderr
# using https://github.com/jacquev6/PyGithub, (pip install PyGithub)
from github import Github
access_token = os.environ['GITHUB_ACCESS_TOKEN']
repo_name = os.environ['GITHUB_REPO_NAME']
commit = os.environ['GIT_COMMIT']
comment = os.environ['COMMENT']
github_user, repo_short_name = repo_name.split('/')
g = Github(access_token)
user = g.get_user(github_user)
repo = user.get_repo(repo_short_name)
commit = repo.get_commit(commit)
commit.create_comment(comment)
print 'python github comment script finished sucessfully'
@rmcgibbo
Copy link
Author

rmcgibbo commented Sep 4, 2012

And to generate the github access token,

$ curl -u vsp-jenkins-bot https://api.github.com/authorizations -d '{"scopes":["repo"]}'
where vsp-jenkins-bot is the github username I'm using for the comments to be listed under.

@swis
Copy link

swis commented Jan 12, 2013

If one wants to repeat the original commit message, one can replace

commit.create_comment(comment)

by

commit.create_comment(comment + " " + commit.commit.message)

(Useful, if you mentioned an issue in the message and the build status should go into the issue, too)

Copy link

ghost commented Oct 22, 2020

How can you revert a commit?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment