Skip to content

Commit 58d6b89

Browse files
authored
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
1 parent 964d81f commit 58d6b89

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

.changes/fs-append-file.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@tauri-apps/api': 'patch:enhance'
3+
'tauri': 'patch:enhance'
4+
---
5+
6+
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.

core/tauri/src/endpoints/file_system.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,10 @@ use serde::{
2323
};
2424
use tauri_macros::{command_enum, module_command_handler, CommandModule};
2525

26-
use std::fmt::{Debug, Formatter};
26+
use std::{
27+
fmt::{Debug, Formatter},
28+
fs::OpenOptions,
29+
};
2730
use std::{
2831
fs,
2932
fs::File,
@@ -49,6 +52,8 @@ pub struct FileOperationOptions {
4952
/// The base directory of the operation.
5053
/// The directory path of the BaseDirectory will be the prefix of the defined file path.
5154
pub dir: Option<BaseDirectory>,
55+
/// Whether writeFile should append to a file or truncate it.
56+
pub append: Option<bool>,
5257
}
5358

5459
/// The API descriptor.
@@ -166,14 +171,24 @@ impl Cmd {
166171
contents: Vec<u8>,
167172
options: Option<FileOperationOptions>,
168173
) -> super::Result<()> {
174+
let append = options
175+
.as_ref()
176+
.and_then(|opt| opt.append)
177+
.unwrap_or_default();
178+
169179
let resolved_path = resolve_path(
170180
&context.config,
171181
&context.package_info,
172182
&context.window,
173183
path,
174184
options.and_then(|o| o.dir),
175185
)?;
176-
File::create(&resolved_path)
186+
187+
OpenOptions::new()
188+
.append(append)
189+
.write(true)
190+
.create(true)
191+
.open(&resolved_path)
177192
.with_context(|| format!("path: {}", resolved_path.display()))
178193
.map_err(Into::into)
179194
.and_then(|mut f| f.write_all(&contents).map_err(|err| err.into()))
@@ -409,6 +424,7 @@ mod tests {
409424
fn arbitrary(g: &mut Gen) -> Self {
410425
Self {
411426
dir: Option::arbitrary(g),
427+
append: Option::arbitrary(g),
412428
}
413429
}
414430
}

tooling/api/src/fs.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,12 @@ export enum BaseDirectory {
110110
*/
111111
interface FsOptions {
112112
dir?: BaseDirectory
113+
/**
114+
* Whether the content should overwrite the content of the file or append to it.
115+
*
116+
* @since 1.5.0
117+
*/
118+
append?: boolean
113119
// note that adding fields here needs a change in the writeBinaryFile check
114120
}
115121

0 commit comments

Comments
 (0)