1#include "cache.h"
2#include "attr.h"
3#include "run-command.h"
4
5/*
6 * convert.c - convert a file when checking it out and checking it in.
7 *
8 * This should use the pathname to decide on whether it wants to do some
9 * more interesting conversions (automatic gzip/unzip, general format
10 * conversions etc etc), but by default it just does automatic CRLF<->LF
11 * translation when the "text" attribute or "auto_crlf" option is set.
12 */
13
14enum action {
15 CRLF_GUESS = -1,
16 CRLF_BINARY = 0,
17 CRLF_TEXT,
18 CRLF_INPUT,
19 CRLF_CRLF,
20 CRLF_AUTO,
21};
22
23struct text_stat {
24 /* NUL, CR, LF and CRLF counts */
25 unsigned nul, cr, lf, crlf;
26
27 /* These are just approximations! */
28 unsigned printable, nonprintable;
29};
30
31static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
32{
33 unsigned long i;
34
35 memset(stats, 0, sizeof(*stats));
36
37 for (i = 0; i < size; i++) {
38 unsigned char c = buf[i];
39 if (c == '\r') {
40 stats->cr++;
41 if (i+1 < size && buf[i+1] == '\n')
42 stats->crlf++;
43 continue;
44 }
45 if (c == '\n') {
46 stats->lf++;
47 continue;
48 }
49 if (c == 127)
50 /* DEL */
51 stats->nonprintable++;
52 else if (c < 32) {
53 switch (c) {
54 /* BS, HT, ESC and FF */
55 case '\b': case '\t': case '\033': case '\014':
56 stats->printable++;
57 break;
58 case 0:
59 stats->nul++;
60 /* fall through */
61 default:
62 stats->nonprintable++;
63 }
64 }
65 else
66 stats->printable++;
67 }
68
69 /* If file ends with EOF then don't count this EOF as non-printable. */
70 if (size >= 1 && buf[size-1] == '\032')
71 stats->nonprintable--;
72}
73
74/*
75 * The same heuristics as diff.c::mmfile_is_binary()
76 */
77static int is_binary(unsigned long size, struct text_stat *stats)
78{
79
80 if (stats->nul)
81 return 1;
82 if ((stats->printable >> 7) < stats->nonprintable)
83 return 1;
84 /*
85 * Other heuristics? Average line length might be relevant,
86 * as might LF vs CR vs CRLF counts..
87 *
88 * NOTE! It might be normal to have a low ratio of CRLF to LF
89 * (somebody starts with a LF-only file and edits it with an editor
90 * that adds CRLF only to lines that are added..). But do we
91 * want to support CR-only? Probably not.
92 */
93 return 0;
94}
95
96static enum eol determine_output_conversion(enum action action)
97{
98 switch (action) {
99 case CRLF_BINARY:
100 return EOL_UNSET;
101 case CRLF_CRLF:
102 return EOL_CRLF;
103 case CRLF_INPUT:
104 return EOL_LF;
105 case CRLF_GUESS:
106 if (!auto_crlf)
107 return EOL_UNSET;
108 /* fall through */
109 case CRLF_TEXT:
110 case CRLF_AUTO:
111 if (auto_crlf == AUTO_CRLF_TRUE)
112 return EOL_CRLF;
113 else if (auto_crlf == AUTO_CRLF_INPUT)
114 return EOL_LF;
115 else if (eol == EOL_UNSET)
116 return EOL_NATIVE;
117 }
118 return eol;
119}
120
121static void check_safe_crlf(const char *path, enum action action,
122 struct text_stat *stats, enum safe_crlf checksafe)
123{
124 if (!checksafe)
125 return;
126
127 if (determine_output_conversion(action) == EOL_LF) {
128 /*
129 * CRLFs would not be restored by checkout:
130 * check if we'd remove CRLFs
131 */
132 if (stats->crlf) {
133 if (checksafe == SAFE_CRLF_WARN)
134 warning("CRLF will be replaced by LF in %s.\nThe file will have its original line endings in your working directory.", path);
135 else /* i.e. SAFE_CRLF_FAIL */
136 die("CRLF would be replaced by LF in %s.", path);
137 }
138 } else if (determine_output_conversion(action) == EOL_CRLF) {
139 /*
140 * CRLFs would be added by checkout:
141 * check if we have "naked" LFs
142 */
143 if (stats->lf != stats->crlf) {
144 if (checksafe == SAFE_CRLF_WARN)
145 warning("LF will be replaced by CRLF in %s.\nThe file will have its original line endings in your working directory.", path);
146 else /* i.e. SAFE_CRLF_FAIL */
147 die("LF would be replaced by CRLF in %s", path);
148 }
149 }
150}
151
152static int has_cr_in_index(const char *path)
153{
154 int pos, len;
155 unsigned long sz;
156 enum object_type type;
157 void *data;
158 int has_cr;
159 struct index_state *istate = &the_index;
160
161 len = strlen(path);
162 pos = index_name_pos(istate, path, len);
163 if (pos < 0) {
164 /*
165 * We might be in the middle of a merge, in which
166 * case we would read stage #2 (ours).
167 */
168 int i;
169 for (i = -pos - 1;
170 (pos < 0 && i < istate->cache_nr &&
171 !strcmp(istate->cache[i]->name, path));
172 i++)
173 if (ce_stage(istate->cache[i]) == 2)
174 pos = i;
175 }
176 if (pos < 0)
177 return 0;
178 data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
179 if (!data || type != OBJ_BLOB) {
180 free(data);
181 return 0;
182 }
183
184 has_cr = memchr(data, '\r', sz) != NULL;
185 free(data);
186 return has_cr;
187}
188
189static int crlf_to_git(const char *path, const char *src, size_t len,
190 struct strbuf *buf, enum action action, enum safe_crlf checksafe)
191{
192 struct text_stat stats;
193 char *dst;
194
195 if (action == CRLF_BINARY ||
196 (action == CRLF_GUESS && auto_crlf == AUTO_CRLF_FALSE) || !len)
197 return 0;
198
199 gather_stats(src, len, &stats);
200
201 if (action == CRLF_AUTO || action == CRLF_GUESS) {
202 /*
203 * We're currently not going to even try to convert stuff
204 * that has bare CR characters. Does anybody do that crazy
205 * stuff?
206 */
207 if (stats.cr != stats.crlf)
208 return 0;
209
210 /*
211 * And add some heuristics for binary vs text, of course...
212 */
213 if (is_binary(len, &stats))
214 return 0;
215
216 if (action == CRLF_GUESS) {
217 /*
218 * If the file in the index has any CR in it, do not convert.
219 * This is the new safer autocrlf handling.
220 */
221 if (has_cr_in_index(path))
222 return 0;
223 }
224 }
225
226 check_safe_crlf(path, action, &stats, checksafe);
227
228 /* Optimization: No CR? Nothing to convert, regardless. */
229 if (!stats.cr)
230 return 0;
231
232 /* only grow if not in place */
233 if (strbuf_avail(buf) + buf->len < len)
234 strbuf_grow(buf, len - buf->len);
235 dst = buf->buf;
236 if (action == CRLF_AUTO || action == CRLF_GUESS) {
237 /*
238 * If we guessed, we already know we rejected a file with
239 * lone CR, and we can strip a CR without looking at what
240 * follow it.
241 */
242 do {
243 unsigned char c = *src++;
244 if (c != '\r')
245 *dst++ = c;
246 } while (--len);
247 } else {
248 do {
249 unsigned char c = *src++;
250 if (! (c == '\r' && (1 < len && *src == '\n')))
251 *dst++ = c;
252 } while (--len);
253 }
254 strbuf_setlen(buf, dst - buf->buf);
255 return 1;
256}
257
258static int crlf_to_worktree(const char *path, const char *src, size_t len,
259 struct strbuf *buf, enum action action)
260{
261 char *to_free = NULL;
262 struct text_stat stats;
263
264 if (!len || determine_output_conversion(action) != EOL_CRLF)
265 return 0;
266
267 gather_stats(src, len, &stats);
268
269 /* No LF? Nothing to convert, regardless. */
270 if (!stats.lf)
271 return 0;
272
273 /* Was it already in CRLF format? */
274 if (stats.lf == stats.crlf)
275 return 0;
276
277 if (action == CRLF_AUTO || action == CRLF_GUESS) {
278 if (action == CRLF_GUESS) {
279 /* If we have any CR or CRLF line endings, we do not touch it */
280 /* This is the new safer autocrlf-handling */
281 if (stats.cr > 0 || stats.crlf > 0)
282 return 0;
283 }
284
285 /* If we have any bare CR characters, we're not going to touch it */
286 if (stats.cr != stats.crlf)
287 return 0;
288
289 if (is_binary(len, &stats))
290 return 0;
291 }
292
293 /* are we "faking" in place editing ? */
294 if (src == buf->buf)
295 to_free = strbuf_detach(buf, NULL);
296
297 strbuf_grow(buf, len + stats.lf - stats.crlf);
298 for (;;) {
299 const char *nl = memchr(src, '\n', len);
300 if (!nl)
301 break;
302 if (nl > src && nl[-1] == '\r') {
303 strbuf_add(buf, src, nl + 1 - src);
304 } else {
305 strbuf_add(buf, src, nl - src);
306 strbuf_addstr(buf, "\r\n");
307 }
308 len -= nl + 1 - src;
309 src = nl + 1;
310 }
311 strbuf_add(buf, src, len);
312
313 free(to_free);
314 return 1;
315}
316
317struct filter_params {
318 const char *src;
319 unsigned long size;
320 const char *cmd;
321};
322
323static int filter_buffer(int in, int out, void *data)
324{
325 /*
326 * Spawn cmd and feed the buffer contents through its stdin.
327 */
328 struct child_process child_process;
329 struct filter_params *params = (struct filter_params *)data;
330 int write_err, status;
331 const char *argv[] = { NULL, NULL };
332
333 argv[0] = params->cmd;
334
335 memset(&child_process, 0, sizeof(child_process));
336 child_process.argv = argv;
337 child_process.use_shell = 1;
338 child_process.in = -1;
339 child_process.out = out;
340
341 if (start_command(&child_process))
342 return error("cannot fork to run external filter %s", params->cmd);
343
344 write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
345 if (close(child_process.in))
346 write_err = 1;
347 if (write_err)
348 error("cannot feed the input to external filter %s", params->cmd);
349
350 status = finish_command(&child_process);
351 if (status)
352 error("external filter %s failed %d", params->cmd, status);
353 return (write_err || status);
354}
355
356static int apply_filter(const char *path, const char *src, size_t len,
357 struct strbuf *dst, const char *cmd)
358{
359 /*
360 * Create a pipeline to have the command filter the buffer's
361 * contents.
362 *
363 * (child --> cmd) --> us
364 */
365 int ret = 1;
366 struct strbuf nbuf = STRBUF_INIT;
367 struct async async;
368 struct filter_params params;
369
370 if (!cmd)
371 return 0;
372
373 memset(&async, 0, sizeof(async));
374 async.proc = filter_buffer;
375 async.data = ¶ms;
376 async.out = -1;
377 params.src = src;
378 params.size = len;
379 params.cmd = cmd;
380
381 fflush(NULL);
382 if (start_async(&async))
383 return 0; /* error was already reported */
384
385 if (strbuf_read(&nbuf, async.out, len) < 0) {
386 error("read from external filter %s failed", cmd);
387 ret = 0;
388 }
389 if (close(async.out)) {
390 error("read from external filter %s failed", cmd);
391 ret = 0;
392 }
393 if (finish_async(&async)) {
394 error("external filter %s failed", cmd);
395 ret = 0;
396 }
397
398 if (ret) {
399 strbuf_swap(dst, &nbuf);
400 }
401 strbuf_release(&nbuf);
402 return ret;
403}
404
405static struct convert_driver {
406 const char *name;
407 struct convert_driver *next;
408 const char *smudge;
409 const char *clean;
410} *user_convert, **user_convert_tail;
411
412static int read_convert_config(const char *var, const char *value, void *cb)
413{
414 const char *ep, *name;
415 int namelen;
416 struct convert_driver *drv;
417
418 /*
419 * External conversion drivers are configured using
420 * "filter.<name>.variable".
421 */
422 if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
423 return 0;
424 name = var + 7;
425 namelen = ep - name;
426 for (drv = user_convert; drv; drv = drv->next)
427 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
428 break;
429 if (!drv) {
430 drv = xcalloc(1, sizeof(struct convert_driver));
431 drv->name = xmemdupz(name, namelen);
432 *user_convert_tail = drv;
433 user_convert_tail = &(drv->next);
434 }
435
436 ep++;
437
438 /*
439 * filter.<name>.smudge and filter.<name>.clean specifies
440 * the command line:
441 *
442 * command-line
443 *
444 * The command-line will not be interpolated in any way.
445 */
446
447 if (!strcmp("smudge", ep))
448 return git_config_string(&drv->smudge, var, value);
449
450 if (!strcmp("clean", ep))
451 return git_config_string(&drv->clean, var, value);
452
453 return 0;
454}
455
456static void setup_convert_check(struct git_attr_check *check)
457{
458 static struct git_attr *attr_text;
459 static struct git_attr *attr_crlf;
460 static struct git_attr *attr_eol;
461 static struct git_attr *attr_ident;
462 static struct git_attr *attr_filter;
463
464 if (!attr_text) {
465 attr_text = git_attr("text");
466 attr_crlf = git_attr("crlf");
467 attr_eol = git_attr("eol");
468 attr_ident = git_attr("ident");
469 attr_filter = git_attr("filter");
470 user_convert_tail = &user_convert;
471 git_config(read_convert_config, NULL);
472 }
473 check[0].attr = attr_crlf;
474 check[1].attr = attr_ident;
475 check[2].attr = attr_filter;
476 check[3].attr = attr_eol;
477 check[4].attr = attr_text;
478}
479
480static int count_ident(const char *cp, unsigned long size)
481{
482 /*
483 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
484 */
485 int cnt = 0;
486 char ch;
487
488 while (size) {
489 ch = *cp++;
490 size--;
491 if (ch != '$')
492 continue;
493 if (size < 3)
494 break;
495 if (memcmp("Id", cp, 2))
496 continue;
497 ch = cp[2];
498 cp += 3;
499 size -= 3;
500 if (ch == '$')
501 cnt++; /* $Id$ */
502 if (ch != ':')
503 continue;
504
505 /*
506 * "$Id: ... "; scan up to the closing dollar sign and discard.
507 */
508 while (size) {
509 ch = *cp++;
510 size--;
511 if (ch == '$') {
512 cnt++;
513 break;
514 }
515 if (ch == '\n')
516 break;
517 }
518 }
519 return cnt;
520}
521
522static int ident_to_git(const char *path, const char *src, size_t len,
523 struct strbuf *buf, int ident)
524{
525 char *dst, *dollar;
526
527 if (!ident || !count_ident(src, len))
528 return 0;
529
530 /* only grow if not in place */
531 if (strbuf_avail(buf) + buf->len < len)
532 strbuf_grow(buf, len - buf->len);
533 dst = buf->buf;
534 for (;;) {
535 dollar = memchr(src, '$', len);
536 if (!dollar)
537 break;
538 memcpy(dst, src, dollar + 1 - src);
539 dst += dollar + 1 - src;
540 len -= dollar + 1 - src;
541 src = dollar + 1;
542
543 if (len > 3 && !memcmp(src, "Id:", 3)) {
544 dollar = memchr(src + 3, '$', len - 3);
545 if (!dollar)
546 break;
547 if (memchr(src + 3, '\n', dollar - src - 3)) {
548 /* Line break before the next dollar. */
549 continue;
550 }
551
552 memcpy(dst, "Id$", 3);
553 dst += 3;
554 len -= dollar + 1 - src;
555 src = dollar + 1;
556 }
557 }
558 memcpy(dst, src, len);
559 strbuf_setlen(buf, dst + len - buf->buf);
560 return 1;
561}
562
563static int ident_to_worktree(const char *path, const char *src, size_t len,
564 struct strbuf *buf, int ident)
565{
566 unsigned char sha1[20];
567 char *to_free = NULL, *dollar, *spc;
568 int cnt;
569
570 if (!ident)
571 return 0;
572
573 cnt = count_ident(src, len);
574 if (!cnt)
575 return 0;
576
577 /* are we "faking" in place editing ? */
578 if (src == buf->buf)
579 to_free = strbuf_detach(buf, NULL);
580 hash_sha1_file(src, len, "blob", sha1);
581
582 strbuf_grow(buf, len + cnt * 43);
583 for (;;) {
584 /* step 1: run to the next '$' */
585 dollar = memchr(src, '$', len);
586 if (!dollar)
587 break;
588 strbuf_add(buf, src, dollar + 1 - src);
589 len -= dollar + 1 - src;
590 src = dollar + 1;
591
592 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
593 if (len < 3 || memcmp("Id", src, 2))
594 continue;
595
596 /* step 3: skip over Id$ or Id:xxxxx$ */
597 if (src[2] == '$') {
598 src += 3;
599 len -= 3;
600 } else if (src[2] == ':') {
601 /*
602 * It's possible that an expanded Id has crept its way into the
603 * repository, we cope with that by stripping the expansion out.
604 * This is probably not a good idea, since it will cause changes
605 * on checkout, which won't go away by stash, but let's keep it
606 * for git-style ids.
607 */
608 dollar = memchr(src + 3, '$', len - 3);
609 if (!dollar) {
610 /* incomplete keyword, no more '$', so just quit the loop */
611 break;
612 }
613
614 if (memchr(src + 3, '\n', dollar - src - 3)) {
615 /* Line break before the next dollar. */
616 continue;
617 }
618
619 spc = memchr(src + 4, ' ', dollar - src - 4);
620 if (spc && spc < dollar-1) {
621 /* There are spaces in unexpected places.
622 * This is probably an id from some other
623 * versioning system. Keep it for now.
624 */
625 continue;
626 }
627
628 len -= dollar + 1 - src;
629 src = dollar + 1;
630 } else {
631 /* it wasn't a "Id$" or "Id:xxxx$" */
632 continue;
633 }
634
635 /* step 4: substitute */
636 strbuf_addstr(buf, "Id: ");
637 strbuf_add(buf, sha1_to_hex(sha1), 40);
638 strbuf_addstr(buf, " $");
639 }
640 strbuf_add(buf, src, len);
641
642 free(to_free);
643 return 1;
644}
645
646static int git_path_check_crlf(const char *path, struct git_attr_check *check)
647{
648 const char *value = check->value;
649
650 if (ATTR_TRUE(value))
651 return CRLF_TEXT;
652 else if (ATTR_FALSE(value))
653 return CRLF_BINARY;
654 else if (ATTR_UNSET(value))
655 ;
656 else if (!strcmp(value, "input"))
657 return CRLF_INPUT;
658 else if (!strcmp(value, "auto"))
659 return CRLF_AUTO;
660 return CRLF_GUESS;
661}
662
663static int git_path_check_eol(const char *path, struct git_attr_check *check)
664{
665 const char *value = check->value;
666
667 if (ATTR_UNSET(value))
668 ;
669 else if (!strcmp(value, "lf"))
670 return EOL_LF;
671 else if (!strcmp(value, "crlf"))
672 return EOL_CRLF;
673 return EOL_UNSET;
674}
675
676static struct convert_driver *git_path_check_convert(const char *path,
677 struct git_attr_check *check)
678{
679 const char *value = check->value;
680 struct convert_driver *drv;
681
682 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
683 return NULL;
684 for (drv = user_convert; drv; drv = drv->next)
685 if (!strcmp(value, drv->name))
686 return drv;
687 return NULL;
688}
689
690static int git_path_check_ident(const char *path, struct git_attr_check *check)
691{
692 const char *value = check->value;
693
694 return !!ATTR_TRUE(value);
695}
696
697static enum action determine_action(enum action text_attr, enum eol eol_attr)
698{
699 if (text_attr == CRLF_BINARY)
700 return CRLF_BINARY;
701 if (eol_attr == EOL_LF)
702 return CRLF_INPUT;
703 if (eol_attr == EOL_CRLF)
704 return CRLF_CRLF;
705 return text_attr;
706}
707
708int convert_to_git(const char *path, const char *src, size_t len,
709 struct strbuf *dst, enum safe_crlf checksafe)
710{
711 struct git_attr_check check[5];
712 enum action action = CRLF_GUESS;
713 enum eol eol_attr = EOL_UNSET;
714 int ident = 0, ret = 0;
715 const char *filter = NULL;
716
717 setup_convert_check(check);
718 if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
719 struct convert_driver *drv;
720 action = git_path_check_crlf(path, check + 4);
721 if (action == CRLF_GUESS)
722 action = git_path_check_crlf(path, check + 0);
723 ident = git_path_check_ident(path, check + 1);
724 drv = git_path_check_convert(path, check + 2);
725 eol_attr = git_path_check_eol(path, check + 3);
726 if (drv && drv->clean)
727 filter = drv->clean;
728 }
729
730 ret |= apply_filter(path, src, len, dst, filter);
731 if (ret) {
732 src = dst->buf;
733 len = dst->len;
734 }
735 action = determine_action(action, eol_attr);
736 ret |= crlf_to_git(path, src, len, dst, action, checksafe);
737 if (ret) {
738 src = dst->buf;
739 len = dst->len;
740 }
741 return ret | ident_to_git(path, src, len, dst, ident);
742}
743
744static int convert_to_working_tree_internal(const char *path, const char *src,
745 size_t len, struct strbuf *dst,
746 int normalizing)
747{
748 struct git_attr_check check[5];
749 enum action action = CRLF_GUESS;
750 enum eol eol_attr = EOL_UNSET;
751 int ident = 0, ret = 0;
752 const char *filter = NULL;
753
754 setup_convert_check(check);
755 if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
756 struct convert_driver *drv;
757 action = git_path_check_crlf(path, check + 4);
758 if (action == CRLF_GUESS)
759 action = git_path_check_crlf(path, check + 0);
760 ident = git_path_check_ident(path, check + 1);
761 drv = git_path_check_convert(path, check + 2);
762 eol_attr = git_path_check_eol(path, check + 3);
763 if (drv && drv->smudge)
764 filter = drv->smudge;
765 }
766
767 ret |= ident_to_worktree(path, src, len, dst, ident);
768 if (ret) {
769 src = dst->buf;
770 len = dst->len;
771 }
772 /*
773 * CRLF conversion can be skipped if normalizing, unless there
774 * is a smudge filter. The filter might expect CRLFs.
775 */
776 if (filter || !normalizing) {
777 action = determine_action(action, eol_attr);
778 ret |= crlf_to_worktree(path, src, len, dst, action);
779 if (ret) {
780 src = dst->buf;
781 len = dst->len;
782 }
783 }
784 return ret | apply_filter(path, src, len, dst, filter);
785}
786
787int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
788{
789 return convert_to_working_tree_internal(path, src, len, dst, 0);
790}
791
792int renormalize_buffer(const char *path, const char *src, size_t len, struct strbuf *dst)
793{
794 int ret = convert_to_working_tree_internal(path, src, len, dst, 1);
795 if (ret) {
796 src = dst->buf;
797 len = dst->len;
798 }
799 return ret | convert_to_git(path, src, len, dst, 0);
800}