Documentation
¶
Overview ¶
Package wildcsv reads delimited text that the calling program did not produce: a customer upload, a spreadsheet export, a bank statement, a file handed to a coding agent.
It answers three questions about bytes of unknown origin:
- Is this delimited text at all, or a workbook, an archive, JSON, a PDF? Detect reports the Kind.
- Which encoding and which dialect does it use, and how sure is that answer? Detect reports the Encoding, the Dialect, a confidence margin and the runner-up dialects.
- What are its records, and where exactly is each problem? NewReader returns a Reader that streams records under explicit Limits and reports every problem as a *ParseError with its record, line, column and byte offset.
Detection examines a sample of fixed size, reading holds at most one record, and every field and record has a size limit, so no input makes memory grow without limit. The same bytes and options always give the same answer.
The package depends only on the standard library. Its contract, including the detection method and the reading rules, is in docs/design.md.
Index ¶
- Constants
- Variables
- type Alternative
- type Column
- type Detection
- type Dialect
- type Encoding
- type EncodingError
- type HeaderGuess
- type Kind
- type KindError
- type Limits
- type Options
- type ParseError
- type Reader
- func (r *Reader) All() iter.Seq2[[]string, error]
- func (r *Reader) Close() error
- func (r *Reader) Detection() *Detection
- func (r *Reader) FieldPos(field int) (line, column int)
- func (r *Reader) InputOffset() int64
- func (r *Reader) Read() ([]string, error)
- func (r *Reader) ReadSlices() ([][]byte, error)
- func (r *Reader) Stats() Stats
- type Stats
- type ValueKind
Examples ¶
Constants ¶
const ( BasisDeclared = "declared" // Options.Encoding BasisCustom = "custom" // Options.Decode BasisBOM = "bom" // a byte order mark BasisUTF16Pattern = "utf16-pattern" // zero bytes at alternate offsets BasisASCII = "ascii" // the sample is ASCII; decided at the first byte that is not BasisUTF8 = "utf8" // the sample is valid UTF-8 BasisFallback = "fallback" // nothing else fits: Windows-1252 )
The basis of an encoding decision, as reported in Detection.EncodingBasis.
const ( DefaultSampleBytes = 64 << 10 DefaultMaxFieldBytes = 1 << 20 DefaultMaxRecordBytes = 4 << 20 DefaultMaxFields = 16384 )
Default limits. A zero field in Limits selects the default.
Variables ¶
var ( ErrBareQuote = errors.New("quote character in an unquoted field") ErrStrayQuote = errors.New("quote character inside a quoted field that neither doubles nor closes it") ErrInvalidUTF8 = errors.New("invalid UTF-8") ErrUnterminatedQuote = errors.New("quoted field not closed before the end of the input") ErrFieldTooLarge = errors.New("field exceeds MaxFieldBytes") ErrRecordTooLarge = errors.New("record exceeds MaxRecordBytes") ErrTooManyFields = errors.New("record exceeds MaxFields") )
Errors wrapped by *ParseError. The first three are accepted as data when reading leniently and are errors only with Options.Strict.
var ( ErrNotDelimited = errors.New("input is not delimited text") ErrUnsupportedEncoding = errors.New("unsupported encoding") ErrInvalidOptions = errors.New("invalid options") )
Errors wrapped by the other error types, and the error for invalid options.
var ErrClosed = errors.New("wildcsv: Reader closed")
ErrClosed is returned by the read methods of a Reader after Close.
Functions ¶
This section is empty.
Types ¶
type Alternative ¶
type Alternative struct {
Dialect Dialect
RelativeScore float64 // its score divided by the winner's
}
Alternative is a runner-up dialect.
type Column ¶
type Column struct {
Name string // the first record's cell, when the header is present
Kind ValueKind // the kind of most of its values
DecimalComma bool // numbers in it use a comma as decimal separator
}
Column describes one column of the sample.
type Detection ¶
type Detection struct {
Kind Kind
Encoding Encoding
EncodingBasis string // how the encoding was decided; one of the Basis constants
BOM bool // a byte order mark was found and removed
Dialect Dialect
LineEnding string // lf, crlf, cr, mixed, or none
Confidence float64 // margin over the best dialect with another delimiter: 0 to 1
Alternatives []Alternative // up to three runner-up dialects
Header HeaderGuess
Columns []Column
SampleBytes int // bytes examined
SampleRecords int // records of the sample the report rests on
Complete bool // the sample is the whole input
}
Detection reports what a sample of the input is and how to read it.
func Detect ¶
Detect reads a sample of r and reports its kind, encoding and dialect, the header guess and the kind of each column. It reads at most Limits.SampleBytes + 1 bytes.
It returns a report for every kind, and an error only when reading fails, the options are invalid or the encoding is not supported.
Example ¶
package main
import (
"fmt"
"log"
"strings"
"github.com/Altitud-Studio-S-L-U/wildcsv"
)
func main() {
det, err := wildcsv.Detect(strings.NewReader("date|total\n2026-01-05|3.5\n2026-01-06|4\n"), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(det.Kind, det.Dialect, det.Header)
for _, c := range det.Columns {
fmt.Println(c.Name, c.Kind)
}
}
Output: delimited delimiter '|' quote '"' present date date total number
type Dialect ¶
type Dialect struct {
Delimiter rune // separates fields
Quote rune // surrounds a field that contains delimiters or line breaks; 0 when fields are never quoted
Escape rune // inside a quoted field, makes the next quote or escape character literal; 0 when unused
SkipInitialSpace bool // spaces after a delimiter are padding, not data
}
Dialect says how a delimited text separates fields and quotes them.
Records end at a line feed, at a carriage return followed by a line feed, or at a lone carriage return; all three are accepted in the same input.
type Encoding ¶
type Encoding string
Encoding names a character encoding. Its value is the name used in reports.
type EncodingError ¶
type EncodingError struct {
Encoding string
}
EncodingError is returned for an encoding that wildcsv recognises but does not read, such as UTF-32.
func (*EncodingError) Error ¶
func (e *EncodingError) Error() string
func (*EncodingError) Unwrap ¶
func (e *EncodingError) Unwrap() error
type HeaderGuess ¶
type HeaderGuess string
HeaderGuess says whether the first record looks like a header.
const ( HeaderUnknown HeaderGuess = "unknown" HeaderPresent HeaderGuess = "present" HeaderAbsent HeaderGuess = "absent" )
A table made only of text gives no evidence either way, so the guess has three values. The reader never drops the first record on its own.
type Kind ¶
type Kind string
Kind says what an input looks like. Only delimited and empty inputs can be read.
const ( KindEmpty Kind = "empty" KindDelimited Kind = "delimited" KindXLSX Kind = "xlsx" KindODS Kind = "ods" KindZIP Kind = "zip" KindXLS Kind = "xls" KindGzip Kind = "gzip" KindBzip2 Kind = "bzip2" KindXZ Kind = "xz" KindZstd Kind = "zstd" KindPDF Kind = "pdf" KindParquet Kind = "parquet" KindBinary Kind = "binary" KindHTML Kind = "html" KindXML Kind = "xml" KindJSONL Kind = "jsonl" KindJSON Kind = "json" )
Kinds that Detect recognises.
type KindError ¶
type KindError struct {
Kind Kind
}
KindError is returned by NewReader for input that is not delimited text.
Example ¶
A file that is not delimited text is named, not misread.
package main
import (
"errors"
"fmt"
"strings"
"github.com/Altitud-Studio-S-L-U/wildcsv"
)
func main() {
_, err := wildcsv.NewReader(strings.NewReader(`{"id": 1}`+"\n"+`{"id": 2}`+"\n"), nil)
var ke *wildcsv.KindError
if errors.As(err, &ke) {
fmt.Println("not delimited text:", ke.Kind)
}
}
Output: not delimited text: jsonl
type Limits ¶
type Limits struct {
SampleBytes int // bytes examined by detection
MaxFieldBytes int // bytes of one field's content
MaxRecordBytes int // bytes of one record in the input, with its quotes and delimiters
MaxFields int // fields in one record
}
Limits bounds what detection examines and what one record may hold.
type Options ¶
type Options struct {
Dialect *Dialect // use this dialect; do not detect one
Delimiters []rune // candidate delimiters for detection
Quotes []rune // candidate quotes for detection; 0 stands for no quoting
Encoding Encoding // use this encoding; do not detect one
Decode func(io.Reader) io.Reader // convert the source to UTF-8; wildcsv then does no decoding of its own
SkipLines int // lines to discard before the table
Strict bool // report quoting defects and invalid UTF-8 as errors
Warn func(*ParseError) // called for each defect that lenient reading accepts
ReuseRecord bool // Read may return a slice that shares its backing array with the previous one
Concurrency int // goroutines that read the text: 0 adapts, 1 is sequential; see Reader
Limits Limits
}
Options controls detection and reading. A nil *Options and a zero Options both mean: detect everything, read leniently, default limits.
Example (Decode) ¶
Options.Decode accepts any decoder to UTF-8, such as one from golang.org/x/text; this one upper-cases ASCII to stand in for it.
package main
import (
"fmt"
"io"
"log"
"strings"
"github.com/Altitud-Studio-S-L-U/wildcsv"
)
func main() {
upper := func(r io.Reader) io.Reader {
b, _ := io.ReadAll(r)
return strings.NewReader(strings.ToUpper(string(b)))
}
r, err := wildcsv.NewReader(strings.NewReader("a;b\nc;d\n"), &wildcsv.Options{Decode: upper})
if err != nil {
log.Fatal(err)
}
rec, _ := r.Read()
fmt.Println(rec, r.Detection().Encoding)
}
Output: [A B] custom
Example (Warn) ¶
Lenient reading keeps going through defects and reports each of them.
package main
import (
"fmt"
"log"
"strings"
"github.com/Altitud-Studio-S-L-U/wildcsv"
)
func main() {
in := `id,comment` + "\n" + `1,"He said "hi" to me, twice"` + "\n"
opts := &wildcsv.Options{Warn: func(e *wildcsv.ParseError) {
fmt.Printf("warning: line %d, column %d: %v\n", e.Line, e.Column, e.Err)
}}
r, err := wildcsv.NewReader(strings.NewReader(in), opts)
if err != nil {
log.Fatal(err)
}
for rec, err := range r.All() {
if err == nil {
fmt.Println(rec[1])
}
}
}
Output: comment warning: line 2, column 12: quote character inside a quoted field that neither doubles nor closes it warning: line 2, column 15: quote character inside a quoted field that neither doubles nor closes it He said "hi" to me, twice
type ParseError ¶
type ParseError struct {
Record int // 1-based number of the record being read
Line int // 1-based line of the position
Column int // 1-based byte index in that line
Offset int64 // 0-based byte offset in the text
Quoted bool // the position is inside a quoted field, or is its opening quote
Err error // one of ErrBareQuote, ErrStrayQuote, ErrInvalidUTF8, ErrUnterminatedQuote, ErrFieldTooLarge, ErrRecordTooLarge, ErrTooManyFields
}
ParseError reports a problem in the data and where it is.
Lines count every line break, including those inside quoted fields and blank lines. Columns and offsets count bytes of the UTF-8 text after decoding and after a byte order mark is removed.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
func (*ParseError) Unwrap ¶
func (e *ParseError) Unwrap() error
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader streams the records of delimited text.
Options.Concurrency sets how many goroutines read it. With 1, the goroutine that calls Read does. With n above 1, a producer goroutine reads the underlying reader and cuts the text into chunks, n goroutines read the chunks, and Read returns their records in order. With 0, the default, the calling goroutine reads the first 128 KiB and, if the input goes on, hands over to min(GOMAXPROCS, 8) goroutines. Whatever the setting, the records, errors, warnings and their order, counts, positions and offsets are the same, and Options.Warn is called from the goroutine that calls Read. A parallel Reader stops its goroutines at the end of the input, on an error that ends it, on Close, or once it is unreachable.
A Reader is not safe for concurrent use. Readers do not share state.
func NewReader ¶
NewReader detects the kind, encoding and dialect of r from a sample, then returns a Reader that streams the records of the whole input. The sample is read once; r need not be seekable.
It returns a *KindError when the input is not delimited text, unless Options.Dialect declares the dialect. An empty input gives a Reader whose first Read returns io.EOF.
Example ¶
A spreadsheet export with semicolons, decimal commas and a Windows-1252 accented letter is read without saying any of that.
package main
import (
"fmt"
"io"
"log"
"strings"
"github.com/Altitud-Studio-S-L-U/wildcsv"
)
func main() {
export := "id;name;amount\r\n1;Jos\xe9;12,50\r\n2;Ana;7,00\r\n"
r, err := wildcsv.NewReader(strings.NewReader(export), nil)
if err != nil {
log.Fatal(err)
}
det := r.Detection()
fmt.Printf("delimiter %q, encoding %s, header %s\n", det.Dialect.Delimiter, det.Encoding, det.Header)
for {
rec, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Println(strings.Join(rec, " | "))
}
}
Output: delimiter ';', encoding windows-1252, header present id | name | amount 1 | José | 12,50 2 | Ana | 7,00
func (*Reader) All ¶
All yields each record or error in turn. It stops at the end of the input or after an error that is not a *ParseError.
Example ¶
Every problem carries its position, and the reader goes on with the next line, so one pass lists all of them.
package main
import (
"errors"
"fmt"
"log"
"strings"
"github.com/Altitud-Studio-S-L-U/wildcsv"
)
func main() {
in := "a,b\n1,2,3\n\"open,4\n"
r, err := wildcsv.NewReader(strings.NewReader(in), &wildcsv.Options{
Dialect: &wildcsv.Dialect{Delimiter: ',', Quote: '"'},
Limits: wildcsv.Limits{MaxFields: 2},
})
if err != nil {
log.Fatal(err)
}
for rec, err := range r.All() {
var pe *wildcsv.ParseError
if errors.As(err, &pe) {
fmt.Printf("line %d, column %d: %v\n", pe.Line, pe.Column, pe.Err)
continue
}
fmt.Println(rec)
}
}
Output: [a b] line 2, column 5: record exceeds MaxFields line 3, column 1: quoted field not closed before the end of the input
func (*Reader) Close ¶
Close stops the goroutines of a Reader whose Options.Concurrency is above one; for other Readers it only marks them closed. Reading to io.EOF, or to an error that is not a *ParseError, stops the goroutines as well, and so does the garbage collector once the Reader is unreachable. After Close the read methods return ErrClosed, or the error that ended the input if one had. A producer blocked in a Read of the underlying reader stops when that Read returns. Close does not close the underlying reader, and always returns nil.
func (*Reader) Detection ¶
Detection returns the report of the sample the Reader was built from.
With Options.Dialect declared, the header guess and the columns are worked out on the first call, so a Reader that never asks does not pay for them.
func (*Reader) FieldPos ¶
FieldPos returns the line and byte column where the given field of the record last returned starts; for a quoted field, its opening quote. It panics if field is out of range.
func (*Reader) InputOffset ¶
InputOffset returns the byte offset in the text just after the record last returned, including its line break.
func (*Reader) Read ¶
Read returns the next record. It returns io.EOF at the end of the input and a *ParseError for a problem in the data, after which it can be called again. Errors from the underlying reader are returned as they are.
Unless Options.ReuseRecord is set, each call returns a new slice.
func (*Reader) ReadSlices ¶
ReadSlices is Read without copies: like the line bufio.Reader.ReadSlice returns, the fields point into the Reader's buffers and are valid only until the next call to a read method, and the slice holding them is reused. Once the Reader has warmed up it allocates nothing, which makes it the fastest way to read when each field is parsed or copied right away.
Example ¶
ReadSlices hands out the fields without copying them, for code that parses or copies each field right away, such as this sum of amounts.
package main
import (
"fmt"
"io"
"log"
"strconv"
"strings"
"github.com/Altitud-Studio-S-L-U/wildcsv"
)
func main() {
data := "sku,amount\nA1,12.50\nB2,7.25\nC3,0.25\n"
r, err := wildcsv.NewReader(strings.NewReader(data), nil)
if err != nil {
log.Fatal(err)
}
if _, err := r.ReadSlices(); err != nil { // the header
log.Fatal(err)
}
total := 0.0
for {
fields, err := r.ReadSlices()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
// fields[1] is valid only until the next call, so it is used now.
v, err := strconv.ParseFloat(string(fields[1]), 64)
if err != nil {
log.Fatal(err)
}
total += v
}
fmt.Printf("%.2f\n", total)
}
Output: 20.00
type Stats ¶
type Stats struct {
Records int64 // records returned
BareQuotes int64 // quote characters read as data in unquoted fields
StrayQuotes int64 // quote characters read as data inside quoted fields
InvalidUTF8 int64 // invalid sequences replaced with U+FFFD
Encoding Encoding // the encoding finally used
}
Stats counts what a Reader has read and the defects it accepted.
type ValueKind ¶
type ValueKind string
ValueKind is the kind of value a cell or a column holds.
const ( ValueEmpty ValueKind = "empty" ValueNull ValueKind = "null" ValueBoolean ValueKind = "boolean" ValueInteger ValueKind = "integer" ValueNumber ValueKind = "number" ValuePercent ValueKind = "percent" ValueCurrency ValueKind = "currency" ValueDate ValueKind = "date" ValueTime ValueKind = "time" ValueDateTime ValueKind = "datetime" ValueURL ValueKind = "url" ValueEmail ValueKind = "email" ValueIPv4 ValueKind = "ipv4" ValueUUID ValueKind = "uuid" ValuePath ValueKind = "path" ValueText ValueKind = "text" ValueOther ValueKind = "other" )
Value kinds, in the order the classifier tests them (design §7.3).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
wildcsv
command
Command wildcsv tells what a tabular text file is and how to read it, lists every problem in it with its position, and rewrites it as RFC 4180 CSV in UTF-8.
|
Command wildcsv tells what a tabular text file is and how to read it, lists every problem in it with its position, and rewrites it as RFC 4180 CSV in UTF-8. |
|
internal
|
|
|
accuracy
Package accuracy measures dialect detection on the public benchmark sets that other tools publish results for: POLLOCK, the W3C CSV on the Web test files and the CSV Wrangling files, with the annotations and the pass rule of García's CSVsniffer benchmark.
|
Package accuracy measures dialect detection on the public benchmark sets that other tools publish results for: POLLOCK, the W3C CSV on the Web test files and the CSV Wrangling files, with the annotations and the pass rule of García's CSVsniffer benchmark. |
|
cmd/accuracy
command
Command accuracy fetches the public benchmark sets and measures dialect detection on them.
|
Command accuracy fetches the public benchmark sets and measures dialect detection on them. |
|
cmd/release
command
Command release builds the release archives of the wildcsv command, their checksums, the Homebrew and Scoop manifests and the release notes.
|
Command release builds the release archives of the wildcsv command, their checksums, the Homebrew and Scoop manifests and the release notes. |