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