Skip to content

Commit 9b81f46

Browse files
bschellenberger2600cursoragentBen Schellenberger
authored
Improve testkit robustness and release readiness (#1)
## Summary - harden snapshot restoration by rejecting unsafe archive paths and skipping root pseudo-entry when creating tar snapshots - replace custom string splitting utilities with standard library parsing for remotes, branch lists, and SHA trimming - add baseline CI (`go vet` + `go test`) and expand README requirements/common usage patterns for release readiness ## Test plan - [x] `gofmt -w fixtures.go snapshots.go` - [x] `go test ./...` - [x] `go vet ./...` Made with [Cursor](https://cursor.com) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Touching snapshot restore and path handling can break existing tests or introduce regressions in file extraction behavior, though changes add explicit safety checks and new test coverage. CI/toolchain updates are low risk but may surface new failures on older Go versions. > > **Overview** > Improves release readiness by adding a GitHub Actions CI workflow that runs `go vet` and `go test` on PRs and `main`, and by expanding `README.md` plus a new `DEVELOPER_GUIDE.md` with usage and contribution/release guidance. > > Hardens snapshot creation/restoration by skipping the tar root pseudo-entry, normalizing snapshot names, and preventing path traversal/absolute paths during `RestoreSnapshot` via `safeJoin` (with new snapshot safety tests). > > Makes git-output parsing more robust by switching `GetRemotes`, `GetBranches`, and `GetCurrentSHA` to standard-library string trimming/splitting, adds coverage for remote URLs containing spaces, introduces new USB-volume fixture helpers (`usb_fixtures.go`) with tests, and updates `go.mod` to Go 1.22. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d0c6cb2. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Expanded README with API overview, quickstart, usage examples * Added developer guide with setup, testing, contribution, and release guidance * **Chores** * Updated declared Go toolchain version to 1.22 * Added CI workflow to run vet and tests on PRs and main * **Bug Fixes** * Safer snapshot restore/load path handling and normalized snapshot naming * More robust parsing of repository metadata output * **New Features** * Test utilities for USB-volume fixtures and related helpers * **Tests** * Added tests for snapshot safety, name normalization, restore behavior, remotes parsing, and USB fixture utilities <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Ben Schellenberger <TBRX103@users.noreply.github.com>
1 parent 39100e1 commit 9b81f46

10 files changed

Lines changed: 831 additions & 64 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
name: CI
2+
3+
on:
4+
push:
5+
branches:
6+
- main
7+
pull_request:
8+
9+
jobs:
10+
test:
11+
runs-on: ubuntu-latest
12+
strategy:
13+
fail-fast: false
14+
matrix:
15+
go-version: ["1.22.x", "stable"]
16+
17+
steps:
18+
- name: Checkout
19+
uses: actions/checkout@v4
20+
21+
- name: Setup Go
22+
uses: actions/setup-go@v5
23+
with:
24+
go-version: ${{ matrix.go-version }}
25+
26+
- name: Run vet
27+
run: go vet ./...
28+
29+
- name: Run tests
30+
run: go test ./...

‎DEVELOPER_GUIDE.md‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
# Developer Guide
2+
3+
This guide covers how to use `git-testkit`, contribute safely, run checks locally, and maintain releases.
4+
5+
## Audience
6+
7+
- **Users** writing tests that need real git repositories.
8+
- **Contributors** making code/docs changes.
9+
- **Maintainers/admins** preparing releases and keeping CI healthy.
10+
11+
## Local setup
12+
13+
Requirements:
14+
15+
- Go 1.22+
16+
- `git` on `PATH`
17+
18+
Clone and verify:
19+
20+
```bash
21+
# HTTPS (no SSH keys required)
22+
git clone https://github.com/git-fire/git-testkit.git
23+
24+
# or SSH
25+
# git clone git@github.com:git-fire/git-testkit.git
26+
27+
cd git-testkit
28+
go test ./...
29+
```
30+
31+
## Project structure
32+
33+
- `fixtures.go`: base repo creation and command helpers.
34+
- `scenarios.go`: fluent scenario builder and predefined multi-repo scenarios.
35+
- `snapshots.go`: snapshot/restore utilities for expensive test setup reuse.
36+
- `fixtures_test.go`: external package tests (`testutil_test`) that validate public API usage.
37+
- `scenarios_test.go`: package-internal tests for scenario/snapshot behavior.
38+
39+
## Design principles
40+
41+
- Prefer real git commands over mocks for behavior confidence.
42+
- Keep helper APIs composable and minimal.
43+
- Fail fast in setup helpers (`t.Fatalf`) so fixture errors are obvious.
44+
- Keep tests isolated using `t.TempDir()`.
45+
46+
## Testing and quality checks
47+
48+
Run before opening a PR:
49+
50+
```bash
51+
gofmt -w *.go
52+
go vet ./...
53+
go test ./...
54+
```
55+
56+
Optional:
57+
58+
```bash
59+
go test -short ./...
60+
```
61+
62+
CI mirrors the required checks (`go vet` and `go test`) on pull requests.
63+
64+
## Usage guidance for library consumers
65+
66+
- Prefer scenario builders for integration-style tests with remotes/worktrees.
67+
- Prefer base fixtures for small unit/integration tests that only need one repo.
68+
- Keep assertions close to setup; helper failures already include command output.
69+
- Use snapshots for expensive setups that are reused across subtests.
70+
71+
Common usage split:
72+
73+
- `CreateTestRepo`: fast setup for single-repo state.
74+
- `NewScenario`: multi-repo topologies and fluent setup.
75+
- `SnapshotRepo`/`RestoreSnapshot`: performance optimization for repeated expensive setups.
76+
77+
## Adding new helpers
78+
79+
When adding new exported helpers:
80+
81+
- Add or update tests in `fixtures_test.go` and/or `scenarios_test.go`.
82+
- Add usage notes/examples to `README.md` when the helper is user-facing.
83+
- Keep function names explicit and test-focused (avoid generic utility names).
84+
85+
## Snapshot safety expectations
86+
87+
- Snapshot restore must never write outside the restore root.
88+
- Avoid introducing behavior that can restore unsupported file types silently.
89+
- Keep snapshot behavior deterministic for repeatable tests.
90+
91+
## Pull request guidance
92+
93+
- Keep PRs focused and small when possible.
94+
- Include a clear "why" in the commit/PR description.
95+
- Include a short test plan with commands you ran locally.
96+
- Prefer additive, backward-compatible changes for existing exported helpers.
97+
98+
Suggested PR checklist:
99+
100+
- [ ] public API changes documented in `README.md`
101+
- [ ] tests added/updated for behavior changes
102+
- [ ] `gofmt`, `go vet`, and `go test` all pass locally
103+
- [ ] no unrelated refactors mixed into functional changes
104+
105+
## Maintainer/admin workflow
106+
107+
### Branch and PR flow
108+
109+
1. Create a feature branch from `main`.
110+
2. Commit focused changes with clear commit messages.
111+
3. Open a PR with summary and test plan.
112+
4. Merge only after CI is green.
113+
114+
### Release flow
115+
116+
1. Verify `main` has passed CI.
117+
2. Confirm `README.md` and this guide reflect current API/behavior.
118+
3. Pull release notes from merged PRs (user-visible changes first).
119+
4. Create and push a version tag.
120+
5. Publish a GitHub release with:
121+
- notable changes
122+
- compatibility notes (for example, minimum Go version)
123+
- migration notes when behavior changed
124+
125+
## Release notes checklist
126+
127+
Before cutting a release:
128+
129+
- Ensure CI is green on `main`.
130+
- Summarize user-visible changes (new helpers, behavior changes, compatibility notes).
131+
- Call out any minimum Go version changes.
132+
- Verify examples in `README.md` still compile conceptually with current API.

‎README.md‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,57 @@
22

33
`git-testkit` provides helpers for writing Go tests that exercise real Git repositories.
44

5+
## Why use this
6+
7+
- Exercise real git behavior instead of mocking command output.
8+
- Build common repo states quickly (dirty trees, detached HEAD, diverged remotes, worktrees).
9+
- Reuse expensive setups across tests with in-memory snapshots.
10+
511
## Install
612

713
```bash
814
go get github.com/git-fire/git-testkit
915
```
1016

17+
## Requirements
18+
19+
- `git` must be installed and available on `PATH`
20+
- Go 1.22+
21+
1122
## What it includes
1223

1324
- Repository fixtures (`CreateTestRepo`, `CreateBareRemote`, `RunGitCmd`)
1425
- Scenario builders for common multi-repo states (`NewScenario`, conflict/worktree helpers)
1526
- Snapshot helpers for capturing and restoring repository state in tests
1627

28+
## API overview
29+
30+
- `CreateTestRepo(t, RepoOptions)` creates a real repository with optional files/remotes/branches.
31+
- `CreateBareRemote(t, name)` creates a bare repository for remote testing.
32+
- `NewScenario(t)` returns a fluent builder for multi-repo test topologies.
33+
- `SnapshotRepo(t, path)` and `RestoreSnapshot(t, snap)` speed up repeated fixture setup.
34+
- `IsDirty`, `GetCurrentSHA`, `GetBranches`, `GetRemotes` provide common assertions/helpers.
35+
36+
## Quickstart for using in tests
37+
38+
1. Create fixture repos with `CreateTestRepo` or `NewScenario`.
39+
2. Apply setup operations with fluent helpers (`AddFile`, `Commit`, `WithRemote`, `Push`).
40+
3. Run your code under test against the real repository paths.
41+
4. Assert with helper methods (`IsDirty`, `GetCurrentSHA`, `GetBranches`).
42+
43+
Minimal test flow:
44+
45+
```go
46+
func TestMyGitBehavior(t *testing.T) {
47+
repoPath := testutil.CreateTestRepo(t, testutil.RepoOptions{Name: "subject"})
48+
testutil.RunGitCmd(t, repoPath, "checkout", "-b", "feature")
49+
// call your package functions here
50+
if testutil.IsDirty(t, repoPath) {
51+
t.Fatal("repo should be clean")
52+
}
53+
}
54+
```
55+
1756
## Example
1857

1958
```go
@@ -34,3 +73,50 @@ func TestWithRepo(t *testing.T) {
3473
}
3574
}
3675
```
76+
77+
## Cleanup behavior
78+
79+
- All helper-created repositories use `t.TempDir()`.
80+
- Repos/worktrees are automatically removed by Go's test framework at test completion.
81+
- As with any temp directories, force-killed test processes may leave files behind.
82+
83+
## Common patterns
84+
85+
### Build a conflict scenario
86+
87+
```go
88+
func TestConflictFlow(t *testing.T) {
89+
_, local, _ := testutil.CreateConflictScenario(t)
90+
91+
// Exercise your logic against a real diverged local clone.
92+
testutil.RunGitCmd(t, local.Path(), "status")
93+
}
94+
```
95+
96+
### Snapshot expensive setup
97+
98+
```go
99+
func TestUsingSnapshot(t *testing.T) {
100+
_, repo := testutil.CreateLargeRepoScenario(t, 20, 10)
101+
102+
snap := testutil.SnapshotRepo(t, repo.Path())
103+
clonePath := testutil.RestoreSnapshot(t, snap)
104+
105+
// Use clonePath in assertions without rebuilding the fixture each time.
106+
testutil.RunGitCmd(t, clonePath, "status")
107+
}
108+
```
109+
110+
## Notes
111+
112+
- Snapshots are intended for deterministic test fixtures and only restore regular files/directories.
113+
- Helpers fail tests immediately (`t.Fatalf`) when git commands fail, so errors surface close to setup code.
114+
- When tests build large repo graphs repeatedly, prefer snapshot/restore to reduce total runtime.
115+
116+
## Developer docs
117+
118+
- See `DEVELOPER_GUIDE.md` for:
119+
- testing and quality gates
120+
- usage guidance for library consumers
121+
- administration/maintenance and release workflow
122+
- contribution process and PR expectations

‎fixtures.go‎

Lines changed: 22 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"os"
55
"os/exec"
66
"path/filepath"
7+
"strings"
78
"testing"
89
)
910

@@ -193,69 +194,39 @@ func GetRemotes(t *testing.T, repoPath string) map[string]string {
193194
// "origin /path/to/remote (push)"
194195
remotes := make(map[string]string)
195196

196-
lines := string(output)
197+
lines := strings.TrimSpace(string(output))
197198
if lines == "" {
198199
return remotes
199200
}
200201

201-
// Simple parsing - just extract remote names
202-
// Full parsing not needed for tests
203-
for _, line := range splitLines(lines) {
202+
for _, line := range strings.Split(lines, "\n") {
203+
line = strings.TrimSpace(line)
204204
if line == "" {
205205
continue
206206
}
207-
// Just check if "origin" appears in the line
208-
// Good enough for test validation
209-
if len(line) > 0 {
210-
// Extract first word (remote name)
211-
parts := splitWhitespace(line)
212-
if len(parts) >= 2 {
213-
name := parts[0]
214-
url := parts[1]
215-
remotes[name] = url
207+
name, remainder, ok := strings.Cut(line, "\t")
208+
if !ok {
209+
// Fallback for unusual formatting that does not use tabs.
210+
idx := strings.IndexAny(line, " \t")
211+
if idx == -1 {
212+
continue
216213
}
214+
name = strings.TrimSpace(line[:idx])
215+
remainder = strings.TrimSpace(line[idx+1:])
216+
} else {
217+
name = strings.TrimSpace(name)
218+
remainder = strings.TrimSpace(remainder)
217219
}
218-
}
219220

220-
return remotes
221-
}
221+
remainder = strings.TrimSuffix(remainder, " (fetch)")
222+
remainder = strings.TrimSuffix(remainder, " (push)")
222223

223-
// Helper: split by newlines
224-
func splitLines(s string) []string {
225-
var lines []string
226-
current := ""
227-
for _, ch := range s {
228-
if ch == '\n' {
229-
lines = append(lines, current)
230-
current = ""
231-
} else {
232-
current += string(ch)
224+
if name != "" && remainder != "" {
225+
remotes[name] = remainder
233226
}
234227
}
235-
if current != "" {
236-
lines = append(lines, current)
237-
}
238-
return lines
239-
}
240228

241-
// Helper: split by whitespace/tabs
242-
func splitWhitespace(s string) []string {
243-
var parts []string
244-
current := ""
245-
for _, ch := range s {
246-
if ch == ' ' || ch == '\t' {
247-
if current != "" {
248-
parts = append(parts, current)
249-
current = ""
250-
}
251-
} else {
252-
current += string(ch)
253-
}
254-
}
255-
if current != "" {
256-
parts = append(parts, current)
257-
}
258-
return parts
229+
return remotes
259230
}
260231

261232
// RunGitCmd runs a git command and fails the test if it errors
@@ -277,13 +248,7 @@ func GetCurrentSHA(t *testing.T, repoPath string) string {
277248
t.Fatalf("Failed to get current SHA: %v", err)
278249
}
279250

280-
sha := string(output)
281-
// Trim newline
282-
if len(sha) > 0 && sha[len(sha)-1] == '\n' {
283-
sha = sha[:len(sha)-1]
284-
}
285-
286-
return sha
251+
return strings.TrimSpace(string(output))
287252
}
288253

289254
// GetBranches returns all branches in the repo
@@ -298,7 +263,7 @@ func GetBranches(t *testing.T, repoPath string) []string {
298263
t.Fatalf("Failed to get branches: %v", err)
299264
}
300265

301-
branches := splitLines(string(output))
266+
branches := strings.Split(strings.TrimSpace(string(output)), "\n")
302267

303268
// Filter out empty lines
304269
var result []string

0 commit comments

Comments
 (0)