GeMA
The GeMA main application
FileLib

Introduction

FileLib is a set of utilitary functions for file and directory manipulation, complementing the standard functions provided by the os Lua functions. All the provided functions support both Windows and Linux style path separators (\ or /) and path macro expansion, making it unnecessary to make use of the translatePath() function. Instead of relying on external extensions, several of the provided functions are implemented by calling the appropriate system shell command through os.execute() so, when appropriate, file name wildcards should conform to the current system standard.

Important: Please rememeber that the library must be loaded, before the first call to one of its exported methods, by a call to dofile("$SCRIPTS/fileLib.lua").

Index:

Exported constants

fileLib.platform
Description: Returns the type of the platform where the simulation is running. Stored values con be either "windows" or "linux".

Example:

if fileLib.platform == 'windows' then
... -- Do Windows stuff
else
... -- Do Linux studd
end


fileLib.separator
Description: Returns the path separator character used by the current platform. Can de either / (Linux) or \ (Windows).

Example:

local fullPath = 'myPath'..fileLib.separator..'myfile.txt'


Path translation functions

fileLib.toNativeSeparators(path, keepMacros)
Description: Converts path separators to the platform standard (\ on Windows and / on Linux). Unless keepMacros is true, macros in the path, such as $SIMULATIONDIR, will be replaced by their values. This function also 'cleans' the path by removing . and .. occurrences, duplicated separators and separators on the end of the path.
Parameters: path The path to be converted.
keepMacros An optional boolean parameter that when set to true prevents path macros on the given path to be expanded.
Returns: Returns the converted path.

Example:

local realPath = fileLib.toNativeSeparators('$SIMULATIONDIR/teste.pos')


fileLib.toStdSeparators(path, keepMacros)
Description: Converts path separators to the Linux (/) standard. It can be used in most file functions, including those exported by GeMA and by the standard Lua io library, independently of the platform. Unfortunately it can not be used in calls to os.execute() on Windows. Unless keepMacros is true, macros in the path, such as $SIMULATIONDIR, will be replaced by their values. This function also 'cleans' the path by removing . and .. occurrences, duplicated separators and separators on the end of the path.
Parameters: path The path to be converted.
keepMacros An optional boolean parameter that when set to true prevents path macros on the given path to be expanded.
Returns: Returns the converted path.

Example:

local realPath = fileLib.toStdSeparators('$SIMULATIONDIR/teste.pos')


Path handling functions

fileLib.isAbsolute(path)
Description: Returns true if the given path is an absolute path. Absolute paths are detected by the presence of a path separator at the first character or by a drive letter (on Windows).
Parameters: path - The path to be queried.
Returns: Returns true if the given path is an absolute path, false otherwise.

Example:

print(fileLib.isAbsolute('/Documents/Gema/model.lua')) -- Prints true
print(fileLib.isAbsolute('Gema/model.lua')) -- Prints false


fileLib.isRoot(path)
Description: Returns true if the given path is the root directory. For relative paths, tries to remove back references from the current directory to determine if the path is the root directory or not.
Parameters: path - The path to be queried.
Returns: Returns true if the given path is the root path, false otherwise.

Example:

print(fileLib.isRoot('c:/')) -- Prints true
print(fileLib.isRoot('../')) -- Result depends on the current directory


fileLib.splitPath(path, keepMacros)
Description: Splits the given path into its subdirectories and file components, returning a table listing all of them. The path "abc/def/xyz.txt" is converted into the table {"abc", "def", "xyz.txt"}. The global path "/abc/def/xyz.txt" is converted into the table {"", "abc", "def", "xyz.txt"} while "c:/abc/def/xyz.txt" is transformed into {"c:", "abc", "def", "xyz.txt"}. The input path is also cleaned, as described in fileLib.toStdSeparators(). Unless keepMacros is true, macros in the path, such as $SIMULATIONDIR, will be replaced by their values.
Parameters: path The path to be splitted.
keepMacros An optional boolean parameter that when set to true prevents path macros on the given path to be expanded.
Returns: Returns a table with the splitted path.

Example:

local t = fileLib.splitPath('abc/def/xyz.txt')
for _, name in ipairs(t) do
print(name) -- Will print 'abc', 'def' and 'xyz.txt'
end


fileLib.filePath(filePath, keepMacros)
Description: Returns the path part of the given file name. The input path is also cleaned, as described in fileLib.toStdSeparators(), but the returned path will include a terminating /, unless the given filePath does not includes a path at all, when it will return an empty string. This is necessary to distinguish an empty path (user gave just the file name) from the root directory. Unless keepMacros is true, macros in the path, such as $SIMULATIONDIR, will be replaced by their values.
Parameters: filePath The file path.
keepMacros An optional boolean parameter that when set to true prevents path macros on the given file path to be expanded.
Returns: Returns the given file path, without the file name.

Example:

local path = fileLib.filePath('abc/def/xyz.txt') -- path will be equal to "abc/def/"
local name = fileLib.filePath('abc/def/xyz.txt') -- name will be equal to "xyz.txt"


fileLib.fileName(filePath, noext, keepMacros)
Description: Returns the file name from a full file path. If noext is true, the file extension (defined by the last set of characters after the last .), together with the separating dot, will be removed from the result. Unless keepMacros is true, macros in the file name, such as $SIMULATIONNAME, will be replaced by their values.
Parameters: filePath The file path.
noext An optional boolean parameter that when set to true prevents the file extension to be included in the returned string.
keepMacros An optional boolean parameter that when set to true prevents path macros on the given file path to be expanded.
Returns: Returns the given file name, without the path part.

Example:

local name1 = fileLib.fileName('abc/def/xyz.txt') -- name1 will be equal to "xyz.txt"
local name2 = fileLib.fileName('abc/def/xyz.txt', true) -- name2 will be equal to "xyz"


fileLib.fileExtension(filePath, keepMacros)
Description: Returns the file extension, defined by the last set of characters after the last ., from a file name. Unless keepMacros is true, macros in the file name, such as $yy, will be replaced by their values.
Parameters: filePath The file path.
keepMacros An optional boolean parameter that when set to true prevents path macros on the given file path to be expanded.
Returns: Returns the given file extension.

Example:

local ext1 = fileLib.fileExtension('abc/def/xyz.txt') -- ext1 will be equal to "txt"
local ext2 = fileLib.fileExtension('abc/def/xyz.temp.txt') -- ext2 will be equal to "txt"


Common functions (work with both files and directories)

fileLib.exists(path)
Description: Checks if a path consisting either of a file name or a directory name exists. The given path can contain macro names and/or any kind of path separators. Operates by trying to rename the path to itself. Returns true if the path exists, nil if not.
Parameters: path - The file or directory path.
Returns: Returns true if the path exists, nil if not.

Example:

if fileLib.exists('$SIMULATIONDIR/abc/xyz.txt') then
...
end


fileLib.isDir(path)
Description: Checks if the given path refers to a directory or not. The given path can contain macro names and/or any kind of path separators. Returns nil if the path doesn't exists, false if it exists but is a file and true if it is a directory.
Parameters: path - The file or directory path.
Returns: Returns nil if the path doesn't exists, false if it exists but is a file and true if it is a directory.

Example:

if fileLib.isDir('$SIMULATIONDIR/out') then
...
end


fileLib.copy(srcPath, dstPath, nomsg)
Description: Copies the given source file(s) to the given destination. On Windows, operates by calling the shell command copy /y. On linux by calling cp -f. If nomsg is set to true, redirects any shell messages to null, preventing them from appearing. Since this function uses the standard shell copying facilities, the given src can contain wildcards as interpreted by the shell. The given paths can also contain macro names and/or any kind of path separators.
Parameters: srcPath The source file(s) path. Can be a directory and/or contain wildcards.
dstPath The destination path.
nomsg An optional boolean parameter that when set to true redirects to null any messages written by the shell.
Returns: Returns true on success. On error, returns nil followed by a message, followed by an optional error code.

Example:

fileLib.copy('$SIMULATIONDIR/abc.txt', '$SIMULATIONDIR/def.txt')


fileLib.remove(path, nomsg)
Description: Removes the given file or directory. A directory is removed only when empty. For removing a directory with files, use the fileLib.dirRemove() function. On Windows, removing a directory operates by calling the shell command rmdir. In that case, if nomsg is set to true, redirects any shell messages to null, preventing them from appearing. The given path can contain macro names and/or any kind of path separators.
Parameters: path The file or directory path.
nomsg An optional boolean parameter that when set to true redirects to null any messages written by the shell.
Returns: Returns true on success. On error, returns nil followed by a message, followed by an optional error code.

Example:

fileLib.remove('$SIMULATIONDIR/abc.txt')


fileLib.rename(oldPath, newPath)
Description: Renames the given file or directory. Since the end location of the renamed file/directory can be different on the given old and new paths, this function can also be used to move files/directories around. The given paths can contain macro names and/or any kind of path separators.
Equivalent to calling os.rename(translatePath(oldFilePath),translatePath(newFilePath)).
Parameters: oldPath The old file or directory path.
newPath The new file or directory path.
Returns: Returns true on success. On error, returns nil followed by a message, followed by an optional error code.

Example:

fileLib.rename('$SIMULATIONDIR/abc.txt', '$SIMULATIONDIR/def.txt')


File handling functions

fileLib.fileOpen(filePath, mode)
Description: Opens the given file with the given mode. Equivalent to calling io.open(translatePath(filePath), mode).
Parameters: filePath The path to the file to be opened.
mode Opening mode. See the Lua documentation for the io.open() function.
Returns: Returns the Lua file handle on success. On error, returns nil followed by a message.

Example:

local fileh = fileLib.fileOpen('$SIMULATIONDIR/abc.txt', 'w')


fileLib.fileCompare(file1, file2, format, tolerance)
Description: Compares two files, returning true if the files are equal. The format parameter defines the type of comparisson. See below. For non text based comparisson, the tolerance parameter can be used to provide a tolerance to be used on numerical value comparissons. The given paths can contain macro names and/or any kind of path separators.
Parameters: file1 The path for the first file to be compared.
file2 The path for the second file to be compared.
format Optional parameter defining the comparisson type. Options are:
'text' - Compares two text files. No interpretation. Files must match exactly.
'log' - Compares two GeMA log files generated with the -regression command line flag. Lines between GeMA_BEGIN and GeMA_END lines will be interpreted and numeric values compared as such using the provided tolerance.
'nf' - Compares two Neutral files generated by GeMA. The file date is ignored. Numeric values on data lines are compared as such using the provided tolerance.
The default when this parameter is missing is "text"
tolerance Optional relative tolerance. For both "log" and "nf" formats, if no tolerance is given, the numbers are compared with the standard == operator. When given, it should be a relative tolerance (0.1 means 10%, 0.01 means 1%, and so on).
Returns: Returns true if the files are equal, false followed by an error message if they are different.

Example:

local ok, err = fileLib.fileCompare('$SIMULATIONDIR/abc.txt', '$SIMULATIONDIR/def.txt', 'nf')


Directory handling functions

fileLib.dirCurrent()
Description: Returns the current directory by calling, from the command shell, cd on Windows or pwd on Linux.
Parameters: None.
Returns: Returns the crurrent directory on success. On error, returns nil followed by an error message.

Example:

print(fileLib.dirCurrent())


fileLib.dirList(mask, options)
Description: Returns a table with the list of files following the given mask (which can include a path). Operates by calling the shell command dir on Windows or ls on Linux. The given path can contain macro names and/or any kind of path separators. The possible switches for the optional options table are defined below.
Parameters: mask The mask selecting the files and/or directories to be listed.
options An optional Lua table providing a set of boolean options controlling the entries that will be included in the result list. Available options are:
dironly - table will list directory entries only (overrides fileonly).
fileonly - table will list file entries only.
showhidden - table will include hidden files/directories.
Returns: Returns a table with the listed files. On error, returns nil followed by an error message, followed by an optional error code.

Example:

-- Get the list of files on the out dir, ignoring sub-directories.
local t = fileLib.dirList('out/*', {fileonly = true})
-- Print file names
for _, name in ipairs(t) do
print(name)
end


fileLib.dirCreate(path, nomsg)
Description: Creates the given directory. If the path contains missing subdirectories, those will be created too (on Windows that depends on command extensions beeing enabled, which is the default). Operates by calling the shell command mkdir. If nomsg is set to true, redirects any shell messages to null, preventing them from appearing. The given path can contain macro names and/or any kind of path separators.
Parameters: path The directory path.
nomsg An optional boolean parameter that when set to true redirects to null any messages written by the shell.
Returns: Returns true on success. On error, returns nil followed by a message, followed by an optional error code.

Example:

-- Creates the output directory if it already doesn't exists
fileLib.dirCreate('$SIMULATIONDIR/out', true)


fileLib.dirRemove(path, nomsg)
Description: Removes the given directory, together with all its contents. Use it carefully (what if path is your root directory or your Windows folder path???). In order to prevent disasters, this function will try to prevent removing the volume root directory (no guarantees though), but that is the only help it provides. On Windows, operates by calling the shell command rmdir /s /q. On linux by calling rm -rf. If nomsg is set to true, redirects any shell messages to null, preventing them from appearing. The given path can contain macro names and/or any kind of path separators.
Parameters: path The directory path.
nomsg An optional boolean parameter that when set to true redirects to null any messages written by the shell.
Returns: Returns true on success. On error, returns nil followed by a message, followed by an optional error code.

Example:

-- Removes the output directory and ALL its contents
fileLib.dirRemove('$SIMULATIONDIR/out')


fileLib.dirClear(mask, options)
Description: Removes files and / or directories returned by a call to fileLib.dirList(mask, options). Directories selected for removal are removed even if not empty, removing all its contents. Use it carefully (what if path is your root directory or your Windows folder path and the mask * or *.* ???). In order to prevent disasters, this function will try to prevent removing all files from the volume root directory (no guarantees though), but that is the only help it provides. The given path can contain macro names and/or any kind of path separators.
Parameters: mask The mask defining the files and/or directories that will be deleted.
options An optional Lua table providing a set of boolean options controlling the entries that will be included in the 'to delete' list. Available options are:
dironly - table will list directory entries only (overrides fileonly).
fileonly - table will list file entries only.
showhidden - table will include hidden files/directories.
Returns: Returns true on success. On error, returns nil followed by a message, followed by an optional error code.

Example:

-- Removes all .txt file from the out directory
fileLib.dirClear('out/*.txt')