Last active
January 11, 2023 12:59
-
-
Save exerro/9500ea57b51ec8d2595b73c294dff290 to your computer and use it in GitHub Desktop.
Lua path library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--[[ Path library for Lua (by exerro aka Benedict Allen) | |
Create a path using | |
local p = Path 'my/directory' | |
Combine paths like | |
local file = p / 'subdir' / 'myfile.txt' | |
print(file) --> my/directory/subdir/myfile.txt | |
Use methods like | |
print(file:name()) --> myfile.txt | |
print(file:name(false)) --> myfile | |
print(file:parent()) --> my/directory/subdir | |
See the code for comprehensive documentation. Best viewed/used with the VSCode | |
Lua Language server by sumneko. | |
Copyright 2023 Benedict Allen | |
Permission is hereby granted, free of charge, to any person obtaining a copy of | |
this software and associated documentation files (the "Software"), to deal in | |
the Software without restriction, including without limitation the rights to | |
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of | |
the Software, and to permit persons to whom the Software is furnished to do so, | |
subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS | |
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | |
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | |
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN | |
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
]] | |
local RUN_TESTS = false | |
local dd_lookup = setmetatable({ | |
['/../../'] = '/../../', | |
['../../'] = '../../', | |
['/../..'] = '/../..', | |
['../..'] = '../..', | |
}, { __index = function(_, a) | |
if a:sub(1, 1) == '/' and a:sub(-1) == '/' then | |
return '/' | |
else | |
return '' | |
end | |
end }) | |
--- @param s string | |
--- @return string | |
local function normalise_path(s) | |
while true do | |
local s0 = s | |
s = s:gsub('//+', '/') | |
:gsub('(.)/$', '%1') | |
:gsub('/%./', '/'):gsub('/%.$', ''):gsub('^%./', ''):gsub('^%.$', '') | |
:gsub('/[^/]+/%.%./', dd_lookup):gsub('/[^/]+/%.%.$', dd_lookup):gsub('^[^/]+/%.%./', dd_lookup):gsub('^[^/]+/%.%.$', dd_lookup) | |
if s == s0 then | |
break | |
end | |
end | |
return s | |
end | |
-------------------------------------------------------------------------------- | |
--- @class PathLibrary | |
--- @operator call(string): Path | |
local Path = {} | |
--- @class Path | |
--- @field private _string_repr string | |
--- @operator concat(Path | string): Path | |
--- @operator div(Path | string): Path | |
local PathInstance = {} | |
---------------------------------------------------------------- | |
--- Create a new `Path` from `s` | |
--- @param s string | Path | |
--- @return Path | |
function Path.new(s) | |
if Path.is_path(s) then | |
return s --[[ @as Path ]] | |
elseif type(s) ~= 'string' then | |
error('Expected string path, got ' .. type(s), 2) | |
--- @diagnostic disable-next-line: missing-return-value | |
return | |
end | |
local p = { _string_repr = normalise_path(s) } | |
setmetatable(p, { | |
__index = PathInstance, | |
__eq = PathInstance.equals, | |
__concat = PathInstance.concatenate, | |
__div = PathInstance.combine, | |
__tostring = PathInstance.to_string, | |
}) | |
return p | |
end | |
--- Return whether `object` is a `Path`. | |
--- @param object any | |
--- @return boolean | |
function Path.is_path(object) | |
return type(object) == 'table' and object._string_repr ~= nil | |
end | |
--- Find the path that is the parent of all the paths given (`a, ...`). If there | |
--- is no parent, `nil` will be returned. | |
--- For example, `Path.common_root(Path 'a/b', Path 'a/c/d')` will be `a`. | |
--- @param a Path | |
--- @param ... Path | |
--- @return Path | nil | |
function Path.common_root(a, ...) | |
local raw_paths = { a, ... } | |
--- @type string[][] | |
local paths = {} | |
local min_length = math.huge | |
local is_absolute = a:is_absolute() | |
for i = 2, #raw_paths do | |
if raw_paths[i]:is_absolute() ~= is_absolute then | |
return nil | |
end | |
end | |
for i = 1, #raw_paths do | |
local parts = {} | |
for part in raw_paths[i]:to_string():gmatch '[^/]+' do | |
table.insert(parts, part) | |
end | |
paths[i] = parts | |
min_length = math.min(min_length, #parts) | |
end | |
for i = 1, min_length do | |
for j = 2, #paths do | |
if paths[j][i] ~= paths[1][i] then | |
local s = table.concat(paths[1], '/', 1, i - 1) | |
if is_absolute then s = '/' .. s end | |
return Path(s) | |
end | |
end | |
end | |
local s = table.concat(paths[1], '/', 1, min_length) | |
if is_absolute then s = '/' .. s end | |
return Path(s) | |
end | |
---------------------------------------------------------------- | |
--- Return the string representation of this path | |
--- @return string | |
function PathInstance:to_string() | |
return self._string_repr | |
end | |
--- Return whether this path equals the other. | |
--- @param other any | |
--- @return boolean | |
function PathInstance:equals(other) | |
if not Path.is_path(self) or not Path.is_path(other) then return false end | |
return self._string_repr == other._string_repr | |
end | |
--- Return the name of the last segment of this path, e.g. `a/b/c.lua` would | |
--- return `c.lua` as the name, or `c` as the name if `include_extension` is | |
--- false. | |
--- @param include_extension boolean | nil Defaults to true | |
--- @return string | |
function PathInstance:name(include_extension) | |
local raw_name = self._string_repr:match "/([^/]+)$" or self._string_repr | |
if include_extension == false then | |
return raw_name:match '(.+)%.[^%.]-$' or raw_name | |
end | |
return raw_name | |
end | |
--- Return the parent path (i.e. containing directory), e.g. `a/b/c.lua` would | |
--- return `a/b` as the parent path. | |
--- @return Path | |
function PathInstance:parent() | |
return Path(self._string_repr:match "^.+/" or '') | |
end | |
--- Return whether this path is a child of the parent, or if `strict` is false, | |
--- also whether it is the parent. For example `a/b` is within `a`, and `a/b` is | |
--- within `a/b` only if `strict` is false. | |
--- @param parent Path | |
--- @param strict boolean | nil | |
--- @return boolean | |
function PathInstance:is_within(parent, strict) | |
if strict then | |
return self:parent():is_within(parent, false) | |
end | |
if parent._string_repr == '' then | |
return self._string_repr:sub(1, 1) ~= '/' | |
elseif parent._string_repr == '/' then | |
return self._string_repr:sub(1, 1) == '/' | |
end | |
if self._string_repr == parent._string_repr then | |
return true | |
end | |
return self._string_repr:sub(1, #parent._string_repr + 1) == parent._string_repr .. '/' | |
end | |
--- Return this path relative to the other, e.g. `a/b/c` relative to `a/d` would | |
--- be `../b/c`. | |
--- @param other Path | |
--- @return Path | nil | |
function PathInstance:relative_to(other) | |
local common_root_path = Path.common_root(self, other) | |
if not common_root_path then return nil end | |
local common_root = common_root_path._string_repr | |
local self_relative = self._string_repr:sub(#common_root + 1) | |
local other_relative = other._string_repr:sub(#common_root + 1) | |
if self_relative:sub(1, 1) == '/' then self_relative = self_relative:sub(2) end | |
if other_relative:sub(1, 1) == '/' then other_relative = other_relative:sub(2) end | |
local up_levels = #other_relative == 0 and 0 or select(2, other_relative:gsub('/', '')) + 1 | |
return Path(('../'):rep(up_levels) .. self_relative) | |
end | |
--- Return whether this path is absolute (starts with a /) | |
--- @return boolean | |
function PathInstance:is_absolute() | |
return self._string_repr:sub(1, 1) == '/' | |
end | |
--- Return a copy of this path that is absolute by prepending a / | |
--- @return Path | |
function PathInstance:as_absolute() | |
return Path('/' .. self._string_repr) | |
end | |
--- Return this path concatenated with another, e.g. | |
--- `Path 'a' .. 'b' == Path 'ab'` | |
--- @param other Path | string | |
--- @return Path | |
function PathInstance:concatenate(other) | |
if Path.is_path(other) then | |
other = other._string_repr | |
elseif type(other) ~= 'string' then | |
error('Expected Path or string, got ' .. type(other), 2) | |
end | |
return Path(self._string_repr .. other) | |
end | |
--- Return this path combined with another, e.g. `Path 'a' / 'b' == Path 'a/b'` | |
--- @param other Path | string | |
--- @return Path | |
function PathInstance:combine(other) | |
if Path.is_path(other) then | |
other = other._string_repr | |
elseif type(other) ~= 'string' then | |
error('Expected Path or string, got ' .. type(other), 2) | |
end | |
return Path(self._string_repr .. '/' .. other) | |
end | |
-------------------------------------------------------------------------------- | |
setmetatable(Path, { | |
__call = function(_, s) | |
return Path.new(s) | |
end | |
}) | |
-------------------------------------------------------------------------------- | |
local function assert_equals(a, b) | |
if a ~= b then | |
if not Path.is_path(b) or a ~= b:to_string() then | |
error('Assertion failed:\n expected: ' .. tostring(a) .. '\n got : ' .. tostring(b), 2) | |
end | |
end | |
end | |
if RUN_TESTS then | |
do -- normalisation | |
assert_equals('a/b', Path 'a//b') | |
assert_equals('a/b', Path 'a///b') | |
assert_equals('a/b', Path 'a///b/') | |
assert_equals('a/b', Path 'a/b//') | |
assert_equals('/a/b', Path '/a/b//') | |
assert_equals('/a/b', Path '//a/b//') | |
assert_equals('/', Path '/') | |
assert_equals('/', Path '///') | |
assert_equals('/a/b', Path '//a/./b//') | |
assert_equals('a/b', Path './/a/./b//') | |
assert_equals('a/b', Path 'a/b//.') | |
assert_equals('a', Path 'a/b//..') | |
assert_equals('a/c', Path 'a/b//../c') | |
assert_equals('c', Path 'a/../c') | |
assert_equals('../c', Path '../c') | |
assert_equals('/../c', Path '/../c') | |
assert_equals('/../../c', Path '/../../c') | |
assert_equals('../../c', Path '../../c') | |
end | |
do -- PathLibrary.common_root() | |
assert_equals('/a', Path.common_root(Path '/a/b', Path '/a/c', Path '/a/d')) | |
assert_equals('a', Path.common_root(Path 'a/b', Path 'a/c', Path 'a/d')) | |
assert_equals(nil, Path.common_root(Path '/a/b', Path 'a/c', Path 'a/d')) | |
assert_equals('a/b', Path.common_root(Path 'a/b/c', Path 'a/b/d')) | |
assert_equals('a/b', Path.common_root(Path 'a/b/c', Path 'a/b')) | |
assert_equals('a/b', Path.common_root(Path 'a/b', Path 'a/b/c')) | |
assert_equals('a/b', Path.common_root(Path 'a/b', Path 'a/b')) | |
assert_equals('', Path.common_root(Path 'a/b', Path 'c/d')) | |
assert_equals('/', Path.common_root(Path '/a/b', Path '/c/d')) | |
end | |
do -- Path:name() | |
assert_equals('a', Path 'a' :name()) | |
assert_equals('b', Path 'a/b' :name()) | |
assert_equals('c', Path 'a/b/c' :name()) | |
assert_equals('a.lua', Path 'a.lua' :name()) | |
assert_equals('b.lua', Path 'a/b.lua' :name()) | |
assert_equals('c.lua', Path 'a/b/c.lua' :name()) | |
assert_equals('a', Path 'a.lua' :name(false)) | |
assert_equals('b', Path 'a/b.lua' :name(false)) | |
assert_equals('c', Path 'a/b/c.lua' :name(false)) | |
assert_equals('a.some', Path 'a.some.lua' :name(false)) | |
assert_equals('b.some', Path 'a/b.some.lua' :name(false)) | |
assert_equals('c.some', Path 'a/b/c.some.lua' :name(false)) | |
end | |
do -- Path:parent() | |
assert_equals('', Path 'a' :parent()) | |
assert_equals('a', Path 'a/b' :parent()) | |
assert_equals('a/b', Path 'a/b/c' :parent()) | |
assert_equals('', Path 'a.lua' :parent()) | |
assert_equals('a', Path 'a/b.lua' :parent()) | |
assert_equals('a/b', Path 'a/b/c.lua' :parent()) | |
end | |
do -- Path:is_within() | |
assert_equals(true, Path 'a/b' :is_within(Path 'a')) | |
assert_equals(true, Path 'a/b' :is_within(Path '')) | |
assert_equals(true, Path 'a/b/c' :is_within(Path 'a')) | |
assert_equals(true, Path 'a/b/c' :is_within(Path 'a/b')) | |
assert_equals(true, Path 'a/b/c' :is_within(Path '')) | |
assert_equals(true, Path '/a/b' :is_within(Path '/a')) | |
assert_equals(true, Path '/a/b' :is_within(Path '/')) | |
assert_equals(true, Path '/a/b/c' :is_within(Path '/a')) | |
assert_equals(true, Path '/a/b/c' :is_within(Path '/a/b')) | |
assert_equals(true, Path '/a/b/c' :is_within(Path '/')) | |
assert_equals(false, Path '/a/b' :is_within(Path 'a')) | |
assert_equals(false, Path '/a/b' :is_within(Path '')) | |
assert_equals(false, Path '/a/b/c' :is_within(Path 'a')) | |
assert_equals(false, Path '/a/b/c' :is_within(Path 'a/b')) | |
assert_equals(false, Path '/a/b/c' :is_within(Path '')) | |
assert_equals(false, Path 'a/b' :is_within(Path '/a')) | |
assert_equals(false, Path 'a/b' :is_within(Path '/')) | |
assert_equals(false, Path 'a/b/c' :is_within(Path '/a')) | |
assert_equals(false, Path 'a/b/c' :is_within(Path '/a/b')) | |
assert_equals(false, Path 'a/b/c' :is_within(Path '/')) | |
assert_equals(false, Path 'a/b' :is_within(Path 'a/c')) | |
assert_equals(false, Path 'a/b/d' :is_within(Path 'a/c')) | |
assert_equals(false, Path 'a' :is_within(Path 'a/b')) | |
assert_equals(false, Path 'a/b' :is_within(Path 'a/b', true)) | |
assert_equals(true, Path 'a/b' :is_within(Path 'a/b', false)) | |
end | |
do -- Path:relative_to() | |
assert_equals('b', Path 'a/b' :relative_to(Path 'a')) | |
assert_equals('../b', Path 'a/b' :relative_to(Path 'a/c')) | |
assert_equals('../../b/c', Path 'a/b/c' :relative_to(Path 'a/d/e')) | |
assert_equals('b/c', Path 'a/b/c' :relative_to(Path 'a')) | |
assert_equals('../a', Path 'a' :relative_to(Path 'b')) | |
assert_equals('b', Path '/a/b' :relative_to(Path '/a')) | |
assert_equals('../b', Path '/a/b' :relative_to(Path '/a/c')) | |
assert_equals('../../b/c', Path '/a/b/c' :relative_to(Path '/a/d/e')) | |
assert_equals('b/c', Path '/a/b/c' :relative_to(Path '/a')) | |
assert_equals('../a', Path '/a' :relative_to(Path '/b')) | |
assert_equals(nil, Path 'a/b/c' :relative_to(Path '/a')) | |
assert_equals(nil, Path '/a/b/c' :relative_to(Path 'a')) | |
end | |
do -- Path:concatenate() | |
assert_equals('ab', Path 'a' .. 'b') | |
assert_equals('ab', Path 'a' .. Path 'b') | |
assert_equals('/ab', Path '/a' .. 'b') | |
assert_equals('/ab', Path '/a' .. Path 'b') | |
assert_equals('abc', Path 'a' .. 'b' .. 'c') | |
assert_equals('abc', Path 'a' .. Path 'b' .. Path 'c') | |
assert_equals('a/b', Path 'a' .. '/b') | |
assert_equals('a/b', Path 'a' .. Path '/b') | |
end | |
do -- Path:combine() | |
assert_equals('a/b', Path 'a' / 'b') | |
assert_equals('a/b', Path 'a' / Path 'b') | |
assert_equals('/a/b', Path '/a' / 'b') | |
assert_equals('/a/b', Path '/a' / Path 'b') | |
assert_equals('a', Path 'a' / '.') | |
assert_equals('a', Path 'a' / Path '.') | |
assert_equals('a/b', Path 'a' / './b') | |
assert_equals('a/b', Path 'a' / Path './b') | |
assert_equals('b', Path 'a' / '../b') | |
assert_equals('b', Path 'a' / Path '../b') | |
assert_equals('/b', Path '/a' / '../b') | |
assert_equals('/b', Path '/a' / Path '../b') | |
end | |
end | |
-------------------------------------------------------------------------------- | |
return Path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment