Merge branch 'jn/maint-doc-ignore' into next
[git/dscho.git] / convert.c
blob46622b0d3c25f3c1da3b13689737f2e6d46b54d6
1 #include "cache.h"
2 #include "attr.h"
3 #include "run-command.h"
5 /*
6 * convert.c - convert a file when checking it out and checking it in.
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 "auto_crlf" option is set.
14 #define CRLF_GUESS (-1)
15 #define CRLF_BINARY 0
16 #define CRLF_TEXT 1
17 #define CRLF_INPUT 2
19 struct text_stat {
20 /* NUL, CR, LF and CRLF counts */
21 unsigned nul, cr, lf, crlf;
23 /* These are just approximations! */
24 unsigned printable, nonprintable;
27 static void gather_stats(const char *buf, unsigned long size, struct text_stat *stats)
29 unsigned long i;
31 memset(stats, 0, sizeof(*stats));
33 for (i = 0; i < size; i++) {
34 unsigned char c = buf[i];
35 if (c == '\r') {
36 stats->cr++;
37 if (i+1 < size && buf[i+1] == '\n')
38 stats->crlf++;
39 continue;
41 if (c == '\n') {
42 stats->lf++;
43 continue;
45 if (c == 127)
46 /* DEL */
47 stats->nonprintable++;
48 else if (c < 32) {
49 switch (c) {
50 /* BS, HT, ESC and FF */
51 case '\b': case '\t': case '\033': case '\014':
52 stats->printable++;
53 break;
54 case 0:
55 stats->nul++;
56 /* fall through */
57 default:
58 stats->nonprintable++;
61 else
62 stats->printable++;
65 /* If file ends with EOF then don't count this EOF as non-printable. */
66 if (size >= 1 && buf[size-1] == '\032')
67 stats->nonprintable--;
71 * The same heuristics as diff.c::mmfile_is_binary()
73 static int is_binary(unsigned long size, struct text_stat *stats)
76 if (stats->nul)
77 return 1;
78 if ((stats->printable >> 7) < stats->nonprintable)
79 return 1;
81 * Other heuristics? Average line length might be relevant,
82 * as might LF vs CR vs CRLF counts..
84 * NOTE! It might be normal to have a low ratio of CRLF to LF
85 * (somebody starts with a LF-only file and edits it with an editor
86 * that adds CRLF only to lines that are added..). But do we
87 * want to support CR-only? Probably not.
89 return 0;
92 static void check_safe_crlf(const char *path, int action,
93 struct text_stat *stats, enum safe_crlf checksafe)
95 if (!checksafe)
96 return;
98 if (action == CRLF_INPUT || auto_crlf <= 0) {
100 * CRLFs would not be restored by checkout:
101 * check if we'd remove CRLFs
103 if (stats->crlf) {
104 if (checksafe == SAFE_CRLF_WARN)
105 warning("CRLF will be replaced by LF in %s.", path);
106 else /* i.e. SAFE_CRLF_FAIL */
107 die("CRLF would be replaced by LF in %s.", path);
109 } else if (auto_crlf > 0) {
111 * CRLFs would be added by checkout:
112 * check if we have "naked" LFs
114 if (stats->lf != stats->crlf) {
115 if (checksafe == SAFE_CRLF_WARN)
116 warning("LF will be replaced by CRLF in %s", path);
117 else /* i.e. SAFE_CRLF_FAIL */
118 die("LF would be replaced by CRLF in %s", path);
123 static int has_cr_in_index(const char *path)
125 int pos, len;
126 unsigned long sz;
127 enum object_type type;
128 void *data;
129 int has_cr;
130 struct index_state *istate = &the_index;
132 len = strlen(path);
133 pos = index_name_pos(istate, path, len);
134 if (pos < 0) {
136 * We might be in the middle of a merge, in which
137 * case we would read stage #2 (ours).
139 int i;
140 for (i = -pos - 1;
141 (pos < 0 && i < istate->cache_nr &&
142 !strcmp(istate->cache[i]->name, path));
143 i++)
144 if (ce_stage(istate->cache[i]) == 2)
145 pos = i;
147 if (pos < 0)
148 return 0;
149 data = read_sha1_file(istate->cache[pos]->sha1, &type, &sz);
150 if (!data || type != OBJ_BLOB) {
151 free(data);
152 return 0;
155 has_cr = memchr(data, '\r', sz) != NULL;
156 free(data);
157 return has_cr;
160 static int crlf_to_git(const char *path, const char *src, size_t len,
161 struct strbuf *buf, int action, enum safe_crlf checksafe)
163 struct text_stat stats;
164 char *dst;
166 if ((action == CRLF_BINARY) || !auto_crlf || !len)
167 return 0;
169 gather_stats(src, len, &stats);
171 if (action == CRLF_GUESS) {
173 * We're currently not going to even try to convert stuff
174 * that has bare CR characters. Does anybody do that crazy
175 * stuff?
177 if (stats.cr != stats.crlf)
178 return 0;
181 * And add some heuristics for binary vs text, of course...
183 if (is_binary(len, &stats))
184 return 0;
187 * If the file in the index has any CR in it, do not convert.
188 * This is the new safer autocrlf handling.
190 if (has_cr_in_index(path))
191 return 0;
194 check_safe_crlf(path, action, &stats, checksafe);
196 /* Optimization: No CR? Nothing to convert, regardless. */
197 if (!stats.cr)
198 return 0;
200 /* only grow if not in place */
201 if (strbuf_avail(buf) + buf->len < len)
202 strbuf_grow(buf, len - buf->len);
203 dst = buf->buf;
204 if (action == CRLF_GUESS) {
206 * If we guessed, we already know we rejected a file with
207 * lone CR, and we can strip a CR without looking at what
208 * follow it.
210 do {
211 unsigned char c = *src++;
212 if (c != '\r')
213 *dst++ = c;
214 } while (--len);
215 } else {
216 do {
217 unsigned char c = *src++;
218 if (! (c == '\r' && (1 < len && *src == '\n')))
219 *dst++ = c;
220 } while (--len);
222 strbuf_setlen(buf, dst - buf->buf);
223 return 1;
226 static int crlf_to_worktree(const char *path, const char *src, size_t len,
227 struct strbuf *buf, int action)
229 char *to_free = NULL;
230 struct text_stat stats;
232 if ((action == CRLF_BINARY) || (action == CRLF_INPUT) ||
233 auto_crlf <= 0)
234 return 0;
236 if (!len)
237 return 0;
239 gather_stats(src, len, &stats);
241 /* No LF? Nothing to convert, regardless. */
242 if (!stats.lf)
243 return 0;
245 /* Was it already in CRLF format? */
246 if (stats.lf == stats.crlf)
247 return 0;
249 if (action == CRLF_GUESS) {
250 /* If we have any CR or CRLF line endings, we do not touch it */
251 /* This is the new safer autocrlf-handling */
252 if (stats.cr > 0 || stats.crlf > 0)
253 return 0;
255 /* If we have any bare CR characters, we're not going to touch it */
256 if (stats.cr != stats.crlf)
257 return 0;
259 if (is_binary(len, &stats))
260 return 0;
263 /* are we "faking" in place editing ? */
264 if (src == buf->buf)
265 to_free = strbuf_detach(buf, NULL);
267 strbuf_grow(buf, len + stats.lf - stats.crlf);
268 for (;;) {
269 const char *nl = memchr(src, '\n', len);
270 if (!nl)
271 break;
272 if (nl > src && nl[-1] == '\r') {
273 strbuf_add(buf, src, nl + 1 - src);
274 } else {
275 strbuf_add(buf, src, nl - src);
276 strbuf_addstr(buf, "\r\n");
278 len -= nl + 1 - src;
279 src = nl + 1;
281 strbuf_add(buf, src, len);
283 free(to_free);
284 return 1;
287 struct filter_params {
288 const char *src;
289 unsigned long size;
290 const char *cmd;
293 static int filter_buffer(int in, int out, void *data)
296 * Spawn cmd and feed the buffer contents through its stdin.
298 struct child_process child_process;
299 struct filter_params *params = (struct filter_params *)data;
300 int write_err, status;
301 const char *argv[] = { params->cmd, NULL };
303 memset(&child_process, 0, sizeof(child_process));
304 child_process.argv = argv;
305 child_process.use_shell = 1;
306 child_process.in = -1;
307 child_process.out = out;
309 if (start_command(&child_process))
310 return error("cannot fork to run external filter %s", params->cmd);
312 write_err = (write_in_full(child_process.in, params->src, params->size) < 0);
313 if (close(child_process.in))
314 write_err = 1;
315 if (write_err)
316 error("cannot feed the input to external filter %s", params->cmd);
318 status = finish_command(&child_process);
319 if (status)
320 error("external filter %s failed %d", params->cmd, status);
321 return (write_err || status);
324 static int apply_filter(const char *path, const char *src, size_t len,
325 struct strbuf *dst, const char *cmd)
328 * Create a pipeline to have the command filter the buffer's
329 * contents.
331 * (child --> cmd) --> us
333 int ret = 1;
334 struct strbuf nbuf = STRBUF_INIT;
335 struct async async;
336 struct filter_params params;
338 if (!cmd)
339 return 0;
341 memset(&async, 0, sizeof(async));
342 async.proc = filter_buffer;
343 async.data = &params;
344 async.out = -1;
345 params.src = src;
346 params.size = len;
347 params.cmd = cmd;
349 fflush(NULL);
350 if (start_async(&async))
351 return 0; /* error was already reported */
353 if (strbuf_read(&nbuf, async.out, len) < 0) {
354 error("read from external filter %s failed", cmd);
355 ret = 0;
357 if (close(async.out)) {
358 error("read from external filter %s failed", cmd);
359 ret = 0;
361 if (finish_async(&async)) {
362 error("external filter %s failed", cmd);
363 ret = 0;
366 if (ret) {
367 strbuf_swap(dst, &nbuf);
369 strbuf_release(&nbuf);
370 return ret;
373 static struct convert_driver {
374 const char *name;
375 struct convert_driver *next;
376 const char *smudge;
377 const char *clean;
378 } *user_convert, **user_convert_tail;
380 static int read_convert_config(const char *var, const char *value, void *cb)
382 const char *ep, *name;
383 int namelen;
384 struct convert_driver *drv;
387 * External conversion drivers are configured using
388 * "filter.<name>.variable".
390 if (prefixcmp(var, "filter.") || (ep = strrchr(var, '.')) == var + 6)
391 return 0;
392 name = var + 7;
393 namelen = ep - name;
394 for (drv = user_convert; drv; drv = drv->next)
395 if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
396 break;
397 if (!drv) {
398 drv = xcalloc(1, sizeof(struct convert_driver));
399 drv->name = xmemdupz(name, namelen);
400 *user_convert_tail = drv;
401 user_convert_tail = &(drv->next);
404 ep++;
407 * filter.<name>.smudge and filter.<name>.clean specifies
408 * the command line:
410 * command-line
412 * The command-line will not be interpolated in any way.
415 if (!strcmp("smudge", ep))
416 return git_config_string(&drv->smudge, var, value);
418 if (!strcmp("clean", ep))
419 return git_config_string(&drv->clean, var, value);
421 return 0;
424 static void setup_convert_check(struct git_attr_check *check)
426 static struct git_attr *attr_crlf;
427 static struct git_attr *attr_ident;
428 static struct git_attr *attr_filter;
430 if (!attr_crlf) {
431 attr_crlf = git_attr("crlf");
432 attr_ident = git_attr("ident");
433 attr_filter = git_attr("filter");
434 user_convert_tail = &user_convert;
435 git_config(read_convert_config, NULL);
437 check[0].attr = attr_crlf;
438 check[1].attr = attr_ident;
439 check[2].attr = attr_filter;
442 static int count_ident(const char *cp, unsigned long size)
445 * "$Id: 0000000000000000000000000000000000000000 $" <=> "$Id$"
447 int cnt = 0;
448 char ch;
450 while (size) {
451 ch = *cp++;
452 size--;
453 if (ch != '$')
454 continue;
455 if (size < 3)
456 break;
457 if (memcmp("Id", cp, 2))
458 continue;
459 ch = cp[2];
460 cp += 3;
461 size -= 3;
462 if (ch == '$')
463 cnt++; /* $Id$ */
464 if (ch != ':')
465 continue;
468 * "$Id: ... "; scan up to the closing dollar sign and discard.
470 while (size) {
471 ch = *cp++;
472 size--;
473 if (ch == '$') {
474 cnt++;
475 break;
479 return cnt;
482 static int ident_to_git(const char *path, const char *src, size_t len,
483 struct strbuf *buf, int ident)
485 char *dst, *dollar;
487 if (!ident || !count_ident(src, len))
488 return 0;
490 /* only grow if not in place */
491 if (strbuf_avail(buf) + buf->len < len)
492 strbuf_grow(buf, len - buf->len);
493 dst = buf->buf;
494 for (;;) {
495 dollar = memchr(src, '$', len);
496 if (!dollar)
497 break;
498 memcpy(dst, src, dollar + 1 - src);
499 dst += dollar + 1 - src;
500 len -= dollar + 1 - src;
501 src = dollar + 1;
503 if (len > 3 && !memcmp(src, "Id:", 3)) {
504 dollar = memchr(src + 3, '$', len - 3);
505 if (!dollar)
506 break;
507 memcpy(dst, "Id$", 3);
508 dst += 3;
509 len -= dollar + 1 - src;
510 src = dollar + 1;
513 memcpy(dst, src, len);
514 strbuf_setlen(buf, dst + len - buf->buf);
515 return 1;
518 static int ident_to_worktree(const char *path, const char *src, size_t len,
519 struct strbuf *buf, int ident)
521 unsigned char sha1[20];
522 char *to_free = NULL, *dollar;
523 int cnt;
525 if (!ident)
526 return 0;
528 cnt = count_ident(src, len);
529 if (!cnt)
530 return 0;
532 /* are we "faking" in place editing ? */
533 if (src == buf->buf)
534 to_free = strbuf_detach(buf, NULL);
535 hash_sha1_file(src, len, "blob", sha1);
537 strbuf_grow(buf, len + cnt * 43);
538 for (;;) {
539 /* step 1: run to the next '$' */
540 dollar = memchr(src, '$', len);
541 if (!dollar)
542 break;
543 strbuf_add(buf, src, dollar + 1 - src);
544 len -= dollar + 1 - src;
545 src = dollar + 1;
547 /* step 2: does it looks like a bit like Id:xxx$ or Id$ ? */
548 if (len < 3 || memcmp("Id", src, 2))
549 continue;
551 /* step 3: skip over Id$ or Id:xxxxx$ */
552 if (src[2] == '$') {
553 src += 3;
554 len -= 3;
555 } else if (src[2] == ':') {
557 * It's possible that an expanded Id has crept its way into the
558 * repository, we cope with that by stripping the expansion out
560 dollar = memchr(src + 3, '$', len - 3);
561 if (!dollar) {
562 /* incomplete keyword, no more '$', so just quit the loop */
563 break;
566 len -= dollar + 1 - src;
567 src = dollar + 1;
568 } else {
569 /* it wasn't a "Id$" or "Id:xxxx$" */
570 continue;
573 /* step 4: substitute */
574 strbuf_addstr(buf, "Id: ");
575 strbuf_add(buf, sha1_to_hex(sha1), 40);
576 strbuf_addstr(buf, " $");
578 strbuf_add(buf, src, len);
580 free(to_free);
581 return 1;
584 static int git_path_check_crlf(const char *path, struct git_attr_check *check)
586 const char *value = check->value;
588 if (ATTR_TRUE(value))
589 return CRLF_TEXT;
590 else if (ATTR_FALSE(value))
591 return CRLF_BINARY;
592 else if (ATTR_UNSET(value))
594 else if (!strcmp(value, "input"))
595 return CRLF_INPUT;
596 return CRLF_GUESS;
599 static struct convert_driver *git_path_check_convert(const char *path,
600 struct git_attr_check *check)
602 const char *value = check->value;
603 struct convert_driver *drv;
605 if (ATTR_TRUE(value) || ATTR_FALSE(value) || ATTR_UNSET(value))
606 return NULL;
607 for (drv = user_convert; drv; drv = drv->next)
608 if (!strcmp(value, drv->name))
609 return drv;
610 return NULL;
613 static int git_path_check_ident(const char *path, struct git_attr_check *check)
615 const char *value = check->value;
617 return !!ATTR_TRUE(value);
620 int convert_to_git(const char *path, const char *src, size_t len,
621 struct strbuf *dst, enum safe_crlf checksafe)
623 struct git_attr_check check[3];
624 int crlf = CRLF_GUESS;
625 int ident = 0, ret = 0;
626 const char *filter = NULL;
628 setup_convert_check(check);
629 if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
630 struct convert_driver *drv;
631 crlf = git_path_check_crlf(path, check + 0);
632 ident = git_path_check_ident(path, check + 1);
633 drv = git_path_check_convert(path, check + 2);
634 if (drv && drv->clean)
635 filter = drv->clean;
638 ret |= apply_filter(path, src, len, dst, filter);
639 if (ret) {
640 src = dst->buf;
641 len = dst->len;
643 ret |= crlf_to_git(path, src, len, dst, crlf, checksafe);
644 if (ret) {
645 src = dst->buf;
646 len = dst->len;
648 return ret | ident_to_git(path, src, len, dst, ident);
651 int convert_to_working_tree(const char *path, const char *src, size_t len, struct strbuf *dst)
653 struct git_attr_check check[3];
654 int crlf = CRLF_GUESS;
655 int ident = 0, ret = 0;
656 const char *filter = NULL;
658 setup_convert_check(check);
659 if (!git_checkattr(path, ARRAY_SIZE(check), check)) {
660 struct convert_driver *drv;
661 crlf = git_path_check_crlf(path, check + 0);
662 ident = git_path_check_ident(path, check + 1);
663 drv = git_path_check_convert(path, check + 2);
664 if (drv && drv->smudge)
665 filter = drv->smudge;
668 ret |= ident_to_worktree(path, src, len, dst, ident);
669 if (ret) {
670 src = dst->buf;
671 len = dst->len;
673 ret |= crlf_to_worktree(path, src, len, dst, crlf);
674 if (ret) {
675 src = dst->buf;
676 len = dst->len;
678 return ret | apply_filter(path, src, len, dst, filter);