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

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

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.



380
381
382
383
384
385
386
387
388
# File 'lib/datadog/ci/git/local_repository.rb', line 380

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

  BaseBranchShaDetector.base_branch_sha(base_branch)
rescue => e
  Telemetry.track_error(e, Ext::Telemetry::Command::BASE_COMMIT_SHA)
  log_failure(e, "git base ref")
  nil
end

.current_folder_nameObject



87
88
89
# File 'lib/datadog/ci/git/local_repository.rb', line 87

def self.current_folder_name
  File.basename(root)
end

.fetch_head_commit_sha(commit_sha) ⇒ Object



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
# File 'lib/datadog/ci/git/local_repository.rb', line 320

def self.fetch_head_commit_sha(commit_sha)
  remote = get_remote_name
  # @type var res: String?
  res = nil

  duration_ms = Core::Utils::Time.measure(:float_millisecond) do
    cmd = [
      "fetch",
      "--update-shallow",
      "--filter=blob:none",
      "--recurse-submodules=no",
      "--no-write-fetch-head",
      remote,
      commit_sha
    ]
    res = CLI.exec_git_command(cmd)
  end

  Telemetry.git_command_ms(Ext::Telemetry::Command::FETCH_HEAD_COMMIT_SHA, duration_ms)
  res
rescue => e
  log_failure(e, "git fetch_head_commit_sha")
  Telemetry.track_error(e, Ext::Telemetry::Command::FETCH_HEAD_COMMIT_SHA)
  nil
end

.filter_invalid_commits(commits) ⇒ Object



410
411
412
# File 'lib/datadog/ci/git/local_repository.rb', line 410

def self.filter_invalid_commits(commits)
  commits.filter { |commit| Utils::Git.valid_commit_sha?(commit) }
end

.get_changes_since(base_commit) ⇒ Object

Returns a Diff object with relative file paths for files that were changed since the given base_commit. If base_commit is nil, returns nil. On error, returns nil.



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/datadog/ci/git/local_repository.rb', line 348

def self.get_changes_since(base_commit)
  return Diff.new 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 = CLI.exec_git_command(["diff", "-U0", "--word-diff=porcelain", base_commit, "HEAD"], timeout: CLI::LONG_TIMEOUT)
    end
    Telemetry.git_command_ms(Ext::Telemetry::Command::DIFF, duration_ms)

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

    return Diff.new if output.nil?

    # 2. Parse the output using Git::Diff
    Diff.parse_diff_output(output)
  rescue => e
    Telemetry.track_error(e, Ext::Telemetry::Command::DIFF)
    log_failure(e, "get changed files from diff")
    Diff.new
  end
end

.get_remote_nameObject



397
398
399
400
401
402
403
404
405
406
407
408
# File 'lib/datadog/ci/git/local_repository.rb', line 397

def self.get_remote_name
  upstream = LocalRepository.get_upstream_branch

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

.get_upstream_branchObject



390
391
392
393
394
395
# File 'lib/datadog/ci/git/local_repository.rb', line 390

def self.get_upstream_branch
  CLI.exec_git_command(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"])
rescue => e
  Datadog.logger.debug { "Error getting upstream: #{e}" }
  nil
end

.git_branchObject



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

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 = CLI.exec_git_command(["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_message(commit_sha = nil) ⇒ Object



146
147
148
149
150
151
# File 'lib/datadog/ci/git/local_repository.rb', line 146

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

.git_commit_shaObject



115
116
117
118
119
120
# File 'lib/datadog/ci/git/local_repository.rb', line 115

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

.git_commit_users(commit_sha = nil) ⇒ Object



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

def self.git_commit_users(commit_sha = nil)
  # Get committer and author information in one command.
  output = CLI.exec_git_command(["show", "-s", "--format=%an\t%ae\t%at\t%cn\t%ce\t%ct", commit_sha].compact)
  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



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

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 = CLI.exec_git_command(["log", "--format=%H", "-n", "1000", "--since=\"1 month ago\""], timeout: CLI::LONG_TIMEOUT)
  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



200
201
202
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
# File 'lib/datadog/ci/git/local_repository.rb', line 200

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

  # @type var res: String?
  res = nil

  duration_ms = Core::Utils::Time.measure(:float_millisecond) do
    cmd = [
      "rev-list",
      "--objects",
      "--no-object-names",
      "--filter=blob:none",
      "--since=\"1 month ago\""
    ] + excluded_commits_list + included_commits_list

    res = CLI.exec_git_command(cmd, timeout: CLI::LONG_TIMEOUT)
  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



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

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
    CLI.exec_git_command(
      ["pack-objects", "--compression=9", "--max-pack-size=3m", "#{path}/#{basename}"],
      stdin: commit_tree,
      timeout: CLI::LONG_TIMEOUT
    )
  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



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

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 = CLI.exec_git_command(["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



108
109
110
111
112
113
# File 'lib/datadog/ci/git/local_repository.rb', line 108

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

.git_shallow_clone?Boolean

Returns:

  • (Boolean)


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

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 = CLI.exec_git_command(["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



139
140
141
142
143
144
# File 'lib/datadog/ci/git/local_repository.rb', line 139

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

.git_unshallowObject



271
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
314
315
316
317
318
# File 'lib/datadog/ci/git/local_repository.rb', line 271

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

  default_remote = CLI.exec_git_command(["config", "--default", "origin", "--get", "clone.defaultRemoteName"])&.strip
  head_commit = git_commit_sha
  upstream_branch = get_upstream_branch

  # Build array of remotes to try, filtering out nil values
  unshallow_remotes = []
  unshallow_remotes << head_commit if head_commit
  unshallow_remotes << upstream_branch if upstream_branch
  unshallow_remotes << nil # Ensure the loop runs at least once, even if no valid remotes are available. This acts as a fallback mechanism.

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

      res =
        begin
          # @type var cmd: Array[String]
          cmd = [
            "fetch",
            "--shallow-since=\"1 month ago\"",
            "--update-shallow",
            "--filter=blob:none",
            "--recurse-submodules=no",
            default_remote
          ]
          cmd << remote if remote

          CLI.exec_git_command(cmd, timeout: CLI::UNSHALLOW_TIMEOUT)
        rescue => e
          log_failure(e, "git unshallow")
          Telemetry.track_error(e, Ext::Telemetry::Command::UNSHALLOW)
          unshallowing_errored = true
          nil
        end

      # If the command succeeded, break and return the result
      break [] if res && !unshallowing_errored
    end
  end

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

.log_failure(e, action) ⇒ Object



414
415
416
417
418
# File 'lib/datadog/ci/git/local_repository.rb', line 414

def self.log_failure(e, action)
  Datadog.logger.debug(
    "Unable to perform #{action}: #{e.class.name} #{e.message} at #{Array(e.backtrace).first}"
  )
end

.relative_to_root(path) ⇒ Object

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



27
28
29
30
31
32
33
34
35
36
37
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
# File 'lib/datadog/ci/git/local_repository.rb', line 27

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

    # this means that the root is not a prefix of this path somehow
    return "" if path[prefix_index] != File::SEPARATOR

    res = path[prefix_index + 1..]
  else
    # prefix_to_root is a difference between the root path and the given path
    if defined?(@prefix_to_root)
      # if path starts with ./ remove the dot before applying the optimization
      # @type var path: String
      path = path[1..] if path.start_with?("./")

      if @prefix_to_root == ""
        return path
      elsif @prefix_to_root
        return File.join(@prefix_to_root, path)
      end
    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

.repository_nameObject



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/datadog/ci/git/local_repository.rb', line 73

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



19
20
21
22
23
# File 'lib/datadog/ci/git/local_repository.rb', line 19

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

  @root = git_root || Dir.pwd
end