csvgen

module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2021 License: MIT

README

csvgen

csvgen is a simple code generator for CSV readers that write records directly into structs and not just slices of strings.

Usage

type SomeRecord struct {
    CreatedAt time.Time
    Description string
}

//go:generate csvgen --output gen_somereader.go
type SomeReader struct {
	reader *csv.Reader
}

func (r *SomeReader) parseDate(ctx context.Context, raw string, format string) (time.Time, error) {
    return time.Parse(format, raw)
}

Next, place a csvgen.yml file within the package where you've put the go:generate call.

processors:
  - type: SomeReader
    recordType: SomeRecord
    encoding: Windows1252
    comma: ";"
    fields:
      CreatedAt:
        column: 0
        decoder:
          name: ".parseDate"
          options:
            - "02.01.2006"
      Description:
        column: 1

When you now run go:generate, csvgen will create a gen_somereader.go file in the same directory as the source file which provides a constructor function for the struct as well as a Read and ReadAll function similar to the ones provided by encoding/csv.Reader.

Configuration file

All the configuration what field should be filled based on what column in the CSV file is handled within a configuration file that you can specify when calling csvgen. As you saw in the example above, you specify a list of "processors" that map a record to a reader. For each such mapping you can define a field mapping with each field having a column number (0-indexed) and a decoder.

The decoder's name, if starting with a . is mapped to a method within the processor type, otherwise a function within the module is used.

Why no struct tags?

One alterative for the field format would have been to add all of that to the target record type. The problem with this is that it moves reader knowledge into a pure data object. That being said, we might add support for this in the future.

Directories

Path Synopsis
cmd
internal
pkg

Jump to

Keyboard shortcuts

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