Files

60 lines
1.1 KiB
Go

package text
import (
"context"
"errors"
"strings"
)
var ErrEmptyInput = errors.New("batch input content cannot be empty")
type Line struct {
RowNo int
Text string
}
type FieldLine struct {
RowNo int
Fields []string
}
func ParseNonEmptyLines(ctx context.Context, input string) ([]Line, error) {
lines := strings.Split(input, "\n")
result := make([]Line, 0, len(lines))
for index, line := range lines {
if err := ctx.Err(); err != nil {
return nil, err
}
value := strings.TrimSpace(line)
if value == "" {
continue
}
result = append(result, Line{
RowNo: index + 1,
Text: value,
})
}
if len(result) == 0 {
return nil, ErrEmptyInput
}
return result, nil
}
func ParseWhitespaceFields(ctx context.Context, input string) ([]FieldLine, error) {
lines, err := ParseNonEmptyLines(ctx, input)
if err != nil {
return nil, err
}
result := make([]FieldLine, 0, len(lines))
for _, line := range lines {
if err = ctx.Err(); err != nil {
return nil, err
}
result = append(result, FieldLine{
RowNo: line.RowNo,
Fields: strings.Fields(line.Text),
})
}
return result, nil
}