Debian Codegraph @

mime.go

raw symbols SCIP
1 package mimetype
2
3 import (
4 stdmime "mime"
5 "slices"
6 "strings"
7
8 "github.com/gabriel-vasile/mimetype/internal/charset"
9 "github.com/gabriel-vasile/mimetype/internal/magic"
10 )
11
12 // MIME struct holds information about a file format: the string representation
13 // of the MIME type, the extension and the parent file format.
14 type MIME struct {
15 mime string
16 aliases []string
17 extension string
18 // detector receives the raw input and a limit for the number of bytes it is
19 // allowed to check. It returns whether the input matches a signature or not.
20 detector magic.Detector
21 children []*MIME
22 parent *MIME
23 }
24
25 // String returns the string representation of the MIME type, e.g., "application/zip".
26 func (m *MIME) String() string {
27 return m.mime
28 }
29
30 // Extension returns the file extension associated with the MIME type.
31 // It includes the leading dot, as in ".html". When the file format does not
32 // have an extension, the empty string is returned.
33 func (m *MIME) Extension() string {
34 return m.extension
35 }
36
37 // Parent returns the parent MIME type from the hierarchy.
38 // Each MIME type has a non-nil parent, except for the root MIME type.
39 //
40 // For example, the application/json and text/html MIME types have text/plain as
41 // their parent because they are text files who happen to contain JSON or HTML.
42 // Another example is the ZIP format, which is used as container
43 // for Microsoft Office files, EPUB files, JAR files, and others.
44 func (m *MIME) Parent() *MIME {
45 return m.parent
46 }
47
48 // Is checks whether this MIME type, or any of its aliases, is equal to the
49 // expected MIME type. MIME type equality test is done on the "type/subtype"
50 // section, ignores any optional MIME parameters, ignores any leading and
51 // trailing whitespace, and is case insensitive.
52 func (m *MIME) Is(expectedMIME string) bool {
53 // Parsing is needed because some detected MIME types contain parameters
54 // that need to be stripped for the comparison.
55 expectedMIME, _, _ = stdmime.ParseMediaType(expectedMIME)
56 found, _, _ := stdmime.ParseMediaType(m.mime)
57
58 if expectedMIME == found {
59 return true
60 }
61
62 if slices.Contains(m.aliases, expectedMIME) {
63 return true
64 }
65
66 return false
67 }
68
69 func newMIME(
70 mime, extension string,
71 detector magic.Detector,
72 children ...*MIME) *MIME {
73 m := &MIME{
74 mime: mime,
75 extension: extension,
76 detector: detector,
77 children: children,
78 }
79
80 for _, c := range children {
81 c.parent = m
82 }
83
84 return m
85 }
86
87 func (m *MIME) alias(aliases ...string) *MIME {
88 m.aliases = aliases
89 return m
90 }
91
92 // match does a depth-first search on the signature tree. It returns the deepest
93 // successful node for which all the children detection functions fail.
94 func (m *MIME) match(in []byte, readLimit uint32) *MIME {
95 for _, c := range m.children {
96 if c.detector(in, readLimit) {
97 return c.match(in, readLimit)
98 }
99 }
100
101 needsCharset := map[string]func([]byte) string{
102 "text/plain": charset.FromPlain,
103 "text/html": charset.FromHTML,
104 "text/xml": charset.FromXML,
105 }
106 charset := ""
107 if f, ok := needsCharset[m.mime]; ok {
108 // The charset comes from BOM, from HTML headers, from XML headers.
109 // Limit the number of bytes searched for to 1024.
110 charset = f(in[:min(len(in), 1024)])
111 }
112 if m == root || charset == "" {
113 return m
114 }
115
116 return m.cloneHierarchy(charset)
117 }
118
119 // flatten transforms an hierarchy of MIMEs into a slice of MIMEs.
120 func (m *MIME) flatten() []*MIME {
121 out := []*MIME{m} //nolint:prealloc
122 for _, c := range m.children {
123 out = append(out, c.flatten()...)
124 }
125
126 return out
127 }
128
129 // hierarchy returns an easy to read list of ancestors for m.
130 // For example, application/json would return json>txt>root.
131 func (m *MIME) hierarchy() string {
132 h := ""
133 for m := m; m != nil; m = m.Parent() {
134 e := strings.TrimPrefix(m.Extension(), ".")
135 if e == "" {
136 // There are some MIME without extensions. When generating the hierarchy,
137 // it would be confusing to use empty string as extension.
138 // Use the subtype instead; ex: application/x-executable -> x-executable.
139 e = strings.Split(m.String(), "/")[1]
140 if m.Is("application/octet-stream") {
141 // for octet-stream use root, because it's short and used in many places
142 e = "root"
143 }
144 }
145 h += ">" + e
146 }
147 return strings.TrimPrefix(h, ">")
148 }
149
150 // clone creates a new MIME with the provided optional MIME parameters.
151 func (m *MIME) clone(charset string) *MIME {
152 clonedMIME := m.mime
153 if charset != "" {
154 clonedMIME = m.mime + "; charset=" + charset
155 }
156
157 return &MIME{
158 mime: clonedMIME,
159 aliases: m.aliases,
160 extension: m.extension,
161 }
162 }
163
164 // cloneHierarchy creates a clone of m and all its ancestors. The optional MIME
165 // parameters are set on the last child of the hierarchy.
166 func (m *MIME) cloneHierarchy(charset string) *MIME {
167 ret := m.clone(charset)
168 lastChild := ret
169 for p := m.Parent(); p != nil; p = p.Parent() {
170 pClone := p.clone("")
171 lastChild.parent = pClone
172 lastChild = pClone
173 }
174
175 return ret
176 }
177
178 func (m *MIME) lookup(mime string) *MIME {
179 if mime == m.mime {
180 return m
181 }
182 if slices.Contains(m.aliases, mime) {
183 return m
184 }
185
186 for _, c := range m.children {
187 if m := c.lookup(mime); m != nil {
188 return m
189 }
190 }
191 return nil
192 }
193
194 // Extend adds detection for a sub-format. The detector is a function
195 // returning true when the raw input file satisfies a signature.
196 // The sub-format will be detected if all the detectors in the parent chain return true.
197 // The extension should include the leading dot, as in ".html".
198 func (m *MIME) Extend(detector func(raw []byte, limit uint32) bool, mime, extension string, aliases ...string) {
199 mime, _, _ = stdmime.ParseMediaType(mime)
200 c := &MIME{
201 mime: mime,
202 extension: extension,
203 detector: detector,
204 parent: m,
205 aliases: aliases,
206 }
207
208 mu.Lock()
209 m.children = append([]*MIME{c}, m.children...)
210 mu.Unlock()
211 }