aboutsummaryrefslogtreecommitdiffstats
path: root/cache/filter.go
blob: 3bcfe13e204af91dd75ae2d8ef1331c89dc75c00 (plain) (blame)
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
package cache

import (
	"strings"

	"github.com/MichaelMure/git-bug/bug"
)

// Filter is a functor that match a subset of bugs
type Filter func(excerpt *BugExcerpt) bool

// StatusFilter return a Filter that match a bug status
func StatusFilter(query string) (Filter, error) {
	status, err := bug.StatusFromString(query)
	if err != nil {
		return nil, err
	}

	return func(excerpt *BugExcerpt) bool {
		return excerpt.Status == status
	}, nil
}

// AuthorFilter return a Filter that match a bug author
func AuthorFilter(query string) Filter {
	cleaned := strings.TrimFunc(query, func(r rune) bool {
		return r == '"' || r == '\''
	})

	return func(excerpt *BugExcerpt) bool {
		return excerpt.Author.Match(cleaned)
	}
}

// LabelFilter return a Filter that match a label
func LabelFilter(label string) Filter {
	return func(excerpt *BugExcerpt) bool {
		for _, l := range excerpt.Labels {
			if string(l) == label {
				return true
			}
		}
		return false
	}
}

// NoLabelFilter return a Filter that match the absence of labels
func NoLabelFilter() Filter {
	return func(excerpt *BugExcerpt) bool {
		return len(excerpt.Labels) == 0
	}
}

// Filters is a collection of Filter that implement a complex filter
type Filters struct {
	Status    []Filter
	Author    []Filter
	Label     []Filter
	NoFilters []Filter
}

// Match check if a bug match the set of filters
func (f *Filters) Match(excerpt *BugExcerpt) bool {
	if match := f.orMatch(f.Status, excerpt); !match {
		return false
	}

	if match := f.orMatch(f.Author, excerpt); !match {
		return false
	}

	if match := f.orMatch(f.Label, excerpt); !match {
		return false
	}

	if match := f.andMatch(f.NoFilters, excerpt); !match {
		return false
	}

	return true
}

// Check if any of the filters provided match the bug
func (*Filters) orMatch(filters []Filter, excerpt *BugExcerpt) bool {
	if len(filters) == 0 {
		return true
	}

	match := false
	for _, f := range filters {
		match = match || f(excerpt)
	}

	return match
}

// Check if all of the filters provided match the bug
func (*Filters) andMatch(filters []Filter, excerpt *BugExcerpt) bool {
	if len(filters) == 0 {
		return true
	}

	match := true
	for _, f := range filters {
		match = match && f(excerpt)
	}

	return match
}