typedcsv

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2023 License: MIT Imports: 8 Imported by: 0

README

typedcsv

This package provides functionality for reading and writing CSV files with structs. It supports multiple tags to customize the behavior of the CSV reader and writer, as well as TextMarshaler/TextUnmarshaler interfaces. Check out documentation of TypedCSVReader/TypedCSVWriter for more information.

Examples

Reading
CSV
name,release_date,repo,stars
rust,2010-07-07,https://github.com/rust-lang/rust,85700
go,2009-11-10,https://github.com/golang/go,115000
ruby,1995-01-01,https://github.com/ruby/ruby,20800
Struct
type ProgrammingLanguage struct {
	Name        string    `csv:"name"`
	ReleaseDate time.Time `csv:"release_date" time_format:"2006-01-02"`
	Repo        string    `csv:"repo"`
	Stars       int       `csv:"stars"`
}
Read
file, err := os.Open("programming_languages.csv")
if err != nil {
    panic(err)
}
defer file.Close()

csvReader := typedcsv.NewReader[ProgrammingLanguage](csv.NewReader(file))
err = csvReader.ReadHeader()
if err != nil {
    panic(err)
}

languages, err := csvReader.ReadAll()
if err != nil {
    panic(err)
}

// languages[0] => ProgrammingLanguage{Name:"rust", ReleaseDate:time.Date(2010, time.July, 7, 0, 0, 0, 0, time.UTC), Repo:"https://github.com/rust-lang/rust", Stars:85700}
// languages[1] => ProgrammingLanguage{Name:"go", ReleaseDate:time.Date(2009, time.November, 10, 0, 0, 0, 0, time.UTC), Repo:"https://github.com/golang/go", Stars:115000}
// languages[2] => ProgrammingLanguage{Name:"ruby", ReleaseDate:time.Date(1995, time.January, 1, 0, 0, 0, 0, time.UTC), Repo:"https://github.com/ruby/ruby", Stars:20800}
Writing
Struct
type ProgrammingLanguage struct {
	Name        string    `csv:"name"`
	ReleaseDate time.Time `csv:"release_date" time_format:"2006-01-02"`
	Repo        string    `csv:"repo"`
	Stars       int       `csv:"stars"`
}
Write
file, err := os.Create("programming_languages.csv")
if err != nil {
    panic(err)
}
defer file.Close()

csvWriter := typedcsv.NewWriter[ProgrammingLanguage](csv.NewWriter(file))
err = csvWriter.WriteHeader()
if err != nil {
    panic(err)
}

languages := []ProgrammingLanguage{
    {Name: "rust", ReleaseDate: time.Date(2010, time.July, 7, 0, 0, 0, 0, time.UTC), Repo: "https://github.com/rust-lang/rust", Stars: 85700},
    {Name: "go", ReleaseDate: time.Date(2009, time.November, 10, 0, 0, 0, 0, time.UTC), Repo: "https://github.com/golang/go", Stars: 115000},
    {Name: "ruby", ReleaseDate: time.Date(1995, time.January, 1, 0, 0, 0, 0, time.UTC), Repo: "https://github.com/ruby/ruby", Stars: 20800},
}

for _, language := range languages {
    err = csvWriter.WriteRecord(language)
    if err != nil {
        panic(err)
    }
}

csvWriter.Flush()
Result (CSV)
name,release_date,repo,stars
rust,2010-07-07,https://github.com/rust-lang/rust,85700
go,2009-11-10,https://github.com/golang/go,115000
ruby,1995-01-01,https://github.com/ruby/ruby,20800

Documentation

Overview

Package typedcsv provides functionality for reading and writing CSV files with structs.

Index

Constants

This section is empty.

Variables

View Source
var ErrHeaderNotRead = errors.New("typedcsv: header not read")

ErrHeaderNotRead is returned when ReadRecord is called before ReadHeader.

Functions

This section is empty.

Types

type FieldFormatError

type FieldFormatError struct {
	Field       string
	NestedError error
}

FieldFormatError is returned when a field cannot be formatted.

func (FieldFormatError) Error

func (e FieldFormatError) Error() string

Error returns the error message.

func (FieldFormatError) Unwrap

func (e FieldFormatError) Unwrap() error

Unwrap returns the nested error.

type FieldParseError

type FieldParseError struct {
	// Field is the name of the field that could not be parsed.
	Field string
	// NestedError is the error returned by the underlying parser.
	NestedError error
}

FieldParseError is returned when a field cannot be parsed.

func (FieldParseError) Error

func (e FieldParseError) Error() string

Error returns the error message.

func (FieldParseError) Unwrap

func (e FieldParseError) Unwrap() error

Unwrap returns the nested error.

type TypedCSVReader

type TypedCSVReader[T any] struct {
	Reader *csv.Reader
	Header map[string]int
}

A TypedCSVReader reads structs from a CSV file.

The struct must have exported fields with a "csv" tag.

  • the "csv" tag value is used as the CSV header.
  • the "null" tag value is used to set the field to nil when the CSV value is equal to the tag value.
  • the "time_format" tag value is used to parse time.Time fields. The value must be a valid time.Time format.
  • the "time_location" tag value is used to set the location of time.Time fields. The value must be a valid time.Location name. Should be used with the "time_format" tag value.
  • the "separator" tag value is used to split slice fields.

If a field implements encoding.TextUnmarshaler, the CSV value is passed to UnmarshalText.

func NewReader

func NewReader[T any](reader *csv.Reader) *TypedCSVReader[T]

NewReader returns a new TypedCSVReader that wraps the given csv.Reader.

func (*TypedCSVReader[T]) ReadAll

func (r *TypedCSVReader[T]) ReadAll() (records []*T, err error)

ReadAll reads all the remaining records from the underlying reader. It returns ErrHeaderNotRead if ReadHeader was not called. It returns a FieldParseError if a field cannot be parsed. Otherwise, it returns any error returned by the underlying reader.

func (*TypedCSVReader[T]) ReadHeader

func (r *TypedCSVReader[T]) ReadHeader() error

ReadHeader reads the CSV header from the underlying reader. It uses the "csv" tag value of the struct fields. It returns io.EOF if there is no header.

func (*TypedCSVReader[T]) ReadRecord

func (r *TypedCSVReader[T]) ReadRecord() (record *T, err error)

ReadRecord reads the CSV record from the underlying reader. It returns ErrHeaderNotRead if ReadHeader was not called. It returns io.EOF if there are no more records. It returns a FieldParseError if a field cannot be parsed. Otherwise, it returns any error returned by the underlying reader.

type TypedCSVWriter

type TypedCSVWriter[T any] struct {
	Writer *csv.Writer
}

A TypedCSVWriter writes structs to a CSV file.

The struct must have exported fields with a "csv" tag.

  • the "csv" tag value is used as the CSV header.
  • the "null" tag value is used as the CSV value when the field is nil.
  • the "format" tag value is used as the CSV value. The format and the field value are passed to fmt.Sprintf.
  • the "time_format" tag value is used to format time.Time fields. The value must be a valid time.Time format.
  • the "time_location" tag value is used to set the location of time.Time fields. The value must be a valid time.Location name. Should be used with the "time_format" tag value.
  • the "separator" tag value is used to join slice fields. Can be used with the "format" tag value.

If a field implements encoding.TextMarshaler, the CSV value is the result of calling MarshalText.

func NewWriter

func NewWriter[T any](writer *csv.Writer) *TypedCSVWriter[T]

NewWriter returns a new TypedCSVWriter that wraps the given csv.Writer.

func (*TypedCSVWriter[T]) Error

func (w *TypedCSVWriter[T]) Error() error

Error reports any error that has occurred during a previous WriteHeader, WriteRecord or Flush.

func (*TypedCSVWriter[T]) Flush

func (w *TypedCSVWriter[T]) Flush()

Flush writes any buffered data to the underlying csv.Writer. To check if an error occurred during the Flush, call Error.

func (*TypedCSVWriter[T]) WriteHeader

func (w *TypedCSVWriter[T]) WriteHeader() error

WriteHeader writes the CSV header to the underlying writer. It uses the "csv" tag value of the struct fields.

func (*TypedCSVWriter[T]) WriteRecord

func (w *TypedCSVWriter[T]) WriteRecord(record T) error

WriteRecord writes the CSV record to the underlying writer. It returns a FieldFormatError if a field cannot be formatted. Otherwise, it returns any error returned by the underlying writer.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL