Class: Dependabot::Clients::Azure

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Includes:
JsonResponseParser
Defined in:
lib/dependabot/clients/azure.rb

Overview

rubocop:disable Metrics/ClassLength

Defined Under Namespace

Classes: BadGateway, Forbidden, InternalServerError, NotFound, ServiceNotAvailable, TagsCreationForbidden, Unauthorized

Constant Summary collapse

JsonObject =
T.type_alias { JsonResponseParser::JsonObject }
JsonObjects =
T.type_alias { T::Array[JsonObject] }
RETRYABLE_ERRORS =
T.let(
  [InternalServerError, BadGateway, ServiceNotAvailable].freeze,
  T::Array[T.class_of(StandardError)]
)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, credentials, max_retries: 3) ⇒ Azure

Returns a new instance of Azure.



64
65
66
67
68
69
# File 'lib/dependabot/clients/azure.rb', line 64

def initialize(source, credentials, max_retries: 3)
  @source = source
  @credentials = credentials
  @auth_header = T.let(auth_header_for(credentials&.fetch("token", nil)), T::Hash[String, String])
  @max_retries = T.let(max_retries || 3, Integer)
end

Class Method Details

.for_source(source:, credentials:) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/dependabot/clients/azure.rb', line 43

def self.for_source(source:, credentials:)
  credential =
    credentials
    .select { |cred| cred["type"] == "git_source" }
    .find { |cred| cred["host"] == source.hostname }

  new(source, credential)
end

Instance Method Details

#autocomplete_pull_request(pull_request_id, auto_complete_set_by, merge_commit_message, delete_source_branch = true, squash_merge = true, merge_strategy = "squash", trans_work_items = true, ignore_config_ids = []) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/dependabot/clients/azure.rb', line 301

def autocomplete_pull_request(
  pull_request_id,
  auto_complete_set_by,
  merge_commit_message,
  delete_source_branch = true,
  squash_merge = true,
  merge_strategy = "squash",
  trans_work_items = true,
  ignore_config_ids = []
)
  content = {
    autoCompleteSetBy: {
      id: auto_complete_set_by
    },
    completionOptions: {
      mergeCommitMessage: merge_commit_message,
      deleteSourceBranch: delete_source_branch,
      squashMerge: squash_merge,
      mergeStrategy: merge_strategy,
      transitionWorkItems: trans_work_items,
      autoCompleteIgnoreConfigIds: ignore_config_ids
    }
  }

  response = patch(
    T.must(source.api_endpoint) +
                               source.organization + "/" + source.project +
                               "/_apis/git/repositories/" + source.unscoped_repo +
                               "/pullrequests/" + pull_request_id.to_s + "?api-version=5.1",
    content.to_json
  )

  parse_json_object(response.body, "pull request autocomplete")
end

#branch(branch_name) ⇒ Object



171
172
173
174
175
176
177
178
179
180
181
# File 'lib/dependabot/clients/azure.rb', line 171

def branch(branch_name)
  response = get(
    T.must(source.api_endpoint) +
              source.organization + "/" + source.project +
              "/_apis/git/repositories/" + source.unscoped_repo +
              "/refs?filter=heads/" + branch_name
  )

  root = parse_json_object(response.body, "branch")
  object_array_field(root, "value", "branch").first
end

#commits(branch_name = nil) ⇒ Object



156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/dependabot/clients/azure.rb', line 156

def commits(branch_name = nil)
  commits_url = T.must(source.api_endpoint) +
                source.organization + "/" + source.project +
                "/_apis/git/repositories/" + source.unscoped_repo +
                "/commits"

  commits_url += "?searchCriteria.itemVersion.version=" + T.must(branch_name) unless branch_name.to_s.empty?

  response = get(commits_url)

  root = parse_json_object(response.body, "commits")
  object_array_field(root, "value", "commits")
end

#compare(previous_tag, new_tag, type) ⇒ Object



377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/dependabot/clients/azure.rb', line 377

def compare(previous_tag, new_tag, type)
  response = get(
    T.must(source.api_endpoint) +
                             source.organization + "/" + source.project +
                             "/_apis/git/repositories/" + source.unscoped_repo +
                             "/commits?searchCriteria.itemVersion.versionType=#{type}" \
                             "&searchCriteria.itemVersion.version=#{previous_tag}" \
                             "&searchCriteria.compareVersion.versionType=#{type}" \
                             "&searchCriteria.compareVersion.version=#{new_tag}"
  )

  root = parse_json_object(response.body, "commit comparison")
  object_array_field(root, "value", "commit comparison")
end

#create_commit(branch_name, base_commit, commit_message, files, author_details) ⇒ Object



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/dependabot/clients/azure.rb', line 208

def create_commit(
  branch_name,
  base_commit,
  commit_message,
  files,
  author_details
)
  content = {
    refUpdates: [
      { name: "refs/heads/" + branch_name, oldObjectId: base_commit }
    ],
    commits: [
      {
        comment: commit_message,
        author: author_details,
        changes: files.map do |file|
          {
            changeType: "edit",
            item: { path: file.path },
            newContent: {
              content: Base64.encode64(T.must(file.content)),
              contentType: "base64encoded"
            }
          }
        end
      }.compact
    ]
  }

  post(
    T.must(source.api_endpoint) + source.organization + "/" + source.project +
              "/_apis/git/repositories/" + source.unscoped_repo +
              "/pushes?api-version=5.0",
    content.to_json
  )
end

#create_pull_request(pr_name, source_branch, target_branch, pr_description, labels, reviewers = nil, assignees = nil, work_item = nil) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/dependabot/clients/azure.rb', line 259

def create_pull_request(
  pr_name,
  source_branch,
  target_branch,
  pr_description,
  labels,
  reviewers = nil,
  assignees = nil,
  work_item = nil
)
  content = {
    sourceRefName: "refs/heads/" + source_branch,
    targetRefName: "refs/heads/" + target_branch,
    title: pr_name,
    description: pr_description,
    labels: labels.map { |label| { name: label } },
    reviewers: pr_reviewers(reviewers, assignees),
    workItemRefs: [{ id: work_item }]
  }

  post(
    T.must(source.api_endpoint) +
              source.organization + "/" + source.project +
              "/_apis/git/repositories/" + source.unscoped_repo +
              "/pullrequests?api-version=5.0",
    content.to_json
  )
end

#fetch_commit(_repo, branch) ⇒ Object

Raises:



72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/dependabot/clients/azure.rb', line 72

def fetch_commit(_repo, branch)
  response = get(
    T.must(source.api_endpoint) +
              source.organization + "/" + source.project +
              "/_apis/git/repositories/" + source.unscoped_repo +
              "/stats/branches?name=" + branch
  )

  raise NotFound if response.status == 400

  root = parse_json_object(response.body, "branch stats")
  commit = object_field(root, "commit", "branch stats")
  string_field(commit, "commitId", "branch stats")
end

#fetch_default_branch(_repo) ⇒ Object



88
89
90
91
92
93
94
95
96
97
# File 'lib/dependabot/clients/azure.rb', line 88

def fetch_default_branch(_repo)
  response = get(
    T.must(source.api_endpoint) +
              source.organization + "/" + source.project +
              "/_apis/git/repositories/" + source.unscoped_repo
  )

  root = parse_json_object(response.body, "repository")
  string_field(root, "defaultBranch", "repository").gsub("refs/heads/", "")
end

#fetch_file_contents(commit, path) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/dependabot/clients/azure.rb', line 142

def fetch_file_contents(commit, path)
  response = get(
    T.must(source.api_endpoint) +
              source.organization + "/" + source.project +
              "/_apis/git/repositories/" + source.unscoped_repo +
              "/items?path=" + path +
              "&versionDescriptor.versionType=commit" \
              "&versionDescriptor.version=" + commit
  )

  response.body
end

#fetch_repo_contents(commit = nil, path = nil) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/dependabot/clients/azure.rb', line 106

def fetch_repo_contents(commit = nil, path = nil)
  tree = fetch_repo_contents_treeroot(commit, path)

  response = get(
    T.must(source.api_endpoint) +
              source.organization + "/" + source.project +
              "/_apis/git/repositories/" + source.unscoped_repo +
              "/trees/" + tree + "?recursive=false"
  )

  root = parse_json_object(response.body, "repository tree")
  object_array_field(root, "treeEntries", "repository tree")
end

#fetch_repo_contents_treeroot(commit = nil, path = nil) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/dependabot/clients/azure.rb', line 121

def fetch_repo_contents_treeroot(commit = nil, path = nil)
  actual_path = path
  actual_path = "/" if path.to_s.empty?

  tree_url = T.must(source.api_endpoint) +
             source.organization + "/" + source.project +
             "/_apis/git/repositories/" + source.unscoped_repo +
             "/items?path=" + T.must(actual_path)

  unless commit.to_s.empty?
    tree_url += "&versionDescriptor.versionType=commit" \
                "&versionDescriptor.version=" + T.must(commit)
  end

  tree_response = get(tree_url)

  root = parse_json_object(tree_response.body, "repository item")
  string_field(root, "objectId", "repository item")
end

#get(url) ⇒ Object

Raises:



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/dependabot/clients/azure.rb', line 393

def get(url)
  response = T.let(nil, T.nilable(Excon::Response))

  retry_connection_failures do
    response = Excon.get(
      url,
      user: credentials&.fetch("username", nil),
      password: credentials&.fetch("password", nil),
      idempotent: true,
      **SharedHelpers.excon_defaults(
        headers: auth_header
      )
    )

    raise InternalServerError if response.status == 500
    raise BadGateway if response.status == 502
    raise ServiceNotAvailable if response.status == 503
  end

  raise Unauthorized if response&.status == 401
  raise Forbidden if response&.status == 403
  raise NotFound if response&.status == 404

  T.must(response)
end

#patch(url, json) ⇒ Object

Raises:



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/dependabot/clients/azure.rb', line 457

def patch(url, json)
  response = T.let(nil, T.nilable(Excon::Response))

  retry_connection_failures do
    response = Excon.patch(
      url,
      body: json,
      user: credentials&.fetch("username", nil),
      password: credentials&.fetch("password", nil),
      idempotent: true,
      **SharedHelpers.excon_defaults(
        headers: auth_header.merge(
          {
            "Content-Type" => "application/json"
          }
        )
      )
    )

    raise InternalServerError if response&.status == 500
    raise BadGateway if response&.status == 502
    raise ServiceNotAvailable if response&.status == 503
  end

  raise Unauthorized if response&.status == 401
  raise Forbidden if response&.status == 403
  raise NotFound if response&.status == 404

  T.must(response)
end

#post(url, json) ⇒ Object

rubocop:disable Metrics/PerceivedComplexity

Raises:



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# File 'lib/dependabot/clients/azure.rb', line 420

def post(url, json) # rubocop:disable Metrics/PerceivedComplexity
  response = T.let(nil, T.nilable(Excon::Response))

  retry_connection_failures do
    response = Excon.post(
      url,
      body: json,
      user: credentials&.fetch("username", nil),
      password: credentials&.fetch("password", nil),
      idempotent: true,
      **SharedHelpers.excon_defaults(
        headers: auth_header.merge(
          {
            "Content-Type" => "application/json"
          }
        )
      )
    )

    raise InternalServerError if response&.status == 500
    raise BadGateway if response&.status == 502
    raise ServiceNotAvailable if response&.status == 503
  end

  raise Unauthorized if response&.status == 401

  if response&.status == 403
    raise TagsCreationForbidden if tags_creation_forbidden?(T.must(response))

    raise Forbidden
  end
  raise NotFound if response&.status == 404

  T.must(response)
end

#pull_request(pull_request_id) ⇒ Object



337
338
339
340
341
342
343
344
345
# File 'lib/dependabot/clients/azure.rb', line 337

def pull_request(pull_request_id)
  response = get(
    T.must(source.api_endpoint) +
              source.organization + "/" + source.project +
              "/_apis/git/pullrequests/" + pull_request_id
  )

  parse_json_object(response.body, "pull request")
end

#pull_requests(source_branch, target_branch) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/dependabot/clients/azure.rb', line 184

def pull_requests(source_branch, target_branch)
  response = get(
    T.must(source.api_endpoint) +
              source.organization + "/" + source.project +
              "/_apis/git/repositories/" + source.unscoped_repo +
              "/pullrequests?searchCriteria.status=all" \
              "&searchCriteria.sourceRefName=refs/heads/" + source_branch +
              "&searchCriteria.targetRefName=refs/heads/" + target_branch
  )

  root = parse_json_object(response.body, "pull requests")
  object_array_field(root, "value", "pull requests")
end

#update_ref(branch_name, old_commit, new_commit) ⇒ Object



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# File 'lib/dependabot/clients/azure.rb', line 348

def update_ref(branch_name, old_commit, new_commit)
  content = [
    {
      name: "refs/heads/" + branch_name,
      oldObjectId: old_commit,
      newObjectId: new_commit
    }
  ]

  response = post(
    T.must(source.api_endpoint) + source.organization + "/" + source.project +
                            "/_apis/git/repositories/" + source.unscoped_repo +
                            "/refs?api-version=5.0",
    content.to_json
  )

  root = parse_json_object(response.body, "updated ref")
  first_object_field(root, "value", "updated ref")
end