Skip to content

Commit

Permalink
add Utils::Git.relative_to_root method to return source file paths re…
Browse files Browse the repository at this point in the history
…lative to git repo's root
  • Loading branch information
anmarchenko committed Jan 4, 2024
1 parent cba9dd1 commit b308a62
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
13 changes: 13 additions & 0 deletions lib/datadog/ci/utils/git.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require "open3"
require "pathname"

module Datadog
module CI
Expand All @@ -25,6 +26,18 @@ def self.root
@@root = exec_git_command("git rev-parse --show-toplevel")
end

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

git_root = root
return path if git_root.nil?

path = Pathname.new(File.expand_path(path))
git_root = Pathname.new(git_root)

path.relative_path_from(git_root).to_s
end

def self.exec_git_command(cmd)
out, status = Open3.capture2e(cmd)

Expand Down
8 changes: 6 additions & 2 deletions sig/datadog/ci/utils/git.rbs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@ module Datadog
module Git
@@root: String?

def self?.normalize_ref: (untyped name) -> (nil | untyped)
def self.normalize_ref: (String? name) -> String?

def self?.is_git_tag?: (untyped ref) -> untyped
def self.is_git_tag?: (String? ref) -> bool

def self.exec_git_command: (String ref) -> String?

def self.root: -> String?

def self.relative_to_root: (String? path) -> String?
end
end
end
Expand Down
41 changes: 41 additions & 0 deletions spec/datadog/ci/utils/git_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,45 @@
end
end
end

describe ".relative_to_root" do
subject { described_class.relative_to_root(path) }

context "when path is nil" do
let(:path) { nil }

it { is_expected.to be_nil }
end

context "when git root is nil" do
before do
allow(described_class).to receive(:root).and_return(nil)
end

let(:path) { "foo/bar" }

it { is_expected.to eq("foo/bar") }
end

context "when git root is not nil" do
context "when path is absolute" do
before do
allow(described_class).to receive(:root).and_return("/foo/bar")
end
let(:path) { "/foo/bar/baz" }

it { is_expected.to eq("baz") }
end

context "when path is relative" do
before do
allow(described_class).to receive(:root).and_return("#{Dir.pwd}/foo/bar")
end

let(:path) { "./baz" }

it { is_expected.to eq("../../baz") }
end
end
end
end

0 comments on commit b308a62

Please sign in to comment.