1use std::fmt::Write as _;
19use std::path::{Path, PathBuf};
20
21pub const GENERATED: &str = "serve_assets.rs";
23
24pub fn embed() {
30 let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR")
31 .map(PathBuf::from)
32 .unwrap_or_else(|| {
33 fail("CARGO_MANIFEST_DIR is not set; call serve_build::embed() from build.rs")
34 });
35 let out_dir = std::env::var_os("OUT_DIR")
36 .map(PathBuf::from)
37 .unwrap_or_else(|| fail("OUT_DIR is not set; call serve_build::embed() from build.rs"));
38
39 let source = match generate(&manifest_dir) {
40 Ok(source) => source,
41 Err(err) => fail(&format!("serve-build: {err}")),
42 };
43 if let Err(err) = std::fs::write(out_dir.join(GENERATED), source) {
44 fail(&format!("serve-build: writing {GENERATED}: {err}"));
45 }
46 println!(
47 "cargo:rerun-if-changed={}",
48 manifest_dir.join("agent").display()
49 );
50 println!(
51 "cargo:rerun-if-changed={}",
52 manifest_dir.join("serve.toml").display()
53 );
54}
55
56fn fail(message: &str) -> ! {
57 eprintln!("{message}");
59 std::process::exit(1)
60}
61
62pub fn generate(manifest_dir: &Path) -> std::io::Result<String> {
66 let mut out = String::from("// @generated by serve-build. Do not edit.\n");
67 let agent_dir = manifest_dir.join("agent");
68 let mut files = Vec::new();
69 if agent_dir.is_dir() {
70 collect(&agent_dir, &mut files)?;
71 }
72 files.sort();
73 for file in files {
74 let relative = file
75 .strip_prefix(&agent_dir)
76 .map_err(std::io::Error::other)?
77 .to_string_lossy()
78 .replace('\\', "/");
79 let absolute = file.to_string_lossy().to_string();
80 let _ = writeln!(
81 out,
82 "::serve::__private::inventory::submit! {{ ::serve::__private::AssetRegistration {{ path: {relative:?}, contents: ::core::include_str!({absolute:?}), disk: {absolute:?} }} }}"
83 );
84 }
85 let config = manifest_dir.join("serve.toml");
86 if config.is_file() {
87 let absolute = config.to_string_lossy().to_string();
88 let _ = writeln!(
89 out,
90 "::serve::__private::inventory::submit! {{ ::serve::__private::AssetRegistration {{ path: \"@serve.toml\", contents: ::core::include_str!({absolute:?}), disk: {absolute:?} }} }}"
91 );
92 }
93 Ok(out)
94}
95
96fn collect(dir: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
97 for entry in std::fs::read_dir(dir)? {
98 let path = entry?.path();
99 let hidden = path
100 .file_name()
101 .is_some_and(|name| name.to_string_lossy().starts_with('.'));
102 if hidden {
103 continue;
104 }
105 if path.is_dir() {
106 collect(&path, files)?;
107 } else if is_text_asset(&path) {
108 files.push(path);
109 }
110 }
111 Ok(())
112}
113
114fn is_text_asset(path: &Path) -> bool {
116 matches!(
117 path.extension().and_then(|ext| ext.to_str()),
118 Some("md" | "txt" | "json" | "yaml" | "yml" | "toml" | "sql")
119 )
120}
121
122#[cfg(test)]
123mod tests {
124 #![allow(clippy::unwrap_used, clippy::expect_used)]
125
126 use super::generate;
127
128 #[test]
129 fn embeds_agent_markdown_and_config_but_skips_hidden_and_binary_files() {
130 let dir = tempfile::tempdir().unwrap();
131 let root = dir.path();
132 std::fs::create_dir_all(root.join("agent/skills/sql-style")).unwrap();
133 std::fs::write(root.join("agent/instructions.md"), "hi").unwrap();
134 std::fs::write(root.join("agent/skills/sql-style/SKILL.md"), "skill").unwrap();
135 std::fs::write(root.join("agent/.draft.md"), "hidden").unwrap();
136 std::fs::write(root.join("agent/logo.png"), [0u8, 1, 2]).unwrap();
137 std::fs::write(root.join("serve.toml"), "name = \"x\"").unwrap();
138
139 let source = generate(root).unwrap();
140 assert!(source.contains("path: \"instructions.md\""), "{source}");
141 assert!(
142 source.contains("path: \"skills/sql-style/SKILL.md\""),
143 "{source}"
144 );
145 assert!(source.contains("path: \"@serve.toml\""), "{source}");
146 assert!(!source.contains(".draft.md"), "{source}");
147 assert!(!source.contains("logo.png"), "{source}");
148 }
149
150 #[test]
151 fn a_crate_without_agent_dir_embeds_nothing() {
152 let dir = tempfile::tempdir().unwrap();
153 let source = generate(dir.path()).unwrap();
154 assert_eq!(source.lines().count(), 1, "{source}");
155 }
156}