convert: git cherry-pick -Xrenormalize did not work
[git] / convert.c
1 #include "cache.h"
2 #include "attr.h"
3 #include "run-command.h"
4 #include "quote.h"
5 #include "sigchain.h"
6
7 /*
8  * convert.c - convert a file when checking it out and checking it in.
9  *
10  * This should use the pathname to decide on whether it wants to do some
11  * more interesting conversions (automatic gzip/unzip, general format
12  * conversions etc etc), but by default it just does automatic CRLF<->LF
13  * translation when the "text" attribute or "auto_crlf" option is set.
14  */
15
16 /* Stat bits: When BIN is set, the txt bits are unset */
17 #define CONVERT_STAT_BITS_TXT_LF    0x1
18 #define CONVERT_STAT_BITS_TXT_CRLF  0x2
19 #define CONVERT_STAT_BITS_BIN       0x4
20
21 enum crlf_action {
22         CRLF_UNDEFINED,
23         CRLF_BINARY,
24         CRLF_TEXT,
25         CRLF_TEXT_INPUT,
26         CRLF_TEXT_CRLF,
27         CRLF_AUTO,
28         CRLF_AUTO_INPUT,
29         CRLF_AUTO_CRLF
30 };
31
32 struct text_stat {
33         /* NUL, CR, LF and CRLF counts */
34         unsigned nul, lonecr, lonelf, crlf;
35
36         /* These are just approximations! */
37         unsigned printable, nonprintable;
38 };
39
40 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
41 {
42         unsigned long i;
43
44         memset(stats, 0, sizeof(*stats));
45
46         for (i = 0; i < size; i++) {
47                 unsigned char c = buf[i];
48                 if (c == '\r') {
49                         if (i+1 < size && buf[i+1] == '\n') {
50                                 stats->crlf++;
51                                 i++;
52                         } else
53                                 stats->lonecr++;
54                         continue;
55                 }
56                 if (c == '\n') {
57                         stats->lonelf++;
58                         continue;
59                 }
60                 if (c == 127)
61                         /* DEL */
62                         stats->nonprintable++;
63                 else if (c < 32) {
64                         switch (c) {
65                                 /* BS, HT, ESC and FF */
66                         case '\b': case '\t': case '\033': case '\014':
67                                 stats->printable++;
68                                 break;
69                         case 0:
70                                 stats->nul++;
71                                 /* fall through */
72                         default:
73                                 stats->nonprintable++;
74                         }
75                 }
76                 else
77                         stats->printable++;
78         }
79
80         /* If file ends with EOF then don't count this EOF as non-printable. */
81         if (size >= 1 && buf[size-1] == '\032')
82                 stats->nonprintable--;
83 }
84
85 /*
86  * The same heuristics as diff.c::mmfile_is_binary()
87  * We treat files with bare CR as binary
88  */
89 static int convert_is_binary(unsigned long size, const struct text_stat *stats)
90 {
91         if (stats->lonecr)
92                 return 1;
93         if (stats->nul)
94                 return 1;
95         if ((stats->printable >> 7) < stats->nonprintable)
96                 return 1;
97         return 0;
98 }
99
100 static unsigned int gather_convert_stats(const char *data, unsigned long size)
101 {
102         struct text_stat stats;
103         int ret = 0;
104         if (!data || !size)
105                 return 0;
106         gather_stats(data, size, &stats);
107         if (convert_is_binary(size, &stats))
108                 ret |= CONVERT_STAT_BITS_BIN;
109         if (stats.crlf)
110                 ret |= CONVERT_STAT_BITS_TXT_CRLF;
111         if (stats.lonelf)
112                 ret |=  CONVERT_STAT_BITS_TXT_LF;
113
114         return ret;
115 }
116
117 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
118 {
119         unsigned int convert_stats = gather_convert_stats(data, size);
120
121         if (convert_stats & CONVERT_STAT_BITS_BIN)
122                 return "-text";
123         switch (convert_stats) {
124         case CONVERT_STAT_BITS_TXT_LF:
125                 return "lf";
126         case CONVERT_STAT_BITS_TXT_CRLF:
127                 return "crlf";
128         case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
129                 return "mixed";
130         default:
131                 return "none";
132         }
133 }
134
135 const char *get_cached_convert_stats_ascii(const char *path)
136 {
137         const char *ret;
138         unsigned long sz;
139         void *data = read_blob_data_from_cache(path, &sz);
140         ret = gather_convert_stats_ascii(data, sz);
141         free(data);
142         return ret;
143 }
144
145 const char *get_wt_convert_stats_ascii(const char *path)
146 {
147         const char *ret = "";
148         struct strbuf sb = STRBUF_INIT;
149         if (strbuf_read_file(&sb, path, 0) >= 0)
150                 ret = gather_convert_stats_ascii(sb.buf, sb.len);
151         strbuf_release(&sb);
152         return ret;
153 }
154
155 static int text_eol_is_crlf(void)
156 {
157         if (auto_crlf == AUTO_CRLF_TRUE)
158                 return 1;
159         else if (auto_crlf == AUTO_CRLF_INPUT)
160                 return 0;
161         if (core_eol == EOL_CRLF)
162                 return 1;
163         if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
164                 return 1;
165         return 0;
166 }
167
168 static enum eol output_eol(enum crlf_action crlf_action)
169 {
170         switch (crlf_action) {
171         case CRLF_BINARY:
172                 return EOL_UNSET;
173         case CRLF_TEXT_CRLF:
174                 return EOL_CRLF;
175         case CRLF_TEXT_INPUT:
176                 return EOL_LF;
177         case CRLF_UNDEFINED:
178         case CRLF_AUTO_CRLF:
179                 return EOL_CRLF;
180         case CRLF_AUTO_INPUT:
181                 return EOL_LF;
182         case CRLF_TEXT:
183         case CRLF_AUTO:
184                 /* fall through */
185                 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
186         }
187         warning("Illegal crlf_action %d\n", (int)crlf_action);
188         return core_eol;
189 }
190
191 static void check_safe_crlf(const char *path, enum crlf_action crlf_action,
192                             struct text_stat *old_stats, struct text_stat *new_stats,
193                             enum safe_crlf checksafe)
194 {
195         if (old_stats->crlf && !new_stats->crlf ) {
196                 /*
197                  * CRLFs would not be restored by checkout
198                  */
199                 if (checksafe == SAFE_CRLF_WARN)
200                         warning("CRLF will be replaced by LF in %s.\nThe file will have its original line endings in your working directory.", path);
201                 else /* i.e. SAFE_CRLF_FAIL */
202                         die("CRLF would be replaced by LF in %s.", path);
203         } else if (old_stats->lonelf && !new_stats->lonelf ) {
204                 /*
205                  * CRLFs would be added by checkout
206                  */
207                 if (checksafe == SAFE_CRLF_WARN)
208                         warning("LF will be replaced by CRLF in %s.\nThe file will have its original line endings in your working directory.", path);
209                 else /* i.e. SAFE_CRLF_FAIL */
210                         die("LF would be replaced by CRLF in %s", path);
211         }
212 }
213
214 static int has_cr_in_index(const char *path)
215 {
216         unsigned long sz;
217         void *data;
218         int has_cr;
219
220         data = read_blob_data_from_cache(path, &sz);
221         if (!data)
222                 return 0;
223         has_cr = memchr(data, '\r', sz) != NULL;
224         free(data);
225         return has_cr;
226 }
227
228 static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
229                                    enum crlf_action crlf_action)
230 {
231         if (output_eol(crlf_action) != EOL_CRLF)
232                 return 0;
233         /* No "naked" LF? Nothing to convert, regardless. */
234         if (!stats->lonelf)
235                 return 0;
236
237         if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
238                 /* If we have any CR or CRLF line endings, we do not touch it */
239                 /* This is the new safer autocrlf-handling */
240                 if (stats->lonecr || stats->crlf)
241                         return 0;
242
243                 if (convert_is_binary(len, stats))
244                         return 0;
245         }
246         return 1;
247
248 }
249
250 static int crlf_to_git(const char *path, const char *src, size_t len,
251                        struct strbuf *buf,
252                        enum crlf_action crlf_action, enum safe_crlf checksafe)
253 {
254         struct text_stat stats;
255         char *dst;
256         int convert_crlf_into_lf;
257
258         if (crlf_action == CRLF_BINARY ||
259             (src && !len))
260                 return 0;
261
262         /*
263          * If we are doing a dry-run and have no source buffer, there is
264          * nothing to analyze; we must assume we would convert.
265          */
266         if (!buf && !src)
267                 return 1;
268
269         gather_stats(src, len, &stats);
270         /* Optimization: No CRLF? Nothing to convert, regardless. */
271         convert_crlf_into_lf = !!stats.crlf;
272
273         if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
274                 if (convert_is_binary(len, &stats))
275                         return 0;
276                 /*
277                  * If the file in the index has any CR in it, do not
278                  * convert.  This is the new safer autocrlf handling,
279                  * unless we want to renormalize in a merge or
280                  * cherry-pick.
281                  */
282                 if ((checksafe != SAFE_CRLF_RENORMALIZE) && has_cr_in_index(path))
283                         convert_crlf_into_lf = 0;
284         }
285         if ((checksafe == SAFE_CRLF_WARN ||
286             (checksafe == SAFE_CRLF_FAIL)) && len) {
287                 struct text_stat new_stats;
288                 memcpy(&new_stats, &stats, sizeof(new_stats));
289                 /* simulate "git add" */
290                 if (convert_crlf_into_lf) {
291                         new_stats.lonelf += new_stats.crlf;
292                         new_stats.crlf = 0;
293                 }
294                 /* simulate "git checkout" */
295                 if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
296                         new_stats.crlf += new_stats.lonelf;
297                         new_stats.lonelf = 0;
298                 }
299                 check_safe_crlf(path, crlf_action, &stats, &new_stats, checksafe);
300         }
301         if (!convert_crlf_into_lf)
302                 return 0;
303
304         /*
305          * At this point all of our source analysis is done, and we are sure we
306          * would convert. If we are in dry-run mode, we can give an answer.
307          */
308         if (!buf)
309                 return 1;
310
311         /* only grow if not in place */
312         if (strbuf_avail(buf) + buf->len < len)
313                 strbuf_grow(buf, len - buf->len);
314         dst = buf->buf;
315         if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
316                 /*
317                  * If we guessed, we already know we rejected a file with
318                  * lone CR, and we can strip a CR without looking at what
319                  * follow it.
320                  */
321                 do {
322                         unsigned char c = *src++;
323                         if (c != '\r')
324                                 *dst++ = c;
325                 } while (--len);
326         } else {
327                 do {
328                         unsigned char c = *src++;
329                         if (! (c == '\r' && (1 < len && *src == '\n')))
330                                 *dst++ = c;
331                 } while (--len);
332         }
333         strbuf_setlen(buf, dst - buf->buf);
334         return 1;
335 }
336
337 static int crlf_to_worktree(const char *path, const char *src, size_t len,
338                             struct strbuf *buf, enum crlf_action crlf_action)
339 {
340         char *to_free = NULL;
341         struct text_stat stats;
342
343         if (!len || output_eol(crlf_action) != EOL_CRLF)
344                 return 0;
345
346         gather_stats(src, len, &stats);
347         if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
348                 return 0;
349
350         /* are we "faking" in place editing ? */
351         if (src == buf->buf)
352                 to_free = strbuf_detach(buf, NULL);
353
354         strbuf_grow(buf, len + stats.lonelf);
355         for (;;) {
356                 const char *nl = memchr(src, '\n', len);
357                 if (!nl)
358                         break;
359                 if (nl > src && nl[-1] == '\r') {
360                         strbuf_add(buf, src, nl + 1 - src);
361                 } else {
362                         strbuf_add(buf, src, nl - src);
363                         strbuf_addstr(buf, "\r\n");
364                 }
365                 len -= nl + 1 - src;
366                 src  = nl + 1;
367         }
368         strbuf_add(buf, src, len);
369
370         free(to_free);
371         return 1;
372 }
373
374 struct filter_params {
375         const char *src;
376         unsigned long size;
377         int fd;
378         const char *cmd;
379         const char *path;
380 };
381
382 static int filter_buffer_or_fd(int in, int out, void *data)
383 {
384         /*
385          * Spawn cmd and feed the buffer contents through its stdin.
386          */
387         struct child_process child_process = CHILD_PROCESS_INIT;
388         struct filter_params *params = (struct filter_params *)data;
389         int write_err, status;
390         const char *argv[] = { NULL, NULL };
391
392         /* apply % substitution to cmd */
393         struct strbuf cmd = STRBUF_INIT;
394         struct strbuf path = STRBUF_INIT;
395         struct strbuf_expand_dict_entry dict[] = {
396                 { "f", NULL, },
397                 { NULL, NULL, },
398         };
399
400         /* quote the path to preserve spaces, etc. */
401         sq_quote_buf(&path, params->path);
402         dict[0].value = path.buf;
403
404         /* expand all %f with the quoted path */
405         strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
406         strbuf_release(&path);
407
408         argv[0] = cmd.buf;
409
410         child_process.argv = argv;
411         child_process.use_shell = 1;
412         child_process.in = -1;
413         child_process.out = out;
414
415         if (start_command(&child_process))
416                 return error("cannot fork to run external filter %s", params->cmd);
417
418         sigchain_push(SIGPIPE, SIG_IGN);
419
420         if (params->src) {
421                 write_err = (write_in_full(child_process.in,
422                                            params->src, params->size) < 0);
423                 if (errno == EPIPE)
424                         write_err = 0;
425         } else {
426                 write_err = copy_fd(params->fd, child_process.in);
427                 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
428                         write_err = 0;
429         }
430
431         if (close(child_process.in))
432                 write_err = 1;
433         if (write_err)
434                 error("cannot feed the input to external filter %s", params->cmd);
435
436         sigchain_pop(SIGPIPE);
437
438         status = finish_command(&child_process);
439         if (status)
440                 error("external filter %s failed %d", params->cmd, status);
441
442         strbuf_release(&cmd);
443         return (write_err || status);
444 }
445
446 static int apply_filter(const char *path, const char *src, size_t len, int fd,
447                         struct strbuf *dst, const char *cmd)
448 {
449         /*
450          * Create a pipeline to have the command filter the buffer's
451          * contents.
452          *
453          * (child --> cmd) --> us
454          */
455         int ret = 1;
456         struct strbuf nbuf = STRBUF_INIT;
457         struct async async;
458         struct filter_params params;
459
460         if (!cmd || !*cmd)
461                 return 0;
462
463         if (!dst)
464                 return 1;
465
466         memset(&async, 0, sizeof(async));
467         async.proc = filter_buffer_or_fd;
468         async.data = &params;
469         async.out = -1;
470         params.src = src;
471         params.size = len;
472         params.fd = fd;
473         params.cmd = cmd;
474         params.path = path;
475
476         fflush(NULL);
477         if (start_async(&async))
478                 return 0;       /* error was already reported */
479
480         if (strbuf_read(&nbuf, async.out, len) < 0) {
481                 error("read from external filter %s failed", cmd);
482                 ret = 0;
483         }
484         if (close(async.out)) {
485                 error("read from external filter %s failed", cmd);
486                 ret = 0;
487         }
488         if (finish_async(&async)) {
489                 error("external filter %s failed", cmd);
490                 ret = 0;
491         }
492
493         if (ret) {
494                 strbuf_swap(dst, &nbuf);
495         }
496         strbuf_release(&nbuf);
497         return ret;
498 }
499
500 static struct convert_driver {
501         const char *name;
502         struct convert_driver *next;
503         const char *smudge;
504         const char *clean;
505         int required;
506 } *user_convert, **user_convert_tail;
507
508 static int read_convert_config(const char *var, const char *value, void *cb)
509 {
510         const char *key, *name;
511         int namelen;
512         struct convert_driver *drv;
513
514         /*
515          * External conversion drivers are configured using
516          * "filter.<name>.variable".
517          */
518         if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
519                 return 0;
520         for (drv = user_convert; drv; drv = drv->next)
521                 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
522                         break;
523         if (!drv) {
524                 drv = xcalloc(1, sizeof(struct convert_driver));
525                 drv->name = xmemdupz(name, namelen);
526                 *user_convert_tail = drv;
527                 user_convert_tail = &(drv->next);
528         }
529
530         /*
531          * filter.<name>.smudge and filter.<name>.clean specifies
532          * the command line:
533          *
534          *      command-line
535          *
536          * The command-line will not be interpolated in any way.
537          */
538
539         if (!strcmp("smudge", key))
540                 return git_config_string(&drv->smudge, var, value);
541
542         if (!strcmp("clean", key))
543                 return git_config_string(&drv->clean, var, value);
544
545         if (!strcmp("required", key)) {
546                 drv->required = git_config_bool(var, value);
547                 return 0;
548         }
549
550         return 0;
551 }
552
553 static int count_ident(const char *cp, unsigned long size)
554 {
555         /*
556          * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
557          */
558         int cnt = 0;
559         char ch;
560
561         while (size) {
562                 ch = *cp++;
563                 size--;
564                 if (ch != '$')
565                         continue;
566                 if (size < 3)
567                         break;
568                 if (memcmp("Id", cp, 2))
569                         continue;
570                 ch = cp[2];
571                 cp += 3;
572                 size -= 3;
573                 if (ch == '$')
574                         cnt++; /* $Id$ */
575                 if (ch != ':')
576                         continue;
577
578                 /*
579                  * "$Id: ... "; scan up to the closing dollar sign and discard.
580                  */
581                 while (size) {
582                         ch = *cp++;
583                         size--;
584                         if (ch == '$') {
585                                 cnt++;
586                                 break;
587                         }
588                         if (ch == '\n')
589                                 break;
590                 }
591         }
592         return cnt;
593 }
594
595 static int ident_to_git(const char *path, const char *src, size_t len,
596                         struct strbuf *buf, int ident)
597 {
598         char *dst, *dollar;
599
600         if (!ident || (src && !count_ident(src, len)))
601                 return 0;
602
603         if (!buf)
604                 return 1;
605
606         /* only grow if not in place */
607         if (strbuf_avail(buf) + buf->len < len)
608                 strbuf_grow(buf, len - buf->len);
609         dst = buf->buf;
610         for (;;) {
611                 dollar = memchr(src, '$', len);
612                 if (!dollar)
613                         break;
614                 memmove(dst, src, dollar + 1 - src);
615                 dst += dollar + 1 - src;
616                 len -= dollar + 1 - src;
617                 src  = dollar + 1;
618
619                 if (len > 3 && !memcmp(src, "Id:", 3)) {
620                         dollar = memchr(src + 3, '$', len - 3);
621                         if (!dollar)
622                                 break;
623                         if (memchr(src + 3, '\n', dollar - src - 3)) {
624                                 /* Line break before the next dollar. */
625                                 continue;
626                         }
627
628                         memcpy(dst, "Id$", 3);
629                         dst += 3;
630                         len -= dollar + 1 - src;
631                         src  = dollar + 1;
632                 }
633         }
634         memmove(dst, src, len);
635         strbuf_setlen(buf, dst + len - buf->buf);
636         return 1;
637 }
638
639 static int ident_to_worktree(const char *path, const char *src, size_t len,
640                              struct strbuf *buf, int ident)
641 {
642         unsigned char sha1[20];
643         char *to_free = NULL, *dollar, *spc;
644         int cnt;
645
646         if (!ident)
647                 return 0;
648
649         cnt = count_ident(src, len);
650         if (!cnt)
651                 return 0;
652
653         /* are we "faking" in place editing ? */
654         if (src == buf->buf)
655                 to_free = strbuf_detach(buf, NULL);
656         hash_sha1_file(src, len, "blob", sha1);
657
658         strbuf_grow(buf, len + cnt * 43);
659         for (;;) {
660                 /* step 1: run to the next '$' */
661                 dollar = memchr(src, '$', len);
662                 if (!dollar)
663                         break;
664                 strbuf_add(buf, src, dollar + 1 - src);
665                 len -= dollar + 1 - src;
666                 src  = dollar + 1;
667
668                 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
669                 if (len < 3 || memcmp("Id", src, 2))
670                         continue;
671
672                 /* step 3: skip over Id$ or Id:xxxxx$ */
673                 if (src[2] == '$') {
674                         src += 3;
675                         len -= 3;
676                 } else if (src[2] == ':') {
677                         /*
678                          * It's possible that an expanded Id has crept its way into the
679                          * repository, we cope with that by stripping the expansion out.
680                          * This is probably not a good idea, since it will cause changes
681                          * on checkout, which won't go away by stash, but let's keep it
682                          * for git-style ids.
683                          */
684                         dollar = memchr(src + 3, '$', len - 3);
685                         if (!dollar) {
686                                 /* incomplete keyword, no more '$', so just quit the loop */
687                                 break;
688                         }
689
690                         if (memchr(src + 3, '\n', dollar - src - 3)) {
691                                 /* Line break before the next dollar. */
692                                 continue;
693                         }
694
695                         spc = memchr(src + 4, ' ', dollar - src - 4);
696                         if (spc && spc < dollar-1) {
697                                 /* There are spaces in unexpected places.
698                                  * This is probably an id from some other
699                                  * versioning system. Keep it for now.
700                                  */
701                                 continue;
702                         }
703
704                         len -= dollar + 1 - src;
705                         src  = dollar + 1;
706                 } else {
707                         /* it wasn't a "Id$" or "Id:xxxx$" */
708                         continue;
709                 }
710
711                 /* step 4: substitute */
712                 strbuf_addstr(buf, "Id: ");
713                 strbuf_add(buf, sha1_to_hex(sha1), 40);
714                 strbuf_addstr(buf, " $");
715         }
716         strbuf_add(buf, src, len);
717
718         free(to_free);
719         return 1;
720 }
721
722 static enum crlf_action git_path_check_crlf(struct git_attr_check *check)
723 {
724         const char *value = check->value;
725
726         if (ATTR_TRUE(value))
727                 return CRLF_TEXT;
728         else if (ATTR_FALSE(value))
729                 return CRLF_BINARY;
730         else if (ATTR_UNSET(value))
731                 ;
732         else if (!strcmp(value, "input"))
733                 return CRLF_TEXT_INPUT;
734         else if (!strcmp(value, "auto"))
735                 return CRLF_AUTO;
736         return CRLF_UNDEFINED;
737 }
738
739 static enum eol git_path_check_eol(struct git_attr_check *check)
740 {
741         const char *value = check->value;
742
743         if (ATTR_UNSET(value))
744                 ;
745         else if (!strcmp(value, "lf"))
746                 return EOL_LF;
747         else if (!strcmp(value, "crlf"))
748                 return EOL_CRLF;
749         return EOL_UNSET;
750 }
751
752 static struct convert_driver *git_path_check_convert(struct git_attr_check *check)
753 {
754         const char *value = check->value;
755         struct convert_driver *drv;
756
757         if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
758                 return NULL;
759         for (drv = user_convert; drv; drv = drv->next)
760                 if (!strcmp(value, drv->name))
761                         return drv;
762         return NULL;
763 }
764
765 static int git_path_check_ident(struct git_attr_check *check)
766 {
767         const char *value = check->value;
768
769         return !!ATTR_TRUE(value);
770 }
771
772 struct conv_attrs {
773         struct convert_driver *drv;
774         enum crlf_action attr_action; /* What attr says */
775         enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
776         int ident;
777 };
778
779 static const char *conv_attr_name[] = {
780         "crlf", "ident", "filter", "eol", "text",
781 };
782 #define NUM_CONV_ATTRS ARRAY_SIZE(conv_attr_name)
783
784 static void convert_attrs(struct conv_attrs *ca, const char *path)
785 {
786         int i;
787         static struct git_attr_check ccheck[NUM_CONV_ATTRS];
788
789         if (!ccheck[0].attr) {
790                 for (i = 0; i < NUM_CONV_ATTRS; i++)
791                         ccheck[i].attr = git_attr(conv_attr_name[i]);
792                 user_convert_tail = &user_convert;
793                 git_config(read_convert_config, NULL);
794         }
795
796         if (!git_check_attr(path, NUM_CONV_ATTRS, ccheck)) {
797                 ca->crlf_action = git_path_check_crlf(ccheck + 4);
798                 if (ca->crlf_action == CRLF_UNDEFINED)
799                         ca->crlf_action = git_path_check_crlf(ccheck + 0);
800                 ca->attr_action = ca->crlf_action;
801                 ca->ident = git_path_check_ident(ccheck + 1);
802                 ca->drv = git_path_check_convert(ccheck + 2);
803                 if (ca->crlf_action != CRLF_BINARY) {
804                         enum eol eol_attr = git_path_check_eol(ccheck + 3);
805                         if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
806                                 ca->crlf_action = CRLF_AUTO_INPUT;
807                         else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
808                                 ca->crlf_action = CRLF_AUTO_CRLF;
809                         else if (eol_attr == EOL_LF)
810                                 ca->crlf_action = CRLF_TEXT_INPUT;
811                         else if (eol_attr == EOL_CRLF)
812                                 ca->crlf_action = CRLF_TEXT_CRLF;
813                 }
814                 ca->attr_action = ca->crlf_action;
815         } else {
816                 ca->drv = NULL;
817                 ca->crlf_action = CRLF_UNDEFINED;
818                 ca->ident = 0;
819         }
820         if (ca->crlf_action == CRLF_TEXT)
821                 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
822         if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
823                 ca->crlf_action = CRLF_BINARY;
824         if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
825                 ca->crlf_action = CRLF_AUTO_CRLF;
826         if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
827                 ca->crlf_action = CRLF_AUTO_INPUT;
828 }
829
830 int would_convert_to_git_filter_fd(const char *path)
831 {
832         struct conv_attrs ca;
833
834         convert_attrs(&ca, path);
835         if (!ca.drv)
836                 return 0;
837
838         /*
839          * Apply a filter to an fd only if the filter is required to succeed.
840          * We must die if the filter fails, because the original data before
841          * filtering is not available.
842          */
843         if (!ca.drv->required)
844                 return 0;
845
846         return apply_filter(path, NULL, 0, -1, NULL, ca.drv->clean);
847 }
848
849 const char *get_convert_attr_ascii(const char *path)
850 {
851         struct conv_attrs ca;
852
853         convert_attrs(&ca, path);
854         switch (ca.attr_action) {
855         case CRLF_UNDEFINED:
856                 return "";
857         case CRLF_BINARY:
858                 return "-text";
859         case CRLF_TEXT:
860                 return "text";
861         case CRLF_TEXT_INPUT:
862                 return "text eol=lf";
863         case CRLF_TEXT_CRLF:
864                 return "text eol=crlf";
865         case CRLF_AUTO:
866                 return "text=auto";
867         case CRLF_AUTO_CRLF:
868                 return "text=auto eol=crlf";
869         case CRLF_AUTO_INPUT:
870                 return "text=auto eol=lf";
871         }
872         return "";
873 }
874
875 int convert_to_git(const char *path, const char *src, size_t len,
876                    struct strbuf *dst, enum safe_crlf checksafe)
877 {
878         int ret = 0;
879         const char *filter = NULL;
880         int required = 0;
881         struct conv_attrs ca;
882
883         convert_attrs(&ca, path);
884         if (ca.drv) {
885                 filter = ca.drv->clean;
886                 required = ca.drv->required;
887         }
888
889         ret |= apply_filter(path, src, len, -1, dst, filter);
890         if (!ret && required)
891                 die("%s: clean filter '%s' failed", path, ca.drv->name);
892
893         if (ret && dst) {
894                 src = dst->buf;
895                 len = dst->len;
896         }
897         ret |= crlf_to_git(path, src, len, dst, ca.crlf_action, checksafe);
898         if (ret && dst) {
899                 src = dst->buf;
900                 len = dst->len;
901         }
902         return ret | ident_to_git(path, src, len, dst, ca.ident);
903 }
904
905 void convert_to_git_filter_fd(const char *path, int fd, struct strbuf *dst,
906                               enum safe_crlf checksafe)
907 {
908         struct conv_attrs ca;
909         convert_attrs(&ca, path);
910
911         assert(ca.drv);
912         assert(ca.drv->clean);
913
914         if (!apply_filter(path, NULL, 0, fd, dst, ca.drv->clean))
915                 die("%s: clean filter '%s' failed", path, ca.drv->name);
916
917         crlf_to_git(path, dst->buf, dst->len, dst, ca.crlf_action, checksafe);
918         ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
919 }
920
921 static int convert_to_working_tree_internal(const char *path, const char *src,
922                                             size_t len, struct strbuf *dst,
923                                             int normalizing)
924 {
925         int ret = 0, ret_filter = 0;
926         const char *filter = NULL;
927         int required = 0;
928         struct conv_attrs ca;
929
930         convert_attrs(&ca, path);
931         if (ca.drv) {
932                 filter = ca.drv->smudge;
933                 required = ca.drv->required;
934         }
935
936         ret |= ident_to_worktree(path, src, len, dst, ca.ident);
937         if (ret) {
938                 src = dst->buf;
939                 len = dst->len;
940         }
941         /*
942          * CRLF conversion can be skipped if normalizing, unless there
943          * is a smudge filter.  The filter might expect CRLFs.
944          */
945         if (filter || !normalizing) {
946                 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
947                 if (ret) {
948                         src = dst->buf;
949                         len = dst->len;
950                 }
951         }
952
953         ret_filter = apply_filter(path, src, len, -1, dst, filter);
954         if (!ret_filter && required)
955                 die("%s: smudge filter %s failed", path, ca.drv->name);
956
957         return ret | ret_filter;
958 }
959
960 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
961 {
962         return convert_to_working_tree_internal(path, src, len, dst, 0);
963 }
964
965 int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
966 {
967         int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
968         if (ret) {
969                 src = dst->buf;
970                 len = dst->len;
971         }
972         return ret | convert_to_git(path, src, len, dst, SAFE_CRLF_RENORMALIZE);
973 }
974
975 /*****************************************************************
976  *
977  * Streaming conversion support
978  *
979  *****************************************************************/
980
981 typedef int (*filter_fn)(struct stream_filter *,
982                          const char *input, size_t *isize_p,
983                          char *output, size_t *osize_p);
984 typedef void (*free_fn)(struct stream_filter *);
985
986 struct stream_filter_vtbl {
987         filter_fn filter;
988         free_fn free;
989 };
990
991 struct stream_filter {
992         struct stream_filter_vtbl *vtbl;
993 };
994
995 static int null_filter_fn(struct stream_filter *filter,
996                           const char *input, size_t *isize_p,
997                           char *output, size_t *osize_p)
998 {
999         size_t count;
1000
1001         if (!input)
1002                 return 0; /* we do not keep any states */
1003         count = *isize_p;
1004         if (*osize_p < count)
1005                 count = *osize_p;
1006         if (count) {
1007                 memmove(output, input, count);
1008                 *isize_p -= count;
1009                 *osize_p -= count;
1010         }
1011         return 0;
1012 }
1013
1014 static void null_free_fn(struct stream_filter *filter)
1015 {
1016         ; /* nothing -- null instances are shared */
1017 }
1018
1019 static struct stream_filter_vtbl null_vtbl = {
1020         null_filter_fn,
1021         null_free_fn,
1022 };
1023
1024 static struct stream_filter null_filter_singleton = {
1025         &null_vtbl,
1026 };
1027
1028 int is_null_stream_filter(struct stream_filter *filter)
1029 {
1030         return filter == &null_filter_singleton;
1031 }
1032
1033
1034 /*
1035  * LF-to-CRLF filter
1036  */
1037
1038 struct lf_to_crlf_filter {
1039         struct stream_filter filter;
1040         unsigned has_held:1;
1041         char held;
1042 };
1043
1044 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1045                                 const char *input, size_t *isize_p,
1046                                 char *output, size_t *osize_p)
1047 {
1048         size_t count, o = 0;
1049         struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1050
1051         /*
1052          * We may be holding onto the CR to see if it is followed by a
1053          * LF, in which case we would need to go to the main loop.
1054          * Otherwise, just emit it to the output stream.
1055          */
1056         if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1057                 output[o++] = lf_to_crlf->held;
1058                 lf_to_crlf->has_held = 0;
1059         }
1060
1061         /* We are told to drain */
1062         if (!input) {
1063                 *osize_p -= o;
1064                 return 0;
1065         }
1066
1067         count = *isize_p;
1068         if (count || lf_to_crlf->has_held) {
1069                 size_t i;
1070                 int was_cr = 0;
1071
1072                 if (lf_to_crlf->has_held) {
1073                         was_cr = 1;
1074                         lf_to_crlf->has_held = 0;
1075                 }
1076
1077                 for (i = 0; o < *osize_p && i < count; i++) {
1078                         char ch = input[i];
1079
1080                         if (ch == '\n') {
1081                                 output[o++] = '\r';
1082                         } else if (was_cr) {
1083                                 /*
1084                                  * Previous round saw CR and it is not followed
1085                                  * by a LF; emit the CR before processing the
1086                                  * current character.
1087                                  */
1088                                 output[o++] = '\r';
1089                         }
1090
1091                         /*
1092                          * We may have consumed the last output slot,
1093                          * in which case we need to break out of this
1094                          * loop; hold the current character before
1095                          * returning.
1096                          */
1097                         if (*osize_p <= o) {
1098                                 lf_to_crlf->has_held = 1;
1099                                 lf_to_crlf->held = ch;
1100                                 continue; /* break but increment i */
1101                         }
1102
1103                         if (ch == '\r') {
1104                                 was_cr = 1;
1105                                 continue;
1106                         }
1107
1108                         was_cr = 0;
1109                         output[o++] = ch;
1110                 }
1111
1112                 *osize_p -= o;
1113                 *isize_p -= i;
1114
1115                 if (!lf_to_crlf->has_held && was_cr) {
1116                         lf_to_crlf->has_held = 1;
1117                         lf_to_crlf->held = '\r';
1118                 }
1119         }
1120         return 0;
1121 }
1122
1123 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1124 {
1125         free(filter);
1126 }
1127
1128 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1129         lf_to_crlf_filter_fn,
1130         lf_to_crlf_free_fn,
1131 };
1132
1133 static struct stream_filter *lf_to_crlf_filter(void)
1134 {
1135         struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1136
1137         lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1138         return (struct stream_filter *)lf_to_crlf;
1139 }
1140
1141 /*
1142  * Cascade filter
1143  */
1144 #define FILTER_BUFFER 1024
1145 struct cascade_filter {
1146         struct stream_filter filter;
1147         struct stream_filter *one;
1148         struct stream_filter *two;
1149         char buf[FILTER_BUFFER];
1150         int end, ptr;
1151 };
1152
1153 static int cascade_filter_fn(struct stream_filter *filter,
1154                              const char *input, size_t *isize_p,
1155                              char *output, size_t *osize_p)
1156 {
1157         struct cascade_filter *cas = (struct cascade_filter *) filter;
1158         size_t filled = 0;
1159         size_t sz = *osize_p;
1160         size_t to_feed, remaining;
1161
1162         /*
1163          * input -- (one) --> buf -- (two) --> output
1164          */
1165         while (filled < sz) {
1166                 remaining = sz - filled;
1167
1168                 /* do we already have something to feed two with? */
1169                 if (cas->ptr < cas->end) {
1170                         to_feed = cas->end - cas->ptr;
1171                         if (stream_filter(cas->two,
1172                                           cas->buf + cas->ptr, &to_feed,
1173                                           output + filled, &remaining))
1174                                 return -1;
1175                         cas->ptr += (cas->end - cas->ptr) - to_feed;
1176                         filled = sz - remaining;
1177                         continue;
1178                 }
1179
1180                 /* feed one from upstream and have it emit into our buffer */
1181                 to_feed = input ? *isize_p : 0;
1182                 if (input && !to_feed)
1183                         break;
1184                 remaining = sizeof(cas->buf);
1185                 if (stream_filter(cas->one,
1186                                   input, &to_feed,
1187                                   cas->buf, &remaining))
1188                         return -1;
1189                 cas->end = sizeof(cas->buf) - remaining;
1190                 cas->ptr = 0;
1191                 if (input) {
1192                         size_t fed = *isize_p - to_feed;
1193                         *isize_p -= fed;
1194                         input += fed;
1195                 }
1196
1197                 /* do we know that we drained one completely? */
1198                 if (input || cas->end)
1199                         continue;
1200
1201                 /* tell two to drain; we have nothing more to give it */
1202                 to_feed = 0;
1203                 remaining = sz - filled;
1204                 if (stream_filter(cas->two,
1205                                   NULL, &to_feed,
1206                                   output + filled, &remaining))
1207                         return -1;
1208                 if (remaining == (sz - filled))
1209                         break; /* completely drained two */
1210                 filled = sz - remaining;
1211         }
1212         *osize_p -= filled;
1213         return 0;
1214 }
1215
1216 static void cascade_free_fn(struct stream_filter *filter)
1217 {
1218         struct cascade_filter *cas = (struct cascade_filter *)filter;
1219         free_stream_filter(cas->one);
1220         free_stream_filter(cas->two);
1221         free(filter);
1222 }
1223
1224 static struct stream_filter_vtbl cascade_vtbl = {
1225         cascade_filter_fn,
1226         cascade_free_fn,
1227 };
1228
1229 static struct stream_filter *cascade_filter(struct stream_filter *one,
1230                                             struct stream_filter *two)
1231 {
1232         struct cascade_filter *cascade;
1233
1234         if (!one || is_null_stream_filter(one))
1235                 return two;
1236         if (!two || is_null_stream_filter(two))
1237                 return one;
1238
1239         cascade = xmalloc(sizeof(*cascade));
1240         cascade->one = one;
1241         cascade->two = two;
1242         cascade->end = cascade->ptr = 0;
1243         cascade->filter.vtbl = &cascade_vtbl;
1244         return (struct stream_filter *)cascade;
1245 }
1246
1247 /*
1248  * ident filter
1249  */
1250 #define IDENT_DRAINING (-1)
1251 #define IDENT_SKIPPING (-2)
1252 struct ident_filter {
1253         struct stream_filter filter;
1254         struct strbuf left;
1255         int state;
1256         char ident[45]; /* ": x40 $" */
1257 };
1258
1259 static int is_foreign_ident(const char *str)
1260 {
1261         int i;
1262
1263         if (!skip_prefix(str, "$Id: ", &str))
1264                 return 0;
1265         for (i = 0; str[i]; i++) {
1266                 if (isspace(str[i]) && str[i+1] != '$')
1267                         return 1;
1268         }
1269         return 0;
1270 }
1271
1272 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1273 {
1274         size_t to_drain = ident->left.len;
1275
1276         if (*osize_p < to_drain)
1277                 to_drain = *osize_p;
1278         if (to_drain) {
1279                 memcpy(*output_p, ident->left.buf, to_drain);
1280                 strbuf_remove(&ident->left, 0, to_drain);
1281                 *output_p += to_drain;
1282                 *osize_p -= to_drain;
1283         }
1284         if (!ident->left.len)
1285                 ident->state = 0;
1286 }
1287
1288 static int ident_filter_fn(struct stream_filter *filter,
1289                            const char *input, size_t *isize_p,
1290                            char *output, size_t *osize_p)
1291 {
1292         struct ident_filter *ident = (struct ident_filter *)filter;
1293         static const char head[] = "$Id";
1294
1295         if (!input) {
1296                 /* drain upon eof */
1297                 switch (ident->state) {
1298                 default:
1299                         strbuf_add(&ident->left, head, ident->state);
1300                 case IDENT_SKIPPING:
1301                         /* fallthru */
1302                 case IDENT_DRAINING:
1303                         ident_drain(ident, &output, osize_p);
1304                 }
1305                 return 0;
1306         }
1307
1308         while (*isize_p || (ident->state == IDENT_DRAINING)) {
1309                 int ch;
1310
1311                 if (ident->state == IDENT_DRAINING) {
1312                         ident_drain(ident, &output, osize_p);
1313                         if (!*osize_p)
1314                                 break;
1315                         continue;
1316                 }
1317
1318                 ch = *(input++);
1319                 (*isize_p)--;
1320
1321                 if (ident->state == IDENT_SKIPPING) {
1322                         /*
1323                          * Skipping until '$' or LF, but keeping them
1324                          * in case it is a foreign ident.
1325                          */
1326                         strbuf_addch(&ident->left, ch);
1327                         if (ch != '\n' && ch != '$')
1328                                 continue;
1329                         if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1330                                 strbuf_setlen(&ident->left, sizeof(head) - 1);
1331                                 strbuf_addstr(&ident->left, ident->ident);
1332                         }
1333                         ident->state = IDENT_DRAINING;
1334                         continue;
1335                 }
1336
1337                 if (ident->state < sizeof(head) &&
1338                     head[ident->state] == ch) {
1339                         ident->state++;
1340                         continue;
1341                 }
1342
1343                 if (ident->state)
1344                         strbuf_add(&ident->left, head, ident->state);
1345                 if (ident->state == sizeof(head) - 1) {
1346                         if (ch != ':' && ch != '$') {
1347                                 strbuf_addch(&ident->left, ch);
1348                                 ident->state = 0;
1349                                 continue;
1350                         }
1351
1352                         if (ch == ':') {
1353                                 strbuf_addch(&ident->left, ch);
1354                                 ident->state = IDENT_SKIPPING;
1355                         } else {
1356                                 strbuf_addstr(&ident->left, ident->ident);
1357                                 ident->state = IDENT_DRAINING;
1358                         }
1359                         continue;
1360                 }
1361
1362                 strbuf_addch(&ident->left, ch);
1363                 ident->state = IDENT_DRAINING;
1364         }
1365         return 0;
1366 }
1367
1368 static void ident_free_fn(struct stream_filter *filter)
1369 {
1370         struct ident_filter *ident = (struct ident_filter *)filter;
1371         strbuf_release(&ident->left);
1372         free(filter);
1373 }
1374
1375 static struct stream_filter_vtbl ident_vtbl = {
1376         ident_filter_fn,
1377         ident_free_fn,
1378 };
1379
1380 static struct stream_filter *ident_filter(const unsigned char *sha1)
1381 {
1382         struct ident_filter *ident = xmalloc(sizeof(*ident));
1383
1384         xsnprintf(ident->ident, sizeof(ident->ident),
1385                   ": %s $", sha1_to_hex(sha1));
1386         strbuf_init(&ident->left, 0);
1387         ident->filter.vtbl = &ident_vtbl;
1388         ident->state = 0;
1389         return (struct stream_filter *)ident;
1390 }
1391
1392 /*
1393  * Return an appropriately constructed filter for the path, or NULL if
1394  * the contents cannot be filtered without reading the whole thing
1395  * in-core.
1396  *
1397  * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1398  * large binary blob you would want us not to slurp into the memory!
1399  */
1400 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1401 {
1402         struct conv_attrs ca;
1403         struct stream_filter *filter = NULL;
1404
1405         convert_attrs(&ca, path);
1406         if (ca.drv && (ca.drv->smudge || ca.drv->clean))
1407                 return NULL;
1408
1409         if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1410                 return NULL;
1411
1412         if (ca.ident)
1413                 filter = ident_filter(sha1);
1414
1415         if (output_eol(ca.crlf_action) == EOL_CRLF)
1416                 filter = cascade_filter(filter, lf_to_crlf_filter());
1417         else
1418                 filter = cascade_filter(filter, &null_filter_singleton);
1419
1420         return filter;
1421 }
1422
1423 void free_stream_filter(struct stream_filter *filter)
1424 {
1425         filter->vtbl->free(filter);
1426 }
1427
1428 int stream_filter(struct stream_filter *filter,
1429                   const char *input, size_t *isize_p,
1430                   char *output, size_t *osize_p)
1431 {
1432         return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
1433 }