@@ -66,6 +66,43 @@ func Parse(conf cfg.Config, input io.Reader) (Tabdata, error) {
6666 return data , err
6767}
6868
69+ /*
70+ * Setup headers, given headers might be usable headers or just the
71+ * first row, which we use to determine how many headers to generate,
72+ * if enabled.
73+ */
74+ func SetHeaders (conf cfg.Config , headers []string ) []string {
75+ if ! conf .AutoHeaders && len (conf .CustomHeaders ) == 0 {
76+ return headers
77+ }
78+
79+ if conf .AutoHeaders {
80+ heads := make ([]string , len (headers ))
81+ for idx := range headers {
82+ heads [idx ] = fmt .Sprintf ("%d" , idx + 1 )
83+ }
84+
85+ return heads
86+ }
87+
88+ if len (conf .CustomHeaders ) == len (headers ) {
89+ return conf .CustomHeaders
90+ }
91+
92+ // use as much custom ones we have, generate the remainder
93+ heads := make ([]string , len (headers ))
94+
95+ for idx := range headers {
96+ if idx < len (conf .CustomHeaders ) {
97+ heads [idx ] = conf .CustomHeaders [idx ]
98+ } else {
99+ heads [idx ] = fmt .Sprintf ("%d" , idx + 1 )
100+ }
101+ }
102+
103+ return heads
104+ }
105+
69106/*
70107Parse CSV input.
71108*/
@@ -87,7 +124,7 @@ func parseCSV(conf cfg.Config, input io.Reader) (Tabdata, error) {
87124 }
88125
89126 if len (records ) >= 1 {
90- data .headers = records [0 ]
127+ data .headers = SetHeaders ( conf , records [0 ])
91128 data .columns = len (records )
92129
93130 for _ , head := range data .headers {
@@ -98,9 +135,14 @@ func parseCSV(conf cfg.Config, input io.Reader) (Tabdata, error) {
98135 }
99136 }
100137
101- if len (records ) > 1 {
102- data .entries = records [1 :]
138+ if len (records ) >= 1 {
139+ if conf .AutoHeaders || len (conf .CustomHeaders ) > 0 {
140+ data .entries = records
141+ } else {
142+ data .entries = records [1 :]
143+ }
103144 }
145+
104146 }
105147
106148 return data , nil
@@ -128,19 +170,32 @@ func parseTabular(conf cfg.Config, input io.Reader) (Tabdata, error) {
128170 data .columns = len (parts )
129171
130172 // process all header fields
131- for _ , part := range parts {
173+ firstrow := make ([]string , len (parts ))
174+
175+ for idx , part := range parts {
132176 // register widest header field
133177 headerlen := len (part )
134178 if headerlen > data .maxwidthHeader {
135179 data .maxwidthHeader = headerlen
136180 }
137181
138182 // register fields data
139- data . headers = append ( data . headers , strings .TrimSpace (part ) )
183+ firstrow [ idx ] = strings .TrimSpace (part )
140184
141185 // done
142186 hadFirst = true
143187 }
188+
189+ data .headers = SetHeaders (conf , firstrow )
190+
191+ if conf .AutoHeaders || len (conf .CustomHeaders ) > 0 {
192+ // we do not use generated headers, consider as row
193+ if matchPattern (conf , line ) == conf .InvertMatch {
194+ continue
195+ }
196+
197+ data .entries = append (data .entries , firstrow )
198+ }
144199 } else {
145200 // data processing
146201 if matchPattern (conf , line ) == conf .InvertMatch {
0 commit comments