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