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