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