]> git.cameronkatri.com Git - apple_cmds.git/blob - text_cmds/join/join.c
patch_cmds: diffstat without autotools
[apple_cmds.git] / text_cmds / join / join.c
1 /*-
2 * Copyright (c) 1991, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
4 *
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.
8 *
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. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 */
37
38 #ifndef lint
39 static const char copyright[] =
40 "@(#) Copyright (c) 1991, 1993, 1994\n\
41 The Regents of the University of California. All rights reserved.\n";
42 #endif /* not lint */
43
44 #ifndef lint
45 #if 0
46 static char sccsid[] = "@(#)join.c 8.6 (Berkeley) 5/4/95";
47 #endif
48 #endif /* not lint */
49 #include <sys/cdefs.h>
50 __FBSDID("$FreeBSD: src/usr.bin/join/join.c,v 1.20 2004/08/26 06:28:05 maxim Exp $");
51
52 #include <sys/param.h>
53
54 #include <err.h>
55 #include <errno.h>
56 #include <limits.h>
57 #include <locale.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 #include <wchar.h>
63 #include <sysexits.h>
64
65 #ifdef __APPLE__
66 #include "get_compat.h"
67 #else
68 #define COMPAT_MODE(func, mode) 1
69 #endif
70
71 /*
72 * There's a structure per input file which encapsulates the state of the
73 * file. We repeatedly read lines from each file until we've read in all
74 * the consecutive lines from the file with a common join field. Then we
75 * compare the set of lines with an equivalent set from the other file.
76 */
77 typedef struct {
78 char *line; /* line */
79 u_long linealloc; /* line allocated count */
80 char **fields; /* line field(s) */
81 u_long fieldcnt; /* line field(s) count */
82 u_long fieldalloc; /* line field(s) allocated count */
83 } LINE;
84
85 typedef struct {
86 FILE *fp; /* file descriptor */
87 u_long joinf; /* join field (-1, -2, -j) */
88 int unpair; /* output unpairable lines (-a) */
89 u_long number; /* 1 for file 1, 2 for file 2 */
90
91 LINE *set; /* set of lines with same field */
92 int pushbool; /* if pushback is set */
93 u_long pushback; /* line on the stack */
94 u_long setcnt; /* set count */
95 u_long setalloc; /* set allocated count */
96 } INPUT;
97 INPUT input1 = { NULL, 0, 0, 1, NULL, 0, 0, 0, 0 },
98 input2 = { NULL, 0, 0, 2, NULL, 0, 0, 0, 0 };
99
100 typedef struct {
101 u_long filenum; /* file number */
102 u_long fieldno; /* field number */
103 } OLIST;
104 OLIST *olist; /* output field list */
105 u_long olistcnt; /* output field list count */
106 u_long olistalloc; /* output field allocated count */
107
108 int joinout = 1; /* show lines with matched join fields (-v) */
109 int needsep; /* need separator character */
110 int spans = 1; /* span multiple delimiters (-t) */
111 char *empty; /* empty field replacement string (-e) */
112 static wchar_t default_tabchar[] = L" \t";
113 wchar_t *tabchar = default_tabchar;/* delimiter characters (-t) */
114
115 int cmp(LINE *, u_long, LINE *, u_long);
116 void fieldarg(char *);
117 void joinlines(INPUT *, INPUT *);
118 int mbscoll(const char *, const char *);
119 char *mbssep(char **, const wchar_t *);
120 void obsolete(char **);
121 void outfield(LINE *, u_long, int);
122 void outoneline(INPUT *, LINE *);
123 void outtwoline(INPUT *, LINE *, INPUT *, LINE *);
124 void slurp(INPUT *);
125 wchar_t *towcs(const char *);
126 void usage(void);
127
128 int
129 main(int argc, char *argv[])
130 {
131 INPUT *F1, *F2;
132 int aflag, ch, cval, vflag;
133 char *end;
134
135 setlocale(LC_ALL, "");
136
137 F1 = &input1;
138 F2 = &input2;
139
140 aflag = vflag = 0;
141 if (!COMPAT_MODE("bin/join", "Unix2003"))
142 obsolete(argv);
143 while ((ch = getopt(argc, argv, "\01a:e:j:1:2:o:t:v:")) != -1) {
144 switch (ch) {
145 case '\01': /* See comment in obsolete(). */
146 aflag = 1;
147 F1->unpair = F2->unpair = 1;
148 break;
149 case '1':
150 if ((F1->joinf = strtol(optarg, &end, 10)) < 1)
151 errx(1, "-1 option field number less than 1");
152 if (*end)
153 errx(1, "illegal field number -- %s", optarg);
154 --F1->joinf;
155 break;
156 case '2':
157 if ((F2->joinf = strtol(optarg, &end, 10)) < 1)
158 errx(1, "-2 option field number less than 1");
159 if (*end)
160 errx(1, "illegal field number -- %s", optarg);
161 --F2->joinf;
162 break;
163 case 'a':
164 aflag = 1;
165 switch(strtol(optarg, &end, 10)) {
166 case 1:
167 F1->unpair = 1;
168 break;
169 case 2:
170 F2->unpair = 1;
171 break;
172 default:
173 errx(1, "-a option file number not 1 or 2");
174 break;
175 }
176 if (*end)
177 errx(1, "illegal file number -- %s", optarg);
178 break;
179 case 'e':
180 empty = optarg;
181 break;
182 case 'j':
183 if ((F1->joinf = F2->joinf =
184 strtol(optarg, &end, 10)) < 1)
185 errx(1, "-j option field number less than 1");
186 if (*end)
187 errx(1, "illegal field number -- %s", optarg);
188 --F1->joinf;
189 --F2->joinf;
190 break;
191 case 'o':
192 fieldarg(optarg);
193 break;
194 case 't':
195 spans = 0;
196 if (mbrtowc(&tabchar[0], optarg, MB_LEN_MAX, NULL) !=
197 strlen(optarg))
198 errx(1, "illegal tab character specification");
199 tabchar[1] = L'\0';
200 break;
201 case 'v':
202 vflag = 1;
203 joinout = 0;
204 switch (strtol(optarg, &end, 10)) {
205 case 1:
206 F1->unpair = 1;
207 break;
208 case 2:
209 F2->unpair = 1;
210 break;
211 default:
212 errx(1, "-v option file number not 1 or 2");
213 break;
214 }
215 if (*end)
216 errx(1, "illegal file number -- %s", optarg);
217 break;
218 case '?':
219 default:
220 usage();
221 }
222 }
223 argc -= optind;
224 argv += optind;
225
226 if (aflag && vflag)
227 errx(1, "the -a and -v options are mutually exclusive");
228
229 if (argc != 2 || argv[0]==NULL || argv[1]==NULL)
230 usage();
231
232 /* Open the files; "-" means stdin. */
233 if (!strcmp(*argv, "-"))
234 F1->fp = stdin;
235 else if ((F1->fp = fopen(*argv, "r")) == NULL)
236 err(1, "%s", *argv);
237 ++argv;
238 if (!strcmp(*argv, "-"))
239 F2->fp = stdin;
240 else if ((F2->fp = fopen(*argv, "r")) == NULL)
241 err(1, "%s", *argv);
242 if (F1->fp == stdin && F2->fp == stdin)
243 errx(1, "only one input file may be stdin");
244
245 slurp(F1);
246 slurp(F2);
247 while (F1->setcnt && F2->setcnt) {
248 cval = cmp(F1->set, F1->joinf, F2->set, F2->joinf);
249 if (cval == 0) {
250 /* Oh joy, oh rapture, oh beauty divine! */
251 if (joinout)
252 joinlines(F1, F2);
253 slurp(F1);
254 slurp(F2);
255 } else if (cval < 0) {
256 /* File 1 takes the lead... */
257 if (F1->unpair)
258 joinlines(F1, NULL);
259 slurp(F1);
260 } else {
261 /* File 2 takes the lead... */
262 if (F2->unpair)
263 joinlines(F2, NULL);
264 slurp(F2);
265 }
266 }
267
268 /*
269 * Now that one of the files is used up, optionally output any
270 * remaining lines from the other file.
271 */
272 if (F1->unpair)
273 while (F1->setcnt) {
274 joinlines(F1, NULL);
275 slurp(F1);
276 }
277 if (F2->unpair)
278 while (F2->setcnt) {
279 joinlines(F2, NULL);
280 slurp(F2);
281 }
282 exit(0);
283 }
284
285 void
286 slurp(INPUT *F)
287 {
288 LINE *lp, *lastlp, tmp;
289 size_t len;
290 int cnt;
291 char *bp, *fieldp;
292
293 /*
294 * Read all of the lines from an input file that have the same
295 * join field.
296 */
297 F->setcnt = 0;
298 for (lastlp = NULL;; ++F->setcnt) {
299 /*
300 * If we're out of space to hold line structures, allocate
301 * more. Initialize the structure so that we know that this
302 * is new space.
303 */
304 if (F->setcnt == F->setalloc) {
305 cnt = F->setalloc;
306 F->setalloc += 50;
307 if ((F->set = realloc(F->set,
308 F->setalloc * sizeof(LINE))) == NULL)
309 err(1, NULL);
310 memset(F->set + cnt, 0, 50 * sizeof(LINE));
311
312 /* re-set lastlp in case it moved */
313 if (lastlp != NULL)
314 lastlp = &F->set[F->setcnt - 1];
315 }
316
317 /*
318 * Get any pushed back line, else get the next line. Allocate
319 * space as necessary. If taking the line from the stack swap
320 * the two structures so that we don't lose space allocated to
321 * either structure. This could be avoided by doing another
322 * level of indirection, but it's probably okay as is.
323 */
324 lp = &F->set[F->setcnt];
325 if (F->setcnt)
326 lastlp = &F->set[F->setcnt - 1];
327 if (F->pushbool) {
328 tmp = F->set[F->setcnt];
329 F->set[F->setcnt] = F->set[F->pushback];
330 F->set[F->pushback] = tmp;
331 F->pushbool = 0;
332 continue;
333 }
334 if ((bp = fgetln(F->fp, &len)) == NULL) {
335 if (ferror(F->fp)) {
336 err(EX_IOERR, NULL);
337 }
338 return;
339 }
340 if (lp->linealloc <= len + 1) {
341 lp->linealloc += MAX(100, len + 1 - lp->linealloc);
342 if ((lp->line =
343 realloc(lp->line, lp->linealloc)) == NULL)
344 err(1, NULL);
345 }
346 memmove(lp->line, bp, len);
347
348 /* Replace trailing newline, if it exists. */
349 if (bp[len - 1] == '\n')
350 lp->line[len - 1] = '\0';
351 else
352 lp->line[len] = '\0';
353 bp = lp->line;
354
355 /* Split the line into fields, allocate space as necessary. */
356 lp->fieldcnt = 0;
357 while ((fieldp = mbssep(&bp, tabchar)) != NULL) {
358 if (spans && *fieldp == '\0')
359 continue;
360 if (lp->fieldcnt == lp->fieldalloc) {
361 lp->fieldalloc += 50;
362 if ((lp->fields = realloc(lp->fields,
363 lp->fieldalloc * sizeof(char *))) == NULL)
364 err(1, NULL);
365 }
366 lp->fields[lp->fieldcnt++] = fieldp;
367 }
368
369 /* See if the join field value has changed. */
370 if (lastlp != NULL && cmp(lp, F->joinf, lastlp, F->joinf)) {
371 F->pushbool = 1;
372 F->pushback = F->setcnt;
373 break;
374 }
375 }
376 }
377
378 char *
379 mbssep(char **stringp, const wchar_t *delim)
380 {
381 char *s, *tok;
382 const wchar_t *spanp;
383 wchar_t c, sc;
384 size_t n;
385
386 if ((s = *stringp) == NULL)
387 return (NULL);
388 for (tok = s;;) {
389 n = mbrtowc(&c, s, MB_LEN_MAX, NULL);
390 if (n == (size_t)-1 || n == (size_t)-2)
391 errc(1, EILSEQ, NULL); /* XXX */
392 s += n;
393 spanp = delim;
394 do {
395 if ((sc = *spanp++) == c) {
396 if (c == 0)
397 s = NULL;
398 else
399 s[-n] = '\0';
400 *stringp = s;
401 return (tok);
402 }
403 } while (sc != 0);
404 }
405 }
406
407 int
408 cmp(LINE *lp1, u_long fieldno1, LINE *lp2, u_long fieldno2)
409 {
410 if (lp1->fieldcnt <= fieldno1)
411 return (lp2->fieldcnt <= fieldno2 ? 0 : 1);
412 if (lp2->fieldcnt <= fieldno2)
413 return (-1);
414 return (mbscoll(lp1->fields[fieldno1], lp2->fields[fieldno2]));
415 }
416
417 int
418 mbscoll(const char *s1, const char *s2)
419 {
420 wchar_t *w1, *w2;
421 int ret;
422
423 if (MB_CUR_MAX == 1)
424 return (strcoll(s1, s2));
425 if ((w1 = towcs(s1)) == NULL || (w2 = towcs(s2)) == NULL)
426 err(1, NULL); /* XXX */
427 ret = wcscoll(w1, w2);
428 free(w1);
429 free(w2);
430 return (ret);
431 }
432
433 wchar_t *
434 towcs(const char *s)
435 {
436 wchar_t *wcs;
437 size_t n;
438
439 if ((n = mbsrtowcs(NULL, &s, 0, NULL)) == (size_t)-1)
440 return (NULL);
441 if ((wcs = malloc((n + 1) * sizeof(*wcs))) == NULL)
442 return (NULL);
443 mbsrtowcs(wcs, &s, n + 1, NULL);
444 return (wcs);
445 }
446
447 void
448 joinlines(INPUT *F1, INPUT *F2)
449 {
450 u_long cnt1, cnt2;
451
452 /*
453 * Output the results of a join comparison. The output may be from
454 * either file 1 or file 2 (in which case the first argument is the
455 * file from which to output) or from both.
456 */
457 if (F2 == NULL) {
458 for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
459 outoneline(F1, &F1->set[cnt1]);
460 return;
461 }
462 for (cnt1 = 0; cnt1 < F1->setcnt; ++cnt1)
463 for (cnt2 = 0; cnt2 < F2->setcnt; ++cnt2)
464 outtwoline(F1, &F1->set[cnt1], F2, &F2->set[cnt2]);
465 }
466
467 void
468 outoneline(INPUT *F, LINE *lp)
469 {
470 u_long cnt;
471
472 /*
473 * Output a single line from one of the files, according to the
474 * join rules. This happens when we are writing unmatched single
475 * lines. Output empty fields in the right places.
476 */
477 if (olist)
478 for (cnt = 0; cnt < olistcnt; ++cnt) {
479 if (olist[cnt].filenum == (unsigned)F->number)
480 outfield(lp, olist[cnt].fieldno, 0);
481 else if (olist[cnt].filenum == 0)
482 outfield(lp, F->joinf, 0);
483 else
484 outfield(lp, 0, 1);
485 }
486 else
487 for (cnt = 0; cnt < lp->fieldcnt; ++cnt)
488 outfield(lp, cnt, 0);
489 (void)printf("\n");
490 if (ferror(stdout))
491 err(1, "stdout");
492 needsep = 0;
493 }
494
495 void
496 outtwoline(INPUT *F1, LINE *lp1, INPUT *F2, LINE *lp2)
497 {
498 u_long cnt;
499
500 /* Output a pair of lines according to the join list (if any). */
501 if (olist)
502 for (cnt = 0; cnt < olistcnt; ++cnt)
503 if (olist[cnt].filenum == 0) {
504 if (lp1->fieldcnt >= F1->joinf)
505 outfield(lp1, F1->joinf, 0);
506 else
507 outfield(lp2, F2->joinf, 0);
508 } else if (olist[cnt].filenum == 1)
509 outfield(lp1, olist[cnt].fieldno, 0);
510 else /* if (olist[cnt].filenum == 2) */
511 outfield(lp2, olist[cnt].fieldno, 0);
512 else {
513 /*
514 * Output the join field, then the remaining fields from F1
515 * and F2.
516 */
517 outfield(lp1, F1->joinf, 0);
518 for (cnt = 0; cnt < lp1->fieldcnt; ++cnt)
519 if (F1->joinf != cnt)
520 outfield(lp1, cnt, 0);
521 for (cnt = 0; cnt < lp2->fieldcnt; ++cnt)
522 if (F2->joinf != cnt)
523 outfield(lp2, cnt, 0);
524 }
525 (void)printf("\n");
526 if (ferror(stdout))
527 err(1, "stdout");
528 needsep = 0;
529 }
530
531 void
532 outfield(LINE *lp, u_long fieldno, int out_empty)
533 {
534 if (needsep++)
535 (void)printf("%lc", *tabchar);
536 if (!ferror(stdout)) {
537 if (lp->fieldcnt <= fieldno || out_empty) {
538 if (empty != NULL)
539 (void)printf("%s", empty);
540 } else {
541 if (*lp->fields[fieldno] == '\0') {
542 if (COMPAT_MODE("bin/join", "Unix2003") && empty != NULL)
543 (void)printf("%s", empty);
544 else
545 return;
546 } else
547 (void)printf("%s", lp->fields[fieldno]);
548 }
549 }
550 if (ferror(stdout))
551 err(1, "stdout");
552 }
553
554 /*
555 * Convert an output list argument "2.1, 1.3, 2.4" into an array of output
556 * fields.
557 */
558 void
559 fieldarg(char *option)
560 {
561 u_long fieldno, filenum;
562 char *end, *token;
563
564 while ((token = strsep(&option, ", \t")) != NULL) {
565 if (*token == '\0')
566 continue;
567 if (token[0] == '0')
568 filenum = fieldno = 0;
569 else if ((token[0] == '1' || token[0] == '2') &&
570 token[1] == '.') {
571 filenum = token[0] - '0';
572 fieldno = strtol(token + 2, &end, 10);
573 if (*end)
574 errx(1, "malformed -o option field");
575 if (fieldno == 0)
576 errx(1, "field numbers are 1 based");
577 --fieldno;
578 } else
579 errx(1, "malformed -o option field");
580 if (olistcnt == olistalloc) {
581 olistalloc += 50;
582 if ((olist = realloc(olist,
583 olistalloc * sizeof(OLIST))) == NULL)
584 err(1, NULL);
585 }
586 olist[olistcnt].filenum = filenum;
587 olist[olistcnt].fieldno = fieldno;
588 ++olistcnt;
589 }
590 }
591
592 void
593 obsolete(char **argv)
594 {
595 size_t len;
596 char **p, *ap, *t;
597
598 while ((ap = *++argv) != NULL) {
599 /* Return if "--". */
600 if (ap[0] == '-' && ap[1] == '-')
601 return;
602 /* skip if not an option */
603 if (ap[0] != '-')
604 continue;
605 switch (ap[1]) {
606 case 'a':
607 /*
608 * The original join allowed "-a", which meant the
609 * same as -a1 plus -a2. POSIX 1003.2, Draft 11.2
610 * only specifies this as "-a 1" and "a -2", so we
611 * have to use another option flag, one that is
612 * unlikely to ever be used or accidentally entered
613 * on the command line. (Well, we could reallocate
614 * the argv array, but that hardly seems worthwhile.)
615 */
616 if (ap[2] == '\0' && (argv[1] == NULL ||
617 (strcmp(argv[1], "1") != 0 &&
618 strcmp(argv[1], "2") != 0))) {
619 ap[1] = '\01';
620 warnx("-a option used without an argument; "
621 "reverting to historical behavior");
622 }
623 break;
624 case 'j':
625 /*
626 * The original join allowed "-j[12] arg" and "-j arg".
627 * Convert the former to "-[12] arg". Don't convert
628 * the latter since getopt(3) can handle it.
629 */
630 switch(ap[2]) {
631 case '1':
632 if (ap[3] != '\0')
633 goto jbad;
634 ap[1] = '1';
635 ap[2] = '\0';
636 break;
637 case '2':
638 if (ap[3] != '\0')
639 goto jbad;
640 ap[1] = '2';
641 ap[2] = '\0';
642 break;
643 case '\0':
644 break;
645 default:
646 jbad: errx(1, "illegal option -- %s", ap);
647 usage();
648 }
649 break;
650 case 'o':
651 /*
652 * The original join allowed "-o arg arg".
653 * Convert to "-o arg -o arg".
654 */
655 if (ap[2] != '\0')
656 break;
657 for (p = argv + 2; *p; ++p) {
658 if (p[0][0] == '0' || ((p[0][0] != '1' &&
659 p[0][0] != '2') || p[0][1] != '.'))
660 break;
661 len = strlen(*p);
662 if (len - 2 != strspn(*p + 2, "0123456789"))
663 break;
664 if ((t = malloc(len + 3)) == NULL)
665 err(1, NULL);
666 t[0] = '-';
667 t[1] = 'o';
668 memmove(t + 2, *p, len + 1);
669 *p = t;
670 }
671 argv = p - 1;
672 break;
673 }
674 }
675 }
676
677 void
678 usage(void)
679 {
680 (void)fprintf(stderr, "%s %s\n%s\n",
681 "usage: join [-a fileno | -v fileno ] [-e string] [-1 field]",
682 "[-2 field]",
683 " [-o list] [-t char] file1 file2");
684 exit(1);
685 }