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