1#include "cache.h" 2#include "refs.h" 3#include "object.h" 4#include "tag.h" 5#include "dir.h" 6#include "string-list.h" 7 8/* 9 * How to handle various characters in refnames: 10 * 0: An acceptable character for refs 11 * 1: End-of-component 12 * 2: ., look for a preceding . to reject .. in refs 13 * 3: {, look for a preceding @ to reject @{ in refs 14 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 15 */ 16static unsigned char refname_disposition[256] = { 17 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 18 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 19 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 1, 20 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 4, 21 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 4, 0, 23 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 4 25}; 26 27/* 28 * Used as a flag to ref_transaction_delete when a loose ref is being 29 * pruned. 30 */ 31#define REF_ISPRUNING 0x0100 32/* 33 * Try to read one refname component from the front of refname. 34 * Return the length of the component found, or -1 if the component is 35 * not legal. It is legal if it is something reasonable to have under 36 * ".git/refs/"; We do not like it if: 37 * 38 * - any path component of it begins with ".", or 39 * - it has double dots "..", or 40 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 41 * - it ends with a "/". 42 * - it ends with ".lock" 43 * - it contains a "\" (backslash) 44 */ 45static int check_refname_component(const char *refname, int flags) 46{ 47 const char *cp; 48 char last = '\0'; 49 50 for (cp = refname; ; cp++) { 51 int ch = *cp & 255; 52 unsigned char disp = refname_disposition[ch]; 53 switch (disp) { 54 case 1: 55 goto out; 56 case 2: 57 if (last == '.') 58 return -1; /* Refname contains "..". */ 59 break; 60 case 3: 61 if (last == '@') 62 return -1; /* Refname contains "@{". */ 63 break; 64 case 4: 65 return -1; 66 } 67 last = ch; 68 } 69out: 70 if (cp == refname) 71 return 0; /* Component has zero length. */ 72 if (refname[0] == '.') { 73 if (!(flags & REFNAME_DOT_COMPONENT)) 74 return -1; /* Component starts with '.'. */ 75 /* 76 * Even if leading dots are allowed, don't allow "." 77 * as a component (".." is prevented by a rule above). 78 */ 79 if (refname[1] == '\0') 80 return -1; /* Component equals ".". */ 81 } 82 if (cp - refname >= LOCK_SUFFIX_LEN && 83 !memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 84 return -1; /* Refname ends with ".lock". */ 85 return cp - refname; 86} 87 88int check_refname_format(const char *refname, int flags) 89{ 90 int component_len, component_count = 0; 91 92 if (!strcmp(refname, "@")) 93 /* Refname is a single character '@'. */ 94 return -1; 95 96 while (1) { 97 /* We are at the start of a path component. */ 98 component_len = check_refname_component(refname, flags); 99 if (component_len <= 0) { 100 if ((flags & REFNAME_REFSPEC_PATTERN) && 101 refname[0] == '*' && 102 (refname[1] == '\0' || refname[1] == '/')) { 103 /* Accept one wildcard as a full refname component. */ 104 flags &= ~REFNAME_REFSPEC_PATTERN; 105 component_len = 1; 106 } else { 107 return -1; 108 } 109 } 110 component_count++; 111 if (refname[component_len] == '\0') 112 break; 113 /* Skip to next component. */ 114 refname += component_len + 1; 115 } 116 117 if (refname[component_len - 1] == '.') 118 return -1; /* Refname ends with '.'. */ 119 if (!(flags & REFNAME_ALLOW_ONELEVEL) && component_count < 2) 120 return -1; /* Refname has only one component. */ 121 return 0; 122} 123 124struct ref_entry; 125 126/* 127 * Information used (along with the information in ref_entry) to 128 * describe a single cached reference. This data structure only 129 * occurs embedded in a union in struct ref_entry, and only when 130 * (ref_entry->flag & REF_DIR) is zero. 131 */ 132struct ref_value { 133 /* 134 * The name of the object to which this reference resolves 135 * (which may be a tag object). If REF_ISBROKEN, this is 136 * null. If REF_ISSYMREF, then this is the name of the object 137 * referred to by the last reference in the symlink chain. 138 */ 139 unsigned char sha1[20]; 140 141 /* 142 * If REF_KNOWS_PEELED, then this field holds the peeled value 143 * of this reference, or null if the reference is known not to 144 * be peelable. See the documentation for peel_ref() for an 145 * exact definition of "peelable". 146 */ 147 unsigned char peeled[20]; 148}; 149 150struct ref_cache; 151 152/* 153 * Information used (along with the information in ref_entry) to 154 * describe a level in the hierarchy of references. This data 155 * structure only occurs embedded in a union in struct ref_entry, and 156 * only when (ref_entry.flag & REF_DIR) is set. In that case, 157 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 158 * in the directory have already been read: 159 * 160 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 161 * or packed references, already read. 162 * 163 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 164 * references that hasn't been read yet (nor has any of its 165 * subdirectories). 166 * 167 * Entries within a directory are stored within a growable array of 168 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 169 * sorted are sorted by their component name in strcmp() order and the 170 * remaining entries are unsorted. 171 * 172 * Loose references are read lazily, one directory at a time. When a 173 * directory of loose references is read, then all of the references 174 * in that directory are stored, and REF_INCOMPLETE stubs are created 175 * for any subdirectories, but the subdirectories themselves are not 176 * read. The reading is triggered by get_ref_dir(). 177 */ 178struct ref_dir { 179 int nr, alloc; 180 181 /* 182 * Entries with index 0 <= i < sorted are sorted by name. New 183 * entries are appended to the list unsorted, and are sorted 184 * only when required; thus we avoid the need to sort the list 185 * after the addition of every reference. 186 */ 187 int sorted; 188 189 /* A pointer to the ref_cache that contains this ref_dir. */ 190 struct ref_cache *ref_cache; 191 192 struct ref_entry **entries; 193}; 194 195/* 196 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 197 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see 198 * refs.h. 199 */ 200 201/* 202 * The field ref_entry->u.value.peeled of this value entry contains 203 * the correct peeled value for the reference, which might be 204 * null_sha1 if the reference is not a tag or if it is broken. 205 */ 206#define REF_KNOWS_PEELED 0x08 207 208/* ref_entry represents a directory of references */ 209#define REF_DIR 0x10 210 211/* 212 * Entry has not yet been read from disk (used only for REF_DIR 213 * entries representing loose references) 214 */ 215#define REF_INCOMPLETE 0x20 216 217/* 218 * A ref_entry represents either a reference or a "subdirectory" of 219 * references. 220 * 221 * Each directory in the reference namespace is represented by a 222 * ref_entry with (flags & REF_DIR) set and containing a subdir member 223 * that holds the entries in that directory that have been read so 224 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 225 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 226 * used for loose reference directories. 227 * 228 * References are represented by a ref_entry with (flags & REF_DIR) 229 * unset and a value member that describes the reference's value. The 230 * flag member is at the ref_entry level, but it is also needed to 231 * interpret the contents of the value field (in other words, a 232 * ref_value object is not very much use without the enclosing 233 * ref_entry). 234 * 235 * Reference names cannot end with slash and directories' names are 236 * always stored with a trailing slash (except for the top-level 237 * directory, which is always denoted by ""). This has two nice 238 * consequences: (1) when the entries in each subdir are sorted 239 * lexicographically by name (as they usually are), the references in 240 * a whole tree can be generated in lexicographic order by traversing 241 * the tree in left-to-right, depth-first order; (2) the names of 242 * references and subdirectories cannot conflict, and therefore the 243 * presence of an empty subdirectory does not block the creation of a 244 * similarly-named reference. (The fact that reference names with the 245 * same leading components can conflict *with each other* is a 246 * separate issue that is regulated by is_refname_available().) 247 * 248 * Please note that the name field contains the fully-qualified 249 * reference (or subdirectory) name. Space could be saved by only 250 * storing the relative names. But that would require the full names 251 * to be generated on the fly when iterating in do_for_each_ref(), and 252 * would break callback functions, who have always been able to assume 253 * that the name strings that they are passed will not be freed during 254 * the iteration. 255 */ 256struct ref_entry { 257 unsigned char flag; /* ISSYMREF? ISPACKED? */ 258 union { 259 struct ref_value value; /* if not (flags&REF_DIR) */ 260 struct ref_dir subdir; /* if (flags&REF_DIR) */ 261 } u; 262 /* 263 * The full name of the reference (e.g., "refs/heads/master") 264 * or the full name of the directory with a trailing slash 265 * (e.g., "refs/heads/"): 266 */ 267 char name[FLEX_ARRAY]; 268}; 269 270static void read_loose_refs(const char *dirname, struct ref_dir *dir); 271 272static struct ref_dir *get_ref_dir(struct ref_entry *entry) 273{ 274 struct ref_dir *dir; 275 assert(entry->flag & REF_DIR); 276 dir = &entry->u.subdir; 277 if (entry->flag & REF_INCOMPLETE) { 278 read_loose_refs(entry->name, dir); 279 entry->flag &= ~REF_INCOMPLETE; 280 } 281 return dir; 282} 283 284static struct ref_entry *create_ref_entry(const char *refname, 285 const unsigned char *sha1, int flag, 286 int check_name) 287{ 288 int len; 289 struct ref_entry *ref; 290 291 if (check_name && 292 check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) 293 die("Reference has invalid format: '%s'", refname); 294 len = strlen(refname) + 1; 295 ref = xmalloc(sizeof(struct ref_entry) + len); 296 hashcpy(ref->u.value.sha1, sha1); 297 hashclr(ref->u.value.peeled); 298 memcpy(ref->name, refname, len); 299 ref->flag = flag; 300 return ref; 301} 302 303static void clear_ref_dir(struct ref_dir *dir); 304 305static void free_ref_entry(struct ref_entry *entry) 306{ 307 if (entry->flag & REF_DIR) { 308 /* 309 * Do not use get_ref_dir() here, as that might 310 * trigger the reading of loose refs. 311 */ 312 clear_ref_dir(&entry->u.subdir); 313 } 314 free(entry); 315} 316 317/* 318 * Add a ref_entry to the end of dir (unsorted). Entry is always 319 * stored directly in dir; no recursion into subdirectories is 320 * done. 321 */ 322static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry) 323{ 324 ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc); 325 dir->entries[dir->nr++] = entry; 326 /* optimize for the case that entries are added in order */ 327 if (dir->nr == 1 || 328 (dir->nr == dir->sorted + 1 && 329 strcmp(dir->entries[dir->nr - 2]->name, 330 dir->entries[dir->nr - 1]->name) < 0)) 331 dir->sorted = dir->nr; 332} 333 334/* 335 * Clear and free all entries in dir, recursively. 336 */ 337static void clear_ref_dir(struct ref_dir *dir) 338{ 339 int i; 340 for (i = 0; i < dir->nr; i++) 341 free_ref_entry(dir->entries[i]); 342 free(dir->entries); 343 dir->sorted = dir->nr = dir->alloc = 0; 344 dir->entries = NULL; 345} 346 347/* 348 * Create a struct ref_entry object for the specified dirname. 349 * dirname is the name of the directory with a trailing slash (e.g., 350 * "refs/heads/") or "" for the top-level directory. 351 */ 352static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 353 const char *dirname, size_t len, 354 int incomplete) 355{ 356 struct ref_entry *direntry; 357 direntry = xcalloc(1, sizeof(struct ref_entry) + len + 1); 358 memcpy(direntry->name, dirname, len); 359 direntry->name[len] = '\0'; 360 direntry->u.subdir.ref_cache = ref_cache; 361 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0); 362 return direntry; 363} 364 365static int ref_entry_cmp(const void *a, const void *b) 366{ 367 struct ref_entry *one = *(struct ref_entry **)a; 368 struct ref_entry *two = *(struct ref_entry **)b; 369 return strcmp(one->name, two->name); 370} 371 372static void sort_ref_dir(struct ref_dir *dir); 373 374struct string_slice { 375 size_t len; 376 const char *str; 377}; 378 379static int ref_entry_cmp_sslice(const void *key_, const void *ent_) 380{ 381 const struct string_slice *key = key_; 382 const struct ref_entry *ent = *(const struct ref_entry * const *)ent_; 383 int cmp = strncmp(key->str, ent->name, key->len); 384 if (cmp) 385 return cmp; 386 return '\0' - (unsigned char)ent->name[key->len]; 387} 388 389/* 390 * Return the index of the entry with the given refname from the 391 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 392 * no such entry is found. dir must already be complete. 393 */ 394static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len) 395{ 396 struct ref_entry **r; 397 struct string_slice key; 398 399 if (refname == NULL || !dir->nr) 400 return -1; 401 402 sort_ref_dir(dir); 403 key.len = len; 404 key.str = refname; 405 r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries), 406 ref_entry_cmp_sslice); 407 408 if (r == NULL) 409 return -1; 410 411 return r - dir->entries; 412} 413 414/* 415 * Search for a directory entry directly within dir (without 416 * recursing). Sort dir if necessary. subdirname must be a directory 417 * name (i.e., end in '/'). If mkdir is set, then create the 418 * directory if it is missing; otherwise, return NULL if the desired 419 * directory cannot be found. dir must already be complete. 420 */ 421static struct ref_dir *search_for_subdir(struct ref_dir *dir, 422 const char *subdirname, size_t len, 423 int mkdir) 424{ 425 int entry_index = search_ref_dir(dir, subdirname, len); 426 struct ref_entry *entry; 427 if (entry_index == -1) { 428 if (!mkdir) 429 return NULL; 430 /* 431 * Since dir is complete, the absence of a subdir 432 * means that the subdir really doesn't exist; 433 * therefore, create an empty record for it but mark 434 * the record complete. 435 */ 436 entry = create_dir_entry(dir->ref_cache, subdirname, len, 0); 437 add_entry_to_dir(dir, entry); 438 } else { 439 entry = dir->entries[entry_index]; 440 } 441 return get_ref_dir(entry); 442} 443 444/* 445 * If refname is a reference name, find the ref_dir within the dir 446 * tree that should hold refname. If refname is a directory name 447 * (i.e., ends in '/'), then return that ref_dir itself. dir must 448 * represent the top-level directory and must already be complete. 449 * Sort ref_dirs and recurse into subdirectories as necessary. If 450 * mkdir is set, then create any missing directories; otherwise, 451 * return NULL if the desired directory cannot be found. 452 */ 453static struct ref_dir *find_containing_dir(struct ref_dir *dir, 454 const char *refname, int mkdir) 455{ 456 const char *slash; 457 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) { 458 size_t dirnamelen = slash - refname + 1; 459 struct ref_dir *subdir; 460 subdir = search_for_subdir(dir, refname, dirnamelen, mkdir); 461 if (!subdir) { 462 dir = NULL; 463 break; 464 } 465 dir = subdir; 466 } 467 468 return dir; 469} 470 471/* 472 * Find the value entry with the given name in dir, sorting ref_dirs 473 * and recursing into subdirectories as necessary. If the name is not 474 * found or it corresponds to a directory entry, return NULL. 475 */ 476static struct ref_entry *find_ref(struct ref_dir *dir, const char *refname) 477{ 478 int entry_index; 479 struct ref_entry *entry; 480 dir = find_containing_dir(dir, refname, 0); 481 if (!dir) 482 return NULL; 483 entry_index = search_ref_dir(dir, refname, strlen(refname)); 484 if (entry_index == -1) 485 return NULL; 486 entry = dir->entries[entry_index]; 487 return (entry->flag & REF_DIR) ? NULL : entry; 488} 489 490/* 491 * Remove the entry with the given name from dir, recursing into 492 * subdirectories as necessary. If refname is the name of a directory 493 * (i.e., ends with '/'), then remove the directory and its contents. 494 * If the removal was successful, return the number of entries 495 * remaining in the directory entry that contained the deleted entry. 496 * If the name was not found, return -1. Please note that this 497 * function only deletes the entry from the cache; it does not delete 498 * it from the filesystem or ensure that other cache entries (which 499 * might be symbolic references to the removed entry) are updated. 500 * Nor does it remove any containing dir entries that might be made 501 * empty by the removal. dir must represent the top-level directory 502 * and must already be complete. 503 */ 504static int remove_entry(struct ref_dir *dir, const char *refname) 505{ 506 int refname_len = strlen(refname); 507 int entry_index; 508 struct ref_entry *entry; 509 int is_dir = refname[refname_len - 1] == '/'; 510 if (is_dir) { 511 /* 512 * refname represents a reference directory. Remove 513 * the trailing slash; otherwise we will get the 514 * directory *representing* refname rather than the 515 * one *containing* it. 516 */ 517 char *dirname = xmemdupz(refname, refname_len - 1); 518 dir = find_containing_dir(dir, dirname, 0); 519 free(dirname); 520 } else { 521 dir = find_containing_dir(dir, refname, 0); 522 } 523 if (!dir) 524 return -1; 525 entry_index = search_ref_dir(dir, refname, refname_len); 526 if (entry_index == -1) 527 return -1; 528 entry = dir->entries[entry_index]; 529 530 memmove(&dir->entries[entry_index], 531 &dir->entries[entry_index + 1], 532 (dir->nr - entry_index - 1) * sizeof(*dir->entries) 533 ); 534 dir->nr--; 535 if (dir->sorted > entry_index) 536 dir->sorted--; 537 free_ref_entry(entry); 538 return dir->nr; 539} 540 541/* 542 * Add a ref_entry to the ref_dir (unsorted), recursing into 543 * subdirectories as necessary. dir must represent the top-level 544 * directory. Return 0 on success. 545 */ 546static int add_ref(struct ref_dir *dir, struct ref_entry *ref) 547{ 548 dir = find_containing_dir(dir, ref->name, 1); 549 if (!dir) 550 return -1; 551 add_entry_to_dir(dir, ref); 552 return 0; 553} 554 555/* 556 * Emit a warning and return true iff ref1 and ref2 have the same name 557 * and the same sha1. Die if they have the same name but different 558 * sha1s. 559 */ 560static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2) 561{ 562 if (strcmp(ref1->name, ref2->name)) 563 return 0; 564 565 /* Duplicate name; make sure that they don't conflict: */ 566 567 if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 568 /* This is impossible by construction */ 569 die("Reference directory conflict: %s", ref1->name); 570 571 if (hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 572 die("Duplicated ref, and SHA1s don't match: %s", ref1->name); 573 574 warning("Duplicated ref: %s", ref1->name); 575 return 1; 576} 577 578/* 579 * Sort the entries in dir non-recursively (if they are not already 580 * sorted) and remove any duplicate entries. 581 */ 582static void sort_ref_dir(struct ref_dir *dir) 583{ 584 int i, j; 585 struct ref_entry *last = NULL; 586 587 /* 588 * This check also prevents passing a zero-length array to qsort(), 589 * which is a problem on some platforms. 590 */ 591 if (dir->sorted == dir->nr) 592 return; 593 594 qsort(dir->entries, dir->nr, sizeof(*dir->entries), ref_entry_cmp); 595 596 /* Remove any duplicates: */ 597 for (i = 0, j = 0; j < dir->nr; j++) { 598 struct ref_entry *entry = dir->entries[j]; 599 if (last && is_dup_ref(last, entry)) 600 free_ref_entry(entry); 601 else 602 last = dir->entries[i++] = entry; 603 } 604 dir->sorted = dir->nr = i; 605} 606 607/* Include broken references in a do_for_each_ref*() iteration: */ 608#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 609 610/* 611 * Return true iff the reference described by entry can be resolved to 612 * an object in the database. Emit a warning if the referred-to 613 * object does not exist. 614 */ 615static int ref_resolves_to_object(struct ref_entry *entry) 616{ 617 if (entry->flag & REF_ISBROKEN) 618 return 0; 619 if (!has_sha1_file(entry->u.value.sha1)) { 620 error("%s does not point to a valid object!", entry->name); 621 return 0; 622 } 623 return 1; 624} 625 626/* 627 * current_ref is a performance hack: when iterating over references 628 * using the for_each_ref*() functions, current_ref is set to the 629 * current reference's entry before calling the callback function. If 630 * the callback function calls peel_ref(), then peel_ref() first 631 * checks whether the reference to be peeled is the current reference 632 * (it usually is) and if so, returns that reference's peeled version 633 * if it is available. This avoids a refname lookup in a common case. 634 */ 635static struct ref_entry *current_ref; 636 637typedef int each_ref_entry_fn(struct ref_entry *entry, void *cb_data); 638 639struct ref_entry_cb { 640 const char *base; 641 int trim; 642 int flags; 643 each_ref_fn *fn; 644 void *cb_data; 645}; 646 647/* 648 * Handle one reference in a do_for_each_ref*()-style iteration, 649 * calling an each_ref_fn for each entry. 650 */ 651static int do_one_ref(struct ref_entry *entry, void *cb_data) 652{ 653 struct ref_entry_cb *data = cb_data; 654 struct ref_entry *old_current_ref; 655 int retval; 656 657 if (!starts_with(entry->name, data->base)) 658 return 0; 659 660 if (!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 661 !ref_resolves_to_object(entry)) 662 return 0; 663 664 /* Store the old value, in case this is a recursive call: */ 665 old_current_ref = current_ref; 666 current_ref = entry; 667 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 668 entry->flag, data->cb_data); 669 current_ref = old_current_ref; 670 return retval; 671} 672 673/* 674 * Call fn for each reference in dir that has index in the range 675 * offset <= index < dir->nr. Recurse into subdirectories that are in 676 * that index range, sorting them before iterating. This function 677 * does not sort dir itself; it should be sorted beforehand. fn is 678 * called for all references, including broken ones. 679 */ 680static int do_for_each_entry_in_dir(struct ref_dir *dir, int offset, 681 each_ref_entry_fn fn, void *cb_data) 682{ 683 int i; 684 assert(dir->sorted == dir->nr); 685 for (i = offset; i < dir->nr; i++) { 686 struct ref_entry *entry = dir->entries[i]; 687 int retval; 688 if (entry->flag & REF_DIR) { 689 struct ref_dir *subdir = get_ref_dir(entry); 690 sort_ref_dir(subdir); 691 retval = do_for_each_entry_in_dir(subdir, 0, fn, cb_data); 692 } else { 693 retval = fn(entry, cb_data); 694 } 695 if (retval) 696 return retval; 697 } 698 return 0; 699} 700 701/* 702 * Call fn for each reference in the union of dir1 and dir2, in order 703 * by refname. Recurse into subdirectories. If a value entry appears 704 * in both dir1 and dir2, then only process the version that is in 705 * dir2. The input dirs must already be sorted, but subdirs will be 706 * sorted as needed. fn is called for all references, including 707 * broken ones. 708 */ 709static int do_for_each_entry_in_dirs(struct ref_dir *dir1, 710 struct ref_dir *dir2, 711 each_ref_entry_fn fn, void *cb_data) 712{ 713 int retval; 714 int i1 = 0, i2 = 0; 715 716 assert(dir1->sorted == dir1->nr); 717 assert(dir2->sorted == dir2->nr); 718 while (1) { 719 struct ref_entry *e1, *e2; 720 int cmp; 721 if (i1 == dir1->nr) { 722 return do_for_each_entry_in_dir(dir2, i2, fn, cb_data); 723 } 724 if (i2 == dir2->nr) { 725 return do_for_each_entry_in_dir(dir1, i1, fn, cb_data); 726 } 727 e1 = dir1->entries[i1]; 728 e2 = dir2->entries[i2]; 729 cmp = strcmp(e1->name, e2->name); 730 if (cmp == 0) { 731 if ((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 732 /* Both are directories; descend them in parallel. */ 733 struct ref_dir *subdir1 = get_ref_dir(e1); 734 struct ref_dir *subdir2 = get_ref_dir(e2); 735 sort_ref_dir(subdir1); 736 sort_ref_dir(subdir2); 737 retval = do_for_each_entry_in_dirs( 738 subdir1, subdir2, fn, cb_data); 739 i1++; 740 i2++; 741 } else if (!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 742 /* Both are references; ignore the one from dir1. */ 743 retval = fn(e2, cb_data); 744 i1++; 745 i2++; 746 } else { 747 die("conflict between reference and directory: %s", 748 e1->name); 749 } 750 } else { 751 struct ref_entry *e; 752 if (cmp < 0) { 753 e = e1; 754 i1++; 755 } else { 756 e = e2; 757 i2++; 758 } 759 if (e->flag & REF_DIR) { 760 struct ref_dir *subdir = get_ref_dir(e); 761 sort_ref_dir(subdir); 762 retval = do_for_each_entry_in_dir( 763 subdir, 0, fn, cb_data); 764 } else { 765 retval = fn(e, cb_data); 766 } 767 } 768 if (retval) 769 return retval; 770 } 771} 772 773/* 774 * Load all of the refs from the dir into our in-memory cache. The hard work 775 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 776 * through all of the sub-directories. We do not even need to care about 777 * sorting, as traversal order does not matter to us. 778 */ 779static void prime_ref_dir(struct ref_dir *dir) 780{ 781 int i; 782 for (i = 0; i < dir->nr; i++) { 783 struct ref_entry *entry = dir->entries[i]; 784 if (entry->flag & REF_DIR) 785 prime_ref_dir(get_ref_dir(entry)); 786 } 787} 788 789static int entry_matches(struct ref_entry *entry, const char *refname) 790{ 791 return refname && !strcmp(entry->name, refname); 792} 793 794struct nonmatching_ref_data { 795 const char *skip; 796 struct ref_entry *found; 797}; 798 799static int nonmatching_ref_fn(struct ref_entry *entry, void *vdata) 800{ 801 struct nonmatching_ref_data *data = vdata; 802 803 if (entry_matches(entry, data->skip)) 804 return 0; 805 806 data->found = entry; 807 return 1; 808} 809 810static void report_refname_conflict(struct ref_entry *entry, 811 const char *refname) 812{ 813 error("'%s' exists; cannot create '%s'", entry->name, refname); 814} 815 816/* 817 * Return true iff a reference named refname could be created without 818 * conflicting with the name of an existing reference in dir. If 819 * oldrefname is non-NULL, ignore potential conflicts with oldrefname 820 * (e.g., because oldrefname is scheduled for deletion in the same 821 * operation). 822 * 823 * Two reference names conflict if one of them exactly matches the 824 * leading components of the other; e.g., "foo/bar" conflicts with 825 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 826 * "foo/barbados". 827 */ 828static int is_refname_available(const char *refname, const char *oldrefname, 829 struct ref_dir *dir) 830{ 831 const char *slash; 832 size_t len; 833 int pos; 834 char *dirname; 835 836 for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) { 837 /* 838 * We are still at a leading dir of the refname; we are 839 * looking for a conflict with a leaf entry. 840 * 841 * If we find one, we still must make sure it is 842 * not "oldrefname". 843 */ 844 pos = search_ref_dir(dir, refname, slash - refname); 845 if (pos >= 0) { 846 struct ref_entry *entry = dir->entries[pos]; 847 if (entry_matches(entry, oldrefname)) 848 return 1; 849 report_refname_conflict(entry, refname); 850 return 0; 851 } 852 853 854 /* 855 * Otherwise, we can try to continue our search with 856 * the next component; if we come up empty, we know 857 * there is nothing under this whole prefix. 858 */ 859 pos = search_ref_dir(dir, refname, slash + 1 - refname); 860 if (pos < 0) 861 return 1; 862 863 dir = get_ref_dir(dir->entries[pos]); 864 } 865 866 /* 867 * We are at the leaf of our refname; we want to 868 * make sure there are no directories which match it. 869 */ 870 len = strlen(refname); 871 dirname = xmallocz(len + 1); 872 sprintf(dirname, "%s/", refname); 873 pos = search_ref_dir(dir, dirname, len + 1); 874 free(dirname); 875 876 if (pos >= 0) { 877 /* 878 * We found a directory named "refname". It is a 879 * problem iff it contains any ref that is not 880 * "oldrefname". 881 */ 882 struct ref_entry *entry = dir->entries[pos]; 883 struct ref_dir *dir = get_ref_dir(entry); 884 struct nonmatching_ref_data data; 885 886 data.skip = oldrefname; 887 sort_ref_dir(dir); 888 if (!do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) 889 return 1; 890 891 report_refname_conflict(data.found, refname); 892 return 0; 893 } 894 895 /* 896 * There is no point in searching for another leaf 897 * node which matches it; such an entry would be the 898 * ref we are looking for, not a conflict. 899 */ 900 return 1; 901} 902 903struct packed_ref_cache { 904 struct ref_entry *root; 905 906 /* 907 * Count of references to the data structure in this instance, 908 * including the pointer from ref_cache::packed if any. The 909 * data will not be freed as long as the reference count is 910 * nonzero. 911 */ 912 unsigned int referrers; 913 914 /* 915 * Iff the packed-refs file associated with this instance is 916 * currently locked for writing, this points at the associated 917 * lock (which is owned by somebody else). The referrer count 918 * is also incremented when the file is locked and decremented 919 * when it is unlocked. 920 */ 921 struct lock_file *lock; 922 923 /* The metadata from when this packed-refs cache was read */ 924 struct stat_validity validity; 925}; 926 927/* 928 * Future: need to be in "struct repository" 929 * when doing a full libification. 930 */ 931static struct ref_cache { 932 struct ref_cache *next; 933 struct ref_entry *loose; 934 struct packed_ref_cache *packed; 935 /* 936 * The submodule name, or "" for the main repo. We allocate 937 * length 1 rather than FLEX_ARRAY so that the main ref_cache 938 * is initialized correctly. 939 */ 940 char name[1]; 941} ref_cache, *submodule_ref_caches; 942 943/* Lock used for the main packed-refs file: */ 944static struct lock_file packlock; 945 946/* 947 * Increment the reference count of *packed_refs. 948 */ 949static void acquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 950{ 951 packed_refs->referrers++; 952} 953 954/* 955 * Decrease the reference count of *packed_refs. If it goes to zero, 956 * free *packed_refs and return true; otherwise return false. 957 */ 958static int release_packed_ref_cache(struct packed_ref_cache *packed_refs) 959{ 960 if (!--packed_refs->referrers) { 961 free_ref_entry(packed_refs->root); 962 stat_validity_clear(&packed_refs->validity); 963 free(packed_refs); 964 return 1; 965 } else { 966 return 0; 967 } 968} 969 970static void clear_packed_ref_cache(struct ref_cache *refs) 971{ 972 if (refs->packed) { 973 struct packed_ref_cache *packed_refs = refs->packed; 974 975 if (packed_refs->lock) 976 die("internal error: packed-ref cache cleared while locked"); 977 refs->packed = NULL; 978 release_packed_ref_cache(packed_refs); 979 } 980} 981 982static void clear_loose_ref_cache(struct ref_cache *refs) 983{ 984 if (refs->loose) { 985 free_ref_entry(refs->loose); 986 refs->loose = NULL; 987 } 988} 989 990static struct ref_cache *create_ref_cache(const char *submodule) 991{ 992 int len; 993 struct ref_cache *refs; 994 if (!submodule) 995 submodule = ""; 996 len = strlen(submodule) + 1; 997 refs = xcalloc(1, sizeof(struct ref_cache) + len); 998 memcpy(refs->name, submodule, len); 999 return refs;1000}10011002/*1003 * Return a pointer to a ref_cache for the specified submodule. For1004 * the main repository, use submodule==NULL. The returned structure1005 * will be allocated and initialized but not necessarily populated; it1006 * should not be freed.1007 */1008static struct ref_cache *get_ref_cache(const char *submodule)1009{1010 struct ref_cache *refs;10111012 if (!submodule || !*submodule)1013 return &ref_cache;10141015 for (refs = submodule_ref_caches; refs; refs = refs->next)1016 if (!strcmp(submodule, refs->name))1017 return refs;10181019 refs = create_ref_cache(submodule);1020 refs->next = submodule_ref_caches;1021 submodule_ref_caches = refs;1022 return refs;1023}10241025/* The length of a peeled reference line in packed-refs, including EOL: */1026#define PEELED_LINE_LENGTH 4210271028/*1029 * The packed-refs header line that we write out. Perhaps other1030 * traits will be added later. The trailing space is required.1031 */1032static const char PACKED_REFS_HEADER[] =1033 "# pack-refs with: peeled fully-peeled \n";10341035/*1036 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1037 * Return a pointer to the refname within the line (null-terminated),1038 * or NULL if there was a problem.1039 */1040static const char *parse_ref_line(char *line, unsigned char *sha1)1041{1042 /*1043 * 42: the answer to everything.1044 *1045 * In this case, it happens to be the answer to1046 * 40 (length of sha1 hex representation)1047 * +1 (space in between hex and name)1048 * +1 (newline at the end of the line)1049 */1050 int len = strlen(line) - 42;10511052 if (len <= 0)1053 return NULL;1054 if (get_sha1_hex(line, sha1) < 0)1055 return NULL;1056 if (!isspace(line[40]))1057 return NULL;1058 line += 41;1059 if (isspace(*line))1060 return NULL;1061 if (line[len] != '\n')1062 return NULL;1063 line[len] = 0;10641065 return line;1066}10671068/*1069 * Read f, which is a packed-refs file, into dir.1070 *1071 * A comment line of the form "# pack-refs with: " may contain zero or1072 * more traits. We interpret the traits as follows:1073 *1074 * No traits:1075 *1076 * Probably no references are peeled. But if the file contains a1077 * peeled value for a reference, we will use it.1078 *1079 * peeled:1080 *1081 * References under "refs/tags/", if they *can* be peeled, *are*1082 * peeled in this file. References outside of "refs/tags/" are1083 * probably not peeled even if they could have been, but if we find1084 * a peeled value for such a reference we will use it.1085 *1086 * fully-peeled:1087 *1088 * All references in the file that can be peeled are peeled.1089 * Inversely (and this is more important), any references in the1090 * file for which no peeled value is recorded is not peelable. This1091 * trait should typically be written alongside "peeled" for1092 * compatibility with older clients, but we do not require it1093 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1094 */1095static void read_packed_refs(FILE *f, struct ref_dir *dir)1096{1097 struct ref_entry *last = NULL;1098 char refline[PATH_MAX];1099 enum { PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11001101 while (fgets(refline, sizeof(refline), f)) {1102 unsigned char sha1[20];1103 const char *refname;1104 static const char header[] = "# pack-refs with:";11051106 if (!strncmp(refline, header, sizeof(header)-1)) {1107 const char *traits = refline + sizeof(header) - 1;1108 if (strstr(traits, " fully-peeled "))1109 peeled = PEELED_FULLY;1110 else if (strstr(traits, " peeled "))1111 peeled = PEELED_TAGS;1112 /* perhaps other traits later as well */1113 continue;1114 }11151116 refname = parse_ref_line(refline, sha1);1117 if (refname) {1118 last = create_ref_entry(refname, sha1, REF_ISPACKED, 1);1119 if (peeled == PEELED_FULLY ||1120 (peeled == PEELED_TAGS && starts_with(refname, "refs/tags/")))1121 last->flag |= REF_KNOWS_PEELED;1122 add_ref(dir, last);1123 continue;1124 }1125 if (last &&1126 refline[0] == '^' &&1127 strlen(refline) == PEELED_LINE_LENGTH &&1128 refline[PEELED_LINE_LENGTH - 1] == '\n' &&1129 !get_sha1_hex(refline + 1, sha1)) {1130 hashcpy(last->u.value.peeled, sha1);1131 /*1132 * Regardless of what the file header said,1133 * we definitely know the value of *this*1134 * reference:1135 */1136 last->flag |= REF_KNOWS_PEELED;1137 }1138 }1139}11401141/*1142 * Get the packed_ref_cache for the specified ref_cache, creating it1143 * if necessary.1144 */1145static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1146{1147 const char *packed_refs_file;11481149 if (*refs->name)1150 packed_refs_file = git_path_submodule(refs->name, "packed-refs");1151 else1152 packed_refs_file = git_path("packed-refs");11531154 if (refs->packed &&1155 !stat_validity_check(&refs->packed->validity, packed_refs_file))1156 clear_packed_ref_cache(refs);11571158 if (!refs->packed) {1159 FILE *f;11601161 refs->packed = xcalloc(1, sizeof(*refs->packed));1162 acquire_packed_ref_cache(refs->packed);1163 refs->packed->root = create_dir_entry(refs, "", 0, 0);1164 f = fopen(packed_refs_file, "r");1165 if (f) {1166 stat_validity_update(&refs->packed->validity, fileno(f));1167 read_packed_refs(f, get_ref_dir(refs->packed->root));1168 fclose(f);1169 }1170 }1171 return refs->packed;1172}11731174static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1175{1176 return get_ref_dir(packed_ref_cache->root);1177}11781179static struct ref_dir *get_packed_refs(struct ref_cache *refs)1180{1181 return get_packed_ref_dir(get_packed_ref_cache(refs));1182}11831184void add_packed_ref(const char *refname, const unsigned char *sha1)1185{1186 struct packed_ref_cache *packed_ref_cache =1187 get_packed_ref_cache(&ref_cache);11881189 if (!packed_ref_cache->lock)1190 die("internal error: packed refs not locked");1191 add_ref(get_packed_ref_dir(packed_ref_cache),1192 create_ref_entry(refname, sha1, REF_ISPACKED, 1));1193}11941195/*1196 * Read the loose references from the namespace dirname into dir1197 * (without recursing). dirname must end with '/'. dir must be the1198 * directory entry corresponding to dirname.1199 */1200static void read_loose_refs(const char *dirname, struct ref_dir *dir)1201{1202 struct ref_cache *refs = dir->ref_cache;1203 DIR *d;1204 const char *path;1205 struct dirent *de;1206 int dirnamelen = strlen(dirname);1207 struct strbuf refname;12081209 if (*refs->name)1210 path = git_path_submodule(refs->name, "%s", dirname);1211 else1212 path = git_path("%s", dirname);12131214 d = opendir(path);1215 if (!d)1216 return;12171218 strbuf_init(&refname, dirnamelen + 257);1219 strbuf_add(&refname, dirname, dirnamelen);12201221 while ((de = readdir(d)) != NULL) {1222 unsigned char sha1[20];1223 struct stat st;1224 int flag;1225 const char *refdir;12261227 if (de->d_name[0] == '.')1228 continue;1229 if (ends_with(de->d_name, ".lock"))1230 continue;1231 strbuf_addstr(&refname, de->d_name);1232 refdir = *refs->name1233 ? git_path_submodule(refs->name, "%s", refname.buf)1234 : git_path("%s", refname.buf);1235 if (stat(refdir, &st) < 0) {1236 ; /* silently ignore */1237 } else if (S_ISDIR(st.st_mode)) {1238 strbuf_addch(&refname, '/');1239 add_entry_to_dir(dir,1240 create_dir_entry(refs, refname.buf,1241 refname.len, 1));1242 } else {1243 if (*refs->name) {1244 hashclr(sha1);1245 flag = 0;1246 if (resolve_gitlink_ref(refs->name, refname.buf, sha1) < 0) {1247 hashclr(sha1);1248 flag |= REF_ISBROKEN;1249 }1250 } else if (read_ref_full(refname.buf, sha1, 1, &flag)) {1251 hashclr(sha1);1252 flag |= REF_ISBROKEN;1253 }1254 add_entry_to_dir(dir,1255 create_ref_entry(refname.buf, sha1, flag, 1));1256 }1257 strbuf_setlen(&refname, dirnamelen);1258 }1259 strbuf_release(&refname);1260 closedir(d);1261}12621263static struct ref_dir *get_loose_refs(struct ref_cache *refs)1264{1265 if (!refs->loose) {1266 /*1267 * Mark the top-level directory complete because we1268 * are about to read the only subdirectory that can1269 * hold references:1270 */1271 refs->loose = create_dir_entry(refs, "", 0, 0);1272 /*1273 * Create an incomplete entry for "refs/":1274 */1275 add_entry_to_dir(get_ref_dir(refs->loose),1276 create_dir_entry(refs, "refs/", 5, 1));1277 }1278 return get_ref_dir(refs->loose);1279}12801281/* We allow "recursive" symbolic refs. Only within reason, though */1282#define MAXDEPTH 51283#define MAXREFLEN (1024)12841285/*1286 * Called by resolve_gitlink_ref_recursive() after it failed to read1287 * from the loose refs in ref_cache refs. Find <refname> in the1288 * packed-refs file for the submodule.1289 */1290static int resolve_gitlink_packed_ref(struct ref_cache *refs,1291 const char *refname, unsigned char *sha1)1292{1293 struct ref_entry *ref;1294 struct ref_dir *dir = get_packed_refs(refs);12951296 ref = find_ref(dir, refname);1297 if (ref == NULL)1298 return -1;12991300 hashcpy(sha1, ref->u.value.sha1);1301 return 0;1302}13031304static int resolve_gitlink_ref_recursive(struct ref_cache *refs,1305 const char *refname, unsigned char *sha1,1306 int recursion)1307{1308 int fd, len;1309 char buffer[128], *p;1310 char *path;13111312 if (recursion > MAXDEPTH || strlen(refname) > MAXREFLEN)1313 return -1;1314 path = *refs->name1315 ? git_path_submodule(refs->name, "%s", refname)1316 : git_path("%s", refname);1317 fd = open(path, O_RDONLY);1318 if (fd < 0)1319 return resolve_gitlink_packed_ref(refs, refname, sha1);13201321 len = read(fd, buffer, sizeof(buffer)-1);1322 close(fd);1323 if (len < 0)1324 return -1;1325 while (len && isspace(buffer[len-1]))1326 len--;1327 buffer[len] = 0;13281329 /* Was it a detached head or an old-fashioned symlink? */1330 if (!get_sha1_hex(buffer, sha1))1331 return 0;13321333 /* Symref? */1334 if (strncmp(buffer, "ref:", 4))1335 return -1;1336 p = buffer + 4;1337 while (isspace(*p))1338 p++;13391340 return resolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1341}13421343int resolve_gitlink_ref(const char *path, const char *refname, unsigned char *sha1)1344{1345 int len = strlen(path), retval;1346 char *submodule;1347 struct ref_cache *refs;13481349 while (len && path[len-1] == '/')1350 len--;1351 if (!len)1352 return -1;1353 submodule = xstrndup(path, len);1354 refs = get_ref_cache(submodule);1355 free(submodule);13561357 retval = resolve_gitlink_ref_recursive(refs, refname, sha1, 0);1358 return retval;1359}13601361/*1362 * Return the ref_entry for the given refname from the packed1363 * references. If it does not exist, return NULL.1364 */1365static struct ref_entry *get_packed_ref(const char *refname)1366{1367 return find_ref(get_packed_refs(&ref_cache), refname);1368}13691370/*1371 * A loose ref file doesn't exist; check for a packed ref. The1372 * options are forwarded from resolve_safe_unsafe().1373 */1374static const char *handle_missing_loose_ref(const char *refname,1375 unsigned char *sha1,1376 int reading,1377 int *flag)1378{1379 struct ref_entry *entry;13801381 /*1382 * The loose reference file does not exist; check for a packed1383 * reference.1384 */1385 entry = get_packed_ref(refname);1386 if (entry) {1387 hashcpy(sha1, entry->u.value.sha1);1388 if (flag)1389 *flag |= REF_ISPACKED;1390 return refname;1391 }1392 /* The reference is not a packed reference, either. */1393 if (reading) {1394 return NULL;1395 } else {1396 hashclr(sha1);1397 return refname;1398 }1399}14001401/* This function needs to return a meaningful errno on failure */1402const char *resolve_ref_unsafe(const char *refname, unsigned char *sha1, int reading, int *flag)1403{1404 int depth = MAXDEPTH;1405 ssize_t len;1406 char buffer[256];1407 static char refname_buffer[256];14081409 if (flag)1410 *flag = 0;14111412 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1413 errno = EINVAL;1414 return NULL;1415 }14161417 for (;;) {1418 char path[PATH_MAX];1419 struct stat st;1420 char *buf;1421 int fd;14221423 if (--depth < 0) {1424 errno = ELOOP;1425 return NULL;1426 }14271428 git_snpath(path, sizeof(path), "%s", refname);14291430 /*1431 * We might have to loop back here to avoid a race1432 * condition: first we lstat() the file, then we try1433 * to read it as a link or as a file. But if somebody1434 * changes the type of the file (file <-> directory1435 * <-> symlink) between the lstat() and reading, then1436 * we don't want to report that as an error but rather1437 * try again starting with the lstat().1438 */1439 stat_ref:1440 if (lstat(path, &st) < 0) {1441 if (errno == ENOENT)1442 return handle_missing_loose_ref(refname, sha1,1443 reading, flag);1444 else1445 return NULL;1446 }14471448 /* Follow "normalized" - ie "refs/.." symlinks by hand */1449 if (S_ISLNK(st.st_mode)) {1450 len = readlink(path, buffer, sizeof(buffer)-1);1451 if (len < 0) {1452 if (errno == ENOENT || errno == EINVAL)1453 /* inconsistent with lstat; retry */1454 goto stat_ref;1455 else1456 return NULL;1457 }1458 buffer[len] = 0;1459 if (starts_with(buffer, "refs/") &&1460 !check_refname_format(buffer, 0)) {1461 strcpy(refname_buffer, buffer);1462 refname = refname_buffer;1463 if (flag)1464 *flag |= REF_ISSYMREF;1465 continue;1466 }1467 }14681469 /* Is it a directory? */1470 if (S_ISDIR(st.st_mode)) {1471 errno = EISDIR;1472 return NULL;1473 }14741475 /*1476 * Anything else, just open it and try to use it as1477 * a ref1478 */1479 fd = open(path, O_RDONLY);1480 if (fd < 0) {1481 if (errno == ENOENT)1482 /* inconsistent with lstat; retry */1483 goto stat_ref;1484 else1485 return NULL;1486 }1487 len = read_in_full(fd, buffer, sizeof(buffer)-1);1488 if (len < 0) {1489 int save_errno = errno;1490 close(fd);1491 errno = save_errno;1492 return NULL;1493 }1494 close(fd);1495 while (len && isspace(buffer[len-1]))1496 len--;1497 buffer[len] = '\0';14981499 /*1500 * Is it a symbolic ref?1501 */1502 if (!starts_with(buffer, "ref:")) {1503 /*1504 * Please note that FETCH_HEAD has a second1505 * line containing other data.1506 */1507 if (get_sha1_hex(buffer, sha1) ||1508 (buffer[40] != '\0' && !isspace(buffer[40]))) {1509 if (flag)1510 *flag |= REF_ISBROKEN;1511 errno = EINVAL;1512 return NULL;1513 }1514 return refname;1515 }1516 if (flag)1517 *flag |= REF_ISSYMREF;1518 buf = buffer + 4;1519 while (isspace(*buf))1520 buf++;1521 if (check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1522 if (flag)1523 *flag |= REF_ISBROKEN;1524 errno = EINVAL;1525 return NULL;1526 }1527 refname = strcpy(refname_buffer, buf);1528 }1529}15301531char *resolve_refdup(const char *ref, unsigned char *sha1, int reading, int *flag)1532{1533 const char *ret = resolve_ref_unsafe(ref, sha1, reading, flag);1534 return ret ? xstrdup(ret) : NULL;1535}15361537/* The argument to filter_refs */1538struct ref_filter {1539 const char *pattern;1540 each_ref_fn *fn;1541 void *cb_data;1542};15431544int read_ref_full(const char *refname, unsigned char *sha1, int reading, int *flags)1545{1546 if (resolve_ref_unsafe(refname, sha1, reading, flags))1547 return 0;1548 return -1;1549}15501551int read_ref(const char *refname, unsigned char *sha1)1552{1553 return read_ref_full(refname, sha1, 1, NULL);1554}15551556int ref_exists(const char *refname)1557{1558 unsigned char sha1[20];1559 return !!resolve_ref_unsafe(refname, sha1, 1, NULL);1560}15611562static int filter_refs(const char *refname, const unsigned char *sha1, int flags,1563 void *data)1564{1565 struct ref_filter *filter = (struct ref_filter *)data;1566 if (wildmatch(filter->pattern, refname, 0, NULL))1567 return 0;1568 return filter->fn(refname, sha1, flags, filter->cb_data);1569}15701571enum peel_status {1572 /* object was peeled successfully: */1573 PEEL_PEELED = 0,15741575 /*1576 * object cannot be peeled because the named object (or an1577 * object referred to by a tag in the peel chain), does not1578 * exist.1579 */1580 PEEL_INVALID = -1,15811582 /* object cannot be peeled because it is not a tag: */1583 PEEL_NON_TAG = -2,15841585 /* ref_entry contains no peeled value because it is a symref: */1586 PEEL_IS_SYMREF = -3,15871588 /*1589 * ref_entry cannot be peeled because it is broken (i.e., the1590 * symbolic reference cannot even be resolved to an object1591 * name):1592 */1593 PEEL_BROKEN = -41594};15951596/*1597 * Peel the named object; i.e., if the object is a tag, resolve the1598 * tag recursively until a non-tag is found. If successful, store the1599 * result to sha1 and return PEEL_PEELED. If the object is not a tag1600 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1601 * and leave sha1 unchanged.1602 */1603static enum peel_status peel_object(const unsigned char *name, unsigned char *sha1)1604{1605 struct object *o = lookup_unknown_object(name);16061607 if (o->type == OBJ_NONE) {1608 int type = sha1_object_info(name, NULL);1609 if (type < 0 || !object_as_type(o, type, 0))1610 return PEEL_INVALID;1611 }16121613 if (o->type != OBJ_TAG)1614 return PEEL_NON_TAG;16151616 o = deref_tag_noverify(o);1617 if (!o)1618 return PEEL_INVALID;16191620 hashcpy(sha1, o->sha1);1621 return PEEL_PEELED;1622}16231624/*1625 * Peel the entry (if possible) and return its new peel_status. If1626 * repeel is true, re-peel the entry even if there is an old peeled1627 * value that is already stored in it.1628 *1629 * It is OK to call this function with a packed reference entry that1630 * might be stale and might even refer to an object that has since1631 * been garbage-collected. In such a case, if the entry has1632 * REF_KNOWS_PEELED then leave the status unchanged and return1633 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1634 */1635static enum peel_status peel_entry(struct ref_entry *entry, int repeel)1636{1637 enum peel_status status;16381639 if (entry->flag & REF_KNOWS_PEELED) {1640 if (repeel) {1641 entry->flag &= ~REF_KNOWS_PEELED;1642 hashclr(entry->u.value.peeled);1643 } else {1644 return is_null_sha1(entry->u.value.peeled) ?1645 PEEL_NON_TAG : PEEL_PEELED;1646 }1647 }1648 if (entry->flag & REF_ISBROKEN)1649 return PEEL_BROKEN;1650 if (entry->flag & REF_ISSYMREF)1651 return PEEL_IS_SYMREF;16521653 status = peel_object(entry->u.value.sha1, entry->u.value.peeled);1654 if (status == PEEL_PEELED || status == PEEL_NON_TAG)1655 entry->flag |= REF_KNOWS_PEELED;1656 return status;1657}16581659int peel_ref(const char *refname, unsigned char *sha1)1660{1661 int flag;1662 unsigned char base[20];16631664 if (current_ref && (current_ref->name == refname1665 || !strcmp(current_ref->name, refname))) {1666 if (peel_entry(current_ref, 0))1667 return -1;1668 hashcpy(sha1, current_ref->u.value.peeled);1669 return 0;1670 }16711672 if (read_ref_full(refname, base, 1, &flag))1673 return -1;16741675 /*1676 * If the reference is packed, read its ref_entry from the1677 * cache in the hope that we already know its peeled value.1678 * We only try this optimization on packed references because1679 * (a) forcing the filling of the loose reference cache could1680 * be expensive and (b) loose references anyway usually do not1681 * have REF_KNOWS_PEELED.1682 */1683 if (flag & REF_ISPACKED) {1684 struct ref_entry *r = get_packed_ref(refname);1685 if (r) {1686 if (peel_entry(r, 0))1687 return -1;1688 hashcpy(sha1, r->u.value.peeled);1689 return 0;1690 }1691 }16921693 return peel_object(base, sha1);1694}16951696struct warn_if_dangling_data {1697 FILE *fp;1698 const char *refname;1699 const struct string_list *refnames;1700 const char *msg_fmt;1701};17021703static int warn_if_dangling_symref(const char *refname, const unsigned char *sha1,1704 int flags, void *cb_data)1705{1706 struct warn_if_dangling_data *d = cb_data;1707 const char *resolves_to;1708 unsigned char junk[20];17091710 if (!(flags & REF_ISSYMREF))1711 return 0;17121713 resolves_to = resolve_ref_unsafe(refname, junk, 0, NULL);1714 if (!resolves_to1715 || (d->refname1716 ? strcmp(resolves_to, d->refname)1717 : !string_list_has_string(d->refnames, resolves_to))) {1718 return 0;1719 }17201721 fprintf(d->fp, d->msg_fmt, refname);1722 fputc('\n', d->fp);1723 return 0;1724}17251726void warn_dangling_symref(FILE *fp, const char *msg_fmt, const char *refname)1727{1728 struct warn_if_dangling_data data;17291730 data.fp = fp;1731 data.refname = refname;1732 data.refnames = NULL;1733 data.msg_fmt = msg_fmt;1734 for_each_rawref(warn_if_dangling_symref, &data);1735}17361737void warn_dangling_symrefs(FILE *fp, const char *msg_fmt, const struct string_list *refnames)1738{1739 struct warn_if_dangling_data data;17401741 data.fp = fp;1742 data.refname = NULL;1743 data.refnames = refnames;1744 data.msg_fmt = msg_fmt;1745 for_each_rawref(warn_if_dangling_symref, &data);1746}17471748/*1749 * Call fn for each reference in the specified ref_cache, omitting1750 * references not in the containing_dir of base. fn is called for all1751 * references, including broken ones. If fn ever returns a non-zero1752 * value, stop the iteration and return that value; otherwise, return1753 * 0.1754 */1755static int do_for_each_entry(struct ref_cache *refs, const char *base,1756 each_ref_entry_fn fn, void *cb_data)1757{1758 struct packed_ref_cache *packed_ref_cache;1759 struct ref_dir *loose_dir;1760 struct ref_dir *packed_dir;1761 int retval = 0;17621763 /*1764 * We must make sure that all loose refs are read before accessing the1765 * packed-refs file; this avoids a race condition in which loose refs1766 * are migrated to the packed-refs file by a simultaneous process, but1767 * our in-memory view is from before the migration. get_packed_ref_cache()1768 * takes care of making sure our view is up to date with what is on1769 * disk.1770 */1771 loose_dir = get_loose_refs(refs);1772 if (base && *base) {1773 loose_dir = find_containing_dir(loose_dir, base, 0);1774 }1775 if (loose_dir)1776 prime_ref_dir(loose_dir);17771778 packed_ref_cache = get_packed_ref_cache(refs);1779 acquire_packed_ref_cache(packed_ref_cache);1780 packed_dir = get_packed_ref_dir(packed_ref_cache);1781 if (base && *base) {1782 packed_dir = find_containing_dir(packed_dir, base, 0);1783 }17841785 if (packed_dir && loose_dir) {1786 sort_ref_dir(packed_dir);1787 sort_ref_dir(loose_dir);1788 retval = do_for_each_entry_in_dirs(1789 packed_dir, loose_dir, fn, cb_data);1790 } else if (packed_dir) {1791 sort_ref_dir(packed_dir);1792 retval = do_for_each_entry_in_dir(1793 packed_dir, 0, fn, cb_data);1794 } else if (loose_dir) {1795 sort_ref_dir(loose_dir);1796 retval = do_for_each_entry_in_dir(1797 loose_dir, 0, fn, cb_data);1798 }17991800 release_packed_ref_cache(packed_ref_cache);1801 return retval;1802}18031804/*1805 * Call fn for each reference in the specified ref_cache for which the1806 * refname begins with base. If trim is non-zero, then trim that many1807 * characters off the beginning of each refname before passing the1808 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1809 * broken references in the iteration. If fn ever returns a non-zero1810 * value, stop the iteration and return that value; otherwise, return1811 * 0.1812 */1813static int do_for_each_ref(struct ref_cache *refs, const char *base,1814 each_ref_fn fn, int trim, int flags, void *cb_data)1815{1816 struct ref_entry_cb data;1817 data.base = base;1818 data.trim = trim;1819 data.flags = flags;1820 data.fn = fn;1821 data.cb_data = cb_data;18221823 return do_for_each_entry(refs, base, do_one_ref, &data);1824}18251826static int do_head_ref(const char *submodule, each_ref_fn fn, void *cb_data)1827{1828 unsigned char sha1[20];1829 int flag;18301831 if (submodule) {1832 if (resolve_gitlink_ref(submodule, "HEAD", sha1) == 0)1833 return fn("HEAD", sha1, 0, cb_data);18341835 return 0;1836 }18371838 if (!read_ref_full("HEAD", sha1, 1, &flag))1839 return fn("HEAD", sha1, flag, cb_data);18401841 return 0;1842}18431844int head_ref(each_ref_fn fn, void *cb_data)1845{1846 return do_head_ref(NULL, fn, cb_data);1847}18481849int head_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)1850{1851 return do_head_ref(submodule, fn, cb_data);1852}18531854int for_each_ref(each_ref_fn fn, void *cb_data)1855{1856 return do_for_each_ref(&ref_cache, "", fn, 0, 0, cb_data);1857}18581859int for_each_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)1860{1861 return do_for_each_ref(get_ref_cache(submodule), "", fn, 0, 0, cb_data);1862}18631864int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)1865{1866 return do_for_each_ref(&ref_cache, prefix, fn, strlen(prefix), 0, cb_data);1867}18681869int for_each_ref_in_submodule(const char *submodule, const char *prefix,1870 each_ref_fn fn, void *cb_data)1871{1872 return do_for_each_ref(get_ref_cache(submodule), prefix, fn, strlen(prefix), 0, cb_data);1873}18741875int for_each_tag_ref(each_ref_fn fn, void *cb_data)1876{1877 return for_each_ref_in("refs/tags/", fn, cb_data);1878}18791880int for_each_tag_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)1881{1882 return for_each_ref_in_submodule(submodule, "refs/tags/", fn, cb_data);1883}18841885int for_each_branch_ref(each_ref_fn fn, void *cb_data)1886{1887 return for_each_ref_in("refs/heads/", fn, cb_data);1888}18891890int for_each_branch_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)1891{1892 return for_each_ref_in_submodule(submodule, "refs/heads/", fn, cb_data);1893}18941895int for_each_remote_ref(each_ref_fn fn, void *cb_data)1896{1897 return for_each_ref_in("refs/remotes/", fn, cb_data);1898}18991900int for_each_remote_ref_submodule(const char *submodule, each_ref_fn fn, void *cb_data)1901{1902 return for_each_ref_in_submodule(submodule, "refs/remotes/", fn, cb_data);1903}19041905int for_each_replace_ref(each_ref_fn fn, void *cb_data)1906{1907 return do_for_each_ref(&ref_cache, "refs/replace/", fn, 13, 0, cb_data);1908}19091910int head_ref_namespaced(each_ref_fn fn, void *cb_data)1911{1912 struct strbuf buf = STRBUF_INIT;1913 int ret = 0;1914 unsigned char sha1[20];1915 int flag;19161917 strbuf_addf(&buf, "%sHEAD", get_git_namespace());1918 if (!read_ref_full(buf.buf, sha1, 1, &flag))1919 ret = fn(buf.buf, sha1, flag, cb_data);1920 strbuf_release(&buf);19211922 return ret;1923}19241925int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)1926{1927 struct strbuf buf = STRBUF_INIT;1928 int ret;1929 strbuf_addf(&buf, "%srefs/", get_git_namespace());1930 ret = do_for_each_ref(&ref_cache, buf.buf, fn, 0, 0, cb_data);1931 strbuf_release(&buf);1932 return ret;1933}19341935int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,1936 const char *prefix, void *cb_data)1937{1938 struct strbuf real_pattern = STRBUF_INIT;1939 struct ref_filter filter;1940 int ret;19411942 if (!prefix && !starts_with(pattern, "refs/"))1943 strbuf_addstr(&real_pattern, "refs/");1944 else if (prefix)1945 strbuf_addstr(&real_pattern, prefix);1946 strbuf_addstr(&real_pattern, pattern);19471948 if (!has_glob_specials(pattern)) {1949 /* Append implied '/' '*' if not present. */1950 if (real_pattern.buf[real_pattern.len - 1] != '/')1951 strbuf_addch(&real_pattern, '/');1952 /* No need to check for '*', there is none. */1953 strbuf_addch(&real_pattern, '*');1954 }19551956 filter.pattern = real_pattern.buf;1957 filter.fn = fn;1958 filter.cb_data = cb_data;1959 ret = for_each_ref(filter_refs, &filter);19601961 strbuf_release(&real_pattern);1962 return ret;1963}19641965int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data)1966{1967 return for_each_glob_ref_in(fn, pattern, NULL, cb_data);1968}19691970int for_each_rawref(each_ref_fn fn, void *cb_data)1971{1972 return do_for_each_ref(&ref_cache, "", fn, 0,1973 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1974}19751976const char *prettify_refname(const char *name)1977{1978 return name + (1979 starts_with(name, "refs/heads/") ? 11 :1980 starts_with(name, "refs/tags/") ? 10 :1981 starts_with(name, "refs/remotes/") ? 13 :1982 0);1983}19841985static const char *ref_rev_parse_rules[] = {1986 "%.*s",1987 "refs/%.*s",1988 "refs/tags/%.*s",1989 "refs/heads/%.*s",1990 "refs/remotes/%.*s",1991 "refs/remotes/%.*s/HEAD",1992 NULL1993};19941995int refname_match(const char *abbrev_name, const char *full_name)1996{1997 const char **p;1998 const int abbrev_name_len = strlen(abbrev_name);19992000 for (p = ref_rev_parse_rules; *p; p++) {2001 if (!strcmp(full_name, mkpath(*p, abbrev_name_len, abbrev_name))) {2002 return 1;2003 }2004 }20052006 return 0;2007}20082009/* This function should make sure errno is meaningful on error */2010static struct ref_lock *verify_lock(struct ref_lock *lock,2011 const unsigned char *old_sha1, int mustexist)2012{2013 if (read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {2014 int save_errno = errno;2015 error("Can't verify ref %s", lock->ref_name);2016 unlock_ref(lock);2017 errno = save_errno;2018 return NULL;2019 }2020 if (hashcmp(lock->old_sha1, old_sha1)) {2021 error("Ref %s is at %s but expected %s", lock->ref_name,2022 sha1_to_hex(lock->old_sha1), sha1_to_hex(old_sha1));2023 unlock_ref(lock);2024 errno = EBUSY;2025 return NULL;2026 }2027 return lock;2028}20292030static int remove_empty_directories(const char *file)2031{2032 /* we want to create a file but there is a directory there;2033 * if that is an empty directory (or a directory that contains2034 * only empty directories), remove them.2035 */2036 struct strbuf path;2037 int result, save_errno;20382039 strbuf_init(&path, 20);2040 strbuf_addstr(&path, file);20412042 result = remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2043 save_errno = errno;20442045 strbuf_release(&path);2046 errno = save_errno;20472048 return result;2049}20502051/*2052 * *string and *len will only be substituted, and *string returned (for2053 * later free()ing) if the string passed in is a magic short-hand form2054 * to name a branch.2055 */2056static char *substitute_branch_name(const char **string, int *len)2057{2058 struct strbuf buf = STRBUF_INIT;2059 int ret = interpret_branch_name(*string, *len, &buf);20602061 if (ret == *len) {2062 size_t size;2063 *string = strbuf_detach(&buf, &size);2064 *len = size;2065 return (char *)*string;2066 }20672068 return NULL;2069}20702071int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)2072{2073 char *last_branch = substitute_branch_name(&str, &len);2074 const char **p, *r;2075 int refs_found = 0;20762077 *ref = NULL;2078 for (p = ref_rev_parse_rules; *p; p++) {2079 char fullref[PATH_MAX];2080 unsigned char sha1_from_ref[20];2081 unsigned char *this_result;2082 int flag;20832084 this_result = refs_found ? sha1_from_ref : sha1;2085 mksnpath(fullref, sizeof(fullref), *p, len, str);2086 r = resolve_ref_unsafe(fullref, this_result, 1, &flag);2087 if (r) {2088 if (!refs_found++)2089 *ref = xstrdup(r);2090 if (!warn_ambiguous_refs)2091 break;2092 } else if ((flag & REF_ISSYMREF) && strcmp(fullref, "HEAD")) {2093 warning("ignoring dangling symref %s.", fullref);2094 } else if ((flag & REF_ISBROKEN) && strchr(fullref, '/')) {2095 warning("ignoring broken ref %s.", fullref);2096 }2097 }2098 free(last_branch);2099 return refs_found;2100}21012102int dwim_log(const char *str, int len, unsigned char *sha1, char **log)2103{2104 char *last_branch = substitute_branch_name(&str, &len);2105 const char **p;2106 int logs_found = 0;21072108 *log = NULL;2109 for (p = ref_rev_parse_rules; *p; p++) {2110 unsigned char hash[20];2111 char path[PATH_MAX];2112 const char *ref, *it;21132114 mksnpath(path, sizeof(path), *p, len, str);2115 ref = resolve_ref_unsafe(path, hash, 1, NULL);2116 if (!ref)2117 continue;2118 if (reflog_exists(path))2119 it = path;2120 else if (strcmp(ref, path) && reflog_exists(ref))2121 it = ref;2122 else2123 continue;2124 if (!logs_found++) {2125 *log = xstrdup(it);2126 hashcpy(sha1, hash);2127 }2128 if (!warn_ambiguous_refs)2129 break;2130 }2131 free(last_branch);2132 return logs_found;2133}21342135/*2136 * Locks a "refs/" ref returning the lock on success and NULL on failure.2137 * On failure errno is set to something meaningful.2138 */2139static struct ref_lock *lock_ref_sha1_basic(const char *refname,2140 const unsigned char *old_sha1,2141 int flags, int *type_p)2142{2143 char *ref_file;2144 const char *orig_refname = refname;2145 struct ref_lock *lock;2146 int last_errno = 0;2147 int type, lflags;2148 int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2149 int missing = 0;2150 int attempts_remaining = 3;21512152 lock = xcalloc(1, sizeof(struct ref_lock));2153 lock->lock_fd = -1;21542155 refname = resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);2156 if (!refname && errno == EISDIR) {2157 /* we are trying to lock foo but we used to2158 * have foo/bar which now does not exist;2159 * it is normal for the empty directory 'foo'2160 * to remain.2161 */2162 ref_file = git_path("%s", orig_refname);2163 if (remove_empty_directories(ref_file)) {2164 last_errno = errno;2165 error("there are still refs under '%s'", orig_refname);2166 goto error_return;2167 }2168 refname = resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);2169 }2170 if (type_p)2171 *type_p = type;2172 if (!refname) {2173 last_errno = errno;2174 error("unable to resolve reference %s: %s",2175 orig_refname, strerror(errno));2176 goto error_return;2177 }2178 missing = is_null_sha1(lock->old_sha1);2179 /* When the ref did not exist and we are creating it,2180 * make sure there is no existing ref that is packed2181 * whose name begins with our refname, nor a ref whose2182 * name is a proper prefix of our refname.2183 */2184 if (missing &&2185 !is_refname_available(refname, NULL, get_packed_refs(&ref_cache))) {2186 last_errno = ENOTDIR;2187 goto error_return;2188 }21892190 lock->lk = xcalloc(1, sizeof(struct lock_file));21912192 lflags = 0;2193 if (flags & REF_NODEREF) {2194 refname = orig_refname;2195 lflags |= LOCK_NODEREF;2196 }2197 lock->ref_name = xstrdup(refname);2198 lock->orig_ref_name = xstrdup(orig_refname);2199 ref_file = git_path("%s", refname);2200 if (missing)2201 lock->force_write = 1;2202 if ((flags & REF_NODEREF) && (type & REF_ISSYMREF))2203 lock->force_write = 1;22042205 retry:2206 switch (safe_create_leading_directories(ref_file)) {2207 case SCLD_OK:2208 break; /* success */2209 case SCLD_VANISHED:2210 if (--attempts_remaining > 0)2211 goto retry;2212 /* fall through */2213 default:2214 last_errno = errno;2215 error("unable to create directory for %s", ref_file);2216 goto error_return;2217 }22182219 lock->lock_fd = hold_lock_file_for_update(lock->lk, ref_file, lflags);2220 if (lock->lock_fd < 0) {2221 if (errno == ENOENT && --attempts_remaining > 0)2222 /*2223 * Maybe somebody just deleted one of the2224 * directories leading to ref_file. Try2225 * again:2226 */2227 goto retry;2228 else2229 unable_to_lock_die(ref_file, errno);2230 }2231 return old_sha1 ? verify_lock(lock, old_sha1, mustexist) : lock;22322233 error_return:2234 unlock_ref(lock);2235 errno = last_errno;2236 return NULL;2237}22382239struct ref_lock *lock_any_ref_for_update(const char *refname,2240 const unsigned char *old_sha1,2241 int flags, int *type_p)2242{2243 if (check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))2244 return NULL;2245 return lock_ref_sha1_basic(refname, old_sha1, flags, type_p);2246}22472248/*2249 * Write an entry to the packed-refs file for the specified refname.2250 * If peeled is non-NULL, write it as the entry's peeled value.2251 */2252static void write_packed_entry(FILE *fh, char *refname, unsigned char *sha1,2253 unsigned char *peeled)2254{2255 fprintf_or_die(fh, "%s %s\n", sha1_to_hex(sha1), refname);2256 if (peeled)2257 fprintf_or_die(fh, "^%s\n", sha1_to_hex(peeled));2258}22592260/*2261 * An each_ref_entry_fn that writes the entry to a packed-refs file.2262 */2263static int write_packed_entry_fn(struct ref_entry *entry, void *cb_data)2264{2265 enum peel_status peel_status = peel_entry(entry, 0);22662267 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2268 error("internal error: %s is not a valid packed reference!",2269 entry->name);2270 write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2271 peel_status == PEEL_PEELED ?2272 entry->u.value.peeled : NULL);2273 return 0;2274}22752276/* This should return a meaningful errno on failure */2277int lock_packed_refs(int flags)2278{2279 struct packed_ref_cache *packed_ref_cache;22802281 if (hold_lock_file_for_update(&packlock, git_path("packed-refs"), flags) < 0)2282 return -1;2283 /*2284 * Get the current packed-refs while holding the lock. If the2285 * packed-refs file has been modified since we last read it,2286 * this will automatically invalidate the cache and re-read2287 * the packed-refs file.2288 */2289 packed_ref_cache = get_packed_ref_cache(&ref_cache);2290 packed_ref_cache->lock = &packlock;2291 /* Increment the reference count to prevent it from being freed: */2292 acquire_packed_ref_cache(packed_ref_cache);2293 return 0;2294}22952296/*2297 * Commit the packed refs changes.2298 * On error we must make sure that errno contains a meaningful value.2299 */2300int commit_packed_refs(void)2301{2302 struct packed_ref_cache *packed_ref_cache =2303 get_packed_ref_cache(&ref_cache);2304 int error = 0;2305 int save_errno = 0;2306 FILE *out;23072308 if (!packed_ref_cache->lock)2309 die("internal error: packed-refs not locked");23102311 out = fdopen(packed_ref_cache->lock->fd, "w");2312 if (!out)2313 die_errno("unable to fdopen packed-refs descriptor");23142315 fprintf_or_die(out, "%s", PACKED_REFS_HEADER);2316 do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),2317 0, write_packed_entry_fn, out);2318 if (fclose(out))2319 die_errno("write error");2320 packed_ref_cache->lock->fd = -1;23212322 if (commit_lock_file(packed_ref_cache->lock)) {2323 save_errno = errno;2324 error = -1;2325 }2326 packed_ref_cache->lock = NULL;2327 release_packed_ref_cache(packed_ref_cache);2328 errno = save_errno;2329 return error;2330}23312332void rollback_packed_refs(void)2333{2334 struct packed_ref_cache *packed_ref_cache =2335 get_packed_ref_cache(&ref_cache);23362337 if (!packed_ref_cache->lock)2338 die("internal error: packed-refs not locked");2339 rollback_lock_file(packed_ref_cache->lock);2340 packed_ref_cache->lock = NULL;2341 release_packed_ref_cache(packed_ref_cache);2342 clear_packed_ref_cache(&ref_cache);2343}23442345struct ref_to_prune {2346 struct ref_to_prune *next;2347 unsigned char sha1[20];2348 char name[FLEX_ARRAY];2349};23502351struct pack_refs_cb_data {2352 unsigned int flags;2353 struct ref_dir *packed_refs;2354 struct ref_to_prune *ref_to_prune;2355};23562357/*2358 * An each_ref_entry_fn that is run over loose references only. If2359 * the loose reference can be packed, add an entry in the packed ref2360 * cache. If the reference should be pruned, also add it to2361 * ref_to_prune in the pack_refs_cb_data.2362 */2363static int pack_if_possible_fn(struct ref_entry *entry, void *cb_data)2364{2365 struct pack_refs_cb_data *cb = cb_data;2366 enum peel_status peel_status;2367 struct ref_entry *packed_entry;2368 int is_tag_ref = starts_with(entry->name, "refs/tags/");23692370 /* ALWAYS pack tags */2371 if (!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2372 return 0;23732374 /* Do not pack symbolic or broken refs: */2375 if ((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2376 return 0;23772378 /* Add a packed ref cache entry equivalent to the loose entry. */2379 peel_status = peel_entry(entry, 1);2380 if (peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2381 die("internal error peeling reference %s (%s)",2382 entry->name, sha1_to_hex(entry->u.value.sha1));2383 packed_entry = find_ref(cb->packed_refs, entry->name);2384 if (packed_entry) {2385 /* Overwrite existing packed entry with info from loose entry */2386 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2387 hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2388 } else {2389 packed_entry = create_ref_entry(entry->name, entry->u.value.sha1,2390 REF_ISPACKED | REF_KNOWS_PEELED, 0);2391 add_ref(cb->packed_refs, packed_entry);2392 }2393 hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);23942395 /* Schedule the loose reference for pruning if requested. */2396 if ((cb->flags & PACK_REFS_PRUNE)) {2397 int namelen = strlen(entry->name) + 1;2398 struct ref_to_prune *n = xcalloc(1, sizeof(*n) + namelen);2399 hashcpy(n->sha1, entry->u.value.sha1);2400 strcpy(n->name, entry->name);2401 n->next = cb->ref_to_prune;2402 cb->ref_to_prune = n;2403 }2404 return 0;2405}24062407/*2408 * Remove empty parents, but spare refs/ and immediate subdirs.2409 * Note: munges *name.2410 */2411static void try_remove_empty_parents(char *name)2412{2413 char *p, *q;2414 int i;2415 p = name;2416 for (i = 0; i < 2; i++) { /* refs/{heads,tags,...}/ */2417 while (*p && *p != '/')2418 p++;2419 /* tolerate duplicate slashes; see check_refname_format() */2420 while (*p == '/')2421 p++;2422 }2423 for (q = p; *q; q++)2424 ;2425 while (1) {2426 while (q > p && *q != '/')2427 q--;2428 while (q > p && *(q-1) == '/')2429 q--;2430 if (q == p)2431 break;2432 *q = '\0';2433 if (rmdir(git_path("%s", name)))2434 break;2435 }2436}24372438/* make sure nobody touched the ref, and unlink */2439static void prune_ref(struct ref_to_prune *r)2440{2441 struct ref_transaction *transaction;2442 struct strbuf err = STRBUF_INIT;24432444 if (check_refname_format(r->name, 0))2445 return;24462447 transaction = ref_transaction_begin(&err);2448 if (!transaction ||2449 ref_transaction_delete(transaction, r->name, r->sha1,2450 REF_ISPRUNING, 1, &err) ||2451 ref_transaction_commit(transaction, NULL, &err)) {2452 ref_transaction_free(transaction);2453 error("%s", err.buf);2454 strbuf_release(&err);2455 return;2456 }2457 ref_transaction_free(transaction);2458 strbuf_release(&err);2459 try_remove_empty_parents(r->name);2460}24612462static void prune_refs(struct ref_to_prune *r)2463{2464 while (r) {2465 prune_ref(r);2466 r = r->next;2467 }2468}24692470int pack_refs(unsigned int flags)2471{2472 struct pack_refs_cb_data cbdata;24732474 memset(&cbdata, 0, sizeof(cbdata));2475 cbdata.flags = flags;24762477 lock_packed_refs(LOCK_DIE_ON_ERROR);2478 cbdata.packed_refs = get_packed_refs(&ref_cache);24792480 do_for_each_entry_in_dir(get_loose_refs(&ref_cache), 0,2481 pack_if_possible_fn, &cbdata);24822483 if (commit_packed_refs())2484 die_errno("unable to overwrite old ref-pack file");24852486 prune_refs(cbdata.ref_to_prune);2487 return 0;2488}24892490/*2491 * If entry is no longer needed in packed-refs, add it to the string2492 * list pointed to by cb_data. Reasons for deleting entries:2493 *2494 * - Entry is broken.2495 * - Entry is overridden by a loose ref.2496 * - Entry does not point at a valid object.2497 *2498 * In the first and third cases, also emit an error message because these2499 * are indications of repository corruption.2500 */2501static int curate_packed_ref_fn(struct ref_entry *entry, void *cb_data)2502{2503 struct string_list *refs_to_delete = cb_data;25042505 if (entry->flag & REF_ISBROKEN) {2506 /* This shouldn't happen to packed refs. */2507 error("%s is broken!", entry->name);2508 string_list_append(refs_to_delete, entry->name);2509 return 0;2510 }2511 if (!has_sha1_file(entry->u.value.sha1)) {2512 unsigned char sha1[20];2513 int flags;25142515 if (read_ref_full(entry->name, sha1, 0, &flags))2516 /* We should at least have found the packed ref. */2517 die("Internal error");2518 if ((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2519 /*2520 * This packed reference is overridden by a2521 * loose reference, so it is OK that its value2522 * is no longer valid; for example, it might2523 * refer to an object that has been garbage2524 * collected. For this purpose we don't even2525 * care whether the loose reference itself is2526 * invalid, broken, symbolic, etc. Silently2527 * remove the packed reference.2528 */2529 string_list_append(refs_to_delete, entry->name);2530 return 0;2531 }2532 /*2533 * There is no overriding loose reference, so the fact2534 * that this reference doesn't refer to a valid object2535 * indicates some kind of repository corruption.2536 * Report the problem, then omit the reference from2537 * the output.2538 */2539 error("%s does not point to a valid object!", entry->name);2540 string_list_append(refs_to_delete, entry->name);2541 return 0;2542 }25432544 return 0;2545}25462547int repack_without_refs(const char **refnames, int n, struct strbuf *err)2548{2549 struct ref_dir *packed;2550 struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2551 struct string_list_item *ref_to_delete;2552 int i, ret, removed = 0;25532554 /* Look for a packed ref */2555 for (i = 0; i < n; i++)2556 if (get_packed_ref(refnames[i]))2557 break;25582559 /* Avoid locking if we have nothing to do */2560 if (i == n)2561 return 0; /* no refname exists in packed refs */25622563 if (lock_packed_refs(0)) {2564 if (err) {2565 unable_to_lock_message(git_path("packed-refs"), errno,2566 err);2567 return -1;2568 }2569 unable_to_lock_error(git_path("packed-refs"), errno);2570 return error("cannot delete '%s' from packed refs", refnames[i]);2571 }2572 packed = get_packed_refs(&ref_cache);25732574 /* Remove refnames from the cache */2575 for (i = 0; i < n; i++)2576 if (remove_entry(packed, refnames[i]) != -1)2577 removed = 1;2578 if (!removed) {2579 /*2580 * All packed entries disappeared while we were2581 * acquiring the lock.2582 */2583 rollback_packed_refs();2584 return 0;2585 }25862587 /* Remove any other accumulated cruft */2588 do_for_each_entry_in_dir(packed, 0, curate_packed_ref_fn, &refs_to_delete);2589 for_each_string_list_item(ref_to_delete, &refs_to_delete) {2590 if (remove_entry(packed, ref_to_delete->string) == -1)2591 die("internal error");2592 }25932594 /* Write what remains */2595 ret = commit_packed_refs();2596 if (ret && err)2597 strbuf_addf(err, "unable to overwrite old ref-pack file: %s",2598 strerror(errno));2599 return ret;2600}26012602static int delete_ref_loose(struct ref_lock *lock, int flag)2603{2604 if (!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2605 /* loose */2606 int err, i = strlen(lock->lk->filename) - LOCK_SUFFIX_LEN;26072608 lock->lk->filename[i] = 0;2609 err = unlink_or_warn(lock->lk->filename);2610 lock->lk->filename[i] = LOCK_SUFFIX[0];2611 if (err && errno != ENOENT)2612 return 1;2613 }2614 return 0;2615}26162617int delete_ref(const char *refname, const unsigned char *sha1, int delopt)2618{2619 struct ref_transaction *transaction;2620 struct strbuf err = STRBUF_INIT;26212622 transaction = ref_transaction_begin(&err);2623 if (!transaction ||2624 ref_transaction_delete(transaction, refname, sha1, delopt,2625 sha1 && !is_null_sha1(sha1), &err) ||2626 ref_transaction_commit(transaction, NULL, &err)) {2627 error("%s", err.buf);2628 ref_transaction_free(transaction);2629 strbuf_release(&err);2630 return 1;2631 }2632 ref_transaction_free(transaction);2633 strbuf_release(&err);2634 return 0;2635}26362637/*2638 * People using contrib's git-new-workdir have .git/logs/refs ->2639 * /some/other/path/.git/logs/refs, and that may live on another device.2640 *2641 * IOW, to avoid cross device rename errors, the temporary renamed log must2642 * live into logs/refs.2643 */2644#define TMP_RENAMED_LOG "logs/refs/.tmp-renamed-log"26452646static int rename_tmp_log(const char *newrefname)2647{2648 int attempts_remaining = 4;26492650 retry:2651 switch (safe_create_leading_directories(git_path("logs/%s", newrefname))) {2652 case SCLD_OK:2653 break; /* success */2654 case SCLD_VANISHED:2655 if (--attempts_remaining > 0)2656 goto retry;2657 /* fall through */2658 default:2659 error("unable to create directory for %s", newrefname);2660 return -1;2661 }26622663 if (rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", newrefname))) {2664 if ((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining > 0) {2665 /*2666 * rename(a, b) when b is an existing2667 * directory ought to result in ISDIR, but2668 * Solaris 5.8 gives ENOTDIR. Sheesh.2669 */2670 if (remove_empty_directories(git_path("logs/%s", newrefname))) {2671 error("Directory not empty: logs/%s", newrefname);2672 return -1;2673 }2674 goto retry;2675 } else if (errno == ENOENT && --attempts_remaining > 0) {2676 /*2677 * Maybe another process just deleted one of2678 * the directories in the path to newrefname.2679 * Try again from the beginning.2680 */2681 goto retry;2682 } else {2683 error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s: %s",2684 newrefname, strerror(errno));2685 return -1;2686 }2687 }2688 return 0;2689}26902691int rename_ref(const char *oldrefname, const char *newrefname, const char *logmsg)2692{2693 unsigned char sha1[20], orig_sha1[20];2694 int flag = 0, logmoved = 0;2695 struct ref_lock *lock;2696 struct stat loginfo;2697 int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2698 const char *symref = NULL;26992700 if (log && S_ISLNK(loginfo.st_mode))2701 return error("reflog for %s is a symlink", oldrefname);27022703 symref = resolve_ref_unsafe(oldrefname, orig_sha1, 1, &flag);2704 if (flag & REF_ISSYMREF)2705 return error("refname %s is a symbolic ref, renaming it is not supported",2706 oldrefname);2707 if (!symref)2708 return error("refname %s not found", oldrefname);27092710 if (!is_refname_available(newrefname, oldrefname, get_packed_refs(&ref_cache)))2711 return 1;27122713 if (!is_refname_available(newrefname, oldrefname, get_loose_refs(&ref_cache)))2714 return 1;27152716 if (log && rename(git_path("logs/%s", oldrefname), git_path(TMP_RENAMED_LOG)))2717 return error("unable to move logfile logs/%s to "TMP_RENAMED_LOG": %s",2718 oldrefname, strerror(errno));27192720 if (delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2721 error("unable to delete old %s", oldrefname);2722 goto rollback;2723 }27242725 if (!read_ref_full(newrefname, sha1, 1, &flag) &&2726 delete_ref(newrefname, sha1, REF_NODEREF)) {2727 if (errno==EISDIR) {2728 if (remove_empty_directories(git_path("%s", newrefname))) {2729 error("Directory not empty: %s", newrefname);2730 goto rollback;2731 }2732 } else {2733 error("unable to delete existing %s", newrefname);2734 goto rollback;2735 }2736 }27372738 if (log && rename_tmp_log(newrefname))2739 goto rollback;27402741 logmoved = log;27422743 lock = lock_ref_sha1_basic(newrefname, NULL, 0, NULL);2744 if (!lock) {2745 error("unable to lock %s for update", newrefname);2746 goto rollback;2747 }2748 lock->force_write = 1;2749 hashcpy(lock->old_sha1, orig_sha1);2750 if (write_ref_sha1(lock, orig_sha1, logmsg)) {2751 error("unable to write current sha1 into %s", newrefname);2752 goto rollback;2753 }27542755 return 0;27562757 rollback:2758 lock = lock_ref_sha1_basic(oldrefname, NULL, 0, NULL);2759 if (!lock) {2760 error("unable to lock %s for rollback", oldrefname);2761 goto rollbacklog;2762 }27632764 lock->force_write = 1;2765 flag = log_all_ref_updates;2766 log_all_ref_updates = 0;2767 if (write_ref_sha1(lock, orig_sha1, NULL))2768 error("unable to write current sha1 into %s", oldrefname);2769 log_all_ref_updates = flag;27702771 rollbacklog:2772 if (logmoved && rename(git_path("logs/%s", newrefname), git_path("logs/%s", oldrefname)))2773 error("unable to restore logfile %s from %s: %s",2774 oldrefname, newrefname, strerror(errno));2775 if (!logmoved && log &&2776 rename(git_path(TMP_RENAMED_LOG), git_path("logs/%s", oldrefname)))2777 error("unable to restore logfile %s from "TMP_RENAMED_LOG": %s",2778 oldrefname, strerror(errno));27792780 return 1;2781}27822783int close_ref(struct ref_lock *lock)2784{2785 if (close_lock_file(lock->lk))2786 return -1;2787 lock->lock_fd = -1;2788 return 0;2789}27902791int commit_ref(struct ref_lock *lock)2792{2793 if (commit_lock_file(lock->lk))2794 return -1;2795 lock->lock_fd = -1;2796 return 0;2797}27982799void unlock_ref(struct ref_lock *lock)2800{2801 /* Do not free lock->lk -- atexit() still looks at them */2802 if (lock->lk)2803 rollback_lock_file(lock->lk);2804 free(lock->ref_name);2805 free(lock->orig_ref_name);2806 free(lock);2807}28082809/*2810 * copy the reflog message msg to buf, which has been allocated sufficiently2811 * large, while cleaning up the whitespaces. Especially, convert LF to space,2812 * because reflog file is one line per entry.2813 */2814static int copy_msg(char *buf, const char *msg)2815{2816 char *cp = buf;2817 char c;2818 int wasspace = 1;28192820 *cp++ = '\t';2821 while ((c = *msg++)) {2822 if (wasspace && isspace(c))2823 continue;2824 wasspace = isspace(c);2825 if (wasspace)2826 c = ' ';2827 *cp++ = c;2828 }2829 while (buf < cp && isspace(cp[-1]))2830 cp--;2831 *cp++ = '\n';2832 return cp - buf;2833}28342835/* This function must set a meaningful errno on failure */2836int log_ref_setup(const char *refname, char *logfile, int bufsize)2837{2838 int logfd, oflags = O_APPEND | O_WRONLY;28392840 git_snpath(logfile, bufsize, "logs/%s", refname);2841 if (log_all_ref_updates &&2842 (starts_with(refname, "refs/heads/") ||2843 starts_with(refname, "refs/remotes/") ||2844 starts_with(refname, "refs/notes/") ||2845 !strcmp(refname, "HEAD"))) {2846 if (safe_create_leading_directories(logfile) < 0) {2847 int save_errno = errno;2848 error("unable to create directory for %s", logfile);2849 errno = save_errno;2850 return -1;2851 }2852 oflags |= O_CREAT;2853 }28542855 logfd = open(logfile, oflags, 0666);2856 if (logfd < 0) {2857 if (!(oflags & O_CREAT) && errno == ENOENT)2858 return 0;28592860 if ((oflags & O_CREAT) && errno == EISDIR) {2861 if (remove_empty_directories(logfile)) {2862 int save_errno = errno;2863 error("There are still logs under '%s'",2864 logfile);2865 errno = save_errno;2866 return -1;2867 }2868 logfd = open(logfile, oflags, 0666);2869 }28702871 if (logfd < 0) {2872 int save_errno = errno;2873 error("Unable to append to %s: %s", logfile,2874 strerror(errno));2875 errno = save_errno;2876 return -1;2877 }2878 }28792880 adjust_shared_perm(logfile);2881 close(logfd);2882 return 0;2883}28842885static int log_ref_write(const char *refname, const unsigned char *old_sha1,2886 const unsigned char *new_sha1, const char *msg)2887{2888 int logfd, result, written, oflags = O_APPEND | O_WRONLY;2889 unsigned maxlen, len;2890 int msglen;2891 char log_file[PATH_MAX];2892 char *logrec;2893 const char *committer;28942895 if (log_all_ref_updates < 0)2896 log_all_ref_updates = !is_bare_repository();28972898 result = log_ref_setup(refname, log_file, sizeof(log_file));2899 if (result)2900 return result;29012902 logfd = open(log_file, oflags);2903 if (logfd < 0)2904 return 0;2905 msglen = msg ? strlen(msg) : 0;2906 committer = git_committer_info(0);2907 maxlen = strlen(committer) + msglen + 100;2908 logrec = xmalloc(maxlen);2909 len = sprintf(logrec, "%s %s %s\n",2910 sha1_to_hex(old_sha1),2911 sha1_to_hex(new_sha1),2912 committer);2913 if (msglen)2914 len += copy_msg(logrec + len - 1, msg) - 1;2915 written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;2916 free(logrec);2917 if (written != len) {2918 int save_errno = errno;2919 close(logfd);2920 error("Unable to append to %s", log_file);2921 errno = save_errno;2922 return -1;2923 }2924 if (close(logfd)) {2925 int save_errno = errno;2926 error("Unable to append to %s", log_file);2927 errno = save_errno;2928 return -1;2929 }2930 return 0;2931}29322933int is_branch(const char *refname)2934{2935 return !strcmp(refname, "HEAD") || starts_with(refname, "refs/heads/");2936}29372938/* This function must return a meaningful errno */2939int write_ref_sha1(struct ref_lock *lock,2940 const unsigned char *sha1, const char *logmsg)2941{2942 static char term = '\n';2943 struct object *o;29442945 if (!lock) {2946 errno = EINVAL;2947 return -1;2948 }2949 if (!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {2950 unlock_ref(lock);2951 return 0;2952 }2953 o = parse_object(sha1);2954 if (!o) {2955 error("Trying to write ref %s with nonexistent object %s",2956 lock->ref_name, sha1_to_hex(sha1));2957 unlock_ref(lock);2958 errno = EINVAL;2959 return -1;2960 }2961 if (o->type != OBJ_COMMIT && is_branch(lock->ref_name)) {2962 error("Trying to write non-commit object %s to branch %s",2963 sha1_to_hex(sha1), lock->ref_name);2964 unlock_ref(lock);2965 errno = EINVAL;2966 return -1;2967 }2968 if (write_in_full(lock->lock_fd, sha1_to_hex(sha1), 40) != 40 ||2969 write_in_full(lock->lock_fd, &term, 1) != 1 ||2970 close_ref(lock) < 0) {2971 int save_errno = errno;2972 error("Couldn't write %s", lock->lk->filename);2973 unlock_ref(lock);2974 errno = save_errno;2975 return -1;2976 }2977 clear_loose_ref_cache(&ref_cache);2978 if (log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) < 0 ||2979 (strcmp(lock->ref_name, lock->orig_ref_name) &&2980 log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) < 0)) {2981 unlock_ref(lock);2982 return -1;2983 }2984 if (strcmp(lock->orig_ref_name, "HEAD") != 0) {2985 /*2986 * Special hack: If a branch is updated directly and HEAD2987 * points to it (may happen on the remote side of a push2988 * for example) then logically the HEAD reflog should be2989 * updated too.2990 * A generic solution implies reverse symref information,2991 * but finding all symrefs pointing to the given branch2992 * would be rather costly for this rare event (the direct2993 * update of a branch) to be worth it. So let's cheat and2994 * check with HEAD only which should cover 99% of all usage2995 * scenarios (even 100% of the default ones).2996 */2997 unsigned char head_sha1[20];2998 int head_flag;2999 const char *head_ref;3000 head_ref = resolve_ref_unsafe("HEAD", head_sha1, 1, &head_flag);3001 if (head_ref && (head_flag & REF_ISSYMREF) &&3002 !strcmp(head_ref, lock->ref_name))3003 log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3004 }3005 if (commit_ref(lock)) {3006 error("Couldn't set %s", lock->ref_name);3007 unlock_ref(lock);3008 return -1;3009 }3010 unlock_ref(lock);3011 return 0;3012}30133014int create_symref(const char *ref_target, const char *refs_heads_master,3015 const char *logmsg)3016{3017 const char *lockpath;3018 char ref[1000];3019 int fd, len, written;3020 char *git_HEAD = git_pathdup("%s", ref_target);3021 unsigned char old_sha1[20], new_sha1[20];30223023 if (logmsg && read_ref(ref_target, old_sha1))3024 hashclr(old_sha1);30253026 if (safe_create_leading_directories(git_HEAD) < 0)3027 return error("unable to create directory for %s", git_HEAD);30283029#ifndef NO_SYMLINK_HEAD3030 if (prefer_symlink_refs) {3031 unlink(git_HEAD);3032 if (!symlink(refs_heads_master, git_HEAD))3033 goto done;3034 fprintf(stderr, "no symlink - falling back to symbolic ref\n");3035 }3036#endif30373038 len = snprintf(ref, sizeof(ref), "ref: %s\n", refs_heads_master);3039 if (sizeof(ref) <= len) {3040 error("refname too long: %s", refs_heads_master);3041 goto error_free_return;3042 }3043 lockpath = mkpath("%s.lock", git_HEAD);3044 fd = open(lockpath, O_CREAT | O_EXCL | O_WRONLY, 0666);3045 if (fd < 0) {3046 error("Unable to open %s for writing", lockpath);3047 goto error_free_return;3048 }3049 written = write_in_full(fd, ref, len);3050 if (close(fd) != 0 || written != len) {3051 error("Unable to write to %s", lockpath);3052 goto error_unlink_return;3053 }3054 if (rename(lockpath, git_HEAD) < 0) {3055 error("Unable to create %s", git_HEAD);3056 goto error_unlink_return;3057 }3058 if (adjust_shared_perm(git_HEAD)) {3059 error("Unable to fix permissions on %s", lockpath);3060 error_unlink_return:3061 unlink_or_warn(lockpath);3062 error_free_return:3063 free(git_HEAD);3064 return -1;3065 }30663067#ifndef NO_SYMLINK_HEAD3068 done:3069#endif3070 if (logmsg && !read_ref(refs_heads_master, new_sha1))3071 log_ref_write(ref_target, old_sha1, new_sha1, logmsg);30723073 free(git_HEAD);3074 return 0;3075}30763077struct read_ref_at_cb {3078 const char *refname;3079 unsigned long at_time;3080 int cnt;3081 int reccnt;3082 unsigned char *sha1;3083 int found_it;30843085 unsigned char osha1[20];3086 unsigned char nsha1[20];3087 int tz;3088 unsigned long date;3089 char **msg;3090 unsigned long *cutoff_time;3091 int *cutoff_tz;3092 int *cutoff_cnt;3093};30943095static int read_ref_at_ent(unsigned char *osha1, unsigned char *nsha1,3096 const char *email, unsigned long timestamp, int tz,3097 const char *message, void *cb_data)3098{3099 struct read_ref_at_cb *cb = cb_data;31003101 cb->reccnt++;3102 cb->tz = tz;3103 cb->date = timestamp;31043105 if (timestamp <= cb->at_time || cb->cnt == 0) {3106 if (cb->msg)3107 *cb->msg = xstrdup(message);3108 if (cb->cutoff_time)3109 *cb->cutoff_time = timestamp;3110 if (cb->cutoff_tz)3111 *cb->cutoff_tz = tz;3112 if (cb->cutoff_cnt)3113 *cb->cutoff_cnt = cb->reccnt - 1;3114 /*3115 * we have not yet updated cb->[n|o]sha1 so they still3116 * hold the values for the previous record.3117 */3118 if (!is_null_sha1(cb->osha1)) {3119 hashcpy(cb->sha1, nsha1);3120 if (hashcmp(cb->osha1, nsha1))3121 warning("Log for ref %s has gap after %s.",3122 cb->refname, show_date(cb->date, cb->tz, DATE_RFC2822));3123 }3124 else if (cb->date == cb->at_time)3125 hashcpy(cb->sha1, nsha1);3126 else if (hashcmp(nsha1, cb->sha1))3127 warning("Log for ref %s unexpectedly ended on %s.",3128 cb->refname, show_date(cb->date, cb->tz,3129 DATE_RFC2822));3130 hashcpy(cb->osha1, osha1);3131 hashcpy(cb->nsha1, nsha1);3132 cb->found_it = 1;3133 return 1;3134 }3135 hashcpy(cb->osha1, osha1);3136 hashcpy(cb->nsha1, nsha1);3137 if (cb->cnt > 0)3138 cb->cnt--;3139 return 0;3140}31413142static int read_ref_at_ent_oldest(unsigned char *osha1, unsigned char *nsha1,3143 const char *email, unsigned long timestamp,3144 int tz, const char *message, void *cb_data)3145{3146 struct read_ref_at_cb *cb = cb_data;31473148 if (cb->msg)3149 *cb->msg = xstrdup(message);3150 if (cb->cutoff_time)3151 *cb->cutoff_time = timestamp;3152 if (cb->cutoff_tz)3153 *cb->cutoff_tz = tz;3154 if (cb->cutoff_cnt)3155 *cb->cutoff_cnt = cb->reccnt;3156 hashcpy(cb->sha1, osha1);3157 if (is_null_sha1(cb->sha1))3158 hashcpy(cb->sha1, nsha1);3159 /* We just want the first entry */3160 return 1;3161}31623163int read_ref_at(const char *refname, unsigned int flags, unsigned long at_time, int cnt,3164 unsigned char *sha1, char **msg,3165 unsigned long *cutoff_time, int *cutoff_tz, int *cutoff_cnt)3166{3167 struct read_ref_at_cb cb;31683169 memset(&cb, 0, sizeof(cb));3170 cb.refname = refname;3171 cb.at_time = at_time;3172 cb.cnt = cnt;3173 cb.msg = msg;3174 cb.cutoff_time = cutoff_time;3175 cb.cutoff_tz = cutoff_tz;3176 cb.cutoff_cnt = cutoff_cnt;3177 cb.sha1 = sha1;31783179 for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);31803181 if (!cb.reccnt) {3182 if (flags & GET_SHA1_QUIETLY)3183 exit(128);3184 else3185 die("Log for %s is empty.", refname);3186 }3187 if (cb.found_it)3188 return 0;31893190 for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);31913192 return 1;3193}31943195int reflog_exists(const char *refname)3196{3197 struct stat st;31983199 return !lstat(git_path("logs/%s", refname), &st) &&3200 S_ISREG(st.st_mode);3201}32023203int delete_reflog(const char *refname)3204{3205 return remove_path(git_path("logs/%s", refname));3206}32073208static int show_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn, void *cb_data)3209{3210 unsigned char osha1[20], nsha1[20];3211 char *email_end, *message;3212 unsigned long timestamp;3213 int tz;32143215 /* old SP new SP name <email> SP time TAB msg LF */3216 if (sb->len < 83 || sb->buf[sb->len - 1] != '\n' ||3217 get_sha1_hex(sb->buf, osha1) || sb->buf[40] != ' ' ||3218 get_sha1_hex(sb->buf + 41, nsha1) || sb->buf[81] != ' ' ||3219 !(email_end = strchr(sb->buf + 82, '>')) ||3220 email_end[1] != ' ' ||3221 !(timestamp = strtoul(email_end + 2, &message, 10)) ||3222 !message || message[0] != ' ' ||3223 (message[1] != '+' && message[1] != '-') ||3224 !isdigit(message[2]) || !isdigit(message[3]) ||3225 !isdigit(message[4]) || !isdigit(message[5]))3226 return 0; /* corrupt? */3227 email_end[1] = '\0';3228 tz = strtol(message + 1, NULL, 10);3229 if (message[6] != '\t')3230 message += 6;3231 else3232 message += 7;3233 return fn(osha1, nsha1, sb->buf + 82, timestamp, tz, message, cb_data);3234}32353236static char *find_beginning_of_line(char *bob, char *scan)3237{3238 while (bob < scan && *(--scan) != '\n')3239 ; /* keep scanning backwards */3240 /*3241 * Return either beginning of the buffer, or LF at the end of3242 * the previous line.3243 */3244 return scan;3245}32463247int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn, void *cb_data)3248{3249 struct strbuf sb = STRBUF_INIT;3250 FILE *logfp;3251 long pos;3252 int ret = 0, at_tail = 1;32533254 logfp = fopen(git_path("logs/%s", refname), "r");3255 if (!logfp)3256 return -1;32573258 /* Jump to the end */3259 if (fseek(logfp, 0, SEEK_END) < 0)3260 return error("cannot seek back reflog for %s: %s",3261 refname, strerror(errno));3262 pos = ftell(logfp);3263 while (!ret && 0 < pos) {3264 int cnt;3265 size_t nread;3266 char buf[BUFSIZ];3267 char *endp, *scanp;32683269 /* Fill next block from the end */3270 cnt = (sizeof(buf) < pos) ? sizeof(buf) : pos;3271 if (fseek(logfp, pos - cnt, SEEK_SET))3272 return error("cannot seek back reflog for %s: %s",3273 refname, strerror(errno));3274 nread = fread(buf, cnt, 1, logfp);3275 if (nread != 1)3276 return error("cannot read %d bytes from reflog for %s: %s",3277 cnt, refname, strerror(errno));3278 pos -= cnt;32793280 scanp = endp = buf + cnt;3281 if (at_tail && scanp[-1] == '\n')3282 /* Looking at the final LF at the end of the file */3283 scanp--;3284 at_tail = 0;32853286 while (buf < scanp) {3287 /*3288 * terminating LF of the previous line, or the beginning3289 * of the buffer.3290 */3291 char *bp;32923293 bp = find_beginning_of_line(buf, scanp);32943295 if (*bp != '\n') {3296 strbuf_splice(&sb, 0, 0, buf, endp - buf);3297 if (pos)3298 break; /* need to fill another block */3299 scanp = buf - 1; /* leave loop */3300 } else {3301 /*3302 * (bp + 1) thru endp is the beginning of the3303 * current line we have in sb3304 */3305 strbuf_splice(&sb, 0, 0, bp + 1, endp - (bp + 1));3306 scanp = bp;3307 endp = bp + 1;3308 }3309 ret = show_one_reflog_ent(&sb, fn, cb_data);3310 strbuf_reset(&sb);3311 if (ret)3312 break;3313 }33143315 }3316 if (!ret && sb.len)3317 ret = show_one_reflog_ent(&sb, fn, cb_data);33183319 fclose(logfp);3320 strbuf_release(&sb);3321 return ret;3322}33233324int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn, void *cb_data)3325{3326 FILE *logfp;3327 struct strbuf sb = STRBUF_INIT;3328 int ret = 0;33293330 logfp = fopen(git_path("logs/%s", refname), "r");3331 if (!logfp)3332 return -1;33333334 while (!ret && !strbuf_getwholeline(&sb, logfp, '\n'))3335 ret = show_one_reflog_ent(&sb, fn, cb_data);3336 fclose(logfp);3337 strbuf_release(&sb);3338 return ret;3339}3340/*3341 * Call fn for each reflog in the namespace indicated by name. name3342 * must be empty or end with '/'. Name will be used as a scratch3343 * space, but its contents will be restored before return.3344 */3345static int do_for_each_reflog(struct strbuf *name, each_ref_fn fn, void *cb_data)3346{3347 DIR *d = opendir(git_path("logs/%s", name->buf));3348 int retval = 0;3349 struct dirent *de;3350 int oldlen = name->len;33513352 if (!d)3353 return name->len ? errno : 0;33543355 while ((de = readdir(d)) != NULL) {3356 struct stat st;33573358 if (de->d_name[0] == '.')3359 continue;3360 if (ends_with(de->d_name, ".lock"))3361 continue;3362 strbuf_addstr(name, de->d_name);3363 if (stat(git_path("logs/%s", name->buf), &st) < 0) {3364 ; /* silently ignore */3365 } else {3366 if (S_ISDIR(st.st_mode)) {3367 strbuf_addch(name, '/');3368 retval = do_for_each_reflog(name, fn, cb_data);3369 } else {3370 unsigned char sha1[20];3371 if (read_ref_full(name->buf, sha1, 0, NULL))3372 retval = error("bad ref for %s", name->buf);3373 else3374 retval = fn(name->buf, sha1, 0, cb_data);3375 }3376 if (retval)3377 break;3378 }3379 strbuf_setlen(name, oldlen);3380 }3381 closedir(d);3382 return retval;3383}33843385int for_each_reflog(each_ref_fn fn, void *cb_data)3386{3387 int retval;3388 struct strbuf name;3389 strbuf_init(&name, PATH_MAX);3390 retval = do_for_each_reflog(&name, fn, cb_data);3391 strbuf_release(&name);3392 return retval;3393}33943395/**3396 * Information needed for a single ref update. Set new_sha1 to the3397 * new value or to zero to delete the ref. To check the old value3398 * while locking the ref, set have_old to 1 and set old_sha1 to the3399 * value or to zero to ensure the ref does not exist before update.3400 */3401struct ref_update {3402 unsigned char new_sha1[20];3403 unsigned char old_sha1[20];3404 int flags; /* REF_NODEREF? */3405 int have_old; /* 1 if old_sha1 is valid, 0 otherwise */3406 struct ref_lock *lock;3407 int type;3408 const char refname[FLEX_ARRAY];3409};34103411/*3412 * Transaction states.3413 * OPEN: The transaction is in a valid state and can accept new updates.3414 * An OPEN transaction can be committed.3415 * CLOSED: A closed transaction is no longer active and no other operations3416 * than free can be used on it in this state.3417 * A transaction can either become closed by successfully committing3418 * an active transaction or if there is a failure while building3419 * the transaction thus rendering it failed/inactive.3420 */3421enum ref_transaction_state {3422 REF_TRANSACTION_OPEN = 0,3423 REF_TRANSACTION_CLOSED = 13424};34253426/*3427 * Data structure for holding a reference transaction, which can3428 * consist of checks and updates to multiple references, carried out3429 * as atomically as possible. This structure is opaque to callers.3430 */3431struct ref_transaction {3432 struct ref_update **updates;3433 size_t alloc;3434 size_t nr;3435 enum ref_transaction_state state;3436};34373438struct ref_transaction *ref_transaction_begin(struct strbuf *err)3439{3440 return xcalloc(1, sizeof(struct ref_transaction));3441}34423443void ref_transaction_free(struct ref_transaction *transaction)3444{3445 int i;34463447 if (!transaction)3448 return;34493450 for (i = 0; i < transaction->nr; i++)3451 free(transaction->updates[i]);34523453 free(transaction->updates);3454 free(transaction);3455}34563457static struct ref_update *add_update(struct ref_transaction *transaction,3458 const char *refname)3459{3460 size_t len = strlen(refname);3461 struct ref_update *update = xcalloc(1, sizeof(*update) + len + 1);34623463 strcpy((char *)update->refname, refname);3464 ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);3465 transaction->updates[transaction->nr++] = update;3466 return update;3467}34683469int ref_transaction_update(struct ref_transaction *transaction,3470 const char *refname,3471 const unsigned char *new_sha1,3472 const unsigned char *old_sha1,3473 int flags, int have_old,3474 struct strbuf *err)3475{3476 struct ref_update *update;34773478 if (transaction->state != REF_TRANSACTION_OPEN)3479 die("BUG: update called for transaction that is not open");34803481 if (have_old && !old_sha1)3482 die("BUG: have_old is true but old_sha1 is NULL");34833484 update = add_update(transaction, refname);3485 hashcpy(update->new_sha1, new_sha1);3486 update->flags = flags;3487 update->have_old = have_old;3488 if (have_old)3489 hashcpy(update->old_sha1, old_sha1);3490 return 0;3491}34923493int ref_transaction_create(struct ref_transaction *transaction,3494 const char *refname,3495 const unsigned char *new_sha1,3496 int flags,3497 struct strbuf *err)3498{3499 struct ref_update *update;35003501 if (transaction->state != REF_TRANSACTION_OPEN)3502 die("BUG: create called for transaction that is not open");35033504 if (!new_sha1 || is_null_sha1(new_sha1))3505 die("BUG: create ref with null new_sha1");35063507 update = add_update(transaction, refname);35083509 hashcpy(update->new_sha1, new_sha1);3510 hashclr(update->old_sha1);3511 update->flags = flags;3512 update->have_old = 1;3513 return 0;3514}35153516int ref_transaction_delete(struct ref_transaction *transaction,3517 const char *refname,3518 const unsigned char *old_sha1,3519 int flags, int have_old,3520 struct strbuf *err)3521{3522 struct ref_update *update;35233524 if (transaction->state != REF_TRANSACTION_OPEN)3525 die("BUG: delete called for transaction that is not open");35263527 if (have_old && !old_sha1)3528 die("BUG: have_old is true but old_sha1 is NULL");35293530 update = add_update(transaction, refname);3531 update->flags = flags;3532 update->have_old = have_old;3533 if (have_old) {3534 assert(!is_null_sha1(old_sha1));3535 hashcpy(update->old_sha1, old_sha1);3536 }3537 return 0;3538}35393540int update_ref(const char *action, const char *refname,3541 const unsigned char *sha1, const unsigned char *oldval,3542 int flags, enum action_on_err onerr)3543{3544 struct ref_transaction *t;3545 struct strbuf err = STRBUF_INIT;35463547 t = ref_transaction_begin(&err);3548 if (!t ||3549 ref_transaction_update(t, refname, sha1, oldval, flags,3550 !!oldval, &err) ||3551 ref_transaction_commit(t, action, &err)) {3552 const char *str = "update_ref failed for ref '%s': %s";35533554 ref_transaction_free(t);3555 switch (onerr) {3556 case UPDATE_REFS_MSG_ON_ERR:3557 error(str, refname, err.buf);3558 break;3559 case UPDATE_REFS_DIE_ON_ERR:3560 die(str, refname, err.buf);3561 break;3562 case UPDATE_REFS_QUIET_ON_ERR:3563 break;3564 }3565 strbuf_release(&err);3566 return 1;3567 }3568 strbuf_release(&err);3569 ref_transaction_free(t);3570 return 0;3571}35723573static int ref_update_compare(const void *r1, const void *r2)3574{3575 const struct ref_update * const *u1 = r1;3576 const struct ref_update * const *u2 = r2;3577 return strcmp((*u1)->refname, (*u2)->refname);3578}35793580static int ref_update_reject_duplicates(struct ref_update **updates, int n,3581 struct strbuf *err)3582{3583 int i;3584 for (i = 1; i < n; i++)3585 if (!strcmp(updates[i - 1]->refname, updates[i]->refname)) {3586 const char *str =3587 "Multiple updates for ref '%s' not allowed.";3588 if (err)3589 strbuf_addf(err, str, updates[i]->refname);35903591 return 1;3592 }3593 return 0;3594}35953596int ref_transaction_commit(struct ref_transaction *transaction,3597 const char *msg, struct strbuf *err)3598{3599 int ret = 0, delnum = 0, i;3600 const char **delnames;3601 int n = transaction->nr;3602 struct ref_update **updates = transaction->updates;36033604 if (transaction->state != REF_TRANSACTION_OPEN)3605 die("BUG: commit called for transaction that is not open");36063607 if (!n) {3608 transaction->state = REF_TRANSACTION_CLOSED;3609 return 0;3610 }36113612 /* Allocate work space */3613 delnames = xmalloc(sizeof(*delnames) * n);36143615 /* Copy, sort, and reject duplicate refs */3616 qsort(updates, n, sizeof(*updates), ref_update_compare);3617 ret = ref_update_reject_duplicates(updates, n, err);3618 if (ret)3619 goto cleanup;36203621 /* Acquire all locks while verifying old values */3622 for (i = 0; i < n; i++) {3623 struct ref_update *update = updates[i];36243625 update->lock = lock_any_ref_for_update(update->refname,3626 (update->have_old ?3627 update->old_sha1 :3628 NULL),3629 update->flags,3630 &update->type);3631 if (!update->lock) {3632 if (err)3633 strbuf_addf(err, "Cannot lock the ref '%s'.",3634 update->refname);3635 ret = 1;3636 goto cleanup;3637 }3638 }36393640 /* Perform updates first so live commits remain referenced */3641 for (i = 0; i < n; i++) {3642 struct ref_update *update = updates[i];36433644 if (!is_null_sha1(update->new_sha1)) {3645 ret = write_ref_sha1(update->lock, update->new_sha1,3646 msg);3647 update->lock = NULL; /* freed by write_ref_sha1 */3648 if (ret) {3649 if (err)3650 strbuf_addf(err, "Cannot update the ref '%s'.",3651 update->refname);3652 goto cleanup;3653 }3654 }3655 }36563657 /* Perform deletes now that updates are safely completed */3658 for (i = 0; i < n; i++) {3659 struct ref_update *update = updates[i];36603661 if (update->lock) {3662 ret |= delete_ref_loose(update->lock, update->type);3663 if (!(update->flags & REF_ISPRUNING))3664 delnames[delnum++] = update->lock->ref_name;3665 }3666 }36673668 ret |= repack_without_refs(delnames, delnum, err);3669 for (i = 0; i < delnum; i++)3670 unlink_or_warn(git_path("logs/%s", delnames[i]));3671 clear_loose_ref_cache(&ref_cache);36723673cleanup:3674 transaction->state = REF_TRANSACTION_CLOSED;36753676 for (i = 0; i < n; i++)3677 if (updates[i]->lock)3678 unlock_ref(updates[i]->lock);3679 free(delnames);3680 return ret;3681}36823683char *shorten_unambiguous_ref(const char *refname, int strict)3684{3685 int i;3686 static char **scanf_fmts;3687 static int nr_rules;3688 char *short_name;36893690 if (!nr_rules) {3691 /*3692 * Pre-generate scanf formats from ref_rev_parse_rules[].3693 * Generate a format suitable for scanf from a3694 * ref_rev_parse_rules rule by interpolating "%s" at the3695 * location of the "%.*s".3696 */3697 size_t total_len = 0;3698 size_t offset = 0;36993700 /* the rule list is NULL terminated, count them first */3701 for (nr_rules = 0; ref_rev_parse_rules[nr_rules]; nr_rules++)3702 /* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3703 total_len += strlen(ref_rev_parse_rules[nr_rules]) - 2 + 1;37043705 scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len);37063707 offset = 0;3708 for (i = 0; i < nr_rules; i++) {3709 assert(offset < total_len);3710 scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;3711 offset += snprintf(scanf_fmts[i], total_len - offset,3712 ref_rev_parse_rules[i], 2, "%s") + 1;3713 }3714 }37153716 /* bail out if there are no rules */3717 if (!nr_rules)3718 return xstrdup(refname);37193720 /* buffer for scanf result, at most refname must fit */3721 short_name = xstrdup(refname);37223723 /* skip first rule, it will always match */3724 for (i = nr_rules - 1; i > 0 ; --i) {3725 int j;3726 int rules_to_fail = i;3727 int short_name_len;37283729 if (1 != sscanf(refname, scanf_fmts[i], short_name))3730 continue;37313732 short_name_len = strlen(short_name);37333734 /*3735 * in strict mode, all (except the matched one) rules3736 * must fail to resolve to a valid non-ambiguous ref3737 */3738 if (strict)3739 rules_to_fail = nr_rules;37403741 /*3742 * check if the short name resolves to a valid ref,3743 * but use only rules prior to the matched one3744 */3745 for (j = 0; j < rules_to_fail; j++) {3746 const char *rule = ref_rev_parse_rules[j];3747 char refname[PATH_MAX];37483749 /* skip matched rule */3750 if (i == j)3751 continue;37523753 /*3754 * the short name is ambiguous, if it resolves3755 * (with this previous rule) to a valid ref3756 * read_ref() returns 0 on success3757 */3758 mksnpath(refname, sizeof(refname),3759 rule, short_name_len, short_name);3760 if (ref_exists(refname))3761 break;3762 }37633764 /*3765 * short name is non-ambiguous if all previous rules3766 * haven't resolved to a valid ref3767 */3768 if (j == rules_to_fail)3769 return short_name;3770 }37713772 free(short_name);3773 return xstrdup(refname);3774}37753776static struct string_list *hide_refs;37773778int parse_hide_refs_config(const char *var, const char *value, const char *section)3779{3780 if (!strcmp("transfer.hiderefs", var) ||3781 /* NEEDSWORK: use parse_config_key() once both are merged */3782 (starts_with(var, section) && var[strlen(section)] == '.' &&3783 !strcmp(var + strlen(section), ".hiderefs"))) {3784 char *ref;3785 int len;37863787 if (!value)3788 return config_error_nonbool(var);3789 ref = xstrdup(value);3790 len = strlen(ref);3791 while (len && ref[len - 1] == '/')3792 ref[--len] = '\0';3793 if (!hide_refs) {3794 hide_refs = xcalloc(1, sizeof(*hide_refs));3795 hide_refs->strdup_strings = 1;3796 }3797 string_list_append(hide_refs, ref);3798 }3799 return 0;3800}38013802int ref_is_hidden(const char *refname)3803{3804 struct string_list_item *item;38053806 if (!hide_refs)3807 return 0;3808 for_each_string_list_item(item, hide_refs) {3809 int len;3810 if (!starts_with(refname, item->string))3811 continue;3812 len = strlen(item->string);3813 if (!refname[len] || refname[len] == '/')3814 return 1;3815 }3816 return 0;3817}