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