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