Skip to content

Commit d3bc384

Browse files
authored
fix(path): make find_upwards() search root (#506)
The previous implementation of `Path:find_upwards()` used the loop condition `folder ~= root` to bound the search which meant the root directory would never be searched. This commit instead breaks the `while true` loop after searching the root directory. The function now also returns `nil` rather than a blank string to indicate that the search has failed. Finally, this commit adds specs for the function.
1 parent f031bef commit d3bc384

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

lua/plenary/path.lua

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -931,11 +931,14 @@ function Path:find_upwards(filename)
931931
local folder = Path:new(self)
932932
local root = path.root(folder:absolute())
933933

934-
while folder:absolute() ~= root do
934+
while true do
935935
local p = folder:joinpath(filename)
936936
if p:exists() then
937937
return p
938938
end
939+
if folder:absolute() == root then
940+
break
941+
end
939942
folder = folder:parent()
940943
end
941944
return nil

tests/plenary/path_spec.lua

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -721,6 +721,34 @@ SOFTWARE.]]
721721
assert.are.same(should, data)
722722
end)
723723
end)
724+
725+
describe(":find_upwards", function()
726+
it("finds files that exist", function()
727+
local p = Path:new(debug.getinfo(1, "S").source:sub(2))
728+
local found = p:find_upwards "README.md"
729+
assert.are.same(found:absolute(), Path:new("README.md"):absolute())
730+
end)
731+
732+
it("finds files that exist at the root", function()
733+
local p = Path:new(debug.getinfo(1, "S").source:sub(2))
734+
735+
-- Temporarily set path.root to the root of this repository
736+
local root = p.path.root
737+
p.path.root = function(_)
738+
return p:parent():parent():parent().filename
739+
end
740+
741+
local found = p:find_upwards "README.md"
742+
assert.are.same(found:absolute(), Path:new("README.md"):absolute())
743+
p.path.root = root
744+
end)
745+
746+
it("returns nil if no file is found", function()
747+
local p = Path:new(debug.getinfo(1, "S").source:sub(2))
748+
local found = p:find_upwards "MISSINGNO.md"
749+
assert.are.same(found, nil)
750+
end)
751+
end)
724752
end)
725753

726754
-- function TestPath:testIsDir()

0 commit comments

Comments
 (0)