sort.c 8.8 KB

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