Skip to content

Commit

Permalink
stdio: add rename(2) binding.
Browse files Browse the repository at this point in the history
Closes #228, #229
* specs/posix_stdio_spec.yaml (rename): Specify behaviour of
posix.stdio.rename.
* ext/posix/stdio.c (Prename): Bind rename(2).
(posix_stdio_fns): Export Prename.

Signed-off-by: Gary V. Vaughan <gary@gnu.org>
  • Loading branch information
zevv authored and gvvaughan committed Jun 30, 2015
1 parent e2194e5 commit d9f5c65
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
24 changes: 24 additions & 0 deletions ext/posix/stdio.c
Expand Up @@ -98,12 +98,36 @@ Pfdopen(lua_State *L) /** fdopen(fd, mode) */
return 1;
}

/***
Change the name or location of a file
@function rename
@tparam string oldpath
@tparam string newpath
@treturn[1] int `0` if successful
@return[2] nil
@treturn[2] string error message
@treturn[2] int errnum
@see rename(2)
@usage
local ok, errmsg = P.rename (oldpath, newpath)
if not ok then error (errmsg) end
*/
static int
Prename(lua_State *L) /** rename(oldpath, newpath) */
{
const char *oldpath = luaL_checkstring(L, 1);
const char *newpath = luaL_checkstring(L, 2);
checknargs(L, 2);
return pushresult(L, rename(oldpath, newpath), NULL);
}


static const luaL_Reg posix_stdio_fns[] =
{
LPOSIX_FUNC( Pctermid ),
LPOSIX_FUNC( Pfileno ),
LPOSIX_FUNC( Pfdopen ),
LPOSIX_FUNC( Prename ),
{NULL, NULL}
};

Expand Down
26 changes: 25 additions & 1 deletion specs/posix_stdio_spec.yaml
@@ -1,12 +1,12 @@
specify posix.stdio:
- before:
stdio = require "posix.stdio"
unistd = require "posix.unistd"


- describe fdopen:
- before:
fdopen = stdio.fdopen
unistd = require "posix.unistd"
STDOUT_FILENO = unistd.STDOUT_FILENO
f = fdopen (STDOUT_FILENO, "w")

Expand All @@ -19,3 +19,27 @@ specify posix.stdio:
- it writes to the duplicated stream:
-- Lua 5.1 file.write returns true; > 5.1 returns file handle
expect (f:write ("writing to fdopen(stdout)\n")).not_to_be (nil)


- describe rename:
- before:
rename = stdio.rename
fd, path = require "posix.stdlib".mkstemp (template)
- after:
unistd.close (fd)
os.remove (path)

- context with bad arguments:
badargs.diagnose (rename, "(string,string)")

- it renames an existing file:
newpath = path .. ".renamed"
expect (fd).not_to_be (nil)
unistd.write (fd, "rename me")
rename (path, newpath)
expect (io.open (path, "r")).to_be (nil)
fh = io.open (newpath, "r")
expect (fh).not_to_be (nil)
expect (fh:read ()).to_be "rename me"
fh:close ()
rename (newpath, path)

0 comments on commit d9f5c65

Please sign in to comment.