ffb418ccffc751ef87d8534264fa56b1ca8a6683
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 * Copyright (C) Johannes Schindelin, 2005
   6 *
   7 */
   8#include "cache.h"
   9
  10#define MAXNAME (256)
  11
  12static FILE *config_file;
  13static const char *config_file_name;
  14static int config_linenr;
  15static int zlib_compression_seen;
  16
  17static int get_next_char(void)
  18{
  19        int c;
  20        FILE *f;
  21
  22        c = '\n';
  23        if ((f = config_file) != NULL) {
  24                c = fgetc(f);
  25                if (c == '\r') {
  26                        /* DOS like systems */
  27                        c = fgetc(f);
  28                        if (c != '\n') {
  29                                ungetc(c, f);
  30                                c = '\r';
  31                        }
  32                }
  33                if (c == '\n')
  34                        config_linenr++;
  35                if (c == EOF) {
  36                        config_file = NULL;
  37                        c = '\n';
  38                }
  39        }
  40        return c;
  41}
  42
  43static char *parse_value(void)
  44{
  45        static char value[1024];
  46        int quote = 0, comment = 0, len = 0, space = 0;
  47
  48        for (;;) {
  49                int c = get_next_char();
  50                if (len >= sizeof(value))
  51                        return NULL;
  52                if (c == '\n') {
  53                        if (quote)
  54                                return NULL;
  55                        value[len] = 0;
  56                        return value;
  57                }
  58                if (comment)
  59                        continue;
  60                if (isspace(c) && !quote) {
  61                        space = 1;
  62                        continue;
  63                }
  64                if (!quote) {
  65                        if (c == ';' || c == '#') {
  66                                comment = 1;
  67                                continue;
  68                        }
  69                }
  70                if (space) {
  71                        if (len)
  72                                value[len++] = ' ';
  73                        space = 0;
  74                }
  75                if (c == '\\') {
  76                        c = get_next_char();
  77                        switch (c) {
  78                        case '\n':
  79                                continue;
  80                        case 't':
  81                                c = '\t';
  82                                break;
  83                        case 'b':
  84                                c = '\b';
  85                                break;
  86                        case 'n':
  87                                c = '\n';
  88                                break;
  89                        /* Some characters escape as themselves */
  90                        case '\\': case '"':
  91                                break;
  92                        /* Reject unknown escape sequences */
  93                        default:
  94                                return NULL;
  95                        }
  96                        value[len++] = c;
  97                        continue;
  98                }
  99                if (c == '"') {
 100                        quote = 1-quote;
 101                        continue;
 102                }
 103                value[len++] = c;
 104        }
 105}
 106
 107static inline int iskeychar(int c)
 108{
 109        return isalnum(c) || c == '-';
 110}
 111
 112static int get_value(config_fn_t fn, char *name, unsigned int len)
 113{
 114        int c;
 115        char *value;
 116
 117        /* Get the full name */
 118        for (;;) {
 119                c = get_next_char();
 120                if (c == EOF)
 121                        break;
 122                if (!iskeychar(c))
 123                        break;
 124                name[len++] = tolower(c);
 125                if (len >= MAXNAME)
 126                        return -1;
 127        }
 128        name[len] = 0;
 129        while (c == ' ' || c == '\t')
 130                c = get_next_char();
 131
 132        value = NULL;
 133        if (c != '\n') {
 134                if (c != '=')
 135                        return -1;
 136                value = parse_value();
 137                if (!value)
 138                        return -1;
 139        }
 140        return fn(name, value);
 141}
 142
 143static int get_extended_base_var(char *name, int baselen, int c)
 144{
 145        do {
 146                if (c == '\n')
 147                        return -1;
 148                c = get_next_char();
 149        } while (isspace(c));
 150
 151        /* We require the format to be '[base "extension"]' */
 152        if (c != '"')
 153                return -1;
 154        name[baselen++] = '.';
 155
 156        for (;;) {
 157                int c = get_next_char();
 158                if (c == '\n')
 159                        return -1;
 160                if (c == '"')
 161                        break;
 162                if (c == '\\') {
 163                        c = get_next_char();
 164                        if (c == '\n')
 165                                return -1;
 166                }
 167                name[baselen++] = c;
 168                if (baselen > MAXNAME / 2)
 169                        return -1;
 170        }
 171
 172        /* Final ']' */
 173        if (get_next_char() != ']')
 174                return -1;
 175        return baselen;
 176}
 177
 178static int get_base_var(char *name)
 179{
 180        int baselen = 0;
 181
 182        for (;;) {
 183                int c = get_next_char();
 184                if (c == EOF)
 185                        return -1;
 186                if (c == ']')
 187                        return baselen;
 188                if (isspace(c))
 189                        return get_extended_base_var(name, baselen, c);
 190                if (!iskeychar(c) && c != '.')
 191                        return -1;
 192                if (baselen > MAXNAME / 2)
 193                        return -1;
 194                name[baselen++] = tolower(c);
 195        }
 196}
 197
 198static int git_parse_file(config_fn_t fn)
 199{
 200        int comment = 0;
 201        int baselen = 0;
 202        static char var[MAXNAME];
 203
 204        for (;;) {
 205                int c = get_next_char();
 206                if (c == '\n') {
 207                        /* EOF? */
 208                        if (!config_file)
 209                                return 0;
 210                        comment = 0;
 211                        continue;
 212                }
 213                if (comment || isspace(c))
 214                        continue;
 215                if (c == '#' || c == ';') {
 216                        comment = 1;
 217                        continue;
 218                }
 219                if (c == '[') {
 220                        baselen = get_base_var(var);
 221                        if (baselen <= 0)
 222                                break;
 223                        var[baselen++] = '.';
 224                        var[baselen] = 0;
 225                        continue;
 226                }
 227                if (!isalpha(c))
 228                        break;
 229                var[baselen] = tolower(c);
 230                if (get_value(fn, var, baselen+1) < 0)
 231                        break;
 232        }
 233        die("bad config file line %d in %s", config_linenr, config_file_name);
 234}
 235
 236static unsigned long get_unit_factor(const char *end)
 237{
 238        if (!*end)
 239                return 1;
 240        else if (!strcasecmp(end, "k"))
 241                return 1024;
 242        else if (!strcasecmp(end, "m"))
 243                return 1024 * 1024;
 244        else if (!strcasecmp(end, "g"))
 245                return 1024 * 1024 * 1024;
 246        die("unknown unit: '%s'", end);
 247}
 248
 249static struct whitespace_rule {
 250        const char *rule_name;
 251        unsigned rule_bits;
 252} whitespace_rule_names[] = {
 253        { "trailing-space", WS_TRAILING_SPACE },
 254        { "space-before-tab", WS_SPACE_BEFORE_TAB },
 255};
 256
 257static unsigned parse_whitespace_rule(const char *string)
 258{
 259        unsigned rule = WS_DEFAULT_RULE;
 260
 261        while (string) {
 262                int i;
 263                size_t len;
 264                const char *ep;
 265                int negated = 0;
 266
 267                string = string + strspn(string, ", \t\n\r");
 268                ep = strchr(string, ',');
 269                if (!ep)
 270                        len = strlen(string);
 271                else
 272                        len = ep - string;
 273
 274                if (*string == '-') {
 275                        negated = 1;
 276                        string++;
 277                        len--;
 278                }
 279                if (!len)
 280                        break;
 281                for (i = 0; i < ARRAY_SIZE(whitespace_rule_names); i++) {
 282                        if (strncmp(whitespace_rule_names[i].rule_name,
 283                                    string, len))
 284                                continue;
 285                        if (negated)
 286                                rule &= ~whitespace_rule_names[i].rule_bits;
 287                        else
 288                                rule |= whitespace_rule_names[i].rule_bits;
 289                        break;
 290                }
 291                string = ep;
 292        }
 293        return rule;
 294}
 295
 296int git_parse_long(const char *value, long *ret)
 297{
 298        if (value && *value) {
 299                char *end;
 300                long val = strtol(value, &end, 0);
 301                *ret = val * get_unit_factor(end);
 302                return 1;
 303        }
 304        return 0;
 305}
 306
 307int git_parse_ulong(const char *value, unsigned long *ret)
 308{
 309        if (value && *value) {
 310                char *end;
 311                unsigned long val = strtoul(value, &end, 0);
 312                *ret = val * get_unit_factor(end);
 313                return 1;
 314        }
 315        return 0;
 316}
 317
 318int git_config_int(const char *name, const char *value)
 319{
 320        long ret;
 321        if (!git_parse_long(value, &ret))
 322                die("bad config value for '%s' in %s", name, config_file_name);
 323        return ret;
 324}
 325
 326unsigned long git_config_ulong(const char *name, const char *value)
 327{
 328        unsigned long ret;
 329        if (!git_parse_ulong(value, &ret))
 330                die("bad config value for '%s' in %s", name, config_file_name);
 331        return ret;
 332}
 333
 334int git_config_bool(const char *name, const char *value)
 335{
 336        if (!value)
 337                return 1;
 338        if (!*value)
 339                return 0;
 340        if (!strcasecmp(value, "true") || !strcasecmp(value, "yes"))
 341                return 1;
 342        if (!strcasecmp(value, "false") || !strcasecmp(value, "no"))
 343                return 0;
 344        return git_config_int(name, value) != 0;
 345}
 346
 347int git_default_config(const char *var, const char *value)
 348{
 349        /* This needs a better name */
 350        if (!strcmp(var, "core.filemode")) {
 351                trust_executable_bit = git_config_bool(var, value);
 352                return 0;
 353        }
 354
 355        if (!strcmp(var, "core.quotepath")) {
 356                quote_path_fully = git_config_bool(var, value);
 357                return 0;
 358        }
 359
 360        if (!strcmp(var, "core.symlinks")) {
 361                has_symlinks = git_config_bool(var, value);
 362                return 0;
 363        }
 364
 365        if (!strcmp(var, "core.bare")) {
 366                is_bare_repository_cfg = git_config_bool(var, value);
 367                return 0;
 368        }
 369
 370        if (!strcmp(var, "core.ignorestat")) {
 371                assume_unchanged = git_config_bool(var, value);
 372                return 0;
 373        }
 374
 375        if (!strcmp(var, "core.prefersymlinkrefs")) {
 376                prefer_symlink_refs = git_config_bool(var, value);
 377                return 0;
 378        }
 379
 380        if (!strcmp(var, "core.logallrefupdates")) {
 381                log_all_ref_updates = git_config_bool(var, value);
 382                return 0;
 383        }
 384
 385        if (!strcmp(var, "core.warnambiguousrefs")) {
 386                warn_ambiguous_refs = git_config_bool(var, value);
 387                return 0;
 388        }
 389
 390        if (!strcmp(var, "core.loosecompression")) {
 391                int level = git_config_int(var, value);
 392                if (level == -1)
 393                        level = Z_DEFAULT_COMPRESSION;
 394                else if (level < 0 || level > Z_BEST_COMPRESSION)
 395                        die("bad zlib compression level %d", level);
 396                zlib_compression_level = level;
 397                zlib_compression_seen = 1;
 398                return 0;
 399        }
 400
 401        if (!strcmp(var, "core.compression")) {
 402                int level = git_config_int(var, value);
 403                if (level == -1)
 404                        level = Z_DEFAULT_COMPRESSION;
 405                else if (level < 0 || level > Z_BEST_COMPRESSION)
 406                        die("bad zlib compression level %d", level);
 407                core_compression_level = level;
 408                core_compression_seen = 1;
 409                if (!zlib_compression_seen)
 410                        zlib_compression_level = level;
 411                return 0;
 412        }
 413
 414        if (!strcmp(var, "core.packedgitwindowsize")) {
 415                int pgsz_x2 = getpagesize() * 2;
 416                packed_git_window_size = git_config_int(var, value);
 417
 418                /* This value must be multiple of (pagesize * 2) */
 419                packed_git_window_size /= pgsz_x2;
 420                if (packed_git_window_size < 1)
 421                        packed_git_window_size = 1;
 422                packed_git_window_size *= pgsz_x2;
 423                return 0;
 424        }
 425
 426        if (!strcmp(var, "core.packedgitlimit")) {
 427                packed_git_limit = git_config_int(var, value);
 428                return 0;
 429        }
 430
 431        if (!strcmp(var, "core.deltabasecachelimit")) {
 432                delta_base_cache_limit = git_config_int(var, value);
 433                return 0;
 434        }
 435
 436        if (!strcmp(var, "core.autocrlf")) {
 437                if (value && !strcasecmp(value, "input")) {
 438                        auto_crlf = -1;
 439                        return 0;
 440                }
 441                auto_crlf = git_config_bool(var, value);
 442                return 0;
 443        }
 444
 445        if (!strcmp(var, "user.name")) {
 446                strlcpy(git_default_name, value, sizeof(git_default_name));
 447                return 0;
 448        }
 449
 450        if (!strcmp(var, "user.email")) {
 451                strlcpy(git_default_email, value, sizeof(git_default_email));
 452                return 0;
 453        }
 454
 455        if (!strcmp(var, "i18n.commitencoding")) {
 456                git_commit_encoding = xstrdup(value);
 457                return 0;
 458        }
 459
 460        if (!strcmp(var, "i18n.logoutputencoding")) {
 461                git_log_output_encoding = xstrdup(value);
 462                return 0;
 463        }
 464
 465
 466        if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
 467                pager_use_color = git_config_bool(var,value);
 468                return 0;
 469        }
 470
 471        if (!strcmp(var, "core.pager")) {
 472                pager_program = xstrdup(value);
 473                return 0;
 474        }
 475
 476        if (!strcmp(var, "core.editor")) {
 477                editor_program = xstrdup(value);
 478                return 0;
 479        }
 480
 481        if (!strcmp(var, "core.whitespace")) {
 482                whitespace_rule = parse_whitespace_rule(value);
 483                return 0;
 484        }
 485
 486        /* Add other config variables here and to Documentation/config.txt. */
 487        return 0;
 488}
 489
 490int git_config_from_file(config_fn_t fn, const char *filename)
 491{
 492        int ret;
 493        FILE *f = fopen(filename, "r");
 494
 495        ret = -1;
 496        if (f) {
 497                config_file = f;
 498                config_file_name = filename;
 499                config_linenr = 1;
 500                ret = git_parse_file(fn);
 501                fclose(f);
 502                config_file_name = NULL;
 503        }
 504        return ret;
 505}
 506
 507int git_config(config_fn_t fn)
 508{
 509        int ret = 0;
 510        char *repo_config = NULL;
 511        const char *home = NULL, *filename;
 512
 513        /* $GIT_CONFIG makes git read _only_ the given config file,
 514         * $GIT_CONFIG_LOCAL will make it process it in addition to the
 515         * global config file, the same way it would the per-repository
 516         * config file otherwise. */
 517        filename = getenv(CONFIG_ENVIRONMENT);
 518        if (!filename) {
 519                if (!access(ETC_GITCONFIG, R_OK))
 520                        ret += git_config_from_file(fn, ETC_GITCONFIG);
 521                home = getenv("HOME");
 522                filename = getenv(CONFIG_LOCAL_ENVIRONMENT);
 523                if (!filename)
 524                        filename = repo_config = xstrdup(git_path("config"));
 525        }
 526
 527        if (home) {
 528                char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
 529                if (!access(user_config, R_OK))
 530                        ret = git_config_from_file(fn, user_config);
 531                free(user_config);
 532        }
 533
 534        ret += git_config_from_file(fn, filename);
 535        free(repo_config);
 536        return ret;
 537}
 538
 539/*
 540 * Find all the stuff for git_config_set() below.
 541 */
 542
 543#define MAX_MATCHES 512
 544
 545static struct {
 546        int baselen;
 547        char* key;
 548        int do_not_match;
 549        regex_t* value_regex;
 550        int multi_replace;
 551        size_t offset[MAX_MATCHES];
 552        enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
 553        int seen;
 554} store;
 555
 556static int matches(const char* key, const char* value)
 557{
 558        return !strcmp(key, store.key) &&
 559                (store.value_regex == NULL ||
 560                 (store.do_not_match ^
 561                  !regexec(store.value_regex, value, 0, NULL, 0)));
 562}
 563
 564static int store_aux(const char* key, const char* value)
 565{
 566        const char *ep;
 567        size_t section_len;
 568
 569        switch (store.state) {
 570        case KEY_SEEN:
 571                if (matches(key, value)) {
 572                        if (store.seen == 1 && store.multi_replace == 0) {
 573                                fprintf(stderr,
 574                                        "Warning: %s has multiple values\n",
 575                                        key);
 576                        } else if (store.seen >= MAX_MATCHES) {
 577                                fprintf(stderr, "Too many matches\n");
 578                                return 1;
 579                        }
 580
 581                        store.offset[store.seen] = ftell(config_file);
 582                        store.seen++;
 583                }
 584                break;
 585        case SECTION_SEEN:
 586                /*
 587                 * What we are looking for is in store.key (both
 588                 * section and var), and its section part is baselen
 589                 * long.  We found key (again, both section and var).
 590                 * We would want to know if this key is in the same
 591                 * section as what we are looking for.  We already
 592                 * know we are in the same section as what should
 593                 * hold store.key.
 594                 */
 595                ep = strrchr(key, '.');
 596                section_len = ep - key;
 597
 598                if ((section_len != store.baselen) ||
 599                    memcmp(key, store.key, section_len+1)) {
 600                        store.state = SECTION_END_SEEN;
 601                        break;
 602                }
 603
 604                /*
 605                 * Do not increment matches: this is no match, but we
 606                 * just made sure we are in the desired section.
 607                 */
 608                store.offset[store.seen] = ftell(config_file);
 609                /* fallthru */
 610        case SECTION_END_SEEN:
 611        case START:
 612                if (matches(key, value)) {
 613                        store.offset[store.seen] = ftell(config_file);
 614                        store.state = KEY_SEEN;
 615                        store.seen++;
 616                } else {
 617                        if (strrchr(key, '.') - key == store.baselen &&
 618                              !strncmp(key, store.key, store.baselen)) {
 619                                        store.state = SECTION_SEEN;
 620                                        store.offset[store.seen] = ftell(config_file);
 621                        }
 622                }
 623        }
 624        return 0;
 625}
 626
 627static int write_error(void)
 628{
 629        fprintf(stderr, "Failed to write new configuration file\n");
 630
 631        /* Same error code as "failed to rename". */
 632        return 4;
 633}
 634
 635static int store_write_section(int fd, const char* key)
 636{
 637        const char *dot = strchr(key, '.');
 638        int len1 = store.baselen, len2 = -1;
 639
 640        dot = strchr(key, '.');
 641        if (dot) {
 642                int dotlen = dot - key;
 643                if (dotlen < len1) {
 644                        len2 = len1 - dotlen - 1;
 645                        len1 = dotlen;
 646                }
 647        }
 648
 649        if (write_in_full(fd, "[", 1) != 1 ||
 650            write_in_full(fd, key, len1) != len1)
 651                return 0;
 652        if (len2 >= 0) {
 653                if (write_in_full(fd, " \"", 2) != 2)
 654                        return 0;
 655                while (--len2 >= 0) {
 656                        unsigned char c = *++dot;
 657                        if (c == '"')
 658                                if (write_in_full(fd, "\\", 1) != 1)
 659                                        return 0;
 660                        if (write_in_full(fd, &c, 1) != 1)
 661                                return 0;
 662                }
 663                if (write_in_full(fd, "\"", 1) != 1)
 664                        return 0;
 665        }
 666        if (write_in_full(fd, "]\n", 2) != 2)
 667                return 0;
 668
 669        return 1;
 670}
 671
 672static int store_write_pair(int fd, const char* key, const char* value)
 673{
 674        int i;
 675        int length = strlen(key+store.baselen+1);
 676        int quote = 0;
 677
 678        /* Check to see if the value needs to be quoted. */
 679        if (value[0] == ' ')
 680                quote = 1;
 681        for (i = 0; value[i]; i++)
 682                if (value[i] == ';' || value[i] == '#')
 683                        quote = 1;
 684        if (value[i-1] == ' ')
 685                quote = 1;
 686
 687        if (write_in_full(fd, "\t", 1) != 1 ||
 688            write_in_full(fd, key+store.baselen+1, length) != length ||
 689            write_in_full(fd, " = ", 3) != 3)
 690                return 0;
 691        if (quote && write_in_full(fd, "\"", 1) != 1)
 692                return 0;
 693        for (i = 0; value[i]; i++)
 694                switch (value[i]) {
 695                case '\n':
 696                        if (write_in_full(fd, "\\n", 2) != 2)
 697                                return 0;
 698                        break;
 699                case '\t':
 700                        if (write_in_full(fd, "\\t", 2) != 2)
 701                                return 0;
 702                        break;
 703                case '"':
 704                case '\\':
 705                        if (write_in_full(fd, "\\", 1) != 1)
 706                                return 0;
 707                default:
 708                        if (write_in_full(fd, value+i, 1) != 1)
 709                                return 0;
 710                        break;
 711                }
 712        if (quote && write_in_full(fd, "\"", 1) != 1)
 713                return 0;
 714        if (write_in_full(fd, "\n", 1) != 1)
 715                return 0;
 716        return 1;
 717}
 718
 719static ssize_t find_beginning_of_line(const char* contents, size_t size,
 720        size_t offset_, int* found_bracket)
 721{
 722        size_t equal_offset = size, bracket_offset = size;
 723        ssize_t offset;
 724
 725        for (offset = offset_-2; offset > 0
 726                        && contents[offset] != '\n'; offset--)
 727                switch (contents[offset]) {
 728                        case '=': equal_offset = offset; break;
 729                        case ']': bracket_offset = offset; break;
 730                }
 731        if (bracket_offset < equal_offset) {
 732                *found_bracket = 1;
 733                offset = bracket_offset+1;
 734        } else
 735                offset++;
 736
 737        return offset;
 738}
 739
 740int git_config_set(const char* key, const char* value)
 741{
 742        return git_config_set_multivar(key, value, NULL, 0);
 743}
 744
 745/*
 746 * If value==NULL, unset in (remove from) config,
 747 * if value_regex!=NULL, disregard key/value pairs where value does not match.
 748 * if multi_replace==0, nothing, or only one matching key/value is replaced,
 749 *     else all matching key/values (regardless how many) are removed,
 750 *     before the new pair is written.
 751 *
 752 * Returns 0 on success.
 753 *
 754 * This function does this:
 755 *
 756 * - it locks the config file by creating ".git/config.lock"
 757 *
 758 * - it then parses the config using store_aux() as validator to find
 759 *   the position on the key/value pair to replace. If it is to be unset,
 760 *   it must be found exactly once.
 761 *
 762 * - the config file is mmap()ed and the part before the match (if any) is
 763 *   written to the lock file, then the changed part and the rest.
 764 *
 765 * - the config file is removed and the lock file rename()d to it.
 766 *
 767 */
 768int git_config_set_multivar(const char* key, const char* value,
 769        const char* value_regex, int multi_replace)
 770{
 771        int i, dot;
 772        int fd = -1, in_fd;
 773        int ret;
 774        char* config_filename;
 775        struct lock_file *lock = NULL;
 776        const char* last_dot = strrchr(key, '.');
 777
 778        config_filename = getenv(CONFIG_ENVIRONMENT);
 779        if (!config_filename) {
 780                config_filename = getenv(CONFIG_LOCAL_ENVIRONMENT);
 781                if (!config_filename)
 782                        config_filename  = git_path("config");
 783        }
 784        config_filename = xstrdup(config_filename);
 785
 786        /*
 787         * Since "key" actually contains the section name and the real
 788         * key name separated by a dot, we have to know where the dot is.
 789         */
 790
 791        if (last_dot == NULL) {
 792                fprintf(stderr, "key does not contain a section: %s\n", key);
 793                ret = 2;
 794                goto out_free;
 795        }
 796        store.baselen = last_dot - key;
 797
 798        store.multi_replace = multi_replace;
 799
 800        /*
 801         * Validate the key and while at it, lower case it for matching.
 802         */
 803        store.key = xmalloc(strlen(key) + 1);
 804        dot = 0;
 805        for (i = 0; key[i]; i++) {
 806                unsigned char c = key[i];
 807                if (c == '.')
 808                        dot = 1;
 809                /* Leave the extended basename untouched.. */
 810                if (!dot || i > store.baselen) {
 811                        if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
 812                                fprintf(stderr, "invalid key: %s\n", key);
 813                                free(store.key);
 814                                ret = 1;
 815                                goto out_free;
 816                        }
 817                        c = tolower(c);
 818                } else if (c == '\n') {
 819                        fprintf(stderr, "invalid key (newline): %s\n", key);
 820                        free(store.key);
 821                        ret = 1;
 822                        goto out_free;
 823                }
 824                store.key[i] = c;
 825        }
 826        store.key[i] = 0;
 827
 828        /*
 829         * The lock serves a purpose in addition to locking: the new
 830         * contents of .git/config will be written into it.
 831         */
 832        lock = xcalloc(sizeof(struct lock_file), 1);
 833        fd = hold_lock_file_for_update(lock, config_filename, 0);
 834        if (fd < 0) {
 835                fprintf(stderr, "could not lock config file\n");
 836                free(store.key);
 837                ret = -1;
 838                goto out_free;
 839        }
 840
 841        /*
 842         * If .git/config does not exist yet, write a minimal version.
 843         */
 844        in_fd = open(config_filename, O_RDONLY);
 845        if ( in_fd < 0 ) {
 846                free(store.key);
 847
 848                if ( ENOENT != errno ) {
 849                        error("opening %s: %s", config_filename,
 850                              strerror(errno));
 851                        ret = 3; /* same as "invalid config file" */
 852                        goto out_free;
 853                }
 854                /* if nothing to unset, error out */
 855                if (value == NULL) {
 856                        ret = 5;
 857                        goto out_free;
 858                }
 859
 860                store.key = (char*)key;
 861                if (!store_write_section(fd, key) ||
 862                    !store_write_pair(fd, key, value))
 863                        goto write_err_out;
 864        } else {
 865                struct stat st;
 866                char* contents;
 867                size_t contents_sz, copy_begin, copy_end;
 868                int i, new_line = 0;
 869
 870                if (value_regex == NULL)
 871                        store.value_regex = NULL;
 872                else {
 873                        if (value_regex[0] == '!') {
 874                                store.do_not_match = 1;
 875                                value_regex++;
 876                        } else
 877                                store.do_not_match = 0;
 878
 879                        store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
 880                        if (regcomp(store.value_regex, value_regex,
 881                                        REG_EXTENDED)) {
 882                                fprintf(stderr, "Invalid pattern: %s\n",
 883                                        value_regex);
 884                                free(store.value_regex);
 885                                ret = 6;
 886                                goto out_free;
 887                        }
 888                }
 889
 890                store.offset[0] = 0;
 891                store.state = START;
 892                store.seen = 0;
 893
 894                /*
 895                 * After this, store.offset will contain the *end* offset
 896                 * of the last match, or remain at 0 if no match was found.
 897                 * As a side effect, we make sure to transform only a valid
 898                 * existing config file.
 899                 */
 900                if (git_config_from_file(store_aux, config_filename)) {
 901                        fprintf(stderr, "invalid config file\n");
 902                        free(store.key);
 903                        if (store.value_regex != NULL) {
 904                                regfree(store.value_regex);
 905                                free(store.value_regex);
 906                        }
 907                        ret = 3;
 908                        goto out_free;
 909                }
 910
 911                free(store.key);
 912                if (store.value_regex != NULL) {
 913                        regfree(store.value_regex);
 914                        free(store.value_regex);
 915                }
 916
 917                /* if nothing to unset, or too many matches, error out */
 918                if ((store.seen == 0 && value == NULL) ||
 919                                (store.seen > 1 && multi_replace == 0)) {
 920                        ret = 5;
 921                        goto out_free;
 922                }
 923
 924                fstat(in_fd, &st);
 925                contents_sz = xsize_t(st.st_size);
 926                contents = xmmap(NULL, contents_sz, PROT_READ,
 927                        MAP_PRIVATE, in_fd, 0);
 928                close(in_fd);
 929
 930                if (store.seen == 0)
 931                        store.seen = 1;
 932
 933                for (i = 0, copy_begin = 0; i < store.seen; i++) {
 934                        if (store.offset[i] == 0) {
 935                                store.offset[i] = copy_end = contents_sz;
 936                        } else if (store.state != KEY_SEEN) {
 937                                copy_end = store.offset[i];
 938                        } else
 939                                copy_end = find_beginning_of_line(
 940                                        contents, contents_sz,
 941                                        store.offset[i]-2, &new_line);
 942
 943                        /* write the first part of the config */
 944                        if (copy_end > copy_begin) {
 945                                if (write_in_full(fd, contents + copy_begin,
 946                                                  copy_end - copy_begin) <
 947                                    copy_end - copy_begin)
 948                                        goto write_err_out;
 949                                if (new_line &&
 950                                    write_in_full(fd, "\n", 1) != 1)
 951                                        goto write_err_out;
 952                        }
 953                        copy_begin = store.offset[i];
 954                }
 955
 956                /* write the pair (value == NULL means unset) */
 957                if (value != NULL) {
 958                        if (store.state == START) {
 959                                if (!store_write_section(fd, key))
 960                                        goto write_err_out;
 961                        }
 962                        if (!store_write_pair(fd, key, value))
 963                                goto write_err_out;
 964                }
 965
 966                /* write the rest of the config */
 967                if (copy_begin < contents_sz)
 968                        if (write_in_full(fd, contents + copy_begin,
 969                                          contents_sz - copy_begin) <
 970                            contents_sz - copy_begin)
 971                                goto write_err_out;
 972
 973                munmap(contents, contents_sz);
 974        }
 975
 976        if (close(fd) || commit_lock_file(lock) < 0) {
 977                fprintf(stderr, "Cannot commit config file!\n");
 978                ret = 4;
 979                goto out_free;
 980        }
 981
 982        /* fd is closed, so don't try to close it below. */
 983        fd = -1;
 984        /*
 985         * lock is committed, so don't try to roll it back below.
 986         * NOTE: Since lockfile.c keeps a linked list of all created
 987         * lock_file structures, it isn't safe to free(lock).  It's
 988         * better to just leave it hanging around.
 989         */
 990        lock = NULL;
 991        ret = 0;
 992
 993out_free:
 994        if (0 <= fd)
 995                close(fd);
 996        if (lock)
 997                rollback_lock_file(lock);
 998        free(config_filename);
 999        return ret;
1000
1001write_err_out:
1002        ret = write_error();
1003        goto out_free;
1004
1005}
1006
1007static int section_name_match (const char *buf, const char *name)
1008{
1009        int i = 0, j = 0, dot = 0;
1010        for (; buf[i] && buf[i] != ']'; i++) {
1011                if (!dot && isspace(buf[i])) {
1012                        dot = 1;
1013                        if (name[j++] != '.')
1014                                break;
1015                        for (i++; isspace(buf[i]); i++)
1016                                ; /* do nothing */
1017                        if (buf[i] != '"')
1018                                break;
1019                        continue;
1020                }
1021                if (buf[i] == '\\' && dot)
1022                        i++;
1023                else if (buf[i] == '"' && dot) {
1024                        for (i++; isspace(buf[i]); i++)
1025                                ; /* do_nothing */
1026                        break;
1027                }
1028                if (buf[i] != name[j++])
1029                        break;
1030        }
1031        return (buf[i] == ']' && name[j] == 0);
1032}
1033
1034/* if new_name == NULL, the section is removed instead */
1035int git_config_rename_section(const char *old_name, const char *new_name)
1036{
1037        int ret = 0, remove = 0;
1038        char *config_filename;
1039        struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1040        int out_fd;
1041        char buf[1024];
1042
1043        config_filename = getenv(CONFIG_ENVIRONMENT);
1044        if (!config_filename) {
1045                config_filename = getenv(CONFIG_LOCAL_ENVIRONMENT);
1046                if (!config_filename)
1047                        config_filename  = git_path("config");
1048        }
1049        config_filename = xstrdup(config_filename);
1050        out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1051        if (out_fd < 0) {
1052                ret = error("Could not lock config file!");
1053                goto out;
1054        }
1055
1056        if (!(config_file = fopen(config_filename, "rb"))) {
1057                /* no config file means nothing to rename, no error */
1058                goto unlock_and_out;
1059        }
1060
1061        while (fgets(buf, sizeof(buf), config_file)) {
1062                int i;
1063                int length;
1064                for (i = 0; buf[i] && isspace(buf[i]); i++)
1065                        ; /* do nothing */
1066                if (buf[i] == '[') {
1067                        /* it's a section */
1068                        if (section_name_match (&buf[i+1], old_name)) {
1069                                ret++;
1070                                if (new_name == NULL) {
1071                                        remove = 1;
1072                                        continue;
1073                                }
1074                                store.baselen = strlen(new_name);
1075                                if (!store_write_section(out_fd, new_name)) {
1076                                        ret = write_error();
1077                                        goto out;
1078                                }
1079                                continue;
1080                        }
1081                        remove = 0;
1082                }
1083                if (remove)
1084                        continue;
1085                length = strlen(buf);
1086                if (write_in_full(out_fd, buf, length) != length) {
1087                        ret = write_error();
1088                        goto out;
1089                }
1090        }
1091        fclose(config_file);
1092 unlock_and_out:
1093        if (close(out_fd) || commit_lock_file(lock) < 0)
1094                        ret = error("Cannot commit config file!");
1095 out:
1096        free(config_filename);
1097        return ret;
1098}