From 322e8d4535a8210dbd052d271aa53c61eec75c45 Mon Sep 17 00:00:00 2001 From: kajvans <54155240+kajvans@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:49:49 +0200 Subject: [PATCH] Templates can declare setup steps and next steps in .foundry.yaml post replaces the language default (for example pnpm install instead of npm install), post: [] means no setup, placeholders work in the lines, and the file is never copied. Commands have no shell and are not run for templates fetched with --git. --- CHANGELOG.md | 8 ++++ README.md | 2 +- docs/templates.md | 21 ++++++++++ internal/cli/cli_test.go | 61 ++++++++++++++++++++++++++++++ internal/cli/new.go | 61 ++++++++++++++++++++++++++---- internal/post/post.go | 19 ++++++++++ internal/post/post_test.go | 12 ++++++ internal/template/meta.go | 42 ++++++++++++++++++++ internal/template/template.go | 2 +- internal/template/template_test.go | 26 +++++++++++++ 10 files changed, 245 insertions(+), 9 deletions(-) create mode 100644 internal/template/meta.go diff --git a/CHANGELOG.md b/CHANGELOG.md index a3ac0e5..2ec7672 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ and versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [0.4.0] - 2026-10-16 + +### Added +- Templates can declare their own setup steps and next steps in a `.foundry.yaml` (see `docs/templates.md`), + for example `pnpm install` instead of the default `npm install`. `post: []` means "no setup at all". Placeholders + such as `{{PROJECT_NAME_KEBAB}}` work in these lines. The file is not copied into projects, and the commands are + not run for templates fetched with `--git`. + ## [0.3.0] - 2026-10-16 ### Added diff --git a/README.md b/README.md index 34f9d42..60b8dbb 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ Write `{{PROJECT_NAME}}`, `{{AUTHOR}}` and friends in your template files **and | `{{ANYTHING}}` | whatever you pass with `--var ANYTHING=value` | `foundry template vars ` lists the placeholders a template uses and which need `--var`. -Details, ignore rules and tips: [docs/templates.md](docs/templates.md). +Details, ignore rules, setup steps (`.foundry.yaml`) and tips: [docs/templates.md](docs/templates.md). ## Commands diff --git a/docs/templates.md b/docs/templates.md index 3e7fced..5f11628 100644 --- a/docs/templates.md +++ b/docs/templates.md @@ -53,6 +53,27 @@ These are always left out: `.git/`, `node_modules/`, `.venv/`, `__pycache__/`, ` `build/` and the `.foundryignore` file itself. A template that really needs one of them can re-include it with a rule such as `!build/`. +## Setup steps: `.foundry.yaml` + +A template can say what to do after a project was created from it. Put a `.foundry.yaml` at its root: + +```yaml +post: # commands to run in the new project, in order + - pnpm install +next: # what to tell the user to do next + - pnpm dev +``` + +- `post` replaces the default setup of the language (`go mod tidy`, `npm install`). Each line is one program with + arguments; there is no shell, so no `&&`, pipes, redirects or `$VARIABLES`. A line with shell syntax is refused + and nothing from it runs. +- `post: []` (an empty list) means "no setup steps at all", for a template that needs none. +- `next` replaces the hints printed at the end. +- `--no-post` skips the commands. +- The file is never copied into the project. +- For a template fetched with `--git`, the `post` commands are **not run** (a repository you just downloaded is not + trusted to run commands); the `next` hints are still shown. + ## Language Foundry guesses the language from the files (`go.mod`, `package.json`, `.py` files ...). Override it diff --git a/internal/cli/cli_test.go b/internal/cli/cli_test.go index 12b1975..e7a3dfe 100644 --- a/internal/cli/cli_test.go +++ b/internal/cli/cli_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/SandSoftwareSolutions/Foundry/internal/config" + "github.com/SandSoftwareSolutions/Foundry/internal/template" "github.com/fatih/color" ) @@ -469,3 +470,63 @@ func TestSavedTemplateShadowsBuiltInWithTheSameName(t *testing.T) { t.Fatalf("the name must be listed once: %q", list) } } + +func TestTemplateDeclaresItsOwnSetupSteps(t *testing.T) { + h := newHarness(t) + dir := h.writeTemplate("with-setup", map[string]string{ + "README.md": "# {{PROJECT_NAME}}\n", + "package.json": `{"name":"x"}` + "\n", + template.MetaFile: "post:\n - go version\nnext:\n - pnpm dev {{PROJECT_NAME_KEBAB}}\n", + }) + h.mustRun("template", "add", "with-setup", dir) + out := h.mustRun("new", "app", "--template", "with-setup", "--path", h.root, "--no-git") + if !strings.Contains(out, "Run: go version") || !strings.Contains(out, "Setup finished") { + t.Fatalf("declared step did not run: %s", out) + } + if strings.Contains(out, "npm install") { + t.Fatalf("the language default must be replaced by the declared steps: %s", out) + } + if !strings.Contains(out, "pnpm dev app") { + t.Fatalf("declared next steps (with placeholders filled in) missing: %s", out) + } + if _, err := os.Stat(filepath.Join(h.root, "app", template.MetaFile)); err == nil { + t.Fatal("the meta file must not be copied into the project") + } + // --no-post still skips everything. + out = h.mustRun("new", "app2", "--template", "with-setup", "--path", h.root, "--no-git", "--no-post") + if strings.Contains(out, "Run:") { + t.Fatalf("--no-post must skip declared steps: %s", out) + } +} + +func TestInvalidDeclaredStepIsRefusedWithoutRunningAnything(t *testing.T) { + h := newHarness(t) + dir := h.writeTemplate("bad-setup", map[string]string{ + "README.md": "x\n", + template.MetaFile: "post:\n - touch pwned && echo hi\n", + }) + h.mustRun("template", "add", "bad-setup", dir) + _, errOut, err := h.run("new", "app", "--template", "bad-setup", "--path", h.root, "--no-git") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(errOut, "not valid") { + t.Fatalf("stderr: %q", errOut) + } + if _, err := os.Stat(filepath.Join(h.root, "app", "pwned")); err == nil { + t.Fatal("a command from a refused line was executed") + } +} + +func TestEmptyPostListMeansNoSetupSteps(t *testing.T) { + h := newHarness(t) + dir := h.writeTemplate("no-setup", map[string]string{ + "package.json": `{"name":"x"}` + "\n", + template.MetaFile: "post: []\n", + }) + h.mustRun("template", "add", "no-setup", dir) + out := h.mustRun("new", "app", "--template", "no-setup", "--path", h.root, "--no-git") + if strings.Contains(out, "npm install") || strings.Contains(out, "Setup finished") { + t.Fatalf("an empty post list must run nothing: %s", out) + } +} diff --git a/internal/cli/new.go b/internal/cli/new.go index e8d71ea..5306192 100644 --- a/internal/cli/new.go +++ b/internal/cli/new.go @@ -15,6 +15,7 @@ import ( "github.com/SandSoftwareSolutions/Foundry/internal/gitutil" "github.com/SandSoftwareSolutions/Foundry/internal/post" "github.com/SandSoftwareSolutions/Foundry/internal/project" + "github.com/SandSoftwareSolutions/Foundry/internal/render" "github.com/SandSoftwareSolutions/Foundry/internal/template" "github.com/SandSoftwareSolutions/Foundry/templates" "github.com/spf13/cobra" @@ -76,6 +77,7 @@ Placeholders: {{PROJECT_NAME}}, {{PROJECT_NAME_LOWER}}, {{PROJECT_NAME_UPPER}}, // source is where the files of the new project come from. type source struct { + fromGit bool // fetched with --git: its setup commands are not trusted dir string // template directory language string label string // shown to the user @@ -129,7 +131,7 @@ func runNew(cmd *cobra.Command, name string, o newOptions) error { if err != nil { return err } - src = source{dir: dir, language: lang, label: o.gitURL} + src = source{fromGit: true, dir: dir, language: lang, label: o.gitURL} } else { tmpl, cleanup, err := selectTemplate(cfg, o) if err != nil { @@ -171,20 +173,61 @@ func runNew(cmd *cobra.Command, name string, o newOptions) error { } } - runPost(cmd, o, src.language, target) + meta := renderMeta(loadMeta(cmd, src), plan.Vars) + runPost(cmd, o, src.language, target, meta) setupGit(cmd, o, cfg, src.language, target) maybeOpenEditor(cmd, o, cfg, target) - printNextSteps(out, target, src.language) + printNextSteps(out, target, src.language, meta) return nil } -func runPost(cmd *cobra.Command, o newOptions, language, target string) { +// renderMeta fills placeholders such as {{PROJECT_NAME_KEBAB}} into the declared commands and hints, so a +// template can say "git remote add origin git@github.com:org/{{PROJECT_NAME_KEBAB}}.git". An absent list stays +// absent: an empty "post: []" is different from no "post" at all. +func renderMeta(m template.Meta, vars render.Vars) template.Meta { + apply := func(in []string) []string { + if in == nil { + return nil + } + out := make([]string, len(in)) + for i, l := range in { + out[i] = render.Apply(l, vars) + } + return out + } + return template.Meta{Post: apply(m.Post), Next: apply(m.Next)} +} + +// loadMeta reads the setup steps a template declares. A repository fetched with --git is not trusted to run +// commands, so its declaration is ignored (with a note). +func loadMeta(cmd *cobra.Command, src source) template.Meta { + meta, err := template.LoadMeta(src.dir) + if err != nil { + warnf(cmd.ErrOrStderr(), "%v", err) + return template.Meta{} + } + if src.fromGit && meta.Post != nil { + infof(cmd.OutOrStdout(), "The template repository lists setup commands; they are not run for a template fetched with --git.") + return template.Meta{Next: meta.Next} + } + return meta +} + +func runPost(cmd *cobra.Command, o newOptions, language, target string, meta template.Meta) { out, errOut := cmd.OutOrStdout(), cmd.ErrOrStderr() if o.noPost { - infof(out, "Skipped the language setup step (--no-post).") + infof(out, "Skipped the setup step (--no-post).") return } steps := post.StepsFor(language, target) + if meta.Post != nil { // an empty list ("post: []") means: no setup steps at all + declared, err := post.FromCommands(meta.Post) + if err != nil { + warnf(errOut, "The template's setup commands are not valid: %v", err) + return + } + steps = declared + } for _, s := range steps { infof(out, "%s: %s", s.Name, s.String()) } @@ -248,11 +291,15 @@ func maybeOpenEditor(cmd *cobra.Command, o newOptions, cfg *config.Config, targe okf(cmd.OutOrStdout(), "Opened the project in VS Code.") } -func printNextSteps(out io.Writer, target, language string) { +func printNextSteps(out io.Writer, target, language string, meta template.Meta) { fmt.Fprintln(out) boldf(out, "Next steps") fmt.Fprintf(out, " cd %s\n", shellQuote(target)) - for _, s := range post.NextSteps(language) { + next := post.NextSteps(language) + if len(meta.Next) > 0 { + next = meta.Next + } + for _, s := range next { fmt.Fprintf(out, " %s\n", s) } } diff --git a/internal/post/post.go b/internal/post/post.go index de70999..4e68ab6 100644 --- a/internal/post/post.go +++ b/internal/post/post.go @@ -45,6 +45,25 @@ func StepsFor(language, dir string) []Step { return nil } +// FromCommands turns command lines from a template into steps. A line is a program and its arguments separated +// by spaces; there is no shell, so quotes, pipes, redirects and && are not available. +func FromCommands(lines []string) ([]Step, error) { + var steps []Step + for _, line := range lines { + fields := strings.Fields(line) + if len(fields) == 0 { + continue + } + for _, f := range fields { + if strings.ContainsAny(f, ";|&<>`$()") { + return nil, fmt.Errorf("%q: only one plain command per line is allowed; shell syntax such as %q is not supported", line, f) + } + } + steps = append(steps, Step{Name: "Run", Cmd: fields[0], Args: fields[1:]}) + } + return steps, nil +} + // NextSteps are commands the user can run themselves afterwards (nothing here is executed). func NextSteps(language string) []string { switch strings.ToLower(language) { diff --git a/internal/post/post_test.go b/internal/post/post_test.go index 13449db..ac8d718 100644 --- a/internal/post/post_test.go +++ b/internal/post/post_test.go @@ -72,3 +72,15 @@ func TestNextSteps(t *testing.T) { t.Fatal("unknown language has no next steps") } } + +func TestFromCommands(t *testing.T) { + steps, err := FromCommands([]string{"pnpm install", "", " go mod tidy "}) + if err != nil || len(steps) != 2 || steps[0].String() != "pnpm install" || steps[1].String() != "go mod tidy" { + t.Fatalf("steps = %v, err = %v", steps, err) + } + for _, bad := range []string{"a && b", "a | b", "a > out", "echo $HOME", "echo `x`", "a; b", "(cd x)"} { + if _, err := FromCommands([]string{bad}); err == nil { + t.Errorf("%q should be refused", bad) + } + } +} diff --git a/internal/template/meta.go b/internal/template/meta.go new file mode 100644 index 0000000..1bec812 --- /dev/null +++ b/internal/template/meta.go @@ -0,0 +1,42 @@ +package template + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + + "gopkg.in/yaml.v3" +) + +// MetaFile is an optional file at the root of a template that says what to do after a project was created +// from it. It is never copied into the project. +const MetaFile = ".foundry.yaml" + +// Meta is the content of MetaFile. +// +// post: # commands to run in the new project, one per line, no shell syntax +// - pnpm install +// next: # what to tell the user to do next (shown at the end) +// - pnpm dev +type Meta struct { + Post []string `yaml:"post"` + Next []string `yaml:"next"` +} + +// LoadMeta reads the template's MetaFile. A missing file gives an empty Meta. +func LoadMeta(dir string) (Meta, error) { + data, err := os.ReadFile(filepath.Join(dir, MetaFile)) + if errors.Is(err, fs.ErrNotExist) { + return Meta{}, nil + } + if err != nil { + return Meta{}, err + } + var m Meta + if err := yaml.Unmarshal(data, &m); err != nil { + return Meta{}, fmt.Errorf("cannot parse %s: %w", MetaFile, err) + } + return m, nil +} diff --git a/internal/template/template.go b/internal/template/template.go index ec459b0..d754642 100644 --- a/internal/template/template.go +++ b/internal/template/template.go @@ -18,7 +18,7 @@ const IgnoreFile = ".foundryignore" // DefaultIgnores are always excluded from templates. A rule in .foundryignore can re-include them, // for example "!build/". -var DefaultIgnores = []string{".git/", "node_modules/", ".venv/", "__pycache__/", "vendor/", "dist/", "build/", IgnoreFile} +var DefaultIgnores = []string{".git/", "node_modules/", ".venv/", "__pycache__/", "vendor/", "dist/", "build/", IgnoreFile, MetaFile} var extensionLanguage = map[string]string{ ".go": "Go", ".py": "Python", ".js": "JavaScript", ".mjs": "JavaScript", ".cjs": "JavaScript", diff --git a/internal/template/template_test.go b/internal/template/template_test.go index bf2deb5..4efc39b 100644 --- a/internal/template/template_test.go +++ b/internal/template/template_test.go @@ -101,3 +101,29 @@ func TestValidateName(t *testing.T) { } } } + +func TestMetaIsLoadedAndNeverListedAsAFile(t *testing.T) { + root := t.TempDir() + write(t, root, "main.go", "package main") + write(t, root, MetaFile, "post:\n - go mod tidy\nnext:\n - go run .\n") + m, err := LoadMeta(root) + if err != nil || len(m.Post) != 1 || m.Post[0] != "go mod tidy" || len(m.Next) != 1 { + t.Fatalf("meta = %+v, err = %v", m, err) + } + files, err := ListFiles(root) + if err != nil { + t.Fatal(err) + } + for _, f := range files { + if f == MetaFile { + t.Fatal("the meta file must not be part of the template files") + } + } + if m, err := LoadMeta(t.TempDir()); err != nil || len(m.Post) != 0 { + t.Fatalf("missing file must give an empty Meta: %+v %v", m, err) + } + write(t, root, MetaFile, "post: [unclosed") + if _, err := LoadMeta(root); err == nil { + t.Fatal("broken YAML must be reported") + } +}