Module eco.file
File utilities.
This module provides file and filesystem related helpers, bind common POSIX file APIs.
Exported constants:
- open(2) flags:
O_RDONLY,O_WRONLY,O_RDWR,O_APPEND,O_CLOEXEC,O_CREAT,O_EXCL,O_NOCTTY,O_NONBLOCK,O_TRUNC - stat(2) mode bits:
S_IRWXU,S_IRUSR,S_IWUSR,S_IXUSR,S_IRWXG,S_IRGRP,S_IWGRP,S_IXGRP,S_IRWXO,S_IROTH,S_IWOTH,S_IXOTH,S_ISUID,S_ISGID,S_ISVTX - lseek(2) whence:
SEEK_SET,SEEK_CUR,SEEK_END - flock(2) operations:
LOCK_SH,LOCK_EX,LOCK_UN - inotify(7) masks:
IN_ACCESS,IN_MODIFY,IN_ATTRIB,IN_CLOSE_WRITE,IN_CLOSE_NOWRITE,IN_CLOSE,IN_OPEN,IN_MOVED_FROM,IN_MOVED_TO,IN_MOVE,IN_CREATE,IN_DELETE,IN_DELETE_SELF,IN_MOVE_SELF,IN_ALL_EVENTS,IN_ISDIR
Functions
| readfile (path[, m='*a']) | Read contents from a file. |
| writefile (path, data[, append=false]) | Write data to a file. |
| open (path[, flags=file.O_RDONLY[, mode=0]]) | Open and possibly create a file |
| inotify () | Create an inotify watcher. |
| walk (root, cb) | Recursively traverse a directory tree. |
| sync () | Commit filesystem caches to disk
Calls the underlying POSIX sync(2) function. |
| mkdir (pathname[, mode=0777]) | Create a directory. |
| access (file[, mode]) | Test file accessibility. |
| readlink (path) | Read value of a symbolic link. |
| stat (path) | Get file status by path. |
| statvfs (path) | Get filesystem statistics. |
| dir (path) | Iterate a directory. |
| chown (pathname[, uid[, gid]]) | Change owner and group of a file. |
| dirname (path) | Get directory part of a path. |
| basename (path) | Get last path component. |
Fields
| SKIP | Special return value for walk callback to skip descending into the current directory. |
Class file
| file:read () | See read |
| file:readfull () | See readfull |
| file:readuntil () | See readuntil |
| file:write () | See write |
| file:lseek (offset, where) | Reposition read/write file offset. |
| file:stat () | Get file status. |
| file:flock (fd, operation[, timeout]) | Acquire or release an advisory file lock. |
| file:close () | Close the file. |
Class inotify
| inotify:wait ([timeout]) | Wait for an inotify event. |
| inotify:add (path[, mask]) | Add a path to be watched. |
| inotify:del (wd) | Remove a watch by its watch descriptor. |
| inotify:close () | Close the watcher. |
Functions
- readfile (path[, m='*a'])
-
Read contents from a file.
Opens the file in read-only mode and reads data using file:read. The file handle is automatically closed after use.
Parameters:
- path string Path of the file to read.
- m
string or number
Read mode passed to file:read.
- 'a': read the whole file (default)
- 'l': read a line without newline
- 'L': read a line with newline
- 'n': read a number
- int: read specified number of bytes
Returns:
-
any
Result returned by file:read on success.
Or
- nil On failure to open file.
- string Error message when failed.
Usage:
local data, err = file.readfile('/etc/os-release') if not data then print('readfile failed:', err) end
- writefile (path, data[, append=false])
-
Write data to a file.
Opens the file in write mode (
'w') by default, or append mode ('a') whenappendis true.Parameters:
- path string Path of the file to write.
- data string Data to write.
- append boolean Append instead of truncate. (default false)
Returns:
-
boolean
true On success.
Or
- nil On failure.
- string Error message.
Usage:
local ok, err = file.writefile('/tmp/out.txt', 'hello\n') assert(ok, err)
- open (path[, flags=file.O_RDONLY[, mode=0]])
-
Open and possibly create a file
Parameters:
- path string Path of the file.
- flags
int
Open flags (bitwise OR of
file.O_*constants). (default file.O_RDONLY) - mode
int
File mode bits (bitwise OR of
file.S_I*constants, only meaningful with flagfile.O_CREAT). (default 0)
Returns:
-
file
File object on success.
Or
- nil On failure.
- string Error message.
- inotify ()
-
Create an inotify watcher.
Returns:
-
inotify
Watcher object.
Or
- nil On failure.
- string Error message.
Usage:
local w, err = file.inotify() assert(w, err) local wd = assert(w:add('/tmp', file.IN_CREATE | file.IN_DELETE)) while true do local ev = assert(w:wait()) print(ev.name, ev.mask) end
- walk (root, cb)
-
Recursively traverse a directory tree.
For each entry under
root, invokescb(fullpath, name, info).infois the same table returned by dir.Callback return values:
false: terminate traversal- file.SKIP: if the current entry is a directory, do not descend into it
- anything else / nil: continue
Parameters:
- root string Root directory.
- cb function Callback function.
Usage:
file.walk('/etc', function(path, name, info) print(path, info.type) if name == '.git' then return file.SKIP end end)
- sync ()
-
Commit filesystem caches to disk
Calls the underlying POSIX
sync(2)function. - mkdir (pathname[, mode=0777])
-
Create a directory.
Calls the underlying POSIX
mkdir(2)function.Parameters:
- pathname string Path of the directory to create.
- mode int Permission bits for the new directory (before umask). (default 0777)
Returns:
-
boolean
true On success.
Or
- nil On failure.
- string Error message when failed.
Usage:
local ok, err = file.mkdir('/tmp/test', 0755) if not ok then print('mkdir failed:', err) end
- access (file[, mode])
-
Test file accessibility.
Thin wrapper around POSIX
access(2).Parameters:
- file string Path to test.
- mode
string
Access mode string: contains
r,w, orx. If omitted, checks existence (F_OK). (optional)
Returns:
-
boolean
trueif accessible, otherwisefalse. - readlink (path)
-
Read value of a symbolic link.
Thin wrapper around POSIX
readlink(2).Parameters:
- path string Symbolic link path.
Returns:
-
string
Link target.
Or
- nil On failure.
- string Error message.
- stat (path)
-
Get file status by path.
Thin wrapper around POSIX
stat(2).Parameters:
- path string Path to file.
Returns:
Or
- nil On failure.
- string Error message.
- statvfs (path)
-
Get filesystem statistics.
Thin wrapper around
statvfs(3). The returned values are in KiB (kibibytes).Parameters:
- path string Any path on the target filesystem.
Returns:
- number Total size in KiB.
- number Available size in KiB for unprivileged processes.
- number Used size in KiB.
Or
- nil On failure.
- string Error message.
- dir (path)
-
Iterate a directory.
Convenience iterator around
opendir(3)/readdir(3). Each iteration returns entry name and a stat style info table.Parameters:
- path string Directory path.
Returns:
- function Iterator function.
- any Iterator state.
- any Iterator initial value.
-
any
A closeable userdata (for
__close).
Usage:
for name, info in file.dir('/tmp') do print(name, info.type, info.size) end
- chown (pathname[, uid[, gid]])
-
Change owner and group of a file.
Thin wrapper around POSIX
chown(2). To keep a value unchanged, passnilfor that argument.Parameters:
- pathname string Path of the file.
- uid
int
New user id, or
nilto keep. (optional) - gid
int
New group id, or
nilto keep. (optional)
Returns:
-
boolean
true On success.
Or
- nil On failure.
- string Error message.
- dirname (path)
-
Get directory part of a path.
Wrapper around
dirname(3).Parameters:
- path string Input path.
Returns:
-
string
Directory component.
- basename (path)
-
Get last path component.
Wrapper around
basename(3).Parameters:
- path string Input path.
Returns:
-
string
Base name.
Fields
- SKIP
- Special return value for walk callback to skip descending into the current directory.
Class file
This object wraps a file descriptor.
- file:read ()
- See read
- file:readfull ()
- See readfull
- file:readuntil ()
- See readuntil
- file:write ()
- See write
- file:lseek (offset, where)
-
Reposition read/write file offset.
Parameters:
- offset int Offset.
- where
int
One of
file.SEEK_SET,file.SEEK_CUR,file.SEEK_END.
Returns:
-
int
New offset on success.
Or
- nil On failure.
- string Error message.
- file:stat ()
-
Get file status.
Thin wrapper around POSIX
fstat(2).Returns:
Or
- nil On failure.
- string Error message.
- file:flock (fd, operation[, timeout])
-
Acquire or release an advisory file lock.
Parameters:
- fd int File descriptor.
- operation
int
Lock operation (
file.LOCK_SH,file.LOCK_EX,file.LOCK_UN). - timeout number Timeout in seconds. (optional)
Returns:
-
boolean
true On success.
Or
- nil On failure.
-
string
Error message (or
'timeout').
- file:close ()
-
Close the file.
This is idempotent and is also used as the
__gc/__closemetamethod.
Class inotify
- inotify:wait ([timeout])
-
Wait for an inotify event.
If there are already parsed events buffered in the watcher, returns the next one immediately; otherwise, reads from the underlying inotify fd.
The returned event is a table with fields:
name: full path of the affected entrymask: inotify mask bits (file.IN_ACCESS,file.IN_MODIFY,file.IN_OPEN,...)
Parameters:
- timeout number Timeout in seconds. (optional)
Returns:
-
table
Event table
{ name = string, mask = int }.Or
- nil On timeout or error.
- string Error message.
Usage:
local w = assert(file.inotify()) assert(w:add('/tmp', file.IN_CREATE | file.IN_DELETE)) while true do local ev = assert(w:wait()) print(ev.name, ev.mask) end
- inotify:add (path[, mask])
-
Add a path to be watched.
Parameters:
- path string Path to watch.
- mask
int
Event mask. Defaults to
file.IN_ALL_EVENTS. (optional)
Returns:
-
int
Watch descriptor (
wd).Or
- nil On failure.
- string Error message.
Usage:
local w = assert(file.inotify()) local wd = assert(w:add('/tmp', file.IN_CREATE))
- inotify:del (wd)
-
Remove a watch by its watch descriptor.
Parameters:
- wd int Watch descriptor returned by inotify:add.
Returns:
-
boolean
true On success.
Or
- nil On failure.
- string Error message.
- inotify:close ()
- Close the watcher.