summaryrefslogtreecommitdiff
path: root/shelf/ignore.go
blob: be061f33591741380b0c5a4bc80c1948ac538bfe (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
package shelf

import (
	"bufio"
	"bytes"
	"path/filepath"
	"strings"

	"github.com/go-git/go-git/v5/plumbing/format/gitignore"
)

type Ignore struct {
	matcher gitignore.Matcher
}

func newIgnore(data []byte) *Ignore {
	var patterns []gitignore.Pattern

	scanner := bufio.NewScanner(bytes.NewReader(data))

	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())

		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		patterns = append(patterns, gitignore.ParsePattern(line, nil))
	}

	return &Ignore{
		matcher: gitignore.NewMatcher(patterns),
	}
}

func (i *Ignore) Match(path string, isDir bool) bool {
	parts := strings.Split(filepath.ToSlash(path), "/")

	var segments []string

	for _, p := range parts {
		if p != "" {
			segments = append(segments, p)
		}
	}

	return i.matcher.Match(segments, isDir)
}