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