all repos — erl @ d29d0816680a343ee47c40fa9ace8d80862ac412

Execute Reload Loop

ignore/ignore.go (view raw)

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
package ignore

import (
	"context"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"slices"
	"strings"

	ignore "github.com/sabhiram/go-gitignore"

	"alin.ovh/erl/repository"
)

var DefaultIgnoreFilename = ".ignore"

type Filter struct {
	repo        *repository.Repo
	projectRoot string
	wd          string

	givenPaths []string
	paths      []string
	ignores    []*Ignore
}

type Ignore struct {
	*ignore.GitIgnore

	filename string
}

func New(wd string, path ...string) *Filter {
	return &Filter{
		wd:         wd,
		givenPaths: path,
	}
}

func (f *Filter) ReadIgnoreFiles(ctx context.Context) error {
	if f.projectRoot == "" {
		repo, err := repository.GetRepo(ctx, f.wd)
		if err != nil {
			return err
		}

		f.repo = repo
		f.projectRoot = repo.GetRoot()
	}

	err := f.getPaths()
	if err != nil {
		return err
	}

	f.ignores = []*Ignore{}
	for _, path := range f.paths {
		ig, err := ignore.CompileIgnoreFile(path)
		if err != nil {
			return err
		}

		f.ignores = append(f.ignores, &Ignore{
			GitIgnore: ig,
			filename:  path,
		})
	}

	return nil
}

func (f *Filter) Ignored(path string) bool {
	return slices.ContainsFunc(f.ignores, func(ig *Ignore) bool {
		return ig.MatchesPath(path)
	})
}

func (f *Filter) getPaths() error {
	f.paths = f.givenPaths

	rel, err := filepath.Rel(f.projectRoot, f.wd)
	if err != nil {
		return err
	}

	ignoreFileNames := []string{DefaultIgnoreFilename}
	ignoreFileNames = append(ignoreFileNames, f.repo.GetIgnoreFileNames()...)
	dirs := strings.Split(rel, string(filepath.Separator))
	for i := range dirs {
		var dir string
		if i == 0 {
			dir = "."
		} else {
			dir = filepath.Join(dirs[:i+1]...)
		}

		for _, basename := range ignoreFileNames {
			filename := filepath.Join(f.projectRoot, dir, basename)
			stat, err := os.Stat(filename)
			if err != nil {
				if errors.Is(err, os.ErrNotExist) {
					continue
				}

				return err
			}
			if stat.IsDir() {
				return fmt.Errorf(
					"%s path is a directory: %s",
					basename,
					filepath.Join(f.projectRoot, dir, filename),
				)
			}

			f.paths = append(f.paths, filename)
		}
	}

	return nil
}