40d5a16614770dd09130d0bd9e23503d8b5fbc7b
[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[100];
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 file_or_dir_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 += file_or_dir_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 file_with_size {
171   char *filename;
172   size_sum_t size;
173   struct file_with_size *next;
174 };
175
176 struct file_with_size *create(char *name, struct file_with_size *current) {
177   struct file_with_size *result;
178   result = safe_malloc(sizeof(struct file_with_size));
179   result->filename = strdup(name);
180   result->size = file_or_dir_size(name);
181   result->next = current;
182   return result;
183 }
184
185 void destroy(struct file_with_size *node) {
186   struct file_with_size *next;
187   while(node) {
188     next = node->next;
189     free(node->filename);
190     free(node);
191     node = next;
192   }
193 }
194
195 /**********************************************************************/
196
197 int compare_files(const void *x1, const void *x2) {
198   const struct file_with_size **f1, **f2;
199
200   f1 = (const struct file_with_size **) x1;
201   f2 = (const struct file_with_size **) 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 file_with_size *root, int width, int height) {
273   char line[BUFFER_SIZE];
274   struct file_with_size *node;
275   struct file_with_size **nodes;
276   int nb_nodes, n, first, last;
277
278   nb_nodes = 0;
279   for(node = root; node; node = node->next) {
280     nb_nodes++;
281   }
282
283   nodes = safe_malloc(nb_nodes * sizeof(struct file_with_size *));
284
285   n = 0;
286   for(node = root; node; node = node->next) {
287     nodes[n++] = node;
288   }
289
290   qsort(nodes, nb_nodes, sizeof(struct file_with_size *), compare_files);
291
292   first = 0;
293   last = nb_nodes;
294
295   if(forced_height) {
296     height = forced_height;
297   }
298
299   if(height >= 0 && nb_nodes > height && !show_top && !forced_height) {
300     printf("...\n");
301   }
302
303   if(height > 0 && height < nb_nodes) {
304     first = nb_nodes - height;
305   }
306
307   if(show_top) {
308     n = last;
309     last = nb_nodes - first;
310     first = nb_nodes - n;
311   }
312
313   for(n = first; n < last; n++) {
314     if(size_min < 0 || nodes[n]->size >= size_min) {
315       if(fancy_size_display) {
316         fancy_print(line, nodes[n]->filename, nodes[n]->size);
317       } else {
318         raw_print(line, nodes[n]->filename, nodes[n]->size);
319       }
320       if(width >= 0 && width < BUFFER_SIZE) {
321         line[width] = '\0';
322       }
323       printf(line);
324     }
325   }
326
327   if(height >= 0 && nb_nodes > height && show_top && !forced_height) {
328     printf("...\n");
329   }
330
331   free(nodes);
332 }
333
334 /**********************************************************************/
335
336 void print_help(FILE *out) {
337   fprintf(out, "Usage: dus [OPTION]... [FILE]...\n");
338   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
339   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");
340   fprintf(out, "\n");
341   fprintf(out, "   -d          ignore files and directories starting with a '.'\n");
342   fprintf(out, "   -f          display size with float values and K, M and G units.\n");
343   fprintf(out, "   -r          reverse the sorting order.\n");
344   fprintf(out, "   -t          show the top of the list.\n");
345   fprintf(out, "   -c <cols>   specificy the number of columns to display. The value -1\n");
346   fprintf(out, "               corresponds to no constraint. By default the command\n");
347   fprintf(out, "               uses the tty width, or no constraint if the stdout is\n");
348   fprintf(out, "               not a tty.\n");
349   fprintf(out, "   -l <lines>  same as -c for number of lines.\n");
350   fprintf(out, "   -h          show this help.\n");
351   fprintf(out, "   -m <size>   size min.\n");
352   fprintf(out, "\n");
353   fprintf(out, "Report bugs and comments to <francois@fleuret.org>\n");
354 }
355
356 /**********************************************************************/
357
358 int main(int argc, char **argv) {
359   int c;
360   struct file_with_size *root;
361   struct winsize win;
362
363   root = 0;
364
365   setlocale (LC_ALL, "");
366
367   while (1) {
368     c = getopt(argc, argv, "dfrtl:c:m:hdu");
369     if (c == -1)
370       break;
371
372     switch (c) {
373
374     case 'd':
375       ignore_dotfiles = 1;
376       break;
377
378     case 'f':
379       fancy_size_display = 1;
380       break;
381
382     case 'r':
383       reverse_sorting = 1;
384       break;
385
386     case 't':
387       show_top = 1;
388       break;
389
390     case 'l':
391       forced_height = atoi(optarg);
392       break;
393
394     case 'c':
395       forced_width = atoi(optarg);
396       break;
397
398     case 'm':
399       size_min = atoss(optarg);
400       break;
401
402     case 'h':
403       print_help(stdout);
404       exit(EXIT_SUCCESS);
405
406       break;
407
408     default:
409       print_help(stderr);
410       exit(EXIT_FAILURE);
411     }
412   }
413
414   if (optind < argc) {
415     while (optind < argc) {
416       root = create(argv[optind++], root);
417     }
418   } else {
419     DIR *dir;
420     struct dirent *dir_e;
421     dir = opendir(".");
422     if(dir) {
423       while((dir_e = readdir(dir))) {
424         if(!ignore_entry(dir_e->d_name)) {
425           root = create(dir_e->d_name, root);
426         }
427       }
428       closedir(dir);
429     } else {
430       fprintf(stderr, "Can not open ./: %s\n", strerror(errno));
431       exit (EXIT_FAILURE);
432     }
433   }
434
435   if(isatty(STDOUT_FILENO) &&
436      !ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
437     print_sorted(root, win.ws_col, win.ws_row - 2);
438   } else {
439     print_sorted(root, -1, -1);
440   }
441
442   destroy(root);
443
444   exit(EXIT_SUCCESS);
445 }