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 the asset catalog's fonts
30    /// directory, `/_proa/immutable/fonts`).
31    pub url_prefix: Option<String>,
32}
33
34/// Vendor and lock every font declared in the project's source.
35pub fn sync(opts: SyncOptions) -> Result<()> {
36    let collect_opts = CollectOptions {
37        crate_root: opts.root.clone(),
38        // No module emission outside a build script; `cargo build` owns that.
39        out_dir: PathBuf::new(),
40        fonts_out_dir: opts
41            .fonts_dir
42            .unwrap_or_else(|| PathBuf::from("public/fonts")),
43        url_prefix: opts
44            .url_prefix
45            .unwrap_or_else(|| proa_fonts_build::CATALOG_URL_PREFIX.to_string()),
46        lock_path: None,
47    };
48    let result = collect::sync(&collect_opts, opts.offline)
49        .with_context(|| format!("syncing fonts under {}", opts.root.display()))?;
50
51    for path in &result.skipped_sources {
52        eprintln!(
53            "warning: {} failed to parse; its declarations are preserved unverified",
54            path.display()
55        );
56    }
57    if result.reports.is_empty() && result.preserved.is_empty() {
58        println!(
59            "no google_font!/local_font! declarations found under {}",
60            opts.root.join("src").display()
61        );
62        return Ok(());
63    }
64    for report in &result.reports {
65        let status = if report.repaired {
66            "re-vendored (integrity mismatch)"
67        } else if report.refreshed {
68            "vendored"
69        } else {
70            "verified"
71        };
72        println!(
73            "font {key}: {family}, {n} file(s) {status}",
74            key = report.key,
75            family = report.family,
76            n = report.files,
77        );
78    }
79    for key in &result.preserved {
80        println!("font {key}: preserved (source file did not parse)");
81    }
82    for filename in &result.removed {
83        println!("removed stale {filename}");
84    }
85    Ok(())
86}
87
88/// Print the fonts recorded in `proa-fonts.lock`.
89pub fn list(root: PathBuf, json: bool) -> Result<()> {
90    let path = root.join(LOCK_FILE);
91    let lock: FontsLock = if path.exists() {
92        let text = std::fs::read_to_string(&path)
93            .with_context(|| format!("reading {}", path.display()))?;
94        toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?
95    } else {
96        FontsLock::default()
97    };
98
99    if json {
100        println!("{}", serde_json::to_string_pretty(&lock)?);
101        return Ok(());
102    }
103    if lock.fonts.is_empty() {
104        println!(
105            "no fonts locked (declare one with google_font!/local_font!, then run \
106             `cargo proa font sync` or `cargo build`)"
107        );
108        return Ok(());
109    }
110    for (key, e) in &lock.fonts {
111        println!(
112            "{key:>24}  {family}  {n} file(s)  class `{class}`  var `{var}`",
113            family = e.family,
114            n = e.files.len(),
115            class = e.class_name,
116            var = e.css_variable,
117        );
118    }
119    Ok(())
120}