fix(fs): fix panic due to unwrap & truncate by default (#847)

* fix(fs): fix panic due to unwrap & truncate by default

closes #846

* fmt and change file
pull/857/head
Amr Bashir 1 year ago committed by GitHub
parent 38b5d37b54
commit c60123093d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -0,0 +1,6 @@
---
"fs": "patch"
"fs-js": "patch"
---
Add `createNew` option for `writeFile` and `writeTextFile` to create the file if doesn't exist and fail if it does.

@ -0,0 +1,6 @@
---
"fs": "patch"
"fs-js": "patch"
---
Truncate files when using `writeFile` and `writeTextFile` with `append: false`.

@ -0,0 +1,6 @@
---
"fs": "patch"
"fs-js": "patch"
---
Fix panic when using `writeFile` or `writeTextFile` without passing an option object.

@ -980,6 +980,8 @@ interface WriteFileOptions {
append?: boolean;
/** Sets the option to allow creating a new file, if one doesn't already exist at the specified path (defaults to `true`). */
create?: boolean;
/** Sets the option to create a new file, failing if it already exists. */
createNew?: boolean;
/** File permissions. Ignored on Windows. */
mode?: number;
/** Base directory for `path` */
@ -1023,7 +1025,7 @@ async function writeFile(
*
* await writeTextFile('file.txt', "Hello world", { dir: BaseDirectory.App });
* ```
*
*
* @since 2.0.0
*/
async function writeTextFile(

@ -579,11 +579,16 @@ pub fn write<R: Runtime>(
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WriteFileOptions {
#[serde(flatten)]
base: BaseOptions,
append: Option<bool>,
create: Option<bool>,
#[serde(default)]
append: bool,
#[serde(default)]
create: bool,
#[serde(default)]
create_new: bool,
#[allow(unused)]
mode: Option<u32>,
}
@ -597,18 +602,25 @@ fn write_file_inner<R: Runtime>(
let resolved_path = resolve_path(&app, path, options.as_ref().and_then(|o| o.base.base_dir))?;
let mut opts = std::fs::OpenOptions::new();
opts.append(options.as_ref().map(|o| o.append.unwrap_or(false)).unwrap());
opts.create(options.as_ref().map(|o| o.create.unwrap_or(true)).unwrap());
// defaults
opts.read(false).write(true).truncate(true).create(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
if let Some(Some(mode)) = options.map(|o| o.mode) {
opts.mode(mode & 0o777);
if let Some(options) = options {
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
if let Some(mode) = options.mode {
opts.mode(mode);
}
}
opts.create(options.create)
.append(options.append)
.truncate(!options.append)
.create_new(options.create_new);
}
let mut file = opts.write(true).open(&resolved_path).map_err(|e| {
let mut file = opts.open(&resolved_path).map_err(|e| {
format!(
"failed to open file at path: {} with error: {e}",
resolved_path.display()

Loading…
Cancel
Save