diff --git a/README.md b/README.md index 8cf9f4c..f1e8766 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,7 @@ deploy: path: /opt/myapp restart: systemctl restart myapp # run over SSH after upload # optional: port · ssh_key · build · binary · goos · goarch · remote_build + # include: [".env.production.example"] # extra paths --remote-build may ship # multi-environment instead of the inline target: # default: production # targets: @@ -106,6 +107,12 @@ togo deploy --dry-run # print the plan, change nothing togo deploy --remote-build # rsync source and build on the server ``` +`--remote-build` ships the source tree but never `.env`, `.env.*` (except +`.env.example`), `.git/`, local database files (`*.db`, `*.sqlite`, `-wal`/`-shm`), +`node_modules/` or `.togo/`, and it honours `.gitignore`. Use `deploy.include` to +opt a path back in. It requires `rsync` (the `scp` fallback is refused for remote +builds because it cannot exclude files). `--dry-run` lists the exclusions. + Env overrides: `TOGO_DEPLOY_HOST` / `_USER` / `_PATH` / `_SSH_KEY`. ## Generators diff --git a/cmd/deploy.go b/cmd/deploy.go index 15a1f8d..268be61 100644 --- a/cmd/deploy.go +++ b/cmd/deploy.go @@ -173,6 +173,8 @@ func runDeploy(proj *config.Project, env string, o deployOpts) error { ui.Step("1. build : %s", buildDesc(t, o)) if remoteBuild { ui.Step("2. ship : rsync ./ → %s, then build on server", remote) + ui.Step(" excludes: %s", strings.Join(remoteBuildExcludeNames(t), " ")) + ui.Step(" (also skips files matched by .gitignore; deploy.include re-adds paths)") } else { ui.Step("2. ship : rsync %s → %s", relTo(proj.Root, artifact), remote) } @@ -181,7 +183,7 @@ func runDeploy(proj *config.Project, env string, o deployOpts) error { } if remoteBuild { - if err := rsyncTo(proj.Root+string(os.PathSeparator), remote, t); err != nil { + if err := rsyncTo(proj.Root+string(os.PathSeparator), remote, t, remoteBuildFilters(t)); err != nil { return err } build := t.Build @@ -198,7 +200,7 @@ func runDeploy(proj *config.Project, env string, o deployOpts) error { return err } } - if err := rsyncTo(artifact, remote, t); err != nil { + if err := rsyncTo(artifact, remote, t, nil); err != nil { return err } } @@ -262,17 +264,74 @@ func sshRun(t config.DeployTarget, remoteCmd string) error { return c.Run() } -func rsyncTo(src, remote string, t config.DeployTarget) error { +// defaultRemoteBuildExcludes are never shipped by --remote-build: secrets, VCS +// history, local databases and machine-local state. .env.example is re-included +// (see remoteBuildFilters). Patterns use rsync syntax. +var defaultRemoteBuildExcludes = []string{ + ".env", + ".env.*", + ".git/", + "*.db", + "*.db-wal", + "*.db-shm", + "*.db-journal", + "*.sqlite", + "*.sqlite3", + "*.sqlite-wal", + "*.sqlite-shm", + "node_modules/", + ".togo/", +} + +// remoteBuildFilters returns the rsync filter arguments for a --remote-build +// upload. rsync applies the first matching rule, so the order matters: +// deploy.include opt-ins, then .env.example, then the default excludes, then the +// project's .gitignore (per directory). +func remoteBuildFilters(t config.DeployTarget) []string { + var f []string + for _, p := range t.Include { + f = append(f, "--include="+p) + } + f = append(f, "--include=.env.example") + for _, p := range defaultRemoteBuildExcludes { + f = append(f, "--exclude="+p) + } + return append(f, "--filter=:- .gitignore") +} + +// remoteBuildExcludeNames lists the excluded patterns for display (--dry-run). +func remoteBuildExcludeNames(t config.DeployTarget) []string { + names := append([]string{}, defaultRemoteBuildExcludes...) + if len(t.Include) > 0 { + names = append(names, fmt.Sprintf("(except deploy.include: %s)", strings.Join(t.Include, ", "))) + } + return append(names, "(.env.example is kept)") +} + +// rsyncArgs builds the rsync argument list. +func rsyncArgs(src, remote, transport string, filters []string) []string { + args := []string{"-az", "-e", transport} + args = append(args, filters...) + return append(args, src, remote) +} + +// rsyncTo uploads src to remote. filters (rsync --include/--exclude/--filter +// args) are applied when set. scp cannot apply them, so with filters the scp +// fallback is refused rather than uploading everything. +func rsyncTo(src, remote string, t config.DeployTarget, filters []string) error { if _, err := exec.LookPath("rsync"); err == nil { transport := "ssh" if extra := sshArgs(t); len(extra) > 0 { transport = "ssh " + strings.Join(extra, " ") } ui.Step("rsync %s → %s", src, remote) - c := exec.Command("rsync", "-az", "-e", transport, src, remote) + c := exec.Command("rsync", rsyncArgs(src, remote, transport, filters)...) c.Stdout, c.Stderr = os.Stdout, os.Stderr return c.Run() } + if len(filters) > 0 { + return fmt.Errorf("rsync not found on PATH: --remote-build needs rsync to skip .env, .git and local databases (scp would upload them); install rsync") + } if _, err := exec.LookPath("scp"); err != nil { return fmt.Errorf("neither rsync nor scp found on PATH") } diff --git a/cmd/deploy_remote_test.go b/cmd/deploy_remote_test.go new file mode 100644 index 0000000..f2ecb6c --- /dev/null +++ b/cmd/deploy_remote_test.go @@ -0,0 +1,119 @@ +package cmd + +import ( + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/togo-framework/cli/internal/config" +) + +func TestRemoteBuildFilters_Defaults(t *testing.T) { + got := strings.Join(remoteBuildFilters(config.DeployTarget{}), " ") + for _, want := range []string{ + "--exclude=.env", "--exclude=.env.*", "--exclude=.git/", "--exclude=*.db", + "--exclude=*.db-wal", "--exclude=*.db-shm", "--exclude=*.sqlite", "--exclude=*.sqlite3", + "--exclude=node_modules/", "--exclude=.togo/", "--include=.env.example", "--filter=:- .gitignore", + } { + if !strings.Contains(got, want) { + t.Errorf("filters missing %q: %s", want, got) + } + } + // rsync uses the first matching rule: .env.example must win over .env.*. + if strings.Index(got, "--include=.env.example") > strings.Index(got, "--exclude=.env.*") { + t.Errorf(".env.example include must come before the .env.* exclude: %s", got) + } +} + +func TestRemoteBuildFilters_IncludeComesFirst(t *testing.T) { + f := remoteBuildFilters(config.DeployTarget{Include: []string{"data/seed.db"}}) + if f[0] != "--include=data/seed.db" { + t.Fatalf("deploy.include must be the first rule, got %v", f) + } +} + +func TestRsyncArgs(t *testing.T) { + args := rsyncArgs("/proj/", "u@h:/opt/app", "ssh -p 2222", []string{"--exclude=.env"}) + want := []string{"-az", "-e", "ssh -p 2222", "--exclude=.env", "/proj/", "u@h:/opt/app"} + if strings.Join(args, "|") != strings.Join(want, "|") { + t.Fatalf("args = %v; want %v", args, want) + } +} + +// Without rsync, a filtered (remote-build) upload must fail instead of falling +// back to scp, which would upload .env, .git and local databases. +func TestRsyncTo_RefusesScpFallbackWithFilters(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + err := rsyncTo("/proj/", "u@h:/opt/app", config.DeployTarget{}, remoteBuildFilters(config.DeployTarget{})) + if err == nil || !strings.Contains(err.Error(), "rsync not found") { + t.Fatalf("expected a refusal mentioning rsync, got %v", err) + } +} + +func write(t *testing.T, root, rel, body string) { + t.Helper() + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } +} + +func listFiles(t *testing.T, root string) []string { + t.Helper() + var out []string + _ = filepath.WalkDir(root, func(p string, d os.DirEntry, err error) error { + if err == nil && !d.IsDir() { + r, _ := filepath.Rel(root, p) + out = append(out, filepath.ToSlash(r)) + } + return nil + }) + sort.Strings(out) + return out +} + +// End-to-end with the real rsync (local destination): secrets, VCS history and +// local databases are not delivered; .env.example and the source are. +func TestRemoteBuildFilters_RsyncDelivery(t *testing.T) { + if _, err := exec.LookPath("rsync"); err != nil { + t.Skip("rsync not installed") + } + src, dst := t.TempDir(), t.TempDir() + for rel, body := range map[string]string{ + "main.go": "package main", + "togo.yaml": "name: demo", + ".env": "AUTH_SECRET=do-not-ship", + ".env.local": "x=1", + "api/.env": "nested", + ".env.example": "AUTH_SECRET=", + ".git/HEAD": "ref: refs/heads/main", + "togo.db": "db", + "togo.db-wal": "wal", + "data/dev.sqlite3": "db", + "node_modules/x/i.js": "x", + "web/node_modules/y.js": "y", + ".togo/cache": "c", + ".gitignore": "ignored.txt\n", + "ignored.txt": "gitignored", + "data/seed.db": "seed", + "deploy/keep.env.sample": "ok", + } { + write(t, src, rel, body) + } + target := config.DeployTarget{Include: []string{"data/seed.db"}} + args := rsyncArgs(src+string(os.PathSeparator), dst, "ssh", remoteBuildFilters(target)) + if out, err := exec.Command("rsync", args...).CombinedOutput(); err != nil { + t.Fatalf("rsync: %v\n%s", err, out) + } + got := strings.Join(listFiles(t, dst), ",") + want := ".env.example,.gitignore,data/seed.db,deploy/keep.env.sample,main.go,togo.yaml" + if got != want { + t.Fatalf("delivered files:\n got %s\n want %s", got, want) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 33d08fa..9d92bfe 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -100,6 +100,7 @@ type DeployTarget struct { Artifact string `yaml:"artifact"` // file/dir to ship; default = the built binary Restart string `yaml:"restart"` // remote command run after upload RemoteBuild bool `yaml:"remote_build"` // rsync source and build on the server + Include []string `yaml:"include"` // extra paths --remote-build may ship despite the default excludes (e.g. ".env.production.example") GOOS string `yaml:"goos"` // target OS for the binary (default linux) GOARCH string `yaml:"goarch"` // target arch (default amd64) Binary string `yaml:"binary"` // output binary name (default = project name)