Print errors to stderr.
[dus.git] / dus.c
diff --git a/dus.c b/dus.c
index 4ad1fff..04147a1 100644 (file)
--- a/dus.c
+++ b/dus.c
@@ -1,24 +1,26 @@
 
-/*************************************************************************/
-/* START_IP_HEADER                                                       */
-/*                                                                       */
-/* This program is free software: you can redistribute it and/or modify  */
-/* it under the terms of the version 3 of the GNU General Public License */
-/* as published by the Free Software Foundation.                         */
-/*                                                                       */
-/* This program is distributed in the hope that it will be useful, but   */
-/* WITHOUT ANY WARRANTY; without even the implied warranty of            */
-/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      */
-/* General Public License for more details.                              */
-/*                                                                       */
-/* You should have received a copy of the GNU General Public License     */
-/* along with this program. If not, see <http://www.gnu.org/licenses/>.  */
-/*                                                                       */
-/* Written by and Copyright (C) Francois Fleuret                         */
-/* Contact <francois.fleuret@idiap.ch> for comments & bug reports        */
-/*                                                                       */
-/* END_IP_HEADER                                                         */
-/*************************************************************************/
+/*
+ *  dus is a simple utility to display the files and directories
+ *  according to their total disk occupancy.
+ *
+ *  Copyright (c) 2010 Francois Fleuret
+ *  Written by Francois Fleuret <francois@fleuret.org>
+ *
+ *  This file is part of dus.
+ *
+ *  dus is free software: you can redistribute it and/or modify it
+ *  under the terms of the GNU General Public License version 3 as
+ *  published by the Free Software Foundation.
+ *
+ *  dus is distributed in the hope that it will be useful, but WITHOUT
+ *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ *  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
+ *  License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with dus.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
 
 #define _BSD_SOURCE
 
 #include <unistd.h>
 #include <errno.h>
 #include <string.h>
+#include <sys/ioctl.h>
+#include <locale.h>
+#include <getopt.h>
 
-struct file_with_size {
-  char *filename;
-  size_t size;
-  struct file_with_size *next;
-};
+#define BUFFER_SIZE 4096
+
+typedef int64_t size_sum_t;
+
+/* Yeah, global variables! */
+
+int ignore_dotfiles = 0; /* 1 means ignore files and directories
+                            starting with a dot */
+
+int forced_width = 0; /* -1 means no width limit, strictly positive
+                         means limit, 0 means not active */
+
+int forced_height = 0; /* -1 means no height limit, strictly positive
+                           means limit, 0 means not active */
+
+int fancy_size_display = 0; /* 1 means to use floating values with K, M and G
+                               as units */
+
+int reverse_sorting = 0; /* 1 means to show the large ones first */
+
+int show_top = 0; /* 1 means to show the top of the sorted list
+                     instead of the bottom */
+
+/********************************************************************/
 
-size_t file_or_dir_size(char *name) {
+/* malloc with error checking.  */
+
+void *safe_malloc(size_t n) {
+  void *p = malloc(n);
+  if (!p && n != 0) {
+    fprintf(stderr, "Can not allocate memory: %s\n", strerror(errno));
+    exit(EXIT_FAILURE);
+  }
+  return p;
+}
+
+/********************************************************************/
+
+int ignore_entry(const char *name) {
+  return
+    strcmp(name, ".") == 0 ||
+    strcmp(name, "..") == 0 ||
+    (ignore_dotfiles && name[0] == '.');
+}
+
+void print_size_sum(size_sum_t s) {
+  char tmp[100];
+  char *a = tmp + sizeof(tmp)/sizeof(char);
+  *(--a) = '\0';
+  if(s) {
+    while(s) {
+      *(--a) = s%10 + '0';
+      s /= 10;
+    }
+  } else {
+    *(--a) = '0';
+  }
+  printf(a);
+}
+
+size_sum_t file_or_dir_size(const char *name) {
   DIR *dir;
   struct dirent *dir_e;
   struct stat dummy;
-  size_t result;
-  char subname[1024];
+  size_sum_t result;
+  char subname[BUFFER_SIZE];
 
   result = 0;
 
   if(lstat(name, &dummy) != 0) {
-    printf("Can not stat %s (%s).\n", name, strerror(errno));
-    exit (1);
+    fprintf(stderr, "Can not stat %s: %s\n", name, strerror(errno));
+    exit(EXIT_FAILURE);
   }
 
   if(S_ISLNK(dummy.st_mode)) {
@@ -59,9 +118,8 @@ size_t file_or_dir_size(char *name) {
 
   if(dir) {
     while((dir_e = readdir(dir))) {
-      if(strcmp(dir_e->d_name, ".") &&
-         strcmp(dir_e->d_name, "..")) {
-        sprintf(subname, "%s/%s", name, dir_e->d_name);
+      if(!ignore_entry(dir_e->d_name)) {
+        snprintf(subname, BUFFER_SIZE, "%s/%s", name, dir_e->d_name);
         result += file_or_dir_size(subname);
       }
     }
@@ -75,30 +133,261 @@ size_t file_or_dir_size(char *name) {
   return result;
 }
 
+/**********************************************************************/
+
+struct file_with_size {
+  char *filename;
+  size_sum_t size;
+  struct file_with_size *next;
+};
+
 struct file_with_size *create(char *name, struct file_with_size *current) {
   struct file_with_size *result;
-  result = malloc(sizeof(struct file_with_size));
+  result = safe_malloc(sizeof(struct file_with_size));
   result->filename = strdup(name);
   result->size = file_or_dir_size(name);
   result->next = current;
   return result;
 }
 
+void destroy(struct file_with_size *node) {
+  struct file_with_size *next;
+  while(node) {
+    next = node->next;
+    free(node->filename);
+    free(node);
+    node = next;
+  }
+}
+
+/**********************************************************************/
+
+int compare_files(const void *x1, const void *x2) {
+  const struct file_with_size **f1, **f2;
+
+  f1 = (const struct file_with_size **) x1;
+  f2 = (const struct file_with_size **) x2;
+
+  if(reverse_sorting) {
+    if((*f1)->size < (*f2)->size) {
+      return 1;
+    } else if((*f1)->size > (*f2)->size) {
+      return -1;
+    } else {
+      return 0;
+    }
+  } else {
+    if((*f1)->size < (*f2)->size) {
+      return -1;
+    } else if((*f1)->size > (*f2)->size) {
+      return 1;
+    } else {
+      return 0;
+    }
+  }
+}
+
+void raw_print(char *buffer, char *filename,  size_sum_t size) {
+  char *a, *b, *c, u;
+
+  b = buffer;
+  if(size) {
+    while(size) {
+      *(b++) = size%10 + '0';
+      size /= 10;
+    }
+  } else {
+    *(b++) = '0';
+  }
+
+  a = buffer;
+  c = b;
+  while(a < c) {
+    u = *a;
+    *(a++) = *(--c);
+    *c = u;
+  }
+
+  *(b++) = ' ';
+
+  sprintf(b, " %s\n", filename);
+}
+
+void fancy_print(char *buffer, char *filename, size_sum_t size) {
+  if(size < 1024) {
+    sprintf(buffer,
+            "% 7d %s\n",
+            ((int) size),
+            filename);
+  } else if(size < 1024 * 1024) {
+    sprintf(buffer,
+            "% 6.1fK %s\n",
+            ((double) (size))/(1024.0),
+            filename);
+  } else if(size < 1024 * 1024 * 1024) {
+    sprintf(buffer,
+            "% 6.1fM %s\n",
+            ((double) (size))/(1024.0 * 1024),
+            filename);
+  } else {
+    sprintf(buffer,
+            "% 6.1fG %s\n",
+            ((double) (size))/(1024.0 * 1024.0 * 1024.0),
+            filename);
+  }
+}
+
+void print_sorted(struct file_with_size *root, int width, int height) {
+  char line[BUFFER_SIZE];
+  struct file_with_size *node;
+  struct file_with_size **nodes;
+  int nb, n, first, last;
+
+  nb = 0;
+  for(node = root; node; node = node->next) {
+    nb++;
+  }
+
+  nodes = safe_malloc(nb * sizeof(struct file_with_size *));
+
+  n = 0;
+  for(node = root; node; node = node->next) {
+    nodes[n++] = node;
+  }
+
+  qsort(nodes, nb, sizeof(struct file_with_size *), compare_files);
+
+  first = 0;
+  last = nb;
+
+  if(forced_height) {
+    height = forced_height;
+  }
+
+  if(height > 0 && height < nb) {
+    first = nb - height;
+  }
+
+  if(show_top) {
+    n = last;
+    last = nb - first;
+    first = nb - n;
+  }
+
+  for(n = first; n < last; n++) {
+    if(fancy_size_display) {
+      fancy_print(line, nodes[n]->filename, nodes[n]->size);
+    } else {
+      raw_print(line, nodes[n]->filename, nodes[n]->size);
+    }
+    if(width >= 0 && width < BUFFER_SIZE) {
+      line[width] = '\0';
+    }
+    printf(line);
+  }
+
+  free(nodes);
+}
+
+/**********************************************************************/
+
 int main(int argc, char **argv) {
-  int k;
+  int c;
   struct file_with_size *root;
 
   root = 0;
-  for(k = 1; k < argc; k++) {
-    root = create(argv[k], root);
+
+  setlocale (LC_ALL, "");
+
+  while (1) {
+    c = getopt(argc, argv, "dfrtl:c:hdu");
+    if (c == -1)
+      break;
+
+    switch (c) {
+
+    case 'd':
+      ignore_dotfiles = 1;
+      break;
+
+    case 'f':
+      fancy_size_display = 1;
+      break;
+
+    case 'r':
+      reverse_sorting = 1;
+      break;
+
+    case 't':
+      show_top = 1;
+      break;
+
+    case 'l':
+      forced_height = atoi(optarg);
+      break;
+
+    case 'c':
+      forced_width = atoi(optarg);
+      break;
+
+    case 'h':
+      printf("Usage: dus [OPTION]... [FILE]...\n");
+      printf("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");
+      printf("\n");
+      printf("   -d          ignore files and directories starting with a '.'\n");
+      printf("   -f          display size with float values and K, M and G units.\n");
+      printf("   -r          reverse the sorting order.\n");
+      printf("   -t          show the top of the list.\n");
+      printf("   -c <cols>   specificy the number of columns to display. The value -1\n");
+      printf("               corresponds to no constraint. By default the command\n");
+      printf("               uses the tty width, or no constraint if the stdout is\n");
+      printf("               not a tty.\n");
+      printf("   -l <lines>  same as -c for number of lines.\n");
+      printf("   -h          show this help.\n");
+      printf("\n");
+      printf("Report bugs and comments to <francois@fleuret.org>\n");
+      exit(EXIT_SUCCESS);
+
+      break;
+
+    default:
+      exit(EXIT_FAILURE);
+    }
+  }
+
+  if (optind < argc) {
+    while (optind < argc) {
+      root = create(argv[optind++], root);
+    }
+  } else {
+    DIR *dir;
+    struct dirent *dir_e;
+    dir = opendir(".");
+    if(dir) {
+      while((dir_e = readdir(dir))) {
+        if(!ignore_entry(dir_e->d_name)) {
+          root = create(dir_e->d_name, root);
+        }
+      }
+      closedir(dir);
+    } else {
+      fprintf(stderr, "Can not open ./: %s\n", strerror(errno));
+      exit (EXIT_FAILURE);
+    }
   }
 
-  while(root) {
-    printf("%u %s\n",
-           root->size,
-           root->filename);
-    root = root->next;
+  if(isatty(STDOUT_FILENO)) {
+    struct winsize win;
+    if(ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
+      fprintf(stderr, "Can not get the tty size: %s\n", strerror(errno));
+      exit (EXIT_FAILURE);
+    }
+    print_sorted(root, win.ws_col, win.ws_row - 2);
+  } else {
+    print_sorted(root, -1, -1);
   }
 
-  exit(0);
+  destroy(root);
+
+  exit(EXIT_SUCCESS);
 }