~gitpocket/gitpocket

1
fb47c81dba66716c2c0264562d89826d3aa46586
mainfeed-discovery
gitpocket/git.go -rw-r--r--17.5 KiB ViewLogBlameView rawPermalink 0f25c94d29 feat(web): pull request range-diff, pickaxe history search, reproducible tarballs and atom feeds 4 hours ago
  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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
package main

import (
	"bytes"
	"context"
	"errors"
	"io"
	"os"
	"os/exec"
	"path"
	"slices"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"
)

type Git struct {
	Dir string
}

type Commit struct {
	Hash      string
	Author    string
	Email     string
	Time      time.Time
	Subject   string
	Body      string
	Parents   []string
	Signature string
	Key       string
	PGP       string
}

var signersFile string

var gnupgHome string

var passEnv []string

type Entry struct {
	Mode string
	Type string
	Hash string
	Size int64
	Name string
}

type Ref struct {
	Name string
	Hash string
	Time time.Time
}

type Line struct {
	Kind string
	Old  int
	New  int
	Text string
}

type Hunk struct {
	Header string
	Lines  []Line
}

type File struct {
	Old     string
	New     string
	Status  string
	Binary  bool
	Hunks   []Hunk
	Added   int
	Removed int
}

var ErrMissing = errors.New("missing")

func (g Git) run(stdin []byte, args ...string) ([]byte, error) {
	return g.runEnv(nil, stdin, args...)
}

func (g Git) runEnv(env []string, stdin []byte, args ...string) ([]byte, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	cmd := exec.CommandContext(ctx, "git", append([]string{"-C", g.Dir}, args...)...)
	cmd.Env = append([]string{"GIT_CONFIG_NOSYSTEM=1", "HOME=/nonexistent", "LC_ALL=C.UTF-8", "PATH=" + os.Getenv("PATH")}, passEnv...)
	cmd.Env = append(cmd.Env, env...)
	if signersFile != "" {
		cmd.Env = append(cmd.Env, "GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=gpg.ssh.allowedSignersFile", "GIT_CONFIG_VALUE_0="+signersFile)
	}
	if gnupgHome != "" {
		cmd.Env = append(cmd.Env, "GNUPGHOME="+gnupgHome)
	}
	if stdin != nil {
		cmd.Stdin = bytes.NewReader(stdin)
	}
	var out, errb bytes.Buffer
	cmd.Stdout = &out
	cmd.Stderr = &errb
	if err := cmd.Run(); err != nil {
		msg := strings.TrimSpace(errb.String())
		if msg == "" {
			msg = err.Error()
		}
		return nil, errors.New(msg)
	}
	return out.Bytes(), nil
}

func initRepo(dir string) error {
	_, err := Git{Dir: "/"}.run(nil, "init", "--bare", "--quiet", "-b", "main", dir)
	return err
}

func cloneRepo(src, dst string) error {
	_, err := Git{Dir: "/"}.run(nil, "clone", "--bare", "--quiet", "--no-hardlinks", src, dst)
	if err != nil {
		return err
	}
	Git{Dir: dst}.run(nil, "remote", "remove", "origin")
	return nil
}

func (g Git) Fetch(srcDir, srcRef, dstRef string) error {
	_, err := g.run(nil, "fetch", "--quiet", "--no-tags", "--force", srcDir, srcRef+":"+dstRef)
	return err
}

func (g Git) MergeBase(a, b string) (string, error) {
	out, err := g.run(nil, "merge-base", a, b)
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(out)), nil
}

func (g Git) LogRange(base, head string, n int) ([]Commit, error) {
	out, err := g.run(nil, "log", "--format="+logFormat, "-n", strconv.Itoa(n), base+".."+head)
	if err != nil {
		return nil, err
	}
	return parseCommits(out), nil
}

func (g Git) DiffRange(base, head string) ([]File, error) {
	out, err := g.run(nil, "diff", "-M", "--no-color", base, head)
	if err != nil {
		return nil, err
	}
	return parseDiff(string(out)), nil
}

func (g Git) Mergeable(target, head string) bool {
	_, err := g.run(nil, "merge-tree", "--write-tree", "refs/heads/"+target, head)
	return err == nil
}

func (g Git) mergeTree(base, ours, theirs string) (string, error) {
	args := []string{"merge-tree", "--write-tree"}
	if base != "" {
		args = append(args, "--merge-base", base)
	}
	out, err := g.run(nil, append(args, ours, theirs)...)
	if err != nil {
		return "", errors.New("merge conflicts, resolve them locally and update the pull request")
	}
	tree, _, _ := strings.Cut(strings.TrimSpace(string(out)), "\n")
	return tree, nil
}

func timeNow() time.Time { return time.Now() }

func ident(name, email string, when time.Time) []string {
	stamp := strconv.FormatInt(when.Unix(), 10) + " +0000"
	return []string{"GIT_AUTHOR_NAME=" + name, "GIT_AUTHOR_EMAIL=" + email, "GIT_AUTHOR_DATE=" + stamp, "GIT_COMMITTER_NAME=" + name, "GIT_COMMITTER_EMAIL=" + email, "GIT_COMMITTER_DATE=" + stamp}
}

func (g Git) Squash(target, head, message, authorName, authorEmail, name, email string) (string, error) {
	targetHash, err := g.Resolve("refs/heads/" + target)
	if err != nil {
		return "", errors.New("target branch is missing")
	}
	headHash, err := g.Resolve(head)
	if err != nil {
		return "", errors.New("pull request head is missing")
	}
	if base, err := g.MergeBase(targetHash, headHash); err == nil && base == headHash {
		return "", errors.New("already merged")
	}
	tree, err := g.mergeTree("", targetHash, headHash)
	if err != nil {
		return "", err
	}
	now := time.Now()
	env := ident(authorName, authorEmail, now)
	env[3], env[4] = "GIT_COMMITTER_NAME="+name, "GIT_COMMITTER_EMAIL="+email
	commit, err := g.runEnv(env, []byte(message), "commit-tree", tree, "-p", targetHash)
	if err != nil {
		return "", err
	}
	hash := strings.TrimSpace(string(commit))
	if _, err := g.run(nil, "update-ref", "refs/heads/"+target, hash, targetHash); err != nil {
		return "", errors.New("target branch moved, try again")
	}
	return hash, nil
}

func (g Git) Rebase(target, head, name, email string) (string, error) {
	targetHash, err := g.Resolve("refs/heads/" + target)
	if err != nil {
		return "", errors.New("target branch is missing")
	}
	headHash, err := g.Resolve(head)
	if err != nil {
		return "", errors.New("pull request head is missing")
	}
	base, err := g.MergeBase(targetHash, headHash)
	if err != nil {
		return "", errors.New("no common history")
	}
	if base == headHash {
		return "", errors.New("already merged")
	}
	out, err := g.run(nil, "rev-list", "--reverse", "--no-merges", base+".."+headHash)
	if err != nil {
		return "", err
	}
	tip := targetHash
	for _, c := range strings.Fields(string(out)) {
		info, err := g.run(nil, "log", "-n", "1", "--format=%P%x00%an%x00%ae%x00%at%x00%B", c)
		if err != nil {
			return "", err
		}
		f := strings.SplitN(string(info), "\x00", 5)
		if len(f) != 5 {
			return "", errors.New("could not read commit " + c)
		}
		parent := strings.Fields(f[0])
		if len(parent) == 0 {
			return "", errors.New("cannot rebase a root commit")
		}
		tree, err := g.mergeTree(parent[0], tip, c)
		if err != nil {
			return "", err
		}
		t, _ := strconv.ParseInt(f[3], 10, 64)
		env := ident(f[1], f[2], time.Unix(t, 0))
		env[3], env[4], env[5] = "GIT_COMMITTER_NAME="+name, "GIT_COMMITTER_EMAIL="+email, "GIT_COMMITTER_DATE="+strconv.FormatInt(time.Now().Unix(), 10)+" +0000"
		commit, err := g.runEnv(env, []byte(strings.TrimRight(f[4], "\n")+"\n"), "commit-tree", tree, "-p", tip)
		if err != nil {
			return "", err
		}
		tip = strings.TrimSpace(string(commit))
	}
	if _, err := g.run(nil, "update-ref", "refs/heads/"+target, tip, targetHash); err != nil {
		return "", errors.New("target branch moved, try again")
	}
	return tip, nil
}

func (g Git) Merge(target, head, message, name, email string) (string, error) {
	targetHash, err := g.Resolve("refs/heads/" + target)
	if err != nil {
		return "", errors.New("target branch is missing")
	}
	headHash, err := g.Resolve(head)
	if err != nil {
		return "", errors.New("pull request head is missing")
	}
	if base, err := g.MergeBase(targetHash, headHash); err == nil && base == headHash {
		return "", errors.New("already merged")
	}
	out, err := g.run(nil, "merge-tree", "--write-tree", targetHash, headHash)
	if err != nil {
		return "", errors.New("merge conflicts, resolve them locally and update the pull request")
	}
	tree, _, _ := strings.Cut(strings.TrimSpace(string(out)), "\n")
	ident := []string{"GIT_AUTHOR_NAME=" + name, "GIT_AUTHOR_EMAIL=" + email, "GIT_COMMITTER_NAME=" + name, "GIT_COMMITTER_EMAIL=" + email}
	commit, err := g.runEnv(ident, []byte(message), "commit-tree", tree, "-p", targetHash, "-p", headHash)
	if err != nil {
		return "", err
	}
	hash := strings.TrimSpace(string(commit))
	if _, err := g.run(nil, "update-ref", "refs/heads/"+target, hash, targetHash); err != nil {
		return "", errors.New("target branch moved, try again")
	}
	return hash, nil
}

func (g Git) Empty() bool {
	_, err := g.run(nil, "rev-parse", "--verify", "--quiet", "HEAD^{commit}")
	return err != nil
}

func (g Git) Head() string {
	out, err := g.run(nil, "symbolic-ref", "--short", "HEAD")
	if err != nil {
		return "main"
	}
	return strings.TrimSpace(string(out))
}

func (g Git) Resolve(ref string) (string, error) {
	if strings.HasPrefix(ref, "-") {
		return "", ErrMissing
	}
	out, err := g.run(nil, "rev-parse", "--verify", "--quiet", "--end-of-options", ref+"^{commit}")
	if err != nil {
		return "", ErrMissing
	}
	return strings.TrimSpace(string(out)), nil
}

const logFormat = "%H%x00%an%x00%ae%x00%at%x00%P%x00%s%x00%b%x00%G?%x00%GK%x00%GP%x00"

func parseCommits(out []byte) []Commit {
	fields := strings.Split(string(out), "\x00")
	var commits []Commit
	for len(fields) >= 10 {
		t, _ := strconv.ParseInt(fields[3], 10, 64)
		c := Commit{Hash: fields[0], Author: fields[1], Email: fields[2], Time: time.Unix(t, 0), Subject: fields[5], Body: strings.TrimSpace(fields[6]), Signature: fields[7], Key: fields[8], PGP: strings.ToUpper(fields[9])}
		if fields[4] != "" {
			c.Parents = strings.Split(fields[4], " ")
		}
		commits = append(commits, c)
		fields = fields[10:]
		if len(fields) > 0 {
			fields[0] = strings.TrimLeft(fields[0], "\n")
		}
	}
	return commits
}

func (g Git) Log(commit string, n int, filePath string, extra ...string) ([]Commit, error) {
	args := append([]string{"log", "--format=" + logFormat, "-n", strconv.Itoa(n)}, extra...)
	args = append(args, commit)
	if filePath != "" {
		args = append(args, "--", filePath)
	}
	out, err := g.run(nil, args...)
	if err != nil {
		return nil, err
	}
	return parseCommits(out), nil
}

func (g Git) Commit(hash string) (Commit, error) {
	out, err := g.run(nil, "log", "--format="+logFormat, "-n", "1", hash)
	if err != nil {
		return Commit{}, ErrMissing
	}
	commits := parseCommits(out)
	if len(commits) == 0 {
		return Commit{}, ErrMissing
	}
	return commits[0], nil
}

func (g Git) Tree(commit, dir string) ([]Entry, error) {
	spec := commit + ":" + dir
	out, err := g.run(nil, "ls-tree", "-l", "-z", spec)
	if err != nil {
		return nil, ErrMissing
	}
	var entries []Entry
	for _, rec := range bytes.Split(out, []byte{0}) {
		if len(rec) == 0 {
			continue
		}
		meta, name, ok := strings.Cut(string(rec), "\t")
		if !ok {
			continue
		}
		f := strings.Fields(meta)
		if len(f) != 4 {
			continue
		}
		e := Entry{Mode: f[0], Type: f[1], Hash: f[2], Name: name}
		if f[3] != "-" {
			e.Size, _ = strconv.ParseInt(f[3], 10, 64)
		}
		entries = append(entries, e)
	}
	slices.SortStableFunc(entries, func(a, b Entry) int {
		if (a.Type == "tree") != (b.Type == "tree") {
			if a.Type == "tree" {
				return -1
			}
			return 1
		}
		return strings.Compare(strings.ToLower(a.Name), strings.ToLower(b.Name))
	})
	return entries, nil
}

type Match struct {
	Path string
	Line int
	Text string
}

func (g Git) Grep(commit, query string, limit int) ([]Match, bool, error) {
	out, err := g.run(nil, "grep", "-n", "-i", "-I", "-F", "-z", "--no-color", "-e", query, commit)
	if err != nil {
		if strings.TrimSpace(err.Error()) == "" || strings.Contains(err.Error(), "exit status 1") {
			return nil, false, nil
		}
		return nil, false, err
	}
	var matches []Match
	prefix := commit + ":"
	for _, line := range strings.Split(string(out), "\n") {
		f := strings.Split(line, "\x00")
		if len(f) != 3 || !strings.HasPrefix(f[0], prefix) {
			continue
		}
		n, _ := strconv.Atoi(f[1])
		matches = append(matches, Match{Path: strings.TrimPrefix(f[0], prefix), Line: n, Text: strings.TrimLeft(f[2], " \t")})
		if len(matches) > limit {
			return matches[:limit], true, nil
		}
	}
	return matches, false, nil
}

func (g Git) Entry(commit, filePath string) *Entry {
	if filePath == "" {
		return nil
	}
	dir, name := path.Split(filePath)
	entries, err := g.Tree(commit, strings.TrimSuffix(dir, "/"))
	if err != nil {
		return nil
	}
	for i := range entries {
		if entries[i].Name == name {
			return &entries[i]
		}
	}
	return nil
}

func (g Git) LastCommits(commit, dir string, names []string) map[string]Commit {
	want := map[string]bool{}
	for _, n := range names {
		want[n] = true
	}
	found := map[string]Commit{}
	args := []string{"log", "--format=%x01%H%x00%at%x00%s", "--name-only", "--no-renames", "-n", "3000", commit}
	if dir != "" {
		args = append(args, "--", dir)
	}
	out, err := g.run(nil, args...)
	if err != nil {
		return found
	}
	prefix := ""
	if dir != "" {
		prefix = dir + "/"
	}
	var cur Commit
	for _, line := range strings.Split(string(out), "\n") {
		if strings.HasPrefix(line, "\x01") {
			f := strings.Split(line[1:], "\x00")
			if len(f) == 3 {
				t, _ := strconv.ParseInt(f[1], 10, 64)
				cur = Commit{Hash: f[0], Time: time.Unix(t, 0), Subject: f[2]}
			}
			continue
		}
		if line == "" || !strings.HasPrefix(line, prefix) {
			continue
		}
		name, _, _ := strings.Cut(line[len(prefix):], "/")
		if want[name] {
			if _, ok := found[name]; !ok {
				found[name] = cur
				if len(found) == len(want) {
					break
				}
			}
		}
	}
	return found
}

func (g Git) Stream(w io.Writer, commit, filePath string) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()
	cmd := exec.CommandContext(ctx, "git", "-C", g.Dir, "cat-file", "blob", commit+":"+filePath)
	cmd.Env = []string{"GIT_CONFIG_NOSYSTEM=1", "HOME=/nonexistent", "PATH=" + os.Getenv("PATH")}
	cmd.Stdout = w
	return cmd.Run()
}

func (g Git) Blob(commit, filePath string) ([]byte, error) {
	out, err := g.run(nil, "cat-file", "blob", commit+":"+filePath)
	if err != nil {
		return nil, ErrMissing
	}
	return out, nil
}

func (g Git) Size(commit, filePath string) int64 {
	out, err := g.run(nil, "cat-file", "-s", commit+":"+filePath)
	if err != nil {
		return 0
	}
	n, _ := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64)
	return n
}

func (g Git) Kind(commit, filePath string) string {
	out, err := g.run(nil, "cat-file", "-t", commit+":"+filePath)
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(out))
}

func (g Git) Refs(prefix string) ([]Ref, error) {
	out, err := g.run(nil, "for-each-ref", "--sort=-creatordate", "--format=%(refname:short)%00%(objectname)%00%(creatordate:unix)", prefix)
	if err != nil {
		return nil, err
	}
	var refs []Ref
	for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
		f := strings.Split(line, "\x00")
		if len(f) != 3 {
			continue
		}
		t, _ := strconv.ParseInt(f[2], 10, 64)
		refs = append(refs, Ref{Name: f[0], Hash: f[1], Time: time.Unix(t, 0)})
	}
	return refs, nil
}

func (g Git) Readme(commit string) (string, []byte) {
	entries, err := g.Tree(commit, "")
	if err != nil {
		return "", nil
	}
	for _, name := range []string{"README.md", "README", "readme.md", "README.txt", "readme"} {
		for _, e := range entries {
			if e.Name == name && e.Type == "blob" {
				data, err := g.Blob(commit, name)
				if err == nil {
					return name, data
				}
			}
		}
	}
	return "", nil
}

func (g Git) Diff(hash string) ([]File, error) {
	out, err := g.run(nil, "diff-tree", "-p", "--root", "-M", "--no-color", "--find-renames", hash)
	if err != nil {
		return nil, err
	}
	return parseDiff(string(out)), nil
}

func parseDiff(text string) []File {
	var files []File
	var cur *File
	var hunk *Hunk
	oldN, newN := 0, 0
	for _, line := range strings.Split(text, "\n") {
		switch {
		case strings.HasPrefix(line, "diff --git "):
			files = append(files, File{Status: "modified"})
			cur = &files[len(files)-1]
			hunk = nil
			rest := strings.TrimPrefix(line, "diff --git ")
			if a, b, ok := strings.Cut(rest, " b/"); ok {
				cur.Old = strings.TrimPrefix(a, "a/")
				cur.New = b
			}
		case cur == nil:
			continue
		case strings.HasPrefix(line, "new file mode"):
			cur.Status = "added"
		case strings.HasPrefix(line, "deleted file mode"):
			cur.Status = "deleted"
		case strings.HasPrefix(line, "rename from "):
			cur.Status = "renamed"
			cur.Old = strings.TrimPrefix(line, "rename from ")
		case strings.HasPrefix(line, "rename to "):
			cur.New = strings.TrimPrefix(line, "rename to ")
		case strings.HasPrefix(line, "Binary files"):
			cur.Binary = true
		case strings.HasPrefix(line, "--- ") || strings.HasPrefix(line, "+++ ") || strings.HasPrefix(line, "index ") || strings.HasPrefix(line, "similarity ") || strings.HasPrefix(line, "old mode") || strings.HasPrefix(line, "new mode"):
			continue
		case strings.HasPrefix(line, "@@"):
			cur.Hunks = append(cur.Hunks, Hunk{Header: line})
			hunk = &cur.Hunks[len(cur.Hunks)-1]
			oldN, newN = hunkStart(line)
		case hunk == nil:
			continue
		case strings.HasPrefix(line, "+"):
			hunk.Lines = append(hunk.Lines, Line{Kind: "add", New: newN, Text: line[1:]})
			newN++
			cur.Added++
		case strings.HasPrefix(line, "-"):
			hunk.Lines = append(hunk.Lines, Line{Kind: "del", Old: oldN, Text: line[1:]})
			oldN++
			cur.Removed++
		case strings.HasPrefix(line, " "):
			hunk.Lines = append(hunk.Lines, Line{Kind: "ctx", Old: oldN, New: newN, Text: line[1:]})
			oldN++
			newN++
		case strings.HasPrefix(line, "\\"):
			hunk.Lines = append(hunk.Lines, Line{Kind: "meta", Text: line})
		}
	}
	return files
}

func hunkStart(header string) (int, int) {
	f := strings.Fields(header)
	if len(f) < 3 {
		return 0, 0
	}
	parse := func(s string) int {
		s = strings.TrimLeft(s, "-+")
		if i := strings.Index(s, ","); i >= 0 {
			s = s[:i]
		}
		n, _ := strconv.Atoi(s)
		return n
	}
	return parse(f[1]), parse(f[2])
}

func isBinary(data []byte) bool {
	head := data
	if len(head) > 8000 {
		head = head[:8000]
	}
	return bytes.IndexByte(head, 0) >= 0 || !utf8.Valid(head)
}

func cleanPath(p string) (string, bool) {
	p = strings.Trim(p, "/")
	if p == "" {
		return "", true
	}
	c := path.Clean(p)
	if c != p || strings.HasPrefix(c, "..") || strings.Contains(c, "/../") || strings.HasPrefix(c, "-") {
		return "", false
	}
	return c, true
}