feat: allow specifying a resource map, closes #5844 (#5950)

Co-authored-by: amrbashir <amr.bashir2015@gmail.com>
closes #5844
This commit is contained in:
Lucas Fernandes Nogueira 2023-07-13 14:28:52 -07:00 committed by GitHub
parent ef962c43af
commit 4dd4893d7d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 1067 additions and 480 deletions

View File

@ -0,0 +1,5 @@
---
"tauri-bundler": minor:feat
---
Allow using a resource map instead of a simple array in `BundleSettings::resources_map`.

View File

@ -0,0 +1,5 @@
---
"tauri-utils": minor:feat
---
Allow specifying resources as a map specifying source and target paths.

View File

@ -9,8 +9,8 @@ use cargo_toml::Manifest;
use heck::AsShoutySnakeCase;
use tauri_utils::{
config::{Config, WebviewInstallMode},
resources::{external_binaries, resource_relpath, ResourcePaths},
config::{BundleResources, Config, WebviewInstallMode},
resources::{external_binaries, ResourcePaths},
};
use std::path::{Path, PathBuf};
@ -72,11 +72,10 @@ fn copy_binaries(
/// Copies resources to a path.
fn copy_resources(resources: ResourcePaths<'_>, path: &Path) -> Result<()> {
for src in resources {
let src = src?;
println!("cargo:rerun-if-changed={}", src.display());
let dest = path.join(resource_relpath(&src));
copy_file(&src, dest)?;
for resource in resources.iter() {
let resource = resource?;
println!("cargo:rerun-if-changed={}", resource.path().display());
copy_file(resource.path(), path.join(resource.target()))?;
}
Ok(())
}
@ -344,7 +343,12 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
}
#[allow(unused_mut, clippy::redundant_clone)]
let mut resources = config.tauri.bundle.resources.clone().unwrap_or_default();
let mut resources = config
.tauri
.bundle
.resources
.clone()
.unwrap_or_else(|| BundleResources::List(Vec::new()));
if target_triple.contains("windows") {
if let Some(fixed_webview2_runtime_path) =
match &config.tauri.bundle.windows.webview_fixed_runtime_path {
@ -358,7 +362,12 @@ pub fn try_build(attributes: Attributes) -> Result<()> {
resources.push(fixed_webview2_runtime_path.display().to_string());
}
}
copy_resources(ResourcePaths::new(resources.as_slice(), true), target_dir)?;
match resources {
BundleResources::List(res) => {
copy_resources(ResourcePaths::new(res.as_slice(), true), target_dir)?
}
BundleResources::Map(map) => copy_resources(ResourcePaths::from_map(&map, true), target_dir)?,
}
if target_triple.contains("darwin") {
if let Some(version) = &config.tauri.bundle.macos.minimum_system_version {

View File

@ -1074,13 +1074,14 @@
},
"resources": {
"description": "App resources to bundle. Each resource is a path to a file or directory. Glob patterns are supported.",
"type": [
"array",
"null"
],
"items": {
"type": "string"
}
"anyOf": [
{
"$ref": "#/definitions/BundleResources"
},
{
"type": "null"
}
]
},
"copyright": {
"description": "A copyright string associated with your application.",
@ -1258,6 +1259,25 @@
}
]
},
"BundleResources": {
"description": "Definition for bundle resources. Can be either a list of paths to include or a map of source to target paths.",
"anyOf": [
{
"description": "A list of paths to include.",
"type": "array",
"items": {
"type": "string"
}
},
{
"description": "A map of source to target paths.",
"type": "object",
"additionalProperties": {
"type": "string"
}
}
]
},
"AppImageConfig": {
"description": "Configuration for AppImage bundles.\n\nSee more: https://tauri.app/v1/api/config#appimageconfig",
"type": "object",

View File

@ -3045,7 +3045,7 @@ fn on_close_requested<'a, T: UserEvent>(
}
fn on_window_close(window_id: WebviewId, windows: Arc<RefCell<HashMap<WebviewId, WindowWrapper>>>) {
if let Some(mut window_wrapper) = windows.borrow_mut().get_mut(&window_id) {
if let Some(window_wrapper) = windows.borrow_mut().get_mut(&window_id) {
window_wrapper.inner = None;
}
}

View File

@ -624,6 +624,31 @@ impl Default for WindowsConfig {
}
}
/// Definition for bundle resources.
/// Can be either a list of paths to include or a map of source to target paths.
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields, untagged)]
pub enum BundleResources {
/// A list of paths to include.
List(Vec<String>),
/// A map of source to target paths.
Map(HashMap<String, String>),
}
impl BundleResources {
/// Adds a path to the resource collection.
pub fn push(&mut self, path: impl Into<String>) {
match self {
Self::List(l) => l.push(path.into()),
Self::Map(l) => {
let path = path.into();
l.insert(path.clone(), path);
}
}
}
}
/// Configuration for tauri-bundler.
///
/// See more: https://tauri.app/v1/api/config#bundleconfig
@ -653,7 +678,7 @@ pub struct BundleConfig {
/// App resources to bundle.
/// Each resource is a path to a file or directory.
/// Glob patterns are supported.
pub resources: Option<Vec<String>>,
pub resources: Option<BundleResources>,
/// A copyright string associated with your application.
pub copyright: Option<String>,
/// The application kind.

View File

@ -2,7 +2,10 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
use std::path::{Component, Path, PathBuf};
use std::{
collections::HashMap,
path::{Component, Path, PathBuf},
};
/// Given a path (absolute or relative) to a resource file, returns the
/// relative path from the bundle resources directory where that resource
@ -39,10 +42,58 @@ pub fn external_binaries(external_binaries: &[String], target_triple: &str) -> V
paths
}
enum PatternIter<'a> {
Slice(std::slice::Iter<'a, String>),
Map(std::collections::hash_map::Iter<'a, String, String>),
}
/// A helper to iterate through resources.
pub struct ResourcePaths<'a> {
iter: ResourcePathsIter<'a>,
}
impl<'a> ResourcePaths<'a> {
/// Creates a new ResourcePaths from a slice of patterns to iterate
pub fn new(patterns: &'a [String], allow_walk: bool) -> ResourcePaths<'a> {
ResourcePaths {
iter: ResourcePathsIter {
pattern_iter: PatternIter::Slice(patterns.iter()),
glob_iter: None,
walk_iter: None,
allow_walk,
current_pattern: None,
current_pattern_is_valid: false,
current_dest: None,
},
}
}
/// Creates a new ResourcePaths from a slice of patterns to iterate
pub fn from_map(patterns: &'a HashMap<String, String>, allow_walk: bool) -> ResourcePaths<'a> {
ResourcePaths {
iter: ResourcePathsIter {
pattern_iter: PatternIter::Map(patterns.iter()),
glob_iter: None,
walk_iter: None,
allow_walk,
current_pattern: None,
current_pattern_is_valid: false,
current_dest: None,
},
}
}
/// Returns the resource iterator that yields the source and target paths.
/// Needed when using [`Self::from_map`].
pub fn iter(self) -> ResourcePathsIter<'a> {
self.iter
}
}
/// Iterator of a [`ResourcePaths`].
pub struct ResourcePathsIter<'a> {
/// the patterns to iterate.
pattern_iter: std::slice::Iter<'a, String>,
pattern_iter: PatternIter<'a>,
/// the glob iterator if the path from the current iteration is a glob pattern.
glob_iter: Option<glob::Paths>,
/// the walkdir iterator if the path from the current iteration is a directory.
@ -50,22 +101,28 @@ pub struct ResourcePaths<'a> {
/// whether the resource paths allows directories or not.
allow_walk: bool,
/// the pattern of the current iteration.
current_pattern: Option<String>,
current_pattern: Option<(String, PathBuf)>,
/// whether the current pattern is valid or not.
current_pattern_is_valid: bool,
/// Current destination path. Only set when the iterator comes from a Map.
current_dest: Option<PathBuf>,
}
impl<'a> ResourcePaths<'a> {
/// Creates a new ResourcePaths from a slice of patterns to iterate
pub fn new(patterns: &'a [String], allow_walk: bool) -> ResourcePaths<'a> {
ResourcePaths {
pattern_iter: patterns.iter(),
glob_iter: None,
walk_iter: None,
allow_walk,
current_pattern: None,
current_pattern_is_valid: false,
}
/// Information for a resource.
pub struct Resource {
path: PathBuf,
target: PathBuf,
}
impl Resource {
/// The path of the resource.
pub fn path(&self) -> &Path {
&self.path
}
/// The target location of the resource.
pub fn target(&self) -> &Path {
&self.target
}
}
@ -73,6 +130,28 @@ impl<'a> Iterator for ResourcePaths<'a> {
type Item = crate::Result<PathBuf>;
fn next(&mut self) -> Option<crate::Result<PathBuf>> {
self.iter.next().map(|r| r.map(|res| res.path))
}
}
fn normalize(path: &Path) -> PathBuf {
let mut dest = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(_) => {}
Component::RootDir => dest.push("/"),
Component::CurDir => {}
Component::ParentDir => dest.push(".."),
Component::Normal(string) => dest.push(string),
}
}
dest
}
impl<'a> Iterator for ResourcePathsIter<'a> {
type Item = crate::Result<Resource>;
fn next(&mut self) -> Option<crate::Result<Resource>> {
loop {
if let Some(ref mut walk_entries) = self.walk_iter {
if let Some(entry) = walk_entries.next() {
@ -85,7 +164,20 @@ impl<'a> Iterator for ResourcePaths<'a> {
continue;
}
self.current_pattern_is_valid = true;
return Some(Ok(path.to_path_buf()));
return Some(Ok(Resource {
target: if let (Some(current_dest), Some(current_pattern)) =
(&self.current_dest, &self.current_pattern)
{
if current_pattern.0.contains('*') {
current_dest.join(path.file_name().unwrap())
} else {
current_dest.join(path.strip_prefix(&current_pattern.1).unwrap())
}
} else {
resource_relpath(path)
},
path: path.to_path_buf(),
}));
}
}
self.walk_iter = None;
@ -105,24 +197,51 @@ impl<'a> Iterator for ResourcePaths<'a> {
}
}
self.current_pattern_is_valid = true;
return Some(Ok(path));
return Some(Ok(Resource {
target: if let Some(current_dest) = &self.current_dest {
current_dest.join(path.file_name().unwrap())
} else {
resource_relpath(&path)
},
path,
}));
} else if let Some(current_path) = &self.current_pattern {
if !self.current_pattern_is_valid {
self.glob_iter = None;
return Some(Err(crate::Error::GlobPathNotFound(current_path.clone())));
return Some(Err(crate::Error::GlobPathNotFound(current_path.0.clone())));
}
}
}
self.glob_iter = None;
if let Some(pattern) = self.pattern_iter.next() {
self.current_pattern = Some(pattern.to_string());
self.current_pattern_is_valid = false;
let glob = match glob::glob(pattern) {
Ok(glob) => glob,
Err(error) => return Some(Err(error.into())),
};
self.glob_iter = Some(glob);
continue;
self.current_dest = None;
match &mut self.pattern_iter {
PatternIter::Slice(iter) => {
if let Some(pattern) = iter.next() {
self.current_pattern = Some((pattern.to_string(), normalize(Path::new(pattern))));
self.current_pattern_is_valid = false;
let glob = match glob::glob(pattern) {
Ok(glob) => glob,
Err(error) => return Some(Err(error.into())),
};
self.glob_iter = Some(glob);
continue;
}
}
PatternIter::Map(iter) => {
if let Some((pattern, dest)) = iter.next() {
self.current_pattern = Some((pattern.to_string(), normalize(Path::new(pattern))));
self.current_pattern_is_valid = false;
let glob = match glob::glob(pattern) {
Ok(glob) => glob,
Err(error) => return Some(Err(error.into())),
};
self
.current_dest
.replace(resource_relpath(&PathBuf::from(dest)));
self.glob_iter = Some(glob);
continue;
}
}
}
return None;
}

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@ edition = "2021"
rust-version = "1.60"
[build-dependencies]
tauri-build = { path = "../../../core/tauri-build", features = [ "codegen" ] }
tauri-build = { path = "../../../core/tauri-build", features = ["codegen"] }
[dependencies]
serde_json = "1.0"

View File

@ -382,6 +382,12 @@ pub struct BundleSettings {
///
/// supports glob patterns.
pub resources: Option<Vec<String>>,
/// The app's resources to bundle. Takes precedence over `Self::resources` when specified.
///
/// Maps each resource path to its target directory in the bundle resources directory.
///
/// Supports glob patterns.
pub resources_map: Option<HashMap<String, String>>,
/// the app's copyright.
pub copyright: Option<String>,
/// the app's category.
@ -732,9 +738,14 @@ impl Settings {
/// Returns an iterator over the resource files to be included in this
/// bundle.
pub fn resource_files(&self) -> ResourcePaths<'_> {
match self.bundle_settings.resources {
Some(ref paths) => ResourcePaths::new(paths.as_slice(), true),
None => ResourcePaths::new(&[], true),
match (
&self.bundle_settings.resources,
&self.bundle_settings.resources_map,
) {
(Some(paths), None) => ResourcePaths::new(paths.as_slice(), true),
(None, Some(map)) => ResourcePaths::from_map(map, true),
(Some(_), Some(_)) => panic!("cannot use both `resources` and `resources_map`"),
(None, None) => ResourcePaths::new(&[], true),
}
}
@ -765,10 +776,10 @@ impl Settings {
/// Copies resources to a path.
pub fn copy_resources(&self, path: &Path) -> crate::Result<()> {
for src in self.resource_files() {
let src = src?;
let dest = path.join(tauri_utils::resources::resource_relpath(&src));
common::copy_file(&src, dest)?;
for resource in self.resource_files().iter() {
let resource = resource?;
let dest = path.join(resource.target());
common::copy_file(resource.path(), dest)?;
}
Ok(())
}

View File

@ -28,8 +28,7 @@ use std::{
path::{Path, PathBuf},
process::Command,
};
use tauri_utils::display_path;
use tauri_utils::{config::WebviewInstallMode, resources::resource_relpath};
use tauri_utils::{config::WebviewInstallMode, display_path};
use uuid::Uuid;
// URLS for the WIX toolchain. Can be used for cross-platform compilation.
@ -90,7 +89,7 @@ struct ResourceFile {
/// the id to use on the WIX XML.
id: String,
/// the file path.
path: String,
path: PathBuf,
}
/// A resource directory to bundle with WIX.
@ -124,7 +123,7 @@ impl ResourceDirectory {
r#"<Component Id="{id}" Guid="{guid}" Win64="$(var.Win64)" KeyPath="yes"><File Id="PathFile_{id}" Source="{path}" /></Component>"#,
id = file.id,
guid = file.guid,
path = file.path
path = file.path.display()
).as_str()
);
}
@ -913,15 +912,11 @@ fn generate_resource_data(settings: &Settings) -> crate::Result<ResourceMap> {
let mut added_resources = Vec::new();
for src in settings.resource_files() {
let src = src?;
let resource_path = cwd
.join(src.clone())
.into_os_string()
.into_string()
.expect("failed to read resource path");
for resource in settings.resource_files().iter() {
let resource = resource?;
let src = cwd.join(resource.path());
let resource_path = dunce::simplified(&src).to_path_buf();
// In some glob resource paths like `assets/**/*` a file might appear twice
// because the `tauri_utils::resources::ResourcePaths` iterator also reads a directory
// when it finds one. So we must check it before processing the file.
@ -934,11 +929,11 @@ fn generate_resource_data(settings: &Settings) -> crate::Result<ResourceMap> {
let resource_entry = ResourceFile {
id: format!("I{}", Uuid::new_v4().as_simple()),
guid: Uuid::new_v4().to_string(),
path: resource_path,
path: resource_path.clone(),
};
// split the resource path directories
let target_path = resource_relpath(&src);
let target_path = resource.target();
let components_count = target_path.components().count();
let directories = target_path
.components()
@ -1003,7 +998,7 @@ fn generate_resource_data(settings: &Settings) -> crate::Result<ResourceMap> {
let out_dir = settings.project_out_directory();
for dll in glob::glob(out_dir.join("*.dll").to_string_lossy().to_string().as_str())? {
let path = dll?;
let resource_path = path.to_string_lossy().into_owned();
let resource_path = dunce::simplified(&path);
let relative_path = path
.strip_prefix(out_dir)
.unwrap()
@ -1013,7 +1008,7 @@ fn generate_resource_data(settings: &Settings) -> crate::Result<ResourceMap> {
dlls.push(ResourceFile {
id: format!("I{}", Uuid::new_v4().as_simple()),
guid: Uuid::new_v4().to_string(),
path: resource_path,
path: resource_path.to_path_buf(),
});
}
}

View File

@ -20,10 +20,7 @@ use tauri_utils::display_path;
use anyhow::Context;
use handlebars::{to_json, Handlebars};
use log::{info, warn};
use tauri_utils::{
config::{NSISInstallerMode, WebviewInstallMode},
resources::resource_relpath,
};
use tauri_utils::config::{NSISInstallerMode, WebviewInstallMode};
use std::{
collections::{BTreeMap, HashMap},
@ -487,16 +484,18 @@ fn build_nsis_app_installer(
}
/// BTreeMap<OriginalPath, (ParentOfTargetPath, TargetPath)>
type ResourcesMap = BTreeMap<PathBuf, (String, PathBuf)>;
type ResourcesMap = BTreeMap<PathBuf, (PathBuf, PathBuf)>;
fn generate_resource_data(settings: &Settings) -> crate::Result<ResourcesMap> {
let mut resources = ResourcesMap::new();
let cwd = std::env::current_dir()?;
let mut added_resources = Vec::new();
for src in settings.resource_files() {
let src = src?;
let resource_path = dunce::canonicalize(cwd.join(&src))?;
for resource in settings.resource_files().iter() {
let resource = resource?;
let src = cwd.join(resource.path());
let resource_path = dunce::simplified(&src).to_path_buf();
// In some glob resource paths like `assets/**/*` a file might appear twice
// because the `tauri_utils::resources::ResourcePaths` iterator also reads a directory
@ -506,15 +505,15 @@ fn generate_resource_data(settings: &Settings) -> crate::Result<ResourcesMap> {
}
added_resources.push(resource_path.clone());
let target_path = resource_relpath(&src);
let target_path = resource.target();
resources.insert(
resource_path,
(
target_path
.parent()
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default(),
target_path,
.expect("Couldn't get parent of target path")
.to_path_buf(),
target_path.to_path_buf(),
),
);
}

View File

@ -1074,13 +1074,14 @@
},
"resources": {
"description": "App resources to bundle. Each resource is a path to a file or directory. Glob patterns are supported.",
"type": [
"array",
"null"
],
"items": {
"type": "string"
}
"anyOf": [
{
"$ref": "#/definitions/BundleResources"
},
{
"type": "null"
}
]
},
"copyright": {
"description": "A copyright string associated with your application.",
@ -1258,6 +1259,25 @@
}
]
},
"BundleResources": {
"description": "Definition for bundle resources. Can be either a list of paths to include or a map of source to target paths.",
"anyOf": [
{
"description": "A list of paths to include.",
"type": "array",
"items": {
"type": "string"
}
},
{
"description": "A map of source to target paths.",
"type": "object",
"additionalProperties": {
"type": "string"
}
}
]
},
"AppImageConfig": {
"description": "Configuration for AppImage bundles.\n\nSee more: https://tauri.app/v1/api/config#appimageconfig",
"type": "object",

View File

@ -35,7 +35,7 @@ use tauri_utils::config::parse::is_configuration_file;
use super::{AppSettings, ExitReason, Interface};
use crate::helpers::{
app_paths::{app_dir, tauri_dir},
config::{nsis_settings, reload as reload_config, wix_settings, Config},
config::{nsis_settings, reload as reload_config, wix_settings, BundleResources, Config},
};
use tauri_utils::display_path;
@ -989,7 +989,9 @@ fn tauri_config_to_bundle_settings(
let windows_icon_path = PathBuf::from("");
#[allow(unused_mut)]
let mut resources = config.resources.unwrap_or_default();
let mut resources = config
.resources
.unwrap_or(BundleResources::List(Vec::new()));
#[allow(unused_mut)]
let mut depends = config.deb.depends.unwrap_or_default();
@ -1040,15 +1042,17 @@ fn tauri_config_to_bundle_settings(
None => config.macos.provider_short_name,
};
let (resources, resources_map) = match resources {
BundleResources::List(paths) => (Some(paths), None),
BundleResources::Map(map) => (None, Some(map)),
};
Ok(BundleSettings {
identifier: Some(config.identifier),
publisher: config.publisher,
icon: Some(config.icon),
resources: if resources.is_empty() {
None
} else {
Some(resources)
},
resources,
resources_map,
copyright: config.copyright,
category: match config.category {
Some(category) => Some(AppCategory::from_str(&category).map_err(|e| match e {