Now do not ignore ./something when the -d option is present.
[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.8"
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] == '.' && name[1] != '/');
94 }
95
96 /**********************************************************************/
97
98 struct file_node {
99   struct file_node *next;
100   char *name;
101   size_t size;
102   ino_t inode;
103   int group_id; /* one per identical file content */
104   int dir_id; /* 1 for DIR1, and 2 for DIR2 */
105 };
106
107 void file_list_delete(struct file_node *head) {
108   struct file_node *next;
109   while(head) {
110     next = head->next;
111     free(head->name);
112     free(head);
113     head = next;
114   }
115 }
116
117 int file_list_length(struct file_node *head) {
118   int l = 0;
119   while(head) {
120     l++;
121     head = head->next;
122   }
123   return l;
124 }
125
126 /**********************************************************************/
127
128 int same_content(struct file_node *f1, struct file_node *f2,
129                  char *buffer1, char *buffer2) {
130   int fd1, fd2, s1, s2;
131
132   fd1 = open(f1->name, O_RDONLY);
133   fd2 = open(f2->name, O_RDONLY);
134
135   if(fd1 >= 0 && fd2 >= 0) {
136     while(1) {
137       s1 = read(fd1, buffer1, READ_BUFFER_SIZE);
138       s2 = read(fd2, buffer2, READ_BUFFER_SIZE);
139
140       if(s1 < 0 || s2 < 0) {
141         close(fd1);
142         close(fd2);
143         return 0;
144       }
145
146       if(s1 == s2) {
147         if(s1 == 0) {
148           close(fd1);
149           close(fd2);
150           return 1;
151         } else {
152           if(memcmp(buffer1, buffer2, s1)) {
153             close(fd1);
154             close(fd2);
155             return 0;
156           }
157         }
158       } else {
159         fprintf(stderr,
160                 "Different read size without error on files of same size.\n");
161         exit(EXIT_FAILURE);
162       }
163     }
164   } else {
165
166     if(fd1 < 0) {
167       fprintf(stderr,
168               "Can not open \"%s\" error: %s\n",
169               f1->name,
170               strerror(errno));
171     }
172
173     if(fd2 < 0) {
174       fprintf(stderr,
175               "Can not open \"%s\" error: %s\n",
176               f2->name,
177               strerror(errno));
178     }
179
180     exit(EXIT_FAILURE);
181   }
182 }
183
184 int same_files(struct file_node *f1, struct file_node *f2,
185                char *buffer1, char *buffer2) {
186   if(ignore_same_inode && f1->inode == f2->inode) {
187     return 0;
188   }
189   return f1->size == f2->size && same_content(f1, f2, buffer1, buffer2);
190 }
191
192 /**********************************************************************/
193
194 struct file_node *scan_directory(struct file_node *tail, const char *name) {
195   DIR *dir;
196   struct dirent *dir_e;
197   struct stat sb;
198   struct file_node *tmp;
199   char subname[PATH_MAX + 1];
200
201   if(lstat(name, &sb) != 0) {
202     fprintf(stderr, "Can not stat \"%s\": %s\n", name, strerror(errno));
203     exit(EXIT_FAILURE);
204   }
205
206   if(S_ISLNK(sb.st_mode)) {
207     return tail;
208   }
209
210   dir = opendir(name);
211
212   if(dir) {
213     while((dir_e = readdir(dir))) {
214       if(!ignore_entry(dir_e->d_name)) {
215         snprintf(subname, PATH_MAX, "%s/%s", name, dir_e->d_name);
216         tail = scan_directory(tail, subname);
217       }
218     }
219     closedir(dir);
220   } else {
221     if(S_ISREG(sb.st_mode)) {
222       if(!ignore_entry(name)) {
223         if(!ignore_empty_files || sb.st_size > 0) {
224           tmp = safe_malloc(sizeof(struct file_node));
225           tmp->next = tail;
226           tmp->name = strdup(name);
227           tmp->size = sb.st_size;
228           tmp->inode = sb.st_ino;
229           tmp->group_id = -1;
230           tmp->dir_id = -1;
231           tail = tmp;
232         }
233       }
234     }
235   }
236
237   return tail;
238 }
239
240 void print_file(struct file_node *node) {
241   char tmp[PATH_MAX + 1];
242   if(show_realpaths) {
243     if(realpath(node->name, tmp)) {
244       if(show_groups) {
245         printf("%d %s\n", node->group_id, tmp);
246       } else {
247         printf("%s\n", tmp);
248       }
249     } else {
250       printf("Can not get the realpath of \"%s\": %s\n",
251              node->name,
252              strerror(errno));
253       exit(EXIT_FAILURE);
254     }
255   } else {
256     if(show_groups) {
257       printf("%d %s\n", node->group_id, node->name);
258     } else {
259       printf("%s\n", node->name);
260     }
261   }
262 }
263
264 int compare_nodes(const void *x1, const void *x2) {
265   const struct file_node **f1, **f2;
266
267   f1 = (const struct file_node **) x1;
268   f2 = (const struct file_node **) x2;
269
270   if((*f1)->group_id < (*f2)->group_id) {
271     return -1;
272   } else if((*f1)->group_id > (*f2)->group_id) {
273     return 1;
274   } else {
275     if((*f1)->dir_id < (*f2)->dir_id) {
276       return -1;
277     } else if((*f1)->dir_id > (*f2)->dir_id) {
278       return 1;
279     } else {
280       return 0;
281     }
282   }
283 }
284
285
286 void print_result(struct file_node *list1, struct file_node *list2) {
287   struct file_node *node1, *node2;
288   struct file_node **nodes;
289   int nb, n;
290
291   nb = 0;
292   for(node1 = list1; node1; node1 = node1->next) {
293     if(node1->group_id >= 0) { nb++; }
294   }
295
296   if(list2) {
297     for(node2 = list2; node2; node2 = node2->next) {
298       if(node2->group_id >= 0) { nb++; }
299     }
300   }
301
302   nodes = safe_malloc(nb * sizeof(struct file_node *));
303
304   n = 0;
305   for(node1 = list1; node1; node1 = node1->next) {
306     if(node1->group_id >= 0) {
307       nodes[n++] = node1;
308     }
309   }
310
311   if(list2) {
312     for(node2 = list2; node2; node2 = node2->next) {
313       if(node2->group_id >= 0) {
314         nodes[n++] = node2;
315       }
316     }
317   }
318
319   qsort(nodes, nb, sizeof(struct file_node *), compare_nodes);
320
321   for(n = 0; n < nb; n++) {
322     if(!show_groups && n > 0 && nodes[n]->group_id != nodes[n-1]->group_id) {
323       printf("\n");
324     }
325     print_file(nodes[n]);
326   }
327
328   free(nodes);
329 }
330
331 void print_progress(int max, int n, int *pp) {
332   int p, k;
333   int width;
334   if(show_progress && tty_width > 0) {
335     width = tty_width - 7;
336     p = (width * n) / (max - 1);
337     if(p > *pp) {
338       for(k = 0; k < p; k++) {
339         fprintf(stderr, "+");
340       }
341       for(; k < width; k++) {
342         fprintf(stderr, "-");
343       }
344       *pp = p;
345       p = (100 * n) / (max - 1);
346       fprintf(stderr, " [%3d%%]\r", p);
347     }
348   }
349 }
350
351 void start(const char *dirname1, const char *dirname2) {
352   struct file_node *list1, *list2;
353   struct file_node *node1, *node2;
354   int not_in, found;
355   int nb_groups, nb_nodes;
356   int list1_length, previous_progress;
357   struct winsize win;
358
359   char *buffer1 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
360   char *buffer2 = safe_malloc(sizeof(char) * READ_BUFFER_SIZE);
361
362   not_in = 0;
363
364   if(show_progress) {
365     if(isatty(STDOUT_FILENO) &&
366        !ioctl (STDOUT_FILENO, TIOCGWINSZ, (char *) &win)) {
367       tty_width = win.ws_col;
368     }
369     fprintf(stderr, "Scanning %s ... ", dirname1);
370   }
371
372   list1 = scan_directory(0, dirname1);
373
374   if(dirname2) {
375     if(strncmp(dirname2, "not:", 4) == 0) {
376       not_in = 1;
377       /* groups are not computed in the not: mode */
378       show_groups = 0;
379       dirname2 += 4;
380     } else if(strncmp(dirname2, "and:", 4) == 0) {
381       dirname2 += 4;
382     }
383     if(show_progress) {
384       fprintf(stderr, "%s ... ", dirname2);
385     }
386     list2 = scan_directory(0, dirname2);
387   } else {
388     list2 = list1;
389   }
390
391   if(show_progress) {
392     fprintf(stderr, "done.\n");
393   }
394
395   nb_groups = 0;
396   previous_progress = -1;
397   nb_nodes = 0;
398   list1_length = file_list_length(list1);
399
400   if(not_in) {
401     for(node1 = list1; node1; node1 = node1->next) {
402       print_progress(list1_length, nb_nodes, &previous_progress);
403       nb_nodes++;
404
405       found = 0;
406
407       for(node2 = list2; !found && node2; node2 = node2->next) {
408         if(same_files(node1, node2, buffer1, buffer2)) {
409           found = 1;
410         }
411       }
412
413       if(!found) {
414         if(show_realpaths) {
415           printf("%s\n", realpath(node1->name, 0));
416         } else {
417           printf("%s\n", node1->name);
418         }
419       }
420     }
421
422   } else {
423     for(node1 = list1; node1; node1 = node1->next) {
424       print_progress(list1_length, nb_nodes, &previous_progress);
425       nb_nodes++;
426
427       for(node2 = list2; node2; node2 = node2->next) {
428         if(node1->group_id < 0 || node2->group_id < 0) {
429           if(same_files(node1, node2, buffer1, buffer2)) {
430             if(node1->group_id < 0) {
431               if(node2->group_id >= 0) {
432                 node1->group_id = node2->group_id;
433               } else {
434                 node1->group_id = nb_groups;
435                 node1->dir_id = 1;
436                 nb_groups++;
437               }
438             }
439             if(node2->group_id < 0) {
440               node2->group_id = node1->group_id;
441               node2->dir_id = 2;
442             }
443           }
444         }
445       }
446     }
447   }
448
449   if(show_progress) {
450     fprintf(stderr, "\n");
451   }
452
453   if(dirname2) {
454     print_result(list1, list2);
455     file_list_delete(list1);
456     file_list_delete(list2);
457   } else {
458     print_result(list1, 0);
459     file_list_delete(list1);
460   }
461
462   free(buffer1);
463   free(buffer2);
464 }
465
466 void print_help(FILE *out) {
467   fprintf(out, "Usage: finddup [OPTION]... DIR1 [[and:|not:]DIR2]\n");
468   fprintf(out, "Version %s (%s)\n", VERSION_NUMBER, UNAME);
469   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");
470   fprintf(out, "\n");
471   /*            01234567890123456789012345678901234567890123456789012345678901234567890123456789*/
472   fprintf(out, "   -h, --help                 show this help\n");
473   fprintf(out, "   -d, --ignore-dots          ignore dot files and directories\n");
474   fprintf(out, "   -0, --ignore-empty         ignore empty files\n");
475   fprintf(out, "   -c, --hide-matchings       do not show which files in DIR2 corresponds to\n");
476   fprintf(out, "                              those in DIR1\n");
477   fprintf(out, "   -g, --no-group-ids         do not show the file groups\n");
478   fprintf(out, "   -p, --show-progress        show progress\n");
479   fprintf(out, "   -r, --real-paths           show the real file paths\n");
480   fprintf(out, "   -i, --same-inodes-are-different\n");
481   fprintf(out, "                              consider files with same inode as different\n");
482   fprintf(out, "\n");
483   fprintf(out, "Report bugs and comments to <francois@fleuret.org>.\n");
484 }
485
486 /**********************************************************************/
487
488 static struct option long_options[] = {
489   { "help", no_argument, 0, 'h' },
490   { "same-inodes-are-different", no_argument, 0, 'i' },
491   { "real-paths", no_argument, 0, 'r' },
492   { "hide-matchings", no_argument, 0, 'c' },
493   { "no-group-ids", no_argument, 0, 'g' },
494   { "ignore-dots", no_argument, 0, 'd' },
495   { "ignore-empty", no_argument, 0, '0' },
496   { "show-progress", no_argument, 0, 'p' },
497   { 0, 0, 0, 0 }
498 };
499
500 int main(int argc, char **argv) {
501   int c;
502
503   setlocale (LC_ALL, "");
504
505   while ((c = getopt_long(argc, argv, "hircgd0p",
506                           long_options, NULL)) != -1) {
507     switch (c) {
508
509     case 'h':
510       print_help(stdout);
511       exit(EXIT_SUCCESS);
512
513       break;
514
515     case 'd':
516       ignore_dotfiles = 1;
517       break;
518
519     case '0':
520       ignore_empty_files = 1;
521       break;
522
523     case 'r':
524       show_realpaths = 1;
525       break;
526
527     case 'i':
528       ignore_same_inode = 1;
529       break;
530
531     case 'g':
532       show_groups = 0;
533       break;
534
535     case 'p':
536       show_progress = 1;
537       break;
538
539     case 'c':
540       show_hits = 0;
541       break;
542
543     default:
544       exit(EXIT_FAILURE);
545     }
546   }
547
548   if(optind + 2 == argc) {
549     start(argv[optind], argv[optind + 1]);
550   } else if(optind + 1 == argc) {
551     ignore_same_inode = 1;
552     start(argv[optind], 0);
553   } else {
554     print_help(stderr);
555     exit(EXIT_FAILURE);
556   }
557
558   exit(EXIT_SUCCESS);
559 }