manpp: handle groff \N[dd] escape sequence
[rofl0r-hardcore-utils.git] / join.c
blob5e8c7f869baeaec28a16d50a2cf6655660bfd2e3
1 /*-
2 * Copyright (c) 1991, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Steve Hayman of the Computer Science Department, Indiana University,
7 * Michiro Hikida and David Goodenough.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
34 #include <sys/param.h>
35 #include <sys/types.h>
36 #include <err.h>
37 #include <errno.h>
38 #include <limits.h>
39 #include <locale.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <wchar.h>
47 * There's a structure per input file which encapsulates the state of the
48 * file. We repeatedly read lines from each file until we've read in all
49 * the consecutive lines from the file with a common join field. Then we
50 * compare the set of lines with an equivalent set from the other file.
52 typedef struct {
53 char *line; /* line */
54 u_long linealloc; /* line allocated count */
55 char **fields; /* line field(s) */
56 u_long fieldcnt; /* line field(s) count */
57 u_long fieldalloc; /* line field(s) allocated count */
58 } LINE;
60 typedef struct {
61 FILE *fp; /* file descriptor */
62 u_long joinf; /* join field (-1, -2, -j) */
63 int unpair; /* output unpairable lines (-a) */
64 u_long number; /* 1 for file 1, 2 for file 2 */
66 LINE *set; /* set of lines with same field */
67 int pushbool; /* if pushback is set */
68 u_long pushback; /* line on the stack */
69 u_long setcnt; /* set count */
70 u_long setalloc; /* set allocated count */
71 } INPUT;
72 static INPUT input1 = { NULL, 0, 0, 1, NULL, 0, 0, 0, 0 },
73 input2 = { NULL, 0, 0, 2, NULL, 0, 0, 0, 0 };
75 typedef struct {
76 u_long filenum; /* file number */
77 u_long fieldno; /* field number */
78 } OLIST;
79 static OLIST *olist; /* output field list */
80 static u_long olistcnt; /* output field list count */
81 static u_long olistalloc; /* output field allocated count */
83 static int joinout = 1; /* show lines with matched join fields (-v) */
84 static int needsep; /* need separator character */
85 static int spans = 1; /* span multiple delimiters (-t) */
86 static char *empty; /* empty field replacement string (-e) */
87 static wchar_t default_tabchar[] = L" \t";
88 static wchar_t *tabchar = default_tabchar; /* delimiter characters (-t) */
90 static int cmp(LINE *, u_long, LINE *, u_long);
91 static void fieldarg(char *);
92 static void joinlines(INPUT *, INPUT *);
93 static int mbscoll(const char *, const char *);
94 static char *mbssep(char **, const wchar_t *);
95 static void obsolete(char **);
96 static void outfield(LINE *, u_long, int);
97 static void outoneline(INPUT *, LINE *);
98 static void outtwoline(INPUT *, LINE *, INPUT *, LINE *);
99 static void slurp(INPUT *);
100 static wchar_t *towcs(const char *);
101 static void usage(void);
104 main(int argc, char *argv[])
106 INPUT *F1, *F2;
107 int aflag, ch, cval, vflag;
108 char *end;
110 setlocale(LC_ALL, "");
112 F1 = &input1;
113 F2 = &input2;
115 aflag = vflag = 0;
116 obsolete(argv);
117 while ((ch = getopt(argc, argv, "\01a:e:j:1:2:o:t:v:")) != -1) {
118 switch (ch) {
119 case '\01': /* See comment in obsolete(). */
120 aflag = 1;
121 F1->unpair = F2->unpair = 1;
122 break;
123 case '1':
124 if ((F1->joinf = strtol(optarg, &end, 10)) < 1)
125 errx(1, "-1 option field number less than 1");
126 if (*end)
127 errx(1, "illegal field number -- %s", optarg);
128 --F1->joinf;
129 break;
130 case '2':
131 if ((F2->joinf = strtol(optarg, &end, 10)) < 1)
132 errx(1, "-2 option field number less than 1");
133 if (*end)
134 errx(1, "illegal field number -- %s", optarg);
135 --F2->joinf;
136 break;
137 case 'a':
138 aflag = 1;
139 switch(strtol(optarg, &end, 10)) {
140 case 1:
141 F1->unpair = 1;
142 break;
143 case 2:
144 F2->unpair = 1;
145 break;
146 default:
147 errx(1, "-a option file number not 1 or 2");
148 break;
150 if (*end)
151 errx(1, "illegal file number -- %s", optarg);
152 break;
153 case 'e':
154 empty = optarg;
155 break;
156 case 'j':
157 if ((F1->joinf = F2->joinf =
158 strtol(optarg, &end, 10)) < 1)
159 errx(1, "-j option field number less than 1");
160 if (*end)
161 errx(1, "illegal field number -- %s", optarg);
162 --F1->joinf;
163 --F2->joinf;
164 break;
165 case 'o':
166 fieldarg(optarg);
167 break;
168 case 't':
169 spans = 0;
170 if (mbrtowc(&tabchar[0], optarg, MB_LEN_MAX, NULL) !=
171 strlen(optarg))
172 errx(1, "illegal tab character specification");
173 tabchar[1] = L'\0';
174 break;
175 case 'v':
176 vflag = 1;
177 joinout = 0;
178 switch (strtol(optarg, &end, 10)) {
179 case 1:
180 F1->unpair = 1;
181 break;
182 case 2:
183 F2->unpair = 1;
184 break;
185 default:
186 errx(1, "-v option file number not 1 or 2");
187 break;
189 if (*end)
190 errx(1, "illegal file number -- %s", optarg);
191 break;
192 case '?':
193 default:
194 usage();
197 argc -= optind;
198 argv += optind;
200 if (aflag && vflag)
201 errx(1, "the -a and -v options are mutually exclusive");
203 if (argc != 2)
204 usage();
206 /* Open the files; "-" means stdin. */
207 if (!strcmp(*argv, "-"))
208 F1->fp = stdin;
209 else if ((F1->fp = fopen(*argv, "r")) == NULL)
210 err(1, "%s", *argv);
211 ++argv;
212 if (!strcmp(*argv, "-"))
213 F2->fp = stdin;
214 else if ((F2->fp = fopen(*argv, "r")) == NULL)
215 err(1, "%s", *argv);
216 if (F1->fp == stdin && F2->fp == stdin)
217 errx(1, "only one input file may be stdin");
219 slurp(F1);
220 slurp(F2);
221 while (F1->setcnt && F2->setcnt) {
222 cval = cmp(F1->set, F1->joinf, F2->set, F2->joinf);
223 if (cval == 0) {
224 /* Oh joy, oh rapture, oh beauty divine! */
225 if (joinout)
226 joinlines(F1, F2);
227 slurp(F1);
228 slurp(F2);
229 } else if (cval < 0) {
230 /* File 1 takes the lead... */
231 if (F1->unpair)
232 joinlines(F1, NULL);
233 slurp(F1);
234 } else {
235 /* File 2 takes the lead... */
236 if (F2->unpair)
237 joinlines(F2, NULL);
238 slurp(F2);
243 * Now that one of the files is used up, optionally output any
244 * remaining lines from the other file.
246 if (F1->unpair)
247 while (F1->setcnt) {
248 joinlines(F1, NULL);
249 slurp(F1);
251 if (F2->unpair)
252 while (F2->setcnt) {
253 joinlines(F2, NULL);
254 slurp(F2);
256 exit(0);
259 static void
260 slurp(INPUT *F)
262 LINE *lp, *lastlp, tmp;
263 size_t len;
264 int cnt;
265 char *bp, *fieldp;
268 * Read all of the lines from an input file that have the same
269 * join field.
271 F->setcnt = 0;
272 for (lastlp = NULL;; ++F->setcnt) {
274 * If we're out of space to hold line structures, allocate
275 * more. Initialize the structure so that we know that this
276 * is new space.
278 if (F->setcnt == F->setalloc) {
279 cnt = F->setalloc;
280 F->setalloc += 50;
281 if ((F->set = realloc(F->set,
282 F->setalloc * sizeof(LINE))) == NULL)
283 err(1, NULL);
284 memset(F->set + cnt, 0, 50 * sizeof(LINE));
286 /* re-set lastlp in case it moved */
287 if (lastlp != NULL)
288 lastlp = &F->set[F->setcnt - 1];
292 * Get any pushed back line, else get the next line. Allocate
293 * space as necessary. If taking the line from the stack swap
294 * the two structures so that we don't lose space allocated to
295 * either structure. This could be avoided by doing another
296 * level of indirection, but it's probably okay as is.
298 lp = &F->set[F->setcnt];
299 if (F->setcnt)
300 lastlp = &F->set[F->setcnt - 1];
301 if (F->pushbool) {
302 tmp = F->set[F->setcnt];
303 F->set[F->setcnt] = F->set[F->pushback];
304 F->set[F->pushback] = tmp;
305 F->pushbool = 0;
306 continue;
308 if ((bp = fgetln(F->fp, &len)) == NULL)
309 return;
310 if (lp->linealloc <= len + 1) {
311 lp->linealloc += MAX(100, len + 1 - lp->linealloc);
312 if ((lp->line =
313 realloc(lp->line, lp->linealloc)) == NULL)
314 err(1, NULL);
316 memmove(lp->line, bp, len);
318 /* Replace trailing newline, if it exists. */
319 if (bp[len - 1] == '\n')
320 lp->line[len - 1] = '\0';
321 else
322 lp->line[len] = '\0';
323 bp = lp->line;
325 /* Split the line into fields, allocate space as necessary. */
326 lp->fieldcnt = 0;
327 while ((fieldp = mbssep(&bp, tabchar)) != NULL) {
328 if (spans && *fieldp == '\0')
329 continue;
330 if (lp->fieldcnt == lp->fieldalloc) {
331 lp->fieldalloc += 50;
332 if ((lp->fields = realloc(lp->fields,
333 lp->fieldalloc * sizeof(char *))) == NULL)
334 err(1, NULL);
336 lp->fields[lp->fieldcnt++] = fieldp;
339 /* See if the join field value has changed. */
340 if (lastlp != NULL && cmp(lp, F->joinf, lastlp, F->joinf)) {
341 F->pushbool = 1;
342 F->pushback = F->setcnt;
343 break;
348 static char *
349 mbssep(char **stringp, const wchar_t *delim)
351 char *s, *tok;
352 const wchar_t *spanp;
353 wchar_t c, sc;
354 size_t n;
356 if ((s = *stringp) == NULL)
357 return (NULL);
358 for (tok = s;;) {
359 n = mbrtowc(&c, s, MB_LEN_MAX, NULL);
360 if (n == (size_t)-1 || n == (size_t)-2) {
361 errno = EILSEQ;
362 err(1, NULL); /* XXX */
364 s += n;
365 spanp = delim;
366 do {
367 if ((sc = *spanp++) == c) {
368 if (c == 0)
369 s = NULL;
370 else
371 s[-n] = '\0';
372 *stringp = s;
373 return (tok);
375 } while (sc != 0);
379 static int
380 cmp(LINE *lp1, u_long fieldno1, LINE *lp2, u_long fieldno2)
382 if (lp1->fieldcnt <= fieldno1)
383 return (lp2->fieldcnt <= fieldno2 ? 0 : 1);
384 if (lp2->fieldcnt <= fieldno2)
385 return (-1);
386 return (mbscoll(lp1->fields[fieldno1], lp2->fields[fieldno2]));
389 static int
390 mbscoll(const char *s1, const char *s2)
392 wchar_t *w1, *w2;
393 int ret;
395 if (MB_CUR_MAX == 1)
396 return (strcoll(s1, s2));
397 if ((w1 = towcs(s1)) == NULL || (w2 = towcs(s2)) == NULL)
398 err(1, NULL); /* XXX */
399 ret = wcscoll(w1, w2);
400 free(w1);
401 free(w2);
402 return (ret);
405 static wchar_t *
406 towcs(const char *s)
408 wchar_t *wcs;
409 size_t n;
411 if ((n = mbsrtowcs(NULL, &s, 0, NULL)) == (size_t)-1)
412 return (NULL);
413 if ((wcs = malloc((n + 1) * sizeof(*wcs))) == NULL)
414 return (NULL);
415 mbsrtowcs(wcs, &s, n + 1, NULL);
416 return (wcs);
419 static void
420 joinlines(INPUT *F1, INPUT *F2)
422 u_long cnt1, cnt2;
425 * Output the results of a join comparison. The output may be from
426 * either file 1 or file 2 (in which case the first argument is the
427 * file from which to output) or from both.
429 if (F2 == NULL) {
430 for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
431 outoneline(F1, &F1->set[cnt1]);
432 return;
434 for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
435 for (cnt2 = 0; cnt2 < F2->setcnt; ++cnt2)
436 outtwoline(F1, &F1->set[cnt1], F2, &F2->set[cnt2]);
439 static void
440 outoneline(INPUT *F, LINE *lp)
442 u_long cnt;
445 * Output a single line from one of the files, according to the
446 * join rules. This happens when we are writing unmatched single
447 * lines. Output empty fields in the right places.
449 if (olist)
450 for (cnt = 0; cnt < olistcnt; ++cnt) {
451 if (olist[cnt].filenum == (unsigned)F->number)
452 outfield(lp, olist[cnt].fieldno, 0);
453 else if (olist[cnt].filenum == 0)
454 outfield(lp, F->joinf, 0);
455 else
456 outfield(lp, 0, 1);
458 else
459 for (cnt = 0; cnt < lp->fieldcnt; ++cnt)
460 outfield(lp, cnt, 0);
461 (void)printf("\n");
462 if (ferror(stdout))
463 err(1, "stdout");
464 needsep = 0;
467 static void
468 outtwoline(INPUT *F1, LINE *lp1, INPUT *F2, LINE *lp2)
470 u_long cnt;
472 /* Output a pair of lines according to the join list (if any). */
473 if (olist)
474 for (cnt = 0; cnt < olistcnt; ++cnt)
475 if (olist[cnt].filenum == 0) {
476 if (lp1->fieldcnt >= F1->joinf)
477 outfield(lp1, F1->joinf, 0);
478 else
479 outfield(lp2, F2->joinf, 0);
480 } else if (olist[cnt].filenum == 1)
481 outfield(lp1, olist[cnt].fieldno, 0);
482 else /* if (olist[cnt].filenum == 2) */
483 outfield(lp2, olist[cnt].fieldno, 0);
484 else {
486 * Output the join field, then the remaining fields from F1
487 * and F2.
489 outfield(lp1, F1->joinf, 0);
490 for (cnt = 0; cnt < lp1->fieldcnt; ++cnt)
491 if (F1->joinf != cnt)
492 outfield(lp1, cnt, 0);
493 for (cnt = 0; cnt < lp2->fieldcnt; ++cnt)
494 if (F2->joinf != cnt)
495 outfield(lp2, cnt, 0);
497 (void)printf("\n");
498 if (ferror(stdout))
499 err(1, "stdout");
500 needsep = 0;
503 static void
504 outfield(LINE *lp, u_long fieldno, int out_empty)
506 if (needsep++)
507 (void)printf("%lc", (wint_t)*tabchar);
508 if (!ferror(stdout)) {
509 if (lp->fieldcnt <= fieldno || out_empty) {
510 if (empty != NULL)
511 (void)printf("%s", empty);
512 } else {
513 if (*lp->fields[fieldno] == '\0')
514 return;
515 (void)printf("%s", lp->fields[fieldno]);
518 if (ferror(stdout))
519 err(1, "stdout");
523 * Convert an output list argument "2.1, 1.3, 2.4" into an array of output
524 * fields.
526 static void
527 fieldarg(char *option)
529 u_long fieldno, filenum;
530 char *end, *token;
532 while ((token = strsep(&option, ", \t")) != NULL) {
533 if (*token == '\0')
534 continue;
535 if (token[0] == '0')
536 filenum = fieldno = 0;
537 else if ((token[0] == '1' || token[0] == '2') &&
538 token[1] == '.') {
539 filenum = token[0] - '0';
540 fieldno = strtol(token + 2, &end, 10);
541 if (*end)
542 errx(1, "malformed -o option field");
543 if (fieldno == 0)
544 errx(1, "field numbers are 1 based");
545 --fieldno;
546 } else
547 errx(1, "malformed -o option field");
548 if (olistcnt == olistalloc) {
549 olistalloc += 50;
550 if ((olist = realloc(olist,
551 olistalloc * sizeof(OLIST))) == NULL)
552 err(1, NULL);
554 olist[olistcnt].filenum = filenum;
555 olist[olistcnt].fieldno = fieldno;
556 ++olistcnt;
560 static void
561 obsolete(char **argv)
563 size_t len;
564 char **p, *ap, *t;
566 while ((ap = *++argv) != NULL) {
567 /* Return if "--". */
568 if (ap[0] == '-' && ap[1] == '-')
569 return;
570 /* skip if not an option */
571 if (ap[0] != '-')
572 continue;
573 switch (ap[1]) {
574 case 'a':
576 * The original join allowed "-a", which meant the
577 * same as -a1 plus -a2. POSIX 1003.2, Draft 11.2
578 * only specifies this as "-a 1" and "a -2", so we
579 * have to use another option flag, one that is
580 * unlikely to ever be used or accidentally entered
581 * on the command line. (Well, we could reallocate
582 * the argv array, but that hardly seems worthwhile.)
584 if (ap[2] == '\0' && (argv[1] == NULL ||
585 (strcmp(argv[1], "1") != 0 &&
586 strcmp(argv[1], "2") != 0))) {
587 ap[1] = '\01';
588 warnx("-a option used without an argument; "
589 "reverting to historical behavior");
591 break;
592 case 'j':
594 * The original join allowed "-j[12] arg" and "-j arg".
595 * Convert the former to "-[12] arg". Don't convert
596 * the latter since getopt(3) can handle it.
598 switch(ap[2]) {
599 case '1':
600 if (ap[3] != '\0')
601 goto jbad;
602 ap[1] = '1';
603 ap[2] = '\0';
604 break;
605 case '2':
606 if (ap[3] != '\0')
607 goto jbad;
608 ap[1] = '2';
609 ap[2] = '\0';
610 break;
611 case '\0':
612 break;
613 default:
614 jbad: errx(1, "illegal option -- %s", ap);
615 usage();
617 break;
618 case 'o':
620 * The original join allowed "-o arg arg".
621 * Convert to "-o arg -o arg".
623 if (ap[2] != '\0')
624 break;
625 for (p = argv + 2; *p; ++p) {
626 if (p[0][0] == '0' || ((p[0][0] != '1' &&
627 p[0][0] != '2') || p[0][1] != '.'))
628 break;
629 len = strlen(*p);
630 if (len - 2 != strspn(*p + 2, "0123456789"))
631 break;
632 if ((t = malloc(len + 3)) == NULL)
633 err(1, NULL);
634 t[0] = '-';
635 t[1] = 'o';
636 memmove(t + 2, *p, len + 1);
637 *p = t;
639 argv = p - 1;
640 break;
645 static void
646 usage(void)
648 (void)fprintf(stderr, "%s %s\n%s\n",
649 "usage: join [-a fileno | -v fileno ] [-e string] [-1 field]",
650 "[-2 field]",
651 " [-o list] [-t char] file1 file2");
652 exit(1);