Skip to content

Commit b692454

Browse files
committedNov 8, 2017
Add minetest.safe_write_file() to script API
1 parent 9526c68 commit b692454

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed
 

‎doc/lua_api.txt

+4
Original file line numberDiff line numberDiff line change
@@ -2380,6 +2380,10 @@ Strings that need to be translated can contain several escapes, preceded by `@`.
23802380
* nil: return all entries,
23812381
* true: return only subdirectory names, or
23822382
* false: return only file names.
2383+
* `minetest.safe_file_write(path, content)`: returns boolean indicating success
2384+
* Replaces contents of file at path with new contents in a safe (atomic) way.
2385+
Use this instead of below code when writing e.g. database files:
2386+
`local f = io.open(path, "wb"); f:write(content); f:close()`
23832387
* `minetest.get_version()`: returns a table containing components of the
23842388
engine version. Components:
23852389
* `project`: Name of the project, eg, "Minetest"

‎src/script/lua_api/l_util.cpp

+18
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,23 @@ int ModApiUtil::l_get_dir_list(lua_State *L)
357357
return 1;
358358
}
359359

360+
// safe_file_write(path, content)
361+
int ModApiUtil::l_safe_file_write(lua_State *L)
362+
{
363+
NO_MAP_LOCK_REQUIRED;
364+
const char *path = luaL_checkstring(L, 1);
365+
size_t size;
366+
const char *content = luaL_checklstring(L, 2, &size);
367+
368+
CHECK_SECURE_PATH(L, path, true);
369+
370+
bool ret = fs::safeWriteToFile(path, std::string(content, size));
371+
lua_pushboolean(L, ret);
372+
373+
return 1;
374+
}
375+
376+
// request_insecure_environment()
360377
int ModApiUtil::l_request_insecure_environment(lua_State *L)
361378
{
362379
NO_MAP_LOCK_REQUIRED;
@@ -476,6 +493,7 @@ void ModApiUtil::Initialize(lua_State *L, int top)
476493

477494
API_FCT(mkdir);
478495
API_FCT(get_dir_list);
496+
API_FCT(safe_file_write);
479497

480498
API_FCT(request_insecure_environment);
481499

‎src/script/lua_api/l_util.h

+3
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,9 @@ class ModApiUtil : public ModApiBase
8080
// get_dir_list(path, is_dir)
8181
static int l_get_dir_list(lua_State *L);
8282

83+
// safe_file_write(path, content)
84+
static int l_safe_file_write(lua_State *L);
85+
8386
// request_insecure_environment()
8487
static int l_request_insecure_environment(lua_State *L);
8588

0 commit comments

Comments
 (0)
Please sign in to comment.