Added the -v option in the help and the man page.
[dus.git] / dus.c
1
2 /*
3  *  dus is a simple utility to display the files and directories
4  *  according to their total disk occupancy.
5  *
6  *  Copyright (c) 2010 Francois Fleuret
7  *  Written by Francois Fleuret <francois@fleuret.org>
8  *
9  *  This file is part of dus.
10  *
11  *  dus is free software: you can redistribute it and/or modify it
12  *  under the terms of the GNU General Public License version 3 as
13  *  published by the Free Software Foundation.
14  *
15  *  dus is distributed in the hope that it will be useful, but WITHOUT
16  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  *  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
18  *  License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with dus.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #define VERSION_NUMBER "1.2"
26
27 #define _BSD_SOURCE
28
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <sys/param.h>
32 #include <dirent.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <unistd.h>
36 #include <errno.h>
37 #include <string.h>
38 #include <sys/ioctl.h>
39 #include <locale.h>
40 #include <getopt.h>
41
42 #define BUFFER_SIZE 4096
43
44 typedef int64_t size_sum_t;
45
46 /* Yeah, global variables! */
47
48 int ignore_dotfiles = 0; /* 1 means ignore files and directories
49                             starting with a dot */
50
51 int forced_width = 0; /* -1 means no width limit, strictly positive
52                          means limit, 0 means not active */
53
54 int forced_height = 0; /* -1 means no height limit, strictly positive
55                            means limit, 0 means not active */
56
57 int fancy_size_display = 0; /* 1 means to use floating values with K, M and G
58                                as units */
59
60 int reverse_sorting = 0; /* 1 means to show the large ones first */
61
62 int show_top = 0; /* 1 means to show the top of the sorted list
63                      instead of the bottom */
64
65 size_sum_t size_min = -1; /* -1 means no minimum size, otherwise lower
66                               bound on the size to display a
67                               file/dir */
68
69 /********************************************************************/
70
71 /* malloc with error checking.  */
72
73 void *safe_malloc(size_t n) {
74   void *p = malloc(n);
75   if (!p && n != 0) {
76     fprintf(stderr, "dus: Can not allocate memory: %s\n", strerror(errno));
77     exit(EXIT_FAILURE);
78   }
79   return p;
80 }
81
82 /********************************************************************/
83
84 int ignore_entry(const char *name) {
85   return
86     strcmp(name, ".") == 0 ||
87     strcmp(name, "..") == 0 ||
88     (ignore_dotfiles && name[0] == '.' && name[1] != '/');
89 }
90
91 size_sum_t entry_size(const char *name) {
92   DIR *dir;
93   struct dirent *dir_e;
94   struct stat dummy;
95   size_sum_t result;
96   char subname[PATH_MAX];
97
98   result = 0;
99
100   if(lstat(name, &dummy) != 0) {
101     fprintf(stderr, "dus: Can not stat %s: %s\n", name, strerror(errno));
102     exit(EXIT_FAILURE);
103   }
104
105   if(S_ISLNK(dummy.st_mode)) {
106     return 0;
107   }
108
109   if(S_ISDIR(dummy.st_mode)) {
110     dir = opendir(name);
111     if(dir) {
112       while((dir_e = readdir(dir))) {
113         if(!ignore_entry(dir_e->d_name)) {
114           snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
115           result += entry_size(subname);
116         }
117       }
118       closedir(dir);
119     } else {
120       fprintf(stderr, "dus: Can not open directory %s: %s\n", name, strerror(errno));
121       exit(EXIT_FAILURE);
122     }
123   } else if(S_ISREG(dummy.st_mode)) {
124     result += dummy.st_size;
125   }
126
127   return result;
128 }
129
130 size_sum_t atoss(const char *string) {
131   size_sum_t total, partial_total;
132   const char *c;
133   total = 0;
134   partial_total = 0;
135
136   for(c = string; *c; c++) {
137     if(*c >= '0' && *c <= '9') {
138       partial_total = 10 * partial_total + ((int) (*c - '0'));
139     } else if(*c == 'B' || *c == 'b') {
140       total += partial_total;
141       partial_total = 0;
142     } else if(*c == 'K' || *c == 'k') {
143       total += partial_total * 1024;
144       partial_total = 0;
145     } else if(*c == 'M' || *c == 'm') {
146       total += partial_total * 1024 * 1024;
147       partial_total = 0;
148     } else if(*c == 'G' || *c == 'g') {
149       total += partial_total * 1024 * 1024 * 1024;
150       partial_total = 0;
151     } else {
152       fprintf(stderr, "dus: Syntax error in size specification `%s'\n", string);
153       exit(EXIT_FAILURE);
154     }
155   }
156
157   total += partial_total;
158
159   return total;
160 }
161
162 /**********************************************************************/
163
164 struct entry_node {
165   struct entry_node *next;
166   char *name;
167   size_sum_t size;
168 };
169
170 struct entry_node *push_entry(char *name, struct entry_node *head) {
171   struct entry_node *result;
172   result = safe_malloc(sizeof(struct entry_node));
173   result->name = strdup(name);
174   result->size = entry_size(name);
175   result->next = head;
176   return result;
177 }
178
179 struct entry_node *push_dir_content(char *name, struct entry_node *head) {
180   char subname[PATH_MAX];
181   DIR *dir;
182   struct dirent *dir_e;
183   dir = opendir(name);
184   if(dir) {
185     while((dir_e = readdir(dir))) {
186       if(!ignore_entry(dir_e->d_name)) {
187         snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
188         head = push_entry(subname, head);
189       }
190     }
191     closedir(dir);
192   } else {
193     fprintf(stderr, "dus: Can not open directory %s: %s\n", name, strerror(errno));
194     exit (EXIT_FAILURE);
195   }
196   return head;
197 }
198
199 void destroy_entry_list(struct entry_node *node) {
200   struct entry_node *next;
201   while(node) {
202     next = node->next;
203     free(node->name);
204     free(node);
205     node = next;
206   }
207 }
208
209 /**********************************************************************/
210
211 int compare_files(const void *x1, const void *x2) {
212   const struct entry_node **f1, **f2;
213
214   f1 = (const struct entry_node **) x1;
215   f2 = (const struct entry_node **) x2;
216
217   if(reverse_sorting) {
218     if((*f1)->size < (*f2)->size) {
219       return 1;
220     } else if((*f1)->size > (*f2)->size) {
221       return -1;
222     } else {
223       return 0;
224     }
225   } else {
226     if((*f1)->size < (*f2)->size) {
227       return -1;
228     } else if((*f1)->size > (*f2)->size) {
229       return 1;
230     } else {
231       return 0;
232     }
233   }
234 }
235
236 void raw_print(char *buffer, size_t buffer_size,
237                char *filename,  size_sum_t size) {
238   char *a, *b, *c, u;
239
240   b = buffer;
241   do {
242     if(b >= buffer + buffer_size) {
243       fprintf(stderr, "dus: Buffer overflow in raw_print (hu?!).\n");
244       exit(EXIT_FAILURE);
245     }
246     *(b++) = size%10 + '0';
247     size /= 10;
248   } while(size);
249
250   a = buffer;
251   c = b;
252   while(a < c) {
253     u = *a;
254     *(a++) = *(--c);
255     *c = u;
256   }
257
258   *(b++) = ' ';
259
260   snprintf(b, buffer_size - (b - buffer), "%s\n", filename);
261 }
262
263 void fancy_print(char *buffer, size_t buffer_size,
264                  char *filename, size_sum_t size) {
265   if(size < 1024) {
266     snprintf(buffer,
267              buffer_size,
268              "% 8d -- %s\n",
269              ((int) size),
270              filename);
271   } else if(size < 1024 * 1024) {
272     snprintf(buffer,
273              buffer_size,
274              "% 7.1fK -- %s\n",
275              ((double) (size))/(1024.0),
276              filename);
277   } else if(size < 1024 * 1024 * 1024) {
278     snprintf(buffer,
279              buffer_size,
280              "% 7.1fM -- %s\n",
281              ((double) (size))/(1024.0 * 1024),
282              filename);
283   } else {
284     snprintf(buffer,
285              buffer_size,
286              "% 7.1fG -- %s\n",
287              ((double) (size))/(1024.0 * 1024.0 * 1024.0),
288              filename);
289   }
290 }
291
292 void print_sorted(struct entry_node *root, int width, int height) {
293   char line[BUFFER_SIZE];
294   struct entry_node *node;
295   struct entry_node **nodes;
296   int nb_nodes, n, first, last;
297
298   nb_nodes = 0;
299   for(node = root; node; node = node->next) {
300     if(size_min < 0 || node->size >= size_min) {
301       nb_nodes++;
302     }
303   }
304
305   nodes = safe_malloc(nb_nodes * sizeof(struct entry_node *));
306
307   n = 0;
308   for(node = root; node; node = node->next) {
309     if(size_min < 0 || node->size >= size_min) {
310       nodes[n++] = node;
311     }
312   }
313
314   qsort(nodes, nb_nodes, sizeof(struct entry_node *), compare_files);
315
316   first = 0;
317   last = nb_nodes;
318
319   if(forced_height) {
320     height = forced_height;
321   }
322
323   if(forced_width) {
324     width = forced_width;
325   }
326
327   if(height >= 0 && nb_nodes > height && !show_top && !forced_height) {
328     printf("...\n");
329   }
330
331   if(height > 0 && height < nb_nodes) {
332     first = nb_nodes - height;
333   }
334
335   if(show_top) {
336     n = last;
337     last = nb_nodes - first;
338     first = nb_nodes - n;
339   }
340
341   /* I do not like valgrind to complain about uninitialized data */
342   if(width < BUFFER_SIZE) {
343     line[width] = '\0';
344   }
345
346   for(n = first; n < last; n++) {
347     if(fancy_size_display) {
348       fancy_print(line, BUFFER_SIZE, nodes[n]->name, nodes[n]->size);
349     } else {
350       raw_print(line, BUFFER_SIZE, nodes[n]->name, nodes[n]->size);
351     }
352     if(width >= 1 && width + 1 < BUFFER_SIZE && line[width]) {
353       line[width] = '\n';
354       line[width + 1] = '\0';
355     }
356     printf(line);
357   }
358
359   if(height >= 0 && nb_nodes > height && show_top && !forced_height) {
360     printf("...\n");
361   }
362
363   free(nodes);
364 }
365
366 /**********************************************************************/
367
368 void usage(FILE *out) {
369   fprintf(out, "Usage: dus [OPTION]... [FILE]...\n");
370   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
371   fprintf(out, "Lists files and directories according to their size. The sizes are computed by summing recursively exact file sizes through directories. If a given directory has its name appended with '/', it is not listed, but the elements it contains are. If no files or directories are provided as arguments, the current directory is used as default.\n");
372   fprintf(out, "\n");
373   /*            01234567890123456789012345678901234567890123456789012345678901234567890123456789*/
374   fprintf(out, "   -h, --help                 show this help.\n");
375   fprintf(out, "   -v, --version              prints the version number and exit\n");
376   fprintf(out, "   -d, --ignore-dots          ignore files and directories starting with a '.'\n");
377   fprintf(out, "   -f, --fancy                display size with float values and K, M and G\n");
378   fprintf(out, "                              units.\n");
379   fprintf(out, "   -r, --reverse-order        reverse the sorting order.\n");
380   fprintf(out, "   -t, --show-top             show the top of the list.\n");
381   fprintf(out, "   -c <cols>, --nb-columns <cols>\n");
382   fprintf(out, "                              specificy the number of columns to display. The\n");
383   fprintf(out, "                              value -1 corresponds to no constraint. By default\n");
384   fprintf(out, "                              the command uses the tty width, or no constraint\n");
385   fprintf(out, "                              if the stdout is not a tty.\n");
386   fprintf(out, "   -l <lines>, --nb-lines <lines>\n");
387   fprintf(out, "                              same as -c for number of lines.\n");
388   fprintf(out, "   -m <size>, --size-min <size>\n");
389   fprintf(out, "                              set the listed entries minimum size. The size\n");
390   fprintf(out, "                              can be specified using the G, M, K, and B units.\n");
391   fprintf(out, "\n");
392   fprintf(out, "Report bugs and comments to <francois@fleuret.org>.\n");
393 }
394
395 /**********************************************************************/
396
397 static struct option long_options[] = {
398   { "version", no_argument, 0, 'v' },
399   { "ignore-dots", no_argument, 0, 'd' },
400   { "reverse-order", no_argument, 0, 'r' },
401   { "show-top", no_argument, 0, 't' },
402   { "help", no_argument, 0, 'h' },
403   { "fancy", no_argument, 0, 'f' },
404   { "nb-columns", 1, 0, 'c' },
405   { "nb-lines", 1, 0, 'l' },
406   { "size-min", 1, 0, 'm' },
407   { 0, 0, 0, 0 }
408 };
409
410 int main(int argc, char **argv) {
411   int c, l;
412   struct entry_node *root;
413   struct winsize win;
414
415   root = 0;
416
417   setlocale (LC_ALL, "");
418
419   while ((c = getopt_long(argc, argv, "vdfrtl:c:m:hd",
420                           long_options, NULL)) != -1) {
421     switch (c) {
422
423     case 'v':
424       printf("dus version %s (%s)\n", VERSION_NUMBER, UNAME);
425       exit(EXIT_SUCCESS);
426       break;
427
428     case 'd':
429       ignore_dotfiles = 1;
430       break;
431
432     case 'f':
433       fancy_size_display = 1;
434       break;
435
436     case 'r':
437       reverse_sorting = 1;
438       break;
439
440     case 't':
441       show_top = 1;
442       break;
443
444     case 'l':
445       forced_height = atoi(optarg);
446       break;
447
448     case 'c':
449       forced_width = atoi(optarg);
450       break;
451
452     case 'm':
453       size_min = atoss(optarg);
454       break;
455
456     case 'h':
457       usage(stdout);
458       exit(EXIT_SUCCESS);
459
460       break;
461
462     default:
463       usage(stderr);
464       exit(EXIT_FAILURE);
465     }
466   }
467
468   if (optind < argc) {
469     while (optind < argc) {
470       l = strlen(argv[optind]);
471       if(l > 0 && argv[optind][l - 1] == '/') {
472         argv[optind][l - 1] = '\0';
473         root = push_dir_content(argv[optind++], root);
474       } else {
475         root = push_entry(argv[optind++], root);
476       }
477     }
478   } else {
479     root = push_dir_content(".", root);
480   }
481
482   if(isatty(STDOUT_FILENO) &&
483      !ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
484     print_sorted(root, win.ws_col, win.ws_row - 2);
485   } else {
486     print_sorted(root, -1, -1);
487   }
488
489   destroy_entry_list(root);
490
491   exit(EXIT_SUCCESS);
492 }