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
use std::path;

use liquid;

use super::files;
use super::slug;
use super::FrontmatterBuilder;
use error::*;

#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub enum SortOrder {
    None,
    Asc,
    Desc,
}

impl Default for SortOrder {
    fn default() -> SortOrder {
        SortOrder::Desc
    }
}

#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct CollectionBuilder {
    pub title: Option<String>,
    pub slug: Option<String>,
    pub description: Option<String>,
    pub source: Option<path::PathBuf>,
    pub dir: Option<String>,
    pub drafts_dir: Option<String>,
    pub include_drafts: bool,
    pub template_extensions: Vec<String>,
    pub ignore: Vec<String>,
    pub order: SortOrder,
    pub rss: Option<String>,
    pub jsonfeed: Option<String>,
    pub base_url: Option<String>,
    pub default: FrontmatterBuilder,
}

impl CollectionBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn merge_frontmatter(mut self, secondary: FrontmatterBuilder) -> Self {
        self.default = self.default.merge(secondary);
        self
    }

    pub fn build(self) -> Result<Collection> {
        let CollectionBuilder {
            title,
            slug,
            description,
            source,
            dir,
            drafts_dir,
            include_drafts,
            template_extensions,
            ignore,
            order,
            rss,
            jsonfeed,
            base_url,
            default,
        } = self;

        let title = title.ok_or("Collection is missing a `title`")?;
        let slug = slug.unwrap_or_else(|| slug::slugify(&title));

        let source = source.ok_or_else(|| "No asset source provided")?;

        let dir = dir.unwrap_or_else(|| slug.clone());
        let pages = Self::build_files(&source, &dir, &template_extensions, &ignore)?;

        let drafts_dir = if include_drafts { drafts_dir } else { None };
        let drafts = drafts_dir
            .map(|dir| Self::build_files(&source, &dir, &template_extensions, &ignore))
            .map_or(Ok(None), |r| r.map(Some))?;

        let mut attributes: liquid::value::Object = vec![
            ("title".into(), liquid::value::Value::scalar(&title)),
            ("slug".into(), liquid::value::Value::scalar(&slug)),
            (
                "description".into(),
                liquid::value::Value::scalar(description.clone().unwrap_or_else(|| "".to_owned())),
            ),
        ].into_iter()
        .collect();
        if let Some(ref rss) = rss {
            attributes.insert("rss".into(), liquid::value::Value::scalar(rss));
        }
        if let Some(ref jsonfeed) = jsonfeed {
            attributes.insert("jsonfeed".into(), liquid::value::Value::scalar(jsonfeed));
        }

        let default = default.set_collection(slug.clone());

        let new = Collection {
            title,
            slug,
            description,
            pages,
            drafts,
            include_drafts,
            order,
            rss,
            jsonfeed,
            base_url,
            default,
            attributes,
        };
        Ok(new)
    }

    fn build_files(
        source: &path::Path,
        dir: &str,
        template_extensions: &[String],
        ignore: &[String],
    ) -> Result<files::Files> {
        if dir.starts_with('/') {
            bail!("Collection dir {} must be a relative path", dir)
        }
        let dir = files::cleanup_path(dir);
        let mut pages = files::FilesBuilder::new(source)?;
        if !dir.is_empty() {
            // In-case `dir` starts with `_`
            pages
                .add_ignore(&format!("!/{}", dir))?
                .add_ignore(&format!("!/{}/**", dir))?
                .add_ignore(&format!("/{}/**/_*", dir))?
                .add_ignore(&format!("/{}/**/_*/**", dir))?;
            pages.limit(path::PathBuf::from(dir))?;
        }
        for line in ignore {
            pages.add_ignore(line.as_str())?;
        }
        for ext in template_extensions {
            pages.add_extension(ext)?;
        }
        pages.build()
    }
}

#[derive(Clone, Debug)]
pub struct Collection {
    pub title: String,
    pub slug: String,
    pub description: Option<String>,
    pub pages: files::Files,
    pub drafts: Option<files::Files>,
    pub include_drafts: bool,
    pub order: SortOrder,
    pub rss: Option<String>,
    pub jsonfeed: Option<String>,
    pub base_url: Option<String>,
    pub default: FrontmatterBuilder,
    pub attributes: liquid::value::Object,
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_build_dir_rel() {
        let mut collection = CollectionBuilder::default();
        collection.source = Some(path::PathBuf::from("/"));
        collection.title = Some("title".to_owned());
        collection.dir = Some("rel".to_owned());
        let collection = collection.build().unwrap();
        assert_eq!(collection.pages.subtree(), path::Path::new("/rel"));
    }

    #[test]
    fn test_build_dir_abs() {
        let mut collection = CollectionBuilder::default();
        collection.source = Some(path::PathBuf::from("/"));
        collection.title = Some("title".to_owned());
        collection.dir = Some("/root".to_owned());
        let collection = collection.build();
        assert!(collection.is_err());
    }

    #[test]
    fn test_build_drafts_rel() {
        let mut collection = CollectionBuilder::default();
        collection.source = Some(path::PathBuf::from("/"));
        collection.title = Some("title".to_owned());
        collection.drafts_dir = Some("rel".to_owned());
        collection.include_drafts = true;
        let collection = collection.build().unwrap();
        assert_eq!(
            collection.drafts.unwrap().subtree(),
            path::Path::new("/rel")
        );
    }

    #[test]
    fn test_build_drafts_abs() {
        let mut collection = CollectionBuilder::default();
        collection.source = Some(path::PathBuf::from("/"));
        collection.title = Some("title".to_owned());
        collection.drafts_dir = Some("/root".to_owned());
        collection.include_drafts = true;
        let collection = collection.build();
        assert!(collection.is_err());
    }
}