From b308a6227650e397102fa8fe3e3809af2630cd1e Mon Sep 17 00:00:00 2001 From: Andrey Marchenko Date: Thu, 4 Jan 2024 13:41:42 +0100 Subject: [PATCH] add Utils::Git.relative_to_root method to return source file paths relative to git repo's root --- lib/datadog/ci/utils/git.rb | 13 ++++++++++ sig/datadog/ci/utils/git.rbs | 8 ++++-- spec/datadog/ci/utils/git_spec.rb | 41 +++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/lib/datadog/ci/utils/git.rb b/lib/datadog/ci/utils/git.rb index 4f89a56e..108b971a 100644 --- a/lib/datadog/ci/utils/git.rb +++ b/lib/datadog/ci/utils/git.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "open3" +require "pathname" module Datadog module CI @@ -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) diff --git a/sig/datadog/ci/utils/git.rbs b/sig/datadog/ci/utils/git.rbs index 4ef0a783..b413f3bc 100644 --- a/sig/datadog/ci/utils/git.rbs +++ b/sig/datadog/ci/utils/git.rbs @@ -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 diff --git a/spec/datadog/ci/utils/git_spec.rb b/spec/datadog/ci/utils/git_spec.rb index 0c6cb14f..770f69d0 100644 --- a/spec/datadog/ci/utils/git_spec.rb +++ b/spec/datadog/ci/utils/git_spec.rb @@ -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