Skip to content

Commit

Permalink
[csv] Add method 'WithComma' to CSV reader
Browse files Browse the repository at this point in the history
  • Loading branch information
andyone committed Jul 13, 2023
1 parent c7c7bcf commit 4586547
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### 12.69.0

* `[csv]` Added method `WithComma` to CSV reader
* `[spinner]` Added symbols customization
* `[spinner]` Change default skip symbol to check mark
* `[spinner]` Change default skip symbol color to dark grey
Expand Down
13 changes: 13 additions & 0 deletions csv/csv.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,20 @@ func (r *Reader) ReadTo(dst []string) error {
return nil
}

// WithComma sets comma (fields delimiter) for CSV reader
func (r *Reader) WithComma(comma rune) *Reader {
if r == nil {
return nil
}

r.Comma = comma

return r
}

// ////////////////////////////////////////////////////////////////////////////////// //

// parseAndFill parses line
func parseAndFill(src string, dst []string, sep string) {
l := len(dst)

Expand Down Expand Up @@ -116,6 +128,7 @@ func parseAndFill(src string, dst []string, sep string) {
}
}

// clean cleans destination slice
func clean(dst []string, since, to int) {
for i := since; i < to; i++ {
dst[i] = ""
Expand Down
5 changes: 2 additions & 3 deletions csv/csv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,7 @@ func (s *CSVSuite) TestRead(c *C) {

defer fd.Close()

reader := NewReader(fd)
reader.Comma = ','

reader := NewReader(fd).WithComma(',')
count := 0

for {
Expand Down Expand Up @@ -146,6 +144,7 @@ func (s *CSVSuite) TestNil(c *C) {

c.Assert(err, DeepEquals, ErrNilReader)
c.Assert(r.ReadTo(b), DeepEquals, ErrNilReader)
c.Assert(r.WithComma('X'), IsNil)
}

// ////////////////////////////////////////////////////////////////////////////////// //
Expand Down
23 changes: 23 additions & 0 deletions csv/examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,26 @@ func ExampleReader_ReadTo() {
fmt.Printf("%#v\n", data)
}
}

func ExampleReader_WithComma() {
fd, err := os.Open("file.csv")

if err != nil {
fmt.Println(err.Error())
return
}

defer fd.Close()

reader := NewReader(fd).WithComma(',')

for {
data, err := reader.Read()

if err == io.EOF {
break
}

fmt.Printf("%#v\n", data)
}
}

0 comments on commit 4586547

Please sign in to comment.