Debian Codegraph @

matchers/matchers.go

raw symbols SCIP
1 package matchers
2
3 import (
4 "github.com/h2non/filetype/types"
5 )
6
7 // Internal shortcut to NewType
8 var newType = types.NewType
9
10 // Matcher function interface as type alias
11 type Matcher func([]byte) bool
12
13 // Type interface to store pairs of type with its matcher function
14 type Map map[types.Type]Matcher
15
16 // Type specific matcher function interface
17 type TypeMatcher func([]byte) types.Type
18
19 // Store registered file type matchers
20 var Matchers = make(map[types.Type]TypeMatcher)
21 var MatcherKeys []types.Type
22
23 // Create and register a new type matcher function
24 func NewMatcher(kind types.Type, fn Matcher) TypeMatcher {
25 matcher := func(buf []byte) types.Type {
26 if fn(buf) {
27 return kind
28 }
29 return types.Unknown
30 }
31
32 Matchers[kind] = matcher
33 // prepend here so any user defined matchers get added first
34 MatcherKeys = append([]types.Type{kind}, MatcherKeys...)
35 return matcher
36 }
37
38 func register(matchers ...Map) {
39 MatcherKeys = MatcherKeys[:0]
40 for _, m := range matchers {
41 for kind, matcher := range m {
42 NewMatcher(kind, matcher)
43 }
44 }
45 }
46
47 func init() {
48 // Arguments order is intentional
49 // Archive files will be checked last due to prepend above in func NewMatcher
50 register(Archive, Document, Font, Audio, Video, Image, Application)
51 }