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
use crate::AppCtx;
pub struct Preview<'a> {
pub base: &'a str,
pub delimiter: &'static str,
pub prefix: &'static str,
}
impl<'a> Preview<'a> {
pub fn new(ctx: &'a AppCtx) -> Self {
Self {
base: &ctx.settings.page.base_domain,
delimiter: ".",
prefix: "deploy-preview-",
}
}
pub fn get_name(&self, preview_number: usize) -> String {
format!(
"{}{preview_number}{}{}",
self.prefix, self.delimiter, self.base
)
}
pub fn extract(&self, hostname: &'a str) -> Option<&'a str> {
if !hostname.contains(self.delimiter)
|| !hostname.contains(self.prefix)
|| !hostname.contains(self.base)
{
return None;
}
let d = format!("{}{}", self.delimiter, self.base);
if hostname.split(&d).count() == 2 {
return hostname.split(&d).next();
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn preview_extract_generate_works() {
const BASE_DOMAIN: &str = "librepages.site";
const PREVIEW_DELIMITER: &str = ".";
const PREVIEW_PREFIX: &str = "deploy-preview-";
const PREVIEW_NUMBER: usize = 1666;
let preview_hostname =
format!("{PREVIEW_PREFIX}{PREVIEW_NUMBER}{PREVIEW_DELIMITER}{BASE_DOMAIN}");
let bad_hostname = BASE_DOMAIN.to_string();
let extractor = Preview {
base: BASE_DOMAIN,
prefix: PREVIEW_PREFIX,
delimiter: PREVIEW_DELIMITER,
};
assert_eq!(extractor.get_name(PREVIEW_NUMBER), preview_hostname);
assert_eq!(extractor.extract(&bad_hostname), None);
assert_eq!(
extractor.extract(&format!(
"{PREVIEW_PREFIX}{PREVIEW_NUMBER}{PREVIEW_DELIMITER}no_base_domain"
)),
None
);
assert_eq!(
extractor.extract(&format!(
"{PREVIEW_PREFIX}{PREVIEW_NUMBER}no-delimiter{BASE_DOMAIN}"
)),
None
);
assert_eq!(
extractor.extract(&format!(
"{PREVIEW_PREFIX}{PREVIEW_NUMBER}no-delimiter{BASE_DOMAIN}"
)),
None
);
assert_eq!(
extractor.extract(&format!(
"noprefix{PREVIEW_NUMBER}{PREVIEW_DELIMITER}{BASE_DOMAIN}"
)),
None
);
assert_eq!(
extractor.extract(&preview_hostname),
Some(format!("{PREVIEW_PREFIX}{PREVIEW_NUMBER}").as_str())
);
}
}