forked from h2non/filetype
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatch.go
105 lines (85 loc) · 2.25 KB
/
match.go
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
package filetype
import (
"io"
"os"
)
// Matcher function interface as type alias
type MatcherFunc func([]byte) bool
// Type interface to store pairs of type with its matcher function
type MapOfMatcherFunc map[Typed]MatcherFunc
// Type specific matcher function interface
type TypeMatcherFunc func([]byte) Typed
// Store registered file type matchers
var Matchers = make(map[Typed]TypeMatcherFunc)
func register(mmapFunc ...MapOfMatcherFunc) {
for _, m := range mmapFunc {
for kind, matchr := range m {
NewMatcher(kind, matchr)
}
}
}
func init() {
// Arguments order is intentional
register(Image, Video, Audio, Font, Document, Archive)
}
// AddMatcher registers a new matcher type
//func AddMatcher(fileType Typed, mFunc MatcherFunc) TypeMatcherFunc {
// return NewMatcher(fileType, mFunc)
//}
// Create and register a new type matcher function
func NewMatcher(t Typed, fn MatcherFunc) TypeMatcherFunc {
matcher := func(buf []byte) Typed {
if fn(buf) {
return t
}
return Unknown
}
Matchers[t] = matcher
return matcher
}
// Match infers the file type of a given buffer inspecting its magic numbers signature
func MatchBuffer(buf []byte) (Typed, error) {
length := len(buf)
if length == 0 {
return Unknown, ErrEmptyBuffer
}
for _, checker := range Matchers {
match := checker(buf)
if match != Unknown && match.Extension != "" {
return match, nil
}
}
return Unknown, nil
}
// MatchReader is convenient wrapper to MatchBuffer() any Reader
func MatchReader(reader io.Reader) (Typed, error) {
buffer := make([]byte, 512)
_, err := reader.Read(buffer)
if err != nil && err != io.EOF {
return Unknown, err
}
return MatchBuffer(buffer)
}
// MatchFile infers a file type for a file
func MatchFile(filepath string) (Typed, error) {
file, err := os.Open(filepath)
if err != nil {
return Unknown, err
}
defer file.Close()
return MatchReader(file)
}
// Matches checks if the given buffer matches with some supported file type
func Matches(buf []byte) bool {
kind, _ := MatchBuffer(buf)
return kind != Unknown
}
// MatchMap performs a file matching againts a map of match functions
func MatchMap(buf []byte, mmapFunc MapOfMatcherFunc) Typed {
for kind, matcher := range mmapFunc {
if matcher(buf) {
return kind
}
}
return Unknown
}