File: filetools_test.go

package info (click to toggle)
git-lfs 3.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,808 kB
  • sloc: sh: 21,256; makefile: 507; ruby: 417
file content (335 lines) | stat: -rw-r--r-- 8,586 bytes parent folder | download
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
package tools

import (
	"fmt"
	"os"
	"os/user"
	"path/filepath"
	"runtime"
	"sort"
	"testing"

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

func TestCleanPathsCleansPaths(t *testing.T) {
	cleaned := CleanPaths("/foo/bar/,/foo/bar/baz", ",")
	assert.Equal(t, []string{"/foo/bar", "/foo/bar/baz"}, cleaned)
}

func TestCleanPathsReturnsNoResultsWhenGivenNoPaths(t *testing.T) {
	cleaned := CleanPaths("", ",")
	assert.Empty(t, cleaned)
}

type ExpandPathTestCase struct {
	Path   string
	Expand bool

	Want    string
	WantErr string

	currentUser func() (*user.User, error)
	lookupUser  func(who string) (*user.User, error)
}

func (c *ExpandPathTestCase) Assert(t *testing.T) {
	if c.currentUser != nil {
		oldCurrentUser := currentUser
		currentUser = c.currentUser
		defer func() { currentUser = oldCurrentUser }()
	}

	if c.lookupUser != nil {
		oldLookupUser := lookupUser
		lookupUser = c.lookupUser
		defer func() { lookupUser = oldLookupUser }()
	}

	got, err := ExpandPath(c.Path, c.Expand)
	if err != nil || len(c.WantErr) > 0 {
		assert.EqualError(t, err, c.WantErr)
	}
	assert.Equal(t, filepath.ToSlash(c.Want), filepath.ToSlash(got))
}

func TestExpandPath(t *testing.T) {
	for desc, c := range map[string]*ExpandPathTestCase{
		"no expand": {
			Path: "/path/to/hooks",
			Want: "/path/to/hooks",
		},
		"current": {
			Path: "~/path/to/hooks",
			Want: "/home/jane/path/to/hooks",
			currentUser: func() (*user.User, error) {
				return &user.User{
					HomeDir: "/home/jane",
				}, nil
			},
		},
		"current, slash": {
			Path: "~/",
			Want: "/home/jane",
			currentUser: func() (*user.User, error) {
				return &user.User{
					HomeDir: "/home/jane",
				}, nil
			},
		},
		"current, no slash": {
			Path: "~",
			Want: "/home/jane",
			currentUser: func() (*user.User, error) {
				return &user.User{
					HomeDir: "/home/jane",
				}, nil
			},
		},
		"non-current": {
			Path: "~other/path/to/hooks",
			Want: "/home/special/path/to/hooks",
			lookupUser: func(who string) (*user.User, error) {
				assert.Equal(t, "other", who)
				return &user.User{
					HomeDir: "/home/special",
				}, nil
			},
		},
		"non-current, no slash": {
			Path: "~other",
			Want: "/home/special",
			lookupUser: func(who string) (*user.User, error) {
				assert.Equal(t, "other", who)
				return &user.User{
					HomeDir: "/home/special",
				}, nil
			},
		},
		"non-current (missing)": {
			Path:    "~other/path/to/hooks",
			WantErr: "could not find user other: missing",
			lookupUser: func(who string) (*user.User, error) {
				assert.Equal(t, "other", who)
				return nil, fmt.Errorf("missing")
			},
		},
	} {
		t.Run(desc, c.Assert)
	}
}

type ExpandConfigPathTestCase struct {
	Path        string
	DefaultPath string

	Want    string
	WantErr string

	currentUser      func() (*user.User, error)
	lookupConfigHome func() string
}

func (c *ExpandConfigPathTestCase) Assert(t *testing.T) {
	if c.currentUser != nil {
		oldCurrentUser := currentUser
		currentUser = c.currentUser
		defer func() { currentUser = oldCurrentUser }()
	}

	if c.lookupConfigHome != nil {
		oldLookupConfigHome := lookupConfigHome
		lookupConfigHome = c.lookupConfigHome
		defer func() { lookupConfigHome = oldLookupConfigHome }()
	}

	got, err := ExpandConfigPath(c.Path, c.DefaultPath)
	if err != nil || len(c.WantErr) > 0 {
		assert.EqualError(t, err, c.WantErr)
	}
	assert.Equal(t, filepath.ToSlash(c.Want), filepath.ToSlash(got))
}

func TestExpandConfigPath(t *testing.T) {
	os.Unsetenv("XDG_CONFIG_HOME")
	for desc, c := range map[string]*ExpandConfigPathTestCase{
		"unexpanded full path": {
			Path: "/path/to/attributes",
			Want: "/path/to/attributes",
		},
		"expanded full path": {
			Path: "~/path/to/attributes",
			Want: "/home/pat/path/to/attributes",
			currentUser: func() (*user.User, error) {
				return &user.User{
					HomeDir: "/home/pat",
				}, nil
			},
		},
		"expanded default path": {
			DefaultPath: "git/attributes",
			Want:        "/home/pat/.config/git/attributes",
			currentUser: func() (*user.User, error) {
				return &user.User{
					HomeDir: "/home/pat",
				}, nil
			},
		},
		"XDG_CONFIG_HOME set": {
			DefaultPath: "git/attributes",
			Want:        "/home/pat/configpath/git/attributes",
			lookupConfigHome: func() string {
				return "/home/pat/configpath"
			},
		},
	} {
		t.Run(desc, c.Assert)
	}
}

func TestFastWalkBasic(t *testing.T) {
	wd, err := os.Getwd()
	assert.NoError(t, err)

	rootDir := t.TempDir()
	os.Chdir(rootDir)
	defer os.Chdir(wd)

	expectedEntries := createFastWalkInputData(10, 160)

	walker := fastWalkWithExcludeFiles(expectedEntries[0])
	gotEntries, gotErrors := collectFastWalkResults(walker.ch)

	assert.Empty(t, gotErrors)

	sort.Strings(expectedEntries)
	sort.Strings(gotEntries)
	assert.Equal(t, expectedEntries, gotEntries)
}

// Make test data - ensure you've Chdir'ed into a temp dir first
// Returns list of files/dirs that are created
// First entry is the parent dir of all others
func createFastWalkInputData(smallFolder, largeFolder int) []string {
	dirs := []string{
		"testroot",
		"testroot/folder1",
		"testroot/folder2",
		"testroot/folder2/subfolder1",
		"testroot/folder2/subfolder2",
		"testroot/folder2/subfolder3",
		"testroot/folder2/subfolder4",
		"testroot/folder2/subfolder4/subsub",
	}
	expectedEntries := make([]string, 0, 250)

	for i, dir := range dirs {
		os.MkdirAll(dir, 0755)
		numFiles := smallFolder
		expectedEntries = append(expectedEntries, dir)
		if i >= 3 && i <= 5 {
			// Bulk test to ensure works with > 1 batch
			numFiles = largeFolder
		}
		for f := 0; f < numFiles; f++ {
			filename := join(dir, fmt.Sprintf("file%d.txt", f))
			os.WriteFile(filename, []byte("TEST"), 0644)
			expectedEntries = append(expectedEntries, filename)
		}
	}

	return expectedEntries
}

func collectFastWalkResults(fchan <-chan fastWalkInfo) ([]string, []error) {
	gotEntries := make([]string, 0, 1000)
	gotErrors := make([]error, 0, 5)
	for o := range fchan {
		if o.Err != nil {
			gotErrors = append(gotErrors, o.Err)
		} else {
			if len(o.ParentDir) == 0 {
				gotEntries = append(gotEntries, o.Info.Name())
			} else {
				gotEntries = append(gotEntries, join(o.ParentDir, o.Info.Name()))
			}
		}
	}

	return gotEntries, gotErrors
}

func getFileMode(filename string) os.FileMode {
	s, err := os.Stat(filename)
	if err != nil {
		return 0000
	}
	return s.Mode()
}

// uniq creates an element-wise copy of "xs" containing only unique elements in
// the same order.
func uniq(xs []string) []string {
	seen := make(map[string]struct{})
	uniq := make([]string, 0, len(xs))

	for _, x := range xs {
		if _, ok := seen[x]; !ok {
			seen[x] = struct{}{}
			uniq = append(uniq, x)
		}
	}

	return uniq
}

func TestSetWriteFlag(t *testing.T) {
	f, err := os.CreateTemp("", "lfstestwriteflag")
	assert.Nil(t, err)
	filename := f.Name()
	defer os.Remove(filename)
	f.Close()
	// Set up with read/write bit for all but no execute
	assert.Nil(t, os.Chmod(filename, 0666))

	assert.Nil(t, SetFileWriteFlag(filename, false))
	// should turn off all write
	assert.EqualValues(t, 0444, getFileMode(filename))
	assert.Nil(t, SetFileWriteFlag(filename, true))
	// should only add back user write (on Mac/Linux)
	if runtime.GOOS == "windows" {
		assert.EqualValues(t, 0666, getFileMode(filename))
	} else {
		assert.EqualValues(t, 0644, getFileMode(filename))
	}

	// Can't run selective UGO tests on Windows as doesn't support separate roles
	// Also Golang only supports read/write but not execute on Windows
	if runtime.GOOS != "windows" {
		// Set up with read/write/execute bit for all but no execute
		assert.Nil(t, os.Chmod(filename, 0777))
		assert.Nil(t, SetFileWriteFlag(filename, false))
		// should turn off all write but not execute
		assert.EqualValues(t, 0555, getFileMode(filename))
		assert.Nil(t, SetFileWriteFlag(filename, true))
		// should only add back user write (on Mac/Linux)
		if runtime.GOOS == "windows" {
			assert.EqualValues(t, 0777, getFileMode(filename))
		} else {
			assert.EqualValues(t, 0755, getFileMode(filename))
		}

		assert.Nil(t, os.Chmod(filename, 0440))
		assert.Nil(t, SetFileWriteFlag(filename, false))
		assert.EqualValues(t, 0440, getFileMode(filename))
		assert.Nil(t, SetFileWriteFlag(filename, true))
		// should only add back user write
		assert.EqualValues(t, 0640, getFileMode(filename))
	}
}

func TestExecutablePermissions(t *testing.T) {
	assert.EqualValues(t, os.FileMode(0755), ExecutablePermissions(0644))
	assert.EqualValues(t, os.FileMode(0750), ExecutablePermissions(0640))
	assert.EqualValues(t, os.FileMode(0700), ExecutablePermissions(0600))
}