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