1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*
* Copyright (C) 2021  Aravinth Manivannan <realaravinth@batsense.net>
*
* 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;

use serde::{Deserialize, Serialize};

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(),
            base_dir: base_dir.into(),
        }
    }

    /// 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()..])
        } else {
            None
        }
    }

    /// 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")
        } 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)]
mod tests {
    use crate::processor::tests::cleanup;
    use crate::processor::*;

    use super::*;
    use std::path::Path;

    #[test]
    fn get_full_path_works() {
        let types = vec![
            mime::IMAGE_PNG,
            mime::IMAGE_SVG,
            mime::IMAGE_JPEG,
            mime::IMAGE_GIF,
        ];

        let config = BusterBuilder::default()
            .source("./dist")
            .result("/tmp/prod2")
            .mime_types(types)
            .copy(true)
            .follow_links(true)
            .build()
            .unwrap();

        let files = config.process().unwrap();

        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",
            &files
        ));

        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",
            &files
        ));
        cleanup(&config);
    }

    fn get_full_path_runner(path: &str, files: &Files) -> bool {
        if let Some(file) = files.get_full_path(path) {
            Path::new(file).exists()
        } else {
            false
        }
    }

    #[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![
            mime::IMAGE_PNG,
            mime::IMAGE_SVG,
            mime::IMAGE_JPEG,
            mime::IMAGE_GIF,
        ];

        let config = BusterBuilder::default()
            .source("./dist")
            .result("/tmp/prod5")
            .mime_types(types)
            .copy(true)
            .follow_links(true)
            .build()
            .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));

        assert!(!get_runner("dist/log-out.svg", &files));
        assert!(!get_runner("dist/a/b/c/d/s/d/svg/credit-card.svg", &files));
        cleanup(&config);
    }

    fn get_runner(path: &str, files: &Files) -> bool {
        if let Some(file) = files.get(path) {
            let path = Path::new(&files.base_dir).join(&file[1..]);
            path.exists()
        } else {
            false
        }
    }
}