- Decided to put the new, smaller delete_files() back into
[rsync/rsync-patches.git] / fuzzy.diff
1 Depends-On-Patch: delete-during.diff
2
3 The changes to generator.c were greatly simplified, making the patch
4 easier to maintain and fixing the failing test in the testsuite.
5 Lightly tested.
6
7 Be sure to run "make proto" before "make".
8
9 --- orig/generator.c    2005-01-18 23:14:23
10 +++ generator.c 2005-01-19 18:39:15
11 @@ -46,6 +46,7 @@ extern int size_only;
12  extern OFF_T max_size;
13  extern int io_timeout;
14  extern int protocol_version;
15 +extern int fuzzy_basis;
16  extern int always_checksum;
17  extern char *partial_dir;
18  extern char *basis_dir[];
19 @@ -226,6 +227,88 @@ static void generate_and_send_sums(int f
20                 unmap_file(mapbuf);
21  }
22  
23 +/* Try to find a filename in the same dir as "fname" with a similar name.
24 + *
25 + * TODO:
26 + *  - We should be using a cache of names for the current dir, not
27 + *    re-reading the destination directory for every file.
28 + *  - We must not return an rsync tempfile from the current transfer.
29 + *  - If the highest-rated name is not a normal file, we should fall-
30 + *    back to the next highest-rated file.
31 + *  - We must not return a destination file that is being updated
32 + *    during the current transfer, even if we already processed it
33 + *    (since the receiver may not be done with it yet).
34 + *  - We must weed out any names that a daemon's config has excluded.
35 + */
36 +static int find_fuzzy(const char *fname, char *buf, STRUCT_STAT *st_ptr)
37 +{
38 +       DIR *d;
39 +       struct dirent *di;
40 +       char *basename, *dirname, *slash;
41 +       char bestname[MAXPATHLEN];
42 +       int suf_len, basename_len;
43 +       uint32 lowest_dist = 0x7FFFFFFF;
44 +       const char *suf;
45 +
46 +       strlcpy(buf, fname, MAXPATHLEN);
47 +       if ((slash = strrchr(buf, '/')) != NULL) {
48 +               dirname = buf;
49 +               *slash = '\0';
50 +               basename = slash + 1;
51 +       } else {
52 +               basename = buf;
53 +               dirname = ".";
54 +       }
55 +       basename_len = strlen(basename);
56 +
57 +       if (!(d = opendir(dirname))) {
58 +               rsyserr(FERROR, errno, "recv_generator opendir(%s)", dirname);
59 +               return -1;
60 +       }
61 +       if (slash)
62 +               *slash = '/';
63 +
64 +       suf = find_filename_suffix(basename, basename_len, &suf_len);
65 +
66 +       bestname[0] = '\0';
67 +       while ((di = readdir(d)) != NULL) {
68 +               const char *dname_suf, *dname = d_name(di);
69 +               uint32 dist;
70 +               int dname_len, dname_suf_len;
71 +
72 +               if (dname[0] == '.' && (dname[1] == '\0'
73 +                   || (dname[1] == '.' && dname[2] == '\0')))
74 +                       continue;
75 +
76 +               dname_len = strlen(dname);
77 +               dname_suf = find_filename_suffix(dname, dname_len, &dname_suf_len);
78 +
79 +               dist = fuzzy_distance(dname, dname_len, basename, basename_len);
80 +               /* Add some extra weight to how well the suffixes match. */
81 +               dist += fuzzy_distance(dname_suf, dname_suf_len, suf, suf_len) * 10;
82 +               if (verbose > 4) {
83 +                       rprintf(FINFO, "fuzzy distance for %s = %d (%d)\n",
84 +                               dname, (int)(dist>>16), (int)(dist&0xFFFF));
85 +               }
86 +               if (dist <= lowest_dist) {
87 +                       strlcpy(bestname, dname, sizeof bestname);
88 +                       lowest_dist = dist;
89 +               }
90 +       }
91 +       closedir(d);
92 +
93 +       /* Found a candidate. */
94 +       if (bestname[0] != '\0') {
95 +               strlcpy(basename, bestname, MAXPATHLEN - (basename - buf));
96 +               if (verbose > 2) {
97 +                       rprintf(FINFO, "fuzzy match %s->%s\n",
98 +                               safe_fname(fname), buf);
99 +               }
100 +               return link_stat(buf, st_ptr, 0);
101 +       }
102 +       return -1;
103 +}
104 +
105  
106  /*
107   * Acts on file number @p i from @p flist, whose name is @p fname.
108 @@ -478,6 +561,15 @@ static void recv_generator(char *fname, 
109         } else
110                 partialptr = NULL;
111  
112 +       if (statret == -1 && fuzzy_basis) {
113 +               if (find_fuzzy(fname, fnamecmpbuf, &st) == 0
114 +                   && S_ISREG(st.st_mode)) {
115 +                       statret = 0;
116 +                       fnamecmp = fnamecmpbuf;
117 +                       fnamecmp_type = FNAMECMP_FUZZY;
118 +               }
119 +       }
120 +
121         if (statret == -1) {
122                 if (preserve_hard_links && hard_link_check(file, HL_SKIP))
123                         return;
124 @@ -506,6 +598,8 @@ static void recv_generator(char *fname, 
125  
126         if (!compare_dest && fnamecmp_type <= FNAMECMP_BASIS_DIR_HIGH)
127                 ;
128 +       else if (fnamecmp_type == FNAMECMP_FUZZY)
129 +               ;
130         else if (unchanged_file(fnamecmp, file, &st)) {
131                 if (fnamecmp_type == FNAMECMP_FNAME)
132                         set_perms(fname, file, &st, PERMS_REPORT);
133 @@ -580,8 +674,24 @@ notify_others:
134         write_int(f_out, i);
135         if (protocol_version >= 29 && inplace && !read_batch)
136                 write_byte(f_out, fnamecmp_type);
137 -       if (f_out_name >= 0)
138 +       if (f_out_name >= 0) {
139                 write_byte(f_out_name, fnamecmp_type);
140 +               if (fnamecmp_type == FNAMECMP_FUZZY) {
141 +                       uchar lenbuf[3], *lb = lenbuf;
142 +                       int len = strlen(fnamecmpbuf);
143 +                       if (len > 0x7F) {
144 +#if MAXPATHLEN > 0x7FFF
145 +                               *lb++ = len / 0x10000 + 0x80;
146 +                               *lb++ = len / 0x100;
147 +#else
148 +                               *lb++ = len / 0x100 + 0x80;
149 +#endif
150 +                       }
151 +                       *lb = len;
152 +                       write_buf(f_out_name, lenbuf, lb - lenbuf + 1);
153 +                       write_buf(f_out_name, fnamecmpbuf, len);
154 +               }
155 +       }
156  
157         if (dry_run || read_batch)
158                 return;
159 --- orig/main.c 2005-01-18 21:56:05
160 +++ main.c      2005-01-14 18:33:15
161 @@ -49,6 +49,7 @@ extern int keep_dirlinks;
162  extern int preserve_hard_links;
163  extern int protocol_version;
164  extern int recurse;
165 +extern int fuzzy_basis;
166  extern int relative_paths;
167  extern int rsync_port;
168  extern int whole_file;
169 @@ -465,7 +466,8 @@ static int do_recv(int f_in,int f_out,st
170         int pid;
171         int status = 0;
172         int error_pipe[2], name_pipe[2];
173 -       BOOL need_name_pipe = (basis_dir[0] || partial_dir) && !dry_run;
174 +       BOOL need_name_pipe = (basis_dir[0] || partial_dir || fuzzy_basis)
175 +                           && !dry_run;
176  
177         /* The receiving side mustn't obey this, or an existing symlink that
178          * points to an identical file won't be replaced by the referent. */
179 --- orig/options.c      2005-01-19 01:07:34
180 +++ options.c   2005-01-15 21:08:13
181 @@ -89,6 +89,7 @@ int copy_unsafe_links = 0;
182  int size_only = 0;
183  int daemon_bwlimit = 0;
184  int bwlimit = 0;
185 +int fuzzy_basis = 0;
186  size_t bwlimit_writemax = 0;
187  int delete_after = 0;
188  int only_existing = 0;
189 @@ -292,6 +293,7 @@ void usage(enum logcode F)
190    rprintf(F,"     --compare-dest=DIR      also compare destination files relative to DIR\n");
191    rprintf(F,"     --copy-dest=DIR         ... and include copies of unchanged files\n");
192    rprintf(F,"     --link-dest=DIR         hardlink to files in DIR when unchanged\n");
193 +  rprintf(F,"     --fuzzy                 find similar file for basis when no dest file\n");
194    rprintf(F," -P                          equivalent to --partial --progress\n");
195    rprintf(F," -z, --compress              compress file data\n");
196    rprintf(F," -C, --cvs-exclude           auto ignore files in the same way CVS does\n");
197 @@ -390,6 +392,7 @@ static struct poptOption long_options[] 
198    {"compare-dest",     0,  POPT_ARG_STRING, 0, OPT_COMPARE_DEST, 0, 0 },
199    {"copy-dest",        0,  POPT_ARG_STRING, 0, OPT_COPY_DEST, 0, 0 },
200    {"link-dest",        0,  POPT_ARG_STRING, 0, OPT_LINK_DEST, 0, 0 },
201 +  {"fuzzy",            0,  POPT_ARG_NONE,   &fuzzy_basis, 0, 0, 0 },
202    /* TODO: Should this take an optional int giving the compression level? */
203    {"compress",        'z', POPT_ARG_NONE,   &do_compression, 0, 0, 0 },
204    {"stats",            0,  POPT_ARG_NONE,   &do_stats, 0, 0, 0 },
205 @@ -1247,6 +1250,9 @@ void server_options(char **args,int *arg
206         if (!implied_dirs && !am_sender)
207                 args[ac++] = "--no-implied-dirs";
208  
209 +       if (fuzzy_basis && am_sender)
210 +               args[ac++] = "--fuzzy";
211 +
212         *argc = ac;
213         return;
214  
215 --- orig/receiver.c     2005-01-18 22:47:38
216 +++ receiver.c  2005-01-15 21:21:02
217 @@ -234,6 +234,27 @@ static int receive_data(int f_in, char *
218  }
219  
220  
221 +static void read_gen_name(int fd, char *buf)
222 +{
223 +       int len = read_byte(fd);
224 +       if (len & 0x80) {
225 +#if MAXPATHLEN > 32767
226 +               uchar lenbuf[2];
227 +               read_buf(fd, (char *)lenbuf, 2);
228 +               len = (len & ~0x80) * 0x10000 + lenbuf[0] * 0x100 + lenbuf[1];
229 +#else
230 +               len = (len & ~0x80) * 0x100 + read_byte(fd);
231 +#endif
232 +       }
233 +       if (len >= MAXPATHLEN) {
234 +               rprintf(FERROR, "bogus data on generator name pipe\n");
235 +               exit_cleanup(RERR_PROTOCOL);
236 +       }
237 +
238 +       read_sbuf(fd, buf, len);
239 +}
240 +
241 +
242  static void discard_receive_data(int f_in, OFF_T length)
243  {
244         receive_data(f_in, NULL, -1, 0, NULL, -1, length);
245 @@ -364,6 +385,10 @@ int recv_files(int f_in, struct file_lis
246                         case FNAMECMP_BACKUP:
247                                 fnamecmp = get_backup_name(fname);
248                                 break;
249 +                       case FNAMECMP_FUZZY:
250 +                               read_gen_name(f_in_name, fnamecmpbuf);
251 +                               fnamecmp = fnamecmpbuf;
252 +                               break;
253                         default:
254                                 if (j >= basis_dir_cnt) {
255                                         rprintf(FERROR,
256 --- orig/rsync.h        2005-01-19 20:11:10
257 +++ rsync.h     2005-01-19 18:36:47
258 @@ -128,6 +128,7 @@
259  #define FNAMECMP_FNAME         0x80
260  #define FNAMECMP_PARTIAL_DIR   0x81
261  #define FNAMECMP_BACKUP        0x82
262 +#define FNAMECMP_FUZZY         0x83
263  
264  /* For calling delete_file() */
265  #define DEL_DIR                        (1<<0)
266 --- orig/rsync.yo       2005-01-19 01:05:05
267 +++ rsync.yo    2005-01-15 21:48:52
268 @@ -359,6 +359,7 @@ verb(
269       --compare-dest=DIR      also compare received files relative to DIR
270       --copy-dest=DIR         ... and include copies of unchanged files
271       --link-dest=DIR         hardlink to files in DIR when unchanged
272 +     --fuzzy                 find similar file for basis when no dest
273   -P                          equivalent to --partial --progress
274   -z, --compress              compress file data
275   -C, --cvs-exclude           auto ignore files in the same way CVS does
276 @@ -888,6 +889,14 @@ Note that rsync versions prior to 2.6.1 
277  (or implied by -a).  You can work-around this bug by avoiding the -o option
278  when sending to an old rsync.
279  
280 +dit(bf(--fuzzy)) This option tells rsync that it should look around for a
281 +basis file for any destination file that is missing.  The current algorithm
282 +looks for a similarly-named file in the same directory as the destination
283 +file, and, if found, uses that to try to speed up the transfer.  Note that
284 +the use of the --delete option might get rid of any potential fuzzy-match
285 +files, so either use --delete-after or filename exclusions if you need to
286 +prevent this.
287 +
288  dit(bf(-z, --compress)) With this option, rsync compresses any data from
289  the files that it sends to the destination machine.  This
290  option is useful on slow connections.  The compression method used is the
291 --- orig/util.c 2005-01-19 20:11:10
292 +++ util.c      2005-01-19 17:30:51
293 @@ -1213,3 +1213,108 @@ void *_realloc_array(void *ptr, unsigned
294                 return malloc(size * num);
295         return realloc(ptr, size * num);
296  }
297 +
298 +/* Take a filename and filename length and return the most significant
299 + * filename suffix we can find.  This ignores suffixes such as "~",
300 + * ".bak", ".orig", ".~1~", etc. */
301 +const char *find_filename_suffix(const char *fn, int fn_len, int *len_ptr)
302 +{
303 +       const char *suf, *s;
304 +       BOOL had_tilde;
305 +       int s_len;
306 +
307 +       /* One or more dots at the start aren't a suffix. */
308 +       while (fn_len && *fn == '.') fn++, fn_len--;
309 +
310 +       /* Ignore the ~ in a "foo~" filename. */
311 +       if (fn_len > 1 && fn[fn_len-1] == '~')
312 +               fn_len--, had_tilde = True;
313 +       else
314 +               had_tilde = False;
315 +
316 +       /* Assume we don't find an suffix. */
317 +       suf = "";
318 +       *len_ptr = 0;
319 +
320 +       /* Find the last significant suffix. */
321 +       for (s = fn + fn_len - 1; fn_len > 1; ) {
322 +               while (*s != '.' && s != fn) s--;
323 +               if (s == fn)
324 +                       break;
325 +               s_len = fn_len - (s - fn);
326 +               fn_len = s - fn;
327 +               if (s_len == 3) {
328 +                       if (strcmp(s+1, "bak") == 0
329 +                        || strcmp(s+1, "old") == 0)
330 +                               continue;
331 +               } else if (s_len == 4) {
332 +                       if (strcmp(s+1, "orig") == 0)
333 +                               continue;
334 +               } else if (s_len > 2 && had_tilde
335 +                   && s[1] == '~' && isdigit(s[2]))
336 +                       continue;
337 +               *len_ptr = s_len;
338 +               suf = s;
339 +               /* Determine if the suffix is all digits. */
340 +               for (s++, s_len--; s_len > 0; s++, s_len--) {
341 +                       if (!isdigit(*s))
342 +                               return suf;
343 +               }
344 +               /* An all-digit suffix may not be that signficant. */
345 +               continue;
346 +       }
347 +
348 +       return suf;
349 +}
350 +
351 +/* This is an implementation of the Levenshtein distance algorithm.  It
352 + * was implemented to avoid needing a two-dimensional matrix (to save
353 + * memory).  It was also tweaked to try to factor in the ASCII distance
354 + * between changed characters as a minor distance quantity.  The normal
355 + * Levenshtein units of distance (each signifying a single change between
356 + * the two strings) are defined as a "UNIT". */
357 +
358 +#define UNIT (1 << 16)
359 +
360 +uint32 fuzzy_distance(const char *s1, int len1, const char *s2, int len2)
361 +{
362 +       uint32 a[MAXPATHLEN], diag, above, left, diag_inc, above_inc, left_inc;
363 +       int32 cost;
364 +       int i1, i2;
365 +
366 +       if (!len1 || !len2) {
367 +               if (!len1) {
368 +                       s1 = s2;
369 +                       len1 = len2;
370 +               }
371 +               for (i1 = 0, cost = 0; i1 < len1; i1++)
372 +                       cost += s1[i1];
373 +               return (int32)len1 * UNIT + cost;
374 +       }
375 +
376 +       for (i2 = 0; i2 < len2; i2++)
377 +               a[i2] = (i2+1) * UNIT;
378 +
379 +       for (i1 = 0; i1 < len1; i1++) {
380 +               diag = i1 * UNIT;
381 +               above = (i1+1) * UNIT;
382 +               for (i2 = 0; i2 < len2; i2++) {
383 +                       left = a[i2];
384 +                       if ((cost = *((uchar*)s1+i1) - *((uchar*)s2+i2)) != 0) {
385 +                               if (cost < 0)
386 +                                       cost = UNIT - cost;
387 +                               else
388 +                                       cost = UNIT + cost;
389 +                       }
390 +                       diag_inc = diag + cost;
391 +                       left_inc = left + UNIT + *((uchar*)s1+i1);
392 +                       above_inc = above + UNIT + *((uchar*)s2+i2);
393 +                       a[i2] = above = left < above
394 +                             ? (left_inc < diag_inc ? left_inc : diag_inc)
395 +                             : (above_inc < diag_inc ? above_inc : diag_inc);
396 +                       diag = left;
397 +               }
398 +       }
399 +
400 +       return a[len2-1];
401 +}