forked from tauri-apps/plugins-workspace
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommands.rs
More file actions
1282 lines (1169 loc) · 35.6 KB
/
commands.rs
File metadata and controls
1282 lines (1169 loc) · 35.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// Copyright 2018-2023 the Deno authors.
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use serde::{Deserialize, Serialize, Serializer};
use serde_repr::{Deserialize_repr, Serialize_repr};
use tauri::{
ipc::{CommandScope, GlobalScope},
path::BaseDirectory,
utils::config::FsScope,
Manager, Resource, ResourceId, Runtime, Webview,
};
use std::{
borrow::Cow,
fs::File,
io::{BufRead, BufReader, Read, Write},
path::{Path, PathBuf},
str::FromStr,
sync::Mutex,
time::{SystemTime, UNIX_EPOCH},
};
use crate::{scope::Entry, Error, SafeFilePath};
#[derive(Debug, thiserror::Error)]
pub enum CommandError {
#[error(transparent)]
Anyhow(#[from] anyhow::Error),
#[error(transparent)]
Plugin(#[from] Error),
#[error(transparent)]
Tauri(#[from] tauri::Error),
#[error(transparent)]
Json(#[from] serde_json::Error),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
UrlParseError(#[from] url::ParseError),
#[cfg(feature = "watch")]
#[error(transparent)]
Watcher(#[from] notify::Error),
}
impl From<String> for CommandError {
fn from(value: String) -> Self {
Self::Anyhow(anyhow::anyhow!(value))
}
}
impl From<&str> for CommandError {
fn from(value: &str) -> Self {
Self::Anyhow(anyhow::anyhow!(value.to_string()))
}
}
impl Serialize for CommandError {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
if let Self::Anyhow(err) = self {
serializer.serialize_str(format!("{err:#}").as_ref())
} else {
serializer.serialize_str(self.to_string().as_ref())
}
}
}
pub type CommandResult<T> = std::result::Result<T, CommandError>;
#[derive(Debug, Default, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BaseOptions {
base_dir: Option<BaseDirectory>,
}
#[tauri::command]
pub fn create<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<ResourceId> {
let resolved_path = resolve_path(
&webview,
&global_scope,
&command_scope,
path,
options.and_then(|o| o.base_dir),
)?;
let file = File::create(&resolved_path).map_err(|e| {
format!(
"failed to create file at path: {} with error: {e}",
resolved_path.display()
)
})?;
let rid = webview.resources_table().add(StdFileResource::new(file));
Ok(rid)
}
#[derive(Debug, Default, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OpenOptions {
#[serde(flatten)]
base: BaseOptions,
#[serde(flatten)]
options: crate::OpenOptions,
}
#[tauri::command]
pub fn open<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<OpenOptions>,
) -> CommandResult<ResourceId> {
let (file, _path) = resolve_file(
&webview,
&global_scope,
&command_scope,
path,
if let Some(opts) = options {
OpenOptions {
base: opts.base,
options: opts.options,
}
} else {
OpenOptions {
base: BaseOptions { base_dir: None },
options: crate::OpenOptions {
read: true,
write: false,
truncate: false,
create: false,
create_new: false,
append: false,
mode: None,
custom_flags: None,
},
}
},
)?;
let rid = webview.resources_table().add(StdFileResource::new(file));
Ok(rid)
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CopyFileOptions {
from_path_base_dir: Option<BaseDirectory>,
to_path_base_dir: Option<BaseDirectory>,
}
#[tauri::command]
pub async fn copy_file<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
from_path: SafeFilePath,
to_path: SafeFilePath,
options: Option<CopyFileOptions>,
) -> CommandResult<()> {
let resolved_from_path = resolve_path(
&webview,
&global_scope,
&command_scope,
from_path,
options.as_ref().and_then(|o| o.from_path_base_dir),
)?;
let resolved_to_path = resolve_path(
&webview,
&global_scope,
&command_scope,
to_path,
options.as_ref().and_then(|o| o.to_path_base_dir),
)?;
std::fs::copy(&resolved_from_path, &resolved_to_path).map_err(|e| {
format!(
"failed to copy file from path: {}, to path: {} with error: {e}",
resolved_from_path.display(),
resolved_to_path.display()
)
})?;
Ok(())
}
#[derive(Debug, Clone, Deserialize)]
pub struct MkdirOptions {
#[serde(flatten)]
base: BaseOptions,
#[allow(unused)]
mode: Option<u32>,
recursive: Option<bool>,
}
#[tauri::command]
pub fn mkdir<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<MkdirOptions>,
) -> CommandResult<()> {
let resolved_path = resolve_path(
&webview,
&global_scope,
&command_scope,
path,
options.as_ref().and_then(|o| o.base.base_dir),
)?;
let mut builder = std::fs::DirBuilder::new();
builder.recursive(options.as_ref().and_then(|o| o.recursive).unwrap_or(false));
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
let mode = options.as_ref().and_then(|o| o.mode).unwrap_or(0o777) & 0o777;
builder.mode(mode);
}
builder
.create(&resolved_path)
.map_err(|e| {
format!(
"failed to create directory at path: {} with error: {e}",
resolved_path.display()
)
})
.map_err(Into::into)
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct DirEntry {
pub name: String,
pub is_directory: bool,
pub is_file: bool,
pub is_symlink: bool,
}
#[tauri::command]
pub async fn read_dir<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<Vec<DirEntry>> {
let resolved_path = resolve_path(
&webview,
&global_scope,
&command_scope,
path,
options.as_ref().and_then(|o| o.base_dir),
)?;
let entries = std::fs::read_dir(&resolved_path).map_err(|e| {
format!(
"failed to read directory at path: {} with error: {e}",
resolved_path.display()
)
})?;
let entries = entries
.filter_map(|entry| {
let entry = entry.ok()?;
let name = entry.file_name().into_string().ok()?;
let metadata = entry.file_type();
macro_rules! method_or_false {
($method:ident) => {
if let Ok(metadata) = &metadata {
metadata.$method()
} else {
false
}
};
}
Some(DirEntry {
name,
is_file: method_or_false!(is_file),
is_directory: method_or_false!(is_dir),
is_symlink: method_or_false!(is_symlink),
})
})
.collect();
Ok(entries)
}
#[tauri::command]
pub async fn read<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
len: usize,
) -> CommandResult<tauri::ipc::Response> {
let mut data = vec![0; len];
let file = webview.resources_table().get::<StdFileResource>(rid)?;
let nread = StdFileResource::with_lock(&file, |mut file| file.read(&mut data))
.map_err(|e| format!("faied to read bytes from file with error: {e}"))?;
// This is an optimization to include the number of read bytes (as bigendian bytes)
// at the end of returned vector so we can use `tauri::ipc::Response`
// and avoid serialization overhead of separate values.
#[cfg(target_pointer_width = "16")]
let nread = {
let nread = nread.to_be_bytes();
let mut out = [0; 8];
out[6..].copy_from_slice(&nread);
out
};
#[cfg(target_pointer_width = "32")]
let nread = {
let nread = nread.to_be_bytes();
let mut out = [0; 8];
out[4..].copy_from_slice(&nread);
out
};
#[cfg(target_pointer_width = "64")]
let nread = nread.to_be_bytes();
data.extend(nread);
Ok(tauri::ipc::Response::new(data))
}
#[tauri::command]
pub async fn read_file<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<tauri::ipc::Response> {
let (mut file, path) = resolve_file(
&webview,
&global_scope,
&command_scope,
path,
OpenOptions {
base: BaseOptions {
base_dir: options.as_ref().and_then(|o| o.base_dir),
},
options: crate::OpenOptions {
read: true,
..Default::default()
},
},
)?;
let mut contents = Vec::new();
file.read_to_end(&mut contents).map_err(|e| {
format!(
"failed to read file as text at path: {} with error: {e}",
path.display()
)
})?;
Ok(tauri::ipc::Response::new(contents))
}
// TODO, remove in v3, rely on `read_file` command instead
#[tauri::command]
pub async fn read_text_file<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<tauri::ipc::Response> {
read_file(webview, global_scope, command_scope, path, options).await
}
#[tauri::command]
pub fn read_text_file_lines<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<ResourceId> {
let resolved_path = resolve_path(
&webview,
&global_scope,
&command_scope,
path,
options.as_ref().and_then(|o| o.base_dir),
)?;
let file = File::open(&resolved_path).map_err(|e| {
format!(
"failed to open file at path: {} with error: {e}",
resolved_path.display()
)
})?;
let lines = BufReader::new(file);
let rid = webview.resources_table().add(StdLinesResource::new(lines));
Ok(rid)
}
#[tauri::command]
pub async fn read_text_file_lines_next<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
) -> CommandResult<tauri::ipc::Response> {
let mut resource_table = webview.resources_table();
let lines = resource_table.get::<StdLinesResource>(rid)?;
let ret = StdLinesResource::with_lock(&lines, |lines| -> CommandResult<Vec<u8>> {
// This is an optimization to include wether we finished iteration or not (1 or 0)
// at the end of returned vector so we can use `tauri::ipc::Response`
// and avoid serialization overhead of separate values.
match lines.next() {
Some(Ok(mut bytes)) => {
bytes.push(false as u8);
Ok(bytes)
}
Some(Err(_)) => Ok(vec![false as u8]),
None => {
resource_table.close(rid)?;
Ok(vec![true as u8])
}
}
});
ret.map(tauri::ipc::Response::new)
}
#[derive(Debug, Clone, Deserialize)]
pub struct RemoveOptions {
#[serde(flatten)]
base: BaseOptions,
recursive: Option<bool>,
}
#[tauri::command]
pub fn remove<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<RemoveOptions>,
) -> CommandResult<()> {
let resolved_path = resolve_path(
&webview,
&global_scope,
&command_scope,
path,
options.as_ref().and_then(|o| o.base.base_dir),
)?;
let metadata = std::fs::symlink_metadata(&resolved_path).map_err(|e| {
format!(
"failed to get metadata of path: {} with error: {e}",
resolved_path.display()
)
})?;
let file_type = metadata.file_type();
// taken from deno source code: https://github.com/denoland/deno/blob/429759fe8b4207240709c240a8344d12a1e39566/runtime/ops/fs.rs#L728
let res = if file_type.is_file() {
std::fs::remove_file(&resolved_path)
} else if options.as_ref().and_then(|o| o.recursive).unwrap_or(false) {
std::fs::remove_dir_all(&resolved_path)
} else if file_type.is_symlink() {
#[cfg(unix)]
{
std::fs::remove_file(&resolved_path)
}
#[cfg(not(unix))]
{
use std::os::windows::fs::MetadataExt;
const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x00000010;
if metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 {
std::fs::remove_dir(&resolved_path)
} else {
std::fs::remove_file(&resolved_path)
}
}
} else if file_type.is_dir() {
std::fs::remove_dir(&resolved_path)
} else {
// pipes, sockets, etc...
std::fs::remove_file(&resolved_path)
};
res.map_err(|e| {
format!(
"failed to remove path: {} with error: {e}",
resolved_path.display()
)
})
.map_err(Into::into)
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RenameOptions {
new_path_base_dir: Option<BaseDirectory>,
old_path_base_dir: Option<BaseDirectory>,
}
#[tauri::command]
pub fn rename<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
old_path: SafeFilePath,
new_path: SafeFilePath,
options: Option<RenameOptions>,
) -> CommandResult<()> {
let resolved_old_path = resolve_path(
&webview,
&global_scope,
&command_scope,
old_path,
options.as_ref().and_then(|o| o.old_path_base_dir),
)?;
let resolved_new_path = resolve_path(
&webview,
&global_scope,
&command_scope,
new_path,
options.as_ref().and_then(|o| o.new_path_base_dir),
)?;
std::fs::rename(&resolved_old_path, &resolved_new_path)
.map_err(|e| {
format!(
"failed to rename old path: {} to new path: {} with error: {e}",
resolved_old_path.display(),
resolved_new_path.display()
)
})
.map_err(Into::into)
}
#[derive(Serialize_repr, Deserialize_repr, Clone, Copy, Debug)]
#[repr(u16)]
pub enum SeekMode {
Start = 0,
Current = 1,
End = 2,
}
#[tauri::command]
pub async fn seek<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
offset: i64,
whence: SeekMode,
) -> CommandResult<u64> {
use std::io::{Seek, SeekFrom};
let file = webview.resources_table().get::<StdFileResource>(rid)?;
StdFileResource::with_lock(&file, |mut file| {
file.seek(match whence {
SeekMode::Start => SeekFrom::Start(offset as u64),
SeekMode::Current => SeekFrom::Current(offset),
SeekMode::End => SeekFrom::End(offset),
})
})
.map_err(|e| format!("failed to seek file with error: {e}"))
.map_err(Into::into)
}
#[cfg(target_os = "android")]
fn get_metadata<R: Runtime, F: FnOnce(&PathBuf) -> std::io::Result<std::fs::Metadata>>(
metadata_fn: F,
webview: &Webview<R>,
global_scope: &GlobalScope<Entry>,
command_scope: &CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<std::fs::Metadata> {
match path {
SafeFilePath::Url(url) => {
let (file, path) = resolve_file(
webview,
global_scope,
command_scope,
SafeFilePath::Url(url),
OpenOptions {
base: BaseOptions { base_dir: None },
options: crate::OpenOptions {
read: true,
..Default::default()
},
},
)?;
file.metadata().map_err(|e| {
format!(
"failed to get metadata of path: {} with error: {e}",
path.display()
)
.into()
})
}
SafeFilePath::Path(p) => get_fs_metadata(
metadata_fn,
webview,
global_scope,
command_scope,
SafeFilePath::Path(p),
options,
),
}
}
#[cfg(not(target_os = "android"))]
fn get_metadata<R: Runtime, F: FnOnce(&PathBuf) -> std::io::Result<std::fs::Metadata>>(
metadata_fn: F,
webview: &Webview<R>,
global_scope: &GlobalScope<Entry>,
command_scope: &CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<std::fs::Metadata> {
get_fs_metadata(
metadata_fn,
webview,
global_scope,
command_scope,
path,
options,
)
}
fn get_fs_metadata<R: Runtime, F: FnOnce(&PathBuf) -> std::io::Result<std::fs::Metadata>>(
metadata_fn: F,
webview: &Webview<R>,
global_scope: &GlobalScope<Entry>,
command_scope: &CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<std::fs::Metadata> {
let resolved_path = resolve_path(
webview,
global_scope,
command_scope,
path,
options.as_ref().and_then(|o| o.base_dir),
)?;
let metadata = metadata_fn(&resolved_path).map_err(|e| {
format!(
"failed to get metadata of path: {} with error: {e}",
resolved_path.display()
)
})?;
Ok(metadata)
}
#[tauri::command]
pub fn stat<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<FileInfo> {
let metadata = get_metadata(
|p| std::fs::metadata(p),
&webview,
&global_scope,
&command_scope,
path,
options,
)?;
Ok(get_stat(metadata))
}
#[tauri::command]
pub fn lstat<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<FileInfo> {
let metadata = get_metadata(
|p| std::fs::symlink_metadata(p),
&webview,
&global_scope,
&command_scope,
path,
options,
)?;
Ok(get_stat(metadata))
}
#[tauri::command]
pub fn fstat<R: Runtime>(webview: Webview<R>, rid: ResourceId) -> CommandResult<FileInfo> {
let file = webview.resources_table().get::<StdFileResource>(rid)?;
let metadata = StdFileResource::with_lock(&file, |file| file.metadata())
.map_err(|e| format!("failed to get metadata of file with error: {e}"))?;
Ok(get_stat(metadata))
}
#[tauri::command]
pub async fn truncate<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
len: Option<u64>,
options: Option<BaseOptions>,
) -> CommandResult<()> {
let resolved_path = resolve_path(
&webview,
&global_scope,
&command_scope,
path,
options.as_ref().and_then(|o| o.base_dir),
)?;
let f = std::fs::OpenOptions::new()
.write(true)
.open(&resolved_path)
.map_err(|e| {
format!(
"failed to open file at path: {} with error: {e}",
resolved_path.display()
)
})?;
f.set_len(len.unwrap_or(0))
.map_err(|e| {
format!(
"failed to truncate file at path: {} with error: {e}",
resolved_path.display()
)
})
.map_err(Into::into)
}
#[tauri::command]
pub async fn ftruncate<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
len: Option<u64>,
) -> CommandResult<()> {
let file = webview.resources_table().get::<StdFileResource>(rid)?;
StdFileResource::with_lock(&file, |file| file.set_len(len.unwrap_or(0)))
.map_err(|e| format!("failed to truncate file with error: {e}"))
.map_err(Into::into)
}
#[tauri::command]
pub async fn write<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
data: Vec<u8>,
) -> CommandResult<usize> {
let file = webview.resources_table().get::<StdFileResource>(rid)?;
StdFileResource::with_lock(&file, |mut file| file.write(&data))
.map_err(|e| format!("failed to write bytes to file with error: {e}"))
.map_err(Into::into)
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WriteFileOptions {
#[serde(flatten)]
base: BaseOptions,
#[serde(default)]
append: bool,
#[serde(default = "default_create_value")]
create: bool,
#[serde(default)]
create_new: bool,
#[allow(unused)]
mode: Option<u32>,
}
fn default_create_value() -> bool {
true
}
#[tauri::command]
pub async fn write_file<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
request: tauri::ipc::Request<'_>,
) -> CommandResult<()> {
let data = match request.body() {
tauri::ipc::InvokeBody::Raw(data) => Cow::Borrowed(data),
tauri::ipc::InvokeBody::Json(serde_json::Value::Array(data)) => Cow::Owned(
data.iter()
.flat_map(|v| v.as_number().and_then(|v| v.as_u64().map(|v| v as u8)))
.collect(),
),
_ => return Err(anyhow::anyhow!("unexpected invoke body").into()),
};
let path = request
.headers()
.get("path")
.ok_or_else(|| anyhow::anyhow!("missing file path").into())
.and_then(|p| {
percent_encoding::percent_decode(p.as_ref())
.decode_utf8()
.map_err(|_| anyhow::anyhow!("path is not a valid UTF-8").into())
})
.and_then(|p| SafeFilePath::from_str(&p).map_err(CommandError::from))?;
let options: Option<WriteFileOptions> = request
.headers()
.get("options")
.and_then(|p| p.to_str().ok())
.and_then(|opts| serde_json::from_str(opts).ok());
let (mut file, path) = resolve_file(
&webview,
&global_scope,
&command_scope,
path,
if let Some(opts) = options {
OpenOptions {
base: opts.base,
options: crate::OpenOptions {
read: false,
write: true,
create: opts.create,
truncate: !opts.append,
append: opts.append,
create_new: opts.create_new,
mode: opts.mode,
custom_flags: None,
},
}
} else {
OpenOptions {
base: BaseOptions { base_dir: None },
options: crate::OpenOptions {
read: false,
write: true,
truncate: true,
create: true,
create_new: false,
append: false,
mode: None,
custom_flags: None,
},
}
},
)?;
file.write_all(&data)
.map_err(|e| {
format!(
"failed to write bytes to file at path: {} with error: {e}",
path.display()
)
})
.map_err(Into::into)
}
// TODO, remove in v3, rely on `write_file` command instead
#[tauri::command]
pub async fn write_text_file<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
request: tauri::ipc::Request<'_>,
) -> CommandResult<()> {
write_file(webview, global_scope, command_scope, request).await
}
#[tauri::command]
pub fn exists<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<bool> {
let resolved_path = resolve_path(
&webview,
&global_scope,
&command_scope,
path,
options.as_ref().and_then(|o| o.base_dir),
)?;
Ok(resolved_path.exists())
}
#[tauri::command]
pub async fn size<R: Runtime>(
webview: Webview<R>,
global_scope: GlobalScope<Entry>,
command_scope: CommandScope<Entry>,
path: SafeFilePath,
options: Option<BaseOptions>,
) -> CommandResult<u64> {
let resolved_path = resolve_path(
&webview,
&global_scope,
&command_scope,
path,
options.as_ref().and_then(|o| o.base_dir),
)?;
let metadata = resolved_path.metadata()?;
if metadata.is_file() {
Ok(metadata.len())
} else {
let size = get_dir_size(&resolved_path).map_err(|e| {
format!(
"failed to get size at path: {} with error: {e}",
resolved_path.display()
)
})?;
Ok(size)
}
}
fn get_dir_size(path: &PathBuf) -> CommandResult<u64> {
let mut size = 0;
for entry in std::fs::read_dir(path)? {
let entry = entry?;
let metadata = entry.metadata()?;
if metadata.is_file() {
size += metadata.len();
} else if metadata.is_dir() {
size += get_dir_size(&entry.path())?;
}
}
Ok(size)
}
#[cfg(not(target_os = "android"))]
pub fn resolve_file<R: Runtime>(
webview: &Webview<R>,
global_scope: &GlobalScope<Entry>,
command_scope: &CommandScope<Entry>,
path: SafeFilePath,
open_options: OpenOptions,
) -> CommandResult<(File, PathBuf)> {
resolve_file_in_fs(webview, global_scope, command_scope, path, open_options)
}
fn resolve_file_in_fs<R: Runtime>(
webview: &Webview<R>,
global_scope: &GlobalScope<Entry>,
command_scope: &CommandScope<Entry>,
path: SafeFilePath,
open_options: OpenOptions,
) -> CommandResult<(File, PathBuf)> {
let path = resolve_path(
webview,
global_scope,
command_scope,
path,
open_options.base.base_dir,
)?;
let file = std::fs::OpenOptions::from(open_options.options)
.open(&path)
.map_err(|e| {
format!(
"failed to open file at path: {} with error: {e}",
path.display()
)
})?;
Ok((file, path))
}
#[cfg(target_os = "android")]
pub fn resolve_file<R: Runtime>(
webview: &Webview<R>,
global_scope: &GlobalScope<Entry>,
command_scope: &CommandScope<Entry>,
path: SafeFilePath,
open_options: OpenOptions,
) -> CommandResult<(File, PathBuf)> {
use crate::FsExt;
match path {
SafeFilePath::Url(url) => {
let path = url.as_str().into();
let file = webview
.fs()
.open(SafeFilePath::Url(url), open_options.options)?;
Ok((file, path))
}
SafeFilePath::Path(path) => resolve_file_in_fs(
webview,