• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* sort.c - put input lines into order
2  *
3  * Copyright 2004, 2008 Rob Landley <rob@landley.net>
4  *
5  * See http://opengroup.org/onlinepubs/007904975/utilities/sort.html
6  *
7  * Deviations from POSIX: Lots.
8  * We invented -x
9 
10 USE_SORT(NEWTOY(sort, USE_SORT_FLOAT("g")"S:T:m" "o:k*t:" "xVbMCcszdfirun", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_ARGFAIL(2)))
11 
12 config SORT
13   bool "sort"
14   default y
15   help
16     usage: sort [-runbcdfiMsz] [FILE...] [-k#[,#[x]] [-t X]] [-o FILE]
17 
18     Sort all lines of text from input files (or stdin) to stdout.
19 
20     -r	Reverse
21     -u	Unique lines only
22     -n	Numeric order (instead of alphabetical)
23     -b	Ignore leading blanks (or trailing blanks in second part of key)
24     -C	Check whether input is sorted
25     -c	Warn if input is unsorted
26     -d	Dictionary order (use alphanumeric and whitespace chars only)
27     -f	Force uppercase (case insensitive sort)
28     -i	Ignore nonprinting characters
29     -M	Month sort (jan, feb, etc)
30     -x	Hexadecimal numerical sort
31     -s	Skip fallback sort (only sort with keys)
32     -z	Zero (null) terminated lines
33     -k	Sort by "key" (see below)
34     -t	Use a key separator other than whitespace
35     -o	Output to FILE instead of stdout
36     -V	Version numbers (name-1.234-rc6.5b.tgz)
37 
38     Sorting by key looks at a subset of the words on each line. -k2 uses the
39     second word to the end of the line, -k2,2 looks at only the second word,
40     -k2,4 looks from the start of the second to the end of the fourth word.
41     -k2.4,5 starts from the fourth character of the second word, to the end
42     of the fifth word. Specifying multiple keys uses the later keys as tie
43     breakers, in order. A type specifier appended to a sort key (such as -2,2n)
44     applies only to sorting that key.
45 
46 config SORT_FLOAT
47   bool
48   default y
49   depends on TOYBOX_FLOAT
50   help
51     usage: sort [-g]
52 
53     -g	General numeric sort (double precision with nan and inf)
54 */
55 
56 #define FOR_sort
57 #include "toys.h"
58 
59 GLOBALS(
60   char *t;
61   struct arg_list *k;
62   char *o, *T, S;
63 
64   void *key_list;
65   unsigned linecount;
66   char **lines, *name;
67 )
68 
69 // The sort types are n, g, and M.
70 // u, c, s, and z apply to top level only, not to keys.
71 // b at top level implies bb.
72 // The remaining options can be applied to search keys.
73 
74 #define FLAG_bb (1<<31)  // Ignore trailing blanks
75 
76 struct sort_key {
77   struct sort_key *next_key;  // linked list
78   unsigned range[4];          // start word, start char, end word, end char
79   int flags;
80 };
81 
82 // Copy of the part of this string corresponding to a key/flags.
83 
get_key_data(char * str,struct sort_key * key,int flags)84 static char *get_key_data(char *str, struct sort_key *key, int flags)
85 {
86   int start = 0, end, len, i, j;
87 
88   // Special case whole string, so we don't have to make a copy
89 
90   if(key->range[0]==1 && !key->range[1] && !key->range[2] && !key->range[3]
91     && !(flags&(FLAG_b|FLAG_d|FLAG_i|FLAG_bb))) return str;
92 
93   // Find start of key on first pass, end on second pass
94 
95   len = strlen(str);
96   for (j=0; j<2; j++) {
97     if (!key->range[2*j]) end=len;
98 
99     // Loop through fields
100     else {
101       end = 0;
102       for (i = 1; i < key->range[2*j]+j; i++) {
103 
104         // Skip leading blanks
105         if (str[end] && !TT.t) while (isspace(str[end])) end++;
106 
107         // Skip body of key
108         for (; str[end]; end++) {
109           if (TT.t) {
110             if (str[end]==*TT.t) {
111               end++;
112               break;
113             }
114           } else if (isspace(str[end])) break;
115         }
116       }
117     }
118     if (!j) start = end;
119   }
120 
121   // Key with explicit separator starts after the separator
122   if (TT.t && str[start]==*TT.t) start++;
123 
124   // Strip leading and trailing whitespace if necessary
125   if ((flags&FLAG_b) || (!TT.t && !key->range[3]))
126     while (isspace(str[start])) start++;
127   if (flags&FLAG_bb) while (end>start && isspace(str[end-1])) end--;
128 
129   // Handle offsets on start and end
130   if (key->range[3]) {
131     end += key->range[3]-1;
132     if (end>len) end=len;
133   }
134   if (key->range[1]) {
135     start += key->range[1]-1;
136     if (start>len) start=len;
137   }
138 
139   // Make the copy
140   if (end<start) end = start;
141   str = xstrndup(str+start, end-start);
142 
143   // Handle -d
144   if (flags&FLAG_d) {
145     for (start = end = 0; str[end]; end++)
146       if (isspace(str[end]) || isalnum(str[end])) str[start++] = str[end];
147     str[start] = 0;
148   }
149 
150   // Handle -i
151   if (flags&FLAG_i) {
152     for (start = end = 0; str[end]; end++)
153       if (isprint(str[end])) str[start++] = str[end];
154     str[start] = 0;
155   }
156 
157   return str;
158 }
159 
160 // append a sort_key to key_list.
161 
add_key(void)162 static struct sort_key *add_key(void)
163 {
164   void **stupid_compiler = &TT.key_list;
165   struct sort_key **pkey = (struct sort_key **)stupid_compiler;
166 
167   while (*pkey) pkey = &((*pkey)->next_key);
168   return *pkey = xzalloc(sizeof(struct sort_key));
169 }
170 
171 // Perform actual comparison
compare_values(int flags,char * x,char * y)172 static int compare_values(int flags, char *x, char *y)
173 {
174   if (CFG_SORT_FLOAT && (flags & FLAG_g)) {
175     char *xx,*yy;
176     double dx = strtod(x,&xx), dy = strtod(y,&yy);
177     int xinf, yinf;
178 
179     // not numbers < NaN < -infinity < numbers < +infinity
180 
181     if (x==xx) return y==yy ? 0 : -1;
182     if (y==yy) return 1;
183 
184     // Check for isnan
185     if (dx!=dx) return (dy!=dy) ? 0 : -1;
186     if (dy!=dy) return 1;
187 
188     // Check for infinity.  (Could underflow, but avoids needing libm.)
189     xinf = (1.0/dx == 0.0);
190     yinf = (1.0/dy == 0.0);
191     if (xinf) {
192       if(dx<0) return (yinf && dy<0) ? 0 : -1;
193       return (yinf && dy>0) ? 0 : 1;
194     }
195     if (yinf) return dy<0 ? 1 : -1;
196 
197     return dx<dy ? -1 : dx>dy;
198   } else if (flags & FLAG_M) {
199     struct tm thyme;
200     int dx;
201     char *xx,*yy;
202 
203     xx = strptime(x,"%b",&thyme);
204     dx = thyme.tm_mon;
205     yy = strptime(y,"%b",&thyme);
206     if (!xx) return !yy ? 0 : -1;
207     else if (!yy) return 1;
208     else return dx==thyme.tm_mon ? 0 : dx-thyme.tm_mon;
209 
210   } else if (flags & FLAG_x) return strtol(x, NULL, 16)-strtol(y, NULL, 16);
211   else if (flags & FLAG_V) {
212     while (*x && *y) {
213       while (*x && *x == *y) x++, y++;
214       if (isdigit(*x) && isdigit(*y)) {
215         long long xx = strtoll(x, &x, 10), yy = strtoll(y, &y, 10);
216 
217         if (xx<yy) return -1;
218         if (xx>yy) return 1;
219       } else {
220         char xx = *x ? *x : x[-1], yy = *y ? *y : y[-1];
221 
222         // -rc/-pre hack so abc-123 > abc-123-rc1 (other way already - < 0-9)
223         if (xx != yy) {
224           if (xx<yy && !strstart(&y, "-rc") && !strstart(&y, "-pre")) return -1;
225           else return 1;
226         }
227       }
228     }
229     return *x ? !!*y : -1;
230   // This is actually an integer sort with decimals sorted by string fallback.
231   } else if (flags & FLAG_n) {
232     long long dx = atoll(x), dy = atoll(y);
233 
234     return dx<dy ? -1 : dx>dy;
235 
236   // Ascii sort
237   } else return ((flags&FLAG_f) ? strcasecmp : strcmp)(x, y);
238 }
239 
240 // Callback from qsort(): Iterate through key_list and perform comparisons.
compare_keys(const void * xarg,const void * yarg)241 static int compare_keys(const void *xarg, const void *yarg)
242 {
243   int flags = toys.optflags, retval = 0;
244   char *x, *y, *xx = *(char **)xarg, *yy = *(char **)yarg;
245   struct sort_key *key;
246 
247   for (key=(void *)TT.key_list; !retval && key; key = key->next_key) {
248     flags = key->flags ? : toys.optflags;
249 
250     // Chop out and modify key chunks, handling -dfib
251 
252     x = get_key_data(xx, key, flags);
253     y = get_key_data(yy, key, flags);
254 
255     retval = compare_values(flags, x, y);
256 
257     // Free the copies get_key_data() made.
258 
259     if (x != xx) free(x);
260     if (y != yy) free(y);
261 
262     if (retval) break;
263   }
264 
265   // Perform fallback sort if necessary (always case insensitive, no -f,
266   // the point is to get a stable order even for -f sorts)
267   if (!retval && !FLAG(s)) {
268     flags = toys.optflags;
269     retval = strcmp(xx, yy);
270   }
271 
272   return retval * ((flags&FLAG_r) ? -1 : 1);
273 }
274 
275 // Read each line from file, appending to a big array.
sort_lines(char ** pline,long len)276 static void sort_lines(char **pline, long len)
277 {
278   char *line;
279 
280   if (!pline) return;
281   line = *pline;
282   if (!FLAG(z) && len && line[len-1]=='\n') line[--len] = 0;
283   *pline = 0;
284 
285   // handle -c here so we don't allocate more memory than necessary.
286   if (FLAG(C)||FLAG(c)) {
287     if (TT.lines && compare_keys((void *)&TT.lines, &line)>-FLAG(u)) {
288       toys.exitval = 1;
289       if (FLAG(C)) xexit();
290       error_exit("%s: Check line %u", TT.name, TT.linecount+1);
291     }
292     free(TT.lines);
293     TT.lines = (void *)line;
294   } else {
295     if (!(TT.linecount&63))
296       TT.lines = xrealloc(TT.lines, sizeof(char *)*(TT.linecount+64));
297     TT.lines[TT.linecount] = line;
298   }
299   TT.linecount++;
300 }
301 
302 // Callback from loopfiles to handle input files.
sort_read(int fd,char * name)303 static void sort_read(int fd, char *name)
304 {
305   TT.name = name;
306   do_lines(fd, '\n'*!FLAG(z), sort_lines);
307 }
308 
sort_main(void)309 void sort_main(void)
310 {
311   int idx, jdx, fd = 1;
312 
313   if (FLAG(u)) toys.optflags |= FLAG_s;
314 
315   // Parse -k sort keys.
316   if (TT.k) {
317     struct arg_list *arg;
318 
319     for (arg = TT.k; arg; arg = arg->next) {
320       struct sort_key *key = add_key();
321       char *temp, *temp2, *optlist;
322       int flag;
323 
324       idx = 0;
325       temp = arg->arg;
326       while (*temp) {
327         // Start of range
328         key->range[2*idx] = strtol(temp, &temp, 10);
329         if (*temp=='.') key->range[(2*idx)+1] = strtol(temp+1, &temp, 10);
330 
331         // Handle flags appended to a key type.
332         for (;*temp;temp++) {
333 
334           // Second comma becomes an "Unknown key" error.
335           if (*temp==',' && !idx++) {
336             temp++;
337             break;
338           }
339 
340           // Which flag is this?
341           optlist = toys.which->options;
342           temp2 = strchr(optlist, *temp);
343           flag = 1<<(optlist-temp2+strlen(optlist)-1);
344 
345           // Was it a flag that can apply to a key?
346           if (!temp2 || flag>FLAG_x || (flag&(FLAG_u|FLAG_c|FLAG_s|FLAG_z)))
347             error_exit("Unknown key option.");
348 
349           // b after , means strip _trailing_ space, not leading.
350           if (idx && flag==FLAG_b) flag = FLAG_bb;
351           key->flags |= flag;
352         }
353       }
354     }
355   }
356 
357   // global b flag strips both leading and trailing spaces
358   if (FLAG(b)) toys.optflags |= FLAG_bb;
359 
360   // If no keys, perform alphabetic sort over the whole line.
361   if (!TT.key_list) add_key()->range[0] = 1;
362 
363   // Open input files and read data, populating TT.lines[TT.linecount]
364   loopfiles(toys.optargs, sort_read);
365 
366   // The compare (-c) logic was handled in sort_read(),
367   // so if we got here, we're done.
368   if (FLAG(C)||FLAG(c)) goto exit_now;
369 
370   // Perform the actual sort
371   qsort(TT.lines, TT.linecount, sizeof(char *), compare_keys);
372 
373   // handle unique (-u)
374   if (FLAG(u)) {
375     for (jdx=0, idx=1; idx<TT.linecount; idx++) {
376       if (!compare_keys(&TT.lines[jdx], &TT.lines[idx])) free(TT.lines[idx]);
377       else TT.lines[++jdx] = TT.lines[idx];
378     }
379     if (TT.linecount) TT.linecount = jdx+1;
380   }
381 
382   // Open output file if necessary. We can't do this until we've finished
383   // reading in case the output file is one of the input files.
384   if (TT.o) fd = xcreate(TT.o, O_CREAT|O_TRUNC|O_WRONLY, 0666);
385 
386   // Output result
387   for (idx = 0; idx<TT.linecount; idx++) {
388     char *s = TT.lines[idx];
389     unsigned i = strlen(s);
390 
391     if (!FLAG(z)) s[i] = '\n';
392     xwrite(fd, s, i+1);
393     if (CFG_TOYBOX_FREE) free(s);
394   }
395 
396 exit_now:
397   if (CFG_TOYBOX_FREE) {
398     if (fd != 1) close(fd);
399     free(TT.lines);
400   }
401 }
402