import { luaAssert } from "./luafuncs" ; export namespace Path { export const separator = ( ( ) => { const config = ( _G . package as typeof _G [ "package" ] & Record < "config" , string | undefined > ) . config ; if ( config ) { const [ sep ] = config . match ( "^[^\n]+" ) ; if ( sep ) { return sep ; } } return "/" ; } ) ( ) ; let cwd ; export function getCwd ( ) { if ( ! cwd ) { const [ p ] = io . popen ( separator === "\\" ? "cd" : "pwd" ) ; if ( p ) { const output = p . read ( "*a" ) ; if ( output ) { [ cwd ] = output . match ( "^%s*(.-)%s*$" ) ; } } cwd = cwd ?? "" ; } return cwd ; } export function dirName ( path ) { const [ dir ] = path . match ( `^(.-)${ separator }+[^${ separator }]+$` ) ; return dir ?? "." ; } export function splitDrive ( path ) { let [ drive , pathPart ] = path . match ( "^[@=]?([a-zA-Z]:)[\\/](.*)" ) ; if ( drive ) { drive = drive . upper ( ) + separator ; } else { [ drive , pathPart ] = path . match ( "^[@=]?([\\/]*)(.*)" ) ; } return $multi ( luaAssert ( drive ) , luaAssert ( pathPart ) ) ; } const formattedPathCache = { } ; export function format ( path ) { let formattedPath = formattedPathCache [ path ] ; if ( ! formattedPath ) { const [ drive , pathOnly ] = splitDrive ( path ) ; const pathParts = [ ] ; for ( const [ part ] of luaAssert ( pathOnly ) . gmatch ( "[^\\/]+" ) ) { if ( part !== "." ) { if ( part === ".." && pathParts . length > 0 && pathParts [ pathParts . length - 1 ] !== ".." ) { table . remove ( pathParts ) ; } else { table . insert ( pathParts , part ) ; } } } const [ formattedDrive ] = drive . gsub ( "[\\/]+" , separator ) ; formattedPath = `${ formattedDrive }${ table . concat ( pathParts , separator ) }` ; formattedPathCache [ path ] = formattedPath ; } return formattedPath ; } export function isAbsolute ( path ) { const [ drive ] = splitDrive ( path ) ; return drive . length > 0 ; } export function getAbsolute ( path ) { if ( isAbsolute ( path ) ) { return format ( path ) ; } return format ( `${ getCwd ( ) }${ separator }${ path }` ) ; } }