1use std::collections::{BTreeMap, HashMap};
10use std::path::Path;
11
12use bynk_project::{ParsedFile, UnitKind};
13use bynk_syntax::ast::CommonsItem;
14use bynk_syntax::error::CompileError;
15
16use crate::firstparty;
17use crate::project_model::ErrorSink;
18use crate::symbols::UnitTable;
19
20pub const CONTAINER_CLASS_PREFIX: &str = "__Container_";
25
26pub fn container_class_name(capability: &str) -> String {
29 format!("{CONTAINER_CLASS_PREFIX}{capability}")
30}
31
32pub fn build_path_problem(path: &str) -> Option<&'static str> {
37 if path.is_empty() {
38 return Some("is empty");
39 }
40 if path.contains('\\') {
41 return Some("uses `\\`; write a `/`-separated path");
42 }
43 if path.contains(['\0', '\n', '\r']) || path.chars().any(char::is_control) {
44 return Some("holds a control character");
45 }
46 if path.starts_with('/')
47 || matches!(path.as_bytes(), [d, b':'] | [d, b':', b'/', ..] if d.is_ascii_alphabetic())
48 {
49 return Some("is absolute; it must be relative to the project root");
50 }
51 if path.split('/').any(|seg| seg == "..") {
52 return Some("leaves the project with `..`");
53 }
54 if normalise_build(path).is_empty() {
55 return Some("names the project root, not a directory beneath it");
56 }
57 None
58}
59
60pub fn normalise_build(path: &str) -> String {
64 path.split('/')
65 .filter(|seg| !seg.is_empty() && *seg != ".")
66 .collect::<Vec<_>>()
67 .join("/")
68}
69
70pub fn dockerfile_path(build: &str) -> String {
72 format!("{}/Dockerfile", normalise_build(build))
73}
74
75pub fn port_problem(value: i64) -> Option<&'static str> {
77 (!(1..=65535).contains(&value)).then_some("is a TCP port, 1 to 65535")
78}
79
80pub fn sleep_after_seconds(millis: i64) -> Option<i64> {
83 (millis > 0
84 && millis % 1000 == 0
85 && millis / 1000 <= firstparty::CONTAINER_MAX_SLEEP_AFTER_SECONDS)
86 .then_some(millis / 1000)
87}
88
89pub fn is_forwardable_name(name: &str) -> bool {
93 let mut chars = name.chars();
94 chars
95 .next()
96 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
97 && name.len() <= 128
98 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
99}
100
101pub fn forward_problem(items: &[String]) -> Option<String> {
105 if items.len() > firstparty::CONTAINER_MAX_FORWARD {
106 return Some(format!(
107 "`@forward` lists {} names, and a container takes at most {}",
108 items.len(),
109 firstparty::CONTAINER_MAX_FORWARD
110 ));
111 }
112 items.iter().enumerate().find_map(|(i, item)| {
113 if !is_forwardable_name(item) {
114 return Some(format!(
115 "`{}` is not a name a container's environment can hold",
116 item.escape_debug()
117 ));
118 }
119 items[..i]
120 .contains(item)
121 .then(|| format!("`{item}` is listed twice"))
122 })
123}
124
125pub fn dockerfile_problem(build: &str, has_file: &dyn Fn(&str) -> bool) -> Option<String> {
129 let file = dockerfile_path(build);
130 (!has_file(&file)).then(|| format!("`{file}` does not exist"))
131}
132
133pub fn phase_container_builds(
138 groups: &BTreeMap<String, Vec<usize>>,
139 kinds: &BTreeMap<String, UnitKind>,
140 parsed: &[ParsedFile],
141 unit_tables: &HashMap<String, UnitTable>,
142 project_root: &Path,
143 errors: &mut ErrorSink,
144) {
145 let has_file = |rel: &str| project_root.join(rel).is_file();
146 for (name, indices) in groups {
147 if kinds.get(name) != Some(&UnitKind::Context) {
148 continue;
149 }
150 let Some(table) = unit_tables.get(name) else {
151 continue;
152 };
153 for &i in indices {
154 if parsed[i].is_synthetic() {
155 continue;
156 }
157 let path = parsed[i].identity_path();
158 for item in parsed[i].items() {
159 let CommonsItem::Capability(c) = item else {
160 continue;
161 };
162 let Some(build) = table
163 .derived
164 .get(&c.name.name)
165 .and_then(|d| d.container_build())
166 else {
167 continue;
168 };
169 let Some(problem) = dockerfile_problem(build, &has_file) else {
170 continue;
171 };
172 errors.push_for(
173 Some(&path),
174 CompileError::new(
175 "bynk.container.build_missing",
176 c.span,
177 format!(
178 "the container `{}` has no Dockerfile: {problem}",
179 c.name.name
180 ),
181 )
182 .with_note(format!(
183 "`@build(\"{build}\")` names the directory that holds the Dockerfile, relative to the project root; create `{}`",
184 dockerfile_path(build)
185 )),
186 );
187 }
188 }
189 }
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 #[test]
197 fn a_build_path_stays_inside_the_project() {
198 assert_eq!(build_path_problem("containers/renderer"), None);
199 assert_eq!(build_path_problem("./containers/renderer/"), None);
200 assert!(build_path_problem("").is_some());
201 assert!(build_path_problem("../x").is_some());
202 assert!(build_path_problem("a/../../x").is_some());
203 assert!(build_path_problem("/abs").is_some());
204 assert!(build_path_problem("C:/abs").is_some());
205 assert_eq!(build_path_problem("a:b/c"), None);
206 assert!(build_path_problem("a\\b").is_some());
207 assert!(build_path_problem(".").is_some());
208 assert!(build_path_problem("a\nb").is_some());
209 }
210
211 #[test]
212 fn a_build_path_is_normalised() {
213 assert_eq!(
214 normalise_build("./containers//renderer/"),
215 "containers/renderer"
216 );
217 assert_eq!(
218 dockerfile_path("containers/renderer/"),
219 "containers/renderer/Dockerfile"
220 );
221 }
222
223 #[test]
224 fn sleep_after_is_whole_seconds_up_to_six_hours() {
225 assert_eq!(sleep_after_seconds(300_000), Some(300));
226 assert_eq!(sleep_after_seconds(21_600_000), Some(21_600));
227 assert_eq!(sleep_after_seconds(21_601_000), None);
228 assert_eq!(sleep_after_seconds(0), None);
229 assert_eq!(sleep_after_seconds(1_500), None);
230 }
231
232 #[test]
233 fn forwarded_names_are_plain_identifiers() {
234 assert!(forward_problem(&["API_KEY".into(), "_x1".into()]).is_none());
235 assert!(forward_problem(&["1X".into()]).is_some());
236 assert!(forward_problem(&["A-B".into()]).is_some());
237 assert!(forward_problem(&["A".into(), "A".into()]).is_some());
238 assert!(port_problem(0).is_some() && port_problem(65536).is_some());
239 assert!(port_problem(8080).is_none());
240 }
241}