mirror of
https://github.com/fscotto/infra.git
synced 2026-11-25 21:29:51 +00:00
Replace Python devcontainer generator with Go CLI
This commit is contained in:
11
cmd/devcontainer/delta.Dockerfile
Normal file
11
cmd/devcontainer/delta.Dockerfile
Normal 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
3
cmd/devcontainer/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module github.com/fscotto/infra/cmd/devcontainer
|
||||
|
||||
go 1.22
|
||||
292
cmd/devcontainer/main.go
Normal file
292
cmd/devcontainer/main.go
Normal 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)
|
||||
}
|
||||
}
|
||||
190
cmd/devcontainer/main_test.go
Normal file
190
cmd/devcontainer/main_test.go
Normal 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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
18
cmd/devcontainer/profiles.go
Normal file
18
cmd/devcontainer/profiles.go
Normal 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"}},
|
||||
}
|
||||
Reference in New Issue
Block a user