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