Class: Danger::RequestSources::GitHub
- Inherits:
-
RequestSource
- Object
- RequestSource
- Danger::RequestSources::GitHub
- Includes:
- Helpers::CommentsHelper
- Defined in:
- lib/danger/request_source/github.rb
Constant Summary
Constants inherited from RequestSource
RequestSource::DANGER_REPO_NAME
Instance Attribute Summary collapse
-
#issue_json ⇒ Object
Returns the value of attribute issue_json.
-
#pr_json ⇒ Object
Returns the value of attribute pr_json.
-
#support_tokenless_auth ⇒ Object
Returns the value of attribute support_tokenless_auth.
Attributes inherited from RequestSource
#ci_source, #environment, #ignored_violations
Instance Method Summary collapse
- #api_url ⇒ Object
- #client ⇒ Object
-
#delete_old_comments!(except: nil, danger_id: "danger") ⇒ Object
Get rid of the previously posted comment, to only have the latest one.
- #fetch_details ⇒ Object
- #fetch_issue_details(pr_json) ⇒ Object
-
#file_url(organisation: nil, repository: nil, branch: "master", path: nil) ⇒ String
A URL to the specific file, ready to be downloaded.
- #find_position_in_diff(diff_lines, message) ⇒ Object
- #host ⇒ Object
- #ignored_violations_from_pr(pr_json) ⇒ Object
-
#initialize(ci_source, environment) ⇒ GitHub
constructor
A new instance of GitHub.
- #issue_comments ⇒ Object
- #markdown_link_to_message(message, hide_link) ⇒ Object
- #messages_are_equivalent(m1, m2) ⇒ Object
-
#organisation ⇒ String
The organisation name, is nil if it can’t be detected.
-
#parse_message_from_row(row) ⇒ Object
See the tests for examples of data coming in looks like.
- #pr_diff ⇒ Object
- #scm ⇒ Object
- #setup_danger_branches ⇒ Object
- #submit_inline_comments!(warnings: [], errors: [], messages: [], markdowns: [], previous_violations: [], danger_id: "danger") ⇒ Object
- #submit_inline_comments_for_kind!(emoji, messages, diff_lines, danger_comments, previous_violations, danger_id: "danger") ⇒ Object
- #submit_pull_request_status!(warnings: [], errors: [], details_url: []) ⇒ Object
-
#update_pull_request!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger") ⇒ Object
Sending data to GitHub.
- #validates_as_api_source? ⇒ Boolean
Methods included from Helpers::CommentsHelper
#apply_template, #character_from_emoji, #generate_comment, #generate_description, #generate_inline_comment_body, #generate_inline_markdown_body, #markdown_parser, #parse_comment, #process_markdown, #random_compliment, #table
Methods included from Helpers::CommentsParsingHelper
#parse_comment, #parse_tables_from_comment, #table_kind_from_title, #violations_from_table
Methods inherited from RequestSource
available_request_sources, inherited, #validates_as_ci?
Constructor Details
#initialize(ci_source, environment) ⇒ GitHub
Returns a new instance of GitHub.
12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/danger/request_source/github.rb', line 12 def initialize(ci_source, environment) self.ci_source = ci_source self.environment = environment self.support_tokenless_auth = false Octokit.auto_paginate = true @token = @environment["DANGER_GITHUB_API_TOKEN"] if api_url Octokit.api_endpoint = api_url end end |
Instance Attribute Details
#issue_json ⇒ Object
Returns the value of attribute issue_json.
10 11 12 |
# File 'lib/danger/request_source/github.rb', line 10 def issue_json @issue_json end |
#pr_json ⇒ Object
Returns the value of attribute pr_json.
10 11 12 |
# File 'lib/danger/request_source/github.rb', line 10 def pr_json @pr_json end |
#support_tokenless_auth ⇒ Object
Returns the value of attribute support_tokenless_auth.
10 11 12 |
# File 'lib/danger/request_source/github.rb', line 10 def support_tokenless_auth @support_tokenless_auth end |
Instance Method Details
#api_url ⇒ Object
36 37 38 39 40 41 |
# File 'lib/danger/request_source/github.rb', line 36 def api_url # `DANGER_GITHUB_API_HOST` is the old name kept for legacy reasons and # backwards compatibility. `DANGER_GITHUB_API_BASE_URL` is the new # correctly named variable. @environment["DANGER_GITHUB_API_HOST"] || @environment["DANGER_GITHUB_API_BASE_URL"] end |
#client ⇒ Object
43 44 45 46 |
# File 'lib/danger/request_source/github.rb', line 43 def client raise "No API token given, please provide one using `DANGER_GITHUB_API_TOKEN`" if !@token && !support_tokenless_auth @client ||= Octokit::Client.new(access_token: @token) end |
#delete_old_comments!(except: nil, danger_id: "danger") ⇒ Object
Get rid of the previously posted comment, to only have the latest one
191 192 193 194 195 196 197 |
# File 'lib/danger/request_source/github.rb', line 191 def delete_old_comments!(except: nil, danger_id: "danger") issue_comments.each do |comment| next unless comment.generated_by_danger?(danger_id) next if comment.id == except client.delete_comment(ci_source.repo_slug, comment.id) end end |
#fetch_details ⇒ Object
65 66 67 68 69 70 71 72 73 |
# File 'lib/danger/request_source/github.rb', line 65 def fetch_details self.pr_json = client.pull_request(ci_source.repo_slug, ci_source.pull_request_id) if self.pr_json[:message] == "Moved Permanently" raise "Repo moved or renamed, make sure to update the git remote".red end fetch_issue_details(self.pr_json) self.ignored_violations = ignored_violations_from_pr(self.pr_json) end |
#fetch_issue_details(pr_json) ⇒ Object
81 82 83 84 |
# File 'lib/danger/request_source/github.rb', line 81 def fetch_issue_details(pr_json) href = pr_json[:_links][:issue][:href] self.issue_json = client.get(href) end |
#file_url(organisation: nil, repository: nil, branch: "master", path: nil) ⇒ String
Returns A URL to the specific file, ready to be downloaded.
380 381 382 383 |
# File 'lib/danger/request_source/github.rb', line 380 def file_url(organisation: nil, repository: nil, branch: "master", path: nil) organisation ||= self.organisation "https://raw.githubusercontent.com/#{organisation}/#{repository}/#{branch}/#{path}" end |
#find_position_in_diff(diff_lines, message) ⇒ Object
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
# File 'lib/danger/request_source/github.rb', line 299 def find_position_in_diff(diff_lines, ) range_header_regexp = /@@ -([0-9]+),([0-9]+) \+(?<start>[0-9]+)(,(?<end>[0-9]+))? @@.*/ file_header_regexp = %r{ a/.*} pattern = "+++ b/" + .file + "\n" file_start = diff_lines.index(pattern) return nil if file_start.nil? position = -1 file_line = nil diff_lines.drop(file_start).each do |line| match = line.match range_header_regexp # file_line is set once we find the hunk the line is in # we need to count how many lines in new file we have # so we do it one by one ignoring the deleted lines if !file_line.nil? && !line.start_with?("-") break if file_line == .line file_line += 1 end # We need to count how many diff lines are between us and # the line we're looking for position += 1 next unless match # If we found the start of another file diff, we went too far break if line.match file_header_regexp range_start = match[:start].to_i if match[:end] range_end = match[:end].to_i + range_start else range_end = range_start end # We are past the line position, just abort break if .line < range_start next unless .line >= range_start && .line <= range_end file_line = range_start end position unless file_line.nil? end |
#host ⇒ Object
32 33 34 |
# File 'lib/danger/request_source/github.rb', line 32 def host @host = @environment["DANGER_GITHUB_HOST"] || "github.com" end |
#ignored_violations_from_pr(pr_json) ⇒ Object
75 76 77 78 79 |
# File 'lib/danger/request_source/github.rb', line 75 def ignored_violations_from_pr(pr_json) pr_body = pr_json[:body] return [] if pr_body.nil? pr_body.chomp.scan(/>\s*danger\s*:\s*ignore\s*"(.*)"/i).flatten end |
#issue_comments ⇒ Object
86 87 88 89 |
# File 'lib/danger/request_source/github.rb', line 86 def issue_comments @comments ||= client.issue_comments(ci_source.repo_slug, ci_source.pull_request_id) .map { |comment| Comment.from_github(comment) } end |
#markdown_link_to_message(message, hide_link) ⇒ Object
361 362 363 364 365 366 367 368 369 |
# File 'lib/danger/request_source/github.rb', line 361 def (, hide_link) url = "https://github.com/#{ci_source.repo_slug}/blob/#{pr_json[:head][:sha]}/#{message.file}#L#{message.line}" if hide_link "<span data-href=\"#{url}\"/>" else "[#{message.file}#L#{message.line}](#{url}) - " end end |
#messages_are_equivalent(m1, m2) ⇒ Object
235 236 237 238 239 |
# File 'lib/danger/request_source/github.rb', line 235 def (m1, m2) blob_regexp = %r{blob/[0-9a-z]+/} m1.file == m2.file && m1.line == m2.line && m1..sub(blob_regexp, "") == m2..sub(blob_regexp, "") end |
#organisation ⇒ String
Returns The organisation name, is nil if it can’t be detected.
372 373 374 375 376 377 |
# File 'lib/danger/request_source/github.rb', line 372 def organisation matched = self.issue_json[:repository_url].match(%r{repos\/(.*)\/}) return matched[1] if matched && matched[1] rescue nil end |
#parse_message_from_row(row) ⇒ Object
See the tests for examples of data coming in looks like
349 350 351 352 353 354 355 356 357 358 359 |
# File 'lib/danger/request_source/github.rb', line 349 def (row) = %r{(<(a |span data-)href="https://github.com/#{ci_source.repo_slug}/blob/[0-9a-z]+/(?<file>[^#]+)#L(?<line>[0-9]+)"(>[^<]*</a> - |/>))?(?<message>.*?)}im match = .match(row) if match[:line] line = match[:line].to_i else line = nil end Violation.new(row, true, match[:file], line) end |
#pr_diff ⇒ Object
48 49 50 |
# File 'lib/danger/request_source/github.rb', line 48 def pr_diff @pr_diff ||= client.pull_request(ci_source.repo_slug, ci_source.pull_request_id, accept: "application/vnd.github.v3.diff") end |
#scm ⇒ Object
28 29 30 |
# File 'lib/danger/request_source/github.rb', line 28 def scm @scm ||= GitRepo.new end |
#setup_danger_branches ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/danger/request_source/github.rb', line 52 def setup_danger_branches # we can use a github specific feature here: base_commit = self.pr_json[:base][:sha] head_commit = self.pr_json[:head][:sha] # Next, we want to ensure that we have a version of the current branch at a known location self.scm.exec "branch #{EnvironmentManager.danger_base_branch} #{base_commit}" # OK, so we want to ensure that we have a known head branch, this will always represent # the head of the PR ( e.g. the most recent commit that will be merged. ) self.scm.exec "branch #{EnvironmentManager.danger_head_branch} #{head_commit}" end |
#submit_inline_comments!(warnings: [], errors: [], messages: [], markdowns: [], previous_violations: [], danger_id: "danger") ⇒ Object
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
# File 'lib/danger/request_source/github.rb', line 199 def submit_inline_comments!(warnings: [], errors: [], messages: [], markdowns: [], previous_violations: [], danger_id: "danger") # Avoid doing any fetchs if there's no inline comments return if (warnings + errors + ).select(&:inline?).empty? diff_lines = self.pr_diff.lines pr_comments = client.pull_request_comments(ci_source.repo_slug, ci_source.pull_request_id) danger_comments = pr_comments.select { |comment| comment[:body].include?("generated_by_#{danger_id}") } non_danger_comments = pr_comments - danger_comments submit_inline_comments_for_kind!("warning", warnings, diff_lines, danger_comments, previous_violations[:warning], danger_id: danger_id) submit_inline_comments_for_kind!("no_entry_sign", errors, diff_lines, danger_comments, previous_violations[:error], danger_id: danger_id) submit_inline_comments_for_kind!("book", , diff_lines, danger_comments, previous_violations[:message], danger_id: danger_id) submit_inline_comments_for_kind!(nil, markdowns, diff_lines, danger_comments, [], danger_id: danger_id) # submit removes from the array all comments that are still in force # so we strike out all remaining ones danger_comments.each do |comment| violation = violations_from_table(comment[:body]).first if !violation.nil? && violation.sticky body = generate_inline_comment_body("white_check_mark", violation, danger_id: danger_id, resolved: true, template: "github") client.update_pull_request_comment(ci_source.repo_slug, comment[:id], body) else # We remove non-sticky violations that have no replies # Since there's no direct concept of a reply in GH, we simply consider # the existance of non-danger comments in that line as replies replies = non_danger_comments.select do |potential| potential[:path] == comment[:path] && potential[:position] == comment[:position] && potential[:commit_id] == comment[:commit_id] end client.delete_pull_request_comment(ci_source.repo_slug, comment[:id]) if replies.empty? end end end |
#submit_inline_comments_for_kind!(emoji, messages, diff_lines, danger_comments, previous_violations, danger_id: "danger") ⇒ Object
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
# File 'lib/danger/request_source/github.rb', line 241 def submit_inline_comments_for_kind!(emoji, , diff_lines, danger_comments, previous_violations, danger_id: "danger") head_ref = pr_json[:head][:sha] previous_violations ||= [] is_markdown_content = emoji.nil? submit_inline = proc do |m| next false unless m.file && m.line position = find_position_in_diff diff_lines, m # Keep the change if it's line is not in the diff next false if position.nil? # Once we know we're gonna submit it, we format it if is_markdown_content body = generate_inline_markdown_body(m, danger_id: danger_id, template: "github") else # Hide the inline link behind a span m = process_markdown(m, true) body = generate_inline_comment_body(emoji, m, danger_id: danger_id, template: "github") # A comment might be in previous_violations because only now it's part of the unified diff # We remove from the array since it won't have a place in the table anymore previous_violations.reject! { |v| (v, m) } end matching_comments = danger_comments.select do |comment_data| if comment_data[:path] == m.file && comment_data[:commit_id] == head_ref && comment_data[:position] == position # Parse it to avoid problems with strikethrough violation = violations_from_table(comment_data[:body]).first if violation (violation, m) else comment_data[:body] == body end else false end end if matching_comments.empty? client.create_pull_request_comment(ci_source.repo_slug, ci_source.pull_request_id, body, head_ref, m.file, position) else # Remove the surviving comment so we don't strike it out danger_comments.reject! { |c| matching_comments.include? c } # Update the comment to remove the strikethrough if present comment = matching_comments.first client.update_pull_request_comment(ci_source.repo_slug, comment[:id], body) end # Remove this element from the array next true end .reject!(&submit_inline) end |
#submit_pull_request_status!(warnings: [], errors: [], details_url: []) ⇒ Object
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
# File 'lib/danger/request_source/github.rb', line 156 def submit_pull_request_status!(warnings: [], errors: [], details_url: []) status = (errors.count.zero? ? "success" : "failure") = generate_description(warnings: warnings, errors: errors) latest_pr_commit_ref = self.pr_json[:head][:sha] if latest_pr_commit_ref.empty? || latest_pr_commit_ref.nil? raise "Couldn't find a commit to update its status".red end begin client.create_status(ci_source.repo_slug, latest_pr_commit_ref, status, { description: , context: "danger/danger", target_url: details_url }) rescue # This usually means the user has no commit access to this repo # That's always the case for open source projects where you can only # use a read-only GitHub account if errors.count > 0 # We need to fail the actual build here is_private = pr_json[:base][:repo][:private] if is_private abort("\nDanger has failed this build. \nFound #{'error'.danger_pluralize(errors.count)} and I don't have write access to the PR to set a PR status.") else abort("\nDanger has failed this build. \nFound #{'error'.danger_pluralize(errors.count)}.") end else puts end end end |
#update_pull_request!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger") ⇒ Object
Sending data to GitHub
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
# File 'lib/danger/request_source/github.rb', line 92 def update_pull_request!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger") comment_result = {} editable_comments = issue_comments.select { |comment| comment.generated_by_danger?(danger_id) } if editable_comments.empty? previous_violations = {} else comment = editable_comments.first.body previous_violations = parse_comment(comment) end main_violations = (warnings + errors + + markdowns).reject(&:inline?) if previous_violations.empty? && main_violations.empty? # Just remove the comment, if there's nothing to say. delete_old_comments!(danger_id: danger_id) end cmp = proc do |a, b| next -1 unless a.file next 1 unless b.file next a.line <=> b.line if a.file == b.file next a.file <=> b.file end # Sort to group inline comments by file # We copy because we need to mutate this arrays for inlines comment_warnings = warnings.sort(&cmp) comment_errors = errors.sort(&cmp) = .sort(&cmp) comment_markdowns = markdowns.sort(&cmp) submit_inline_comments!(warnings: comment_warnings, errors: comment_errors, messages: , markdowns: comment_markdowns, previous_violations: previous_violations, danger_id: danger_id) # If there are still violations to show unless main_violations.empty? body = generate_comment(warnings: comment_warnings, errors: comment_errors, messages: , markdowns: comment_markdowns, previous_violations: previous_violations, danger_id: danger_id, template: "github") if editable_comments.empty? comment_result = client.add_comment(ci_source.repo_slug, ci_source.pull_request_id, body) else original_id = editable_comments.first.id comment_result = client.update_comment(ci_source.repo_slug, original_id, body) end end # Now, set the pull request status. # Note: this can terminate the entire process. submit_pull_request_status!(warnings: warnings, errors: errors, details_url: comment_result[:html_url]) end |
#validates_as_api_source? ⇒ Boolean
24 25 26 |
# File 'lib/danger/request_source/github.rb', line 24 def validates_as_api_source? (@token && !@token.empty?) || self.environment["DANGER_USE_LOCAL_GIT"] end |