Vectrum
Sign In
78 lines · 1.4 KB · Shell
#!/usr/bin/env bash
set -euo pipefail
cat > go.mod <<'EOF'
module conf

go 1.22
EOF
cat > conf.go <<'EOF'
package conf

import (
	"encoding/json"
	"os"
)

// Settings is the on-disk configuration.
type Settings struct {
	Name    string `json:"name"`
	Retries int    `json:"retries"`
}

// Load reads settings from path.
func Load(path string) Settings {
	data, _ := os.ReadFile(path)
	var s Settings
	json.Unmarshal(data, &s)
	return s
}
EOF
cat > main_helper.go <<'EOF'
package conf

// Describe summarises the settings at path.
func Describe(path string) string {
	s := Load(path)
	return s.Name
}
EOF
cat > conf_test.go <<'EOF'
package conf

import (
	"os"
	"path/filepath"
	"testing"
)

func TestLoadValid(t *testing.T) {
	dir := t.TempDir()
	p := filepath.Join(dir, "c.json")
	os.WriteFile(p, []byte(`{"name":"svc","retries":3}`), 0o644)

	s, err := Load(p)
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if s.Name != "svc" || s.Retries != 3 {
		t.Errorf("got %+v", s)
	}
}

func TestLoadMissingFile(t *testing.T) {
	if _, err := Load(filepath.Join(t.TempDir(), "nope.json")); err == nil {
		t.Error("want an error for a missing file")
	}
}

func TestLoadBadJSON(t *testing.T) {
	dir := t.TempDir()
	p := filepath.Join(dir, "c.json")
	os.WriteFile(p, []byte(`{not json`), 0o644)

	if _, err := Load(p); err == nil {
		t.Error("want an error for malformed JSON")
	}
}
EOF
git init -q . && git add -A && git -c user.email=e@x -c user.name=n commit -qm base