Module: Datadog::CI::Git::LocalRepository

Defined in:
lib/datadog/ci/git/local_repository.rb

Defined Under Namespace

Classes: GitCommandExecutionError

Constant Summary collapse

COMMAND_RETRY_COUNT =
3
POSSIBLE_BASE_BRANCHES =
%w[main master preprod prod dev development trunk].freeze
DEFAULT_LIKE_BRANCH_FILTER =
/^(#{POSSIBLE_BASE_BRANCHES.join("|")}|release\/.*|hotfix\/.*)$/.freeze

Class Method Summary collapse

Class Method Details

.base_commit_sha(base_branch: nil) ⇒ Object

On best effort basis determines the git sha of the most likely base branch for the current PR.



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/datadog/ci/git/local_repository.rb', line 364

def self.base_commit_sha(base_branch: nil)
  Telemetry.git_command(Ext::Telemetry::Command::BASE_COMMIT_SHA)

  remote_name = get_remote_name
  Datadog.logger.debug { "Remote name: '#{remote_name}'" }

  source_branch = get_source_branch
  return nil if source_branch.nil?

  Datadog.logger.debug { "Source branch: '#{source_branch}'" }

  # Early exit if source is a main-like branch
  if main_like_branch?(source_branch, remote_name)
    Datadog.logger.debug { "Branch '#{source_branch}' already matches base branch filter (#{DEFAULT_LIKE_BRANCH_FILTER})" }
    return nil
  end

  possible_base_branches = base_branch.nil? ? POSSIBLE_BASE_BRANCHES : [base_branch]
  # Check and fetch base branches if they don't exist in local git repository
  check_and_fetch_base_branches(possible_base_branches, remote_name)

  default_branch = detect_default_branch(remote_name)
  Datadog.logger.debug { "Default branch: '#{default_branch}'" }

  candidates = build_candidate_list(remote_name, source_branch, base_branch)
  if candidates.nil? || candidates.empty?
    Datadog.logger.debug { "No candidate branches found." }
    return nil
  end

  metrics = compute_branch_metrics(candidates, source_branch)
  Datadog.logger.debug { "Branch metrics: '#{metrics}'" }

  best_branch_sha = find_best_branch(metrics, default_branch, remote_name)
  Datadog.logger.debug { "Best branch: '#{best_branch_sha}'" }

  best_branch_sha
rescue => e
  telemetry_track_error(e, Ext::Telemetry::Command::BASE_COMMIT_SHA)
  log_failure(e, "git base ref")
  nil
end

.build_candidate_list(remote_name, source_branch, base_branch) ⇒ Object



478
479
480
481
482
483
484
485
486
487
488
# File 'lib/datadog/ci/git/local_repository.rb', line 478

def self.build_candidate_list(remote_name, source_branch, base_branch)
  unless base_branch.nil?
    return [base_branch]
  end

  candidates = exec_git_command("git for-each-ref --format='%(refname:short)' refs/heads \"refs/remotes/#{remote_name}\"")&.lines&.map(&:strip)
  Datadog.logger.debug { "Available branches: '#{candidates}'" }
  candidates&.select! { |b| b.match?(DEFAULT_LIKE_BRANCH_FILTER) && b != source_branch }
  Datadog.logger.debug { "Candidate branches: '#{candidates}'" }
  candidates
end

.check_and_fetch_base_branches(branches, remote_name) ⇒ Object



427
428
429
430
431
# File 'lib/datadog/ci/git/local_repository.rb', line 427

def self.check_and_fetch_base_branches(branches, remote_name)
  branches.each do |branch|
    check_and_fetch_branch(branch, remote_name)
  end
end

.check_and_fetch_branch(branch, remote_name) ⇒ Object



407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'lib/datadog/ci/git/local_repository.rb', line 407

def self.check_and_fetch_branch(branch, remote_name)
  # Check if branch exists locally
  exec_git_command("git show-ref --verify --quiet refs/heads/#{branch}")
  Datadog.logger.debug { "Branch '#{branch}' exists locally, skipping" }
rescue GitCommandExecutionError => e
  Datadog.logger.debug { "Branch '#{branch}' doesn't exist locally, checking remote: #{e}" }
  begin
    remote_heads = exec_git_command("git ls-remote --heads #{remote_name} #{branch}")
    if remote_heads.nil? || remote_heads.empty?
      Datadog.logger.debug { "Branch '#{branch}' doesn't exist in remote" }
      return
    end

    Datadog.logger.debug { "Branch '#{branch}' exists in remote, fetching" }
    exec_git_command("git fetch --depth 1 #{remote_name} #{branch}:#{branch}")
  rescue GitCommandExecutionError => e
    Datadog.logger.debug { "Branch '#{branch}' couldn't be fetched from remote: #{e}" }
  end
end

.compute_branch_metrics(candidates, source_branch) ⇒ Object



490
491
492
493
494
495
496
497
498
499
500
# File 'lib/datadog/ci/git/local_repository.rb', line 490

def self.compute_branch_metrics(candidates, source_branch)
  metrics = {}
  candidates.each do |cand|
    base_sha = exec_git_command("git merge-base #{cand} #{source_branch} 2>/dev/null")&.strip
    next if base_sha.nil? || base_sha.empty?

    behind, ahead = exec_git_command("git rev-list --left-right --count #{cand}...#{source_branch}")&.strip&.split&.map(&:to_i)
    metrics[cand] = {behind: behind, ahead: ahead, base_sha: base_sha}
  end
  metrics
end

.current_folder_nameObject



90
91
92
# File 'lib/datadog/ci/git/local_repository.rb', line 90

def self.current_folder_name
  File.basename(root)
end

.default_branch?(branch, default_branch, remote_name) ⇒ Boolean

Returns:

  • (Boolean)


515
516
517
# File 'lib/datadog/ci/git/local_repository.rb', line 515

def self.default_branch?(branch, default_branch, remote_name)
  branch == default_branch || branch == "#{remote_name}/#{default_branch}"
end

.detect_default_branch(remote_name) ⇒ Object



453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/datadog/ci/git/local_repository.rb', line 453

def self.detect_default_branch(remote_name)
  # @type var default_branch: String?
  default_branch = nil
  begin
    default_ref = exec_git_command("git symbolic-ref --quiet --short \"refs/remotes/#{remote_name}/HEAD\" 2>/dev/null")
    default_branch = remove_remote_prefix(default_ref, remote_name) unless default_ref.nil?
  rescue
    Datadog.logger.debug { "Could not get symbolic-ref, trying to find a fallback (main, master)..." }
  end

  default_branch = find_fallback_default_branch(remote_name) if default_branch.nil?
  default_branch
end

.find_best_branch(metrics, default_branch, remote_name) ⇒ Object



502
503
504
505
506
507
508
509
510
511
512
513
# File 'lib/datadog/ci/git/local_repository.rb', line 502

def self.find_best_branch(metrics, default_branch, remote_name)
  return nil if metrics.empty?

  _, best_data = metrics.min_by do |cand, data|
    [
      data[:ahead],
      default_branch?(cand, default_branch, remote_name) ? 0 : 1 # prefer default branch on tie
    ]
  end

  best_data ? best_data[:base_sha] : nil
end

.find_fallback_default_branch(remote_name) ⇒ Object



467
468
469
470
471
472
473
474
475
476
# File 'lib/datadog/ci/git/local_repository.rb', line 467

def self.find_fallback_default_branch(remote_name)
  ["main", "master"].each do |fallback|
    exec_git_command("git show-ref --verify --quiet \"refs/remotes/#{remote_name}/#{fallback}\"")
    Datadog.logger.debug { "Found fallback default branch '#{fallback}'" }
    return fallback
  rescue
    next
  end
  nil
end

.get_changed_files_from_diff(base_commit) ⇒ Object

Returns a Set of normalized file paths changed since the given base_commit. If base_commit is nil, returns nil. On error, returns nil.



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/datadog/ci/git/local_repository.rb', line 317

def self.get_changed_files_from_diff(base_commit)
  return nil if base_commit.nil?

  Datadog.logger.debug { "calculating git diff from base_commit: #{base_commit}" }

  Telemetry.git_command(Ext::Telemetry::Command::DIFF)

  begin
    # 1. Run the git diff command

    # @type var output: String?
    output = nil
    duration_ms = Core::Utils::Time.measure(:float_millisecond) do
      output = exec_git_command("git diff -U0 --word-diff=porcelain #{base_commit} HEAD")
    end
    Telemetry.git_command_ms(Ext::Telemetry::Command::DIFF, duration_ms)

    Datadog.logger.debug { "git diff output: #{output}" }

    return nil if output.nil?

    # 2. Parse the output to extract which files changed
    changed_files = Set.new
    output.each_line do |line|
      # Match lines like: diff --git a/foo/bar.rb b/foo/bar.rb
      # This captures git changes on file level
      match = /^diff --git a\/(?<file>.+) b\/(?<file2>.+)$/.match(line)
      if match && match[:file]
        changed_file = match[:file]
        # Normalize to repo root
        normalized_changed_file = relative_to_root(changed_file)
        changed_files << normalized_changed_file unless normalized_changed_file.nil? || normalized_changed_file.empty?

        Datadog.logger.debug { "matched changed_file: #{changed_file} from line: #{line}" }
        Datadog.logger.debug { "normalized_changed_file: #{normalized_changed_file}" }
      end
    end
    changed_files
  rescue => e
    telemetry_track_error(e, Ext::Telemetry::Command::DIFF)
    log_failure(e, "get changed files from diff")
    nil
  end
end

.get_remote_nameObject



519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
# File 'lib/datadog/ci/git/local_repository.rb', line 519

def self.get_remote_name
  # Try to find remote from upstream tracking
  upstream = nil
  begin
    upstream = exec_git_command("git rev-parse --abbrev-ref --symbolic-full-name @{upstream}")&.strip
  rescue => e
    Datadog.logger.debug { "Error getting upstream: #{e}" }
  end

  if upstream
    upstream.split("/").first
  else
    # Fallback to first remote if no upstream is set
    first_remote_value = exec_git_command("git remote")&.split("\n")&.first
    Datadog.logger.debug { "First remote value: '#{first_remote_value}'" }
    first_remote_value || "origin"
  end
end

.get_source_branchObject



433
434
435
436
437
438
439
440
441
442
# File 'lib/datadog/ci/git/local_repository.rb', line 433

def self.get_source_branch
  source_branch = exec_git_command("git rev-parse --abbrev-ref HEAD")&.strip
  if source_branch.nil?
    Datadog.logger.debug { "Could not get current branch" }
    return nil
  end

  exec_git_command("git rev-parse --verify --quiet #{source_branch} > /dev/null")
  source_branch
end

.git_branchObject



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/datadog/ci/git/local_repository.rb', line 125

def self.git_branch
  Telemetry.git_command(Ext::Telemetry::Command::GET_BRANCH)
  # @type var res: String?
  res = nil

  duration_ms = Core::Utils::Time.measure(:float_millisecond) do
    res = exec_git_command("git rev-parse --abbrev-ref HEAD")
  end

  Telemetry.git_command_ms(Ext::Telemetry::Command::GET_BRANCH, duration_ms)
  res
rescue => e
  log_failure(e, "git branch")
  telemetry_track_error(e, Ext::Telemetry::Command::GET_BRANCH)
  nil
end

.git_commit_messageObject



149
150
151
152
153
154
# File 'lib/datadog/ci/git/local_repository.rb', line 149

def self.git_commit_message
  exec_git_command("git log -n 1 --format=%B")
rescue => e
  log_failure(e, "git commit message")
  nil
end

.git_commit_shaObject



118
119
120
121
122
123
# File 'lib/datadog/ci/git/local_repository.rb', line 118

def self.git_commit_sha
  exec_git_command("git rev-parse HEAD")
rescue => e
  log_failure(e, "git commit sha")
  nil
end

.git_commit_usersObject



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/datadog/ci/git/local_repository.rb', line 156

def self.git_commit_users
  # Get committer and author information in one command.
  output = exec_git_command("git show -s --format='%an\t%ae\t%at\t%cn\t%ce\t%ct'")
  unless output
    Datadog.logger.debug(
      "Unable to read git commit users: git command output is nil"
    )
    nil_user = NilUser.new
    return [nil_user, nil_user]
  end

  author_name, author_email, author_timestamp,
    committer_name, committer_email, committer_timestamp = output.split("\t").each(&:strip!)

  author = User.new(author_name, author_email, author_timestamp)
  committer = User.new(committer_name, committer_email, committer_timestamp)

  [author, committer]
rescue => e
  log_failure(e, "git commit users")

  nil_user = NilUser.new
  [nil_user, nil_user]
end

.git_commitsObject

returns maximum of 1000 latest commits in the last month



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/datadog/ci/git/local_repository.rb', line 182

def self.git_commits
  Telemetry.git_command(Ext::Telemetry::Command::GET_LOCAL_COMMITS)

  # @type var output: String?
  output = nil

  duration_ms = Core::Utils::Time.measure(:float_millisecond) do
    output = exec_git_command("git log --format=%H -n 1000 --since=\"1 month ago\"")
  end

  Telemetry.git_command_ms(Ext::Telemetry::Command::GET_LOCAL_COMMITS, duration_ms)

  return [] if output.nil?

  output.split("\n")
rescue => e
  log_failure(e, "git commits")
  telemetry_track_error(e, Ext::Telemetry::Command::GET_LOCAL_COMMITS)
  []
end

.git_commits_rev_list(included_commits:, excluded_commits:) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/datadog/ci/git/local_repository.rb', line 203

def self.git_commits_rev_list(included_commits:, excluded_commits:)
  Telemetry.git_command(Ext::Telemetry::Command::GET_OBJECTS)
  included_commits = filter_invalid_commits(included_commits).join(" ")
  excluded_commits = filter_invalid_commits(excluded_commits).map! { |sha| "^#{sha}" }.join(" ")

  # @type var res: String?
  res = nil

  duration_ms = Core::Utils::Time.measure(:float_millisecond) do
    res = exec_git_command(
      "git rev-list " \
      "--objects " \
      "--no-object-names " \
      "--filter=blob:none " \
      "--since=\"1 month ago\" " \
      "#{excluded_commits} #{included_commits}"
    )
  end

  Telemetry.git_command_ms(Ext::Telemetry::Command::GET_OBJECTS, duration_ms)

  res
rescue => e
  log_failure(e, "git commits rev list")
  telemetry_track_error(e, Ext::Telemetry::Command::GET_OBJECTS)
  nil
end

.git_generate_packfiles(included_commits:, excluded_commits:, path:) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/datadog/ci/git/local_repository.rb', line 231

def self.git_generate_packfiles(included_commits:, excluded_commits:, path:)
  return nil unless File.exist?(path)

  commit_tree = git_commits_rev_list(included_commits: included_commits, excluded_commits: excluded_commits)
  return nil if commit_tree.nil?

  basename = SecureRandom.hex(4)

  Telemetry.git_command(Ext::Telemetry::Command::PACK_OBJECTS)

  duration_ms = Core::Utils::Time.measure(:float_millisecond) do
    exec_git_command(
      "git pack-objects --compression=9 --max-pack-size=3m #{path}/#{basename}",
      stdin: commit_tree
    )
  end
  Telemetry.git_command_ms(Ext::Telemetry::Command::PACK_OBJECTS, duration_ms)

  basename
rescue => e
  log_failure(e, "git generate packfiles")
  telemetry_track_error(e, Ext::Telemetry::Command::PACK_OBJECTS)
  nil
end

.git_repository_urlObject



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/datadog/ci/git/local_repository.rb', line 94

def self.git_repository_url
  Telemetry.git_command(Ext::Telemetry::Command::GET_REPOSITORY)
  # @type var res: String?
  res = nil

  duration_ms = Core::Utils::Time.measure(:float_millisecond) do
    res = exec_git_command("git ls-remote --get-url")
  end

  Telemetry.git_command_ms(Ext::Telemetry::Command::GET_REPOSITORY, duration_ms)
  res
rescue => e
  log_failure(e, "git repository url")
  telemetry_track_error(e, Ext::Telemetry::Command::GET_REPOSITORY)
  nil
end

.git_rootObject



111
112
113
114
115
116
# File 'lib/datadog/ci/git/local_repository.rb', line 111

def self.git_root
  exec_git_command("git rev-parse --show-toplevel")
rescue => e
  log_failure(e, "git root path")
  nil
end

.git_shallow_clone?Boolean

Returns:

  • (Boolean)


256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/datadog/ci/git/local_repository.rb', line 256

def self.git_shallow_clone?
  Telemetry.git_command(Ext::Telemetry::Command::CHECK_SHALLOW)
  res = false

  duration_ms = Core::Utils::Time.measure(:float_millisecond) do
    res = exec_git_command("git rev-parse --is-shallow-repository") == "true"
  end
  Telemetry.git_command_ms(Ext::Telemetry::Command::CHECK_SHALLOW, duration_ms)

  res
rescue => e
  log_failure(e, "git shallow clone")
  telemetry_track_error(e, Ext::Telemetry::Command::CHECK_SHALLOW)
  false
end

.git_tagObject



142
143
144
145
146
147
# File 'lib/datadog/ci/git/local_repository.rb', line 142

def self.git_tag
  exec_git_command("git tag --points-at HEAD")
rescue => e
  log_failure(e, "git tag")
  nil
end

.git_unshallowObject



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/datadog/ci/git/local_repository.rb', line 272

def self.git_unshallow
  Telemetry.git_command(Ext::Telemetry::Command::UNSHALLOW)
  # @type var res: String?
  res = nil

  unshallow_command =
    "git fetch " \
    "--shallow-since=\"1 month ago\" " \
    "--update-shallow " \
    "--filter=\"blob:none\" " \
    "--recurse-submodules=no " \
    "$(git config --default origin --get clone.defaultRemoteName)"

  unshallow_remotes = [
    "$(git rev-parse HEAD)",
    "$(git rev-parse --abbrev-ref --symbolic-full-name @{upstream})",
    nil
  ]

  duration_ms = Core::Utils::Time.measure(:float_millisecond) do
    unshallow_remotes.each do |remote|
      unshallowing_errored = false

      res =
        begin
          exec_git_command(
            "#{unshallow_command} #{remote}"
          )
        rescue => e
          log_failure(e, "git unshallow")
          telemetry_track_error(e, Ext::Telemetry::Command::UNSHALLOW)
          unshallowing_errored = true
          nil
        end

      break [] unless unshallowing_errored
    end
  end

  Telemetry.git_command_ms(Ext::Telemetry::Command::UNSHALLOW, duration_ms)
  res
end

.main_like_branch?(branch_name, remote_name) ⇒ Boolean

Returns:

  • (Boolean)


448
449
450
451
# File 'lib/datadog/ci/git/local_repository.rb', line 448

def self.main_like_branch?(branch_name, remote_name)
  short_branch_name = remove_remote_prefix(branch_name, remote_name)
  short_branch_name&.match?(DEFAULT_LIKE_BRANCH_FILTER)
end

.relative_to_root(path) ⇒ Object

ATTENTION: this function is running in a hot path and should be optimized for performance



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/datadog/ci/git/local_repository.rb', line 38

def self.relative_to_root(path)
  return "" if path.nil?

  root_path = root
  return path if root_path.nil?

  if File.absolute_path?(path)
    # prefix_index is where the root path ends in the given path
    prefix_index = root_path.size

    # impossible case - absolute paths are returned from code coverage tool that always checks
    # that root is a prefix of the path
    return "" if path.size < prefix_index

    prefix_index += 1 if path[prefix_index] == File::SEPARATOR
    res = path[prefix_index..]
  else
    # prefix_to_root is a difference between the root path and the given path
    if @prefix_to_root == ""
      return path
    elsif @prefix_to_root
      return File.join(@prefix_to_root, path)
    end

    pathname = Pathname.new(File.expand_path(path))
    root_path = Pathname.new(root_path)

    # relative_path_from is an expensive function
    res = pathname.relative_path_from(root_path).to_s

    unless defined?(@prefix_to_root)
      @prefix_to_root = res.gsub(path, "") if res.end_with?(path)
    end
  end

  res || ""
end

.remove_remote_prefix(branch_name, remote_name) ⇒ Object



444
445
446
# File 'lib/datadog/ci/git/local_repository.rb', line 444

def self.remove_remote_prefix(branch_name, remote_name)
  branch_name&.sub(/^#{Regexp.escape(remote_name)}\//, "")
end

.repository_nameObject



76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/datadog/ci/git/local_repository.rb', line 76

def self.repository_name
  return @repository_name if defined?(@repository_name)

  git_remote_url = git_repository_url

  # return git repository name from remote url without .git extension
  last_path_segment = git_remote_url.split("/").last if git_remote_url
  @repository_name = last_path_segment.gsub(".git", "") if last_path_segment
  @repository_name ||= current_folder_name
rescue => e
  log_failure(e, "git repository name")
  @repository_name = current_folder_name
end

.rootObject



30
31
32
33
34
# File 'lib/datadog/ci/git/local_repository.rb', line 30

def self.root
  return @root if defined?(@root)

  @root = git_root || Dir.pwd
end