1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"../iterator.h" 5#include"../dir-iterator.h" 6#include"../lockfile.h" 7#include"../object.h" 8#include"../dir.h" 9 10struct ref_lock { 11char*ref_name; 12struct lock_file *lk; 13struct object_id old_oid; 14}; 15 16struct ref_entry; 17 18/* 19 * Information used (along with the information in ref_entry) to 20 * describe a single cached reference. This data structure only 21 * occurs embedded in a union in struct ref_entry, and only when 22 * (ref_entry->flag & REF_DIR) is zero. 23 */ 24struct ref_value { 25/* 26 * The name of the object to which this reference resolves 27 * (which may be a tag object). If REF_ISBROKEN, this is 28 * null. If REF_ISSYMREF, then this is the name of the object 29 * referred to by the last reference in the symlink chain. 30 */ 31struct object_id oid; 32 33/* 34 * If REF_KNOWS_PEELED, then this field holds the peeled value 35 * of this reference, or null if the reference is known not to 36 * be peelable. See the documentation for peel_ref() for an 37 * exact definition of "peelable". 38 */ 39struct object_id peeled; 40}; 41 42struct ref_cache; 43 44/* 45 * Information used (along with the information in ref_entry) to 46 * describe a level in the hierarchy of references. This data 47 * structure only occurs embedded in a union in struct ref_entry, and 48 * only when (ref_entry.flag & REF_DIR) is set. In that case, 49 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 50 * in the directory have already been read: 51 * 52 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 53 * or packed references, already read. 54 * 55 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 56 * references that hasn't been read yet (nor has any of its 57 * subdirectories). 58 * 59 * Entries within a directory are stored within a growable array of 60 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 61 * sorted are sorted by their component name in strcmp() order and the 62 * remaining entries are unsorted. 63 * 64 * Loose references are read lazily, one directory at a time. When a 65 * directory of loose references is read, then all of the references 66 * in that directory are stored, and REF_INCOMPLETE stubs are created 67 * for any subdirectories, but the subdirectories themselves are not 68 * read. The reading is triggered by get_ref_dir(). 69 */ 70struct ref_dir { 71int nr, alloc; 72 73/* 74 * Entries with index 0 <= i < sorted are sorted by name. New 75 * entries are appended to the list unsorted, and are sorted 76 * only when required; thus we avoid the need to sort the list 77 * after the addition of every reference. 78 */ 79int sorted; 80 81/* A pointer to the ref_cache that contains this ref_dir. */ 82struct ref_cache *ref_cache; 83 84struct ref_entry **entries; 85}; 86 87/* 88 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 89 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 90 * public values; see refs.h. 91 */ 92 93/* 94 * The field ref_entry->u.value.peeled of this value entry contains 95 * the correct peeled value for the reference, which might be 96 * null_sha1 if the reference is not a tag or if it is broken. 97 */ 98#define REF_KNOWS_PEELED 0x10 99 100/* ref_entry represents a directory of references */ 101#define REF_DIR 0x20 102 103/* 104 * Entry has not yet been read from disk (used only for REF_DIR 105 * entries representing loose references) 106 */ 107#define REF_INCOMPLETE 0x40 108 109/* 110 * A ref_entry represents either a reference or a "subdirectory" of 111 * references. 112 * 113 * Each directory in the reference namespace is represented by a 114 * ref_entry with (flags & REF_DIR) set and containing a subdir member 115 * that holds the entries in that directory that have been read so 116 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 117 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 118 * used for loose reference directories. 119 * 120 * References are represented by a ref_entry with (flags & REF_DIR) 121 * unset and a value member that describes the reference's value. The 122 * flag member is at the ref_entry level, but it is also needed to 123 * interpret the contents of the value field (in other words, a 124 * ref_value object is not very much use without the enclosing 125 * ref_entry). 126 * 127 * Reference names cannot end with slash and directories' names are 128 * always stored with a trailing slash (except for the top-level 129 * directory, which is always denoted by ""). This has two nice 130 * consequences: (1) when the entries in each subdir are sorted 131 * lexicographically by name (as they usually are), the references in 132 * a whole tree can be generated in lexicographic order by traversing 133 * the tree in left-to-right, depth-first order; (2) the names of 134 * references and subdirectories cannot conflict, and therefore the 135 * presence of an empty subdirectory does not block the creation of a 136 * similarly-named reference. (The fact that reference names with the 137 * same leading components can conflict *with each other* is a 138 * separate issue that is regulated by verify_refname_available().) 139 * 140 * Please note that the name field contains the fully-qualified 141 * reference (or subdirectory) name. Space could be saved by only 142 * storing the relative names. But that would require the full names 143 * to be generated on the fly when iterating in do_for_each_ref(), and 144 * would break callback functions, who have always been able to assume 145 * that the name strings that they are passed will not be freed during 146 * the iteration. 147 */ 148struct ref_entry { 149unsigned char flag;/* ISSYMREF? ISPACKED? */ 150union{ 151struct ref_value value;/* if not (flags&REF_DIR) */ 152struct ref_dir subdir;/* if (flags&REF_DIR) */ 153} u; 154/* 155 * The full name of the reference (e.g., "refs/heads/master") 156 * or the full name of the directory with a trailing slash 157 * (e.g., "refs/heads/"): 158 */ 159char name[FLEX_ARRAY]; 160}; 161 162static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 163static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len); 164static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 165const char*dirname,size_t len, 166int incomplete); 167static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry); 168 169static struct ref_dir *get_ref_dir(struct ref_entry *entry) 170{ 171struct ref_dir *dir; 172assert(entry->flag & REF_DIR); 173 dir = &entry->u.subdir; 174if(entry->flag & REF_INCOMPLETE) { 175read_loose_refs(entry->name, dir); 176 177/* 178 * Manually add refs/bisect, which, being 179 * per-worktree, might not appear in the directory 180 * listing for refs/ in the main repo. 181 */ 182if(!strcmp(entry->name,"refs/")) { 183int pos =search_ref_dir(dir,"refs/bisect/",12); 184if(pos <0) { 185struct ref_entry *child_entry; 186 child_entry =create_dir_entry(dir->ref_cache, 187"refs/bisect/", 18812,1); 189add_entry_to_dir(dir, child_entry); 190read_loose_refs("refs/bisect", 191&child_entry->u.subdir); 192} 193} 194 entry->flag &= ~REF_INCOMPLETE; 195} 196return dir; 197} 198 199static struct ref_entry *create_ref_entry(const char*refname, 200const unsigned char*sha1,int flag, 201int check_name) 202{ 203struct ref_entry *ref; 204 205if(check_name && 206check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 207die("Reference has invalid format: '%s'", refname); 208FLEX_ALLOC_STR(ref, name, refname); 209hashcpy(ref->u.value.oid.hash, sha1); 210oidclr(&ref->u.value.peeled); 211 ref->flag = flag; 212return ref; 213} 214 215static voidclear_ref_dir(struct ref_dir *dir); 216 217static voidfree_ref_entry(struct ref_entry *entry) 218{ 219if(entry->flag & REF_DIR) { 220/* 221 * Do not use get_ref_dir() here, as that might 222 * trigger the reading of loose refs. 223 */ 224clear_ref_dir(&entry->u.subdir); 225} 226free(entry); 227} 228 229/* 230 * Add a ref_entry to the end of dir (unsorted). Entry is always 231 * stored directly in dir; no recursion into subdirectories is 232 * done. 233 */ 234static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 235{ 236ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 237 dir->entries[dir->nr++] = entry; 238/* optimize for the case that entries are added in order */ 239if(dir->nr ==1|| 240(dir->nr == dir->sorted +1&& 241strcmp(dir->entries[dir->nr -2]->name, 242 dir->entries[dir->nr -1]->name) <0)) 243 dir->sorted = dir->nr; 244} 245 246/* 247 * Clear and free all entries in dir, recursively. 248 */ 249static voidclear_ref_dir(struct ref_dir *dir) 250{ 251int i; 252for(i =0; i < dir->nr; i++) 253free_ref_entry(dir->entries[i]); 254free(dir->entries); 255 dir->sorted = dir->nr = dir->alloc =0; 256 dir->entries = NULL; 257} 258 259/* 260 * Create a struct ref_entry object for the specified dirname. 261 * dirname is the name of the directory with a trailing slash (e.g., 262 * "refs/heads/") or "" for the top-level directory. 263 */ 264static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 265const char*dirname,size_t len, 266int incomplete) 267{ 268struct ref_entry *direntry; 269FLEX_ALLOC_MEM(direntry, name, dirname, len); 270 direntry->u.subdir.ref_cache = ref_cache; 271 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 272return direntry; 273} 274 275static intref_entry_cmp(const void*a,const void*b) 276{ 277struct ref_entry *one = *(struct ref_entry **)a; 278struct ref_entry *two = *(struct ref_entry **)b; 279returnstrcmp(one->name, two->name); 280} 281 282static voidsort_ref_dir(struct ref_dir *dir); 283 284struct string_slice { 285size_t len; 286const char*str; 287}; 288 289static intref_entry_cmp_sslice(const void*key_,const void*ent_) 290{ 291const struct string_slice *key = key_; 292const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 293int cmp =strncmp(key->str, ent->name, key->len); 294if(cmp) 295return cmp; 296return'\0'- (unsigned char)ent->name[key->len]; 297} 298 299/* 300 * Return the index of the entry with the given refname from the 301 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 302 * no such entry is found. dir must already be complete. 303 */ 304static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 305{ 306struct ref_entry **r; 307struct string_slice key; 308 309if(refname == NULL || !dir->nr) 310return-1; 311 312sort_ref_dir(dir); 313 key.len = len; 314 key.str = refname; 315 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 316 ref_entry_cmp_sslice); 317 318if(r == NULL) 319return-1; 320 321return r - dir->entries; 322} 323 324/* 325 * Search for a directory entry directly within dir (without 326 * recursing). Sort dir if necessary. subdirname must be a directory 327 * name (i.e., end in '/'). If mkdir is set, then create the 328 * directory if it is missing; otherwise, return NULL if the desired 329 * directory cannot be found. dir must already be complete. 330 */ 331static struct ref_dir *search_for_subdir(struct ref_dir *dir, 332const char*subdirname,size_t len, 333int mkdir) 334{ 335int entry_index =search_ref_dir(dir, subdirname, len); 336struct ref_entry *entry; 337if(entry_index == -1) { 338if(!mkdir) 339return NULL; 340/* 341 * Since dir is complete, the absence of a subdir 342 * means that the subdir really doesn't exist; 343 * therefore, create an empty record for it but mark 344 * the record complete. 345 */ 346 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 347add_entry_to_dir(dir, entry); 348}else{ 349 entry = dir->entries[entry_index]; 350} 351returnget_ref_dir(entry); 352} 353 354/* 355 * If refname is a reference name, find the ref_dir within the dir 356 * tree that should hold refname. If refname is a directory name 357 * (i.e., ends in '/'), then return that ref_dir itself. dir must 358 * represent the top-level directory and must already be complete. 359 * Sort ref_dirs and recurse into subdirectories as necessary. If 360 * mkdir is set, then create any missing directories; otherwise, 361 * return NULL if the desired directory cannot be found. 362 */ 363static struct ref_dir *find_containing_dir(struct ref_dir *dir, 364const char*refname,int mkdir) 365{ 366const char*slash; 367for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 368size_t dirnamelen = slash - refname +1; 369struct ref_dir *subdir; 370 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 371if(!subdir) { 372 dir = NULL; 373break; 374} 375 dir = subdir; 376} 377 378return dir; 379} 380 381/* 382 * Find the value entry with the given name in dir, sorting ref_dirs 383 * and recursing into subdirectories as necessary. If the name is not 384 * found or it corresponds to a directory entry, return NULL. 385 */ 386static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 387{ 388int entry_index; 389struct ref_entry *entry; 390 dir =find_containing_dir(dir, refname,0); 391if(!dir) 392return NULL; 393 entry_index =search_ref_dir(dir, refname,strlen(refname)); 394if(entry_index == -1) 395return NULL; 396 entry = dir->entries[entry_index]; 397return(entry->flag & REF_DIR) ? NULL : entry; 398} 399 400/* 401 * Remove the entry with the given name from dir, recursing into 402 * subdirectories as necessary. If refname is the name of a directory 403 * (i.e., ends with '/'), then remove the directory and its contents. 404 * If the removal was successful, return the number of entries 405 * remaining in the directory entry that contained the deleted entry. 406 * If the name was not found, return -1. Please note that this 407 * function only deletes the entry from the cache; it does not delete 408 * it from the filesystem or ensure that other cache entries (which 409 * might be symbolic references to the removed entry) are updated. 410 * Nor does it remove any containing dir entries that might be made 411 * empty by the removal. dir must represent the top-level directory 412 * and must already be complete. 413 */ 414static intremove_entry(struct ref_dir *dir,const char*refname) 415{ 416int refname_len =strlen(refname); 417int entry_index; 418struct ref_entry *entry; 419int is_dir = refname[refname_len -1] =='/'; 420if(is_dir) { 421/* 422 * refname represents a reference directory. Remove 423 * the trailing slash; otherwise we will get the 424 * directory *representing* refname rather than the 425 * one *containing* it. 426 */ 427char*dirname =xmemdupz(refname, refname_len -1); 428 dir =find_containing_dir(dir, dirname,0); 429free(dirname); 430}else{ 431 dir =find_containing_dir(dir, refname,0); 432} 433if(!dir) 434return-1; 435 entry_index =search_ref_dir(dir, refname, refname_len); 436if(entry_index == -1) 437return-1; 438 entry = dir->entries[entry_index]; 439 440memmove(&dir->entries[entry_index], 441&dir->entries[entry_index +1], 442(dir->nr - entry_index -1) *sizeof(*dir->entries) 443); 444 dir->nr--; 445if(dir->sorted > entry_index) 446 dir->sorted--; 447free_ref_entry(entry); 448return dir->nr; 449} 450 451/* 452 * Add a ref_entry to the ref_dir (unsorted), recursing into 453 * subdirectories as necessary. dir must represent the top-level 454 * directory. Return 0 on success. 455 */ 456static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 457{ 458 dir =find_containing_dir(dir, ref->name,1); 459if(!dir) 460return-1; 461add_entry_to_dir(dir, ref); 462return0; 463} 464 465/* 466 * Emit a warning and return true iff ref1 and ref2 have the same name 467 * and the same sha1. Die if they have the same name but different 468 * sha1s. 469 */ 470static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 471{ 472if(strcmp(ref1->name, ref2->name)) 473return0; 474 475/* Duplicate name; make sure that they don't conflict: */ 476 477if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 478/* This is impossible by construction */ 479die("Reference directory conflict:%s", ref1->name); 480 481if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 482die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 483 484warning("Duplicated ref:%s", ref1->name); 485return1; 486} 487 488/* 489 * Sort the entries in dir non-recursively (if they are not already 490 * sorted) and remove any duplicate entries. 491 */ 492static voidsort_ref_dir(struct ref_dir *dir) 493{ 494int i, j; 495struct ref_entry *last = NULL; 496 497/* 498 * This check also prevents passing a zero-length array to qsort(), 499 * which is a problem on some platforms. 500 */ 501if(dir->sorted == dir->nr) 502return; 503 504qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 505 506/* Remove any duplicates: */ 507for(i =0, j =0; j < dir->nr; j++) { 508struct ref_entry *entry = dir->entries[j]; 509if(last &&is_dup_ref(last, entry)) 510free_ref_entry(entry); 511else 512 last = dir->entries[i++] = entry; 513} 514 dir->sorted = dir->nr = i; 515} 516 517/* 518 * Return true if refname, which has the specified oid and flags, can 519 * be resolved to an object in the database. If the referred-to object 520 * does not exist, emit a warning and return false. 521 */ 522static intref_resolves_to_object(const char*refname, 523const struct object_id *oid, 524unsigned int flags) 525{ 526if(flags & REF_ISBROKEN) 527return0; 528if(!has_sha1_file(oid->hash)) { 529error("%sdoes not point to a valid object!", refname); 530return0; 531} 532return1; 533} 534 535/* 536 * Return true if the reference described by entry can be resolved to 537 * an object in the database; otherwise, emit a warning and return 538 * false. 539 */ 540static intentry_resolves_to_object(struct ref_entry *entry) 541{ 542returnref_resolves_to_object(entry->name, 543&entry->u.value.oid, entry->flag); 544} 545 546typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 547 548/* 549 * Call fn for each reference in dir that has index in the range 550 * offset <= index < dir->nr. Recurse into subdirectories that are in 551 * that index range, sorting them before iterating. This function 552 * does not sort dir itself; it should be sorted beforehand. fn is 553 * called for all references, including broken ones. 554 */ 555static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 556 each_ref_entry_fn fn,void*cb_data) 557{ 558int i; 559assert(dir->sorted == dir->nr); 560for(i = offset; i < dir->nr; i++) { 561struct ref_entry *entry = dir->entries[i]; 562int retval; 563if(entry->flag & REF_DIR) { 564struct ref_dir *subdir =get_ref_dir(entry); 565sort_ref_dir(subdir); 566 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 567}else{ 568 retval =fn(entry, cb_data); 569} 570if(retval) 571return retval; 572} 573return0; 574} 575 576/* 577 * Load all of the refs from the dir into our in-memory cache. The hard work 578 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 579 * through all of the sub-directories. We do not even need to care about 580 * sorting, as traversal order does not matter to us. 581 */ 582static voidprime_ref_dir(struct ref_dir *dir) 583{ 584int i; 585for(i =0; i < dir->nr; i++) { 586struct ref_entry *entry = dir->entries[i]; 587if(entry->flag & REF_DIR) 588prime_ref_dir(get_ref_dir(entry)); 589} 590} 591 592/* 593 * A level in the reference hierarchy that is currently being iterated 594 * through. 595 */ 596struct cache_ref_iterator_level { 597/* 598 * The ref_dir being iterated over at this level. The ref_dir 599 * is sorted before being stored here. 600 */ 601struct ref_dir *dir; 602 603/* 604 * The index of the current entry within dir (which might 605 * itself be a directory). If index == -1, then the iteration 606 * hasn't yet begun. If index == dir->nr, then the iteration 607 * through this level is over. 608 */ 609int index; 610}; 611 612/* 613 * Represent an iteration through a ref_dir in the memory cache. The 614 * iteration recurses through subdirectories. 615 */ 616struct cache_ref_iterator { 617struct ref_iterator base; 618 619/* 620 * The number of levels currently on the stack. This is always 621 * at least 1, because when it becomes zero the iteration is 622 * ended and this struct is freed. 623 */ 624size_t levels_nr; 625 626/* The number of levels that have been allocated on the stack */ 627size_t levels_alloc; 628 629/* 630 * A stack of levels. levels[0] is the uppermost level that is 631 * being iterated over in this iteration. (This is not 632 * necessary the top level in the references hierarchy. If we 633 * are iterating through a subtree, then levels[0] will hold 634 * the ref_dir for that subtree, and subsequent levels will go 635 * on from there.) 636 */ 637struct cache_ref_iterator_level *levels; 638}; 639 640static intcache_ref_iterator_advance(struct ref_iterator *ref_iterator) 641{ 642struct cache_ref_iterator *iter = 643(struct cache_ref_iterator *)ref_iterator; 644 645while(1) { 646struct cache_ref_iterator_level *level = 647&iter->levels[iter->levels_nr -1]; 648struct ref_dir *dir = level->dir; 649struct ref_entry *entry; 650 651if(level->index == -1) 652sort_ref_dir(dir); 653 654if(++level->index == level->dir->nr) { 655/* This level is exhausted; pop up a level */ 656if(--iter->levels_nr ==0) 657returnref_iterator_abort(ref_iterator); 658 659continue; 660} 661 662 entry = dir->entries[level->index]; 663 664if(entry->flag & REF_DIR) { 665/* push down a level */ 666ALLOC_GROW(iter->levels, iter->levels_nr +1, 667 iter->levels_alloc); 668 669 level = &iter->levels[iter->levels_nr++]; 670 level->dir =get_ref_dir(entry); 671 level->index = -1; 672}else{ 673 iter->base.refname = entry->name; 674 iter->base.oid = &entry->u.value.oid; 675 iter->base.flags = entry->flag; 676return ITER_OK; 677} 678} 679} 680 681static enum peel_status peel_entry(struct ref_entry *entry,int repeel); 682 683static intcache_ref_iterator_peel(struct ref_iterator *ref_iterator, 684struct object_id *peeled) 685{ 686struct cache_ref_iterator *iter = 687(struct cache_ref_iterator *)ref_iterator; 688struct cache_ref_iterator_level *level; 689struct ref_entry *entry; 690 691 level = &iter->levels[iter->levels_nr -1]; 692 693if(level->index == -1) 694die("BUG: peel called before advance for cache iterator"); 695 696 entry = level->dir->entries[level->index]; 697 698if(peel_entry(entry,0)) 699return-1; 700hashcpy(peeled->hash, entry->u.value.peeled.hash); 701return0; 702} 703 704static intcache_ref_iterator_abort(struct ref_iterator *ref_iterator) 705{ 706struct cache_ref_iterator *iter = 707(struct cache_ref_iterator *)ref_iterator; 708 709free(iter->levels); 710base_ref_iterator_free(ref_iterator); 711return ITER_DONE; 712} 713 714static struct ref_iterator_vtable cache_ref_iterator_vtable = { 715 cache_ref_iterator_advance, 716 cache_ref_iterator_peel, 717 cache_ref_iterator_abort 718}; 719 720static struct ref_iterator *cache_ref_iterator_begin(struct ref_dir *dir) 721{ 722struct cache_ref_iterator *iter; 723struct ref_iterator *ref_iterator; 724struct cache_ref_iterator_level *level; 725 726 iter =xcalloc(1,sizeof(*iter)); 727 ref_iterator = &iter->base; 728base_ref_iterator_init(ref_iterator, &cache_ref_iterator_vtable); 729ALLOC_GROW(iter->levels,10, iter->levels_alloc); 730 731 iter->levels_nr =1; 732 level = &iter->levels[0]; 733 level->index = -1; 734 level->dir = dir; 735 736return ref_iterator; 737} 738 739struct nonmatching_ref_data { 740const struct string_list *skip; 741const char*conflicting_refname; 742}; 743 744static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 745{ 746struct nonmatching_ref_data *data = vdata; 747 748if(data->skip &&string_list_has_string(data->skip, entry->name)) 749return0; 750 751 data->conflicting_refname = entry->name; 752return1; 753} 754 755/* 756 * Return 0 if a reference named refname could be created without 757 * conflicting with the name of an existing reference in dir. 758 * See verify_refname_available for more information. 759 */ 760static intverify_refname_available_dir(const char*refname, 761const struct string_list *extras, 762const struct string_list *skip, 763struct ref_dir *dir, 764struct strbuf *err) 765{ 766const char*slash; 767const char*extra_refname; 768int pos; 769struct strbuf dirname = STRBUF_INIT; 770int ret = -1; 771 772/* 773 * For the sake of comments in this function, suppose that 774 * refname is "refs/foo/bar". 775 */ 776 777assert(err); 778 779strbuf_grow(&dirname,strlen(refname) +1); 780for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 781/* Expand dirname to the new prefix, not including the trailing slash: */ 782strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 783 784/* 785 * We are still at a leading dir of the refname (e.g., 786 * "refs/foo"; if there is a reference with that name, 787 * it is a conflict, *unless* it is in skip. 788 */ 789if(dir) { 790 pos =search_ref_dir(dir, dirname.buf, dirname.len); 791if(pos >=0&& 792(!skip || !string_list_has_string(skip, dirname.buf))) { 793/* 794 * We found a reference whose name is 795 * a proper prefix of refname; e.g., 796 * "refs/foo", and is not in skip. 797 */ 798strbuf_addf(err,"'%s' exists; cannot create '%s'", 799 dirname.buf, refname); 800goto cleanup; 801} 802} 803 804if(extras &&string_list_has_string(extras, dirname.buf) && 805(!skip || !string_list_has_string(skip, dirname.buf))) { 806strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 807 refname, dirname.buf); 808goto cleanup; 809} 810 811/* 812 * Otherwise, we can try to continue our search with 813 * the next component. So try to look up the 814 * directory, e.g., "refs/foo/". If we come up empty, 815 * we know there is nothing under this whole prefix, 816 * but even in that case we still have to continue the 817 * search for conflicts with extras. 818 */ 819strbuf_addch(&dirname,'/'); 820if(dir) { 821 pos =search_ref_dir(dir, dirname.buf, dirname.len); 822if(pos <0) { 823/* 824 * There was no directory "refs/foo/", 825 * so there is nothing under this 826 * whole prefix. So there is no need 827 * to continue looking for conflicting 828 * references. But we need to continue 829 * looking for conflicting extras. 830 */ 831 dir = NULL; 832}else{ 833 dir =get_ref_dir(dir->entries[pos]); 834} 835} 836} 837 838/* 839 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 840 * There is no point in searching for a reference with that 841 * name, because a refname isn't considered to conflict with 842 * itself. But we still need to check for references whose 843 * names are in the "refs/foo/bar/" namespace, because they 844 * *do* conflict. 845 */ 846strbuf_addstr(&dirname, refname + dirname.len); 847strbuf_addch(&dirname,'/'); 848 849if(dir) { 850 pos =search_ref_dir(dir, dirname.buf, dirname.len); 851 852if(pos >=0) { 853/* 854 * We found a directory named "$refname/" 855 * (e.g., "refs/foo/bar/"). It is a problem 856 * iff it contains any ref that is not in 857 * "skip". 858 */ 859struct nonmatching_ref_data data; 860 861 data.skip = skip; 862 data.conflicting_refname = NULL; 863 dir =get_ref_dir(dir->entries[pos]); 864sort_ref_dir(dir); 865if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 866strbuf_addf(err,"'%s' exists; cannot create '%s'", 867 data.conflicting_refname, refname); 868goto cleanup; 869} 870} 871} 872 873 extra_refname =find_descendant_ref(dirname.buf, extras, skip); 874if(extra_refname) 875strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 876 refname, extra_refname); 877else 878 ret =0; 879 880cleanup: 881strbuf_release(&dirname); 882return ret; 883} 884 885struct packed_ref_cache { 886struct ref_entry *root; 887 888/* 889 * Count of references to the data structure in this instance, 890 * including the pointer from ref_cache::packed if any. The 891 * data will not be freed as long as the reference count is 892 * nonzero. 893 */ 894unsigned int referrers; 895 896/* 897 * Iff the packed-refs file associated with this instance is 898 * currently locked for writing, this points at the associated 899 * lock (which is owned by somebody else). The referrer count 900 * is also incremented when the file is locked and decremented 901 * when it is unlocked. 902 */ 903struct lock_file *lock; 904 905/* The metadata from when this packed-refs cache was read */ 906struct stat_validity validity; 907}; 908 909/* 910 * Future: need to be in "struct repository" 911 * when doing a full libification. 912 */ 913static struct ref_cache { 914struct ref_cache *next; 915struct ref_entry *loose; 916struct packed_ref_cache *packed; 917/* 918 * The submodule name, or "" for the main repo. We allocate 919 * length 1 rather than FLEX_ARRAY so that the main ref_cache 920 * is initialized correctly. 921 */ 922char name[1]; 923} ref_cache, *submodule_ref_caches; 924 925/* Lock used for the main packed-refs file: */ 926static struct lock_file packlock; 927 928/* 929 * Increment the reference count of *packed_refs. 930 */ 931static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 932{ 933 packed_refs->referrers++; 934} 935 936/* 937 * Decrease the reference count of *packed_refs. If it goes to zero, 938 * free *packed_refs and return true; otherwise return false. 939 */ 940static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 941{ 942if(!--packed_refs->referrers) { 943free_ref_entry(packed_refs->root); 944stat_validity_clear(&packed_refs->validity); 945free(packed_refs); 946return1; 947}else{ 948return0; 949} 950} 951 952static voidclear_packed_ref_cache(struct ref_cache *refs) 953{ 954if(refs->packed) { 955struct packed_ref_cache *packed_refs = refs->packed; 956 957if(packed_refs->lock) 958die("internal error: packed-ref cache cleared while locked"); 959 refs->packed = NULL; 960release_packed_ref_cache(packed_refs); 961} 962} 963 964static voidclear_loose_ref_cache(struct ref_cache *refs) 965{ 966if(refs->loose) { 967free_ref_entry(refs->loose); 968 refs->loose = NULL; 969} 970} 971 972/* 973 * Create a new submodule ref cache and add it to the internal 974 * set of caches. 975 */ 976static struct ref_cache *create_ref_cache(const char*submodule) 977{ 978struct ref_cache *refs; 979if(!submodule) 980 submodule =""; 981FLEX_ALLOC_STR(refs, name, submodule); 982 refs->next = submodule_ref_caches; 983 submodule_ref_caches = refs; 984return refs; 985} 986 987static struct ref_cache *lookup_ref_cache(const char*submodule) 988{ 989struct ref_cache *refs; 990 991if(!submodule || !*submodule) 992return&ref_cache; 993 994for(refs = submodule_ref_caches; refs; refs = refs->next) 995if(!strcmp(submodule, refs->name)) 996return refs; 997return NULL; 998} 9991000/*1001 * Return a pointer to a ref_cache for the specified submodule. For1002 * the main repository, use submodule==NULL; such a call cannot fail.1003 * For a submodule, the submodule must exist and be a nonbare1004 * repository, otherwise return NULL.1005 *1006 * The returned structure will be allocated and initialized but not1007 * necessarily populated; it should not be freed.1008 */1009static struct ref_cache *get_ref_cache(const char*submodule)1010{1011struct ref_cache *refs =lookup_ref_cache(submodule);10121013if(!refs) {1014struct strbuf submodule_sb = STRBUF_INIT;10151016strbuf_addstr(&submodule_sb, submodule);1017if(is_nonbare_repository_dir(&submodule_sb))1018 refs =create_ref_cache(submodule);1019strbuf_release(&submodule_sb);1020}10211022return 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(struct strbuf *line,unsigned char*sha1)1041{1042const char*ref;10431044/*1045 * 42: the answer to everything.1046 *1047 * In this case, it happens to be the answer to1048 * 40 (length of sha1 hex representation)1049 * +1 (space in between hex and name)1050 * +1 (newline at the end of the line)1051 */1052if(line->len <=42)1053return NULL;10541055if(get_sha1_hex(line->buf, sha1) <0)1056return NULL;1057if(!isspace(line->buf[40]))1058return NULL;10591060 ref = line->buf +41;1061if(isspace(*ref))1062return NULL;10631064if(line->buf[line->len -1] !='\n')1065return NULL;1066 line->buf[--line->len] =0;10671068return ref;1069}10701071/*1072 * Read f, which is a packed-refs file, into dir.1073 *1074 * A comment line of the form "# pack-refs with: " may contain zero or1075 * more traits. We interpret the traits as follows:1076 *1077 * No traits:1078 *1079 * Probably no references are peeled. But if the file contains a1080 * peeled value for a reference, we will use it.1081 *1082 * peeled:1083 *1084 * References under "refs/tags/", if they *can* be peeled, *are*1085 * peeled in this file. References outside of "refs/tags/" are1086 * probably not peeled even if they could have been, but if we find1087 * a peeled value for such a reference we will use it.1088 *1089 * fully-peeled:1090 *1091 * All references in the file that can be peeled are peeled.1092 * Inversely (and this is more important), any references in the1093 * file for which no peeled value is recorded is not peelable. This1094 * trait should typically be written alongside "peeled" for1095 * compatibility with older clients, but we do not require it1096 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1097 */1098static voidread_packed_refs(FILE*f,struct ref_dir *dir)1099{1100struct ref_entry *last = NULL;1101struct strbuf line = STRBUF_INIT;1102enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11031104while(strbuf_getwholeline(&line, f,'\n') != EOF) {1105unsigned char sha1[20];1106const char*refname;1107const char*traits;11081109if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1110if(strstr(traits," fully-peeled "))1111 peeled = PEELED_FULLY;1112else if(strstr(traits," peeled "))1113 peeled = PEELED_TAGS;1114/* perhaps other traits later as well */1115continue;1116}11171118 refname =parse_ref_line(&line, sha1);1119if(refname) {1120int flag = REF_ISPACKED;11211122if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1123if(!refname_is_safe(refname))1124die("packed refname is dangerous:%s", refname);1125hashclr(sha1);1126 flag |= REF_BAD_NAME | REF_ISBROKEN;1127}1128 last =create_ref_entry(refname, sha1, flag,0);1129if(peeled == PEELED_FULLY ||1130(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1131 last->flag |= REF_KNOWS_PEELED;1132add_ref(dir, last);1133continue;1134}1135if(last &&1136 line.buf[0] =='^'&&1137 line.len == PEELED_LINE_LENGTH &&1138 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1139!get_sha1_hex(line.buf +1, sha1)) {1140hashcpy(last->u.value.peeled.hash, sha1);1141/*1142 * Regardless of what the file header said,1143 * we definitely know the value of *this*1144 * reference:1145 */1146 last->flag |= REF_KNOWS_PEELED;1147}1148}11491150strbuf_release(&line);1151}11521153/*1154 * Get the packed_ref_cache for the specified ref_cache, creating it1155 * if necessary.1156 */1157static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1158{1159char*packed_refs_file;11601161if(*refs->name)1162 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1163else1164 packed_refs_file =git_pathdup("packed-refs");11651166if(refs->packed &&1167!stat_validity_check(&refs->packed->validity, packed_refs_file))1168clear_packed_ref_cache(refs);11691170if(!refs->packed) {1171FILE*f;11721173 refs->packed =xcalloc(1,sizeof(*refs->packed));1174acquire_packed_ref_cache(refs->packed);1175 refs->packed->root =create_dir_entry(refs,"",0,0);1176 f =fopen(packed_refs_file,"r");1177if(f) {1178stat_validity_update(&refs->packed->validity,fileno(f));1179read_packed_refs(f,get_ref_dir(refs->packed->root));1180fclose(f);1181}1182}1183free(packed_refs_file);1184return refs->packed;1185}11861187static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1188{1189returnget_ref_dir(packed_ref_cache->root);1190}11911192static struct ref_dir *get_packed_refs(struct ref_cache *refs)1193{1194returnget_packed_ref_dir(get_packed_ref_cache(refs));1195}11961197/*1198 * Add a reference to the in-memory packed reference cache. This may1199 * only be called while the packed-refs file is locked (see1200 * lock_packed_refs()). To actually write the packed-refs file, call1201 * commit_packed_refs().1202 */1203static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1204{1205struct packed_ref_cache *packed_ref_cache =1206get_packed_ref_cache(&ref_cache);12071208if(!packed_ref_cache->lock)1209die("internal error: packed refs not locked");1210add_ref(get_packed_ref_dir(packed_ref_cache),1211create_ref_entry(refname, sha1, REF_ISPACKED,1));1212}12131214/*1215 * Read the loose references from the namespace dirname into dir1216 * (without recursing). dirname must end with '/'. dir must be the1217 * directory entry corresponding to dirname.1218 */1219static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1220{1221struct ref_cache *refs = dir->ref_cache;1222DIR*d;1223struct dirent *de;1224int dirnamelen =strlen(dirname);1225struct strbuf refname;1226struct strbuf path = STRBUF_INIT;1227size_t path_baselen;1228int err =0;12291230if(*refs->name)1231 err =strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1232else1233strbuf_git_path(&path,"%s", dirname);1234 path_baselen = path.len;12351236if(err) {1237strbuf_release(&path);1238return;1239}12401241 d =opendir(path.buf);1242if(!d) {1243strbuf_release(&path);1244return;1245}12461247strbuf_init(&refname, dirnamelen +257);1248strbuf_add(&refname, dirname, dirnamelen);12491250while((de =readdir(d)) != NULL) {1251unsigned char sha1[20];1252struct stat st;1253int flag;12541255if(de->d_name[0] =='.')1256continue;1257if(ends_with(de->d_name,".lock"))1258continue;1259strbuf_addstr(&refname, de->d_name);1260strbuf_addstr(&path, de->d_name);1261if(stat(path.buf, &st) <0) {1262;/* silently ignore */1263}else if(S_ISDIR(st.st_mode)) {1264strbuf_addch(&refname,'/');1265add_entry_to_dir(dir,1266create_dir_entry(refs, refname.buf,1267 refname.len,1));1268}else{1269int read_ok;12701271if(*refs->name) {1272hashclr(sha1);1273 flag =0;1274 read_ok = !resolve_gitlink_ref(refs->name,1275 refname.buf, sha1);1276}else{1277 read_ok = !read_ref_full(refname.buf,1278 RESOLVE_REF_READING,1279 sha1, &flag);1280}12811282if(!read_ok) {1283hashclr(sha1);1284 flag |= REF_ISBROKEN;1285}else if(is_null_sha1(sha1)) {1286/*1287 * It is so astronomically unlikely1288 * that NULL_SHA1 is the SHA-1 of an1289 * actual object that we consider its1290 * appearance in a loose reference1291 * file to be repo corruption1292 * (probably due to a software bug).1293 */1294 flag |= REF_ISBROKEN;1295}12961297if(check_refname_format(refname.buf,1298 REFNAME_ALLOW_ONELEVEL)) {1299if(!refname_is_safe(refname.buf))1300die("loose refname is dangerous:%s", refname.buf);1301hashclr(sha1);1302 flag |= REF_BAD_NAME | REF_ISBROKEN;1303}1304add_entry_to_dir(dir,1305create_ref_entry(refname.buf, sha1, flag,0));1306}1307strbuf_setlen(&refname, dirnamelen);1308strbuf_setlen(&path, path_baselen);1309}1310strbuf_release(&refname);1311strbuf_release(&path);1312closedir(d);1313}13141315static struct ref_dir *get_loose_refs(struct ref_cache *refs)1316{1317if(!refs->loose) {1318/*1319 * Mark the top-level directory complete because we1320 * are about to read the only subdirectory that can1321 * hold references:1322 */1323 refs->loose =create_dir_entry(refs,"",0,0);1324/*1325 * Create an incomplete entry for "refs/":1326 */1327add_entry_to_dir(get_ref_dir(refs->loose),1328create_dir_entry(refs,"refs/",5,1));1329}1330returnget_ref_dir(refs->loose);1331}13321333#define MAXREFLEN (1024)13341335/*1336 * Called by resolve_gitlink_ref_recursive() after it failed to read1337 * from the loose refs in ref_cache refs. Find <refname> in the1338 * packed-refs file for the submodule.1339 */1340static intresolve_gitlink_packed_ref(struct ref_cache *refs,1341const char*refname,unsigned char*sha1)1342{1343struct ref_entry *ref;1344struct ref_dir *dir =get_packed_refs(refs);13451346 ref =find_ref(dir, refname);1347if(ref == NULL)1348return-1;13491350hashcpy(sha1, ref->u.value.oid.hash);1351return0;1352}13531354static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1355const char*refname,unsigned char*sha1,1356int recursion)1357{1358int fd, len;1359char buffer[128], *p;1360char*path;13611362if(recursion > SYMREF_MAXDEPTH ||strlen(refname) > MAXREFLEN)1363return-1;1364 path = *refs->name1365?git_pathdup_submodule(refs->name,"%s", refname)1366:git_pathdup("%s", refname);1367 fd =open(path, O_RDONLY);1368free(path);1369if(fd <0)1370returnresolve_gitlink_packed_ref(refs, refname, sha1);13711372 len =read(fd, buffer,sizeof(buffer)-1);1373close(fd);1374if(len <0)1375return-1;1376while(len &&isspace(buffer[len-1]))1377 len--;1378 buffer[len] =0;13791380/* Was it a detached head or an old-fashioned symlink? */1381if(!get_sha1_hex(buffer, sha1))1382return0;13831384/* Symref? */1385if(strncmp(buffer,"ref:",4))1386return-1;1387 p = buffer +4;1388while(isspace(*p))1389 p++;13901391returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1392}13931394intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1395{1396int len =strlen(path), retval;1397struct strbuf submodule = STRBUF_INIT;1398struct ref_cache *refs;13991400while(len && path[len-1] =='/')1401 len--;1402if(!len)1403return-1;14041405strbuf_add(&submodule, path, len);1406 refs =get_ref_cache(submodule.buf);1407if(!refs) {1408strbuf_release(&submodule);1409return-1;1410}1411strbuf_release(&submodule);14121413 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1414return retval;1415}14161417/*1418 * Return the ref_entry for the given refname from the packed1419 * references. If it does not exist, return NULL.1420 */1421static struct ref_entry *get_packed_ref(const char*refname)1422{1423returnfind_ref(get_packed_refs(&ref_cache), refname);1424}14251426/*1427 * A loose ref file doesn't exist; check for a packed ref.1428 */1429static intresolve_missing_loose_ref(const char*refname,1430unsigned char*sha1,1431unsigned int*flags)1432{1433struct ref_entry *entry;14341435/*1436 * The loose reference file does not exist; check for a packed1437 * reference.1438 */1439 entry =get_packed_ref(refname);1440if(entry) {1441hashcpy(sha1, entry->u.value.oid.hash);1442*flags |= REF_ISPACKED;1443return0;1444}1445/* refname is not a packed reference. */1446return-1;1447}14481449intread_raw_ref(const char*refname,unsigned char*sha1,1450struct strbuf *referent,unsigned int*type)1451{1452struct strbuf sb_contents = STRBUF_INIT;1453struct strbuf sb_path = STRBUF_INIT;1454const char*path;1455const char*buf;1456struct stat st;1457int fd;1458int ret = -1;1459int save_errno;14601461*type =0;1462strbuf_reset(&sb_path);1463strbuf_git_path(&sb_path,"%s", refname);1464 path = sb_path.buf;14651466stat_ref:1467/*1468 * We might have to loop back here to avoid a race1469 * condition: first we lstat() the file, then we try1470 * to read it as a link or as a file. But if somebody1471 * changes the type of the file (file <-> directory1472 * <-> symlink) between the lstat() and reading, then1473 * we don't want to report that as an error but rather1474 * try again starting with the lstat().1475 */14761477if(lstat(path, &st) <0) {1478if(errno != ENOENT)1479goto out;1480if(resolve_missing_loose_ref(refname, sha1, type)) {1481 errno = ENOENT;1482goto out;1483}1484 ret =0;1485goto out;1486}14871488/* Follow "normalized" - ie "refs/.." symlinks by hand */1489if(S_ISLNK(st.st_mode)) {1490strbuf_reset(&sb_contents);1491if(strbuf_readlink(&sb_contents, path,0) <0) {1492if(errno == ENOENT || errno == EINVAL)1493/* inconsistent with lstat; retry */1494goto stat_ref;1495else1496goto out;1497}1498if(starts_with(sb_contents.buf,"refs/") &&1499!check_refname_format(sb_contents.buf,0)) {1500strbuf_swap(&sb_contents, referent);1501*type |= REF_ISSYMREF;1502 ret =0;1503goto out;1504}1505}15061507/* Is it a directory? */1508if(S_ISDIR(st.st_mode)) {1509/*1510 * Even though there is a directory where the loose1511 * ref is supposed to be, there could still be a1512 * packed ref:1513 */1514if(resolve_missing_loose_ref(refname, sha1, type)) {1515 errno = EISDIR;1516goto out;1517}1518 ret =0;1519goto out;1520}15211522/*1523 * Anything else, just open it and try to use it as1524 * a ref1525 */1526 fd =open(path, O_RDONLY);1527if(fd <0) {1528if(errno == ENOENT)1529/* inconsistent with lstat; retry */1530goto stat_ref;1531else1532goto out;1533}1534strbuf_reset(&sb_contents);1535if(strbuf_read(&sb_contents, fd,256) <0) {1536int save_errno = errno;1537close(fd);1538 errno = save_errno;1539goto out;1540}1541close(fd);1542strbuf_rtrim(&sb_contents);1543 buf = sb_contents.buf;1544if(starts_with(buf,"ref:")) {1545 buf +=4;1546while(isspace(*buf))1547 buf++;15481549strbuf_reset(referent);1550strbuf_addstr(referent, buf);1551*type |= REF_ISSYMREF;1552 ret =0;1553goto out;1554}15551556/*1557 * Please note that FETCH_HEAD has additional1558 * data after the sha.1559 */1560if(get_sha1_hex(buf, sha1) ||1561(buf[40] !='\0'&& !isspace(buf[40]))) {1562*type |= REF_ISBROKEN;1563 errno = EINVAL;1564goto out;1565}15661567 ret =0;15681569out:1570 save_errno = errno;1571strbuf_release(&sb_path);1572strbuf_release(&sb_contents);1573 errno = save_errno;1574return ret;1575}15761577static voidunlock_ref(struct ref_lock *lock)1578{1579/* Do not free lock->lk -- atexit() still looks at them */1580if(lock->lk)1581rollback_lock_file(lock->lk);1582free(lock->ref_name);1583free(lock);1584}15851586/*1587 * Lock refname, without following symrefs, and set *lock_p to point1588 * at a newly-allocated lock object. Fill in lock->old_oid, referent,1589 * and type similarly to read_raw_ref().1590 *1591 * The caller must verify that refname is a "safe" reference name (in1592 * the sense of refname_is_safe()) before calling this function.1593 *1594 * If the reference doesn't already exist, verify that refname doesn't1595 * have a D/F conflict with any existing references. extras and skip1596 * are passed to verify_refname_available_dir() for this check.1597 *1598 * If mustexist is not set and the reference is not found or is1599 * broken, lock the reference anyway but clear sha1.1600 *1601 * Return 0 on success. On failure, write an error message to err and1602 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.1603 *1604 * Implementation note: This function is basically1605 *1606 * lock reference1607 * read_raw_ref()1608 *1609 * but it includes a lot more code to1610 * - Deal with possible races with other processes1611 * - Avoid calling verify_refname_available_dir() when it can be1612 * avoided, namely if we were successfully able to read the ref1613 * - Generate informative error messages in the case of failure1614 */1615static intlock_raw_ref(const char*refname,int mustexist,1616const struct string_list *extras,1617const struct string_list *skip,1618struct ref_lock **lock_p,1619struct strbuf *referent,1620unsigned int*type,1621struct strbuf *err)1622{1623struct ref_lock *lock;1624struct strbuf ref_file = STRBUF_INIT;1625int attempts_remaining =3;1626int ret = TRANSACTION_GENERIC_ERROR;16271628assert(err);1629*type =0;16301631/* First lock the file so it can't change out from under us. */16321633*lock_p = lock =xcalloc(1,sizeof(*lock));16341635 lock->ref_name =xstrdup(refname);1636strbuf_git_path(&ref_file,"%s", refname);16371638retry:1639switch(safe_create_leading_directories(ref_file.buf)) {1640case SCLD_OK:1641break;/* success */1642case SCLD_EXISTS:1643/*1644 * Suppose refname is "refs/foo/bar". We just failed1645 * to create the containing directory, "refs/foo",1646 * because there was a non-directory in the way. This1647 * indicates a D/F conflict, probably because of1648 * another reference such as "refs/foo". There is no1649 * reason to expect this error to be transitory.1650 */1651if(verify_refname_available(refname, extras, skip, err)) {1652if(mustexist) {1653/*1654 * To the user the relevant error is1655 * that the "mustexist" reference is1656 * missing:1657 */1658strbuf_reset(err);1659strbuf_addf(err,"unable to resolve reference '%s'",1660 refname);1661}else{1662/*1663 * The error message set by1664 * verify_refname_available_dir() is OK.1665 */1666 ret = TRANSACTION_NAME_CONFLICT;1667}1668}else{1669/*1670 * The file that is in the way isn't a loose1671 * reference. Report it as a low-level1672 * failure.1673 */1674strbuf_addf(err,"unable to create lock file%s.lock; "1675"non-directory in the way",1676 ref_file.buf);1677}1678goto error_return;1679case SCLD_VANISHED:1680/* Maybe another process was tidying up. Try again. */1681if(--attempts_remaining >0)1682goto retry;1683/* fall through */1684default:1685strbuf_addf(err,"unable to create directory for%s",1686 ref_file.buf);1687goto error_return;1688}16891690if(!lock->lk)1691 lock->lk =xcalloc(1,sizeof(struct lock_file));16921693if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) {1694if(errno == ENOENT && --attempts_remaining >0) {1695/*1696 * Maybe somebody just deleted one of the1697 * directories leading to ref_file. Try1698 * again:1699 */1700goto retry;1701}else{1702unable_to_lock_message(ref_file.buf, errno, err);1703goto error_return;1704}1705}17061707/*1708 * Now we hold the lock and can read the reference without1709 * fear that its value will change.1710 */17111712if(read_raw_ref(refname, lock->old_oid.hash, referent, type)) {1713if(errno == ENOENT) {1714if(mustexist) {1715/* Garden variety missing reference. */1716strbuf_addf(err,"unable to resolve reference '%s'",1717 refname);1718goto error_return;1719}else{1720/*1721 * Reference is missing, but that's OK. We1722 * know that there is not a conflict with1723 * another loose reference because1724 * (supposing that we are trying to lock1725 * reference "refs/foo/bar"):1726 *1727 * - We were successfully able to create1728 * the lockfile refs/foo/bar.lock, so we1729 * know there cannot be a loose reference1730 * named "refs/foo".1731 *1732 * - We got ENOENT and not EISDIR, so we1733 * know that there cannot be a loose1734 * reference named "refs/foo/bar/baz".1735 */1736}1737}else if(errno == EISDIR) {1738/*1739 * There is a directory in the way. It might have1740 * contained references that have been deleted. If1741 * we don't require that the reference already1742 * exists, try to remove the directory so that it1743 * doesn't cause trouble when we want to rename the1744 * lockfile into place later.1745 */1746if(mustexist) {1747/* Garden variety missing reference. */1748strbuf_addf(err,"unable to resolve reference '%s'",1749 refname);1750goto error_return;1751}else if(remove_dir_recursively(&ref_file,1752 REMOVE_DIR_EMPTY_ONLY)) {1753if(verify_refname_available_dir(1754 refname, extras, skip,1755get_loose_refs(&ref_cache),1756 err)) {1757/*1758 * The error message set by1759 * verify_refname_available() is OK.1760 */1761 ret = TRANSACTION_NAME_CONFLICT;1762goto error_return;1763}else{1764/*1765 * We can't delete the directory,1766 * but we also don't know of any1767 * references that it should1768 * contain.1769 */1770strbuf_addf(err,"there is a non-empty directory '%s' "1771"blocking reference '%s'",1772 ref_file.buf, refname);1773goto error_return;1774}1775}1776}else if(errno == EINVAL && (*type & REF_ISBROKEN)) {1777strbuf_addf(err,"unable to resolve reference '%s': "1778"reference broken", refname);1779goto error_return;1780}else{1781strbuf_addf(err,"unable to resolve reference '%s':%s",1782 refname,strerror(errno));1783goto error_return;1784}17851786/*1787 * If the ref did not exist and we are creating it,1788 * make sure there is no existing packed ref whose1789 * name begins with our refname, nor a packed ref1790 * whose name is a proper prefix of our refname.1791 */1792if(verify_refname_available_dir(1793 refname, extras, skip,1794get_packed_refs(&ref_cache),1795 err)) {1796goto error_return;1797}1798}17991800 ret =0;1801goto out;18021803error_return:1804unlock_ref(lock);1805*lock_p = NULL;18061807out:1808strbuf_release(&ref_file);1809return ret;1810}18111812/*1813 * Peel the entry (if possible) and return its new peel_status. If1814 * repeel is true, re-peel the entry even if there is an old peeled1815 * value that is already stored in it.1816 *1817 * It is OK to call this function with a packed reference entry that1818 * might be stale and might even refer to an object that has since1819 * been garbage-collected. In such a case, if the entry has1820 * REF_KNOWS_PEELED then leave the status unchanged and return1821 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1822 */1823static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1824{1825enum peel_status status;18261827if(entry->flag & REF_KNOWS_PEELED) {1828if(repeel) {1829 entry->flag &= ~REF_KNOWS_PEELED;1830oidclr(&entry->u.value.peeled);1831}else{1832returnis_null_oid(&entry->u.value.peeled) ?1833 PEEL_NON_TAG : PEEL_PEELED;1834}1835}1836if(entry->flag & REF_ISBROKEN)1837return PEEL_BROKEN;1838if(entry->flag & REF_ISSYMREF)1839return PEEL_IS_SYMREF;18401841 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1842if(status == PEEL_PEELED || status == PEEL_NON_TAG)1843 entry->flag |= REF_KNOWS_PEELED;1844return status;1845}18461847intpeel_ref(const char*refname,unsigned char*sha1)1848{1849int flag;1850unsigned char base[20];18511852if(current_ref_iter && current_ref_iter->refname == refname) {1853struct object_id peeled;18541855if(ref_iterator_peel(current_ref_iter, &peeled))1856return-1;1857hashcpy(sha1, peeled.hash);1858return0;1859}18601861if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1862return-1;18631864/*1865 * If the reference is packed, read its ref_entry from the1866 * cache in the hope that we already know its peeled value.1867 * We only try this optimization on packed references because1868 * (a) forcing the filling of the loose reference cache could1869 * be expensive and (b) loose references anyway usually do not1870 * have REF_KNOWS_PEELED.1871 */1872if(flag & REF_ISPACKED) {1873struct ref_entry *r =get_packed_ref(refname);1874if(r) {1875if(peel_entry(r,0))1876return-1;1877hashcpy(sha1, r->u.value.peeled.hash);1878return0;1879}1880}18811882returnpeel_object(base, sha1);1883}18841885struct files_ref_iterator {1886struct ref_iterator base;18871888struct packed_ref_cache *packed_ref_cache;1889struct ref_iterator *iter0;1890unsigned int flags;1891};18921893static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1894{1895struct files_ref_iterator *iter =1896(struct files_ref_iterator *)ref_iterator;1897int ok;18981899while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1900if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1901!ref_resolves_to_object(iter->iter0->refname,1902 iter->iter0->oid,1903 iter->iter0->flags))1904continue;19051906 iter->base.refname = iter->iter0->refname;1907 iter->base.oid = iter->iter0->oid;1908 iter->base.flags = iter->iter0->flags;1909return ITER_OK;1910}19111912 iter->iter0 = NULL;1913if(ref_iterator_abort(ref_iterator) != ITER_DONE)1914 ok = ITER_ERROR;19151916return ok;1917}19181919static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1920struct object_id *peeled)1921{1922struct files_ref_iterator *iter =1923(struct files_ref_iterator *)ref_iterator;19241925returnref_iterator_peel(iter->iter0, peeled);1926}19271928static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1929{1930struct files_ref_iterator *iter =1931(struct files_ref_iterator *)ref_iterator;1932int ok = ITER_DONE;19331934if(iter->iter0)1935 ok =ref_iterator_abort(iter->iter0);19361937release_packed_ref_cache(iter->packed_ref_cache);1938base_ref_iterator_free(ref_iterator);1939return ok;1940}19411942static struct ref_iterator_vtable files_ref_iterator_vtable = {1943 files_ref_iterator_advance,1944 files_ref_iterator_peel,1945 files_ref_iterator_abort1946};19471948struct ref_iterator *files_ref_iterator_begin(1949const char*submodule,1950const char*prefix,unsigned int flags)1951{1952struct ref_cache *refs =get_ref_cache(submodule);1953struct ref_dir *loose_dir, *packed_dir;1954struct ref_iterator *loose_iter, *packed_iter;1955struct files_ref_iterator *iter;1956struct ref_iterator *ref_iterator;19571958if(!refs)1959returnempty_ref_iterator_begin();19601961if(ref_paranoia <0)1962 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1963if(ref_paranoia)1964 flags |= DO_FOR_EACH_INCLUDE_BROKEN;19651966 iter =xcalloc(1,sizeof(*iter));1967 ref_iterator = &iter->base;1968base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);19691970/*1971 * We must make sure that all loose refs are read before1972 * accessing the packed-refs file; this avoids a race1973 * condition if loose refs are migrated to the packed-refs1974 * file by a simultaneous process, but our in-memory view is1975 * from before the migration. We ensure this as follows:1976 * First, we call prime_ref_dir(), which pre-reads the loose1977 * references for the subtree into the cache. (If they've1978 * already been read, that's OK; we only need to guarantee1979 * that they're read before the packed refs, not *how much*1980 * before.) After that, we call get_packed_ref_cache(), which1981 * internally checks whether the packed-ref cache is up to1982 * date with what is on disk, and re-reads it if not.1983 */19841985 loose_dir =get_loose_refs(refs);19861987if(prefix && *prefix)1988 loose_dir =find_containing_dir(loose_dir, prefix,0);19891990if(loose_dir) {1991prime_ref_dir(loose_dir);1992 loose_iter =cache_ref_iterator_begin(loose_dir);1993}else{1994/* There's nothing to iterate over. */1995 loose_iter =empty_ref_iterator_begin();1996}19971998 iter->packed_ref_cache =get_packed_ref_cache(refs);1999acquire_packed_ref_cache(iter->packed_ref_cache);2000 packed_dir =get_packed_ref_dir(iter->packed_ref_cache);20012002if(prefix && *prefix)2003 packed_dir =find_containing_dir(packed_dir, prefix,0);20042005if(packed_dir) {2006 packed_iter =cache_ref_iterator_begin(packed_dir);2007}else{2008/* There's nothing to iterate over. */2009 packed_iter =empty_ref_iterator_begin();2010}20112012 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);2013 iter->flags = flags;20142015return ref_iterator;2016}20172018/*2019 * Verify that the reference locked by lock has the value old_sha1.2020 * Fail if the reference doesn't exist and mustexist is set. Return 02021 * on success. On error, write an error message to err, set errno, and2022 * return a negative value.2023 */2024static intverify_lock(struct ref_lock *lock,2025const unsigned char*old_sha1,int mustexist,2026struct strbuf *err)2027{2028assert(err);20292030if(read_ref_full(lock->ref_name,2031 mustexist ? RESOLVE_REF_READING :0,2032 lock->old_oid.hash, NULL)) {2033if(old_sha1) {2034int save_errno = errno;2035strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);2036 errno = save_errno;2037return-1;2038}else{2039oidclr(&lock->old_oid);2040return0;2041}2042}2043if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {2044strbuf_addf(err,"ref '%s' is at%sbut expected%s",2045 lock->ref_name,2046oid_to_hex(&lock->old_oid),2047sha1_to_hex(old_sha1));2048 errno = EBUSY;2049return-1;2050}2051return0;2052}20532054static intremove_empty_directories(struct strbuf *path)2055{2056/*2057 * we want to create a file but there is a directory there;2058 * if that is an empty directory (or a directory that contains2059 * only empty directories), remove them.2060 */2061returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);2062}20632064/*2065 * Locks a ref returning the lock on success and NULL on failure.2066 * On failure errno is set to something meaningful.2067 */2068static struct ref_lock *lock_ref_sha1_basic(const char*refname,2069const unsigned char*old_sha1,2070const struct string_list *extras,2071const struct string_list *skip,2072unsigned int flags,int*type,2073struct strbuf *err)2074{2075struct strbuf ref_file = STRBUF_INIT;2076struct ref_lock *lock;2077int last_errno =0;2078int lflags = LOCK_NO_DEREF;2079int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2080int resolve_flags = RESOLVE_REF_NO_RECURSE;2081int attempts_remaining =3;2082int resolved;20832084assert(err);20852086 lock =xcalloc(1,sizeof(struct ref_lock));20872088if(mustexist)2089 resolve_flags |= RESOLVE_REF_READING;2090if(flags & REF_DELETING)2091 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;20922093strbuf_git_path(&ref_file,"%s", refname);2094 resolved = !!resolve_ref_unsafe(refname, resolve_flags,2095 lock->old_oid.hash, type);2096if(!resolved && errno == EISDIR) {2097/*2098 * we are trying to lock foo but we used to2099 * have foo/bar which now does not exist;2100 * it is normal for the empty directory 'foo'2101 * to remain.2102 */2103if(remove_empty_directories(&ref_file)) {2104 last_errno = errno;2105if(!verify_refname_available_dir(refname, extras, skip,2106get_loose_refs(&ref_cache), err))2107strbuf_addf(err,"there are still refs under '%s'",2108 refname);2109goto error_return;2110}2111 resolved = !!resolve_ref_unsafe(refname, resolve_flags,2112 lock->old_oid.hash, type);2113}2114if(!resolved) {2115 last_errno = errno;2116if(last_errno != ENOTDIR ||2117!verify_refname_available_dir(refname, extras, skip,2118get_loose_refs(&ref_cache), err))2119strbuf_addf(err,"unable to resolve reference '%s':%s",2120 refname,strerror(last_errno));21212122goto error_return;2123}21242125/*2126 * If the ref did not exist and we are creating it, make sure2127 * there is no existing packed ref whose name begins with our2128 * refname, nor a packed ref whose name is a proper prefix of2129 * our refname.2130 */2131if(is_null_oid(&lock->old_oid) &&2132verify_refname_available_dir(refname, extras, skip,2133get_packed_refs(&ref_cache), err)) {2134 last_errno = ENOTDIR;2135goto error_return;2136}21372138 lock->lk =xcalloc(1,sizeof(struct lock_file));21392140 lock->ref_name =xstrdup(refname);21412142 retry:2143switch(safe_create_leading_directories_const(ref_file.buf)) {2144case SCLD_OK:2145break;/* success */2146case SCLD_VANISHED:2147if(--attempts_remaining >0)2148goto retry;2149/* fall through */2150default:2151 last_errno = errno;2152strbuf_addf(err,"unable to create directory for '%s'",2153 ref_file.buf);2154goto error_return;2155}21562157if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2158 last_errno = errno;2159if(errno == ENOENT && --attempts_remaining >0)2160/*2161 * Maybe somebody just deleted one of the2162 * directories leading to ref_file. Try2163 * again:2164 */2165goto retry;2166else{2167unable_to_lock_message(ref_file.buf, errno, err);2168goto error_return;2169}2170}2171if(verify_lock(lock, old_sha1, mustexist, err)) {2172 last_errno = errno;2173goto error_return;2174}2175goto out;21762177 error_return:2178unlock_ref(lock);2179 lock = NULL;21802181 out:2182strbuf_release(&ref_file);2183 errno = last_errno;2184return lock;2185}21862187/*2188 * Write an entry to the packed-refs file for the specified refname.2189 * If peeled is non-NULL, write it as the entry's peeled value.2190 */2191static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2192unsigned char*peeled)2193{2194fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2195if(peeled)2196fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2197}21982199/*2200 * An each_ref_entry_fn that writes the entry to a packed-refs file.2201 */2202static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2203{2204enum peel_status peel_status =peel_entry(entry,0);22052206if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2207error("internal error:%sis not a valid packed reference!",2208 entry->name);2209write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2210 peel_status == PEEL_PEELED ?2211 entry->u.value.peeled.hash : NULL);2212return0;2213}22142215/*2216 * Lock the packed-refs file for writing. Flags is passed to2217 * hold_lock_file_for_update(). Return 0 on success. On errors, set2218 * errno appropriately and return a nonzero value.2219 */2220static intlock_packed_refs(int flags)2221{2222static int timeout_configured =0;2223static int timeout_value =1000;22242225struct packed_ref_cache *packed_ref_cache;22262227if(!timeout_configured) {2228git_config_get_int("core.packedrefstimeout", &timeout_value);2229 timeout_configured =1;2230}22312232if(hold_lock_file_for_update_timeout(2233&packlock,git_path("packed-refs"),2234 flags, timeout_value) <0)2235return-1;2236/*2237 * Get the current packed-refs while holding the lock. If the2238 * packed-refs file has been modified since we last read it,2239 * this will automatically invalidate the cache and re-read2240 * the packed-refs file.2241 */2242 packed_ref_cache =get_packed_ref_cache(&ref_cache);2243 packed_ref_cache->lock = &packlock;2244/* Increment the reference count to prevent it from being freed: */2245acquire_packed_ref_cache(packed_ref_cache);2246return0;2247}22482249/*2250 * Write the current version of the packed refs cache from memory to2251 * disk. The packed-refs file must already be locked for writing (see2252 * lock_packed_refs()). Return zero on success. On errors, set errno2253 * and return a nonzero value2254 */2255static intcommit_packed_refs(void)2256{2257struct packed_ref_cache *packed_ref_cache =2258get_packed_ref_cache(&ref_cache);2259int error =0;2260int save_errno =0;2261FILE*out;22622263if(!packed_ref_cache->lock)2264die("internal error: packed-refs not locked");22652266 out =fdopen_lock_file(packed_ref_cache->lock,"w");2267if(!out)2268die_errno("unable to fdopen packed-refs descriptor");22692270fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2271do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),22720, write_packed_entry_fn, out);22732274if(commit_lock_file(packed_ref_cache->lock)) {2275 save_errno = errno;2276 error = -1;2277}2278 packed_ref_cache->lock = NULL;2279release_packed_ref_cache(packed_ref_cache);2280 errno = save_errno;2281return error;2282}22832284/*2285 * Rollback the lockfile for the packed-refs file, and discard the2286 * in-memory packed reference cache. (The packed-refs file will be2287 * read anew if it is needed again after this function is called.)2288 */2289static voidrollback_packed_refs(void)2290{2291struct packed_ref_cache *packed_ref_cache =2292get_packed_ref_cache(&ref_cache);22932294if(!packed_ref_cache->lock)2295die("internal error: packed-refs not locked");2296rollback_lock_file(packed_ref_cache->lock);2297 packed_ref_cache->lock = NULL;2298release_packed_ref_cache(packed_ref_cache);2299clear_packed_ref_cache(&ref_cache);2300}23012302struct ref_to_prune {2303struct ref_to_prune *next;2304unsigned char sha1[20];2305char name[FLEX_ARRAY];2306};23072308struct pack_refs_cb_data {2309unsigned int flags;2310struct ref_dir *packed_refs;2311struct ref_to_prune *ref_to_prune;2312};23132314/*2315 * An each_ref_entry_fn that is run over loose references only. If2316 * the loose reference can be packed, add an entry in the packed ref2317 * cache. If the reference should be pruned, also add it to2318 * ref_to_prune in the pack_refs_cb_data.2319 */2320static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2321{2322struct pack_refs_cb_data *cb = cb_data;2323enum peel_status peel_status;2324struct ref_entry *packed_entry;2325int is_tag_ref =starts_with(entry->name,"refs/tags/");23262327/* Do not pack per-worktree refs: */2328if(ref_type(entry->name) != REF_TYPE_NORMAL)2329return0;23302331/* ALWAYS pack tags */2332if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2333return0;23342335/* Do not pack symbolic or broken refs: */2336if((entry->flag & REF_ISSYMREF) || !entry_resolves_to_object(entry))2337return0;23382339/* Add a packed ref cache entry equivalent to the loose entry. */2340 peel_status =peel_entry(entry,1);2341if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2342die("internal error peeling reference%s(%s)",2343 entry->name,oid_to_hex(&entry->u.value.oid));2344 packed_entry =find_ref(cb->packed_refs, entry->name);2345if(packed_entry) {2346/* Overwrite existing packed entry with info from loose entry */2347 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2348oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2349}else{2350 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2351 REF_ISPACKED | REF_KNOWS_PEELED,0);2352add_ref(cb->packed_refs, packed_entry);2353}2354oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);23552356/* Schedule the loose reference for pruning if requested. */2357if((cb->flags & PACK_REFS_PRUNE)) {2358struct ref_to_prune *n;2359FLEX_ALLOC_STR(n, name, entry->name);2360hashcpy(n->sha1, entry->u.value.oid.hash);2361 n->next = cb->ref_to_prune;2362 cb->ref_to_prune = n;2363}2364return0;2365}23662367/*2368 * Remove empty parents, but spare refs/ and immediate subdirs.2369 * Note: munges *name.2370 */2371static voidtry_remove_empty_parents(char*name)2372{2373char*p, *q;2374int i;2375 p = name;2376for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2377while(*p && *p !='/')2378 p++;2379/* tolerate duplicate slashes; see check_refname_format() */2380while(*p =='/')2381 p++;2382}2383for(q = p; *q; q++)2384;2385while(1) {2386while(q > p && *q !='/')2387 q--;2388while(q > p && *(q-1) =='/')2389 q--;2390if(q == p)2391break;2392*q ='\0';2393if(rmdir(git_path("%s", name)))2394break;2395}2396}23972398/* make sure nobody touched the ref, and unlink */2399static voidprune_ref(struct ref_to_prune *r)2400{2401struct ref_transaction *transaction;2402struct strbuf err = STRBUF_INIT;24032404if(check_refname_format(r->name,0))2405return;24062407 transaction =ref_transaction_begin(&err);2408if(!transaction ||2409ref_transaction_delete(transaction, r->name, r->sha1,2410 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||2411ref_transaction_commit(transaction, &err)) {2412ref_transaction_free(transaction);2413error("%s", err.buf);2414strbuf_release(&err);2415return;2416}2417ref_transaction_free(transaction);2418strbuf_release(&err);2419try_remove_empty_parents(r->name);2420}24212422static voidprune_refs(struct ref_to_prune *r)2423{2424while(r) {2425prune_ref(r);2426 r = r->next;2427}2428}24292430intpack_refs(unsigned int flags)2431{2432struct pack_refs_cb_data cbdata;24332434memset(&cbdata,0,sizeof(cbdata));2435 cbdata.flags = flags;24362437lock_packed_refs(LOCK_DIE_ON_ERROR);2438 cbdata.packed_refs =get_packed_refs(&ref_cache);24392440do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2441 pack_if_possible_fn, &cbdata);24422443if(commit_packed_refs())2444die_errno("unable to overwrite old ref-pack file");24452446prune_refs(cbdata.ref_to_prune);2447return0;2448}24492450/*2451 * Rewrite the packed-refs file, omitting any refs listed in2452 * 'refnames'. On error, leave packed-refs unchanged, write an error2453 * message to 'err', and return a nonzero value.2454 *2455 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2456 */2457static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2458{2459struct ref_dir *packed;2460struct string_list_item *refname;2461int ret, needs_repacking =0, removed =0;24622463assert(err);24642465/* Look for a packed ref */2466for_each_string_list_item(refname, refnames) {2467if(get_packed_ref(refname->string)) {2468 needs_repacking =1;2469break;2470}2471}24722473/* Avoid locking if we have nothing to do */2474if(!needs_repacking)2475return0;/* no refname exists in packed refs */24762477if(lock_packed_refs(0)) {2478unable_to_lock_message(git_path("packed-refs"), errno, err);2479return-1;2480}2481 packed =get_packed_refs(&ref_cache);24822483/* Remove refnames from the cache */2484for_each_string_list_item(refname, refnames)2485if(remove_entry(packed, refname->string) != -1)2486 removed =1;2487if(!removed) {2488/*2489 * All packed entries disappeared while we were2490 * acquiring the lock.2491 */2492rollback_packed_refs();2493return0;2494}24952496/* Write what remains */2497 ret =commit_packed_refs();2498if(ret)2499strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2500strerror(errno));2501return ret;2502}25032504static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2505{2506assert(err);25072508if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2509/*2510 * loose. The loose file name is the same as the2511 * lockfile name, minus ".lock":2512 */2513char*loose_filename =get_locked_file_path(lock->lk);2514int res =unlink_or_msg(loose_filename, err);2515free(loose_filename);2516if(res)2517return1;2518}2519return0;2520}25212522intdelete_refs(struct string_list *refnames,unsigned int flags)2523{2524struct strbuf err = STRBUF_INIT;2525int i, result =0;25262527if(!refnames->nr)2528return0;25292530 result =repack_without_refs(refnames, &err);2531if(result) {2532/*2533 * If we failed to rewrite the packed-refs file, then2534 * it is unsafe to try to remove loose refs, because2535 * doing so might expose an obsolete packed value for2536 * a reference that might even point at an object that2537 * has been garbage collected.2538 */2539if(refnames->nr ==1)2540error(_("could not delete reference%s:%s"),2541 refnames->items[0].string, err.buf);2542else2543error(_("could not delete references:%s"), err.buf);25442545goto out;2546}25472548for(i =0; i < refnames->nr; i++) {2549const char*refname = refnames->items[i].string;25502551if(delete_ref(refname, NULL, flags))2552 result |=error(_("could not remove reference%s"), refname);2553}25542555out:2556strbuf_release(&err);2557return result;2558}25592560/*2561 * People using contrib's git-new-workdir have .git/logs/refs ->2562 * /some/other/path/.git/logs/refs, and that may live on another device.2563 *2564 * IOW, to avoid cross device rename errors, the temporary renamed log must2565 * live into logs/refs.2566 */2567#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"25682569static intrename_tmp_log(const char*newrefname)2570{2571int attempts_remaining =4;2572struct strbuf path = STRBUF_INIT;2573int ret = -1;25742575 retry:2576strbuf_reset(&path);2577strbuf_git_path(&path,"logs/%s", newrefname);2578switch(safe_create_leading_directories_const(path.buf)) {2579case SCLD_OK:2580break;/* success */2581case SCLD_VANISHED:2582if(--attempts_remaining >0)2583goto retry;2584/* fall through */2585default:2586error("unable to create directory for%s", newrefname);2587goto out;2588}25892590if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2591if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2592/*2593 * rename(a, b) when b is an existing2594 * directory ought to result in ISDIR, but2595 * Solaris 5.8 gives ENOTDIR. Sheesh.2596 */2597if(remove_empty_directories(&path)) {2598error("Directory not empty: logs/%s", newrefname);2599goto out;2600}2601goto retry;2602}else if(errno == ENOENT && --attempts_remaining >0) {2603/*2604 * Maybe another process just deleted one of2605 * the directories in the path to newrefname.2606 * Try again from the beginning.2607 */2608goto retry;2609}else{2610error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2611 newrefname,strerror(errno));2612goto out;2613}2614}2615 ret =0;2616out:2617strbuf_release(&path);2618return ret;2619}26202621intverify_refname_available(const char*newname,2622const struct string_list *extras,2623const struct string_list *skip,2624struct strbuf *err)2625{2626struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2627struct ref_dir *loose_refs =get_loose_refs(&ref_cache);26282629if(verify_refname_available_dir(newname, extras, skip,2630 packed_refs, err) ||2631verify_refname_available_dir(newname, extras, skip,2632 loose_refs, err))2633return-1;26342635return0;2636}26372638static intwrite_ref_to_lockfile(struct ref_lock *lock,2639const unsigned char*sha1,struct strbuf *err);2640static intcommit_ref_update(struct ref_lock *lock,2641const unsigned char*sha1,const char*logmsg,2642struct strbuf *err);26432644intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2645{2646unsigned char sha1[20], orig_sha1[20];2647int flag =0, logmoved =0;2648struct ref_lock *lock;2649struct stat loginfo;2650int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2651struct strbuf err = STRBUF_INIT;26522653if(log &&S_ISLNK(loginfo.st_mode))2654returnerror("reflog for%sis a symlink", oldrefname);26552656if(!resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2657 orig_sha1, &flag))2658returnerror("refname%snot found", oldrefname);26592660if(flag & REF_ISSYMREF)2661returnerror("refname%sis a symbolic ref, renaming it is not supported",2662 oldrefname);2663if(!rename_ref_available(oldrefname, newrefname))2664return1;26652666if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2667returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2668 oldrefname,strerror(errno));26692670if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2671error("unable to delete old%s", oldrefname);2672goto rollback;2673}26742675/*2676 * Since we are doing a shallow lookup, sha1 is not the2677 * correct value to pass to delete_ref as old_sha1. But that2678 * doesn't matter, because an old_sha1 check wouldn't add to2679 * the safety anyway; we want to delete the reference whatever2680 * its current value.2681 */2682if(!read_ref_full(newrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2683 sha1, NULL) &&2684delete_ref(newrefname, NULL, REF_NODEREF)) {2685if(errno==EISDIR) {2686struct strbuf path = STRBUF_INIT;2687int result;26882689strbuf_git_path(&path,"%s", newrefname);2690 result =remove_empty_directories(&path);2691strbuf_release(&path);26922693if(result) {2694error("Directory not empty:%s", newrefname);2695goto rollback;2696}2697}else{2698error("unable to delete existing%s", newrefname);2699goto rollback;2700}2701}27022703if(log &&rename_tmp_log(newrefname))2704goto rollback;27052706 logmoved = log;27072708 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, REF_NODEREF,2709 NULL, &err);2710if(!lock) {2711error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2712strbuf_release(&err);2713goto rollback;2714}2715hashcpy(lock->old_oid.hash, orig_sha1);27162717if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2718commit_ref_update(lock, orig_sha1, logmsg, &err)) {2719error("unable to write current sha1 into%s:%s", newrefname, err.buf);2720strbuf_release(&err);2721goto rollback;2722}27232724return0;27252726 rollback:2727 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, REF_NODEREF,2728 NULL, &err);2729if(!lock) {2730error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2731strbuf_release(&err);2732goto rollbacklog;2733}27342735 flag = log_all_ref_updates;2736 log_all_ref_updates =0;2737if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2738commit_ref_update(lock, orig_sha1, NULL, &err)) {2739error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2740strbuf_release(&err);2741}2742 log_all_ref_updates = flag;27432744 rollbacklog:2745if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2746error("unable to restore logfile%sfrom%s:%s",2747 oldrefname, newrefname,strerror(errno));2748if(!logmoved && log &&2749rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2750error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2751 oldrefname,strerror(errno));27522753return1;2754}27552756static intclose_ref(struct ref_lock *lock)2757{2758if(close_lock_file(lock->lk))2759return-1;2760return0;2761}27622763static intcommit_ref(struct ref_lock *lock)2764{2765char*path =get_locked_file_path(lock->lk);2766struct stat st;27672768if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {2769/*2770 * There is a directory at the path we want to rename2771 * the lockfile to. Hopefully it is empty; try to2772 * delete it.2773 */2774size_t len =strlen(path);2775struct strbuf sb_path = STRBUF_INIT;27762777strbuf_attach(&sb_path, path, len, len);27782779/*2780 * If this fails, commit_lock_file() will also fail2781 * and will report the problem.2782 */2783remove_empty_directories(&sb_path);2784strbuf_release(&sb_path);2785}else{2786free(path);2787}27882789if(commit_lock_file(lock->lk))2790return-1;2791return0;2792}27932794/*2795 * Create a reflog for a ref. If force_create = 0, the reflog will2796 * only be created for certain refs (those for which2797 * should_autocreate_reflog returns non-zero. Otherwise, create it2798 * regardless of the ref name. Fill in *err and return -1 on failure.2799 */2800static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2801{2802int logfd, oflags = O_APPEND | O_WRONLY;28032804strbuf_git_path(logfile,"logs/%s", refname);2805if(force_create ||should_autocreate_reflog(refname)) {2806if(safe_create_leading_directories(logfile->buf) <0) {2807strbuf_addf(err,"unable to create directory for '%s': "2808"%s", logfile->buf,strerror(errno));2809return-1;2810}2811 oflags |= O_CREAT;2812}28132814 logfd =open(logfile->buf, oflags,0666);2815if(logfd <0) {2816if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2817return0;28182819if(errno == EISDIR) {2820if(remove_empty_directories(logfile)) {2821strbuf_addf(err,"there are still logs under "2822"'%s'", logfile->buf);2823return-1;2824}2825 logfd =open(logfile->buf, oflags,0666);2826}28272828if(logfd <0) {2829strbuf_addf(err,"unable to append to '%s':%s",2830 logfile->buf,strerror(errno));2831return-1;2832}2833}28342835adjust_shared_perm(logfile->buf);2836close(logfd);2837return0;2838}283928402841intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2842{2843int ret;2844struct strbuf sb = STRBUF_INIT;28452846 ret =log_ref_setup(refname, &sb, err, force_create);2847strbuf_release(&sb);2848return ret;2849}28502851static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2852const unsigned char*new_sha1,2853const char*committer,const char*msg)2854{2855int msglen, written;2856unsigned maxlen, len;2857char*logrec;28582859 msglen = msg ?strlen(msg) :0;2860 maxlen =strlen(committer) + msglen +100;2861 logrec =xmalloc(maxlen);2862 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2863sha1_to_hex(old_sha1),2864sha1_to_hex(new_sha1),2865 committer);2866if(msglen)2867 len +=copy_reflog_msg(logrec + len -1, msg) -1;28682869 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2870free(logrec);2871if(written != len)2872return-1;28732874return0;2875}28762877static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2878const unsigned char*new_sha1,const char*msg,2879struct strbuf *logfile,int flags,2880struct strbuf *err)2881{2882int logfd, result, oflags = O_APPEND | O_WRONLY;28832884if(log_all_ref_updates <0)2885 log_all_ref_updates = !is_bare_repository();28862887 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);28882889if(result)2890return result;28912892 logfd =open(logfile->buf, oflags);2893if(logfd <0)2894return0;2895 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2896git_committer_info(0), msg);2897if(result) {2898strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,2899strerror(errno));2900close(logfd);2901return-1;2902}2903if(close(logfd)) {2904strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,2905strerror(errno));2906return-1;2907}2908return0;2909}29102911static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2912const unsigned char*new_sha1,const char*msg,2913int flags,struct strbuf *err)2914{2915returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2916 err);2917}29182919intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2920const unsigned char*new_sha1,const char*msg,2921int flags,struct strbuf *err)2922{2923struct strbuf sb = STRBUF_INIT;2924int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2925 err);2926strbuf_release(&sb);2927return ret;2928}29292930/*2931 * Write sha1 into the open lockfile, then close the lockfile. On2932 * errors, rollback the lockfile, fill in *err and2933 * return -1.2934 */2935static intwrite_ref_to_lockfile(struct ref_lock *lock,2936const unsigned char*sha1,struct strbuf *err)2937{2938static char term ='\n';2939struct object *o;2940int fd;29412942 o =parse_object(sha1);2943if(!o) {2944strbuf_addf(err,2945"trying to write ref '%s' with nonexistent object%s",2946 lock->ref_name,sha1_to_hex(sha1));2947unlock_ref(lock);2948return-1;2949}2950if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2951strbuf_addf(err,2952"trying to write non-commit object%sto branch '%s'",2953sha1_to_hex(sha1), lock->ref_name);2954unlock_ref(lock);2955return-1;2956}2957 fd =get_lock_file_fd(lock->lk);2958if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2959write_in_full(fd, &term,1) !=1||2960close_ref(lock) <0) {2961strbuf_addf(err,2962"couldn't write '%s'",get_lock_file_path(lock->lk));2963unlock_ref(lock);2964return-1;2965}2966return0;2967}29682969/*2970 * Commit a change to a loose reference that has already been written2971 * to the loose reference lockfile. Also update the reflogs if2972 * necessary, using the specified lockmsg (which can be NULL).2973 */2974static intcommit_ref_update(struct ref_lock *lock,2975const unsigned char*sha1,const char*logmsg,2976struct strbuf *err)2977{2978clear_loose_ref_cache(&ref_cache);2979if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg,0, err)) {2980char*old_msg =strbuf_detach(err, NULL);2981strbuf_addf(err,"cannot update the ref '%s':%s",2982 lock->ref_name, old_msg);2983free(old_msg);2984unlock_ref(lock);2985return-1;2986}29872988if(strcmp(lock->ref_name,"HEAD") !=0) {2989/*2990 * Special hack: If a branch is updated directly and HEAD2991 * points to it (may happen on the remote side of a push2992 * for example) then logically the HEAD reflog should be2993 * updated too.2994 * A generic solution implies reverse symref information,2995 * but finding all symrefs pointing to the given branch2996 * would be rather costly for this rare event (the direct2997 * update of a branch) to be worth it. So let's cheat and2998 * check with HEAD only which should cover 99% of all usage2999 * scenarios (even 100% of the default ones).3000 */3001unsigned char head_sha1[20];3002int head_flag;3003const char*head_ref;30043005 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3006 head_sha1, &head_flag);3007if(head_ref && (head_flag & REF_ISSYMREF) &&3008!strcmp(head_ref, lock->ref_name)) {3009struct strbuf log_err = STRBUF_INIT;3010if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3011 logmsg,0, &log_err)) {3012error("%s", log_err.buf);3013strbuf_release(&log_err);3014}3015}3016}30173018if(commit_ref(lock)) {3019strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3020unlock_ref(lock);3021return-1;3022}30233024unlock_ref(lock);3025return0;3026}30273028static intcreate_ref_symlink(struct ref_lock *lock,const char*target)3029{3030int ret = -1;3031#ifndef NO_SYMLINK_HEAD3032char*ref_path =get_locked_file_path(lock->lk);3033unlink(ref_path);3034 ret =symlink(target, ref_path);3035free(ref_path);30363037if(ret)3038fprintf(stderr,"no symlink - falling back to symbolic ref\n");3039#endif3040return ret;3041}30423043static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,3044const char*target,const char*logmsg)3045{3046struct strbuf err = STRBUF_INIT;3047unsigned char new_sha1[20];3048if(logmsg && !read_ref(target, new_sha1) &&3049log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {3050error("%s", err.buf);3051strbuf_release(&err);3052}3053}30543055static intcreate_symref_locked(struct ref_lock *lock,const char*refname,3056const char*target,const char*logmsg)3057{3058if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {3059update_symref_reflog(lock, refname, target, logmsg);3060return0;3061}30623063if(!fdopen_lock_file(lock->lk,"w"))3064returnerror("unable to fdopen%s:%s",3065 lock->lk->tempfile.filename.buf,strerror(errno));30663067update_symref_reflog(lock, refname, target, logmsg);30683069/* no error check; commit_ref will check ferror */3070fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);3071if(commit_ref(lock) <0)3072returnerror("unable to write symref for%s:%s", refname,3073strerror(errno));3074return0;3075}30763077intcreate_symref(const char*refname,const char*target,const char*logmsg)3078{3079struct strbuf err = STRBUF_INIT;3080struct ref_lock *lock;3081int ret;30823083 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,3084&err);3085if(!lock) {3086error("%s", err.buf);3087strbuf_release(&err);3088return-1;3089}30903091 ret =create_symref_locked(lock, refname, target, logmsg);3092unlock_ref(lock);3093return ret;3094}30953096intset_worktree_head_symref(const char*gitdir,const char*target)3097{3098static struct lock_file head_lock;3099struct ref_lock *lock;3100struct strbuf head_path = STRBUF_INIT;3101const char*head_rel;3102int ret;31033104strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));3105if(hold_lock_file_for_update(&head_lock, head_path.buf,3106 LOCK_NO_DEREF) <0) {3107struct strbuf err = STRBUF_INIT;3108unable_to_lock_message(head_path.buf, errno, &err);3109error("%s", err.buf);3110strbuf_release(&err);3111strbuf_release(&head_path);3112return-1;3113}31143115/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for3116 linked trees */3117 head_rel =remove_leading_path(head_path.buf,3118absolute_path(get_git_common_dir()));3119/* to make use of create_symref_locked(), initialize ref_lock */3120 lock =xcalloc(1,sizeof(struct ref_lock));3121 lock->lk = &head_lock;3122 lock->ref_name =xstrdup(head_rel);31233124 ret =create_symref_locked(lock, head_rel, target, NULL);31253126unlock_ref(lock);/* will free lock */3127strbuf_release(&head_path);3128return ret;3129}31303131intreflog_exists(const char*refname)3132{3133struct stat st;31343135return!lstat(git_path("logs/%s", refname), &st) &&3136S_ISREG(st.st_mode);3137}31383139intdelete_reflog(const char*refname)3140{3141returnremove_path(git_path("logs/%s", refname));3142}31433144static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3145{3146unsigned char osha1[20], nsha1[20];3147char*email_end, *message;3148unsigned long timestamp;3149int tz;31503151/* old SP new SP name <email> SP time TAB msg LF */3152if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3153get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3154get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3155!(email_end =strchr(sb->buf +82,'>')) ||3156 email_end[1] !=' '||3157!(timestamp =strtoul(email_end +2, &message,10)) ||3158!message || message[0] !=' '||3159(message[1] !='+'&& message[1] !='-') ||3160!isdigit(message[2]) || !isdigit(message[3]) ||3161!isdigit(message[4]) || !isdigit(message[5]))3162return0;/* corrupt? */3163 email_end[1] ='\0';3164 tz =strtol(message +1, NULL,10);3165if(message[6] !='\t')3166 message +=6;3167else3168 message +=7;3169returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3170}31713172static char*find_beginning_of_line(char*bob,char*scan)3173{3174while(bob < scan && *(--scan) !='\n')3175;/* keep scanning backwards */3176/*3177 * Return either beginning of the buffer, or LF at the end of3178 * the previous line.3179 */3180return scan;3181}31823183intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3184{3185struct strbuf sb = STRBUF_INIT;3186FILE*logfp;3187long pos;3188int ret =0, at_tail =1;31893190 logfp =fopen(git_path("logs/%s", refname),"r");3191if(!logfp)3192return-1;31933194/* Jump to the end */3195if(fseek(logfp,0, SEEK_END) <0)3196returnerror("cannot seek back reflog for%s:%s",3197 refname,strerror(errno));3198 pos =ftell(logfp);3199while(!ret &&0< pos) {3200int cnt;3201size_t nread;3202char buf[BUFSIZ];3203char*endp, *scanp;32043205/* Fill next block from the end */3206 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3207if(fseek(logfp, pos - cnt, SEEK_SET))3208returnerror("cannot seek back reflog for%s:%s",3209 refname,strerror(errno));3210 nread =fread(buf, cnt,1, logfp);3211if(nread !=1)3212returnerror("cannot read%dbytes from reflog for%s:%s",3213 cnt, refname,strerror(errno));3214 pos -= cnt;32153216 scanp = endp = buf + cnt;3217if(at_tail && scanp[-1] =='\n')3218/* Looking at the final LF at the end of the file */3219 scanp--;3220 at_tail =0;32213222while(buf < scanp) {3223/*3224 * terminating LF of the previous line, or the beginning3225 * of the buffer.3226 */3227char*bp;32283229 bp =find_beginning_of_line(buf, scanp);32303231if(*bp =='\n') {3232/*3233 * The newline is the end of the previous line,3234 * so we know we have complete line starting3235 * at (bp + 1). Prefix it onto any prior data3236 * we collected for the line and process it.3237 */3238strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3239 scanp = bp;3240 endp = bp +1;3241 ret =show_one_reflog_ent(&sb, fn, cb_data);3242strbuf_reset(&sb);3243if(ret)3244break;3245}else if(!pos) {3246/*3247 * We are at the start of the buffer, and the3248 * start of the file; there is no previous3249 * line, and we have everything for this one.3250 * Process it, and we can end the loop.3251 */3252strbuf_splice(&sb,0,0, buf, endp - buf);3253 ret =show_one_reflog_ent(&sb, fn, cb_data);3254strbuf_reset(&sb);3255break;3256}32573258if(bp == buf) {3259/*3260 * We are at the start of the buffer, and there3261 * is more file to read backwards. Which means3262 * we are in the middle of a line. Note that we3263 * may get here even if *bp was a newline; that3264 * just means we are at the exact end of the3265 * previous line, rather than some spot in the3266 * middle.3267 *3268 * Save away what we have to be combined with3269 * the data from the next read.3270 */3271strbuf_splice(&sb,0,0, buf, endp - buf);3272break;3273}3274}32753276}3277if(!ret && sb.len)3278die("BUG: reverse reflog parser had leftover data");32793280fclose(logfp);3281strbuf_release(&sb);3282return ret;3283}32843285intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3286{3287FILE*logfp;3288struct strbuf sb = STRBUF_INIT;3289int ret =0;32903291 logfp =fopen(git_path("logs/%s", refname),"r");3292if(!logfp)3293return-1;32943295while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3296 ret =show_one_reflog_ent(&sb, fn, cb_data);3297fclose(logfp);3298strbuf_release(&sb);3299return ret;3300}33013302struct files_reflog_iterator {3303struct ref_iterator base;33043305struct dir_iterator *dir_iterator;3306struct object_id oid;3307};33083309static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)3310{3311struct files_reflog_iterator *iter =3312(struct files_reflog_iterator *)ref_iterator;3313struct dir_iterator *diter = iter->dir_iterator;3314int ok;33153316while((ok =dir_iterator_advance(diter)) == ITER_OK) {3317int flags;33183319if(!S_ISREG(diter->st.st_mode))3320continue;3321if(diter->basename[0] =='.')3322continue;3323if(ends_with(diter->basename,".lock"))3324continue;33253326if(read_ref_full(diter->relative_path,0,3327 iter->oid.hash, &flags)) {3328error("bad ref for%s", diter->path.buf);3329continue;3330}33313332 iter->base.refname = diter->relative_path;3333 iter->base.oid = &iter->oid;3334 iter->base.flags = flags;3335return ITER_OK;3336}33373338 iter->dir_iterator = NULL;3339if(ref_iterator_abort(ref_iterator) == ITER_ERROR)3340 ok = ITER_ERROR;3341return ok;3342}33433344static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,3345struct object_id *peeled)3346{3347die("BUG: ref_iterator_peel() called for reflog_iterator");3348}33493350static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)3351{3352struct files_reflog_iterator *iter =3353(struct files_reflog_iterator *)ref_iterator;3354int ok = ITER_DONE;33553356if(iter->dir_iterator)3357 ok =dir_iterator_abort(iter->dir_iterator);33583359base_ref_iterator_free(ref_iterator);3360return ok;3361}33623363static struct ref_iterator_vtable files_reflog_iterator_vtable = {3364 files_reflog_iterator_advance,3365 files_reflog_iterator_peel,3366 files_reflog_iterator_abort3367};33683369struct ref_iterator *files_reflog_iterator_begin(void)3370{3371struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));3372struct ref_iterator *ref_iterator = &iter->base;33733374base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);3375 iter->dir_iterator =dir_iterator_begin(git_path("logs"));3376return ref_iterator;3377}33783379intfor_each_reflog(each_ref_fn fn,void*cb_data)3380{3381returndo_for_each_ref_iterator(files_reflog_iterator_begin(),3382 fn, cb_data);3383}33843385static intref_update_reject_duplicates(struct string_list *refnames,3386struct strbuf *err)3387{3388int i, n = refnames->nr;33893390assert(err);33913392for(i =1; i < n; i++)3393if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3394strbuf_addf(err,3395"multiple updates for ref '%s' not allowed.",3396 refnames->items[i].string);3397return1;3398}3399return0;3400}34013402/*3403 * If update is a direct update of head_ref (the reference pointed to3404 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.3405 */3406static intsplit_head_update(struct ref_update *update,3407struct ref_transaction *transaction,3408const char*head_ref,3409struct string_list *affected_refnames,3410struct strbuf *err)3411{3412struct string_list_item *item;3413struct ref_update *new_update;34143415if((update->flags & REF_LOG_ONLY) ||3416(update->flags & REF_ISPRUNING) ||3417(update->flags & REF_UPDATE_VIA_HEAD))3418return0;34193420if(strcmp(update->refname, head_ref))3421return0;34223423/*3424 * First make sure that HEAD is not already in the3425 * transaction. This insertion is O(N) in the transaction3426 * size, but it happens at most once per transaction.3427 */3428 item =string_list_insert(affected_refnames,"HEAD");3429if(item->util) {3430/* An entry already existed */3431strbuf_addf(err,3432"multiple updates for 'HEAD' (including one "3433"via its referent '%s') are not allowed",3434 update->refname);3435return TRANSACTION_NAME_CONFLICT;3436}34373438 new_update =ref_transaction_add_update(3439 transaction,"HEAD",3440 update->flags | REF_LOG_ONLY | REF_NODEREF,3441 update->new_sha1, update->old_sha1,3442 update->msg);34433444 item->util = new_update;34453446return0;3447}34483449/*3450 * update is for a symref that points at referent and doesn't have3451 * REF_NODEREF set. Split it into two updates:3452 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set3453 * - A new, separate update for the referent reference3454 * Note that the new update will itself be subject to splitting when3455 * the iteration gets to it.3456 */3457static intsplit_symref_update(struct ref_update *update,3458const char*referent,3459struct ref_transaction *transaction,3460struct string_list *affected_refnames,3461struct strbuf *err)3462{3463struct string_list_item *item;3464struct ref_update *new_update;3465unsigned int new_flags;34663467/*3468 * First make sure that referent is not already in the3469 * transaction. This insertion is O(N) in the transaction3470 * size, but it happens at most once per symref in a3471 * transaction.3472 */3473 item =string_list_insert(affected_refnames, referent);3474if(item->util) {3475/* An entry already existed */3476strbuf_addf(err,3477"multiple updates for '%s' (including one "3478"via symref '%s') are not allowed",3479 referent, update->refname);3480return TRANSACTION_NAME_CONFLICT;3481}34823483 new_flags = update->flags;3484if(!strcmp(update->refname,"HEAD")) {3485/*3486 * Record that the new update came via HEAD, so that3487 * when we process it, split_head_update() doesn't try3488 * to add another reflog update for HEAD. Note that3489 * this bit will be propagated if the new_update3490 * itself needs to be split.3491 */3492 new_flags |= REF_UPDATE_VIA_HEAD;3493}34943495 new_update =ref_transaction_add_update(3496 transaction, referent, new_flags,3497 update->new_sha1, update->old_sha1,3498 update->msg);34993500 new_update->parent_update = update;35013502/*3503 * Change the symbolic ref update to log only. Also, it3504 * doesn't need to check its old SHA-1 value, as that will be3505 * done when new_update is processed.3506 */3507 update->flags |= REF_LOG_ONLY | REF_NODEREF;3508 update->flags &= ~REF_HAVE_OLD;35093510 item->util = new_update;35113512return0;3513}35143515/*3516 * Return the refname under which update was originally requested.3517 */3518static const char*original_update_refname(struct ref_update *update)3519{3520while(update->parent_update)3521 update = update->parent_update;35223523return update->refname;3524}35253526/*3527 * Check whether the REF_HAVE_OLD and old_oid values stored in update3528 * are consistent with oid, which is the reference's current value. If3529 * everything is OK, return 0; otherwise, write an error message to3530 * err and return -1.3531 */3532static intcheck_old_oid(struct ref_update *update,struct object_id *oid,3533struct strbuf *err)3534{3535if(!(update->flags & REF_HAVE_OLD) ||3536!hashcmp(oid->hash, update->old_sha1))3537return0;35383539if(is_null_sha1(update->old_sha1))3540strbuf_addf(err,"cannot lock ref '%s': "3541"reference already exists",3542original_update_refname(update));3543else if(is_null_oid(oid))3544strbuf_addf(err,"cannot lock ref '%s': "3545"reference is missing but expected%s",3546original_update_refname(update),3547sha1_to_hex(update->old_sha1));3548else3549strbuf_addf(err,"cannot lock ref '%s': "3550"is at%sbut expected%s",3551original_update_refname(update),3552oid_to_hex(oid),3553sha1_to_hex(update->old_sha1));35543555return-1;3556}35573558/*3559 * Prepare for carrying out update:3560 * - Lock the reference referred to by update.3561 * - Read the reference under lock.3562 * - Check that its old SHA-1 value (if specified) is correct, and in3563 * any case record it in update->lock->old_oid for later use when3564 * writing the reflog.3565 * - If it is a symref update without REF_NODEREF, split it up into a3566 * REF_LOG_ONLY update of the symref and add a separate update for3567 * the referent to transaction.3568 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY3569 * update of HEAD.3570 */3571static intlock_ref_for_update(struct ref_update *update,3572struct ref_transaction *transaction,3573const char*head_ref,3574struct string_list *affected_refnames,3575struct strbuf *err)3576{3577struct strbuf referent = STRBUF_INIT;3578int mustexist = (update->flags & REF_HAVE_OLD) &&3579!is_null_sha1(update->old_sha1);3580int ret;3581struct ref_lock *lock;35823583if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))3584 update->flags |= REF_DELETING;35853586if(head_ref) {3587 ret =split_head_update(update, transaction, head_ref,3588 affected_refnames, err);3589if(ret)3590return ret;3591}35923593 ret =lock_raw_ref(update->refname, mustexist,3594 affected_refnames, NULL,3595&update->lock, &referent,3596&update->type, err);35973598if(ret) {3599char*reason;36003601 reason =strbuf_detach(err, NULL);3602strbuf_addf(err,"cannot lock ref '%s':%s",3603original_update_refname(update), reason);3604free(reason);3605return ret;3606}36073608 lock = update->lock;36093610if(update->type & REF_ISSYMREF) {3611if(update->flags & REF_NODEREF) {3612/*3613 * We won't be reading the referent as part of3614 * the transaction, so we have to read it here3615 * to record and possibly check old_sha1:3616 */3617if(read_ref_full(referent.buf,0,3618 lock->old_oid.hash, NULL)) {3619if(update->flags & REF_HAVE_OLD) {3620strbuf_addf(err,"cannot lock ref '%s': "3621"error reading reference",3622original_update_refname(update));3623return-1;3624}3625}else if(check_old_oid(update, &lock->old_oid, err)) {3626return TRANSACTION_GENERIC_ERROR;3627}3628}else{3629/*3630 * Create a new update for the reference this3631 * symref is pointing at. Also, we will record3632 * and verify old_sha1 for this update as part3633 * of processing the split-off update, so we3634 * don't have to do it here.3635 */3636 ret =split_symref_update(update, referent.buf, transaction,3637 affected_refnames, err);3638if(ret)3639return ret;3640}3641}else{3642struct ref_update *parent_update;36433644if(check_old_oid(update, &lock->old_oid, err))3645return TRANSACTION_GENERIC_ERROR;36463647/*3648 * If this update is happening indirectly because of a3649 * symref update, record the old SHA-1 in the parent3650 * update:3651 */3652for(parent_update = update->parent_update;3653 parent_update;3654 parent_update = parent_update->parent_update) {3655oidcpy(&parent_update->lock->old_oid, &lock->old_oid);3656}3657}36583659if((update->flags & REF_HAVE_NEW) &&3660!(update->flags & REF_DELETING) &&3661!(update->flags & REF_LOG_ONLY)) {3662if(!(update->type & REF_ISSYMREF) &&3663!hashcmp(lock->old_oid.hash, update->new_sha1)) {3664/*3665 * The reference already has the desired3666 * value, so we don't need to write it.3667 */3668}else if(write_ref_to_lockfile(lock, update->new_sha1,3669 err)) {3670char*write_err =strbuf_detach(err, NULL);36713672/*3673 * The lock was freed upon failure of3674 * write_ref_to_lockfile():3675 */3676 update->lock = NULL;3677strbuf_addf(err,3678"cannot update ref '%s':%s",3679 update->refname, write_err);3680free(write_err);3681return TRANSACTION_GENERIC_ERROR;3682}else{3683 update->flags |= REF_NEEDS_COMMIT;3684}3685}3686if(!(update->flags & REF_NEEDS_COMMIT)) {3687/*3688 * We didn't call write_ref_to_lockfile(), so3689 * the lockfile is still open. Close it to3690 * free up the file descriptor:3691 */3692if(close_ref(lock)) {3693strbuf_addf(err,"couldn't close '%s.lock'",3694 update->refname);3695return TRANSACTION_GENERIC_ERROR;3696}3697}3698return0;3699}37003701intref_transaction_commit(struct ref_transaction *transaction,3702struct strbuf *err)3703{3704int ret =0, i;3705struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3706struct string_list_item *ref_to_delete;3707struct string_list affected_refnames = STRING_LIST_INIT_NODUP;3708char*head_ref = NULL;3709int head_type;3710struct object_id head_oid;37113712assert(err);37133714if(transaction->state != REF_TRANSACTION_OPEN)3715die("BUG: commit called for transaction that is not open");37163717if(!transaction->nr) {3718 transaction->state = REF_TRANSACTION_CLOSED;3719return0;3720}37213722/*3723 * Fail if a refname appears more than once in the3724 * transaction. (If we end up splitting up any updates using3725 * split_symref_update() or split_head_update(), those3726 * functions will check that the new updates don't have the3727 * same refname as any existing ones.)3728 */3729for(i =0; i < transaction->nr; i++) {3730struct ref_update *update = transaction->updates[i];3731struct string_list_item *item =3732string_list_append(&affected_refnames, update->refname);37333734/*3735 * We store a pointer to update in item->util, but at3736 * the moment we never use the value of this field3737 * except to check whether it is non-NULL.3738 */3739 item->util = update;3740}3741string_list_sort(&affected_refnames);3742if(ref_update_reject_duplicates(&affected_refnames, err)) {3743 ret = TRANSACTION_GENERIC_ERROR;3744goto cleanup;3745}37463747/*3748 * Special hack: If a branch is updated directly and HEAD3749 * points to it (may happen on the remote side of a push3750 * for example) then logically the HEAD reflog should be3751 * updated too.3752 *3753 * A generic solution would require reverse symref lookups,3754 * but finding all symrefs pointing to a given branch would be3755 * rather costly for this rare event (the direct update of a3756 * branch) to be worth it. So let's cheat and check with HEAD3757 * only, which should cover 99% of all usage scenarios (even3758 * 100% of the default ones).3759 *3760 * So if HEAD is a symbolic reference, then record the name of3761 * the reference that it points to. If we see an update of3762 * head_ref within the transaction, then split_head_update()3763 * arranges for the reflog of HEAD to be updated, too.3764 */3765 head_ref =resolve_refdup("HEAD", RESOLVE_REF_NO_RECURSE,3766 head_oid.hash, &head_type);37673768if(head_ref && !(head_type & REF_ISSYMREF)) {3769free(head_ref);3770 head_ref = NULL;3771}37723773/*3774 * Acquire all locks, verify old values if provided, check3775 * that new values are valid, and write new values to the3776 * lockfiles, ready to be activated. Only keep one lockfile3777 * open at a time to avoid running out of file descriptors.3778 */3779for(i =0; i < transaction->nr; i++) {3780struct ref_update *update = transaction->updates[i];37813782 ret =lock_ref_for_update(update, transaction, head_ref,3783&affected_refnames, err);3784if(ret)3785goto cleanup;3786}37873788/* Perform updates first so live commits remain referenced */3789for(i =0; i < transaction->nr; i++) {3790struct ref_update *update = transaction->updates[i];3791struct ref_lock *lock = update->lock;37923793if(update->flags & REF_NEEDS_COMMIT ||3794 update->flags & REF_LOG_ONLY) {3795if(log_ref_write(lock->ref_name, lock->old_oid.hash,3796 update->new_sha1,3797 update->msg, update->flags, err)) {3798char*old_msg =strbuf_detach(err, NULL);37993800strbuf_addf(err,"cannot update the ref '%s':%s",3801 lock->ref_name, old_msg);3802free(old_msg);3803unlock_ref(lock);3804 update->lock = NULL;3805 ret = TRANSACTION_GENERIC_ERROR;3806goto cleanup;3807}3808}3809if(update->flags & REF_NEEDS_COMMIT) {3810clear_loose_ref_cache(&ref_cache);3811if(commit_ref(lock)) {3812strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3813unlock_ref(lock);3814 update->lock = NULL;3815 ret = TRANSACTION_GENERIC_ERROR;3816goto cleanup;3817}3818}3819}3820/* Perform deletes now that updates are safely completed */3821for(i =0; i < transaction->nr; i++) {3822struct ref_update *update = transaction->updates[i];38233824if(update->flags & REF_DELETING &&3825!(update->flags & REF_LOG_ONLY)) {3826if(delete_ref_loose(update->lock, update->type, err)) {3827 ret = TRANSACTION_GENERIC_ERROR;3828goto cleanup;3829}38303831if(!(update->flags & REF_ISPRUNING))3832string_list_append(&refs_to_delete,3833 update->lock->ref_name);3834}3835}38363837if(repack_without_refs(&refs_to_delete, err)) {3838 ret = TRANSACTION_GENERIC_ERROR;3839goto cleanup;3840}3841for_each_string_list_item(ref_to_delete, &refs_to_delete)3842unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3843clear_loose_ref_cache(&ref_cache);38443845cleanup:3846 transaction->state = REF_TRANSACTION_CLOSED;38473848for(i =0; i < transaction->nr; i++)3849if(transaction->updates[i]->lock)3850unlock_ref(transaction->updates[i]->lock);3851string_list_clear(&refs_to_delete,0);3852free(head_ref);3853string_list_clear(&affected_refnames,0);38543855return ret;3856}38573858static intref_present(const char*refname,3859const struct object_id *oid,int flags,void*cb_data)3860{3861struct string_list *affected_refnames = cb_data;38623863returnstring_list_has_string(affected_refnames, refname);3864}38653866intinitial_ref_transaction_commit(struct ref_transaction *transaction,3867struct strbuf *err)3868{3869int ret =0, i;3870struct string_list affected_refnames = STRING_LIST_INIT_NODUP;38713872assert(err);38733874if(transaction->state != REF_TRANSACTION_OPEN)3875die("BUG: commit called for transaction that is not open");38763877/* Fail if a refname appears more than once in the transaction: */3878for(i =0; i < transaction->nr; i++)3879string_list_append(&affected_refnames,3880 transaction->updates[i]->refname);3881string_list_sort(&affected_refnames);3882if(ref_update_reject_duplicates(&affected_refnames, err)) {3883 ret = TRANSACTION_GENERIC_ERROR;3884goto cleanup;3885}38863887/*3888 * It's really undefined to call this function in an active3889 * repository or when there are existing references: we are3890 * only locking and changing packed-refs, so (1) any3891 * simultaneous processes might try to change a reference at3892 * the same time we do, and (2) any existing loose versions of3893 * the references that we are setting would have precedence3894 * over our values. But some remote helpers create the remote3895 * "HEAD" and "master" branches before calling this function,3896 * so here we really only check that none of the references3897 * that we are creating already exists.3898 */3899if(for_each_rawref(ref_present, &affected_refnames))3900die("BUG: initial ref transaction called with existing refs");39013902for(i =0; i < transaction->nr; i++) {3903struct ref_update *update = transaction->updates[i];39043905if((update->flags & REF_HAVE_OLD) &&3906!is_null_sha1(update->old_sha1))3907die("BUG: initial ref transaction with old_sha1 set");3908if(verify_refname_available(update->refname,3909&affected_refnames, NULL,3910 err)) {3911 ret = TRANSACTION_NAME_CONFLICT;3912goto cleanup;3913}3914}39153916if(lock_packed_refs(0)) {3917strbuf_addf(err,"unable to lock packed-refs file:%s",3918strerror(errno));3919 ret = TRANSACTION_GENERIC_ERROR;3920goto cleanup;3921}39223923for(i =0; i < transaction->nr; i++) {3924struct ref_update *update = transaction->updates[i];39253926if((update->flags & REF_HAVE_NEW) &&3927!is_null_sha1(update->new_sha1))3928add_packed_ref(update->refname, update->new_sha1);3929}39303931if(commit_packed_refs()) {3932strbuf_addf(err,"unable to commit packed-refs file:%s",3933strerror(errno));3934 ret = TRANSACTION_GENERIC_ERROR;3935goto cleanup;3936}39373938cleanup:3939 transaction->state = REF_TRANSACTION_CLOSED;3940string_list_clear(&affected_refnames,0);3941return ret;3942}39433944struct expire_reflog_cb {3945unsigned int flags;3946 reflog_expiry_should_prune_fn *should_prune_fn;3947void*policy_cb;3948FILE*newlog;3949unsigned char last_kept_sha1[20];3950};39513952static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3953const char*email,unsigned long timestamp,int tz,3954const char*message,void*cb_data)3955{3956struct expire_reflog_cb *cb = cb_data;3957struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;39583959if(cb->flags & EXPIRE_REFLOGS_REWRITE)3960 osha1 = cb->last_kept_sha1;39613962if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3963 message, policy_cb)) {3964if(!cb->newlog)3965printf("would prune%s", message);3966else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3967printf("prune%s", message);3968}else{3969if(cb->newlog) {3970fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3971sha1_to_hex(osha1),sha1_to_hex(nsha1),3972 email, timestamp, tz, message);3973hashcpy(cb->last_kept_sha1, nsha1);3974}3975if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3976printf("keep%s", message);3977}3978return0;3979}39803981intreflog_expire(const char*refname,const unsigned char*sha1,3982unsigned int flags,3983 reflog_expiry_prepare_fn prepare_fn,3984 reflog_expiry_should_prune_fn should_prune_fn,3985 reflog_expiry_cleanup_fn cleanup_fn,3986void*policy_cb_data)3987{3988static struct lock_file reflog_lock;3989struct expire_reflog_cb cb;3990struct ref_lock *lock;3991char*log_file;3992int status =0;3993int type;3994struct strbuf err = STRBUF_INIT;39953996memset(&cb,0,sizeof(cb));3997 cb.flags = flags;3998 cb.policy_cb = policy_cb_data;3999 cb.should_prune_fn = should_prune_fn;40004001/*4002 * The reflog file is locked by holding the lock on the4003 * reference itself, plus we might need to update the4004 * reference if --updateref was specified:4005 */4006 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL, REF_NODEREF,4007&type, &err);4008if(!lock) {4009error("cannot lock ref '%s':%s", refname, err.buf);4010strbuf_release(&err);4011return-1;4012}4013if(!reflog_exists(refname)) {4014unlock_ref(lock);4015return0;4016}40174018 log_file =git_pathdup("logs/%s", refname);4019if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4020/*4021 * Even though holding $GIT_DIR/logs/$reflog.lock has4022 * no locking implications, we use the lock_file4023 * machinery here anyway because it does a lot of the4024 * work we need, including cleaning up if the program4025 * exits unexpectedly.4026 */4027if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4028struct strbuf err = STRBUF_INIT;4029unable_to_lock_message(log_file, errno, &err);4030error("%s", err.buf);4031strbuf_release(&err);4032goto failure;4033}4034 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4035if(!cb.newlog) {4036error("cannot fdopen%s(%s)",4037get_lock_file_path(&reflog_lock),strerror(errno));4038goto failure;4039}4040}40414042(*prepare_fn)(refname, sha1, cb.policy_cb);4043for_each_reflog_ent(refname, expire_reflog_ent, &cb);4044(*cleanup_fn)(cb.policy_cb);40454046if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4047/*4048 * It doesn't make sense to adjust a reference pointed4049 * to by a symbolic ref based on expiring entries in4050 * the symbolic reference's reflog. Nor can we update4051 * a reference if there are no remaining reflog4052 * entries.4053 */4054int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4055!(type & REF_ISSYMREF) &&4056!is_null_sha1(cb.last_kept_sha1);40574058if(close_lock_file(&reflog_lock)) {4059 status |=error("couldn't write%s:%s", log_file,4060strerror(errno));4061}else if(update &&4062(write_in_full(get_lock_file_fd(lock->lk),4063sha1_to_hex(cb.last_kept_sha1),40) !=40||4064write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||4065close_ref(lock) <0)) {4066 status |=error("couldn't write%s",4067get_lock_file_path(lock->lk));4068rollback_lock_file(&reflog_lock);4069}else if(commit_lock_file(&reflog_lock)) {4070 status |=error("unable to write reflog '%s' (%s)",4071 log_file,strerror(errno));4072}else if(update &&commit_ref(lock)) {4073 status |=error("couldn't set%s", lock->ref_name);4074}4075}4076free(log_file);4077unlock_ref(lock);4078return status;40794080 failure:4081rollback_lock_file(&reflog_lock);4082free(log_file);4083unlock_ref(lock);4084return-1;4085}