config.con commit Complete prototype of git_config_from_parameters() (b3d83d9)
   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#include "exec_cmd.h"
  10#include "strbuf.h"
  11
  12#define MAXNAME (256)
  13
  14static FILE *config_file;
  15static const char *config_file_name;
  16static int config_linenr;
  17static int config_file_eof;
  18static int zlib_compression_seen;
  19
  20const char *config_exclusive_filename = NULL;
  21
  22struct config_item
  23{
  24        struct config_item *next;
  25        char *name;
  26        char *value;
  27};
  28static struct config_item *config_parameters;
  29static struct config_item **config_parameters_tail = &config_parameters;
  30
  31static void lowercase(char *p)
  32{
  33        for (; *p; p++)
  34                *p = tolower(*p);
  35}
  36
  37int git_config_parse_parameter(const char *text)
  38{
  39        struct config_item *ct;
  40        struct strbuf tmp = STRBUF_INIT;
  41        struct strbuf **pair;
  42        strbuf_addstr(&tmp, text);
  43        pair = strbuf_split(&tmp, '=');
  44        if (pair[0]->len && pair[0]->buf[pair[0]->len - 1] == '=')
  45                strbuf_setlen(pair[0], pair[0]->len - 1);
  46        strbuf_trim(pair[0]);
  47        if (!pair[0]->len) {
  48                strbuf_list_free(pair);
  49                return -1;
  50        }
  51        ct = xcalloc(1, sizeof(struct config_item));
  52        ct->name = strbuf_detach(pair[0], NULL);
  53        if (pair[1]) {
  54                strbuf_trim(pair[1]);
  55                ct->value = strbuf_detach(pair[1], NULL);
  56        }
  57        strbuf_list_free(pair);
  58        lowercase(ct->name);
  59        *config_parameters_tail = ct;
  60        config_parameters_tail = &ct->next;
  61        return 0;
  62}
  63
  64static int get_next_char(void)
  65{
  66        int c;
  67        FILE *f;
  68
  69        c = '\n';
  70        if ((f = config_file) != NULL) {
  71                c = fgetc(f);
  72                if (c == '\r') {
  73                        /* DOS like systems */
  74                        c = fgetc(f);
  75                        if (c != '\n') {
  76                                ungetc(c, f);
  77                                c = '\r';
  78                        }
  79                }
  80                if (c == '\n')
  81                        config_linenr++;
  82                if (c == EOF) {
  83                        config_file_eof = 1;
  84                        c = '\n';
  85                }
  86        }
  87        return c;
  88}
  89
  90static char *parse_value(void)
  91{
  92        static char value[1024];
  93        int quote = 0, comment = 0, len = 0, space = 0;
  94
  95        for (;;) {
  96                int c = get_next_char();
  97                if (len >= sizeof(value) - 1)
  98                        return NULL;
  99                if (c == '\n') {
 100                        if (quote)
 101                                return NULL;
 102                        value[len] = 0;
 103                        return value;
 104                }
 105                if (comment)
 106                        continue;
 107                if (isspace(c) && !quote) {
 108                        if (len)
 109                                space++;
 110                        continue;
 111                }
 112                if (!quote) {
 113                        if (c == ';' || c == '#') {
 114                                comment = 1;
 115                                continue;
 116                        }
 117                }
 118                for (; space; space--)
 119                        value[len++] = ' ';
 120                if (c == '\\') {
 121                        c = get_next_char();
 122                        switch (c) {
 123                        case '\n':
 124                                continue;
 125                        case 't':
 126                                c = '\t';
 127                                break;
 128                        case 'b':
 129                                c = '\b';
 130                                break;
 131                        case 'n':
 132                                c = '\n';
 133                                break;
 134                        /* Some characters escape as themselves */
 135                        case '\\': case '"':
 136                                break;
 137                        /* Reject unknown escape sequences */
 138                        default:
 139                                return NULL;
 140                        }
 141                        value[len++] = c;
 142                        continue;
 143                }
 144                if (c == '"') {
 145                        quote = 1-quote;
 146                        continue;
 147                }
 148                value[len++] = c;
 149        }
 150}
 151
 152static inline int iskeychar(int c)
 153{
 154        return isalnum(c) || c == '-';
 155}
 156
 157static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
 158{
 159        int c;
 160        char *value;
 161
 162        /* Get the full name */
 163        for (;;) {
 164                c = get_next_char();
 165                if (config_file_eof)
 166                        break;
 167                if (!iskeychar(c))
 168                        break;
 169                name[len++] = tolower(c);
 170                if (len >= MAXNAME)
 171                        return -1;
 172        }
 173        name[len] = 0;
 174        while (c == ' ' || c == '\t')
 175                c = get_next_char();
 176
 177        value = NULL;
 178        if (c != '\n') {
 179                if (c != '=')
 180                        return -1;
 181                value = parse_value();
 182                if (!value)
 183                        return -1;
 184        }
 185        return fn(name, value, data);
 186}
 187
 188static int get_extended_base_var(char *name, int baselen, int c)
 189{
 190        do {
 191                if (c == '\n')
 192                        return -1;
 193                c = get_next_char();
 194        } while (isspace(c));
 195
 196        /* We require the format to be '[base "extension"]' */
 197        if (c != '"')
 198                return -1;
 199        name[baselen++] = '.';
 200
 201        for (;;) {
 202                int c = get_next_char();
 203                if (c == '\n')
 204                        return -1;
 205                if (c == '"')
 206                        break;
 207                if (c == '\\') {
 208                        c = get_next_char();
 209                        if (c == '\n')
 210                                return -1;
 211                }
 212                name[baselen++] = c;
 213                if (baselen > MAXNAME / 2)
 214                        return -1;
 215        }
 216
 217        /* Final ']' */
 218        if (get_next_char() != ']')
 219                return -1;
 220        return baselen;
 221}
 222
 223static int get_base_var(char *name)
 224{
 225        int baselen = 0;
 226
 227        for (;;) {
 228                int c = get_next_char();
 229                if (config_file_eof)
 230                        return -1;
 231                if (c == ']')
 232                        return baselen;
 233                if (isspace(c))
 234                        return get_extended_base_var(name, baselen, c);
 235                if (!iskeychar(c) && c != '.')
 236                        return -1;
 237                if (baselen > MAXNAME / 2)
 238                        return -1;
 239                name[baselen++] = tolower(c);
 240        }
 241}
 242
 243static int git_parse_file(config_fn_t fn, void *data)
 244{
 245        int comment = 0;
 246        int baselen = 0;
 247        static char var[MAXNAME];
 248
 249        /* U+FEFF Byte Order Mark in UTF8 */
 250        static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
 251        const unsigned char *bomptr = utf8_bom;
 252
 253        for (;;) {
 254                int c = get_next_char();
 255                if (bomptr && *bomptr) {
 256                        /* We are at the file beginning; skip UTF8-encoded BOM
 257                         * if present. Sane editors won't put this in on their
 258                         * own, but e.g. Windows Notepad will do it happily. */
 259                        if ((unsigned char) c == *bomptr) {
 260                                bomptr++;
 261                                continue;
 262                        } else {
 263                                /* Do not tolerate partial BOM. */
 264                                if (bomptr != utf8_bom)
 265                                        break;
 266                                /* No BOM at file beginning. Cool. */
 267                                bomptr = NULL;
 268                        }
 269                }
 270                if (c == '\n') {
 271                        if (config_file_eof)
 272                                return 0;
 273                        comment = 0;
 274                        continue;
 275                }
 276                if (comment || isspace(c))
 277                        continue;
 278                if (c == '#' || c == ';') {
 279                        comment = 1;
 280                        continue;
 281                }
 282                if (c == '[') {
 283                        baselen = get_base_var(var);
 284                        if (baselen <= 0)
 285                                break;
 286                        var[baselen++] = '.';
 287                        var[baselen] = 0;
 288                        continue;
 289                }
 290                if (!isalpha(c))
 291                        break;
 292                var[baselen] = tolower(c);
 293                if (get_value(fn, data, var, baselen+1) < 0)
 294                        break;
 295        }
 296        die("bad config file line %d in %s", config_linenr, config_file_name);
 297}
 298
 299static int parse_unit_factor(const char *end, unsigned long *val)
 300{
 301        if (!*end)
 302                return 1;
 303        else if (!strcasecmp(end, "k")) {
 304                *val *= 1024;
 305                return 1;
 306        }
 307        else if (!strcasecmp(end, "m")) {
 308                *val *= 1024 * 1024;
 309                return 1;
 310        }
 311        else if (!strcasecmp(end, "g")) {
 312                *val *= 1024 * 1024 * 1024;
 313                return 1;
 314        }
 315        return 0;
 316}
 317
 318static int git_parse_long(const char *value, long *ret)
 319{
 320        if (value && *value) {
 321                char *end;
 322                long val = strtol(value, &end, 0);
 323                unsigned long factor = 1;
 324                if (!parse_unit_factor(end, &factor))
 325                        return 0;
 326                *ret = val * factor;
 327                return 1;
 328        }
 329        return 0;
 330}
 331
 332int git_parse_ulong(const char *value, unsigned long *ret)
 333{
 334        if (value && *value) {
 335                char *end;
 336                unsigned long val = strtoul(value, &end, 0);
 337                if (!parse_unit_factor(end, &val))
 338                        return 0;
 339                *ret = val;
 340                return 1;
 341        }
 342        return 0;
 343}
 344
 345static void die_bad_config(const char *name)
 346{
 347        if (config_file_name)
 348                die("bad config value for '%s' in %s", name, config_file_name);
 349        die("bad config value for '%s'", name);
 350}
 351
 352int git_config_int(const char *name, const char *value)
 353{
 354        long ret = 0;
 355        if (!git_parse_long(value, &ret))
 356                die_bad_config(name);
 357        return ret;
 358}
 359
 360unsigned long git_config_ulong(const char *name, const char *value)
 361{
 362        unsigned long ret;
 363        if (!git_parse_ulong(value, &ret))
 364                die_bad_config(name);
 365        return ret;
 366}
 367
 368int git_config_bool_or_int(const char *name, const char *value, int *is_bool)
 369{
 370        *is_bool = 1;
 371        if (!value)
 372                return 1;
 373        if (!*value)
 374                return 0;
 375        if (!strcasecmp(value, "true") || !strcasecmp(value, "yes") || !strcasecmp(value, "on"))
 376                return 1;
 377        if (!strcasecmp(value, "false") || !strcasecmp(value, "no") || !strcasecmp(value, "off"))
 378                return 0;
 379        *is_bool = 0;
 380        return git_config_int(name, value);
 381}
 382
 383int git_config_bool(const char *name, const char *value)
 384{
 385        int discard;
 386        return !!git_config_bool_or_int(name, value, &discard);
 387}
 388
 389int git_config_string(const char **dest, const char *var, const char *value)
 390{
 391        if (!value)
 392                return config_error_nonbool(var);
 393        *dest = xstrdup(value);
 394        return 0;
 395}
 396
 397int git_config_pathname(const char **dest, const char *var, const char *value)
 398{
 399        if (!value)
 400                return config_error_nonbool(var);
 401        *dest = expand_user_path(value);
 402        if (!*dest)
 403                die("Failed to expand user dir in: '%s'", value);
 404        return 0;
 405}
 406
 407static int git_default_core_config(const char *var, const char *value)
 408{
 409        /* This needs a better name */
 410        if (!strcmp(var, "core.filemode")) {
 411                trust_executable_bit = git_config_bool(var, value);
 412                return 0;
 413        }
 414        if (!strcmp(var, "core.trustctime")) {
 415                trust_ctime = git_config_bool(var, value);
 416                return 0;
 417        }
 418
 419        if (!strcmp(var, "core.quotepath")) {
 420                quote_path_fully = git_config_bool(var, value);
 421                return 0;
 422        }
 423
 424        if (!strcmp(var, "core.symlinks")) {
 425                has_symlinks = git_config_bool(var, value);
 426                return 0;
 427        }
 428
 429        if (!strcmp(var, "core.ignorecase")) {
 430                ignore_case = git_config_bool(var, value);
 431                return 0;
 432        }
 433
 434        if (!strcmp(var, "core.bare")) {
 435                is_bare_repository_cfg = git_config_bool(var, value);
 436                return 0;
 437        }
 438
 439        if (!strcmp(var, "core.ignorestat")) {
 440                assume_unchanged = git_config_bool(var, value);
 441                return 0;
 442        }
 443
 444        if (!strcmp(var, "core.prefersymlinkrefs")) {
 445                prefer_symlink_refs = git_config_bool(var, value);
 446                return 0;
 447        }
 448
 449        if (!strcmp(var, "core.logallrefupdates")) {
 450                log_all_ref_updates = git_config_bool(var, value);
 451                return 0;
 452        }
 453
 454        if (!strcmp(var, "core.warnambiguousrefs")) {
 455                warn_ambiguous_refs = git_config_bool(var, value);
 456                return 0;
 457        }
 458
 459        if (!strcmp(var, "core.loosecompression")) {
 460                int level = git_config_int(var, value);
 461                if (level == -1)
 462                        level = Z_DEFAULT_COMPRESSION;
 463                else if (level < 0 || level > Z_BEST_COMPRESSION)
 464                        die("bad zlib compression level %d", level);
 465                zlib_compression_level = level;
 466                zlib_compression_seen = 1;
 467                return 0;
 468        }
 469
 470        if (!strcmp(var, "core.compression")) {
 471                int level = git_config_int(var, value);
 472                if (level == -1)
 473                        level = Z_DEFAULT_COMPRESSION;
 474                else if (level < 0 || level > Z_BEST_COMPRESSION)
 475                        die("bad zlib compression level %d", level);
 476                core_compression_level = level;
 477                core_compression_seen = 1;
 478                if (!zlib_compression_seen)
 479                        zlib_compression_level = level;
 480                return 0;
 481        }
 482
 483        if (!strcmp(var, "core.packedgitwindowsize")) {
 484                int pgsz_x2 = getpagesize() * 2;
 485                packed_git_window_size = git_config_int(var, value);
 486
 487                /* This value must be multiple of (pagesize * 2) */
 488                packed_git_window_size /= pgsz_x2;
 489                if (packed_git_window_size < 1)
 490                        packed_git_window_size = 1;
 491                packed_git_window_size *= pgsz_x2;
 492                return 0;
 493        }
 494
 495        if (!strcmp(var, "core.packedgitlimit")) {
 496                packed_git_limit = git_config_int(var, value);
 497                return 0;
 498        }
 499
 500        if (!strcmp(var, "core.deltabasecachelimit")) {
 501                delta_base_cache_limit = git_config_int(var, value);
 502                return 0;
 503        }
 504
 505        if (!strcmp(var, "core.autocrlf")) {
 506                if (value && !strcasecmp(value, "input")) {
 507                        auto_crlf = -1;
 508                        return 0;
 509                }
 510                auto_crlf = git_config_bool(var, value);
 511                return 0;
 512        }
 513
 514        if (!strcmp(var, "core.safecrlf")) {
 515                if (value && !strcasecmp(value, "warn")) {
 516                        safe_crlf = SAFE_CRLF_WARN;
 517                        return 0;
 518                }
 519                safe_crlf = git_config_bool(var, value);
 520                return 0;
 521        }
 522
 523        if (!strcmp(var, "core.notesref")) {
 524                notes_ref_name = xstrdup(value);
 525                return 0;
 526        }
 527
 528        if (!strcmp(var, "core.pager"))
 529                return git_config_string(&pager_program, var, value);
 530
 531        if (!strcmp(var, "core.editor"))
 532                return git_config_string(&editor_program, var, value);
 533
 534        if (!strcmp(var, "core.excludesfile"))
 535                return git_config_pathname(&excludes_file, var, value);
 536
 537        if (!strcmp(var, "core.whitespace")) {
 538                if (!value)
 539                        return config_error_nonbool(var);
 540                whitespace_rule_cfg = parse_whitespace_rule(value);
 541                return 0;
 542        }
 543
 544        if (!strcmp(var, "core.fsyncobjectfiles")) {
 545                fsync_object_files = git_config_bool(var, value);
 546                return 0;
 547        }
 548
 549        if (!strcmp(var, "core.preloadindex")) {
 550                core_preload_index = git_config_bool(var, value);
 551                return 0;
 552        }
 553
 554        if (!strcmp(var, "core.createobject")) {
 555                if (!strcmp(value, "rename"))
 556                        object_creation_mode = OBJECT_CREATION_USES_RENAMES;
 557                else if (!strcmp(value, "link"))
 558                        object_creation_mode = OBJECT_CREATION_USES_HARDLINKS;
 559                else
 560                        die("Invalid mode for object creation: %s", value);
 561                return 0;
 562        }
 563
 564        if (!strcmp(var, "core.sparsecheckout")) {
 565                core_apply_sparse_checkout = git_config_bool(var, value);
 566                return 0;
 567        }
 568
 569        /* Add other config variables here and to Documentation/config.txt. */
 570        return 0;
 571}
 572
 573static int git_default_user_config(const char *var, const char *value)
 574{
 575        if (!strcmp(var, "user.name")) {
 576                if (!value)
 577                        return config_error_nonbool(var);
 578                strlcpy(git_default_name, value, sizeof(git_default_name));
 579                user_ident_explicitly_given |= IDENT_NAME_GIVEN;
 580                return 0;
 581        }
 582
 583        if (!strcmp(var, "user.email")) {
 584                if (!value)
 585                        return config_error_nonbool(var);
 586                strlcpy(git_default_email, value, sizeof(git_default_email));
 587                user_ident_explicitly_given |= IDENT_MAIL_GIVEN;
 588                return 0;
 589        }
 590
 591        /* Add other config variables here and to Documentation/config.txt. */
 592        return 0;
 593}
 594
 595static int git_default_i18n_config(const char *var, const char *value)
 596{
 597        if (!strcmp(var, "i18n.commitencoding"))
 598                return git_config_string(&git_commit_encoding, var, value);
 599
 600        if (!strcmp(var, "i18n.logoutputencoding"))
 601                return git_config_string(&git_log_output_encoding, var, value);
 602
 603        /* Add other config variables here and to Documentation/config.txt. */
 604        return 0;
 605}
 606
 607static int git_default_branch_config(const char *var, const char *value)
 608{
 609        if (!strcmp(var, "branch.autosetupmerge")) {
 610                if (value && !strcasecmp(value, "always")) {
 611                        git_branch_track = BRANCH_TRACK_ALWAYS;
 612                        return 0;
 613                }
 614                git_branch_track = git_config_bool(var, value);
 615                return 0;
 616        }
 617        if (!strcmp(var, "branch.autosetuprebase")) {
 618                if (!value)
 619                        return config_error_nonbool(var);
 620                else if (!strcmp(value, "never"))
 621                        autorebase = AUTOREBASE_NEVER;
 622                else if (!strcmp(value, "local"))
 623                        autorebase = AUTOREBASE_LOCAL;
 624                else if (!strcmp(value, "remote"))
 625                        autorebase = AUTOREBASE_REMOTE;
 626                else if (!strcmp(value, "always"))
 627                        autorebase = AUTOREBASE_ALWAYS;
 628                else
 629                        return error("Malformed value for %s", var);
 630                return 0;
 631        }
 632
 633        /* Add other config variables here and to Documentation/config.txt. */
 634        return 0;
 635}
 636
 637static int git_default_push_config(const char *var, const char *value)
 638{
 639        if (!strcmp(var, "push.default")) {
 640                if (!value)
 641                        return config_error_nonbool(var);
 642                else if (!strcmp(value, "nothing"))
 643                        push_default = PUSH_DEFAULT_NOTHING;
 644                else if (!strcmp(value, "matching"))
 645                        push_default = PUSH_DEFAULT_MATCHING;
 646                else if (!strcmp(value, "tracking"))
 647                        push_default = PUSH_DEFAULT_TRACKING;
 648                else if (!strcmp(value, "current"))
 649                        push_default = PUSH_DEFAULT_CURRENT;
 650                else {
 651                        error("Malformed value for %s: %s", var, value);
 652                        return error("Must be one of nothing, matching, "
 653                                     "tracking or current.");
 654                }
 655                return 0;
 656        }
 657
 658        /* Add other config variables here and to Documentation/config.txt. */
 659        return 0;
 660}
 661
 662static int git_default_mailmap_config(const char *var, const char *value)
 663{
 664        if (!strcmp(var, "mailmap.file"))
 665                return git_config_string(&git_mailmap_file, var, value);
 666
 667        /* Add other config variables here and to Documentation/config.txt. */
 668        return 0;
 669}
 670
 671int git_default_config(const char *var, const char *value, void *dummy)
 672{
 673        if (!prefixcmp(var, "core."))
 674                return git_default_core_config(var, value);
 675
 676        if (!prefixcmp(var, "user."))
 677                return git_default_user_config(var, value);
 678
 679        if (!prefixcmp(var, "i18n."))
 680                return git_default_i18n_config(var, value);
 681
 682        if (!prefixcmp(var, "branch."))
 683                return git_default_branch_config(var, value);
 684
 685        if (!prefixcmp(var, "push."))
 686                return git_default_push_config(var, value);
 687
 688        if (!prefixcmp(var, "mailmap."))
 689                return git_default_mailmap_config(var, value);
 690
 691        if (!prefixcmp(var, "advice."))
 692                return git_default_advice_config(var, value);
 693
 694        if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
 695                pager_use_color = git_config_bool(var,value);
 696                return 0;
 697        }
 698
 699        /* Add other config variables here and to Documentation/config.txt. */
 700        return 0;
 701}
 702
 703int git_config_from_file(config_fn_t fn, const char *filename, void *data)
 704{
 705        int ret;
 706        FILE *f = fopen(filename, "r");
 707
 708        ret = -1;
 709        if (f) {
 710                config_file = f;
 711                config_file_name = filename;
 712                config_linenr = 1;
 713                config_file_eof = 0;
 714                ret = git_parse_file(fn, data);
 715                fclose(f);
 716                config_file_name = NULL;
 717        }
 718        return ret;
 719}
 720
 721const char *git_etc_gitconfig(void)
 722{
 723        static const char *system_wide;
 724        if (!system_wide)
 725                system_wide = system_path(ETC_GITCONFIG);
 726        return system_wide;
 727}
 728
 729static int git_env_bool(const char *k, int def)
 730{
 731        const char *v = getenv(k);
 732        return v ? git_config_bool(k, v) : def;
 733}
 734
 735int git_config_system(void)
 736{
 737        return !git_env_bool("GIT_CONFIG_NOSYSTEM", 0);
 738}
 739
 740int git_config_global(void)
 741{
 742        return !git_env_bool("GIT_CONFIG_NOGLOBAL", 0);
 743}
 744
 745int git_config_from_parameters(config_fn_t fn, void *data)
 746{
 747        const struct config_item *ct;
 748        for (ct = config_parameters; ct; ct = ct->next)
 749                if (fn(ct->name, ct->value, data) < 0)
 750                        return -1;
 751        return 0;
 752}
 753
 754int git_config(config_fn_t fn, void *data)
 755{
 756        int ret = 0, found = 0;
 757        char *repo_config = NULL;
 758        const char *home = NULL;
 759
 760        /* Setting $GIT_CONFIG makes git read _only_ the given config file. */
 761        if (config_exclusive_filename)
 762                return git_config_from_file(fn, config_exclusive_filename, data);
 763        if (git_config_system() && !access(git_etc_gitconfig(), R_OK)) {
 764                ret += git_config_from_file(fn, git_etc_gitconfig(),
 765                                            data);
 766                found += 1;
 767        }
 768
 769        home = getenv("HOME");
 770        if (git_config_global() && home) {
 771                char *user_config = xstrdup(mkpath("%s/.gitconfig", home));
 772                if (!access(user_config, R_OK)) {
 773                        ret += git_config_from_file(fn, user_config, data);
 774                        found += 1;
 775                }
 776                free(user_config);
 777        }
 778
 779        repo_config = git_pathdup("config");
 780        if (!access(repo_config, R_OK)) {
 781                ret += git_config_from_file(fn, repo_config, data);
 782                found += 1;
 783        }
 784        free(repo_config);
 785
 786        if (config_parameters) {
 787                ret += git_config_from_parameters(fn, data);
 788                found += 1;
 789        }
 790
 791        if (found == 0)
 792                return -1;
 793        return ret;
 794}
 795
 796/*
 797 * Find all the stuff for git_config_set() below.
 798 */
 799
 800#define MAX_MATCHES 512
 801
 802static struct {
 803        int baselen;
 804        char *key;
 805        int do_not_match;
 806        regex_t *value_regex;
 807        int multi_replace;
 808        size_t offset[MAX_MATCHES];
 809        enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
 810        int seen;
 811} store;
 812
 813static int matches(const char *key, const char *value)
 814{
 815        return !strcmp(key, store.key) &&
 816                (store.value_regex == NULL ||
 817                 (store.do_not_match ^
 818                  !regexec(store.value_regex, value, 0, NULL, 0)));
 819}
 820
 821static int store_aux(const char *key, const char *value, void *cb)
 822{
 823        const char *ep;
 824        size_t section_len;
 825
 826        switch (store.state) {
 827        case KEY_SEEN:
 828                if (matches(key, value)) {
 829                        if (store.seen == 1 && store.multi_replace == 0) {
 830                                warning("%s has multiple values", key);
 831                        } else if (store.seen >= MAX_MATCHES) {
 832                                error("too many matches for %s", key);
 833                                return 1;
 834                        }
 835
 836                        store.offset[store.seen] = ftell(config_file);
 837                        store.seen++;
 838                }
 839                break;
 840        case SECTION_SEEN:
 841                /*
 842                 * What we are looking for is in store.key (both
 843                 * section and var), and its section part is baselen
 844                 * long.  We found key (again, both section and var).
 845                 * We would want to know if this key is in the same
 846                 * section as what we are looking for.  We already
 847                 * know we are in the same section as what should
 848                 * hold store.key.
 849                 */
 850                ep = strrchr(key, '.');
 851                section_len = ep - key;
 852
 853                if ((section_len != store.baselen) ||
 854                    memcmp(key, store.key, section_len+1)) {
 855                        store.state = SECTION_END_SEEN;
 856                        break;
 857                }
 858
 859                /*
 860                 * Do not increment matches: this is no match, but we
 861                 * just made sure we are in the desired section.
 862                 */
 863                store.offset[store.seen] = ftell(config_file);
 864                /* fallthru */
 865        case SECTION_END_SEEN:
 866        case START:
 867                if (matches(key, value)) {
 868                        store.offset[store.seen] = ftell(config_file);
 869                        store.state = KEY_SEEN;
 870                        store.seen++;
 871                } else {
 872                        if (strrchr(key, '.') - key == store.baselen &&
 873                              !strncmp(key, store.key, store.baselen)) {
 874                                        store.state = SECTION_SEEN;
 875                                        store.offset[store.seen] = ftell(config_file);
 876                        }
 877                }
 878        }
 879        return 0;
 880}
 881
 882static int write_error(const char *filename)
 883{
 884        error("failed to write new configuration file %s", filename);
 885
 886        /* Same error code as "failed to rename". */
 887        return 4;
 888}
 889
 890static int store_write_section(int fd, const char *key)
 891{
 892        const char *dot;
 893        int i, success;
 894        struct strbuf sb = STRBUF_INIT;
 895
 896        dot = memchr(key, '.', store.baselen);
 897        if (dot) {
 898                strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
 899                for (i = dot - key + 1; i < store.baselen; i++) {
 900                        if (key[i] == '"' || key[i] == '\\')
 901                                strbuf_addch(&sb, '\\');
 902                        strbuf_addch(&sb, key[i]);
 903                }
 904                strbuf_addstr(&sb, "\"]\n");
 905        } else {
 906                strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
 907        }
 908
 909        success = write_in_full(fd, sb.buf, sb.len) == sb.len;
 910        strbuf_release(&sb);
 911
 912        return success;
 913}
 914
 915static int store_write_pair(int fd, const char *key, const char *value)
 916{
 917        int i, success;
 918        int length = strlen(key + store.baselen + 1);
 919        const char *quote = "";
 920        struct strbuf sb = STRBUF_INIT;
 921
 922        /*
 923         * Check to see if the value needs to be surrounded with a dq pair.
 924         * Note that problematic characters are always backslash-quoted; this
 925         * check is about not losing leading or trailing SP and strings that
 926         * follow beginning-of-comment characters (i.e. ';' and '#') by the
 927         * configuration parser.
 928         */
 929        if (value[0] == ' ')
 930                quote = "\"";
 931        for (i = 0; value[i]; i++)
 932                if (value[i] == ';' || value[i] == '#')
 933                        quote = "\"";
 934        if (i && value[i - 1] == ' ')
 935                quote = "\"";
 936
 937        strbuf_addf(&sb, "\t%.*s = %s",
 938                    length, key + store.baselen + 1, quote);
 939
 940        for (i = 0; value[i]; i++)
 941                switch (value[i]) {
 942                case '\n':
 943                        strbuf_addstr(&sb, "\\n");
 944                        break;
 945                case '\t':
 946                        strbuf_addstr(&sb, "\\t");
 947                        break;
 948                case '"':
 949                case '\\':
 950                        strbuf_addch(&sb, '\\');
 951                default:
 952                        strbuf_addch(&sb, value[i]);
 953                        break;
 954                }
 955        strbuf_addf(&sb, "%s\n", quote);
 956
 957        success = write_in_full(fd, sb.buf, sb.len) == sb.len;
 958        strbuf_release(&sb);
 959
 960        return success;
 961}
 962
 963static ssize_t find_beginning_of_line(const char *contents, size_t size,
 964        size_t offset_, int *found_bracket)
 965{
 966        size_t equal_offset = size, bracket_offset = size;
 967        ssize_t offset;
 968
 969contline:
 970        for (offset = offset_-2; offset > 0
 971                        && contents[offset] != '\n'; offset--)
 972                switch (contents[offset]) {
 973                        case '=': equal_offset = offset; break;
 974                        case ']': bracket_offset = offset; break;
 975                }
 976        if (offset > 0 && contents[offset-1] == '\\') {
 977                offset_ = offset;
 978                goto contline;
 979        }
 980        if (bracket_offset < equal_offset) {
 981                *found_bracket = 1;
 982                offset = bracket_offset+1;
 983        } else
 984                offset++;
 985
 986        return offset;
 987}
 988
 989int git_config_set(const char *key, const char *value)
 990{
 991        return git_config_set_multivar(key, value, NULL, 0);
 992}
 993
 994/*
 995 * If value==NULL, unset in (remove from) config,
 996 * if value_regex!=NULL, disregard key/value pairs where value does not match.
 997 * if multi_replace==0, nothing, or only one matching key/value is replaced,
 998 *     else all matching key/values (regardless how many) are removed,
 999 *     before the new pair is written.
1000 *
1001 * Returns 0 on success.
1002 *
1003 * This function does this:
1004 *
1005 * - it locks the config file by creating ".git/config.lock"
1006 *
1007 * - it then parses the config using store_aux() as validator to find
1008 *   the position on the key/value pair to replace. If it is to be unset,
1009 *   it must be found exactly once.
1010 *
1011 * - the config file is mmap()ed and the part before the match (if any) is
1012 *   written to the lock file, then the changed part and the rest.
1013 *
1014 * - the config file is removed and the lock file rename()d to it.
1015 *
1016 */
1017int git_config_set_multivar(const char *key, const char *value,
1018        const char *value_regex, int multi_replace)
1019{
1020        int i, dot;
1021        int fd = -1, in_fd;
1022        int ret;
1023        char *config_filename;
1024        struct lock_file *lock = NULL;
1025        const char *last_dot = strrchr(key, '.');
1026
1027        if (config_exclusive_filename)
1028                config_filename = xstrdup(config_exclusive_filename);
1029        else
1030                config_filename = git_pathdup("config");
1031
1032        /*
1033         * Since "key" actually contains the section name and the real
1034         * key name separated by a dot, we have to know where the dot is.
1035         */
1036
1037        if (last_dot == NULL) {
1038                error("key does not contain a section: %s", key);
1039                ret = 2;
1040                goto out_free;
1041        }
1042        store.baselen = last_dot - key;
1043
1044        store.multi_replace = multi_replace;
1045
1046        /*
1047         * Validate the key and while at it, lower case it for matching.
1048         */
1049        store.key = xmalloc(strlen(key) + 1);
1050        dot = 0;
1051        for (i = 0; key[i]; i++) {
1052                unsigned char c = key[i];
1053                if (c == '.')
1054                        dot = 1;
1055                /* Leave the extended basename untouched.. */
1056                if (!dot || i > store.baselen) {
1057                        if (!iskeychar(c) || (i == store.baselen+1 && !isalpha(c))) {
1058                                error("invalid key: %s", key);
1059                                free(store.key);
1060                                ret = 1;
1061                                goto out_free;
1062                        }
1063                        c = tolower(c);
1064                } else if (c == '\n') {
1065                        error("invalid key (newline): %s", key);
1066                        free(store.key);
1067                        ret = 1;
1068                        goto out_free;
1069                }
1070                store.key[i] = c;
1071        }
1072        store.key[i] = 0;
1073
1074        /*
1075         * The lock serves a purpose in addition to locking: the new
1076         * contents of .git/config will be written into it.
1077         */
1078        lock = xcalloc(sizeof(struct lock_file), 1);
1079        fd = hold_lock_file_for_update(lock, config_filename, 0);
1080        if (fd < 0) {
1081                error("could not lock config file %s: %s", config_filename, strerror(errno));
1082                free(store.key);
1083                ret = -1;
1084                goto out_free;
1085        }
1086
1087        /*
1088         * If .git/config does not exist yet, write a minimal version.
1089         */
1090        in_fd = open(config_filename, O_RDONLY);
1091        if ( in_fd < 0 ) {
1092                free(store.key);
1093
1094                if ( ENOENT != errno ) {
1095                        error("opening %s: %s", config_filename,
1096                              strerror(errno));
1097                        ret = 3; /* same as "invalid config file" */
1098                        goto out_free;
1099                }
1100                /* if nothing to unset, error out */
1101                if (value == NULL) {
1102                        ret = 5;
1103                        goto out_free;
1104                }
1105
1106                store.key = (char *)key;
1107                if (!store_write_section(fd, key) ||
1108                    !store_write_pair(fd, key, value))
1109                        goto write_err_out;
1110        } else {
1111                struct stat st;
1112                char *contents;
1113                size_t contents_sz, copy_begin, copy_end;
1114                int i, new_line = 0;
1115
1116                if (value_regex == NULL)
1117                        store.value_regex = NULL;
1118                else {
1119                        if (value_regex[0] == '!') {
1120                                store.do_not_match = 1;
1121                                value_regex++;
1122                        } else
1123                                store.do_not_match = 0;
1124
1125                        store.value_regex = (regex_t*)xmalloc(sizeof(regex_t));
1126                        if (regcomp(store.value_regex, value_regex,
1127                                        REG_EXTENDED)) {
1128                                error("invalid pattern: %s", value_regex);
1129                                free(store.value_regex);
1130                                ret = 6;
1131                                goto out_free;
1132                        }
1133                }
1134
1135                store.offset[0] = 0;
1136                store.state = START;
1137                store.seen = 0;
1138
1139                /*
1140                 * After this, store.offset will contain the *end* offset
1141                 * of the last match, or remain at 0 if no match was found.
1142                 * As a side effect, we make sure to transform only a valid
1143                 * existing config file.
1144                 */
1145                if (git_config_from_file(store_aux, config_filename, NULL)) {
1146                        error("invalid config file %s", config_filename);
1147                        free(store.key);
1148                        if (store.value_regex != NULL) {
1149                                regfree(store.value_regex);
1150                                free(store.value_regex);
1151                        }
1152                        ret = 3;
1153                        goto out_free;
1154                }
1155
1156                free(store.key);
1157                if (store.value_regex != NULL) {
1158                        regfree(store.value_regex);
1159                        free(store.value_regex);
1160                }
1161
1162                /* if nothing to unset, or too many matches, error out */
1163                if ((store.seen == 0 && value == NULL) ||
1164                                (store.seen > 1 && multi_replace == 0)) {
1165                        ret = 5;
1166                        goto out_free;
1167                }
1168
1169                fstat(in_fd, &st);
1170                contents_sz = xsize_t(st.st_size);
1171                contents = xmmap(NULL, contents_sz, PROT_READ,
1172                        MAP_PRIVATE, in_fd, 0);
1173                close(in_fd);
1174
1175                if (store.seen == 0)
1176                        store.seen = 1;
1177
1178                for (i = 0, copy_begin = 0; i < store.seen; i++) {
1179                        if (store.offset[i] == 0) {
1180                                store.offset[i] = copy_end = contents_sz;
1181                        } else if (store.state != KEY_SEEN) {
1182                                copy_end = store.offset[i];
1183                        } else
1184                                copy_end = find_beginning_of_line(
1185                                        contents, contents_sz,
1186                                        store.offset[i]-2, &new_line);
1187
1188                        if (copy_end > 0 && contents[copy_end-1] != '\n')
1189                                new_line = 1;
1190
1191                        /* write the first part of the config */
1192                        if (copy_end > copy_begin) {
1193                                if (write_in_full(fd, contents + copy_begin,
1194                                                  copy_end - copy_begin) <
1195                                    copy_end - copy_begin)
1196                                        goto write_err_out;
1197                                if (new_line &&
1198                                    write_str_in_full(fd, "\n") != 1)
1199                                        goto write_err_out;
1200                        }
1201                        copy_begin = store.offset[i];
1202                }
1203
1204                /* write the pair (value == NULL means unset) */
1205                if (value != NULL) {
1206                        if (store.state == START) {
1207                                if (!store_write_section(fd, key))
1208                                        goto write_err_out;
1209                        }
1210                        if (!store_write_pair(fd, key, value))
1211                                goto write_err_out;
1212                }
1213
1214                /* write the rest of the config */
1215                if (copy_begin < contents_sz)
1216                        if (write_in_full(fd, contents + copy_begin,
1217                                          contents_sz - copy_begin) <
1218                            contents_sz - copy_begin)
1219                                goto write_err_out;
1220
1221                munmap(contents, contents_sz);
1222        }
1223
1224        if (commit_lock_file(lock) < 0) {
1225                error("could not commit config file %s", config_filename);
1226                ret = 4;
1227                goto out_free;
1228        }
1229
1230        /*
1231         * lock is committed, so don't try to roll it back below.
1232         * NOTE: Since lockfile.c keeps a linked list of all created
1233         * lock_file structures, it isn't safe to free(lock).  It's
1234         * better to just leave it hanging around.
1235         */
1236        lock = NULL;
1237        ret = 0;
1238
1239out_free:
1240        if (lock)
1241                rollback_lock_file(lock);
1242        free(config_filename);
1243        return ret;
1244
1245write_err_out:
1246        ret = write_error(lock->filename);
1247        goto out_free;
1248
1249}
1250
1251static int section_name_match (const char *buf, const char *name)
1252{
1253        int i = 0, j = 0, dot = 0;
1254        if (buf[i] != '[')
1255                return 0;
1256        for (i = 1; buf[i] && buf[i] != ']'; i++) {
1257                if (!dot && isspace(buf[i])) {
1258                        dot = 1;
1259                        if (name[j++] != '.')
1260                                break;
1261                        for (i++; isspace(buf[i]); i++)
1262                                ; /* do nothing */
1263                        if (buf[i] != '"')
1264                                break;
1265                        continue;
1266                }
1267                if (buf[i] == '\\' && dot)
1268                        i++;
1269                else if (buf[i] == '"' && dot) {
1270                        for (i++; isspace(buf[i]); i++)
1271                                ; /* do_nothing */
1272                        break;
1273                }
1274                if (buf[i] != name[j++])
1275                        break;
1276        }
1277        if (buf[i] == ']' && name[j] == 0) {
1278                /*
1279                 * We match, now just find the right length offset by
1280                 * gobbling up any whitespace after it, as well
1281                 */
1282                i++;
1283                for (; buf[i] && isspace(buf[i]); i++)
1284                        ; /* do nothing */
1285                return i;
1286        }
1287        return 0;
1288}
1289
1290/* if new_name == NULL, the section is removed instead */
1291int git_config_rename_section(const char *old_name, const char *new_name)
1292{
1293        int ret = 0, remove = 0;
1294        char *config_filename;
1295        struct lock_file *lock = xcalloc(sizeof(struct lock_file), 1);
1296        int out_fd;
1297        char buf[1024];
1298
1299        if (config_exclusive_filename)
1300                config_filename = xstrdup(config_exclusive_filename);
1301        else
1302                config_filename = git_pathdup("config");
1303        out_fd = hold_lock_file_for_update(lock, config_filename, 0);
1304        if (out_fd < 0) {
1305                ret = error("could not lock config file %s", config_filename);
1306                goto out;
1307        }
1308
1309        if (!(config_file = fopen(config_filename, "rb"))) {
1310                /* no config file means nothing to rename, no error */
1311                goto unlock_and_out;
1312        }
1313
1314        while (fgets(buf, sizeof(buf), config_file)) {
1315                int i;
1316                int length;
1317                char *output = buf;
1318                for (i = 0; buf[i] && isspace(buf[i]); i++)
1319                        ; /* do nothing */
1320                if (buf[i] == '[') {
1321                        /* it's a section */
1322                        int offset = section_name_match(&buf[i], old_name);
1323                        if (offset > 0) {
1324                                ret++;
1325                                if (new_name == NULL) {
1326                                        remove = 1;
1327                                        continue;
1328                                }
1329                                store.baselen = strlen(new_name);
1330                                if (!store_write_section(out_fd, new_name)) {
1331                                        ret = write_error(lock->filename);
1332                                        goto out;
1333                                }
1334                                /*
1335                                 * We wrote out the new section, with
1336                                 * a newline, now skip the old
1337                                 * section's length
1338                                 */
1339                                output += offset + i;
1340                                if (strlen(output) > 0) {
1341                                        /*
1342                                         * More content means there's
1343                                         * a declaration to put on the
1344                                         * next line; indent with a
1345                                         * tab
1346                                         */
1347                                        output -= 1;
1348                                        output[0] = '\t';
1349                                }
1350                        }
1351                        remove = 0;
1352                }
1353                if (remove)
1354                        continue;
1355                length = strlen(output);
1356                if (write_in_full(out_fd, output, length) != length) {
1357                        ret = write_error(lock->filename);
1358                        goto out;
1359                }
1360        }
1361        fclose(config_file);
1362 unlock_and_out:
1363        if (commit_lock_file(lock) < 0)
1364                ret = error("could not commit config file %s", config_filename);
1365 out:
1366        free(config_filename);
1367        return ret;
1368}
1369
1370/*
1371 * Call this to report error for your variable that should not
1372 * get a boolean value (i.e. "[my] var" means "true").
1373 */
1374int config_error_nonbool(const char *var)
1375{
1376        return error("Missing value for '%s'", var);
1377}