Add minetest.safe_write_file() to script API
authorsfan5 <sfan5@live.de>
Tue, 7 Nov 2017 10:46:06 +0000 (11:46 +0100)
committerSmallJoker <mk939@ymail.com>
Sun, 3 Jun 2018 15:32:00 +0000 (17:32 +0200)
doc/lua_api.txt
src/script/lua_api/l_util.cpp
src/script/lua_api/l_util.h

index 13881ef700d7f37f83068e1d7d4bb950f8619683..ab5caca0d9f9cbe8b272101ef1f0c80e136b4eea 100644 (file)
@@ -2223,6 +2223,10 @@ Helper functions
       * nil: return all entries,
       * true: return only subdirectory names, or
       * false: return only file names.
+* `minetest.safe_file_write(path, content)`: returns boolean indicating success
+    * Replaces contents of file at path with new contents in a safe (atomic) way.
+      Use this instead of below code when writing e.g. database files:
+      `local f = io.open(path, "wb"); f:write(content); f:close()`
 * `minetest.get_version()`: returns a table containing components of the
    engine version.  Components:
     * `project`: Name of the project, eg, "Minetest"
index 901105fe07c8c6e0c77a175098fc736be99d6948..aaccf17ee70605062a650d898faa288213e8b06a 100644 (file)
@@ -356,6 +356,23 @@ int ModApiUtil::l_get_dir_list(lua_State *L)
        return 1;
 }
 
+// safe_file_write(path, content)
+int ModApiUtil::l_safe_file_write(lua_State *L)
+{
+       NO_MAP_LOCK_REQUIRED;
+       const char *path = luaL_checkstring(L, 1);
+       size_t size;
+       const char *content = luaL_checklstring(L, 2, &size);
+
+       CHECK_SECURE_PATH(L, path, true);
+
+       bool ret = fs::safeWriteToFile(path, std::string(content, size));
+       lua_pushboolean(L, ret);
+
+       return 1;
+}
+
+// request_insecure_environment()
 int ModApiUtil::l_request_insecure_environment(lua_State *L)
 {
        NO_MAP_LOCK_REQUIRED;
@@ -475,6 +492,7 @@ void ModApiUtil::Initialize(lua_State *L, int top)
 
        API_FCT(mkdir);
        API_FCT(get_dir_list);
+       API_FCT(safe_file_write);
 
        API_FCT(request_insecure_environment);
 
index 16f4edea89d5854197d0b0b658e225622d49397d..872e436257c6d8fc9828ed2e984c2f7a25596480 100644 (file)
@@ -81,6 +81,9 @@ private:
        // get_dir_list(path, is_dir)
        static int l_get_dir_list(lua_State *L);
 
+       // safe_file_write(path, content)
+       static int l_safe_file_write(lua_State *L);
+
        // request_insecure_environment()
        static int l_request_insecure_environment(lua_State *L);