1use std::{
2 collections::{HashMap, HashSet},
3 fmt::Display,
4 path::{Path, PathBuf},
5 sync::Arc,
6};
7
8use gpui::AsyncWindowContext;
9use node_runtime::NodeRuntime;
10use serde::Deserialize;
11use settings::{DevContainerConnection, Settings as _};
12use smol::{fs, process::Command};
13use util::rel_path::RelPath;
14use workspace::Workspace;
15
16use crate::{DevContainerFeature, DevContainerSettings, DevContainerTemplate};
17
18/// Represents a discovered devcontainer configuration
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct DevContainerConfig {
21 /// Display name for the configuration (subfolder name or "default")
22 pub name: String,
23 /// Relative path to the devcontainer.json file from the project root
24 pub config_path: PathBuf,
25}
26
27impl DevContainerConfig {
28 pub fn default_config() -> Self {
29 Self {
30 name: "default".to_string(),
31 config_path: PathBuf::from(".devcontainer/devcontainer.json"),
32 }
33 }
34}
35
36#[derive(Debug, Deserialize)]
37#[serde(rename_all = "camelCase")]
38struct DevContainerUp {
39 _outcome: String,
40 container_id: String,
41 remote_user: String,
42 remote_workspace_folder: String,
43}
44
45#[derive(Debug, Deserialize)]
46#[serde(rename_all = "camelCase")]
47pub(crate) struct DevContainerApply {
48 pub(crate) files: Vec<String>,
49}
50
51#[derive(Debug, Deserialize)]
52#[serde(rename_all = "camelCase")]
53pub(crate) struct DevContainerConfiguration {
54 name: Option<String>,
55}
56
57#[derive(Debug, Deserialize)]
58pub(crate) struct DevContainerConfigurationOutput {
59 configuration: DevContainerConfiguration,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum DevContainerError {
64 DockerNotAvailable,
65 DevContainerCliNotAvailable,
66 DevContainerTemplateApplyFailed(String),
67 DevContainerUpFailed(String),
68 DevContainerNotFound,
69 DevContainerParseFailed,
70 NodeRuntimeNotAvailable,
71 NotInValidProject,
72}
73
74impl Display for DevContainerError {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 write!(
77 f,
78 "{}",
79 match self {
80 DevContainerError::DockerNotAvailable =>
81 "docker CLI not found on $PATH".to_string(),
82 DevContainerError::DevContainerCliNotAvailable =>
83 "devcontainer CLI not found on path".to_string(),
84 DevContainerError::DevContainerUpFailed(_) => {
85 "DevContainer creation failed".to_string()
86 }
87 DevContainerError::DevContainerTemplateApplyFailed(_) => {
88 "DevContainer template apply failed".to_string()
89 }
90 DevContainerError::DevContainerNotFound =>
91 "No valid dev container definition found in project".to_string(),
92 DevContainerError::DevContainerParseFailed =>
93 "Failed to parse file .devcontainer/devcontainer.json".to_string(),
94 DevContainerError::NodeRuntimeNotAvailable =>
95 "Cannot find a valid node runtime".to_string(),
96 DevContainerError::NotInValidProject => "Not within a valid project".to_string(),
97 }
98 )
99 }
100}
101
102pub(crate) async fn read_devcontainer_configuration_for_project(
103 cx: &mut AsyncWindowContext,
104 node_runtime: &NodeRuntime,
105) -> Result<DevContainerConfigurationOutput, DevContainerError> {
106 let (path_to_devcontainer_cli, found_in_path) = ensure_devcontainer_cli(&node_runtime).await?;
107
108 let Some(directory) = project_directory(cx) else {
109 return Err(DevContainerError::NotInValidProject);
110 };
111
112 devcontainer_read_configuration(
113 &path_to_devcontainer_cli,
114 found_in_path,
115 node_runtime,
116 &directory,
117 None,
118 use_podman(cx),
119 )
120 .await
121}
122
123pub(crate) async fn apply_dev_container_template(
124 template: &DevContainerTemplate,
125 options_selected: &HashMap<String, String>,
126 features_selected: &HashSet<DevContainerFeature>,
127 cx: &mut AsyncWindowContext,
128 node_runtime: &NodeRuntime,
129) -> Result<DevContainerApply, DevContainerError> {
130 let (path_to_devcontainer_cli, found_in_path) = ensure_devcontainer_cli(&node_runtime).await?;
131
132 let Some(directory) = project_directory(cx) else {
133 return Err(DevContainerError::NotInValidProject);
134 };
135
136 devcontainer_template_apply(
137 template,
138 options_selected,
139 features_selected,
140 &path_to_devcontainer_cli,
141 found_in_path,
142 node_runtime,
143 &directory,
144 false, // devcontainer template apply does not use --docker-path option
145 )
146 .await
147}
148
149fn use_podman(cx: &mut AsyncWindowContext) -> bool {
150 cx.update(|_, cx| DevContainerSettings::get_global(cx).use_podman)
151 .unwrap_or(false)
152}
153
154/// Finds all available devcontainer configurations in the project.
155///
156/// This function scans for:
157/// 1. `.devcontainer/devcontainer.json` (the default location)
158/// 2. `.devcontainer/<subfolder>/devcontainer.json` (named configurations)
159///
160/// Returns a list of found configurations, or an empty list if none are found.
161pub fn find_devcontainer_configs(cx: &mut AsyncWindowContext) -> Vec<DevContainerConfig> {
162 let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
163 log::debug!("find_devcontainer_configs: No workspace found");
164 return Vec::new();
165 };
166
167 let Ok(configs) = workspace.update(cx, |workspace, _, cx| {
168 let project = workspace.project().read(cx);
169
170 let worktree = project
171 .visible_worktrees(cx)
172 .find_map(|tree| tree.read(cx).root_entry()?.is_dir().then_some(tree));
173
174 let Some(worktree) = worktree else {
175 log::debug!("find_devcontainer_configs: No worktree found");
176 return Vec::new();
177 };
178
179 let worktree = worktree.read(cx);
180 let mut configs = Vec::new();
181
182 let devcontainer_path = RelPath::unix(".devcontainer").expect("valid path");
183
184 let Some(devcontainer_entry) = worktree.entry_for_path(devcontainer_path) else {
185 log::debug!("find_devcontainer_configs: .devcontainer directory not found in worktree");
186 return Vec::new();
187 };
188
189 if !devcontainer_entry.is_dir() {
190 log::debug!("find_devcontainer_configs: .devcontainer is not a directory");
191 return Vec::new();
192 }
193
194 log::debug!("find_devcontainer_configs: Scanning .devcontainer directory");
195 let devcontainer_json_path =
196 RelPath::unix(".devcontainer/devcontainer.json").expect("valid path");
197 for entry in worktree.child_entries(devcontainer_path) {
198 log::debug!(
199 "find_devcontainer_configs: Found entry: {:?}, is_file: {}, is_dir: {}",
200 entry.path.as_unix_str(),
201 entry.is_file(),
202 entry.is_dir()
203 );
204
205 if entry.is_file() && entry.path.as_ref() == devcontainer_json_path {
206 log::debug!("find_devcontainer_configs: Found default devcontainer.json");
207 configs.push(DevContainerConfig::default_config());
208 } else if entry.is_dir() {
209 let subfolder_name = entry
210 .path
211 .file_name()
212 .map(|n| n.to_string())
213 .unwrap_or_default();
214
215 let config_json_path = format!("{}/devcontainer.json", entry.path.as_unix_str());
216 if let Ok(rel_config_path) = RelPath::unix(&config_json_path) {
217 if worktree.entry_for_path(rel_config_path).is_some() {
218 log::debug!(
219 "find_devcontainer_configs: Found config in subfolder: {}",
220 subfolder_name
221 );
222 configs.push(DevContainerConfig {
223 name: subfolder_name,
224 config_path: PathBuf::from(&config_json_path),
225 });
226 } else {
227 log::debug!(
228 "find_devcontainer_configs: Subfolder {} has no devcontainer.json",
229 subfolder_name
230 );
231 }
232 }
233 }
234 }
235
236 log::info!(
237 "find_devcontainer_configs: Found {} configurations",
238 configs.len()
239 );
240
241 configs.sort_by(|a, b| {
242 if a.name == "default" {
243 std::cmp::Ordering::Less
244 } else if b.name == "default" {
245 std::cmp::Ordering::Greater
246 } else {
247 a.name.cmp(&b.name)
248 }
249 });
250
251 configs
252 }) else {
253 log::debug!("find_devcontainer_configs: Failed to update workspace");
254 return Vec::new();
255 };
256
257 configs
258}
259
260pub async fn start_dev_container_with_config(
261 cx: &mut AsyncWindowContext,
262 node_runtime: NodeRuntime,
263 config: Option<DevContainerConfig>,
264) -> Result<(DevContainerConnection, String), DevContainerError> {
265 let use_podman = use_podman(cx);
266 check_for_docker(use_podman).await?;
267
268 let (path_to_devcontainer_cli, found_in_path) = ensure_devcontainer_cli(&node_runtime).await?;
269
270 let Some(directory) = project_directory(cx) else {
271 return Err(DevContainerError::NotInValidProject);
272 };
273
274 let config_path = config.map(|c| directory.join(&c.config_path));
275
276 match devcontainer_up(
277 &path_to_devcontainer_cli,
278 found_in_path,
279 &node_runtime,
280 directory.clone(),
281 config_path.clone(),
282 use_podman,
283 )
284 .await
285 {
286 Ok(DevContainerUp {
287 container_id,
288 remote_workspace_folder,
289 remote_user,
290 ..
291 }) => {
292 let project_name = match devcontainer_read_configuration(
293 &path_to_devcontainer_cli,
294 found_in_path,
295 &node_runtime,
296 &directory,
297 config_path.as_ref(),
298 use_podman,
299 )
300 .await
301 {
302 Ok(DevContainerConfigurationOutput {
303 configuration:
304 DevContainerConfiguration {
305 name: Some(project_name),
306 },
307 }) => project_name,
308 _ => get_backup_project_name(&remote_workspace_folder, &container_id),
309 };
310
311 let connection = DevContainerConnection {
312 name: project_name,
313 container_id: container_id,
314 use_podman,
315 remote_user,
316 };
317
318 Ok((connection, remote_workspace_folder))
319 }
320 Err(err) => {
321 let message = format!("Failed with nested error: {}", err);
322 Err(DevContainerError::DevContainerUpFailed(message))
323 }
324 }
325}
326
327#[cfg(not(target_os = "windows"))]
328fn dev_container_cli() -> String {
329 "devcontainer".to_string()
330}
331
332#[cfg(target_os = "windows")]
333fn dev_container_cli() -> String {
334 "devcontainer.cmd".to_string()
335}
336
337fn dev_container_script() -> String {
338 "devcontainer.js".to_string()
339}
340
341async fn check_for_docker(use_podman: bool) -> Result<(), DevContainerError> {
342 let mut command = if use_podman {
343 util::command::new_smol_command("podman")
344 } else {
345 util::command::new_smol_command("docker")
346 };
347 command.arg("--version");
348
349 match command.output().await {
350 Ok(_) => Ok(()),
351 Err(e) => {
352 log::error!("Unable to find docker in $PATH: {:?}", e);
353 Err(DevContainerError::DockerNotAvailable)
354 }
355 }
356}
357
358async fn ensure_devcontainer_cli(
359 node_runtime: &NodeRuntime,
360) -> Result<(PathBuf, bool), DevContainerError> {
361 let mut command = util::command::new_smol_command(&dev_container_cli());
362 command.arg("--version");
363
364 if let Err(e) = command.output().await {
365 log::error!(
366 "Unable to find devcontainer CLI in $PATH. Checking for a zed installed version. Error: {:?}",
367 e
368 );
369
370 let Ok(node_runtime_path) = node_runtime.binary_path().await else {
371 return Err(DevContainerError::NodeRuntimeNotAvailable);
372 };
373
374 let datadir_cli_path = paths::devcontainer_dir()
375 .join("node_modules")
376 .join("@devcontainers")
377 .join("cli")
378 .join(&dev_container_script());
379
380 log::debug!(
381 "devcontainer not found in path, using local location: ${}",
382 datadir_cli_path.display()
383 );
384
385 let mut command =
386 util::command::new_smol_command(node_runtime_path.as_os_str().display().to_string());
387 command.arg(datadir_cli_path.display().to_string());
388 command.arg("--version");
389
390 match command.output().await {
391 Err(e) => log::error!(
392 "Unable to find devcontainer CLI in Data dir. Will try to install. Error: {:?}",
393 e
394 ),
395 Ok(output) => {
396 if output.status.success() {
397 log::info!("Found devcontainer CLI in Data dir");
398 return Ok((datadir_cli_path.clone(), false));
399 } else {
400 log::error!(
401 "Could not run devcontainer CLI from data_dir. Will try once more to install. Output: {:?}",
402 output
403 );
404 }
405 }
406 }
407
408 if let Err(e) = fs::create_dir_all(paths::devcontainer_dir()).await {
409 log::error!("Unable to create devcontainer directory. Error: {:?}", e);
410 return Err(DevContainerError::DevContainerCliNotAvailable);
411 }
412
413 if let Err(e) = node_runtime
414 .npm_install_packages(
415 &paths::devcontainer_dir(),
416 &[("@devcontainers/cli", "latest")],
417 )
418 .await
419 {
420 log::error!(
421 "Unable to install devcontainer CLI to data directory. Error: {:?}",
422 e
423 );
424 return Err(DevContainerError::DevContainerCliNotAvailable);
425 };
426
427 let mut command =
428 util::command::new_smol_command(node_runtime_path.as_os_str().display().to_string());
429 command.arg(datadir_cli_path.display().to_string());
430 command.arg("--version");
431 if let Err(e) = command.output().await {
432 log::error!(
433 "Unable to find devcontainer cli after NPM install. Error: {:?}",
434 e
435 );
436 Err(DevContainerError::DevContainerCliNotAvailable)
437 } else {
438 Ok((datadir_cli_path, false))
439 }
440 } else {
441 log::info!("Found devcontainer cli on $PATH, using it");
442 Ok((PathBuf::from(&dev_container_cli()), true))
443 }
444}
445
446async fn devcontainer_up(
447 path_to_cli: &PathBuf,
448 found_in_path: bool,
449 node_runtime: &NodeRuntime,
450 path: Arc<Path>,
451 config_path: Option<PathBuf>,
452 use_podman: bool,
453) -> Result<DevContainerUp, DevContainerError> {
454 let Ok(node_runtime_path) = node_runtime.binary_path().await else {
455 log::error!("Unable to find node runtime path");
456 return Err(DevContainerError::NodeRuntimeNotAvailable);
457 };
458
459 let mut command =
460 devcontainer_cli_command(path_to_cli, found_in_path, &node_runtime_path, use_podman);
461 command.arg("up");
462 command.arg("--workspace-folder");
463 command.arg(path.display().to_string());
464
465 if let Some(config) = config_path {
466 command.arg("--config");
467 command.arg(config.display().to_string());
468 }
469
470 log::info!("Running full devcontainer up command: {:?}", command);
471
472 match command.output().await {
473 Ok(output) => {
474 if output.status.success() {
475 let raw = String::from_utf8_lossy(&output.stdout);
476 parse_json_from_cli(&raw)
477 } else {
478 let message = format!(
479 "Non-success status running devcontainer up for workspace: out: {}, err: {}",
480 String::from_utf8_lossy(&output.stdout),
481 String::from_utf8_lossy(&output.stderr)
482 );
483
484 log::error!("{}", &message);
485 Err(DevContainerError::DevContainerUpFailed(message))
486 }
487 }
488 Err(e) => {
489 let message = format!("Error running devcontainer up: {:?}", e);
490 log::error!("{}", &message);
491 Err(DevContainerError::DevContainerUpFailed(message))
492 }
493 }
494}
495
496async fn devcontainer_read_configuration(
497 path_to_cli: &PathBuf,
498 found_in_path: bool,
499 node_runtime: &NodeRuntime,
500 path: &Arc<Path>,
501 config_path: Option<&PathBuf>,
502 use_podman: bool,
503) -> Result<DevContainerConfigurationOutput, DevContainerError> {
504 let Ok(node_runtime_path) = node_runtime.binary_path().await else {
505 log::error!("Unable to find node runtime path");
506 return Err(DevContainerError::NodeRuntimeNotAvailable);
507 };
508
509 let mut command =
510 devcontainer_cli_command(path_to_cli, found_in_path, &node_runtime_path, use_podman);
511 command.arg("read-configuration");
512 command.arg("--workspace-folder");
513 command.arg(path.display().to_string());
514
515 if let Some(config) = config_path {
516 command.arg("--config");
517 command.arg(config.display().to_string());
518 }
519
520 match command.output().await {
521 Ok(output) => {
522 if output.status.success() {
523 let raw = String::from_utf8_lossy(&output.stdout);
524 parse_json_from_cli(&raw)
525 } else {
526 let message = format!(
527 "Non-success status running devcontainer read-configuration for workspace: out: {:?}, err: {:?}",
528 String::from_utf8_lossy(&output.stdout),
529 String::from_utf8_lossy(&output.stderr)
530 );
531 log::error!("{}", &message);
532 Err(DevContainerError::DevContainerNotFound)
533 }
534 }
535 Err(e) => {
536 let message = format!("Error running devcontainer read-configuration: {:?}", e);
537 log::error!("{}", &message);
538 Err(DevContainerError::DevContainerNotFound)
539 }
540 }
541}
542
543async fn devcontainer_template_apply(
544 template: &DevContainerTemplate,
545 template_options: &HashMap<String, String>,
546 features_selected: &HashSet<DevContainerFeature>,
547 path_to_cli: &PathBuf,
548 found_in_path: bool,
549 node_runtime: &NodeRuntime,
550 path: &Arc<Path>,
551 use_podman: bool,
552) -> Result<DevContainerApply, DevContainerError> {
553 let Ok(node_runtime_path) = node_runtime.binary_path().await else {
554 log::error!("Unable to find node runtime path");
555 return Err(DevContainerError::NodeRuntimeNotAvailable);
556 };
557
558 let mut command =
559 devcontainer_cli_command(path_to_cli, found_in_path, &node_runtime_path, use_podman);
560
561 let Ok(serialized_options) = serde_json::to_string(template_options) else {
562 log::error!("Unable to serialize options for {:?}", template_options);
563 return Err(DevContainerError::DevContainerParseFailed);
564 };
565
566 command.arg("templates");
567 command.arg("apply");
568 command.arg("--workspace-folder");
569 command.arg(path.display().to_string());
570 command.arg("--template-id");
571 command.arg(format!(
572 "{}/{}",
573 template
574 .source_repository
575 .as_ref()
576 .unwrap_or(&String::from("")),
577 template.id
578 ));
579 command.arg("--template-args");
580 command.arg(serialized_options);
581 command.arg("--features");
582 command.arg(template_features_to_json(features_selected));
583
584 log::debug!("Running full devcontainer apply command: {:?}", command);
585
586 match command.output().await {
587 Ok(output) => {
588 if output.status.success() {
589 let raw = String::from_utf8_lossy(&output.stdout);
590 parse_json_from_cli(&raw)
591 } else {
592 let message = format!(
593 "Non-success status running devcontainer templates apply for workspace: out: {:?}, err: {:?}",
594 String::from_utf8_lossy(&output.stdout),
595 String::from_utf8_lossy(&output.stderr)
596 );
597
598 log::error!("{}", &message);
599 Err(DevContainerError::DevContainerTemplateApplyFailed(message))
600 }
601 }
602 Err(e) => {
603 let message = format!("Error running devcontainer templates apply: {:?}", e);
604 log::error!("{}", &message);
605 Err(DevContainerError::DevContainerTemplateApplyFailed(message))
606 }
607 }
608}
609// Try to parse directly first (newer versions output pure JSON)
610// If that fails, look for JSON start (older versions have plaintext prefix)
611fn parse_json_from_cli<T: serde::de::DeserializeOwned>(raw: &str) -> Result<T, DevContainerError> {
612 serde_json::from_str::<T>(&raw)
613 .or_else(|e| {
614 log::error!("Error parsing json: {} - will try to find json object in larger plaintext", e);
615 let json_start = raw
616 .find(|c| c == '{')
617 .ok_or_else(|| {
618 log::error!("No JSON found in devcontainer up output");
619 DevContainerError::DevContainerParseFailed
620 })?;
621
622 serde_json::from_str(&raw[json_start..]).map_err(|e| {
623 log::error!(
624 "Unable to parse JSON from devcontainer up output (starting at position {}), error: {:?}",
625 json_start,
626 e
627 );
628 DevContainerError::DevContainerParseFailed
629 })
630 })
631}
632
633fn devcontainer_cli_command(
634 path_to_cli: &PathBuf,
635 found_in_path: bool,
636 node_runtime_path: &PathBuf,
637 use_podman: bool,
638) -> Command {
639 let mut command = if found_in_path {
640 util::command::new_smol_command(path_to_cli.display().to_string())
641 } else {
642 let mut command =
643 util::command::new_smol_command(node_runtime_path.as_os_str().display().to_string());
644 command.arg(path_to_cli.display().to_string());
645 command
646 };
647
648 if use_podman {
649 command.arg("--docker-path");
650 command.arg("podman");
651 }
652 command
653}
654
655fn get_backup_project_name(remote_workspace_folder: &str, container_id: &str) -> String {
656 Path::new(remote_workspace_folder)
657 .file_name()
658 .and_then(|name| name.to_str())
659 .map(|string| string.to_string())
660 .unwrap_or_else(|| container_id.to_string())
661}
662
663fn project_directory(cx: &mut AsyncWindowContext) -> Option<Arc<Path>> {
664 let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
665 return None;
666 };
667
668 match workspace.update(cx, |workspace, _, cx| {
669 workspace.project().read(cx).active_project_directory(cx)
670 }) {
671 Ok(dir) => dir,
672 Err(e) => {
673 log::error!("Error getting project directory from workspace: {:?}", e);
674 None
675 }
676 }
677}
678
679fn template_features_to_json(features_selected: &HashSet<DevContainerFeature>) -> String {
680 let features_map = features_selected
681 .iter()
682 .map(|feature| {
683 let mut map = HashMap::new();
684 map.insert(
685 "id",
686 format!(
687 "{}/{}:{}",
688 feature
689 .source_repository
690 .as_ref()
691 .unwrap_or(&String::from("")),
692 feature.id,
693 feature.major_version()
694 ),
695 );
696 map
697 })
698 .collect::<Vec<HashMap<&str, String>>>();
699 serde_json::to_string(&features_map).unwrap()
700}
701
702#[cfg(test)]
703mod tests {
704 use crate::devcontainer_api::{DevContainerUp, parse_json_from_cli};
705
706 #[test]
707 fn should_parse_from_devcontainer_json() {
708 let json = r#"{"outcome":"success","containerId":"826abcac45afd412abff083ab30793daff2f3c8ce2c831df728baf39933cb37a","remoteUser":"vscode","remoteWorkspaceFolder":"/workspaces/zed"}"#;
709 let up: DevContainerUp = parse_json_from_cli(json).unwrap();
710 assert_eq!(up._outcome, "success");
711 assert_eq!(
712 up.container_id,
713 "826abcac45afd412abff083ab30793daff2f3c8ce2c831df728baf39933cb37a"
714 );
715 assert_eq!(up.remote_user, "vscode");
716 assert_eq!(up.remote_workspace_folder, "/workspaces/zed");
717
718 let json_in_plaintext = r#"[2026-01-22T16:19:08.802Z] @devcontainers/cli 0.80.1. Node.js v22.21.1. darwin 24.6.0 arm64.
719 {"outcome":"success","containerId":"826abcac45afd412abff083ab30793daff2f3c8ce2c831df728baf39933cb37a","remoteUser":"vscode","remoteWorkspaceFolder":"/workspaces/zed"}"#;
720 let up: DevContainerUp = parse_json_from_cli(json_in_plaintext).unwrap();
721 assert_eq!(up._outcome, "success");
722 assert_eq!(
723 up.container_id,
724 "826abcac45afd412abff083ab30793daff2f3c8ce2c831df728baf39933cb37a"
725 );
726 assert_eq!(up.remote_user, "vscode");
727 assert_eq!(up.remote_workspace_folder, "/workspaces/zed");
728 }
729}