sort: fix ENDCHAR handling in "-kSTART,N.ENDCHAR"
[oweals/busybox.git] / coreutils / sort.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * SuS3 compliant sort implementation for busybox
4  *
5  * Copyright (C) 2004 by Rob Landley <rob@landley.net>
6  *
7  * MAINTAINER: Rob Landley <rob@landley.net>
8  *
9  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
10  *
11  * See SuS3 sort standard at:
12  * http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
13  */
14
15 //usage:#define sort_trivial_usage
16 //usage:       "[-nru"
17 //usage:        IF_FEATURE_SORT_BIG("gMcszbdfimSTokt] [-o FILE] [-k start[.offset][opts][,end[.offset][opts]] [-t CHAR")
18 //usage:       "] [FILE]..."
19 //usage:#define sort_full_usage "\n\n"
20 //usage:       "Sort lines of text\n"
21 //usage:        IF_FEATURE_SORT_BIG(
22 //usage:     "\n        -b      Ignore leading blanks"
23 //usage:     "\n        -c      Check whether input is sorted"
24 //usage:     "\n        -d      Dictionary order (blank or alphanumeric only)"
25 //usage:     "\n        -f      Ignore case"
26 //usage:     "\n        -g      General numerical sort"
27 //usage:     "\n        -i      Ignore unprintable characters"
28 //usage:     "\n        -M      Sort month"
29 //usage:        )
30 //-h, --human-numeric-sort: compare human readable numbers (e.g., 2K 1G)
31 //usage:     "\n        -n      Sort numbers"
32 //usage:        IF_FEATURE_SORT_BIG(
33 //usage:     "\n        -o      Output to file"
34 //usage:     "\n        -t CHAR Field separator"
35 //usage:     "\n        -k N[,M] Sort by Nth field"
36 //usage:        )
37 //usage:     "\n        -r      Reverse sort order"
38 //usage:        IF_FEATURE_SORT_BIG(
39 //usage:     "\n        -s      Stable (don't sort ties alphabetically)"
40 //usage:        )
41 //usage:     "\n        -u      Suppress duplicate lines"
42 //usage:        IF_FEATURE_SORT_BIG(
43 //usage:     "\n        -z      Lines are terminated by NUL, not newline"
44 //usage:     "\n        -mST    Ignored for GNU compatibility")
45 //usage:
46 //usage:#define sort_example_usage
47 //usage:       "$ echo -e \"e\\nf\\nb\\nd\\nc\\na\" | sort\n"
48 //usage:       "a\n"
49 //usage:       "b\n"
50 //usage:       "c\n"
51 //usage:       "d\n"
52 //usage:       "e\n"
53 //usage:       "f\n"
54 //usage:        IF_FEATURE_SORT_BIG(
55 //usage:                "$ echo -e \"c 3\\nb 2\\nd 2\" | $SORT -k 2,2n -k 1,1r\n"
56 //usage:                "d 2\n"
57 //usage:                "b 2\n"
58 //usage:                "c 3\n"
59 //usage:        )
60 //usage:       ""
61
62 #include "libbb.h"
63
64 /* This is a NOEXEC applet. Be very careful! */
65
66
67 /*
68         sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
69         sort -c [-bdfinru][-t char][-k keydef][file]
70 */
71
72 /* These are sort types */
73 static const char OPT_STR[] ALIGN1 = "ngMucszbrdfimS:T:o:k:t:";
74 enum {
75         FLAG_n  = 1,            /* Numeric sort */
76         FLAG_g  = 2,            /* Sort using strtod() */
77         FLAG_M  = 4,            /* Sort date */
78 /* ucsz apply to root level only, not keys.  b at root level implies bb */
79         FLAG_u  = 8,            /* Unique */
80         FLAG_c  = 0x10,         /* Check: no output, exit(!ordered) */
81         FLAG_s  = 0x20,         /* Stable sort, no ascii fallback at end */
82         FLAG_z  = 0x40,         /* Input and output is NUL terminated, not \n */
83 /* These can be applied to search keys, the previous four can't */
84         FLAG_b  = 0x80,         /* Ignore leading blanks */
85         FLAG_r  = 0x100,        /* Reverse */
86         FLAG_d  = 0x200,        /* Ignore !(isalnum()|isspace()) */
87         FLAG_f  = 0x400,        /* Force uppercase */
88         FLAG_i  = 0x800,        /* Ignore !isprint() */
89         FLAG_m  = 0x1000,       /* ignored: merge already sorted files; do not sort */
90         FLAG_S  = 0x2000,       /* ignored: -S, --buffer-size=SIZE */
91         FLAG_T  = 0x4000,       /* ignored: -T, --temporary-directory=DIR */
92         FLAG_o  = 0x8000,
93         FLAG_k  = 0x10000,
94         FLAG_t  = 0x20000,
95         FLAG_bb = 0x80000000,   /* Ignore trailing blanks  */
96 };
97
98 #if ENABLE_FEATURE_SORT_BIG
99 static char key_separator;
100
101 static struct sort_key {
102         struct sort_key *next_key;  /* linked list */
103         unsigned range[4];          /* start word, start char, end word, end char */
104         unsigned flags;
105 } *key_list;
106
107 static char *get_key(char *str, struct sort_key *key, int flags)
108 {
109         int start = start; /* for compiler */
110         int end;
111         int len, j;
112         unsigned i;
113
114         /* Special case whole string, so we don't have to make a copy */
115         if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
116          && !(flags & (FLAG_b | FLAG_d | FLAG_f | FLAG_i | FLAG_bb))
117         ) {
118                 return str;
119         }
120
121         /* Find start of key on first pass, end on second pass */
122         len = strlen(str);
123         for (j = 0; j < 2; j++) {
124                 if (!key->range[2*j])
125                         end = len;
126                 /* Loop through fields */
127                 else {
128                         unsigned char ch = 0;
129
130                         end = 0;
131                         for (i = 1; i < key->range[2*j] + j; i++) {
132                                 if (key_separator) {
133                                         /* Skip body of key and separator */
134                                         while ((ch = str[end]) != '\0') {
135                                                         end++;
136                                                 if (ch == key_separator)
137                                                         break;
138                                         }
139                                 } else {
140                                         /* Skip leading blanks */
141                                         while (isspace(str[end]))
142                                                 end++;
143                                         /* Skip body of key */
144                                         while (str[end] != '\0') {
145                                                 if (isspace(str[end]))
146                                                         break;
147                                                 end++;
148                                         }
149                                 }
150                         }
151                         /* Remove last delim: "abc:def:" => "abc:def" */
152                         if (j && ch) {
153                                 //if (str[end-1] != key_separator)
154                                 //  bb_error_msg(_and_die("BUG! "
155                                 //  "str[start:%d,end:%d]:'%.*s'",
156                                 //  start, end, (int)(end-start), &str[start]);
157                                 end--;
158                         }
159                 }
160                 if (!j) start = end;
161         }
162         /* Strip leading whitespace if necessary */
163         if (flags & FLAG_b)
164                 /* not using skip_whitespace() for speed */
165                 while (isspace(str[start])) start++;
166         /* Strip trailing whitespace if necessary */
167         if (flags & FLAG_bb)
168                 while (end > start && isspace(str[end-1])) end--;
169         /* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based) */
170         if (key->range[3]) {
171                 end = key->range[3];
172                 if (end > len) end = len;
173         }
174         /* -kN.STARTCHAR[,...]: honor STARTCHAR (1-based) */
175         if (key->range[1]) {
176                 start += key->range[1] - 1;
177                 if (start > len) start = len;
178         }
179         /* Make the copy */
180         if (end < start)
181                 end = start;
182         str = xstrndup(str+start, end-start);
183         /* Handle -d */
184         if (flags & FLAG_d) {
185                 for (start = end = 0; str[end]; end++)
186                         if (isspace(str[end]) || isalnum(str[end]))
187                                 str[start++] = str[end];
188                 str[start] = '\0';
189         }
190         /* Handle -i */
191         if (flags & FLAG_i) {
192                 for (start = end = 0; str[end]; end++)
193                         if (isprint_asciionly(str[end]))
194                                 str[start++] = str[end];
195                 str[start] = '\0';
196         }
197         /* Handle -f */
198         if (flags & FLAG_f)
199                 for (i = 0; str[i]; i++)
200                         str[i] = toupper(str[i]);
201
202         return str;
203 }
204
205 static struct sort_key *add_key(void)
206 {
207         struct sort_key **pkey = &key_list;
208         while (*pkey)
209                 pkey = &((*pkey)->next_key);
210         return *pkey = xzalloc(sizeof(struct sort_key));
211 }
212
213 #define GET_LINE(fp) \
214         ((option_mask32 & FLAG_z) \
215         ? bb_get_chunk_from_file(fp, NULL) \
216         : xmalloc_fgetline(fp))
217 #else
218 #define GET_LINE(fp) xmalloc_fgetline(fp)
219 #endif
220
221 /* Iterate through keys list and perform comparisons */
222 static int compare_keys(const void *xarg, const void *yarg)
223 {
224         int flags = option_mask32, retval = 0;
225         char *x, *y;
226
227 #if ENABLE_FEATURE_SORT_BIG
228         struct sort_key *key;
229
230         for (key = key_list; !retval && key; key = key->next_key) {
231                 flags = key->flags ? key->flags : option_mask32;
232                 /* Chop out and modify key chunks, handling -dfib */
233                 x = get_key(*(char **)xarg, key, flags);
234                 y = get_key(*(char **)yarg, key, flags);
235 #else
236         /* This curly bracket serves no purpose but to match the nesting
237          * level of the for () loop we're not using */
238         {
239                 x = *(char **)xarg;
240                 y = *(char **)yarg;
241 #endif
242                 /* Perform actual comparison */
243                 switch (flags & (FLAG_n | FLAG_M | FLAG_g)) {
244                 default:
245                         bb_error_msg_and_die("unknown sort type");
246                         break;
247                 /* Ascii sort */
248                 case 0:
249 #if ENABLE_LOCALE_SUPPORT
250                         retval = strcoll(x, y);
251 #else
252                         retval = strcmp(x, y);
253 #endif
254                         break;
255 #if ENABLE_FEATURE_SORT_BIG
256                 case FLAG_g: {
257                         char *xx, *yy;
258                         double dx = strtod(x, &xx);
259                         double dy = strtod(y, &yy);
260                         /* not numbers < NaN < -infinity < numbers < +infinity) */
261                         if (x == xx)
262                                 retval = (y == yy ? 0 : -1);
263                         else if (y == yy)
264                                 retval = 1;
265                         /* Check for isnan */
266                         else if (dx != dx)
267                                 retval = (dy != dy) ? 0 : -1;
268                         else if (dy != dy)
269                                 retval = 1;
270                         /* Check for infinity.  Could underflow, but it avoids libm. */
271                         else if (1.0 / dx == 0.0) {
272                                 if (dx < 0)
273                                         retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
274                                 else
275                                         retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
276                         } else if (1.0 / dy == 0.0)
277                                 retval = (dy < 0) ? 1 : -1;
278                         else
279                                 retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
280                         break;
281                 }
282                 case FLAG_M: {
283                         struct tm thyme;
284                         int dx;
285                         char *xx, *yy;
286
287                         xx = strptime(x, "%b", &thyme);
288                         dx = thyme.tm_mon;
289                         yy = strptime(y, "%b", &thyme);
290                         if (!xx)
291                                 retval = (!yy) ? 0 : -1;
292                         else if (!yy)
293                                 retval = 1;
294                         else
295                                 retval = dx - thyme.tm_mon;
296                         break;
297                 }
298                 /* Full floating point version of -n */
299                 case FLAG_n: {
300                         double dx = atof(x);
301                         double dy = atof(y);
302                         retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
303                         break;
304                 }
305                 } /* switch */
306                 /* Free key copies. */
307                 if (x != *(char **)xarg) free(x);
308                 if (y != *(char **)yarg) free(y);
309                 /* if (retval) break; - done by for () anyway */
310 #else
311                 /* Integer version of -n for tiny systems */
312                 case FLAG_n:
313                         retval = atoi(x) - atoi(y);
314                         break;
315                 } /* switch */
316 #endif
317         } /* for */
318
319         /* Perform fallback sort if necessary */
320         if (!retval && !(option_mask32 & FLAG_s)) {
321                 flags = option_mask32;
322                 retval = strcmp(*(char **)xarg, *(char **)yarg);
323         }
324
325         if (flags & FLAG_r)
326                 return -retval;
327
328         return retval;
329 }
330
331 #if ENABLE_FEATURE_SORT_BIG
332 static unsigned str2u(char **str)
333 {
334         unsigned long lu;
335         if (!isdigit((*str)[0]))
336                 bb_error_msg_and_die("bad field specification");
337         lu = strtoul(*str, str, 10);
338         if ((sizeof(long) > sizeof(int) && lu > INT_MAX) || !lu)
339                 bb_error_msg_and_die("bad field specification");
340         return lu;
341 }
342 #endif
343
344 int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
345 int sort_main(int argc UNUSED_PARAM, char **argv)
346 {
347         char *line, **lines;
348         char *str_ignored, *str_o, *str_t;
349         llist_t *lst_k = NULL;
350         int i;
351         int linecount;
352         unsigned opts;
353
354         xfunc_error_retval = 2;
355
356         /* Parse command line options */
357         /* -o and -t can be given at most once */
358         opt_complementary = "o--o:t--t:" /* -t, -o: at most one of each */
359                         "k::"; /* -k takes list */
360         opts = getopt32(argv, OPT_STR, &str_ignored, &str_ignored, &str_o, &lst_k, &str_t);
361         /* global b strips leading and trailing spaces */
362         if (opts & FLAG_b)
363                 option_mask32 |= FLAG_bb;
364 #if ENABLE_FEATURE_SORT_BIG
365         if (opts & FLAG_t) {
366                 if (!str_t[0] || str_t[1])
367                         bb_error_msg_and_die("bad -t parameter");
368                 key_separator = str_t[0];
369         }
370         /* note: below this point we use option_mask32, not opts,
371          * since that reduces register pressure and makes code smaller */
372
373         /* Parse sort key */
374         while (lst_k) {
375                 enum {
376                         FLAG_allowed_for_k =
377                                 FLAG_n | /* Numeric sort */
378                                 FLAG_g | /* Sort using strtod() */
379                                 FLAG_M | /* Sort date */
380                                 FLAG_b | /* Ignore leading blanks */
381                                 FLAG_r | /* Reverse */
382                                 FLAG_d | /* Ignore !(isalnum()|isspace()) */
383                                 FLAG_f | /* Force uppercase */
384                                 FLAG_i | /* Ignore !isprint() */
385                         0
386                 };
387                 struct sort_key *key = add_key();
388                 char *str_k = llist_pop(&lst_k);
389
390                 i = 0; /* i==0 before comma, 1 after (-k3,6) */
391                 while (*str_k) {
392                         /* Start of range */
393                         /* Cannot use bb_strtou - suffix can be a letter */
394                         key->range[2*i] = str2u(&str_k);
395                         if (*str_k == '.') {
396                                 str_k++;
397                                 key->range[2*i+1] = str2u(&str_k);
398                         }
399                         while (*str_k) {
400                                 int flag;
401                                 const char *idx;
402
403                                 if (*str_k == ',' && !i++) {
404                                         str_k++;
405                                         break;
406                                 } /* no else needed: fall through to syntax error
407                                         because comma isn't in OPT_STR */
408                                 idx = strchr(OPT_STR, *str_k);
409                                 if (!idx)
410                                         bb_error_msg_and_die("unknown key option");
411                                 flag = 1 << (idx - OPT_STR);
412                                 if (flag & ~FLAG_allowed_for_k)
413                                         bb_error_msg_and_die("unknown sort type");
414                                 /* b after ',' means strip _trailing_ space */
415                                 if (i && flag == FLAG_b)
416                                         flag = FLAG_bb;
417                                 key->flags |= flag;
418                                 str_k++;
419                         }
420                 }
421         }
422 #endif
423
424         /* Open input files and read data */
425         argv += optind;
426         if (!*argv)
427                 *--argv = (char*)"-";
428         linecount = 0;
429         lines = NULL;
430         do {
431                 /* coreutils 6.9 compat: abort on first open error,
432                  * do not continue to next file: */
433                 FILE *fp = xfopen_stdin(*argv);
434                 for (;;) {
435                         line = GET_LINE(fp);
436                         if (!line)
437                                 break;
438                         lines = xrealloc_vector(lines, 6, linecount);
439                         lines[linecount++] = line;
440                 }
441                 fclose_if_not_stdin(fp);
442         } while (*++argv);
443
444 #if ENABLE_FEATURE_SORT_BIG
445         /* If no key, perform alphabetic sort */
446         if (!key_list)
447                 add_key()->range[0] = 1;
448         /* Handle -c */
449         if (option_mask32 & FLAG_c) {
450                 int j = (option_mask32 & FLAG_u) ? -1 : 0;
451                 for (i = 1; i < linecount; i++) {
452                         if (compare_keys(&lines[i-1], &lines[i]) > j) {
453                                 fprintf(stderr, "Check line %u\n", i);
454                                 return EXIT_FAILURE;
455                         }
456                 }
457                 return EXIT_SUCCESS;
458         }
459 #endif
460         /* Perform the actual sort */
461         qsort(lines, linecount, sizeof(lines[0]), compare_keys);
462
463         /* Handle -u */
464         if (option_mask32 & FLAG_u) {
465                 int j = 0;
466                 /* coreutils 6.3 drop lines for which only key is the same */
467                 /* -- disabling last-resort compare... */
468                 option_mask32 |= FLAG_s;
469                 for (i = 1; i < linecount; i++) {
470                         if (compare_keys(&lines[j], &lines[i]) == 0)
471                                 free(lines[i]);
472                         else
473                                 lines[++j] = lines[i];
474                 }
475                 if (linecount)
476                         linecount = j+1;
477         }
478
479         /* Print it */
480 #if ENABLE_FEATURE_SORT_BIG
481         /* Open output file _after_ we read all input ones */
482         if (option_mask32 & FLAG_o)
483                 xmove_fd(xopen(str_o, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
484 #endif
485         {
486                 int ch = (option_mask32 & FLAG_z) ? '\0' : '\n';
487                 for (i = 0; i < linecount; i++)
488                         printf("%s%c", lines[i], ch);
489         }
490
491         fflush_stdout_and_exit(EXIT_SUCCESS);
492 }