Files
skillshare/internal/git/info_test.go
T
Willie 9dab28fc19 fix(git): undo a pull's partial checkout and explain permission errors
When git cannot finish a pull's checkout (for example, it may not unlink
a root-owned file), it stops without undoing the files it already wrote,
and with no MERGE_HEAD there is nothing for merge --abort to undo. The
remote's copies then showed up as local changes: the dashboard blocked
the next pull and suggested committing them, which would push the stale
remote content back as a new commit.

A failed pull now restores paths that were clean before it started and
now hold exactly the upstream version, leaving the user's own edits
alone. The dashboard reports permission failures with a
permission_denied code and shows the chown command that gives the
source folder back to the current user.
2026-09-27 02:10:12 +08:00

994 lines
29 KiB
Go

package git
import (
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"skillshare/internal/install"
)
// initTestRepo creates a temporary git repo with one commit
func initTestRepo(t *testing.T) string {
t.Helper()
dir := t.TempDir()
run := func(args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(),
"GIT_AUTHOR_NAME=test",
"GIT_AUTHOR_EMAIL=test@test.com",
"GIT_COMMITTER_NAME=test",
"GIT_COMMITTER_EMAIL=test@test.com",
)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v failed: %s\n%s", args, err, out)
}
}
run("init")
run("config", "user.email", "test@test.com")
run("config", "user.name", "test")
os.WriteFile(filepath.Join(dir, "README.md"), []byte("# test"), 0644)
run("add", "-A")
run("commit", "-m", "initial")
return dir
}
// TestPushRemoteWithEnv_TokenNotInError uses a fake git executable to verify
// that PushRemoteWithEnv sanitizes credential-bearing content from git error
// output. This does not assume every real git failure prints credentials; it
// verifies that this wrapper does not return sensitive subprocess output
// verbatim when such output is present.
func TestPushRemoteWithEnv_TokenNotInError(t *testing.T) {
const token = "ghp_test_token_12345_redact"
const fakeGitErr = "fatal: unable to access 'https://x-access-token:" + token + "@github.com/org/repo.git/': Could not resolve host: github.com"
fakeBin := t.TempDir()
fakeGit := filepath.Join(fakeBin, "git")
script := "#!/bin/sh\n" +
"echo \"" + fakeGitErr + "\" >&2\n" +
"exit 128\n"
if err := os.WriteFile(fakeGit, []byte(script), 0755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", fakeBin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("GITHUB_TOKEN", token)
extraEnv := []string{
"GIT_CONFIG_COUNT=1",
"GIT_CONFIG_KEY_0=url.https://x-access-token:" + token + "@github.com/.insteadOf",
"GIT_CONFIG_VALUE_0=https://github.com/",
}
err := PushRemoteWithEnv(t.TempDir(), extraEnv)
if err == nil {
t.Fatal("expected git push to fail")
}
msg := err.Error()
// Token must not appear in error output.
if strings.Contains(msg, token) {
t.Fatalf("token leaked in error: %v", err)
}
// Useful diagnostic text should survive sanitization.
if !strings.Contains(msg, "Could not resolve host") && !strings.Contains(msg, "unable to access") {
t.Fatalf("expected useful diagnostic in error, got: %v", err)
}
}
func TestPushRemoteWithEnv_PreservesStdoutDiagnostics(t *testing.T) {
const token = "ghp_stdout_token_12345_redact"
const stdoutDiagnostic = "pre-push hook rejected branch https://x-access-token:" + token + "@github.com/org/repo.git/"
fakeBin := t.TempDir()
fakeGit := filepath.Join(fakeBin, "git")
script := "#!/bin/sh\n" +
"echo \"" + stdoutDiagnostic + "\"\n" +
"echo \"error: failed to push some refs to 'https://github.com/org/repo.git'\" >&2\n" +
"exit 1\n"
if err := os.WriteFile(fakeGit, []byte(script), 0755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", fakeBin+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("GITHUB_TOKEN", token)
extraEnv := []string{
"GIT_CONFIG_COUNT=1",
"GIT_CONFIG_KEY_0=url.https://x-access-token:" + token + "@github.com/.insteadOf",
"GIT_CONFIG_VALUE_0=https://github.com/",
}
err := PushRemoteWithEnv(t.TempDir(), extraEnv)
if err == nil {
t.Fatal("expected git push to fail")
}
msg := err.Error()
if strings.Contains(msg, token) {
t.Fatalf("token leaked in error: %v", err)
}
if !strings.Contains(msg, "pre-push hook rejected branch") {
t.Fatalf("expected stdout diagnostic in error, got: %v", err)
}
if !strings.Contains(msg, "failed to push some refs") {
t.Fatalf("expected stderr diagnostic in error, got: %v", err)
}
}
func TestIsRepo(t *testing.T) {
repo := initTestRepo(t)
if !IsRepo(repo) {
t.Error("expected IsRepo to return true for a git repo")
}
notRepo := t.TempDir()
if IsRepo(notRepo) {
t.Error("expected IsRepo to return false for a non-repo dir")
}
}
func TestHasRemote(t *testing.T) {
repo := initTestRepo(t)
if HasRemote(repo) {
t.Error("expected HasRemote to return false for repo without remote")
}
// Add a remote
cmd := exec.Command("git", "remote", "add", "origin", "https://example.com/repo.git")
cmd.Dir = repo
if err := cmd.Run(); err != nil {
t.Fatal(err)
}
if !HasRemote(repo) {
t.Error("expected HasRemote to return true after adding remote")
}
}
func TestGetCurrentBranch(t *testing.T) {
repo := initTestRepo(t)
branch, err := GetCurrentBranch(repo)
if err != nil {
t.Fatal(err)
}
// Default branch could be main or master depending on git config
if branch != "main" && branch != "master" {
t.Errorf("unexpected branch name: %s", branch)
}
}
func TestStageAndCommit(t *testing.T) {
repo := initTestRepo(t)
// Create a new file
os.WriteFile(filepath.Join(repo, "new.txt"), []byte("hello"), 0644)
// Stage all
if err := StageAll(repo); err != nil {
t.Fatalf("StageAll failed: %v", err)
}
// Commit
if err := Commit(repo, "add new file"); err != nil {
t.Fatalf("Commit failed: %v", err)
}
// Should be clean now
dirty, err := IsDirty(repo)
if err != nil {
t.Fatal(err)
}
if dirty {
t.Error("expected repo to be clean after commit")
}
}
func TestGetStatus(t *testing.T) {
repo := initTestRepo(t)
// Clean repo
status, err := GetStatus(repo)
if err != nil {
t.Fatal(err)
}
if status != "" {
t.Errorf("expected empty status for clean repo, got: %q", status)
}
// Create untracked file
os.WriteFile(filepath.Join(repo, "untracked.txt"), []byte("x"), 0644)
status, err = GetStatus(repo)
if err != nil {
t.Fatal(err)
}
if status == "" {
t.Error("expected non-empty status after adding untracked file")
}
}
func TestIsDirtyAndGetDirtyFiles(t *testing.T) {
repo := initTestRepo(t)
dirty, err := IsDirty(repo)
if err != nil {
t.Fatal(err)
}
if dirty {
t.Error("expected clean repo")
}
// Modify a file
os.WriteFile(filepath.Join(repo, "README.md"), []byte("# modified"), 0644)
dirty, err = IsDirty(repo)
if err != nil {
t.Fatal(err)
}
if !dirty {
t.Error("expected dirty repo")
}
files, err := GetDirtyFiles(repo)
if err != nil {
t.Fatal(err)
}
if len(files) == 0 {
t.Error("expected at least one dirty file")
}
}
func addRemote(t *testing.T, repoPath, remoteURL string) {
t.Helper()
cmd := exec.Command("git", "remote", "add", "origin", remoteURL)
cmd.Dir = repoPath
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("failed to add remote: %v (%s)", err, strings.TrimSpace(string(out)))
}
}
func TestAuthEnvForRepo_UsesGitHubToken(t *testing.T) {
repo := initTestRepo(t)
addRemote(t, repo, "https://github.com/org/private-repo.git")
t.Setenv("GITHUB_TOKEN", "ghp_test_token_123")
env := AuthEnvForRepo(repo)
if len(env) != 3 {
t.Fatalf("expected auth env with 3 entries, got %d: %v", len(env), env)
}
if !strings.Contains(env[1], "url.https://x-access-token:ghp_test_token_123@github.com/.insteadOf") {
t.Fatalf("unexpected auth key env: %q", env[1])
}
if !strings.Contains(env[2], "https://github.com/") {
t.Fatalf("unexpected auth value env: %q", env[2])
}
}
func TestAuthEnvForRepo_UsesGitLabToken(t *testing.T) {
repo := initTestRepo(t)
addRemote(t, repo, "https://gitlab.com/group/private-repo.git")
t.Setenv("GITLAB_TOKEN", "glpat_test_token_123")
env := AuthEnvForRepo(repo)
if len(env) != 3 {
t.Fatalf("expected auth env with 3 entries, got %d: %v", len(env), env)
}
if !strings.Contains(env[1], "url.https://oauth2:glpat_test_token_123@gitlab.com/.insteadOf") {
t.Fatalf("unexpected auth key env: %q", env[1])
}
if !strings.Contains(env[2], "https://gitlab.com/") {
t.Fatalf("unexpected auth value env: %q", env[2])
}
}
func TestAuthEnvForRepo_NoTokenReturnsNil(t *testing.T) {
repo := initTestRepo(t)
addRemote(t, repo, "https://github.com/org/private-repo.git")
t.Setenv("GITHUB_TOKEN", "")
t.Setenv("SKILLSHARE_GIT_TOKEN", "")
env := AuthEnvForRepo(repo)
if env != nil {
t.Fatalf("expected nil auth env without tokens, got: %v", env)
}
}
func TestAuthEnvForRepo_SSHRemote_ReturnsNil(t *testing.T) {
repo := initTestRepo(t)
addRemote(t, repo, "git@github.com:org/private-repo.git")
t.Setenv("GITHUB_TOKEN", "ghp_test_token_123")
t.Setenv("SKILLSHARE_GIT_TOKEN", "generic-token")
env := AuthEnvForRepo(repo)
if env != nil {
t.Fatalf("expected nil auth env for SSH remote, got: %v", env)
}
}
func TestGetRemoteDefaultBranch_UsesOriginHEAD(t *testing.T) {
remote := createBareRemoteWithBranch(t, "trunk", map[string]string{
"README.md": "# trunk\n",
})
repo := cloneRepo(t, remote)
branch, err := GetRemoteDefaultBranch(repo)
if err != nil {
t.Fatalf("GetRemoteDefaultBranch failed: %v", err)
}
if branch != "trunk" {
t.Fatalf("expected trunk, got %q", branch)
}
}
func TestGetRemoteDefaultBranch_FallbackMainMaster(t *testing.T) {
for _, wantBranch := range []string{"main", "master"} {
t.Run(wantBranch, func(t *testing.T) {
remote := createBareRemoteWithBranch(t, wantBranch, map[string]string{
"README.md": "# " + wantBranch + "\n",
})
repo := cloneRepo(t, remote)
runGit(t, repo, "update-ref", "-d", "refs/remotes/origin/HEAD")
branch, err := GetRemoteDefaultBranch(repo)
if err != nil {
t.Fatalf("GetRemoteDefaultBranch failed: %v", err)
}
if branch != wantBranch {
t.Fatalf("expected %s, got %q", wantBranch, branch)
}
})
}
}
func TestGetRemoteDefaultBranch_FallbackFirstRemoteBranch(t *testing.T) {
remote := createBareRemoteWithBranch(t, "release", map[string]string{
"README.md": "# release\n",
})
repo := cloneRepo(t, remote)
runGit(t, repo, "update-ref", "-d", "refs/remotes/origin/HEAD")
branch, err := GetRemoteDefaultBranch(repo)
if err != nil {
t.Fatalf("GetRemoteDefaultBranch failed: %v", err)
}
if branch != "release" {
t.Fatalf("expected release, got %q", branch)
}
}
func TestHasRemoteSkillDirs(t *testing.T) {
remote := createBareRemoteWithBranch(t, "main", map[string]string{
"README.md": "# docs\n",
"skill-one/SKILL.md": "# one\n",
"skill-two/README.txt": "x\n",
})
repo := cloneRepo(t, remote)
hasSkills, err := HasRemoteSkillDirs(repo, "main")
if err != nil {
t.Fatalf("HasRemoteSkillDirs failed: %v", err)
}
if !hasSkills {
t.Fatal("expected remote to have skill directories")
}
}
func TestHasLocalSkillDirs(t *testing.T) {
repo := initTestRepo(t)
hasSkills, err := HasLocalSkillDirs(repo)
if err != nil {
t.Fatalf("HasLocalSkillDirs failed: %v", err)
}
if hasSkills {
t.Fatal("expected no local skill directories in fresh repo")
}
if err := os.MkdirAll(filepath.Join(repo, "my-skill"), 0o755); err != nil {
t.Fatalf("failed to create local skill dir: %v", err)
}
hasSkills, err = HasLocalSkillDirs(repo)
if err != nil {
t.Fatalf("HasLocalSkillDirs failed: %v", err)
}
if !hasSkills {
t.Fatal("expected local skill directory to be detected")
}
}
func TestGetChangedFiles_Rename(t *testing.T) {
repo := initTestRepo(t)
// Record the starting commit
fromHash := runGit(t, repo, "rev-parse", "HEAD")
// Rename README.md → GUIDE.md (keep content similar for rename detection)
os.Rename(filepath.Join(repo, "README.md"), filepath.Join(repo, "GUIDE.md"))
runGit(t, repo, "add", "-A")
runGit(t, repo, "commit", "-m", "rename file")
toHash := runGit(t, repo, "rev-parse", "HEAD")
changes, err := GetChangedFiles(repo, fromHash, toHash)
if err != nil {
t.Fatalf("GetChangedFiles failed: %v", err)
}
// Should have at least one rename entry
var found bool
for _, c := range changes {
if c.Status == "R" && c.Path == "GUIDE.md" {
found = true
if c.OldPath != "README.md" {
t.Errorf("expected OldPath=README.md, got %q", c.OldPath)
}
break
}
}
if !found {
t.Errorf("expected rename entry for GUIDE.md, got: %+v", changes)
}
}
func TestGetChangedFiles_AddModifyDelete(t *testing.T) {
repo := initTestRepo(t)
// Add a file to delete later
os.WriteFile(filepath.Join(repo, "to-delete.txt"), []byte("delete me"), 0644)
runGit(t, repo, "add", "-A")
runGit(t, repo, "commit", "-m", "add to-delete")
fromHash := runGit(t, repo, "rev-parse", "HEAD")
// Add new, modify existing, delete file
os.WriteFile(filepath.Join(repo, "new.txt"), []byte("new file"), 0644)
os.WriteFile(filepath.Join(repo, "README.md"), []byte("# modified"), 0644)
os.Remove(filepath.Join(repo, "to-delete.txt"))
runGit(t, repo, "add", "-A")
runGit(t, repo, "commit", "-m", "mixed changes")
toHash := runGit(t, repo, "rev-parse", "HEAD")
changes, err := GetChangedFiles(repo, fromHash, toHash)
if err != nil {
t.Fatalf("GetChangedFiles failed: %v", err)
}
statuses := map[string]string{}
for _, c := range changes {
statuses[c.Path] = c.Status
}
if statuses["new.txt"] != "A" {
t.Errorf("expected new.txt=A, got %q", statuses["new.txt"])
}
if statuses["README.md"] != "M" {
t.Errorf("expected README.md=M, got %q", statuses["README.md"])
}
if statuses["to-delete.txt"] != "D" {
t.Errorf("expected to-delete.txt=D, got %q", statuses["to-delete.txt"])
}
}
func TestPullWithProgress(t *testing.T) {
remote := createBareRemoteWithBranch(t, "main", map[string]string{
"README.md": "# v1\n",
})
repo := cloneRepo(t, remote)
updater := filepath.Join(t.TempDir(), "updater")
runGit(t, "", "clone", remote, updater)
runGit(t, updater, "config", "user.email", "test@test.com")
runGit(t, updater, "config", "user.name", "test")
if err := os.WriteFile(filepath.Join(updater, "README.md"), []byte("# v2\n"), 0644); err != nil {
t.Fatalf("failed writing update: %v", err)
}
runGit(t, updater, "add", "-A")
runGit(t, updater, "commit", "-m", "update")
runGit(t, updater, "push", "origin", "HEAD:main")
info, err := PullWithProgress(repo, nil, func(string) {})
if err != nil {
t.Fatalf("PullWithProgress failed: %v", err)
}
if info.UpToDate {
t.Fatalf("expected update to pull new commit")
}
if info.AfterHash == info.BeforeHash {
t.Fatalf("expected before/after hash to differ")
}
}
// divergeFromRemote commits remoteFile on another clone and pushes it, then
// commits localFile in repo without pushing, as two machines syncing would.
func divergeFromRemote(t *testing.T, remote, repo string, remoteFile, localFile [2]string) {
t.Helper()
other := cloneRepo(t, remote)
for _, c := range []struct {
dir string
file [2]string
}{{other, remoteFile}, {repo, localFile}} {
runGit(t, c.dir, "config", "user.email", "test@test.com")
runGit(t, c.dir, "config", "user.name", "test")
if err := os.WriteFile(filepath.Join(c.dir, c.file[0]), []byte(c.file[1]), 0644); err != nil {
t.Fatal(err)
}
runGit(t, c.dir, "add", "-A")
runGit(t, c.dir, "commit", "-m", "edit "+c.file[0])
}
runGit(t, other, "push", "origin", "HEAD:main")
}
func TestPullWithProgress_MergesDivergedHistory(t *testing.T) {
remote := createBareRemoteWithBranch(t, "main", map[string]string{"README.md": "# v1\n"})
repo := cloneRepo(t, remote)
divergeFromRemote(t, remote, repo, [2]string{"remote.md", "r\n"}, [2]string{"local.md", "l\n"})
if _, err := PullWithProgress(repo, nil, nil); err != nil {
t.Fatalf("expected diverged pull to merge, got: %v", err)
}
for _, f := range []string{"remote.md", "local.md"} {
if _, err := os.Stat(filepath.Join(repo, f)); err != nil {
t.Errorf("expected %s after merge: %v", f, err)
}
}
}
func TestPullWithProgress_ConflictLeavesRepoClean(t *testing.T) {
remote := createBareRemoteWithBranch(t, "main", map[string]string{"README.md": "# v1\n"})
repo := cloneRepo(t, remote)
divergeFromRemote(t, remote, repo, [2]string{"README.md", "# remote\n"}, [2]string{"README.md", "# local\n"})
if _, err := PullWithProgress(repo, nil, nil); err == nil {
t.Fatal("expected a conflicting pull to fail")
}
if status := runGit(t, repo, "status", "--porcelain"); status != "" {
t.Fatalf("expected the merge to be aborted, got status:\n%s", status)
}
}
// blockedPull pushes a remote commit that edits a.txt, adds added.txt, and
// edits sub/b.txt, then makes sub/ read-only so the pull fails partway: git
// writes a.txt and added.txt before it cannot unlink sub/b.txt.
func blockedPull(t *testing.T) string {
t.Helper()
if os.Getuid() == 0 {
t.Skip("test requires non-root user")
}
remote := createBareRemoteWithBranch(t, "main", map[string]string{
"a.txt": "a1\n", "sub/b.txt": "b1\n",
})
repo := cloneRepo(t, remote)
other := cloneRepo(t, remote)
runGit(t, other, "config", "user.email", "test@test.com")
runGit(t, other, "config", "user.name", "test")
for name, body := range map[string]string{"a.txt": "a2\n", "added.txt": "new\n", "sub/b.txt": "b2\n"} {
if err := os.WriteFile(filepath.Join(other, name), []byte(body), 0644); err != nil {
t.Fatal(err)
}
}
runGit(t, other, "add", "-A")
runGit(t, other, "commit", "-m", "remote edits")
runGit(t, other, "push", "origin", "HEAD:main")
sub := filepath.Join(repo, "sub")
if err := os.Chmod(sub, 0555); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.Chmod(sub, 0755) })
return repo
}
func TestPullWithProgress_FailedCheckoutLeavesNoResidue(t *testing.T) {
repo := blockedPull(t)
if _, err := PullWithProgress(repo, nil, nil); err == nil {
t.Fatal("expected the pull to fail on the read-only directory")
}
if status := runGit(t, repo, "status", "--porcelain", "-uall"); status != "" {
t.Fatalf("expected the partial checkout to be undone, got status:\n%s", status)
}
}
func TestPullWithProgress_FailedCheckoutKeepsLocalEdits(t *testing.T) {
repo := blockedPull(t)
notes := filepath.Join(repo, "notes.txt")
if err := os.WriteFile(notes, []byte("mine\n"), 0644); err != nil {
t.Fatal(err)
}
if _, err := PullWithProgress(repo, nil, nil); err == nil {
t.Fatal("expected the pull to fail on the read-only directory")
}
if got, err := os.ReadFile(notes); err != nil || string(got) != "mine\n" {
t.Fatalf("expected the local edit to survive, got %q (%v)", got, err)
}
}
func TestPullWithProgress_ResolvesMetadataConflict(t *testing.T) {
meta := func(entries string) string {
return `{"version": 1, "entries": {` + entries + `}}` + "\n"
}
shared := func(at string) string {
return `"shared": {"source": "github.com/o/r/shared", "installed_at": "` + at + `"}`
}
remote := createBareRemoteWithBranch(t, "main", map[string]string{
".metadata.json": meta(shared("2026-01-01T00:00:00Z")),
})
repo := cloneRepo(t, remote)
divergeFromRemote(t, remote, repo,
[2]string{".metadata.json", meta(shared("2026-03-01T00:00:00Z") + `, "remote-only": {"source": "r"}`)},
[2]string{".metadata.json", meta(shared("2026-02-01T00:00:00Z") + `, "local-only": {"source": "l"}`)})
if _, err := PullWithProgress(repo, nil, nil); err != nil {
t.Fatalf("expected a metadata-only conflict to resolve, got: %v", err)
}
store, err := install.LoadMetadata(repo)
if err != nil {
t.Fatal(err)
}
for _, name := range []string{"remote-only", "local-only"} {
if !store.Has(name) {
t.Errorf("expected entry %q after merge", name)
}
}
if got := store.Get("shared").InstalledAt.Format("2006-01-02"); got != "2026-03-01" {
t.Errorf("expected the later installed_at to win, got %s", got)
}
if status := runGit(t, repo, "status", "--porcelain"); status != "" {
t.Fatalf("expected the merge to be committed, got status:\n%s", status)
}
}
func TestForcePullWithProgress(t *testing.T) {
remote := createBareRemoteWithBranch(t, "main", map[string]string{
"README.md": "# v1\n",
})
repo := cloneRepo(t, remote)
runGit(t, repo, "config", "user.email", "test@test.com")
runGit(t, repo, "config", "user.name", "test")
// Add remote commit.
updater := filepath.Join(t.TempDir(), "updater")
runGit(t, "", "clone", remote, updater)
runGit(t, updater, "config", "user.email", "test@test.com")
runGit(t, updater, "config", "user.name", "test")
if err := os.WriteFile(filepath.Join(updater, "README.md"), []byte("# remote\n"), 0644); err != nil {
t.Fatalf("failed writing remote update: %v", err)
}
runGit(t, updater, "add", "-A")
runGit(t, updater, "commit", "-m", "remote update")
runGit(t, updater, "push", "origin", "HEAD:main")
// Create divergent local commit.
if err := os.WriteFile(filepath.Join(repo, "local.txt"), []byte("local"), 0644); err != nil {
t.Fatalf("failed writing local update: %v", err)
}
runGit(t, repo, "add", "-A")
runGit(t, repo, "commit", "-m", "local change")
info, err := ForcePullWithProgress(repo, nil, func(string) {})
if err != nil {
t.Fatalf("ForcePullWithProgress failed: %v", err)
}
if info.UpToDate {
t.Fatalf("expected force pull to change local hash")
}
if info.AfterHash == info.BeforeHash {
t.Fatalf("expected before/after hash to differ")
}
content, err := os.ReadFile(filepath.Join(repo, "README.md"))
if err != nil {
t.Fatalf("failed reading README after force pull: %v", err)
}
if !strings.Contains(string(content), "remote") {
t.Fatalf("expected repo to reset to remote content, got: %s", content)
}
}
func TestListLocalBranches(t *testing.T) {
repo := initTestRepo(t)
branches, err := ListLocalBranches(repo)
if err != nil {
t.Fatalf("ListLocalBranches failed: %v", err)
}
if len(branches) != 1 {
t.Fatalf("expected 1 branch, got %d: %v", len(branches), branches)
}
// Create another branch
runGit(t, repo, "branch", "feature-x")
branches, err = ListLocalBranches(repo)
if err != nil {
t.Fatalf("ListLocalBranches failed: %v", err)
}
if len(branches) != 2 {
t.Fatalf("expected 2 branches, got %d: %v", len(branches), branches)
}
found := false
for _, b := range branches {
if b == "feature-x" {
found = true
}
}
if !found {
t.Errorf("expected to find feature-x in %v", branches)
}
}
func TestListRemoteBranches(t *testing.T) {
remote := createBareRemoteWithBranch(t, "main", map[string]string{
"README.md": "# test\n",
})
repo := cloneRepo(t, remote)
// Push a second branch to remote
updater := filepath.Join(t.TempDir(), "updater")
runGit(t, "", "clone", remote, updater)
runGit(t, updater, "config", "user.email", "test@test.com")
runGit(t, updater, "config", "user.name", "test")
runGit(t, updater, "checkout", "-b", "develop")
os.WriteFile(filepath.Join(updater, "dev.txt"), []byte("dev"), 0644)
runGit(t, updater, "add", "-A")
runGit(t, updater, "commit", "-m", "dev branch")
runGit(t, updater, "push", "origin", "develop")
// Fetch so repo knows about remote develop
runGit(t, repo, "fetch")
remoteBranches, err := ListRemoteBranches(repo)
if err != nil {
t.Fatalf("ListRemoteBranches failed: %v", err)
}
// "main" is local, so only "develop" should appear as remote-only
found := false
for _, b := range remoteBranches {
if b == "main" {
t.Error("main should not be in remote-only list (it exists locally)")
}
if b == "develop" {
found = true
}
}
if !found {
t.Errorf("expected develop in remote branches, got: %v", remoteBranches)
}
}
func TestCheckout_LocalBranch(t *testing.T) {
repo := initTestRepo(t)
// Create a local branch and switch back
runGit(t, repo, "branch", "feature-a")
if err := Checkout(repo, "feature-a"); err != nil {
t.Fatalf("Checkout local branch failed: %v", err)
}
branch, _ := GetCurrentBranch(repo)
if branch != "feature-a" {
t.Errorf("expected branch feature-a, got %s", branch)
}
}
func TestCheckout_RemoteBranch(t *testing.T) {
remote := createBareRemoteWithBranch(t, "main", map[string]string{
"README.md": "# test\n",
})
repo := cloneRepo(t, remote)
// Push a develop branch to remote via another clone
updater := filepath.Join(t.TempDir(), "updater")
runGit(t, "", "clone", remote, updater)
runGit(t, updater, "config", "user.email", "test@test.com")
runGit(t, updater, "config", "user.name", "test")
runGit(t, updater, "checkout", "-b", "develop")
os.WriteFile(filepath.Join(updater, "dev.txt"), []byte("dev"), 0644)
runGit(t, updater, "add", "-A")
runGit(t, updater, "commit", "-m", "dev branch")
runGit(t, updater, "push", "origin", "develop")
// Fetch so repo sees origin/develop
runGit(t, repo, "fetch")
// Checkout remote-only branch
if err := Checkout(repo, "develop"); err != nil {
t.Fatalf("Checkout remote branch failed: %v", err)
}
branch, _ := GetCurrentBranch(repo)
if branch != "develop" {
t.Errorf("expected branch develop, got %s", branch)
}
}
func TestCheckout_NonexistentBranch(t *testing.T) {
repo := initTestRepo(t)
err := Checkout(repo, "does-not-exist")
if err == nil {
t.Error("expected error for non-existent branch")
}
}
func TestGetRemoteURL(t *testing.T) {
dir := initTestRepo(t)
// No remote → error (git exits non-zero when no remote configured)
url, err := GetRemoteURL(dir)
if err == nil {
t.Fatal("GetRemoteURL() expected error for repo with no remote, got nil")
}
if url != "" {
t.Errorf("GetRemoteURL() = %q, want empty on error", url)
}
// Add remote
addRemote(t, dir, "https://github.com/test/repo.git")
url, err = GetRemoteURL(dir)
if err != nil {
t.Fatalf("GetRemoteURL() error: %v", err)
}
if url != "https://github.com/test/repo.git" {
t.Errorf("GetRemoteURL() = %q, want %q", url, "https://github.com/test/repo.git")
}
}
func TestGetHeadMessage(t *testing.T) {
dir := initTestRepo(t) // commits "initial"
msg, err := GetHeadMessage(dir)
if err != nil {
t.Fatalf("GetHeadMessage() error: %v", err)
}
if msg != "initial" {
t.Errorf("GetHeadMessage() = %q, want %q", msg, "initial")
}
}
func TestGetTrackingBranch(t *testing.T) {
dir := initTestRepo(t)
// No upstream → empty string, no error
branch, err := GetTrackingBranch(dir)
if err != nil {
t.Fatalf("GetTrackingBranch() error: %v", err)
}
if branch != "" {
t.Errorf("GetTrackingBranch() = %q, want empty", branch)
}
}
func runGit(t *testing.T, dir string, args ...string) string {
t.Helper()
cmd := exec.Command("git", args...)
if dir != "" {
cmd.Dir = dir
}
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v failed: %v (%s)", args, err, strings.TrimSpace(string(out)))
}
return strings.TrimSpace(string(out))
}
func createBareRemoteWithBranch(t *testing.T, branch string, files map[string]string) string {
t.Helper()
root := t.TempDir()
remote := filepath.Join(root, "remote.git")
runGit(t, "", "init", "--bare", remote)
seed := filepath.Join(root, "seed")
runGit(t, "", "clone", remote, seed)
runGit(t, seed, "config", "user.email", "test@test.com")
runGit(t, seed, "config", "user.name", "test")
for rel, content := range files {
path := filepath.Join(seed, rel)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatalf("failed to create dir for %s: %v", rel, err)
}
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatalf("failed to write %s: %v", rel, err)
}
}
runGit(t, seed, "add", "-A")
runGit(t, seed, "commit", "-m", "seed "+branch)
runGit(t, seed, "push", "origin", "HEAD:"+branch)
runGit(t, remote, "symbolic-ref", "HEAD", "refs/heads/"+branch)
return remote
}
func cloneRepo(t *testing.T, remote string) string {
t.Helper()
repo := filepath.Join(t.TempDir(), "repo")
runGit(t, "", "clone", remote, repo)
return repo
}
func TestSetOrAddRemote(t *testing.T) {
repo := initTestRepo(t)
// Adds origin when absent.
if err := SetOrAddRemote(repo, "https://example.com/a.git"); err != nil {
t.Fatalf("add origin: %v", err)
}
if got, _ := GetRemoteURL(repo); got != "https://example.com/a.git" {
t.Errorf("origin = %q, want a.git", got)
}
// Updates the URL when origin already exists.
if err := SetOrAddRemote(repo, "https://example.com/b.git"); err != nil {
t.Fatalf("update origin: %v", err)
}
if got, _ := GetRemoteURL(repo); got != "https://example.com/b.git" {
t.Errorf("origin = %q, want b.git", got)
}
// Rejects flag-smuggling URLs (argv injection) without invoking git.
if err := SetOrAddRemote(repo, "--upload-pack=touch /tmp/pwned"); err == nil {
t.Error("expected dash-prefixed remote URL to be rejected")
}
if got, _ := GetRemoteURL(repo); got != "https://example.com/b.git" {
t.Errorf("origin changed after rejected input: %q", got)
}
}
func TestAheadCount_CountsUnpushedCommits(t *testing.T) {
repo := cloneRepo(t, createBareRemoteWithBranch(t, "main", map[string]string{"a/SKILL.md": "# a\n"}))
runGit(t, repo, "-c", "user.name=test", "-c", "user.email=test@test.com", "commit", "--allow-empty", "-m", "local")
if got := AheadCount(repo); got != 1 {
t.Fatalf("AheadCount() = %d, want 1", got)
}
}
func TestFirstPull_MergesUnrelatedRemoteHistory(t *testing.T) {
remote := createBareRemoteWithBranch(t, "main", map[string]string{"remote-skill/SKILL.md": "# remote\n"})
repo := initTestRepo(t)
if err := os.MkdirAll(filepath.Join(repo, "local-skill"), 0o755); err != nil {
t.Fatal(err)
}
runGit(t, repo, "remote", "add", "origin", remote)
if _, err := FirstPull(repo, false); err != nil {
t.Fatalf("FirstPull() error: %v", err)
}
_, statErr := os.Stat(filepath.Join(repo, "remote-skill", "SKILL.md"))
if statErr != nil || !HasUpstream(repo) {
t.Fatalf("expected remote files merged and upstream set (stat err: %v, upstream: %v)", statErr, HasUpstream(repo))
}
}
func TestFirstPull_EmptyRemoteReportsNoBranches(t *testing.T) {
remote := filepath.Join(t.TempDir(), "remote.git")
runGit(t, "", "init", "--bare", remote)
repo := initTestRepo(t)
runGit(t, repo, "remote", "add", "origin", remote)
if _, err := FirstPull(repo, false); !errors.Is(err, ErrNoRemoteBranches) {
t.Fatalf("FirstPull() error = %v, want ErrNoRemoteBranches", err)
}
}