From 9fa38d17a20c8277837dd49301599ed3d8d455f2 Mon Sep 17 00:00:00 2001 From: Lorenzo Cogotti Date: Sat, 23 Sep 2023 16:03:12 +0200 Subject: [PATCH] [strings] Add utility to test whether a path is absolute --- strings.lua | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/strings.lua b/strings.lua index b2e9ea9..d49d286 100644 --- a/strings.lua +++ b/strings.lua @@ -155,6 +155,28 @@ function strings.splitpath(path) return path:match("(.-)([^\\/]-)(%.?[^%.\\/]*)$") end +--- Test whether the path is absolute. +-- +-- @string path a path to be tested +-- @string[opt] sep separator pattern, '/' for Unix, '\\' for Windows, if none is provided, path is tested for both +-- @treturn boolean true if path is absolute, false otherwise +function strings.isabspath(path, sep) + if sep == nil then + -- Conservative test, both Unix-style and Windows-style + return strings.isabspath(path, '/') or strings.isabspath(path, '\\') + elseif sep == '/' then + -- Unix-style + return #path >= 1 and path:byte(1) == SLASH + elseif sep == '\\' then + -- Windows-style + return + (#path >= 1 and path:byte(1) == BACKSLASH) or + (#path >= 3 and path:byte(2) == COLON and path:byte(3) == BACKSLASH) + else + error(("Unsupported separator pattern: %q"):format(sep)) + end +end + --- Test whether a string starts with a prefix. -- -- This is an optimized version of: return s:sub(1, #prefix) == prefix.