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
337async fn check_for_docker(use_podman: bool) -> Result<(), DevContainerError> {
338 let mut command = if use_podman {
339 util::command::new_smol_command("podman")
340 } else {
341 util::command::new_smol_command("docker")
342 };
343 command.arg("--version");
344
345 match command.output().await {
346 Ok(_) => Ok(()),
347 Err(e) => {
348 log::error!("Unable to find docker in $PATH: {:?}", e);
349 Err(DevContainerError::DockerNotAvailable)
350 }
351 }
352}
353
354async fn ensure_devcontainer_cli(
355 node_runtime: &NodeRuntime,
356) -> Result<(PathBuf, bool), DevContainerError> {
357 let mut command = util::command::new_smol_command(&dev_container_cli());
358 command.arg("--version");
359
360 if let Err(e) = command.output().await {
361 log::error!(
362 "Unable to find devcontainer CLI in $PATH. Checking for a zed installed version. Error: {:?}",
363 e
364 );
365
366 let Ok(node_runtime_path) = node_runtime.binary_path().await else {
367 return Err(DevContainerError::NodeRuntimeNotAvailable);
368 };
369
370 let datadir_cli_path = paths::devcontainer_dir()
371 .join("node_modules")
372 .join("@devcontainers")
373 .join("cli")
374 .join(format!("{}.js", &dev_container_cli()));
375
376 log::debug!(
377 "devcontainer not found in path, using local location: ${}",
378 datadir_cli_path.display()
379 );
380
381 let mut command =
382 util::command::new_smol_command(node_runtime_path.as_os_str().display().to_string());
383 command.arg(datadir_cli_path.display().to_string());
384 command.arg("--version");
385
386 match command.output().await {
387 Err(e) => log::error!(
388 "Unable to find devcontainer CLI in Data dir. Will try to install. Error: {:?}",
389 e
390 ),
391 Ok(output) => {
392 if output.status.success() {
393 log::info!("Found devcontainer CLI in Data dir");
394 return Ok((datadir_cli_path.clone(), false));
395 } else {
396 log::error!(
397 "Could not run devcontainer CLI from data_dir. Will try once more to install. Output: {:?}",
398 output
399 );
400 }
401 }
402 }
403
404 if let Err(e) = fs::create_dir_all(paths::devcontainer_dir()).await {
405 log::error!("Unable to create devcontainer directory. Error: {:?}", e);
406 return Err(DevContainerError::DevContainerCliNotAvailable);
407 }
408
409 if let Err(e) = node_runtime
410 .npm_install_packages(
411 &paths::devcontainer_dir(),
412 &[("@devcontainers/cli", "latest")],
413 )
414 .await
415 {
416 log::error!(
417 "Unable to install devcontainer CLI to data directory. Error: {:?}",
418 e
419 );
420 return Err(DevContainerError::DevContainerCliNotAvailable);
421 };
422
423 let mut command =
424 util::command::new_smol_command(node_runtime_path.as_os_str().display().to_string());
425 command.arg(datadir_cli_path.display().to_string());
426 command.arg("--version");
427 if let Err(e) = command.output().await {
428 log::error!(
429 "Unable to find devcontainer cli after NPM install. Error: {:?}",
430 e
431 );
432 Err(DevContainerError::DevContainerCliNotAvailable)
433 } else {
434 Ok((datadir_cli_path, false))
435 }
436 } else {
437 log::info!("Found devcontainer cli on $PATH, using it");
438 Ok((PathBuf::from(&dev_container_cli()), true))
439 }
440}
441
442async fn devcontainer_up(
443 path_to_cli: &PathBuf,
444 found_in_path: bool,
445 node_runtime: &NodeRuntime,
446 path: Arc<Path>,
447 config_path: Option<PathBuf>,
448 use_podman: bool,
449) -> Result<DevContainerUp, DevContainerError> {
450 let Ok(node_runtime_path) = node_runtime.binary_path().await else {
451 log::error!("Unable to find node runtime path");
452 return Err(DevContainerError::NodeRuntimeNotAvailable);
453 };
454
455 let mut command =
456 devcontainer_cli_command(path_to_cli, found_in_path, &node_runtime_path, use_podman);
457 command.arg("up");
458 command.arg("--workspace-folder");
459 command.arg(path.display().to_string());
460
461 if let Some(config) = config_path {
462 command.arg("--config");
463 command.arg(config.display().to_string());
464 }
465
466 log::info!("Running full devcontainer up command: {:?}", command);
467
468 match command.output().await {
469 Ok(output) => {
470 if output.status.success() {
471 let raw = String::from_utf8_lossy(&output.stdout);
472 parse_json_from_cli(&raw)
473 } else {
474 let message = format!(
475 "Non-success status running devcontainer up for workspace: out: {}, err: {}",
476 String::from_utf8_lossy(&output.stdout),
477 String::from_utf8_lossy(&output.stderr)
478 );
479
480 log::error!("{}", &message);
481 Err(DevContainerError::DevContainerUpFailed(message))
482 }
483 }
484 Err(e) => {
485 let message = format!("Error running devcontainer up: {:?}", e);
486 log::error!("{}", &message);
487 Err(DevContainerError::DevContainerUpFailed(message))
488 }
489 }
490}
491
492async fn devcontainer_read_configuration(
493 path_to_cli: &PathBuf,
494 found_in_path: bool,
495 node_runtime: &NodeRuntime,
496 path: &Arc<Path>,
497 config_path: Option<&PathBuf>,
498 use_podman: bool,
499) -> Result<DevContainerConfigurationOutput, DevContainerError> {
500 let Ok(node_runtime_path) = node_runtime.binary_path().await else {
501 log::error!("Unable to find node runtime path");
502 return Err(DevContainerError::NodeRuntimeNotAvailable);
503 };
504
505 let mut command =
506 devcontainer_cli_command(path_to_cli, found_in_path, &node_runtime_path, use_podman);
507 command.arg("read-configuration");
508 command.arg("--workspace-folder");
509 command.arg(path.display().to_string());
510
511 if let Some(config) = config_path {
512 command.arg("--config");
513 command.arg(config.display().to_string());
514 }
515
516 match command.output().await {
517 Ok(output) => {
518 if output.status.success() {
519 let raw = String::from_utf8_lossy(&output.stdout);
520 parse_json_from_cli(&raw)
521 } else {
522 let message = format!(
523 "Non-success status running devcontainer read-configuration for workspace: out: {:?}, err: {:?}",
524 String::from_utf8_lossy(&output.stdout),
525 String::from_utf8_lossy(&output.stderr)
526 );
527 log::error!("{}", &message);
528 Err(DevContainerError::DevContainerNotFound)
529 }
530 }
531 Err(e) => {
532 let message = format!("Error running devcontainer read-configuration: {:?}", e);
533 log::error!("{}", &message);
534 Err(DevContainerError::DevContainerNotFound)
535 }
536 }
537}
538
539async fn devcontainer_template_apply(
540 template: &DevContainerTemplate,
541 template_options: &HashMap<String, String>,
542 features_selected: &HashSet<DevContainerFeature>,
543 path_to_cli: &PathBuf,
544 found_in_path: bool,
545 node_runtime: &NodeRuntime,
546 path: &Arc<Path>,
547 use_podman: bool,
548) -> Result<DevContainerApply, DevContainerError> {
549 let Ok(node_runtime_path) = node_runtime.binary_path().await else {
550 log::error!("Unable to find node runtime path");
551 return Err(DevContainerError::NodeRuntimeNotAvailable);
552 };
553
554 let mut command =
555 devcontainer_cli_command(path_to_cli, found_in_path, &node_runtime_path, use_podman);
556
557 let Ok(serialized_options) = serde_json::to_string(template_options) else {
558 log::error!("Unable to serialize options for {:?}", template_options);
559 return Err(DevContainerError::DevContainerParseFailed);
560 };
561
562 command.arg("templates");
563 command.arg("apply");
564 command.arg("--workspace-folder");
565 command.arg(path.display().to_string());
566 command.arg("--template-id");
567 command.arg(format!(
568 "{}/{}",
569 template
570 .source_repository
571 .as_ref()
572 .unwrap_or(&String::from("")),
573 template.id
574 ));
575 command.arg("--template-args");
576 command.arg(serialized_options);
577 command.arg("--features");
578 command.arg(template_features_to_json(features_selected));
579
580 log::debug!("Running full devcontainer apply command: {:?}", command);
581
582 match command.output().await {
583 Ok(output) => {
584 if output.status.success() {
585 let raw = String::from_utf8_lossy(&output.stdout);
586 parse_json_from_cli(&raw)
587 } else {
588 let message = format!(
589 "Non-success status running devcontainer templates apply for workspace: out: {:?}, err: {:?}",
590 String::from_utf8_lossy(&output.stdout),
591 String::from_utf8_lossy(&output.stderr)
592 );
593
594 log::error!("{}", &message);
595 Err(DevContainerError::DevContainerTemplateApplyFailed(message))
596 }
597 }
598 Err(e) => {
599 let message = format!("Error running devcontainer templates apply: {:?}", e);
600 log::error!("{}", &message);
601 Err(DevContainerError::DevContainerTemplateApplyFailed(message))
602 }
603 }
604}
605// Try to parse directly first (newer versions output pure JSON)
606// If that fails, look for JSON start (older versions have plaintext prefix)
607fn parse_json_from_cli<T: serde::de::DeserializeOwned>(raw: &str) -> Result<T, DevContainerError> {
608 serde_json::from_str::<T>(&raw)
609 .or_else(|e| {
610 log::error!("Error parsing json: {} - will try to find json object in larger plaintext", e);
611 let json_start = raw
612 .find(|c| c == '{')
613 .ok_or_else(|| {
614 log::error!("No JSON found in devcontainer up output");
615 DevContainerError::DevContainerParseFailed
616 })?;
617
618 serde_json::from_str(&raw[json_start..]).map_err(|e| {
619 log::error!(
620 "Unable to parse JSON from devcontainer up output (starting at position {}), error: {:?}",
621 json_start,
622 e
623 );
624 DevContainerError::DevContainerParseFailed
625 })
626 })
627}
628
629fn devcontainer_cli_command(
630 path_to_cli: &PathBuf,
631 found_in_path: bool,
632 node_runtime_path: &PathBuf,
633 use_podman: bool,
634) -> Command {
635 let mut command = if found_in_path {
636 util::command::new_smol_command(path_to_cli.display().to_string())
637 } else {
638 let mut command =
639 util::command::new_smol_command(node_runtime_path.as_os_str().display().to_string());
640 command.arg(path_to_cli.display().to_string());
641 command
642 };
643
644 if use_podman {
645 command.arg("--docker-path");
646 command.arg("podman");
647 }
648 command
649}
650
651fn get_backup_project_name(remote_workspace_folder: &str, container_id: &str) -> String {
652 Path::new(remote_workspace_folder)
653 .file_name()
654 .and_then(|name| name.to_str())
655 .map(|string| string.to_string())
656 .unwrap_or_else(|| container_id.to_string())
657}
658
659fn project_directory(cx: &mut AsyncWindowContext) -> Option<Arc<Path>> {
660 let Some(workspace) = cx.window_handle().downcast::<Workspace>() else {
661 return None;
662 };
663
664 match workspace.update(cx, |workspace, _, cx| {
665 workspace.project().read(cx).active_project_directory(cx)
666 }) {
667 Ok(dir) => dir,
668 Err(e) => {
669 log::error!("Error getting project directory from workspace: {:?}", e);
670 None
671 }
672 }
673}
674
675fn template_features_to_json(features_selected: &HashSet<DevContainerFeature>) -> String {
676 let features_map = features_selected
677 .iter()
678 .map(|feature| {
679 let mut map = HashMap::new();
680 map.insert(
681 "id",
682 format!(
683 "{}/{}:{}",
684 feature
685 .source_repository
686 .as_ref()
687 .unwrap_or(&String::from("")),
688 feature.id,
689 feature.major_version()
690 ),
691 );
692 map
693 })
694 .collect::<Vec<HashMap<&str, String>>>();
695 serde_json::to_string(&features_map).unwrap()
696}
697
698#[cfg(test)]
699mod tests {
700 use crate::devcontainer_api::{DevContainerUp, parse_json_from_cli};
701
702 #[test]
703 fn should_parse_from_devcontainer_json() {
704 let json = r#"{"outcome":"success","containerId":"826abcac45afd412abff083ab30793daff2f3c8ce2c831df728baf39933cb37a","remoteUser":"vscode","remoteWorkspaceFolder":"/workspaces/zed"}"#;
705 let up: DevContainerUp = parse_json_from_cli(json).unwrap();
706 assert_eq!(up._outcome, "success");
707 assert_eq!(
708 up.container_id,
709 "826abcac45afd412abff083ab30793daff2f3c8ce2c831df728baf39933cb37a"
710 );
711 assert_eq!(up.remote_user, "vscode");
712 assert_eq!(up.remote_workspace_folder, "/workspaces/zed");
713
714 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.
715 {"outcome":"success","containerId":"826abcac45afd412abff083ab30793daff2f3c8ce2c831df728baf39933cb37a","remoteUser":"vscode","remoteWorkspaceFolder":"/workspaces/zed"}"#;
716 let up: DevContainerUp = parse_json_from_cli(json_in_plaintext).unwrap();
717 assert_eq!(up._outcome, "success");
718 assert_eq!(
719 up.container_id,
720 "826abcac45afd412abff083ab30793daff2f3c8ce2c831df728baf39933cb37a"
721 );
722 assert_eq!(up.remote_user, "vscode");
723 assert_eq!(up.remote_workspace_folder, "/workspaces/zed");
724 }
725}