Replace Python devcontainer generator with Go CLI

This commit is contained in:
Fabio Scotto di Santolo
2026-11-15 10:18:22 +00:00
parent 59160abf0d
commit e2370ec91d
10 changed files with 532 additions and 224 deletions

View File

@@ -606,9 +606,9 @@ validated exports of older historical data will use a dedicated Atlas NFS datase
data, and MFA state were removed with the operator's explicit authorization. data, and MFA state were removed with the operator's explicit authorization.
## Project Devcontainer Generator ## Project Devcontainer Generator
- `scripts/devcontainer.py` generates standalone per-project language configurations; - `cmd/devcontainer/` generates standalone per-project language configurations;
it does not replace existing deadalus ecaas/cdp provisioning or remove host tools. it does not replace existing deadalus ecaas/cdp provisioning or remove host tools.
- Keep shared Git/agent behavior documented in `docs/project-devcontainers.md`. - Keep shared Git/agent behavior documented in `docs/project-devcontainers.md`.
- Focused validation: `python3 -m unittest discover -s tests -p test_devcontainer.py -v`. - Focused validation: `go -C cmd/devcontainer test ./...`.
- Real engine builds, host credential forwarding and Fedora SELinux/Podman checks - Real engine builds, host credential forwarding and Fedora SELinux/Podman checks
require target-host validation; do not report generator tests as runtime evidence. require target-host validation; do not report generator tests as runtime evidence.

View File

@@ -897,6 +897,6 @@ The legacy `void` and `desktop` groups remain compatibility parents, so hosts in
## Project devcontainer generator ## Project devcontainer generator
Generate a reusable language environment for an existing project with Generate a reusable language environment for an existing project with
`python3 scripts/devcontainer.py ~/src/project --language python --agents codex,cline`. `devcontainer ~/src/project --language python --agents codex,cline`.
Git and selected coding-agent configuration are shared from the development host. Git and selected coding-agent configuration are shared from the development host.
See [profiles, host requirements and validation](docs/project-devcontainers.md). See [profiles, host requirements and validation](docs/project-devcontainers.md).

View File

@@ -0,0 +1,11 @@
RUN apt-get update \
&& arch="$(dpkg --print-architecture)" \
&& case "$arch" in \
amd64) sha256=ea4f0222950ee750a3d38dd80d03bce4cee07a3f63928fc47548383bcaf23093 ;; \
arm64) sha256=0edc36cf514f1bd84becac3e94ee8ae9f8818c6a1f99f7b2ee67b362afa253d3 ;; \
*) echo "Unsupported architecture for delta: $arch" >&2; exit 1 ;; \
esac \
&& curl -fsSL --retry 3 "https://github.com/dandavison/delta/releases/download/0.19.2/git-delta_0.19.2_${arch}.deb" -o /tmp/git-delta.deb \
&& echo "$sha256 /tmp/git-delta.deb" | sha256sum -c - \
&& apt-get install -y --no-install-recommends /tmp/git-delta.deb \
&& rm -rf /var/lib/apt/lists/* /tmp/git-delta.deb

3
cmd/devcontainer/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module github.com/fscotto/infra/cmd/devcontainer
go 1.22

292
cmd/devcontainer/main.go Normal file
View File

@@ -0,0 +1,292 @@
// Command devcontainer generates project configurations sharing host Git and agent state.
package main
import (
"bytes"
_ "embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
)
//go:embed delta.Dockerfile
var deltaDockerfile string
type profile struct {
Image, Packages string
Extensions []string
}
type agent struct {
Package string
Paths []string
}
type mount struct {
Type string `json:"type"`
Source string `json:"source"`
Target string `json:"target"`
ReadOnly bool `json:"readOnly"`
}
func exists(path string) bool { _, err := os.Stat(path); return err == nil }
func isDir(path string) bool { info, err := os.Stat(path); return err == nil && info.IsDir() }
func quote(s string) string { return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'" }
func symlink(path string) bool {
info, err := os.Lstat(path)
return err == nil && info.Mode()&os.ModeSymlink != 0
}
func selectAgents(selection, home string) ([]string, error) {
result := []string{}
candidates := strings.Split(selection, ",")
if selection == "none" {
return result, nil
}
if selection == "auto" {
candidates = nil
for name := range agents {
candidates = append(candidates, name)
}
sort.Strings(candidates)
}
seen := map[string]bool{}
for _, name := range candidates {
name = strings.TrimSpace(name)
a, ok := agents[name]
if !ok {
return nil, fmt.Errorf("unknown agent %q", name)
}
available := true
for _, path := range a.Paths {
if !isDir(filepath.Join(home, path)) {
available = false
}
}
if selection == "auto" && !available {
continue
}
if !seen[name] {
result = append(result, name)
seen[name] = true
}
}
return result, nil
}
func generate(project, language, home string, selected []string, force bool) (string, error) {
p, ok := profiles[language]
if !ok {
return "", fmt.Errorf("unknown language %q", language)
}
project, err := filepath.Abs(project)
if err != nil {
return "", err
}
project, err = filepath.EvalSymlinks(project)
if err != nil {
return "", err
}
home, err = filepath.Abs(home)
if err != nil {
return "", err
}
home, err = filepath.EvalSymlinks(home)
if err != nil {
return "", err
}
if !isDir(project) {
return "", fmt.Errorf("project directory does not exist: %s", project)
}
if home == "/" || strings.ContainsAny(home, "\n\r$,\\\"") {
return "", errors.New("unsupported host home path")
}
target := filepath.Join(project, ".devcontainer")
if symlink(target) {
return "", errors.New("refusing a symlinked .devcontainer directory")
}
if exists(target) && !force {
return "", errors.New(".devcontainer already exists; use --force to replace generated files")
}
paths := []struct {
path string
readonly bool
}{{".gitconfig", true}, {".config/git", true}, {".gitignore_global", true}, {".config/ai", true}}
claude := false
for _, name := range selected {
a, ok := agents[name]
if !ok {
return "", fmt.Errorf("unknown agent %q", name)
}
for _, path := range a.Paths {
if !isDir(filepath.Join(home, path)) {
return "", fmt.Errorf("missing host directory for %s: %s", name, filepath.Join(home, path))
}
paths = append(paths, struct {
path string
readonly bool
}{path, false})
}
if name == "claude" {
claude = true
}
}
if claude {
paths = append(paths, struct {
path string
readonly bool
}{".claude.json", false})
}
mounts := []mount{}
for _, item := range paths {
if exists(filepath.Join(home, item.path)) {
destination := filepath.Join(home, item.path)
if item.path == ".gitconfig" {
destination = "/run/host-gitconfig"
}
mounts = append(mounts, mount{"bind", "${localEnv:HOME}/" + item.path, destination, item.readonly})
}
}
dockerfile := fmt.Sprintf("FROM %s\nUSER root\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client ripgrep zoxide %s \\\n && rm -rf /var/lib/apt/lists/*\n", p.Image, p.Packages)
dockerfile += deltaDockerfile
if home != "/home/vscode" {
dockerfile += "RUN usermod --home " + quote(home) + " --move-home vscode\n"
}
// Docker ENV uses its own quoting syntax, rather than shell quoting.
envHome, _ := json.Marshal(home)
dockerfile += "ENV HOME=" + string(envHome) + "\n"
if language == "python" {
dockerfile += "RUN python -m pip install --no-cache-dir uv ruff ty\n"
}
if language == "infra" {
dockerfile += "RUN python -m pip install --no-cache-dir ansible-core ansible-lint yamllint\n"
}
config := map[string]any{
"name": filepath.Base(project) + " — " + language,
"build": map[string]string{"dockerfile": "Dockerfile"},
"remoteUser": "vscode", "updateRemoteUserUID": true,
"containerEnv": map[string]string{"HOME": home}, "mounts": mounts,
"customizations": map[string]any{"vscode": map[string]any{"extensions": p.Extensions}},
}
if len(selected) > 0 {
packages := []string{}
for _, name := range selected {
packages = append(packages, quote(agents[name].Package))
}
config["postCreateCommand"] = "sudo npm install --global --no-audit --no-fund " + strings.Join(packages, " ")
if language != "node" {
config["features"] = map[string]any{"ghcr.io/devcontainers/features/node:1": map[string]string{"version": "22"}}
}
}
if claude {
config["remoteEnv"] = map[string]string{"ANTHROPIC_AUTH_TOKEN": "${localEnv:ANTHROPIC_AUTH_TOKEN}"}
}
dockerfile += "USER vscode\n"
if exists(filepath.Join(home, ".gitconfig")) {
dockerfile += "RUN git config --global include.path /run/host-gitconfig\n"
}
var data bytes.Buffer
encoder := json.NewEncoder(&data)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
if err := encoder.Encode(config); err != nil {
return "", err
}
files := []struct{ name, content string }{{"Dockerfile", dockerfile}, {"devcontainer.json", data.String()}}
// Validate every output before replacing any file.
for _, file := range files {
path := filepath.Join(target, file.name)
if info, err := os.Lstat(path); err == nil {
if !info.Mode().IsRegular() {
return "", fmt.Errorf("refusing non-regular output: %s", path)
}
} else if !os.IsNotExist(err) {
return "", err
}
}
if err := os.MkdirAll(target, 0755); err != nil {
return "", err
}
for _, file := range files {
if err := writeAtomic(filepath.Join(target, file.name), file.content); err != nil {
return "", err
}
}
return target, nil
}
func writeAtomic(path, content string) error {
file, err := os.CreateTemp(filepath.Dir(path), ".devcontainer-*")
if err != nil {
return err
}
defer os.Remove(file.Name())
if _, err = io.WriteString(file, content); err != nil {
file.Close()
return err
}
if err = file.Chmod(0644); err != nil {
file.Close()
return err
}
if err = file.Close(); err != nil {
return err
}
return os.Rename(file.Name(), path)
}
func run(args []string, home string, out, stderr io.Writer) error {
flags := flag.NewFlagSet("devcontainer", flag.ContinueOnError)
flags.SetOutput(stderr)
language := flags.String("language", "", "c-cpp, go, rust, python, node, java, infra (required)")
selection := flags.String("agents", "auto", "auto, none, or comma-separated codex,cline,opencode,claude,gemini")
force := flags.Bool("force", false, "Replace the two generated files")
flags.Usage = func() {
fmt.Fprintln(stderr, "Usage: devcontainer PROJECT --language LANGUAGE [--agents AGENTS] [--force]")
flags.PrintDefaults()
}
// Accept the project's original position before the flags as well as flags first.
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
args = append(append([]string{}, args[1:]...), args[0])
}
if err := flags.Parse(args); err != nil {
return err
}
if flags.NArg() != 1 || *language == "" {
flags.Usage()
return errors.New("one project and --language are required")
}
selected, err := selectAgents(*selection, home)
if err != nil {
return err
}
target, err := generate(flags.Arg(0), *language, home, selected, *force)
if err != nil {
return err
}
names := strings.Join(selected, ", ")
if names == "" {
names = "none"
}
fmt.Fprintf(out, "Created %s; agents: %s\n", target, names)
fmt.Fprintln(out, "Open the project in VS Code and choose Dev Containers: Reopen in Container.")
return nil
}
func main() {
home, err := os.UserHomeDir()
if err == nil {
err = run(os.Args[1:], home, os.Stdout, os.Stderr)
}
if errors.Is(err, flag.ErrHelp) {
return
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

View File

@@ -0,0 +1,190 @@
package main
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func setup(t *testing.T) (string, string) {
t.Helper()
root := t.TempDir()
home, project := filepath.Join(root, "host home"), filepath.Join(root, "project with spaces")
for _, path := range []string{home, project} {
if err := os.MkdirAll(path, 0755); err != nil {
t.Fatal(err)
}
}
return home, project
}
func read(t *testing.T, path string) string {
t.Helper()
b, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return string(b)
}
func put(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0600); err != nil {
t.Fatal(err)
}
}
func TestProfiles(t *testing.T) {
for name := range profiles {
t.Run(name, func(t *testing.T) {
home, project := setup(t)
target, err := generate(project, name, home, nil, false)
if err != nil {
t.Fatal(err)
}
var config map[string]any
if err := json.Unmarshal([]byte(read(t, filepath.Join(target, "devcontainer.json"))), &config); err != nil {
t.Fatal(err)
}
if config["containerEnv"].(map[string]any)["HOME"] != home {
t.Fatal("wrong home")
}
if _, ok := config["postCreateCommand"]; ok {
t.Fatal("unexpected agent install")
}
dockerfile := read(t, filepath.Join(target, "Dockerfile"))
if !strings.HasPrefix(dockerfile, "FROM "+profiles[name].Image+"\n") || !strings.HasSuffix(dockerfile, "USER vscode\n") {
t.Fatal("wrong Dockerfile")
}
})
}
}
func TestSharedConfig(t *testing.T) {
home, project := setup(t)
put(t, filepath.Join(home, ".codex/auth.json"), "secret-value")
put(t, filepath.Join(home, ".gitconfig"), "[user]\nname = Test\n")
target, err := generate(project, "python", home, []string{"codex"}, false)
if err != nil {
t.Fatal(err)
}
configText := read(t, filepath.Join(target, "devcontainer.json"))
dockerfile := read(t, filepath.Join(target, "Dockerfile"))
if strings.Contains(configText+dockerfile, "secret-value") {
t.Fatal("credential leaked")
}
var config struct {
Mounts []mount
PostCreateCommand string
Features map[string]any
}
if err := json.Unmarshal([]byte(configText), &config); err != nil {
t.Fatal(err)
}
foundGit, foundAgent := false, false
for _, m := range config.Mounts {
if m.Target == "/run/host-gitconfig" {
foundGit = m.ReadOnly
}
if m.Target == filepath.Join(home, ".codex") {
foundAgent = !m.ReadOnly
}
}
if !foundGit || !foundAgent || !strings.Contains(dockerfile, "include.path /run/host-gitconfig") {
t.Fatal("incorrect sharing")
}
if !strings.Contains(config.PostCreateCommand, "@openai/codex") || len(config.Features) == 0 {
t.Fatal("missing CLI or Node feature")
}
}
func TestOverwriteAndSymlinks(t *testing.T) {
home, project := setup(t)
target, err := generate(project, "go", home, nil, false)
if err != nil {
t.Fatal(err)
}
before := read(t, filepath.Join(target, "Dockerfile"))
if _, err := generate(project, "rust", home, nil, false); err == nil {
t.Fatal("overwrote existing configuration")
}
path := filepath.Join(target, "devcontainer.json")
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
victim := filepath.Join(home, "victim")
put(t, victim, "keep")
if err := os.Symlink(victim, path); err != nil {
t.Fatal(err)
}
if _, err := generate(project, "rust", home, nil, true); err == nil {
t.Fatal("accepted symlink")
}
if read(t, victim) != "keep" || read(t, filepath.Join(target, "Dockerfile")) != before {
t.Fatal("changed files before rejecting symlink")
}
}
func TestInvalidInputs(t *testing.T) {
for _, kind := range []string{"agent", "language", "missing-directory", "home", "target-symlink"} {
t.Run(kind, func(t *testing.T) {
home, project := setup(t)
language := "go"
var selected []string
switch kind {
case "agent":
selected = []string{"codex"}
case "language":
language = "unknown"
case "missing-directory":
project = filepath.Join(project, "missing")
case "home":
home = "/"
case "target-symlink":
if err := os.Symlink(home, filepath.Join(project, ".devcontainer")); err != nil {
t.Fatal(err)
}
}
if _, err := generate(project, language, home, selected, true); err == nil {
t.Fatal("invalid input accepted")
}
if exists(filepath.Join(project, ".devcontainer/Dockerfile")) {
t.Fatal("wrote invalid configuration")
}
})
}
}
func TestAgentSelection(t *testing.T) {
home, _ := setup(t)
put(t, filepath.Join(home, ".codex/config.toml"), "")
got, err := selectAgents("auto", home)
if err != nil || strings.Join(got, ",") != "codex" {
t.Fatalf("auto: %v %v", got, err)
}
got, err = selectAgents("codex,codex", home)
if err != nil || len(got) != 1 {
t.Fatal("duplicate agents")
}
if _, err := selectAgents("invalid", home); err == nil {
t.Fatal("unknown agent accepted")
}
}
func TestCLI(t *testing.T) {
for _, first := range []bool{true, false} {
t.Run(map[bool]string{true: "project-first", false: "flags-first"}[first], func(t *testing.T) {
home, project := setup(t)
args := []string{"--language", "go", "--agents", "none", project}
if first {
args = []string{project, "--language", "go", "--agents", "none"}
}
var out bytes.Buffer
if err := run(args, home, &out, &out); err != nil {
t.Fatal(err)
}
if !strings.Contains(out.String(), "agents: none") {
t.Fatal("missing output")
}
})
}
}

View File

@@ -0,0 +1,18 @@
package main
var profiles = map[string]profile{
"c-cpp": {Image: "mcr.microsoft.com/devcontainers/base:bookworm", Packages: "build-essential clang clangd cmake gdb valgrind universal-ctags cscope", Extensions: []string{"ms-vscode.cpptools", "ms-vscode.cmake-tools"}},
"go": {Image: "mcr.microsoft.com/devcontainers/go:1.25-bookworm", Packages: "", Extensions: []string{"golang.go"}},
"rust": {Image: "mcr.microsoft.com/devcontainers/rust:1-bookworm", Packages: "", Extensions: []string{"rust-lang.rust-analyzer"}},
"python": {Image: "mcr.microsoft.com/devcontainers/python:3.13-bookworm", Packages: "", Extensions: []string{"ms-python.python", "charliermarsh.ruff"}},
"node": {Image: "mcr.microsoft.com/devcontainers/javascript-node:22-bookworm", Packages: "", Extensions: []string{"esbenp.prettier-vscode"}},
"java": {Image: "mcr.microsoft.com/devcontainers/java:21-bookworm", Packages: "maven", Extensions: []string{"vscjava.vscode-java-pack"}},
"infra": {Image: "mcr.microsoft.com/devcontainers/python:3.13-bookworm", Packages: "shellcheck shfmt", Extensions: []string{"redhat.ansible", "redhat.vscode-yaml"}},
}
var agents = map[string]agent{
"codex": {Package: "@openai/codex", Paths: []string{".codex"}},
"cline": {Package: "cline", Paths: []string{".cline", ".agents"}},
"opencode": {Package: "opencode-ai", Paths: []string{".config/opencode", ".local/share/opencode", ".local/state/opencode"}},
"claude": {Package: "@anthropic-ai/claude-code@2.1.312", Paths: []string{".claude"}},
"gemini": {Package: "@google/gemini-cli", Paths: []string{".gemini"}},
}

View File

@@ -1,12 +1,20 @@
# Reusable project devcontainers # Reusable project devcontainers
`scripts/devcontainer.py` is a Python 3 CLI (standard library only). Run it on `cmd/devcontainer/` is a Go CLI using only the standard library. Build it with
**the development host**, from an `infra` checkout, against an existing project: Go 1.22 or newer, from an `infra` checkout:
```sh ```sh
python3 scripts/devcontainer.py ~/src/my-project --language go go -C cmd/devcontainer build -o "$HOME/.local/bin/devcontainer" .
python3 scripts/devcontainer.py ~/src/my-project --language python --agents codex,cline ```
python3 scripts/devcontainer.py ~/src/my-project --language c-cpp --agents none
Create `~/.local/bin` first if needed and keep it on `PATH`. The resulting binary
has no Python dependency. Run it on **the development host**, against an existing
project:
```sh
devcontainer ~/src/my-project --language go
devcontainer ~/src/my-project --language python --agents codex,cline
devcontainer ~/src/my-project --language c-cpp --agents none
``` ```
Profiles: `c-cpp`, `go`, `rust`, `python`, `node`, `java`, `infra`. They generate Profiles: `c-cpp`, `go`, `rust`, `python`, `node`, `java`, `infra`. They generate
@@ -79,7 +87,8 @@ for projects that need to launch sibling containers.
Host-side regression checks: Host-side regression checks:
```sh ```sh
python3 -m unittest discover -s tests -p test_devcontainer.py -v go -C cmd/devcontainer test ./...
go -C cmd/devcontainer vet ./...
``` ```
On the target host, build/open a generated project, check the language toolchain, On the target host, build/open a generated project, check the language toolchain,

View File

@@ -1,147 +0,0 @@
#!/usr/bin/env python3
"""Generate a project devcontainer using host Git and coding-agent configuration."""
import argparse
import json
import os
from pathlib import Path
import shlex
import tempfile
PROFILES = {
'c-cpp': ('mcr.microsoft.com/devcontainers/base:bookworm',
'build-essential clang clangd cmake gdb valgrind universal-ctags cscope',
['ms-vscode.cpptools', 'ms-vscode.cmake-tools']),
'go': ('mcr.microsoft.com/devcontainers/go:1.25-bookworm', '', ['golang.go']),
'rust': ('mcr.microsoft.com/devcontainers/rust:1-bookworm', '', ['rust-lang.rust-analyzer']),
'python': ('mcr.microsoft.com/devcontainers/python:3.13-bookworm', '',
['ms-python.python', 'charliermarsh.ruff']),
'node': ('mcr.microsoft.com/devcontainers/javascript-node:22-bookworm', '', ['esbenp.prettier-vscode']),
'java': ('mcr.microsoft.com/devcontainers/java:21-bookworm', 'maven', ['vscjava.vscode-java-pack']),
'infra': ('mcr.microsoft.com/devcontainers/python:3.13-bookworm', 'shellcheck shfmt',
['redhat.ansible', 'redhat.vscode-yaml']),
}
AGENTS = {
'codex': ('@openai/codex', ['.codex']),
'cline': ('cline', ['.cline', '.agents']),
'opencode': ('opencode-ai', ['.config/opencode', '.local/share/opencode', '.local/state/opencode']),
'claude': ('@anthropic-ai/claude-code@2.1.312', ['.claude']),
'gemini': ('@google/gemini-cli', ['.gemini']),
}
def generate(project, profile, home, agents, force=False):
project, home = Path(project).resolve(), Path(home).resolve()
if not project.is_dir():
raise ValueError(f'Project directory does not exist: {project}')
if home == Path('/') or any(c in str(home) for c in '\n\r$,'):
raise ValueError('Unsupported host home path')
target = project / '.devcontainer'
if target.is_symlink():
raise ValueError('Refusing a symlinked .devcontainer directory')
if target.exists() and not force:
raise ValueError('.devcontainer already exists; use --force to replace generated files')
mount_paths = [('.gitconfig', True), ('.config/git', True), ('.gitignore_global', True),
('.config/ai', True)]
for agent in agents:
for path in AGENTS[agent][1]:
if not (home / path).is_dir():
raise ValueError(f'Missing host directory for {agent}: {home / path}')
mount_paths.append((path, False))
# Claude uses both a config directory and a separate onboarding/account file.
if 'claude' in agents:
mount_paths.append(('.claude.json', False))
mounts = []
for path, readonly in mount_paths:
if (home / path).exists():
mounts.append({'type': 'bind', 'source': '${localEnv:HOME}/' + path,
'target': '/run/host-gitconfig' if path == '.gitconfig' else str(home / path),
'readOnly': readonly})
base, packages, extensions = PROFILES[profile]
dockerfile = f'''FROM {base}
USER root
RUN apt-get update && apt-get install -y --no-install-recommends \\
bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client ripgrep zoxide {packages} \\
&& rm -rf /var/lib/apt/lists/*
'''
dockerfile += r'''RUN apt-get update \
&& arch="$(dpkg --print-architecture)" \
&& case "$arch" in \
amd64) sha256=ea4f0222950ee750a3d38dd80d03bce4cee07a3f63928fc47548383bcaf23093 ;; \
arm64) sha256=0edc36cf514f1bd84becac3e94ee8ae9f8818c6a1f99f7b2ee67b362afa253d3 ;; \
*) echo "Unsupported architecture for delta: $arch" >&2; exit 1 ;; \
esac \
&& curl -fsSL --retry 3 "https://github.com/dandavison/delta/releases/download/0.19.2/git-delta_0.19.2_${arch}.deb" -o /tmp/git-delta.deb \
&& echo "$sha256 /tmp/git-delta.deb" | sha256sum -c - \
&& apt-get install -y --no-install-recommends /tmp/git-delta.deb \
&& rm -rf /var/lib/apt/lists/* /tmp/git-delta.deb
'''
# Preserve absolute references from host agent configuration without mounting the home.
if home != Path('/home/vscode'):
dockerfile += 'RUN usermod --home ' + shlex.quote(str(home)) + ' --move-home vscode\n'
dockerfile += 'ENV HOME=' + shlex.quote(str(home)) + '\n'
if profile in ('python', 'infra'):
tools = 'uv ruff ty' if profile == 'python' else 'ansible-core ansible-lint yamllint'
dockerfile += f'RUN python -m pip install --no-cache-dir {tools}\n'
features = {}
if agents and profile != 'node':
features['ghcr.io/devcontainers/features/node:1'] = {'version': '22'}
config = {
'name': f'{project.name} — {profile}',
'build': {'dockerfile': 'Dockerfile'},
'remoteUser': 'vscode', 'updateRemoteUserUID': True,
'containerEnv': {'HOME': str(home)},
'mounts': mounts,
'customizations': {'vscode': {'extensions': extensions}},
}
if agents:
# Node feature is installed after the Dockerfile, so install CLIs at creation.
npm = ' '.join(shlex.quote(AGENTS[a][0]) for a in agents)
config['postCreateCommand'] = f'sudo npm install --global --no-audit --no-fund {npm}'
if features:
config['features'] = features
if 'claude' in agents:
config['remoteEnv'] = {'ANTHROPIC_AUTH_TOKEN': '${localEnv:ANTHROPIC_AUTH_TOKEN}'}
dockerfile += 'USER vscode\n'
if (home / '.gitconfig').exists():
dockerfile += 'RUN git config --global include.path /run/host-gitconfig\n'
for name, content in [('Dockerfile', dockerfile),
('devcontainer.json', json.dumps(config, indent=2) + '\n')]:
destination = target / name
if destination.is_symlink():
raise ValueError(f'Refusing symlink: {destination}')
target.mkdir(exist_ok=True)
for name, content in [('Dockerfile', dockerfile),
('devcontainer.json', json.dumps(config, indent=2) + '\n')]:
with tempfile.NamedTemporaryFile(mode='w', dir=target, delete=False) as stream:
stream.write(content)
temp = Path(stream.name)
temp.chmod(0o644)
os.replace(temp, target / name)
return target
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('project', type=Path)
parser.add_argument('--language', required=True, choices=PROFILES)
parser.add_argument('--agents', default='auto',
help='Comma-separated codex,cline,opencode,claude,gemini; auto detects host config; none disables')
parser.add_argument('--force', action='store_true', help='Replace the two generated files')
args = parser.parse_args()
home = Path.home()
if args.agents == 'auto':
agents = [a for a, (_, paths) in AGENTS.items() if all((home / p).is_dir() for p in paths)]
else:
agents = [] if args.agents == 'none' else list(dict.fromkeys(args.agents.split(',')))
if any(a not in AGENTS for a in agents):
parser.error('Unknown agent; choose ' + ', '.join(AGENTS))
try:
target = generate(args.project, args.language, home, agents, args.force)
except (ValueError, OSError) as error:
parser.exit(1, f'{error}\n')
print(f'Created {target}; agents: {", ".join(agents) or "none"}')
print('Open the project in VS Code and choose Dev Containers: Reopen in Container.')
if __name__ == '__main__':
main()

View File

@@ -1,68 +0,0 @@
"""Host-side generator regression tests; no engine or credentials required."""
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
spec = importlib.util.spec_from_file_location('generator', Path(__file__).resolve().parents[1] / 'scripts/devcontainer.py')
generator = importlib.util.module_from_spec(spec)
spec.loader.exec_module(generator)
class GeneratorTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.home = self.root / 'host home'
self.home.mkdir()
self.project = self.root / 'project with spaces'
self.project.mkdir()
def test_every_profile_produces_valid_config(self):
for profile in generator.PROFILES:
with self.subTest(profile=profile):
target = generator.generate(self.project, profile, self.home, [], force=True)
config = json.loads((target / 'devcontainer.json').read_text())
self.assertEqual(config['containerEnv']['HOME'], str(self.home))
self.assertNotIn('postCreateCommand', config)
self.assertTrue((target / 'Dockerfile').read_text().endswith('USER vscode\n'))
def test_host_config_is_mounted_without_copying_secrets(self):
(self.home / '.codex').mkdir()
(self.home / '.codex/auth.json').write_text('secret-value')
(self.home / '.gitconfig').write_text('[user]\nname = Test\n')
target = generator.generate(self.project, 'python', self.home, ['codex'])
text = (target / 'devcontainer.json').read_text()
config = json.loads(text)
self.assertNotIn('secret-value', text + (target / 'Dockerfile').read_text())
git_mount = next(m for m in config['mounts'] if m['target'] == '/run/host-gitconfig')
self.assertTrue(git_mount['readOnly'])
agent_mount = next(m for m in config['mounts'] if m['target'] == str(self.home / '.codex'))
self.assertFalse(agent_mount['readOnly'])
self.assertIn('include.path /run/host-gitconfig', (target / 'Dockerfile').read_text())
def test_refuses_existing_config(self):
target = generator.generate(self.project, 'go', self.home, [])
before = (target / 'devcontainer.json').read_bytes()
with self.assertRaises(ValueError):
generator.generate(self.project, 'rust', self.home, [])
self.assertEqual(before, (target / 'devcontainer.json').read_bytes())
def test_missing_agent_config_does_not_write(self):
with self.assertRaises(ValueError):
generator.generate(self.project, 'go', self.home, ['codex'])
self.assertFalse((self.project / '.devcontainer').exists())
def test_force_rejects_symlink_without_modifying_other_files(self):
target = generator.generate(self.project, 'go', self.home, [])
before = (target / 'Dockerfile').read_bytes()
(target / 'devcontainer.json').unlink()
victim = self.root / 'victim'
victim.write_text('keep')
(target / 'devcontainer.json').symlink_to(victim)
with self.assertRaises(ValueError):
generator.generate(self.project, 'rust', self.home, [], force=True)
self.assertEqual(victim.read_text(), 'keep')
self.assertEqual(before, (target / 'Dockerfile').read_bytes())