utils/path: add child_of? method
This commit is contained in:
parent
17d5ab381b
commit
4b0e950736
33
Library/Homebrew/test/utils/path_spec.rb
Normal file
33
Library/Homebrew/test/utils/path_spec.rb
Normal 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
|
14
Library/Homebrew/utils/path.rb
Normal file
14
Library/Homebrew/utils/path.rb
Normal 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
|
Loading…
x
Reference in New Issue
Block a user