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