rust-embed-impl-8.7.0/.cargo_vcs_info.json0000644000000001420000000000100140530ustar { "git": { "sha1": "f292486b6c5a2af3c7ecba5905ab3143ebcde10b" }, "path_in_vcs": "impl" }rust-embed-impl-8.7.0/Cargo.lock0000644000000332530000000000100120370ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "aho-corasick" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] [[package]] name = "bitflags" version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" [[package]] name = "block-buffer" version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" dependencies = [ "generic-array", ] [[package]] name = "bstr" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "234113d19d0d7d613b40e86fb654acf958910802bcceab913a4f9e7cda03b1a4" dependencies = [ "memchr", "serde", ] [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cpufeatures" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" dependencies = [ "libc", ] [[package]] name = "crypto-common" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array", "typenum", ] [[package]] name = "digest" version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", ] [[package]] name = "dirs" version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" dependencies = [ "dirs-sys", ] [[package]] name = "dirs-sys" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" dependencies = [ "libc", "option-ext", "redox_users", "windows-sys 0.48.0", ] [[package]] name = "generic-array" version = "0.14.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", ] [[package]] name = "getrandom" version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", "wasi", ] [[package]] name = "globset" version = "0.4.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54a1028dfc5f5df5da8a56a73e6c153c9a9708ec57232470703592a3f18e49f5" dependencies = [ "aho-corasick", "bstr", "log", "regex-automata", "regex-syntax", ] [[package]] name = "libc" version = "0.2.171" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" [[package]] name = "libredox" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ "bitflags", "libc", ] [[package]] name = "log" version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "mime" version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" [[package]] name = "mime_guess" version = "2.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" dependencies = [ "mime", "unicase", ] [[package]] name = "option-ext" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "proc-macro2" version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "redox_users" version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" dependencies = [ "getrandom", "libredox", "thiserror", ] [[package]] name = "regex-automata" version = "0.4.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-syntax" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "rust-embed-impl" version = "8.7.0" dependencies = [ "proc-macro2", "quote", "rust-embed-utils", "shellexpand", "syn", "walkdir", ] [[package]] name = "rust-embed-utils" version = "8.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "08d55b95147fe01265d06b3955db798bdaed52e60e2211c41137701b3aba8e21" dependencies = [ "globset", "mime_guess", "sha2", "walkdir", ] [[package]] name = "same-file" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" dependencies = [ "winapi-util", ] [[package]] name = "serde" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "sha2" version = "0.10.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" dependencies = [ "cfg-if", "cpufeatures", "digest", ] [[package]] name = "shellexpand" version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da03fa3b94cc19e3ebfc88c4229c49d8f08cdbd1228870a45f0ffdf84988e14b" dependencies = [ "dirs", ] [[package]] name = "syn" version = "2.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "thiserror" version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "typenum" version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" [[package]] name = "unicase" version = "2.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "version_check" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "walkdir" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" dependencies = [ "same-file", "winapi-util", ] [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "winapi-util" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ "windows-sys 0.59.0", ] [[package]] name = "windows-sys" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ "windows-targets 0.48.5", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets 0.52.6", ] [[package]] name = "windows-targets" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" dependencies = [ "windows_aarch64_gnullvm 0.48.5", "windows_aarch64_msvc 0.48.5", "windows_i686_gnu 0.48.5", "windows_i686_msvc 0.48.5", "windows_x86_64_gnu 0.48.5", "windows_x86_64_gnullvm 0.48.5", "windows_x86_64_msvc 0.48.5", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", "windows_i686_gnullvm", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.48.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" rust-embed-impl-8.7.0/Cargo.toml0000644000000033370000000000100120620ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "rust-embed-impl" version = "8.7.0" authors = ["pyros2097 "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Rust Custom Derive Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev" documentation = "https://docs.rs/rust-embed" readme = "readme.md" keywords = [ "http", "rocket", "static", "web", "server", ] categories = ["web-programming::http-server"] license = "MIT" repository = "https://github.com/pyros2097/rust-embed" [features] compression = [] debug-embed = [] deterministic-timestamps = [] include-exclude = ["rust-embed-utils/include-exclude"] interpolate-folder-path = ["shellexpand"] mime-guess = ["rust-embed-utils/mime-guess"] [lib] name = "rust_embed_impl" path = "src/lib.rs" proc-macro = true [dependencies.proc-macro2] version = "1" [dependencies.quote] version = "1" [dependencies.rust-embed-utils] version = "8.7.0" [dependencies.shellexpand] version = "3" optional = true [dependencies.syn] version = "2" features = [ "derive", "parsing", "proc-macro", "printing", ] default-features = false [dependencies.walkdir] version = "2.3.1" rust-embed-impl-8.7.0/Cargo.toml.orig000064400000000000000000000020241046102023000155330ustar 00000000000000[package] name = "rust-embed-impl" version = "8.7.0" description = "Rust Custom Derive Macro which loads files into the rust binary at compile time during release and loads the file from the fs during dev" readme = "readme.md" documentation = "https://docs.rs/rust-embed" repository = "https://github.com/pyros2097/rust-embed" license = "MIT" keywords = ["http", "rocket", "static", "web", "server"] categories = ["web-programming::http-server"] authors = ["pyros2097 "] edition = "2018" [lib] proc-macro = true [dependencies] rust-embed-utils = { version = "8.7.0", path = "../utils"} syn = { version = "2", default-features = false, features = ["derive", "parsing", "proc-macro", "printing"] } quote = "1" proc-macro2 = "1" walkdir = "2.3.1" [dependencies.shellexpand] version = "3" optional = true [features] debug-embed = [] interpolate-folder-path = ["shellexpand"] compression = [] mime-guess = ["rust-embed-utils/mime-guess"] include-exclude = ["rust-embed-utils/include-exclude"] deterministic-timestamps = [] rust-embed-impl-8.7.0/license000064400000000000000000000020651046102023000142160ustar 00000000000000The MIT License (MIT) Copyright (c) 2018 pyros2097 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. rust-embed-impl-8.7.0/readme.md000064400000000000000000000001231046102023000144210ustar 00000000000000# Rust Embed Implementation The implementation of the rust-embed macro lies here. rust-embed-impl-8.7.0/src/lib.rs000064400000000000000000000353321046102023000145570ustar 00000000000000#![recursion_limit = "1024"] #![forbid(unsafe_code)] #[macro_use] extern crate quote; extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use rust_embed_utils::PathMatcher; use std::{ collections::BTreeMap, env, io::ErrorKind, iter::FromIterator, path::{Path, PathBuf}, }; use syn::{parse_macro_input, Data, DeriveInput, Expr, ExprLit, Fields, Lit, Meta, MetaNameValue}; fn embedded( ident: &syn::Ident, relative_folder_path: Option<&str>, absolute_folder_path: String, prefix: Option<&str>, includes: &[String], excludes: &[String], metadata_only: bool, crate_path: &syn::Path, ) -> syn::Result { extern crate rust_embed_utils; let mut match_values = BTreeMap::new(); let mut list_values = Vec::::new(); let includes: Vec<&str> = includes.iter().map(AsRef::as_ref).collect(); let excludes: Vec<&str> = excludes.iter().map(AsRef::as_ref).collect(); let matcher = PathMatcher::new(&includes, &excludes); for rust_embed_utils::FileEntry { rel_path, full_canonical_path } in rust_embed_utils::get_files(absolute_folder_path.clone(), matcher) { match_values.insert( rel_path.clone(), embed_file(relative_folder_path, ident, &rel_path, &full_canonical_path, metadata_only, crate_path)?, ); list_values.push(if let Some(prefix) = prefix { format!("{}{}", prefix, rel_path) } else { rel_path }); } let array_len = list_values.len(); // If debug-embed is on, unconditionally include the code below. Otherwise, // make it conditional on cfg(not(debug_assertions)). let not_debug_attr = if cfg!(feature = "debug-embed") { quote! {} } else { quote! { #[cfg(not(debug_assertions))]} }; let handle_prefix = if let Some(prefix) = prefix { quote! { let file_path = file_path.strip_prefix(#prefix)?; } } else { TokenStream2::new() }; let match_values = match_values.into_iter().map(|(path, bytes)| { quote! { (#path, #bytes), } }); let value_type = if cfg!(feature = "compression") { quote! { fn() -> #crate_path::EmbeddedFile } } else { quote! { #crate_path::EmbeddedFile } }; let get_value = if cfg!(feature = "compression") { quote! {|idx| (ENTRIES[idx].1)()} } else { quote! {|idx| ENTRIES[idx].1.clone()} }; Ok(quote! { #not_debug_attr impl #ident { /// Get an embedded file and its metadata. pub fn get(file_path: &str) -> ::std::option::Option<#crate_path::EmbeddedFile> { #handle_prefix let key = file_path.replace("\\", "/"); const ENTRIES: &'static [(&'static str, #value_type)] = &[ #(#match_values)*]; let position = ENTRIES.binary_search_by_key(&key.as_str(), |entry| entry.0); position.ok().map(#get_value) } fn names() -> ::std::slice::Iter<'static, &'static str> { const ITEMS: [&str; #array_len] = [#(#list_values),*]; ITEMS.iter() } /// Iterates over the file paths in the folder. pub fn iter() -> impl ::std::iter::Iterator> { Self::names().map(|x| ::std::borrow::Cow::from(*x)) } } #not_debug_attr impl #crate_path::RustEmbed for #ident { fn get(file_path: &str) -> ::std::option::Option<#crate_path::EmbeddedFile> { #ident::get(file_path) } fn iter() -> #crate_path::Filenames { #crate_path::Filenames::Embedded(#ident::names()) } } }) } fn dynamic( ident: &syn::Ident, folder_path: String, prefix: Option<&str>, includes: &[String], excludes: &[String], metadata_only: bool, crate_path: &syn::Path, ) -> TokenStream2 { let (handle_prefix, map_iter) = if let ::std::option::Option::Some(prefix) = prefix { ( quote! { let file_path = file_path.strip_prefix(#prefix)?; }, quote! { ::std::borrow::Cow::Owned(format!("{}{}", #prefix, e.rel_path)) }, ) } else { (TokenStream2::new(), quote! { ::std::borrow::Cow::from(e.rel_path) }) }; let declare_includes = quote! { const INCLUDES: &[&str] = &[#(#includes),*]; }; let declare_excludes = quote! { const EXCLUDES: &[&str] = &[#(#excludes),*]; }; // In metadata_only mode, we still need to read file contents to generate the // file hash, but then we drop the file data. let strip_contents = metadata_only.then_some(quote! { .map(|mut file| { file.data = ::std::default::Default::default(); file }) }); let non_canonical_folder_path = Path::new(&folder_path); let canonical_folder_path = non_canonical_folder_path .canonicalize() .or_else(|err| match err { err if err.kind() == ErrorKind::NotFound => Ok(non_canonical_folder_path.to_owned()), err => Err(err), }) .expect("folder path must resolve to an absolute path"); let canonical_folder_path = canonical_folder_path.to_str().expect("absolute folder path must be valid unicode"); quote! { #[cfg(debug_assertions)] impl #ident { fn matcher() -> #crate_path::utils::PathMatcher { #declare_includes #declare_excludes static PATH_MATCHER: ::std::sync::OnceLock<#crate_path::utils::PathMatcher> = ::std::sync::OnceLock::new(); PATH_MATCHER.get_or_init(|| #crate_path::utils::PathMatcher::new(INCLUDES, EXCLUDES)).clone() } /// Get an embedded file and its metadata. pub fn get(file_path: &str) -> ::std::option::Option<#crate_path::EmbeddedFile> { #handle_prefix let rel_file_path = file_path.replace("\\", "/"); let file_path = ::std::path::Path::new(#folder_path).join(&rel_file_path); // Make sure the path requested does not escape the folder path let canonical_file_path = file_path.canonicalize().ok()?; if !canonical_file_path.starts_with(#canonical_folder_path) { // Tried to request a path that is not in the embedded folder // TODO: Currently it allows "path_traversal_attack" for the symlink files // For it to be working properly we need to get absolute path first // and check that instead if it starts with `canonical_folder_path` // https://doc.rust-lang.org/std/path/fn.absolute.html (currently nightly) // Should be allowed only if it was a symlink let metadata = ::std::fs::symlink_metadata(&file_path).ok()?; if !metadata.is_symlink() { return ::std::option::Option::None; } } let path_matcher = Self::matcher(); if path_matcher.is_path_included(&rel_file_path) { #crate_path::utils::read_file_from_fs(&canonical_file_path).ok() #strip_contents } else { ::std::option::Option::None } } /// Iterates over the file paths in the folder. pub fn iter() -> impl ::std::iter::Iterator> { use ::std::path::Path; #crate_path::utils::get_files(::std::string::String::from(#folder_path), Self::matcher()) .map(|e| #map_iter) } } #[cfg(debug_assertions)] impl #crate_path::RustEmbed for #ident { fn get(file_path: &str) -> ::std::option::Option<#crate_path::EmbeddedFile> { #ident::get(file_path) } fn iter() -> #crate_path::Filenames { // the return type of iter() is unnamable, so we have to box it #crate_path::Filenames::Dynamic(::std::boxed::Box::new(#ident::iter())) } } } } fn generate_assets( ident: &syn::Ident, relative_folder_path: Option<&str>, absolute_folder_path: String, prefix: Option, includes: Vec, excludes: Vec, metadata_only: bool, crate_path: &syn::Path, ) -> syn::Result { let embedded_impl = embedded( ident, relative_folder_path, absolute_folder_path.clone(), prefix.as_deref(), &includes, &excludes, metadata_only, crate_path, ); if cfg!(feature = "debug-embed") { return embedded_impl; } let embedded_impl = embedded_impl?; let dynamic_impl = dynamic(ident, absolute_folder_path, prefix.as_deref(), &includes, &excludes, metadata_only, crate_path); Ok(quote! { #embedded_impl #dynamic_impl }) } fn embed_file( folder_path: Option<&str>, ident: &syn::Ident, rel_path: &str, full_canonical_path: &str, metadata_only: bool, crate_path: &syn::Path, ) -> syn::Result { let file = rust_embed_utils::read_file_from_fs(Path::new(full_canonical_path)).expect("File should be readable"); let hash = file.metadata.sha256_hash(); let (last_modified, created) = if cfg!(feature = "deterministic-timestamps") { (quote! { ::std::option::Option::Some(0u64) }, quote! { ::std::option::Option::Some(0u64) }) } else { let last_modified = match file.metadata.last_modified() { Some(last_modified) => quote! { ::std::option::Option::Some(#last_modified) }, None => quote! { ::std::option::Option::None }, }; let created = match file.metadata.created() { Some(created) => quote! { ::std::option::Option::Some(#created) }, None => quote! { ::std::option::Option::None }, }; (last_modified, created) }; #[cfg(feature = "mime-guess")] let mimetype_tokens = { let mt = file.metadata.mimetype(); quote! { , #mt } }; #[cfg(not(feature = "mime-guess"))] let mimetype_tokens = TokenStream2::new(); let embedding_code = if metadata_only { quote! { const BYTES: &'static [u8] = &[]; } } else if cfg!(feature = "compression") { let folder_path = folder_path.ok_or(syn::Error::new(ident.span(), "`folder` must be provided under `compression` feature."))?; // Print some debugging information let full_relative_path = PathBuf::from_iter([folder_path, rel_path]); let full_relative_path = full_relative_path.to_string_lossy(); quote! { #crate_path::flate!(static BYTES: [u8] from #full_relative_path); } } else { quote! { const BYTES: &'static [u8] = include_bytes!(#full_canonical_path); } }; let closure_args = if cfg!(feature = "compression") { quote! { || } } else { quote! {} }; Ok(quote! { #closure_args { #embedding_code #crate_path::EmbeddedFile { data: ::std::borrow::Cow::Borrowed(&BYTES), metadata: #crate_path::Metadata::__rust_embed_new([#(#hash),*], #last_modified, #created #mimetype_tokens) } } }) } /// Find all pairs of the `name = "value"` attribute from the derive input fn find_attribute_values(ast: &syn::DeriveInput, attr_name: &str) -> Vec { ast .attrs .iter() .filter(|value| value.path().is_ident(attr_name)) .filter_map(|attr| match &attr.meta { Meta::NameValue(MetaNameValue { value: Expr::Lit(ExprLit { lit: Lit::Str(val), .. }), .. }) => Some(val.value()), _ => None, }) .collect() } fn find_bool_attribute(ast: &syn::DeriveInput, attr_name: &str) -> Option { ast .attrs .iter() .find(|value| value.path().is_ident(attr_name)) .and_then(|attr| match &attr.meta { Meta::NameValue(MetaNameValue { value: Expr::Lit(ExprLit { lit: Lit::Bool(val), .. }), .. }) => Some(val.value()), _ => None, }) } fn impl_rust_embed(ast: &syn::DeriveInput) -> syn::Result { match ast.data { Data::Struct(ref data) => match data.fields { Fields::Unit => {} _ => return Err(syn::Error::new_spanned(ast, "RustEmbed can only be derived for unit structs")), }, _ => return Err(syn::Error::new_spanned(ast, "RustEmbed can only be derived for unit structs")), }; let crate_path: syn::Path = find_attribute_values(ast, "crate_path") .last() .map_or_else(|| syn::parse_str("rust_embed").unwrap(), |v| syn::parse_str(v).unwrap()); let mut folder_paths = find_attribute_values(ast, "folder"); if folder_paths.len() != 1 { return Err(syn::Error::new_spanned( ast, "#[derive(RustEmbed)] must contain one attribute like this #[folder = \"examples/public/\"]", )); } let folder_path = folder_paths.remove(0); let prefix = find_attribute_values(ast, "prefix").into_iter().next(); let includes = find_attribute_values(ast, "include"); let excludes = find_attribute_values(ast, "exclude"); let metadata_only = find_bool_attribute(ast, "metadata_only").unwrap_or(false); let allow_missing = find_bool_attribute(ast, "allow_missing").unwrap_or(false); #[cfg(not(feature = "include-exclude"))] if !includes.is_empty() || !excludes.is_empty() { return Err(syn::Error::new_spanned( ast, "Please turn on the `include-exclude` feature to use the `include` and `exclude` attributes", )); } #[cfg(feature = "interpolate-folder-path")] let folder_path = shellexpand::full(&folder_path) .map_err(|v| syn::Error::new_spanned(ast, v.to_string()))? .to_string(); // Base relative paths on the Cargo.toml location let (relative_path, absolute_folder_path) = if Path::new(&folder_path).is_relative() { let absolute_path = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap()) .join(&folder_path) .to_str() .unwrap() .to_owned(); (Some(folder_path.clone()), absolute_path) } else { if cfg!(feature = "compression") { return Err(syn::Error::new_spanned(ast, "`folder` must be a relative path under `compression` feature.")); } (None, folder_path) }; if !Path::new(&absolute_folder_path).exists() && !allow_missing { let mut message = format!( "#[derive(RustEmbed)] folder '{}' does not exist. cwd: '{}'", absolute_folder_path, std::env::current_dir().unwrap().to_str().unwrap() ); // Add a message about the interpolate-folder-path feature if the path may // include a variable if absolute_folder_path.contains('$') && cfg!(not(feature = "interpolate-folder-path")) { message += "\nA variable has been detected. RustEmbed can expand variables \ when the `interpolate-folder-path` feature is enabled."; } return Err(syn::Error::new_spanned(ast, message)); }; generate_assets( &ast.ident, relative_path.as_deref(), absolute_folder_path, prefix, includes, excludes, metadata_only, &crate_path, ) } #[proc_macro_derive(RustEmbed, attributes(folder, prefix, include, exclude, allow_missing, metadata_only, crate_path))] pub fn derive_input_object(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); match impl_rust_embed(&ast) { Ok(ok) => ok.into(), Err(e) => e.to_compile_error().into(), } }