bim 0.1.0

A content-first static site generator for blogs, digital gardens, and knowledge bases
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
use crate::collections::Collection;
use crate::config::Config;
use crate::content::{Backlink, Page, Site};
use crate::date::{extract_date, strip_date_prefix};
use crate::directives::process_directives;
use crate::git::GitRepo;
use crate::lang::detect_language;
use crate::links::{extract_contexts, extract_internal_links, extract_tags};
use crate::nav::load_nav;
use crate::snippets::process_snippet;
use anyhow::Result;
use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

const IGNORED_DIRS: &[&str] = &[
    "layouts",
    "static",
    "images",
    "dist",
    "node_modules",
    "target",
];

pub fn discover_site(config: &Config) -> Result<Site> {
    let mut site = Site::new();
    let git_repo = GitRepo::open(&config.source_dir);

    // Load navigation
    let (nav_items, nav_html) = load_nav(&config.source_dir);
    site.nav_items = nav_items;
    site.nav_html = nav_html;

    // Discover all content files
    let content_files = discover_content_files(&config.source_dir, config.include_drafts)?;

    // Process markdown files
    for path in &content_files.markdown_files {
        match process_markdown_file(path, &config.source_dir, git_repo.as_ref()) {
            Ok(page) => {
                if !page.is_draft || config.include_drafts {
                    site.pages.push(page);
                }
            }
            Err(e) => {
                tracing::warn!("Failed to process {:?}: {}", path, e);
            }
        }
    }

    // Process snippet files
    for path in &content_files.snippet_files {
        match process_snippet(path, git_repo.as_ref()) {
            Ok(snippet) => {
                site.snippets.push(snippet);
            }
            Err(e) => {
                tracing::warn!("Failed to process snippet {:?}: {}", path, e);
            }
        }
    }

    // Generate auto-indexes for notes directories
    generate_auto_indexes(&mut site, &config.source_dir)?;

    // Generate tag and context pages
    generate_tag_pages(&mut site, &config.source_dir, git_repo.as_ref())?;
    generate_context_pages(&mut site, &config.source_dir, git_repo.as_ref())?;

    // Process directives in all pages
    let site_clone = site.clone();
    for page in &mut site.pages {
        page.html_content = process_directives(&page.html_content, &site_clone);
    }

    // Compute backlinks
    compute_backlinks(&mut site);

    Ok(site)
}

struct ContentFiles {
    markdown_files: Vec<PathBuf>,
    snippet_files: Vec<PathBuf>,
}

fn discover_content_files(source_dir: &Path, include_drafts: bool) -> Result<ContentFiles> {
    let mut markdown_files = Vec::new();
    let mut snippet_files = Vec::new();

    for entry in WalkDir::new(source_dir)
        .follow_links(true)
        .into_iter()
        .filter_entry(|e| !is_ignored(e.path(), source_dir))
    {
        let entry = entry?;
        let path = entry.path();

        if !path.is_file() {
            continue;
        }

        // Skip drafts if not included
        if !include_drafts && is_draft(path) {
            continue;
        }

        let relative = path.strip_prefix(source_dir).unwrap_or(path);
        let first_component = relative
            .components()
            .next()
            .and_then(|c| c.as_os_str().to_str())
            .unwrap_or("");

        if first_component == "snippets" {
            // Snippet files (code files, not markdown)
            if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
                if ext != "md" {
                    snippet_files.push(path.to_path_buf());
                }
            }
        } else if path.extension().and_then(|e| e.to_str()) == Some("md") {
            // Skip nav.md as it's not content
            if path.file_name().and_then(|f| f.to_str()) != Some("nav.md") {
                markdown_files.push(path.to_path_buf());
            }
        }
    }

    Ok(ContentFiles {
        markdown_files,
        snippet_files,
    })
}

fn is_ignored(path: &Path, source_dir: &Path) -> bool {
    let relative = path.strip_prefix(source_dir).unwrap_or(path);

    for component in relative.components() {
        if let Some(name) = component.as_os_str().to_str() {
            // Ignore dot-prefixed files/directories
            if name.starts_with('.') {
                return true;
            }
            // Ignore specific directories
            if IGNORED_DIRS.contains(&name) {
                return true;
            }
        }
    }

    false
}

fn is_draft(path: &Path) -> bool {
    // Check if filename starts with underscore
    if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
        if filename.starts_with('_') {
            return true;
        }
    }

    // Check if any parent directory is _drafts
    for component in path.components() {
        if let Some(name) = component.as_os_str().to_str() {
            if name == "_drafts" {
                return true;
            }
        }
    }

    false
}

fn process_markdown_file(
    path: &Path,
    source_dir: &Path,
    git_repo: Option<&GitRepo>,
) -> Result<Page> {
    let content = std::fs::read_to_string(path)?;
    let relative = path.strip_prefix(source_dir).unwrap_or(path);
    let relative_str = relative.to_string_lossy();

    let collection = Collection::from_path(&relative_str);
    let mut page = Page::new(path.to_path_buf(), collection);

    // Store raw content
    page.raw_content = content.clone();

    // Extract title from first H1
    page.title = extract_title(&content).unwrap_or_else(|| {
        path.file_stem()
            .and_then(|s| s.to_str())
            .map(|s| strip_date_prefix(s).replace(['-', '_'], " "))
            .unwrap_or_else(|| "Untitled".to_string())
    });

    // Extract date
    page.date = extract_date(path, git_repo);

    // Check if draft
    page.is_draft = is_draft(path);

    // Detect language
    let (lang, dir) = detect_language(&content);
    page.lang = lang;
    page.dir = dir;

    // Extract links, tags, contexts
    page.links = extract_internal_links(&content);
    page.tags = extract_tags(&content);
    page.contexts = extract_contexts(&content);

    // Generate URL
    page.url = generate_url(path, source_dir, collection);
    page.is_index = is_index_file(path);

    // Convert markdown to HTML
    page.html_content = markdown_to_html(&content);

    Ok(page)
}

fn extract_title(content: &str) -> Option<String> {
    let parser = Parser::new(content);
    let mut in_h1 = false;
    let mut title = String::new();

    for event in parser {
        match event {
            Event::Start(Tag::Heading {
                level: HeadingLevel::H1,
                ..
            }) => {
                in_h1 = true;
            }
            Event::End(TagEnd::Heading(HeadingLevel::H1)) => {
                if !title.is_empty() {
                    return Some(title);
                }
                in_h1 = false;
            }
            Event::Text(text) if in_h1 => {
                title.push_str(&text);
            }
            Event::Code(code) if in_h1 => {
                title.push_str(&code);
            }
            _ => {}
        }
    }

    None
}

fn generate_url(path: &Path, source_dir: &Path, collection: Collection) -> String {
    let relative = path.strip_prefix(source_dir).unwrap_or(path);

    // Handle index.md at root
    if relative.to_string_lossy() == "index.md" {
        return "/".to_string();
    }

    let mut components: Vec<&str> = relative
        .components()
        .filter_map(|c| c.as_os_str().to_str())
        .collect();

    // Remove file extension and process filename
    if let Some(last) = components.last_mut() {
        let filename = *last;
        if let Some(stem) = filename.strip_suffix(".md") {
            let clean_stem = strip_date_prefix(stem);

            if clean_stem == "index" {
                // Remove index from path
                components.pop();
            } else {
                *last = clean_stem;
            }
        }
    }

    // For flat collections, only keep collection name + slug
    if !collection.is_hierarchical() && components.len() > 1 {
        let collection_name = components[0];
        let slug = slug::slugify(components.last().unwrap_or(&""));
        return format!("/{}/{}/", collection_name, slug);
    }

    // Build URL
    let path_str = components.join("/");
    if path_str.is_empty() {
        "/".to_string()
    } else {
        format!("/{}/", path_str)
    }
}

fn is_index_file(path: &Path) -> bool {
    path.file_name()
        .and_then(|f| f.to_str())
        .map(|f| f == "index.md")
        .unwrap_or(false)
}

pub fn markdown_to_html(content: &str) -> String {
    use pulldown_cmark::{html, Options};

    // Transform tags and contexts to links before parsing
    let content = crate::links::transform_tags_to_links(content);
    let content = crate::links::transform_contexts_to_links(&content);

    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_FOOTNOTES);
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_HEADING_ATTRIBUTES);

    let parser = Parser::new_ext(&content, options);
    let mut html_output = String::new();
    html::push_html(&mut html_output, parser);

    html_output
}

fn generate_auto_indexes(site: &mut Site, source_dir: &Path) -> Result<()> {
    let notes_dir = source_dir.join("notes");
    if !notes_dir.exists() {
        return Ok(());
    }

    // Find all directories in notes that don't have index.md
    let mut dirs_needing_index: HashSet<PathBuf> = HashSet::new();

    for entry in WalkDir::new(&notes_dir)
        .follow_links(true)
        .into_iter()
        .filter_entry(|e| !is_ignored(e.path(), source_dir))
    {
        let entry = entry?;
        if entry.path().is_dir() && entry.path() != notes_dir {
            let index_path = entry.path().join("index.md");
            if !index_path.exists() {
                dirs_needing_index.insert(entry.path().to_path_buf());
            }
        }
    }

    // Collect all notes directories (including those with index.md)
    let mut all_dirs: HashSet<PathBuf> = HashSet::new();
    for entry in WalkDir::new(&notes_dir)
        .follow_links(true)
        .into_iter()
        .filter_entry(|e| !is_ignored(e.path(), source_dir))
    {
        let entry = entry?;
        if entry.path().is_dir() && entry.path() != notes_dir {
            all_dirs.insert(entry.path().to_path_buf());
        }
    }

    // Generate auto-index pages
    for dir in dirs_needing_index {
        let relative = dir.strip_prefix(source_dir).unwrap_or(&dir);
        let url = format!("/{}/", relative.to_string_lossy());

        let title = dir
            .file_name()
            .and_then(|f| f.to_str())
            .unwrap_or("Index")
            .replace(['-', '_'], " ");

        // Group pages by subdirectory
        let mut subdir_pages: HashMap<String, Vec<(&str, &str)>> = HashMap::new();
        let mut root_pages: Vec<(&str, &str)> = Vec::new();

        for page in &site.pages {
            if page.url.starts_with(&url) && page.url != url {
                let suffix = &page.url[url.len()..];
                let trimmed = suffix.trim_matches('/');
                if let Some(slash_pos) = trimmed.find('/') {
                    // Page is in a subdirectory
                    let subdir_name = &trimmed[..slash_pos];
                    subdir_pages
                        .entry(subdir_name.to_string())
                        .or_default()
                        .push((&page.title, &page.url));
                } else {
                    // Direct child page
                    root_pages.push((&page.title, &page.url));
                }
            }
        }

        // Find child directories (for linking even if they have no pages yet)
        let mut child_dir_names: HashSet<String> = HashSet::new();
        for child_dir in &all_dirs {
            if let Some(parent) = child_dir.parent() {
                if parent == dir {
                    if let Some(name) = child_dir.file_name().and_then(|f| f.to_str()) {
                        child_dir_names.insert(name.to_string());
                    }
                }
            }
        }

        let mut html = format!("<h1>{}</h1>\n", html_escape::encode_text(&title));

        // List each subdirectory as a section with its pages
        let mut all_subdirs: Vec<_> = child_dir_names.into_iter().collect();
        all_subdirs.sort();

        for subdir_name in all_subdirs {
            let display_name = subdir_name.replace(['-', '_'], " ");
            let subdir_url = format!("{}{}/", url, subdir_name);

            html.push_str(&format!(
                "<h2><a href=\"{}\">{}/</a></h2>\n",
                html_escape::encode_double_quoted_attribute(&subdir_url),
                html_escape::encode_text(&display_name)
            ));

            if let Some(pages) = subdir_pages.get(&subdir_name) {
                let mut sorted: Vec<_> = pages.iter().collect();
                sorted.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()));

                html.push_str("<ul class=\"collection-list\">\n");
                for (page_title, page_url) in sorted {
                    html.push_str(&format!(
                        "  <li><a href=\"{}\">{}</a></li>\n",
                        html_escape::encode_double_quoted_attribute(page_url),
                        html_escape::encode_text(page_title)
                    ));
                }
                html.push_str("</ul>\n");
            }
        }

        // List root-level pages
        if !root_pages.is_empty() {
            html.push_str("<h2>Pages</h2>\n");
            root_pages.sort_by(|a, b| a.0.to_lowercase().cmp(&b.0.to_lowercase()));

            html.push_str("<ul class=\"collection-list\">\n");
            for (page_title, page_url) in root_pages {
                html.push_str(&format!(
                    "  <li><a href=\"{}\">{}</a></li>\n",
                    html_escape::encode_double_quoted_attribute(page_url),
                    html_escape::encode_text(page_title)
                ));
            }
            html.push_str("</ul>");
        }

        let mut page = Page::new(dir.clone(), Collection::Notes);
        page.url = url;
        page.title = title;
        page.html_content = html;
        page.is_index = true;
        page.is_auto_index = true;

        site.pages.push(page);
    }

    Ok(())
}

fn generate_tag_pages(
    site: &mut Site,
    source_dir: &Path,
    git_repo: Option<&GitRepo>,
) -> Result<()> {
    // Collect all tags
    let mut all_tags: HashMap<String, Vec<usize>> = HashMap::new();

    for (idx, page) in site.pages.iter().enumerate() {
        for tag in &page.tags {
            all_tags.entry(tag.slug.clone()).or_default().push(idx);
        }
    }

    // Generate tag pages
    for (slug, page_indices) in all_tags {
        let url = format!("/tags/{}/", slug);

        // Check if there's a custom tag page
        let tag_md_path = source_dir.join("tags").join(format!("{}.md", slug));
        let custom_content = if tag_md_path.exists() {
            std::fs::read_to_string(&tag_md_path).ok()
        } else {
            None
        };

        let title = slug.replace('-', " ");

        let mut html = if let Some(content) = custom_content {
            markdown_to_html(&content)
        } else {
            format!("<h1>#{}</h1>\n", html_escape::encode_text(&title))
        };

        // Add listing of tagged pages
        html.push_str("<ul class=\"tag-list\">\n");
        for idx in page_indices {
            let page = &site.pages[idx];
            html.push_str(&format!(
                "  <li><a href=\"{}\">{}</a></li>\n",
                html_escape::encode_double_quoted_attribute(&page.url),
                html_escape::encode_text(&page.title)
            ));
        }
        html.push_str("</ul>");

        let mut page = Page::new(tag_md_path.clone(), Collection::Tags);
        page.url = url;
        page.title = format!("#{}", title);
        page.html_content = html;
        page.date = extract_date(&tag_md_path, git_repo);

        site.pages.push(page);
    }

    Ok(())
}

fn generate_context_pages(
    site: &mut Site,
    source_dir: &Path,
    git_repo: Option<&GitRepo>,
) -> Result<()> {
    // Collect all contexts
    let mut all_contexts: HashMap<String, Vec<usize>> = HashMap::new();

    for (idx, page) in site.pages.iter().enumerate() {
        for ctx in &page.contexts {
            all_contexts.entry(ctx.slug.clone()).or_default().push(idx);
        }
    }

    // Generate context pages
    for (slug, page_indices) in all_contexts {
        let url = format!("/contexts/{}/", slug);

        // Check if there's a custom context page
        let ctx_md_path = source_dir.join("contexts").join(format!("{}.md", slug));
        let custom_content = if ctx_md_path.exists() {
            std::fs::read_to_string(&ctx_md_path).ok()
        } else {
            None
        };

        let title = slug.replace('-', " ");

        let mut html = if let Some(content) = custom_content {
            markdown_to_html(&content)
        } else {
            format!("<h1>@{}</h1>\n", html_escape::encode_text(&title))
        };

        // Add listing of context pages
        html.push_str("<ul class=\"context-list\">\n");
        for idx in page_indices {
            let page = &site.pages[idx];
            html.push_str(&format!(
                "  <li><a href=\"{}\">{}</a></li>\n",
                html_escape::encode_double_quoted_attribute(&page.url),
                html_escape::encode_text(&page.title)
            ));
        }
        html.push_str("</ul>");

        let mut page = Page::new(ctx_md_path.clone(), Collection::Contexts);
        page.url = url;
        page.title = format!("@{}", title);
        page.html_content = html;
        page.date = extract_date(&ctx_md_path, git_repo);

        site.pages.push(page);
    }

    Ok(())
}

fn compute_backlinks(site: &mut Site) {
    // Build a map of URL -> page index
    let url_to_idx: HashMap<&str, usize> = site
        .pages
        .iter()
        .enumerate()
        .map(|(idx, page)| (page.url.as_str(), idx))
        .collect();

    // Also map snippet URLs
    let snippet_url_to_idx: HashMap<&str, usize> = site
        .snippets
        .iter()
        .enumerate()
        .map(|(idx, snippet)| (snippet.url.as_str(), idx))
        .collect();

    // Collect backlinks
    let mut page_backlinks: HashMap<usize, Vec<Backlink>> = HashMap::new();
    let mut snippet_backlinks: HashMap<usize, Vec<Backlink>> = HashMap::new();

    for (source_idx, page) in site.pages.iter().enumerate() {
        // Skip slides for backlink computation
        if page.collection == Collection::Slides {
            continue;
        }

        for link in &page.links {
            let target_url = normalize_url(&link.url);

            // Check if target is a page
            if let Some(&target_idx) = url_to_idx.get(target_url.as_str()) {
                if target_idx != source_idx {
                    let target_page = &site.pages[target_idx];
                    if target_page.collection.supports_backlinks() {
                        page_backlinks
                            .entry(target_idx)
                            .or_default()
                            .push(Backlink {
                                url: page.url.clone(),
                                title: page.title.clone(),
                            });
                    }
                }
            }

            // Check if target is a snippet
            if let Some(&target_idx) = snippet_url_to_idx.get(target_url.as_str()) {
                snippet_backlinks
                    .entry(target_idx)
                    .or_default()
                    .push(Backlink {
                        url: page.url.clone(),
                        title: page.title.clone(),
                    });
            }
        }
    }

    // Apply backlinks to pages
    for (idx, backlinks) in page_backlinks {
        site.pages[idx].backlinks = backlinks;
    }

    // Apply backlinks to snippets
    for (idx, backlinks) in snippet_backlinks {
        site.snippets[idx].backlinks = backlinks;
    }
}

fn normalize_url(url: &str) -> String {
    let url = url.trim();

    // Remove anchor
    let url = url.split('#').next().unwrap_or(url);

    // Ensure trailing slash
    if url.ends_with('/') {
        url.to_string()
    } else if url.contains('.') {
        // Likely a file, keep as is
        url.to_string()
    } else {
        format!("{}/", url)
    }
}

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

    #[test]
    fn test_is_draft() {
        assert!(is_draft(Path::new("blog/_my-draft.md")));
        assert!(is_draft(Path::new("blog/_drafts/post.md")));
        assert!(!is_draft(Path::new("blog/my-post.md")));
    }

    #[test]
    fn test_extract_title() {
        let content = "# My Title\n\nSome content";
        assert_eq!(extract_title(content), Some("My Title".to_string()));
    }

    #[test]
    fn test_extract_title_no_h1() {
        let content = "## Not H1\n\nSome content";
        assert_eq!(extract_title(content), None);
    }

    #[test]
    fn test_generate_url_root_index() {
        let path = Path::new("/source/index.md");
        let source_dir = Path::new("/source");
        let url = generate_url(path, source_dir, Collection::Root);
        assert_eq!(url, "/");
    }

    #[test]
    fn test_generate_url_blog_post() {
        let path = Path::new("/source/blog/2024-01-15-my-post.md");
        let source_dir = Path::new("/source");
        let url = generate_url(path, source_dir, Collection::Blog);
        assert_eq!(url, "/blog/my-post/");
    }

    #[test]
    fn test_normalize_url() {
        assert_eq!(normalize_url("/blog/post"), "/blog/post/");
        assert_eq!(normalize_url("/blog/post/"), "/blog/post/");
        assert_eq!(normalize_url("/blog/post#section"), "/blog/post/");
    }
}