Cosmetics in the help and 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, "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, "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   dir = opendir(name);
110
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     if(S_ISREG(dummy.st_mode)) {
121       result += dummy.st_size;
122     }
123   }
124
125   return result;
126 }
127
128 size_sum_t atoss(const char *string) {
129   size_sum_t total, partial_total;
130   const char *c;
131   total = 0;
132   partial_total = 0;
133
134   for(c = string; *c; c++) {
135     if(*c >= '0' && *c <= '9') {
136       partial_total = 10 * partial_total + ((int) (*c - '0'));
137     } else if(*c == 'K' || *c == 'k') {
138       total += partial_total * 1024;
139       partial_total = 0;
140     } else if(*c == 'M' || *c == 'm') {
141       total += partial_total * 1024 * 1024;
142       partial_total = 0;
143     } else if(*c == 'G' || *c == 'g') {
144       total += partial_total * 1024 * 1024 * 1024;
145       partial_total = 0;
146     } else {
147       fprintf(stderr, "Syntax error in %s\n", string);
148     }
149   }
150   return total;
151 }
152
153 /**********************************************************************/
154
155 struct entry_node {
156   struct entry_node *next;
157   char *name;
158   size_sum_t size;
159 };
160
161 struct entry_node *push_entry(char *name, struct entry_node *head) {
162   struct entry_node *result;
163   result = safe_malloc(sizeof(struct entry_node));
164   result->name = strdup(name);
165   result->size = entry_size(name);
166   result->next = head;
167   return result;
168 }
169
170 struct entry_node *push_dir_content(char *name, struct entry_node *head) {
171   char subname[PATH_MAX];
172   DIR *dir;
173   struct dirent *dir_e;
174   dir = opendir(name);
175   if(dir) {
176     while((dir_e = readdir(dir))) {
177       if(!ignore_entry(dir_e->d_name)) {
178         snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
179         head = push_entry(subname, head);
180       }
181     }
182     closedir(dir);
183   } else {
184     fprintf(stderr, "Can not open directory %s: %s\n", name, strerror(errno));
185     exit (EXIT_FAILURE);
186   }
187   return head;
188 }
189
190 void destroy_entry_list(struct entry_node *node) {
191   struct entry_node *next;
192   while(node) {
193     next = node->next;
194     free(node->name);
195     free(node);
196     node = next;
197   }
198 }
199
200 /**********************************************************************/
201
202 int compare_files(const void *x1, const void *x2) {
203   const struct entry_node **f1, **f2;
204
205   f1 = (const struct entry_node **) x1;
206   f2 = (const struct entry_node **) x2;
207
208   if(reverse_sorting) {
209     if((*f1)->size < (*f2)->size) {
210       return 1;
211     } else if((*f1)->size > (*f2)->size) {
212       return -1;
213     } else {
214       return 0;
215     }
216   } else {
217     if((*f1)->size < (*f2)->size) {
218       return -1;
219     } else if((*f1)->size > (*f2)->size) {
220       return 1;
221     } else {
222       return 0;
223     }
224   }
225 }
226
227 void raw_print(char *buffer, size_t buffer_size,
228                char *filename,  size_sum_t size) {
229   char *a, *b, *c, u;
230
231   b = buffer;
232   do {
233     if(b >= buffer + buffer_size) {
234       fprintf(stderr, "Buffer overflow in raw_print (hu?!).\n");
235       exit(EXIT_FAILURE);
236     }
237     *(b++) = size%10 + '0';
238     size /= 10;
239   } while(size);
240
241   a = buffer;
242   c = b;
243   while(a < c) {
244     u = *a;
245     *(a++) = *(--c);
246     *c = u;
247   }
248
249   *(b++) = ' ';
250
251   snprintf(b, buffer_size - (b - buffer), "%s\n", filename);
252 }
253
254 void fancy_print(char *buffer, size_t buffer_size, char *filename, size_sum_t size) {
255   if(size < 1024) {
256     snprintf(buffer,
257              buffer_size,
258              "% 7d -- %s\n",
259              ((int) size),
260              filename);
261   } else if(size < 1024 * 1024) {
262     snprintf(buffer,
263              buffer_size,
264              "% 6.1fK -- %s\n",
265              ((double) (size))/(1024.0),
266              filename);
267   } else if(size < 1024 * 1024 * 1024) {
268     snprintf(buffer,
269              buffer_size,
270              "% 6.1fM -- %s\n",
271              ((double) (size))/(1024.0 * 1024),
272              filename);
273   } else {
274     snprintf(buffer,
275              buffer_size,
276              "% 6.1fG -- %s\n",
277              ((double) (size))/(1024.0 * 1024.0 * 1024.0),
278              filename);
279   }
280 }
281
282 void print_sorted(struct entry_node *root, int width, int height) {
283   char line[BUFFER_SIZE];
284   struct entry_node *node;
285   struct entry_node **nodes;
286   int nb_nodes, n, first, last;
287
288   nb_nodes = 0;
289   for(node = root; node; node = node->next) {
290     if(size_min < 0 || node->size >= size_min) {
291       nb_nodes++;
292     }
293   }
294
295   nodes = safe_malloc(nb_nodes * sizeof(struct entry_node *));
296
297   n = 0;
298   for(node = root; node; node = node->next) {
299     if(size_min < 0 || node->size >= size_min) {
300       nodes[n++] = node;
301     }
302   }
303
304   qsort(nodes, nb_nodes, sizeof(struct entry_node *), compare_files);
305
306   first = 0;
307   last = nb_nodes;
308
309   if(forced_height) {
310     height = forced_height;
311   }
312
313   if(forced_width) {
314     width = forced_width;
315   }
316
317   if(height >= 0 && nb_nodes > height && !show_top && !forced_height) {
318     printf("...\n");
319   }
320
321   if(height > 0 && height < nb_nodes) {
322     first = nb_nodes - height;
323   }
324
325   if(show_top) {
326     n = last;
327     last = nb_nodes - first;
328     first = nb_nodes - n;
329   }
330
331   /* I do not like valgrind to complain about uninitialized data */
332   if(width < BUFFER_SIZE) {
333     line[width] = '\0';
334   }
335
336   for(n = first; n < last; n++) {
337     if(fancy_size_display) {
338       fancy_print(line, BUFFER_SIZE, nodes[n]->name, nodes[n]->size);
339     } else {
340       raw_print(line, BUFFER_SIZE, nodes[n]->name, nodes[n]->size);
341     }
342     if(width >= 1 && width + 1 < BUFFER_SIZE && line[width]) {
343       line[width] = '\n';
344       line[width + 1] = '\0';
345     }
346     printf(line);
347   }
348
349   if(height >= 0 && nb_nodes > height && show_top && !forced_height) {
350     printf("...\n");
351   }
352
353   free(nodes);
354 }
355
356 /**********************************************************************/
357
358 void usage(FILE *out) {
359   fprintf(out, "Usage: dus [OPTION]... [FILE]...\n");
360   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
361   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");
362   fprintf(out, "\n");
363   /*            01234567890123456789012345678901234567890123456789012345678901234567890123456789*/
364   fprintf(out, "   -d, --ignore-dots          ignore files and directories starting with a '.'\n");
365   fprintf(out, "   -f, --fancy                display size with float values and K, M and G\n");
366   fprintf(out, "                              units.\n");
367   fprintf(out, "   -r, --reverse-order        reverse the sorting order.\n");
368   fprintf(out, "   -t, --show-top             show the top of the list.\n");
369   fprintf(out, "   -c <cols>, --nb-columns <cols>\n");
370   fprintf(out, "                              specificy the number of columns to display. The\n");
371   fprintf(out, "                              value -1 corresponds to no constraint. By default\n");
372   fprintf(out, "                              the command uses the tty width, or no constraint\n");
373   fprintf(out, "                              if the stdout is not a tty.\n");
374   fprintf(out, "   -l <lines>, --nb-lines <lines>\n");
375   fprintf(out, "                              same as -c for number of lines.\n");
376   fprintf(out, "   -h, --help                 show this help.\n");
377   fprintf(out, "   -m <size>, --size-min <size>\n");
378   fprintf(out, "                              set the listed entries minimum size.\n");
379   fprintf(out, "\n");
380   fprintf(out, "Report bugs and comments to <francois@fleuret.org>.\n");
381 }
382
383 /**********************************************************************/
384
385 static struct option long_options[] = {
386   { "ignore-dots", no_argument, 0, 'd' },
387   { "reverse-order", no_argument, 0, 'r' },
388   { "show-top", no_argument, 0, 't' },
389   { "help", no_argument, 0, 'h' },
390   { "fancy", no_argument, 0, 'f' },
391   { "nb-columns", 1, 0, 'c' },
392   { "nb-lines", 1, 0, 'l' },
393   { "size-min", 1, 0, 'm' },
394   { 0, 0, 0, 0 }
395 };
396
397 int main(int argc, char **argv) {
398   int c, l;
399   struct entry_node *root;
400   struct winsize win;
401
402   root = 0;
403
404   setlocale (LC_ALL, "");
405
406   while ((c = getopt_long(argc, argv, "dfrtl:c:m:hd",
407                           long_options, NULL)) != -1) {
408     switch (c) {
409
410     case 'd':
411       ignore_dotfiles = 1;
412       break;
413
414     case 'f':
415       fancy_size_display = 1;
416       break;
417
418     case 'r':
419       reverse_sorting = 1;
420       break;
421
422     case 't':
423       show_top = 1;
424       break;
425
426     case 'l':
427       forced_height = atoi(optarg);
428       break;
429
430     case 'c':
431       forced_width = atoi(optarg);
432       break;
433
434     case 'm':
435       size_min = atoss(optarg);
436       break;
437
438     case 'h':
439       usage(stdout);
440       exit(EXIT_SUCCESS);
441
442       break;
443
444     default:
445       usage(stderr);
446       exit(EXIT_FAILURE);
447     }
448   }
449
450   if (optind < argc) {
451     while (optind < argc) {
452       l = strlen(argv[optind]);
453       if(l > 0 && argv[optind][l - 1] == '/') {
454         argv[optind][l - 1] = '\0';
455         root = push_dir_content(argv[optind++], root);
456       } else {
457         root = push_entry(argv[optind++], root);
458       }
459     }
460   } else {
461     root = push_dir_content(".", root);
462   }
463
464   if(isatty(STDOUT_FILENO) &&
465      !ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
466     print_sorted(root, win.ws_col, win.ws_row - 2);
467   } else {
468     print_sorted(root, -1, -1);
469   }
470
471   destroy_entry_list(root);
472
473   exit(EXIT_SUCCESS);
474 }