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