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