From f21a44e55314948416f4bd59f756bec68f0ae2d5 Mon Sep 17 00:00:00 2001 From: Ted Trask Date: Fri, 15 May 2009 09:51:55 +0000 Subject: Added fs.move_file function because os.rename only works on same device. --- lib/fs.lua | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'lib/fs.lua') diff --git a/lib/fs.lua b/lib/fs.lua index 63991d4..962326c 100644 --- a/lib/fs.lua +++ b/lib/fs.lua @@ -93,6 +93,28 @@ function copy_file(oldpath, newpath) return is_file(newpath) end +-- Moves a file to a directory or new filename (creating the directory if necessary) +-- fails if new file already exists +function move_file(oldpath, newpath) + if not is_file(oldpath) or not newpath or newpath == "" or (basename(newpath) ~= "" and posix.stat(newpath)) or (basename(newpath) == "" and posix.stat(newpath .. basename(oldpath))) then + return false + end + if dirname(newpath) and not posix.stat(dirname(newpath)) then create_directory(dirname(newpath)) end + if basename(newpath) == "" then newpath = newpath .. basename(oldpath) end + local status, errstr, errno = os.rename(oldpath, newpath) + -- errno 18 means Invalid cross-device link + if status or errno ~= 18 then + -- successful move or failure due to something else + return (status ~= nil), errstr, errno + else + status = copy_file(oldpath, newpath) + if status then + os.remove(oldpath) + end + return status + end +end + -- Returns the contents of a file as a string function read_file ( path ) local file = io.open(path or "") -- cgit v1.2.3