rootprefix

function rootprefix( path ) --> prefix

Description

Returns the root element from a path, if exiting.

Parameters

path

The path to query.

Return Values

prefix

The root element in the path.

Code

--ZFUNC-rootprefix-v1
local function rootprefix( path ) --> prefix
   local remote = path:match[[^//%w+/]] or path:match[[^\\%w+\]]
   if remote then return remote end

   local unix = path:sub( 1, 1 )
   if unix == "/" then return unix end

   local win = path:match[=[^[a-zA-Z]:[\\/]]=]
   if win then return win end

   return ""
end

return rootprefix

Examples

local t = require( "tapered" )
local rootprefix = require( "rootprefix" )

-- win paths
t.is( "", rootprefix[[a\b\c.txt]] )
t.is( "", rootprefix[[C:a\b\c.txt]] )
t.is( "C:\\", rootprefix[[C:\a\b\c.txt]] )
t.is( "C:/", rootprefix( "C:/a/b/c.txt" ) )
t.is( [[\\server\]], rootprefix[[\\server\a\b\c.txt]] )

-- unix paths
t.is( "", rootprefix( "a/b/c,txt" ) )
t.is( "", rootprefix( "~/a/b/c.txt" ) )
t.is( "/", rootprefix( "/a/b/c.txt" ) )

t.done()