Added an option to set a lower size bound for printing.
[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.1alpha"
26
27 #define _BSD_SOURCE
28
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <dirent.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <string.h>
37 #include <sys/ioctl.h>
38 #include <locale.h>
39 #include <getopt.h>
40
41 #define BUFFER_SIZE 4096
42
43 typedef int64_t size_sum_t;
44
45 /* Yeah, global variables! */
46
47 int ignore_dotfiles = 0; /* 1 means ignore files and directories
48                             starting with a dot */
49
50 int forced_width = 0; /* -1 means no width limit, strictly positive
51                          means limit, 0 means not active */
52
53 int forced_height = 0; /* -1 means no height limit, strictly positive
54                            means limit, 0 means not active */
55
56 int fancy_size_display = 0; /* 1 means to use floating values with K, M and G
57                                as units */
58
59 int reverse_sorting = 0; /* 1 means to show the large ones first */
60
61 int show_top = 0; /* 1 means to show the top of the sorted list
62                      instead of the bottom */
63
64 size_sum_t size_min = -1; /* -1 means no minimum size, otherwise lower
65                               bound on the size to display a
66                               file/dir */
67
68 /********************************************************************/
69
70 /* malloc with error checking.  */
71
72 void *safe_malloc(size_t n) {
73   void *p = malloc(n);
74   if (!p && n != 0) {
75     fprintf(stderr, "Can not allocate memory: %s\n", strerror(errno));
76     exit(EXIT_FAILURE);
77   }
78   return p;
79 }
80
81 /********************************************************************/
82
83 int ignore_entry(const char *name) {
84   return
85     strcmp(name, ".") == 0 ||
86     strcmp(name, "..") == 0 ||
87     (ignore_dotfiles && name[0] == '.');
88 }
89
90 void print_size_sum(size_sum_t s) {
91   char tmp[100];
92   char *a = tmp + sizeof(tmp)/sizeof(char);
93   *(--a) = '\0';
94   if(s) {
95     while(s) {
96       *(--a) = s%10 + '0';
97       s /= 10;
98     }
99   } else {
100     *(--a) = '0';
101   }
102   printf(a);
103 }
104
105 size_sum_t file_or_dir_size(const char *name) {
106   DIR *dir;
107   struct dirent *dir_e;
108   struct stat dummy;
109   size_sum_t result;
110   char subname[BUFFER_SIZE];
111
112   result = 0;
113
114   if(lstat(name, &dummy) != 0) {
115     fprintf(stderr, "Can not stat %s: %s\n", name, strerror(errno));
116     exit(EXIT_FAILURE);
117   }
118
119   if(S_ISLNK(dummy.st_mode)) {
120     return 0;
121   }
122
123   dir = opendir(name);
124
125   if(dir) {
126     while((dir_e = readdir(dir))) {
127       if(!ignore_entry(dir_e->d_name)) {
128         snprintf(subname, BUFFER_SIZE, "%s/%s", name, dir_e->d_name);
129         result += file_or_dir_size(subname);
130       }
131     }
132     closedir(dir);
133   } else {
134     if(S_ISREG(dummy.st_mode)) {
135       result += dummy.st_size;
136     }
137   }
138
139   return result;
140 }
141
142 size_sum_t atoss(const char *string) {
143   size_sum_t total, partial_total;
144   const char *c;
145   total = 0;
146   partial_total = 0;
147
148   for(c = string; *c; c++) {
149     if(*c >= '0' && *c <= '9') {
150       partial_total = 10 * partial_total + ((int) (*c - '0'));
151     } else if(*c == 'K' || *c == 'k') {
152       total += partial_total * 1024;
153       partial_total = 0;
154     } else if(*c == 'M' || *c == 'm') {
155       total += partial_total * 1024 * 1024;
156       partial_total = 0;
157     } else if(*c == 'G' || *c == 'g') {
158       total += partial_total * 1024 * 1024 * 1024;
159       partial_total = 0;
160     } else {
161       fprintf(stderr, "Syntax error in %s\n", string);
162     }
163   }
164   return total;
165 }
166
167 /**********************************************************************/
168
169 struct file_with_size {
170   char *filename;
171   size_sum_t size;
172   struct file_with_size *next;
173 };
174
175 struct file_with_size *create(char *name, struct file_with_size *current) {
176   struct file_with_size *result;
177   result = safe_malloc(sizeof(struct file_with_size));
178   result->filename = strdup(name);
179   result->size = file_or_dir_size(name);
180   result->next = current;
181   return result;
182 }
183
184 void destroy(struct file_with_size *node) {
185   struct file_with_size *next;
186   while(node) {
187     next = node->next;
188     free(node->filename);
189     free(node);
190     node = next;
191   }
192 }
193
194 /**********************************************************************/
195
196 int compare_files(const void *x1, const void *x2) {
197   const struct file_with_size **f1, **f2;
198
199   f1 = (const struct file_with_size **) x1;
200   f2 = (const struct file_with_size **) x2;
201
202   if(reverse_sorting) {
203     if((*f1)->size < (*f2)->size) {
204       return 1;
205     } else if((*f1)->size > (*f2)->size) {
206       return -1;
207     } else {
208       return 0;
209     }
210   } else {
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   }
219 }
220
221 void raw_print(char *buffer, char *filename,  size_sum_t size) {
222   char *a, *b, *c, u;
223
224   b = buffer;
225   if(size) {
226     while(size) {
227       *(b++) = size%10 + '0';
228       size /= 10;
229     }
230   } else {
231     *(b++) = '0';
232   }
233
234   a = buffer;
235   c = b;
236   while(a < c) {
237     u = *a;
238     *(a++) = *(--c);
239     *c = u;
240   }
241
242   *(b++) = ' ';
243
244   sprintf(b, " %s\n", filename);
245 }
246
247 void fancy_print(char *buffer, char *filename, size_sum_t size) {
248   if(size < 1024) {
249     sprintf(buffer,
250             "% 7d -- %s\n",
251             ((int) size),
252             filename);
253   } else if(size < 1024 * 1024) {
254     sprintf(buffer,
255             "% 6.1fK -- %s\n",
256             ((double) (size))/(1024.0),
257             filename);
258   } else if(size < 1024 * 1024 * 1024) {
259     sprintf(buffer,
260             "% 6.1fM -- %s\n",
261             ((double) (size))/(1024.0 * 1024),
262             filename);
263   } else {
264     sprintf(buffer,
265             "% 6.1fG -- %s\n",
266             ((double) (size))/(1024.0 * 1024.0 * 1024.0),
267             filename);
268   }
269 }
270
271 void print_sorted(struct file_with_size *root, int width, int height) {
272   char line[BUFFER_SIZE];
273   struct file_with_size *node;
274   struct file_with_size **nodes;
275   int nb, n, first, last;
276
277   nb = 0;
278   for(node = root; node; node = node->next) {
279     nb++;
280   }
281
282   nodes = safe_malloc(nb * sizeof(struct file_with_size *));
283
284   n = 0;
285   for(node = root; node; node = node->next) {
286     nodes[n++] = node;
287   }
288
289   qsort(nodes, nb, sizeof(struct file_with_size *), compare_files);
290
291   first = 0;
292   last = nb;
293
294   if(forced_height) {
295     height = forced_height;
296   }
297
298   if(height > 0 && height < nb) {
299     first = nb - height;
300   }
301
302   if(show_top) {
303     n = last;
304     last = nb - first;
305     first = nb - n;
306   }
307
308   for(n = first; n < last; n++) {
309     if(size_min < 0 || nodes[n]->size >= size_min) {
310       if(fancy_size_display) {
311         fancy_print(line, nodes[n]->filename, nodes[n]->size);
312       } else {
313         raw_print(line, nodes[n]->filename, nodes[n]->size);
314       }
315       if(width >= 0 && width < BUFFER_SIZE) {
316         line[width] = '\0';
317       }
318       printf(line);
319     }
320   }
321
322   free(nodes);
323 }
324 /**********************************************************************/
325 void print_help(FILE *out) {
326   fprintf(out, "Usage: dus [OPTION]... [FILE]...\n");
327   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
328   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");
329   fprintf(out, "\n");
330   fprintf(out, "   -d          ignore files and directories starting with a '.'\n");
331   fprintf(out, "   -f          display size with float values and K, M and G units.\n");
332   fprintf(out, "   -r          reverse the sorting order.\n");
333   fprintf(out, "   -t          show the top of the list.\n");
334   fprintf(out, "   -c <cols>   specificy the number of columns to display. The value -1\n");
335   fprintf(out, "               corresponds to no constraint. By default the command\n");
336   fprintf(out, "               uses the tty width, or no constraint if the stdout is\n");
337   fprintf(out, "               not a tty.\n");
338   fprintf(out, "   -l <lines>  same as -c for number of lines.\n");
339   fprintf(out, "   -h          show this help.\n");
340   fprintf(out, "   -m <size>   size min.\n");
341   fprintf(out, "\n");
342   fprintf(out, "Report bugs and comments to <francois@fleuret.org>\n");
343 }
344
345 /**********************************************************************/
346
347 int main(int argc, char **argv) {
348   int c;
349   struct file_with_size *root;
350
351   root = 0;
352
353   setlocale (LC_ALL, "");
354
355   while (1) {
356     c = getopt(argc, argv, "dfrtl:c:m:hdu");
357     if (c == -1)
358       break;
359
360     switch (c) {
361
362     case 'd':
363       ignore_dotfiles = 1;
364       break;
365
366     case 'f':
367       fancy_size_display = 1;
368       break;
369
370     case 'r':
371       reverse_sorting = 1;
372       break;
373
374     case 't':
375       show_top = 1;
376       break;
377
378     case 'l':
379       forced_height = atoi(optarg);
380       break;
381
382     case 'c':
383       forced_width = atoi(optarg);
384       break;
385
386     case 'm':
387       size_min = atoss(optarg);
388       break;
389
390     case 'h':
391       print_help(stdout);
392       exit(EXIT_SUCCESS);
393
394       break;
395
396     default:
397       print_help(stderr);
398       exit(EXIT_FAILURE);
399     }
400   }
401
402   if (optind < argc) {
403     while (optind < argc) {
404       root = create(argv[optind++], root);
405     }
406   } else {
407     DIR *dir;
408     struct dirent *dir_e;
409     dir = opendir(".");
410     if(dir) {
411       while((dir_e = readdir(dir))) {
412         if(!ignore_entry(dir_e->d_name)) {
413           root = create(dir_e->d_name, root);
414         }
415       }
416       closedir(dir);
417     } else {
418       fprintf(stderr, "Can not open ./: %s\n", strerror(errno));
419       exit (EXIT_FAILURE);
420     }
421   }
422
423   if(isatty(STDOUT_FILENO)) {
424     struct winsize win;
425     if(ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
426       fprintf(stderr, "Can not get the tty size: %s\n", strerror(errno));
427       exit (EXIT_FAILURE);
428     }
429     print_sorted(root, win.ws_col, win.ws_row - 2);
430   } else {
431     print_sorted(root, -1, -1);
432   }
433
434   destroy(root);
435
436   exit(EXIT_SUCCESS);
437 }