v0.11.0 0633e44

backend_test.go RawHistoryFolder

1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package gitcli_test
4
5import (
6	"context"
7	"encoding/binary"
8	"os"
9	"os/exec"
10	"path/filepath"
11	"strconv"
12	"strings"
13	"testing"
14
15	"github.com/stretchr/testify/assert"
16	"github.com/stretchr/testify/require"
17
18	"bnema.dev/ermite/internal/adapters/gitcli"
19	"bnema.dev/ermite/internal/domain"
20)
21
22func envMap(env []string) map[string]string {
23	m := map[string]string{}
24	for _, e := range env {
25		k, v, _ := strings.Cut(e, "=")
26		m[k] = v
27	}
28	return m
29}
30
31// backendConf returns the GIT_CONFIG_KEY/VALUE pairs of a backend environment
32// and checks that GIT_CONFIG_COUNT matches them.
33func backendConf(e map[string]string) map[string]string {
34	conf := map[string]string{}
35	n := 0
36	for {
37		k, ok := e["GIT_CONFIG_KEY_"+strconv.Itoa(n)]
38		if !ok {
39			break
40		}
41		conf[k] = e["GIT_CONFIG_VALUE_"+strconv.Itoa(n)]
42		n++
43	}
44	if e["GIT_CONFIG_COUNT"] != strconv.Itoa(n) {
45		panic("GIT_CONFIG_COUNT does not match the keys")
46	}
47	return conf
48}
49
50func TestHTTPBackendReceiveMaxInputSize(t *testing.T) {
51	ctx := context.Background()
52	_, data := newGit(t)
53	bin, err := exec.LookPath("git")
54	require.NoError(t, err)
55	g := gitcli.New(gitcli.Config{Bin: bin, DataDir: data, Path: os.Getenv("PATH"), MaxReceiveBytes: 4 << 30})
56
57	push, err := g.HTTPBackend(ctx, true)
58	require.NoError(t, err)
59	assert.Equal(t, "4294967296", backendConf(envMap(push.Env))["receive.maxInputSize"])
60
61	read, err := g.HTTPBackend(ctx, false)
62	require.NoError(t, err)
63	assert.NotContains(t, backendConf(envMap(read.Env)), "receive.maxInputSize", "a fetch does not receive a pack")
64}
65
66func TestHTTPBackendEnvironment(t *testing.T) {
67	ctx := context.Background()
68	g, data := newGit(t)
69
70	read, err := g.HTTPBackend(ctx, false)
71	require.NoError(t, err)
72	execPath, err := exec.Command("git", "--exec-path").Output()
73	require.NoError(t, err)
74	assert.Equal(t, filepath.Join(strings.TrimSpace(string(execPath)), "git-http-backend"), read.Path)
75	assert.Equal(t, filepath.Join(data, "repos"), read.Dir)
76
77	e := envMap(read.Env)
78	assert.Equal(t, "1", e["GIT_CONFIG_NOSYSTEM"])
79	assert.Equal(t, filepath.Join(data, "run", "git-home"), e["HOME"])
80	assert.Equal(t, "0", e["GIT_TERMINAL_PROMPT"])
81	assert.Equal(t, filepath.Join(data, "repos"), e["GIT_PROJECT_ROOT"])
82	assert.Equal(t, "1", e["GIT_HTTP_EXPORT_ALL"])
83	assert.NotContains(t, e, "REMOTE_USER", "a read is not a push")
84
85	assert.Equal(t, map[string]string{
86		"core.hooksPath":         filepath.Join(data, "run", "hooks"),
87		"receive.fsckObjects":    "true",
88		"uploadpack.allowFilter": "true",
89		"pack.threads":           "1",
90		"pack.windowMemory":      "256m",
91	}, backendConf(e))
92
93	push, err := g.HTTPBackend(ctx, true)
94	require.NoError(t, err)
95	pe := envMap(push.Env)
96	assert.Equal(t, "owner", pe["REMOTE_USER"])
97	assert.Equal(t, map[string]string{
98		"core.hooksPath":         filepath.Join(data, "run", "hooks"),
99		"receive.fsckObjects":    "true",
100		"uploadpack.allowFilter": "true",
101		"pack.threads":           "1",
102		"pack.windowMemory":      "256m",
103		"http.receivepack":       "true",
104	}, backendConf(pe), "http.receivepack only for a push; no size limit unless configured")
105
106	// Nothing from the caller's environment leaks.
107	t.Setenv("GIT_DIR", "/leak")
108	again, err := g.HTTPBackend(ctx, true)
109	require.NoError(t, err)
110	assert.NotContains(t, envMap(again.Env), "GIT_DIR")
111
112	// The slice is the caller's: appending does not corrupt the next call.
113	_ = append(read.Env, "X=1")
114	third, err := g.HTTPBackend(ctx, false)
115	require.NoError(t, err)
116	assert.NotContains(t, envMap(third.Env), "X")
117}
118
119func TestHTTPBackendMissing(t *testing.T) {
120	data := t.TempDir()
121	script := writeScript(t, `case "$1" in --exec-path) echo "`+data+`/nowhere";; *) echo "git version 2.50.0";; esac`)
122	g := gitcli.New(gitcli.Config{Bin: script, DataDir: data, Path: "/usr/bin:/bin"})
123	_, err := g.HTTPBackend(context.Background(), false)
124	require.Error(t, err)
125	assert.Contains(t, err.Error(), "git-http-backend")
126
127	// A non-executable file is refused too.
128	require.NoError(t, os.MkdirAll(filepath.Join(data, "exec"), 0o755))
129	require.NoError(t, os.WriteFile(filepath.Join(data, "exec", "git-http-backend"), []byte("x"), 0o644))
130	script = writeScript(t, `echo "`+data+`/exec"`)
131	g = gitcli.New(gitcli.Config{Bin: script, DataDir: data, Path: "/usr/bin:/bin"})
132	_, err = g.HTTPBackend(context.Background(), false)
133	require.Error(t, err)
134	assert.Contains(t, err.Error(), "not an executable")
135}
136
137func TestDefaultBranchAndMaintain(t *testing.T) {
138	ctx := context.Background()
139	g, data := newGit(t)
140	n := name(t, "tools")
141	id, err := g.Stage(ctx)
142	require.NoError(t, err)
143	require.NoError(t, g.Publish(ctx, id, n))
144	dir := filepath.Join(data, "repos", "tools.git")
145
146	branch, exists, err := g.DefaultBranch(ctx, n)
147	require.NoError(t, err)
148	assert.Equal(t, "main", branch)
149	assert.False(t, exists, "no commit yet")
150
151	_, _, err = g.DefaultBranch(ctx, name(t, "ghost"))
152	assert.ErrorIs(t, err, domain.ErrNotFound)
153
154	// Put a commit on "dev" through a work tree.
155	wt := t.TempDir()
156	env := []string{"PATH=" + os.Getenv("PATH"), "HOME=" + t.TempDir(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
157		"GIT_AUTHOR_NAME=T", "GIT_AUTHOR_EMAIL=t@x", "GIT_COMMITTER_NAME=T", "GIT_COMMITTER_EMAIL=t@x"}
158	run := func(args ...string) {
159		cmd := exec.Command("git", args...)
160		cmd.Dir, cmd.Env = wt, env
161		out, err := cmd.CombinedOutput()
162		require.NoError(t, err, string(out))
163	}
164	run("init", "-q", "--initial-branch=dev")
165	require.NoError(t, os.WriteFile(filepath.Join(wt, "f"), []byte("x"), 0o644))
166	run("add", "f")
167	run("commit", "-q", "-m", "one")
168	run("push", "-q", dir, "dev")
169
170	_, exists, err = g.DefaultBranch(ctx, n)
171	require.NoError(t, err)
172	assert.False(t, exists, "HEAD still points to main")
173
174	require.NoError(t, g.SetDefaultBranch(ctx, n, "dev"))
175	branch, exists, err = g.DefaultBranch(ctx, n)
176	require.NoError(t, err)
177	assert.Equal(t, "dev", branch)
178	assert.True(t, exists)
179	assert.Equal(t, "refs/heads/dev", gitOut(t, dir, "symbolic-ref", "HEAD"))
180
181	for _, bad := range []string{"", "-x", "a b", "a..b"} {
182		assert.Error(t, g.SetDefaultBranch(ctx, n, bad), bad)
183	}
184	assert.ErrorIs(t, g.SetDefaultBranch(ctx, name(t, "ghost"), "dev"), domain.ErrNotFound)
185
186	require.NoError(t, g.Maintain(ctx, n))
187	assert.FileExists(t, filepath.Join(dir, "objects", "info", "commit-graphs", "commit-graph-chain"))
188	assert.ErrorIs(t, g.Maintain(ctx, name(t, "ghost")), domain.ErrNotFound)
189}
190
191// bloomVersions returns the Bloom filter hash version (BDAT chunk) of every
192// layer of the commit-graph chain of the repository.
193func bloomVersions(t *testing.T, dir string) []uint32 {
194	t.Helper()
195	files, err := filepath.Glob(filepath.Join(dir, "objects", "info", "commit-graphs", "graph-*.graph"))
196	require.NoError(t, err)
197	require.NotEmpty(t, files)
198	var out []uint32
199	for _, f := range files {
200		d, err := os.ReadFile(f)
201		require.NoError(t, err)
202		chunks := int(d[6])
203		found := false
204		for i := range chunks {
205			row := 8 + 12*i
206			if string(d[row:row+4]) == "BDAT" {
207				off := binary.BigEndian.Uint64(d[row+4 : row+12])
208				out = append(out, binary.BigEndian.Uint32(d[off:off+4]))
209				found = true
210			}
211		}
212		require.True(t, found, "%s has no Bloom filters", f)
213	}
214	return out
215}
216
217// New repositories write v2 Bloom filters (no signed/unsigned char ambiguity),
218// and Maintain keeps writing v2: on top of a v2 chain, and over a v1 chain that
219// an older ermite or a plain git left behind.
220func TestMaintainWritesBloomFiltersV2(t *testing.T) {
221	ctx := context.Background()
222	g, data := newGit(t)
223	n := name(t, "bloom")
224	id, err := g.Stage(ctx)
225	require.NoError(t, err)
226	require.NoError(t, g.Publish(ctx, id, n))
227	dir := filepath.Join(data, "repos", "bloom.git")
228
229	wt := t.TempDir()
230	env := []string{"PATH=" + os.Getenv("PATH"), "HOME=" + t.TempDir(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
231		"GIT_AUTHOR_NAME=T", "GIT_AUTHOR_EMAIL=t@x", "GIT_COMMITTER_NAME=T", "GIT_COMMITTER_EMAIL=t@x"}
232	run := func(dir string, args ...string) {
233		cmd := exec.Command("git", args...)
234		cmd.Dir, cmd.Env = dir, env
235		out, err := cmd.CombinedOutput()
236		require.NoError(t, err, string(out))
237	}
238	run(wt, "init", "-q", "--initial-branch=main")
239	commit := func(i int) {
240		require.NoError(t, os.WriteFile(filepath.Join(wt, "f"), []byte(strings.Repeat("x", i+1)), 0o644))
241		run(wt, "add", "f")
242		run(wt, "commit", "-q", "-m", "c")
243		run(wt, "push", "-q", dir, "main")
244	}
245
246	commit(0)
247	commit(1)
248	require.NoError(t, g.Maintain(ctx, n))
249	assert.Equal(t, []uint32{2}, bloomVersions(t, dir))
250
251	// A v1 chain written by a git that was not configured for v2.
252	run(dir, "-c", "commitGraph.changedPathsVersion=1", "commit-graph", "write", "--reachable", "--changed-paths", "--split=replace")
253	require.Equal(t, []uint32{1}, bloomVersions(t, dir))
254	commit(2)
255	require.NoError(t, g.Maintain(ctx, n))
256	for _, v := range bloomVersions(t, dir) {
257		assert.Equal(t, uint32(2), v, "Maintain does not leave v1 filters in the chain")
258	}
259	commit(3)
260	require.NoError(t, g.Maintain(ctx, n))
261	for _, v := range bloomVersions(t, dir) {
262		assert.Equal(t, uint32(2), v)
263	}
264	run(dir, "commit-graph", "verify")
265}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 2

Tags 45

↑↓ moveenter openesc close