Skip to main content

byob_exec/env/
devcontainer.rs

1//! What a workspace's container is made from: its `.devcontainer/devcontainer.json` (or
2//! `.devcontainer.json`), else the default image.
3//!
4//! Supported: `image`, `build.dockerfile` (+ `build.context`, `build.args`),
5//! `containerEnv`, `remoteEnv`, `onCreateCommand` and `postCreateCommand` (string, array
6//! or object; run once, as root, when the container is created). Everything else that
7//! changes the container — `features`, `mounts`, `runArgs`, `forwardPorts`,
8//! `dockerComposeFile`, `workspaceMount`/`workspaceFolder`, `remoteUser`/`containerUser`,
9//! the other lifecycle commands — is ignored, and the model is told which ones.
10
11use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13
14use serde_json::Value;
15
16/// Where devcontainer.json may live, in order.
17pub const FILES: &[&str] = &[".devcontainer/devcontainer.json", ".devcontainer.json"];
18/// Largest devcontainer.json / Dockerfile read.
19const MAX_FILE: u64 = 1 << 20;
20
21/// Keys byob reads, and keys that don't affect commands (editor settings).
22const KNOWN: &[&str] = &["name", "image", "build", "containerEnv", "remoteEnv", "onCreateCommand", "postCreateCommand", "customizations", "$schema"];
23
24/// The image to run.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum Image {
27    Pull(String),
28    Build { dockerfile: PathBuf, context: PathBuf, args: BTreeMap<String, String> },
29}
30
31/// A lifecycle command: a shell line or an argument list.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum Cmd {
34    Shell(String),
35    Args(Vec<String>),
36}
37
38/// How to make and use one workspace's container.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Spec {
41    pub image: Image,
42    /// Set on the container (`containerEnv`).
43    pub env: Vec<(String, String)>,
44    /// Set for each command (`remoteEnv`).
45    pub remote_env: Vec<(String, String)>,
46    /// Run once after creation, in order.
47    pub on_create: Vec<Cmd>,
48    /// devcontainer.json keys byob doesn't support.
49    pub ignored: Vec<String>,
50    /// The devcontainer.json it came from (workspace-relative), if any.
51    pub file: Option<&'static str>,
52}
53
54impl Spec {
55    /// The default container: `image`, nothing else.
56    pub fn default_image(image: &str) -> Self {
57        Self { image: Image::Pull(image.to_owned()), env: Vec::new(), remote_env: Vec::new(), on_create: Vec::new(), ignored: Vec::new(), file: None }
58    }
59
60    /// For workspace `ws`: its devcontainer.json if it has one, else `default_image`.
61    pub fn for_workspace(ws: &Path, default_image: &str) -> Result<Self, String> {
62        match find(ws) {
63            None => Ok(Self::default_image(default_image)),
64            Some(file) => {
65                let path = ws.join(file);
66                let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
67                if size > MAX_FILE {
68                    return Err(format!("{file} is too large"));
69                }
70                let text = std::fs::read_to_string(&path).map_err(|e| format!("can't read {file}: {e}"))?;
71                let base = path.parent().unwrap_or(ws);
72                Self::parse(&text, base, ws).map(|mut s| {
73                    s.file = Some(file);
74                    s
75                })
76            }
77        }
78    }
79
80    /// Parse devcontainer.json `text`; relative paths are against `base` (its folder).
81    pub fn parse(text: &str, base: &Path, ws: &Path) -> Result<Self, String> {
82        let v: Value = serde_json::from_str(&strip_jsonc(text)).map_err(|e| format!("devcontainer.json isn't valid JSON: {e}"))?;
83        let obj = v.as_object().ok_or("devcontainer.json must be an object")?;
84        let image = if let Some(b) = obj.get("build").and_then(Value::as_object).filter(|b| b.contains_key("dockerfile") || b.contains_key("dockerFile")) {
85            let file = b.get("dockerfile").or_else(|| b.get("dockerFile")).and_then(Value::as_str).ok_or("build.dockerfile must be a string")?;
86            let dockerfile = inside(base, file, ws)?;
87            let context = inside(base, b.get("context").and_then(Value::as_str).unwrap_or("."), ws)?;
88            let args = strings(b.get("args"));
89            Image::Build { dockerfile, context, args: args.into_iter().collect() }
90        } else if let Some(i) = obj.get("image").and_then(Value::as_str).filter(|i| valid_image(i)) {
91            Image::Pull(i.to_owned())
92        } else if obj.contains_key("dockerComposeFile") {
93            return Err("devcontainer.json uses dockerComposeFile, which byob doesn't support (it needs `image` or `build.dockerfile`)".into());
94        } else {
95            return Err("devcontainer.json has no usable `image` or `build.dockerfile`".into());
96        };
97        let mut on_create = Vec::new();
98        for key in ["onCreateCommand", "postCreateCommand"] {
99            on_create.extend(commands(obj.get(key)));
100        }
101        let ignored = obj.keys().filter(|k| !KNOWN.contains(&k.as_str())).cloned().collect();
102        Ok(Self { image, env: strings(obj.get("containerEnv")), remote_env: strings(obj.get("remoteEnv")), on_create, ignored, file: None })
103    }
104
105    /// The image name for messages ("python:3-slim", "built from .devcontainer/Dockerfile").
106    pub fn describe(&self, ws: &Path) -> String {
107        match &self.image {
108            Image::Pull(i) => i.clone(),
109            // Inside the workspace, written the way devcontainer.json writes paths (`/`).
110            Image::Build { dockerfile, .. } => match dockerfile.strip_prefix(ws) {
111                Ok(rel) => {
112                    let parts: Vec<_> = rel.components().map(|c| c.as_os_str().to_string_lossy()).collect();
113                    format!("built from {}", parts.join("/"))
114                }
115                Err(_) => format!("built from {}", dockerfile.display()),
116            },
117        }
118    }
119}
120
121/// The workspace's devcontainer.json, if it has one.
122pub fn find(ws: &Path) -> Option<&'static str> {
123    FILES.iter().copied().find(|f| ws.join(f).is_file())
124}
125
126/// An image reference: no options, spaces or shell characters.
127pub fn valid_image(i: &str) -> bool {
128    !i.is_empty() && i.len() <= 255 && !i.starts_with('-') && i.chars().all(|c| c.is_ascii_alphanumeric() || "._-/:@".contains(c))
129}
130
131/// `rel` against `base`, which must stay inside the workspace (no `..` escapes).
132fn inside(base: &Path, rel: &str, ws: &Path) -> Result<PathBuf, String> {
133    let mut p = base.to_path_buf();
134    for part in Path::new(rel).components() {
135        match part {
136            std::path::Component::ParentDir => {
137                p.pop();
138            }
139            std::path::Component::Normal(n) => p.push(n),
140            std::path::Component::CurDir => {}
141            _ => return Err(format!("{rel:?} must be a relative path")),
142        }
143    }
144    if p.starts_with(ws) { Ok(p) } else { Err(format!("{rel:?} is outside the workspace")) }
145}
146
147/// A `{"KEY": "value"}` object as pairs (other values skipped; names checked).
148fn strings(v: Option<&Value>) -> Vec<(String, String)> {
149    v.and_then(Value::as_object)
150        .map(|o| {
151            o.iter()
152                .filter(|(k, _)| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
153                .filter_map(|(k, v)| v.as_str().filter(|v| !v.contains('\0')).map(|v| (k.clone(), v.to_owned())))
154                .collect()
155        })
156        .unwrap_or_default()
157}
158
159/// A lifecycle command: `"string"`, `["argv"]`, or `{"name": either}`.
160fn commands(v: Option<&Value>) -> Vec<Cmd> {
161    match v {
162        Some(Value::String(s)) if !s.trim().is_empty() => vec![Cmd::Shell(s.clone())],
163        Some(Value::Array(a)) => {
164            let args: Vec<String> = a.iter().filter_map(Value::as_str).map(str::to_owned).collect();
165            if args.is_empty() { Vec::new() } else { vec![Cmd::Args(args)] }
166        }
167        Some(Value::Object(o)) => o.values().flat_map(|v| commands(Some(v))).collect(),
168        _ => Vec::new(),
169    }
170}
171
172/// JSON with comments (`//`, `/* */`) and trailing commas, as devcontainer.json allows,
173/// turned into plain JSON. Strings are left alone.
174pub fn strip_jsonc(text: &str) -> String {
175    let mut out = String::with_capacity(text.len());
176    let mut chars = text.chars().peekable();
177    let mut in_str = false;
178    while let Some(c) = chars.next() {
179        if in_str {
180            out.push(c);
181            if c == '\\' {
182                if let Some(n) = chars.next() {
183                    out.push(n);
184                }
185            } else if c == '"' {
186                in_str = false;
187            }
188            continue;
189        }
190        match c {
191            '"' => {
192                in_str = true;
193                out.push(c);
194            }
195            '/' if chars.peek() == Some(&'/') => {
196                for n in chars.by_ref() {
197                    if n == '\n' {
198                        out.push('\n');
199                        break;
200                    }
201                }
202            }
203            '/' if chars.peek() == Some(&'*') => {
204                chars.next();
205                let mut prev = ' ';
206                for n in chars.by_ref() {
207                    if prev == '*' && n == '/' {
208                        break;
209                    }
210                    prev = n;
211                }
212                out.push(' ');
213            }
214            _ => out.push(c),
215        }
216    }
217    // Trailing commas: a comma followed (after whitespace) by } or ].
218    let bytes: Vec<char> = out.chars().collect();
219    let mut cleaned = String::with_capacity(out.len());
220    let mut in_str = false;
221    let mut i = 0;
222    while i < bytes.len() {
223        let Some(&c) = bytes.get(i) else { break };
224        if in_str {
225            cleaned.push(c);
226            if c == '\\' {
227                if let Some(n) = bytes.get(i + 1) {
228                    cleaned.push(*n);
229                    i += 1;
230                }
231            } else if c == '"' {
232                in_str = false;
233            }
234        } else if c == '"' {
235            in_str = true;
236            cleaned.push(c);
237        } else if c == ',' {
238            let next = bytes.get(i + 1..).unwrap_or_default().iter().find(|c| !c.is_whitespace());
239            if !matches!(next, Some('}' | ']')) {
240                cleaned.push(c);
241            }
242        } else {
243            cleaned.push(c);
244        }
245        i += 1;
246    }
247    cleaned
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    #[test]
255    fn jsonc_comments_and_trailing_commas() {
256        let t = "{\n  // a comment\n  \"image\": \"x\", /* block */\n  \"url\": \"http://a//b\",\n  \"list\": [1, 2,],\n}\n";
257        let v: Value = serde_json::from_str(&strip_jsonc(t)).unwrap();
258        assert_eq!(v["image"], "x");
259        assert_eq!(v["url"], "http://a//b");
260        assert_eq!(v["list"], serde_json::json!([1, 2]));
261        assert_eq!(strip_jsonc(r#"{"a": "x,}\"y"}"#), r#"{"a": "x,}\"y"}"#);
262    }
263
264    #[test]
265    fn devcontainer_specs() {
266        let ws = Path::new("/w");
267        let base = Path::new("/w/.devcontainer");
268        let s = Spec::parse(
269            r#"{
270              "name": "dev",
271              "image": "mcr.microsoft.com/devcontainers/python:3.12",
272              "features": {"ghcr.io/devcontainers/features/node:1": {}},
273              "forwardPorts": [8000],
274              "containerEnv": {"GREETING": "hi", "bad key": "x"},
275              "remoteEnv": {"MODE": "dev"},
276              "onCreateCommand": "echo one",
277              "postCreateCommand": {"a": ["pip", "install", "-r", "requirements.txt"], "b": "echo two"},
278              "customizations": {"vscode": {}},
279            }"#,
280            base,
281            ws,
282        )
283        .unwrap();
284        assert_eq!(s.image, Image::Pull("mcr.microsoft.com/devcontainers/python:3.12".into()));
285        assert_eq!(s.env, vec![("GREETING".to_owned(), "hi".to_owned())]);
286        assert_eq!(s.remote_env, vec![("MODE".to_owned(), "dev".to_owned())]);
287        assert_eq!(s.on_create.len(), 3);
288        assert_eq!(s.on_create[0], Cmd::Shell("echo one".into()));
289        assert_eq!(s.ignored, vec!["features".to_owned(), "forwardPorts".to_owned()]);
290
291        let b = Spec::parse(r#"{"build": {"dockerfile": "Dockerfile", "context": "..", "args": {"V": "1"}}}"#, base, ws).unwrap();
292        let Image::Build { dockerfile, context, args } = b.image.clone() else { panic!("not a build") };
293        assert_eq!((dockerfile, context), (PathBuf::from("/w/.devcontainer/Dockerfile"), PathBuf::from("/w")));
294        assert_eq!(args.get("V").map(String::as_str), Some("1"));
295        assert!(b.describe(ws).contains(".devcontainer/Dockerfile"));
296
297        assert!(Spec::parse(r#"{"build": {"dockerfile": "../../etc/x"}}"#, base, ws).unwrap_err().contains("outside"));
298        assert!(Spec::parse(r#"{"dockerComposeFile": "c.yml"}"#, base, ws).unwrap_err().contains("dockerComposeFile"));
299        assert!(Spec::parse(r#"{"image": "--privileged"}"#, base, ws).is_err());
300        assert!(Spec::parse("[]", base, ws).is_err() && Spec::parse("{", base, ws).is_err());
301    }
302
303    #[test]
304    fn found_in_either_place() {
305        let d = tempfile::tempdir().unwrap();
306        assert_eq!(find(d.path()), None);
307        assert_eq!(Spec::for_workspace(d.path(), "python:3-slim").unwrap(), Spec::default_image("python:3-slim"));
308        std::fs::write(d.path().join(".devcontainer.json"), r#"{"image": "debian:stable-slim"}"#).unwrap();
309        assert_eq!(find(d.path()), Some(".devcontainer.json"));
310        std::fs::create_dir(d.path().join(".devcontainer")).unwrap();
311        std::fs::write(d.path().join(".devcontainer/devcontainer.json"), r#"{"image": "alpine"}"#).unwrap();
312        let s = Spec::for_workspace(d.path(), "x").unwrap();
313        assert_eq!((s.image, s.file), (Image::Pull("alpine".into()), Some(".devcontainer/devcontainer.json")));
314    }
315}