1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package domain
4
5import (
6 "bytes"
7 "net/http"
8 "path"
9 "strings"
10)
11
12// SniffContent sets Binary and MediaType from the first bytes of the content
13// (Path must be set). Only the first BinarySniffLen bytes count, so a caller
14// may pass the whole content or just its head. Every reader of blobs applies
15// this one rule.
16func (b *BlobInfo) SniffContent(content []byte) {
17 head := content[:min(len(content), BinarySniffLen)]
18 b.Binary = bytes.IndexByte(head, 0) >= 0
19 b.MediaType = mediaType(b.Path, head, b.Binary)
20}
21
22// textTypes maps the extensions whose media type is more precise than what
23// the content shows. It is fixed here so that the answer does not depend on the
24// MIME tables of the host.
25var textTypes = map[string]string{
26 ".html": "text/html", ".htm": "text/html", ".css": "text/css",
27 ".js": "text/javascript", ".mjs": "text/javascript",
28 ".json": "application/json", ".xml": "application/xml",
29 ".svg": "image/svg+xml", ".md": "text/markdown", ".csv": "text/csv",
30}
31
32// mediaType guesses a media type without parameters. What the content shows
33// (images, archives, PDF…) wins; for plain text the file name may refine it
34// from textTypes, but a name never makes binary content text.
35func mediaType(name string, head []byte, binary bool) string {
36 sniffed, _, _ := strings.Cut(http.DetectContentType(head), ";")
37 switch {
38 case binary && strings.HasPrefix(sniffed, "text/"):
39 return "application/octet-stream"
40 case sniffed != "text/plain" && sniffed != "text/xml" && sniffed != "application/octet-stream":
41 return sniffed
42 case binary:
43 return "application/octet-stream"
44 }
45 if t, ok := textTypes[strings.ToLower(path.Ext(name))]; ok {
46 return t
47 }
48 return "text/plain"
49}
50
51// ValidGitText replaces the bytes of s that are not valid UTF-8 with U+FFFD:
52// names, emails and messages of commits may hold any bytes.
53func ValidGitText(s string) string { return strings.ToValidUTF8(s, "\uFFFD") }
54
55// SplitCommitMessage turns the raw message of a commit into Commit.Message
56// (valid UTF-8, no trailing line breaks) and Commit.Summary (its first line).
57func SplitCommitMessage(raw string) (message, summary string) {
58 message = strings.TrimRight(ValidGitText(raw), "\n")
59 summary, _, _ = strings.Cut(message, "\n")
60 return message, summary
61}