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