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
66 changes: 65 additions & 1 deletion cmd/promptctl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,9 @@ func logCmd(args []string) {
// commits it there — the dev → staging → prod version promotion. A no-op (the
// prompt already matches on `to`) reports "already up to date" instead of failing
// on an empty commit. The branch (or commit) checked out before is restored after.
// ponytail: assumes both branches exist and the tree is clean; go-git errors surface as-is.
// It refuses to run with staged or modified tracked files: the checkout round
// trip through `to` would silently reset them.
// ponytail: assumes both branches exist; go-git errors surface as-is.
func promote(args []string) {
if len(args) != 3 {
log.Fatal("usage: promptctl promote <file.prompt> <from-branch> <to-branch>")
Expand All @@ -227,11 +229,17 @@ func promote(args []string) {
}

wt := worktree(r)
if dirty := trackedChanges(r, wt); len(dirty) > 0 {
log.Fatalf("promote needs a clean working tree; commit or stash first: %s", strings.Join(dirty, ", "))
}
head, err := r.Head()
if err != nil {
log.Fatal(err)
}
if err := wt.Checkout(&git.CheckoutOptions{Branch: plumbing.NewBranchReferenceName(to)}); err != nil {
// go-git can move HEAD before it fails; put it back so the user is not
// left on `to` with their own files in the tree.
restoreHead(r, head)
log.Fatalf("checkout %s: %v", to, err)
}
h, err := commitFile(r, wt, path, content, fmt.Sprintf("promote %s: %s -> %s", path, from, to))
Expand All @@ -251,6 +259,56 @@ func promote(args []string) {
fmt.Printf("promoted %s onto %s (%s)\n", path, to, h.String()[:12])
}

// trackedChanges lists files that are staged or modified. Untracked files are
// left alone by the checkout round trip, so they don't block promote.
//
// go-git ignores core.autocrlf whenever it has to hash a file (a racy index
// entry, a touched file), so a CRLF checkout of an LF blob shows as modified on
// Windows, and go-git's own Checkout then refuses to run. Such a file is not a
// change: it is rewritten with its committed content (only its line endings
// change, as they do for every file go-git checks out) and not reported.
func trackedChanges(r *git.Repository, wt *git.Worktree) []string {
st, err := wt.Status()
if err != nil {
log.Fatal(err)
}
var head *object.Tree
var dirty []string
for f, fs := range st {
if fs.Staging == git.Untracked && fs.Worktree == git.Untracked {
continue
}
if fs.Staging == git.Unmodified && fs.Worktree == git.Modified {
if head == nil {
head = treeAt(r, "HEAD")
}
committed := blobContent(head, f)
if sameIgnoringLineEndings(committed, diskContent(f)) {
if err := os.WriteFile(filepath.FromSlash(f), []byte(committed), 0o644); err != nil {
log.Fatal(err)
}
continue
}
}
if fs.Staging != git.Unmodified || fs.Worktree != git.Unmodified {
dirty = append(dirty, f)
}
}
sort.Strings(dirty)
return dirty
}

// restoreHead points HEAD back at the branch (or detached commit) it was on.
func restoreHead(r *git.Repository, head *plumbing.Reference) {
ref := plumbing.NewHashReference(plumbing.HEAD, head.Hash())
if head.Name().IsBranch() {
ref = plumbing.NewSymbolicReference(plumbing.HEAD, head.Name())
}
if err := r.Storer.SetReference(ref); err != nil {
log.Printf("could not restore HEAD to %s: %v", head.Name().Short(), err)
}
}

// commitFile writes content to path in the checked-out worktree and commits it.
func commitFile(r *git.Repository, wt *git.Worktree, path, content, msg string) (plumbing.Hash, error) {
if err := os.WriteFile(filepath.FromSlash(path), []byte(content), 0o644); err != nil {
Expand Down Expand Up @@ -549,3 +607,9 @@ func firstLine(s string) string {
func splitLines(s string) []string {
return strings.Split(strings.ReplaceAll(s, "\r\n", "\n"), "\n")
}

// sameIgnoringLineEndings reports whether two versions differ only in CRLF vs
// LF — a core.autocrlf checkout on Windows is not a change.
func sameIgnoringLineEndings(a, b string) bool {
return strings.ReplaceAll(a, "\r\n", "\n") == strings.ReplaceAll(b, "\r\n", "\n")
}
145 changes: 145 additions & 0 deletions cmd/promptctl/promote_dirty_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package main

import (
"os"
"os/exec"
"strings"
"testing"

"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
)

// promoteRepo makes a repo on master whose acme/a.prompt differs on dev, with
// acme/b.prompt committed everywhere, and chdirs into it.
func promoteRepo(t *testing.T) *git.Repository {
t.Helper()
dir := t.TempDir()
t.Chdir(dir)
r, err := git.PlainInit(dir, false)
if err != nil {
t.Fatal(err)
}
wt, _ := r.Worktree()
sig := &object.Signature{Name: "t", Email: "t@t"}
write := func(path, content string) {
t.Helper()
if err := os.MkdirAll("acme", 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
t.Fatal(err)
}
}
write("acme/a.prompt", "A v1 {x}\n")
write("acme/b.prompt", "B v1 {y}\n")
wt.Add("acme")
if _, err := wt.Commit("init", &git.CommitOptions{Author: sig}); err != nil {
t.Fatal(err)
}
head, _ := r.Head()
for _, b := range []string{"dev", "prod"} {
r.Storer.SetReference(plumbing.NewHashReference(plumbing.NewBranchReferenceName(b), head.Hash()))
}
wt.Checkout(&git.CheckoutOptions{Branch: plumbing.NewBranchReferenceName("dev")})
write("acme/a.prompt", "A v2 {x}\n")
wt.Add("acme/a.prompt")
if _, err := wt.Commit("dev edit", &git.CommitOptions{Author: sig}); err != nil {
t.Fatal(err)
}
if err := wt.Checkout(&git.CheckoutOptions{Branch: plumbing.NewBranchReferenceName("master")}); err != nil {
t.Fatal(err)
}
return r
}

// runPromote runs promote in a child process (it exits via log.Fatal) and
// returns its combined output and whether it failed.
func runPromote(t *testing.T, args ...string) (string, bool) {
t.Helper()
cmd := exec.Command(os.Args[0], "-test.run=^TestPromoteHelperProcess$")
cmd.Env = append(os.Environ(), "PROMPTCTL_PROMOTE_ARGS="+strings.Join(args, ","))
out, err := cmd.CombinedOutput()
return string(out), err != nil
}

func TestPromoteHelperProcess(t *testing.T) {
args := os.Getenv("PROMPTCTL_PROMOTE_ARGS")
if args == "" {
t.Skip("helper for runPromote")
}
promote(strings.Split(args, ","))
os.Exit(0)
}

func TestPromoteRefusesStagedChanges(t *testing.T) {
r := promoteRepo(t)
wt, _ := r.Worktree()
os.WriteFile("acme/b.prompt", []byte("B staged {y}\n"), 0o644)
os.WriteFile("acme/n.prompt", []byte("N new {n}\n"), 0o644)
wt.Add("acme")

out, failed := runPromote(t, "acme/a.prompt", "dev", "prod")
if !failed || !strings.Contains(out, "clean working tree") {
t.Fatalf("promote with staged changes: failed=%v out=%q, want refusal", failed, out)
}
if got := diskContent("acme/b.prompt"); got != "B staged {y}\n" {
t.Errorf("staged edit lost: b.prompt = %q", got)
}
if got := diskContent("acme/n.prompt"); got != "N new {n}\n" {
t.Errorf("staged new file lost: n.prompt = %q", got)
}
if st, _ := wt.Status(); st.File("acme/n.prompt").Staging != git.Added {
t.Errorf("n.prompt no longer staged: %q", st.File("acme/n.prompt").Staging)
}
if got := blobContent(treeAt(r, "prod"), "acme/a.prompt"); got != "A v1 {x}\n" {
t.Errorf("prod changed to %q although promote refused", got)
}
}

func TestPromoteRefusesUnstagedChangesAndStaysOnBranch(t *testing.T) {
r := promoteRepo(t)
os.WriteFile("acme/b.prompt", []byte("B wip {y}\n"), 0o644)

out, failed := runPromote(t, "acme/a.prompt", "dev", "prod")
if !failed || !strings.Contains(out, "clean working tree") {
t.Fatalf("promote with unstaged changes: failed=%v out=%q, want refusal", failed, out)
}
if h, _ := r.Head(); h.Name().Short() != "master" {
t.Errorf("HEAD is %s after refused promote, want master", h.Name().Short())
}
if got := diskContent("acme/b.prompt"); got != "B wip {y}\n" {
t.Errorf("unstaged edit lost: b.prompt = %q", got)
}
}

// A CRLF checkout of an LF blob (core.autocrlf on Windows) is not a change,
// even when go-git's status reports it as modified.
func TestPromoteAllowsLineEndingOnlyDifferences(t *testing.T) {
r := promoteRepo(t)
os.WriteFile("acme/b.prompt", []byte("B v1 {y}\r\n"), 0o644)

promote([]string{"acme/a.prompt", "dev", "prod"})

if got := blobContent(treeAt(r, "prod"), "acme/a.prompt"); got != "A v2 {x}\n" {
t.Errorf("prod has %q, want promoted content", got)
}
}

func TestPromoteAllowsUntrackedFiles(t *testing.T) {
r := promoteRepo(t)
os.WriteFile("notes.txt", []byte("scratch"), 0o644)

promote([]string{"acme/a.prompt", "dev", "prod"})

if got := blobContent(treeAt(r, "prod"), "acme/a.prompt"); got != "A v2 {x}\n" {
t.Errorf("prod has %q, want promoted content", got)
}
if b, err := os.ReadFile("notes.txt"); err != nil || string(b) != "scratch" {
t.Errorf("untracked file lost: %q %v", b, err)
}
if h, _ := r.Head(); h.Name().Short() != "master" {
t.Errorf("HEAD is %s, want master", h.Name().Short())
}
}
Loading