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