csvadapter

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2024 License: MIT Imports: 9 Imported by: 0

README

CSVAdapter

The csvadapter package provides a way to map CSV data into Go structs. This package allows you to easily read CSV files and convert them into a sequence of structs. The package uses struct tags to map CSV columns to struct fields.

Overview

The main component of this package is the CSVAdapter struct. It adapts a struct type to a CSV file by mapping CSV columns to struct fields based on tags defined in the struct.

Installation

To install the package, run:

go get github.com/ic-it/csvadapter

Usage

Defining Structs

To use the CSVAdapter, define your struct with csva tags specifying the CSV column names:

type Person struct {
    Name     string `csva:"name"`
    Age      int    `csva:"alias=age"`
    Email    string `csva:"email,omitempty"` // `omitempty` allows the field to be empty
    SomeDataToIgnore string `csva:"-"`
}
Creating a CSVAdapter

Create a new CSVAdapter for your struct type:

adapter, err := NewCSVAdapter[Person]()
if err != nil {
    log.Fatalf("failed to create CSVAdapter: %v", err)
}
Options

The NewCSVAdapter function supports the following options:

  • Comma(r rune): Sets the field separator. (default: ,) (more info and more info)
  • Comment(r rune): Sets the comment character. (more info)
  • LazyQuotes(lazyQuotes bool): Sets the lazy quotes flag. (more info)
  • TrimLeadingSpace(trimLeadingSpace bool): Sets the trim leading space flag. (more info)
  • ReuseRecord(reuseRecord bool): Sets the reuse record flag. (more info)
  • UseCRLF(useCRLF bool): Sets the use CRLF flag. (more info)
  • WriteHeader(writeHeader bool): Sets the write header flag. When set to true, the header will be written when calling ToCSV.
  • NoImplicitAlias(noImplicitAlias bool): Sets the no implicit alias flag. When set to true, field names will not be used as aliases when not specified.
Reading a CSV File

To read a CSV file and populate a slice of structs:

file, err := os.Open("data.csv")
if err != nil {
    log.Fatalf("failed to open file: %v", err)
}
defer file.Close()


people, err := adapter.FromCSV(reader)
if err != nil {
    log.Fatalf("failed to read CSV: %v", err)
}

for person, err := range people {
    if err != nil {
        log.Fatalf("failed to read person: %v", err)
    }
    fmt.Printf("Person: %+v\n", person)
}
Writing a CSV File

To write a slice of structs to a CSV file:

file, err := os.Create("data.csv")
if err != nil {
    log.Fatalf("failed to create file: %v", err)
}
defer file.Close()

people := []Person{
    {Name: "Alice", Age: 30, Email: "testme@gmail.com"},
    {Name: "Bob", Age: 25, Email: "testmes2@gmail.com"},
}

if err := adapter.ToCSV(file, slices.Values(people)); err != nil {
    log.Fatalf("failed to write CSV: %v", err)
}

fmt.Println("CSV written successfully")

CSVAdapter Type

The CSVAdapter type is a generic struct that adapts a Go struct to a CSV file:

Allowed Types

The CSVAdapter supports the following types:

  • string
  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64
  • bool
  • Any type that implements the encoding.TextUnmarshaler interface

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Code generated by Taskfile; DO NOT EDIT.

Index

Constants

View Source
const Version = "v0.1.2"

Variables

View Source
var (
	ErrUnsupportedTag      = fmt.Errorf("unsupported tag")
	ErrInvalidTag          = fmt.Errorf("invalid tag")
	ErrorNotStruct         = fmt.Errorf("not a struct")
	ErrReadingCSV          = fmt.Errorf("error reading csv")
	ErrReadingCSVLines     = fmt.Errorf("error reading csv lines")
	ErrProcessingCSVLines  = fmt.Errorf("error processing csv lines")
	ErrFieldNotFound       = fmt.Errorf("field not found in csv")
	ErrUnprocessableType   = fmt.Errorf("unprocessable type")
	ErrParsingType         = fmt.Errorf("error parsing type")
	ErrEmptyValue          = fmt.Errorf("empty value")
	ErrAliasNotFound       = fmt.Errorf("alias not found")
	ErrWrongNumberOfFields = fmt.Errorf("wrong number of fields")
)

Errors

Functions

func Comma

func Comma(r rune) csvAdapterOption

Comma sets the field separator

more info: https://pkg.go.dev/encoding/csv#Reader and https://pkg.go.dev/encoding/csv#Writer

func Comment

func Comment(r rune) csvAdapterOption

Comment sets the comment character

more info: https://pkg.go.dev/encoding/csv#Reader

func LazyQuotes

func LazyQuotes(lazyQuotes bool) csvAdapterOption

LazyQuotes sets the lazy quotes flag

more info: https://pkg.go.dev/encoding/csv#Reader

func NoImplicitAlias

func NoImplicitAlias(noImplicitAlias bool) csvAdapterOption

sets the no implicit alias flag

when set to true, field names will not be used as aliases when not specified.

func ReuseRecord

func ReuseRecord(reuseRecord bool) csvAdapterOption

ReuseRecord sets the reuse record flag

more info: https://pkg.go.dev/encoding/csv#Reader

func TrimLeadingSpace

func TrimLeadingSpace(trimLeadingSpace bool) csvAdapterOption

TrimLeadingSpace sets the trim leading space flag

more info: https://pkg.go.dev/encoding/csv#Reader

func UseCRLF

func UseCRLF(useCRLF bool) csvAdapterOption

sets the use CRLF flag.

more info: https://pkg.go.dev/encoding/csv#Writer

func WriteHeader

func WriteHeader(writeHeader bool) csvAdapterOption

sets the write header flag

when set to true, the header will be written when calling ToCSV

Types

type CSVAdapter

type CSVAdapter[T any] struct {
	// contains filtered or unexported fields
}

CSVAdapter is a struct that adapts a struct to a csv file

func NewCSVAdapter

func NewCSVAdapter[T any](options ...csvAdapterOption) (*CSVAdapter[T], error)

NewCSVAdapter creates a new CSVAdapter

func (*CSVAdapter[T]) FromCSV

func (c *CSVAdapter[T]) FromCSV(reader io.Reader) (iter.Seq2[T, error], error)

FromCSV reads a csv file and fills a slice of structs

func (CSVAdapter[T]) String

func (c CSVAdapter[T]) String() string

func (*CSVAdapter[T]) ToCSV

func (c *CSVAdapter[T]) ToCSV(writer io.Writer, data iter.Seq[T]) error

ToCSV writes a slice of structs to a csv file

type ReadingError

type ReadingError struct {
	Line       int
	Field      string
	FieldAlias string
}

func (ReadingError) Error

func (r ReadingError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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