Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,28 +194,40 @@ command = "claude"
# Ceiling for `devcontainer up`, in seconds.
up_timeout_secs = 300

# Extra arguments appended to every `devcontainer up`.
up_args = ["--log-level", "debug"]

[repos."/home/you/workspace/foo"]
enabled = "auto" # "auto" (default) | "true" | "false"
config = ".devcontainer/alt/devcontainer.json" # repo-relative
shell = "/bin/zsh" # default: the container user's login shell
env = ["ANTHROPIC_BASE_URL=http://proxy:8080"] # passed as `docker exec -e`
up_args = ["--mount", "type=bind,source=/data,target=/data"] # appended after the global ones
```

| Setting | Meaning |
|---|---|
| `command` | Payload for the `command` pane; default `claude` |
| `up_timeout_secs` | Bring-up timeout in seconds; default `300` |
| `up_args` (global) | Extra arguments appended to `devcontainer up` for every repository |
| `enabled = "auto"` | Require a Dev Container config at a standard or explicitly configured path |
| `enabled = "true"` | Skip detection entirely and let `devcontainer up` decide what is valid |
| `enabled = "false"` | Refuse to open container panes for that repository |
| `config` | Alternate repo-relative `devcontainer.json` path |
| `shell` | Shell to exec into, overriding the one probed from the container |
| `env` | `KEY=value` assignments passed to `docker exec -e` |
| `up_args` (per repo) | Extra arguments appended to `devcontainer up` after the global `up_args` |

An `env` entry that is not `KEY=value` is dropped with a warning rather than
forwarded: `docker exec -e NAME` with no `=` exports the *host's* variable of
that name into the container, which is never what the setting asked for.

`up_args` is an array of separate arguments, not a shell string: write `["--log-level", "debug"]`, not `["--log-level debug"]`.
Each entry is passed as-is, with no shell expansion.
An `up_args` list that contains a non-string, an empty string, or one of `--workspace-folder`, `--config`, or `--id-label` is ignored as a whole with a warning.
The reserved flags' camelCase aliases (`--workspaceFolder`, `--idLabel`) and `--flag=value` forms are rejected too.
The plugin sets the first two itself, and `--id-label` would replace the labels it uses to find and stop the container.

Under `auto`, detection checks, in order:

```text
Expand Down
133 changes: 133 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use crate::error::Error;
pub const DEFAULT_COMMAND: &str = "claude";
pub const DEFAULT_UP_TIMEOUT_SECS: u64 = 300;

const RESERVED_UP_FLAGS: &[&str] = &["--workspace-folder", "--config", "--id-label"];

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Enabled {
Auto,
Expand All @@ -24,6 +26,7 @@ pub struct RepoConfig {
/// devcontainer.json's `remoteEnv`, which a plain `docker exec` does not
/// apply and which this plugin deliberately does not parse.
pub env: Vec<String>,
pub up_args: Vec<String>,
}

impl Default for RepoConfig {
Expand All @@ -33,6 +36,7 @@ impl Default for RepoConfig {
config: None,
shell: None,
env: Vec::new(),
up_args: Vec::new(),
}
}
}
Expand All @@ -41,6 +45,7 @@ impl Default for RepoConfig {
pub struct Config {
pub command: String,
pub up_timeout_secs: u64,
pub up_args: Vec<String>,
pub warnings: Vec<String>,
repos: BTreeMap<PathBuf, RepoConfig>,
}
Expand All @@ -50,6 +55,7 @@ impl Config {
Config {
command: DEFAULT_COMMAND.to_string(),
up_timeout_secs: DEFAULT_UP_TIMEOUT_SECS,
up_args: Vec::new(),
warnings: Vec::new(),
repos: BTreeMap::new(),
}
Expand All @@ -68,6 +74,10 @@ impl Config {
}
RepoConfig::default()
}

pub fn up_args(&self, rc: &RepoConfig) -> Vec<String> {
self.up_args.iter().chain(&rc.up_args).cloned().collect()
}
}

pub fn load() -> Result<Config, Error> {
Expand Down Expand Up @@ -158,6 +168,11 @@ pub fn parse(text: &str) -> Config {
.warnings
.push("`up_timeout_secs` must be a positive integer".into()),
},
"up_args" => {
if let Some(args) = parse_up_args("`up_args`", &value, &mut cfg) {
cfg.up_args = args;
}
}
"repos" => parse_repos(value, &mut cfg),
other => cfg
.warnings
Expand Down Expand Up @@ -202,6 +217,13 @@ fn parse_repos(value: toml::Value, cfg: &mut Config) {
.push(format!("repos.\"{root}\".shell must be a non-empty string")),
},
"env" => parse_repo_env(root, val, &mut rc, cfg),
"up_args" => {
if let Some(args) =
parse_up_args(&format!("repos.\"{root}\".up_args"), val, cfg)
{
rc.up_args = args;
}
}
other => cfg
.warnings
.push(format!("unknown key repos.\"{root}\".{other} ignored")),
Expand All @@ -211,6 +233,43 @@ fn parse_repos(value: toml::Value, cfg: &mut Config) {
}
}

fn parse_up_args(label: &str, value: &toml::Value, cfg: &mut Config) -> Option<Vec<String>> {
let invalid = |cfg: &mut Config| {
cfg.warnings.push(format!(
"{label} ignored; expected an array of non-empty strings"
));
None
};
let Some(items) = value.as_array() else {
return invalid(cfg);
};
let mut args = Vec::with_capacity(items.len());
for item in items {
match item.as_str() {
Some(s) if !s.is_empty() => args.push(s.to_string()),
_ => return invalid(cfg),
}
}
if let Some(flag) = args.iter().find_map(|a| reserved_up_flag(a)) {
cfg.warnings.push(format!(
"{label} ignored; `{flag}` is managed by herdr-devcontainer"
));
return None;
}
Some(args)
}

fn reserved_up_flag(arg: &str) -> Option<&'static str> {
let name = arg.split_once('=').map_or(arg, |(name, _)| name);
// The CLI's yargs parser accepts camelCase aliases for dashed options.
let name = match name {
"--workspaceFolder" => "--workspace-folder",
"--idLabel" => "--id-label",
name => name,
};
RESERVED_UP_FLAGS.iter().copied().find(|flag| name == *flag)
}

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/// `env` entries reach `docker exec -e` verbatim, so a malformed one is
/// dropped with a warning rather than passed on: `-e` with no `=` tells docker
/// to *forward the host's* variable of that name, which would silently leak
Expand Down Expand Up @@ -322,6 +381,80 @@ mod tests {
assert_eq!(cfg.warnings.len(), 1);
}

#[test]
fn up_args_parse_globally_and_per_repo() {
let cfg = parse(
r#"
up_args = ["--build-no-cache"]

[repos."/x/repo"]
up_args = ["--mount", "type=bind,source=/a,target=/b"]
"#,
);
assert!(cfg.warnings.is_empty(), "{:?}", cfg.warnings);
let rc = cfg.repo(Path::new("/x/repo"));
assert_eq!(
cfg.up_args(&rc),
vec![
"--build-no-cache".to_string(),
"--mount".to_string(),
"type=bind,source=/a,target=/b".to_string(),
]
);
let other = cfg.repo(Path::new("/elsewhere"));
assert_eq!(cfg.up_args(&other), vec!["--build-no-cache".to_string()]);
}

#[test]
fn up_args_with_a_bad_entry_are_dropped_whole() {
let cfg = parse("up_args = [\"--mount\", 1]\n");
assert!(cfg.up_args.is_empty());
assert_eq!(cfg.warnings.len(), 1);

let cfg = parse("up_args = \"--build-no-cache\"\n");
assert!(cfg.up_args.is_empty());
assert_eq!(cfg.warnings.len(), 1);
}

#[test]
fn up_args_naming_a_reserved_flag_are_dropped_whole() {
for flag in [
"--workspace-folder",
"--workspaceFolder",
"--config",
"--id-label",
"--idLabel",
] {
for suffix in ["", "=/x"] {
let arg = format!("{flag}{suffix}");
for scope in ["", "[repos.\"/x/repo\"]\n"] {
let cfg = parse(&format!(
"{scope}up_args = [\"--build-no-cache\", \"{arg}\"]\n"
));
let rc = cfg.repo(Path::new("/x/repo"));
assert!(cfg.up_args(&rc).is_empty(), "{scope}{arg}");
assert_eq!(cfg.warnings.len(), 1, "{scope}{arg}");
}
}
}
}

#[test]
fn up_args_with_similar_flag_names_are_preserved() {
let cfg = parse(
"up_args = [\"--configuration\", \"--workspaceFolderExtra=/x\", \"--idLabelExtra=x=y\"]\n",
);
assert!(cfg.warnings.is_empty());
assert_eq!(
cfg.up_args,
[
"--configuration",
"--workspaceFolderExtra=/x",
"--idLabelExtra=x=y"
]
);
}

#[test]
fn unknown_keys_warn_but_do_not_fail() {
let cfg = parse("command = \"claude\"\nshiny = true\n");
Expand Down
1 change: 1 addition & 0 deletions src/pane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub fn run_pane(shell: bool) -> Result<(), Error> {
&devcontainer_bin,
&repo_root,
detection.config_arg.as_deref(),
&cfg.up_args(&repo_cfg),
Duration::from_secs(cfg.up_timeout_secs),
)?
};
Expand Down
37 changes: 35 additions & 2 deletions src/up.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub fn up_argv(
devcontainer_bin: &Path,
repo_root: &Path,
config_arg: Option<&Path>,
extra_args: &[String],
) -> Vec<String> {
let mut argv = vec![
devcontainer_bin.display().to_string(),
Expand All @@ -34,6 +35,7 @@ pub fn up_argv(
argv.push("--config".to_string());
argv.push(cfg.display().to_string());
}
argv.extend(extra_args.iter().cloned());
argv
}

Expand Down Expand Up @@ -70,10 +72,11 @@ pub fn bring_up(
devcontainer_bin: &Path,
repo_root: &Path,
config_arg: Option<&Path>,
extra_args: &[String],
timeout: Duration,
) -> Result<UpResult, Error> {
eprintln!("bringing up dev container for {} ...", repo_root.display());
let argv = up_argv(devcontainer_bin, repo_root, config_arg);
let argv = up_argv(devcontainer_bin, repo_root, config_arg, extra_args);
let res = run(&argv, timeout, StderrMode::Inherit)?;
if res.timed_out {
return Err(Error::UpTimeout {
Expand All @@ -99,7 +102,12 @@ mod tests {

#[test]
fn argv_without_custom_config() {
let argv = up_argv(Path::new("/usr/bin/devcontainer"), Path::new("/r"), None);
let argv = up_argv(
Path::new("/usr/bin/devcontainer"),
Path::new("/r"),
None,
&[],
);
assert_eq!(
argv,
vec!["/usr/bin/devcontainer", "up", "--workspace-folder", "/r"]
Expand All @@ -112,13 +120,38 @@ mod tests {
Path::new("devcontainer"),
Path::new("/r"),
Some(Path::new("/r/alt.json")),
&[],
);
assert_eq!(
argv[4..],
["--config".to_string(), "/r/alt.json".to_string()]
);
}

#[test]
fn argv_appends_extra_args_last() {
let argv = up_argv(
Path::new("devcontainer"),
Path::new("/r"),
Some(Path::new("/r/alt.json")),
&[
"--build-no-cache".to_string(),
"--log-level".to_string(),
"debug".to_string(),
],
);
assert_eq!(
argv[4..],
[
"--config",
"/r/alt.json",
"--build-no-cache",
"--log-level",
"debug"
]
);
}

#[test]
fn parses_a_success_line() {
let up = parse_up_output(OK).unwrap();
Expand Down
10 changes: 8 additions & 2 deletions tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,14 @@ fn bring_up_exec_and_stop_roundtrip() {
let repo = fixture_repo(tmp.path());
let _cleanup = StopFixtureContainer { repo: repo.clone() };

let result = up::bring_up(&devcontainer_bin, &repo, None, Duration::from_secs(300))
.expect("devcontainer up");
let result = up::bring_up(
&devcontainer_bin,
&repo,
None,
&[],
Duration::from_secs(300),
)
.expect("devcontainer up");
assert!(!result.container_id.is_empty());
assert!(result.remote_workspace_folder.starts_with('/'));

Expand Down
Loading