From 58d6b899e21d37bb42810890d289deb57f2273bd Mon Sep 17 00:00:00 2001 From: Fabian-Lars Date: Wed, 16 Aug 2023 18:09:05 +0200 Subject: [PATCH] feat(api): Add `append` option to writeFile apis (#7636) * feat(api): Add `append` option to writeFile apis. * wording * fmt * Update .changes/fs-append-file.md * clippeeeyyyy --- .changes/fs-append-file.md | 6 ++++++ core/tauri/src/endpoints/file_system.rs | 20 ++++++++++++++++++-- tooling/api/src/fs.ts | 6 ++++++ 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 .changes/fs-append-file.md diff --git a/.changes/fs-append-file.md b/.changes/fs-append-file.md new file mode 100644 index 00000000000..a55e0dcbbeb --- /dev/null +++ b/.changes/fs-append-file.md @@ -0,0 +1,6 @@ +--- +'@tauri-apps/api': 'patch:enhance' +'tauri': 'patch:enhance' +--- + +Add `append` option to `FsOptions` in the `fs` JS module, used in `writeTextFile` and `writeBinaryFile`, to be able to append to existing files instead of overwriting it. diff --git a/core/tauri/src/endpoints/file_system.rs b/core/tauri/src/endpoints/file_system.rs index 0acea50db38..48e62f9bc56 100644 --- a/core/tauri/src/endpoints/file_system.rs +++ b/core/tauri/src/endpoints/file_system.rs @@ -23,7 +23,10 @@ use serde::{ }; use tauri_macros::{command_enum, module_command_handler, CommandModule}; -use std::fmt::{Debug, Formatter}; +use std::{ + fmt::{Debug, Formatter}, + fs::OpenOptions, +}; use std::{ fs, fs::File, @@ -49,6 +52,8 @@ pub struct FileOperationOptions { /// The base directory of the operation. /// The directory path of the BaseDirectory will be the prefix of the defined file path. pub dir: Option, + /// Whether writeFile should append to a file or truncate it. + pub append: Option, } /// The API descriptor. @@ -166,6 +171,11 @@ impl Cmd { contents: Vec, options: Option, ) -> super::Result<()> { + let append = options + .as_ref() + .and_then(|opt| opt.append) + .unwrap_or_default(); + let resolved_path = resolve_path( &context.config, &context.package_info, @@ -173,7 +183,12 @@ impl Cmd { path, options.and_then(|o| o.dir), )?; - File::create(&resolved_path) + + OpenOptions::new() + .append(append) + .write(true) + .create(true) + .open(&resolved_path) .with_context(|| format!("path: {}", resolved_path.display())) .map_err(Into::into) .and_then(|mut f| f.write_all(&contents).map_err(|err| err.into())) @@ -409,6 +424,7 @@ mod tests { fn arbitrary(g: &mut Gen) -> Self { Self { dir: Option::arbitrary(g), + append: Option::arbitrary(g), } } } diff --git a/tooling/api/src/fs.ts b/tooling/api/src/fs.ts index 9d47b8a19a4..956073e0186 100644 --- a/tooling/api/src/fs.ts +++ b/tooling/api/src/fs.ts @@ -110,6 +110,12 @@ export enum BaseDirectory { */ interface FsOptions { dir?: BaseDirectory + /** + * Whether the content should overwrite the content of the file or append to it. + * + * @since 1.5.0 + */ + append?: boolean // note that adding fields here needs a change in the writeBinaryFile check }