]> git.lizzy.rs Git - minetest.git/commitdiff
Add minetest.safe_write_file() to script API
authorsfan5 <sfan5@live.de>
Tue, 7 Nov 2017 10:46:06 +0000 (11:46 +0100)
committersfan5 <sfan5@live.de>
Wed, 8 Nov 2017 15:14:05 +0000 (16:14 +0100)
doc/lua_api.txt
src/script/lua_api/l_util.cpp
src/script/lua_api/l_util.h

index fd49e8c2276cb9f17ffe404fa9efc0a5709f6daa..9f92aba99fe19983a39eab1a860ba2236e89c6a5 100644 (file)
@@ -2380,6 +2380,10 @@ Strings that need to be translated can contain several escapes, preceded by `@`.
       * 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 ef4df8182c87881d66e44cf76f304594b70a7c71..839c4be1189e061e33bba615c521fe6b373db588 100644 (file)
@@ -357,6 +357,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;
@@ -476,6 +493,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 e17425d733aaf293f03bae3d5a93b4221dd2e36e..4392a4339c0acd2e6ff4d0e99936d6e17e33680b 100644 (file)
@@ -80,6 +80,9 @@ class ModApiUtil : public ModApiBase
        // 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);