Dangerfile and Git and GitHub
To someone unfamiliar with the internal workings of Danger, it’s not particularly obvious how one is meant to interact with Git and GitHub inside the Dangerfile.
Here’s the deal: Danger has built-in “plugins” for Git and GitHub (and others). The best explanation of their methods and examples are to be found in the source code, to which I have linked below.
git
At Tanda, we currently use three git methods in our Danger config: git.diff
, git.added_files
, and git.modified_files
. The latter returns an Array-like object that comes in handy sometimes:
if git.modified_files.any? {|f| f.end_with?("_endpoint.rb")}
warn "Make sure we QA these API changes."
end
github
You can pull a tonne of information out of GitHub using this plugin.
if github.branch_for_base != "master"
warn "The base branch should be master."
endif (github.pr_labels & ["bug", "feature"]).count != 1
warn "Please specify the appropriate label."
end
A lot of these methods are just wrappers for the JSON response from the GitHub API. You need to work with this response directly sometimes (via github.pr_json
) when there is no helper method, as is the case with assignees:
if github.pr_json["assignees"].count == 0
warn "This PR has no assignees."
end
Unfortunately the documented response is either incomplete or outdated. The assignees
key, for example, is missing from their docs.
Here’s what we learned about reviewers: a reviewer is only considered “requested” until they have reviewed. This means that two API calls are required to keep track of all the reviewers. github.api
returns the Octokit client instance which helps you out here with the pull_request_reviews
method:
requested_reviewers = github.pr_json["requested_reviewers"]pr_num = github.pr_json["number"]
reviews = github.api.pull_request_reviews("dhaigh/my-repo", pr_num)
actual_reviewers = reviews.map {|u| u["user"]}reviewers = requested_reviewers + actual_reviewers
Here are the Octokit docs on pull requests. For whatever reason, the Octokit docs on pull request reviews is a separate module. There are loads of modules in Octokit; check out the sidebar on the left.
That’s all I got. 👋