Debian Codegraph @

internal/magic/text_csv.go

raw symbols SCIP
1 package magic
2
3 import (
4 "github.com/gabriel-vasile/mimetype/internal/csv"
5 "github.com/gabriel-vasile/mimetype/internal/scan"
6 )
7
8 // CSV matches a comma-separated values file.
9 func CSV(raw []byte, limit uint32) bool {
10 return sv(raw, ',', limit)
11 }
12
13 // TSV matches a tab-separated values file.
14 func TSV(raw []byte, limit uint32) bool {
15 return sv(raw, '\t', limit)
16 }
17
18 func sv(in []byte, comma byte, limit uint32) bool {
19 s := scan.Bytes(in)
20 r := csv.NewParser(comma, '#', &s)
21
22 headerFields, _, hasMore := r.CountFields(false)
23 if headerFields < 2 || !hasMore {
24 return false
25 }
26 csvLines := 1 // 1 for header
27 for {
28 fields, _, hasMore := r.CountFields(false)
29 if !hasMore && fields == 0 {
30 break
31 }
32 if fields == headerFields {
33 csvLines++
34 } else {
35 // maybeTruncated signals the input was cut at the read limit,
36 // meaning the last line may be an incomplete CSV record.
37 maybeTruncated := limit > 0 && uint64(len(in)) >= uint64(limit)
38 if maybeTruncated && fields < headerFields {
39 // Allow the last row to have any number of fields
40 // if the input is maybeTruncated.
41 // BUG: if len(input) == limit, then the input is not truncated
42 // but it is still allowed to have the wrong number of fields
43 // and it will be reported as valid CSV.
44 if len(s) == 0 {
45 break
46 }
47 }
48 return false
49 }
50 if csvLines >= 10 {
51 return true
52 }
53 }
54
55 return csvLines >= 2
56 }