Class: Danger::Dangerfile

Inherits:
Object
  • Object
show all
Includes:
DSL
Defined in:
lib/danger/danger_core/dangerfile.rb,
lib/danger/danger_core/dangerfile_dsl.rb

Defined Under Namespace

Modules: DSL

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env_manager, cork_board = nil) ⇒ Dangerfile

cork_board not being set comes from plugins #585



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/danger/danger_core/dangerfile.rb', line 77

def initialize(env_manager, cork_board = nil)
  @plugins = {}
  @core_plugins = []
  @ui = cork_board || Cork::Board.new(silent: false, verbose: false)

  # Triggers the core plugins
  @env = env_manager

  # Triggers local plugins from the root of a project
  Dir["./danger_plugins/*.rb"].each do |file|
    require File.expand_path(file)
  end

  refresh_plugins if env_manager.pr?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_sym, *arguments, **keyword_arguments, &_block) ⇒ Object

When an undefined method is called, we check to see if it’s something that the core DSLs have, then starts looking at plugins support.



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/danger/danger_core/dangerfile.rb', line 63

def method_missing(method_sym, *arguments, **keyword_arguments, &_block)
  @core_plugins.each do |plugin|
    if plugin.public_methods(false).include?(method_sym)
      if keyword_arguments.empty?
        return plugin.send(method_sym, *arguments)
      else
        return plugin.send(method_sym, *arguments, **keyword_arguments)
      end
    end
  end
  super
end

Instance Attribute Details

#defined_in_filePathname

Returns the path where the Dangerfile was loaded from. It is nil if the Dangerfile was generated programmatically.

Returns:

  • (Pathname)

    the path where the Dangerfile was loaded from. It is nil if the Dangerfile was generated programmatically.



26
27
28
# File 'lib/danger/danger_core/dangerfile.rb', line 26

def defined_in_file
  @defined_in_file
end

#envObject

Returns the value of attribute env.



21
22
23
# File 'lib/danger/danger_core/dangerfile.rb', line 21

def env
  @env
end

#pluginsObject

Returns the value of attribute plugins.



21
22
23
# File 'lib/danger/danger_core/dangerfile.rb', line 21

def plugins
  @plugins
end

#uiObject

Returns the value of attribute ui.



21
22
23
# File 'lib/danger/danger_core/dangerfile.rb', line 21

def ui
  @ui
end

#verboseObject

Returns the value of attribute verbose.



21
22
23
# File 'lib/danger/danger_core/dangerfile.rb', line 21

def verbose
  @verbose
end

Class Method Details

.core_plugin_classesObject

These are the classes that are allowed to also use method_missing in order to provide broader plugin support



37
38
39
# File 'lib/danger/danger_core/dangerfile.rb', line 37

def self.core_plugin_classes
  [DangerfileMessagingPlugin]
end

.essential_plugin_classesObject

The ones that everything would break without



42
43
44
# File 'lib/danger/danger_core/dangerfile.rb', line 42

def self.essential_plugin_classes
  [DangerfileMessagingPlugin, DangerfileGitPlugin, DangerfileDangerPlugin, DangerfileGitHubPlugin, DangerfileGitLabPlugin, DangerfileBitbucketServerPlugin, DangerfileBitbucketCloudPlugin, DangerfileVSTSPlugin, DangerfileLocalOnlyPlugin]
end

Instance Method Details

#core_dsl_attributesObject



113
114
115
# File 'lib/danger/danger_core/dangerfile.rb', line 113

def core_dsl_attributes
  @core_plugins.map { |plugin| { plugin: plugin, methods: plugin.public_methods(false) } }
end

#external_dsl_attributesObject



117
118
119
# File 'lib/danger/danger_core/dangerfile.rb', line 117

def external_dsl_attributes
  plugins.values.reject { |plugin| @core_plugins.include? plugin }.map { |plugin| { plugin: plugin, methods: plugin.public_methods(false) } }
end

#fail(*args, **kargs, &blk) ⇒ Object



56
57
58
# File 'lib/danger/danger_core/dangerfile.rb', line 56

def fail(*args, **kargs, &blk)
  method_missing(:fail, *args, **kargs, &blk)
end

#failed?Boolean

Returns:

  • (Boolean)


244
245
246
# File 'lib/danger/danger_core/dangerfile.rb', line 244

def failed?
  violation_report[:errors].count > 0
end

#method_values_for_plugin_hashes(plugin_hashes) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/danger/danger_core/dangerfile.rb', line 121

def method_values_for_plugin_hashes(plugin_hashes)
  plugin_hashes.flat_map do |plugin_hash|
    plugin = plugin_hash[:plugin]
    methods = plugin_hash[:methods].select { |name| plugin.method(name).parameters.empty? }

    methods.map do |method|
      case method
      when :api
        value = "Octokit::Client"

      when :pr_json, :mr_json
        value = "[Skipped JSON]"

      when :pr_diff, :mr_diff
        value = "[Skipped Diff]"

      else
        value = plugin.send(method)
        value = wrap_text(value.encode("utf-8")) if value.kind_of?(String)
        # So that we either have one value per row
        # or we have [] for an empty array
        value = value.join("\n") if value.kind_of?(Array) && value.count > 0
      end

      [method.to_s, value]
    end
  end
end

#parse(path, contents = nil) ⇒ Object

Parses the file at a path, optionally takes the content of the file for DI



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/danger/danger_core/dangerfile.rb', line 178

def parse(path, contents = nil)
  print_known_info if verbose

  contents ||= File.open(path, "r:utf-8", &:read)

  # Work around for Rubinius incomplete encoding in 1.9 mode
  if contents.respond_to?(:encoding) && contents.encoding.name != "UTF-8"
    contents.encode!("UTF-8")
  end

  if contents.tr!("“”‘’‛", %(""'''))
    # Changes have been made
    ui.puts "Your #{path.basename} has had smart quotes sanitised. " \
      "To avoid issues in the future, you should not use " \
      "TextEdit for editing it. If you are not using TextEdit, " \
      "you should turn off smart quotes in your editor of choice.".red
  end

  if contents.include?("puts")
    ui.puts "You used `puts` in your Dangerfile. To print out text to GitHub use `message` instead"
  end

  self.defined_in_file = path
  instance_eval do
    # rubocop:disable Lint/RescueException

    eval_file(contents, path)
  rescue Exception => e
    message = "Invalid `#{path.basename}` file: #{e.message}"
    raise DSLError.new(message, path, e.backtrace, contents)

    # rubocop:enable Lint/RescueException
  end
end

#post_results(danger_id, new_comment, remove_previous_comments) ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/danger/danger_core/dangerfile.rb', line 248

def post_results(danger_id, new_comment, remove_previous_comments)
  violations = violation_report
  report = {
      warnings: violations[:warnings].uniq,
      errors: violations[:errors].uniq,
      messages: violations[:messages].uniq,
      markdowns: status_report[:markdowns].uniq,
      danger_id: danger_id
  }

  if env.request_source.respond_to?(:update_pr_by_line!) && ENV["DANGER_MESSAGE_AGGREGATION"]
    env.request_source.(message_groups: MessageAggregator.aggregate(**report),
                                          new_comment: new_comment,
                                          remove_previous_comments: remove_previous_comments,
                                          danger_id: report[:danger_id])
  else
    env.request_source.update_pull_request!(
      **report,
      new_comment: new_comment,
      remove_previous_comments: remove_previous_comments
    )
  end
end

Iterates through the DSL’s attributes, and table’s the output



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/danger/danger_core/dangerfile.rb', line 151

def print_known_info
  rows = []
  rows += method_values_for_plugin_hashes(core_dsl_attributes)
  rows << ["---", "---"]
  rows += method_values_for_plugin_hashes(external_dsl_attributes)
  rows << ["---", "---"]
  rows << ["SCM", env.scm.class]
  rows << ["Source", env.ci_source.class]
  rows << ["Requests", env.request_source.class]
  rows << ["Base Commit", env.meta_info_for_base]
  rows << ["Head Commit", env.meta_info_for_head]

  params = {}
  params[:rows] = rows.each { |current| current[0] = current[0].yellow }
  params[:title] = "Danger v#{Danger::VERSION}\nDSL Attributes".green

  ui.section("Info:") do
    ui.puts
    table = Terminal::Table.new(params)
    table.align_column(0, :right)
    ui.puts table
    ui.puts
  end
end


213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/danger/danger_core/dangerfile.rb', line 213

def print_results
  status = status_report
  violations = violation_report
  return if (violations[:errors] + violations[:warnings] + violations[:messages] + status[:markdowns]).count.zero?

  ui.section("Results:") do
    %i(errors warnings messages).each do |key|
      formatted = key.to_s.capitalize + ":"
      title = case key
              when :errors
                formatted.red
              when :warnings
                formatted.yellow
              else
                formatted
              end
      rows = violations[key].uniq
      print_list(title, rows)
    end

    if status[:markdowns].count > 0
      ui.title("Markdown:") do
        status[:markdowns].each do |current_markdown|
          ui.puts "#{current_markdown.file}\#L#{current_markdown.line}" if current_markdown.file && current_markdown.line
          ui.puts current_markdown.message
        end
      end
    end
  end
end

#refresh_pluginsObject Also known as: init_plugins

Iterate through available plugin classes and initialize them with a reference to this Dangerfile



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/danger/danger_core/dangerfile.rb', line 95

def refresh_plugins
  plugins = Plugin.all_plugins
  plugins.each do |klass|
    next if klass.respond_to?(:singleton_class?) && klass.singleton_class?

    plugin = klass.new(self)
    next if plugin.nil? || @plugins[klass]

    name = plugin.class.instance_name
    self.class.send(:attr_reader, name)
    instance_variable_set("@#{name}", plugin)

    @plugins[klass] = plugin
    @core_plugins << plugin if self.class.core_plugin_classes.include? klass
  end
end

#run(base_branch, head_branch, dangerfile_path, danger_id, new_comment, remove_previous_comments, report_results = true) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/danger/danger_core/dangerfile.rb', line 277

def run(base_branch, head_branch, dangerfile_path, danger_id, new_comment, remove_previous_comments, report_results = true)
  # Setup internal state
  init_plugins
  env.fill_environment_vars

  begin
    # Sets up the git environment
    setup_for_running(base_branch, head_branch)

    # Parse the local Dangerfile
    parse(Pathname.new(dangerfile_path))

    # Push results to the API
    # Pass along the details of the run to the request source
    # to send back to the code review site.
    post_results(danger_id, new_comment, remove_previous_comments) if report_results

    # Print results in the terminal
    print_results
  rescue DSLError => e
    # Push exception to the API and re-raise
    post_exception(e, danger_id, new_comment) unless danger_id.nil?
    raise
  ensure
    # Makes sure that Danger specific git branches are cleaned
    env.clean_up
  end

  failed?
end

#setup_for_running(base_branch, head_branch) ⇒ Object



272
273
274
275
# File 'lib/danger/danger_core/dangerfile.rb', line 272

def setup_for_running(base_branch, head_branch)
  env.ensure_danger_branches_are_setup
  env.scm.diff_for_folder(".".freeze, from: base_branch, to: head_branch, lookup_top_level: true)
end

#to_sString

Returns a string useful to represent the Dangerfile in a message presented to the user.

Returns:

  • (String)

    a string useful to represent the Dangerfile in a message presented to the user.



31
32
33
# File 'lib/danger/danger_core/dangerfile.rb', line 31

def to_s
  "Dangerfile"
end

#warn(*args, **kargs, &blk) ⇒ Object

Both of these methods exist on all objects ruby-doc.org/core-2.2.3/Kernel.html#method-i-warn 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 without overriding them.



52
53
54
# File 'lib/danger/danger_core/dangerfile.rb', line 52

def warn(*args, **kargs, &blk)
  method_missing(:warn, *args, **kargs, &blk)
end