Also, for consistency with other APIs, mp.utils.{write,append}_file now return true on success (and still throw on any error).
Showing the changes to player/javascript.c (1 of 3 files). Show all
Unified · Split
| @@ -924,27 +924,31 @@ static void script_get_user_path(js_State *J, void *af) · 923 unmodified lines | ||
| 924 | 924 | js_pushstring(J, mp_get_user_path(af, jctx(J)->mpctx->global, path)); |
| 925 | 925 | } |
| 926 | 926 | |
| 927 | −// args: prefixed file name, data (c-str) | |
| 928 | −static void script_write_file(js_State *J, void *af) | |
| 927 | +// args: is_append, prefixed file name, data (c-str) | |
| 928 | +static void script__write_file(js_State *J, void *af) | |
| 929 | 929 | { |
| 930 | 930 | static const char *prefix = "file://"; |
| 931 | − const char *fname = js_tostring(J, 1); | |
| 932 | − const char *data = js_tostring(J, 2); | |
| 931 | + bool append = js_toboolean(J, 1); | |
| 932 | + const char *fname = js_tostring(J, 2); | |
| 933 | + const char *data = js_tostring(J, 3); | |
| 934 | + const char *opstr = append ? "append" : "write"; | |
| 935 | + | |
| 933 | 936 | if (strstr(fname, prefix) != fname) // simple protection for incorrect use |
| 934 | 937 | js_error(J, "File name must be prefixed with '%s'", prefix); |
| 935 | 938 | fname += strlen(prefix); |
| 936 | 939 | fname = mp_get_user_path(af, jctx(J)->mpctx->global, fname); |
| 937 | − MP_VERBOSE(jctx(J), "Writing file '%s'\n", fname); | |
| 940 | + MP_VERBOSE(jctx(J), "%s file '%s'\n", opstr, fname); | |
| 938 | 941 | |
| 939 | − FILE *f = fopen(fname, "wb"); | |
| 942 | + FILE *f = fopen(fname, append ? "ab" : "wb"); | |
| 940 | 943 | if (!f) |
| 941 | − js_error(J, "Cannot open file for writing: '%s'", fname); | |
| 944 | + js_error(J, "Cannot open (%s) file: '%s'", opstr, fname); | |
| 942 | 945 | add_af_file(af, f); |
| 943 | 946 | |
| 944 | 947 | int len = strlen(data); // limited by terminating null |
| 945 | 948 | int wrote = fwrite(data, 1, len, f); |
| 946 | 949 | if (len != wrote) |
| 947 | − js_error(J, "Cannot write to file: '%s'", fname); | |
| 950 | + js_error(J, "Cannot %s to file: '%s'", opstr, fname); | |
| 951 | + js_pushboolean(J, 1); // success. doesn't touch last_error | |
| 948 | 952 | } |
| 949 | 953 | |
| 950 | 954 | // args: env var name |
| @@ -1179,7 +1183,7 @@ static const struct fn_entry utils_fns[] = { · 228 unmodified lines | ||
| 1179 | 1183 | FN_ENTRY(get_env_list, 0), |
| 1180 | 1184 | |
| 1181 | 1185 | FN_ENTRY(read_file, 2), |
| 1182 | − AF_ENTRY(write_file, 2), | |
| 1186 | + AF_ENTRY(_write_file, 3), | |
| 1183 | 1187 | FN_ENTRY(getenv, 1), |
| 1184 | 1188 | FN_ENTRY(compile_js, 2), |
| 1185 | 1189 | FN_ENTRY(_gc, 1), |