Module cache_buster::filemap [−][src]
Structs
-Files |
diff --git a/cache_buster/filemap/index.html b/cache_buster/filemap/index.html index 35bc695..839a152 100644 --- a/cache_buster/filemap/index.html +++ b/cache_buster/filemap/index.html @@ -1,6 +1,16 @@
Files |
Module describing runtime compoenet for fetching modified filenames
+Add the following tou your program to load the filemap during compiletime:
+ ++use cache_buster::Files; + +fn main(){ + let files = Files::load(); +}
Files | Filemap struct + |
map: HashMap<String, String>
impl Files
[src]pub fn new(base_dir: &str) -> Self
[src]pub fn get<'a>(&'a self, path: &'a str) -> Option<&'a str>
[src]pub fn get_full_path<'a>(&'a self, path: &'a str) -> Option<&'a String>
[src]pub fn add(&mut self, k: String, v: String) -> Result<(), &'static str>
[src]pub fn to_env(&self)
[src]pub fn load() -> Self
[src]impl Clone for Files
[src]fn clone(&self) -> Files
[src]Returns a copy of the value. Read more
+}Filemap struct
+maps original names to generated names
+map: HashMap<String, String>
filemap<original-path, modified-path>
+impl Files
[src]pub fn new(base_dir: &str) -> Self
[src]Initialize map
+pub fn get<'a>(&'a self, path: &'a str) -> Option<&'a str>
[src]Get relative file path
+If the modified filename path is './prod/test.randomhash.svg, it will output
/test.randomhash.svg`. For full path, see [get_full_path]
pub fn get_full_path<'a>(&'a self, path: &'a str) -> Option<&'a String>
[src]Get file path
+If the modified filename path is './prod/test.randomhash.svg, it will output
/prod/test.randomhash.svg`. For relative path, see [get]
pub fn add(&mut self, k: String, v: String) -> Result<(), &'static str>
[src]Create file map: map original path to modified paths
+pub fn to_env(&self)
[src]This crate uses compile-time environment variables to transfer +data to the main program. This funtction sets that variable
+pub fn load() -> Self
[src]Load filemap in main program. Should be called from main program
+impl Clone for Files
[src]fn clone(&self) -> Files
[src]Returns a copy of the value. Read more
pub fn clone_from(&mut self, source: &Self)
1.0.0[src]Performs copy-assignment from source
. Read more
impl Debug for Files
[src]fn fmt(&self, f: &mut Formatter<'_>) -> Result
[src]Formats the value using the given formatter. Read more
-impl<'de> Deserialize<'de> for Files
[src]fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
__D: Deserializer<'de>,
[src]Deserialize this value from the given Serde deserializer. Read more
-impl PartialEq<Files> for Files
[src]fn eq(&self, other: &Files) -> bool
[src]This method tests for self
and other
values to be equal, and is used
+
impl Debug for Files
[src]fn fmt(&self, f: &mut Formatter<'_>) -> Result
[src]Formats the value using the given formatter. Read more
+impl<'de> Deserialize<'de> for Files
[src]fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
__D: Deserializer<'de>,
[src]Deserialize this value from the given Serde deserializer. Read more
+impl PartialEq<Files> for Files
[src]fn eq(&self, other: &Files) -> bool
[src]This method tests for self
and other
values to be equal, and is used
by ==
. Read more
fn ne(&self, other: &Files) -> bool
[src]This method tests for !=
.
impl Serialize for Files
[src]fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where
__S: Serializer,
[src]Serialize this value into the given Serde serializer. Read more
-impl StructuralPartialEq for Files
[src]impl RefUnwindSafe for Files
[src]impl Send for Files
[src]impl Sync for Files
[src]impl Unpin for Files
[src]impl UnwindSafe for Files
[src]impl<T> Any for T where
T: 'static + ?Sized,
[src]pub fn type_id(&self) -> TypeId
[src]Gets the TypeId
of self
. Read more
fn ne(&self, other: &Files) -> bool
[src]This method tests for !=
.
impl Serialize for Files
[src]fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error> where
__S: Serializer,
[src]Serialize this value into the given Serde serializer. Read more
+impl StructuralPartialEq for Files
[src]impl RefUnwindSafe for Files
[src]impl Send for Files
[src]impl Sync for Files
[src]impl Unpin for Files
[src]impl UnwindSafe for Files
[src]impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]pub fn borrow_mut(&mut self) -> &mut T
[src]Mutably borrows from an owned value. Read more
impl<T> DeserializeOwned for T where
T: for<'de> Deserialize<'de>,
[src]impl<T> From<T> for T
[src]pub fn from(t: T) -> T
[src]Performs the conversion.
diff --git a/cache_buster/index.html b/cache_buster/index.html index 70ac329..7da04a3 100644 --- a/cache_buster/index.html +++ b/cache_buster/index.html @@ -1,13 +1,13 @@use cache_buster::BusterBuilder; fn main() { // note: add error checking yourself. - // println!("cargo:rustc-env=GIT_HASH={}", git_hash); + // println!("cargo:rustc-env=GIT_process={}", git_process); let types = vec![ mime::IMAGE_PNG, mime::IMAGE_SVG, @@ -24,10 +24,11 @@ .build() .unwrap(); - config.init().unwrap(); - config.hash().unwrap(); + config.process().unwrap(); }
pub use processor::BusterBuilder; |
pub use filemap::Files; |
filemap | |
processor |
filemap | Module describing runtime compoenet for fetching modified filenames + |
processor | Module describing file processor that changes filenames to setup cache-busting + |
#[non_exhaustive]pub enum BusterBuilderError { UninitializedField(&'static str), ValidationError(String), }
Error type for BusterBuilder
@@ -9,14 +9,14 @@ Variants (Non-exhaustive)UninitializedField(&'static str)
Uninitialized field
ValidationError(String)
Custom validation error
-impl Debug for BusterBuilderError
[src]fn fmt(&self, f: &mut Formatter<'_>) -> Result
[src]Formats the value using the given formatter. Read more
-impl Display for BusterBuilderError
[src]fn fmt(&self, f: &mut Formatter<'_>) -> Result
[src]Formats the value using the given formatter. Read more
-impl Error for BusterBuilderError
[src]pub fn source(&self) -> Option<&(dyn Error + 'static)>
1.30.0[src]The lower-level source of this error, if any. Read more
+impl Debug for BusterBuilderError
[src]fn fmt(&self, f: &mut Formatter<'_>) -> Result
[src]Formats the value using the given formatter. Read more
+impl Display for BusterBuilderError
[src]fn fmt(&self, f: &mut Formatter<'_>) -> Result
[src]Formats the value using the given formatter. Read more
+impl Error for BusterBuilderError
[src]pub fn source(&self) -> Option<&(dyn Error + 'static)>
1.30.0[src]The lower-level source of this error, if any. Read more
pub fn backtrace(&self) -> Option<&Backtrace>
[src]backtrace
)Returns a stack backtrace, if available, of where this error occurred. Read more
pub fn description(&self) -> &str
1.0.0[src]use the Display impl or to_string()
pub fn cause(&self) -> Option<&dyn Error>
1.0.0[src]replaced by Error::source, which can support downcasting
-impl From<String> for BusterBuilderError
[src]impl From<UninitializedFieldError> for BusterBuilderError
[src]impl From<String> for BusterBuilderError
[src]impl From<UninitializedFieldError> for BusterBuilderError
[src]impl RefUnwindSafe for BusterBuilderError
[src]impl Send for BusterBuilderError
[src]impl Sync for BusterBuilderError
[src]impl Unpin for BusterBuilderError
[src]impl UnwindSafe for BusterBuilderError
[src]impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]pub fn borrow_mut(&mut self) -> &mut T
[src]Mutably borrows from an owned value. Read more
diff --git a/cache_buster/processor/index.html b/cache_buster/processor/index.html index c652deb..5a475d5 100644 --- a/cache_buster/processor/index.html +++ b/cache_buster/processor/index.html @@ -1,8 +1,38 @@Buster | |||||||
BusterBuilder | Builder for Module cache_buster:: |
Buster | Configuration for setting up cache-busting + |
BusterBuilder | Builder for |
BusterBuilderError | Error type for BusterBuilder |
pub struct Buster { /* fields omitted */ }
impl Buster
[src]pub fn init(&self) -> Result<(), Error>
[src]pub fn try_hash(&self) -> Result<Files, Error>
[src]pub fn hash(&self) -> Result<Files, Error>
[src]impl Clone for Buster
[src]fn clone(&self) -> Buster
[src]Returns a copy of the value. Read more
+pub struct Buster { /* fields omitted */ }
Configuration for setting up cache-busting
+impl Buster
[src]pub fn try_process(&self) -> Result<Files, Error>
[src]Processes files.
+If MIME types are uncommon, then use this funtion +as it won't panic when a weird MIM is encountered.
+Otherwise, use [process]
+Note: it omits processing uncommon MIME types
+pub fn process(&self) -> Result<Files, Error>
[src]Processes files.
+If MIME types are common, then use this funtion +as it will panic when a weird MIM is encountered.
+impl Clone for Buster
[src]fn clone(&self) -> Buster
[src]Returns a copy of the value. Read more
pub fn clone_from(&mut self, source: &Self)
1.0.0[src]Performs copy-assignment from source
. Read more
impl Debug for Buster
[src]fn fmt(&self, f: &mut Formatter<'_>) -> Result
[src]Formats the value using the given formatter. Read more
+impl Debug for Buster
[src]impl RefUnwindSafe for Buster
[src]impl Send for Buster
[src]impl Sync for Buster
[src]impl Unpin for Buster
[src]impl UnwindSafe for Buster
[src]impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]pub fn borrow_mut(&mut self) -> &mut T
[src]Mutably borrows from an owned value. Read more
diff --git a/cache_buster/processor/struct.BusterBuilder.html b/cache_buster/processor/struct.BusterBuilder.html index 7ed3d30..0530c1d 100644 --- a/cache_buster/processor/struct.BusterBuilder.html +++ b/cache_buster/processor/struct.BusterBuilder.html @@ -1,13 +1,18 @@pub struct BusterBuilder { /* fields omitted */ }
Builder for Buster
.
impl BusterBuilder
[src]pub fn source<VALUE: Into<String>>(&mut self, value: VALUE) -> &mut Self
[src]pub fn mime_types(&mut self, value: Vec<Mime>) -> &mut Self
[src]pub fn result<VALUE: Into<String>>(&mut self, value: VALUE) -> &mut Self
[src]pub fn copy(&mut self, value: bool) -> &mut Self
[src]pub fn follow_links(&mut self, value: bool) -> &mut Self
[src]pub fn build(&self) -> Result<Buster, BusterBuilderError>
[src]pub struct BusterBuilder { /* fields omitted */ }
Builder for Buster
.
impl BusterBuilder
[src]pub fn source<VALUE: Into<String>>(&mut self, value: VALUE) -> &mut Self
[src]source directory
+pub fn mime_types(&mut self, value: Vec<Mime>) -> &mut Self
[src]mime_types for hashing
+pub fn result<VALUE: Into<String>>(&mut self, value: VALUE) -> &mut Self
[src]directory for writing results
+pub fn copy(&mut self, value: bool) -> &mut Self
[src]copy other non-hashed files from source dire to result dir?
+pub fn follow_links(&mut self, value: bool) -> &mut Self
[src]follow symlinks?
+pub fn build(&self) -> Result<Buster, BusterBuilderError>
[src]impl Clone for BusterBuilder
[src]fn clone(&self) -> BusterBuilder
[src]Returns a copy of the value. Read more
+impl Clone for BusterBuilder
[src]fn clone(&self) -> BusterBuilder
[src]Returns a copy of the value. Read more
pub fn clone_from(&mut self, source: &Self)
1.0.0[src]Performs copy-assignment from source
. Read more
impl Default for BusterBuilder
[src]impl Default for BusterBuilder
[src]impl RefUnwindSafe for BusterBuilder
[src]impl Send for BusterBuilder
[src]impl Sync for BusterBuilder
[src]impl Unpin for BusterBuilder
[src]impl UnwindSafe for BusterBuilder
[src]impl<T> Any for T where
T: 'static + ?Sized,
[src]impl<T> Borrow<T> for T where
T: ?Sized,
[src]impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]pub fn borrow_mut(&mut self) -> &mut T
[src]Mutably borrows from an owned value. Read more
diff --git a/cache_buster/sidebar-items.js b/cache_buster/sidebar-items.js index 548e037..a660ba1 100644 --- a/cache_buster/sidebar-items.js +++ b/cache_buster/sidebar-items.js @@ -1 +1 @@ -initSidebarItems({"mod":[["filemap",""],["processor",""]]}); \ No newline at end of file +initSidebarItems({"mod":[["filemap","Module describing runtime compoenet for fetching modified filenames"],["processor","Module describing file processor that changes filenames to setup cache-busting"]]}); \ No newline at end of file diff --git a/search-index.js b/search-index.js index 1de2120..0dc6c28 100644 --- a/search-index.js +++ b/search-index.js @@ -1,5 +1,5 @@ var searchIndex = JSON.parse('{\ "actix_example":{"doc":"","i":[[5,"main","actix_example","",null,[[]]],[5,"get_full_path_runner","","",null,[[["files",3],["str",15]],["bool",15]]]],"p":[]},\ -"cache_buster":{"doc":"","i":[[0,"processor","cache_buster","",null,null],[3,"Buster","cache_buster::processor","",null,null],[3,"BusterBuilder","","Builder forBuster
.",null,null],[11,"source","","",0,[[["string",3],["into",8]]]],[11,"mime_types","","",0,[[["mime",3],["vec",3]]]],[11,"result","","",0,[[["string",3],["into",8]]]],[11,"copy","","",0,[[["bool",15]]]],[11,"follow_links","","",0,[[["bool",15]]]],[11,"build","","Builds a new Buster
.",0,[[],[["busterbuildererror",4],["buster",3],["result",4]]]],[4,"BusterBuilderError","","Error type for BusterBuilder",null,null],[13,"UninitializedField","","Uninitialized field",1,null],[13,"ValidationError","","Custom validation error",1,null],[11,"init","","",2,[[],[["result",4],["error",3]]]],[11,"try_hash","","",2,[[],[["error",3],["result",4],["files",3]]]],[11,"hash","","",2,[[],[["error",3],["result",4],["files",3]]]],[0,"filemap","cache_buster","",null,null],[3,"Files","cache_buster::filemap","",null,null],[12,"map","","",3,null],[11,"new","","",3,[[["str",15]]]],[11,"get","","",3,[[["str",15]],[["option",4],["str",15]]]],[11,"get_full_path","","",3,[[["str",15]],[["string",3],["option",4]]]],[11,"add","","",3,[[["string",3]],[["result",4],["str",15]]]],[11,"to_env","","",3,[[]]],[11,"load","","",3,[[]]],[11,"from","cache_buster::processor","",2,[[]]],[11,"into","","",2,[[]]],[11,"to_owned","","",2,[[]]],[11,"clone_into","","",2,[[]]],[11,"borrow","","",2,[[]]],[11,"borrow_mut","","",2,[[]]],[11,"try_from","","",2,[[],["result",4]]],[11,"try_into","","",2,[[],["result",4]]],[11,"type_id","","",2,[[],["typeid",3]]],[11,"from","","",0,[[]]],[11,"into","","",0,[[]]],[11,"to_owned","","",0,[[]]],[11,"clone_into","","",0,[[]]],[11,"borrow","","",0,[[]]],[11,"borrow_mut","","",0,[[]]],[11,"try_from","","",0,[[],["result",4]]],[11,"try_into","","",0,[[],["result",4]]],[11,"type_id","","",0,[[],["typeid",3]]],[11,"from","","",1,[[]]],[11,"into","","",1,[[]]],[11,"to_string","","",1,[[],["string",3]]],[11,"borrow","","",1,[[]]],[11,"borrow_mut","","",1,[[]]],[11,"try_from","","",1,[[],["result",4]]],[11,"try_into","","",1,[[],["result",4]]],[11,"type_id","","",1,[[],["typeid",3]]],[11,"from","cache_buster::filemap","",3,[[]]],[11,"into","","",3,[[]]],[11,"to_owned","","",3,[[]]],[11,"clone_into","","",3,[[]]],[11,"borrow","","",3,[[]]],[11,"borrow_mut","","",3,[[]]],[11,"try_from","","",3,[[],["result",4]]],[11,"try_into","","",3,[[],["result",4]]],[11,"type_id","","",3,[[],["typeid",3]]],[11,"from","cache_buster::processor","",1,[[["uninitializedfielderror",3]]]],[11,"from","","",1,[[["string",3]]]],[11,"clone","","",2,[[],["buster",3]]],[11,"clone","","",0,[[],["busterbuilder",3]]],[11,"clone","cache_buster::filemap","",3,[[],["files",3]]],[11,"default","cache_buster::processor","",0,[[]]],[11,"eq","cache_buster::filemap","",3,[[["files",3]],["bool",15]]],[11,"ne","","",3,[[["files",3]],["bool",15]]],[11,"fmt","cache_buster::processor","",2,[[["formatter",3]],["result",6]]],[11,"fmt","","",1,[[["formatter",3]],["result",6]]],[11,"fmt","cache_buster::filemap","",3,[[["formatter",3]],["result",6]]],[11,"fmt","cache_buster::processor","",1,[[["formatter",3]],["result",6]]],[11,"serialize","cache_buster::filemap","",3,[[],["result",4]]],[11,"deserialize","","",3,[[],["result",4]]]],"p":[[3,"BusterBuilder"],[4,"BusterBuilderError"],[3,"Buster"],[3,"Files"]]}\
+"cache_buster":{"doc":"","i":[[0,"processor","cache_buster","Module describing file processor that changes filenames …",null,null],[3,"Buster","cache_buster::processor","Configuration for setting up cache-busting",null,null],[3,"BusterBuilder","","Builder for Buster
.",null,null],[11,"source","","source directory",0,[[["string",3],["into",8]]]],[11,"mime_types","","mime_types for hashing",0,[[["vec",3],["mime",3]]]],[11,"result","","directory for writing results",0,[[["string",3],["into",8]]]],[11,"copy","","copy other non-hashed files from source dire to result …",0,[[["bool",15]]]],[11,"follow_links","","follow symlinks?",0,[[["bool",15]]]],[11,"build","","Builds a new Buster
.",0,[[],[["busterbuildererror",4],["result",4],["buster",3]]]],[4,"BusterBuilderError","","Error type for BusterBuilder",null,null],[13,"UninitializedField","","Uninitialized field",1,null],[13,"ValidationError","","Custom validation error",1,null],[11,"try_process","","Processes files.",2,[[],[["result",4],["files",3],["error",3]]]],[11,"process","","Processes files.",2,[[],[["result",4],["files",3],["error",3]]]],[0,"filemap","cache_buster","Module describing runtime compoenet for fetching modified …",null,null],[3,"Files","cache_buster::filemap","Filemap struct",null,null],[12,"map","","filemap/* * Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net> @@ -198,6 +223,17 @@ * Use of this source code is governed by the Apache 2.0 and/or the MIT * License. */ +//! Module describing runtime compoenet for fetching modified filenames +//! +//! Add the following tou your program to load the filemap during compiletime: +//! +//! ```no_run +//! use cache_buster::Files; +//! +//! fn main(){ +//! let files = Files::load(); +//! } +//! ``` use std::collections::HashMap; use std::env; @@ -206,13 +242,18 @@ const ENV_VAR_NAME: &str = "CACHE_BUSTER_FILE_MAP"; +/// Filemap struct +/// +/// maps original names to generated names #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] pub struct Files { + /// filemap<original-path, modified-path> pub map: HashMap<String, String>, base_dir: String, } impl Files { + /// Initialize map pub fn new(base_dir: &str) -> Self { Files { map: HashMap::default(), @@ -220,6 +261,10 @@ } } + /// Get relative file path + /// + /// If the modified filename path is './prod/test.randomhash.svg`, it will + /// output `/test.randomhash.svg`. For full path, see [get_full_path] pub fn get<'a>(&'a self, path: &'a str) -> Option<&'a str> { if let Some(path) = self.map.get(path) { Some(&path[self.base_dir.len()..]) @@ -228,10 +273,15 @@ } } + /// Get file path + /// + /// If the modified filename path is './prod/test.randomhash.svg`, it will + /// output `/prod/test.randomhash.svg`. For relative path, see [get] pub fn get_full_path<'a>(&'a self, path: &'a str) -> Option<&'a String> { self.map.get(path) } + /// Create file map: map original path to modified paths pub fn add(&mut self, k: String, v: String) -> Result<(), &'static str> { if self.map.contains_key(&k) { Err("key exists") @@ -241,6 +291,8 @@ } } + /// This crate uses compile-time environment variables to transfer + /// data to the main program. This funtction sets that variable pub fn to_env(&self) { println!( "cargo:rustc-env={}={}", @@ -255,6 +307,7 @@ env::set_var(ENV_VAR_NAME, serde_json::to_string(&self).unwrap()); } + /// Load filemap in main program. Should be called from main program pub fn load() -> Self { let env = env::var(ENV_VAR_NAME) .expect("unable to read env var, might be a bug in lib. Please report on GitHub"); @@ -289,8 +342,7 @@ .build() .unwrap(); - config.init().unwrap(); - let files = config.hash().unwrap(); + let files = config.process().unwrap(); assert!(get_full_path_runner("./dist/log-out.svg", &files)); assert!(get_full_path_runner( @@ -332,8 +384,7 @@ .build() .unwrap(); - config.init().unwrap(); - let files = config.hash().unwrap(); + let files = config.process().unwrap(); files.to_env(); @@ -362,8 +413,7 @@ .build() .unwrap(); - config.init().unwrap(); - let files = config.hash().unwrap(); + let files = config.process().unwrap(); assert!(get_runner("./dist/log-out.svg", &files)); assert!(get_runner("./dist/a/b/c/d/s/d/svg/credit-card.svg", &files)); diff --git a/src/cache_buster/lib.rs.html b/src/cache_buster/lib.rs.html index e5e4af8..ccf22a6 100644 --- a/src/cache_buster/lib.rs.html +++ b/src/cache_buster/lib.rs.html @@ -38,7 +38,6 @@ 35 36 37 -38
/* * Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net> @@ -46,13 +45,13 @@ * Use of this source code is governed by the Apache 2.0 and/or the MIT * License. */ - -//! ```rust +#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] +//! ```no_run //! use cache_buster::BusterBuilder; //! //! fn main() { //! // note: add error checking yourself. -//! // println!("cargo:rustc-env=GIT_HASH={}", git_hash); +//! // println!("cargo:rustc-env=GIT_process={}", git_process); //! let types = vec![ //! mime::IMAGE_PNG, //! mime::IMAGE_SVG, @@ -69,8 +68,7 @@ //! .build() //! .unwrap(); //! -//! config.init().unwrap(); -//! config.hash().unwrap(); +//! config.process().unwrap(); //! } //! ``` diff --git a/src/cache_buster/processor.rs.html b/src/cache_buster/processor.rs.html index 7ad4726..620b1d8 100644 --- a/src/cache_buster/processor.rs.html +++ b/src/cache_buster/processor.rs.html @@ -250,6 +250,55 @@ 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
/* * Copyright (C) 2021 Aravinth Manivannan <realaravinth@batsense.net> @@ -258,6 +307,39 @@ * License. */ +//! Module describing file processor that changes filenames to setup cache-busting +//! +//! Run the following during build using `build.rs`: +//! +//! ```rust +//! use cache_buster::BusterBuilder; +//! +//! fn main() { +//! // note: add error checking yourself. +//! // println!("cargo:rustc-env=GIT_process={}", git_process); +//! let types = vec![ +//! mime::IMAGE_PNG, +//! mime::IMAGE_SVG, +//! mime::IMAGE_JPEG, +//! mime::IMAGE_GIF, +//! ]; +//! +//! let config = BusterBuilder::default() +//! .source("./dist") +//! .result("./prod") +//! .mime_types(types) +//! .copy(true) +//! .follow_links(true) +//! .build() +//! .unwrap(); +//! +//! config.process().unwrap(); +//! } +//! ``` +//! +//! There's a runtime component to this library which will let you read modified +//! filenames from within your program. See [Files] + use std::io::Error; use std::path::Path; use std::{fs, path::PathBuf}; @@ -267,23 +349,26 @@ use crate::Files; +/// Configuration for setting up cache-busting #[derive(Debug, Clone, Builder)] pub struct Buster { - // source directory + /// source directory #[builder(setter(into))] source: String, - // mime_types for hashing + /// mime_types for hashing mime_types: Vec<mime::Mime>, - // directory for writing results + /// directory for writing results #[builder(setter(into))] result: String, - // copy other non-hashed files from source dire to result dir? + /// copy other non-hashed files from source dire to result dir? copy: bool, + /// follow symlinks? follow_links: bool, } impl Buster { - pub fn init(&self) -> Result<(), Error> { + // creates base_dir to output files to + fn init(&self) -> Result<(), Error> { let res = Path::new(&self.result); if res.exists() { fs::remove_dir_all(&self.result).unwrap(); @@ -302,11 +387,16 @@ HEXUPPER.encode(&hasher.finalize()) } - // if mime types are common, then you shoud be fine using this - // use [hash] when when they aren't - // - // doesn't process files for which mime is not resolved - pub fn try_hash(&self) -> Result<Files, Error> { + /// Processes files. + /// + /// If MIME types are uncommon, then use this funtion + /// as it won't panic when a weird MIM is encountered. + /// + /// Otherwise, use [process] + /// + /// Note: it omits processing uncommon MIME types + pub fn try_process(&self) -> Result<Files, Error> { + self.init()?; let mut file_map: Files = Files::new(&self.result); for entry in WalkDir::new(&self.source) .follow_links(self.follow_links) @@ -342,9 +432,15 @@ Ok(file_map) } - // panics when mimetypes are detected. This way you'll know which files are ignored - // from processing - pub fn hash(&self) -> Result<Files, Error> { + /// Processes files. + /// + /// If MIME types are common, then use this funtion + /// as it will panic when a weird MIM is encountered. + pub fn process(&self) -> Result<Files, Error> { + // panics when mimetypes are detected. This way you'll know which files are ignored + // from processing + + self.init()?; let mut file_map: Files = Files::new(&self.result); for entry in WalkDir::new(&self.source) @@ -384,6 +480,7 @@ Ok(file_map) } + // helper fn to read file to string fn read_to_string(path: &Path) -> Result<Vec<u8>, Error> { use std::fs::File; use std::io::Read; @@ -394,18 +491,21 @@ Ok(file_content) } + // helper fn to generate filemap fn gen_map<'a>(&self, source: &'a Path, name: &str) -> (&'a Path, PathBuf) { let rel_location = source.strip_prefix(&self.source).unwrap().parent().unwrap(); let destination = Path::new(&self.result).join(rel_location).join(name); (source, destination) } + // helper fn to copy files fn copy(&self, source: &Path, name: &str) { let rel_location = source.strip_prefix(&self.source).unwrap().parent().unwrap(); let destination = Path::new(&self.result).join(rel_location).join(name); fs::copy(source, &destination).unwrap(); } + // helper fn to create directory structure in self.base_dir fn create_dir_structure(&self, path: &Path) -> Result<(), Error> { for entry in WalkDir::new(&path) .follow_links(self.follow_links) @@ -446,15 +546,14 @@ let config = BusterBuilder::default() .source("./dist") - .result("./prod") + .result("./prod56") .mime_types(types) .copy(true) .follow_links(true) .build() .unwrap(); - config.init().unwrap(); - let mut files = config.hash().unwrap(); + let mut files = config.process().unwrap(); for (k, v) in files.map.drain() { let src = Path::new(&k); @@ -466,7 +565,7 @@ } #[test] - fn try_hash_works() { + fn try_process_works() { let types = vec![ mime::IMAGE_PNG, mime::IMAGE_SVG, @@ -483,8 +582,7 @@ .build() .unwrap(); - config.init().unwrap(); - let mut files = config.try_hash().unwrap(); + let mut files = config.try_process().unwrap(); for (k, v) in files.map.drain() { let src = Path::new(&k);