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
// Copyright 2019-2024 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use super::{AppDirectory, Error, Result};
use crate::{AppHandle, Manager, Runtime};
use std::path::{Path, PathBuf};
/// The path resolver is a helper class for general and application-specific path APIs.
pub struct PathResolver<R: Runtime>(pub(crate) AppHandle<R>);
impl<R: Runtime> Clone for PathResolver<R> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<R: Runtime> PathResolver<R> {
/// Returns the final component of the `Path`, if there is one.
///
/// If the path is a normal file, this is the file name. If it's the path of a directory, this
/// is the directory name.
///
/// Returns [`None`] if the path terminates in `..`.
///
/// On Android this also supports checking the file name of content URIs, such as the values returned by the dialog plugin.
///
/// If you are dealing with plain file system paths or not worried about Android content URIs, prefer [`Path::file_name`].
pub fn file_name(&self, path: &str) -> Option<String> {
Path::new(path)
.file_name()
.map(|name| name.to_string_lossy().into_owned())
}
/// Returns the path to the user's audio directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_MUSIC_DIR`.
/// - **macOS:** Resolves to `$HOME/Music`.
/// - **Windows:** Resolves to `{FOLDERID_Music}`.
pub fn audio_dir(&self) -> Result<PathBuf> {
dirs::audio_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's cache directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_CACHE_HOME` or `$HOME/.cache`.
/// - **macOS:** Resolves to `$HOME/Library/Caches`.
/// - **Windows:** Resolves to `{FOLDERID_LocalAppData}`.
pub fn cache_dir(&self) -> Result<PathBuf> {
dirs::cache_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's config directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_CONFIG_HOME` or `$HOME/.config`.
/// - **macOS:** Resolves to `$HOME/Library/Application Support`.
/// - **Windows:** Resolves to `{FOLDERID_RoamingAppData}`.
pub fn config_dir(&self) -> Result<PathBuf> {
dirs::config_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's data directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_DATA_HOME` or `$HOME/.local/share`.
/// - **macOS:** Resolves to `$HOME/Library/Application Support`.
/// - **Windows:** Resolves to `{FOLDERID_RoamingAppData}`.
pub fn data_dir(&self) -> Result<PathBuf> {
dirs::data_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's local data directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_DATA_HOME` or `$HOME/.local/share`.
/// - **macOS:** Resolves to `$HOME/Library/Application Support`.
/// - **Windows:** Resolves to `{FOLDERID_LocalAppData}`.
pub fn local_data_dir(&self) -> Result<PathBuf> {
dirs::data_local_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's desktop directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_DESKTOP_DIR`.
/// - **macOS:** Resolves to `$HOME/Desktop`.
/// - **Windows:** Resolves to `{FOLDERID_Desktop}`.
pub fn desktop_dir(&self) -> Result<PathBuf> {
dirs::desktop_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's document directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_DOCUMENTS_DIR`.
/// - **macOS:** Resolves to `$HOME/Documents`.
/// - **Windows:** Resolves to `{FOLDERID_Documents}`.
pub fn document_dir(&self) -> Result<PathBuf> {
dirs::document_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's download directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_DOWNLOAD_DIR`.
/// - **macOS:** Resolves to `$HOME/Downloads`.
/// - **Windows:** Resolves to `{FOLDERID_Downloads}`.
pub fn download_dir(&self) -> Result<PathBuf> {
dirs::download_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's executable directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_BIN_HOME/../bin` or `$XDG_DATA_HOME/../bin` or `$HOME/.local/bin`.
/// - **macOS:** Not supported.
/// - **Windows:** Not supported.
pub fn executable_dir(&self) -> Result<PathBuf> {
dirs::executable_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's font directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_DATA_HOME/fonts` or `$HOME/.local/share/fonts`.
/// - **macOS:** Resolves to `$HOME/Library/Fonts`.
/// - **Windows:** Not supported.
pub fn font_dir(&self) -> Result<PathBuf> {
dirs::font_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's home directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$HOME`.
/// - **macOS:** Resolves to `$HOME`.
/// - **Windows:** Resolves to `{FOLDERID_Profile}`.
/// - **iOS**: Cannot be written to directly, use one of the app paths instead.
pub fn home_dir(&self) -> Result<PathBuf> {
dirs::home_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's picture directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_PICTURES_DIR`.
/// - **macOS:** Resolves to `$HOME/Pictures`.
/// - **Windows:** Resolves to `{FOLDERID_Pictures}`.
pub fn picture_dir(&self) -> Result<PathBuf> {
dirs::picture_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's public directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_PUBLICSHARE_DIR`.
/// - **macOS:** Resolves to `$HOME/Public`.
/// - **Windows:** Resolves to `{FOLDERID_Public}`.
pub fn public_dir(&self) -> Result<PathBuf> {
dirs::public_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's runtime directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to `$XDG_RUNTIME_DIR`.
/// - **macOS:** Not supported.
/// - **Windows:** Not supported.
pub fn runtime_dir(&self) -> Result<PathBuf> {
dirs::runtime_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's template directory.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_TEMPLATES_DIR`.
/// - **macOS:** Not supported.
/// - **Windows:** Resolves to `{FOLDERID_Templates}`.
pub fn template_dir(&self) -> Result<PathBuf> {
dirs::template_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the user's video dir
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`xdg-user-dirs`](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/)' `XDG_VIDEOS_DIR`.
/// - **macOS:** Resolves to `$HOME/Movies`.
/// - **Windows:** Resolves to `{FOLDERID_Videos}`.
pub fn video_dir(&self) -> Result<PathBuf> {
dirs::video_dir().ok_or(Error::UnknownPath)
}
/// Returns the path to the resource directory of this app.
///
/// ## Platform-specific
///
/// Although we provide the exact path where this function resolves to,
/// this is not a contract and things might change in the future
///
/// - **Windows:** Resolves to the directory that contains the main executable.
/// - **Linux:** When running in an AppImage, the `APPDIR` variable will be set to
/// the mounted location of the app, and the resource dir will be `${APPDIR}/usr/lib/${exe_name}`.
/// If not running in an AppImage, the path is `/usr/lib/${exe_name}`.
/// When running the app from `src-tauri/target/(debug|release)/`, the path is `${exe_dir}/../lib/${exe_name}`.
/// - **macOS:** Resolves to `${exe_dir}/../Resources` (inside .app).
/// - **iOS:** Resolves to `${exe_dir}/assets`.
/// - **Android:** Currently the resources are stored in the APK as assets so it's not a normal file system path,
/// we return a special URI prefix `asset://localhost/` here that can be used with the [file system plugin](https://tauri.app/plugin/file-system/),
/// with that, you can read the files through [`FsExt::fs`](https://docs.rs/tauri-plugin-fs/latest/tauri_plugin_fs/trait.FsExt.html#tymethod.fs)
/// like this: `app.fs().read_to_string(app.path().resource_dir().unwrap().join("resource"));`
///
/// ## Development
///
/// On desktop, when running with `tauri dev` or `cargo run`, resources are read from their
/// source location instead of being copied next to the executable by the build script:
///
/// - If all configured resources are plain relative paths, their bundle layout mirrors the
/// source layout, so this resolves to the directory containing `tauri.conf.json` and
/// resource files are read directly from the sources.
/// - If resources are remapped (map notation, or paths outside the app directory), they are
/// mirrored to the directory containing the executable on the first call, so joined paths
/// keep working, and refreshed on each run.
pub fn resource_dir(&self) -> Result<PathBuf> {
#[cfg(all(dev, desktop))]
if let Some(dir) = self.dev_resource_dir()? {
return Ok(dir);
}
crate::utils::platform::resource_dir(self.0.package_info(), &self.0.env())
.map_err(|_| Error::UnknownPath)
}
#[cfg(all(dev, desktop))]
fn dev_resource_dir(&self) -> Result<Option<PathBuf>> {
use tauri_utils::config::BundleResources;
let manager = &self.0.manager;
let Some(app_dir) = manager.config_parent() else {
return Ok(None);
};
let Some(resources) = manager.config().bundle.resources.as_ref() else {
return Ok(None);
};
match resources {
BundleResources::List(patterns) if patterns.is_empty() => Ok(None),
// the bundle layout mirrors the source layout, so the app directory
// acts as the resource directory and files are read directly from the sources
resources if resources_mirror_source_layout(resources) => Ok(Some(app_dir.clone())),
// remapped resources: mirror the bundle layout next to the executable
resources => {
let mut dev_resources_dir = manager.dev_resources_dir.lock().unwrap();
if let Some(dir) = dev_resources_dir.as_ref() {
return Ok(Some(dir.clone()));
}
let exe_dir = crate::utils::platform::current_exe()?
.parent()
.ok_or(Error::UnknownPath)?
.to_path_buf();
mirror_resources(resources, app_dir, &exe_dir)?;
dev_resources_dir.replace(exe_dir.clone());
Ok(Some(exe_dir))
}
}
}
/// Returns the path to the suggested directory for your app's config files.
///
/// Resolves to [`config_dir`](Self::config_dir)`/${bundle_identifier}`,
/// unless overridden with the [`app > appDirectoriesOverride`](crate::utils::config::AppConfig::app_directories_override) config.
pub fn app_config_dir(&self) -> Result<PathBuf> {
self.app_dir(AppDirectory::Config, || {
dirs::config_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&self.0.config().identifier))
})
}
/// Returns the path to the suggested directory for your app's data files.
///
/// Resolves to [`data_dir`](Self::data_dir)`/${bundle_identifier}`,
/// unless overridden with the [`app > appDirectoriesOverride`](crate::utils::config::AppConfig::app_directories_override) config.
pub fn app_data_dir(&self) -> Result<PathBuf> {
self.app_dir(AppDirectory::Data, || {
dirs::data_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&self.0.config().identifier))
})
}
/// Returns the path to the suggested directory for your app's local data files.
///
/// Resolves to [`local_data_dir`](Self::local_data_dir)`/${bundle_identifier}`,
/// unless overridden with the [`app > appDirectoriesOverride`](crate::utils::config::AppConfig::app_directories_override) config.
///
/// On Windows and Linux this is also the default data directory of the webviews.
pub fn app_local_data_dir(&self) -> Result<PathBuf> {
self.app_dir(AppDirectory::LocalData, || {
dirs::data_local_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&self.0.config().identifier))
})
}
/// Returns the path to the suggested directory for your app's cache files.
///
/// Resolves to [`cache_dir`](Self::cache_dir)`/${bundle_identifier}`,
/// unless overridden with the [`app > appDirectoriesOverride`](crate::utils::config::AppConfig::app_directories_override) config
/// (a single root override resolves to `<root>/caches`).
pub fn app_cache_dir(&self) -> Result<PathBuf> {
self.app_dir(AppDirectory::Cache, || {
dirs::cache_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&self.0.config().identifier))
})
}
/// Returns the path to the suggested directory for your app's log files.
///
/// ## Platform-specific
///
/// - **Linux:** Resolves to [`local_data_dir`](Self::local_data_dir)`/${bundle_identifier}/logs`.
/// - **macOS:** Resolves to [`home_dir`](Self::home_dir)`/Library/Logs/${bundle_identifier}`
/// - **Windows:** Resolves to [`local_data_dir`](Self::local_data_dir)`/${bundle_identifier}/logs`.
///
/// All of them can be overridden with the [`app > appDirectoriesOverride`](crate::utils::config::AppConfig::app_directories_override) config
/// (a single root override resolves to `<root>/logs`).
pub fn app_log_dir(&self) -> Result<PathBuf> {
self.app_dir(AppDirectory::Log, || {
#[cfg(target_os = "macos")]
let path = dirs::home_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join("Library/Logs").join(&self.0.config().identifier));
#[cfg(not(target_os = "macos"))]
let path = dirs::data_local_dir()
.ok_or(Error::UnknownPath)
.map(|dir| dir.join(&self.0.config().identifier).join("logs"));
path
})
}
/// A temporary directory. Resolves to [`std::env::temp_dir`].
pub fn temp_dir(&self) -> Result<PathBuf> {
Ok(std::env::temp_dir())
}
pub(super) fn app_handle(&self) -> &AppHandle<R> {
&self.0
}
/// The directory relative app directory overrides are resolved against: the directory containing the app binary.
///
/// When running from an AppImage on Linux, this is the directory containing the AppImage file,
/// and when running from a `.app` bundle on macOS, the directory containing the bundle.
#[cfg(desktop)]
pub(super) fn app_binary_dir(&self) -> Result<PathBuf> {
let binary = crate::process::current_binary(&self.0.env())?;
let dir = binary.parent().ok_or(Error::NoParent)?;
#[cfg(target_os = "macos")]
if let Some(bundle_parent) = macos_bundle_parent(dir) {
return Ok(bundle_parent);
}
Ok(dir.to_path_buf())
}
}
/// For a `<dir>/<name>.app/Contents/MacOS` directory, returns `<dir>`.
#[cfg(any(target_os = "macos", test))]
fn macos_bundle_parent(macos_dir: &Path) -> Option<PathBuf> {
use std::ffi::OsStr;
if macos_dir.file_name() != Some(OsStr::new("MacOS")) {
return None;
}
let contents_dir = macos_dir.parent()?;
if contents_dir.file_name() != Some(OsStr::new("Contents")) {
return None;
}
let bundle = contents_dir.parent()?;
if bundle.extension() != Some(OsStr::new("app")) {
return None;
}
bundle.parent().map(Path::to_path_buf)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::path::normalize;
use crate::{
App,
test::{MockRuntime, mock_builder, mock_context, noop_assets},
};
use std::path::Component;
use tauri_utils::config::{AppDirectoriesOverride, AppDirectoryOverrides};
const IDENTIFIER: &str = "com.tauri.test";
fn app_with(app_directories_override: Option<AppDirectoriesOverride>) -> App<MockRuntime> {
let mut context = mock_context(noop_assets());
context.config_mut().identifier = IDENTIFIER.into();
context.config_mut().app.app_directories_override = app_directories_override;
mock_builder().build(context).unwrap()
}
/// The directory containing the test binary, which is never inside an app bundle.
fn binary_dir() -> PathBuf {
crate::utils::platform::current_exe()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
#[test]
fn default_directories() {
let app = app_with(None);
let path = app.path();
assert_eq!(
path.app_config_dir().unwrap(),
dirs::config_dir().unwrap().join(IDENTIFIER)
);
assert_eq!(
path.app_data_dir().unwrap(),
dirs::data_dir().unwrap().join(IDENTIFIER)
);
assert_eq!(
path.app_local_data_dir().unwrap(),
dirs::data_local_dir().unwrap().join(IDENTIFIER)
);
assert_eq!(
path.app_cache_dir().unwrap(),
dirs::cache_dir().unwrap().join(IDENTIFIER)
);
}
#[test]
fn root_override_relative_to_binary() {
let binary_dir = binary_dir();
let app = app_with(Some(AppDirectoriesOverride::Root("./".into())));
let path = app.path();
assert_eq!(path.app_config_dir().unwrap(), binary_dir);
assert_eq!(path.app_data_dir().unwrap(), binary_dir);
assert_eq!(path.app_local_data_dir().unwrap(), binary_dir);
assert_eq!(path.app_cache_dir().unwrap(), binary_dir.join("caches"));
assert_eq!(path.app_log_dir().unwrap(), binary_dir.join("logs"));
// the `.` component must not leak into the resolved path
assert!(
!path
.app_cache_dir()
.unwrap()
.components()
.any(|c| c == Component::CurDir)
);
let app = app_with(Some(AppDirectoriesOverride::Root("data".into())));
assert_eq!(app.path().app_data_dir().unwrap(), binary_dir.join("data"));
// `..` components are kept
let app = app_with(Some(AppDirectoriesOverride::Root("../data".into())));
assert_eq!(
app.path().app_data_dir().unwrap(),
binary_dir.join("../data")
);
}
#[test]
fn root_override_absolute() {
let root = normalize(std::env::temp_dir().join("tauri-app-directories-override"));
let app = app_with(Some(AppDirectoriesOverride::Root(root.clone())));
let path = app.path();
assert_eq!(path.app_config_dir().unwrap(), root);
assert_eq!(path.app_data_dir().unwrap(), root);
assert_eq!(path.app_local_data_dir().unwrap(), root);
assert_eq!(path.app_cache_dir().unwrap(), root.join("caches"));
assert_eq!(path.app_log_dir().unwrap(), root.join("logs"));
}
#[test]
fn root_override_variable() {
let data_dir = dirs::data_dir().unwrap();
let app = app_with(Some(AppDirectoriesOverride::Root("$DATA/my-app".into())));
let path = app.path();
assert_eq!(path.app_config_dir().unwrap(), data_dir.join("my-app"));
assert_eq!(
path.app_cache_dir().unwrap(),
data_dir.join("my-app/caches")
);
assert_eq!(path.app_log_dir().unwrap(), data_dir.join("my-app/logs"));
let app = app_with(Some(AppDirectoriesOverride::Root("$DATA".into())));
assert_eq!(app.path().app_data_dir().unwrap(), data_dir);
// `..` components are kept, unlike `PathResolver::parse`
let app = app_with(Some(AppDirectoriesOverride::Root("$DATA/../my-app".into())));
assert_eq!(
app.path().app_data_dir().unwrap(),
data_dir.join("../my-app")
);
}
#[test]
fn directories_override() {
let app = app_with(Some(AppDirectoriesOverride::Directories(
AppDirectoryOverrides {
log: Some("$CACHE/my-app/logs".into()),
cache: Some("custom-cache".into()),
..Default::default()
},
)));
let path = app.path();
// overridden directories resolve to exactly the configured path
assert_eq!(
path.app_log_dir().unwrap(),
dirs::cache_dir().unwrap().join("my-app/logs")
);
assert_eq!(
path.app_cache_dir().unwrap(),
binary_dir().join("custom-cache")
);
// the other directories keep their default location
assert_eq!(
path.app_config_dir().unwrap(),
dirs::config_dir().unwrap().join(IDENTIFIER)
);
assert_eq!(
path.app_data_dir().unwrap(),
dirs::data_dir().unwrap().join(IDENTIFIER)
);
assert_eq!(
path.app_local_data_dir().unwrap(),
dirs::data_local_dir().unwrap().join(IDENTIFIER)
);
}
#[test]
fn rejects_app_directory_variables() {
for variable in [
"$APPCONFIG",
"$APPDATA",
"$APPLOCALDATA",
"$APPCACHE",
"$APPLOG",
] {
let app = app_with(Some(AppDirectoriesOverride::Root(
format!("{variable}/my-app").into(),
)));
let err = app.path().app_data_dir().unwrap_err();
assert!(
matches!(err, Error::InvalidAppDirectoriesOverride(..)),
"{variable}: {err}"
);
}
}
#[test]
fn rejects_unknown_variables() {
let app = app_with(Some(AppDirectoriesOverride::Root("$UNKNOWN/my-app".into())));
let err = app.path().app_data_dir().unwrap_err();
assert!(
matches!(err, Error::InvalidAppDirectoriesOverride(..)),
"{err}"
);
}
#[cfg(windows)]
#[test]
fn rejects_root_relative_paths() {
for root in [r"\my-app", "C:my-app"] {
let app = app_with(Some(AppDirectoriesOverride::Root(root.into())));
let err = app.path().app_data_dir().unwrap_err();
assert!(
matches!(err, Error::InvalidAppDirectoriesOverride(..)),
"{root}: {err}"
);
}
}
#[test]
fn macos_bundle_parent_dir() {
assert_eq!(
macos_bundle_parent(Path::new("/Applications/My App.app/Contents/MacOS")),
Some(PathBuf::from("/Applications"))
);
assert_eq!(
macos_bundle_parent(Path::new("/Applications/My App.app/Contents")),
None
);
assert_eq!(
macos_bundle_parent(Path::new("/Applications/MyApp/Contents/MacOS")),
None
);
assert_eq!(macos_bundle_parent(Path::new("/opt/my-app/bin")), None);
}
}
/// Whether the bundle target path of every configured resource matches its source path,
/// meaning the directory the resource patterns are relative to can be used
/// as the resource directory directly.
///
/// This is only the case for list notation with plain relative patterns:
/// map notation remaps targets, and patterns reaching outside the base directory
/// get their target rewritten (`..` -> `_up_`).
#[cfg(all(dev, desktop))]
fn resources_mirror_source_layout(resources: &tauri_utils::config::BundleResources) -> bool {
match resources {
tauri_utils::config::BundleResources::List(patterns) => patterns.iter().all(|pattern| {
let path = Path::new(pattern);
path.is_relative()
&& !path
.components()
.any(|c| matches!(c, std::path::Component::ParentDir))
}),
tauri_utils::config::BundleResources::Map(_) => false,
}
}
/// Copies the configured resources, laid out as in the bundle, into `out_dir`.
///
/// Copies are skipped when the destination is already up to date, so this stays
/// cheap when called once per run.
#[cfg(all(dev, desktop))]
fn mirror_resources(
resources: &tauri_utils::config::BundleResources,
base_dir: &Path,
out_dir: &Path,
) -> Result<()> {
use tauri_utils::{config::BundleResources, resources::ResourcePaths};
let resources = match resources {
BundleResources::List(patterns) => ResourcePaths::new(patterns.as_slice(), true),
BundleResources::Map(map) => ResourcePaths::from_map(map, true),
};
for resource in resources.with_base_dir(base_dir).iter() {
let resource = resource.map_err(std::io::Error::other)?;
let dest = out_dir.join(resource.target());
if !up_to_date(resource.path(), &dest) {
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::copy(resource.path(), &dest)?;
}
}
Ok(())
}
#[cfg(all(dev, desktop))]
fn up_to_date(src: &Path, dest: &Path) -> bool {
let (Ok(src), Ok(dest)) = (src.metadata(), dest.metadata()) else {
return false;
};
src.len() == dest.len()
&& matches!(
(src.modified(), dest.modified()),
(Ok(src), Ok(dest)) if dest >= src
)
}
#[cfg(all(test, dev, desktop))]
mod resource_mirror_tests {
use std::{collections::HashMap, fs};
use tauri_utils::config::BundleResources;
use super::{mirror_resources, resources_mirror_source_layout};
fn list(patterns: &[&str]) -> BundleResources {
BundleResources::List(patterns.iter().map(ToString::to_string).collect())
}
#[test]
fn source_layout_mirror_detection() {
assert!(resources_mirror_source_layout(&list(&[
"assets/*",
"lang/en.json",
"./data",
"files/**/*"
])));
assert!(!resources_mirror_source_layout(&list(&["../assets/*"])));
assert!(!resources_mirror_source_layout(&list(&[
"assets/*",
"dir/../../escape.txt"
])));
#[cfg(windows)]
assert!(!resources_mirror_source_layout(&list(&["C:\\abs\\file"])));
#[cfg(not(windows))]
assert!(!resources_mirror_source_layout(&list(&["/abs/file"])));
assert!(!resources_mirror_source_layout(&BundleResources::Map(
HashMap::from([("assets".into(), "assets".into())])
)));
}
#[test]
fn resource_dir_resolves_to_sources_in_dev() {
use crate::Manager;
let mut context = crate::test::mock_context(crate::test::noop_assets());
context.config.bundle.resources = Some(list(&["assets/*", "lang/en.json"]));
context.with_config_parent("/app/src-tauri");
let app = crate::test::mock_builder().build(context).unwrap();
assert_eq!(
app.path().resource_dir().unwrap(),
std::path::PathBuf::from("/app/src-tauri")
);
assert_eq!(
app
.path()
.resolve("assets/logo.png", crate::path::BaseDirectory::Resource)
.unwrap(),
std::path::PathBuf::from("/app/src-tauri/assets/logo.png")
);
// without configured resources, the default resolution is used
let context = crate::test::mock_context(crate::test::noop_assets());
let app = crate::test::mock_builder().build(context).unwrap();
// A unit test executable need not have a bundle resource directory.
assert!(!matches!(
app.path().resource_dir(),
Ok(path) if path == std::path::Path::new("/app/src-tauri")
));
}
#[test]
fn mirrors_remapped_resources() {
let mut random = [0; 8];
getrandom::fill(&mut random).unwrap();
let root = std::env::temp_dir().join(format!(
"tauri_dev_resources_test_{}",
random.map(|b| b.to_string()).join("")
));
let _ = fs::remove_dir_all(&root);
let app_dir = root.join("app/src-tauri");
for (path, content) in [
("app/assets/logo.png", "logo"),
("app/assets/nested/deep.txt", "deep"),
("app/src-tauri/lang/en.json", "en"),
("app/src-tauri/data.bin", "data"),
] {
let path = root.join(path);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, content).unwrap();
}
let resources = BundleResources::Map(HashMap::from([
("../assets".to_string(), "assets".to_string()),
("lang/en.json".to_string(), "locales/en.json".to_string()),
("data.bin".to_string(), String::new()),
]));
let out_dir = root.join("out");
fs::create_dir_all(&out_dir).unwrap();
mirror_resources(&resources, &app_dir, &out_dir).unwrap();
for (path, content) in [
("assets/logo.png", "logo"),
("assets/nested/deep.txt", "deep"),
("locales/en.json", "en"),
("data.bin", "data"),
] {
assert_eq!(
fs::read_to_string(out_dir.join(path)).unwrap(),
content,
"unexpected content for {path}"
);
}
// a second run refreshes modified sources and keeps up-to-date copies
let dest_modified = |p: &str| out_dir.join(p).metadata().unwrap().modified().unwrap();
let untouched_before = dest_modified("data.bin");
fs::write(app_dir.join("lang/en.json"), "en-updated").unwrap();
mirror_resources(&resources, &app_dir, &out_dir).unwrap();
assert_eq!(
fs::read_to_string(out_dir.join("locales/en.json")).unwrap(),
"en-updated"
);
assert_eq!(dest_modified("data.bin"), untouched_before);
// resources reaching outside the app dir via list notation get `_up_` targets
let out_dir = root.join("out-list");
fs::create_dir_all(&out_dir).unwrap();
mirror_resources(&list(&["../assets/*.png", "data.bin"]), &app_dir, &out_dir).unwrap();
assert_eq!(
fs::read_to_string(out_dir.join("_up_/assets/logo.png")).unwrap(),
"logo"
);
assert_eq!(
fs::read_to_string(out_dir.join("data.bin")).unwrap(),
"data"
);
let _ = fs::remove_dir_all(&root);
}
}