ddoc 0.18.0

doc site generator
Documentation
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use {
    crate::*,
    lazy_regex::regex_captures,
    rustc_hash::FxHashMap,
    std::{
        borrow::Cow,
        fs,
        io::Write,
        path::{
            Path,
            PathBuf,
        },
    },
    termimad::crossterm::style::Stylize,
};

/// A ddoc project, with its configuration, pages, and
/// location which allows building it.
pub struct Project {
    pub root: PathBuf,
    pub src_path: PathBuf,
    pub build_path: PathBuf,
    pub config: Config,
    modules: Vec<Module>,
    pub pages: FxHashMap<PagePath, Page>,
}

impl Project {
    /// Given the path to a ddoc project root,
    /// load its configuration and pages into a `Project` struct.
    pub fn load(path: &Path) -> DdResult<Self> {
        let mut project = Self {
            root: path.to_owned(),
            config: Default::default(),
            modules: Default::default(),
            pages: Default::default(),
            src_path: path.join("src"),
            build_path: path.join("site"),
        };
        project.load_content()?;
        Ok(project)
    }

    /// List the files and directories that should be watched for changes to
    /// trigger a partial or total rebuild of the project.
    pub fn watch_targets(&self) -> Vec<WatchTarget> {
        let mut targets = Vec::new();
        for module in &self.modules {
            module.add_watch_targets(&mut targets);
        }
        targets
    }

    pub fn plugin_names(&self) -> impl Iterator<Item = &str> {
        self.modules
            .iter()
            .map(|m| m.name.as_str())
            .filter(|name| !name.is_empty())
    }

    /// Load or reload everything, keeping only the root path
    fn load_content(&mut self) -> DdResult<()> {
        // clean
        self.modules = Vec::new();
        self.pages.clear();

        // load all modules, including the main
        let main_module = Module::load("", &self.root)?;
        let mut config = main_module
            .config
            .clone()
            .ok_or(DdError::ConfigNotFound)?
            .take_entity();
        let active_plugins = config.active_plugins.clone();
        self.modules.push(main_module);
        for name in &active_plugins {
            let plugin_root = self.root.join("plugins").join(name);
            if !plugin_root.exists() {
                eprintln!(
                    "{}: plugin '{}' not found at expected path {:?}",
                    "error".red().bold(),
                    name.to_string().red(),
                    plugin_root,
                );
                if plugin_is_known(name) {
                    eprintln!(
                        " Plugin '{}' is known, but not found in the project.\n You can initialize it with {}?",
                        name.to_string().yellow(),
                        format!("ddoc --init-plugin {}", name).green().bold(),
                    );
                }
                continue;
            }
            let plugin_module = Module::load(name, &plugin_root)?;
            if let Some(plugin_config) = &plugin_module.config {
                config.merge(plugin_config.as_ref());
            }
            // TODO merge plugin config into main config
            self.modules.push(plugin_module);
        }

        // fix and apply config
        compat::fix_old_config(&mut config);
        config.site_map.add_pages(self);

        // store it
        self.config = config;
        Ok(())
    }

    /// Fills the 'site' directory with the generated HTML files and static files
    ///
    /// Don't do any prealable cleaning, call `clean_build_dir` first if needed.
    pub fn build(&self) -> DdResult<()> {
        for module in &self.modules {
            module.copy_all_statics_into(&self.build_path)?;
        }
        before_0_16::write_special_js_files_if_needed(&self.config, self)?;
        for page_path in self.pages.keys() {
            self.build_page(page_path)?;
        }
        Ok(())
    }
    pub fn add_js_to_build(
        &self,
        filename: &str,
        bytes: &[u8],
    ) -> DdResult<()> {
        let js_path = self.build_path.join("js").join(filename);
        if !js_path.exists() {
            if let Some(parent) = js_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::write(&js_path, bytes)?;
        }
        Ok(())
    }
    /// Try to update the project. Return true when some real work was done.
    ///
    /// #Errors
    /// Doesn't return error on user/data problems. A missing file, or
    /// an invalid config file will only trigger printed messages, not errors.
    pub fn update(
        &mut self,
        change: FileChange,
        base_url: &str, // for informing the user on the link to look at
    ) -> DdResult<bool> {
        eprintln!("Received change: {:?}", change);
        match change {
            FileChange::Other => {
                self.reload_and_rebuild(base_url)?;
                return Ok(true);
            }
            FileChange::Removal(touched_path) => {
                // we care only if it's a CSS or JS file (header may have changed)
                if let Ok(rel_path) = touched_path.strip_prefix(&self.src_path) {
                    if rel_path.starts_with("css/") || rel_path.starts_with("js/") {
                        self.reload_and_rebuild(base_url)?;
                        return Ok(true);
                    }
                }
            }
            FileChange::Write(touched_path) => {
                // partial update for /src/img/ files and /src/*.md files
                if let Ok(rel_path) = touched_path.strip_prefix(&self.src_path) {
                    let ext = rel_path.extension().and_then(|s| s.to_str());
                    if ext == Some("md") {
                        for (page_path, page) in &self.pages {
                            if page.md_file_path == touched_path {
                                info!("Modified page {:?}", page_path);
                                let url = page_path.to_absolute_url(base_url);
                                eprintln!("Modified {}", url.yellow());
                                self.build_page(page_path)?;
                                return Ok(true);
                            }
                        }
                        return Ok(false); // might be a readme, etc.
                    }
                    if let Ok(rel_img) = rel_path.strip_prefix("img/") {
                        info!("Deployed image {rel_img:?}");
                        eprintln!("Deployed image {}", rel_img.to_string_lossy().yellow());
                        let dst_path = self.build_path.join("img").join(rel_img);
                        if let Some(parent) = dst_path.parent() {
                            fs::create_dir_all(parent)?;
                        }
                        fs::copy(&touched_path, &dst_path)?;
                        return Ok(true);
                    }
                }
                // If the change is related to the config file, a JS or CSS file,
                // then we have to do a full rebuild (all headers may have changed).
                // For JS & CSS we could do it only if the file is new or renamed,
                //  but for now we do a full rebuild).
                self.reload_and_rebuild(base_url)?;
                return Ok(true);
            }
        }
        Ok(false)
    }
    fn reload_and_rebuild(
        &mut self,
        base_url: &str, // for informing the user on the link to look at
    ) -> DdResult<()> {
        info!("full rebuild");
        eprintln!("Full rebuild of {}", base_url.yellow());
        match self.load_content() {
            Ok(()) => {
                self.build()?;
            }
            Err(DdError::ConfigNotFound) => eprintln!(
                "{}: could not read updated config file at {:?}, keeping the old one.",
                "warning".yellow().bold(),
                self.root.join(CONFIG_FILE_NAME),
            ),
            Err(e) => eprintln!(
                "{}: failed to reload the project: {e}",
                "error".red().bold()
            ),
        }
        Ok(())
    }
    /// remove the 'build' directory and its content
    pub fn clean_build_dir(&self) -> DdResult<()> {
        if self.build_path.exists() {
            fs::remove_dir_all(&self.build_path)?;
        }
        Ok(())
    }
    pub fn load_and_build(path: &Path) -> DdResult<()> {
        let project = Self::load(path)?;
        project.build()?;
        Ok(())
    }
    /// If the provided path corresponds to a page in the project,
    /// return its `PagePath`, else return `None`.
    pub fn page_path_of(
        &self,
        path: &Path,
    ) -> Option<&PagePath> {
        for (page_path, page) in &self.pages {
            if page.md_file_path == path {
                return Some(page_path);
            }
        }
        None
    }
    pub fn list_js(&self) -> DdResult<Vec<StaticEntry>> {
        let mut entries = Vec::new();
        for module in &self.modules {
            module.list_js(&mut entries)?;
        }
        Ok(entries)
    }
    pub fn list_css(&self) -> DdResult<Vec<StaticEntry>> {
        let mut entries = Vec::new();
        for module in &self.modules {
            module.list_css(&mut entries)?;
        }
        Ok(entries)
    }

    pub fn copy_static(
        &self,
        dir: &str,
    ) -> DdResult<()> {
        let static_src = self.src_path.join(dir);
        if !static_src.exists() {
            return Ok(());
        }
        let static_dst = self.build_path.join(dir);
        copy_normal_recursive(&static_src, &static_dst)?;
        Ok(())
    }
    pub fn build_page(
        &self,
        page_path: &PagePath,
    ) -> DdResult<()> {
        let page = self
            .pages
            .get(page_path)
            .ok_or_else(|| DdError::internal(format!("Page not found: {:?}", page_path)))?;
        let mut html = String::new();
        page.write_html(&mut html, self)?;
        let html_path = page_path.html_path_buf(&self.build_path);
        if let Some(parent) = html_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        if html_path.exists() {
            fs::remove_file(&html_path)?;
        }
        let mut file = fs::File::create(&html_path)?;
        file.write_all(html.as_bytes())?;
        Ok(())
    }
    pub fn check_img_path(
        &self,
        mut img_path: &str, // a relative path like "img/xyz.png",
        page_path: &PagePath,
    ) {
        // We tolerate leading ../ in img paths, as long as they don't go
        // beyond the project src root.
        // They're useless, but may seem natural to some users.
        for _ in 0..page_path.depth() {
            if img_path.starts_with("../") {
                img_path = &img_path[3..];
            }
        }
        let path = self.build_path.join(img_path);
        if !path.exists() {
            eprintln!(
                "{}: {} contains a broken img src: {}",
                "error".red().bold(),
                page_path.to_string().yellow(),
                img_path.to_string().red(),
            );
        }
    }
    pub fn img_url(
        &self,
        src: &str,
        page_path: &PagePath,
    ) -> String {
        let mut src = src;
        // conf var expansions
        let conf_var_value;
        if let Some(var_name) = src.strip_prefix("--") {
            if let Some(var_value) = self.config.var(var_name) {
                conf_var_value = var_value;
                src = &conf_var_value;
            }
        }
        // filtering to change only relative links to /img files
        if let Some((_, before, path)) = regex_captures!(r"^(\.\./)*(img/.*)$", &src) {
            self.check_img_path(src, page_path);
            let depth = page_path.depth();
            if depth == 0 && before.is_empty() {
                return src.to_string(); // no rewriting needed, it's already correct
            }
            let mut url = String::new();
            for _ in 0..depth {
                url.push_str("../");
            }
            url.push_str(path);
            return url;
        }
        src.to_string()
    }
    pub fn load_file(
        &self,
        path: &str,
    ) -> DdResult<Option<String>> {
        let file_path = self.build_path.join(path);
        if !file_path.exists() {
            return Ok(None);
        }
        let content = fs::read_to_string(file_path)?;
        Ok(Some(content))
    }
    /// Check if the given `PagePath` exists in the project,
    /// write an error if it does not.
    pub fn check_page_path(
        &self,
        page_path: &PagePath,
    ) {
        if !self.pages.contains_key(page_path) {
            eprintln!("Error: link to non-existing page: {:?}", page_path);
        }
    }

    pub fn previous_page(
        &self,
        current_page: &PagePath,
    ) -> Option<&Page> {
        self.config
            .site_map
            .previous(current_page)
            .and_then(|p| self.pages.get(p))
    }
    pub fn next_page(
        &self,
        current_page: &PagePath,
    ) -> Option<&Page> {
        self.config
            .site_map
            .next(current_page)
            .and_then(|p| self.pages.get(p))
    }

    /// Return the modified link URL.
    /// return `None` when no expansion is possible, which should
    /// lead to the container being skipped.
    pub fn rewrite_link_url(
        &self,
        src: &str,
        page_path: &PagePath,
    ) -> Option<String> {
        if let Some(var_name) = src.strip_prefix("--") {
            // conf var expansions, they have priority as they may overload
            // dynamic expansions
            if let Some(var_value) = self.config.var(var_name) {
                return Some(var_value);
            }
            // dynamic expansions
            if var_name == "previous" {
                return self
                    .config
                    .site_map
                    .previous(page_path)
                    .map(|dst_page_path| page_path.link_to(dst_page_path));
            }
            if var_name == "next" {
                return self
                    .config
                    .site_map
                    .next(page_path)
                    .map(|dst_page_path| page_path.link_to(dst_page_path));
            }
            if let Some(value) = before_0_16::expand_special_var(var_name, &self.config) {
                return Some(value);
            }
            return None; // this way the container might be skipped
        }
        // FIXME rewrite absolute internal links coming from var expansions,
        // which may be in the form /path/to/page or /path/to/page.md
        // (this my require refactor to always return a string)

        // rewrite absolute internal links, making them relative to the current page
        if let Some((_, path, file, _ext, hash)) =
            regex_captures!(r"^/([\w\-/]+/)*([\w\-/]*?)(?:index)?(\.md)?/?(#.*)?$", &src,)
        {
            let depth = page_path.depth();
            let mut url = String::new();
            for _ in 0..depth {
                url.push_str("../");
            }
            url.push_str(path);
            url.push_str(file);
            url.push_str(hash);
            let dst_page_path = PagePath::from_path_file(path, file);
            if !self.pages.contains_key(&dst_page_path) {
                eprintln!("path: {}, file: {}", path, file);
                eprintln!("dst_page_path: {:?}", dst_page_path);
                eprintln!(
                    "{}: {} contains a broken link: {}",
                    "error".red(),
                    page_path.to_string().yellow(),
                    src.to_string().red(),
                );
            }
            return Some(url);
        }
        // rewrite relative internal links to .md files
        if let Some((_, path, file, _ext, hash)) =
            regex_captures!(r"^(\.\./|[\w\-/]+/)*([\w\-/]+?)(\.md)?/?(#.*)?$", &src,)
        {
            let dst_page_path = page_path.follow_relative_link(path, file);
            if !self.pages.contains_key(&dst_page_path) {
                eprintln!(
                    "{}: {} contains a broken relative link: {}",
                    "error".red().bold(),
                    page_path.to_string().yellow(),
                    src.to_string().red(),
                );
            }
            let file = if file == "index" { "" } else { file };
            let url = format!("{}{}{}", path, file, hash,);
            return Some(url);
        }
        None
    }
    /// Return a modified link URL if it needs to be rewritten.
    ///
    /// If the src is an expansion and cannot be resolved,
    /// return the src unchanged.
    pub fn link_url<'s>(
        &self,
        src: &'s str,
        page_path: &PagePath,
    ) -> Cow<'s, str> {
        match self.rewrite_link_url(src, page_path) {
            Some(new_url) => Cow::Owned(new_url),
            None => Cow::Borrowed(src),
        }
    }
    pub fn static_url(
        &self,
        filename: &str,
        page_path: &PagePath,
    ) -> String {
        let depth = page_path.depth();
        let mut url = String::new();
        for _ in 0..depth {
            url.push_str("../");
        }
        url.push_str(filename);
        url
    }
}