bckt 0.7.3

bckt is an opinionated but flexible static site generator for blogs
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
use std::env;
use std::fs::{self, File};
use std::io::{self, Read, Seek};
use std::path::{Component, Path, PathBuf};

use anyhow::{Context, Result, anyhow, bail};
use walkdir::WalkDir;
use zip::ZipArchive;

/// Environment variable pointing to a bckt data root directory — a directory
/// that contains `themes/` and `demo/` subdirectories. Uses the platform path
/// separator to allow multiple entries.
pub const SHARE_PATH_ENV: &str = "BCKT_SHARE_PATH";

/// Candidate bckt data roots, in priority order:
/// 1. entries from `BCKT_SHARE_PATH` (an explicit override always wins);
/// 2. exactly one root derived from the executable's *layout on disk*, so we
///    never probe a path that the install type can't have:
///    - Homebrew/Linuxbrew (a `Cellar` component in the canonical path):
///      `<prefix>/share/bckt`, where `<prefix>` is the keg root the binary
///      lives in. `pkgshare.install` writes the data into the keg, so this
///      hits the physical copy directly.
///    - otherwise (tarball, zip, `cargo install`): the directory containing
///      the binary, where the bundled `themes/` and `demo/` sit beside it.
///
/// We classify on the `Cellar` component of the *canonical* path rather than
/// on whether the binary was reached via a symlink: `current_exe()` already
/// resolves symlinks on Linux but not on macOS, so the symlink signal is
/// platform-inconsistent while the `Cellar` check is not.
fn share_roots() -> Vec<PathBuf> {
    let mut roots = Vec::new();
    if let Some(value) = env::var_os(SHARE_PATH_ENV) {
        for part in env::split_paths(&value) {
            if !part.as_os_str().is_empty() {
                roots.push(part);
            }
        }
    }
    if let Ok(exe) = env::current_exe() {
        let real = exe.canonicalize().unwrap_or(exe);
        let is_brew = real.components().any(|c| c.as_os_str() == "Cellar");
        if is_brew {
            // <prefix>/bin/bckt -> <prefix>/share/bckt
            if let Some(prefix) = real.parent().and_then(|bin| bin.parent()) {
                roots.push(prefix.join("share").join("bckt"));
            }
        } else if let Some(dir) = real.parent() {
            roots.push(dir.to_path_buf());
        }
    }
    roots
}

/// Directories searched for bundled themes, derived from share roots by
/// appending `themes/`.
pub fn theme_search_paths() -> Vec<PathBuf> {
    share_roots()
        .into_iter()
        .map(|r| r.join("themes"))
        .collect()
}

/// Resolve a theme spec to a local source: either a `.zip` archive or a theme
/// directory. A spec that ends in `.zip` or contains a path separator is treated
/// as a direct filesystem path; a bare name is looked up across the theme search
/// paths, preferring `<name>.zip` and falling back to a `<name>/` directory.
pub fn resolve_theme(spec: &str) -> Result<PathBuf> {
    if spec.ends_with(".zip") || spec.contains('/') || spec.contains(std::path::MAIN_SEPARATOR) {
        let candidate = Path::new(spec);
        if candidate.is_dir() || candidate.is_file() {
            return Ok(candidate.to_path_buf());
        }
        bail!("theme '{}' not found", spec);
    }

    let file_name = format!("{spec}.zip");
    for dir in theme_search_paths() {
        let archive = dir.join(&file_name);
        if archive.is_file() {
            return Ok(archive);
        }
        let theme_dir = dir.join(spec);
        if theme_dir.is_dir() {
            return Ok(theme_dir);
        }
    }
    bail!(
        "theme '{spec}' not found in theme search path (set {SHARE_PATH_ENV}, or pass a path to a .zip archive or theme directory)"
    )
}

/// Directories searched for demo content, derived from share roots by
/// appending `demo/`.
fn demo_search_paths() -> Vec<PathBuf> {
    share_roots().into_iter().map(|r| r.join("demo")).collect()
}

/// Resolve a demo name to a local directory. A spec that contains a path
/// separator is treated as a direct filesystem path; a bare name is looked up
/// across the demo search paths.
pub fn resolve_demo(name: &str) -> Result<PathBuf> {
    if name.contains('/') || name.contains(std::path::MAIN_SEPARATOR) {
        let candidate = Path::new(name);
        if candidate.is_dir() {
            return Ok(candidate.to_path_buf());
        }
        bail!("demo '{}' not found", name);
    }

    for dir in demo_search_paths() {
        let demo_dir = dir.join(name);
        if demo_dir.is_dir() {
            return Ok(demo_dir);
        }
    }
    bail!("demo '{name}' not found (set {SHARE_PATH_ENV}, or pass a path to a demo directory)")
}

/// Install a theme into `destination`, replacing any existing contents. The
/// source may be a `.zip` archive (whose contents are extracted) or a theme
/// directory (whose contents are copied). Either way the theme directories
/// (`templates/`, `skel/`, `pages/`) are expected at the source root.
pub fn install_theme_source(source: &Path, destination: &Path) -> Result<()> {
    if source.is_dir() {
        return install_theme_dir(source, destination);
    }
    install_theme_archive(source, destination)
}

fn install_theme_dir(source: &Path, destination: &Path) -> Result<()> {
    let source = source
        .canonicalize()
        .with_context(|| format!("failed to resolve theme directory {}", source.display()))?;
    let target = canonical_target(destination)?;
    if target == source || target.starts_with(&source) || source.starts_with(&target) {
        bail!(
            "theme source and destination overlap: {} -> {}",
            source.display(),
            destination.display()
        );
    }

    prepare_destination(destination)?;

    let mut copied = false;
    for entry in WalkDir::new(&source) {
        let entry = entry
            .with_context(|| format!("failed to read theme directory {}", source.display()))?;
        if entry.file_type().is_dir() {
            continue;
        }
        let relative = entry.path().strip_prefix(&source).with_context(|| {
            format!(
                "path {} is not under {}",
                entry.path().display(),
                source.display()
            )
        })?;
        let out_path = destination.join(relative);
        if let Some(parent) = out_path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("failed to create directory {}", parent.display()))?;
        }
        fs::copy(entry.path(), &out_path).with_context(|| {
            format!(
                "failed to copy {} to {}",
                entry.path().display(),
                out_path.display()
            )
        })?;
        copied = true;
    }

    if !copied {
        bail!("theme directory {} is empty", source.display());
    }
    Ok(())
}

fn install_theme_archive(archive_path: &Path, destination: &Path) -> Result<()> {
    prepare_destination(destination)?;

    let file = File::open(archive_path)
        .with_context(|| format!("failed to open theme archive {}", archive_path.display()))?;
    let mut archive = ZipArchive::new(file)
        .with_context(|| format!("failed to read theme archive {}", archive_path.display()))?;

    extract_archive(&mut archive, destination)
}

fn extract_archive<R: Read + Seek>(archive: &mut ZipArchive<R>, destination: &Path) -> Result<()> {
    let mut extracted_any = false;

    for i in 0..archive.len() {
        let mut entry = archive
            .by_index(i)
            .with_context(|| format!("failed to read archive entry #{i}"))?;
        if entry.is_dir() {
            continue;
        }

        let Some(relative) = safe_relative_path(entry.name()) else {
            continue;
        };

        let out_path = destination.join(&relative);
        if let Some(parent) = out_path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("failed to create directory {}", parent.display()))?;
        }

        let mut outfile = File::create(&out_path)
            .with_context(|| format!("failed to create file {}", out_path.display()))?;
        io::copy(&mut entry, &mut outfile)
            .with_context(|| format!("failed to write {}", out_path.display()))?;

        #[cfg(unix)]
        if let Some(mode) = entry.unix_mode() {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&out_path, fs::Permissions::from_mode(mode))
                .with_context(|| format!("failed to set permissions on {}", out_path.display()))?;
        }

        extracted_any = true;
    }

    if !extracted_any {
        return Err(anyhow!("no files extracted from archive"));
    }

    Ok(())
}

/// Remove `destination` if it exists and recreate it as an empty directory.
fn prepare_destination(destination: &Path) -> Result<()> {
    if destination.exists() {
        fs::remove_dir_all(destination).with_context(|| {
            format!(
                "failed to remove existing directory {}",
                destination.display()
            )
        })?;
    }
    fs::create_dir_all(destination)
        .with_context(|| format!("failed to create directory {}", destination.display()))?;
    Ok(())
}

/// Canonical path a destination *will* have, even when it (and some of its
/// parents) do not exist yet: walk up to the nearest existing ancestor,
/// canonicalise it, then re-append the trailing components. Used to detect
/// source/destination overlap before clobbering the destination.
fn canonical_target(destination: &Path) -> Result<PathBuf> {
    let mut suffix: Vec<std::ffi::OsString> = Vec::new();
    let mut current = destination;
    loop {
        if let Ok(canon) = current.canonicalize() {
            let mut result = canon;
            for part in suffix.iter().rev() {
                result.push(part);
            }
            return Ok(result);
        }
        match (current.parent(), current.file_name()) {
            (Some(parent), Some(name)) => {
                suffix.push(name.to_os_string());
                current = parent;
            }
            // No existing ancestor (e.g. a relative path); use it as-is.
            _ => return Ok(destination.to_path_buf()),
        }
    }
}

/// Sanitise an archive entry name into a relative path, rejecting absolute paths
/// and any `..` components to guard against zip-slip.
fn safe_relative_path(name: &str) -> Option<PathBuf> {
    let mut out = PathBuf::new();
    for component in Path::new(name).components() {
        match component {
            Component::Normal(segment) => out.push(segment),
            Component::CurDir => {}
            _ => return None,
        }
    }
    if out.as_os_str().is_empty() {
        None
    } else {
        Some(out)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::TempDir;
    use zip::write::SimpleFileOptions;

    fn write_archive(path: &Path, files: &[(&str, &str)]) {
        let file = File::create(path).unwrap();
        let mut zip = zip::ZipWriter::new(file);
        let options = SimpleFileOptions::default();
        for (name, contents) in files {
            zip.start_file(*name, options).unwrap();
            zip.write_all(contents.as_bytes()).unwrap();
        }
        zip.finish().unwrap();
    }

    #[test]
    fn installs_archive_contents_at_root() {
        let dir = TempDir::new().unwrap();
        let archive = dir.path().join("theme.zip");
        write_archive(
            &archive,
            &[
                ("templates/post.html", "<html></html>"),
                ("skel/assets/js/search.js", "// search"),
            ],
        );

        let destination = dir.path().join("themes/theme");
        install_theme_source(&archive, &destination).unwrap();

        assert!(destination.join("templates/post.html").is_file());
        assert!(destination.join("skel/assets/js/search.js").is_file());
    }

    #[test]
    fn rejects_zip_slip_entries() {
        let dir = TempDir::new().unwrap();
        let archive = dir.path().join("evil.zip");
        write_archive(
            &archive,
            &[
                ("../escape.txt", "nope"),
                ("templates/post.html", "<html></html>"),
            ],
        );

        let destination = dir.path().join("themes/evil");
        install_theme_source(&archive, &destination).unwrap();

        assert!(!dir.path().join("escape.txt").exists());
        assert!(destination.join("templates/post.html").is_file());
    }

    #[test]
    fn installs_directory_source() {
        let dir = TempDir::new().unwrap();
        let source = dir.path().join("src-theme");
        fs::create_dir_all(source.join("templates")).unwrap();
        fs::create_dir_all(source.join("skel/assets/js")).unwrap();
        fs::write(source.join("templates/post.html"), "<html></html>").unwrap();
        fs::write(source.join("skel/assets/js/search.js"), "// search").unwrap();

        let destination = dir.path().join("themes/theme");
        install_theme_source(&source, &destination).unwrap();

        assert!(destination.join("templates/post.html").is_file());
        assert!(destination.join("skel/assets/js/search.js").is_file());
    }

    #[test]
    fn rejects_overlapping_source_and_destination() {
        let dir = TempDir::new().unwrap();
        let source = dir.path().join("themes/bckt3");
        fs::create_dir_all(source.join("templates")).unwrap();
        fs::write(source.join("templates/post.html"), "<html></html>").unwrap();

        // Installing a directory onto itself must not delete the source.
        let result = install_theme_source(&source, &source);
        assert!(result.is_err());
        assert!(source.join("templates/post.html").is_file());
    }

    #[test]
    fn resolve_direct_paths() {
        let dir = TempDir::new().unwrap();
        let archive = dir.path().join("theme.zip");
        write_archive(&archive, &[("templates/post.html", "<html></html>")]);
        assert_eq!(resolve_theme(archive.to_str().unwrap()).unwrap(), archive);

        let theme_dir = dir.path().join("a/themedir");
        fs::create_dir_all(&theme_dir).unwrap();
        assert_eq!(
            resolve_theme(theme_dir.to_str().unwrap()).unwrap(),
            theme_dir
        );

        let missing = dir.path().join("missing.zip");
        assert!(resolve_theme(missing.to_str().unwrap()).is_err());
    }

    #[test]
    fn resolve_named_theme_searches_path() {
        let dir = TempDir::new().unwrap();
        // BCKT_SHARE_PATH points at a share root; themes live under themes/.
        let themes_dir = dir.path().join("themes");
        fs::create_dir_all(&themes_dir).unwrap();
        // A .zip is preferred for one name...
        let archive = themes_dir.join("bckt3.zip");
        write_archive(&archive, &[("templates/post.html", "<html></html>")]);
        // ...and a directory is the fallback for another.
        let other_dir = themes_dir.join("plain");
        fs::create_dir_all(&other_dir).unwrap();

        // SAFETY: env-dependent assertions are consolidated into this single
        // test so the global var is not mutated by concurrent tests.
        unsafe { env::set_var(SHARE_PATH_ENV, dir.path()) };
        let zip = resolve_theme("bckt3");
        let dir_theme = resolve_theme("plain");
        let missing = resolve_theme("does-not-exist");
        unsafe { env::remove_var(SHARE_PATH_ENV) };

        assert_eq!(zip.unwrap(), archive);
        assert_eq!(dir_theme.unwrap(), other_dir);
        assert!(missing.is_err());
    }
}