summaryrefslogtreecommitdiffstats
path: root/modules/git/repo_attribute_test.go
blob: fa34164816033c5b42035c9d7f0af6f4e49951cd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package git

import (
	"context"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
	"time"

	"code.gitea.io/gitea/modules/test"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestNewCheckAttrStdoutReader(t *testing.T) {
	t.Run("two_times", func(t *testing.T) {
		read := newCheckAttrStdoutReader(strings.NewReader(
			".gitignore\x00linguist-vendored\x00unspecified\x00"+
				".gitignore\x00linguist-vendored\x00specified",
		), 1)

		// first read
		attr, err := read()
		require.NoError(t, err)
		assert.Equal(t, map[string]GitAttribute{
			"linguist-vendored": GitAttribute("unspecified"),
		}, attr)

		// second read
		attr, err = read()
		require.NoError(t, err)
		assert.Equal(t, map[string]GitAttribute{
			"linguist-vendored": GitAttribute("specified"),
		}, attr)
	})
	t.Run("incomplete", func(t *testing.T) {
		read := newCheckAttrStdoutReader(strings.NewReader(
			"filename\x00linguist-vendored",
		), 1)

		_, err := read()
		assert.Equal(t, io.ErrUnexpectedEOF, err)
	})
	t.Run("three_times", func(t *testing.T) {
		read := newCheckAttrStdoutReader(strings.NewReader(
			"shouldbe.vendor\x00linguist-vendored\x00set\x00"+
				"shouldbe.vendor\x00linguist-generated\x00unspecified\x00"+
				"shouldbe.vendor\x00linguist-language\x00unspecified\x00",
		), 1)

		// first read
		attr, err := read()
		require.NoError(t, err)
		assert.Equal(t, map[string]GitAttribute{
			"linguist-vendored": GitAttribute("set"),
		}, attr)

		// second read
		attr, err = read()
		require.NoError(t, err)
		assert.Equal(t, map[string]GitAttribute{
			"linguist-generated": GitAttribute("unspecified"),
		}, attr)

		// third read
		attr, err = read()
		require.NoError(t, err)
		assert.Equal(t, map[string]GitAttribute{
			"linguist-language": GitAttribute("unspecified"),
		}, attr)
	})
}

func TestGitAttributeBareNonBare(t *testing.T) {
	if !SupportCheckAttrOnBare {
		t.Skip("git check-attr supported on bare repo starting with git 2.40")
	}

	repoPath := filepath.Join(testReposDir, "language_stats_repo")
	gitRepo, err := openRepositoryWithDefaultContext(repoPath)
	require.NoError(t, err)
	defer gitRepo.Close()

	for _, commitID := range []string{
		"8fee858da5796dfb37704761701bb8e800ad9ef3",
		"341fca5b5ea3de596dc483e54c2db28633cd2f97",
	} {
		bareStats, err := gitRepo.GitAttributes(commitID, "i-am-a-python.p", LinguistAttributes...)
		require.NoError(t, err)

		defer test.MockVariableValue(&SupportCheckAttrOnBare, false)()
		cloneStats, err := gitRepo.GitAttributes(commitID, "i-am-a-python.p", LinguistAttributes...)
		require.NoError(t, err)

		assert.EqualValues(t, cloneStats, bareStats)
		refStats := cloneStats

		t.Run("GitAttributeChecker/"+commitID+"/SupportBare", func(t *testing.T) {
			bareChecker, err := gitRepo.GitAttributeChecker(commitID, LinguistAttributes...)
			require.NoError(t, err)
			defer bareChecker.Close()

			bareStats, err := bareChecker.CheckPath("i-am-a-python.p")
			require.NoError(t, err)
			assert.EqualValues(t, refStats, bareStats)
		})
		t.Run("GitAttributeChecker/"+commitID+"/NoBareSupport", func(t *testing.T) {
			defer test.MockVariableValue(&SupportCheckAttrOnBare, false)()
			cloneChecker, err := gitRepo.GitAttributeChecker(commitID, LinguistAttributes...)
			require.NoError(t, err)
			defer cloneChecker.Close()

			cloneStats, err := cloneChecker.CheckPath("i-am-a-python.p")
			require.NoError(t, err)

			assert.EqualValues(t, refStats, cloneStats)
		})
	}
}

func TestGitAttributes(t *testing.T) {
	repoPath := filepath.Join(testReposDir, "language_stats_repo")
	gitRepo, err := openRepositoryWithDefaultContext(repoPath)
	require.NoError(t, err)
	defer gitRepo.Close()

	attr, err := gitRepo.GitAttributes("8fee858da5796dfb37704761701bb8e800ad9ef3", "i-am-a-python.p", LinguistAttributes...)
	require.NoError(t, err)
	assert.EqualValues(t, map[string]GitAttribute{
		"gitlab-language":        "unspecified",
		"linguist-detectable":    "unspecified",
		"linguist-documentation": "unspecified",
		"linguist-generated":     "unspecified",
		"linguist-language":      "Python",
		"linguist-vendored":      "unspecified",
	}, attr)

	attr, err = gitRepo.GitAttributes("341fca5b5ea3de596dc483e54c2db28633cd2f97", "i-am-a-python.p", LinguistAttributes...)
	require.NoError(t, err)
	assert.EqualValues(t, map[string]GitAttribute{
		"gitlab-language":        "unspecified",
		"linguist-detectable":    "unspecified",
		"linguist-documentation": "unspecified",
		"linguist-generated":     "unspecified",
		"linguist-language":      "Cobra",
		"linguist-vendored":      "unspecified",
	}, attr)
}

func TestGitAttributeFirst(t *testing.T) {
	repoPath := filepath.Join(testReposDir, "language_stats_repo")
	gitRepo, err := openRepositoryWithDefaultContext(repoPath)
	require.NoError(t, err)
	defer gitRepo.Close()

	t.Run("first is specified", func(t *testing.T) {
		language, err := gitRepo.GitAttributeFirst("8fee858da5796dfb37704761701bb8e800ad9ef3", "i-am-a-python.p", "linguist-language", "gitlab-language")
		require.NoError(t, err)
		assert.Equal(t, "Python", language.String())
	})

	t.Run("second is specified", func(t *testing.T) {
		language, err := gitRepo.GitAttributeFirst("8fee858da5796dfb37704761701bb8e800ad9ef3", "i-am-a-python.p", "gitlab-language", "linguist-language")
		require.NoError(t, err)
		assert.Equal(t, "Python", language.String())
	})

	t.Run("none is specified", func(t *testing.T) {
		language, err := gitRepo.GitAttributeFirst("8fee858da5796dfb37704761701bb8e800ad9ef3", "i-am-a-python.p", "linguist-detectable", "gitlab-language", "non-existing")
		require.NoError(t, err)
		assert.Equal(t, "", language.String())
	})
}

func TestGitAttributeStruct(t *testing.T) {
	assert.Equal(t, "", GitAttribute("").String())
	assert.Equal(t, "", GitAttribute("unspecified").String())

	assert.Equal(t, "python", GitAttribute("python").String())

	assert.Equal(t, "text?token=Error", GitAttribute("text?token=Error").String())
	assert.Equal(t, "text", GitAttribute("text?token=Error").Prefix())
}

func TestGitAttributeCheckerError(t *testing.T) {
	prepareRepo := func(t *testing.T) *Repository {
		t.Helper()
		path := t.TempDir()

		// we can't use unittest.CopyDir because of an import cycle (git.Init in unittest)
		require.NoError(t, CopyFS(path, os.DirFS(filepath.Join(testReposDir, "language_stats_repo"))))

		gitRepo, err := openRepositoryWithDefaultContext(path)
		require.NoError(t, err)
		return gitRepo
	}

	t.Run("RemoveAll/BeforeRun", func(t *testing.T) {
		gitRepo := prepareRepo(t)
		defer gitRepo.Close()

		require.NoError(t, os.RemoveAll(gitRepo.Path))

		ac, err := gitRepo.GitAttributeChecker("", "linguist-language")
		require.NoError(t, err)

		_, err = ac.CheckPath("i-am-a-python.p")
		require.Error(t, err)
		assert.Contains(t, err.Error(), `git check-attr (stderr: ""):`)
	})

	t.Run("RemoveAll/DuringRun", func(t *testing.T) {
		gitRepo := prepareRepo(t)
		defer gitRepo.Close()

		ac, err := gitRepo.GitAttributeChecker("", "linguist-language")
		require.NoError(t, err)

		// calling CheckPath before would allow git to cache part of it and successfully return later
		require.NoError(t, os.RemoveAll(gitRepo.Path))

		_, err = ac.CheckPath("i-am-a-python.p")
		if err == nil {
			t.Skip(
				"git check-attr started too fast and CheckPath was successful (and likely cached)",
				"https://codeberg.org/forgejo/forgejo/issues/2948",
			)
		}
		// Depending on the order of execution, the returned error can be:
		// - a launch error "fork/exec /usr/bin/git: no such file or directory" (when the removal happens before the Run)
		// - a git error (stderr: "fatal: Unable to read current working directory: No such file or directory"): exit status 128 (when the removal happens after the Run)
		// (pipe error "write |1: broken pipe" should be replaced by one of the Run errors above)
		assert.Contains(t, err.Error(), `git check-attr`)
	})

	t.Run("Cancelled/BeforeRun", func(t *testing.T) {
		gitRepo := prepareRepo(t)
		defer gitRepo.Close()

		var cancel context.CancelFunc
		gitRepo.Ctx, cancel = context.WithCancel(gitRepo.Ctx)
		cancel()

		ac, err := gitRepo.GitAttributeChecker("8fee858da5796dfb37704761701bb8e800ad9ef3", "linguist-language")
		require.NoError(t, err)

		_, err = ac.CheckPath("i-am-a-python.p")
		require.ErrorIs(t, err, context.Canceled)
	})

	t.Run("Cancelled/DuringRun", func(t *testing.T) {
		gitRepo := prepareRepo(t)
		defer gitRepo.Close()

		var cancel context.CancelFunc
		gitRepo.Ctx, cancel = context.WithCancel(gitRepo.Ctx)

		ac, err := gitRepo.GitAttributeChecker("8fee858da5796dfb37704761701bb8e800ad9ef3", "linguist-language")
		require.NoError(t, err)

		attr, err := ac.CheckPath("i-am-a-python.p")
		require.NoError(t, err)
		assert.Equal(t, "Python", attr["linguist-language"].String())

		errCh := make(chan error)
		go func() {
			cancel()

			for err == nil {
				_, err = ac.CheckPath("i-am-a-python.p")
				runtime.Gosched() // the cancellation must have time to propagate
			}
			errCh <- err
		}()

		select {
		case <-time.After(time.Second):
			t.Error("CheckPath did not complete within 1s")
		case err = <-errCh:
			require.ErrorIs(t, err, context.Canceled)
		}
	})

	t.Run("Closed/BeforeRun", func(t *testing.T) {
		gitRepo := prepareRepo(t)
		defer gitRepo.Close()

		ac, err := gitRepo.GitAttributeChecker("8fee858da5796dfb37704761701bb8e800ad9ef3", "linguist-language")
		require.NoError(t, err)

		require.NoError(t, ac.Close())

		_, err = ac.CheckPath("i-am-a-python.p")
		require.ErrorIs(t, err, fs.ErrClosed)
	})

	t.Run("Closed/DuringRun", func(t *testing.T) {
		gitRepo := prepareRepo(t)
		defer gitRepo.Close()

		ac, err := gitRepo.GitAttributeChecker("8fee858da5796dfb37704761701bb8e800ad9ef3", "linguist-language")
		require.NoError(t, err)

		attr, err := ac.CheckPath("i-am-a-python.p")
		require.NoError(t, err)
		assert.Equal(t, "Python", attr["linguist-language"].String())

		require.NoError(t, ac.Close())

		_, err = ac.CheckPath("i-am-a-python.p")
		require.ErrorIs(t, err, fs.ErrClosed)
	})
}

// CopyFS is adapted from https://github.com/golang/go/issues/62484
// which should be available with go1.23
func CopyFS(dir string, fsys fs.FS) error {
	return fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, _ error) error {
		targ := filepath.Join(dir, filepath.FromSlash(path))
		if d.IsDir() {
			return os.MkdirAll(targ, 0o777)
		}
		r, err := fsys.Open(path)
		if err != nil {
			return err
		}
		defer r.Close()
		info, err := r.Stat()
		if err != nil {
			return err
		}
		w, err := os.OpenFile(targ, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o666|info.Mode()&0o777)
		if err != nil {
			return err
		}
		if _, err := io.Copy(w, r); err != nil {
			w.Close()
			return fmt.Errorf("copying %s: %v", path, err)
		}
		return w.Close()
	})
}