sort.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  20. *
  21. * See SuS3 sort standard at:
  22. * http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html
  23. */
  24. #include <ctype.h>
  25. #include <math.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <string.h>
  29. #include <time.h>
  30. #include <unistd.h>
  31. #include "busybox.h"
  32. static int global_flags;
  33. /*
  34. sort [-m][-o output][-bdfinru][-t char][-k keydef]... [file...]
  35. sort -c [-bdfinru][-t char][-k keydef][file]
  36. */
  37. /* These are sort types */
  38. #define FLAG_n 1 /* Numeric sort */
  39. #define FLAG_g 2 /* Sort using strtod() */
  40. #define FLAG_M 4 /* Sort date */
  41. /* ucsz apply to root level only, not keys. b at root level implies bb */
  42. #define FLAG_u 8 /* Unique */
  43. #define FLAG_c 16 /* Check: no output, exit(!ordered) */
  44. #define FLAG_s 32 /* Stable sort, no ascii fallback at end */
  45. #define FLAG_z 64 /* Input is null terminated, not \n */
  46. /* These can be applied to search keys, the previous four can't */
  47. #define FLAG_b 128 /* Ignore leading blanks */
  48. #define FLAG_r 256 /* Reverse */
  49. #define FLAG_d 512 /* Ignore !(isalnum()|isspace()) */
  50. #define FLAG_f 1024 /* Force uppercase */
  51. #define FLAG_i 2048 /* Ignore !isprint() */
  52. #define FLAG_bb 32768 /* Ignore trailing blanks */
  53. #ifdef CONFIG_SORT_BIG
  54. static char key_separator;
  55. static struct sort_key
  56. {
  57. struct sort_key *next_key; /* linked list */
  58. unsigned short range[4]; /* start word, start char, end word, end char */
  59. int flags;
  60. } *key_list;
  61. static char *get_key(char *str, struct sort_key *key, int flags)
  62. {
  63. int start=0,end,len,i,j;
  64. /* Special case whole string, so we don't have to make a copy */
  65. if(key->range[0]==1 && !key->range[1] && !key->range[2] && !key->range[3]
  66. && !(flags&(FLAG_b&FLAG_d&FLAG_f&FLAG_i&FLAG_bb))) return str;
  67. /* Find start of key on first pass, end on second pass*/
  68. len=strlen(str);
  69. for(j=0;j<2;j++) {
  70. if(!key->range[2*j]) end=len;
  71. /* Loop through fields */
  72. else {
  73. end=0;
  74. for(i=1;i<key->range[2*j]+j;i++) {
  75. /* Skip leading blanks or first separator */
  76. if(str[end]) {
  77. if(key_separator) {
  78. if(str[end]==key_separator) end++;
  79. } else if(isspace(str[end]))
  80. while(isspace(str[end])) end++;
  81. }
  82. /* Skip body of key */
  83. for(;str[end];end++) {
  84. if(key_separator) {
  85. if(str[end]==key_separator) break;
  86. } else if(isspace(str[end])) break;
  87. }
  88. }
  89. }
  90. if(!j) start=end;
  91. }
  92. /* Key with explicit separator starts after separator */
  93. if(key_separator && str[start]==key_separator) start++;
  94. /* Strip leading whitespace if necessary */
  95. if(flags&FLAG_b) while(isspace(str[start])) start++;
  96. /* Strip trailing whitespace if necessary */
  97. if(flags&FLAG_bb) while(end>start && isspace(str[end-1])) end--;
  98. /* Handle offsets on start and end */
  99. if(key->range[3]) {
  100. end+=key->range[3]-1;
  101. if(end>len) end=len;
  102. }
  103. if(key->range[1]) {
  104. start+=key->range[1]-1;
  105. if(start>len) start=len;
  106. }
  107. /* Make the copy */
  108. if(end<start) end=start;
  109. str=bb_xstrndup(str+start,end-start);
  110. /* Handle -d */
  111. if(flags&FLAG_d) {
  112. for(start=end=0;str[end];end++)
  113. if(isspace(str[end]) || isalnum(str[end])) str[start++]=str[end];
  114. str[start]=0;
  115. }
  116. /* Handle -i */
  117. if(flags&FLAG_i) {
  118. for(start=end=0;str[end];end++)
  119. if(isprint(str[end])) str[start++]=str[end];
  120. str[start]=0;
  121. }
  122. /* Handle -f */
  123. if(flags*FLAG_f) for(i=0;str[i];i++) str[i]=toupper(str[i]);
  124. return str;
  125. }
  126. static struct sort_key *add_key(void)
  127. {
  128. struct sort_key **pkey=&key_list;
  129. while(*pkey) pkey=&((*pkey)->next_key);
  130. return *pkey=xcalloc(1,sizeof(struct sort_key));
  131. }
  132. #define GET_LINE(fp) (global_flags&FLAG_z) ? bb_get_chunk_from_file(fp) \
  133. : bb_get_chomped_line_from_file(fp)
  134. #else
  135. #define GET_LINE(fp) bb_get_chomped_line_from_file(fp)
  136. #endif
  137. /* Iterate through keys list and perform comparisons */
  138. static int compare_keys(const void *xarg, const void *yarg)
  139. {
  140. int flags=global_flags,retval=0;
  141. char *x,*y;
  142. #ifdef CONFIG_SORT_BIG
  143. struct sort_key *key;
  144. for(key=key_list;!retval && key;key=key->next_key) {
  145. flags=(key->flags) ? key->flags : global_flags;
  146. /* Chop out and modify key chunks, handling -dfib */
  147. x=get_key(*(char **)xarg,key,flags);
  148. y=get_key(*(char **)yarg,key,flags);
  149. #else
  150. /* This curly bracket serves no purpose but to match the nesting
  151. level of the for() loop we're not using */
  152. {
  153. x=*(char **)xarg;
  154. y=*(char **)yarg;
  155. #endif
  156. /* Perform actual comparison */
  157. switch(flags&7) {
  158. default:
  159. bb_error_msg_and_die("Unknown sort type.");
  160. break;
  161. /* Ascii sort */
  162. case 0:
  163. retval=strcmp(x,y);
  164. break;
  165. #ifdef CONFIG_SORT_BIG
  166. case FLAG_g:
  167. {
  168. char *xx,*yy;
  169. double dx=strtod(x,&xx), dy=strtod(y,&yy);
  170. /* not numbers < NaN < -infinity < numbers < +infinity) */
  171. if(x==xx) retval=(y==yy ? 0 : -1);
  172. else if(y==yy) retval=1;
  173. else if(isnan(dx)) retval=isnan(dy) ? 0 : -1;
  174. else if(isnan(dy)) retval=1;
  175. else if(isinf(dx)) {
  176. if(dx<0) retval=((isinf(dy) && dy<0) ? 0 : -1);
  177. else retval=((isinf(dy) && dy>0) ? 0 : 1);
  178. } else if(isinf(dy)) retval=dy<0 ? 1 : -1;
  179. else retval=dx>dy ? 1 : (dx<dy ? -1 : 0);
  180. break;
  181. }
  182. case FLAG_M:
  183. {
  184. struct tm thyme;
  185. int dx;
  186. char *xx,*yy;
  187. xx=strptime(x,"%b",&thyme);
  188. dx=thyme.tm_mon;
  189. yy=strptime(y,"%b",&thyme);
  190. if(!xx) retval=(!yy ? 0 : -1);
  191. else if(!yy) retval=1;
  192. else retval=(dx==thyme.tm_mon ? 0 : dx-thyme.tm_mon);
  193. break;
  194. }
  195. /* Full floating point version of -n */
  196. case FLAG_n:
  197. {
  198. double dx=atof(x),dy=atof(y);
  199. retval=dx>dy ? 1 : (dx<dy ? -1 : 0);
  200. break;
  201. }
  202. }
  203. /* Free key copies. */
  204. if(x!=*(char **)xarg) free(x);
  205. if(y!=*(char **)yarg) free(y);
  206. if(retval) break;
  207. #else
  208. /* Integer version of -n for tiny systems */
  209. case FLAG_n:
  210. retval=atoi(x)-atoi(y);
  211. break;
  212. }
  213. #endif
  214. }
  215. /* Perform fallback sort if necessary */
  216. if(!retval && !(global_flags&FLAG_s))
  217. retval=strcmp(*(char **)xarg, *(char **)yarg);
  218. return ((flags&FLAG_r)?-1:1)*retval;
  219. }
  220. int sort_main(int argc, char **argv)
  221. {
  222. FILE *fp,*outfile=NULL;
  223. int linecount=0,i,flag;
  224. char *line,**lines=NULL,c,*optlist="ngMucszbrdfimS:T:o:k:t:";
  225. bb_default_error_retval = 2;
  226. /* Parse command line options */
  227. while((c=getopt(argc,argv,optlist))>0) {
  228. line=index(optlist,c);
  229. if(!line) bb_show_usage();
  230. switch(*line) {
  231. #ifdef CONFIG_SORT_BIG
  232. case 'o':
  233. if(outfile) bb_error_msg_and_die("Too many -o.");
  234. outfile=bb_xfopen(optarg,"w");
  235. break;
  236. case 't':
  237. if(key_separator || optarg[1])
  238. bb_error_msg_and_die("Too many -t.");
  239. key_separator=*optarg;
  240. break;
  241. /* parse sort key */
  242. case 'k':
  243. {
  244. struct sort_key *key=add_key();
  245. char *temp, *temp2;
  246. temp=optarg;
  247. for(i=0;*temp;) {
  248. /* Start of range */
  249. key->range[2*i]=(unsigned short)strtol(temp,&temp,10);
  250. if(*temp=='.')
  251. key->range[(2*i)+1]=(unsigned short)strtol(temp+1,&temp,10);
  252. for(;*temp;temp++) {
  253. if(*temp==',' && !i++) {
  254. temp++;
  255. break;
  256. } /* no else needed: fall through to syntax error
  257. because comma isn't in optlist */
  258. temp2=index(optlist,*temp);
  259. flag=(1<<(temp2-optlist));
  260. if(!temp2 || (flag>FLAG_M && flag<FLAG_b))
  261. bb_error_msg_and_die("Unknown key option.");
  262. /* b after , means strip _trailing_ space */
  263. if(i && flag==FLAG_b) flag=FLAG_bb;
  264. key->flags|=flag;
  265. }
  266. }
  267. break;
  268. }
  269. #endif
  270. default:
  271. global_flags|=(1<<(line-optlist));
  272. /* global b strips leading and trailing spaces */
  273. if(global_flags&FLAG_b) global_flags|=FLAG_bb;
  274. break;
  275. }
  276. }
  277. /* Open input files and read data */
  278. for(i=argv[optind] ? optind : optind-1;argv[i];i++) {
  279. if(i<optind || (*argv[i]=='-' && !argv[i][1])) fp=stdin;
  280. else fp=bb_xfopen(argv[i],"r");
  281. for(;;) {
  282. line=GET_LINE(fp);
  283. if(!line) break;
  284. if(!(linecount&63))
  285. lines=xrealloc(lines, sizeof(char *)*(linecount+64));
  286. lines[linecount++]=line;
  287. }
  288. fclose(fp);
  289. }
  290. #ifdef CONFIG_SORT_BIG
  291. /* if no key, perform alphabetic sort */
  292. if(!key_list) add_key()->range[0]=1;
  293. /* handle -c */
  294. if(global_flags&FLAG_c) {
  295. int j=(global_flags&FLAG_u) ? -1 : 0;
  296. for(i=1;i<linecount;i++)
  297. if(compare_keys(&lines[i-1],&lines[i])>j) {
  298. fprintf(stderr,"Check line %d\n",i);
  299. return 1;
  300. }
  301. return 0;
  302. }
  303. #endif
  304. /* Perform the actual sort */
  305. qsort(lines,linecount,sizeof(char *),compare_keys);
  306. /* handle -u */
  307. if(global_flags&FLAG_u) {
  308. for(flag=0,i=1;i<linecount;i++) {
  309. if(!compare_keys(&lines[flag],&lines[i])) free(lines[i]);
  310. else lines[++flag]=lines[i];
  311. }
  312. if(linecount) linecount=flag+1;
  313. }
  314. /* Print it */
  315. if(!outfile) outfile=stdout;
  316. for(i=0;i<linecount;i++) fprintf(outfile,"%s\n",lines[i]);
  317. bb_fflush_stdout_and_exit(EXIT_SUCCESS);
  318. }