2 * A Swiss-Army Knife for CSV-like Files
4 * (c) 2012 Martin Mares <mj@ucw.cz>
20 #define NONRET __attribute__((noreturn))
25 /*** General functions ***/
27 static void NONRET die(char *msg, ...)
31 fprintf(stderr, "xsv: ");
32 vfprintf(stderr, msg, args);
38 /*** Memory allocation ***/
40 static void *xmalloc(size_t bytes)
42 void *p = malloc(bytes);
44 die("Out of memory (cannot allocate %zu bytes)", bytes);
48 static void *xmalloc_zero(size_t bytes)
50 void *p = xmalloc(bytes);
55 static void *xrealloc(void *old, size_t bytes)
57 void *p = realloc(old, bytes);
59 die("Out of memory (cannot allocate %zu bytes)", bytes);
63 #define DECLARE_BUF(name, type) \
64 typedef struct { type *start; int count; int max; } name##_t; \
65 static inline void name##_init(name##_t *b) { b->start = NULL; b->count = b->max = 0; } \
66 static inline void name##_reset(name##_t *b) { b->count = 0; } \
67 static inline int name##_count(name##_t *b) { return b->count; } \
68 static void name##_extend(name##_t *b) { \
69 b->max = b->max ? 2*b->max : 16; \
70 b->start = xrealloc(b->start, b->max * sizeof(type)); \
72 static inline type *name##_push(name##_t *b) { \
73 if (b->count >= b->max) name##_extend(b); \
74 return &b->start[b->count++]; \
76 static inline type *name##_first(name##_t *b) { return b->start; } \
77 static inline type *name##_nth(name##_t *b, int n) { return &b->start[n]; } \
80 DECLARE_BUF(intarray, int);
82 /*** Formats and their parameters ***/
99 int (*read_line)(void);
100 void (*write_line)(void);
101 int needs_two_passes;
111 pcre_extra *pcre_extra;
113 // Temporary file backend:
115 intarray_t column_widths;
121 static struct format *in_format, *out_format;
122 static int want_trim;
129 DECLARE_BUF(fields, struct field);
130 DECLARE_BUF(line, unsigned char);
132 static fields_t in_fields, out_fields;
133 static struct field *in_field;
134 static line_t in_line;
135 static int line_number;
137 static void new_field(int pos)
139 in_field = fields_push(&in_fields);
140 in_field->start_pos = pos;
144 static void ensure_field(int pos)
150 static void warn(struct format *fmt, char *msg, ...)
153 fprintf(stderr, "Warning at line %d: ", line_number);
156 vfprintf(stderr, msg, args);
162 static int next_line(void)
165 int c = getchar_unlocked();
169 return !!line_count(&in_line);
172 *line_push(&in_line) = c;
176 static int field_chars(struct field *f)
178 unsigned char *s = line_nth(&in_line, f->start_pos);
181 memset(&mbs, 0, sizeof(mbs));
185 size_t k = mbrlen((char *) s + i, f->len - i, &mbs);
195 /*** CSV/TSV back-end */
197 static int csv_read(void)
201 int c = getchar_unlocked();
202 int i = line_count(&in_line);
206 if (c < 0 || c == '\n') {
208 warn(in_format, "Missing closing quote.");
210 return !!fields_count(&in_fields);
215 if (c == in_format->quote) {
216 c = getchar_unlocked();
217 if (c != in_format->quote) {
221 // Two quotes assimilate to one
223 // Fall through to pushing the character
224 } else if (c == in_format->quote) {
227 } else if (c == in_format->fs && !quoted) {
233 *line_push(&in_line) = c;
238 static int is_ws(int c)
240 return (c == ' ' || c == '\t' || c == '\f');
243 static void csv_write(void)
245 unsigned char *line = line_first(&in_line);
246 int n = fields_count(&out_fields);
247 for (int i=0; i<n; i++) {
248 struct field *f = fields_nth(&out_fields, i);
250 if (out_format->quote >= 0) {
251 need_quotes = out_format->always_quote;
252 for (int j=0; !need_quotes && j < f->len; j++) {
253 int c = line[f->start_pos + j];
254 if (c == out_format->fs || c == out_format->quote)
259 putchar_unlocked(out_format->fs);
261 putchar_unlocked(out_format->quote);
262 for (int j=0; j < f->len; j++) {
263 int c = line[f->start_pos + j];
264 if (c == out_format->fs && !need_quotes)
265 warn(out_format, "Field separator found inside field and quoting is turned off.");
266 if (c == out_format->quote)
271 putchar_unlocked(out_format->quote);
273 putchar_unlocked('\n');
276 /*** White-space back-end ***/
278 static int ws_read(void)
283 unsigned char *line = line_first(&in_line);
284 int n = line_count(&in_line);
290 for (int i=0; i<n; i++) {
296 if (!in_field->start_pos &&
298 !in_format->strict_ws)
299 in_field->start_pos = i;
308 if (ws && in_format->strict_ws)
313 /*** Regex back-end ***/
315 static const char *regex_set(struct format *f, char *rx)
319 f->pcre = pcre_compile(rx, PCRE_DOLLAR_ENDONLY, &err, &errpos, NULL);
323 f->pcre_extra = pcre_study(f->pcre, 0, &err);
330 static int regex_read(void)
335 unsigned char *c = line_first(&in_line);
336 int n = line_count(&in_line);
343 int sep = pcre_exec(in_format->pcre, in_format->pcre_extra, (char *) c, n, i, 0, ovec, 3);
345 if (sep != PCRE_ERROR_NOMATCH)
346 warn(in_format, "PCRE matching error %d", sep);
347 // No further occurrence of the separator: the rest is a single field
349 in_field->len = n - i;
353 in_field->len = ovec[0] - i;
358 /*** Table back-end ***/
360 static void table_write(void)
362 for (int i = 0; i < fields_count(&in_fields); i++) {
364 printf("%*s", out_format->table_sep, "");
365 struct field *f = fields_nth(&in_fields, i);
366 int fw = field_chars(f);
367 int cw = *intarray_nth(&in_format->column_widths, i);
369 warn(out_format, "Internal error: Wrongly calculated column width (%d > %d)", fw, cw);
372 unsigned char *p = line_nth(&in_line, f->start_pos);
373 for (int j = 0; j < f->len; j++)
374 putchar_unlocked(p[j]);
376 putchar_unlocked(' ');
380 putchar_unlocked('\n');
383 /*** Temporary file back-end ***/
385 static int tmp_read(void)
387 FILE *tf = in_format->tmp_file;
390 int c = getc_unlocked(tf);
396 c = getc_unlocked(tf);
397 c = (c << 8) | getc_unlocked(tf);
398 c = (c << 8) | getc_unlocked(tf);
399 c = (c << 8) | getc_unlocked(tf);
401 new_field(line_count(&in_line));
404 int x = getc_unlocked(tf);
406 warn(in_format, "Truncated temporary file");
409 *line_push(&in_line) = x;
413 if (ferror_unlocked(tf))
414 die("I/O error when reading temporary file");
417 static void tmp_write(void)
419 FILE *tf = out_format->tmp_file;
421 for (int i = 0; i < fields_count(&in_fields); i++) {
422 struct field *f = fields_nth(&in_fields, i);
424 putc_unlocked(f->len, tf);
426 putc_unlocked(0xfe, tf);
427 putc_unlocked((f->len >> 24) & 0xff, tf);
428 putc_unlocked((f->len >> 16) & 0xff, tf);
429 putc_unlocked((f->len >> 8) & 0xff, tf);
430 putc_unlocked(f->len & 0xff, tf);
433 unsigned char *p = line_nth(&in_line, f->start_pos);
434 for (int j = 0; j < f->len; j++)
435 putc_unlocked(*p++, tf);
437 intarray_t *w = &out_format->column_widths;
438 while (i >= intarray_count(w))
439 *intarray_push(w) = 0;
440 int fw = field_chars(f);
441 if (*intarray_nth(w, i) < fw)
442 *intarray_nth(w, i) = fw;
444 putc_unlocked(0xff, tf);
446 if (ferror_unlocked(tf))
447 die("I/O error when writing temporary file");
452 static void trim_fields(void)
454 unsigned char *line = line_first(&in_line);
455 for (int i = 0; i < fields_count(&in_fields); i++) {
456 struct field *f = fields_nth(&in_fields, i);
457 while (f->len && is_ws(line[f->start_pos]))
458 f->start_pos++, f->len--;
459 while (f->len && is_ws(line[f->start_pos + f->len - 1]))
464 /*** Field selection ***/
467 int first_field, last_field;
470 DECLARE_BUF(selectors, struct selector);
471 static selectors_t selectors;
473 static char *parse_selector(char *str)
475 char buf[strlen(str) + 1];
478 struct selector *s = selectors_push(&selectors);
479 char *sep = strchr(buf, '-');
482 s->first_field = atoi(buf);
483 s->last_field = atoi(sep);
485 s->first_field = s->last_field = atoi(buf);
490 static void finish_parse_selectors(void)
492 if (!selectors_count(&selectors))
496 static void select_fields(void)
498 for (int i = 0; i < selectors_count(&selectors); i++) {
499 struct selector *s = selectors_nth(&selectors, i);
500 int first = s->first_field;
503 int last = s->last_field;
505 last = fields_count(&in_fields);
506 for (int j = first; j <= last; j++) {
507 struct field *f = fields_push(&out_fields);
508 if (j >= 1 && j <= fields_count(&in_fields))
509 *f = *fields_nth(&in_fields, j-1);
511 f->start_pos = f->len = 0;
516 /*** Processing of files ***/
518 static void one_pass(void)
523 fields_reset(&in_fields);
524 line_reset(&in_line);
526 if (!in_format->read_line())
528 if (ferror_unlocked(stdin))
529 die("I/O error when reading standard input");
534 fields_reset(&out_fields);
537 out_format->write_line();
538 if (ferror_unlocked(stdout))
539 die("I/O error when writing standard input");
543 static void two_pass(void)
545 struct format *final_format = out_format;
547 // We need to use character set info from the current locale
548 setlocale(LC_CTYPE, "");
550 // Pass 1: Set up writer of intermediate format
551 out_format = xmalloc_zero(sizeof(*out_format));
552 out_format->id = FORM_TMP;
553 out_format->read_line = tmp_read;
554 out_format->write_line = tmp_write;
555 out_format->tmp_file = tmpfile();
556 intarray_init(&out_format->column_widths);
559 // Pass 2: Set up reader of intermediate format
560 in_format = out_format;
561 rewind(in_format->tmp_file);
562 out_format = final_format;
564 fclose(in_format->tmp_file);
567 /*** Parsing of arguments ***/
569 static void NONRET usage(void)
572 Usage: xsv <in-format> [<out-format>] <options> [<fields>]\n\
575 -t, --tsv TAB-separated values (default)\n\
576 -c, --csv Comma-separated values\n\
577 -w, --ws Values separated by arbitrary whitespace\n\
578 -W, --strict-ws Like --ws, but recognize empty columns at start/end\n\
579 -r, --regex=<rx> Separator given by Perl regular expression (input only)\n\
580 --table Format a table (output only)\n\
582 Format parameters:\n\
583 -d, --fs=<char> Delimiter of fields\n\
584 -q, --quiet Do not show warnings\n\
585 --always-quote Put quotes around all fields (CSV output only)\n\
586 --table-sep=<n> Separate table columns by <n> spaces (default: 2)\n\
589 --trim Trim leading and trailing whitespaces in fields\n\
594 static void NONRET bad_args(const char *msg, ...)
599 fprintf(stderr, "xsv: ");
600 vfprintf(stderr, msg, args);
604 fprintf(stderr, "Try `xsv --help' for more information.\n");
608 static const char short_options[] = "cd:qr:twW";
618 static const struct option long_options[] = {
619 { "always-quote", 0, NULL, OPT_ALWAYS_QUOTE },
620 { "csv", 0, NULL, 'c' },
621 { "fs", 1, NULL, 'd' },
622 { "quiet", 0, NULL, 'q' },
623 { "regex", 1, NULL, 'r' },
624 { "strict-ws", 0, NULL, 'W' },
625 { "table", 0, NULL, OPT_TABLE },
626 { "table-sep", 1, NULL, OPT_TABLE_SEP },
627 { "trim", 0, NULL, OPT_TRIM },
628 { "tsv", 0, NULL, 't' },
629 { "ws", 0, NULL, 'w' },
630 { "help", 0, NULL, OPT_HELP },
631 { NULL, 0, NULL, 0 },
634 static void set_format(int format_id)
636 struct format *f = xmalloc_zero(sizeof(*f));
643 f->read_line = csv_read;
644 f->write_line = csv_write;
649 f->read_line = csv_read;
650 f->write_line = csv_write;
655 f->read_line = ws_read;
656 f->write_line = csv_write;
659 f->read_line = regex_read;
662 f->write_line = table_write;
663 f->needs_two_passes = 1;
670 else if (!out_format)
673 bad_args("At most two formats may be given.");
676 static struct format *current_format(void)
682 set_format(FORM_TSV);
686 int main(int argc, char **argv)
691 while ((opt = getopt_long(argc, argv, short_options, long_options, NULL)) >= 0)
694 set_format(FORM_CSV);
698 current_format()->fs = optarg[0];
700 bad_args("No field delimiter given.");
703 current_format()->quiet = 1;
706 set_format(FORM_REGEX);
707 err = regex_set(current_format(), optarg);
709 bad_args("Error compiling regex: %s", err);
712 set_format(FORM_TSV);
719 current_format()->strict_ws = 1;
721 case OPT_ALWAYS_QUOTE:
722 if (current_format()->id != FORM_CSV)
723 bad_args("--always-quote makes sense only for CSV.");
724 current_format()->always_quote = 1;
732 set_format(FORM_TABLE);
735 current_format()->table_sep = atoi(optarg);
743 out_format = in_format;
744 if (!in_format->read_line)
745 bad_args("Write-only format selected for input.");
746 if (!out_format->write_line)
747 bad_args("Read-only format selected for output.");
749 for (int i = optind; i < argc; i++) {
750 err = parse_selector(argv[i]);
754 finish_parse_selectors();
756 fields_init(&in_fields);
757 fields_init(&out_fields);
760 if (out_format->needs_two_passes)