Skip to content

Commit 4dd4893

Browse files
feat: allow specifying a resource map, closes #5844 (#5950)
Co-authored-by: amrbashir <amr.bashir2015@gmail.com> closes #5844
1 parent ef962c4 commit 4dd4893

File tree

14 files changed

+1058
-471
lines changed

14 files changed

+1058
-471
lines changed

.changes/resources-map-bundler.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"tauri-bundler": minor:feat
3+
---
4+
5+
Allow using a resource map instead of a simple array in `BundleSettings::resources_map`.

.changes/resources-map.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"tauri-utils": minor:feat
3+
---
4+
5+
Allow specifying resources as a map specifying source and target paths.

core/tauri-build/src/lib.rs

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ use cargo_toml::Manifest;
99
use heck::AsShoutySnakeCase;
1010

1111
use tauri_utils::{
12-
config::{Config, WebviewInstallMode},
13-
resources::{external_binaries, resource_relpath, ResourcePaths},
12+
config::{BundleResources, Config, WebviewInstallMode},
13+
resources::{external_binaries, ResourcePaths},
1414
};
1515

1616
use std::path::{Path, PathBuf};
@@ -72,11 +72,10 @@ fn copy_binaries(
7272

7373
/// Copies resources to a path.
7474
fn copy_resources(resources: ResourcePaths<'_>, path: &Path) -> Result<()> {
75-
for src in resources {
76-
let src = src?;
77-
println!("cargo:rerun-if-changed={}", src.display());
78-
let dest = path.join(resource_relpath(&src));
79-
copy_file(&src, dest)?;
75+
for resource in resources.iter() {
76+
let resource = resource?;
77+
println!("cargo:rerun-if-changed={}", resource.path().display());
78+
copy_file(resource.path(), path.join(resource.target()))?;
8079
}
8180
Ok(())
8281
}
@@ -344,7 +343,12 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
344343
}
345344

346345
#[allow(unused_mut, clippy::redundant_clone)]
347-
let mut resources = config.tauri.bundle.resources.clone().unwrap_or_default();
346+
let mut resources = config
347+
.tauri
348+
.bundle
349+
.resources
350+
.clone()
351+
.unwrap_or_else(|| BundleResources::List(Vec::new()));
348352
if target_triple.contains("windows") {
349353
if let Some(fixed_webview2_runtime_path) =
350354
match &config.tauri.bundle.windows.webview_fixed_runtime_path {
@@ -358,7 +362,12 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
358362
resources.push(fixed_webview2_runtime_path.display().to_string());
359363
}
360364
}
361-
copy_resources(ResourcePaths::new(resources.as_slice(), true), target_dir)?;
365+
match resources {
366+
BundleResources::List(res) => {
367+
copy_resources(ResourcePaths::new(res.as_slice(), true), target_dir)?
368+
}
369+
BundleResources::Map(map) => copy_resources(ResourcePaths::from_map(&map, true), target_dir)?,
370+
}
362371

363372
if target_triple.contains("darwin") {
364373
if let Some(version) = &config.tauri.bundle.macos.minimum_system_version {

core/tauri-config-schema/schema.json

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1074,13 +1074,14 @@
10741074
},
10751075
"resources": {
10761076
"description": "App resources to bundle. Each resource is a path to a file or directory. Glob patterns are supported.",
1077-
"type": [
1078-
"array",
1079-
"null"
1080-
],
1081-
"items": {
1082-
"type": "string"
1083-
}
1077+
"anyOf": [
1078+
{
1079+
"$ref": "#/definitions/BundleResources"
1080+
},
1081+
{
1082+
"type": "null"
1083+
}
1084+
]
10841085
},
10851086
"copyright": {
10861087
"description": "A copyright string associated with your application.",
@@ -1258,6 +1259,25 @@
12581259
}
12591260
]
12601261
},
1262+
"BundleResources": {
1263+
"description": "Definition for bundle resources. Can be either a list of paths to include or a map of source to target paths.",
1264+
"anyOf": [
1265+
{
1266+
"description": "A list of paths to include.",
1267+
"type": "array",
1268+
"items": {
1269+
"type": "string"
1270+
}
1271+
},
1272+
{
1273+
"description": "A map of source to target paths.",
1274+
"type": "object",
1275+
"additionalProperties": {
1276+
"type": "string"
1277+
}
1278+
}
1279+
]
1280+
},
12611281
"AppImageConfig": {
12621282
"description": "Configuration for AppImage bundles.\n\nSee more: https://tauri.app/v1/api/config#appimageconfig",
12631283
"type": "object",

core/tauri-runtime-wry/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3045,7 +3045,7 @@ fn on_close_requested<'a, T: UserEvent>(
30453045
}
30463046

30473047
fn on_window_close(window_id: WebviewId, windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>) {
3048-
if let Some(mut window_wrapper) = windows.borrow_mut().get_mut(&window_id) {
3048+
if let Some(window_wrapper) = windows.borrow_mut().get_mut(&window_id) {
30493049
window_wrapper.inner = None;
30503050
}
30513051
}

core/tauri-utils/src/config.rs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -624,6 +624,31 @@ impl Default for WindowsConfig {
624624
}
625625
}
626626

627+
/// Definition for bundle resources.
628+
/// Can be either a list of paths to include or a map of source to target paths.
629+
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
630+
#[cfg_attr(feature = "schema", derive(JsonSchema))]
631+
#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
632+
pub enum BundleResources {
633+
/// A list of paths to include.
634+
List(Vec<String>),
635+
/// A map of source to target paths.
636+
Map(HashMap<String, String>),
637+
}
638+
639+
impl BundleResources {
640+
/// Adds a path to the resource collection.
641+
pub fn push(&mut self, path: impl Into<String>) {
642+
match self {
643+
Self::List(l) => l.push(path.into()),
644+
Self::Map(l) => {
645+
let path = path.into();
646+
l.insert(path.clone(), path);
647+
}
648+
}
649+
}
650+
}
651+
627652
/// Configuration for tauri-bundler.
628653
///
629654
/// See more: https://tauri.app/v1/api/config#bundleconfig
@@ -653,7 +678,7 @@ pub struct BundleConfig {
653678
/// App resources to bundle.
654679
/// Each resource is a path to a file or directory.
655680
/// Glob patterns are supported.
656-
pub resources: Option<Vec<String>>,
681+
pub resources: Option<BundleResources>,
657682
/// A copyright string associated with your application.
658683
pub copyright: Option<String>,
659684
/// The application kind.

core/tauri-utils/src/resources.rs

Lines changed: 145 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
// SPDX-License-Identifier: Apache-2.0
33
// SPDX-License-Identifier: MIT
44

5-
use std::path::{Component, Path, PathBuf};
5+
use std::{
6+
collections::HashMap,
7+
path::{Component, Path, PathBuf},
8+
};
69

710
/// Given a path (absolute or relative) to a resource file, returns the
811
/// relative path from the bundle resources directory where that resource
@@ -39,40 +42,116 @@ pub fn external_binaries(external_binaries: &[String], target_triple: &str) -> V
3942
paths
4043
}
4144

45+
enum PatternIter<'a> {
46+
Slice(std::slice::Iter<'a, String>),
47+
Map(std::collections::hash_map::Iter<'a, String, String>),
48+
}
49+
4250
/// A helper to iterate through resources.
4351
pub struct ResourcePaths<'a> {
52+
iter: ResourcePathsIter<'a>,
53+
}
54+
55+
impl<'a> ResourcePaths<'a> {
56+
/// Creates a new ResourcePaths from a slice of patterns to iterate
57+
pub fn new(patterns: &'a [String], allow_walk: bool) -> ResourcePaths<'a> {
58+
ResourcePaths {
59+
iter: ResourcePathsIter {
60+
pattern_iter: PatternIter::Slice(patterns.iter()),
61+
glob_iter: None,
62+
walk_iter: None,
63+
allow_walk,
64+
current_pattern: None,
65+
current_pattern_is_valid: false,
66+
current_dest: None,
67+
},
68+
}
69+
}
70+
71+
/// Creates a new ResourcePaths from a slice of patterns to iterate
72+
pub fn from_map(patterns: &'a HashMap<String, String>, allow_walk: bool) -> ResourcePaths<'a> {
73+
ResourcePaths {
74+
iter: ResourcePathsIter {
75+
pattern_iter: PatternIter::Map(patterns.iter()),
76+
glob_iter: None,
77+
walk_iter: None,
78+
allow_walk,
79+
current_pattern: None,
80+
current_pattern_is_valid: false,
81+
current_dest: None,
82+
},
83+
}
84+
}
85+
86+
/// Returns the resource iterator that yields the source and target paths.
87+
/// Needed when using [`Self::from_map`].
88+
pub fn iter(self) -> ResourcePathsIter<'a> {
89+
self.iter
90+
}
91+
}
92+
93+
/// Iterator of a [`ResourcePaths`].
94+
pub struct ResourcePathsIter<'a> {
4495
/// the patterns to iterate.
45-
pattern_iter: std::slice::Iter<'a, String>,
96+
pattern_iter: PatternIter<'a>,
4697
/// the glob iterator if the path from the current iteration is a glob pattern.
4798
glob_iter: Option<glob::Paths>,
4899
/// the walkdir iterator if the path from the current iteration is a directory.
49100
walk_iter: Option<walkdir::IntoIter>,
50101
/// whether the resource paths allows directories or not.
51102
allow_walk: bool,
52103
/// the pattern of the current iteration.
53-
current_pattern: Option<String>,
104+
current_pattern: Option<(String, PathBuf)>,
54105
/// whether the current pattern is valid or not.
55106
current_pattern_is_valid: bool,
107+
/// Current destination path. Only set when the iterator comes from a Map.
108+
current_dest: Option<PathBuf>,
56109
}
57110

58-
impl<'a> ResourcePaths<'a> {
59-
/// Creates a new ResourcePaths from a slice of patterns to iterate
60-
pub fn new(patterns: &'a [String], allow_walk: bool) -> ResourcePaths<'a> {
61-
ResourcePaths {
62-
pattern_iter: patterns.iter(),
63-
glob_iter: None,
64-
walk_iter: None,
65-
allow_walk,
66-
current_pattern: None,
67-
current_pattern_is_valid: false,
68-
}
111+
/// Information for a resource.
112+
pub struct Resource {
113+
path: PathBuf,
114+
target: PathBuf,
115+
}
116+
117+
impl Resource {
118+
/// The path of the resource.
119+
pub fn path(&self) -> &Path {
120+
&self.path
121+
}
122+
123+
/// The target location of the resource.
124+
pub fn target(&self) -> &Path {
125+
&self.target
69126
}
70127
}
71128

72129
impl<'a> Iterator for ResourcePaths<'a> {
73130
type Item = crate::Result<PathBuf>;
74131

75132
fn next(&mut self) -> Option<crate::Result<PathBuf>> {
133+
self.iter.next().map(|r| r.map(|res| res.path))
134+
}
135+
}
136+
137+
fn normalize(path: &Path) -> PathBuf {
138+
let mut dest = PathBuf::new();
139+
for component in path.components() {
140+
match component {
141+
Component::Prefix(_) => {}
142+
Component::RootDir => dest.push("/"),
143+
Component::CurDir => {}
144+
Component::ParentDir => dest.push(".."),
145+
Component::Normal(string) => dest.push(string),
146+
}
147+
}
148+
dest
149+
}
150+
151+
impl<'a> Iterator for ResourcePathsIter<'a> {
152+
type Item = crate::Result<Resource>;
153+
154+
fn next(&mut self) -> Option<crate::Result<Resource>> {
76155
loop {
77156
if let Some(ref mut walk_entries) = self.walk_iter {
78157
if let Some(entry) = walk_entries.next() {
@@ -85,7 +164,20 @@ impl<'a> Iterator for ResourcePaths<'a> {
85164
continue;
86165
}
87166
self.current_pattern_is_valid = true;
88-
return Some(Ok(path.to_path_buf()));
167+
return Some(Ok(Resource {
168+
target: if let (Some(current_dest), Some(current_pattern)) =
169+
(&self.current_dest, &self.current_pattern)
170+
{
171+
if current_pattern.0.contains('*') {
172+
current_dest.join(path.file_name().unwrap())
173+
} else {
174+
current_dest.join(path.strip_prefix(&current_pattern.1).unwrap())
175+
}
176+
} else {
177+
resource_relpath(path)
178+
},
179+
path: path.to_path_buf(),
180+
}));
89181
}
90182
}
91183
self.walk_iter = None;
@@ -105,24 +197,51 @@ impl<'a> Iterator for ResourcePaths<'a> {
105197
}
106198
}
107199
self.current_pattern_is_valid = true;
108-
return Some(Ok(path));
200+
return Some(Ok(Resource {
201+
target: if let Some(current_dest) = &self.current_dest {
202+
current_dest.join(path.file_name().unwrap())
203+
} else {
204+
resource_relpath(&path)
205+
},
206+
path,
207+
}));
109208
} else if let Some(current_path) = &self.current_pattern {
110209
if !self.current_pattern_is_valid {
111210
self.glob_iter = None;
112-
return Some(Err(crate::Error::GlobPathNotFound(current_path.clone())));
211+
return Some(Err(crate::Error::GlobPathNotFound(current_path.0.clone())));
113212
}
114213
}
115214
}
116215
self.glob_iter = None;
117-
if let Some(pattern) = self.pattern_iter.next() {
118-
self.current_pattern = Some(pattern.to_string());
119-
self.current_pattern_is_valid = false;
120-
let glob = match glob::glob(pattern) {
121-
Ok(glob) => glob,
122-
Err(error) => return Some(Err(error.into())),
123-
};
124-
self.glob_iter = Some(glob);
125-
continue;
216+
self.current_dest = None;
217+
match &mut self.pattern_iter {
218+
PatternIter::Slice(iter) => {
219+
if let Some(pattern) = iter.next() {
220+
self.current_pattern = Some((pattern.to_string(), normalize(Path::new(pattern))));
221+
self.current_pattern_is_valid = false;
222+
let glob = match glob::glob(pattern) {
223+
Ok(glob) => glob,
224+
Err(error) => return Some(Err(error.into())),
225+
};
226+
self.glob_iter = Some(glob);
227+
continue;
228+
}
229+
}
230+
PatternIter::Map(iter) => {
231+
if let Some((pattern, dest)) = iter.next() {
232+
self.current_pattern = Some((pattern.to_string(), normalize(Path::new(pattern))));
233+
self.current_pattern_is_valid = false;
234+
let glob = match glob::glob(pattern) {
235+
Ok(glob) => glob,
236+
Err(error) => return Some(Err(error.into())),
237+
};
238+
self
239+
.current_dest
240+
.replace(resource_relpath(&PathBuf::from(dest)));
241+
self.glob_iter = Some(glob);
242+
continue;
243+
}
244+
}
126245
}
127246
return None;
128247
}

0 commit comments

Comments
 (0)