Skip to main content

proa_cli/
font.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `cargo proa font` — vendor and inspect self-hosted, metric-matched fonts.
5//!
6//! Fonts are declared in code with `google_font!` / `local_font!`; the build
7//! collector in [`proa_fonts_build::collect`] vendors them during `cargo
8//! build`. This command runs the same collector outside a build: `sync`
9//! vendors and locks every declaration right now (or, with `--offline`,
10//! verifies that `proa-fonts.lock` and the vendored files already satisfy
11//! them, the CI gate), and `list` prints what the lock records.
12
13use std::path::PathBuf;
14
15use anyhow::{Context, Result};
16use proa_fonts_build::collect::{self, CollectOptions, LOCK_FILE};
17use proa_fonts_build::config::FontsLock;
18
19/// Options for `font sync`.
20pub struct SyncOptions {
21    pub root: PathBuf,
22    /// Verify only: fail instead of fetching when a declaration is not
23    /// satisfied by the lock and vendored files.
24    pub offline: bool,
25    /// Override the vendored-files directory (defaults to `public/fonts`,
26    /// matching the collector default). Must match the build script's
27    /// `CollectOptions` when that is customized.
28    pub fonts_dir: Option<PathBuf>,
29    /// Override the URL prefix (defaults to `/fonts`).
30    pub url_prefix: Option<String>,
31}
32
33/// Vendor and lock every font declared in the project's source.
34pub fn sync(opts: SyncOptions) -> Result<()> {
35    let collect_opts = CollectOptions {
36        crate_root: opts.root.clone(),
37        // No module emission outside a build script; `cargo build` owns that.
38        out_dir: PathBuf::new(),
39        fonts_out_dir: opts
40            .fonts_dir
41            .unwrap_or_else(|| PathBuf::from("public/fonts")),
42        url_prefix: opts.url_prefix.unwrap_or_else(|| "/fonts".to_string()),
43        lock_path: None,
44    };
45    let result = collect::sync(&collect_opts, opts.offline)
46        .with_context(|| format!("syncing fonts under {}", opts.root.display()))?;
47
48    for path in &result.skipped_sources {
49        eprintln!(
50            "warning: {} failed to parse; its declarations are preserved unverified",
51            path.display()
52        );
53    }
54    if result.reports.is_empty() && result.preserved.is_empty() {
55        println!(
56            "no google_font!/local_font! declarations found under {}",
57            opts.root.join("src").display()
58        );
59        return Ok(());
60    }
61    for report in &result.reports {
62        let status = if report.repaired {
63            "re-vendored (integrity mismatch)"
64        } else if report.refreshed {
65            "vendored"
66        } else {
67            "verified"
68        };
69        println!(
70            "font {key}: {family}, {n} file(s) {status}",
71            key = report.key,
72            family = report.family,
73            n = report.files,
74        );
75    }
76    for key in &result.preserved {
77        println!("font {key}: preserved (source file did not parse)");
78    }
79    for filename in &result.removed {
80        println!("removed stale {filename}");
81    }
82    Ok(())
83}
84
85/// Print the fonts recorded in `proa-fonts.lock`.
86pub fn list(root: PathBuf, json: bool) -> Result<()> {
87    let path = root.join(LOCK_FILE);
88    let lock: FontsLock = if path.exists() {
89        let text = std::fs::read_to_string(&path)
90            .with_context(|| format!("reading {}", path.display()))?;
91        toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?
92    } else {
93        FontsLock::default()
94    };
95
96    if json {
97        println!("{}", serde_json::to_string_pretty(&lock)?);
98        return Ok(());
99    }
100    if lock.fonts.is_empty() {
101        println!(
102            "no fonts locked (declare one with google_font!/local_font!, then run \
103             `cargo proa font sync` or `cargo build`)"
104        );
105        return Ok(());
106    }
107    for (key, e) in &lock.fonts {
108        println!(
109            "{key:>24}  {family}  {n} file(s)  class `{class}`  var `{var}`",
110            family = e.family,
111            n = e.files.len(),
112            class = e.class_name,
113            var = e.css_variable,
114        );
115    }
116    Ok(())
117}