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