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