Cosmetics.
[finddup.git] / finddup.c
index 91079de..1ea54ce 100644 (file)
--- a/finddup.c
+++ b/finddup.c
@@ -1,7 +1,8 @@
 
 /*
- *  finddup is a simple utility to display the files and directories
- *  according to their total disk occupancy.
+ *  finddup is a simple utility to find duplicated files, files common
+ *  to several directories, or files present in one directory and not
+ *  in another one.
  *
  *  Copyright (c) 2010 Francois Fleuret
  *  Written by Francois Fleuret <francois@fleuret.org>
  *
  */
 
-#define VERSION_NUMBER "0.5"
+#define VERSION_NUMBER "0.9"
 
 #define _BSD_SOURCE
 
 #include <sys/types.h>
 #include <sys/stat.h>
+#include <sys/param.h>
 #include <dirent.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <locale.h>
 #include <getopt.h>
 #include <fcntl.h>
+#ifdef WITH_MD5
+#include <openssl/md5.h>
+#endif
 
-#define BUFFER_SIZE 4096
+/* 1M really helps compared to 64k */
+#define READ_BUFFER_SIZE (1024 * 1024)
 
 typedef int64_t size_sum_t;
 
@@ -48,12 +54,31 @@ typedef int64_t size_sum_t;
 int ignore_dotfiles = 0; /* 1 means ignore files and directories
                             starting with a dot */
 
+int ignore_empty_files = 0; /* 1 means ignore empty files */
+
 int show_realpaths = 0; /* 1 means ignore files and directories
                             starting with a dot */
 
-int show_progress = 1; /* 1 means show a progress bar when we are in a
+int show_progress = 0; /* 1 means show a progress bar when we are in a
                           tty */
 
+int show_hits = 1; /* 1 means to show the files from dir2
+                      corresponding to the ones from dir1 */
+
+int show_groups = 1; /* 1 means to show the group IDs when printing
+                        file names */
+
+int same_inodes_are_different = 0; /* 1 means that comparison between
+                                      two file with same inode will
+                                      always be false */
+
+int tty_width = -1; /* Positive value means what width to use to show
+                       the progress bar */
+
+#ifdef WITH_MD5
+int use_md5 = 0; /* 1 means we keep an MD5 signature for each file */
+#endif
+
 /********************************************************************/
 
 /* malloc with error checking.  */
@@ -73,45 +98,35 @@ 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);
+    (ignore_dotfiles && name[0] == '.' && name[1] != '/');
 }
 
 /**********************************************************************/
 
-struct file_with_size {
-  char *filename;
+struct file_node {
+  struct file_node *next;
+  char *name;
   size_t size;
   ino_t inode;
-  struct file_with_size *next;
-  int error;
+  int group_id; /* one per identical file content */
+  int dir_id; /* 1 for DIR1, and 2 for DIR2 */
+#ifdef WITH_MD5
+  int md5_computed;
+  unsigned char md5[MD5_DIGEST_LENGTH];
+#endif
 };
 
-void file_list_delete(struct file_with_size *head) {
-  struct file_with_size *next;
+void file_list_delete(struct file_node *head) {
+  struct file_node *next;
   while(head) {
     next = head->next;
-    free(head->filename);
+    free(head->name);
     free(head);
     head = next;
   }
 }
 
-int file_list_length(struct file_with_size *head) {
+int file_list_length(struct file_node *head) {
   int l = 0;
   while(head) {
     l++;
@@ -122,21 +137,36 @@ int file_list_length(struct file_with_size *head) {
 
 /**********************************************************************/
 
-int same_size(struct file_with_size *f1, struct file_with_size *f2) {
-  return f1->size == f2->size;
-}
-
-int same_content(struct file_with_size *f1, struct file_with_size *f2) {
+int same_content(struct file_node *f1, struct file_node *f2,
+                 char *buffer1, char *buffer2) {
   int fd1, fd2, s1, s2;
-  char buffer1[BUFFER_SIZE], buffer2[BUFFER_SIZE];
 
-  fd1 = open(f1->filename, O_RDONLY);
-  fd2 = open(f2->filename, O_RDONLY);
+#ifdef WITH_MD5
+  MD5_CTX c1, c2;
+
+  if(use_md5) {
+    if(f1->md5_computed && f2->md5_computed) {
+      if(!memcmp(f1->md5, f2->md5, MD5_DIGEST_LENGTH)) {
+        return 0;
+      }
+    } else {
+      if(!f1->md5_computed) {
+        MD5_Init(&c1);
+      }
+      if(!f2->md5_computed) {
+        MD5_Init(&c2);
+      }
+    }
+  }
+#endif
+
+  fd1 = open(f1->name, O_RDONLY);
+  fd2 = open(f2->name, O_RDONLY);
 
   if(fd1 >= 0 && fd2 >= 0) {
     while(1) {
-      s1 = read(fd1, buffer1, BUFFER_SIZE);
-      s2 = read(fd2, buffer2, BUFFER_SIZE);
+      s1 = read(fd1, buffer1, READ_BUFFER_SIZE);
+      s2 = read(fd2, buffer2, READ_BUFFER_SIZE);
 
       if(s1 < 0 || s2 < 0) {
         close(fd1);
@@ -148,13 +178,35 @@ int same_content(struct file_with_size *f1, struct file_with_size *f2) {
         if(s1 == 0) {
           close(fd1);
           close(fd2);
+#ifdef WITH_MD5
+          if(use_md5) {
+            if(!f1->md5_computed) {
+              MD5_Final(f1->md5, &c1);
+              f1->md5_computed = 1;
+            }
+            if(!f2->md5_computed) {
+              MD5_Final(f2->md5, &c2);
+              f2->md5_computed = 1;
+            }
+          }
+#endif
           return 1;
         } else {
-          if(strncmp(buffer1, buffer2, s1)) {
+          if(memcmp(buffer1, buffer2, s1)) {
             close(fd1);
             close(fd2);
             return 0;
           }
+#ifdef WITH_MD5
+          if(use_md5) {
+            if(!f1->md5_computed) {
+              MD5_Update(&c1, buffer1, s1);
+            }
+            if(!f2->md5_computed) {
+              MD5_Update(&c2, buffer2, s2);
+            }
+          }
+#endif
         }
       } else {
         fprintf(stderr,
@@ -163,32 +215,49 @@ int same_content(struct file_with_size *f1, struct file_with_size *f2) {
       }
     }
   } else {
-    if(fd1 >= 0) { close(fd1); }
-    if(fd2 >= 0) { close(fd2); }
-    return 0;
+
+    if(fd1 < 0) {
+      fprintf(stderr,
+              "Can not open \"%s\" error: %s\n",
+              f1->name,
+              strerror(errno));
+    }
+
+    if(fd2 < 0) {
+      fprintf(stderr,
+              "Can not open \"%s\" error: %s\n",
+              f2->name,
+              strerror(errno));
+    }
+
+    exit(EXIT_FAILURE);
   }
 }
 
-int same_files(struct file_with_size *f1, struct file_with_size *f2) {
-  return same_size(f1, f2) && same_content(f1, f2);
+int same_files(struct file_node *f1, struct file_node *f2,
+               char *buffer1, char *buffer2) {
+  if(same_inodes_are_different && f1->inode == f2->inode) {
+    return 0;
+  }
+
+  return f1->size == f2->size && same_content(f1, f2, buffer1, buffer2);
 }
 
 /**********************************************************************/
 
-struct file_with_size *scan_directory(struct file_with_size *tail,
-                                      const char *name) {
+struct file_node *scan_directory(struct file_node *tail, const char *name) {
   DIR *dir;
   struct dirent *dir_e;
-  struct stat dummy;
-  struct file_with_size *tmp;
-  char subname[PATH_MAX];
+  struct stat sb;
+  struct file_node *tmp;
+  char subname[PATH_MAX + 1];
 
-  if(lstat(name, &dummy) != 0) {
+  if(lstat(name, &sb) != 0) {
     fprintf(stderr, "Can not stat \"%s\": %s\n", name, strerror(errno));
     exit(EXIT_FAILURE);
   }
 
-  if(S_ISLNK(dummy.st_mode)) {
+  if(S_ISLNK(sb.st_mode)) {
     return tail;
   }
 
@@ -203,100 +272,299 @@ struct file_with_size *scan_directory(struct file_with_size *tail,
     }
     closedir(dir);
   } else {
-    if(S_ISREG(dummy.st_mode)) {
-      tmp = safe_malloc(sizeof(struct file_with_size));
-      tmp->next = tail;
-      tmp->filename = strdup(name);
-      tmp->size = dummy.st_size;
-      tmp->inode = dummy.st_ino;
-      tail = tmp;
+    if(S_ISREG(sb.st_mode)) {
+      if(!ignore_entry(name)) {
+        if(!ignore_empty_files || sb.st_size > 0) {
+          tmp = safe_malloc(sizeof(struct file_node));
+          tmp->next = tail;
+          tmp->name = strdup(name);
+          tmp->size = sb.st_size;
+          tmp->inode = sb.st_ino;
+          tmp->group_id = -1;
+          tmp->dir_id = -1;
+#ifdef WITH_MD5
+          tmp->md5_computed = 0;
+#endif
+          tail = tmp;
+        }
+      }
     }
   }
 
   return tail;
 }
 
+void print_file(struct file_node *node) {
+  char tmp[PATH_MAX + 1];
+  if(show_realpaths) {
+    if(realpath(node->name, tmp)) {
+      if(show_groups) {
+        printf("%d %s\n", node->group_id, tmp);
+      } else {
+        printf("%s\n", tmp);
+      }
+    } else {
+      printf("Can not get the realpath of \"%s\": %s\n",
+             node->name,
+             strerror(errno));
+      exit(EXIT_FAILURE);
+    }
+  } else {
+    if(show_groups) {
+      printf("%d %s\n", node->group_id, node->name);
+    } else {
+      printf("%s\n", node->name);
+    }
+  }
+}
+
+int compare_nodes(const void *x1, const void *x2) {
+  const struct file_node **f1, **f2;
+
+  f1 = (const struct file_node **) x1;
+  f2 = (const struct file_node **) x2;
+
+  if((*f1)->group_id < (*f2)->group_id) {
+    return -1;
+  } else if((*f1)->group_id > (*f2)->group_id) {
+    return 1;
+  } else {
+    if((*f1)->dir_id < (*f2)->dir_id) {
+      return -1;
+    } else if((*f1)->dir_id > (*f2)->dir_id) {
+      return 1;
+    } else {
+      return 0;
+    }
+  }
+}
+
+
+void print_result(struct file_node *list1, struct file_node *list2) {
+  struct file_node *node1, *node2;
+  struct file_node **nodes;
+  int nb, n;
+
+  nb = 0;
+  for(node1 = list1; node1; node1 = node1->next) {
+    if(node1->group_id >= 0) { nb++; }
+  }
+
+  if(list2) {
+    for(node2 = list2; node2; node2 = node2->next) {
+      if(node2->group_id >= 0) { nb++; }
+    }
+  }
+
+  nodes = safe_malloc(nb * sizeof(struct file_node *));
+
+  n = 0;
+  for(node1 = list1; node1; node1 = node1->next) {
+    if(node1->group_id >= 0) {
+      nodes[n++] = node1;
+    }
+  }
+
+  if(list2) {
+    for(node2 = list2; node2; node2 = node2->next) {
+      if(node2->group_id >= 0) {
+        nodes[n++] = node2;
+      }
+    }
+  }
+
+  qsort(nodes, nb, sizeof(struct file_node *), compare_nodes);
+
+  for(n = 0; n < nb; n++) {
+    if(!show_groups && n > 0 && nodes[n]->group_id != nodes[n-1]->group_id) {
+      printf("\n");
+    }
+    print_file(nodes[n]);
+  }
+
+  free(nodes);
+}
+
+void print_progress(int max, int n, int *pp) {
+  int p, k;
+  int width;
+  if(show_progress && tty_width > 0) {
+    width = tty_width - 7;
+    p = (width * n) / (max - 1);
+    if(p > *pp) {
+      for(k = 0; k < p; k++) {
+        fprintf(stderr, "+");
+      }
+      for(; k < width; k++) {
+        fprintf(stderr, "-");
+      }
+      *pp = p;
+      p = (100 * n) / (max - 1);
+      fprintf(stderr, " [%3d%%]\r", p);
+    }
+  }
+}
+
 void start(const char *dirname1, const char *dirname2) {
-  struct file_with_size *list1, *list2;
-  struct file_with_size *node1, *node2;
+  struct file_node *list1, *list2;
+  struct file_node *node1, *node2;
   int not_in, found;
+  int nb_groups, nb_nodes;
+  int list1_length, previous_progress;
+  struct winsize win;
 
-  if(strncmp(dirname2, "not:", 4) == 0) {
-    not_in = 1;
-    dirname2 += 4;
-  } else {
-    not_in = 0;
+  char *buffer1 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
+  char *buffer2 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
+
+  not_in = 0;
+
+  if(show_progress) {
+    if(isatty(STDOUT_FILENO) &&
+       !ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
+      tty_width = win.ws_col;
+    }
+    fprintf(stderr, "Scanning %s ... ", dirname1);
   }
 
   list1 = scan_directory(0, dirname1);
-  list2 = scan_directory(0, dirname2);
+
+  if(dirname2) {
+    if(strncmp(dirname2, "not:", 4) == 0) {
+      not_in = 1;
+      /* groups are not computed in the not: mode */
+      show_groups = 0;
+      dirname2 += 4;
+    } else if(strncmp(dirname2, "and:", 4) == 0) {
+      dirname2 += 4;
+    }
+    if(show_progress) {
+      fprintf(stderr, "%s ... ", dirname2);
+    }
+    list2 = scan_directory(0, dirname2);
+  } else {
+    list2 = list1;
+  }
+
+  if(show_progress) {
+    fprintf(stderr, "done.\n");
+  }
+
+  nb_groups = 0;
+  previous_progress = -1;
+  nb_nodes = 0;
+  list1_length = file_list_length(list1);
 
   if(not_in) {
     for(node1 = list1; node1; node1 = node1->next) {
+      print_progress(list1_length, nb_nodes, &previous_progress);
+      nb_nodes++;
+
       found = 0;
 
       for(node2 = list2; !found && node2; node2 = node2->next) {
-        if(node1->inode != node2->inode && same_files(node1, node2)) {
+        if(same_files(node1, node2, buffer1, buffer2)) {
           found = 1;
         }
       }
 
       if(!found) {
         if(show_realpaths) {
-          printf("%s\n", realpath(node1->filename, 0));
+          printf("%s\n", realpath(node1->name, 0));
         } else {
-          printf("%s\n", node1->filename);
+          printf("%s\n", node1->name);
         }
       }
     }
 
   } else {
-
     for(node1 = list1; node1; node1 = node1->next) {
+      print_progress(list1_length, nb_nodes, &previous_progress);
+      nb_nodes++;
+
       for(node2 = list2; node2; node2 = node2->next) {
-        if(node1->inode != node2->inode && same_files(node1, node2)) {
-          if(show_realpaths) {
-            printf("%s %s\n",
-                   realpath(node1->filename, 0),
-                   realpath(node2->filename, 0));
-          } else {
-            printf("%s %s\n", node1->filename, node2->filename);
+        if(node1->group_id < 0 || node2->group_id < 0) {
+          if(same_files(node1, node2, buffer1, buffer2)) {
+            if(node1->group_id < 0) {
+              if(node2->group_id >= 0) {
+                node1->group_id = node2->group_id;
+              } else {
+                node1->group_id = nb_groups;
+                node1->dir_id = 1;
+                nb_groups++;
+              }
+            }
+            if(node2->group_id < 0) {
+              node2->group_id = node1->group_id;
+              node2->dir_id = 2;
+            }
           }
         }
       }
     }
   }
 
-  file_list_delete(list1);
-  file_list_delete(list2);
+  if(show_progress) {
+    fprintf(stderr, "\n");
+  }
+
+  if(dirname2) {
+    print_result(list1, list2);
+    file_list_delete(list1);
+    file_list_delete(list2);
+  } else {
+    print_result(list1, 0);
+    file_list_delete(list1);
+  }
+
+  free(buffer1);
+  free(buffer2);
 }
 
 void print_help(FILE *out) {
-  fprintf(out, "Usage: finddup [OPTION]... DIR1 [[not:]DIR2]\n");
+  fprintf(out, "Usage: finddup [OPTION]... DIR1 [[and:|not:]DIR2]\n");
   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
-  fprintf(out, "Without DIR2, lists duplicate files found in DIR1. With DIR2, lists files common to both directories. With the not: prefix, lists files found in DIR1 which do not exist in DIR2.\n");
+  fprintf(out, "Without DIR2, lists duplicated files found in DIR1. With DIR2, lists files common to both directories. With the not: prefix, lists files found in DIR1 which do not exist in DIR2. The and: prefix is the default and should be used only if you have a directory starting with 'not:'\n");
   fprintf(out, "\n");
-  fprintf(out, "   -h   show this help.\n");
-  fprintf(out, "   -r   show the real file paths.\n");
+  /*            01234567890123456789012345678901234567890123456789012345678901234567890123456789*/
+  fprintf(out, "   -h, --help                 show this help\n");
+  fprintf(out, "   -d, --ignore-dots          ignore dot files and directories\n");
+  fprintf(out, "   -0, --ignore-empty         ignore empty files\n");
+  fprintf(out, "   -c, --hide-matchings       do not show which files in DIR2 corresponds to\n");
+  fprintf(out, "                              those in DIR1\n");
+  fprintf(out, "   -g, --no-group-ids         do not show the file groups\n");
+  fprintf(out, "   -p, --show-progress        show progress\n");
+  fprintf(out, "   -r, --real-paths           show the real file paths\n");
+  fprintf(out, "   -i, --same-inodes-are-different\n");
+  fprintf(out, "                              consider files with same inode as different\n");
+#ifdef WITH_MD5
+  fprintf(out, "   -m, --md5                  use MD5 hashing\n");
+#endif
   fprintf(out, "\n");
-  fprintf(out, "Report bugs and comments to <francois@fleuret.org>\n");
+  fprintf(out, "Report bugs and comments to <francois@fleuret.org>.\n");
 }
 
 /**********************************************************************/
 
+static struct option long_options[] = {
+  { "help", no_argument, 0, 'h' },
+  { "same-inodes-are-different", no_argument, 0, 'i' },
+  { "real-paths", no_argument, 0, 'r' },
+  { "hide-matchings", no_argument, 0, 'c' },
+  { "no-group-ids", no_argument, 0, 'g' },
+  { "ignore-dots", no_argument, 0, 'd' },
+  { "ignore-empty", no_argument, 0, '0' },
+  { "show-progress", no_argument, 0, 'p' },
+  { "md5", no_argument, 0, 'm' },
+  { 0, 0, 0, 0 }
+};
+
 int main(int argc, char **argv) {
   int c;
-  struct file_with_size *root;
-
-  root = 0;
 
   setlocale (LC_ALL, "");
 
-  while (1) {
-    c = getopt(argc, argv, "hr");
-    if (c == -1)
-      break;
-
+  while ((c = getopt_long(argc, argv, "hircgd0pm",
+                          long_options, NULL)) != -1) {
     switch (c) {
 
     case 'h':
@@ -305,19 +573,54 @@ int main(int argc, char **argv) {
 
       break;
 
+    case 'd':
+      ignore_dotfiles = 1;
+      break;
+
+    case '0':
+      ignore_empty_files = 1;
+      break;
+
     case 'r':
       show_realpaths = 1;
       break;
 
+    case 'i':
+      same_inodes_are_different = 1;
+      break;
+
+    case 'g':
+      show_groups = 0;
+      break;
+
+    case 'p':
+      show_progress = 1;
+      break;
+
+    case 'c':
+      show_hits = 0;
+      break;
+
+    case 'm':
+#ifdef WITH_MD5
+      use_md5 = 1;
+#else
+      fprintf(stderr,
+              "finddup has not be compiled with MD5 hashing.\n");
+      exit(EXIT_FAILURE);
+#endif
+      break;
+
     default:
       exit(EXIT_FAILURE);
     }
   }
 
-  if(optind + 1 < argc) {
+  if(optind + 2 == argc) {
     start(argv[optind], argv[optind + 1]);
-  } else if(optind < argc) {
-    start(argv[optind], argv[optind]);
+  } else if(optind + 1 == argc) {
+    same_inodes_are_different = 1;
+    start(argv[optind], 0);
   } else {
     print_help(stderr);
     exit(EXIT_FAILURE);