repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/danger_core/plugins/dangerfile_messaging_plugin_spec.rb | spec/lib/danger/danger_core/plugins/dangerfile_messaging_plugin_spec.rb | # frozen_string_literal: true
RSpec.describe Danger::DangerfileMessagingPlugin, host: :github do
subject(:dangerfile) { testing_dangerfile }
describe "#markdown" do
it "adds single markdown" do
dangerfile.parse(nil, "markdown('hello', file: 'foo.rb', line: 1)")
markdown = added_messages(dangerfile, :markdowns).first
expect(markdown.message).to eq("hello")
expect(markdown.file).to eq("foo.rb")
expect(markdown.line).to eq(1)
expect(markdown.type).to eq(:markdown)
end
it "adds markdowns as array" do
dangerfile.parse(nil, "markdown(['hello'], file: 'foo.rb', line: 1)")
markdown = added_messages(dangerfile, :markdowns).first
expect(markdown.message).to eq("hello")
expect(markdown.file).to eq("foo.rb")
expect(markdown.line).to eq(1)
expect(markdown.type).to eq(:markdown)
end
it "adds multiple markdowns" do
dangerfile.parse(nil, "markdown('hello', 'bye', file: 'foo.rb', line: 1)")
markdowns = added_messages(dangerfile, :markdowns)
expect(markdowns.first.message).to eq("hello")
expect(markdowns.first.file).to eq("foo.rb")
expect(markdowns.first.line).to eq(1)
expect(markdowns.first.type).to eq(:markdown)
expect(markdowns.last.message).to eq("bye")
expect(markdowns.last.file).to eq("foo.rb")
expect(markdowns.last.line).to eq(1)
expect(markdowns.last.type).to eq(:markdown)
end
end
describe "#message" do
it "adds single message" do
dangerfile.parse(nil, "message('hello', file: 'foo.rb', line: 1)")
message = added_messages(dangerfile, :messages).first
expect(message.message).to eq("hello")
expect(message.file).to eq("foo.rb")
expect(message.line).to eq(1)
expect(message.type).to eq(:message)
end
it "adds messages as array" do
dangerfile.parse(nil, "message(['hello'], file: 'foo.rb', line: 1)")
message = added_messages(dangerfile, :messages).first
expect(message.message).to eq("hello")
expect(message.file).to eq("foo.rb")
expect(message.line).to eq(1)
expect(message.type).to eq(:message)
end
it "adds multiple messages" do
dangerfile.parse(nil, "message('hello', 'bye', file: 'foo.rb', line: 1)")
messages = added_messages(dangerfile, :messages)
expect(messages.first.message).to eq("hello")
expect(messages.first.file).to eq("foo.rb")
expect(messages.first.line).to eq(1)
expect(messages.first.type).to eq(:message)
expect(messages.last.message).to eq("bye")
expect(messages.last.file).to eq("foo.rb")
expect(messages.last.line).to eq(1)
expect(messages.last.type).to eq(:message)
end
it "does nothing when given a nil message" do
dangerfile.parse(nil, "message(nil)")
messages = added_messages(dangerfile, :messages)
expect(messages).to be_empty
end
end
describe "#warn" do
it "adds single warning" do
dangerfile.parse(nil, "warn('hello', file: 'foo.rb', line: 1)")
warning = added_messages(dangerfile, :warnings).first
expect(warning.message).to eq("hello")
expect(warning.file).to eq("foo.rb")
expect(warning.line).to eq(1)
expect(warning.type).to eq(:warning)
end
it "adds warnings as array" do
dangerfile.parse(nil, "warn(['hello'], file: 'foo.rb', line: 1)")
warning = added_messages(dangerfile, :warnings).first
expect(warning.message).to eq("hello")
expect(warning.file).to eq("foo.rb")
expect(warning.line).to eq(1)
expect(warning.type).to eq(:warning)
end
it "adds multiple warnings" do
dangerfile.parse(nil, "warn('hello', 'bye', file: 'foo.rb', line: 1)")
warnings = added_messages(dangerfile, :warnings)
expect(warnings.first.message).to eq("hello")
expect(warnings.first.file).to eq("foo.rb")
expect(warnings.first.line).to eq(1)
expect(warnings.first.type).to eq(:warning)
expect(warnings.last.message).to eq("bye")
expect(warnings.last.file).to eq("foo.rb")
expect(warnings.last.line).to eq(1)
expect(warnings.last.type).to eq(:warning)
end
it "does nothing when given a nil warning" do
dangerfile.parse(nil, "warn(nil)")
warnings = added_messages(dangerfile, :warnings)
expect(warnings).to be_empty
end
end
describe "#fail" do
it "adds single failure" do
dangerfile.parse(nil, "fail('hello', file: 'foo.rb', line: 1)")
failure = added_messages(dangerfile, :errors).first
expect(failure.message).to eq("hello")
expect(failure.file).to eq("foo.rb")
expect(failure.line).to eq(1)
expect(failure.type).to eq(:error)
end
it "adds failures as array" do
dangerfile.parse(nil, "fail(['hello'], file: 'foo.rb', line: 1)")
error = added_messages(dangerfile, :errors).first
expect(error.message).to eq("hello")
expect(error.file).to eq("foo.rb")
expect(error.line).to eq(1)
expect(error.type).to eq(:error)
end
it "adds multiple failures" do
dangerfile.parse(nil, "fail('hello', 'bye', file: 'foo.rb', line: 1)")
failures = added_messages(dangerfile, :errors)
expect(failures.first.message).to eq("hello")
expect(failures.first.file).to eq("foo.rb")
expect(failures.first.line).to eq(1)
expect(failures.first.type).to eq(:error)
expect(failures.last.message).to eq("bye")
expect(failures.last.file).to eq("foo.rb")
expect(failures.last.line).to eq(1)
expect(failures.last.type).to eq(:error)
end
it "does nothing when given a nil failure" do
dangerfile.parse(nil, "fail(nil)")
failures = added_messages(dangerfile, :errors)
expect(failures).to be_empty
end
end
describe "#status_report" do
it "returns errors, warnings, messages and markdowns" do
code = "fail('failure');" \
"warn('warning');" \
"message('message');" \
"markdown('markdown')"
dangerfile.parse(nil, code)
expect(dangerfile.status_report).to eq(
errors: ["failure"],
warnings: ["warning"],
messages: ["message"],
markdowns: [markdown_factory("markdown")]
)
end
end
describe "#violation_report" do
it "returns errors, warnings and messages" do
code = "fail('failure');" \
"warn('warning');" \
"message('message');"
dangerfile.parse(nil, code)
expect(dangerfile.violation_report).to eq(
errors: [violation_factory("failure")],
warnings: [violation_factory("warning")],
messages: [violation_factory("message")]
)
end
end
def added_messages(dangerfile, type)
plugin = dangerfile.plugins.fetch(Danger::DangerfileMessagingPlugin)
plugin.instance_variable_get("@#{type}")
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/danger_core/plugins/dangerfile_git_plugin_spec.rb | spec/lib/danger/danger_core/plugins/dangerfile_git_plugin_spec.rb | # frozen_string_literal: true
require "ostruct"
def run_in_repo_with_diff
Dir.mktmpdir do |dir|
Dir.chdir dir do
`git init -b master`
File.open("#{dir}/file1", "w") { |f| f.write "More buritto please." }
File.open("#{dir}/file2", "w") { |f| f.write "Shorts.\nShoes." }
`git add .`
`git commit --no-gpg-sign -m "adding file1 & file2"`
`git tag 1.0.0`
`git checkout -b new-branch --quiet`
File.open("#{dir}/file2", "w") { |f| f.write "Pants!" }
File.open("#{dir}/file3", "w") { |f| f.write "Jawns.\nYou know, jawns." }
File.delete("#{dir}/file1")
`git add .`
`git commit --no-gpg-sign -m "update file2, add file 3, remove file1"`
g = Git.open(".")
yield g
end
end
end
RSpec.describe Danger::DangerfileGitPlugin, host: :github do
it "fails init if the dangerfile's request source is not a GitRepo" do
dm = testing_dangerfile
dm.env.scm = []
expect { described_class.new dm }.to raise_error RuntimeError
end
describe "dsl" do
before do
dm = testing_dangerfile
@dsl = described_class.new dm
@repo = dm.env.scm
end
it "gets added_files " do
diff = [OpenStruct.new(type: "new", path: "added")]
allow(@repo).to receive(:diff).and_return(diff)
expect(@dsl.added_files).to eq(Danger::FileList.new(["added"]))
end
it "gets deleted_files " do
diff = [OpenStruct.new(type: "deleted", path: "deleted")]
allow(@repo).to receive(:diff).and_return(diff)
expect(@dsl.deleted_files).to eq(Danger::FileList.new(["deleted"]))
end
it "gets modified_files " do
diff = [OpenStruct.new(type: "modified", path: "my/path/file_name")]
allow(@repo).to receive(:diff).and_return(diff)
expect(@dsl.modified_files).to eq(Danger::FileList.new(["my/path/file_name"]))
end
it "gets lines_of_code" do
diff = OpenStruct.new(lines: 2)
allow(@repo).to receive(:diff).and_return(diff)
expect(@dsl.lines_of_code).to eq(2)
end
it "gets deletions" do
diff = OpenStruct.new(deletions: 4)
allow(@repo).to receive(:diff).and_return(diff)
expect(@dsl.deletions).to eq(4)
end
it "gets insertions" do
diff = OpenStruct.new(insertions: 6)
allow(@repo).to receive(:diff).and_return(diff)
expect(@dsl.insertions).to eq(6)
end
it "gets commits" do
log = ["hi"]
allow(@repo).to receive(:log).and_return(log)
expect(@dsl.commits).to eq(log)
end
it "gets tags" do
tag = "1.0.0\n2.0.0"
allow(@repo).to receive(:tags).and_return(tag)
expect(@dsl.tags).to all be_a(String)
end
describe "getting diff for a specific file" do
it "returns nil when a specific diff does not exist" do
run_in_repo_with_diff do |git|
diff = git.diff("master")
allow(@repo).to receive(:diff).and_return(diff)
expect(@dsl.diff_for_file("file_nope_no_way")).to be_nil
end
end
it "gets a specific diff" do
run_in_repo_with_diff do |git|
diff = git.diff("master")
allow(@repo).to receive(:diff).and_return(diff)
expect(@dsl.diff_for_file("file2")).to_not be_nil
end
end
it "returns a diff when it is deleted" do
run_in_repo_with_diff do |git|
diff = git.diff("master")
allow(@repo).to receive(:diff).and_return(diff)
diff_for_file = @dsl.diff_for_file("file1")
expect(diff_for_file).to_not be_nil
expected_patch = <<~PATCH
diff --git a/file1 b/file1
deleted file mode 100644
index 2cec6e8..0000000
--- a/file1
+++ /dev/null
@@ -1 +0,0 @@
-More buritto please.
\\ No newline at end of file
PATCH
expect(diff_for_file.patch).to eq expected_patch.chomp
end
end
end
describe "getting info for a specific file" do
it "returns nil when specific info does not exist" do
run_in_repo_with_diff do |git|
diff = git.diff("master")
allow(@repo).to receive(:diff).and_return(diff)
expect(@dsl.info_for_file("file_nope_no_way")).to be_nil
end
end
it "returns file info when it is modified" do
run_in_repo_with_diff do |git|
diff = git.diff("master")
allow(@repo).to receive(:diff).and_return(diff)
info = @dsl.info_for_file("file2")
expect(info).to_not be_nil
expect(info[:insertions]).to equal(1)
expect(info[:deletions]).to equal(2)
expect(info[:before]).to eq("Shorts.\nShoes.")
expect(info[:after]).to eq("Pants!")
end
end
it "returns file info when it is added" do
run_in_repo_with_diff do |git|
diff = git.diff("master")
allow(@repo).to receive(:diff).and_return(diff)
info = @dsl.info_for_file("file3")
expect(info).to_not be_nil
expect(info[:insertions]).to equal(2)
expect(info[:deletions]).to equal(0)
expect(info[:before]).to be_nil
expect(info[:after]).to be_nil
end
end
it "returns file info when it is deleted" do
run_in_repo_with_diff do |git|
diff = git.diff("master")
allow(@repo).to receive(:diff).and_return(diff)
info = @dsl.info_for_file("file1")
expect(info).to_not be_nil
expect(info[:insertions]).to equal(0)
expect(info[:deletions]).to equal(1)
expect(info[:before]).to be_nil
expect(info[:after]).to be_nil
end
end
end
describe "#renamed_files" do
it "delegates to scm" do
renamed_files = [{
before: "some/path/old",
after: "some/path/new"
}]
allow(@repo).to receive(:renamed_files).and_return(renamed_files)
expect(@dsl.renamed_files).to eq(renamed_files)
end
end
describe "#diff" do
it "delegates to scm" do
allow(@repo).to receive(:diff).and_return(:diff)
expect(@dsl.diff).to eq(:diff)
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/danger_core/plugins/dangerfile_gitlab_plugin_spec.rb | spec/lib/danger/danger_core/plugins/dangerfile_gitlab_plugin_spec.rb | # frozen_string_literal: true
RSpec.describe Danger::DangerfileGitLabPlugin, host: :gitlab do
let(:env) { stub_env.merge("CI_MERGE_REQUEST_IID" => 1) }
let(:dangerfile) { testing_dangerfile(env) }
let(:plugin) { described_class.new(dangerfile) }
before do
stub_merge_request(
"merge_request_1_response",
"k0nserv%2Fdanger-test",
1
)
end
[
{ method: :mr_title, expected_result: "Add a" },
{ method: :mr_body, expected_result: "The descriptions is here\r\n\r\n\u003e Danger: ignore \"Developer specific files shouldn't be changed\"\r\n\r\n\u003e Danger: ignore \"Testing\"" },
{ method: :mr_author, expected_result: "k0nserv" },
{ method: :mr_labels, expected_result: ["test-label"] },
{ method: :branch_for_merge, expected_result: "master" },
{ method: :branch_for_base, expected_result: "master" },
{ method: :branch_for_head, expected_result: "mr-test" }
].each do |data|
method = data[:method]
expected = data[:expected_result]
describe "##{method}" do
it "sets the correct #{method}" do
with_git_repo(origin: "git@gitlab.com:k0nserv/danger-test.git") do
dangerfile.env.request_source.fetch_details
expect(plugin.send(method)).to eq(expected)
end
end
end
end
describe "#mr_diff" do
before do
stub_merge_request_changes(
"merge_request_1_changes_response",
"k0nserv\%2Fdanger-test",
1
)
end
it "sets the mr_diff" do
with_git_repo(origin: "git@gitlab.com:k0nserv/danger-test.git") do
expect(plugin.mr_diff).to include("Danger rocks!")
expect(plugin.mr_diff).to include("Test message please ignore")
end
end
end
describe "#mr_changes" do
before do
stub_merge_request_changes(
"merge_request_1_changes_response",
"k0nserv\%2Fdanger-test",
1
)
end
it "sets the mr_changes" do
with_git_repo(origin: "git@gitlab.com:k0nserv/danger-test.git") do
expect(plugin.mr_changes[0].to_h).to match(hash_including("old_path" => "Dangerfile", "new_path" => "Dangerfile", "a_mode" => "100644", "b_mode" => "100644", "new_file" => false, "renamed_file" => false, "deleted_file" => false, "diff" => an_instance_of(String)))
expect(plugin.mr_changes[1].to_h).to match(hash_including("old_path" => "a", "new_path" => "a", "a_mode" => "0", "b_mode" => "100644", "new_file" => true, "renamed_file" => false, "deleted_file" => false, "diff" => "--- /dev/null\n+++ b/a\n@@ -0,0 +1 @@\n+Danger rocks!\n"))
expect(plugin.mr_changes[2].to_h).to match(hash_including("old_path" => "b", "new_path" => "b", "a_mode" => "0", "b_mode" => "100644", "new_file" => true, "renamed_file" => false, "deleted_file" => false, "diff" => "--- /dev/null\n+++ b/b\n@@ -0,0 +1 @@\n+Test message please ignore\n"))
end
end
end
describe "#mr_json" do
it "is set" do
with_git_repo(origin: "git@gitlab.com:k0nserv/danger-test.git") do
dangerfile.env.request_source.fetch_details
expect(plugin.mr_json).not_to be_nil
end
end
it "has the expected keys" do
with_git_repo(origin: "git@gitlab.com:k0nserv/danger-test.git") do
dangerfile.env.request_source.fetch_details
%i(
id iid project_id title description state created_at
updated_at target_branch source_branch upvotes downvotes
author assignee source_project_id target_project_id labels
work_in_progress milestone merge_when_pipeline_succeeds merge_status
subscribed user_notes_count approvals_before_merge
should_remove_source_branch force_remove_source_branch diff_refs
).each do |key|
key_present = plugin.pr_json.key?(key.to_s)
expect(key_present).to be_truthy, "Expected key #{key} not found"
end
end
end
end
describe "#html_link" do
it "should render a html link to the given file" do
with_git_repo(origin: "git@gitlab.com:k0nserv/danger-test.git") do
head_commit = "04e58de1fa97502d7e28c1394d471bb8fb1fc4a8"
dangerfile.env.request_source.fetch_details
expect(plugin).to receive(:repository_web_url).
and_return("https://gitlab.com/k0nserv/danger-test")
expect(plugin).to receive(:head_commit).
and_return(head_commit)
expect(plugin.html_link("CHANGELOG.md")).to eq("<a href='https://gitlab.com/k0nserv/danger-test/blob/#{head_commit}/CHANGELOG.md'>CHANGELOG.md</a>")
end
end
end
describe "repository_web_url" do
it "should request the project" do
with_git_repo(origin: "git@gitlab.com:k0nserv/danger-test.git") do
expect(plugin).to receive("mr_json").
and_return({ source_project_id: "15" })
require "gitlab"
project = Gitlab::ObjectifiedHash.new({ web_url: "https://gitlab.com/k0nserv/danger-test" })
expect(plugin.api).to receive("project").
and_return(project)
expect(plugin.repository_web_url).to eq("https://gitlab.com/k0nserv/danger-test")
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/local_only.rb | spec/lib/danger/request_sources/local_only.rb | # frozen_string_literal: true
require "erb"
require "danger/request_sources/local_only"
RSpec.describe Danger::RequestSources::LocalOnly, host: :local do
let(:ci) { instance_double("Danger::LocalOnlyGitRepo", base_commit: "origin/master", head_commit: "feature_branch") }
let(:subject) { described_class.new(ci, {}) }
describe "validation" do
it "validates as an API source" do
expect(subject.validates_as_api_source?).to be_truthy
end
it "validates as CI" do
expect(subject.validates_as_ci?).to be_truthy
end
end
describe "scm" do
it "Sets up the scm" do
expect(subject.scm).to be_kind_of(Danger::GitRepo)
end
end
describe "#setup_danger_branches" do
before do
allow(subject.scm).to receive(:exec).and_return("found_some")
end
context "when specified head is missing" do
before { expect(subject.scm).to receive(:exec).and_return("") }
it "raises an error" do
expect { subject.setup_danger_branches }.to raise_error("Specified commit 'origin/master' not found")
end
end
it "sets danger_head to feature_branch" do
expect(subject.scm).to receive(:exec).with(/^branch.*head.*feature_branch/).and_return("feature_branch")
subject.setup_danger_branches
end
it "sets danger_base to origin/master" do
expect(subject.scm).to receive(:exec).with(%r{^branch.*base.*origin/master}).and_return("origin/master")
subject.setup_danger_branches
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/bitbucket_server_spec.rb | spec/lib/danger/request_sources/bitbucket_server_spec.rb | # frozen_string_literal: true
require "danger/request_sources/bitbucket_server"
RSpec.describe Danger::RequestSources::BitbucketServer, host: :bitbucket_server do
let(:env) { stub_env }
let(:bs) { Danger::RequestSources::BitbucketServer.new(stub_ci, env) }
describe "#new" do
it "should not raise uninitialized constant error" do
expect { described_class.new(stub_ci, env) }.not_to raise_error
end
end
describe "#host" do
it "sets the host specified by `DANGER_BITBUCKETSERVER_HOST`" do
expect(bs.host).to eq("https://stash.example.com")
end
end
describe "#validates_as_api_source" do
it "validates_as_api_source for non empty `DANGER_BITBUCKETSERVER_USERNAME` and `DANGER_BITBUCKETSERVER_PASSWORD`" do
expect(bs.validates_as_api_source?).to be true
end
end
describe "#pr_json" do
before do
stub_pull_request
bs.fetch_details
end
it "has a non empty pr_json after `fetch_details`" do
expect(bs.pr_json).to be_truthy
end
describe "#pr_json[:id]" do
it "has fetched the same pull request id as ci_sources's `pull_request_id`" do
expect(bs.pr_json[:id]).to eq(2080)
end
end
describe "#pr_json[:title]" do
it "has fetched the pull requests title" do
expect(bs.pr_json[:title]).to eq("This is a danger test")
end
end
end
describe "#pr_diff" do
it "has a non empty pr_diff after fetch" do
stub_pull_request_diff
bs.pr_diff
expect(bs.pr_diff).to be_truthy
end
end
describe "#main_violations_group" do
before do
stub_pull_request_diff
end
it "includes file specific messages outside the PR diff by default" do
warning_in_diff = Danger::Violation.new("foo", false, "Gemfile", 3, type: :warning)
warning_outside_of_diff = Danger::Violation.new("bar", false, "file.rb", 1, type: :warning)
warnings = [
warning_in_diff,
warning_outside_of_diff
]
expect(bs.main_violations_group(warnings: warnings)).to eq({
warnings: [warning_outside_of_diff],
errors: [],
messages: [],
markdowns: []
})
end
it "dismisses messages outside the PR diff when env variable is set" do
new_env = stub_env
new_env.merge!({ "DANGER_BITBUCKETSERVER_DISMISS_OUT_OF_RANGE_MESSAGES" => "true" })
inspected = Danger::RequestSources::BitbucketServer.new(stub_ci, new_env)
warnings = [
Danger::Violation.new("foo", false, "Gemfile", 3, type: :warning),
Danger::Violation.new("bar", false, "file.rb", 1, type: :warning)
]
expect(inspected.main_violations_group(warnings: warnings)).to eq({
warnings: [],
errors: [],
messages: [],
markdowns: []
})
end
end
describe "#find_position_in_diff" do
before do
stub_pull_request_diff
end
it "returns false when changes are not in the `pr_diff`" do
expect(bs.find_position_in_diff?("file.rb", 1)).to be_falsy
end
it "returns true when changes are in included in the `pr_diff`" do
expect(bs.find_position_in_diff?("Gemfile", 3)).to be_truthy
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/gitlab_spec.rb | spec/lib/danger/request_sources/gitlab_spec.rb | # frozen_string_literal: true
require "erb"
require "danger/request_sources/gitlab"
RSpec.describe Danger::RequestSources::GitLab, host: :gitlab do
let(:env) { stub_env.merge("CI_MERGE_REQUEST_IID" => 1) }
let(:subject) { stub_request_source(env) }
describe "#inspect" do
it "masks token on inspect" do
expect(subject.inspect).to include(%(@token="********"))
end
end
describe "the GitLab host" do
it "sets the default GitLab host" do
expect(subject.host).to eq("gitlab.com")
end
it "allows the GitLab host to be overridden" do
env["DANGER_GITLAB_HOST"] = "gitlab.example.com"
expect(subject.host).to eq("gitlab.example.com")
end
end
describe "the GitLab API endpoint" do
it "sets the default GitLab API endpoint" do
expect(subject.endpoint).to eq("https://gitlab.com/api/v4")
end
it "allows the GitLab API endpoint to be overridden with `DANGER_GITLAB_API_BASE_URL`" do
env["DANGER_GITLAB_API_BASE_URL"] = "https://gitlab.example.com/api/v3"
expect(subject.endpoint).to eq("https://gitlab.example.com/api/v3")
end
end
describe "the GitLab API client" do
it "sets the provide token" do
env["DANGER_GITLAB_API_TOKEN"] = "token"
expect(subject.client.private_token).to eq("token")
end
it "set the default API endpoint" do
expect(subject.client.endpoint).to eq("https://gitlab.com/api/v4")
end
it "respects overriding the API endpoint" do
env["DANGER_GITLAB_API_BASE_URL"] = "https://gitlab.example.com/api/v3"
expect(subject.client.endpoint).to eq("https://gitlab.example.com/api/v3")
end
end
describe "validation" do
it "validates as an API source" do
expect(subject.validates_as_api_source?).to be_truthy
end
it "does no validate as an API source when the API token is empty" do
env["DANGER_GITLAB_API_TOKEN"] = ""
result = stub_request_source(env).validates_as_api_source?
expect(result).to be_falsey
end
it "does no validate as an API source when there is no API token" do
env.delete("DANGER_GITLAB_API_TOKEN")
result = stub_request_source(env).validates_as_api_source?
expect(result).to be_falsey
end
it "does not validate as CI when there is a port number included in host" do
env["DANGER_GITLAB_HOST"] = "gitlab.example.com:2020"
expect { stub_request_source(env).validates_as_ci? }.to raise_error("Port number included in `DANGER_GITLAB_HOST`, this will fail with GitLab CI Runners")
end
it "does validate as CI when there is no port number included in host" do
env["DANGER_GITLAB_HOST"] = "gitlab.example.com"
git_mock = Danger::GitRepo.new
g = stub_request_source(env)
g.scm = git_mock
allow(git_mock).to receive(:exec).with("remote show origin -n").and_return("Fetch URL: git@gitlab.example.com:artsy/eigen.git")
result = g.validates_as_ci?
expect(result).to be_truthy
end
end
describe "scm" do
it "Sets up the scm" do
expect(subject.scm).to be_kind_of(Danger::GitRepo)
end
end
describe "valid server response" do
before do
stub_merge_request(
"merge_request_1_response",
"k0nserv%2Fdanger-test",
1
)
@comments_stub = stub_merge_request_comments(
"merge_request_1_comments_response",
"k0nserv%2Fdanger-test",
1
)
end
it "determines the correct base_commit" do
subject.fetch_details
expect(subject.base_commit).to eq("0e4db308b6579f7cc733e5a354e026b272e1c076")
end
it "setups the danger branches" do
subject.fetch_details
expect(subject.scm).to receive(:exec)
.with("rev-parse --quiet --verify 0e4db308b6579f7cc733e5a354e026b272e1c076^{commit}")
.and_return("0e4db308b6579f7cc733e5a354e026b272e1c076")
expect(subject.scm).to receive(:exec)
.with("branch danger_base 0e4db308b6579f7cc733e5a354e026b272e1c076")
expect(subject.scm).to receive(:exec)
.with("rev-parse --quiet --verify 04e58de1fa97502d7e28c1394d471bb8fb1fc4a8^{commit}")
.and_return("04e58de1fa97502d7e28c1394d471bb8fb1fc4a8")
expect(subject.scm).to receive(:exec)
.with("branch danger_head 04e58de1fa97502d7e28c1394d471bb8fb1fc4a8")
subject.setup_danger_branches
end
it "set its mr_json" do
subject.fetch_details
expect(subject.mr_json).to be_truthy
end
it "sets its ignored_violations_from_pr" do
subject.fetch_details
expect(subject.ignored_violations).to eq(
[
"Developer specific files shouldn't be changed",
"Testing"
]
)
end
describe "#supports_inline_comments" do
before do
skip "gitlab gem older than 4.6.0" if Gem.loaded_specs["gitlab"].version < Gem::Version.new("4.6.0")
end
it "is false on version before 10.8" do
stub_version("10.6.4")
expect(subject.supports_inline_comments).to be_falsey
end
it "is true on version 10.8" do
stub_version("10.8.0")
expect(subject.supports_inline_comments).to be_truthy
end
it "is true on versions after 10.8" do
stub_version("11.7.0")
expect(subject.supports_inline_comments).to be_truthy
end
end
describe "#update_pull_request!" do
before do
@version_stub = stub_version("11.7.0")
stub_merge_request_discussions(
"merge_request_1_discussions_empty_response",
"k0nserv%2Fdanger-test",
1
)
end
it "checks if the server supports inline comments" do
skip "gitlab gem older than 4.6.0" if Gem.loaded_specs["gitlab"].version < Gem::Version.new("4.6.0")
subject.update_pull_request!(
warnings: [],
errors: [],
messages: []
)
expect(@version_stub).to have_been_made
end
it "creates a new comment when there is not one already" do
body = subject.generate_comment(
warnings: violations_factory(["Test warning"]),
errors: violations_factory(["Test error"]),
messages: violations_factory(["Test message"]),
template: "gitlab"
)
stub_request(:post, "https://gitlab.com/api/v4/projects/k0nserv%2Fdanger-test/merge_requests/1/notes").with(
body: "body=#{ERB::Util.url_encode(body)}",
headers: expected_headers
).to_return(status: 200, body: "", headers: {})
subject.update_pull_request!(
warnings: violations_factory(["Test warning"]),
errors: violations_factory(["Test error"]),
messages: violations_factory(["Test message"])
)
end
context "doesn't support inline comments" do
before do
stub_version("10.7.0")
end
context "existing comment" do
before do
remove_request_stub(@comments_stub)
@comments_stub = stub_merge_request_comments(
"merge_request_1_comments_existing_danger_comment_response",
"k0nserv%2Fdanger-test",
1
)
end
it "updates the existing comment instead of creating a new one" do
allow(subject).to receive(:random_compliment).and_return("random compliment")
body = subject.generate_comment(
warnings: violations_factory(["New Warning"]),
errors: [],
messages: [],
previous_violations: {
warning: [],
error: violations_factory(["Test error"]),
message: []
},
template: "gitlab"
)
stub_request(:put, "https://gitlab.com/api/v4/projects/k0nserv%2Fdanger-test/merge_requests/1/notes/13471894").with(
body: {
body: body
},
headers: expected_headers
).to_return(status: 200, body: "", headers: {})
subject.update_pull_request!(
warnings: violations_factory(["New Warning"]),
errors: [],
messages: []
)
end
it "creates a new comment instead of updating the existing one if --new-comment is provided" do
body = subject.generate_comment(
warnings: violations_factory(["Test warning"]),
errors: violations_factory(["Test error"]),
messages: violations_factory(["Test message"]),
template: "gitlab"
)
stub_request(:post, "https://gitlab.com/api/v4/projects/k0nserv%2Fdanger-test/merge_requests/1/notes").with(
body: {
body: body
},
headers: expected_headers
).to_return(status: 200, body: "", headers: {})
subject.update_pull_request!(
warnings: violations_factory(["Test warning"]),
errors: violations_factory(["Test error"]),
messages: violations_factory(["Test message"]),
new_comment: true
)
end
end
context "existing comment with no sticky messages" do
before do
remove_request_stub(@comments_stub)
@comments_stub = stub_merge_request_comments(
"merge_request_1_comments_no_stickies_response",
"k0nserv%2Fdanger-test",
1
)
end
it "removes the previous danger comment if there are no new messages" do
stub_request(:delete, "https://gitlab.com/api/v4/projects/k0nserv%2Fdanger-test/merge_requests/1/notes/13471894").with(
headers: expected_headers
)
subject.update_pull_request!(
warnings: [],
errors: [],
messages: []
)
end
end
end
context "supports inline comments" do
before do
stub_version("11.7.0")
skip "gitlab gem older than 4.6.0" if Gem.loaded_specs["gitlab"].version < Gem::Version.new("4.6.0")
end
it "adds new comments inline" do
stub_merge_request_changes(
"merge_request_1_changes_response",
"k0nserv\%2Fdanger-test",
1
)
expect(subject.client).to receive(:create_merge_request_discussion)
allow(subject.client).to receive(:delete_merge_request_comment)
subject.fetch_details
v = Danger::Violation.new("Sure thing", true, "a", 4)
subject.update_pull_request!(warnings: [], errors: [], messages: [v])
end
it "ignore new comments inline when out of range" do
stub_merge_request_changes(
"merge_request_1_changes_response",
"k0nserv\%2Fdanger-test",
1
)
expect(subject.client).not_to receive(:create_merge_request_discussion)
allow(subject.client).to receive(:delete_merge_request_comment)
subject.fetch_details
v = Danger::Violation.new("Sure thing", true, "Dangerfile", 14)
subject.dismiss_out_of_range_messages = true
subject.update_pull_request!(warnings: [], errors: [], messages: [v])
end
it "ignore new markdown inline when out of range, allow other kind" do
stub_merge_request_changes(
"merge_request_1_changes_response",
"k0nserv\%2Fdanger-test",
1
)
stub_request(:post, "https://gitlab.com/api/v4/projects/k0nserv%2Fdanger-test/merge_requests/1/notes").
with(body: { "body" => "<table>\n <thead>\n <tr>\n <th width=\"5%\"></th>\n <th width=\"95%\" data-danger-table=\"true\" data-kind=\"Message\">\n 1 Message\n </th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>:book:</td>\n <td data-sticky=\"true\">Dangerfile#L14Sure thing</td>\n </tr>\n </tbody>\n</table>\n\n<p align=\"right\" data-meta=\"generated_by_danger\">\n Generated by :no_entry_sign: <a href=\"https://github.com/danger/danger/\">Danger</a>\n</p>\n" },
headers: { "Accept" => "application/json", "Accept-Encoding" => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3", "Content-Type" => "application/x-www-form-urlencoded", "Private-Token" => "a86e56d46ac78b", "User-Agent" => "Gitlab Ruby Gem 4.16.1" }).
to_return(status: 200, body: "", headers: {})
expect(subject.client).to receive(:create_merge_request_discussion).once
allow(subject.client).to receive(:delete_merge_request_comment)
subject.fetch_details
v = Danger::Violation.new("Sure thing", true, "Dangerfile", 14)
m = Danger::Markdown.new("Sure thing", "Dangerfile", 14)
subject.dismiss_out_of_range_messages = {
warning: false,
error: false,
message: false,
markdown: true
}
subject.update_pull_request!(warnings: [], errors: [], messages: [v], markdowns: [m])
end
it "edits existing inline comment instead of creating a new one if file/line matches" do
stub_merge_request_discussions(
"merge_request_1_discussions_response",
"k0nserv%2Fdanger-test",
1
)
stub_merge_request_changes(
"merge_request_1_changes_response",
"k0nserv\%2Fdanger-test",
1
)
v = Danger::Violation.new("Updated danger comment", true, "a", 1)
body = subject.generate_inline_comment_body("warning", subject.process_markdown(v, true), danger_id: "danger", template: "gitlab")
expect(subject.client).to receive(:update_merge_request_discussion_note).with("k0nserv/danger-test", 1, "f5fd1ab23556baa6683b4b3b36ec4455f8b500f4", 141_485_123, body: body)
allow(subject.client).to receive(:update_merge_request_discussion_note)
allow(subject.client).to receive(:delete_merge_request_comment)
subject.fetch_details
expect { subject.update_pull_request!(warnings: [v], errors: [], messages: []) }.not_to output(/Please convert ObjectifiedHash object/).to_stderr
end
it "deletes non-sticky comments if no violations are present" do
stub_merge_request_discussions(
"merge_request_1_discussions_response",
"k0nserv%2Fdanger-test",
1
)
# Global comment gets updated as its sticky
allow(subject.client).to receive(:edit_merge_request_note)
# Inline comment
expect(subject.client).to receive(:delete_merge_request_comment).with("k0nserv/danger-test", 1, 141_485_123)
subject.update_pull_request!(warnings: [], errors: [], messages: [])
end
it "deletes inline comments if those are no longer relevant" do
stub_merge_request_discussions(
"merge_request_1_discussions_response",
"k0nserv%2Fdanger-test",
1
)
expect(subject.client).to receive(:edit_merge_request_note)
allow(subject.client).to receive(:update_merge_request_discussion_note)
expect(subject.client).to receive(:delete_merge_request_comment).with("k0nserv/danger-test", 1, 141_485_123)
v = Danger::Violation.new("Test error", true)
subject.update_pull_request!(warnings: [], errors: [v], messages: [])
end
it "skips inline comments for files that are not part of the diff" do
stub_merge_request_discussions(
"merge_request_1_discussions_response",
"k0nserv%2Fdanger-test",
1
)
stub_merge_request_changes(
"merge_request_1_changes_response",
"k0nserv\%2Fdanger-test",
1
)
allow(subject.client).to receive(:update_merge_request_discussion_note)
allow(subject.client).to receive(:delete_merge_request_comment)
allow(subject.client).to receive(:edit_merge_request_note)
v = Danger::Violation.new("Error on not-on-diff file", true, "not-on-diff", 1)
subject.fetch_details
subject.update_pull_request!(warnings: [v], errors: [], messages: [])
end
it "doesn't crash if an inline comment fails to publish" do
stub_merge_request_discussions(
"merge_request_1_discussions_empty_response",
"k0nserv%2Fdanger-test",
1
)
stub_merge_request_changes(
"merge_request_1_changes_response",
"k0nserv\%2Fdanger-test",
1
)
url = "https://gitlab.com/api/v4/projects/k0nserv%2Fdanger-test/merge_requests/1/discussions"
WebMock.stub_request(:post, url).to_return(status: [400, "Note {:line_code=>[\"can't be blank\", \"must be a valid line code\"]}"])
v = Danger::Violation.new("Some error", true, "a", 1)
allow(subject.client).to receive(:create_merge_request_note)
subject.fetch_details
subject.update_pull_request!(warnings: [v], errors: [], messages: [])
end
end
end
describe "#file_url" do
it "returns a valid URL with the minimum parameters" do
url = subject.file_url(repository: 1, path: "Dangerfile")
expect(url).to eq("https://gitlab.com/api/v4/projects/1/repository/files/Dangerfile/raw?ref=master&private_token=a86e56d46ac78b")
end
it "returns a valid URL with more parameters" do
url = subject.file_url(repository: 1, organisation: "artsy", branch: "develop", path: "path/Dangerfile")
expect(url).to eq("https://gitlab.com/api/v4/projects/1/repository/files/path%2FDangerfile/raw?ref=develop&private_token=a86e56d46ac78b")
end
it "returns a valid URL with ref parameter" do
url = subject.file_url(repository: 1, organisation: "artsy", ref: "develop", path: "path/Dangerfile")
expect(url).to eq("https://gitlab.com/api/v4/projects/1/repository/files/path%2FDangerfile/raw?ref=develop&private_token=a86e56d46ac78b")
end
it "returns a valid fallback URL" do
url = subject.file_url(repository: 1, organisation: "teapot", path: "Dangerfile")
expect(url).to eq("https://gitlab.com/api/v4/projects/1/repository/files/Dangerfile/raw?ref=master&private_token=a86e56d46ac78b")
end
it "returns a valid URL with slug repository" do
url = subject.file_url(repository: "group/secret_project", organisation: "teapot", path: "Dangerfile")
expect(url).to eq("https://gitlab.com/api/v4/projects/group%2Fsecret_project/repository/files/Dangerfile/raw?ref=master&private_token=a86e56d46ac78b")
end
end
describe "#is_out_of_range" do
let(:new_path) do
"dummy"
end
let(:old_path) do
"dummy"
end
let(:new_file) do
false
end
let(:renamed_file) do
false
end
let(:deleted_file) do
false
end
let(:diff_lines) do
""
end
let(:changes) do
[{
"new_path" => new_path,
"old_path" => old_path,
"diff" => diff_lines,
"new_file" => new_file,
"renamed_file" => renamed_file,
"deleted_file" => deleted_file
}]
end
context "new file" do
let(:diff_lines) do
<<-DIFF
@@ -0,0 +1,3 @@
+foo
+bar
+baz
DIFF
end
let(:new_file) do
true
end
it "return false for new file" do
is_out_of_range = subject.is_out_of_range(changes, double(file: new_path, line: 1))
expect(is_out_of_range).to eq(false)
end
end
context "slightly modified file" do
let(:diff_lines) do
<<-DIFF
@@ -1 +1,2 @@
-foo
+bar
+baz
DIFF
end
it "return false when line is part of addition lines" do
is_out_of_range = subject.is_out_of_range(changes, double(file: new_path, line: 1))
expect(is_out_of_range).to eq(false)
end
it "return true when line is not part of addition lines" do
is_out_of_range = subject.is_out_of_range(changes, double(file: new_path, line: 5))
expect(is_out_of_range).to eq(true)
end
end
context "heavily modified files" do
let(:diff_lines) do
<<-DIFF
@@ -2,7 +2,8 @@
a
a
a
-foo
+bar
+baz
a
a
a
@@ -21,7 +22,8 @@
a
a
a
-foo
+bar
+baz
a
a
a
DIFF
end
it "return false when line message is part of addition line" do
is_out_of_range = subject.is_out_of_range(changes, double(file: new_path, line: 5))
expect(is_out_of_range).to eq(false)
end
it "return false when line message is part of addition line #2" do
is_out_of_range = subject.is_out_of_range(changes, double(file: new_path, line: 25))
expect(is_out_of_range).to eq(false)
end
it "return true when line is just part of hunk but not part of addition line" do
is_out_of_range = subject.is_out_of_range(changes, double(file: new_path, line: 3))
expect(is_out_of_range).to eq(true)
end
end
context "deleted file" do
let(:diff_lines) do
<<-DIFF
@@ -1,3 +0,0 @@
-foo
-bar
-baz
DIFF
end
let(:deleted_file) do
true
end
it "returns true for deleted file" do
is_out_of_range = subject.is_out_of_range(changes, double(file: new_path, line: 1))
expect(is_out_of_range).to eq(true)
end
end
context "renamed only file" do
let(:renamed_file) do
true
end
let(:new_path) do
"new_dummy"
end
it "returns true for renamed only file" do
is_out_of_range = subject.is_out_of_range(changes, double(file: new_path, line: 1))
expect(is_out_of_range).to eq(true)
end
end
end
describe "#find_old_position_in_diff" do
let(:new_path) do
"dummy"
end
let(:old_path) do
"dummy"
end
let(:new_file) do
false
end
let(:renamed_file) do
false
end
let(:deleted_file) do
false
end
let(:diff_lines) do
""
end
let(:changes) do
[{
"new_path" => new_path,
"old_path" => old_path,
"diff" => diff_lines,
"new_file" => new_file,
"renamed_file" => renamed_file,
"deleted_file" => deleted_file
}]
end
context "new file" do
let(:diff_lines) do
<<-DIFF
@@ -0,0 +1,3 @@
+foo
+bar
+baz
DIFF
end
let(:new_file) do
true
end
it "returns path only" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 1))
expect(position[:path]).to eq(old_path)
expect(position[:line]).to be_nil
end
end
context "slightly modified file" do
let(:diff_lines) do
<<-DIFF
@@ -1 +1,2 @@
-foo
+bar
+baz
DIFF
end
it "returns path only" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 1))
expect(position[:path]).to eq(old_path)
expect(position[:line]).to be_nil
end
end
context "heavily modified files" do
let(:diff_lines) do
<<-DIFF
@@ -2,7 +2,8 @@
a
a
a
-foo
+bar
+baz
a
a
a
@@ -21,7 +22,8 @@
a
a
a
-foo
+bar
+baz
a
a
a
DIFF
end
it "returns path only when message line is new" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 5))
expect(position[:path]).to eq(old_path)
expect(position[:line]).to be_nil
end
it "returns path and correct line when message line isn't new" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 3))
expect(position[:path]).to eq(old_path)
expect(position[:line]).to eq(3)
end
it "returns path and correct line when the line is before diffs" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 1))
expect(position[:path]).to eq(old_path)
expect(position[:line]).to eq(1)
end
it "returns path and correct line when the line is between diffs" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 15))
expect(position[:path]).to eq(old_path)
expect(position[:line]).to eq(14)
end
it "returns path and correct line when the line is after diffs" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 35))
expect(position[:path]).to eq(old_path)
expect(position[:line]).to eq(33)
end
end
context "deleted file" do
let(:diff_lines) do
<<-DIFF
@@ -1,3 +0,0 @@
-foo
-bar
-baz
DIFF
end
let(:deleted_file) do
true
end
it "returns nil" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 1))
expect(position).to be_nil
end
end
context "renamed only file" do
let(:renamed_file) do
true
end
let(:new_path) do
"new_dummy"
end
it "returns nil" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 1))
expect(position).to be_nil
end
end
context "renamed and modified file" do
let(:diff_lines) do
<<-DIFF
@@ -1 +1,2 @@
@@ -2,7 +2,8 @@
a
a
a
-foo
+bar
+baz
a
a
a
DIFF
end
let(:renamed_file) do
true
end
let(:new_path) do
"dummy_new"
end
it "returns old path only when message line is new" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 5))
expect(position[:path]).to eq(old_path)
expect(position[:line]).to be_nil
end
it "returns old path and correct line when message line isn't new" do
position = subject.find_old_position_in_diff(changes, double(file: new_path, line: 3))
expect(position[:path]).to eq(old_path)
expect(position[:line]).to eq(3)
end
end
context "unchanged file" do
let(:diff_lines) do
<<-DIFF
@@ -0,0 +1,3 @@
+foo
+bar
+baz
DIFF
end
it "returns nil" do
position = subject.find_old_position_in_diff(changes, double(file: "dummy_unchanged", line: 5))
expect(position).to be_nil
end
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/request_source_spec.rb | spec/lib/danger/request_sources/request_source_spec.rb | # frozen_string_literal: true
require "danger/request_sources/github/github"
RSpec.describe Danger::RequestSources::RequestSource, host: :github do
describe "the base request source" do
it "validates when passed a corresponding repository" do
git_mock = Danger::GitRepo.new
allow(git_mock).to receive(:exec).with("remote show origin -n").and_return("Fetch URL: git@github.com:artsy/eigen.git")
g = stub_request_source
g.scm = git_mock
expect(g.validates_as_ci?).to be true
end
it "validates when passed a corresponding repository with custom host" do
git_mock = Danger::GitRepo.new
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi", "DANGER_GITHUB_HOST" => "git.club-mateusa.com" }
g = Danger::RequestSources::GitHub.new(stub_ci, gh_env)
g.scm = git_mock
allow(git_mock).to receive(:exec).with("remote show origin -n").and_return("Fetch URL: git@git.club-mateusa.com:artsy/eigen.git")
expect(g.validates_as_ci?).to be true
end
end
describe ".source_name" do
context "GitHub" do
it "returns the name of request source" do
result = Danger::RequestSources::GitHub.source_name
expect(result).to eq "GitHub"
end
end
context "GitLab" do
it "returns the name of request source" do
result = Danger::RequestSources::GitLab.source_name
expect(result).to eq "GitLab"
end
end
context "BitbucketCloud" do
it "returns the name of request source" do
result = Danger::RequestSources::BitbucketCloud.source_name
expect(result).to eq "BitbucketCloud"
end
end
context "BitbucketCloud" do
it "returns the name of request source" do
result = Danger::RequestSources::BitbucketServer.source_name
expect(result).to eq "BitbucketServer"
end
end
end
describe ".available_source_names_and_envs" do
it "returns list of items contains source name and envs" do
result = described_class.available_source_names_and_envs.join(", ")
expect(result).to include("- GitHub:")
expect(result).to include("- GitLab:")
expect(result).to include("- BitbucketCloud:")
expect(result).to include("- BitbucketServer:")
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/bitbucket_server_api_spec.rb | spec/lib/danger/request_sources/bitbucket_server_api_spec.rb | # frozen_string_literal: true
require "danger/request_sources/bitbucket_server_api"
RSpec.describe Danger::RequestSources::BitbucketServerAPI, host: :bitbucket_server do
describe "#inspect" do
it "masks password on inspect" do
allow(ENV).to receive(:[]).with("ENVDANGER_BITBUCKETSERVER_PASSWORD") { "supertopsecret" }
api = described_class.new("danger", "danger", 1, stub_env)
inspected = api.inspect
expect(inspected).to include(%(@password="********"))
end
it "handles http hosts" do
env = stub_env
env["DANGER_BITBUCKETSERVER_HOST"] = "http://my_url"
api = described_class.new("danger", "danger", 1, env)
expect(api.pr_api_endpoint).to eq("http://my_url/rest/api/1.0/projects/danger/repos/danger/pull-requests/1")
env["DANGER_BITBUCKETSERVER_HOST"] = "my_url"
api = described_class.new("danger", "danger", 1, env)
expect(api.pr_api_endpoint).to eq("https://my_url/rest/api/1.0/projects/danger/repos/danger/pull-requests/1")
end
it "checks uses ssl only for https urls" do
env = stub_env
env["DANGER_BITBUCKETSERVER_HOST"] = "http://my_url"
api = described_class.new("danger", "danger", 1, env)
expect(api.send(:use_ssl)).to eq(false)
env["DANGER_BITBUCKETSERVER_HOST"] = "https://my_url"
api = described_class.new("danger", "danger", 1, env)
expect(api.send(:use_ssl)).to eq(true)
end
it "post build successful" do
allow(ENV).to receive(:[]).with("ENVDANGER_BITBUCKETSERVER_PASSWORD") { "supertopsecret" }
stub_request(:post, "https://stash.example.com/rest/build-status/1.0/commits/04dede05fb802bf1e6c69782ae98592d29c03b80").
with(body: "{\"state\":\"SUCCESSFUL\",\"key\":\"danger\",\"url\":\"build_job_link\",\"description\":\"description\"}",
headers: { "Accept" => "*/*", "Accept-Encoding" => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3", "Authorization" => "Basic YS5uYW1lOmFfcGFzc3dvcmQ=", "Content-Type" => "application/json", "User-Agent" => "Ruby" }).
to_return(status: 204, body: "", headers: {})
api = described_class.new("danger", "danger", 1, stub_env)
changesetId = "04dede05fb802bf1e6c69782ae98592d29c03b80"
response = api.update_pr_build_status("SUCCESSFUL", changesetId, "build_job_link", "description")
expect(response).to eq(nil)
end
end
describe "ssl verification" do
it "sets ssl verification environment variable to false" do
stub_env = { "DANGER_BITBUCKETSERVER_HOST" => "https://my_url", "DANGER_BITBUCKETSERVER_VERIFY_SSL" => "false" }
api = described_class.new("danger", "danger", 1, stub_env)
expect(api.verify_ssl).to be_falsey
end
it "sets ssl verification environment variable to true" do
stub_env = { "DANGER_BITBUCKETSERVER_HOST" => "https://my_url", "DANGER_BITBUCKETSERVERVERIFY_SSL" => "true" }
api = described_class.new("danger", "danger", 1, stub_env)
expect(api.verify_ssl).to be_truthy
end
it "sets ssl verification environment variable to wrong input" do
stub_env = { "DANGER_BITBUCKETSERVER_HOST" => "https://my_url", "DANGER_BITBUCKETSERVER_VERIFY_SSL" => "wronginput" }
api = described_class.new("danger", "danger", 1, stub_env)
expect(api.verify_ssl).to be_truthy
end
it "unsets ssl verification environment variable" do
stub_env = { "DANGER_BITBUCKETSERVER_HOST" => "https://my_url" }
api = described_class.new("danger", "danger", 1, stub_env)
expect(api.verify_ssl).to be_truthy
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/bitbucket_cloud_spec.rb | spec/lib/danger/request_sources/bitbucket_cloud_spec.rb | # frozen_string_literal: true
require "danger/request_sources/bitbucket_cloud"
require "danger/helpers/message_groups_array_helper"
require "danger/danger_core/message_group"
require "danger/danger_core/messages/violation"
RSpec.describe Danger::RequestSources::BitbucketCloud, host: :bitbucket_cloud do
let(:env) { stub_env }
let(:bs) { stub_request_source(env) }
describe "#new" do
it "should not raise uninitialized constant error" do
expect { described_class.new(stub_ci, env) }.not_to raise_error
end
end
describe "#validates_as_api_source" do
subject { bs.validates_as_api_source? }
context "when DANGER_BITBUKETCLOUD_USERNAME, _UUID, and _PASSWORD are set" do
it { is_expected.to be_truthy }
end
context "when DANGER_BITBUCKETCLOUD_USERNAME is unset" do
let(:env) { stub_env.reject { |k, _| k == "DANGER_BITBUCKETCLOUD_USERNAME" } }
it { is_expected.to be_falsey }
end
context "when DANGER_BITBUCKETCLOUD_USERNAME is empty" do
let(:env) { stub_env.merge("DANGER_BITBUCKETCLOUD_USERNAME" => "") }
it { is_expected.to be_falsey }
end
context "when DANGER_BITBUCKETCLOUD_UUID is unset" do
let(:env) { stub_env.reject { |k, _| k == "DANGER_BITBUCKETCLOUD_UUID" } }
it { is_expected.to be_falsey }
end
context "when DANGER_BITBUCKETCLOUD_UUID is empty" do
let(:env) { stub_env.merge("DANGER_BITBUCKETCLOUD_UUID" => "") }
it { is_expected.to be_falsey }
end
context "when DANGER_BITBUCKETCLOUD_PASSWORD is unset" do
let(:env) { stub_env.reject { |k, _| k == "DANGER_BITBUCKETCLOUD_PASSWORD" } }
it { is_expected.to be_falsey }
end
context "when DANGER_BITBUCKETCLOUD_PASSWORD is empty" do
let(:env) { stub_env.merge("DANGER_BITBUCKETCLOUD_PASSWORD" => "") }
it { is_expected.to be_falsey }
end
end
describe "#pr_json" do
before do
stub_pull_request
bs.fetch_details
end
it "has a non empty pr_json after `fetch_details`" do
expect(bs.pr_json).to be_truthy
end
describe "#pr_json[:id]" do
it "has fetched the same pull request id as ci_sources's `pull_request_id`" do
expect(bs.pr_json[:id]).to eq(2080)
end
end
describe "#pr_json[:title]" do
it "has fetched the pull requests title" do
expect(bs.pr_json[:title]).to eq("This is a danger test for bitbucket cloud")
end
end
end
describe "#delete_old_comments" do
let(:delete_uri) { "https://api.bitbucket.org/2.0/repositories/ios/fancyapp/pullrequests/2080/comments/12345" }
before do
stub_pull_request_comment
end
context "when credentials in place" do
it "matches a comment and deletes it" do
stub_request(:delete, delete_uri).to_return(status: 200, body: "", headers: {})
bs.delete_old_comments
expect(a_request(:delete, delete_uri)).to have_been_made
end
end
context "when missing DANGER_BITBUCKETCLOUD_UUID" do
let(:env) { stub_env.reject { |k, _| k == "DANGER_BITBUCKETCLOUD_UUID" } }
it "raises an error when deleting comment" do
expect { bs.delete_old_comments }.to raise_error(RuntimeError)
end
end
end
describe "#update_pr_by_line!" do
subject do
bs.update_pr_by_line!(message_groups: message_groups,
danger_id: danger_id,
new_comment: new_comment,
remove_previous_comments: remove_previous_comments)
end
let(:new_comment) { false }
let(:remove_previous_comments) { false }
let(:message_groups) { [] }
let(:danger_id) { Base64.encode64(Random.new.bytes(10)) }
before { message_groups.extend(Danger::Helpers::MessageGroupsArrayHelper) }
before { allow(bs).to receive(:delete_old_comments) }
let(:uri) { "https://api.bitbucket.org/2.0/repositories/ios/fancyapp/pullrequests/2080/comments" }
before do
stub_request(:post, uri)
.to_return(status: 200, body: "", headers: {})
end
context "with no message groups" do
it "uploads the summary comment" do
subject
expect(a_request(:post, uri)
.with(body: { content: { raw: /All green/ } })).to have_been_made
end
end
context "with a message group with some message" do
let(:message_groups) { [Danger::MessageGroup.new(file: file, line: line)] }
before do
message_groups.first << Danger::Violation.new("This is bad!",
false,
file,
line,
type: type)
end
let(:type) { :error }
context "that is an error" do
let(:type) { :error }
context "that doesn't relate to a particular line" do
let(:file) { nil }
let(:line) { nil }
it "uploads the summary comment" do
subject
expect(a_request(:post, uri)
.with(body: { content: { raw: /1 Error.*This is bad!/m } })).to have_been_made
end
end
end
context "that relates to a particular line" do
let(:file) { "bad_file.rb" }
let(:line) { 1 }
context "when type is error" do
let(:type) { :error }
it "summary says one error" do
subject
expect(a_request(:post, uri)
.with(body: { content: { raw: /1 Error/ } })).to have_been_made
end
it "makes a request for the error" do
subject
expect(
a_request(:post, uri)
.with(body: {
content: {
raw: /This is bad!/
},
inline: {
path: file,
to: line
}
})
).to have_been_made
end
end
context "when type is warning" do
let(:type) { :warning }
it "summary says one warning" do
subject
expect(a_request(:post, uri)
.with(body: { content: { raw: /1 Warning/ } })).to have_been_made
end
it "makes a request for the warning" do
subject
expect(
a_request(:post, uri)
.with(body: {
content: {
raw: /This is bad!/
},
inline: {
path: file,
to: line
}
})
).to have_been_made
end
end
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/github_spec.rb | spec/lib/danger/request_sources/github_spec.rb | # frozen_string_literal: true
require "danger/request_sources/github/github"
require "danger/ci_source/circle"
require "danger/ci_source/travis"
require "danger/danger_core/messages/violation"
RSpec.describe Danger::RequestSources::GitHub, host: :github do
describe "#inspect" do
it "masks access_token and bearer_token on inspect" do
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi", "DANGER_GITHUB_BEARER_TOKEN" => "ho" }
inspected = Danger::RequestSources::GitHub.new(stub_ci, gh_env).inspect
expect(inspected).to include(%(@access_token="********"))
expect(inspected).to include(%(@bearer_token="********"))
end
end
describe "the github host" do
it "sets a default GitHub host" do
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi" }
result = Danger::RequestSources::GitHub.new(stub_ci, gh_env).host
expect(result).to eq("github.com")
end
it "allows the GitHub host to be overridden" do
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi", "DANGER_GITHUB_HOST" => "git.club-mateusa.com" }
result = Danger::RequestSources::GitHub.new(stub_ci, gh_env).host
expect(result).to eq("git.club-mateusa.com")
end
describe "#api_url" do
it "allows the GitHub API host to be overridden with `DANGER_GITHUB_API_BASE_URL`" do
api_endpoint = "https://git.club-mateusa.com/api/v3/"
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi", "DANGER_GITHUB_API_BASE_URL" => api_endpoint }
result = Danger::RequestSources::GitHub.new(stub_ci, gh_env).api_url
expect(result).to eq api_endpoint
end
it "allows the GitHub API host to be overridden with `DANGER_GITHUB_API_HOST` for backwards compatibility" do
api_endpoint = "https://git.club-mateusa.com/api/v4/"
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi", "DANGER_GITHUB_API_HOST" => api_endpoint }
result = Danger::RequestSources::GitHub.new(stub_ci, gh_env).api_url
expect(result).to eq api_endpoint
end
end
end
describe "bearer token" do
context "with DANGER_GITHUB_BEARER_TOKEN" do
let(:client) { double("client") }
it "creates Octokit client with bearer token" do
allow(Octokit::Client).to receive(:new).and_return(client)
gh_env = { "DANGER_GITHUB_BEARER_TOKEN" => "hi" }
expect(Octokit::Client).to receive(:new).with(hash_including(:bearer_token))
Danger::RequestSources::GitHub.new(stub_ci, gh_env).client
end
end
end
describe "ssl verification" do
it "sets ssl verification environment variable to false" do
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi", "DANGER_GITHUB_HOST" => "git.club-mateusa.com", "DANGER_OCTOKIT_VERIFY_SSL" => "false" }
result = Danger::RequestSources::GitHub.new(stub_ci, gh_env).verify_ssl
expect(result).to be_falsey
end
it "sets ssl verification environment variable to true" do
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi", "DANGER_GITHUB_HOST" => "git.club-mateusa.com", "DANGER_OCTOKIT_VERIFY_SSL" => "true" }
result = Danger::RequestSources::GitHub.new(stub_ci, gh_env).verify_ssl
expect(result).to be_truthy
end
it "sets ssl verification environment variable to wrong input" do
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi", "DANGER_GITHUB_HOST" => "git.club-mateusa.com", "DANGER_OCTOKIT_VERIFY_SSL" => "wronginput" }
result = Danger::RequestSources::GitHub.new(stub_ci, gh_env).verify_ssl
expect(result).to be_truthy
end
it "unsets ssl verification environment variable" do
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi", "DANGER_GITHUB_HOST" => "git.club-mateusa.com" }
result = Danger::RequestSources::GitHub.new(stub_ci, gh_env).verify_ssl
expect(result).to be_truthy
end
end
describe "valid server response" do
before do
gh_env = { "DANGER_GITHUB_API_TOKEN" => "hi" }
@g = Danger::RequestSources::GitHub.new(stub_ci, gh_env)
pr_response = JSON.parse(fixture("github_api/pr_response"))
allow(@g.client).to receive(:pull_request).with("artsy/eigen", "800").and_return(pr_response)
issue_response = JSON.parse(fixture("github_api/issue_response"))
allow(@g.client).to receive(:get).with("https://api.github.com/repos/artsy/eigen/issues/800").and_return(issue_response)
end
it "sets its pr_json" do
@g.fetch_details
expect(@g.pr_json).to be_truthy
end
it "sets its issue_json" do
@g.fetch_details
expect(@g.issue_json).to be_truthy
end
it "raises an exception when the repo was moved from the git remote" do
allow(@g.client).to receive(:pull_request).with("artsy/eigen", "800").and_return({ "message" => "Moved Permanently" })
expect do
@g.fetch_details
end.to raise_error("Repo moved or renamed, make sure to update the git remote".red)
end
it "sets the ignored violations" do
@g.fetch_details
expect(@g.ignored_violations).to eq(
[
"Developer Specific file shouldn't be changed",
"Some warning"
]
)
end
describe "#organisation" do
it "valid value available" do
@g.fetch_details
expect(@g.organisation).to eq("artsy")
end
it "no valid value available doesn't crash" do
@g.issue_json = nil
expect(@g.organisation).to eq(nil)
end
end
describe "#file_url" do
before do
contents_response = JSON.parse(fixture("github_api/contents_response"))
allow(@g.client).to receive(:contents).with("artsy/danger", path: "Dangerfile", ref: nil).and_return(contents_response)
allow(@g.client).to receive(:contents).with("artsy/danger", path: "path/Dangerfile", ref: "master").and_return(contents_response)
allow(@g.client).to receive(:contents).with("teapot/danger", path: "Dangerfile", ref: nil).and_raise(Octokit::NotFound)
end
it "returns a valid URL with the minimum parameters" do
url = @g.file_url(organisation: "artsy", repository: "danger", path: "Dangerfile")
expect(url).to eq("https://raw.githubusercontent.com/artsy/danger/master/path/Dangerfile")
end
it "returns a valid URL with more parameters" do
url = @g.file_url(repository: "danger", organisation: "artsy", branch: "master", path: "path/Dangerfile")
expect(url).to eq("https://raw.githubusercontent.com/artsy/danger/master/path/Dangerfile")
end
it "returns a valid URL with using ref parameter" do
url = @g.file_url(repository: "danger", organisation: "artsy", ref: "master", path: "path/Dangerfile")
expect(url).to eq("https://raw.githubusercontent.com/artsy/danger/master/path/Dangerfile")
end
it "returns a valid fallback URL" do
url = @g.file_url(repository: "danger", organisation: "teapot", path: "Dangerfile")
expect(url).to eq("https://raw.githubusercontent.com/teapot/danger/master/Dangerfile")
end
end
describe "review" do
context "when already asked for review" do
before do
allow(@g.client).to receive(:pull_request_reviews).with("artsy/eigen", "800").and_return([])
@created_review = @g.review
end
it "returns the same review" do
expect(@g.review).to eq(@created_review)
end
end
context "when ask for review first time" do
context "when there are no danger review for PR" do
before do
allow(@g.client).to receive(:pull_request_reviews).with("artsy/eigen", "800").and_return([])
end
it "returns a newly created review" do
@review = @g.review
expect(@review.review_json).to be_nil
end
end
context "when there are danger review for PR" do
before do
pr_reviews_response = JSON.parse(fixture("github_api/pr_reviews_response"))
allow(@g.client).to receive(:pull_request_reviews).with("artsy/eigen", "800").and_return(pr_reviews_response)
end
it "returns the last review from danger" do
@review = @g.review
expect(@review.review_json).to_not be_nil
expect(@review.id).to eq(16_237_194)
end
end
end
context "when running against github enterprise which doesn't support reviews" do
it "returns an unsupported review instance" do
allow(@g.client).to receive(:pull_request_reviews).with("artsy/eigen", "800").and_raise(Octokit::NotFound)
review = @g.review
expect(review).to respond_to(
:id, :body, :status, :review_json, :start, :submit, :message, :warn,
:fail, :markdown
)
end
end
end
describe "status message" do
it "Shows a success message when no errors/warnings" do
message = @g.generate_description(warnings: [], errors: [])
expect(message).to start_with("All green.")
end
it "Shows an error messages when there are errors" do
message = @g.generate_description(warnings: violations_factory([1, 2, 3]), errors: [])
expect(message).to eq("⚠️ 3 Warnings. Don't worry, everything is fixable.")
end
it "Shows an error message when errors and warnings" do
message = @g.generate_description(warnings: violations_factory([1, 2]), errors: violations_factory([1, 2, 3]))
expect(message).to eq("⚠️ 3 Errors. 2 Warnings. Don't worry, everything is fixable.")
end
it "Deals with singualars in messages when errors and warnings" do
message = @g.generate_description(warnings: violations_factory([1]), errors: violations_factory([1]))
expect(message).to eq("⚠️ 1 Error. 1 Warning. Don't worry, everything is fixable.")
end
end
describe "commit status update" do
before do
stub_request(:post, "https://git.club-mateusa.com/api/v3/repos/artsy/eigen/statuses/").to_return status: 200
end
it "fails when no head commit is set" do
@g.pr_json = { "base" => { "sha" => "" }, "head" => { "sha" => "" } }
expect do
@g.submit_pull_request_status!
end.to raise_error("Couldn't find a commit to update its status".red)
end
it "uses danger_id as context of status" do
options = hash_including(context: "danger/special_context")
expect(@g.client).to receive(:create_status).with(any_args, options).and_return({})
@g.pr_json = { "head" => { "sha" => "pr_commit_ref" } }
@g.submit_pull_request_status!(danger_id: "special_context")
end
it "aborts when access to setting the status was denied but there were errors" do
stub_request(:post, "https://api.github.com/repos/artsy/eigen/statuses/pr_commit_ref").to_return(status: 404)
@g.pr_json = { "head" => { "sha" => "pr_commit_ref" }, "base" => { "repo" => { "private" => true } } }
expect do
@g.submit_pull_request_status!(errors: violations_factory(["error"]))
end.to raise_error.and output(/Danger has failed this build/).to_stderr
end
it "warns when access to setting the status was denied but no errors were reported" do
stub_request(:post, "https://api.github.com/repos/artsy/eigen/statuses/pr_commit_ref").to_return(status: 404)
@g.pr_json = { "head" => { "sha" => "pr_commit_ref" }, "base" => { "repo" => { "private" => true } } }
expect do
@g.submit_pull_request_status!(warnings: violations_factory(["error"]))
end.to output(/warning.*not have write access/im).to_stdout
end
end
describe "issue creation" do
before do
@g.pr_json = { "base" => { "sha" => "" }, "head" => { "sha" => "" } }
allow(@g).to receive(:submit_pull_request_status!).and_return(true)
end
it "creates a comment if no danger comments exist" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
comments = []
allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(comments)
body = @g.generate_comment(warnings: violations_factory(["hi"]), errors: [], messages: [])
expect(@g.client).to receive(:add_comment).with("artsy/eigen", "800", body).and_return({})
@g.update_pull_request!(warnings: violations_factory(["hi"]), errors: [], messages: [])
end
it "updates the issue if no danger comments exist" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
comments = [{ "body" => '"generated_by_danger"', "id" => "12" }]
allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(comments)
body = @g.generate_comment(warnings: violations_factory(["hi"]), errors: [], messages: [])
expect(@g.client).to receive(:update_comment).with("artsy/eigen", "12", body).and_return({})
@g.update_pull_request!(warnings: violations_factory(["hi"]), errors: [], messages: [])
end
it "creates a new comment instead of updating the issue if --new-comment is provided" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
comments = [{ "body" => '"generated_by_danger"', "id" => "12" }]
allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(comments)
body = @g.generate_comment(warnings: violations_factory(["hi"]), errors: [], messages: [])
expect(@g.client).to receive(:add_comment).with("artsy/eigen", "800", body).and_return({})
@g.update_pull_request!(warnings: violations_factory(["hi"]), errors: [], messages: [], new_comment: true)
end
it "updates the issue if no danger comments exist and a custom danger_id is provided" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
comments = [{ "body" => '"generated_by_another_danger"', "id" => "12" }]
allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(comments)
body = @g.generate_comment(warnings: violations_factory(["hi"]), errors: [], messages: [], danger_id: "another_danger")
expect(@g.client).to receive(:update_comment).with("artsy/eigen", "12", body).and_return({})
@g.update_pull_request!(warnings: violations_factory(["hi"]), errors: [], messages: [], danger_id: "another_danger")
end
it "deletes existing comments if danger doesnt need to say anything" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
comments = [{ "body" => '"generated_by_danger"', "id" => "12" }]
allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(comments)
allow(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id)
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", "12").and_return({})
@g.update_pull_request!(warnings: [], errors: [], messages: [])
end
it "deletes existing comments if danger doesnt need to say anything and a custom danger_id is provided" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
comments = [{ "body" => '"generated_by_another_danger"', "id" => "12" }]
allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(comments)
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", "12").and_return({})
allow(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id)
@g.update_pull_request!(warnings: [], errors: [], messages: [], danger_id: "another_danger")
end
# it "updates the comment if danger doesnt need to say anything but there are sticky violations" do
# comments = [{ body: "generated_by_danger", id: "12" }]
# allow(@g).to receive(:parse_comment).and_return({ errors: ["an error"] })
# allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(comments)
# expect(@g.client).to receive(:update_comment).with("artsy/eigen", "12", any_args).and_return({})
# @g.update_pull_request!(warnings: [], errors: [], messages: [])
# end
end
describe "#parse_message_from_row" do
it "handles pulling out links that include the file / line when in the main Danger comment" do
body = '<a href="https://github.com/artsy/eigen/blob/8e5d0bab431839a7046b2f7d5cd5ccb91677fe23/CHANGELOG.md#L1">CHANGELOG.md#L1</a> - Testing inline docs'
v = @g.parse_message_from_row(body)
expect(v.file).to eq("CHANGELOG.md")
expect(v.line).to eq(1)
expect(v.message).to include("- Testing inline docs")
end
it "handles pulling out file info from an inline Danger comment" do
body = '<span data-href="https://github.com/artsy/eigen/blob/8e5d0bab431839a7046b2f7d5cd5ccb91677fe23/CHANGELOG.md#L1"/>Testing inline docs'
v = @g.parse_message_from_row(body)
expect(v.file).to eq("CHANGELOG.md")
expect(v.line).to eq(1)
expect(v.message).to include("Testing inline docs")
end
end
let(:main_issue_id) { 76_535_362 }
let(:inline_issue_id_1) { 76_537_315 }
let(:inline_issue_id_2) { 76_537_316 }
describe "inline issues" do
before do
issues = JSON.parse(fixture("github_api/inline_comments"))
allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return(issues)
diff_files = JSON.parse(fixture("github_api/inline_comments_pr_diff_files"))
allow(@g.client).to receive(:pull_request_files).with("artsy/eigen", "800", { accept: "application/vnd.github.v3.diff" }).and_return(diff_files)
@g.fetch_details
allow(@g).to receive(:submit_pull_request_status!)
end
context "with Octokit v7" do
it "passes relative line number in the diff hunk to client.create_pull_request_comment" do
stub_const("Octokit::MAJOR", 7)
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
allow(@g.client).to receive(:create_pull_request_comment)
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_1).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_2).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id).and_return({})
v = Danger::Violation.new("Sure thing", true, "Rakefile", 34)
@g.update_pull_request!(warnings: [], errors: [], messages: [v])
expect(@g.client).to have_received(:create_pull_request_comment).with("artsy/eigen", "800", anything, "561827e46167077b5e53515b4b7349b8ae04610b", "Rakefile", 7)
end
end
context "with Octokit v8" do
it "passes absolute line number in the file to client.create_pull_request_comment" do
stub_const("Octokit::MAJOR", 8)
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
allow(@g.client).to receive(:create_pull_request_comment)
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_1).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_2).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id).and_return({})
v = Danger::Violation.new("Sure thing", true, "Rakefile", 34)
@g.update_pull_request!(warnings: [], errors: [], messages: [v])
expect(@g.client).to have_received(:create_pull_request_comment).with("artsy/eigen", "800", anything, "561827e46167077b5e53515b4b7349b8ae04610b", "Rakefile", 34)
end
end
it "deletes all inline comments if there are no violations at all" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
allow(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id)
allow(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_1)
allow(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_2)
allow(@g).to receive(:submit_pull_request_status!)
@g.update_pull_request!(warnings: [], errors: [], messages: [])
end
it "adds new comments inline" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
expect(@g.client).to receive(:create_pull_request_comment).with("artsy/eigen", "800", anything, "561827e46167077b5e53515b4b7349b8ae04610b", "CHANGELOG.md", 4)
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_1).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_2).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id).and_return({})
v = Danger::Violation.new("Sure thing", true, "CHANGELOG.md", 4)
@g.update_pull_request!(warnings: [], errors: [], messages: [v])
end
it "correctly handles trailing tabs in diff" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
expect(@g.client).to receive(:create_pull_request_comment).with("artsy/eigen", "800", anything, "561827e46167077b5e53515b4b7349b8ae04610b", "ios/Example/App Delegates/README.md", 4)
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_1).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_2).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id).and_return({})
v = Danger::Violation.new("Sure thing", true, "ios/Example/App Delegates/README.md", 4)
@g.update_pull_request!(warnings: [], errors: [], messages: [v])
end
it "adds main comment when inline out of range" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return([])
v = Danger::Violation.new("Sure thing", true, "CHANGELOG.md", 10)
body = @g.generate_comment(warnings: [], errors: [], messages: [v])
expect(@g.client).not_to receive(:create_pull_request_comment).with("artsy/eigen", "800", anything, "561827e46167077b5e53515b4b7349b8ae04610b", "CHANGELOG.md", 10)
expect(@g.client).to receive(:add_comment).with("artsy/eigen", "800", body).and_return({})
@g.update_pull_request!(warnings: [], errors: [], messages: [v])
end
it "ignores out of range inline comments when in dismiss mode" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
expect(@g.client).not_to receive(:create_pull_request_comment).with("artsy/eigen", "800", anything, "561827e46167077b5e53515b4b7349b8ae04610b", "CHANGELOG.md", 10)
expect(@g.client).not_to receive(:add_comment).with("artsy/eigen", "800", anything)
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_1).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_2).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id).and_return({})
v = Danger::Violation.new("Sure thing", true, "CHANGELOG.md", 10)
@g.dismiss_out_of_range_messages = true
@g.update_pull_request!(warnings: [], errors: [], messages: [v])
end
it "ignores out of range inline comments when in dismiss mode per kind" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
expect(@g.client).to receive(:create_pull_request_comment).with("artsy/eigen", "800", anything, "561827e46167077b5e53515b4b7349b8ae04610b", "CHANGELOG.md", 4)
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_1).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_2).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id).and_return({})
v = Danger::Violation.new("Sure thing", true, "CHANGELOG.md", 4)
m = Danger::Markdown.new("Sure thing", "CHANGELOG.md", 4)
@g.dismiss_out_of_range_messages = {
warning: false,
error: false,
message: false,
markdown: true
}
@g.update_pull_request!(warnings: [], errors: [], messages: [v], markdowns: [m])
end
it "crosses out sticky comments" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
expect(@g.client).to receive(:create_pull_request_comment).with("artsy/eigen", "800", anything, "561827e46167077b5e53515b4b7349b8ae04610b", "CHANGELOG.md", 4)
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_1).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_2).and_return({})
expect(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id).and_return({})
m = Danger::Markdown.new("Sure thing", "CHANGELOG.md", 4)
@g.update_pull_request!(warnings: [], errors: [], messages: [], markdowns: [m])
end
it "removes inline comments if they are not included" do
issues = [{ "body" => "'generated_by_another_danger'", "id" => "12" }]
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return(issues)
allow(@g.client).to receive(:create_pull_request_comment).with("artsy/eigen", "800", anything, "561827e46167077b5e53515b4b7349b8ae04610b", "CHANGELOG.md", 4)
# Main
allow(@g.client).to receive(:delete_comment).with("artsy/eigen", main_issue_id)
# Inline Issues
allow(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_1)
allow(@g.client).to receive(:delete_comment).with("artsy/eigen", inline_issue_id_2)
allow(@g).to receive(:submit_pull_request_status!)
v = Danger::Violation.new("Sure thing", true, "CHANGELOG.md", 4)
@g.update_pull_request!(warnings: [], errors: [], messages: [v])
end
it "keeps initial messages order" do
allow(@g.client).to receive(:pull_request_comments).with("artsy/eigen", "800").and_return([])
allow(@g.client).to receive(:issue_comments).with("artsy/eigen", "800").and_return([])
allow(@g.client).to receive(:add_comment).and_return({})
allow(@g).to receive(:submit_pull_request_status!).and_return(true)
allow(@g.client).to receive(:create_pull_request_comment).and_return({})
allow(@g.client).to receive(:delete_comment).and_return(true)
allow(@g.client).to receive(:delete_comment).and_return(true)
messages = [
Danger::Violation.new("1", false, nil, nil),
Danger::Violation.new("2", false, nil, nil),
Danger::Violation.new("3", false, nil, nil),
Danger::Violation.new("4", false, nil, nil),
Danger::Violation.new("5", false, nil, nil),
Danger::Violation.new("6", false, nil, nil),
Danger::Violation.new("7", false, nil, nil),
Danger::Violation.new("8", false, nil, nil),
Danger::Violation.new("9", false, nil, nil),
Danger::Violation.new("10", false, nil, nil)
]
expect(@g).to receive(:generate_comment).with(
template: "github",
danger_id: "danger",
previous_violations: {},
warnings: [],
errors: [],
messages: messages,
markdowns: []
)
@g.update_pull_request!(messages: messages)
end
end
describe "branch setup" do
it "setups the danger branches" do
@g.fetch_details
expect(@g.scm).to receive(:exec)
.with("rev-parse --quiet --verify 704dc55988c6996f69b6873c2424be7d1de67bbe^{commit}")
.and_return("345e74fabb2fecea93091e8925b1a7a208b48ba6")
expect(@g.scm).to receive(:exec)
.with("branch danger_base 704dc55988c6996f69b6873c2424be7d1de67bbe")
expect(@g.scm).to receive(:exec)
.with("rev-parse --quiet --verify 561827e46167077b5e53515b4b7349b8ae04610b^{commit}")
.and_return("561827e46167077b5e53515b4b7349b8ae04610b")
expect(@g.scm).to receive(:exec)
.with("branch danger_head 561827e46167077b5e53515b4b7349b8ae04610b")
@g.setup_danger_branches
end
it "fetches when the branches are not in the local store" do
# not in history
expect(@g.scm).to receive(:exec).
with("rev-parse --quiet --verify 704dc55988c6996f69b6873c2424be7d1de67bbe^{commit}").
and_return("")
[20, 74, 222, 625].each do |depth|
# fetch it
expect(@g.scm).to receive(:exec).with("fetch --depth=#{depth} --prune origin +refs/heads/master:refs/remotes/origin/master")
# still not in history
expect(@g.scm).to receive(:exec).
with("rev-parse --quiet --verify 704dc55988c6996f69b6873c2424be7d1de67bbe^{commit}").
and_return("")
end
# fetch it
expect(@g.scm).to receive(:exec).with("fetch --depth 1000000")
# still not in history
expect(@g.scm).to receive(:exec).
with("rev-parse --quiet --verify 704dc55988c6996f69b6873c2424be7d1de67bbe^{commit}").
and_return("")
expect do
@g.fetch_details
@g.setup_danger_branches
end.to raise_error(RuntimeError, /Commit (\w+|\b[0-9a-f]{5,40}\b) doesn't exist/)
end
end
end
describe "#find_position_in_diff" do
subject do
github.find_position_in_diff(diff_lines, message, kind)
end
let(:diff_lines) do
<<-DIFF.each_line.to_a
diff --git a/#{file_path} b/#{file_path}
index 0000000..0000001 100644
--- a/#{file_path}
+++ b/#{file_path}
@@ -1 +1,2 @@
-foo
+bar
+baz
DIFF
end
let(:file_path) do
"dummy"
end
let(:github) do
described_class.new(stub_ci, "DANGER_GITHUB_API_TOKEN" => "hi")
end
let(:kind) do
:dummy
end
let(:message) do
double(
file: file_path,
line: 1
)
end
context "when the lines count for the original file is omitted" do
it "returns correct position" do
is_expected.to eq(2)
end
end
context "when diff contain `No newline` annotation before added lines" do
let(:diff_lines) do
<<-DIFF.each_line.to_a
diff --git a/#{file_path} b/#{file_path}
index 0000000..0000001 100644
--- a/#{file_path}
+++ b/#{file_path}
@@ -1 +1,3 @@
-foo
\\ No newline at end of file
+foo
+bar
+baz
DIFF
end
it "returns correct position" do
is_expected.to eq(3)
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/bitbucket_cloud_api_spec.rb | spec/lib/danger/request_sources/bitbucket_cloud_api_spec.rb | # frozen_string_literal: true
require "danger/request_sources/bitbucket_cloud_api"
RSpec.describe Danger::RequestSources::BitbucketCloudAPI, host: :bitbucket_cloud do
subject(:api) { described_class.new(repo, pr_id, branch, env) }
let(:repo) { "ios/fancyapp" }
let(:pr_id) { 1 }
let(:branch) { "feature_branch" }
let(:env) { stub_env }
describe "#inspect" do
it "masks password on inspect" do
allow(ENV).to receive(:[]).with("ENVDANGER_BITBUCKETCLOUD_PASSWORD") { "supertopsecret" }
inspected = api.inspect
expect(inspected).to include(%(@password="********"))
end
context "with access token" do
let(:env) do
stub_env.merge(
"DANGER_BITBUCKETCLOUD_OAUTH_KEY" => "XXX",
"DANGER_BITBUCKETCLOUD_OAUTH_SECRET" => "YYY"
)
end
before { stub_access_token }
it "masks access_token on inspect" do
inspected = api.inspect
expect(inspected).to include(%(@access_token="********"))
end
end
end
describe "#project" do
let(:repo) { "org/repo" }
it "gets set from repo_slug" do
expect(api.project).to eq("org")
end
end
describe "#slug" do
let(:repo) { "org/repo" }
it "gets set from repo_slug" do
expect(api.slug).to eq("repo")
end
end
describe "#pull_request_id" do
it "gets set from pull_request_id" do
expect(api.pull_request_id).to eq(1)
end
context "when pr_id is nil" do
let(:pr_id) { nil }
it "fetches the id from bitbucket" do
stub_pull_requests
expect(api.pull_request_id).to eq(2080)
end
end
end
describe "#host" do
it "gets set from host" do
expect(api.host).to eq("https://bitbucket.org/")
end
end
describe "#my_uuid" do
subject { api.my_uuid }
let(:env) { stub_env.merge("DANGER_BITBUCKETCLOUD_UUID" => uuid) }
context "when DANGER_BITBUCKETCLOUD_UUID is empty string" do
let(:uuid) { nil }
it { is_expected.to be nil }
end
context "when DANGER_BITBUCKETCLOUD_UUID is empty string" do
let(:uuid) { "" }
it { is_expected.to eq "" }
end
context "when DANGER_BITBUCKETCLOUD_UUID is uuid without braces" do
let(:uuid) { "c91be865-efc6-49a6-93c5-24e1267c479b" }
it { is_expected.to eq "{c91be865-efc6-49a6-93c5-24e1267c479b}" }
end
context "when DANGER_BITBUCKETCLOUD_UUID is uuid with braces" do
let(:uuid) { "{c91be865-efc6-49a6-93c5-24e1267c479b}" }
it { is_expected.to eq "{c91be865-efc6-49a6-93c5-24e1267c479b}" }
end
end
describe "#credentials_given?" do
subject { api.credentials_given? }
context "when UUID is not given" do
let(:env) { stub_env.reject { |k, _| k == "DANGER_BITBUCKETCLOUD_UUID" } }
it { is_expected.to be_falsy }
end
context "when username is not given" do
let(:env) { stub_env.reject { |k, _| k == "DANGER_BITBUCKETCLOUD_USERNAME" } }
it { is_expected.to be_falsy }
end
context "when password is not given" do
let(:env) { stub_env.reject { |k, _| k == "DANGER_BITBUCKETCLOUD_PASSWORD" } }
it { is_expected.to be_falsy }
end
context "when repository access token is given" do
let(:env) do
stub_env
.reject { |k, _| %w(DANGER_BITBUCKETCLOUD_USERNAME DANGER_BITBUCKETCLOUD_PASSWORD).include?(k) }
.merge("DANGER_BITBUCKETCLOUD_REPO_ACCESSTOKEN" => "xxx")
end
it { is_expected.to be_truthy }
end
it "#fetch_json raise error when missing credentials" do
empty_env = {}
expect { api.pull_request }.to raise_error WebMock::NetConnectNotAllowedError
end
it "#post raise error when missing credentials" do
empty_env = {}
expect { api.post("http://post-url.org", {}) }.to raise_error NoMethodError
end
it "#delete raise error when missing credentials" do
empty_env = {}
expect { api.delete("http://delete-url.org") }.to raise_error NoMethodError
end
end
describe "#fetch_access_token" do
let(:pr_id) { "123" }
let(:branch) { "feature_branch" }
subject { api.access_token }
context "when DANGER_BITBUCKET_CLOUD_OAUTH_KEY and _SECRET are set" do
let(:env) do
stub_env.merge(
"DANGER_BITBUCKETCLOUD_OAUTH_KEY" => "XXX",
"DANGER_BITBUCKETCLOUD_OAUTH_SECRET" => "YYY"
)
end
before { stub_access_token }
it { is_expected.to eq("a_token") }
end
context "when only DANGER_BITBUCKETCLOUD_OAUTH_KEY is set" do
let(:env) { stub_env.merge("DANGER_BITBUCKETCLOUD_OAUTH_KEY" => "XXX") }
before { stub_access_token }
it { is_expected.to be nil }
end
context "when neither DANGER_BITBUCKETCLOUD_OAUTH_KEY and _SECRET are set" do
it { is_expected.to be nil }
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/vsts_spec.rb | spec/lib/danger/request_sources/vsts_spec.rb | # frozen_string_literal: true
require "danger/request_sources/vsts"
RSpec.describe Danger::RequestSources::VSTS, host: :vsts do
let(:env) { stub_env }
let(:subject) { Danger::RequestSources::VSTS.new(stub_ci, env) }
describe "#new" do
it "should not raise uninitialized constant error" do
expect { described_class.new(stub_ci, env) }.not_to raise_error
end
end
describe "#host" do
it "sets the host specified by `DANGER_VSTS_HOST`" do
expect(subject.host).to eq("https://example.visualstudio.com/example")
end
end
describe "#validates_as_api_source" do
it "validates_as_api_source for non empty `DANGER_VSTS_API_TOKEN`" do
expect(subject.validates_as_api_source?).to be true
end
end
describe "#pr_json" do
before do
stub_pull_request
subject.fetch_details
end
it "has a non empty pr_json after `fetch_details`" do
expect(subject.pr_json).to be_truthy
end
describe "#pr_json[:pullRequestId]" do
it "has fetched the same pull request id as ci_sources's `pull_request_id`" do
expect(subject.pr_json[:pullRequestId]).to eq(1)
end
end
describe "#pr_json[:title]" do
it "has fetched the pull requests title" do
expect(subject.pr_json[:title]).to eq("This is a danger test")
end
end
end
describe "#no_danger_comments" do
before do
stub_get_comments_request_no_danger
end
it "has to post a new comment" do
allow(subject).to receive(:post_new_comment)
expect(subject).to receive(:post_new_comment)
subject.update_pull_request!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger", new_comment: false)
end
end
describe "#danger_comment_update" do
before do
stub_get_comments_request_with_danger
end
it "it has to update the previous comment" do
allow(subject).to receive(:update_old_comment)
expect(subject).to receive(:update_old_comment)
subject.update_pull_request!(warnings: [], errors: [], messages: [], markdowns: [], danger_id: "danger", new_comment: false)
end
end
describe "valid server response" do
before do
stub_pull_request
subject.fetch_details
end
it "sets its pr_json" do
expect(subject.pr_json).to be_truthy
end
describe "status message" do
it "Shows a success message when no errors/warnings" do
message = subject.generate_description(warnings: [], errors: [])
expect(message).to start_with("All green.")
end
it "Shows an error messages when there are errors" do
message = subject.generate_description(warnings: violations_factory([1, 2, 3]), errors: [])
expect(message).to eq("⚠️ 3 Warnings. Don't worry, everything is fixable.")
end
it "Shows an error message when errors and warnings" do
message = subject.generate_description(warnings: violations_factory([1, 2]), errors: violations_factory([1, 2, 3]))
expect(message).to eq("⚠️ 3 Errors. 2 Warnings. Don't worry, everything is fixable.")
end
it "Deals with singualars in messages when errors and warnings" do
message = subject.generate_description(warnings: violations_factory([1]), errors: violations_factory([1]))
expect(message).to eq("⚠️ 1 Error. 1 Warning. Don't worry, everything is fixable.")
end
end
describe "inline issues" do
before do
stub_get_comments_request_with_danger
subject.fetch_details
end
it "adds new comments inline" do
expect(subject.client).to receive(:post_inline_comment).with(anything, "CHANGELOG.md", 4)
expect(subject.client).to receive(:update_comment).with(142, 1, anything)
v = Danger::Violation.new("Sure thing", true, "CHANGELOG.md", 4)
subject.update_pull_request!(warnings: [], errors: [], messages: [v])
end
it "crosses out sticky comments" do
expect(subject.client).to receive(:post_inline_comment).with(anything, "CHANGELOG.md", 4)
expect(subject.client).to receive(:update_comment).with(142, 1, anything)
m = Danger::Markdown.new("Sure thing", "CHANGELOG.md", 4)
subject.update_pull_request!(warnings: [], errors: [], messages: [], markdowns: [m])
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/vsts_api_spec.rb | spec/lib/danger/request_sources/vsts_api_spec.rb | # frozen_string_literal: true
require "danger/request_sources/vsts_api"
RSpec.describe Danger::RequestSources::VSTSAPI, host: :vsts do
describe "#inspect" do
it "masks personal access token on inspect" do
allow(ENV).to receive(:[]).with("ENVDANGER_VSTS_API_TOKEN") { "supertopsecret" }
api = described_class.new("danger", 1, stub_env)
inspected = api.inspect
expect(inspected).to include(%(@token="********"))
end
it "handles http hosts" do
env = stub_env
env["DANGER_VSTS_HOST"] = "http://my_url"
api = described_class.new("danger", 1, env)
expect(api.pr_api_endpoint).to eq("http://my_url/_apis/git/repositories/danger/pullRequests/1")
env["DANGER_VSTS_HOST"] = "my_url"
api = described_class.new("danger", 1, env)
expect(api.pr_api_endpoint).to eq("https://my_url/_apis/git/repositories/danger/pullRequests/1")
end
it "checks uses ssl only for https urls" do
env = stub_env
env["DANGER_VSTS_HOST"] = "http://my_url"
api = described_class.new("danger", 1, env)
expect(api.send(:use_ssl)).to eq(false)
env["DANGER_VSTS_HOST"] = "https://my_url"
api = described_class.new("danger", 1, env)
expect(api.send(:use_ssl)).to eq(true)
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/code_insights_api_spec.rb | spec/lib/danger/request_sources/code_insights_api_spec.rb | # frozen_string_literal: true
require "danger/request_sources/bitbucket_server"
RSpec.describe Danger::RequestSources::CodeInsightsAPI, host: :bitbucket_server do
let(:code_insights) do
code_insights_fields = {
"DANGER_BITBUCKETSERVER_CODE_INSIGHTS_REPORT_KEY" => "ReportKey",
"DANGER_BITBUCKETSERVER_CODE_INSIGHTS_REPORT_TITLE" => "Code Insights Report Title",
"DANGER_BITBUCKETSERVER_CODE_INSIGHTS_REPORT_DESCRIPTION" => "Report description",
"DANGER_BITBUCKETSERVER_CODE_INSIGHTS_REPORT_LOGO_URL" => "https://stash.example.com/logo_url.png"
}
stub_env_with_code_insights_fields = stub_env.merge(code_insights_fields)
Danger::RequestSources::CodeInsightsAPI.new("danger", "danger", stub_env_with_code_insights_fields)
end
describe "initialization" do
it "should properly parse corresponding environment variables" do
expect(code_insights.username).to eq("a.name")
expect(code_insights.password).to eq("a_password")
expect(code_insights.host).to eq("stash.example.com")
expect(code_insights.report_key).to eq("ReportKey")
expect(code_insights.report_title).to eq("Code Insights Report Title")
expect(code_insights.report_description).to eq("Report description")
expect(code_insights.logo_url).to eq("https://stash.example.com/logo_url.png")
end
end
describe "#is_ready" do
it "should return true when all required fields are provided" do
expect(code_insights.ready?).to be true
end
it "should return false when username is empty" do
code_insights.username = ""
expect(code_insights.ready?).to be false
end
it "should return false when password is empty" do
code_insights.password = ""
expect(code_insights.ready?).to be false
end
it "should return false when host is empty" do
code_insights.host = ""
expect(code_insights.ready?).to be false
end
it "should return false when report title is empty" do
code_insights.report_title = ""
expect(code_insights.ready?).to be false
end
it "should return false when report description is empty" do
code_insights.report_description = ""
expect(code_insights.ready?).to be false
end
it "should return false when report key is empty" do
code_insights.report_key = ""
expect(code_insights.ready?).to be false
end
end
describe "#inspect" do
it "should mask password on inspect" do
allow(ENV).to receive(:[]).with("ENVDANGER_BITBUCKETSERVER_PASSWORD") { "supertopsecret" }
api = described_class.new("danger", "danger", stub_env)
inspected = api.inspect
expect(inspected).to include(%(@password="********"))
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/support/get_ignored_violation_spec.rb | spec/lib/danger/request_sources/support/get_ignored_violation_spec.rb | # frozen_string_literal: true
RSpec.describe GetIgnoredViolation do
describe "#call" do
context "Without specific ignore sentence" do
it "returns empty array" do
result = described_class.new("No danger ignore").call
expect(result).to eq []
end
end
context "With specific ignore sentence" do
it "returns content in the quotes" do
sentence = %(Danger: Ignore "This build didn't pass tests")
result = described_class.new(sentence).call
expect(result).to eq ["This build didn't pass tests"]
end
end
context "With specific ignore sentence contains escapted quote" do
it "returns content in the quotes" do
sentence = %("ignoring this:\r\n>Danger: Ignore \"`TophatModels.v20` changed.\"")
result = described_class.new(sentence).call
expect(result).to eq [%(`TophatModels.v20` changed.)]
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/github/github_review_spec.rb | spec/lib/danger/request_sources/github/github_review_spec.rb | # frozen_string_literal: true
require "danger/request_sources/github/github_review"
require "danger/helpers/comments_helper"
require "danger/helpers/comment"
RSpec.describe Danger::RequestSources::GitHubSource::Review, host: :github do
include Danger::Helpers::CommentsHelper
let(:client) { double(Octokit::Client) }
describe "submit" do
subject do
Danger::RequestSources::GitHubSource::Review.new(client, stub_ci)
end
before do
subject.start
end
it "submits review request with correct body" do
subject.message("Hi")
subject.markdown("Yo")
subject.warn("I warn you")
subject.fail("This is bad, really bad")
messages = [Danger::Violation.new("Hi", true)]
warnings = [Danger::Violation.new("I warn you", true)]
errors = [Danger::Violation.new("This is bad, really bad", true)]
markdowns = [Danger::Markdown.new("Yo", true)]
expected_body = generate_comment(warnings: warnings,
errors: errors,
messages: messages,
markdowns: markdowns,
previous_violations: parse_comment(""),
danger_id: "danger",
template: "github")
expect(client).to receive(:create_pull_request_review).with(stub_ci.repo_slug, stub_ci.pull_request_id, event: Danger::RequestSources::GitHubSource::Review::EVENT_REQUEST_CHANGES, body: expected_body)
subject.submit
end
context "when there are only messages" do
before do
subject.message("Hi")
end
it "approves the pr" do
expect(client).to receive(:create_pull_request_review).with(stub_ci.repo_slug, stub_ci.pull_request_id, event: Danger::RequestSources::GitHubSource::Review::EVENT_APPROVE, body: anything)
subject.submit
end
end
context "when there are only markdowns" do
before do
subject.markdown("Hi")
end
it "approves the pr" do
expect(client).to receive(:create_pull_request_review).with(stub_ci.repo_slug, stub_ci.pull_request_id, event: Danger::RequestSources::GitHubSource::Review::EVENT_APPROVE, body: anything)
subject.submit
end
end
context "when there are only warnings" do
before do
subject.warn("Hi")
end
it "approves the pr" do
expect(client).to receive(:create_pull_request_review).with(stub_ci.repo_slug, stub_ci.pull_request_id, event: Danger::RequestSources::GitHubSource::Review::EVENT_APPROVE, body: anything)
subject.submit
end
end
context "when there are only errors" do
before do
subject.fail("Yo")
end
it "suggests changes to the pr" do
expect(client).to receive(:create_pull_request_review).with(stub_ci.repo_slug, stub_ci.pull_request_id, event: Danger::RequestSources::GitHubSource::Review::EVENT_REQUEST_CHANGES, body: anything)
subject.submit
end
end
context "when there are errors" do
before do
subject.message("Hi")
subject.markdown("Yo")
subject.warn("I warn you")
subject.fail("This is bad, really bad")
end
it "suggests changes to the pr" do
expect(client).to receive(:create_pull_request_review).with(stub_ci.repo_slug, stub_ci.pull_request_id, event: Danger::RequestSources::GitHubSource::Review::EVENT_REQUEST_CHANGES, body: anything)
subject.submit
end
end
context "when there are no errors" do
before do
subject.message("Hi")
subject.markdown("Yo")
subject.warn("I warn you")
end
it "sapproves the pr" do
expect(client).to receive(:create_pull_request_review).with(stub_ci.repo_slug, stub_ci.pull_request_id, event: Danger::RequestSources::GitHubSource::Review::EVENT_APPROVE, body: anything)
subject.submit
end
end
end
context "when initialized without review json" do
subject do
Danger::RequestSources::GitHubSource::Review.new(client, stub_ci)
end
describe "id" do
it "nil" do
expect(subject.id).to be nil
end
end
describe "status" do
it "returns a pending status" do
expect(subject.status).to eq Danger::RequestSources::GitHubSource::Review::STATUS_PENDING
end
end
describe "body" do
it "returns an empty string" do
expect(subject.body).to eq ""
end
end
end
context "when initialized with review json" do
let(:review_json) { JSON.parse(fixture("github_api/pr_review_response")) }
subject do
Danger::RequestSources::GitHubSource::Review.new(client, stub_ci, review_json)
end
describe "id" do
it "returns an id of request review" do
expect(subject.id).to eq 15_629_060
end
end
describe "status" do
it "returns a status from request review json" do
expect(subject.status).to eq Danger::RequestSources::GitHubSource::Review::STATUS_APPROVED
end
end
describe "body" do
it "returns a body from request review json" do
expect(subject.body).to eq "Looks good"
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/lib/danger/request_sources/github/github_review_resolver_spec.rb | spec/lib/danger/request_sources/github/github_review_resolver_spec.rb | # frozen_string_literal: true
require "danger/request_sources/github/github_review_resolver"
require "danger/request_sources/github/github_review"
RSpec.describe Danger::RequestSources::GitHubSource::ReviewResolver do
let(:review) { double(Danger::RequestSources::GitHubSource::Review) }
describe "should_submit?" do
context "when submission body the same as review has" do
before do
allow(review).to receive(:body).and_return "super body"
end
it "returns false" do
expect(described_class.should_submit?(review, "super body")).to be false
end
end
context "when submission body is different to review body" do
let(:submission_body) { "submission body" }
before do
allow(review).to receive(:body).and_return "unique body"
end
it "returns true" do
expect(described_class.should_submit?(review, "super body")).to be true
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/spec/clients/rubygems_client_spec.rb | spec/clients/rubygems_client_spec.rb | # frozen_string_literal: true
require "danger/clients/rubygems_client"
RSpec.describe Danger::RubyGemsClient do
describe ".latest_danger_version" do
context "rubygems.org is operational" do
it "returns latest danger version" do
latest_version_json = IO.read("spec/fixtures/rubygems_api/api_v1_versions_danger_latest.json")
allow(Faraday).to receive_message_chain(:get, :body) { latest_version_json }
result = described_class.latest_danger_version
expect(result).to eq "3.1.1"
end
end
context "user does not have network connection" do
it "returns dummy version" do
allow(Faraday).to receive_message_chain(:get, :body) { raise Faraday::ConnectionFailed }
result = described_class.latest_danger_version
expect(result).to eq described_class.const_get(:DUMMY_VERSION)
end
end
context "rubygems.org is not operational" do
it "returns dummy version" do
allow(Faraday).to receive_message_chain(:get, :body) { raise "RubyGems.org is down 🔥" }
result = described_class.latest_danger_version
expect(result).to eq described_class.const_get(:DUMMY_VERSION)
end
end
context "rubygems.org returns wrong data" do
it "returns dummy version" do
allow(Faraday).to receive_message_chain(:get, :body) { ["", nil].sample }
result = described_class.latest_danger_version
expect(result).to eq described_class.const_get(:DUMMY_VERSION)
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/docs/yard_support.rb | docs/yard_support.rb | # frozen_string_literal: true
require "kramdown"
require "kramdown-parser-gfm"
# Custom markup provider class that always renders Kramdown using GFM (Github Flavored Markdown).
# @see https://stackoverflow.com/a/63683511/6918498
class KramdownGfmDocument < Kramdown::Document
def initialize(source, options = {})
options[:input] = "GFM" unless options.key?(:input)
super(source, options)
end
end
# Register the new provider as the highest priority option for Markdown.
YARD::Templates::Helpers::MarkupHelper::MARKUP_PROVIDERS[:markdown].insert(0, { const: KramdownGfmDocument.name })
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger.rb | lib/danger.rb | # frozen_string_literal: true
require "danger/version"
require "danger/danger_core/dangerfile"
require "danger/danger_core/environment_manager"
require "danger/commands/runner"
require "danger/plugin_support/plugin"
require "danger/core_ext/string"
require "danger/danger_core/executor"
require "claide"
require "colored2"
require "pathname"
require "terminal-table"
require "cork"
# Import all the Sources (CI, Request and SCM)
Dir[File.expand_path("danger/*source/*.rb", File.dirname(__FILE__))].sort.each do |file|
require file
end
module Danger
GEM_NAME = "danger"
# @return [String] The path to the local gem directory
def self.gem_path
if Gem::Specification.find_all_by_name(GEM_NAME).empty?
raise "Couldn't find gem directory for 'danger'"
end
return Gem::Specification.find_by_name(GEM_NAME).gem_dir
end
# @return [String] Latest version of Danger on https://rubygems.org
def self.danger_outdated?
require "danger/clients/rubygems_client"
latest_version = RubyGemsClient.latest_danger_version
if Gem::Version.new(latest_version) > Gem::Version.new(Danger::VERSION)
latest_version
else
false
end
rescue StandardError => _e
false
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/version.rb | lib/danger/version.rb | # frozen_string_literal: true
module Danger
VERSION = "9.5.3"
DESCRIPTION = "Like Unit Tests, but for your Team Culture."
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/scm_source/git_repo.rb | lib/danger/scm_source/git_repo.rb | # frozen_string_literal: true
# For more info see: https://github.com/schacon/ruby-git
require "git"
module Danger
class GitRepo
attr_accessor :diff, :log, :folder
def diff_for_folder(folder, from: "master", to: "HEAD", lookup_top_level: false)
self.folder = folder
git_top_level = find_git_top_level_if_needed!(folder, lookup_top_level)
repo = Git.open(git_top_level)
ensure_commitish_exists!(from)
ensure_commitish_exists!(to)
merge_base = find_merge_base(repo, from, to)
commits_in_branch_count = commits_in_branch_count(from, to)
self.diff = repo.diff(merge_base, to)
self.log = repo.log(commits_in_branch_count).between(from, to)
end
def renamed_files
# Get raw diff with --find-renames --diff-filter
# We need to pass --find-renames cause
# older versions of git don't use this flag as default
diff = exec(
"diff #{self.diff.from} #{self.diff.to} --find-renames --diff-filter=R"
).lines.map { |line| line.tr("\n", "") }
before_name_regexp = /^rename from (.*)$/
after_name_regexp = /^rename to (.*)$/
# Extract old and new paths via regexp
diff.each_with_index.map do |line, index|
before_match = line.match(before_name_regexp)
next unless before_match
after_match = diff.fetch(index + 1, "").match(after_name_regexp)
next unless after_match
{
before: before_match.captures.first,
after: after_match.captures.first
}
end.compact
end
def exec(string)
require "open3"
Dir.chdir(self.folder || ".") do
git_command = string.split(" ").dup.unshift("git")
Open3.popen2(default_env, *git_command) do |_stdin, stdout, _wait_thr|
stdout.read.rstrip
end
end
end
def head_commit
exec("rev-parse HEAD")
end
def tags
exec("tag")
end
def origins
exec("remote show origin -n").lines.grep(/Fetch URL/)[0].split(": ", 2)[1].chomp
end
def ensure_commitish_exists!(commitish)
return ensure_commitish_exists_on_branch!(commitish, commitish) if commit_is_ref?(commitish)
return if commit_exists?(commitish)
git_in_depth_fetch
raise_if_we_cannot_find_the_commit(commitish) if commit_not_exists?(commitish)
end
def ensure_commitish_exists_on_branch!(branch, commitish)
return if commit_exists?(commitish)
depth = 0
success =
(3..6).any? do |factor|
depth += Math.exp(factor).to_i
git_fetch_branch_to_depth(branch, depth)
commit_exists?(commitish)
end
return if success
git_in_depth_fetch
raise_if_we_cannot_find_the_commit(commitish) if commit_not_exists?(commitish)
end
private
def git_in_depth_fetch
exec("fetch --depth 1000000")
end
def git_fetch_branch_to_depth(branch, depth)
exec("fetch --depth=#{depth} --prune origin +refs/heads/#{branch}:refs/remotes/origin/#{branch}")
end
def default_env
{ "LANG" => "en_US.UTF-8" }
end
def raise_if_we_cannot_find_the_commit(commitish)
raise "Commit #{commitish[0..7]} doesn't exist. Are you running `danger local/pr` against the correct repository? Also this usually happens when you rebase/reset and force-pushed."
end
def commit_exists?(sha1)
!commit_not_exists?(sha1)
end
def commit_not_exists?(sha1)
exec("rev-parse --quiet --verify #{sha1}^{commit}").empty?
end
def find_merge_base(repo, from, to)
possible_merge_base = possible_merge_base(repo, from, to)
return possible_merge_base if possible_merge_base
possible_merge_base = find_merge_base_with_incremental_fetch(repo, from, to)
return possible_merge_base if possible_merge_base
git_in_depth_fetch
possible_merge_base = possible_merge_base(repo, from, to)
raise "Cannot find a merge base between #{from} and #{to}. If you are using shallow clone/fetch, try increasing the --depth" unless possible_merge_base
possible_merge_base
end
def find_merge_base_with_incremental_fetch(repo, from, to)
from_is_ref = commit_is_ref?(from)
to_is_ref = commit_is_ref?(to)
return unless from_is_ref || to_is_ref
depth = 0
(3..6).each do |factor|
depth += Math.exp(factor).to_i
git_fetch_branch_to_depth(from, depth) if from_is_ref
git_fetch_branch_to_depth(to, depth) if to_is_ref
merge_base = possible_merge_base(repo, from, to)
return merge_base if merge_base
end
nil
end
def possible_merge_base(repo, from, to)
[repo.merge_base(from, to)].find { |base| commit_exists?(base) }
end
def commits_in_branch_count(from, to)
exec("rev-list #{from}..#{to} --count").to_i
end
def commit_is_ref?(commit)
/[a-f0-9]{5,40}/ !~ commit
end
def find_git_top_level_if_needed!(folder, lookup_top_level)
git_top_level = Dir.chdir(folder) { exec("rev-parse --show-toplevel") }
return git_top_level if lookup_top_level
# To keep backward compatibility, `GitRepo#diff_for_folder` expects folder
# to be top level git directory or requires `true` to `lookup_top_level`.
# https://github.com/danger/danger/pull/1178
return folder if compare_path(git_top_level, folder)
message = "#{folder} is not the top level git directory. Pass correct path or `true` to `lookup_top_level` option for `diff_for_folder`"
raise ArgumentError, message
end
# Compare given paths as realpath. Return true if both are same.
# `git rev-parse --show-toplevel` returns a path resolving symlink. In rspec, given path can
# be a temporary directory's path created under a symlinked directory `/var`.
def compare_path(path1, path2)
Pathname.new(path1).realdirpath == Pathname.new(path2).realdirpath
end
end
end
module Git
class Base
# Use git-merge-base https://git-scm.com/docs/git-merge-base to
# find as good common ancestors as possible for a merge
def merge_base(commit1, commit2, *other_commits)
Open3.popen2("git", "merge-base", commit1, commit2, *other_commits) { |_stdin, stdout, _wait_thr| stdout.read.rstrip }
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/helpers/message_groups_array_helper.rb | lib/danger/helpers/message_groups_array_helper.rb | # frozen_string_literal: true
module Danger
module Helpers
module MessageGroupsArrayHelper
FakeArray = Struct.new(:count) do
def empty?
count.zero?
end
end
def fake_warnings_array
FakeArray.new(counts[:warnings])
end
def fake_errors_array
FakeArray.new(counts[:errors])
end
def counts
return @counts if @counts
@counts = { warnings: 0, errors: 0 }
each do |message_group, counts|
group_stats = message_group.stats
@counts[:warnings] += group_stats[:warnings_count]
@counts[:errors] += group_stats[:errors_count]
end
@counts
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/helpers/emoji_mapper.rb | lib/danger/helpers/emoji_mapper.rb | # frozen_string_literal: true
module Danger
class EmojiMapper
DATA = {
"github" => {
"no_entry_sign" => "🚫",
"warning" => "⚠️",
"book" => "📖",
"white_check_mark" => "✅"
},
"bitbucket_server" => {
"no_entry_sign" => ":no_entry_sign:",
"warning" => ":warning:",
"book" => ":blue_book:",
"white_check_mark" => ":white_check_mark:"
}
}.freeze
TYPE_TO_EMOJI = {
error: "no_entry_sign",
warning: "warning",
message: "book"
}.freeze
def initialize(template)
@template = DATA.key?(template) ? template : "github"
end
def map(emoji)
cleaned_emoji = emoji&.delete(":") || emoji
DATA[template][cleaned_emoji]
end
def from_type(type)
map(TYPE_TO_EMOJI[type])
end
private
attr_reader :template
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/helpers/comments_helper.rb | lib/danger/helpers/comments_helper.rb | # frozen_string_literal: true
require "kramdown"
require "danger/helpers/comments_parsing_helper"
require "danger/helpers/emoji_mapper"
require "danger/helpers/find_max_num_violations"
module Danger
module Helpers
module CommentsHelper
# This might be a bit weird, but table_kind_from_title is a shared dependency for
# parsing and generating. And rubocop was adamant about file size so...
include Danger::Helpers::CommentsParsingHelper
def markdown_parser(text)
Kramdown::Document.new(text, input: "GFM", smart_quotes: %w(apos apos quot quot))
end
# @!group Extension points
# Produces a markdown link to the file the message points to
#
# request_source implementations are invited to override this method with their
# vendor specific link.
#
# @param [Violation or Markdown] message
# @param [Bool] hide_link Should hide any generated link created
#
# @return [String] The Markdown compatible link
def markdown_link_to_message(message, hide_link)
return "" if hide_link
"#{message.file}#L#{message.line}"
end
# @!group Extension points
# Determine whether two messages are equivalent
#
# request_source implementations are invited to override this method.
# This is mostly here to enable sources to detect when inlines change only in their
# commit hash and not in content per-se. since the link is implementation dependent
# so should be the comparison.
#
# @param [Violation or Markdown] m1
# @param [Violation or Markdown] m2
#
# @return [Boolean] whether they represent the same message
def messages_are_equivalent(m1, m2)
m1 == m2
end
# @endgroup
def process_markdown(violation, hide_link = false)
message = violation.message
message = "#{markdown_link_to_message(violation, hide_link)}#{message}" if violation.file && violation.line
html = markdown_parser(message).to_html
# Remove the outer `<p>` and `</p>`.
html = html.strip.sub(%r{\A<p>(.*)</p>\z}m, '\1')
Violation.new(html, violation.sticky, violation.file, violation.line)
end
def table(name, emoji, violations, all_previous_violations, template: "github")
content = violations
content = content.map { |v| process_markdown(v) } unless ["bitbucket_server", "vsts"].include?(template)
kind = table_kind_from_title(name)
previous_violations = all_previous_violations[kind] || []
resolved_violations = previous_violations.reject do |pv|
content.count { |v| messages_are_equivalent(v, pv) } > 0
end
resolved_messages = resolved_violations.map(&:message).uniq
count = content.count
{
name: name,
emoji: emoji,
content: content,
resolved: resolved_messages,
count: count
}
end
def apply_template(tables: [], markdowns: [], danger_id: "danger", template: "github", request_source: template)
require "erb"
md_template = File.join(Danger.gem_path, "lib/danger/comment_generators/#{template}.md.erb")
# erb: http://www.rrn.dk/rubys-erb-templating-system
# for the extra args: http://stackoverflow.com/questions/4632879/erb-template-removing-the-trailing-line
@tables = tables
@markdowns = markdowns.map(&:message)
@danger_id = danger_id
@emoji_mapper = EmojiMapper.new(request_source.sub("_inline", ""))
return ERB.new(File.read(md_template), trim_mode: "-").result(binding)
end
def generate_comment(warnings: [], errors: [], messages: [], markdowns: [], previous_violations: {}, danger_id: "danger", template: "github")
apply_template(
tables: [
table("Error", "no_entry_sign", errors, previous_violations, template: template),
table("Warning", "warning", warnings, previous_violations, template: template),
table("Message", "book", messages, previous_violations, template: template)
],
markdowns: markdowns,
danger_id: danger_id,
template: template
)
end
# resolved is essentially reserved for future use - eventually we might
# have some nice generic resolved-thing going :)
def generate_message_group_comment(message_group:,
danger_id: "danger",
resolved: [],
template: "github")
# cheating a bit - I don't want to alter the apply_template API
# so just sneak around behind its back setting some instance variables
# to get them to show up in the template
@message_group = message_group
@resolved = resolved
request_source_name = template.sub("_message_group", "")
apply_template(danger_id: danger_id,
markdowns: message_group.markdowns,
template: template,
request_source: request_source_name)
.sub(/\A\n*/, "")
end
def generate_inline_comment_body(emoji,
message,
danger_id: "danger",
resolved: false,
template: "github")
apply_template(
tables: [{ content: [message], resolved: resolved, emoji: emoji }],
danger_id: danger_id,
template: "#{template}_inline"
)
end
def generate_inline_markdown_body(markdown, danger_id: "danger", template: "github")
apply_template(
markdowns: [markdown],
danger_id: danger_id,
template: "#{template}_inline"
)
end
def generate_description(warnings: nil, errors: nil, template: "github")
emoji_mapper = EmojiMapper.new(template)
if (errors.nil? || errors.empty?) && (warnings.nil? || warnings.empty?)
return ENV["DANGER_SUCCESS_MESSAGE"] || "All green. #{random_compliment}"
else
message = "#{emoji_mapper.map('warning')} "
message += "#{'Error'.danger_pluralize(errors.count)}. " unless errors.empty?
message += "#{'Warning'.danger_pluralize(warnings.count)}. " unless warnings.empty?
message += "Don't worry, everything is fixable."
return message
end
end
def random_compliment
["Well done.", "Congrats.", "Woo!",
"Yay.", "Jolly good show.", "Good on 'ya.", "Nice work."].sample
end
private
def pluralize(string, count)
string.danger_pluralize(count)
end
def truncate(string)
max_message_length = 30
string.danger_truncate(max_message_length)
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/helpers/array_subclass.rb | lib/danger/helpers/array_subclass.rb | # frozen_string_literal: true
module Danger
module Helpers
module ArraySubclass
include Comparable
def initialize(array)
@__array__ = array
end
def kind_of?(compare_class)
return true if compare_class == self.class
dummy.kind_of?(compare_class)
end
def method_missing(name, *args, &block)
super unless __array__.respond_to?(name)
respond_to_method(name, *args, &block)
end
def respond_to_missing?(name, include_all)
__array__.respond_to?(name, include_all) || super
end
def to_a
__array__
end
def to_ary
__array__
end
def <=>(other)
return unless other.kind_of?(self.class)
__array__ <=> other.instance_variable_get(:@__array__)
end
private
attr_accessor :__array__
def dummy
Class.new(Array).new
end
def respond_to_method(name, *args, &block)
result = __array__.send(name, *args, &block)
return result unless result.kind_of?(Array)
if name =~ /!/
__array__ = result
self
else
self.class.new(result)
end
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/helpers/comment.rb | lib/danger/helpers/comment.rb | # frozen_string_literal: true
module Danger
class Comment
attr_reader :id, :body
def initialize(id, body, inline = nil)
@id = id
@body = body
@inline = inline
end
def self.from_github(comment)
self.new(comment["id"], comment["body"])
end
def self.from_gitlab(comment)
if comment.respond_to?(:id) && comment.respond_to?(:body)
type = comment.respond_to?(:type) ? comment.type : nil
self.new(comment.id, comment.body, type == "DiffNote")
else
self.new(comment["id"], comment["body"], comment["type"] == "DiffNote")
end
end
def generated_by_danger?(danger_id)
body.include?("\"generated_by_#{danger_id}\"")
end
def inline?
@inline.nil? ? body.include?("") : @inline
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/helpers/comments_parsing_helper.rb | lib/danger/helpers/comments_parsing_helper.rb | # frozen_string_literal: true
module Danger
module Helpers
module CommentsParsingHelper
# @!group Extension points
# Produces a message-like from a row in a comment table
#
# @param [String] row
# The content of the row in the table
#
# @return [Violation or Markdown] the extracted message
def parse_message_from_row(row)
Violation.new(row, true)
end
# @endgroup
def parse_tables_from_comment(comment)
comment.split("</table>")
end
def violations_from_table(table)
row_regex = %r{<td data-sticky="true">(?:<del>)?(.*?)(?:</del>)?\s*</td>}im
table.scan(row_regex).flatten.map do |row|
parse_message_from_row(row.strip)
end
end
def parse_comment(comment)
tables = parse_tables_from_comment(comment)
violations = {}
tables.each do |table|
match = danger_table?(table)
next unless match
title = match[1]
kind = table_kind_from_title(title)
next unless kind
violations[kind] = violations_from_table(table)
end
violations.reject { |_, v| v.empty? }
end
def table_kind_from_title(title)
case title
when /error/i
:error
when /warning/i
:warning
when /message/i
:message
end
end
private
GITHUB_OLD_REGEX = %r{<th width="100%"(.*?)</th>}im.freeze
NEW_REGEX = %r{<th.*data-danger-table="true"(.*?)</th>}im.freeze
def danger_table?(table)
# The old GitHub specific method relied on
# the width of a `th` element to find the table
# title and determine if it was a danger table.
# The new method uses a more robust data-danger-table
# tag instead.
match = GITHUB_OLD_REGEX.match(table)
return match if match
return NEW_REGEX.match(table)
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/helpers/find_max_num_violations.rb | lib/danger/helpers/find_max_num_violations.rb | # frozen_string_literal: true
# Find max_num_violations in lib/danger/comment_generators/github.md.erb.
class FindMaxNumViolations
# Save ~ 5000 for contents other than violations to avoid exceeded 65536 max comment length limit.
LIMIT = 60_000
def initialize(violations)
@violations = violations
end
def call
total = 0
num_of_violations_allowed = 0
violations.each do |violation|
message_length = violation.message.length + 80 # 80 is ~ the size of html wraps violation message.
if total + message_length < LIMIT
total += message_length
num_of_violations_allowed += 1
else
break
end
end
num_of_violations_allowed
end
private
attr_reader :violations
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/local.rb | lib/danger/commands/local.rb | # frozen_string_literal: true
require "danger/commands/local_helpers/http_cache"
require "danger/commands/local_helpers/local_setup"
require "danger/commands/local_helpers/pry_setup"
require "faraday/http_cache"
require "fileutils"
require "octokit"
require "tmpdir"
module Danger
class Local < Runner
self.summary = "Run the Dangerfile locally. This command is generally deprecated in favor of `danger pr`."
self.command = "local"
def self.options
[
["--use-merged-pr=[#id]", "The ID of an already merged PR inside your history to use as a reference for the local run."],
["--clear-http-cache", "Clear the local http cache before running Danger locally."],
["--pry", "Drop into a Pry shell after evaluating the Dangerfile."]
]
end
def initialize(argv)
show_help = true if argv.arguments == ["-h"]
@pr_num = argv.option("use-merged-pr")
@clear_http_cache = argv.flag?("clear-http-cache", false)
# Currently CLAide doesn't support short option like -h https://github.com/CocoaPods/CLAide/pull/60
# when user pass in -h, mimic the behavior of passing in --help.
argv = CLAide::ARGV.new ["--help"] if show_help
super
if argv.flag?("pry", false)
@dangerfile_path = PrySetup.new(cork).setup_pry(@dangerfile_path, Local.command)
end
end
def validate!
super
unless @dangerfile_path
help! "Could not find a Dangerfile."
end
end
def run
ENV["DANGER_USE_LOCAL_GIT"] = "YES"
ENV["LOCAL_GIT_PR_ID"] = @pr_num if @pr_num
configure_octokit(ENV["DANGER_TMPDIR"] || Dir.tmpdir)
env = EnvironmentManager.new(ENV, cork, @danger_id)
dm = Dangerfile.new(env, cork)
LocalSetup.new(dm, cork).setup(verbose: verbose) do
dm.run(
Danger::EnvironmentManager.danger_base_branch,
Danger::EnvironmentManager.danger_head_branch,
@dangerfile_path,
@danger_id,
nil,
nil
)
end
end
private
# this method is a duplicate of Commands::PR#configure_octokit
# - worth a refactor sometime?
def configure_octokit(cache_dir)
# setup caching for Github calls to hitting the API rate limit too quickly
cache_file = File.join(cache_dir, "danger_local_cache")
cache = HTTPCache.new(cache_file, clear_cache: @clear_http_cache)
Octokit.middleware = Faraday::RackBuilder.new do |builder|
builder.use Faraday::HttpCache, store: cache, serializer: Marshal, shared_cache: false
builder.use Octokit::Middleware::FollowRedirects
builder.use Octokit::Response::RaiseError
builder.adapter Faraday.default_adapter
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/staging.rb | lib/danger/commands/staging.rb | # frozen_string_literal: true
require "danger/commands/local_helpers/pry_setup"
require "fileutils"
require "tmpdir"
module Danger
class Staging < Runner
self.summary = "Run the Dangerfile locally against local master"
self.command = "staging"
def self.options
[
["--pry", "Drop into a Pry shell after evaluating the Dangerfile."]
]
end
def initialize(argv)
show_help = true if argv.arguments == ["-h"]
# Currently CLAide doesn't support short option like -h https://github.com/CocoaPods/CLAide/pull/60
# when user pass in -h, mimic the behavior of passing in --help.
argv = CLAide::ARGV.new ["--help"] if show_help
super
if argv.flag?("pry", false)
@dangerfile_path = PrySetup.new(cork).setup_pry(@dangerfile_path, Staging.command)
end
end
def validate!
super
unless @dangerfile_path
help! "Could not find a Dangerfile."
end
end
def run
ENV["DANGER_USE_LOCAL_ONLY_GIT"] = "YES"
env = EnvironmentManager.new(ENV, cork)
dm = Dangerfile.new(env, cork)
dm.run(
Danger::EnvironmentManager.danger_base_branch,
Danger::EnvironmentManager.danger_head_branch,
@dangerfile_path,
nil,
nil,
nil
)
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/mr.rb | lib/danger/commands/mr.rb | # frozen_string_literal: true
require "danger/commands/local_helpers/http_cache"
require "danger/commands/local_helpers/pry_setup"
require "faraday/http_cache"
require "fileutils"
require "tmpdir"
module Danger
class MR < Runner
self.summary = "Run the Dangerfile locally against GitLab Merge Requests. Does not post to the MR. Usage: danger mr <URL>"
self.command = "mr"
def self.options
[
["--clear-http-cache", "Clear the local http cache before running Danger locally."],
["--pry", "Drop into a Pry shell after evaluating the Dangerfile."],
["--dangerfile=<path/to/dangerfile>", "The location of your Dangerfile"]
]
end
def initialize(argv)
show_help = true if argv.arguments == ["-h"]
@mr_url = argv.shift_argument
@clear_http_cache = argv.flag?("clear-http-cache", false)
dangerfile = argv.option("dangerfile", "Dangerfile")
# Currently CLAide doesn't support short option like -h https://github.com/CocoaPods/CLAide/pull/60
# when user pass in -h, mimic the behavior of passing in --help.
argv = CLAide::ARGV.new ["--help"] if show_help
super
@dangerfile_path = dangerfile if File.exist?(dangerfile)
if argv.flag?("pry", false)
@dangerfile_path = PrySetup.new(cork).setup_pry(@dangerfile_path, MR.command)
end
end
def validate!
super
unless @dangerfile_path
help! "Could not find a Dangerfile."
end
unless @mr_url
help! "Could not find a merge-request. Usage: danger mr <URL>"
end
end
def run
ENV["DANGER_USE_LOCAL_GIT"] = "YES"
ENV["LOCAL_GIT_MR_URL"] = @mr_url if @mr_url
configure_gitlab(ENV["DANGER_TMPDIR"] || Dir.tmpdir)
env = EnvironmentManager.new(ENV, cork)
dm = Dangerfile.new(env, cork)
LocalSetup.new(dm, cork).setup(verbose: verbose) do
dm.run(
Danger::EnvironmentManager.danger_base_branch,
Danger::EnvironmentManager.danger_head_branch,
@dangerfile_path,
nil,
nil,
nil,
false
)
end
end
private
def configure_gitlab(cache_dir)
# The require happens inline so that it won't cause exceptions when just using the `danger` gem.
require "gitlab"
# setup caching for GitLab calls to avoid hitting the API rate limit too quickly
cache_file = File.join(cache_dir, "danger_local_gitlab_cache")
HTTPCache.new(cache_file, clear_cache: @clear_http_cache)
# Configure GitLab client
Gitlab.configure do |config|
config.endpoint = ENV["DANGER_GITLAB_API_BASE_URL"] || ENV.fetch("CI_API_V4_URL", "https://gitlab.com/api/v4")
config.private_token = ENV["DANGER_GITLAB_API_TOKEN"]
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/runner.rb | lib/danger/commands/runner.rb | # frozen_string_literal: true
module Danger
class Runner < CLAide::Command
require "danger/commands/init"
require "danger/commands/local"
require "danger/commands/dry_run"
require "danger/commands/staging"
require "danger/commands/systems"
require "danger/commands/pr"
require "danger/commands/mr"
# manually set claide plugins as a subcommand
require "claide_plugin"
@subcommands << CLAide::Command::Plugins
CLAide::Plugins.config =
CLAide::Plugins::Configuration.new(
"Danger",
"danger",
"https://gitlab.com/danger-systems/danger.systems/raw/master/plugins-search-generated.json",
"https://github.com/danger/danger-plugin-template"
)
require "danger/commands/plugins/plugin_lint"
require "danger/commands/plugins/plugin_json"
require "danger/commands/plugins/plugin_readme"
require "danger/commands/dangerfile/init"
require "danger/commands/dangerfile/gem"
attr_accessor :cork
self.summary = "Run the Dangerfile."
self.command = "danger"
self.version = Danger::VERSION
self.plugin_prefixes = %w(claide danger)
def initialize(argv)
dangerfile = argv.option("dangerfile", "Dangerfile")
@dangerfile_path = dangerfile if File.exist?(dangerfile)
@base = argv.option("base")
@head = argv.option("head")
@fail_on_errors = argv.option("fail-on-errors", false)
@fail_if_no_pr = argv.option("fail-if-no-pr", false)
@new_comment = argv.flag?("new-comment")
@remove_previous_comments = argv.flag?("remove-previous-comments")
@danger_id = argv.option("danger_id", "danger")
@cork = Cork::Board.new(silent: argv.option("silent", false),
verbose: argv.option("verbose", false))
adjust_colored2_output(argv)
super
end
def validate!
super
if self.instance_of?(Runner) && !@dangerfile_path
help!("Could not find a Dangerfile.")
end
end
def self.options
[
["--base=[master|dev|stable]", "A branch/tag/commit to use as the base of the diff"],
["--head=[master|dev|stable]", "A branch/tag/commit to use as the head"],
["--fail-on-errors=<true|false>", "Should always fail the build process, defaults to false"],
["--fail-if-no-pr=<true|false>", "Should fail the build process if no PR is found (useful for CircleCI), defaults to false"],
["--dangerfile=<path/to/dangerfile>", "The location of your Dangerfile"],
["--danger_id=<id>", "The identifier of this Danger instance"],
["--new-comment", "Makes Danger post a new comment instead of editing its previous one"],
["--remove-previous-comments", "Removes all previous comment and create a new one in the end of the list"]
].concat(super)
end
def run
Executor.new(ENV).run(
base: @base,
head: @head,
dangerfile_path: @dangerfile_path,
danger_id: @danger_id,
new_comment: @new_comment,
fail_on_errors: @fail_on_errors,
fail_if_no_pr: @fail_if_no_pr,
remove_previous_comments: @remove_previous_comments
)
end
private
def adjust_colored2_output(argv)
# disable/enable colored2 output
# consider it execution wide to avoid need to wrap #run and maintain state
# ARGV#options is non-destructive way to check flags
Colored2.public_send(argv.options.fetch("ansi", true) ? "enable!" : "disable!")
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/systems.rb | lib/danger/commands/systems.rb | # frozen_string_literal: true
module Danger
class Systems < Runner
self.abstract_command = true
self.description = "For commands related to passing information from Danger to Danger.Systems."
self.summary = "Create data for Danger.Systems."
end
class CIDocs < Systems
self.command = "ci_docs"
self.summary = "Outputs the up-to-date CI documentation for Danger."
def run
here = File.dirname(__FILE__)
ci_source_paths = Dir.glob("#{here}/../ci_source/*.rb")
require "yard"
# Pull out all the Danger::CI subclasses docs
registry = YARD::Registry.load(ci_source_paths, true)
ci_sources = registry.all(:class)
.select { |klass| klass.inheritance_tree.map(&:name).include? :CI }
.reject { |source| source.name == :CI }
.reject { |source| source.name == :LocalGitRepo }
# Fail if anything is added and not documented
cis_without_docs = ci_sources.select { |source| source.base_docstring.empty? }
unless cis_without_docs.empty?
cork.puts "Please add docs to: #{cis_without_docs.map(&:name).join(', ')}"
abort("Failed.".red)
end
# Output a JSON array of name and details
require "json"
cork.puts ci_sources.map { |ci|
{
name: ci.name,
docs: ci.docstring
}
}.to_json
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/dry_run.rb | lib/danger/commands/dry_run.rb | # frozen_string_literal: true
require "danger/commands/local_helpers/pry_setup"
require "fileutils"
module Danger
class DryRun < Runner
self.summary = "Dry-Run the Dangerfile locally, so you could check some violations before sending real PR/MR."
self.command = "dry_run"
def self.options
[
["--pry", "Drop into a Pry shell after evaluating the Dangerfile."]
]
end
def initialize(argv)
show_help = true if argv.arguments == ["-h"]
# Currently CLAide doesn't support short option like -h https://github.com/CocoaPods/CLAide/pull/60
# when user pass in -h, mimic the behavior of passing in --help.
argv = CLAide::ARGV.new ["--help"] if show_help
super
if argv.flag?("pry", false)
@dangerfile_path = PrySetup.new(cork).setup_pry(@dangerfile_path, DryRun.command)
end
end
def validate!
super
unless @dangerfile_path
help! "Could not find a Dangerfile."
end
end
def run
ENV["DANGER_USE_LOCAL_ONLY_GIT"] = "YES"
ENV["DANGER_LOCAL_HEAD"] = @head if @head
ENV["DANGER_LOCAL_BASE"] = @base if @base
env = EnvironmentManager.new(ENV, cork)
dm = Dangerfile.new(env, cork)
exit 1 if dm.run(
Danger::EnvironmentManager.danger_base_branch,
Danger::EnvironmentManager.danger_head_branch,
@dangerfile_path,
nil,
nil,
nil
)
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/pr.rb | lib/danger/commands/pr.rb | # frozen_string_literal: true
require "danger/commands/local_helpers/http_cache"
require "danger/commands/local_helpers/pry_setup"
require "faraday/http_cache"
require "fileutils"
require "octokit"
require "tmpdir"
module Danger
class PR < Runner
self.summary = "Run the Dangerfile locally against Pull Requests (works with forks, too). Does not post to the PR. Usage: danger pr <URL>"
self.command = "pr"
def self.options
[
["--clear-http-cache", "Clear the local http cache before running Danger locally."],
["--pry", "Drop into a Pry shell after evaluating the Dangerfile."],
["--dangerfile=<path/to/dangerfile>", "The location of your Dangerfile"],
["--verify-ssl", "Verify SSL in Octokit"]
]
end
def initialize(argv)
show_help = true if argv.arguments == ["-h"]
@pr_url = argv.shift_argument
@clear_http_cache = argv.flag?("clear-http-cache", false)
dangerfile = argv.option("dangerfile", "Dangerfile")
@verify_ssl = argv.flag?("verify-ssl", true)
# Currently CLAide doesn't support short option like -h https://github.com/CocoaPods/CLAide/pull/60
# when user pass in -h, mimic the behavior of passing in --help.
argv = CLAide::ARGV.new ["--help"] if show_help
super
@dangerfile_path = dangerfile if File.exist?(dangerfile)
if argv.flag?("pry", false)
@dangerfile_path = PrySetup.new(cork).setup_pry(@dangerfile_path, PR.command)
end
end
def validate!
super
unless @dangerfile_path
help! "Could not find a Dangerfile."
end
unless @pr_url
help! "Could not find a pull-request. Usage: danger pr <URL>"
end
end
def run
ENV["DANGER_USE_LOCAL_GIT"] = "YES"
ENV["LOCAL_GIT_PR_URL"] = @pr_url if @pr_url
configure_octokit(ENV["DANGER_TMPDIR"] || Dir.tmpdir)
env = EnvironmentManager.new(ENV, cork)
dm = Dangerfile.new(env, cork)
LocalSetup.new(dm, cork).setup(verbose: verbose) do
dm.run(
Danger::EnvironmentManager.danger_base_branch,
Danger::EnvironmentManager.danger_head_branch,
@dangerfile_path,
nil,
nil,
nil,
false
)
end
end
private
def configure_octokit(cache_dir)
# setup caching for Github calls to hitting the API rate limit too quickly
cache_file = File.join(cache_dir, "danger_local_cache")
cache = HTTPCache.new(cache_file, clear_cache: @clear_http_cache)
Octokit.configure do |config|
config.connection_options[:ssl] = { verify: @verify_ssl }
end
Octokit.middleware = Faraday::RackBuilder.new do |builder|
builder.use Faraday::HttpCache, store: cache, serializer: Marshal, shared_cache: false
builder.use Octokit::Middleware::FollowRedirects
builder.use Octokit::Response::RaiseError
builder.adapter Faraday.default_adapter
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/init.rb | lib/danger/commands/init.rb | # frozen_string_literal: true
require "danger/commands/init_helpers/interviewer"
require "danger/danger_core/dangerfile_generator"
require "danger/ci_source/local_git_repo"
require "yaml"
module Danger
class Init < Runner
self.summary = "Helps you set up Danger."
self.command = "init"
attr_accessor :ui
def self.options
[
["--impatient", "'I've not got all day here. Don't add any thematic delays please.'"],
["--mousey", "'Don't make me press return to continue the adventure.'"]
].concat(super)
end
def initialize(argv)
@bot_name = "#{File.basename(Dir.getwd).split('.').first.capitalize}Bot"
super
@ui = Interviewer.new(cork)
ui.no_delay = argv.flag?("impatient", false)
ui.no_waiting = argv.flag?("mousey", false)
end
def run
ui.say "\nOK, thanks #{ENV['LOGNAME']}, have a seat and we'll get you started.\n".yellow
ui.pause 1
show_todo_state
ui.pause 1.4
setup_dangerfile
setup_github_account
setup_access_token
setup_danger_ci
info
thanks
end
def show_todo_state
ui.say "We need to do the following:\n"
ui.pause 0.6
ui.say " - [ ] Create a Dangerfile and add a few simple rules."
ui.pause 0.6
ui.say " - [#{@account_created ? 'x' : ' '}] Create a GitHub account for Danger to use, for messaging."
ui.pause 0.6
ui.say " - [ ] Set up an access token for Danger."
ui.pause 0.6
ui.say " - [ ] Set up Danger to run on your CI.\n\n"
end
def setup_dangerfile
content = DangerfileGenerator.create_dangerfile(".", cork)
File.write("Dangerfile", content)
ui.header "Step 1: Creating a starter Dangerfile"
ui.say "I've set up an example Dangerfile for you in this folder.\n"
ui.pause 1
ui.say "cat #{Dir.pwd}/Dangerfile\n".blue
content.lines.each do |l|
ui.say " #{l.chomp.green}"
end
ui.say ""
ui.pause 2
ui.say "There's a collection of small, simple ideas in here, but Danger is about being able to easily"
ui.say "iterate. The power comes from you having the ability to codify fixes for some of the problems"
ui.say "that come up in day to day programming. It can be difficult to try and see those from day 1."
ui.say "\nIf you'd like to investigate the file, and make some changes - I'll wait here,"
ui.say "press return when you're ready to move on..."
ui.wait_for_return
end
def setup_github_account
ui.header "Step 2: Creating a GitHub account"
ui.say "In order to get the most out of Danger, I'd recommend giving her the ability to post in"
ui.say "the code-review comment section.\n\n"
ui.pause 1
ui.say "IMO, it's best to do this by using the private mode of your browser. Create an account like"
ui.say "#{@bot_name}, and don't forget a cool robot avatar.\n\n"
ui.pause 1
ui.say "Here are great resources for creative commons images of robots:"
ui.link "https://www.flickr.com/search/?text=robot&license=2%2C3%2C4%2C5%2C6%2C9"
ui.link "https://www.google.com/search?q=robot&tbs=sur:fmc&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwjgy8-f95jLAhWI7hoKHV_UD00QsAQIMQ&biw=1265&bih=1359"
ui.pause 1
if considered_an_oss_repo?
ui.say "#{@bot_name} does not need privileged access to your repo or org. This is because Danger will only"
ui.say "be writing comments, and you do not need special access for that."
else
ui.say "#{@bot_name} will need access to your repo. Simply because the code is not available for the public"
ui.say "to read and comment on."
end
ui.say ""
note_about_clicking_links
ui.pause 1
ui.say "\nCool, please press return when you have your account ready (and you've verified the email...)"
ui.wait_for_return
end
def setup_access_token
ui.header "Step 3: Configuring a GitHub Personal Access Token"
ui.say "Here's the link, you should open this in the private session where you just created the new GitHub account"
ui.link "https://github.com/settings/tokens/new"
ui.pause 1
@is_open_source = ui.ask_with_answers("For token access rights, I need to know if this is for an Open Source or Closed Source project\n", ["Open", "Closed"])
if considered_an_oss_repo?
ui.say "For Open Source projects, I'd recommend giving the token the smallest scope possible."
ui.say "This means only providing access to #{'public_repo'.yellow} in the token.\n\n"
ui.pause 1
ui.say "This token limits Danger's abilities to just writing comments on OSS projects. I recommend"
ui.say "this because the token can quite easily be extracted from the environment via pull requests."
ui.say "\nIt is important that you do not store this token in your repository, as GitHub will automatically revoke it when pushed.\n"
elsif @is_open_source == "closed"
ui.say "For Closed Source projects, I'd recommend giving the token access to the whole repo scope."
ui.say "This means only providing access to #{'repo'.yellow}, and its children in the token.\n\n"
ui.pause 1
ui.say "It's worth noting that you #{'should not'.bold.white} re-use this token for OSS repos."
ui.say "Make a new one for those repos with just #{'public_repo'.yellow}."
ui.pause 1
ui.say "Additionally, don't forget to add your new GitHub account as a collaborator to your Closed Source project."
end
ui.say "\n👍, please press return when you have your token set up..."
ui.wait_for_return
end
def considered_an_oss_repo?
@is_open_source == "open"
end
def current_repo_slug
git = GitRepo.new
author_repo_regexp = %r{(?:[/:])([^/]+/[^/]+)(?:.git)?$}
last_git_regexp = /.git$/
matches = git.origins.match(author_repo_regexp)
matches ? matches[1].gsub(last_git_regexp, "").strip : "[Your/Repo]"
end
def setup_danger_ci
ui.header "Step 4: Add Danger for your CI"
uses_travis if File.exist? ".travis.yml"
uses_circle if File.exist? "circle.yml"
unsure_ci unless File.exist?(".travis.yml") || File.exist?(".circle.yml")
ui.say "\nOK, I'll give you a moment to do this..."
ui.wait_for_return
ui.header "Final step: exposing the GitHub token as an environment build variable."
ui.pause 0.4
if considered_an_oss_repo?
ui.say "As you have an Open Source repo, this token should be considered public, otherwise you cannot"
ui.say "run Danger on pull requests from forks, limiting its use.\n"
ui.pause 1
end
travis_token if File.exist? ".travis.yml"
circle_token if File.exist? "circle.yml"
unsure_token unless File.exist?(".travis.yml") || File.exist?(".circle.yml")
ui.pause 0.6
ui.say "This is the last step, I can give you a second..."
ui.wait_for_return
end
def uses_travis
danger = "bundle exec danger".yellow
config = YAML.load(File.read(".travis.yml"))
if config.kind_of?(Hash) && config["script"]
ui.say "Add #{'- '.yellow}#{danger} as a new step in the #{'script'.yellow} section of your .travis.yml file."
else
ui.say "I'd recommend adding #{'before_script: '.yellow}#{danger} to the script section of your .travis.yml file."
end
ui.pause 1
ui.say "You shouldn't use #{'after_success, after_failure, after_script'.red} as they cannot fail your builds."
end
def uses_circle
danger = "- bundle exec danger".yellow
config = YAML.load(File.read("circle.yml"))
if config.kind_of?(Hash) && config["test"]
if config["test"]["post"]
ui.say "Add #{danger} as a new step in the #{'test:post:'.yellow} section of your circle.yml file."
else
ui.say "Add #{danger} as a new step in the #{'test:override:'.yellow} section of your circle.yml file."
end
else
ui.say "Add this to the bottom of your circle.yml file:"
ui.say "test:".green
ui.say " post:".green
ui.say " #{danger}".green
end
end
def unsure_ci
danger = "bundle exec danger".yellow
ui.say "As I'm not sure what CI you want to run Danger on based on the files in your repo, I'll just offer some generic"
ui.say "advice. You want to run #{danger} after your tests have finished running, it should still be during the testing"
ui.say "process so the build can fail."
end
def travis_token
# https://travis-ci.org/artsy/eigen/settings
ui.say "In order to add an environment variable, go to:"
ui.link "https://travis-ci.org/#{current_repo_slug}/settings"
ui.say "\nThe name is #{'DANGER_GITHUB_API_TOKEN'.yellow} and the value is the GitHub Personal Access Token."
if @is_open_source
ui.say 'Make sure to have "Display value in build log" enabled.'
end
end
def circle_token
# https://circleci.com/gh/artsy/eigen/edit#env-vars
if considered_an_oss_repo?
ui.say "Before we start, it's important to be up-front. CircleCI only really has one option to support running Danger"
ui.say "for forks on OSS repos. It is quite a drastic option, and I want to let you know the best place to understand"
ui.say "the ramifications of turning on a setting I'm about to advise.\n"
ui.link "https://circleci.com/docs/fork-pr-builds"
ui.say "TLDR: If you have anything other than Danger config settings in CircleCI, then you should not turn on the setting."
ui.say "I'll give you a minute to read it..."
ui.wait_for_return
ui.say "On danger/danger we turn on #{'Permissive building of fork pull requests'.yellow} this exposes the token to Danger"
ui.say "You can find this setting at:"
ui.link "https://circleci.com/gh/#{current_repo_slug}/edit#advanced-settings\n"
ui.say "I'll hold..."
ui.wait_for_return
end
ui.say "In order to expose an environment variable, go to:"
ui.link "https://circleci.com/gh/#{current_repo_slug}/edit#env-vars"
ui.say "The name is #{'DANGER_GITHUB_API_TOKEN'.yellow} and the value is the GitHub Personal Access Token."
end
def unsure_token
ui.say "You need to expose a token called #{'DANGER_GITHUB_API_TOKEN'.yellow} and the value is the GitHub Personal Access Token."
ui.say "Depending on the CI system, this may need to be done on the machine (in the #{'~/.bashprofile'.yellow}) or in a web UI somewhere."
ui.say "We have a guide for all supported CI systems on danger.systems:"
ui.link "https://danger.systems/guides/getting_started.html#setting-up-danger-to-run-on-your-ci"
end
def note_about_clicking_links
modifier_key = "ctrl"
clicks = "clicking"
modifier_key = "cmd ( ⌘ )" if darwin?
clicks = "double clicking" if darwin? && !ENV["ITERM_SESSION_ID"]
ui.say "Note: Holding #{modifier_key} and #{clicks} a link will open it in your browser."
end
def info
ui.header "Useful info"
ui.say "- One of the best ways to test out new rules locally is via #{'bundle exec danger pr'.yellow}."
ui.pause 0.6
ui.say "- You can have Danger output all of her variables to the console via the #{'--verbose'.yellow} option."
ui.pause 0.6
ui.say "- You can look at the following Dangerfiles to get some more ideas:"
ui.pause 0.6
ui.link "https://github.com/danger/danger/blob/master/Dangerfile"
ui.link "https://github.com/artsy/eigen/blob/master/dangerfile.ts"
ui.pause 1
end
def thanks
ui.say "\n\n🎉"
ui.pause 0.6
ui.say "And you're good to go. Danger is a collaboration between Orta Therox, Gem 'Danger' McShane and Felix Krause."
ui.say "If you like Danger, let others know. If you want to know more, follow #{'@orta'.yellow} and #{'@KrauseFx'.yellow} on Twitter."
ui.say "If you don't like Danger, help us improve the project! xxx"
end
def darwin?
Gem::Platform.local.os == "darwin"
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/dangerfile/init.rb | lib/danger/commands/dangerfile/init.rb | # frozen_string_literal: true
require "danger/danger_core/dangerfile_generator"
# Mainly so we can have a nice structure for commands
module Danger
class DangerfileCommand < Runner
self.summary = "Easily create your Dangerfiles."
self.command = "dangerfile"
self.abstract_command = true
def self.options
[]
end
end
end
# Just a less verbose way of doing the Dangerfile from `danger init`.
module Danger
class DangerfileInit < DangerfileCommand
self.summary = "Create an example Dangerfile."
self.command = "init"
def run
content = DangerfileGenerator.create_dangerfile(".", cork)
File.write("Dangerfile", content)
cork.puts "Created#{'./Dangerfile'.green}"
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/dangerfile/gem.rb | lib/danger/commands/dangerfile/gem.rb | # frozen_string_literal: true
require "claide_plugin"
require "danger/commands/dangerfile/init"
module Danger
class DangerfileGem < DangerfileCommand
self.summary = "Create a gem-based Dangerfile quickly."
def self.description
<<-DESC
Creates a scaffold for the development of a new gem based Dangerfile
named `NAME` according to the best practices.
DESC
end
self.command = "gem"
self.arguments = [
CLAide::Argument.new("NAME", true)
]
def initialize(argv)
@name = argv.shift_argument
prefix = "dangerfile-"
unless @name.nil? || @name.empty? || @name.start_with?(prefix)
@name = prefix + @name.dup
end
@template_url = argv.shift_argument
super
end
def validate!
super
if @name.nil? || @name.empty?
help! "A name for the plugin is required."
end
help! "The plugin name cannot contain spaces." if @name =~ /\s/
end
def run
runner = CLAide::TemplateRunner.new(@name, "https://github.com/danger/dangerfile-gem-template")
runner.clone_template
runner.configure_template
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/init_helpers/interviewer.rb | lib/danger/commands/init_helpers/interviewer.rb | # frozen_string_literal: true
module Danger
class Interviewer
attr_accessor :no_delay, :no_waiting, :ui
def initialize(cork_board)
@ui = cork_board
end
def show_prompt
ui.print "> ".bold.green
end
def yellow_bang
"! ".yellow
end
def green_bang
"! ".green
end
def red_bang
"! ".red
end
def say(output)
ui.puts output
end
def header(title)
say title.yellow
say ""
pause 0.6
end
def link(url)
say " -> #{url.underlined}\n"
end
def pause(time)
sleep(time) unless @no_waiting
end
def wait_for_return
STDOUT.flush
STDIN.gets unless @no_delay
ui.puts
end
def run_command(command, output_command = nil)
output_command ||= command
ui.puts " #{output_command.magenta}"
system command
end
def ask_with_answers(question, possible_answers)
ui.print "\n#{question}? ["
print_info = proc do
possible_answers.each_with_index do |answer, i|
the_answer = i.zero? ? answer.underlined : answer
ui.print " #{the_answer}"
ui.print(" /") if i != possible_answers.length - 1
end
ui.print " ]\n"
end
print_info.call
answer = ""
loop do
show_prompt
answer = @no_waiting ? possible_answers[0].downcase : STDIN.gets.downcase.chomp
answer = "yes" if answer == "y"
answer = "no" if answer == "n"
# default to first answer
if answer == ""
answer = possible_answers[0].downcase
ui.puts "Using: #{answer.yellow}"
end
break if possible_answers.map(&:downcase).include? answer
ui.print "\nPossible answers are ["
print_info.call
end
answer
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/plugins/plugin_json.rb | lib/danger/commands/plugins/plugin_json.rb | # frozen_string_literal: true
require "danger/plugin_support/plugin_parser"
require "danger/plugin_support/plugin_file_resolver"
module Danger
class PluginJSON < CLAide::Command::Plugins
self.summary = "Lint plugins from files, gems or the current folder. Outputs JSON array representation of Plugins on success."
self.command = "json"
attr_accessor :cork
def initialize(argv)
@refs = argv.arguments! unless argv.arguments.empty?
@cork = Cork::Board.new(silent: argv.option("silent", false),
verbose: argv.option("verbose", false))
super
end
self.description = <<-DESC
Converts a collection of file paths of Danger plugins into a JSON format.
DESC
self.arguments = [
CLAide::Argument.new("Paths, Gems or Nothing", false, true)
]
def run
file_resolver = PluginFileResolver.new(@refs)
data = file_resolver.resolve
parser = PluginParser.new(data[:paths])
parser.parse
json = parser.to_json
# Append gem metadata into every plugin
data[:gems].each do |gem_data|
json.each do |plugin|
plugin[:gem_metadata] = gem_data if plugin[:gem] == gem_data[:gem]
end
end
cork.puts json.to_json
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/plugins/plugin_lint.rb | lib/danger/commands/plugins/plugin_lint.rb | # frozen_string_literal: true
require "danger/plugin_support/plugin_parser"
require "danger/plugin_support/plugin_file_resolver"
require "danger/plugin_support/plugin_linter"
module Danger
class PluginLint < CLAide::Command::Plugins
self.summary = "Lints a plugin"
self.command = "lint"
attr_accessor :cork
def initialize(argv)
@warnings_as_errors = argv.flag?("warnings-as-errors", false)
@refs = argv.arguments! unless argv.arguments.empty?
@cork = Cork::Board.new(silent: argv.option("silent", false),
verbose: argv.option("verbose", false))
super
end
self.description = <<-DESC
Converts a collection of file paths of Danger plugins into a JSON format.
Note: Before 1.0, it will also parse the represented JSON to validate whether https://danger.systems would
show the plugin on the website.
DESC
self.arguments = [
CLAide::Argument.new("Paths, Gems or Nothing", false, true)
]
def self.options
[
["--warnings-as-errors", "Ensure strict linting."]
].concat(super)
end
def run
file_resolver = PluginFileResolver.new(@refs)
data = file_resolver.resolve
parser = PluginParser.new(data[:paths], verbose: true)
parser.parse
json = parser.to_json
linter = PluginLinter.new(json)
linter.lint
linter.print_summary(cork)
abort("Failing due to errors\n".red) if linter.failed?
abort("Failing due to warnings as errors\n".red) if @warnings_as_errors && !linter.warnings.empty?
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/plugins/plugin_readme.rb | lib/danger/commands/plugins/plugin_readme.rb | # frozen_string_literal: true
require "danger/plugin_support/plugin_parser"
require "danger/plugin_support/plugin_file_resolver"
require "json"
require "erb"
module Danger
class PluginReadme < CLAide::Command::Plugins
self.summary = "Generates a README from a set of plugins"
self.command = "readme"
attr_accessor :cork, :json, :markdown
def initialize(argv)
@refs = argv.arguments! unless argv.arguments.empty?
@cork = Cork::Board.new(silent: argv.option("silent", false),
verbose: argv.option("verbose", false))
super
end
self.description = <<-DESC
Converts a collection of file paths of Danger plugins into a format usable in a README.
This is useful for Danger itself, but also for any plugins wanting to showcase their API.
DESC
self.arguments = [
CLAide::Argument.new("Paths, Gems or Nothing", false, true)
]
def run
file_resolver = PluginFileResolver.new(@refs)
data = file_resolver.resolve
parser = PluginParser.new(data[:paths])
parser.parse
self.json = JSON.parse(parser.to_json_string)
template = File.join(Danger.gem_path, "lib/danger/plugin_support/templates/readme_table.html.erb")
cork.puts ERB.new(File.read(template), trim_mode: "-").result(binding)
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/local_helpers/local_setup.rb | lib/danger/commands/local_helpers/local_setup.rb | # frozen_string_literal: true
module Danger
class LocalSetup
attr_reader :dm, :cork
def initialize(dangerfile, cork)
@dm = dangerfile
@cork = cork
end
def setup(verbose: false)
source = dm.env.ci_source
if source.nil? or source.repo_slug.empty?
cork.puts "danger local failed because it only works with GitHub and Bitbucket server projects at the moment. Sorry.".red
exit 0
end
gh = dm.env.request_source
# We can use tokenless here, as it's running on someone's computer
# and is IP locked, as opposed to on the CI. Only for Github PRs
if gh.instance_of? Danger::RequestSources::GitHub
gh.support_tokenless_auth = true
end
if gh.instance_of? Danger::RequestSources::BitbucketServer
cork.puts "Running your Dangerfile against this PR - #{gh.host}/projects/#{source.repo_slug.split('/').first}/repos/#{source.repo_slug.split('/').last}/pull-requests/#{source.pull_request_id}"
elsif gh.instance_of? Danger::RequestSources::VSTS
cork.puts "Running your Dangerfile against this PR - #{gh.client.pr_api_endpoint}"
else
cork.puts "Running your Dangerfile against this PR - https://#{gh.host}/#{source.repo_slug}/pull/#{source.pull_request_id}"
end
dm.verbose = verbose
cork.puts
begin
gh.fetch_details
rescue Octokit::NotFound
cork.puts "Local repository was not found on GitHub. If you're trying to test a private repository please provide a valid API token through #{'DANGER_GITHUB_API_TOKEN'.yellow} environment variable."
return
end
yield
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/local_helpers/http_cache.rb | lib/danger/commands/local_helpers/http_cache.rb | # frozen_string_literal: true
require "pstore"
module Danger
class HTTPCache
attr_reader :expires_in
def initialize(cache_file = nil, options = {})
File.delete(cache_file) if options[:clear_cache]
@store = PStore.new(cache_file)
@expires_in = options[:expires_in] || 300 # 5 minutes
end
def read(key)
@store.transaction do
entry = @store[key]
return nil unless entry
return entry[:value] unless entry_has_expired(entry, @expires_in)
@store.delete key
return nil
end
end
def delete(key)
@store.transaction { @store.delete key }
end
def write(key, value)
@store.transaction do
@store[key] = { updated_at: Time.now.to_i, value: value }
end
end
def entry_has_expired(entry, ttl)
Time.now.to_i > entry[:updated_at].to_i + ttl.to_i
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/commands/local_helpers/pry_setup.rb | lib/danger/commands/local_helpers/pry_setup.rb | # frozen_string_literal: true
module Danger
class PrySetup
def initialize(cork)
@cork = cork
end
def setup_pry(dangerfile_path, command)
return dangerfile_path if dangerfile_path.empty?
validate_pry_available(command)
FileUtils.cp dangerfile_path, DANGERFILE_COPY
File.open(DANGERFILE_COPY, "a") do |f|
f.write("\nbinding.pry; File.delete(\"#{DANGERFILE_COPY}\")")
end
DANGERFILE_COPY
end
private
attr_reader :cork
DANGERFILE_COPY = "_Dangerfile.tmp"
def validate_pry_available(command)
Kernel.require "pry"
rescue LoadError
cork.warn "Pry was not found, and is required for 'danger #{command} --pry'."
cork.print_warnings
abort
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/core_ext/string.rb | lib/danger/core_ext/string.rb | # frozen_string_literal: true
class String
# @return [String] the plural form of self determined by count
def danger_pluralize(count)
"#{count} #{self}#{'s' unless count == 1}"
end
# @return [String] converts to underscored, lowercase form
def danger_underscore
self.gsub(/::/, "/").
gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
gsub(/([a-z\d])([A-Z])/, '\1_\2').
tr("-", "_").
downcase
end
# @return [String] truncates string with ellipsis when exceeding the limit
def danger_truncate(limit)
length > limit ? "#{self[0...limit]}..." : self
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/core_ext/file_list.rb | lib/danger/core_ext/file_list.rb | # frozen_string_literal: true
require "danger/helpers/array_subclass"
module Danger
class FileList
include Helpers::ArraySubclass
# Information about pattern: http://ruby-doc.org/core-2.2.0/File.html#method-c-fnmatch
# e.g. "**/something.*" for any file called something with any extension
def include?(pattern)
self.each do |current|
if !current.nil? && (File.fnmatch(pattern, current, File::FNM_EXTGLOB) || pattern == current)
return true
end
end
return false
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/plugin_support/plugin_file_resolver.rb | lib/danger/plugin_support/plugin_file_resolver.rb | # frozen_string_literal: true
require "danger/plugin_support/gems_resolver"
module Danger
class PluginFileResolver
# Takes an array of files, gems or nothing, then resolves them into
# paths that should be sent into the documentation parser
def initialize(references)
@refs = references
end
# When given existing paths, map to absolute & existing paths
# When given a list of gems, resolve for list of gems
# When empty, imply you want to test the current lib folder as a plugin
def resolve
if !refs.nil? and refs.select { |ref| File.file? ref }.any?
paths = refs.select { |ref| File.file? ref }.map { |path| File.expand_path(path) }
elsif refs.kind_of? Array
paths, gems = GemsResolver.new(refs).call
else
paths = Dir.glob(File.join(".", "lib/**/*.rb")).map { |path| File.expand_path(path) }
end
{ paths: paths, gems: gems || [] }
end
private
attr_reader :refs
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/plugin_support/plugin_linter.rb | lib/danger/plugin_support/plugin_linter.rb | # frozen_string_literal: true
module Danger
class PluginLinter
# An internal class that is used to represent a rule for the linter.
class Rule
attr_accessor :modifier, :description, :title, :function, :ref, :metadata, :type
def initialize(modifier, ref, title, description, function)
@modifier = modifier
@title = title
@description = description
@function = function
@ref = ref
end
def object_applied_to
"#{metadata[:name].to_s.bold} (#{type})"
end
end
attr_accessor :json, :warnings, :errors
def initialize(json)
@json = json
@warnings = []
@errors = []
end
# Lints the current JSON, looking at:
# * Class rules
# * Method rules
# * Attribute rules
#
def lint
json.each do |plugin|
apply_rules(plugin, "class", class_rules)
plugin[:methods].each do |method|
apply_rules(method, "method", method_rules)
end
plugin[:attributes].each do |method_hash|
method_name = method_hash.keys.first
method = method_hash[method_name]
value = method[:write] || method[:read]
apply_rules(value, "attribute", method_rules)
end
end
end
# Did the linter pass/fail?
#
def failed?
errors.count > 0
end
# Prints a summary of the errors and warnings.
#
def print_summary(ui)
# Print whether it passed/failed at the top
if failed?
ui.puts "\n[!] Failed\n".red
else
ui.notice "Passed"
end
# A generic proc to handle the similarities between
# errors and warnings.
do_rules = proc do |name, rules|
unless rules.empty?
ui.puts ""
ui.section(name.bold) do
rules.each do |rule|
title = rule.title.bold + " - #{rule.object_applied_to}"
subtitles = [rule.description, link(rule.ref)]
subtitles += [rule.metadata[:files].join(":")] if rule.metadata[:files]
ui.labeled(title, subtitles)
ui.puts ""
end
end
end
end
# Run the rules
do_rules.call("Errors".red, errors)
do_rules.call("Warnings".yellow, warnings)
end
private
# Rules that apply to a class
#
def class_rules
[
Rule.new(:error, 4..6, "Description Markdown", "Above your class you need documentation that covers the scope, and the usage of your plugin.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 30, "Tags", "This plugin does not include `@tags tag1, tag2` and thus will be harder to find in search.", proc do |json|
json[:tags] && json[:tags].empty?
end),
Rule.new(:warning, 29, "References", "Ideally, you have a reference implementation of your plugin that you can show to people, add `@see org/repo` to have the site auto link it.", proc do |json|
json[:see] && json[:see].empty?
end),
Rule.new(:error, 8..27, "Examples", "You should include some examples of common use-cases for your plugin.", proc do |json|
json[:example_code] && json[:example_code].empty?
end)
]
end
# Rules that apply to individual methods, and attributes
#
def method_rules
[
Rule.new(:error, 40..41, "Description", "You should include a description for your method.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 43..45, "Params", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets]&.flat_map(&:values)&.include?(nil)
end),
Rule.new(:warning, 43..45, "Unknown Param", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets]&.flat_map(&:values)&.include?("Unknown")
end),
Rule.new(:warning, 46, "Return Type", "If the function has no useful return value, use ` @return [void]` - this will be ignored by documentation generators.", proc do |json|
return_hash = json[:tags].find { |tag| tag[:name] == "return" }
!(return_hash && return_hash[:types] && !return_hash[:types].first.empty?)
end)
]
end
# Generates a link to see an example of said rule
#
def link(ref)
if ref.kind_of?(Range)
"@see - #{"https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref.min}#-L#{ref.max}".blue}"
elsif ref.kind_of?(Integer)
"@see - #{"https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref}".blue}"
else
"@see - #{'https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb'.blue}"
end
end
# Runs the rule, if it fails then additional metadata
# is added to the rule (for printing later) and it's
# added to either `warnings` or `errors`.
#
def apply_rules(json, type, rules)
rules.each do |rule|
next unless rule.function.call(json)
rule.metadata = json
rule.type = type
case rule.modifier
when :warning
warnings << rule
when :error
errors << rule
end
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/plugin_support/plugin.rb | lib/danger/plugin_support/plugin.rb | # frozen_string_literal: true
module Danger
class Plugin
def initialize(dangerfile)
@dangerfile = dangerfile
end
def self.instance_name
to_s.gsub("Danger", "").danger_underscore.split("/").last
end
# Both of these methods exist on all objects
# http://ruby-doc.org/core-2.2.3/Kernel.html#method-i-warn
# http://ruby-doc.org/core-2.2.3/Kernel.html#method-i-fail
# However, as we're using using them in the DSL, they won't
# get method_missing called correctly.
undef :warn, :fail
# Since we have a reference to the Dangerfile containing all the information
# We need to redirect the self calls to the Dangerfile
def method_missing(method_sym, *arguments, **keyword_arguments, &block)
if keyword_arguments.empty?
@dangerfile.send(method_sym, *arguments, &block)
else
@dangerfile.send(method_sym, *arguments, **keyword_arguments, &block)
end
end
def self.all_plugins
@all_plugins ||= []
end
def self.clear_external_plugins
@all_plugins = @all_plugins.select { |plugin| Dangerfile.essential_plugin_classes.include? plugin }
end
def self.inherited(plugin)
Plugin.all_plugins.push(plugin)
end
private
# When using `danger local --pry`, every plugin had an unreasonable
# amount of text output due to the Dangerfile reference in every
# plugin. So, it is filtered out. Users will start out in the context
# of the Dangerfile, and can view it by just typing `self` into the REPL.
#
def pretty_print_instance_variables
super - [:@dangerfile]
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/plugin_support/gems_resolver.rb | lib/danger/plugin_support/gems_resolver.rb | # frozen_string_literal: true
require "bundler"
module Danger
class GemsResolver
def initialize(gem_names)
@gem_names = gem_names
@dir = Dir.mktmpdir # We want it to persist until OS cleans it on reboot
end
# Returns an Array of paths (plugin lib file paths) and gems (of metadata)
def call
path_gems = []
Bundler.with_clean_env do
Dir.chdir(dir) do
create_gemfile_from_gem_names
`bundle install --path vendor/gems`
path_gems = all_gems_metadata
end
end
return path_gems
end
private
attr_reader :gem_names, :dir
def all_gems_metadata
return paths, gems
end
def create_gemfile_from_gem_names
gemfile = File.new("Gemfile", "w")
gemfile.write "source 'https://rubygems.org'"
gem_names.each do |plugin|
gemfile.write "\ngem '#{plugin}'"
end
gemfile.close
end
# The paths are relative to dir.
def paths
relative_paths = gem_names.flat_map do |plugin|
Dir.glob("vendor/gems/ruby/*/gems/#{plugin}*/lib/**/**/**/**.rb")
end
relative_paths.map { |path| File.join(dir, path) }
end
def gems
real_gems.map { |gem| gem_metadata(gem) }
end
def real_gems
spec_paths = gem_names.flat_map do |plugin|
Dir.glob("vendor/gems/ruby/*/specifications/#{plugin}*.gemspec").first
end
spec_paths.map { |path| Gem::Specification.load path }
end
def gem_metadata(gem)
{
name: gem.name,
gem: gem.name,
author: gem.authors,
url: gem.homepage,
description: gem.summary,
license: gem.license || "Unknown",
version: gem.version.to_s
}
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/plugin_support/plugin_parser.rb | lib/danger/plugin_support/plugin_parser.rb | require "json"
=begin
So you want to improve this? Great. Hard thing is getting yourself into a position where you
have access to all the tokens, so here's something you should run in `bundle exec pry` to dig in:
require 'danger'
require 'yard'
parser = Danger::PluginParser.new "spec/fixtures/plugins/example_fully_documented.rb"
parser.parse
plugins = parser.plugins_from_classes(parser.classes_in_file)
git = plugins.first
klass = git
parser.to_dict(plugins)
Then some helpers
attribute_meths = klass.attributes[:instance].values.map(&:values).flatten
methods = klass.meths - klass.inherited_meths - attribute_meths
usable_methods = methods.select { |m| m.visibility == :public }.reject { |m| m.name == :initialize }
the alternative, is to add
require 'pry'
binding.pry
anywhere inside the source code below.
=end
module Danger
class PluginParser
attr_accessor :registry
def initialize(paths, verbose = false)
raise "Path cannot be empty" if paths.empty?
setup_yard(verbose)
if paths.kind_of? String
@paths = [File.expand_path(paths)]
else
@paths = paths
end
end
def setup_yard(verbose)
require 'yard'
# Unless specifically asked, don't output anything.
unless verbose
YARD::Logger.instance.level = YARD::Logger::FATAL
end
# Add some of our custom tags
YARD::Tags::Library.define_tag('tags', :tags)
YARD::Tags::Library.define_tag('availability', :availability)
end
def parse
files = ["lib/danger/plugin_support/plugin.rb"] + @paths
# This turns on YARD debugging
# $DEBUG = true
self.registry = YARD::Registry.load(files, true)
end
def classes_in_file
registry.all(:class).select { |klass| @paths.include? klass.file }
end
def plugins_from_classes(classes)
classes.select { |klass| klass.inheritance_tree.map(&:name).include? :Plugin }
end
def to_json
plugins = plugins_from_classes(classes_in_file)
to_h(plugins)
end
def to_json_string
plugins = plugins_from_classes(classes_in_file)
to_h(plugins).to_json
end
# rubocop:disable Metrics/AbcSize
def method_return_string(meth)
return "" unless meth[:tags]
return_value = meth[:tags].find { |t| t[:name] == "return" && t[:types] }
return "" if return_value.nil?
return "" if return_value[:types].nil?
return "" unless return_value[:types].kind_of? Array
unless return_value.empty?
return "" if return_value[:types].first == "void"
return return_value[:types].first
end
""
end
def method_params(method)
return {} unless method[:params]
params_names = method[:params].map { |param| param.compact.join("=").strip }
params_values = method[:tags].select { |t| t[:name] == "param" }
return {} if params_values.empty?
return {} if params_values.select { |p| p[:types] }.empty?
return params_names.map.with_index do |name, index|
name = name.delete ":"
if index < params_values.length
type = params_values[index][:types]
{ name => type ? type.first : "Unknown" }
else
{ name => "Unknown" }
end
end
end
def method_parser(gem_path, meth)
return nil if meth.nil?
method = {
name: meth.name,
body_md: meth.docstring,
params: meth.parameters,
files: meth.files.map { |item| [item.first.gsub(gem_path, ""), item.last] },
tags: meth.tags.map { |t| { name: t.tag_name, types: t.types } }
}
return_v = method_return_string(method)
params_v = method_params(method)
# Pull out some derived data
method[:param_couplets] = params_v
method[:return] = return_v
# Create the center params, `thing: OK, other: Thing`
string_params = params_v.map do |param|
name = param.keys.first
param[name].nil? ? name : name + ": " + param[name]
end.join ", "
# Wrap it in () if there _are_ params
string_params = "(" + string_params + ")" unless string_params.empty?
# Append the return type if we have one
suffix = return_v.empty? ? "" : " -> #{return_v}"
method[:one_liner] = meth.name.to_s + string_params + suffix
method
end
def attribute_parser(gem_path, attribute)
{
read: method_parser(gem_path, attribute[:read]),
write: method_parser(gem_path, attribute[:write])
}
end
def to_h(classes)
classes.map do |klass|
# Adds the class being parsed into the ruby runtime, so that we can access it's instance_name
require klass.file
real_klass = Danger.const_get klass.name
attribute_meths = klass.attributes[:instance].values.map(&:values).flatten
methods = klass.meths - klass.inherited_meths - attribute_meths
usable_methods = methods.select { |m| m.visibility == :public }.reject { |m| m.name == :initialize || m.name == :instance_name || m.name == :new }
plugin_gem = klass.file.include?("gems") ? klass.file.split("gems/").last.split("-")[0..-2].join("-") : nil
# Pull out the gem's path ( to make relative file paths )
# if no gem is found, index = 0, making gem_path = ""
index_of_gem_in_path = plugin_gem ? klass.file.split("/").index { |component| component.include? plugin_gem } : 0
gem_path = klass.file.split("/")[0..index_of_gem_in_path].join("/")
{
name: klass.name.to_s,
body_md: klass.docstring,
instance_name: real_klass.instance_name,
gem: plugin_gem,
gem_path: gem_path,
files: klass.files.map { |item| [item.first.gsub(gem_path, ""), item.last] },
example_code: klass.tags.select { |t| t.tag_name == "example" }.map { |tag| { title: tag.name, text: tag.text } }.compact,
attributes: klass.attributes[:instance].map { |pair| { pair.first => attribute_parser(gem_path, pair.last) } },
methods: usable_methods.map { |m| method_parser(gem_path, m) },
tags: klass.tags.select { |t| t.tag_name == "tags" }.map(&:text).compact,
see: klass.tags.select { |t| t.tag_name == "see" }.map(&:name).map(&:split).flatten.compact,
}
end
end
# rubocop:enable Metrics/AbcSize
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/travis.rb | lib/danger/ci_source/travis.rb | # frozen_string_literal: true
# http://docs.travis-ci.com/user/osx-ci-environment/
# http://docs.travis-ci.com/user/environment-variables/
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
# You need to edit your `.travis.yml` to include `bundle exec danger`. If you already have
# a `script:` section then we recommend adding this command at the end of the script step: `- bundle exec danger`.
#
# Otherwise, add a `before_script` step to the root of the `.travis.yml` with `bundle exec danger`
#
# ```ruby
# before_script:
# - bundle exec danger
# ```
#
# Adding this to your `.travis.yml` allows Danger to fail your build, both on the TravisCI website and within your Pull Request.
# With that set up, you can edit your job to add `bundle exec danger` at the build action.
#
# _Note:_ Travis CI defaults to using an older version of Ruby, so you may need to add `rvm: 2.0.0` to the root your `.travis.yml`.
#
# ### Token Setup
#
# You need to add the `DANGER_GITHUB_API_TOKEN` environment variable, to do this,
# go to your repo's settings, which should look like: `https://travis-ci.org/[user]/[repo]/settings`.
#
# If you have an open source project, you should ensure "Display value in build log" enabled, so that PRs from forks work.
#
class Travis < CI
def self.validates_as_ci?(env)
env.key? "HAS_JOSH_K_SEAL_OF_APPROVAL"
end
def self.validates_as_pr?(env)
exists = ["TRAVIS_PULL_REQUEST", "TRAVIS_REPO_SLUG"].all? { |x| env[x] && !env[x].empty? }
exists && env["TRAVIS_PULL_REQUEST"].to_i > 0
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def initialize(env)
self.repo_slug = env["TRAVIS_REPO_SLUG"]
if env["TRAVIS_PULL_REQUEST"].to_i > 0
self.pull_request_id = env["TRAVIS_PULL_REQUEST"]
end
self.repo_url = GitRepo.new.origins # Travis doesn't provide a repo url env variable :/
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/bamboo.rb | lib/danger/ci_source/bamboo.rb | # frozen_string_literal: true
require "set"
module Danger
# ### CI Setup
#
# Add a Run Script task that executes `danger` (or `bundle exec danger` if you're using Bundler
# to manage your gems) as your as part of your Bamboo plan.
# The minimum supported version is Bamboo 6.9.
#
# ### Token Setup
#
# IMPORTANT: All required Bamboo environment variables will be available
# only if the plan is run as part of a pull request. This can be achieved by selecting:
# Configure plan -> Branches -> Create plan branch: "When pull request is created".
# Otherwise, `bamboo_repository_pr_key` and `bamboo_planRepository_repositoryUrl`
# will not be available.
#
class Bamboo < CI
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::BitbucketServer
]
end
def self.validates_as_ci?(env)
env.key? "bamboo_buildKey"
end
def self.validates_as_pr?(env)
exists = ["bamboo_repository_pr_key", "bamboo_planRepository_repositoryUrl"].all? { |x| env[x] && !env[x].empty? }
exists && env["bamboo_repository_pr_key"].to_i > 0
end
def initialize(env)
self.repo_url = env["bamboo_planRepository_repositoryUrl"]
self.pull_request_id = env["bamboo_repository_pr_key"]
repo_matches = self.repo_url.match(%r{([/:])([^/]+/[^/]+?)(\.git$|$)})
self.repo_slug = repo_matches[2] unless repo_matches.nil?
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/semaphore.rb | lib/danger/ci_source/semaphore.rb | # frozen_string_literal: true
# https://docs.semaphoreci.com/article/12-environment-variables
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# For Semaphore you will want to go to the settings page of the project. Inside "Build Settings"
# you should add `bundle exec danger` to the Setup thread. Note that Semaphore only provides
# the build environment variables necessary for Danger on PRs across forks.
#
# ### Token Setup
#
# You can add your `DANGER_GITHUB_API_TOKEN` inside the "Environment Variables" section in the settings.
#
class Semaphore < CI
def self.validates_as_ci?(env)
env.key? "SEMAPHORE"
end
def self.validates_as_pr?(env)
one = ["SEMAPHORE_REPO_SLUG", "PULL_REQUEST_NUMBER"].all? { |x| env[x] && !env[x].empty? }
two = ["SEMAPHORE_GIT_REPO_SLUG", "SEMAPHORE_GIT_PR_NUMBER"].all? { |x| env[x] && !env[x].empty? }
one || two
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def initialize(env)
self.repo_slug = env["SEMAPHORE_GIT_REPO_SLUG"] || env["SEMAPHORE_REPO_SLUG"]
self.pull_request_id = env["SEMAPHORE_GIT_PR_NUMBER"] || env["PULL_REQUEST_NUMBER"]
self.repo_url = env["SEMAPHORE_GIT_URL"] || GitRepo.new.origins
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/jenkins.rb | lib/danger/ci_source/jenkins.rb | # frozen_string_literal: true
# https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project#Buildingasoftwareproject-JenkinsSetEnvironmentVariables
# https://wiki.jenkins-ci.org/display/JENKINS/GitHub+pull+request+builder+plugin
require "danger/request_sources/github/github"
require "danger/request_sources/gitlab"
require "danger/request_sources/bitbucket_server"
require "danger/request_sources/bitbucket_cloud"
module Danger
# https://jenkins-ci.org
# ### CI Setup
# Ah Jenkins, so many memories. So, if you're using Jenkins, you're hosting your own environment.
#
# #### GitHub
# You will want to be using the [GitHub pull request builder plugin](https://wiki.jenkins-ci.org/display/JENKINS/GitHub+pull+request+builder+plugin)
# in order to ensure that you have the build environment set up for PR integration.
#
# With that set up, you can edit your job to add `bundle exec danger` at the build action.
#
# ##### Pipeline
# If your're using [pipelines](https://jenkins.io/solutions/pipeline/) you should be using the [GitHub branch source plugin](https://wiki.jenkins-ci.org/display/JENKINS/GitHub+Branch+Source+Plugin)
# for easy setup and handling of PRs.
#
# After you've set up the plugin, add a `sh 'bundle exec danger'` line in your pipeline script and make sure that build PRs is enabled.
#
# #### GitLab
# You will want to be using the [GitLab Plugin](https://github.com/jenkinsci/gitlab-plugin)
# in order to ensure that you have the build environment set up for MR integration.
#
# With that set up, you can edit your job to add `bundle exec danger` at the build action.
#
# #### General
#
# People occasionally see issues with Danger not classing your CI runs as a PR, to give you visibility
# the Jenkins side of Danger expects to see one of these env vars:
# - ghprbPullId
# - CHANGE_ID
# - gitlabMergeRequestIid
# - gitlabMergeRequestId
#
# ### Token Setup
#
# #### GitHub
# As you own the machine, it's up to you to add the environment variable for the `DANGER_GITHUB_API_TOKEN`.
#
# #### GitLab
# As you own the machine, it's up to you to add the environment variable for the `DANGER_GITLAB_API_TOKEN`.
#
class Jenkins < CI
attr_accessor :project_url
class EnvNotFound < StandardError
def initialize
super("ENV not found, please check your Jenkins. Related: https://stackoverflow.com/search?q=jenkins+env+null")
end
end
def self.validates_as_ci?(env)
env.key? "JENKINS_URL"
end
def self.validates_as_pr?(env)
id = pull_request_id(env)
!id.nil? && !id.empty? && !!id.match(/^\d+$/)
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::GitLab,
Danger::RequestSources::BitbucketServer,
Danger::RequestSources::BitbucketCloud
]
end
def initialize(env)
raise EnvNotFound.new if env.nil? || env.empty?
self.repo_url = self.class.repo_url(env)
self.pull_request_id = self.class.pull_request_id(env)
self.repo_slug = self.class.repo_slug(self.repo_url)
self.project_url = env["CI_MERGE_REQUEST_PROJECT_URL"] || env["CI_PROJECT_URL"]
end
def self.repo_slug(repo_url)
slug = self.slug_ssh(repo_url)
slug ||= self.slug_http(repo_url)
slug ||= self.slug_bitbucket(repo_url)
slug ||= self.slug_fallback(repo_url)
return slug.gsub(/\.git$/, "") unless slug.nil?
end
def self.slug_bitbucket(repo_url)
repo_matches = repo_url.match(%r{(?:[/:])projects/([^/.]+)/repos/([^/.]+)})
return "#{repo_matches[1]}/#{repo_matches[2]}" if repo_matches
end
def self.slug_ssh(repo_url)
repo_matches = repo_url.match(/^git@.+:(.+)/)
return repo_matches[1] if repo_matches
end
def self.slug_http(repo_url)
repo_matches = repo_url.match(%r{^https?.+(?>\.\w*\d*/)(.+.git$)})
return repo_matches[1] if repo_matches
end
def self.slug_fallback(repo_url)
repo_matches = repo_url.match(%r{([/:])([^/]+/[^/]+)$})
return repo_matches[2]
end
def self.pull_request_id(env)
if env["ghprbPullId"]
env["ghprbPullId"]
elsif env["CHANGE_ID"]
env["CHANGE_ID"]
elsif env["gitlabMergeRequestIid"]
env["gitlabMergeRequestIid"]
else
env["gitlabMergeRequestId"]
end
end
def self.repo_url(env)
if env["GIT_URL_1"]
env["GIT_URL_1"]
elsif env["CHANGE_URL"]
change_url = env["CHANGE_URL"]
case change_url
when %r{/pull/} # GitHub
matches = change_url.match(%r{(.+)/pull/[0-9]+})
matches[1] unless matches.nil?
when %r{/merge_requests/} # GitLab
matches = change_url.match(%r{(.+?)(/-)?/merge_requests/[0-9]+})
matches[1] unless matches.nil?
when %r{/pull-requests/} # Bitbucket
matches = change_url.match(%r{(.+)/pull-requests/[0-9]+})
matches[1] unless matches.nil?
else
change_url
end
else
env["GIT_URL"]
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/drone.rb | lib/danger/ci_source/drone.rb | # frozen_string_literal: true
# http://readme.drone.io/usage/variables/
require "danger/request_sources/github/github"
require "danger/request_sources/gitlab"
module Danger
# ### CI Setup
#
# With Drone you run the docker images yourself, so you will want to add `bundle exec danger` at the end of
# your `.drone.yml`.
#
# ```shell
# build:
# image: golang
# commands:
# - ...
# - bundle exec danger
# ```
#
# ### Token Setup
#
# As this is self-hosted, you will need to expose the `DANGER_GITHUB_API_TOKEN` as a secret to your
# builds:
#
# Drone secrets: http://readme.drone.io/usage/secret-guide/
# NOTE: This is a new syntax in DroneCI 0.6+
#
# ```yml
# build:
# image: golang
# secrets:
# - DANGER_GITHUB_API_TOKEN
# commands:
# - ...
# - bundle exec danger
# ```
class Drone < CI
def self.validates_as_ci?(env)
validates_as_ci_post_06?(env) or validates_as_ci_pre_06?(env)
end
def self.validates_as_pr?(env)
env["DRONE_PULL_REQUEST"].to_i > 0
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub, Danger::RequestSources::GitLab]
end
def initialize(env)
if self.class.validates_as_ci_post_06?(env)
self.repo_slug = "#{env['DRONE_REPO_OWNER']}/#{env['DRONE_REPO_NAME']}"
self.repo_url = env["DRONE_REPO_LINK"] if self.class.validates_as_ci_post_06?(env)
elsif self.class.validates_as_ci_pre_06?(env)
self.repo_slug = env["DRONE_REPO"]
self.repo_url = GitRepo.new.origins
end
self.pull_request_id = env["DRONE_PULL_REQUEST"]
end
# Check if this build is valid for CI with drone 0.6 or later
def self.validates_as_ci_post_06?(env)
env.key? "DRONE_REPO_OWNER" and env.key? "DRONE_REPO_NAME"
end
# Checks if this build is valid for CI with drone 0.5 or earlier
def self.validates_as_ci_pre_06?(env)
env.key? "DRONE_REPO"
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/codeship.rb | lib/danger/ci_source/codeship.rb | # frozen_string_literal: true
# https://semaphoreci.com/docs/available-environment-variables.html
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# In Codeship, go to your "Project Settings", then add `bundle exec danger` as a test step inside
# one of your pipelines.
#
# ### Token Setup
#
# Add your `DANGER_GITHUB_API_TOKEN` to "Environment" section in "Project Settings".
#
class Codeship < CI
def self.validates_as_ci?(env)
env["CI_NAME"] == "codeship"
end
def self.validates_as_pr?(env)
return false unless env["CI_BRANCH"] && !env["CI_BRANCH"].empty?
!pr_from_env(env).nil?
end
def self.owner_for_github(env)
env["CI_REPO_NAME"].split("/").first
end
# this is fairly hacky, see https://github.com/danger/danger/pull/892#issuecomment-329030616 for why
def self.pr_from_env(env)
Danger::RequestSources::GitHub.new(nil, env).get_pr_from_branch(env["CI_REPO_NAME"], env["CI_BRANCH"], owner_for_github(env))
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def initialize(env)
self.repo_slug = env["CI_REPO_NAME"]
self.pull_request_id = self.class.pr_from_env(env)
self.repo_url = GitRepo.new.origins
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/concourse.rb | lib/danger/ci_source/concourse.rb | # frozen_string_literal: true
require "git"
require "danger/request_sources/local_only"
module Danger
# Concourse CI Integration
#
# https://concourse-ci.org/
#
# ### CI Setup
#
# With Concourse, you run the docker images yourself, so you will want to add `yarn danger ci` within one of your build jobs.
#
# ```shell
# build:
# image: golang
# commands:
# - ...
# - yarn danger ci
# ```
#
# ### Environment Variable Setup
#
# As this is self-hosted, you will need to add the `CONCOURSE` environment variable `export CONCOURSE=true` to your build environment,
# as well as setting environment variables for `PULL_REQUEST_ID` and `REPO_SLUG`. Assuming you are using the github pull request resource
# https://github.com/jtarchie/github-pullrequest-resource the id of the PR can be accessed from `git config --get pullrequest.id`.
#
# ### Token Setup
#
# Once again as this is self-hosted, you will need to add `DANGER_GITHUB_API_TOKEN` environment variable to the build environment.
# The suggested method of storing the token is within the vault - https://concourse-ci.org/creds.html
class Concourse < CI
def self.validates_as_ci?(env)
env.key? "CONCOURSE"
end
def self.validates_as_pr?(env)
exists = ["PULL_REQUEST_ID", "REPO_SLUG"].all? { |x| env[x] && !env[x].empty? }
exists && env["PULL_REQUEST_ID"].to_i > 0
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::GitLab,
Danger::RequestSources::BitbucketServer,
Danger::RequestSources::BitbucketCloud
]
end
def initialize(env)
self.repo_slug = env["REPO_SLUG"]
if env["PULL_REQUEST_ID"].to_i > 0
self.pull_request_id = env["PULL_REQUEST_ID"]
end
self.repo_url = GitRepo.new.origins
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/buddybuild.rb | lib/danger/ci_source/buddybuild.rb | # frozen_string_literal: true
module Danger
# ### CI Setup
#
# Read how you can setup Danger on the buddybuild blog:
# https://www.buddybuild.com/blog/using-danger-with-buddybuild/
#
# ### Token Setup
#
# Login to buddybuild and select your app. Go to your *App Settings* and
# in the *Build Settings* menu on the left, choose *Environment Variables*.
# http://docs.buddybuild.com/docs/environment-variables
#
# #### GitHub
# Add the `DANGER_GITHUB_API_TOKEN` to your build user's ENV.
#
# #### GitLab
# Add the `DANGER_GITLAB_API_TOKEN` to your build user's ENV.
#
# #### Bitbucket Cloud
# Add the `DANGER_BITBUCKETSERVER_USERNAME`, `DANGER_BITBUCKETSERVER_PASSWORD`
# to your build user's ENV.
#
# #### Bitbucket server
# Add the `DANGER_BITBUCKETSERVER_USERNAME`, `DANGER_BITBUCKETSERVER_PASSWORD`
# and `DANGER_BITBUCKETSERVER_HOST` to your build user's ENV.
#
# ### Running Danger
#
# Once the environment variables are all available, create a custom build step
# to run Danger as part of your build process:
# http://docs.buddybuild.com/docs/custom-prebuild-and-postbuild-steps
class Buddybuild < CI
#######################################################################
def self.validates_as_ci?(env)
value = env["BUDDYBUILD_BUILD_ID"]
return !value.nil? && !env["BUDDYBUILD_BUILD_ID"].empty?
end
#######################################################################
def self.validates_as_pr?(env)
value = env["BUDDYBUILD_PULL_REQUEST"]
return !value.nil? && !env["BUDDYBUILD_PULL_REQUEST"].empty?
end
#######################################################################
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::GitLab,
Danger::RequestSources::BitbucketServer,
Danger::RequestSources::BitbucketCloud
]
end
#######################################################################
def initialize(env)
self.repo_slug = env["BUDDYBUILD_REPO_SLUG"]
self.pull_request_id = env["BUDDYBUILD_PULL_REQUEST"]
self.repo_url = GitRepo.new.origins # Buddybuild doesn't provide a repo url env variable for now
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/github_actions.rb | lib/danger/ci_source/github_actions.rb | # frozen_string_literal: true
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# You can use `danger/danger` Action in your `.github/workflows/xxx.yml`.
# And so, you can use GITHUB_TOKEN secret as `DANGER_GITHUB_API_TOKEN` environment variable.
#
# ```yml
# ...
# steps:
# - uses: actions/checkout@v3
# - uses: danger/danger@master
# env:
# DANGER_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# ```
#
class GitHubActions < CI
def self.validates_as_ci?(env)
env.key? "GITHUB_ACTION"
end
def self.validates_as_pr?(env)
value = env["GITHUB_EVENT_NAME"]
["pull_request", "pull_request_target"].include?(value)
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def initialize(env)
self.repo_slug = env["GITHUB_REPOSITORY"]
pull_request_event = JSON.parse(File.read(env["GITHUB_EVENT_PATH"]))
self.pull_request_id = pull_request_event["number"]
self.repo_url = pull_request_event["repository"]["clone_url"]
# if environment variable DANGER_GITHUB_API_TOKEN is not set, use env GITHUB_TOKEN
if (env.key? "GITHUB_ACTION") && (!env.key? "DANGER_GITHUB_API_TOKEN")
env["DANGER_GITHUB_API_TOKEN"] = env["GITHUB_TOKEN"]
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/azure_pipelines.rb | lib/danger/ci_source/azure_pipelines.rb | # frozen_string_literal: true
# https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables
require "uri"
require "danger/request_sources/github/github"
require "danger/request_sources/vsts"
module Danger
# ### CI Setup
#
# Add a script step:
#
# ```shell
# #!/usr/bin/env bash
# bundle install
# bundle exec danger
# ```
#
# ### Token Setup
#
# #### GitHub
#
# You need to add the `DANGER_GITHUB_API_TOKEN` environment variable, to do this, go to your build definition's variables tab.
#
# #### Azure Git
#
# You need to add the `DANGER_VSTS_API_TOKEN` and `DANGER_VSTS_HOST` environment variable, to do this,
# go to your build definition's variables tab. The `DANGER_VSTS_API_TOKEN` is your vsts personal access token.
# Instructions for creating a personal access token can be found [here](https://www.visualstudio.com/en-us/docs/setup-admin/team-services/use-personal-access-tokens-to-authenticate).
# For the `DANGER_VSTS_HOST` variable the suggested value is `$(System.TeamFoundationCollectionUri)$(System.TeamProject)`
# which will automatically get your vsts domain and your project name needed for the vsts api.
#
class AzurePipelines < CI
def self.validates_as_ci?(env)
has_all_variables = ["AGENT_ID", "BUILD_SOURCEBRANCH", "BUILD_REPOSITORY_URI", "BUILD_REASON", "BUILD_REPOSITORY_NAME"].all? { |x| env[x] && !env[x].empty? }
# AGENT_ID is being used by AppCenter as well, so checking here to make sure AppCenter CI doesn't get a false positive for AzurePipelines
# Anyone working with AzurePipelines could provide a better/truly unique env key to avoid checking for AppCenter
!Danger::Appcenter.validates_as_ci?(env) &&
has_all_variables
end
def self.validates_as_pr?(env)
return env["BUILD_REASON"] == "PullRequest"
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::GitLab,
Danger::RequestSources::BitbucketServer,
Danger::RequestSources::BitbucketCloud,
Danger::RequestSources::VSTS
]
end
def initialize(env)
self.pull_request_id = env["SYSTEM_PULLREQUEST_PULLREQUESTNUMBER"] || env["SYSTEM_PULLREQUEST_PULLREQUESTID"]
self.repo_url = env["BUILD_REPOSITORY_URI"]
self.repo_slug = env["BUILD_REPOSITORY_NAME"]
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/buildkite.rb | lib/danger/ci_source/buildkite.rb | # frozen_string_literal: true
# https://buildkite.com/docs/agent/osx
# https://buildkite.com/docs/guides/environment-variables
require "danger/request_sources/github/github"
require "danger/request_sources/gitlab"
module Danger
# ### CI Setup
#
# With BuildKite you run the server yourself, so you will want to run it as a part of your build process.
# It is common to have build steps, so we would recommend adding this to your script:
#
# ```shell
# echo "--- Running Danger"
# bundle exec danger
# ```
#
# ### Token Setup
#
# #### GitHub
#
# As this is self-hosted, you will need to add the `DANGER_GITHUB_API_TOKEN` to your build user's ENV. The alternative
# is to pass in the token as a prefix to the command `DANGER_GITHUB_API_TOKEN="123" bundle exec danger`.
#
# #### GitLab
#
# As this is self-hosted, you will need to add the `DANGER_GITLAB_API_TOKEN` to your build user's ENV. The alternative
# is to pass in the token as a prefix to the command `DANGER_GITLAB_API_TOKEN="123" bundle exec danger`.
#
class Buildkite < CI
def self.validates_as_ci?(env)
env.key? "BUILDKITE"
end
def self.validates_as_pr?(env)
exists = ["BUILDKITE_PULL_REQUEST_REPO", "BUILDKITE_PULL_REQUEST"].all? { |x| env[x] }
exists && !env["BUILDKITE_PULL_REQUEST_REPO"].empty?
end
def initialize(env)
self.repo_url = env["BUILDKITE_REPO"]
self.pull_request_id = env["BUILDKITE_PULL_REQUEST"]
repo_matches = self.repo_url.match(%r{([/:])([^/]+/[^/]+?)(\.git$|$)})
self.repo_slug = repo_matches[2] unless repo_matches.nil?
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub, Danger::RequestSources::GitLab, Danger::RequestSources::BitbucketServer]
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/code_build.rb | lib/danger/ci_source/code_build.rb | # frozen_string_literal: true
# https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# In CodeBuild, make sure to correctly forward `CODEBUILD_BUILD_ID`, `CODEBUILD_SOURCE_VERSION`, `CODEBUILD_SOURCE_REPO_URL` and `DANGER_GITHUB_API_TOKEN`.
# In CodeBuild with batch builds, make sure to correctly forward `CODEBUILD_BUILD_ID`, `CODEBUILD_WEBHOOK_TRIGGER`, `CODEBUILD_SOURCE_REPO_URL`, `CODEBUILD_BATCH_BUILD_IDENTIFIER` and `DANGER_GITHUB_API_TOKEN`.
#
# ### Token Setup
#
# Add your `DANGER_GITHUB_API_TOKEN` to your project. Edit -> Environment -> Additional configuration -> Create a parameter
#
class CodeBuild < CI
def self.validates_as_ci?(env)
env.key? "CODEBUILD_BUILD_ID"
end
def self.validates_as_pr?(env)
!!self.extract_pr_url(env)
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def initialize(env)
self.repo_slug = self.class.extract_repo_slug(env)
if env["CODEBUILD_BATCH_BUILD_IDENTIFIER"]
self.pull_request_id = env["CODEBUILD_WEBHOOK_TRIGGER"].split("/")[1].to_i
else
self.pull_request_id = env["CODEBUILD_SOURCE_VERSION"].split("/")[1].to_i
end
self.repo_url = self.class.extract_repo_url(env)
end
def self.extract_repo_slug(env)
return nil unless env.key? "CODEBUILD_SOURCE_REPO_URL"
gh_host = env["DANGER_GITHUB_HOST"] || "github.com"
env["CODEBUILD_SOURCE_REPO_URL"].gsub(%r{^.*?#{Regexp.escape(gh_host)}/(.*?)(\.git)?$}, '\1')
end
def self.extract_repo_url(env)
return nil unless env.key? "CODEBUILD_SOURCE_REPO_URL"
env["CODEBUILD_SOURCE_REPO_URL"].gsub(/\.git$/, "")
end
def self.extract_pr_url(env)
if env["CODEBUILD_BATCH_BUILD_IDENTIFIER"]
return nil unless env.key? "CODEBUILD_WEBHOOK_TRIGGER"
return nil unless env.key? "CODEBUILD_SOURCE_REPO_URL"
return nil unless env["CODEBUILD_WEBHOOK_TRIGGER"].split("/").length == 2
event_type, pr_number = env["CODEBUILD_WEBHOOK_TRIGGER"].split("/")
return nil unless event_type == "pr"
else
return nil unless env.key? "CODEBUILD_SOURCE_VERSION"
return nil unless env.key? "CODEBUILD_SOURCE_REPO_URL"
return nil unless env["CODEBUILD_SOURCE_VERSION"].split("/").length == 2
_source_origin, pr_number = env["CODEBUILD_SOURCE_VERSION"].split("/")
end
github_repo_url = env["CODEBUILD_SOURCE_REPO_URL"].gsub(/\.git$/, "")
"#{github_repo_url}/pull/#{pr_number}"
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/ci_source.rb | lib/danger/ci_source/ci_source.rb | # frozen_string_literal: true
require "set"
module Danger
# "abstract" CI class
class CI
attr_accessor :repo_slug, :pull_request_id, :repo_url, :supported_request_sources
def self.inherited(child_class)
available_ci_sources.add child_class
super
end
def self.available_ci_sources
@available_ci_sources ||= Set.new
end
def supported_request_sources
raise "CISource subclass must specify the supported request sources"
end
def supports?(request_source)
supported_request_sources.include?(request_source)
end
def self.validates_as_ci?(_env)
abort "You need to include a function for #{self} for validates_as_ci?"
end
def self.validates_as_pr?(_env)
abort "You need to include a function for #{self} for validates_as_pr?"
end
def initialize(_env)
raise "Subclass and overwrite initialize" if method(__method__).owner == Danger::CI
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/bitrise.rb | lib/danger/ci_source/bitrise.rb | # frozen_string_literal: true
# http://devcenter.bitrise.io/docs/available-environment-variables
require "danger/request_sources/github/github"
require "danger/request_sources/gitlab"
module Danger
# ### CI Setup
#
# Add a script step to your workflow:
#
# ```yml
# - script@1.1.2:
# inputs:
# - content: |-
# bundle install
# bundle exec danger
# ```
#
# ### Token Setup
#
# Add the `DANGER_GITHUB_API_TOKEN` to your workflow's [Secret App Env Vars](https://blog.bitrise.io/anyone-even-prs-can-have-secrets).
#
# ### Bitbucket Server and Bitrise
#
# Danger will read the environment variable `GIT_REPOSITORY_URL` to construct the Bitbucket Server API URL
# finding the project and repo slug in the `GIT_REPOSITORY_URL` variable. This `GIT_REPOSITORY_URL` variable
# comes from the App Settings tab for your Bitrise App. If you are manually setting a repo URL in the
# Git Clone Repo step, you may need to set adjust this property in the settings tab, maybe even fake it.
# The patterns used are `(%r{\.com/(.*)})` and `(%r{\.com:(.*)})` and `.split(/\.git$|$/)` to remove ".git" if the URL contains it.
#
class Bitrise < CI
def self.validates_as_ci?(env)
env.key? "BITRISE_IO"
end
def self.validates_as_pr?(env)
return !env["BITRISE_PULL_REQUEST"].to_s.empty?
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::GitLab,
Danger::RequestSources::BitbucketServer,
Danger::RequestSources::BitbucketCloud
]
end
def initialize(env)
self.pull_request_id = env["BITRISE_PULL_REQUEST"]
self.repo_url = env["GIT_REPOSITORY_URL"]
self.repo_slug = repo_slug_from(self.repo_url)
end
def repo_slug_from(url)
if url =~ URI::DEFAULT_PARSER.make_regexp
# Try to parse the URL as a valid URI. This should cover the cases of http/https/ssh URLs.
begin
uri = URI.parse(url)
return uri.path.sub(%r{^(/)}, "").sub(/(.git)$/, "")
rescue URI::InvalidURIError
# In case URL could not be parsed fallback to git URL parsing.
repo_slug_asgiturl(url)
end
else
# In case URL could not be parsed fallback to git URL parsing. git@github.com:organization/repo.git
repo_slug_asgiturl(url)
end
end
def repo_slug_asgiturl(url)
matcher_url = url
repo_matches = matcher_url.match(%r{([/:])(([^/]+/)+[^/]+?)(\.git$|$)})[2]
return repo_matches unless repo_matches.nil?
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/appcircle.rb | lib/danger/ci_source/appcircle.rb | # frozen_string_literal: true
# https://docs.appcircle.io/environment-variables/managing-variables
# https://docs.appcircle.io/build/build-profile-configuration#environment-variables-configuration
require "danger/request_sources/github/github"
require "danger/request_sources/gitlab"
module Danger
# ### CI Setup
#
# Add a Custom Script step to your workflow and set it as a bash:
#
# ```shell
# cd $AC_REPOSITORY_DIR
# bundle install
# bundle exec danger
# ```
# ### Token Setup
#
# Login to Appcircle and select your build profile. Go to your *Config* and
# choose *Environment Variables*.
# https://docs.appcircle.io/environment-variables/managing-variables
#
# #### GitHub
# Add the `DANGER_GITHUB_API_TOKEN` to your profile's ENV.
#
# #### GitLab
# Add the `DANGER_GITLAB_API_TOKEN` to your profile's ENV.
#
# #### Bitbucket Cloud
# Add the `DANGER_BITBUCKETSERVER_USERNAME`, `DANGER_BITBUCKETSERVER_PASSWORD`
# to your profile's ENV.
#
# #### Bitbucket server
# Add the `DANGER_BITBUCKETSERVER_USERNAME`, `DANGER_BITBUCKETSERVER_PASSWORD`
# and `DANGER_BITBUCKETSERVER_HOST` to your profile's ENV.
#
class Appcircle < CI
def self.validates_as_ci?(env)
env.key? "AC_APPCIRCLE"
end
def self.validates_as_pr?(env)
return false unless env.key? "AC_PULL_NUMBER"
env["AC_PULL_NUMBER"].to_i > 0
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::BitbucketCloud,
Danger::RequestSources::BitbucketServer,
Danger::RequestSources::GitLab
]
end
def initialize(env)
self.pull_request_id = env["AC_PULL_NUMBER"]
self.repo_url = env["AC_GIT_URL"]
self.repo_slug = repo_slug_from(self.repo_url)
end
def repo_slug_from(url)
if url =~ URI::DEFAULT_PARSER.make_regexp
# Try to parse the URL as a valid URI. This should cover the cases of http/https/ssh URLs.
begin
uri = URI.parse(url)
return uri.path.sub(%r{^(/)}, "").sub(/(.git)$/, "")
rescue URI::InvalidURIError
# In case URL could not be parsed fallback to git URL parsing.
repo_slug_asgiturl(url)
end
else
# In case URL could not be parsed fallback to git URL parsing. git@github.com:organization/repo.git
repo_slug_asgiturl(url)
end
end
def repo_slug_asgiturl(url)
matcher_url = url
repo_matches = matcher_url.match(%r{([/:])(([^/]+/)+[^/]+?)(\.git$|$)})[2]
return repo_matches unless repo_matches.nil?
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/bitbucket_pipelines.rb | lib/danger/ci_source/bitbucket_pipelines.rb | # frozen_string_literal: true
module Danger
# ### CI Setup
#
# Install dependencies and add a danger step to your `bitbucket-pipelines.yml`.
#
# ```yaml
# script:
# - bundle exec danger --verbose
# ```
#
# ### Token Setup
#
# For username and password, you need to set.
#
# - `DANGER_BITBUCKETCLOUD_USERNAME` = The username for the account used to comment, as shown on
# https://bitbucket.org/account/
# - `DANGER_BITBUCKETCLOUD_PASSWORD` = The password for the account used to comment, you could use
# [App passwords](https://confluence.atlassian.com/bitbucket/app-passwords-828781300.html#Apppasswords-Aboutapppasswords)
# with Read Pull Requests and Read Account Permissions.
#
# For OAuth key and OAuth secret, you can get them from.
#
# - Open [BitBucket Cloud Website](https://bitbucket.org)
# - Navigate to Settings > OAuth > Add consumer
# - Put `https://bitbucket.org/site/oauth2/authorize` for `Callback URL`, and enable Read Pull requests, and Read Account
# Permission.
#
# - `DANGER_BITBUCKETCLOUD_OAUTH_KEY` = The consumer key for the account used to comment, as show as `Key` on the website.
# - `DANGER_BITBUCKETCLOUD_OAUTH_SECRET` = The consumer secret for the account used to comment, as show as `Secret` on the
# website.
#
# For [repository access token](https://support.atlassian.com/bitbucket-cloud/docs/repository-access-tokens/), what you
# need to create one is:
#
# - Open your repository URL
# - Navigate to Settings > Security > Access Tokens > Create Repository Access Token
# - Give it a name and set Pull requests write scope
class BitbucketPipelines < CI
def self.validates_as_ci?(env)
env.key? "BITBUCKET_BUILD_NUMBER"
end
def self.validates_as_pr?(env)
env.key? "BITBUCKET_PR_ID"
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::BitbucketCloud]
end
def initialize(env)
self.repo_url = env["BITBUCKET_GIT_HTTP_ORIGIN"]
self.repo_slug = "#{env['BITBUCKET_REPO_OWNER']}/#{env['BITBUCKET_REPO_SLUG']}"
self.pull_request_id = env["BITBUCKET_PR_ID"]
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/circle.rb | lib/danger/ci_source/circle.rb | # frozen_string_literal: true
# https://circleci.com/docs/environment-variables
require "uri"
require "danger/ci_source/circle_api"
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# For setting up CircleCI, we recommend turning on "Only build pull requests" in "Advanced Settings." Without this enabled,
# it's trickier for Danger to determine whether you're in a pull request or not, as the environment metadata
# isn't as reliable.
#
# A common scenario is when CircleCI begins building a commit before the commit becomes associated with a PR
# (e.g. a developer pushes their branch to the remote repo for the first time. CircleCI spins up and begins building.
# Moments later the developer creates a PR on GitHub. Since the build process started before the PR existed,
# Danger won't be able to use the Circle-provided environment variables to retrieve PR metadata.)
#
# With "Only build pull requests" enabled, you can add `bundle exec danger` to your `config.yml` (Circle 2.0).
#
# e.g.
#
# ```yaml
# - run: bundle exec danger --verbose
# ```
#
# And that should be it!
#
# ### Token Setup
#
# If "Only build pull requests" can't be enabled for your project, Danger _can_ still work by relying on CircleCI's API
# to retrieve PR metadata, which will require an API token.
#
# 1. Go to your project > Settings > API Permissions. Create a token with scope "view-builds" and a label like "DANGER_CIRCLE_CI_API_TOKEN".
# 2. Settings > Environment Variables. Add the token as a CircleCI environment variable, which exposes it to the Danger process.
#
# There is no difference here for OSS vs Closed, both scenarios will need this environment variable.
#
# With these pieces in place, Danger should be able to work as expected.
#
class CircleCI < CI
# Side note: CircleCI is complicated. The env vars for PRs are not guaranteed to exist
# if the build was triggered from a commit, to look at examples of the different types
# of CI states, see this repo: https://github.com/orta/show_circle_env
def self.validates_as_ci?(env)
env.key? "CIRCLE_BUILD_NUM"
end
def self.validates_as_pr?(env)
# This will get used if it's available, instead of the API faffing.
return true if env["CI_PULL_REQUEST"] && !env["CI_PULL_REQUEST"].empty?
return true if env["CIRCLE_PULL_REQUEST"] && !env["CIRCLE_PULL_REQUEST"].empty?
# Real-world talk, it should be worrying if none of these are in the environment
return false unless ["DANGER_CIRCLE_CI_API_TOKEN", "CIRCLE_PROJECT_USERNAME", "CIRCLE_PROJECT_REPONAME", "CIRCLE_BUILD_NUM"].all? { |x| env[x] && !env[x].empty? }
# Uses the Circle API to determine if it's a PR otherwise
api = CircleAPI.new
api.pull_request?(env)
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub, Danger::RequestSources::BitbucketCloud]
end
def initialize(env)
self.repo_url = env["CIRCLE_REPOSITORY_URL"]
pr_url = env["CI_PULL_REQUEST"] || env["CIRCLE_PULL_REQUEST"]
# If it's not a real URL, use the Circle API
unless pr_url && URI.parse(pr_url).kind_of?(URI::HTTP)
api = CircleAPI.new
pr_url = api.pull_request_url(env)
end
# We should either have got it via the API, or
# an ENV var.
pr_path = URI.parse(pr_url).path.split("/")
if pr_path.count == 5
# The first one is an extra slash, ignore it
self.repo_slug = "#{pr_path[1]}/#{pr_path[2]}"
self.pull_request_id = pr_path[4]
else
message = "Danger::Circle.rb considers this a PR, " \
"but did not get enough information to get a repo slug" \
"and PR id.\n\n" \
"PR path: #{pr_url}\n" \
"Keys: #{env.keys}"
raise message.red
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/custom_ci_with_github.rb | lib/danger/ci_source/custom_ci_with_github.rb | # frozen_string_literal: true
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# Custom CI with GitHub
#
# This CI source is for custom, most likely internal, CI systems that are use GitHub as source control.
# An example could be argo-workflows or tekton hosted in your own Kubernetes cluster.
#
# The following environment variables are required:
# - `CUSTOM_CI_WITH_GITHUB` - Set to any value to indicate that this is a custom CI with GitHub
#
# ### Token Setup
#
# #### GitHub
# As you own the setup, it's up to you to add the environment variable for the `DANGER_GITHUB_API_TOKEN`.
#
class CustomCIWithGithub < CI
def self.validates_as_ci?(env)
env.key? "CUSTOM_CI_WITH_GITHUB"
end
def self.validates_as_pr?(env)
value = env["GITHUB_EVENT_NAME"]
["pull_request", "pull_request_target"].include?(value)
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def initialize(env)
super
self.repo_slug = env["GITHUB_REPOSITORY"]
pull_request_event = JSON.parse(File.read(env["GITHUB_EVENT_PATH"]))
self.pull_request_id = pull_request_event["number"]
self.repo_url = pull_request_event["repository"]["clone_url"]
# if environment variable DANGER_GITHUB_API_TOKEN is not set, use env GITHUB_TOKEN
if (env.key? "CUSTOM_CI_WITH_GITHUB") && (!env.key? "DANGER_GITHUB_API_TOKEN")
env["DANGER_GITHUB_API_TOKEN"] = env["GITHUB_TOKEN"]
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/appcenter.rb | lib/danger/ci_source/appcenter.rb | # frozen_string_literal: true
# https://docs.microsoft.com/en-us/appcenter/build/custom/variables/
require "uri"
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# Add a script step to your appcenter-post-build.sh:
#
# ```shell
# #!/usr/bin/env bash
# bundle install
# bundle exec danger
# ```
#
# ### Token Setup
#
# Add the `DANGER_GITHUB_API_TOKEN` to your environment variables.
#
class Appcenter < CI
def self.validates_as_ci?(env)
env.key? "APPCENTER_BUILD_ID"
end
def self.validates_as_pr?(env)
return env["BUILD_REASON"] == "PullRequest"
end
def self.owner_for_github(env)
URI.parse(env["BUILD_REPOSITORY_URI"]).path.split("/")[1]
end
def self.repo_identifier_for_github(env)
repo_name = env["BUILD_REPOSITORY_NAME"]
owner = owner_for_github(env)
"#{owner}/#{repo_name}"
end
# Hopefully it's a temporary workaround (same as in Codeship integration) because App Center
# doesn't expose PR's ID. There's a future request https://github.com/Microsoft/appcenter/issues/79
def self.pr_from_env(env)
Danger::RequestSources::GitHub.new(nil, env).get_pr_from_branch(repo_identifier_for_github(env), env["BUILD_SOURCEBRANCHNAME"], owner_for_github(env))
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def initialize(env)
self.pull_request_id = self.class.pr_from_env(env)
self.repo_url = env["BUILD_REPOSITORY_URI"]
self.repo_slug = self.class.repo_identifier_for_github(env)
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/cirrus.rb | lib/danger/ci_source/cirrus.rb | # frozen_string_literal: true
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
# You need to edit your `.cirrus.yml` to include `bundler exec danger`.
#
# Adding this to your `.cirrus.yml` allows Danger to fail your build, both on the Cirrus CI website and within your Pull Request.
# With that set up, you can edit your task to add `bundler exec danger` in any script instruction.
class Cirrus < CI
def self.validates_as_ci?(env)
env.key? "CIRRUS_CI"
end
def self.validates_as_pr?(env)
exists = ["CIRRUS_PR", "CIRRUS_REPO_FULL_NAME"].all? { |x| env[x] && !env[x].empty? }
exists && env["CIRRUS_PR"].to_i > 0
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def initialize(env)
self.repo_slug = env["CIRRUS_REPO_FULL_NAME"]
if env["CIRRUS_PR"].to_i > 0
self.pull_request_id = env["CIRRUS_PR"]
end
self.repo_url = env["CIRRUS_GIT_CLONE_URL"]
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/codemagic.rb | lib/danger/ci_source/codemagic.rb | # frozen_string_literal: true
# https://docs.codemagic.io/building/environment-variables/
module Danger
# ### CI Setup
#
# Add a script step to your workflow:
#
# ```
# - name: Running Danger
# script: |
# bundle install
# bundle exec danger
# ```
#
# ### Token Setup
#
# Add the following environment variables to your workflow's environment configuration.
# https://docs.codemagic.io/getting-started/yaml/
#
# #### GitHub
# Add the `DANGER_GITHUB_API_TOKEN` to your build user's ENV.
#
# #### GitLab
# Add the `DANGER_GITLAB_API_TOKEN` to your build user's ENV.
#
# #### Bitbucket Cloud
# Add the `DANGER_BITBUCKETSERVER_USERNAME`, `DANGER_BITBUCKETSERVER_PASSWORD`
# to your build user's ENV.
#
# #### Bitbucket server
# Add the `DANGER_BITBUCKETSERVER_USERNAME`, `DANGER_BITBUCKETSERVER_PASSWORD`
# and `DANGER_BITBUCKETSERVER_HOST` to your build user's ENV.
#
class Codemagic < CI
def self.validates_as_ci?(env)
env.key? "FCI_PROJECT_ID"
end
def self.validates_as_pr?(env)
return !env["FCI_PULL_REQUEST_NUMBER"].to_s.empty?
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::GitLab,
Danger::RequestSources::BitbucketServer,
Danger::RequestSources::BitbucketCloud
]
end
def initialize(env)
self.pull_request_id = env["FCI_PULL_REQUEST_NUMBER"]
self.repo_slug = env["FCI_REPO_SLUG"]
self.repo_url = GitRepo.new.origins # Codemagic doesn't provide a repo url env variable for n
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/local_only_git_repo.rb | lib/danger/ci_source/local_only_git_repo.rb | # frozen_string_literal: true
require "git"
require "danger/request_sources/local_only"
module Danger
# ### CI Setup
#
# For setting up LocalOnlyGitRepo there is not much needed. Either `--base` and `--head` need to be specified or
# origin/master is expected for base and HEAD for head
#
class LocalOnlyGitRepo < CI
attr_accessor :base_commit, :head_commit
HEAD_VAR = "DANGER_LOCAL_HEAD"
BASE_VAR = "DANGER_LOCAL_BASE"
def self.validates_as_ci?(env)
env.key? "DANGER_USE_LOCAL_ONLY_GIT"
end
def self.validates_as_pr?(_env)
false
end
def git
@git ||= GitRepo.new
end
def run_git(command)
git.exec(command).encode("UTF-8", "binary", invalid: :replace, undef: :replace, replace: "")
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::LocalOnly]
end
def initialize(env = {})
# expects --base/--head specified OR origin/master to be base and HEAD head
self.base_commit = env[BASE_VAR] || run_git("rev-parse --abbrev-ref origin/master")
self.head_commit = env[HEAD_VAR] || run_git("rev-parse --abbrev-ref HEAD")
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/circle_api.rb | lib/danger/ci_source/circle_api.rb | # frozen_string_literal: true
require "faraday"
module Danger
class CircleAPI
# Determine if there's a PR attached to this commit,
# and return a bool
def pull_request?(env)
url = pull_request_url(env)
return !url.nil?
end
# Determine if there's a PR attached to this commit,
# and return the url if so
def pull_request_url(env)
url = env["CI_PULL_REQUEST"]
if url.nil? && !env["CIRCLE_PROJECT_USERNAME"].nil? && !env["CIRCLE_PROJECT_REPONAME"].nil?
repo_slug = "#{env['CIRCLE_PROJECT_USERNAME']}/#{env['CIRCLE_PROJECT_REPONAME']}"
if !env["CIRCLE_PR_NUMBER"].nil?
host = env["DANGER_GITHUB_HOST"] || "github.com"
url = "https://#{host}/#{repo_slug}/pull/#{env['CIRCLE_PR_NUMBER']}"
else
token = env["DANGER_CIRCLE_CI_API_TOKEN"]
url = fetch_pull_request_url(repo_slug, env["CIRCLE_BUILD_NUM"], token)
end
end
url
end
def client
@client ||= Faraday.new(url: "https://circleci.com/api/v1")
end
# Ask the API if the commit is inside a PR
def fetch_pull_request_url(repo_slug, build_number, token)
build_json = fetch_build(repo_slug, build_number, token)
pull_requests = build_json[:pull_requests]
return nil unless pull_requests&.first
pull_requests.first[:url]
end
# Make the API call, and parse the JSON
def fetch_build(repo_slug, build_number, token)
url = "project/#{repo_slug}/#{build_number}"
params = { "circle-token" => token }
response = client.get url, params, accept: "application/json"
JSON.parse(response.body, symbolize_names: true)
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/dotci.rb | lib/danger/ci_source/dotci.rb | # frozen_string_literal: true
require "danger/request_sources/github/github"
module Danger
# https://groupon.github.io/DotCi
# ### CI Setup
# DotCi is a layer on top of jenkins. So, if you're using DotCi, you're hosting your own environment.
#
# ### Token Setup
#
# #### GitHub
# As you own the machine, it's up to you to add the environment variable for the `DANGER_GITHUB_API_TOKEN`.
#
class DotCi < CI
def self.validates_as_ci?(env)
env.key? "DOTCI"
end
def self.validates_as_pr?(env)
!env["DOTCI_PULL_REQUEST"].nil? && !env["DOTCI_PULL_REQUEST"].match(/^[0-9]+$/).nil?
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub
]
end
def initialize(env)
self.repo_url = self.class.repo_url(env)
self.pull_request_id = self.class.pull_request_id(env)
repo_matches = self.repo_url.match(%r{([/:])([^/]+/[^/]+)$})
self.repo_slug = repo_matches[2].gsub(/\.git$/, "") unless repo_matches.nil?
end
def self.pull_request_id(env)
env["DOTCI_PULL_REQUEST"]
end
def self.repo_url(env)
if env["DOTCI_INSTALL_PACKAGES_GIT_CLONE_URL"]
env["DOTCI_INSTALL_PACKAGES_GIT_CLONE_URL"]
elsif env["DOTCI_DOCKER_COMPOSE_GIT_CLONE_URL"]
env["DOTCI_DOCKER_COMPOSE_GIT_CLONE_URL"]
else
env["GIT_URL"]
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/teamcity.rb | lib/danger/ci_source/teamcity.rb | # frozen_string_literal: true
# https://www.jetbrains.com/teamcity/
require "danger/request_sources/github/github"
require "danger/request_sources/gitlab"
module Danger
# ### CI Setup
#
# You need to go to your project settings. Then depending on the type of your build settings, you may need
# to add a new build step for Danger. You want to be able to run the command `bundle exec danger`, so
# the "Simple Command Runner" should be all you need to do that.
#
# ### Token + Environment Setup
#
# #### GitHub
#
# As this is self-hosted, you will need to add the `DANGER_GITHUB_API_TOKEN` to your build user's ENV. The alternative
# is to pass in the token as a prefix to the command `DANGER_GITHUB_API_TOKEN="123" bundle exec danger`.
#
# However, you will need to find a way to add the environment vars: `GITHUB_REPO_SLUG`, `GITHUB_PULL_REQUEST_ID` and
# `GITHUB_REPO_URL`. These are not added by default. You can manually add `GITHUB_REPO_SLUG` and `GITHUB_REPO_URL`
# as build parameters or by exporting them inside your Simple Command Runner.
#
# As for `GITHUB_PULL_REQUEST_ID`, TeamCity provides the `%teamcity.build.branch%` variable which is in the format
# `PR_NUMBER/merge`. You can slice the Pull Request ID out by doing the following:
#
# ```sh
# branch="%teamcity.build.branch%"
# export GITHUB_PULL_REQUEST_ID=(${branch//\// })
# ```
#
# Or if you are using the pull request feature you can set an environment parameter called `GITHUB_PULL_REQUEST_ID`
# to the value of: `%teamcity.pullRequest.number`
#
# #### GitLab
#
# As this is self-hosted, you will need to add the `DANGER_GITLAB_API_TOKEN` to your build user's ENV. The alternative
# is to pass in the token as a prefix to the command `DANGER_GITLAB_API_TOKEN="123" bundle exec danger`.
#
# However, you will need to find a way to add the environment vars: `GITLAB_REPO_SLUG`, `GITLAB_PULL_REQUEST_ID` and
# `GITLAB_REPO_URL`. These are not added by default. You could do this via the GitLab API potentially.
#
# We would love some advice on improving this setup.
#
# #### BitBucket Cloud
#
# You will need to add the following environment variables as build parameters or by exporting them inside your
# Simple Command Runner.
#
#
# - `BITBUCKET_REPO_SLUG`
# - `BITBUCKET_REPO_URL`
#
# - `DANGER_BITBUCKETCLOUD_USERNAME`
# - `DANGER_BITBUCKETCLOUD_PASSWORD`
#
# or
#
# - `DANGER_BITBUCKETCLOUD_OAUTH_KEY`
# - `DANGER_BITBUCKETCLOUD_OAUTH_SECRET`
#
# You will also need to set the `BITBUCKET_BRANCH_NAME` environment variable.
# TeamCity provides `%teamcity.build.branch%`, which you can use at the top of your Simple Command Runner:
#
# ```sh
# export BITBUCKET_BRANCH_NAME="%teamcity.build.branch%"
# ```
#
# #### BitBucket Server
#
# You will need to add the following environment variables as build parameters or by exporting them inside your
# Simple Command Runner.
#
# - `DANGER_BITBUCKETSERVER_USERNAME`
# - `DANGER_BITBUCKETSERVER_PASSWORD`
# - `DANGER_BITBUCKETSERVER_HOST`
# - `BITBUCKETSERVER_REPO_SLUG`
# - `BITBUCKETSERVER_PULL_REQUEST_ID`
# - `BITBUCKETSERVER_REPO_URL`
#
class TeamCity < CI
class << self
def validates_as_github_pr?(env)
["GITHUB_PULL_REQUEST_ID", "GITHUB_REPO_URL"].all? { |x| env[x] && !env[x].empty? }
end
def validates_as_gitlab_pr?(env)
["GITLAB_REPO_SLUG", "GITLAB_PULL_REQUEST_ID", "GITLAB_REPO_URL"].all? { |x| env[x] && !env[x].empty? }
end
def validates_as_bitbucket_cloud_pr?(env)
["BITBUCKET_REPO_SLUG", "BITBUCKET_BRANCH_NAME", "BITBUCKET_REPO_URL"].all? { |x| env[x] && !env[x].empty? }
end
def validates_as_bitbucket_server_pr?(env)
["BITBUCKETSERVER_REPO_SLUG", "BITBUCKETSERVER_PULL_REQUEST_ID", "BITBUCKETSERVER_REPO_URL"].all? { |x| env[x] && !env[x].empty? }
end
end
def self.validates_as_ci?(env)
env.key? "TEAMCITY_VERSION"
end
def self.validates_as_pr?(env)
validates_as_github_pr?(env) || validates_as_gitlab_pr?(env) || validates_as_bitbucket_cloud_pr?(env) || validates_as_bitbucket_server_pr?(env)
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub, Danger::RequestSources::GitLab, Danger::RequestSources::BitbucketCloud, Danger::RequestSources::BitbucketServer]
end
def initialize(env)
# NB: Unfortunately TeamCity doesn't provide these variables
# automatically so you have to add these variables manually to your
# project or build configuration
if self.class.validates_as_github_pr?(env)
extract_github_variables!(env)
elsif self.class.validates_as_gitlab_pr?(env)
extract_gitlab_variables!(env)
elsif self.class.validates_as_bitbucket_cloud_pr?(env)
extract_bitbucket_variables!(env)
elsif self.class.validates_as_bitbucket_server_pr?(env)
extract_bitbucket_server_variables!(env)
end
end
private
def extract_github_variables!(env)
self.repo_slug = env["GITHUB_REPO_SLUG"]
self.pull_request_id = env["GITHUB_PULL_REQUEST_ID"].to_i
self.repo_url = env["GITHUB_REPO_URL"]
end
def extract_gitlab_variables!(env)
self.repo_slug = env["GITLAB_REPO_SLUG"]
self.pull_request_id = env["GITLAB_PULL_REQUEST_ID"].to_i
self.repo_url = env["GITLAB_REPO_URL"]
end
def extract_bitbucket_variables!(env)
self.repo_slug = env["BITBUCKET_REPO_SLUG"]
self.pull_request_id = bitbucket_pr_from_env(env)
self.repo_url = env["BITBUCKET_REPO_URL"]
end
def extract_bitbucket_server_variables!(env)
self.repo_slug = env["BITBUCKETSERVER_REPO_SLUG"]
self.pull_request_id = env["BITBUCKETSERVER_PULL_REQUEST_ID"].to_i
self.repo_url = env["BITBUCKETSERVER_REPO_URL"]
end
# This is a little hacky, because Bitbucket doesn't provide us a PR id
def bitbucket_pr_from_env(env)
branch_name = env["BITBUCKET_BRANCH_NAME"]
repo_slug = env["BITBUCKET_REPO_SLUG"]
begin
Danger::RequestSources::BitbucketCloudAPI.new(repo_slug, nil, branch_name, env).pull_request_id
rescue StandardError
raise "Failed to find a pull request for branch \"#{branch_name}\" on Bitbucket."
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/screwdriver.rb | lib/danger/ci_source/screwdriver.rb | # frozen_string_literal: true
# http://screwdriver.cd
# https://docs.screwdriver.cd/user-guide/environment-variables
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# Install dependencies and add a danger step to your screwdriver.yaml:
#
# ```yml
# jobs:
# danger:
# requires: [~pr, ~commit]
# steps:
# - setup: bundle install --path vendor
# - danger: bundle exec danger
# secrets:
# - DANGER_GITHUB_API_TOKEN
# ```
#
# ### Token Setup
#
# Add the `DANGER_GITHUB_API_TOKEN` to your pipeline env as a
# [build secret](https://docs.screwdriver.cd/user-guide/configuration/secrets)
#
class Screwdriver < CI
def self.validates_as_ci?(env)
env.key? "SCREWDRIVER"
end
def self.validates_as_pr?(env)
exists = ["SD_PULL_REQUEST", "SCM_URL"].all? { |x| env[x] && !env[x].empty? }
exists && env["SD_PULL_REQUEST"].to_i > 0
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def initialize(env)
self.repo_slug = env["SCM_URL"].split(":").last.gsub(".git", "").split("#", 2).first
self.repo_url = env["SCM_URL"].split("#", 2).first
if env["SD_PULL_REQUEST"].to_i > 0
self.pull_request_id = env["SD_PULL_REQUEST"]
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/codefresh.rb | lib/danger/ci_source/codefresh.rb | # frozen_string_literal: true
# https://semaphoreci.com/docs/available-environment-variables.html
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# To set up Danger on Codefresh, create a freestyle step in your Codefresh yaml configuration:
#
# ```yml
# Danger:
# title: Run Danger
# image: alpine/bundle
# working_directory: ${{main_clone}}
# commands:
# - bundle install --deployment
# - bundle exec danger --verbose
# ```
#
# Don't forget to add the `DANGER_GITHUB_API_TOKEN` variable to your pipeline settings so that Danger can properly post comments to your pull request.
#
class Codefresh < CI
def self.validates_as_ci?(env)
env.key?("CF_BUILD_ID") && env.key?("CF_BUILD_URL")
end
def self.validates_as_pr?(env)
return !env["CF_PULL_REQUEST_NUMBER"].to_s.empty?
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def self.slug_from(env)
return "" if env["CF_REPO_OWNER"].to_s.empty?
return "" if env["CF_REPO_NAME"].to_s.empty?
"#{env['CF_REPO_OWNER']}/#{env['CF_REPO_NAME']}".downcase
end
def initialize(env)
self.repo_url = env["CF_COMMIT_URL"].to_s.gsub(%r{/commit.+$}, "")
self.repo_slug = self.class.slug_from(env)
self.pull_request_id = env["CF_PULL_REQUEST_NUMBER"]
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/xcode_server.rb | lib/danger/ci_source/xcode_server.rb | # frozen_string_literal: true
# Following the advice from @czechboy0 https://github.com/danger/danger/issues/171
# https://github.com/czechboy0/Buildasaur
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# If you're bold enough to use Xcode Bots. You will need to use [Buildasaur](https://github.com/czechboy0/Buildasaur)
# in order to work with Danger. This will set up your build environment for you, as the name of the bot contains all
# of the environment variables that Danger needs to work.
#
# With Buildasaur set up, you can edit your job to add `bundle exec danger` as a post-action build script.
#
# ### Token Setup
#
# As this is self-hosted, you will need to add the `DANGER_GITHUB_API_TOKEN` to your build user's ENV. The alternative
# is to pass in the token as a prefix to the command `DANGER_GITHUB_API_TOKEN="123" bundle exec danger`.`.
#
class XcodeServer < CI
def self.validates_as_ci?(env)
env.key? "XCS_BOT_NAME"
end
def self.validates_as_pr?(env)
value = env["XCS_BOT_NAME"]
!value.nil? && value.include?("BuildaBot")
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::BitbucketServer,
Danger::RequestSources::BitbucketCloud
]
end
def initialize(env)
bot_name = env["XCS_BOT_NAME"]
return if bot_name.nil?
repo_matches = bot_name.match(/\[(.+)\]/)
self.repo_slug = repo_matches[1] unless repo_matches.nil?
pull_request_id_matches = bot_name.match(/#(\d+)/)
self.pull_request_id = pull_request_id_matches[1] unless pull_request_id_matches.nil?
self.repo_url = GitRepo.new.origins # Xcode Server doesn't provide a repo url env variable :/
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/gitlab_ci.rb | lib/danger/ci_source/gitlab_ci.rb | # frozen_string_literal: true
# http://docs.gitlab.com/ce/ci/variables/README.html
require "uri"
require "danger/request_sources/github/github"
require "danger/request_sources/gitlab"
module Danger
# ### CI Setup
#
# Install dependencies and add a danger step to your .gitlab-ci.yml:
#
# ```yml
# before_script:
# - bundle install
# danger:
# script:
# - bundle exec danger
# ```
#
# ### Token Setup
#
# Add the `DANGER_GITLAB_API_TOKEN` to your pipeline env variables if you
# are hosting your code on GitLab. If you are using GitLab as a mirror
# for the purpose of CI/CD, while hosting your repo on GitHub, set the
# `DANGER_GITHUB_API_TOKEN` as well as the project repo URL to
# `DANGER_PROJECT_REPO_URL`.
class GitLabCI < CI
def self.validates_as_ci?(env)
env.key? "GITLAB_CI"
end
def self.validates_as_pr?(env)
exists = [
"GITLAB_CI", "CI_PROJECT_PATH"
].all? { |x| env[x] }
exists && determine_pull_or_merge_request_id(env).to_i > 0
end
def self.determine_pull_or_merge_request_id(env)
return env["CI_MERGE_REQUEST_IID"] if env["CI_MERGE_REQUEST_IID"]
return env["CI_EXTERNAL_PULL_REQUEST_IID"] if env["CI_EXTERNAL_PULL_REQUEST_IID"]
return 0 unless env["CI_COMMIT_SHA"]
project_path = env["CI_MERGE_REQUEST_PROJECT_PATH"] || env["CI_PROJECT_PATH"]
base_commit = env["CI_COMMIT_SHA"]
client = RequestSources::GitLab.new(nil, env).client
client_version = Gem::Version.new(client.version.version)
if client_version >= Gem::Version.new("10.7")
# Use the 'list merge requests associated with a commit' API, for speed
# (GET /projects/:id/repository/commits/:sha/merge_requests) available for GitLab >= 10.7
merge_request = client.commit_merge_requests(project_path, base_commit, state: :opened).first
if client_version >= Gem::Version.new("13.8")
# Gitlab 13.8.0 started returning merge requests for merge commits and squashed commits
# By checking for merge_request.state, we can ensure danger only comments on MRs which are open
return 0 if merge_request.nil?
return 0 unless merge_request.state == "opened"
end
else
merge_requests = client.merge_requests(project_path, state: :opened)
merge_request = merge_requests.auto_paginate.find do |mr|
mr.sha == base_commit
end
end
merge_request.nil? ? 0 : merge_request.iid
end
def self.slug_from(env)
if env["DANGER_PROJECT_REPO_URL"]
env["DANGER_PROJECT_REPO_URL"].split("/").last(2).join("/")
else
env["CI_MERGE_REQUEST_PROJECT_PATH"] || env["CI_PROJECT_PATH"]
end
end
def initialize(env)
self.repo_slug = self.class.slug_from(env)
self.pull_request_id = self.class.determine_pull_or_merge_request_id(env)
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::GitLab
]
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/local_git_repo.rb | lib/danger/ci_source/local_git_repo.rb | # frozen_string_literal: true
# For more info see: https://github.com/schacon/ruby-git
require "git"
require "uri"
require "danger/request_sources/github/github"
require "danger/ci_source/support/find_repo_info_from_url"
require "danger/ci_source/support/find_repo_info_from_logs"
require "danger/ci_source/support/no_repo_info"
require "danger/ci_source/support/pull_request_finder"
require "danger/ci_source/support/commits"
module Danger
class LocalGitRepo < CI
attr_accessor :base_commit, :head_commit
def self.validates_as_ci?(env)
env.key? "DANGER_USE_LOCAL_GIT"
end
def self.validates_as_pr?(_env)
false
end
def git
@git ||= GitRepo.new
end
def run_git(command)
git.exec(command).encode("UTF-8", "binary", invalid: :replace, undef: :replace, replace: "")
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::BitbucketServer,
Danger::RequestSources::BitbucketCloud,
Danger::RequestSources::VSTS,
Danger::RequestSources::GitLab
]
end
def initialize(env = {})
@remote_info = find_remote_info(env)
@found_pull_request = find_pull_request(env)
self.repo_slug = remote_info.slug
raise_error_for_missing_remote if remote_info.kind_of?(NoRepoInfo)
self.pull_request_id = found_pull_request.pull_request_id
if sha
self.base_commit = commits.base
self.head_commit = commits.head
else
self.base_commit = found_pull_request.base
self.head_commit = found_pull_request.head
end
end
private
attr_reader :remote_info, :found_pull_request
def raise_error_for_missing_remote
raise missing_remote_error_message
end
def missing_remote_error_message
"danger cannot find your git remote, please set a remote. " \
"And the repository must host on GitHub.com or GitHub Enterprise."
end
def find_remote_info(env)
if given_pull_request_url?(env)
pr_url = env["LOCAL_GIT_PR_URL"] || env["LOCAL_GIT_MR_URL"]
FindRepoInfoFromURL.new(pr_url).call
else
FindRepoInfoFromLogs.new(
env["DANGER_GITHUB_HOST"] || "github.com",
run_git("remote show origin -n")
).call
end || NoRepoInfo.new
end
def find_pull_request(env)
if given_pull_request_url?(env)
remote_url = env["LOCAL_GIT_PR_URL"] || env["LOCAL_GIT_MR_URL"]
PullRequestFinder.new(
remote_info.id,
remote_info.slug,
remote: true,
remote_url: remote_url
).call(env: env)
else
PullRequestFinder.new(
env.fetch("LOCAL_GIT_PR_ID") { env.fetch("LOCAL_GIT_MR_ID", "") },
remote_info.slug,
remote: false,
git_logs: run_git("log --oneline -1000000")
).call(env: env)
end
end
def given_pull_request_url?(env)
(env["LOCAL_GIT_PR_URL"] && !env["LOCAL_GIT_PR_URL"].empty?) ||
(env["LOCAL_GIT_MR_URL"] && !env["LOCAL_GIT_MR_URL"].empty?)
end
def sha
@_sha ||= found_pull_request.sha
end
def commits
@_commits ||= Commits.new(run_git("rev-list --parents -n 1 #{sha}"))
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/xcode_cloud.rb | lib/danger/ci_source/xcode_cloud.rb | # frozen_string_literal: true
module Danger
# ### CI Setup
#
# In order to work with Xcode Cloud and Danger, you will need to add `bundle exec danger` to
# the `ci_scripts/ci_post_xcodebuild.sh` (Xcode Cloud's expected filename for a post-action build script).
# More details and documentation on Xcode Cloud configuration can be found [here](https://developer.apple.com/documentation/xcode/writing-custom-build-scripts).
#
# ### Token Setup
#
# You will need to add the `DANGER_GITHUB_API_TOKEN` to your build environment.
# If running on GitHub Enterprise, make sure you also set the expected values for
# both `DANGER_GITHUB_API_HOST` and `DANGER_GITHUB_HOST`.
#
class XcodeCloud < CI
def self.validates_as_ci?(env)
env.key? "CI_XCODEBUILD_ACTION"
end
def self.validates_as_pr?(env)
env.key? "CI_PULL_REQUEST_NUMBER"
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::GitLab,
Danger::RequestSources::BitbucketCloud,
Danger::RequestSources::BitbucketServer
]
end
def initialize(env)
self.repo_slug = env["CI_PULL_REQUEST_SOURCE_REPO"]
self.pull_request_id = env["CI_PULL_REQUEST_NUMBER"]
self.repo_url = env["CI_PULL_REQUEST_HTML_URL"]
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/surf.rb | lib/danger/ci_source/surf.rb | # frozen_string_literal: true
# http://github.com/surf-build/surf
require "danger/request_sources/github/github"
module Danger
# ### CI Setup
#
# You want to add `bundle exec danger` to your `build.sh` file to run Danger at the
# end of your build.
#
# ### Token Setup
#
# As this is self-hosted, you will need to add the `DANGER_GITHUB_API_TOKEN` to your build user's ENV. The alternative
# is to pass in the token as a prefix to the command `DANGER_GITHUB_API_TOKEN="123" bundle exec danger`.
#
class Surf < CI
def self.validates_as_ci?(env)
return ["SURF_REPO", "SURF_NWO"].all? { |x| env[x] && !env[x].empty? }
end
def self.validates_as_pr?(env)
validates_as_ci?(env)
end
def supported_request_sources
@supported_request_sources ||= [Danger::RequestSources::GitHub]
end
def initialize(env)
self.repo_slug = env["SURF_NWO"]
if env["SURF_PR_NUM"].to_i > 0
self.pull_request_id = env["SURF_PR_NUM"]
end
self.repo_url = env["SURF_REPO"]
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/appveyor.rb | lib/danger/ci_source/appveyor.rb | # frozen_string_literal: true
# https://www.appveyor.com/docs/build-configuration/
module Danger
# ### CI Setup
#
# Install dependencies and add a danger step to your `appveyor.yml`.
#
# ```yaml
# install:
# - cmd: >-
# set PATH=C:\Ruby25-x64\bin;%PATH%
#
# bundle install
# after_test:
# - cmd: >-
# bundle exec danger
# ```
#
# ### Token Setup
#
# For public repositories, add your plain token to environment variables in `appveyor.yml`.
# Encrypted environment variables will not be decrypted on PR builds.
# see here: https://www.appveyor.com/docs/build-configuration/#secure-variables
#
# ```yaml
# environment:
# DANGER_GITHUB_API_TOKEN: <YOUR_TOKEN_HERE>
# ```
#
# For private repositories, enter your token in `Settings>Environment>Environment variables>Add variable` and turn on `variable encryption`.
# You will see encrypted variable text in `Settings>Export YAML` so just copy to your `appveyor.yml`.
#
# ```yaml
# environment:
# DANGER_GITHUB_API_TOKEN:
# secure: <YOUR_ENCRYPTED_TOKEN_HERE>
# ```
#
class AppVeyor < CI
def self.validates_as_ci?(env)
env.key? "APPVEYOR"
end
def self.validates_as_pr?(env)
return false unless env.key? "APPVEYOR_PULL_REQUEST_NUMBER"
env["APPVEYOR_PULL_REQUEST_NUMBER"].to_i > 0
end
def initialize(env)
self.repo_slug = env["APPVEYOR_REPO_NAME"]
self.pull_request_id = env["APPVEYOR_PULL_REQUEST_NUMBER"]
self.repo_url = GitRepo.new.origins # AppVeyor doesn't provide a repo url env variable for now
end
def supported_request_sources
@supported_request_sources ||= [
Danger::RequestSources::GitHub,
Danger::RequestSources::BitbucketCloud,
Danger::RequestSources::BitbucketServer,
Danger::RequestSources::GitLab
]
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/support/local_pull_request.rb | lib/danger/ci_source/support/local_pull_request.rb | # frozen_string_literal: true
module Danger
class LocalPullRequest
attr_reader :pull_request_id, :sha
def initialize(log_line)
@pull_request_id = log_line.match(/#(?<id>[0-9]+)/)[:id]
@sha = log_line.split(" ").first
end
def valid?
pull_request_id && sha
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/support/no_pull_request.rb | lib/danger/ci_source/support/no_pull_request.rb | # frozen_string_literal: true
module Danger
class NoPullRequest
def valid?
false
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/support/find_repo_info_from_logs.rb | lib/danger/ci_source/support/find_repo_info_from_logs.rb | # frozen_string_literal: true
require "danger/ci_source/support/repo_info"
module Danger
class FindRepoInfoFromLogs
def initialize(github_host, remote_logs)
@github_host = github_host
@remote_logs = remote_logs
end
def call
matched = remote.match(regexp)
if matched
RepoInfo.new(matched["repo_slug"], nil)
end
end
private
attr_reader :remote_logs, :github_host
def remote
remote_logs.lines.grep(/Fetch URL/)[0].split(": ", 2)[1]
end
def regexp
%r{
#{Regexp.escape(github_host)}
(:|/|(:/))
(?<repo_slug>[^/]+/.+?)
(?:\.git)?$
}x
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/support/pull_request_finder.rb | lib/danger/ci_source/support/pull_request_finder.rb | # frozen_string_literal: true
require "danger/ci_source/support/local_pull_request"
require "danger/ci_source/support/remote_pull_request"
require "danger/ci_source/support/no_pull_request"
module Danger
class PullRequestFinder
def initialize(specific_pull_request_id, repo_slug = nil, remote: false, git_logs: "", remote_url: "")
@specific_pull_request_id = specific_pull_request_id
@git_logs = git_logs
@repo_slug = repo_slug
@remote = to_boolean(remote)
@remote_url = remote_url
end
def call(env: nil)
find_pull_request(env).tap do |pull_request|
raise_pull_request_not_found!(pull_request) unless pull_request.valid?
end
end
private
attr_reader :specific_pull_request_id, :git_logs, :repo_slug, :remote, :remote_url
def to_boolean(maybe_string)
["true", "1", "yes", "y", true].include?(maybe_string)
end
def raise_pull_request_not_found!(_pull_request)
if specific_pull_request_id.empty?
raise "No recent Pull Requests found for this repo, danger requires at least one Pull Request for the local mode."
else
raise "Could not find the Pull Request (#{specific_pull_request_id}) inside the git history for this repo."
end
end
# @return [String] Log line of most recent merged Pull Request
def find_pull_request(env)
return if pull_request_ref.empty?
if both_present?
LocalPullRequest.new(pick_the_most_recent_one_from_two_matches)
elsif only_merged_pull_request_present?
LocalPullRequest.new(most_recent_merged_pull_request)
elsif only_squash_and_merged_pull_request_present?
LocalPullRequest.new(most_recent_squash_and_merged_pull_request)
elsif remote
remote_pull_request = find_remote_pull_request(env)
remote_pull_request ? generate_remote_pull_request(remote_pull_request) : NoPullRequest.new
else
NoPullRequest.new
end
end
# @return [String] "#42"
def pull_request_ref
!specific_pull_request_id.empty? ? "##{specific_pull_request_id}" : "#\\d+"
end
def generate_remote_pull_request(remote_pull_request)
scm_provider = find_scm_provider(remote_url)
case scm_provider
when :bitbucket_cloud
RemotePullRequest.new(
remote_pull_request[:id].to_s,
remote_pull_request[:source][:commit][:hash],
remote_pull_request[:destination][:commit][:hash]
)
when :bitbucket_server
RemotePullRequest.new(
remote_pull_request[:id].to_s,
remote_pull_request[:fromRef][:latestCommit],
remote_pull_request[:toRef][:latestCommit]
)
when :github
RemotePullRequest.new(
remote_pull_request.number.to_s,
remote_pull_request.head.sha,
remote_pull_request.base.sha
)
when :gitlab
RemotePullRequest.new(
remote_pull_request.iid.to_s,
remote_pull_request.diff_refs.head_sha,
remote_pull_request.diff_refs.base_sha
)
when :vsts
RemotePullRequest.new(
remote_pull_request[:pullRequestId].to_s,
remote_pull_request[:lastMergeSourceCommit][:commitId],
remote_pull_request[:lastMergeTargetCommit][:commitId]
)
else
raise "SCM provider not supported: #{scm_provider}"
end
end
def find_remote_pull_request(env)
scm_provider = find_scm_provider(remote_url)
if scm_provider == :gitlab
client(env).merge_request(repo_slug, specific_pull_request_id)
else
client(env).pull_request(repo_slug, specific_pull_request_id)
end
end
def both_present?
most_recent_merged_pull_request && most_recent_squash_and_merged_pull_request
end
# @return [String] Log line of format: "Merge pull request #42"
def most_recent_merged_pull_request
@most_recent_merged_pull_request ||= git_logs.lines.grep(/Merge pull request #{pull_request_ref} from/)[0]
end
# @return [String] Log line of format: "description (#42)"
def most_recent_squash_and_merged_pull_request
@most_recent_squash_and_merged_pull_request ||= git_logs.lines.grep(/\(#{pull_request_ref}\)/)[0]
end
def pick_the_most_recent_one_from_two_matches
merged_index = git_logs.lines.index(most_recent_merged_pull_request)
squash_and_merged_index = git_logs.lines.index(most_recent_squash_and_merged_pull_request)
if merged_index > squash_and_merged_index # smaller index is more recent
most_recent_squash_and_merged_pull_request
else
most_recent_merged_pull_request
end
end
def only_merged_pull_request_present?
return false if most_recent_squash_and_merged_pull_request
!most_recent_merged_pull_request.nil? && !most_recent_merged_pull_request.empty?
end
def only_squash_and_merged_pull_request_present?
return false if most_recent_merged_pull_request
!most_recent_squash_and_merged_pull_request.nil? && !most_recent_squash_and_merged_pull_request.empty?
end
def client(env)
scm_provider = find_scm_provider(remote_url)
case scm_provider
when :bitbucket_cloud
bitbucket_cloud_client(env)
when :bitbucket_server
bitbucket_server_client(env)
when :vsts
vsts_client(env)
when :gitlab
gitlab_client(env)
when :github
github_client(env)
else
raise "SCM provider not supported: #{scm_provider}"
end
end
def bitbucket_cloud_client(env)
require "danger/request_sources/bitbucket_cloud_api"
branch_name = ENV["DANGER_BITBUCKET_TARGET_BRANCH"] # Optional env variable (specifying the target branch) to help find the PR.
RequestSources::BitbucketCloudAPI.new(repo_slug, specific_pull_request_id, branch_name, env)
end
def bitbucket_server_client(env)
require "danger/request_sources/bitbucket_server_api"
project, slug = repo_slug.split("/")
RequestSources::BitbucketServerAPI.new(project, slug, specific_pull_request_id, env)
end
def vsts_client(env)
require "danger/request_sources/vsts_api"
RequestSources::VSTSAPI.new(repo_slug, specific_pull_request_id, env)
end
def gitlab_client(env)
require "gitlab"
token = env&.fetch("DANGER_GITLAB_API_TOKEN", nil) || ENV["DANGER_GITLAB_API_TOKEN"]
if token && !token.empty?
endpoint = env&.fetch("DANGER_GITLAB_API_BASE_URL", nil) || env&.fetch("CI_API_V4_URL", nil) || ENV["DANGER_GITLAB_API_BASE_URL"] || ENV.fetch("CI_API_V4_URL", "https://gitlab.com/api/v4")
Gitlab.client(endpoint: endpoint, private_token: token)
else
raise "No API token given, please provide one using `DANGER_GITLAB_API_TOKEN`"
end
end
def github_client(env)
require "octokit"
access_token = env&.fetch("DANGER_GITHUB_API_TOKEN", nil) || ENV["DANGER_GITHUB_API_TOKEN"]
bearer_token = env&.fetch("DANGER_GITHUB_BEARER_TOKEN", nil) || ENV["DANGER_GITHUB_BEARER_TOKEN"]
if bearer_token && !bearer_token.empty?
Octokit::Client.new(bearer_token: bearer_token, api_endpoint: api_url)
elsif access_token && !access_token.empty?
Octokit::Client.new(access_token: access_token, api_endpoint: api_url)
else
raise "No API token given, please provide one using `DANGER_GITHUB_API_TOKEN` or `DANGER_GITHUB_BEARER_TOKEN`"
end
end
def api_url
ENV.fetch("DANGER_GITHUB_API_HOST") do
ENV.fetch("DANGER_GITHUB_API_BASE_URL", "https://api.github.com/")
end
end
def find_scm_provider(remote_url)
case remote_url
when %r{/bitbucket.org/}
:bitbucket_cloud
when %r{/pull-requests/}
:bitbucket_server
when /\.visualstudio\.com/i, /dev\.azure\.com/i
:vsts
when /gitlab\.com/, %r{-/merge_requests/}
:gitlab
else
:github
end
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/support/repo_info.rb | lib/danger/ci_source/support/repo_info.rb | # frozen_string_literal: true
module Danger
class RepoInfo
attr_reader :slug, :id
def initialize(slug, id)
@slug = slug
@id = id
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/support/find_repo_info_from_url.rb | lib/danger/ci_source/support/find_repo_info_from_url.rb | # frozen_string_literal: true
require "danger/ci_source/support/repo_info"
module Danger
class FindRepoInfoFromURL
REGEXP = %r{
://[^/]+/
(([^/]+/){1,2}_git/)?
(?<slug>[^/]+(/[^/]+){0,2})
(/(pull|pullrequest|merge_requests|pull-requests)/)
(?<id>\d+)
}x.freeze
# Regex used to extract info from Bitbucket server URLs, as they use a quite different format
REGEXPBB = %r{
(?:[/:])projects
/([^/.]+)
/repos/([^/.]+)
/pull-requests
/(\d+)
}x.freeze
def initialize(url)
@url = url
end
def call
matched = url.match(REGEXPBB)
if matched
RepoInfo.new("#{matched[1]}/#{matched[2]}", matched[3])
else
matched = url.match(REGEXP)
if matched
# Clean up the slug to remove any trailing dashes or slashes that might be part of the GitLab URL format
clean_slug = matched[:slug].gsub(%r{[-/]+$}, "")
RepoInfo.new(clean_slug, matched[:id])
end
end
end
private
attr_reader :url
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/support/remote_pull_request.rb | lib/danger/ci_source/support/remote_pull_request.rb | # frozen_string_literal: true
module Danger
class RemotePullRequest
attr_reader :pull_request_id, :sha, :head, :base
def initialize(pull_request_id, head, base)
@pull_request_id = pull_request_id
@head = head
@base = base
end
def valid?
pull_request_id && head && base
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/support/commits.rb | lib/danger/ci_source/support/commits.rb | # frozen_string_literal: true
module Danger
class Commits
def initialize(base_head)
@base_head = base_head.strip.split(" ")
end
def base
base_head.first
end
def head
base_head.last
end
private
attr_reader :base_head
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/ci_source/support/no_repo_info.rb | lib/danger/ci_source/support/no_repo_info.rb | # frozen_string_literal: true
module Danger
class NoRepoInfo
attr_reader :slug, :id
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/danger_core/message_group.rb | lib/danger/danger_core/message_group.rb | # frozen_string_literal: true
module Danger
class MessageGroup
def initialize(file: nil, line: nil)
@file = file
@line = line
end
# Returns whether this `MessageGroup` is for the same line of code as
# `other`, taking which file they are in to account.
# @param other [MessageGroup, Markdown, Violation]
# @return [Boolean] whether this `MessageGroup` is for the same line of code
def same_line?(other)
other.file == file && other.line == line
end
# Merges two `MessageGroup`s that represent the same line of code
# In future, perhaps `MessageGroup` will be able to represent a group of
# messages for multiple lines.
def merge(other)
raise ArgumentError, "Cannot merge with MessageGroup for a different line" unless same_line?(other)
@messages = (messages + other.messages).uniq
end
# Adds a message to the group.
# @param message [Markdown, Violation] the message to add
def <<(message)
# TODO: insertion sort
return nil unless same_line?(message)
inserted = false
messages.each.with_index do |other, idx|
if (message <=> other) == -1
inserted = true
messages.insert(idx, message)
break
end
end
messages << message unless inserted
messages
end
# The list of messages in this group. This list will be sorted in decreasing
# order of severity (error, warning, message, markdown)
def messages
@messages ||= []
end
attr_reader :file, :line
# @return a hash of statistics. Currently only :warnings_count and
# :errors_count
def stats
stats = { warnings_count: 0, errors_count: 0 }
messages.each do |msg|
stats[:warnings_count] += 1 if msg.type == :warning
stats[:errors_count] += 1 if msg.type == :error
end
stats
end
def markdowns
messages.select { |x| x.type == :markdown }
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/danger_core/environment_manager.rb | lib/danger/danger_core/environment_manager.rb | # frozen_string_literal: true
require "danger/ci_source/ci_source"
require "danger/request_sources/request_source"
module Danger
class EnvironmentManager
attr_accessor :ci_source, :request_source, :scm, :ui, :danger_id
# Finds a Danger::CI class based on the ENV
def self.local_ci_source(env)
return Danger::LocalOnlyGitRepo if LocalOnlyGitRepo.validates_as_ci? env
CI.available_ci_sources.find { |ci| ci.validates_as_ci? env }
end
# Uses the current Danger::CI subclass, and sees if it is a PR
def self.pr?(env)
local_ci_source(env).validates_as_pr?(env)
end
# @return [String] danger's default head branch
def self.danger_head_branch
"danger_head"
end
# @return [String] danger's default base branch
def self.danger_base_branch
"danger_base"
end
def initialize(env, ui = nil, danger_id = "danger")
ci_klass = self.class.local_ci_source(env)
self.ci_source = ci_klass.new(env)
self.ui = ui || Cork::Board.new(silent: false, verbose: false)
self.danger_id = danger_id
RequestSources::RequestSource.available_request_sources.each do |klass|
next unless self.ci_source.supports?(klass)
request_source = klass.new(self.ci_source, env)
next unless request_source.validates_as_ci?
next unless request_source.validates_as_api_source?
self.request_source = request_source
end
raise_error_for_no_request_source(env, self.ui) unless self.request_source
self.scm = self.request_source.scm
end
def pr?
self.ci_source != nil
end
def fill_environment_vars
request_source.fetch_details
end
def ensure_danger_branches_are_setup
clean_up
self.request_source.setup_danger_branches
end
def clean_up
[EnvironmentManager.danger_base_branch, EnvironmentManager.danger_head_branch].each do |branch|
scm.exec("branch -D #{branch}") unless scm.exec("rev-parse --quiet --verify #{branch}").empty?
end
end
def meta_info_for_head
scm.exec("--no-pager log #{EnvironmentManager.danger_head_branch} -n1")
end
def meta_info_for_base
scm.exec("--no-pager log #{EnvironmentManager.danger_base_branch} -n1")
end
def raise_error_for_no_request_source(env, ui)
title, subtitle = extract_title_and_subtitle_from_source(ci_source.repo_url)
subtitle += travis_note if env["TRAVIS_SECURE_ENV_VARS"] == "true"
ui_display_no_request_source_error_message(ui, env, title, subtitle)
exit(1)
end
private
def get_repo_source(repo_url)
case repo_url
when /github/i
RequestSources::GitHub
when /gitlab/i
RequestSources::GitLab
when /bitbucket\.(org|com)/i
RequestSources::BitbucketCloud
when /\.visualstudio\.com/i, /dev\.azure\.com/i
RequestSources::VSTS
end
end
def extract_title_and_subtitle_from_source(repo_url)
source = get_repo_source(repo_url)
if source
title = "For your #{source.source_name} repo, you need to expose: " + source.env_vars.join(", ").yellow
subtitle = "You may also need: #{source.optional_env_vars.join(', ')}" if source.optional_env_vars.any?
else
title = "For Danger to run on this project, you need to expose a set of following the ENV vars:\n#{RequestSources::RequestSource.available_source_names_and_envs.join("\n")}"
end
[title, subtitle || ""]
end
def ui_display_no_request_source_error_message(ui, env, title, subtitle)
ui.title "Could not set up API to Code Review site for Danger\n"
ui.puts title
ui.puts subtitle
ui.puts "\nFound these keys in your ENV: #{env.keys.join(', ')}."
ui.puts "\nFailing the build, Danger cannot run without API access."
ui.puts "You can see more information at https://danger.systems/guides/getting_started.html"
end
def travis_note
"\nTravis note: If you have an open source project, you should ensure 'Display value in build log' enabled for these flags, so that PRs from forks work." \
"\nThis also means that people can see this token, so this account should have no write access to repos."
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/danger_core/standard_error.rb | lib/danger/danger_core/standard_error.rb | # frozen_string_literal: true
require "claide"
require "claide/informative_error"
module Danger
# From below here - this entire file was taken verbatim for CocoaPods-Core.
#-------------------------------------------------------------------------#
# Wraps an exception raised by a DSL file in order to show to the user the
# contents of the line that raised the exception.
#
class DSLError < StandardError
# @return [String] the description that should be presented to the user.
#
attr_reader :description
# @return [String] the path of the dsl file that raised the exception.
#
attr_reader :dsl_path
# @return [Exception] the backtrace of the exception raised by the
# evaluation of the dsl file.
#
attr_reader :backtrace
# @param [Exception] backtrace @see backtrace
# @param [String] dsl_path @see dsl_path
#
def initialize(description, dsl_path, backtrace, contents = nil)
@description = description
@dsl_path = dsl_path
@backtrace = backtrace
@contents = contents
end
# @return [String] the contents of the DSL that cause the exception to
# be raised.
#
def contents
@contents ||= dsl_path && File.exist?(dsl_path) && File.read(dsl_path)
end
# The message of the exception reports the content of podspec for the
# line that generated the original exception.
#
# @example Output
#
# Invalid podspec at `RestKit.podspec` - undefined method
# `exclude_header_search_paths=' for #<Pod::Specification for
# `RestKit/Network (0.9.3)`>
#
# from spec-repos/master/RestKit/0.9.3/RestKit.podspec:36
# -------------------------------------------
# # because it would break: #import <CoreData/CoreData.h>
# > ns.exclude_header_search_paths = 'Code/RestKit.h'
# end
# -------------------------------------------
#
# @return [String] the message of the exception.
#
def message
@message ||= begin
description, stacktrace = parse.values_at(:description, :stacktrace)
msg = description
msg = msg.red if msg.respond_to?(:red)
msg << stacktrace if stacktrace
msg
end
end
def to_markdown
@markdown ||= begin
description, stacktrace = parse.values_at(:description, :stacktrace)
# Highlight failed method in markdown
description = description.tr("'", "`")
# Escape markdown brackets
description = description.gsub(/<|>/) { |bracket| "\\#{bracket}" }
md = +"## Danger has errored"
md << "#{description}\n"
md << "```#{stacktrace}```" if stacktrace
Markdown.new(md, nil, nil)
end
end
private
def parse
result = {}
trace_line, description = parse_line_number_from_description
latest_version = Danger.danger_outdated?
result[:description] = +"\n[!] #{description}"
result[:description] << upgrade_message(latest_version) if latest_version
return result unless backtrace && dsl_path && contents
trace_line = backtrace.find { |l| l.include?(dsl_path.to_s) } || trace_line
return result unless trace_line
line_numer = trace_line.split(":")[1].to_i - 1
return result unless line_numer
lines = contents.lines
indent = " # "
indicator = indent.tr("#", ">")
first_line = line_numer.zero?
last_line = (line_numer == (lines.count - 1))
result[:stacktrace] = +"\n"
result[:stacktrace] << "#{indent}from #{trace_line.gsub(/:in.*$/, '')}\n"
result[:stacktrace] << "#{indent}-------------------------------------------\n"
result[:stacktrace] << "#{indent}#{lines[line_numer - 1]}" unless first_line
result[:stacktrace] << "#{indicator}#{lines[line_numer]}"
result[:stacktrace] << "#{indent}#{lines[line_numer + 1]}" unless last_line
result[:stacktrace] << "\n" unless result[:stacktrace].end_with?("\n")
result[:stacktrace] << "#{indent}-------------------------------------------\n"
result
end
def parse_line_number_from_description
description = self.description
if dsl_path && description =~ /((#{Regexp.quote File.expand_path(dsl_path)}|#{Regexp.quote dsl_path.to_s}):\d+)/
trace_line = Regexp.last_match[1]
description = description.sub(/#{Regexp.quote trace_line}:\s*/, "")
end
[trace_line, description]
end
def upgrade_message(latest_version)
". Updating the Danger gem might fix the issue. "\
"Your Danger version: #{Danger::VERSION}, "\
"latest Danger version: #{latest_version}\n"
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/danger_core/message_aggregator.rb | lib/danger/danger_core/message_aggregator.rb | # frozen_string_literal: true
require "danger/danger_core/message_group"
require "danger/helpers/message_groups_array_helper"
module Danger
class MessageAggregator
def self.aggregate(*args, **kwargs)
new(*args, **kwargs).aggregate
end
def initialize(warnings: [],
errors: [],
messages: [],
markdowns: [],
danger_id: "danger")
@messages = warnings + errors + messages + markdowns
@danger_id = danger_id
end
# aggregates the messages into an array of MessageGroups
# @return [[MessageGroup]]
def aggregate
# oookay I took some shortcuts with this one.
# first, sort messages by file and line
@messages.sort! { |a, b| a.compare_by_file_and_line(b) }
# now create an initial empty message group
first_group = MessageGroup.new(file: nil,
line: nil)
@message_groups = @messages.reduce([first_group]) do |groups, msg|
# We get to take a shortcut because we sorted the messages earlier - only
# have to see if we can append msg to the last group in the list
if groups.last << msg
# we appended it, so return groups unchanged
groups
else
# have to create a new group since msg wasn't appended to the other
# group
new_group = MessageGroup.new(file: msg.file,
line: msg.line)
new_group << msg
groups << new_group
end
end
@message_groups.extend(Helpers::MessageGroupsArrayHelper)
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
danger/danger | https://github.com/danger/danger/blob/20f1243775da2ce53f55ad5ba65112de5da6e118/lib/danger/danger_core/dangerfile_generator.rb | lib/danger/danger_core/dangerfile_generator.rb | # frozen_string_literal: true
module Danger
class DangerfileGenerator
# returns the string for a Dangerfile based on a folder's contents'
def self.create_dangerfile(_path, _ui)
# Use this template for now, but this is a really ripe place to
# improve now!
dir = Danger.gem_path
File.read(File.join(dir, "lib", "assets", "DangerfileTemplate"))
end
end
end
| ruby | MIT | 20f1243775da2ce53f55ad5ba65112de5da6e118 | 2026-01-04T15:42:56.145797Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.