Merge branch 'sg/subtree-signed-commits' into pu
[git] / convert.c
1 #define NO_THE_INDEX_COMPATIBILITY_MACROS
2 #include "cache.h"
3 #include "config.h"
4 #include "attr.h"
5 #include "run-command.h"
6 #include "quote.h"
7 #include "sigchain.h"
8 #include "pkt-line.h"
9 #include "sub-process.h"
10 #include "utf8.h"
11
12 /*
13  * convert.c - convert a file when checking it out and checking it in.
14  *
15  * This should use the pathname to decide on whether it wants to do some
16  * more interesting conversions (automatic gzip/unzip, general format
17  * conversions etc etc), but by default it just does automatic CRLF<->LF
18  * translation when the "text" attribute or "auto_crlf" option is set.
19  */
20
21 /* Stat bits: When BIN is set, the txt bits are unset */
22 #define CONVERT_STAT_BITS_TXT_LF    0x1
23 #define CONVERT_STAT_BITS_TXT_CRLF  0x2
24 #define CONVERT_STAT_BITS_BIN       0x4
25
26 enum crlf_action {
27         CRLF_UNDEFINED,
28         CRLF_BINARY,
29         CRLF_TEXT,
30         CRLF_TEXT_INPUT,
31         CRLF_TEXT_CRLF,
32         CRLF_AUTO,
33         CRLF_AUTO_INPUT,
34         CRLF_AUTO_CRLF
35 };
36
37 struct text_stat {
38         /* NUL, CR, LF and CRLF counts */
39         unsigned nul, lonecr, lonelf, crlf;
40
41         /* These are just approximations! */
42         unsigned printable, nonprintable;
43 };
44
45 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
46 {
47         unsigned long i;
48
49         memset(stats, 0, sizeof(*stats));
50
51         for (i = 0; i < size; i++) {
52                 unsigned char c = buf[i];
53                 if (c == '\r') {
54                         if (i+1 < size && buf[i+1] == '\n') {
55                                 stats->crlf++;
56                                 i++;
57                         } else
58                                 stats->lonecr++;
59                         continue;
60                 }
61                 if (c == '\n') {
62                         stats->lonelf++;
63                         continue;
64                 }
65                 if (c == 127)
66                         /* DEL */
67                         stats->nonprintable++;
68                 else if (c < 32) {
69                         switch (c) {
70                                 /* BS, HT, ESC and FF */
71                         case '\b': case '\t': case '\033': case '\014':
72                                 stats->printable++;
73                                 break;
74                         case 0:
75                                 stats->nul++;
76                                 /* fall through */
77                         default:
78                                 stats->nonprintable++;
79                         }
80                 }
81                 else
82                         stats->printable++;
83         }
84
85         /* If file ends with EOF then don't count this EOF as non-printable. */
86         if (size >= 1 && buf[size-1] == '\032')
87                 stats->nonprintable--;
88 }
89
90 /*
91  * The same heuristics as diff.c::mmfile_is_binary()
92  * We treat files with bare CR as binary
93  */
94 static int convert_is_binary(unsigned long size, const struct text_stat *stats)
95 {
96         if (stats->lonecr)
97                 return 1;
98         if (stats->nul)
99                 return 1;
100         if ((stats->printable >> 7) < stats->nonprintable)
101                 return 1;
102         return 0;
103 }
104
105 static unsigned int gather_convert_stats(const char *data, unsigned long size)
106 {
107         struct text_stat stats;
108         int ret = 0;
109         if (!data || !size)
110                 return 0;
111         gather_stats(data, size, &stats);
112         if (convert_is_binary(size, &stats))
113                 ret |= CONVERT_STAT_BITS_BIN;
114         if (stats.crlf)
115                 ret |= CONVERT_STAT_BITS_TXT_CRLF;
116         if (stats.lonelf)
117                 ret |=  CONVERT_STAT_BITS_TXT_LF;
118
119         return ret;
120 }
121
122 static const char *gather_convert_stats_ascii(const char *data, unsigned long size)
123 {
124         unsigned int convert_stats = gather_convert_stats(data, size);
125
126         if (convert_stats & CONVERT_STAT_BITS_BIN)
127                 return "-text";
128         switch (convert_stats) {
129         case CONVERT_STAT_BITS_TXT_LF:
130                 return "lf";
131         case CONVERT_STAT_BITS_TXT_CRLF:
132                 return "crlf";
133         case CONVERT_STAT_BITS_TXT_LF | CONVERT_STAT_BITS_TXT_CRLF:
134                 return "mixed";
135         default:
136                 return "none";
137         }
138 }
139
140 const char *get_cached_convert_stats_ascii(const struct index_state *istate,
141                                            const char *path)
142 {
143         const char *ret;
144         unsigned long sz;
145         void *data = read_blob_data_from_index(istate, path, &sz);
146         ret = gather_convert_stats_ascii(data, sz);
147         free(data);
148         return ret;
149 }
150
151 const char *get_wt_convert_stats_ascii(const char *path)
152 {
153         const char *ret = "";
154         struct strbuf sb = STRBUF_INIT;
155         if (strbuf_read_file(&sb, path, 0) >= 0)
156                 ret = gather_convert_stats_ascii(sb.buf, sb.len);
157         strbuf_release(&sb);
158         return ret;
159 }
160
161 static int text_eol_is_crlf(void)
162 {
163         if (auto_crlf == AUTO_CRLF_TRUE)
164                 return 1;
165         else if (auto_crlf == AUTO_CRLF_INPUT)
166                 return 0;
167         if (core_eol == EOL_CRLF)
168                 return 1;
169         if (core_eol == EOL_UNSET && EOL_NATIVE == EOL_CRLF)
170                 return 1;
171         return 0;
172 }
173
174 static enum eol output_eol(enum crlf_action crlf_action)
175 {
176         switch (crlf_action) {
177         case CRLF_BINARY:
178                 return EOL_UNSET;
179         case CRLF_TEXT_CRLF:
180                 return EOL_CRLF;
181         case CRLF_TEXT_INPUT:
182                 return EOL_LF;
183         case CRLF_UNDEFINED:
184         case CRLF_AUTO_CRLF:
185                 return EOL_CRLF;
186         case CRLF_AUTO_INPUT:
187                 return EOL_LF;
188         case CRLF_TEXT:
189         case CRLF_AUTO:
190                 /* fall through */
191                 return text_eol_is_crlf() ? EOL_CRLF : EOL_LF;
192         }
193         warning("Illegal crlf_action %d\n", (int)crlf_action);
194         return core_eol;
195 }
196
197 static void check_global_conv_flags_eol(const char *path, enum crlf_action crlf_action,
198                             struct text_stat *old_stats, struct text_stat *new_stats,
199                             int conv_flags)
200 {
201         if (old_stats->crlf && !new_stats->crlf ) {
202                 /*
203                  * CRLFs would not be restored by checkout
204                  */
205                 if (conv_flags & CONV_EOL_RNDTRP_DIE)
206                         die(_("CRLF would be replaced by LF in %s."), path);
207                 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
208                         warning(_("CRLF will be replaced by LF in %s.\n"
209                                   "The file will have its original line"
210                                   " endings in your working directory."), path);
211         } else if (old_stats->lonelf && !new_stats->lonelf ) {
212                 /*
213                  * CRLFs would be added by checkout
214                  */
215                 if (conv_flags & CONV_EOL_RNDTRP_DIE)
216                         die(_("LF would be replaced by CRLF in %s"), path);
217                 else if (conv_flags & CONV_EOL_RNDTRP_WARN)
218                         warning(_("LF will be replaced by CRLF in %s.\n"
219                                   "The file will have its original line"
220                                   " endings in your working directory."), path);
221         }
222 }
223
224 static int has_crlf_in_index(const struct index_state *istate, const char *path)
225 {
226         unsigned long sz;
227         void *data;
228         const char *crp;
229         int has_crlf = 0;
230
231         data = read_blob_data_from_index(istate, path, &sz);
232         if (!data)
233                 return 0;
234
235         crp = memchr(data, '\r', sz);
236         if (crp) {
237                 unsigned int ret_stats;
238                 ret_stats = gather_convert_stats(data, sz);
239                 if (!(ret_stats & CONVERT_STAT_BITS_BIN) &&
240                     (ret_stats & CONVERT_STAT_BITS_TXT_CRLF))
241                         has_crlf = 1;
242         }
243         free(data);
244         return has_crlf;
245 }
246
247 static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
248                                    enum crlf_action crlf_action)
249 {
250         if (output_eol(crlf_action) != EOL_CRLF)
251                 return 0;
252         /* No "naked" LF? Nothing to convert, regardless. */
253         if (!stats->lonelf)
254                 return 0;
255
256         if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
257                 /* If we have any CR or CRLF line endings, we do not touch it */
258                 /* This is the new safer autocrlf-handling */
259                 if (stats->lonecr || stats->crlf)
260                         return 0;
261
262                 if (convert_is_binary(len, stats))
263                         return 0;
264         }
265         return 1;
266
267 }
268
269 static void trace_encoding(const char *context, const char *path,
270                            const char *encoding, const char *buf, size_t len)
271 {
272         static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
273         struct strbuf trace = STRBUF_INIT;
274         int i;
275
276         strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
277         for (i = 0; i < len && buf; ++i) {
278                 strbuf_addf(
279                         &trace,"| \e[2m%2i:\e[0m %2x \e[2m%c\e[0m%c",
280                         i,
281                         (unsigned char) buf[i],
282                         (buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
283                         ((i+1) % 8 && (i+1) < len ? ' ' : '\n')
284                 );
285         }
286         strbuf_addchars(&trace, '\n', 1);
287
288         trace_strbuf(&coe, &trace);
289         strbuf_release(&trace);
290 }
291
292 static int check_roundtrip(const char* enc_name)
293 {
294         /*
295          * check_roundtrip_encoding contains a string of space and/or
296          * comma separated encodings (eg. "UTF-16, ASCII, CP1125").
297          * Search for the given encoding in that string.
298          */
299         const char *found = strcasestr(check_roundtrip_encoding, enc_name);
300         const char *next = found + strlen(enc_name);
301         int len = strlen(check_roundtrip_encoding);
302         return (found && (
303                         /*
304                          * check that the found encoding is at the
305                          * beginning of check_roundtrip_encoding or
306                          * that it is prefixed with a space or comma
307                          */
308                         found == check_roundtrip_encoding || (
309                                 found > check_roundtrip_encoding &&
310                                 (*(found-1) == ' ' || *(found-1) == ',')
311                         )
312                 ) && (
313                         /*
314                          * check that the found encoding is at the
315                          * end of check_roundtrip_encoding or
316                          * that it is suffixed with a space or comma
317                          */
318                         next == check_roundtrip_encoding + len || (
319                                 next < check_roundtrip_encoding + len &&
320                                 (*next == ' ' || *next == ',')
321                         )
322                 ));
323 }
324
325 static struct encoding {
326         const char *name;
327         struct encoding *next;
328 } *encoding, **encoding_tail;
329 static const char *default_encoding = "UTF-8";
330
331 static int encode_to_git(const char *path, const char *src, size_t src_len,
332                          struct strbuf *buf, struct encoding *enc, int conv_flags)
333 {
334         char *dst;
335         int dst_len;
336
337         /*
338          * No encoding is specified or there is nothing to encode.
339          * Tell the caller that the content was not modified.
340          */
341         if (!enc || (src && !src_len))
342                 return 0;
343
344         /*
345          * Looks like we got called from "would_convert_to_git()".
346          * This means Git wants to know if it would encode (= modify!)
347          * the content. Let's answer with "yes", since an encoding was
348          * specified.
349          */
350         if (!buf && !src)
351                 return 1;
352
353         if (has_prohibited_utf_bom(enc->name, src, src_len)) {
354                 const char *error_msg = _(
355                         "BOM is prohibited in '%s' if encoded as %s");
356                 /*
357                  * This advise is shown for UTF-??BE and UTF-??LE encodings.
358                  * We truncate the encoding name to 6 chars with %.6s to cut
359                  * off the last two "byte order" characters.
360                  */
361                 const char *advise_msg = _(
362                         "The file '%s' contains a byte order mark (BOM). "
363                         "Please use %.6s as working-tree-encoding.");
364                 advise(advise_msg, path, enc->name);
365                 if (conv_flags & CONV_WRITE_OBJECT)
366                         die(error_msg, path, enc->name);
367                 else
368                         error(error_msg, path, enc->name);
369
370         } else if (is_missing_required_utf_bom(enc->name, src, src_len)) {
371                 const char *error_msg = _(
372                         "BOM is required in '%s' if encoded as %s");
373                 const char *advise_msg = _(
374                         "The file '%s' is missing a byte order mark (BOM). "
375                         "Please use %sBE or %sLE (depending on the byte order) "
376                         "as working-tree-encoding.");
377                 advise(advise_msg, path, enc->name, enc->name);
378                 if (conv_flags & CONV_WRITE_OBJECT)
379                         die(error_msg, path, enc->name);
380                 else
381                         error(error_msg, path, enc->name);
382         }
383
384         trace_encoding("source", path, enc->name, src, src_len);
385         dst = reencode_string_len(src, src_len, default_encoding, enc->name,
386                                   &dst_len);
387         if (!dst) {
388                 /*
389                  * We could add the blob "as-is" to Git. However, on checkout
390                  * we would try to reencode to the original encoding. This
391                  * would fail and we would leave the user with a messed-up
392                  * working tree. Let's try to avoid this by screaming loud.
393                  */
394                 const char* msg = _("failed to encode '%s' from %s to %s");
395                 if (conv_flags & CONV_WRITE_OBJECT)
396                         die(msg, path, enc->name, default_encoding);
397                 else
398                         error(msg, path, enc->name, default_encoding);
399         }
400         trace_encoding("destination", path, default_encoding, dst, dst_len);
401
402         /*
403          * UTF supports lossless conversion round tripping [1] and conversions
404          * between UTF and other encodings are mostly round trip safe as
405          * Unicode aims to be a superset of all other character encodings.
406          * However, certain encodings (e.g. SHIFT-JIS) are known to have round
407          * trip issues [2]. Check the round trip conversion for all encodings
408          * listed in core.checkRoundtripEncoding.
409          *
410          * The round trip check is only performed if content is written to Git.
411          * This ensures that no information is lost during conversion to/from
412          * the internal UTF-8 representation.
413          *
414          * Please note, the code below is not tested because I was not able to
415          * generate a faulty round trip without an iconv error. Iconv errors
416          * are already caught above.
417          *
418          * [1] http://unicode.org/faq/utf_bom.html#gen2
419          * [2] https://support.microsoft.com/en-us/help/170559/prb-conversion-problem-between-shift-jis-and-unicode
420          */
421         if ((conv_flags & CONV_WRITE_OBJECT) && check_roundtrip(enc->name)) {
422                 char *re_src;
423                 int re_src_len;
424
425                 re_src = reencode_string_len(dst, dst_len,
426                                              enc->name, default_encoding,
427                                              &re_src_len);
428
429                 trace_printf("Checking roundtrip encoding for %s...\n", enc->name);
430                 trace_encoding("reencoded source", path, enc->name,
431                                re_src, re_src_len);
432
433                 if (!re_src || src_len != re_src_len ||
434                     memcmp(src, re_src, src_len)) {
435                         const char* msg = _("encoding '%s' from %s to %s and "
436                                             "back is not the same");
437                         die(msg, path, enc->name, default_encoding);
438                 }
439
440                 free(re_src);
441         }
442
443         strbuf_attach(buf, dst, dst_len, dst_len + 1);
444         return 1;
445 }
446
447 static int encode_to_worktree(const char *path, const char *src, size_t src_len,
448                               struct strbuf *buf, struct encoding *enc)
449 {
450         char *dst;
451         int dst_len;
452
453         /*
454          * No encoding is specified or there is nothing to encode.
455          * Tell the caller that the content was not modified.
456          */
457         if (!enc || (src && !src_len))
458                 return 0;
459
460         dst = reencode_string_len(src, src_len, enc->name, default_encoding,
461                                   &dst_len);
462         if (!dst) {
463                 error("failed to encode '%s' from %s to %s",
464                         path, enc->name, default_encoding);
465                 return 0;
466         }
467
468         strbuf_attach(buf, dst, dst_len, dst_len + 1);
469         return 1;
470 }
471
472 static int crlf_to_git(const struct index_state *istate,
473                        const char *path, const char *src, size_t len,
474                        struct strbuf *buf,
475                        enum crlf_action crlf_action, int conv_flags)
476 {
477         struct text_stat stats;
478         char *dst;
479         int convert_crlf_into_lf;
480
481         if (crlf_action == CRLF_BINARY ||
482             (src && !len))
483                 return 0;
484
485         /*
486          * If we are doing a dry-run and have no source buffer, there is
487          * nothing to analyze; we must assume we would convert.
488          */
489         if (!buf && !src)
490                 return 1;
491
492         gather_stats(src, len, &stats);
493         /* Optimization: No CRLF? Nothing to convert, regardless. */
494         convert_crlf_into_lf = !!stats.crlf;
495
496         if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
497                 if (convert_is_binary(len, &stats))
498                         return 0;
499                 /*
500                  * If the file in the index has any CR in it, do not
501                  * convert.  This is the new safer autocrlf handling,
502                  * unless we want to renormalize in a merge or
503                  * cherry-pick.
504                  */
505                 if ((!(conv_flags & CONV_EOL_RENORMALIZE)) &&
506                     has_crlf_in_index(istate, path))
507                         convert_crlf_into_lf = 0;
508         }
509         if (((conv_flags & CONV_EOL_RNDTRP_WARN) ||
510              ((conv_flags & CONV_EOL_RNDTRP_DIE) && len))) {
511                 struct text_stat new_stats;
512                 memcpy(&new_stats, &stats, sizeof(new_stats));
513                 /* simulate "git add" */
514                 if (convert_crlf_into_lf) {
515                         new_stats.lonelf += new_stats.crlf;
516                         new_stats.crlf = 0;
517                 }
518                 /* simulate "git checkout" */
519                 if (will_convert_lf_to_crlf(len, &new_stats, crlf_action)) {
520                         new_stats.crlf += new_stats.lonelf;
521                         new_stats.lonelf = 0;
522                 }
523                 check_global_conv_flags_eol(path, crlf_action, &stats, &new_stats, conv_flags);
524         }
525         if (!convert_crlf_into_lf)
526                 return 0;
527
528         /*
529          * At this point all of our source analysis is done, and we are sure we
530          * would convert. If we are in dry-run mode, we can give an answer.
531          */
532         if (!buf)
533                 return 1;
534
535         /* only grow if not in place */
536         if (strbuf_avail(buf) + buf->len < len)
537                 strbuf_grow(buf, len - buf->len);
538         dst = buf->buf;
539         if (crlf_action == CRLF_AUTO || crlf_action == CRLF_AUTO_INPUT || crlf_action == CRLF_AUTO_CRLF) {
540                 /*
541                  * If we guessed, we already know we rejected a file with
542                  * lone CR, and we can strip a CR without looking at what
543                  * follow it.
544                  */
545                 do {
546                         unsigned char c = *src++;
547                         if (c != '\r')
548                                 *dst++ = c;
549                 } while (--len);
550         } else {
551                 do {
552                         unsigned char c = *src++;
553                         if (! (c == '\r' && (1 < len && *src == '\n')))
554                                 *dst++ = c;
555                 } while (--len);
556         }
557         strbuf_setlen(buf, dst - buf->buf);
558         return 1;
559 }
560
561 static int crlf_to_worktree(const char *path, const char *src, size_t len,
562                             struct strbuf *buf, enum crlf_action crlf_action)
563 {
564         char *to_free = NULL;
565         struct text_stat stats;
566
567         if (!len || output_eol(crlf_action) != EOL_CRLF)
568                 return 0;
569
570         gather_stats(src, len, &stats);
571         if (!will_convert_lf_to_crlf(len, &stats, crlf_action))
572                 return 0;
573
574         /* are we "faking" in place editing ? */
575         if (src == buf->buf)
576                 to_free = strbuf_detach(buf, NULL);
577
578         strbuf_grow(buf, len + stats.lonelf);
579         for (;;) {
580                 const char *nl = memchr(src, '\n', len);
581                 if (!nl)
582                         break;
583                 if (nl > src && nl[-1] == '\r') {
584                         strbuf_add(buf, src, nl + 1 - src);
585                 } else {
586                         strbuf_add(buf, src, nl - src);
587                         strbuf_addstr(buf, "\r\n");
588                 }
589                 len -= nl + 1 - src;
590                 src  = nl + 1;
591         }
592         strbuf_add(buf, src, len);
593
594         free(to_free);
595         return 1;
596 }
597
598 struct filter_params {
599         const char *src;
600         unsigned long size;
601         int fd;
602         const char *cmd;
603         const char *path;
604 };
605
606 static int filter_buffer_or_fd(int in, int out, void *data)
607 {
608         /*
609          * Spawn cmd and feed the buffer contents through its stdin.
610          */
611         struct child_process child_process = CHILD_PROCESS_INIT;
612         struct filter_params *params = (struct filter_params *)data;
613         int write_err, status;
614         const char *argv[] = { NULL, NULL };
615
616         /* apply % substitution to cmd */
617         struct strbuf cmd = STRBUF_INIT;
618         struct strbuf path = STRBUF_INIT;
619         struct strbuf_expand_dict_entry dict[] = {
620                 { "f", NULL, },
621                 { NULL, NULL, },
622         };
623
624         /* quote the path to preserve spaces, etc. */
625         sq_quote_buf(&path, params->path);
626         dict[0].value = path.buf;
627
628         /* expand all %f with the quoted path */
629         strbuf_expand(&cmd, params->cmd, strbuf_expand_dict_cb, &dict);
630         strbuf_release(&path);
631
632         argv[0] = cmd.buf;
633
634         child_process.argv = argv;
635         child_process.use_shell = 1;
636         child_process.in = -1;
637         child_process.out = out;
638
639         if (start_command(&child_process)) {
640                 strbuf_release(&cmd);
641                 return error("cannot fork to run external filter '%s'", params->cmd);
642         }
643
644         sigchain_push(SIGPIPE, SIG_IGN);
645
646         if (params->src) {
647                 write_err = (write_in_full(child_process.in,
648                                            params->src, params->size) < 0);
649                 if (errno == EPIPE)
650                         write_err = 0;
651         } else {
652                 write_err = copy_fd(params->fd, child_process.in);
653                 if (write_err == COPY_WRITE_ERROR && errno == EPIPE)
654                         write_err = 0;
655         }
656
657         if (close(child_process.in))
658                 write_err = 1;
659         if (write_err)
660                 error("cannot feed the input to external filter '%s'", params->cmd);
661
662         sigchain_pop(SIGPIPE);
663
664         status = finish_command(&child_process);
665         if (status)
666                 error("external filter '%s' failed %d", params->cmd, status);
667
668         strbuf_release(&cmd);
669         return (write_err || status);
670 }
671
672 static int apply_single_file_filter(const char *path, const char *src, size_t len, int fd,
673                         struct strbuf *dst, const char *cmd)
674 {
675         /*
676          * Create a pipeline to have the command filter the buffer's
677          * contents.
678          *
679          * (child --> cmd) --> us
680          */
681         int err = 0;
682         struct strbuf nbuf = STRBUF_INIT;
683         struct async async;
684         struct filter_params params;
685
686         memset(&async, 0, sizeof(async));
687         async.proc = filter_buffer_or_fd;
688         async.data = &params;
689         async.out = -1;
690         params.src = src;
691         params.size = len;
692         params.fd = fd;
693         params.cmd = cmd;
694         params.path = path;
695
696         fflush(NULL);
697         if (start_async(&async))
698                 return 0;       /* error was already reported */
699
700         if (strbuf_read(&nbuf, async.out, len) < 0) {
701                 err = error("read from external filter '%s' failed", cmd);
702         }
703         if (close(async.out)) {
704                 err = error("read from external filter '%s' failed", cmd);
705         }
706         if (finish_async(&async)) {
707                 err = error("external filter '%s' failed", cmd);
708         }
709
710         if (!err) {
711                 strbuf_swap(dst, &nbuf);
712         }
713         strbuf_release(&nbuf);
714         return !err;
715 }
716
717 #define CAP_CLEAN    (1u<<0)
718 #define CAP_SMUDGE   (1u<<1)
719 #define CAP_DELAY    (1u<<2)
720
721 struct cmd2process {
722         struct subprocess_entry subprocess; /* must be the first member! */
723         unsigned int supported_capabilities;
724 };
725
726 static int subprocess_map_initialized;
727 static struct hashmap subprocess_map;
728
729 static int start_multi_file_filter_fn(struct subprocess_entry *subprocess)
730 {
731         static int versions[] = {2, 0};
732         static struct subprocess_capability capabilities[] = {
733                 { "clean",  CAP_CLEAN  },
734                 { "smudge", CAP_SMUDGE },
735                 { "delay",  CAP_DELAY  },
736                 { NULL, 0 }
737         };
738         struct cmd2process *entry = (struct cmd2process *)subprocess;
739         return subprocess_handshake(subprocess, "git-filter", versions, NULL,
740                                     capabilities,
741                                     &entry->supported_capabilities);
742 }
743
744 static void handle_filter_error(const struct strbuf *filter_status,
745                                 struct cmd2process *entry,
746                                 const unsigned int wanted_capability) {
747         if (!strcmp(filter_status->buf, "error"))
748                 ; /* The filter signaled a problem with the file. */
749         else if (!strcmp(filter_status->buf, "abort") && wanted_capability) {
750                 /*
751                  * The filter signaled a permanent problem. Don't try to filter
752                  * files with the same command for the lifetime of the current
753                  * Git process.
754                  */
755                  entry->supported_capabilities &= ~wanted_capability;
756         } else {
757                 /*
758                  * Something went wrong with the protocol filter.
759                  * Force shutdown and restart if another blob requires filtering.
760                  */
761                 error("external filter '%s' failed", entry->subprocess.cmd);
762                 subprocess_stop(&subprocess_map, &entry->subprocess);
763                 free(entry);
764         }
765 }
766
767 static int apply_multi_file_filter(const char *path, const char *src, size_t len,
768                                    int fd, struct strbuf *dst, const char *cmd,
769                                    const unsigned int wanted_capability,
770                                    struct delayed_checkout *dco)
771 {
772         int err;
773         int can_delay = 0;
774         struct cmd2process *entry;
775         struct child_process *process;
776         struct strbuf nbuf = STRBUF_INIT;
777         struct strbuf filter_status = STRBUF_INIT;
778         const char *filter_type;
779
780         if (!subprocess_map_initialized) {
781                 subprocess_map_initialized = 1;
782                 hashmap_init(&subprocess_map, cmd2process_cmp, NULL, 0);
783                 entry = NULL;
784         } else {
785                 entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
786         }
787
788         fflush(NULL);
789
790         if (!entry) {
791                 entry = xmalloc(sizeof(*entry));
792                 entry->supported_capabilities = 0;
793
794                 if (subprocess_start(&subprocess_map, &entry->subprocess, cmd, start_multi_file_filter_fn)) {
795                         free(entry);
796                         return 0;
797                 }
798         }
799         process = &entry->subprocess.process;
800
801         if (!(entry->supported_capabilities & wanted_capability))
802                 return 0;
803
804         if (wanted_capability & CAP_CLEAN)
805                 filter_type = "clean";
806         else if (wanted_capability & CAP_SMUDGE)
807                 filter_type = "smudge";
808         else
809                 die("unexpected filter type");
810
811         sigchain_push(SIGPIPE, SIG_IGN);
812
813         assert(strlen(filter_type) < LARGE_PACKET_DATA_MAX - strlen("command=\n"));
814         err = packet_write_fmt_gently(process->in, "command=%s\n", filter_type);
815         if (err)
816                 goto done;
817
818         err = strlen(path) > LARGE_PACKET_DATA_MAX - strlen("pathname=\n");
819         if (err) {
820                 error("path name too long for external filter");
821                 goto done;
822         }
823
824         err = packet_write_fmt_gently(process->in, "pathname=%s\n", path);
825         if (err)
826                 goto done;
827
828         if ((entry->supported_capabilities & CAP_DELAY) &&
829             dco && dco->state == CE_CAN_DELAY) {
830                 can_delay = 1;
831                 err = packet_write_fmt_gently(process->in, "can-delay=1\n");
832                 if (err)
833                         goto done;
834         }
835
836         err = packet_flush_gently(process->in);
837         if (err)
838                 goto done;
839
840         if (fd >= 0)
841                 err = write_packetized_from_fd(fd, process->in);
842         else
843                 err = write_packetized_from_buf(src, len, process->in);
844         if (err)
845                 goto done;
846
847         err = subprocess_read_status(process->out, &filter_status);
848         if (err)
849                 goto done;
850
851         if (can_delay && !strcmp(filter_status.buf, "delayed")) {
852                 string_list_insert(&dco->filters, cmd);
853                 string_list_insert(&dco->paths, path);
854         } else {
855                 /* The filter got the blob and wants to send us a response. */
856                 err = strcmp(filter_status.buf, "success");
857                 if (err)
858                         goto done;
859
860                 err = read_packetized_to_strbuf(process->out, &nbuf) < 0;
861                 if (err)
862                         goto done;
863
864                 err = subprocess_read_status(process->out, &filter_status);
865                 if (err)
866                         goto done;
867
868                 err = strcmp(filter_status.buf, "success");
869         }
870
871 done:
872         sigchain_pop(SIGPIPE);
873
874         if (err)
875                 handle_filter_error(&filter_status, entry, wanted_capability);
876         else
877                 strbuf_swap(dst, &nbuf);
878         strbuf_release(&nbuf);
879         return !err;
880 }
881
882
883 int async_query_available_blobs(const char *cmd, struct string_list *available_paths)
884 {
885         int err;
886         char *line;
887         struct cmd2process *entry;
888         struct child_process *process;
889         struct strbuf filter_status = STRBUF_INIT;
890
891         assert(subprocess_map_initialized);
892         entry = (struct cmd2process *)subprocess_find_entry(&subprocess_map, cmd);
893         if (!entry) {
894                 error("external filter '%s' is not available anymore although "
895                       "not all paths have been filtered", cmd);
896                 return 0;
897         }
898         process = &entry->subprocess.process;
899         sigchain_push(SIGPIPE, SIG_IGN);
900
901         err = packet_write_fmt_gently(
902                 process->in, "command=list_available_blobs\n");
903         if (err)
904                 goto done;
905
906         err = packet_flush_gently(process->in);
907         if (err)
908                 goto done;
909
910         while ((line = packet_read_line(process->out, NULL))) {
911                 const char *path;
912                 if (skip_prefix(line, "pathname=", &path))
913                         string_list_insert(available_paths, xstrdup(path));
914                 else
915                         ; /* ignore unknown keys */
916         }
917
918         err = subprocess_read_status(process->out, &filter_status);
919         if (err)
920                 goto done;
921
922         err = strcmp(filter_status.buf, "success");
923
924 done:
925         sigchain_pop(SIGPIPE);
926
927         if (err)
928                 handle_filter_error(&filter_status, entry, 0);
929         return !err;
930 }
931
932 static struct convert_driver {
933         const char *name;
934         struct convert_driver *next;
935         const char *smudge;
936         const char *clean;
937         const char *process;
938         int required;
939 } *user_convert, **user_convert_tail;
940
941 static int apply_filter(const char *path, const char *src, size_t len,
942                         int fd, struct strbuf *dst, struct convert_driver *drv,
943                         const unsigned int wanted_capability,
944                         struct delayed_checkout *dco)
945 {
946         const char *cmd = NULL;
947
948         if (!drv)
949                 return 0;
950
951         if (!dst)
952                 return 1;
953
954         if ((wanted_capability & CAP_CLEAN) && !drv->process && drv->clean)
955                 cmd = drv->clean;
956         else if ((wanted_capability & CAP_SMUDGE) && !drv->process && drv->smudge)
957                 cmd = drv->smudge;
958
959         if (cmd && *cmd)
960                 return apply_single_file_filter(path, src, len, fd, dst, cmd);
961         else if (drv->process && *drv->process)
962                 return apply_multi_file_filter(path, src, len, fd, dst,
963                         drv->process, wanted_capability, dco);
964
965         return 0;
966 }
967
968 static int read_convert_config(const char *var, const char *value, void *cb)
969 {
970         const char *key, *name;
971         int namelen;
972         struct convert_driver *drv;
973
974         /*
975          * External conversion drivers are configured using
976          * "filter.<name>.variable".
977          */
978         if (parse_config_key(var, "filter", &name, &namelen, &key) < 0 || !name)
979                 return 0;
980         for (drv = user_convert; drv; drv = drv->next)
981                 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
982                         break;
983         if (!drv) {
984                 drv = xcalloc(1, sizeof(struct convert_driver));
985                 drv->name = xmemdupz(name, namelen);
986                 *user_convert_tail = drv;
987                 user_convert_tail = &(drv->next);
988         }
989
990         /*
991          * filter.<name>.smudge and filter.<name>.clean specifies
992          * the command line:
993          *
994          *      command-line
995          *
996          * The command-line will not be interpolated in any way.
997          */
998
999         if (!strcmp("smudge", key))
1000                 return git_config_string(&drv->smudge, var, value);
1001
1002         if (!strcmp("clean", key))
1003                 return git_config_string(&drv->clean, var, value);
1004
1005         if (!strcmp("process", key))
1006                 return git_config_string(&drv->process, var, value);
1007
1008         if (!strcmp("required", key)) {
1009                 drv->required = git_config_bool(var, value);
1010                 return 0;
1011         }
1012
1013         return 0;
1014 }
1015
1016 static int count_ident(const char *cp, unsigned long size)
1017 {
1018         /*
1019          * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
1020          */
1021         int cnt = 0;
1022         char ch;
1023
1024         while (size) {
1025                 ch = *cp++;
1026                 size--;
1027                 if (ch != '$')
1028                         continue;
1029                 if (size < 3)
1030                         break;
1031                 if (memcmp("Id", cp, 2))
1032                         continue;
1033                 ch = cp[2];
1034                 cp += 3;
1035                 size -= 3;
1036                 if (ch == '$')
1037                         cnt++; /* $Id$ */
1038                 if (ch != ':')
1039                         continue;
1040
1041                 /*
1042                  * "$Id: ... "; scan up to the closing dollar sign and discard.
1043                  */
1044                 while (size) {
1045                         ch = *cp++;
1046                         size--;
1047                         if (ch == '$') {
1048                                 cnt++;
1049                                 break;
1050                         }
1051                         if (ch == '\n')
1052                                 break;
1053                 }
1054         }
1055         return cnt;
1056 }
1057
1058 static int ident_to_git(const char *path, const char *src, size_t len,
1059                         struct strbuf *buf, int ident)
1060 {
1061         char *dst, *dollar;
1062
1063         if (!ident || (src && !count_ident(src, len)))
1064                 return 0;
1065
1066         if (!buf)
1067                 return 1;
1068
1069         /* only grow if not in place */
1070         if (strbuf_avail(buf) + buf->len < len)
1071                 strbuf_grow(buf, len - buf->len);
1072         dst = buf->buf;
1073         for (;;) {
1074                 dollar = memchr(src, '$', len);
1075                 if (!dollar)
1076                         break;
1077                 memmove(dst, src, dollar + 1 - src);
1078                 dst += dollar + 1 - src;
1079                 len -= dollar + 1 - src;
1080                 src  = dollar + 1;
1081
1082                 if (len > 3 && !memcmp(src, "Id:", 3)) {
1083                         dollar = memchr(src + 3, '$', len - 3);
1084                         if (!dollar)
1085                                 break;
1086                         if (memchr(src + 3, '\n', dollar - src - 3)) {
1087                                 /* Line break before the next dollar. */
1088                                 continue;
1089                         }
1090
1091                         memcpy(dst, "Id$", 3);
1092                         dst += 3;
1093                         len -= dollar + 1 - src;
1094                         src  = dollar + 1;
1095                 }
1096         }
1097         memmove(dst, src, len);
1098         strbuf_setlen(buf, dst + len - buf->buf);
1099         return 1;
1100 }
1101
1102 static int ident_to_worktree(const char *path, const char *src, size_t len,
1103                              struct strbuf *buf, int ident)
1104 {
1105         struct object_id oid;
1106         char *to_free = NULL, *dollar, *spc;
1107         int cnt;
1108
1109         if (!ident)
1110                 return 0;
1111
1112         cnt = count_ident(src, len);
1113         if (!cnt)
1114                 return 0;
1115
1116         /* are we "faking" in place editing ? */
1117         if (src == buf->buf)
1118                 to_free = strbuf_detach(buf, NULL);
1119         hash_object_file(src, len, "blob", &oid);
1120
1121         strbuf_grow(buf, len + cnt * 43);
1122         for (;;) {
1123                 /* step 1: run to the next '$' */
1124                 dollar = memchr(src, '$', len);
1125                 if (!dollar)
1126                         break;
1127                 strbuf_add(buf, src, dollar + 1 - src);
1128                 len -= dollar + 1 - src;
1129                 src  = dollar + 1;
1130
1131                 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
1132                 if (len < 3 || memcmp("Id", src, 2))
1133                         continue;
1134
1135                 /* step 3: skip over Id$ or Id:xxxxx$ */
1136                 if (src[2] == '$') {
1137                         src += 3;
1138                         len -= 3;
1139                 } else if (src[2] == ':') {
1140                         /*
1141                          * It's possible that an expanded Id has crept its way into the
1142                          * repository, we cope with that by stripping the expansion out.
1143                          * This is probably not a good idea, since it will cause changes
1144                          * on checkout, which won't go away by stash, but let's keep it
1145                          * for git-style ids.
1146                          */
1147                         dollar = memchr(src + 3, '$', len - 3);
1148                         if (!dollar) {
1149                                 /* incomplete keyword, no more '$', so just quit the loop */
1150                                 break;
1151                         }
1152
1153                         if (memchr(src + 3, '\n', dollar - src - 3)) {
1154                                 /* Line break before the next dollar. */
1155                                 continue;
1156                         }
1157
1158                         spc = memchr(src + 4, ' ', dollar - src - 4);
1159                         if (spc && spc < dollar-1) {
1160                                 /* There are spaces in unexpected places.
1161                                  * This is probably an id from some other
1162                                  * versioning system. Keep it for now.
1163                                  */
1164                                 continue;
1165                         }
1166
1167                         len -= dollar + 1 - src;
1168                         src  = dollar + 1;
1169                 } else {
1170                         /* it wasn't a "Id$" or "Id:xxxx$" */
1171                         continue;
1172                 }
1173
1174                 /* step 4: substitute */
1175                 strbuf_addstr(buf, "Id: ");
1176                 strbuf_addstr(buf, oid_to_hex(&oid));
1177                 strbuf_addstr(buf, " $");
1178         }
1179         strbuf_add(buf, src, len);
1180
1181         free(to_free);
1182         return 1;
1183 }
1184
1185 static struct encoding *git_path_check_encoding(struct attr_check_item *check)
1186 {
1187         const char *value = check->value;
1188         struct encoding *enc;
1189
1190         if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value) ||
1191             !strlen(value))
1192                 return NULL;
1193
1194         for (enc = encoding; enc; enc = enc->next)
1195                 if (!strcasecmp(value, enc->name))
1196                         return enc;
1197
1198         /* Don't encode to the default encoding */
1199         if (!strcasecmp(value, default_encoding))
1200                 return NULL;
1201
1202         enc = xcalloc(1, sizeof(*enc));
1203         /*
1204          * Ensure encoding names are always upper case (e.g. UTF-8) to
1205          * simplify subsequent string comparisons.
1206          */
1207         enc->name = xstrdup_toupper(value);
1208         *encoding_tail = enc;
1209         encoding_tail = &(enc->next);
1210
1211         return enc;
1212 }
1213
1214 static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
1215 {
1216         const char *value = check->value;
1217
1218         if (ATTR_TRUE(value))
1219                 return CRLF_TEXT;
1220         else if (ATTR_FALSE(value))
1221                 return CRLF_BINARY;
1222         else if (ATTR_UNSET(value))
1223                 ;
1224         else if (!strcmp(value, "input"))
1225                 return CRLF_TEXT_INPUT;
1226         else if (!strcmp(value, "auto"))
1227                 return CRLF_AUTO;
1228         return CRLF_UNDEFINED;
1229 }
1230
1231 static enum eol git_path_check_eol(struct attr_check_item *check)
1232 {
1233         const char *value = check->value;
1234
1235         if (ATTR_UNSET(value))
1236                 ;
1237         else if (!strcmp(value, "lf"))
1238                 return EOL_LF;
1239         else if (!strcmp(value, "crlf"))
1240                 return EOL_CRLF;
1241         return EOL_UNSET;
1242 }
1243
1244 static struct convert_driver *git_path_check_convert(struct attr_check_item *check)
1245 {
1246         const char *value = check->value;
1247         struct convert_driver *drv;
1248
1249         if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
1250                 return NULL;
1251         for (drv = user_convert; drv; drv = drv->next)
1252                 if (!strcmp(value, drv->name))
1253                         return drv;
1254         return NULL;
1255 }
1256
1257 static int git_path_check_ident(struct attr_check_item *check)
1258 {
1259         const char *value = check->value;
1260
1261         return !!ATTR_TRUE(value);
1262 }
1263
1264 struct conv_attrs {
1265         struct convert_driver *drv;
1266         enum crlf_action attr_action; /* What attr says */
1267         enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
1268         int ident;
1269         struct encoding *working_tree_encoding; /* Supported encoding or default encoding if NULL */
1270 };
1271
1272 static void convert_attrs(struct conv_attrs *ca, const char *path)
1273 {
1274         static struct attr_check *check;
1275
1276         if (!check) {
1277                 check = attr_check_initl("crlf", "ident", "filter",
1278                                          "eol", "text", "working-tree-encoding",
1279                                          NULL);
1280                 user_convert_tail = &user_convert;
1281                 encoding_tail = &encoding;
1282                 git_config(read_convert_config, NULL);
1283         }
1284
1285         if (!git_check_attr(path, check)) {
1286                 struct attr_check_item *ccheck = check->items;
1287                 ca->crlf_action = git_path_check_crlf(ccheck + 4);
1288                 if (ca->crlf_action == CRLF_UNDEFINED)
1289                         ca->crlf_action = git_path_check_crlf(ccheck + 0);
1290                 ca->ident = git_path_check_ident(ccheck + 1);
1291                 ca->drv = git_path_check_convert(ccheck + 2);
1292                 if (ca->crlf_action != CRLF_BINARY) {
1293                         enum eol eol_attr = git_path_check_eol(ccheck + 3);
1294                         if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_LF)
1295                                 ca->crlf_action = CRLF_AUTO_INPUT;
1296                         else if (ca->crlf_action == CRLF_AUTO && eol_attr == EOL_CRLF)
1297                                 ca->crlf_action = CRLF_AUTO_CRLF;
1298                         else if (eol_attr == EOL_LF)
1299                                 ca->crlf_action = CRLF_TEXT_INPUT;
1300                         else if (eol_attr == EOL_CRLF)
1301                                 ca->crlf_action = CRLF_TEXT_CRLF;
1302                 }
1303                 ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
1304         } else {
1305                 ca->drv = NULL;
1306                 ca->crlf_action = CRLF_UNDEFINED;
1307                 ca->ident = 0;
1308         }
1309
1310         /* Save attr and make a decision for action */
1311         ca->attr_action = ca->crlf_action;
1312         if (ca->crlf_action == CRLF_TEXT)
1313                 ca->crlf_action = text_eol_is_crlf() ? CRLF_TEXT_CRLF : CRLF_TEXT_INPUT;
1314         if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_FALSE)
1315                 ca->crlf_action = CRLF_BINARY;
1316         if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_TRUE)
1317                 ca->crlf_action = CRLF_AUTO_CRLF;
1318         if (ca->crlf_action == CRLF_UNDEFINED && auto_crlf == AUTO_CRLF_INPUT)
1319                 ca->crlf_action = CRLF_AUTO_INPUT;
1320 }
1321
1322 int would_convert_to_git_filter_fd(const char *path)
1323 {
1324         struct conv_attrs ca;
1325
1326         convert_attrs(&ca, path);
1327         if (!ca.drv)
1328                 return 0;
1329
1330         /*
1331          * Apply a filter to an fd only if the filter is required to succeed.
1332          * We must die if the filter fails, because the original data before
1333          * filtering is not available.
1334          */
1335         if (!ca.drv->required)
1336                 return 0;
1337
1338         return apply_filter(path, NULL, 0, -1, NULL, ca.drv, CAP_CLEAN, NULL);
1339 }
1340
1341 const char *get_convert_attr_ascii(const char *path)
1342 {
1343         struct conv_attrs ca;
1344
1345         convert_attrs(&ca, path);
1346         switch (ca.attr_action) {
1347         case CRLF_UNDEFINED:
1348                 return "";
1349         case CRLF_BINARY:
1350                 return "-text";
1351         case CRLF_TEXT:
1352                 return "text";
1353         case CRLF_TEXT_INPUT:
1354                 return "text eol=lf";
1355         case CRLF_TEXT_CRLF:
1356                 return "text eol=crlf";
1357         case CRLF_AUTO:
1358                 return "text=auto";
1359         case CRLF_AUTO_CRLF:
1360                 return "text=auto eol=crlf";
1361         case CRLF_AUTO_INPUT:
1362                 return "text=auto eol=lf";
1363         }
1364         return "";
1365 }
1366
1367 int convert_to_git(const struct index_state *istate,
1368                    const char *path, const char *src, size_t len,
1369                    struct strbuf *dst, int conv_flags)
1370 {
1371         int ret = 0;
1372         struct conv_attrs ca;
1373
1374         convert_attrs(&ca, path);
1375
1376         ret |= apply_filter(path, src, len, -1, dst, ca.drv, CAP_CLEAN, NULL);
1377         if (!ret && ca.drv && ca.drv->required)
1378                 die("%s: clean filter '%s' failed", path, ca.drv->name);
1379
1380         if (ret && dst) {
1381                 src = dst->buf;
1382                 len = dst->len;
1383         }
1384
1385         ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
1386         if (ret && dst) {
1387                 src = dst->buf;
1388                 len = dst->len;
1389         }
1390
1391         if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
1392                 ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
1393                 if (ret && dst) {
1394                         src = dst->buf;
1395                         len = dst->len;
1396                 }
1397         }
1398         return ret | ident_to_git(path, src, len, dst, ca.ident);
1399 }
1400
1401 void convert_to_git_filter_fd(const struct index_state *istate,
1402                               const char *path, int fd, struct strbuf *dst,
1403                               int conv_flags)
1404 {
1405         struct conv_attrs ca;
1406         convert_attrs(&ca, path);
1407
1408         assert(ca.drv);
1409         assert(ca.drv->clean || ca.drv->process);
1410
1411         if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL))
1412                 die("%s: clean filter '%s' failed", path, ca.drv->name);
1413
1414         encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
1415         crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
1416         ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
1417 }
1418
1419 static int convert_to_working_tree_internal(const char *path, const char *src,
1420                                             size_t len, struct strbuf *dst,
1421                                             int normalizing, struct delayed_checkout *dco)
1422 {
1423         int ret = 0, ret_filter = 0;
1424         struct conv_attrs ca;
1425
1426         convert_attrs(&ca, path);
1427
1428         ret |= ident_to_worktree(path, src, len, dst, ca.ident);
1429         if (ret) {
1430                 src = dst->buf;
1431                 len = dst->len;
1432         }
1433         /*
1434          * CRLF conversion can be skipped if normalizing, unless there
1435          * is a smudge or process filter (even if the process filter doesn't
1436          * support smudge).  The filters might expect CRLFs.
1437          */
1438         if ((ca.drv && (ca.drv->smudge || ca.drv->process)) || !normalizing) {
1439                 ret |= crlf_to_worktree(path, src, len, dst, ca.crlf_action);
1440                 if (ret) {
1441                         src = dst->buf;
1442                         len = dst->len;
1443                 }
1444         }
1445
1446         ret |= encode_to_worktree(path, src, len, dst, ca.working_tree_encoding);
1447         if (ret) {
1448                 src = dst->buf;
1449                 len = dst->len;
1450         }
1451
1452         ret_filter = apply_filter(
1453                 path, src, len, -1, dst, ca.drv, CAP_SMUDGE, dco);
1454         if (!ret_filter && ca.drv && ca.drv->required)
1455                 die("%s: smudge filter %s failed", path, ca.drv->name);
1456
1457         return ret | ret_filter;
1458 }
1459
1460 int async_convert_to_working_tree(const char *path, const char *src,
1461                                   size_t len, struct strbuf *dst,
1462                                   void *dco)
1463 {
1464         return convert_to_working_tree_internal(path, src, len, dst, 0, dco);
1465 }
1466
1467 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
1468 {
1469         return convert_to_working_tree_internal(path, src, len, dst, 0, NULL);
1470 }
1471
1472 int renormalize_buffer(const struct index_state *istate, const char *path,
1473                        const char *src, size_t len, struct strbuf *dst)
1474 {
1475         int ret = convert_to_working_tree_internal(path, src, len, dst, 1, NULL);
1476         if (ret) {
1477                 src = dst->buf;
1478                 len = dst->len;
1479         }
1480         return ret | convert_to_git(istate, path, src, len, dst, CONV_EOL_RENORMALIZE);
1481 }
1482
1483 /*****************************************************************
1484  *
1485  * Streaming conversion support
1486  *
1487  *****************************************************************/
1488
1489 typedef int (*filter_fn)(struct stream_filter *,
1490                          const char *input, size_t *isize_p,
1491                          char *output, size_t *osize_p);
1492 typedef void (*free_fn)(struct stream_filter *);
1493
1494 struct stream_filter_vtbl {
1495         filter_fn filter;
1496         free_fn free;
1497 };
1498
1499 struct stream_filter {
1500         struct stream_filter_vtbl *vtbl;
1501 };
1502
1503 static int null_filter_fn(struct stream_filter *filter,
1504                           const char *input, size_t *isize_p,
1505                           char *output, size_t *osize_p)
1506 {
1507         size_t count;
1508
1509         if (!input)
1510                 return 0; /* we do not keep any states */
1511         count = *isize_p;
1512         if (*osize_p < count)
1513                 count = *osize_p;
1514         if (count) {
1515                 memmove(output, input, count);
1516                 *isize_p -= count;
1517                 *osize_p -= count;
1518         }
1519         return 0;
1520 }
1521
1522 static void null_free_fn(struct stream_filter *filter)
1523 {
1524         ; /* nothing -- null instances are shared */
1525 }
1526
1527 static struct stream_filter_vtbl null_vtbl = {
1528         null_filter_fn,
1529         null_free_fn,
1530 };
1531
1532 static struct stream_filter null_filter_singleton = {
1533         &null_vtbl,
1534 };
1535
1536 int is_null_stream_filter(struct stream_filter *filter)
1537 {
1538         return filter == &null_filter_singleton;
1539 }
1540
1541
1542 /*
1543  * LF-to-CRLF filter
1544  */
1545
1546 struct lf_to_crlf_filter {
1547         struct stream_filter filter;
1548         unsigned has_held:1;
1549         char held;
1550 };
1551
1552 static int lf_to_crlf_filter_fn(struct stream_filter *filter,
1553                                 const char *input, size_t *isize_p,
1554                                 char *output, size_t *osize_p)
1555 {
1556         size_t count, o = 0;
1557         struct lf_to_crlf_filter *lf_to_crlf = (struct lf_to_crlf_filter *)filter;
1558
1559         /*
1560          * We may be holding onto the CR to see if it is followed by a
1561          * LF, in which case we would need to go to the main loop.
1562          * Otherwise, just emit it to the output stream.
1563          */
1564         if (lf_to_crlf->has_held && (lf_to_crlf->held != '\r' || !input)) {
1565                 output[o++] = lf_to_crlf->held;
1566                 lf_to_crlf->has_held = 0;
1567         }
1568
1569         /* We are told to drain */
1570         if (!input) {
1571                 *osize_p -= o;
1572                 return 0;
1573         }
1574
1575         count = *isize_p;
1576         if (count || lf_to_crlf->has_held) {
1577                 size_t i;
1578                 int was_cr = 0;
1579
1580                 if (lf_to_crlf->has_held) {
1581                         was_cr = 1;
1582                         lf_to_crlf->has_held = 0;
1583                 }
1584
1585                 for (i = 0; o < *osize_p && i < count; i++) {
1586                         char ch = input[i];
1587
1588                         if (ch == '\n') {
1589                                 output[o++] = '\r';
1590                         } else if (was_cr) {
1591                                 /*
1592                                  * Previous round saw CR and it is not followed
1593                                  * by a LF; emit the CR before processing the
1594                                  * current character.
1595                                  */
1596                                 output[o++] = '\r';
1597                         }
1598
1599                         /*
1600                          * We may have consumed the last output slot,
1601                          * in which case we need to break out of this
1602                          * loop; hold the current character before
1603                          * returning.
1604                          */
1605                         if (*osize_p <= o) {
1606                                 lf_to_crlf->has_held = 1;
1607                                 lf_to_crlf->held = ch;
1608                                 continue; /* break but increment i */
1609                         }
1610
1611                         if (ch == '\r') {
1612                                 was_cr = 1;
1613                                 continue;
1614                         }
1615
1616                         was_cr = 0;
1617                         output[o++] = ch;
1618                 }
1619
1620                 *osize_p -= o;
1621                 *isize_p -= i;
1622
1623                 if (!lf_to_crlf->has_held && was_cr) {
1624                         lf_to_crlf->has_held = 1;
1625                         lf_to_crlf->held = '\r';
1626                 }
1627         }
1628         return 0;
1629 }
1630
1631 static void lf_to_crlf_free_fn(struct stream_filter *filter)
1632 {
1633         free(filter);
1634 }
1635
1636 static struct stream_filter_vtbl lf_to_crlf_vtbl = {
1637         lf_to_crlf_filter_fn,
1638         lf_to_crlf_free_fn,
1639 };
1640
1641 static struct stream_filter *lf_to_crlf_filter(void)
1642 {
1643         struct lf_to_crlf_filter *lf_to_crlf = xcalloc(1, sizeof(*lf_to_crlf));
1644
1645         lf_to_crlf->filter.vtbl = &lf_to_crlf_vtbl;
1646         return (struct stream_filter *)lf_to_crlf;
1647 }
1648
1649 /*
1650  * Cascade filter
1651  */
1652 #define FILTER_BUFFER 1024
1653 struct cascade_filter {
1654         struct stream_filter filter;
1655         struct stream_filter *one;
1656         struct stream_filter *two;
1657         char buf[FILTER_BUFFER];
1658         int end, ptr;
1659 };
1660
1661 static int cascade_filter_fn(struct stream_filter *filter,
1662                              const char *input, size_t *isize_p,
1663                              char *output, size_t *osize_p)
1664 {
1665         struct cascade_filter *cas = (struct cascade_filter *) filter;
1666         size_t filled = 0;
1667         size_t sz = *osize_p;
1668         size_t to_feed, remaining;
1669
1670         /*
1671          * input -- (one) --> buf -- (two) --> output
1672          */
1673         while (filled < sz) {
1674                 remaining = sz - filled;
1675
1676                 /* do we already have something to feed two with? */
1677                 if (cas->ptr < cas->end) {
1678                         to_feed = cas->end - cas->ptr;
1679                         if (stream_filter(cas->two,
1680                                           cas->buf + cas->ptr, &to_feed,
1681                                           output + filled, &remaining))
1682                                 return -1;
1683                         cas->ptr += (cas->end - cas->ptr) - to_feed;
1684                         filled = sz - remaining;
1685                         continue;
1686                 }
1687
1688                 /* feed one from upstream and have it emit into our buffer */
1689                 to_feed = input ? *isize_p : 0;
1690                 if (input && !to_feed)
1691                         break;
1692                 remaining = sizeof(cas->buf);
1693                 if (stream_filter(cas->one,
1694                                   input, &to_feed,
1695                                   cas->buf, &remaining))
1696                         return -1;
1697                 cas->end = sizeof(cas->buf) - remaining;
1698                 cas->ptr = 0;
1699                 if (input) {
1700                         size_t fed = *isize_p - to_feed;
1701                         *isize_p -= fed;
1702                         input += fed;
1703                 }
1704
1705                 /* do we know that we drained one completely? */
1706                 if (input || cas->end)
1707                         continue;
1708
1709                 /* tell two to drain; we have nothing more to give it */
1710                 to_feed = 0;
1711                 remaining = sz - filled;
1712                 if (stream_filter(cas->two,
1713                                   NULL, &to_feed,
1714                                   output + filled, &remaining))
1715                         return -1;
1716                 if (remaining == (sz - filled))
1717                         break; /* completely drained two */
1718                 filled = sz - remaining;
1719         }
1720         *osize_p -= filled;
1721         return 0;
1722 }
1723
1724 static void cascade_free_fn(struct stream_filter *filter)
1725 {
1726         struct cascade_filter *cas = (struct cascade_filter *)filter;
1727         free_stream_filter(cas->one);
1728         free_stream_filter(cas->two);
1729         free(filter);
1730 }
1731
1732 static struct stream_filter_vtbl cascade_vtbl = {
1733         cascade_filter_fn,
1734         cascade_free_fn,
1735 };
1736
1737 static struct stream_filter *cascade_filter(struct stream_filter *one,
1738                                             struct stream_filter *two)
1739 {
1740         struct cascade_filter *cascade;
1741
1742         if (!one || is_null_stream_filter(one))
1743                 return two;
1744         if (!two || is_null_stream_filter(two))
1745                 return one;
1746
1747         cascade = xmalloc(sizeof(*cascade));
1748         cascade->one = one;
1749         cascade->two = two;
1750         cascade->end = cascade->ptr = 0;
1751         cascade->filter.vtbl = &cascade_vtbl;
1752         return (struct stream_filter *)cascade;
1753 }
1754
1755 /*
1756  * ident filter
1757  */
1758 #define IDENT_DRAINING (-1)
1759 #define IDENT_SKIPPING (-2)
1760 struct ident_filter {
1761         struct stream_filter filter;
1762         struct strbuf left;
1763         int state;
1764         char ident[45]; /* ": x40 $" */
1765 };
1766
1767 static int is_foreign_ident(const char *str)
1768 {
1769         int i;
1770
1771         if (!skip_prefix(str, "$Id: ", &str))
1772                 return 0;
1773         for (i = 0; str[i]; i++) {
1774                 if (isspace(str[i]) && str[i+1] != '$')
1775                         return 1;
1776         }
1777         return 0;
1778 }
1779
1780 static void ident_drain(struct ident_filter *ident, char **output_p, size_t *osize_p)
1781 {
1782         size_t to_drain = ident->left.len;
1783
1784         if (*osize_p < to_drain)
1785                 to_drain = *osize_p;
1786         if (to_drain) {
1787                 memcpy(*output_p, ident->left.buf, to_drain);
1788                 strbuf_remove(&ident->left, 0, to_drain);
1789                 *output_p += to_drain;
1790                 *osize_p -= to_drain;
1791         }
1792         if (!ident->left.len)
1793                 ident->state = 0;
1794 }
1795
1796 static int ident_filter_fn(struct stream_filter *filter,
1797                            const char *input, size_t *isize_p,
1798                            char *output, size_t *osize_p)
1799 {
1800         struct ident_filter *ident = (struct ident_filter *)filter;
1801         static const char head[] = "$Id";
1802
1803         if (!input) {
1804                 /* drain upon eof */
1805                 switch (ident->state) {
1806                 default:
1807                         strbuf_add(&ident->left, head, ident->state);
1808                         /* fallthrough */
1809                 case IDENT_SKIPPING:
1810                         /* fallthrough */
1811                 case IDENT_DRAINING:
1812                         ident_drain(ident, &output, osize_p);
1813                 }
1814                 return 0;
1815         }
1816
1817         while (*isize_p || (ident->state == IDENT_DRAINING)) {
1818                 int ch;
1819
1820                 if (ident->state == IDENT_DRAINING) {
1821                         ident_drain(ident, &output, osize_p);
1822                         if (!*osize_p)
1823                                 break;
1824                         continue;
1825                 }
1826
1827                 ch = *(input++);
1828                 (*isize_p)--;
1829
1830                 if (ident->state == IDENT_SKIPPING) {
1831                         /*
1832                          * Skipping until '$' or LF, but keeping them
1833                          * in case it is a foreign ident.
1834                          */
1835                         strbuf_addch(&ident->left, ch);
1836                         if (ch != '\n' && ch != '$')
1837                                 continue;
1838                         if (ch == '$' && !is_foreign_ident(ident->left.buf)) {
1839                                 strbuf_setlen(&ident->left, sizeof(head) - 1);
1840                                 strbuf_addstr(&ident->left, ident->ident);
1841                         }
1842                         ident->state = IDENT_DRAINING;
1843                         continue;
1844                 }
1845
1846                 if (ident->state < sizeof(head) &&
1847                     head[ident->state] == ch) {
1848                         ident->state++;
1849                         continue;
1850                 }
1851
1852                 if (ident->state)
1853                         strbuf_add(&ident->left, head, ident->state);
1854                 if (ident->state == sizeof(head) - 1) {
1855                         if (ch != ':' && ch != '$') {
1856                                 strbuf_addch(&ident->left, ch);
1857                                 ident->state = 0;
1858                                 continue;
1859                         }
1860
1861                         if (ch == ':') {
1862                                 strbuf_addch(&ident->left, ch);
1863                                 ident->state = IDENT_SKIPPING;
1864                         } else {
1865                                 strbuf_addstr(&ident->left, ident->ident);
1866                                 ident->state = IDENT_DRAINING;
1867                         }
1868                         continue;
1869                 }
1870
1871                 strbuf_addch(&ident->left, ch);
1872                 ident->state = IDENT_DRAINING;
1873         }
1874         return 0;
1875 }
1876
1877 static void ident_free_fn(struct stream_filter *filter)
1878 {
1879         struct ident_filter *ident = (struct ident_filter *)filter;
1880         strbuf_release(&ident->left);
1881         free(filter);
1882 }
1883
1884 static struct stream_filter_vtbl ident_vtbl = {
1885         ident_filter_fn,
1886         ident_free_fn,
1887 };
1888
1889 static struct stream_filter *ident_filter(const unsigned char *sha1)
1890 {
1891         struct ident_filter *ident = xmalloc(sizeof(*ident));
1892
1893         xsnprintf(ident->ident, sizeof(ident->ident),
1894                   ": %s $", sha1_to_hex(sha1));
1895         strbuf_init(&ident->left, 0);
1896         ident->filter.vtbl = &ident_vtbl;
1897         ident->state = 0;
1898         return (struct stream_filter *)ident;
1899 }
1900
1901 /*
1902  * Return an appropriately constructed filter for the path, or NULL if
1903  * the contents cannot be filtered without reading the whole thing
1904  * in-core.
1905  *
1906  * Note that you would be crazy to set CRLF, smuge/clean or ident to a
1907  * large binary blob you would want us not to slurp into the memory!
1908  */
1909 struct stream_filter *get_stream_filter(const char *path, const unsigned char *sha1)
1910 {
1911         struct conv_attrs ca;
1912         struct stream_filter *filter = NULL;
1913
1914         convert_attrs(&ca, path);
1915         if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
1916                 return NULL;
1917
1918         if (ca.working_tree_encoding)
1919                 return NULL;
1920
1921         if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
1922                 return NULL;
1923
1924         if (ca.ident)
1925                 filter = ident_filter(sha1);
1926
1927         if (output_eol(ca.crlf_action) == EOL_CRLF)
1928                 filter = cascade_filter(filter, lf_to_crlf_filter());
1929         else
1930                 filter = cascade_filter(filter, &null_filter_singleton);
1931
1932         return filter;
1933 }
1934
1935 void free_stream_filter(struct stream_filter *filter)
1936 {
1937         filter->vtbl->free(filter);
1938 }
1939
1940 int stream_filter(struct stream_filter *filter,
1941                   const char *input, size_t *isize_p,
1942                   char *output, size_t *osize_p)
1943 {
1944         return filter->vtbl->filter(filter, input, isize_p, output, osize_p);
1945 }