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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <name>` 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

Expand Down
21 changes: 21 additions & 0 deletions docs/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
61 changes: 61 additions & 0 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"testing"

"github.com/SandSoftwareSolutions/Foundry/internal/config"
"github.com/SandSoftwareSolutions/Foundry/internal/template"
"github.com/fatih/color"
)

Expand Down Expand Up @@ -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)
}
}
61 changes: 54 additions & 7 deletions internal/cli/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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())
}
Expand Down Expand Up @@ -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)
}
}
Expand Down
19 changes: 19 additions & 0 deletions internal/post/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
12 changes: 12 additions & 0 deletions internal/post/post_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
42 changes: 42 additions & 0 deletions internal/template/meta.go
Original file line number Diff line number Diff line change
@@ -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
}
2 changes: 1 addition & 1 deletion internal/template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
26 changes: 26 additions & 0 deletions internal/template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
Loading