[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: [ANN] file_slurp - read/write entire files from/to a string (module design discussion)
- From: David Manura <dm.lua@...>
- Date: Thu, 3 Nov 2011 22:29:31 -0400
file_slurp [1] provides simple functions to read/write entire files
from/to a string.
SYNOPSIS
-- Example to convert tabs to spaces in a file.
local FS = require 'file_slurp'
local s = FS.readfile 'foo.txt'
s = s:gsub('\t', ' ')
FS.writefile('foo.txt', s)
-- Also supports ascii/binary, error policies, and pipes:
s = FS.readfile('ls -la', 'p')
This is a common pattern. I tried to strike a balance without
over-engineering it so that this module might be commonly used. There
are similar functions in Penlight (`pl.util`), and this alternate
implementation has been submitted to Penlight for consideration, but
regardless that decision, I still plan to maintain it as a standalone
module.
Any comments on the module implementation or style are welcome. Use
of this simple module is also an experiment in finding best practices
for module authoring in Lua. For example, _VERSION = 0.001001 is a
number (not string) of the form x.yyyzzz, which is a style that may be
debatable but allows trivial numeric comparison [2]. The "slurp"
naming was inspired from Perl (e.g. [2]). The module name was chosen
as `file_slurp` rather than `file.slurp` since the latter gives the
false impression that `file` is a table, and `fileslurp` might
initially misread as `files lurp`. On the other hand, function names
are `readfile` and `writefile` even though I prefer inserting
underscores between words for clarity. Clarity isn't an issue in this
case, which follows Lua conventions similar to `loadstring`. The
inclusion of `io.popen` support is also debatable, but it shares most
of the implementation and won't normally pose as a security risk since
the `options` flag would not normally be tainted from user input.
Care is also taken to check the return value of `fh:close()`, which
not everyone bothers with, but that is particularly important with 5.2
pipes. The file was packed for posting on gist and for readability
(e.g. POD-like documentation in a comment at top before code) but can
be easily unpacked as well.
[1] https://gist.github.com/1325400/
[2] lua-users.org/wiki/ModuleVersioning
[3] http://search.cpan.org/perldoc?File::Slurp