utils/path: add child_of? method

This commit is contained in:
Caleb Xu 2024-03-25 10:55:40 -04:00
parent 17d5ab381b
commit 4b0e950736
No known key found for this signature in database
GPG Key ID: 47E6040D07B8407D
2 changed files with 47 additions and 0 deletions

View File

@ -0,0 +1,33 @@
# frozen_string_literal: true
require "utils/path"
RSpec.describe Utils::Path do
describe "::child_of?" do
it "recognizes a path as its own child" do
expect(described_class.child_of?("/foo/bar", "/foo/bar")).to be(true)
end
it "recognizes a path that is a child of the parent" do
expect(described_class.child_of?("/foo", "/foo/bar")).to be(true)
end
it "recognizes a path that is a grandchild of the parent" do
expect(described_class.child_of?("/foo", "/foo/bar/baz")).to be(true)
end
it "does not recognize a path that is not a child" do
expect(described_class.child_of?("/foo", "/bar/baz")).to be(false)
end
it "handles . and .. in paths correctly" do
expect(described_class.child_of?("/foo", "/foo/./bar")).to be(true)
expect(described_class.child_of?("/foo/bar", "/foo/../foo/bar/baz")).to be(true)
end
it "handles relative paths correctly" do
expect(described_class.child_of?("foo", "./bar/baz")).to be(false)
expect(described_class.child_of?("../foo", "./bar/baz/../../../foo/bar/baz")).to be(true)
end
end
end

View File

@ -0,0 +1,14 @@
# typed: strict
# frozen_string_literal: true
module Utils
module Path
sig { params(parent: T.any(Pathname, String), child: T.any(Pathname, String)).returns(T::Boolean) }
def self.child_of?(parent, child)
parent_pathname = Pathname(parent).expand_path
child_pathname = Pathname(child).expand_path
child_pathname.ascend { |p| return true if p == parent_pathname }
false
end
end
end