2 * A Swiss-Army Knife for CSV-like Files
4 * (c) 2012 Martin Mares <mj@ucw.cz>
17 /*** Memory allocation ***/
19 static void *xmalloc(size_t bytes)
21 void *p = malloc(bytes);
23 fprintf(stderr, "xsv: Out of memory (cannot allocate %zu bytes)\n", bytes);
29 static void *xmalloc_zero(size_t bytes)
31 void *p = xmalloc(bytes);
36 static void *xrealloc(void *old, size_t bytes)
38 void *p = realloc(old, bytes);
40 fprintf(stderr, "xsv: Out of memory (cannot allocate %zu bytes)\n", bytes);
46 #define DECLARE_BUF(name, type) \
47 typedef struct { type *start; int count; int max; } name##_t; \
48 static inline void name##_init(name##_t *b) { b->start = NULL; b->count = b->max = 0; } \
49 static inline void name##_reset(name##_t *b) { b->count = 0; } \
50 static inline int name##_count(name##_t *b) { return b->count; } \
51 static void name##_extend(name##_t *b) { \
52 b->max = b->max ? 2*b->max : 16; \
53 b->start = xrealloc(b->start, b->max * sizeof(type)); \
55 static inline type *name##_push(name##_t *b) { \
56 if (b->count >= b->max) name##_extend(b); \
57 return &b->start[b->count++]; \
59 static inline type *name##_first(name##_t *b) { return b->start; } \
60 static inline type *name##_nth(name##_t *b, int n) { return &b->start[n]; } \
63 DECLARE_BUF(intarray, int);
65 /*** Formats and their parameters ***/
82 int (*read_line)(void);
83 void (*write_line)(void);
94 pcre_extra *pcre_extra;
96 // Temporary file backend:
98 intarray_t column_widths;
104 static struct format *in_format, *out_format;
105 static int want_trim;
112 DECLARE_BUF(fields, struct field);
113 DECLARE_BUF(line, unsigned char);
115 static fields_t in_fields, out_fields;
116 static struct field *in_field;
117 static line_t in_line;
118 static int line_number;
120 static void new_field(int pos)
122 in_field = fields_push(&in_fields);
123 in_field->start_pos = pos;
127 static void ensure_field(int pos)
133 static void warn(struct format *fmt, char *msg, ...)
136 fprintf(stderr, "Warning at line %d: ", line_number);
139 vfprintf(stderr, msg, args);
145 static int next_line(void)
152 return !!line_count(&in_line);
155 *line_push(&in_line) = c;
159 static int field_chars(struct field *f)
161 unsigned char *s = line_nth(&in_line, f->start_pos);
164 memset(&mbs, 0, sizeof(mbs));
168 size_t k = mbrlen((char *) s + i, f->len - i, &mbs);
178 /*** CSV/TSV back-end */
180 static int csv_read(void)
185 int i = line_count(&in_line);
189 if (c < 0 || c == '\n') {
191 warn(in_format, "Missing closing quote.");
193 return !!fields_count(&in_fields);
198 if (c == in_format->quote) {
200 if (c != in_format->quote) {
204 // Two quotes assimilate to one
206 // Fall through to pushing the character
207 } else if (c == in_format->quote) {
210 } else if (c == in_format->fs && !quoted) {
216 *line_push(&in_line) = c;
221 static int is_ws(int c)
223 return (c == ' ' || c == '\t' || c == '\f');
226 static void csv_write(void)
228 unsigned char *line = line_first(&in_line);
229 int n = fields_count(&out_fields);
230 for (int i=0; i<n; i++) {
231 struct field *f = fields_nth(&out_fields, i);
233 if (out_format->quote >= 0) {
234 need_quotes = out_format->always_quote;
235 for (int j=0; !need_quotes && j < f->len; j++) {
236 int c = line[f->start_pos + j];
237 if (c == out_format->fs || c == out_format->quote)
242 putchar(out_format->fs);
244 putchar(out_format->quote);
245 for (int j=0; j < f->len; j++) {
246 int c = line[f->start_pos + j];
247 if (c == out_format->fs && !need_quotes)
248 warn(out_format, "Field separator found inside field and quoting is turned off.");
249 if (c == out_format->quote)
254 putchar(out_format->quote);
259 /*** White-space back-end ***/
261 static int ws_read(void)
266 unsigned char *line = line_first(&in_line);
267 int n = line_count(&in_line);
273 for (int i=0; i<n; i++) {
279 if (!in_field->start_pos &&
281 !in_format->strict_ws)
282 in_field->start_pos = i;
291 if (ws && in_format->strict_ws)
296 /*** Regex back-end ***/
298 static const char *regex_set(struct format *f, char *rx)
302 f->pcre = pcre_compile(rx, PCRE_DOLLAR_ENDONLY, &err, &errpos, NULL);
306 f->pcre_extra = pcre_study(f->pcre, 0, &err);
313 static int regex_read(void)
318 unsigned char *c = line_first(&in_line);
319 int n = line_count(&in_line);
326 int sep = pcre_exec(in_format->pcre, in_format->pcre_extra, (char *) c, n, i, 0, ovec, 3);
328 if (sep != PCRE_ERROR_NOMATCH)
329 warn(in_format, "PCRE matching error %d", sep);
330 // No further occurrence of the separator: the rest is a single field
332 in_field->len = n - i;
336 in_field->len = ovec[0] - i;
341 /*** Table back-end ***/
343 static void table_write(void)
345 for (int i = 0; i < fields_count(&in_fields); i++) {
347 printf("%*s", out_format->table_sep, "");
348 struct field *f = fields_nth(&in_fields, i);
349 int fw = field_chars(f);
350 int cw = *intarray_nth(&in_format->column_widths, i);
352 warn(out_format, "Internal error: Wrongly calculated column width (%d > %d)", fw, cw);
355 unsigned char *p = line_nth(&in_line, f->start_pos);
356 for (int j = 0; j < f->len; j++)
366 /*** Temporary file back-end ***/
368 static int tmp_read(void)
370 FILE *tf = in_format->tmp_file;
380 c = (c << 8) | fgetc(tf);
381 c = (c << 8) | fgetc(tf);
382 c = (c << 8) | fgetc(tf);
384 new_field(line_count(&in_line));
389 warn(in_format, "Truncated temporary file");
392 *line_push(&in_line) = x;
397 static void tmp_write(void)
399 FILE *tf = out_format->tmp_file;
401 for (int i = 0; i < fields_count(&in_fields); i++) {
402 struct field *f = fields_nth(&in_fields, i);
407 fputc((f->len >> 24) & 0xff, tf);
408 fputc((f->len >> 16) & 0xff, tf);
409 fputc((f->len >> 8) & 0xff, tf);
410 fputc(f->len & 0xff, tf);
413 unsigned char *p = line_nth(&in_line, f->start_pos);
414 for (int j = 0; j < f->len; j++)
417 intarray_t *w = &out_format->column_widths;
418 while (i >= intarray_count(w))
419 *intarray_push(w) = 0;
420 int fw = field_chars(f);
421 if (*intarray_nth(w, i) < fw)
422 *intarray_nth(w, i) = fw;
429 static void trim_fields(void)
431 unsigned char *line = line_first(&in_line);
432 for (int i = 0; i < fields_count(&in_fields); i++) {
433 struct field *f = fields_nth(&in_fields, i);
434 while (f->len && is_ws(line[f->start_pos]))
435 f->start_pos++, f->len--;
436 while (f->len && is_ws(line[f->start_pos + f->len - 1]))
441 /*** Field selection ***/
444 int first_field, last_field;
447 DECLARE_BUF(selectors, struct selector);
448 static selectors_t selectors;
450 static char *parse_selector(char *str)
452 char buf[strlen(str) + 1];
455 struct selector *s = selectors_push(&selectors);
456 char *sep = strchr(buf, '-');
459 s->first_field = atoi(buf);
460 s->last_field = atoi(sep);
462 s->first_field = s->last_field = atoi(buf);
467 static void finish_parse_selectors(void)
469 if (!selectors_count(&selectors))
473 static void select_fields(void)
475 for (int i = 0; i < selectors_count(&selectors); i++) {
476 struct selector *s = selectors_nth(&selectors, i);
477 int first = s->first_field;
480 int last = s->last_field;
482 last = fields_count(&in_fields);
483 for (int j = first; j <= last; j++) {
484 struct field *f = fields_push(&out_fields);
485 if (j >= 1 && j <= fields_count(&in_fields))
486 *f = *fields_nth(&in_fields, j-1);
488 f->start_pos = f->len = 0;
493 /*** Processing of files ***/
495 static void one_pass(void)
500 fields_reset(&in_fields);
501 line_reset(&in_line);
503 if (!in_format->read_line())
509 fields_reset(&out_fields);
512 out_format->write_line();
516 static void two_pass(void)
518 struct format *final_format = out_format;
520 // We need to use character set info from the current locale
521 setlocale(LC_CTYPE, "");
523 // Pass 1: Set up writer of intermediate format
524 out_format = xmalloc_zero(sizeof(*out_format));
525 out_format->id = FORM_TMP;
526 out_format->read_line = tmp_read;
527 out_format->write_line = tmp_write;
528 out_format->tmp_file = tmpfile();
529 intarray_init(&out_format->column_widths);
532 // Pass 2: Set up reader of intermediate format
533 in_format = out_format;
534 rewind(in_format->tmp_file);
535 out_format = final_format;
537 fclose(in_format->tmp_file);
540 /*** Parsing of arguments ***/
542 static void usage(void)
545 Usage: xsv <in-format> [<out-format>] <options> [<fields>]\n\
548 -t, --tsv TAB-separated values (default)\n\
549 -c, --csv Comma-separated values\n\
550 -w, --ws Values separated by arbitrary whitespace\n\
551 -W, --strict-ws Like --ws, but recognize empty columns at start/end\n\
552 -r, --regex=<rx> Separator given by Perl regular expression (input only)\n\
553 --table Format a table (output only)\n\
555 Format parameters:\n\
556 -d, --fs=<char> Delimiter of fields\n\
557 -q, --quiet Do not show warnings\n\
558 --always-quote Put quotes around all fields (CSV output only)\n\
559 --table-sep=<n> Separate table columns by <n> spaces (default: 2)\n\
562 --trim Trim leading and trailing whitespaces in fields\n\
567 static void bad_args(const char *msg, ...)
572 fprintf(stderr, "xsv: ");
573 vfprintf(stderr, msg, args);
577 fprintf(stderr, "Try `xsv --help' for more information.\n");
581 static const char short_options[] = "cd:qr:twW";
591 static const struct option long_options[] = {
592 { "always-quote", 0, NULL, OPT_ALWAYS_QUOTE },
593 { "csv", 0, NULL, 'c' },
594 { "fs", 1, NULL, 'd' },
595 { "quiet", 0, NULL, 'q' },
596 { "regex", 1, NULL, 'r' },
597 { "strict-ws", 0, NULL, 'W' },
598 { "table", 0, NULL, OPT_TABLE },
599 { "table-sep", 1, NULL, OPT_TABLE_SEP },
600 { "trim", 0, NULL, OPT_TRIM },
601 { "tsv", 0, NULL, 't' },
602 { "ws", 0, NULL, 'w' },
603 { "help", 0, NULL, OPT_HELP },
604 { NULL, 0, NULL, 0 },
607 static void set_format(int format_id)
609 struct format *f = xmalloc_zero(sizeof(*f));
616 f->read_line = csv_read;
617 f->write_line = csv_write;
622 f->read_line = csv_read;
623 f->write_line = csv_write;
628 f->read_line = ws_read;
629 f->write_line = csv_write;
632 f->read_line = regex_read;
635 f->write_line = table_write;
636 f->needs_two_passes = 1;
643 else if (!out_format)
646 bad_args("At most two formats may be given.");
649 static struct format *current_format(void)
655 set_format(FORM_TSV);
659 int main(int argc, char **argv)
664 while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) >= 0)
667 set_format(FORM_CSV);
671 current_format()->fs = optarg[0];
673 bad_args("No field delimiter given.");
676 current_format()->quiet = 1;
679 set_format(FORM_REGEX);
680 err = regex_set(current_format(), optarg);
682 bad_args("Error compiling regex: %s", err);
685 set_format(FORM_TSV);
692 current_format()->strict_ws = 1;
694 case OPT_ALWAYS_QUOTE:
695 if (current_format()->id != FORM_CSV)
696 bad_args("--always-quote makes sense only for CSV.");
697 current_format()->always_quote = 1;
705 set_format(FORM_TABLE);
708 current_format()->table_sep = atoi(optarg);
716 out_format = in_format;
717 if (!in_format->read_line)
718 bad_args("Write-only format selected for input.");
719 if (!out_format->write_line)
720 bad_args("Read-only format selected for output.");
722 for (int i = optind; i < argc; i++) {
723 err = parse_selector(argv[i]);
727 finish_parse_selectors();
729 fields_init(&in_fields);
730 fields_init(&out_fields);
733 if (out_format->needs_two_passes)