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