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
use anyhow::Result;
use hyper::{
    body::{self, Buf},
    http::HeaderValue,
    Client, Request, Uri,
};
use hyper_tls::HttpsConnector;
use rayon::iter::{ParallelBridge, ParallelIterator};
use std::{
    collections::HashMap,
    fs,
    io::{self, ErrorKind, Read},
    path::Path,
    process::Command,
};
use time::{format_description, Date};

pub fn run_command(program: &str, args: &[&str]) -> Result<String, io::Error> {
    let out = Command::new(program).args(args).output()?;
    match out.status.success() {
        true => Ok(String::from_utf8(out.stdout).unwrap().trim().to_string()),
        false => Err(io::Error::new(
            ErrorKind::Other,
            format!("run command `{program} {}` failed.", args.join(" ")),
        )),
    }
}

pub fn capitalize(text: &str) -> String {
    let mut chars = text.chars();
    match chars.next() {
        None => String::new(),
        Some(f) => f.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
    }
}

pub fn format_date(date: &Date) -> String {
    let format = format_description::parse("[year]-[month]-[day]").expect("Shouldn't happen");
    date.format(&format).expect("Serialize date error")
}

/// Split styles into string pair.
///
/// ```rust
/// use genkit::helpers::split_styles;
///
/// let pair = split_styles("color: #abcdef; font-size: 14px; background-image: url('/test.png');");
/// assert_eq!(pair.get("color").unwrap(), &"#abcdef");
/// assert_eq!(pair.get("font-size").unwrap(), &"14px");
/// assert_eq!(pair.get("background-image").unwrap(), &"url('/test.png')");
/// assert_eq!(pair.get("width"), None);
///
/// let pair = split_styles("invalid");
/// assert!(pair.is_empty());
/// ```
pub fn split_styles(style: &str) -> HashMap<&str, &str> {
    style
        .split(';')
        .filter_map(|pair| {
            let mut v = pair.split(':').take(2);
            match (v.next(), v.next()) {
                (Some(key), Some(value)) => Some((key.trim(), value.trim())),
                _ => None,
            }
        })
        .collect::<HashMap<_, _>>()
}

pub async fn fetch_url(url: &str) -> Result<impl Read> {
    let client = Client::builder().build::<_, hyper::Body>(HttpsConnector::new());
    let mut req = Request::new(Default::default());
    *req.uri_mut() = url.parse::<Uri>()?;
    req.headers_mut().insert(
        "User-Agent",
        HeaderValue::from_static(
            "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
        ),
    );
    let resp = client.request(req).await?;
    if resp.status().is_redirection() {
        if let Some(location) = resp.headers().get("Location") {
            println!(
                "Warning: url `{url}` has been redirected to `{}`",
                location.to_str()?,
            );
        } else {
            println!("Warning: url `{url}` has been redirected");
        }
    } else if !resp.status().is_success() {
        let warning = format!(
            "Warning: failed to fetch url `{url}`, status code: {status}",
            url = url,
            status = resp.status()
        );
        println!("{warning}");
        anyhow::bail!(warning);
    }
    let bytes = body::to_bytes(resp.into_body()).await?;
    Ok(bytes.reader())
}

/// Copy directory recursively.
/// Note: the empty directory is ignored.
pub fn copy_dir(source: &Path, dest: &Path) -> Result<()> {
    let source_parent = source.parent().expect("Can not copy the root dir");
    walkdir::WalkDir::new(source)
        .into_iter()
        .par_bridge()
        .try_for_each(|entry| {
            let entry = entry?;
            let path = entry.path();
            // `path` would be a file or directory. However, we are
            // in a rayon's parallel thread, there is no guarantee
            // that parent directory iterated before the file.
            // So we just ignore the `path.is_dir()` case, when coming
            // across the first file we'll create the parent directory.
            if path.is_file() {
                if let Some(parent) = path.parent() {
                    let dest_parent = dest.join(parent.strip_prefix(source_parent)?);
                    if !dest_parent.exists() {
                        // Create the same dir concurrently is ok according to the docs.
                        fs::create_dir_all(dest_parent)?;
                    }
                }
                let to = dest.join(path.strip_prefix(source_parent)?);
                fs::copy(path, to)?;
            }

            anyhow::Ok(())
        })?;
    Ok(())
}

/// A serde module to serialize and deserialize [`time::Date`] type.
pub mod serde_date {
    use super::*;
    use serde::{de, Serialize, Serializer};

    pub fn serialize<S: Serializer>(date: &Date, serializer: S) -> Result<S::Ok, S::Error> {
        super::format_date(date).serialize(serializer)
    }

    pub fn deserialize<'de, D>(d: D) -> Result<Date, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        d.deserialize_any(DateVisitor)
    }

    struct DateVisitor;

    impl<'de> de::Visitor<'de> for DateVisitor {
        type Value = Date;

        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
            formatter.write_str("The date format is YYYY-MM-DD")
        }

        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            let format =
                format_description::parse("[year]-[month]-[day]").expect("Shouldn't happen");
            Date::parse(v, &format)
                .map_err(|e| E::custom(format!("The date value {} is invalid: {}", v, e)))
        }
    }

    pub mod options {
        use super::*;

        struct OptionDateVisitor;

        pub fn serialize<S: Serializer>(
            date: &Option<Date>,
            serializer: S,
        ) -> Result<S::Ok, S::Error> {
            if let Some(date) = date {
                super::serialize(date, serializer)
            } else {
                None::<Date>.serialize(serializer)
            }
        }

        pub fn deserialize<'de, D>(d: D) -> Result<Option<Date>, D::Error>
        where
            D: de::Deserializer<'de>,
        {
            d.deserialize_option(OptionDateVisitor)
        }

        impl<'de> de::Visitor<'de> for OptionDateVisitor {
            type Value = Option<Date>;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a YYYY-MM-DD date or none")
            }

            fn visit_some<D>(self, d: D) -> Result<Self::Value, D::Error>
            where
                D: de::Deserializer<'de>,
            {
                d.deserialize_str(DateVisitor).map(Some)
            }

            fn visit_none<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(None)
            }
        }
    }
}