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
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,20 @@ and versions follow [Semantic Versioning](https://semver.org/).

## [Unreleased]

## [0.5.0] - 2026-10-16

### Added
- **Placeholders are asked for.** A template can declare them in `.foundry.yaml` (`vars:` with a prompt and a
default); in a terminal Foundry asks, with `--non-interactive` the default is used, and any other used-but-missing
placeholder is asked for too. `--strict` stops before writing anything when a placeholder has no value, which is
what you want in CI.
- `foundry template init <folder>` creates the skeleton of a new template (`--add` saves it right away).
- `foundry template add <name> <git-address>` keeps a copy of a template from Git (`--branch`);
`template update` fast-forwards it, `template remove` deletes the copy. Setup commands of such templates are
never run.
- The `.deb` packages install shell completions for bash, zsh and fish.
- `foundry template show` and `template vars` show the source of a template and the placeholders that are asked for.

## [0.4.0] - 2026-10-16

### Added
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,14 +134,15 @@ Details, ignore rules, setup steps (`.foundry.yaml`) and tips: [docs/templates.m

| Command | What it does |
| --- | --- |
| `foundry new <name>` | Create a project. Flags: `--template`, `--language`, `--git`, `--branch`, `--path`, `--var KEY=VALUE`, `--dry-run`, `--json` (with `--dry-run`), `--no-git`, `--no-post`, `--no-open`, `--non-interactive` |
| `foundry template add <name> <path>` | Save a directory as a template (`--description`, `--language`) |
| `foundry new <name>` | Create a project. Flags: `--template`, `--language`, `--git`, `--branch`, `--path`, `--var KEY=VALUE`, `--dry-run`, `--json` (with `--dry-run`), `--strict`, `--no-git`, `--no-post`, `--no-open`, `--non-interactive` |
| `foundry template add <name> <path-or-git-url>` | Save a directory or a Git repository as a template (`--description`, `--language`, `--branch`) |
| `foundry template list` | List built-in and saved templates (`--saved`, `--builtin`, `--sort name\|language`, `--quiet`, `--json`) |
| `foundry template show <name>` | Show details and files (`--files-only`, `--summary`, `--json`) |
| `foundry template update [name...]` | Rescan templates so file lists stay current |
| `foundry template edit <name>` | Change description, language, path or name |
| `foundry template vars <name>` | List the placeholders a template uses |
| `foundry template export <name> <folder>` | Copy a built-in template to a folder so you can change it |
| `foundry template init <folder>` | Create the skeleton of a new template (`--add <name>` to save it) |
| `foundry template remove <name>` | Forget a template (`--force` if it is a default); files stay |
| `foundry config` | Show settings; set with `--user`, `--license`, `--default-language`, `--docker`, `--interactive`; `--json`, `--path` |
| `foundry config <language> <template>` | Set the default template of a language, built-in or your own (`""` clears it) |
Expand Down
27 changes: 27 additions & 0 deletions docs/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,33 @@ 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/`.

## Starting a new template

`foundry template init ./my-template` creates the skeleton (README with placeholders, a commented `.foundry.yaml`,
a `.foundryignore` and an example file). Add `--add my-template --language Go` to save it right away.

## Templates from Git

`foundry template add team-api https://github.com/acme/api-template [--branch main]` keeps Foundry's own copy of
the repository in its config folder. `foundry template update` fetches new commits (fast-forward only), and
`foundry template remove` deletes the copy again. Setup commands (`post`) of such a template are **never run**;
its hints (`next`) and declared placeholders (`vars`) are used.

## Placeholders that are asked for

Declare them in `.foundry.yaml` so Foundry asks for them in a terminal, and uses the default when it may not ask:

```yaml
vars:
- name: PORT
prompt: Port the service listens on
default: "8080"
```

A placeholder that is used but not declared is asked for too (in a terminal). `--var NAME=value` always wins,
`--non-interactive` never asks, and `--strict` stops before writing anything if a placeholder still has no value.
`foundry template vars <name>` shows what a template uses and what is asked.

## 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:
Expand Down
177 changes: 177 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/render"
"github.com/SandSoftwareSolutions/Foundry/internal/template"
"github.com/fatih/color"
)
Expand Down Expand Up @@ -530,3 +531,179 @@ func TestEmptyPostListMeansNoSetupSteps(t *testing.T) {
t.Fatalf("an empty post list must run nothing: %s", out)
}
}

func TestDeclaredVarsUseDefaultsWhenNotAllowedToAsk(t *testing.T) {
h := newHarness(t)
dir := h.writeTemplate("with-vars", map[string]string{
"config.txt": "port={{PORT}} name={{PROJECT_NAME}} token={{TOKEN}}\n",
template.MetaFile: "vars:\n - name: PORT\n prompt: Port\n default: \"8080\"\n - name: TOKEN\n prompt: Token without a default\npost: []\n",
})
h.mustRun("template", "add", "with-vars", dir)

// A default fills in without asking; a declared var without a default stays unresolved and is reported.
out, errOut, err := h.run("new", "app", "--template", "with-vars", "--path", h.root, "--no-git", "--non-interactive")
if err != nil {
t.Fatalf("%v\n%s\n%s", err, out, errOut)
}
b, _ := os.ReadFile(filepath.Join(h.root, "app", "config.txt"))
if !strings.Contains(string(b), "port=8080") || !strings.Contains(string(b), "{{TOKEN}}") {
t.Fatalf("config.txt = %q", b)
}
if !strings.Contains(errOut, "TOKEN") {
t.Fatalf("the missing value must be reported: %q", errOut)
}

// --var wins over the default.
h.mustRun("new", "app2", "--template", "with-vars", "--path", h.root, "--no-git", "--non-interactive", "--var", "PORT=9000", "--var", "TOKEN=abc")
b, _ = os.ReadFile(filepath.Join(h.root, "app2", "config.txt"))
if string(b) != "port=9000 name=app2 token=abc\n" {
t.Fatalf("config.txt = %q", b)
}

// vars lists what is asked for.
if out := h.mustRun("template", "vars", "with-vars"); !strings.Contains(out, `asked for; default "8080"`) || !strings.Contains(out, "TOKEN") {
t.Fatalf("vars: %s", out)
}
}

func TestStrictStopsBeforeWritingAnything(t *testing.T) {
h := newHarness(t)
dir := h.writeTemplate("needs-port", map[string]string{"a.txt": "{{PORT}}\n"})
h.mustRun("template", "add", "needs-port", dir)
_, _, err := h.run("new", "app", "--template", "needs-port", "--path", h.root, "--no-git", "--strict")
if err == nil || !strings.Contains(err.Error(), "PORT") {
t.Fatalf("expected a strict error naming PORT, got %v", err)
}
if _, statErr := os.Stat(filepath.Join(h.root, "app")); statErr == nil {
t.Fatal("nothing may be written when --strict stops the run")
}
h.mustRun("new", "app", "--template", "needs-port", "--path", h.root, "--no-git", "--strict", "--var", "PORT=1")
}

func TestFillDeclaredAsksOnlyForWhatIsMissing(t *testing.T) {
var asked []string
ask := func(name, prompt, def string) (string, error) {
asked = append(asked, name)
return "answer-" + name, nil
}
have := render.Vars{"A": "given"}
got, err := fillDeclared([]template.VarSpec{{Name: "A"}, {Name: "B", Default: "d"}, {Name: "C"}}, have, ask)
if err != nil {
t.Fatal(err)
}
if strings.Join(asked, ",") != "B,C" || got["A"] != "given" || got["B"] != "answer-B" {
t.Fatalf("asked %v, got %v", asked, got)
}
if _, err := fillDeclared([]template.VarSpec{{Name: "bad name"}}, nil, nil); err == nil {
t.Fatal("an invalid declared name must be refused")
}
if have["B"] != "" {
t.Fatal("the input map must not be modified")
}
}

func TestTemplateInitCreatesAUsableSkeleton(t *testing.T) {
h := newHarness(t)
dir := filepath.Join(h.root, "skeleton")
out := h.mustRun("template", "init", dir, "--add", "mine", "--language", "Go", "--description", "Mine")
if !strings.Contains(out, "Created the template skeleton") || !strings.Contains(out, `Saved it as template "mine"`) {
t.Fatalf("output: %s", out)
}
for _, f := range []string{"README.md", "notes.txt", template.IgnoreFile, template.MetaFile} {
if _, err := os.Stat(filepath.Join(dir, f)); err != nil {
t.Fatalf("missing %s: %v", f, err)
}
}
// The skeleton works as a template straight away, and the commented .foundry.yaml is harmless.
h.mustRun("new", "demo", "--template", "mine", "--path", h.root, "--no-git")
b, _ := os.ReadFile(filepath.Join(h.root, "demo", "notes.txt"))
if !strings.Contains(string(b), "called demo (demo)") {
t.Fatalf("notes.txt: %q", b)
}
if _, err := os.Stat(filepath.Join(h.root, "demo", template.MetaFile)); err == nil {
t.Fatal("the meta file must not be copied")
}
if _, _, err := h.run("template", "init", dir); err == nil {
t.Fatal("init into a non-empty folder must fail")
}
}

func TestTemplateFromGitAddUpdateRunAndRemove(t *testing.T) {
if !gitAvailable() {
t.Skip("git is not installed")
}
h := newHarness(t)
repo := h.writeTemplate("remote-tpl", map[string]string{
"README.md": "# {{PROJECT_NAME}}\n",
template.MetaFile: "post:\n - go version\nnext:\n - echo hello {{PROJECT_NAME}}\n",
})
if out, err := gitInitCommit(repo); err != nil {
t.Fatalf("%v: %s", err, out)
}
url := "file://" + filepath.ToSlash(repo)
if !strings.HasPrefix(url, "file:///") {
url = "file:///" + strings.TrimPrefix(url, "file://")
}

out := h.mustRun("template", "add", "team", url)
if !strings.Contains(out, `Template "team" saved`) {
t.Fatalf("add: %s", out)
}
show := h.mustRun("template", "show", "team", "--summary")
if !strings.Contains(show, "Source:") || !strings.Contains(show, "remote-tpl") {
t.Fatalf("show: %s", show)
}
cfg, _ := config.Load()
tpl, _ := cfg.FindTemplate("team")
if tpl.Source != url || !strings.Contains(tpl.Path, filepath.Join("templates", "team")) {
t.Fatalf("saved template: %+v", tpl)
}
copyDir := tpl.Path

// Setup commands of a template that came from Git are not run; its hints are shown.
made := h.mustRun("new", "app", "--template", "team", "--path", h.root, "--no-git")
if strings.Contains(made, "Run: go version") || strings.Contains(made, "Setup finished") {
t.Fatalf("setup commands from a Git template must not run: %s", made)
}
if !strings.Contains(made, "echo hello app") {
t.Fatalf("next hint missing: %s", made)
}

// A new commit upstream arrives with update.
if err := os.WriteFile(filepath.Join(repo, "extra.txt"), []byte("x"), 0o644); err != nil {
t.Fatal(err)
}
if out, err := gitOutput(repo, "add", "--all"); err != nil {
t.Fatalf("%v %s", err, out)
}
if out, err := gitOutput(repo, "-c", "user.name=T", "-c", "user.email=t@example.com", "commit", "--quiet", "-m", "more"); err != nil {
t.Fatalf("%v %s", err, out)
}
h.mustRun("template", "update", "team")
cfg, _ = config.Load()
tpl, _ = cfg.FindTemplate("team")
found := false
for _, f := range tpl.Files {
found = found || f == "extra.txt"
}
if !found {
t.Fatalf("update did not bring the new file: %v", tpl.Files)
}

// Removing it also removes Foundry's own copy, but nothing else.
h.mustRun("template", "remove", "team")
if _, err := os.Stat(copyDir); err == nil {
t.Fatal("the copy Foundry made must be deleted")
}
if _, err := os.Stat(repo); err != nil {
t.Fatal("the original repository must stay")
}
}

func TestBranchFlagNeedsAGitAddress(t *testing.T) {
h := newHarness(t)
dir := h.writeTemplate("plain", map[string]string{"a.txt": "x"})
if _, _, err := h.run("template", "add", "plain", dir, "--branch", "main"); err == nil {
t.Fatal("--branch with a directory must be refused")
}
}
46 changes: 38 additions & 8 deletions internal/cli/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const pageSize = 10
type newOptions struct {
language, templateName, gitURL, branch, path string
noGit, noPost, noOpen, nonInteractive bool
dryRun, asJSON bool
dryRun, asJSON, strict bool
vars []string
}

Expand Down Expand Up @@ -71,6 +71,7 @@ Placeholders: {{PROJECT_NAME}}, {{PROJECT_NAME_LOWER}}, {{PROJECT_NAME_UPPER}},
f.BoolVar(&o.nonInteractive, "non-interactive", false, "Never prompt; require --template, --language or --git")
f.StringArrayVar(&o.vars, "var", nil, "Placeholder value as KEY=VALUE (repeatable)")
f.BoolVar(&o.dryRun, "dry-run", false, "Show what would be created without writing anything")
f.BoolVar(&o.strict, "strict", false, "Stop (before writing anything) when a placeholder has no value")
f.BoolVar(&o.asJSON, "json", false, "With --dry-run: print the plan as JSON")
return cmd
}
Expand Down Expand Up @@ -142,16 +143,46 @@ func runNew(cmd *cobra.Command, name string, o newOptions) error {
if tmpl.Description != "" && isBuiltinName(tmpl.Name, cfg) {
label = tmpl.Name + " (built-in)"
}
src = source{dir: tmpl.Path, language: tmpl.Language, label: label}
src = source{fromGit: tmpl.Source != "", dir: tmpl.Path, language: tmpl.Language, label: label}
}

plan, err := project.BuildPlan(project.Options{
TemplateDir: src.dir, Name: name, TargetDir: target,
Author: cfg.Author, License: cfg.License, Vars: vars,
})
meta := loadMeta(cmd, src)
// Ask only on a terminal, and never when the output must be machine readable.
var ask asker
if !o.nonInteractive && !o.asJSON && cfg.Interactive && interactive() {
ask = surveyAsk
}
vars, err = fillDeclared(meta.Vars, vars, ask)
if err != nil {
return err
}
build := func(v render.Vars) (*project.Plan, error) {
return project.BuildPlan(project.Options{
TemplateDir: src.dir, Name: name, TargetDir: target,
Author: cfg.Author, License: cfg.License, Vars: v,
})
}
plan, err := build(vars)
if err != nil {
return err
}
if missing := unresolvedNames(plan); len(missing) > 0 {
switch {
case ask != nil:
if vars, err = askMissing(missing, vars, ask); err != nil {
return err
}
if plan, err = build(vars); err != nil {
return err
}
case o.strict:
return strictError(plan)
}
}
if o.strict && len(plan.Unresolved) > 0 {
return strictError(plan)
}
meta = renderMeta(meta, plan.Vars)

if o.dryRun {
return printDryRun(out, plan, src, target, o.asJSON)
Expand All @@ -173,7 +204,6 @@ func runNew(cmd *cobra.Command, name string, o newOptions) error {
}
}

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)
Expand Down Expand Up @@ -208,7 +238,7 @@ func loadMeta(cmd *cobra.Command, src source) 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 template.Meta{Vars: meta.Vars, Next: meta.Next}
}
return meta
}
Expand Down
Loading
Loading