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