gitlab-triage 1.56.2 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,8 +11,9 @@ module Gitlab
11
11
  # Applies work_items actions through the Work Items REST API update
12
12
  # endpoint (PATCH) rather than the issues note/quick-action path.
13
13
  #
14
- # - labels -> features.labels.add_label_ids (resolved from names)
15
- # - assignees -> features.assignees.assignee_ids (resolved from usernames)
14
+ # - labels -> features.labels.add_label_ids (resolved from names)
15
+ # - remove_labels -> features.labels.remove_label_ids (resolved from names)
16
+ # - assignees -> features.assignees.assignee_ids (resolved from usernames)
16
17
  #
17
18
  # Missing labels or usernames stop the automation immediately (matching
18
19
  # the labels action behaviour on the issues type) rather than silently
@@ -21,9 +22,8 @@ module Gitlab
21
22
  class WorkItem < Base
22
23
  UpdateNotAppliedError = Class.new(StandardError)
23
24
 
24
- # The dry run must not touch the network. It prints the requested
25
- # label names and assignee usernames rather than resolving them to
26
- # ids, mirroring how Comment::Dry avoids network calls.
25
+ # Prints the requested changes without writing them. verify! still
26
+ # looks the names up first, so a typo fails the dry run too.
27
27
  class Dry < WorkItem
28
28
  def act
29
29
  puts "The following work items would be updated for the rule **#{policy.name}**:\n\n"
@@ -36,13 +36,25 @@ module Gitlab
36
36
  def perform(resource)
37
37
  puts "# #{resource[:web_url]}"
38
38
  puts "Would add labels: #{requested_labels.join(', ')}" if requested_labels.any?
39
+ puts "Would remove labels: #{requested_removed_labels.join(', ')}" if requested_removed_labels.any?
39
40
  puts "Would assign: #{requested_assignees.join(', ')}" if requested_assignees.any?
40
41
  puts "\n"
41
42
  end
42
43
  end
43
44
 
45
+ # Resolves every item's labels and assignees up front, so a name missing
46
+ # in a later item's namespace fails the run before any item is labeled.
47
+ def verify!
48
+ policy.resources.each do |resource|
49
+ label_ids_to_add(resource) if requested_labels.any?
50
+ label_ids_to_remove(resource) if requested_removed_labels.any?
51
+ end
52
+
53
+ assignee_ids if requested_assignees.any?
54
+ end
55
+
44
56
  def act
45
- return unless requested_labels.any? || requested_assignees.any?
57
+ return unless requested_labels.any? || requested_removed_labels.any? || requested_assignees.any?
46
58
 
47
59
  policy.resources.each do |resource|
48
60
  perform(resource)
@@ -63,7 +75,11 @@ module Gitlab
63
75
  def build_features(resource)
64
76
  features = {}
65
77
 
66
- features[:labels] = { add_label_ids: label_ids_to_add(resource) } if requested_labels.any?
78
+ label_changes = {}
79
+ label_changes[:add_label_ids] = label_ids_to_add(resource) if requested_labels.any?
80
+ label_changes[:remove_label_ids] = label_ids_to_remove(resource) if requested_removed_labels.any?
81
+ features[:labels] = label_changes if label_changes.any?
82
+
67
83
  features[:assignees] = { assignee_ids: assignee_ids } if requested_assignees.any?
68
84
 
69
85
  features
@@ -73,6 +89,10 @@ module Gitlab
73
89
  @requested_labels ||= Array(policy.actions[:labels])
74
90
  end
75
91
 
92
+ def requested_removed_labels
93
+ @requested_removed_labels ||= Array(policy.actions[:remove_labels])
94
+ end
95
+
76
96
  def requested_assignees
77
97
  @requested_assignees ||= Array(policy.actions[:assignees])
78
98
  end
@@ -82,14 +102,16 @@ module Gitlab
82
102
  network: network, options: network.options)
83
103
  end
84
104
 
85
- # Label ids are namespace-specific, so resolve them against the
86
- # resource's own namespace and cache per scope - a group-spanning run
87
- # then makes one label lookup per distinct project/group.
105
+ # Label ids are namespace-specific, so resolve against the resource's
106
+ # own namespace. The fetched label list is cached per scope, so a rule
107
+ # that both adds and removes labels - or a group-spanning run - makes
108
+ # one lookup per distinct project/group.
88
109
  def label_ids_to_add(resource)
89
- scope = source.scope_for(resource)
110
+ resolve_label_ids(requested_labels, source.scope_for(resource))
111
+ end
90
112
 
91
- @label_ids_by_scope ||= {}
92
- @label_ids_by_scope[scope] ||= resolve_label_ids(requested_labels, scope)
113
+ def label_ids_to_remove(resource)
114
+ resolve_label_ids(requested_removed_labels, source.scope_for(resource))
93
115
  end
94
116
 
95
117
  def assignee_ids
@@ -102,7 +124,7 @@ module Gitlab
102
124
  def resolve_label_ids(names, scope)
103
125
  return [] if names.empty?
104
126
 
105
- by_name = network.query_api(labels_url(scope)).index_by { |label| label[:name] }
127
+ by_name = labels_by_name(scope)
106
128
 
107
129
  names.map do |name|
108
130
  label = by_name[name]
@@ -112,24 +134,41 @@ module Gitlab
112
134
  end
113
135
  end
114
136
 
137
+ def labels_by_name(scope)
138
+ @labels_by_name_by_scope ||= {}
139
+ @labels_by_name_by_scope[scope] ||= network.query_api_cached(labels_url(scope)).index_by { |label| label[:name] }
140
+ end
141
+
115
142
  # The Work Items REST update endpoint can return success without
116
143
  # persisting a change when the token lacks permission. The response
117
144
  # echoes the resulting widgets, so confirm the requested ids landed and
118
145
  # raise otherwise rather than reporting a silent no-op as success.
119
146
  def verify_applied!(resource, response)
120
147
  verify_labels_applied!(resource, response) if requested_labels.any?
148
+ verify_labels_removed!(resource, response) if requested_removed_labels.any?
121
149
  verify_assignees_applied!(resource, response) if requested_assignees.any?
122
150
  end
123
151
 
124
152
  def verify_labels_applied!(resource, response)
125
- applied_ids = [*response.dig(:features, :labels, :labels)].pluck(:id)
126
- missing = label_ids_to_add(resource) - applied_ids
153
+ missing = label_ids_to_add(resource) - applied_label_ids(response)
127
154
  return if missing.empty?
128
155
 
129
156
  raise UpdateNotAppliedError,
130
157
  "Labels were not applied to #{resource[:web_url]}; the token may lack permission."
131
158
  end
132
159
 
160
+ def verify_labels_removed!(resource, response)
161
+ still_present = label_ids_to_remove(resource) & applied_label_ids(response)
162
+ return if still_present.empty?
163
+
164
+ raise UpdateNotAppliedError,
165
+ "Labels were not removed from #{resource[:web_url]}; the token may lack permission."
166
+ end
167
+
168
+ def applied_label_ids(response)
169
+ [*response.dig(:features, :labels, :labels)].pluck(:id)
170
+ end
171
+
133
172
  def verify_assignees_applied!(resource, response)
134
173
  applied_ids = [*response.dig(:features, :assignees)].pluck(:id)
135
174
  missing = assignee_ids - applied_ids
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'comment'
4
+ require_relative '../sources/work_items_rest_source'
5
+
6
+ module Gitlab
7
+ module Triage
8
+ module Action
9
+ # Posts comments on work items through the Work Items REST API notes
10
+ # endpoint rather than the issues note/quick-action path. The comment body
11
+ # (templating, redaction, and mentions) is built exactly as on the issues
12
+ # type - only the write target differs, so this reuses Comment and
13
+ # overrides just where the note is sent.
14
+ class WorkItemComment < Comment
15
+ # WorkItem writes labels before this posts, so reject an unknown
16
+ # comment_type up front rather than after the labels are written.
17
+ def verify!
18
+ sub_resource_type
19
+ end
20
+
21
+ private
22
+
23
+ # Raising would also lose every later item's note, and any labels are
24
+ # already written. Warn and move on, as issues drop a rejected note.
25
+ def perform(resource, comment)
26
+ print_debug(resource, comment)
27
+ source.create_note(resource, post_body(comment), sub_resource_type: sub_resource_type)
28
+ rescue Sources::WorkItemsRestSource::NoteNotCreatedError => e
29
+ puts Gitlab::Triage::UI.warn(e.message)
30
+ end
31
+
32
+ def source
33
+ @source ||= Sources::WorkItemsRestSource.new(
34
+ network: network, options: network.options)
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -7,6 +7,7 @@ require_relative 'action/issue'
7
7
  require_relative 'action/delete'
8
8
  require_relative 'action/work_item_status'
9
9
  require_relative 'action/work_item'
10
+ require_relative 'action/work_item_comment'
10
11
  require_relative 'action/update'
11
12
 
12
13
  module Gitlab
@@ -24,10 +25,9 @@ module Gitlab
24
25
  end
25
26
  end
26
27
 
27
- # Comment runs before the actions that write labels, so without this a
28
- # rule naming a label, user, milestone, or move destination that no
29
- # longer exists posts its note and only then raises, and the next
30
- # scheduled run posts it again.
28
+ # Without this, a rule naming a label, user, milestone, or move
29
+ # destination that no longer exists raises only after earlier actions
30
+ # wrote, such as an issues note the next scheduled run posts again.
31
31
  def self.verify!(actions, policy:, network:)
32
32
  actions.each do |action|
33
33
  action.new(policy: policy, network: network).verify!
@@ -36,13 +36,17 @@ module Gitlab
36
36
 
37
37
  # Work items are fetched and updated through the Work Items REST API,
38
38
  # which does not share the issues note/quick-action write path. Their
39
- # actions (assign, label, comment) are handled by a dedicated action
40
- # instead of the note-based Comment action.
39
+ # actions are handled by dedicated actions: WorkItem (assign, label) and
40
+ # WorkItemComment, which posts through the REST notes endpoint rather than
41
+ # the issues Comment path. Unlike issues, labels are written before the
42
+ # note: a failed label write then loses a note once, instead of leaving
43
+ # unlabeled items that get the note again on every run.
41
44
  def self.actions_for(policy)
42
45
  if policy.type == 'work_items'
43
46
  [
44
47
  [Summarize, policy.summarize?],
45
48
  [WorkItem, policy.work_item?],
49
+ [WorkItemComment, policy.comment?],
46
50
  [CommentOnSummary, policy.comment_on_summary?]
47
51
  ]
48
52
  else
@@ -33,6 +33,7 @@ require_relative 'rest_api_network'
33
33
  require_relative 'network_adapters/httparty_adapter'
34
34
  require_relative 'network_adapters/graphql_adapter'
35
35
  require_relative 'graphql_queries/query_builder'
36
+ require_relative 'milestone_wildcards'
36
37
  require_relative 'sources/work_items_rest_source'
37
38
  require_relative 'validators/params_validator'
38
39
  require_relative 'validators/policy_validator'
@@ -47,6 +48,8 @@ module Gitlab
47
48
  # This filter map is used to help make the filter_resource method
48
49
  # smaller. We loop through each of the keys (conditions) and map
49
50
  # that to the filters that will be used for it.
51
+ # A filter enabled for work_items must also be added to
52
+ # Validators::PolicyValidator::RUBY_WORK_ITEM_CONDITIONS.
50
53
  FILTER_MAP = {
51
54
  date: {
52
55
  'branches' => Filters::BranchDateFilter,
@@ -70,9 +73,9 @@ module Gitlab
70
73
  ALLOWED_STATE_VALUES = {
71
74
  issues: %w[opened closed],
72
75
  merge_requests: %w[opened closed merged],
73
- work_items: %w[opened closed]
76
+ work_items: Validators::PolicyValidator::WORK_ITEM_STATES
74
77
  }.with_indifferent_access.freeze
75
- MILESTONE_TIMEBOX_VALUES = %w[none any upcoming started].freeze
78
+ MILESTONE_TIMEBOX_VALUES = MilestoneWildcards::VALUES
76
79
  ITERATION_SELECTION_VALUES = %w[none any].freeze
77
80
  EpicsTriagingForProjectImpossibleError = Class.new(StandardError)
78
81
  MultiPolicyInInjectionModeError = Class.new(StandardError)
@@ -515,14 +518,8 @@ module Gitlab
515
518
  conditions = expanded_conditions.dup
516
519
  conditions[:iids] = options.resource_reference[1..] if options.resource_reference
517
520
 
518
- # The work_items path bypasses build_get_url, so validate `state` here
519
- # the same way the URL builders do for the other resource types.
520
- if conditions[:state]
521
- ParamsValidator.new(
522
- [{ name: 'state', type: String, values: ALLOWED_STATE_VALUES[:work_items] }],
523
- { 'state' => conditions[:state] }).validate!
524
- end
525
-
521
+ # The work_items path bypasses build_get_url, so `state` is not checked by
522
+ # the URL builders. PolicyValidator checks it in #perform before any fetch.
526
523
  work_items_source.list(conditions)
527
524
  end
528
525
 
@@ -679,12 +676,8 @@ module Gitlab
679
676
  return if milestone_value.empty?
680
677
 
681
678
  # Issues API should use the `milestone_id` param for timebox values, and `milestone` for milestone title
682
- args =
683
- if resource_type.to_sym == :issues && MILESTONE_TIMEBOX_VALUES.include?(milestone_value.downcase)
684
- ['milestone_id', milestone_value.titleize] # The API only accepts titleized values.
685
- else
686
- ['milestone', milestone_value]
687
- end
679
+ wildcard = MilestoneWildcards.api_value(milestone_value) if resource_type.to_sym == :issues
680
+ args = wildcard ? ['milestone_id', wildcard] : ['milestone', milestone_value]
688
681
 
689
682
  APIQueryBuilders::SingleQueryParamBuilder.new(*args)
690
683
  end
@@ -730,7 +723,7 @@ module Gitlab
730
723
  end
731
724
 
732
725
  def draft_condition_builder(draft_condittion)
733
- # Issues API only accepts 'yes' and 'no' as strings: https://docs.gitlab.com/ee/api/merge_requests.html
726
+ # Issues API only accepts 'yes' and 'no' as strings: https://docs.gitlab.com/api/merge_requests/
734
727
  wip =
735
728
  case draft_condittion
736
729
  when true
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_support/core_ext/string/inflections'
4
+
5
+ module Gitlab
6
+ module Triage
7
+ # Milestone condition values that select a group of milestones rather than one
8
+ # title. Kept apart from Engine so the work items source and the policy validator
9
+ # can share it: Engine requires both of them.
10
+ module MilestoneWildcards
11
+ VALUES = %w[none any upcoming started].freeze
12
+
13
+ # The Issues API (milestone_id) and the Work Items API (milestone_wildcard_id)
14
+ # only accept the capitalised form, for example Started. Returns nil for a title.
15
+ def self.api_value(milestone)
16
+ value = milestone.to_s.downcase
17
+
18
+ value.titleize if VALUES.include?(value)
19
+ end
20
+ end
21
+ end
22
+ end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'active_support/core_ext/object/blank'
4
+
3
5
  require_relative '../version'
4
6
 
5
7
  module Gitlab
@@ -14,6 +16,21 @@ module Gitlab
14
16
  @options = options
15
17
  @tracker = tracker
16
18
  end
19
+
20
+ private
21
+
22
+ # When the rate-limit headers are absent (e.g. a server that doesn't send
23
+ # them), treat the limit as not-a-concern rather than coercing a missing
24
+ # header to 0/1970, which would otherwise trip rate_limit_wait.
25
+ def rate_limit_remaining(headers)
26
+ value = headers['ratelimit-remaining']
27
+ value.present? ? value.to_i : Float::INFINITY
28
+ end
29
+
30
+ def rate_limit_reset_at(headers)
31
+ value = headers['ratelimit-reset']
32
+ Time.at(value.to_i) if value.present?
33
+ end
17
34
  end
18
35
  end
19
36
  end
@@ -58,14 +58,9 @@ module Gitlab
58
58
 
59
59
  raise_on_error!(response)
60
60
 
61
- parsed_response = response.data
62
61
  headers = response.extensions.fetch('headers', {})
63
62
 
64
- {
65
- ratelimit_remaining: headers['ratelimit-remaining'].to_i,
66
- ratelimit_reset_at: Time.at(headers['ratelimit-reset'].to_i),
67
- results: parsed_response.to_h
68
- }
63
+ build_graphql_response(response.data.to_h, headers)
69
64
  end
70
65
 
71
66
  delegate :parse, to: :client
@@ -96,19 +91,6 @@ module Gitlab
96
91
  end
97
92
  end
98
93
 
99
- # When the rate-limit headers are absent (e.g. a server that doesn't send
100
- # them), treat the limit as not-a-concern rather than coercing a missing
101
- # header to 0/1970, which would otherwise trip rate_limit_wait.
102
- def rate_limit_remaining(headers)
103
- value = headers['ratelimit-remaining']
104
- value.present? ? value.to_i : Float::INFINITY
105
- end
106
-
107
- def rate_limit_reset_at(headers)
108
- value = headers['ratelimit-reset']
109
- Time.at(value.to_i) if value.present?
110
- end
111
-
112
94
  # Converts a parsed GraphQL::Client response node into plain Ruby so the
113
95
  # shared builder only ever deals with Hash/Array, never client objects.
114
96
  def plain_node(parsed_response)
@@ -28,8 +28,8 @@ module Gitlab
28
28
  more_pages: (response.headers["x-next-page"].to_s != ""),
29
29
  next_page_url: next_page_url(url, response),
30
30
  results: response.parsed_response,
31
- ratelimit_remaining: response.headers["ratelimit-remaining"].to_i,
32
- ratelimit_reset_at: Time.at(response.headers["ratelimit-reset"].to_i)
31
+ ratelimit_remaining: rate_limit_remaining(response.headers),
32
+ ratelimit_reset_at: rate_limit_reset_at(response.headers)
33
33
  }
34
34
 
35
35
  resource_count = result[:results].is_a?(Array) ? result[:results].size : 0
@@ -57,8 +57,8 @@ module Gitlab
57
57
 
58
58
  {
59
59
  results: response.parsed_response,
60
- ratelimit_remaining: response.headers["ratelimit-remaining"].to_i,
61
- ratelimit_reset_at: Time.at(response.headers["ratelimit-reset"].to_i)
60
+ ratelimit_remaining: rate_limit_remaining(response.headers),
61
+ ratelimit_reset_at: rate_limit_reset_at(response.headers)
62
62
  }
63
63
  end
64
64
 
@@ -81,8 +81,8 @@ module Gitlab
81
81
 
82
82
  {
83
83
  results: response.parsed_response,
84
- ratelimit_remaining: response.headers['ratelimit-remaining'].to_i,
85
- ratelimit_reset_at: Time.at(response.headers['ratelimit-reset'].to_i)
84
+ ratelimit_remaining: rate_limit_remaining(response.headers),
85
+ ratelimit_reset_at: rate_limit_reset_at(response.headers)
86
86
  }
87
87
  end
88
88
 
@@ -105,8 +105,8 @@ module Gitlab
105
105
 
106
106
  {
107
107
  results: response.parsed_response,
108
- ratelimit_remaining: response.headers['ratelimit-remaining'].to_i,
109
- ratelimit_reset_at: Time.at(response.headers['ratelimit-reset'].to_i)
108
+ ratelimit_remaining: rate_limit_remaining(response.headers),
109
+ ratelimit_reset_at: rate_limit_reset_at(response.headers)
110
110
  }
111
111
  end
112
112
 
@@ -126,9 +126,10 @@ module Gitlab
126
126
  tracker&.record('DELETE', url)
127
127
 
128
128
  {
129
+ status: response.code,
129
130
  results: response.parsed_response,
130
- ratelimit_remaining: response.headers["ratelimit-remaining"].to_i,
131
- ratelimit_reset_at: Time.at(response.headers["ratelimit-reset"].to_i)
131
+ ratelimit_remaining: rate_limit_remaining(response.headers),
132
+ ratelimit_reset_at: rate_limit_reset_at(response.headers)
132
133
  }
133
134
  end
134
135
 
@@ -27,10 +27,22 @@ module Gitlab
27
27
  confidential: resource[:confidential],
28
28
  created_at: resource[:created_at],
29
29
  updated_at: resource[:updated_at],
30
+ closed_at: resource[:closed_at],
30
31
  author: resource[:author],
32
+ closed_by: resource[:closed_by],
33
+ # Same shape as the Issues API, which full_resource_reference and
34
+ # the {{full_reference}} placeholder read.
35
+ references: ({ full: resource[:reference] } if resource[:reference]),
31
36
  labels: label_titles(features),
32
37
  assignees: assignees(features),
38
+ # The issues API's deprecated single assignee, read by {{assignee}}.
39
+ assignee: assignees(features).first,
33
40
  milestone: features[:milestone],
41
+ upvotes: features.dig(:award_emoji, :upvotes),
42
+ downvotes: features.dig(:award_emoji, :downvotes),
43
+ # Flat string, like the Issues API: ruby conditions compare
44
+ # resource[:health_status] with values such as 'at_risk'.
45
+ health_status: features.dig(:health_status, :health_status),
34
46
  work_item_type: resource.dig(:work_item_type, :name),
35
47
  work_item_status: status_name(features),
36
48
  start_date: features.dig(:start_and_due_date, :start_date),
@@ -74,10 +74,10 @@ module Gitlab
74
74
  end
75
75
 
76
76
  opts.on('--cache-dir [string]', String,
77
- 'Directory containing pre-fetched API responses. ' \
78
- 'Files must follow the naming convention: <source>_<id>_<resource>.json ' \
79
- '(e.g. groups_9970_members.json). ' \
80
- 'Can also be set via the GITLAB_TRIAGE_CACHE_DIR environment variable.') do |value|
77
+ 'Directory containing pre-fetched API responses.',
78
+ 'Files must follow the naming convention: <source>_<id>_<resource>.json',
79
+ '(e.g. groups_9970_members.json).',
80
+ 'Can also be set via the GITLAB_TRIAGE_CACHE_DIR environment variable.') do |value|
81
81
  options.cache_dir = value
82
82
  end
83
83
 
@@ -80,7 +80,7 @@ module Gitlab
80
80
  end
81
81
 
82
82
  def work_item?
83
- (actions.keys.map(&:to_sym) & %i[labels assignees]).any?
83
+ (actions.keys.map(&:to_sym) & %i[labels remove_labels assignees]).any?
84
84
  end
85
85
 
86
86
  def build_issue
@@ -147,6 +147,7 @@ module Gitlab
147
147
 
148
148
  rate_limit_debug(response) if options.debug
149
149
  rate_limit_wait(response)
150
+ warn_on_failed_delete(url, response)
150
151
  end
151
152
 
152
153
  private
@@ -210,9 +211,27 @@ module Gitlab
210
211
  def rate_limit_wait(response)
211
212
  return unless response.delete(:ratelimit_remaining) < MINIMUM_RATE_LIMIT
212
213
 
213
- puts Gitlab::Triage::UI.debug "Rate limit almost exceeded, sleeping for #{response[:ratelimit_reset_at] - Time.now} seconds" if options.debug
214
+ reset_at = response[:ratelimit_reset_at]
215
+ return unless reset_at
216
+
217
+ puts Gitlab::Triage::UI.debug "Rate limit almost exceeded, sleeping for #{reset_at - Time.now} seconds" if options.debug
214
218
  @adapter.tracker&.record_rate_limit_wait
215
- sleep(1) until Time.now >= response[:ratelimit_reset_at]
219
+ sleep(1) until Time.now >= reset_at
220
+ end
221
+
222
+ # Warns rather than raises, so one refused DELETE does not stop the
223
+ # other deletions of the rule.
224
+ def warn_on_failed_delete(url, response)
225
+ status = response[:status]
226
+ return if status.nil? || (200..299).cover?(status)
227
+
228
+ results = response[:results]
229
+ message = results['message'] || results['error'] if results.is_a?(Hash)
230
+
231
+ warning = "DELETE #{url} failed with status #{status}"
232
+ warning += ": #{message}" if message
233
+
234
+ puts Gitlab::Triage::UI.warn(warning)
216
235
  end
217
236
 
218
237
  def raise_unexpected_response(results)