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