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