Welcome to mirror list, hosted at ThFree Co, Russian Federation.

apply_gitattributes_test.go « repository « service « gitaly « internal - gitlab.com/gitlab-org/gitaly.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d0bf78f7369654263d4387299f8f6bd87f26bc7a (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
package repository

import (
	"bytes"
	"context"
	"errors"
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/require"
	"gitlab.com/gitlab-org/gitaly/v15/internal/backchannel"
	"gitlab.com/gitlab-org/gitaly/v15/internal/git/gittest"
	"gitlab.com/gitlab-org/gitaly/v15/internal/helper"
	"gitlab.com/gitlab-org/gitaly/v15/internal/metadata"
	"gitlab.com/gitlab-org/gitaly/v15/internal/testhelper"
	"gitlab.com/gitlab-org/gitaly/v15/internal/testhelper/testcfg"
	"gitlab.com/gitlab-org/gitaly/v15/internal/transaction/txinfo"
	"gitlab.com/gitlab-org/gitaly/v15/internal/transaction/voting"
	"gitlab.com/gitlab-org/gitaly/v15/proto/go/gitalypb"
	"google.golang.org/grpc"
)

func TestApplyGitattributes_successful(t *testing.T) {
	t.Parallel()

	ctx := testhelper.Context(t)
	cfg, client := setupRepositoryServiceWithoutRepo(t)

	repo, repoPath := gittest.CreateRepository(t, ctx, cfg)
	gitattributesContent := "pattern attr=value"
	commitWithGitattributes := gittest.WriteCommit(t, cfg, repoPath, gittest.WithTreeEntries(
		gittest.TreeEntry{Path: ".gitattributes", Mode: "100644", Content: gitattributesContent},
	))
	commitWithoutGitattributes := gittest.WriteCommit(t, cfg, repoPath)

	infoPath := filepath.Join(repoPath, "info")
	attributesPath := filepath.Join(infoPath, "attributes")

	for _, tc := range []struct {
		desc            string
		revision        []byte
		expectedContent []byte
	}{
		{
			desc:            "With a .gitattributes file",
			revision:        []byte(commitWithGitattributes),
			expectedContent: []byte(gitattributesContent),
		},
		{
			desc:            "Without a .gitattributes file",
			revision:        []byte(commitWithoutGitattributes),
			expectedContent: nil,
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			t.Run("without 'info' directory", func(t *testing.T) {
				require.NoError(t, os.RemoveAll(infoPath))
				requireApplyGitattributes(t, ctx, client, repo, attributesPath, tc.revision, tc.expectedContent)
			})

			t.Run("without 'info/attributes' directory", func(t *testing.T) {
				require.NoError(t, os.RemoveAll(infoPath))
				require.NoError(t, os.Mkdir(infoPath, 0o755))
				requireApplyGitattributes(t, ctx, client, repo, attributesPath, tc.revision, tc.expectedContent)
			})

			t.Run("with preexisting 'info/attributes'", func(t *testing.T) {
				require.NoError(t, os.RemoveAll(infoPath))
				require.NoError(t, os.Mkdir(infoPath, 0o755))
				require.NoError(t, os.WriteFile(attributesPath, []byte("*.docx diff=word"), 0o644))
				requireApplyGitattributes(t, ctx, client, repo, attributesPath, tc.revision, tc.expectedContent)
			})
		})
	}
}

type testTransactionServer struct {
	gitalypb.UnimplementedRefTransactionServer
	vote func(*gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error)
}

func (s *testTransactionServer) VoteTransaction(ctx context.Context, in *gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error) {
	if s.vote != nil {
		return s.vote(in)
	}
	return nil, nil
}

func TestApplyGitattributes_transactional(t *testing.T) {
	t.Parallel()

	ctx := testhelper.Context(t)
	cfg := testcfg.Build(t)

	repo, repoPath := gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{
		SkipCreationViaService: true,
	})
	gitattributesContent := "pattern attr=value"
	commitWithGitattributes := gittest.WriteCommit(t, cfg, repoPath, gittest.WithTreeEntries(
		gittest.TreeEntry{Path: ".gitattributes", Mode: "100644", Content: gitattributesContent},
	))
	commitWithoutGitattributes := gittest.WriteCommit(t, cfg, repoPath)

	transactionServer := &testTransactionServer{}
	runRepositoryService(t, cfg, nil)

	// We're using internal listener in order to route around
	// Praefect in our tests. Otherwise Praefect would replace our
	// carefully crafted transaction and server information.
	logger := testhelper.NewDiscardingLogEntry(t)

	client := newMuxedRepositoryClient(t, ctx, cfg, "unix://"+cfg.InternalSocketPath(),
		backchannel.NewClientHandshaker(logger, func() backchannel.Server {
			srv := grpc.NewServer()
			gitalypb.RegisterRefTransactionServer(srv, transactionServer)
			return srv
		}),
	)

	for _, tc := range []struct {
		desc          string
		revision      []byte
		voteFn        func(*testing.T, *gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error)
		shouldExist   bool
		expectedErr   error
		expectedVotes int
	}{
		{
			desc:     "successful vote writes gitattributes",
			revision: []byte(commitWithGitattributes),
			voteFn: func(t *testing.T, request *gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error) {
				vote := voting.VoteFromData([]byte(gitattributesContent))
				expectedHash := vote.Bytes()

				require.Equal(t, expectedHash, request.ReferenceUpdatesHash)
				return &gitalypb.VoteTransactionResponse{
					State: gitalypb.VoteTransactionResponse_COMMIT,
				}, nil
			},
			shouldExist:   true,
			expectedVotes: 2,
		},
		{
			desc:     "aborted vote does not write gitattributes",
			revision: []byte(commitWithGitattributes),
			voteFn: func(t *testing.T, request *gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error) {
				return &gitalypb.VoteTransactionResponse{
					State: gitalypb.VoteTransactionResponse_ABORT,
				}, nil
			},
			shouldExist: false,
			expectedErr: func() error {
				return helper.ErrInternalf("committing gitattributes: voting on locked file: preimage vote: transaction was aborted")
			}(),
			expectedVotes: 1,
		},
		{
			desc:     "failing vote does not write gitattributes",
			revision: []byte(commitWithGitattributes),
			voteFn: func(t *testing.T, request *gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error) {
				return nil, errors.New("foobar")
			},
			shouldExist: false,
			expectedErr: func() error {
				return helper.ErrInternalf("committing gitattributes: voting on locked file: preimage vote: rpc error: code = Unknown desc = foobar")
			}(),
			expectedVotes: 1,
		},
		{
			desc:     "commit without gitattributes performs vote",
			revision: []byte(commitWithoutGitattributes),
			voteFn: func(t *testing.T, request *gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error) {
				require.Equal(t, bytes.Repeat([]byte{0x00}, 20), request.ReferenceUpdatesHash)
				return &gitalypb.VoteTransactionResponse{
					State: gitalypb.VoteTransactionResponse_COMMIT,
				}, nil
			},
			shouldExist:   false,
			expectedVotes: 2,
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			infoPath := filepath.Join(repoPath, "info")
			require.NoError(t, os.RemoveAll(infoPath))

			ctx, err := txinfo.InjectTransaction(ctx, 1, "primary", true)
			require.NoError(t, err)
			ctx = metadata.IncomingToOutgoing(ctx)

			var votes int
			transactionServer.vote = func(request *gitalypb.VoteTransactionRequest) (*gitalypb.VoteTransactionResponse, error) {
				votes++
				return tc.voteFn(t, request)
			}

			_, err = client.ApplyGitattributes(ctx, &gitalypb.ApplyGitattributesRequest{
				Repository: repo,
				Revision:   tc.revision,
			})
			testhelper.RequireGrpcError(t, tc.expectedErr, err)

			path := filepath.Join(infoPath, "attributes")
			if tc.shouldExist {
				content := testhelper.MustReadFile(t, path)
				require.Equal(t, []byte(gitattributesContent), content)
			} else {
				require.NoFileExists(t, path)
			}
			require.Equal(t, tc.expectedVotes, votes)
		})
	}
}

func TestApplyGitattributes_failure(t *testing.T) {
	t.Parallel()

	ctx := testhelper.Context(t)
	cfg, client := setupRepositoryServiceWithoutRepo(t)
	repo, _ := gittest.CreateRepository(t, ctx, cfg)

	for _, tc := range []struct {
		desc        string
		repo        *gitalypb.Repository
		revision    []byte
		expectedErr error
	}{
		{
			desc:     "no repository provided",
			repo:     nil,
			revision: nil,
			expectedErr: helper.ErrInvalidArgumentf(testhelper.GitalyOrPraefect(
				"empty Repository",
				"repo scoped: empty Repository",
			)),
		},
		{
			desc: "unknown storage provided",
			repo: &gitalypb.Repository{
				RelativePath: "stub",
				StorageName:  "foo",
			},
			revision: []byte("master"),
			expectedErr: helper.ErrInvalidArgumentf(testhelper.GitalyOrPraefect(
				`GetStorageByName: no such storage: "foo"`,
				"repo scoped: invalid Repository",
			)),
		},
		{
			desc: "storage not provided",
			repo: &gitalypb.Repository{
				RelativePath: repo.GetRelativePath(),
			},
			revision: []byte("master"),
			expectedErr: helper.ErrInvalidArgumentf(testhelper.GitalyOrPraefect(
				"empty StorageName",
				"repo scoped: invalid Repository",
			)),
		},
		{
			desc: "repository doesn't exist on disk",
			repo: &gitalypb.Repository{
				StorageName:  repo.GetStorageName(),
				RelativePath: "bar",
			},
			revision: []byte("master"),
			expectedErr: helper.ErrNotFoundf(testhelper.GitalyOrPraefect(
				`GetRepoPath: not a git repository: "`+cfg.Storages[0].Path+`/bar"`,
				`mutator call: route repository mutator: get repository id: repository "default"/"bar" not found`,
			)),
		},
		{
			desc:        "no revision provided",
			repo:        repo,
			revision:    []byte(""),
			expectedErr: helper.ErrInvalidArgumentf("revision: empty revision"),
		},
		{
			desc:        "unknown revision",
			repo:        repo,
			revision:    []byte("not-existing-ref"),
			expectedErr: helper.ErrInvalidArgumentf("revision does not exist"),
		},
		{
			desc:        "invalid revision",
			repo:        repo,
			revision:    []byte("--output=/meow"),
			expectedErr: helper.ErrInvalidArgumentf("revision: revision can't start with '-'"),
		},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			_, err := client.ApplyGitattributes(ctx, &gitalypb.ApplyGitattributesRequest{
				Repository: tc.repo,
				Revision:   tc.revision,
			})
			testhelper.RequireGrpcError(t, tc.expectedErr, err)
		})
	}
}

func requireApplyGitattributes(
	t *testing.T,
	ctx context.Context,
	client gitalypb.RepositoryServiceClient,
	repo *gitalypb.Repository,
	attributesPath string,
	revision, expectedContent []byte,
) {
	t.Helper()

	response, err := client.ApplyGitattributes(ctx, &gitalypb.ApplyGitattributesRequest{
		Repository: repo,
		Revision:   revision,
	})
	require.NoError(t, err)
	testhelper.ProtoEqual(t, &gitalypb.ApplyGitattributesResponse{}, response)

	if expectedContent == nil {
		require.NoFileExists(t, attributesPath)
	} else {
		require.Equal(t, expectedContent, testhelper.MustReadFile(t, attributesPath))

		info, err := os.Stat(attributesPath)
		require.NoError(t, err)
		require.Equal(t, attributesFileMode, info.Mode())
	}
}