Added long options.
[finddup.git] / finddup.c
1
2 /*
3  *  finddup is a simple utility to find duplicated files, files common
4  *  to several directories, or files present in one directory and not
5  *  in another one.
6  *
7  *  Copyright (c) 2010 Francois Fleuret
8  *  Written by Francois Fleuret <francois@fleuret.org>
9  *
10  *  This file is part of finddup.
11  *
12  *  finddup is free software: you can redistribute it and/or modify it
13  *  under the terms of the GNU General Public License version 3 as
14  *  published by the Free Software Foundation.
15  *
16  *  finddup is distributed in the hope that it will be useful, but WITHOUT
17  *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18  *  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
19  *  License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License
22  *  along with finddup.  If not, see <http://www.gnu.org/licenses/>.
23  *
24  */
25
26 #define VERSION_NUMBER "0.7"
27
28 #define _BSD_SOURCE
29
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <sys/param.h>
33 #include <dirent.h>
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <unistd.h>
37 #include <errno.h>
38 #include <string.h>
39 #include <sys/ioctl.h>
40 #include <locale.h>
41 #include <getopt.h>
42 #include <fcntl.h>
43
44 /* 1M really helps compared to 64k */
45 #define READ_BUFFER_SIZE (1024 * 1024)
46
47 typedef int64_t size_sum_t;
48
49 /* Yeah, global variables! */
50
51 int ignore_dotfiles = 0; /* 1 means ignore files and directories
52                             starting with a dot */
53
54 int ignore_empty_files = 0; /* 1 means ignore empty files */
55
56 int show_realpaths = 0; /* 1 means ignore files and directories
57                             starting with a dot */
58
59 int show_progress = 0; /* 1 means show a progress bar when we are in a
60                           tty */
61
62 int show_hits = 1; /* 1 means to show the files from dir2
63                       corresponding to the ones from dir1 */
64
65 int show_groups = 1; /* 1 means to show the group IDs when printing
66                         file names */
67
68 int ignore_same_inode = 0; /* 1 means that comparison between two file
69                               with same inode will always be false */
70
71 int tty_width = -1; /* Positive value means what width to use to show
72                        the progress bar */
73
74 /********************************************************************/
75
76 /* malloc with error checking.  */
77
78 void *safe_malloc(size_t n) {
79   void *p = malloc(n);
80   if (!p && n != 0) {
81     printf("Can not allocate memory: %s\n", strerror(errno));
82     exit(EXIT_FAILURE);
83   }
84   return p;
85 }
86
87 /********************************************************************/
88
89 int ignore_entry(const char *name) {
90   return
91     strcmp(name, ".") == 0 ||
92     strcmp(name, "..") == 0 ||
93     (ignore_dotfiles && name[0] == '.');
94 }
95
96 /**********************************************************************/
97
98 struct file_with_size {
99   char *filename;
100   size_t size;
101   ino_t inode;
102   struct file_with_size *next;
103   int group_id, dir_id;
104 };
105
106 void file_list_delete(struct file_with_size *head) {
107   struct file_with_size *next;
108   while(head) {
109     next = head->next;
110     free(head->filename);
111     free(head);
112     head = next;
113   }
114 }
115
116 int file_list_length(struct file_with_size *head) {
117   int l = 0;
118   while(head) {
119     l++;
120     head = head->next;
121   }
122   return l;
123 }
124
125 /**********************************************************************/
126
127 int same_content(struct file_with_size *f1, struct file_with_size *f2,
128                  char *buffer1, char *buffer2) {
129   int fd1, fd2, s1, s2;
130
131   fd1 = open(f1->filename, O_RDONLY);
132   fd2 = open(f2->filename, O_RDONLY);
133
134   if(fd1 >= 0 && fd2 >= 0) {
135     while(1) {
136       s1 = read(fd1, buffer1, READ_BUFFER_SIZE);
137       s2 = read(fd2, buffer2, READ_BUFFER_SIZE);
138
139       if(s1 < 0 || s2 < 0) {
140         close(fd1);
141         close(fd2);
142         return 0;
143       }
144
145       if(s1 == s2) {
146         if(s1 == 0) {
147           close(fd1);
148           close(fd2);
149           return 1;
150         } else {
151           if(memcmp(buffer1, buffer2, s1)) {
152             close(fd1);
153             close(fd2);
154             return 0;
155           }
156         }
157       } else {
158         fprintf(stderr,
159                 "Different read size without error on files of same size.\n");
160         exit(EXIT_FAILURE);
161       }
162     }
163   } else {
164
165     if(fd1 < 0) {
166       fprintf(stderr,
167               "Can not open \"%s\" error: %s\n",
168               f1->filename,
169               strerror(errno));
170     }
171
172     if(fd2 < 0) {
173       fprintf(stderr,
174               "Can not open \"%s\" error: %s\n",
175               f2->filename,
176               strerror(errno));
177     }
178     exit(EXIT_FAILURE);
179   }
180 }
181
182 int same_files(struct file_with_size *f1, struct file_with_size *f2,
183                char *buffer1, char *buffer2) {
184   if(ignore_same_inode && f1->inode == f2->inode) {
185     return 0;
186   }
187   return f1->size == f2->size && same_content(f1, f2, buffer1, buffer2);
188 }
189
190 /**********************************************************************/
191
192 struct file_with_size *scan_directory(struct file_with_size *tail,
193                                       const char *name) {
194   DIR *dir;
195   struct dirent *dir_e;
196   struct stat sb;
197   struct file_with_size *tmp;
198   char subname[PATH_MAX + 1];
199
200   if(lstat(name, &sb) != 0) {
201     fprintf(stderr, "Can not stat \"%s\": %s\n", name, strerror(errno));
202     exit(EXIT_FAILURE);
203   }
204
205   if(S_ISLNK(sb.st_mode)) {
206     return tail;
207   }
208
209   dir = opendir(name);
210
211   if(dir) {
212     while((dir_e = readdir(dir))) {
213       if(!ignore_entry(dir_e->d_name)) {
214         snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
215         tail = scan_directory(tail, subname);
216       }
217     }
218     closedir(dir);
219   } else {
220     if(S_ISREG(sb.st_mode)) {
221       if(!ignore_entry(name)) {
222         if(!ignore_empty_files || sb.st_size > 0) {
223           tmp = safe_malloc(sizeof(struct file_with_size));
224           tmp->next = tail;
225           tmp->filename = strdup(name);
226           tmp->size = sb.st_size;
227           tmp->inode = sb.st_ino;
228           tmp->group_id = -1;
229           tmp->dir_id = -1;
230           tail = tmp;
231         }
232       }
233     }
234   }
235
236   return tail;
237 }
238
239 void print_file(struct file_with_size *node) {
240   char tmp[PATH_MAX + 1];
241   if(show_realpaths) {
242     if(realpath(node->filename, tmp)) {
243       if(show_groups) {
244         printf("%d %s\n", node->group_id, tmp);
245       } else {
246         printf("%s\n", tmp);
247       }
248     } else {
249       printf("Can not get the realpath of \"%s\": %s\n",
250              node->filename,
251              strerror(errno));
252       exit(EXIT_FAILURE);
253     }
254   } else {
255     if(show_groups) {
256       printf("%d %s\n", node->group_id, node->filename);
257     } else {
258       printf("%s\n", node->filename);
259     }
260   }
261 }
262
263 int compare_nodes(const void *x1, const void *x2) {
264   const struct file_with_size **f1, **f2;
265
266   f1 = (const struct file_with_size **) x1;
267   f2 = (const struct file_with_size **) x2;
268
269   if((*f1)->group_id < (*f2)->group_id) {
270     return -1;
271   } else if((*f1)->group_id > (*f2)->group_id) {
272     return 1;
273   } else {
274     if((*f1)->dir_id < (*f2)->dir_id) {
275       return -1;
276     } else if((*f1)->dir_id > (*f2)->dir_id) {
277       return 1;
278     } else {
279       return 0;
280     }
281   }
282 }
283
284
285 void print_result(struct file_with_size *list1, struct file_with_size *list2) {
286   struct file_with_size *node1, *node2;
287   struct file_with_size **nodes;
288   int nb, n;
289
290   nb = 0;
291   for(node1 = list1; node1; node1 = node1->next) {
292     if(node1->group_id >= 0) { nb++; }
293   }
294
295   if(list2) {
296     for(node2 = list2; node2; node2 = node2->next) {
297       if(node2->group_id >= 0) { nb++; }
298     }
299   }
300
301   nodes = safe_malloc(nb * sizeof(struct file_with_size *));
302
303   n = 0;
304   for(node1 = list1; node1; node1 = node1->next) {
305     if(node1->group_id >= 0) {
306       nodes[n++] = node1;
307     }
308   }
309
310   if(list2) {
311     for(node2 = list2; node2; node2 = node2->next) {
312       if(node2->group_id >= 0) {
313         nodes[n++] = node2;
314       }
315     }
316   }
317
318   qsort(nodes, nb, sizeof(struct file_with_size *), compare_nodes);
319
320   for(n = 0; n < nb; n++) {
321     if(!show_groups && n > 0 && nodes[n]->group_id != nodes[n-1]->group_id) {
322       printf("\n");
323     }
324     print_file(nodes[n]);
325   }
326
327   free(nodes);
328 }
329
330 void print_progress(int max, int n, int *pp) {
331   int p, k;
332   int width;
333   if(show_progress && tty_width > 0) {
334     width = tty_width - 7;
335     p = (width * n) / (max - 1);
336     if(p > *pp) {
337       for(k = 0; k < p; k++) {
338         fprintf(stderr, "+");
339       }
340       for(; k < width; k++) {
341         fprintf(stderr, "-");
342       }
343       *pp = p;
344       p = (100 * n) / (max - 1);
345       fprintf(stderr, " [%3d%%]\r", p);
346     }
347   }
348 }
349
350 void start(const char *dirname1, const char *dirname2) {
351   struct file_with_size *list1, *list2;
352   struct file_with_size *node1, *node2;
353   int not_in, found;
354   int nb_groups, nb_nodes;
355   int list1_length, previous_progress;
356
357   char *buffer1 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
358   char *buffer2 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
359
360   not_in = 0;
361
362   if(show_progress) {
363     fprintf(stderr, "Scanning %s ... ", dirname1);
364   }
365
366   list1 = scan_directory(0, dirname1);
367
368   if(dirname2) {
369     if(strncmp(dirname2, "not:", 4) == 0) {
370       not_in = 1;
371       /* groups are not computed in the not: mode */
372       show_groups = 0;
373       dirname2 += 4;
374     } else if(strncmp(dirname2, "and:", 4) == 0) {
375       dirname2 += 4;
376     }
377     if(show_progress) {
378       fprintf(stderr, "%s ... ", dirname2);
379     }
380     list2 = scan_directory(0, dirname2);
381   } else {
382     list2 = list1;
383   }
384
385   if(show_progress) {
386     fprintf(stderr, "done.\n");
387   }
388
389   nb_groups = 0;
390   previous_progress = -1;
391   nb_nodes = 0;
392   list1_length = file_list_length(list1);
393
394   if(not_in) {
395     for(node1 = list1; node1; node1 = node1->next) {
396       print_progress(list1_length, nb_nodes, &previous_progress);
397       nb_nodes++;
398
399       found = 0;
400
401       for(node2 = list2; !found && node2; node2 = node2->next) {
402         if(same_files(node1, node2, buffer1, buffer2)) {
403           found = 1;
404         }
405       }
406
407       if(!found) {
408         if(show_realpaths) {
409           printf("%s\n", realpath(node1->filename, 0));
410         } else {
411           printf("%s\n", node1->filename);
412         }
413       }
414     }
415
416   } else {
417     for(node1 = list1; node1; node1 = node1->next) {
418       print_progress(list1_length, nb_nodes, &previous_progress);
419       nb_nodes++;
420
421       for(node2 = list2; node2; node2 = node2->next) {
422         if(node1->group_id < 0 || node2->group_id < 0) {
423           if(same_files(node1, node2, buffer1, buffer2)) {
424             if(node1->group_id < 0) {
425               if(node2->group_id >= 0) {
426                 node1->group_id = node2->group_id;
427               } else {
428                 node1->group_id = nb_groups;
429                 node1->dir_id = 1;
430                 nb_groups++;
431               }
432             }
433             if(node2->group_id < 0) {
434               node2->group_id = node1->group_id;
435               node2->dir_id = 2;
436             }
437           }
438         }
439       }
440     }
441   }
442
443   if(show_progress) {
444     fprintf(stderr, "\n");
445   }
446
447   if(dirname2) {
448     print_result(list1, list2);
449     file_list_delete(list1);
450     file_list_delete(list2);
451   } else {
452     print_result(list1, 0);
453     file_list_delete(list1);
454   }
455
456   free(buffer1);
457   free(buffer2);
458 }
459
460 void print_help(FILE *out) {
461   fprintf(out, "Usage: finddup [OPTION]... DIR1 [[and:|not:]DIR2]\n");
462   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
463   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");
464   fprintf(out, "\n");
465   fprintf(out, "   -h, --help\n");
466   fprintf(out, "        show this help\n");
467   fprintf(out, "   -d, --ignore-dots\n");
468   fprintf(out, "        ignore dot files and directories\n");
469   fprintf(out, "   -0, --ignore-empty\n");
470   fprintf(out, "        ignore empty files\n");
471   fprintf(out, "   -c, --hide-matchings\n");
472   fprintf(out, "        do not show which files in DIR2 corresponds to those in DIR1\n");
473   fprintf(out, "   -g, --no-group-ids\n");
474   fprintf(out, "        do not show the file groups\n");
475   fprintf(out, "   -p, --show-progress\n");
476   fprintf(out, "        show progress\n");
477   fprintf(out, "   -r, --real-paths\n");
478   fprintf(out, "        show the real file paths\n");
479   fprintf(out, "   -i, --same-inodes-are-different\n");
480   fprintf(out, "        consider files with same inode as different\n");
481   fprintf(out, "\n");
482   fprintf(out, "Report bugs and comments to <francois@fleuret.org>\n");
483 }
484
485 /**********************************************************************/
486
487 int main(int argc, char **argv) {
488   int c;
489   struct file_with_size *root;
490   struct winsize win;
491
492   root = 0;
493
494   setlocale (LC_ALL, "");
495
496   while (1) {
497     int option_index = 0;
498     static struct option long_options[] = {
499       { "help", no_argument, 0, 'h' },
500       { "same-inodes-are-different", no_argument, 0, 'i' },
501       { "real-paths", no_argument, 0, 'r' },
502       { "hide-matchings", no_argument, 0, 'c' },
503       { "no-group-ids", no_argument, 0, 'g' },
504       { "ignore-dots", no_argument, 0, 'd' },
505       { "ignore-empty", no_argument, 0, '0' },
506       { "show-progress", no_argument, 0, 'p' },
507       { 0, 0, 0, 0 }
508     };
509
510     c = getopt_long(argc, argv, "hircgd0p",
511                     long_options, &option_index);
512     if (c == -1)
513       break;
514
515     switch (c) {
516
517     case 'h':
518       print_help(stdout);
519       exit(EXIT_SUCCESS);
520
521       break;
522
523     case 'd':
524       ignore_dotfiles = 1;
525       break;
526
527     case '0':
528       ignore_empty_files = 1;
529       break;
530
531     case 'r':
532       show_realpaths = 1;
533       break;
534
535     case 'i':
536       ignore_same_inode = 1;
537       break;
538
539     case 'g':
540       show_groups = 0;
541       break;
542
543     case 'p':
544       show_progress = 1;
545       break;
546
547     case 'c':
548       show_hits = 0;
549       break;
550
551     default:
552       exit(EXIT_FAILURE);
553     }
554   }
555
556   if(show_progress &&
557      isatty(STDOUT_FILENO) &&
558      !ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
559     tty_width = win.ws_col;
560   }
561
562   if(optind + 2 == argc) {
563     start(argv[optind], argv[optind + 1]);
564   } else if(optind + 1 == argc) {
565     ignore_same_inode = 1;
566     start(argv[optind], 0);
567   } else {
568     print_help(stderr);
569     exit(EXIT_FAILURE);
570   }
571
572   exit(EXIT_SUCCESS);
573 }