ergonomics and changed some public methods to private

This commit is contained in:
Aravinth Manivannan 2021-04-11 22:53:16 +05:30
parent 71d5ef67a2
commit 09fbbe186c
Signed by: realaravinth
GPG key ID: AD9F0F08E855ED88
8 changed files with 98 additions and 86 deletions

View file

@ -1,5 +1,14 @@
## 0.1.1
### Changed:
- `Files::load()` became `Files::new()`
### Removed:
- Some methods on `Files` were for internal use only but they had a
public API, they were modified to private.
## 0.1.0
## Added:
### Added:
- `SHA-256`-based cache-buster
- runtime filemap loading

2
Cargo.lock generated
View file

@ -21,7 +21,7 @@ dependencies = [
[[package]]
name = "cache-buster"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"data-encoding",
"derive_builder",

View file

@ -1,6 +1,6 @@
[package]
name = "cache-buster"
version = "0.1.0"
version = "0.1.1"
authors = ["realaravinth <realaravinth@batsense.net>"]
edition = "2018"
license = "MIT OR Apache-2.0"

View file

@ -17,5 +17,5 @@ fn main() {
.build()
.unwrap();
config.process().unwrap().to_env();
config.process().unwrap();
}

View file

@ -1,7 +1,7 @@
use cache_buster::Files;
fn main() {
let files = Files::load();
let files = Files::new();
assert!(get_full_path_runner("../dist/log-out.svg", &files));
assert!(get_full_path_runner(

View file

@ -12,7 +12,7 @@
//! use cache_buster::Files;
//!
//! fn main(){
//! let files = Files::load();
//! let files = Files::new();
//! }
//! ```
@ -29,17 +29,17 @@ const ENV_VAR_NAME: &str = "CACHE_BUSTER_FILE_MAP";
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Files {
/// filemap<original-path, modified-path>
pub map: HashMap<String, String>,
map: HashMap<String, String>,
base_dir: String,
}
impl Files {
/// Initialize map
pub fn new(base_dir: &str) -> Self {
Files {
map: HashMap::default(),
base_dir: base_dir.into(),
}
/// Load filemap in main program. Should be called from main program
pub fn new() -> Self {
let env = env::var(ENV_VAR_NAME)
.expect("unable to read env var, might be a bug in lib. Please report on GitHub");
let res: Files = serde_json::from_str(&env).unwrap();
res
}
/// Get relative file path
@ -61,40 +61,6 @@ impl Files {
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")
} else {
self.map.insert(k, v);
Ok(())
}
}
/// 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={}={}",
ENV_VAR_NAME,
serde_json::to_string(&self).unwrap()
);
// needed for testing load()
// if the above statement fails(println), then something's broken
// with the rust compiler. So not really worried about that.
#[cfg(test)]
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");
let res: Files = serde_json::from_str(&env).unwrap();
res
}
}
#[cfg(test)]
@ -123,8 +89,9 @@ mod tests {
.build()
.unwrap();
let files = config.process().unwrap();
config.process().unwrap();
let files = Files::new();
assert!(get_full_path_runner("./dist/log-out.svg", &files));
assert!(get_full_path_runner(
"./dist/a/b/c/d/s/d/svg/credit-card.svg",
@ -147,35 +114,6 @@ mod tests {
}
}
#[test]
fn load_works() {
let types = vec![
mime::IMAGE_PNG,
mime::IMAGE_SVG,
mime::IMAGE_JPEG,
mime::IMAGE_GIF,
];
let config = BusterBuilder::default()
.source("./dist")
.result("/tmp/prod3")
.mime_types(types)
.copy(true)
.follow_links(true)
.build()
.unwrap();
let files = config.process().unwrap();
files.to_env();
let x = Files::load();
assert_eq!(files, x);
cleanup(&config);
}
#[test]
fn get_works() {
let types = vec![
@ -194,7 +132,9 @@ mod tests {
.build()
.unwrap();
let files = config.process().unwrap();
config.process().unwrap();
let files = Files::new();
assert!(get_runner("./dist/log-out.svg", &files));
assert!(get_runner("./dist/a/b/c/d/s/d/svg/credit-card.svg", &files));

View file

@ -35,3 +35,6 @@ pub mod processor;
pub use processor::BusterBuilder;
pub mod filemap;
pub use filemap::Files;
/// env var to which filemap is written during compilation
pub const ENV_VAR_NAME: &str = "CACHE_BUSTER_FILE_MAP";

View file

@ -38,14 +38,16 @@
//! There's a runtime component to this library which will let you read modified
//! filenames from within your program. See [Files]
use std::collections::HashMap;
use std::io::Error;
use std::path::Path;
use std::{fs, path::PathBuf};
use derive_builder::Builder;
use serde::{Deserialize, Serialize};
use walkdir::WalkDir;
use crate::Files;
use crate::ENV_VAR_NAME;
/// Configuration for setting up cache-busting
#[derive(Debug, Clone, Builder)]
@ -93,7 +95,7 @@ impl Buster {
/// Otherwise, use [process][Self::process]
///
/// Note: it omits processing uncommon MIME types
pub fn try_process(&self) -> Result<Files, Error> {
pub fn try_process(&self) -> Result<(), Error> {
self.init()?;
let mut file_map: Files = Files::new(&self.result);
for entry in WalkDir::new(&self.source)
@ -126,15 +128,15 @@ impl Buster {
}
}
}
Ok(file_map)
file_map.to_env();
Ok(())
}
/// 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> {
pub fn process(&self) -> Result<(), Error> {
// panics when mimetypes are detected. This way you'll know which files are ignored
// from processing
@ -175,7 +177,8 @@ impl Buster {
}
}
Ok(file_map)
file_map.to_env();
Ok(())
}
// helper fn to read file to string
@ -229,6 +232,61 @@ impl Buster {
}
}
/// Filemap struct
///
/// maps original names to generated names
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
struct Files {
/// filemap<original-path, modified-path>
pub map: HashMap<String, String>,
base_dir: String,
}
impl Files {
/// Initialize map
fn new(base_dir: &str) -> Self {
Files {
map: HashMap::default(),
base_dir: base_dir.into(),
}
}
/// Create file map: map original path to modified paths
fn add(&mut self, k: String, v: String) -> Result<(), &'static str> {
if self.map.contains_key(&k) {
Err("key exists")
} else {
self.map.insert(k, v);
Ok(())
}
}
/// This crate uses compile-time environment variables to transfer
/// data to the main program. This funtction sets that variable
fn to_env(&self) {
println!(
"cargo:rustc-env={}={}",
ENV_VAR_NAME,
serde_json::to_string(&self).unwrap()
);
// needed for testing load()
// if the above statement fails(println), then something's broken
// with the rust compiler. So not really worried about that.
#[cfg(test)]
std::env::set_var(ENV_VAR_NAME, serde_json::to_string(&self).unwrap());
}
#[cfg(test)]
/// Load filemap in main program. Should be called from main program
fn load() -> Self {
let env = std::env::var(ENV_VAR_NAME)
.expect("unable to read env var, might be a bug in lib. Please report on GitHub");
let res: Files = serde_json::from_str(&env).unwrap();
res
}
}
#[cfg(test)]
pub mod tests {
use super::*;
@ -251,7 +309,8 @@ pub mod tests {
.build()
.unwrap();
let mut files = config.process().unwrap();
config.process().unwrap();
let mut files = Files::load();
for (k, v) in files.map.drain() {
let src = Path::new(&k);
@ -280,7 +339,8 @@ pub mod tests {
.build()
.unwrap();
let mut files = config.try_process().unwrap();
config.process().unwrap();
let mut files = Files::load();
for (k, v) in files.map.drain() {
let src = Path::new(&k);