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 files_ref_store; 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 files_ref_store that contains this ref_dir. */ 82struct files_ref_store *ref_store; 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 files_ref_store *ref_store, 165const char*dirname,size_t len, 166int incomplete); 167static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry); 168static intfiles_log_ref_write(struct files_ref_store *refs, 169const char*refname,const unsigned char*old_sha1, 170const unsigned char*new_sha1,const char*msg, 171int flags,struct strbuf *err); 172 173static struct ref_dir *get_ref_dir(struct ref_entry *entry) 174{ 175struct ref_dir *dir; 176assert(entry->flag & REF_DIR); 177 dir = &entry->u.subdir; 178if(entry->flag & REF_INCOMPLETE) { 179read_loose_refs(entry->name, dir); 180 181/* 182 * Manually add refs/bisect, which, being 183 * per-worktree, might not appear in the directory 184 * listing for refs/ in the main repo. 185 */ 186if(!strcmp(entry->name,"refs/")) { 187int pos =search_ref_dir(dir,"refs/bisect/",12); 188if(pos <0) { 189struct ref_entry *child_entry; 190 child_entry =create_dir_entry(dir->ref_store, 191"refs/bisect/", 19212,1); 193add_entry_to_dir(dir, child_entry); 194} 195} 196 entry->flag &= ~REF_INCOMPLETE; 197} 198return dir; 199} 200 201static struct ref_entry *create_ref_entry(const char*refname, 202const unsigned char*sha1,int flag, 203int check_name) 204{ 205struct ref_entry *ref; 206 207if(check_name && 208check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 209die("Reference has invalid format: '%s'", refname); 210FLEX_ALLOC_STR(ref, name, refname); 211hashcpy(ref->u.value.oid.hash, sha1); 212oidclr(&ref->u.value.peeled); 213 ref->flag = flag; 214return ref; 215} 216 217static voidclear_ref_dir(struct ref_dir *dir); 218 219static voidfree_ref_entry(struct ref_entry *entry) 220{ 221if(entry->flag & REF_DIR) { 222/* 223 * Do not use get_ref_dir() here, as that might 224 * trigger the reading of loose refs. 225 */ 226clear_ref_dir(&entry->u.subdir); 227} 228free(entry); 229} 230 231/* 232 * Add a ref_entry to the end of dir (unsorted). Entry is always 233 * stored directly in dir; no recursion into subdirectories is 234 * done. 235 */ 236static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 237{ 238ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 239 dir->entries[dir->nr++] = entry; 240/* optimize for the case that entries are added in order */ 241if(dir->nr ==1|| 242(dir->nr == dir->sorted +1&& 243strcmp(dir->entries[dir->nr -2]->name, 244 dir->entries[dir->nr -1]->name) <0)) 245 dir->sorted = dir->nr; 246} 247 248/* 249 * Clear and free all entries in dir, recursively. 250 */ 251static voidclear_ref_dir(struct ref_dir *dir) 252{ 253int i; 254for(i =0; i < dir->nr; i++) 255free_ref_entry(dir->entries[i]); 256free(dir->entries); 257 dir->sorted = dir->nr = dir->alloc =0; 258 dir->entries = NULL; 259} 260 261/* 262 * Create a struct ref_entry object for the specified dirname. 263 * dirname is the name of the directory with a trailing slash (e.g., 264 * "refs/heads/") or "" for the top-level directory. 265 */ 266static struct ref_entry *create_dir_entry(struct files_ref_store *ref_store, 267const char*dirname,size_t len, 268int incomplete) 269{ 270struct ref_entry *direntry; 271FLEX_ALLOC_MEM(direntry, name, dirname, len); 272 direntry->u.subdir.ref_store = ref_store; 273 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 274return direntry; 275} 276 277static intref_entry_cmp(const void*a,const void*b) 278{ 279struct ref_entry *one = *(struct ref_entry **)a; 280struct ref_entry *two = *(struct ref_entry **)b; 281returnstrcmp(one->name, two->name); 282} 283 284static voidsort_ref_dir(struct ref_dir *dir); 285 286struct string_slice { 287size_t len; 288const char*str; 289}; 290 291static intref_entry_cmp_sslice(const void*key_,const void*ent_) 292{ 293const struct string_slice *key = key_; 294const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 295int cmp =strncmp(key->str, ent->name, key->len); 296if(cmp) 297return cmp; 298return'\0'- (unsigned char)ent->name[key->len]; 299} 300 301/* 302 * Return the index of the entry with the given refname from the 303 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 304 * no such entry is found. dir must already be complete. 305 */ 306static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 307{ 308struct ref_entry **r; 309struct string_slice key; 310 311if(refname == NULL || !dir->nr) 312return-1; 313 314sort_ref_dir(dir); 315 key.len = len; 316 key.str = refname; 317 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 318 ref_entry_cmp_sslice); 319 320if(r == NULL) 321return-1; 322 323return r - dir->entries; 324} 325 326/* 327 * Search for a directory entry directly within dir (without 328 * recursing). Sort dir if necessary. subdirname must be a directory 329 * name (i.e., end in '/'). If mkdir is set, then create the 330 * directory if it is missing; otherwise, return NULL if the desired 331 * directory cannot be found. dir must already be complete. 332 */ 333static struct ref_dir *search_for_subdir(struct ref_dir *dir, 334const char*subdirname,size_t len, 335int mkdir) 336{ 337int entry_index =search_ref_dir(dir, subdirname, len); 338struct ref_entry *entry; 339if(entry_index == -1) { 340if(!mkdir) 341return NULL; 342/* 343 * Since dir is complete, the absence of a subdir 344 * means that the subdir really doesn't exist; 345 * therefore, create an empty record for it but mark 346 * the record complete. 347 */ 348 entry =create_dir_entry(dir->ref_store, subdirname, len,0); 349add_entry_to_dir(dir, entry); 350}else{ 351 entry = dir->entries[entry_index]; 352} 353returnget_ref_dir(entry); 354} 355 356/* 357 * If refname is a reference name, find the ref_dir within the dir 358 * tree that should hold refname. If refname is a directory name 359 * (i.e., ends in '/'), then return that ref_dir itself. dir must 360 * represent the top-level directory and must already be complete. 361 * Sort ref_dirs and recurse into subdirectories as necessary. If 362 * mkdir is set, then create any missing directories; otherwise, 363 * return NULL if the desired directory cannot be found. 364 */ 365static struct ref_dir *find_containing_dir(struct ref_dir *dir, 366const char*refname,int mkdir) 367{ 368const char*slash; 369for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 370size_t dirnamelen = slash - refname +1; 371struct ref_dir *subdir; 372 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 373if(!subdir) { 374 dir = NULL; 375break; 376} 377 dir = subdir; 378} 379 380return dir; 381} 382 383/* 384 * Find the value entry with the given name in dir, sorting ref_dirs 385 * and recursing into subdirectories as necessary. If the name is not 386 * found or it corresponds to a directory entry, return NULL. 387 */ 388static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 389{ 390int entry_index; 391struct ref_entry *entry; 392 dir =find_containing_dir(dir, refname,0); 393if(!dir) 394return NULL; 395 entry_index =search_ref_dir(dir, refname,strlen(refname)); 396if(entry_index == -1) 397return NULL; 398 entry = dir->entries[entry_index]; 399return(entry->flag & REF_DIR) ? NULL : entry; 400} 401 402/* 403 * Remove the entry with the given name from dir, recursing into 404 * subdirectories as necessary. If refname is the name of a directory 405 * (i.e., ends with '/'), then remove the directory and its contents. 406 * If the removal was successful, return the number of entries 407 * remaining in the directory entry that contained the deleted entry. 408 * If the name was not found, return -1. Please note that this 409 * function only deletes the entry from the cache; it does not delete 410 * it from the filesystem or ensure that other cache entries (which 411 * might be symbolic references to the removed entry) are updated. 412 * Nor does it remove any containing dir entries that might be made 413 * empty by the removal. dir must represent the top-level directory 414 * and must already be complete. 415 */ 416static intremove_entry(struct ref_dir *dir,const char*refname) 417{ 418int refname_len =strlen(refname); 419int entry_index; 420struct ref_entry *entry; 421int is_dir = refname[refname_len -1] =='/'; 422if(is_dir) { 423/* 424 * refname represents a reference directory. Remove 425 * the trailing slash; otherwise we will get the 426 * directory *representing* refname rather than the 427 * one *containing* it. 428 */ 429char*dirname =xmemdupz(refname, refname_len -1); 430 dir =find_containing_dir(dir, dirname,0); 431free(dirname); 432}else{ 433 dir =find_containing_dir(dir, refname,0); 434} 435if(!dir) 436return-1; 437 entry_index =search_ref_dir(dir, refname, refname_len); 438if(entry_index == -1) 439return-1; 440 entry = dir->entries[entry_index]; 441 442memmove(&dir->entries[entry_index], 443&dir->entries[entry_index +1], 444(dir->nr - entry_index -1) *sizeof(*dir->entries) 445); 446 dir->nr--; 447if(dir->sorted > entry_index) 448 dir->sorted--; 449free_ref_entry(entry); 450return dir->nr; 451} 452 453/* 454 * Add a ref_entry to the ref_dir (unsorted), recursing into 455 * subdirectories as necessary. dir must represent the top-level 456 * directory. Return 0 on success. 457 */ 458static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 459{ 460 dir =find_containing_dir(dir, ref->name,1); 461if(!dir) 462return-1; 463add_entry_to_dir(dir, ref); 464return0; 465} 466 467/* 468 * Emit a warning and return true iff ref1 and ref2 have the same name 469 * and the same sha1. Die if they have the same name but different 470 * sha1s. 471 */ 472static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 473{ 474if(strcmp(ref1->name, ref2->name)) 475return0; 476 477/* Duplicate name; make sure that they don't conflict: */ 478 479if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 480/* This is impossible by construction */ 481die("Reference directory conflict:%s", ref1->name); 482 483if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 484die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 485 486warning("Duplicated ref:%s", ref1->name); 487return1; 488} 489 490/* 491 * Sort the entries in dir non-recursively (if they are not already 492 * sorted) and remove any duplicate entries. 493 */ 494static voidsort_ref_dir(struct ref_dir *dir) 495{ 496int i, j; 497struct ref_entry *last = NULL; 498 499/* 500 * This check also prevents passing a zero-length array to qsort(), 501 * which is a problem on some platforms. 502 */ 503if(dir->sorted == dir->nr) 504return; 505 506QSORT(dir->entries, dir->nr, ref_entry_cmp); 507 508/* Remove any duplicates: */ 509for(i =0, j =0; j < dir->nr; j++) { 510struct ref_entry *entry = dir->entries[j]; 511if(last &&is_dup_ref(last, entry)) 512free_ref_entry(entry); 513else 514 last = dir->entries[i++] = entry; 515} 516 dir->sorted = dir->nr = i; 517} 518 519/* 520 * Return true if refname, which has the specified oid and flags, can 521 * be resolved to an object in the database. If the referred-to object 522 * does not exist, emit a warning and return false. 523 */ 524static intref_resolves_to_object(const char*refname, 525const struct object_id *oid, 526unsigned int flags) 527{ 528if(flags & REF_ISBROKEN) 529return0; 530if(!has_sha1_file(oid->hash)) { 531error("%sdoes not point to a valid object!", refname); 532return0; 533} 534return1; 535} 536 537/* 538 * Return true if the reference described by entry can be resolved to 539 * an object in the database; otherwise, emit a warning and return 540 * false. 541 */ 542static intentry_resolves_to_object(struct ref_entry *entry) 543{ 544returnref_resolves_to_object(entry->name, 545&entry->u.value.oid, entry->flag); 546} 547 548typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 549 550/* 551 * Call fn for each reference in dir that has index in the range 552 * offset <= index < dir->nr. Recurse into subdirectories that are in 553 * that index range, sorting them before iterating. This function 554 * does not sort dir itself; it should be sorted beforehand. fn is 555 * called for all references, including broken ones. 556 */ 557static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 558 each_ref_entry_fn fn,void*cb_data) 559{ 560int i; 561assert(dir->sorted == dir->nr); 562for(i = offset; i < dir->nr; i++) { 563struct ref_entry *entry = dir->entries[i]; 564int retval; 565if(entry->flag & REF_DIR) { 566struct ref_dir *subdir =get_ref_dir(entry); 567sort_ref_dir(subdir); 568 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 569}else{ 570 retval =fn(entry, cb_data); 571} 572if(retval) 573return retval; 574} 575return0; 576} 577 578/* 579 * Load all of the refs from the dir into our in-memory cache. The hard work 580 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 581 * through all of the sub-directories. We do not even need to care about 582 * sorting, as traversal order does not matter to us. 583 */ 584static voidprime_ref_dir(struct ref_dir *dir) 585{ 586int i; 587for(i =0; i < dir->nr; i++) { 588struct ref_entry *entry = dir->entries[i]; 589if(entry->flag & REF_DIR) 590prime_ref_dir(get_ref_dir(entry)); 591} 592} 593 594/* 595 * A level in the reference hierarchy that is currently being iterated 596 * through. 597 */ 598struct cache_ref_iterator_level { 599/* 600 * The ref_dir being iterated over at this level. The ref_dir 601 * is sorted before being stored here. 602 */ 603struct ref_dir *dir; 604 605/* 606 * The index of the current entry within dir (which might 607 * itself be a directory). If index == -1, then the iteration 608 * hasn't yet begun. If index == dir->nr, then the iteration 609 * through this level is over. 610 */ 611int index; 612}; 613 614/* 615 * Represent an iteration through a ref_dir in the memory cache. The 616 * iteration recurses through subdirectories. 617 */ 618struct cache_ref_iterator { 619struct ref_iterator base; 620 621/* 622 * The number of levels currently on the stack. This is always 623 * at least 1, because when it becomes zero the iteration is 624 * ended and this struct is freed. 625 */ 626size_t levels_nr; 627 628/* The number of levels that have been allocated on the stack */ 629size_t levels_alloc; 630 631/* 632 * A stack of levels. levels[0] is the uppermost level that is 633 * being iterated over in this iteration. (This is not 634 * necessary the top level in the references hierarchy. If we 635 * are iterating through a subtree, then levels[0] will hold 636 * the ref_dir for that subtree, and subsequent levels will go 637 * on from there.) 638 */ 639struct cache_ref_iterator_level *levels; 640}; 641 642static intcache_ref_iterator_advance(struct ref_iterator *ref_iterator) 643{ 644struct cache_ref_iterator *iter = 645(struct cache_ref_iterator *)ref_iterator; 646 647while(1) { 648struct cache_ref_iterator_level *level = 649&iter->levels[iter->levels_nr -1]; 650struct ref_dir *dir = level->dir; 651struct ref_entry *entry; 652 653if(level->index == -1) 654sort_ref_dir(dir); 655 656if(++level->index == level->dir->nr) { 657/* This level is exhausted; pop up a level */ 658if(--iter->levels_nr ==0) 659returnref_iterator_abort(ref_iterator); 660 661continue; 662} 663 664 entry = dir->entries[level->index]; 665 666if(entry->flag & REF_DIR) { 667/* push down a level */ 668ALLOC_GROW(iter->levels, iter->levels_nr +1, 669 iter->levels_alloc); 670 671 level = &iter->levels[iter->levels_nr++]; 672 level->dir =get_ref_dir(entry); 673 level->index = -1; 674}else{ 675 iter->base.refname = entry->name; 676 iter->base.oid = &entry->u.value.oid; 677 iter->base.flags = entry->flag; 678return ITER_OK; 679} 680} 681} 682 683static enum peel_status peel_entry(struct ref_entry *entry,int repeel); 684 685static intcache_ref_iterator_peel(struct ref_iterator *ref_iterator, 686struct object_id *peeled) 687{ 688struct cache_ref_iterator *iter = 689(struct cache_ref_iterator *)ref_iterator; 690struct cache_ref_iterator_level *level; 691struct ref_entry *entry; 692 693 level = &iter->levels[iter->levels_nr -1]; 694 695if(level->index == -1) 696die("BUG: peel called before advance for cache iterator"); 697 698 entry = level->dir->entries[level->index]; 699 700if(peel_entry(entry,0)) 701return-1; 702oidcpy(peeled, &entry->u.value.peeled); 703return0; 704} 705 706static intcache_ref_iterator_abort(struct ref_iterator *ref_iterator) 707{ 708struct cache_ref_iterator *iter = 709(struct cache_ref_iterator *)ref_iterator; 710 711free(iter->levels); 712base_ref_iterator_free(ref_iterator); 713return ITER_DONE; 714} 715 716static struct ref_iterator_vtable cache_ref_iterator_vtable = { 717 cache_ref_iterator_advance, 718 cache_ref_iterator_peel, 719 cache_ref_iterator_abort 720}; 721 722static struct ref_iterator *cache_ref_iterator_begin(struct ref_dir *dir) 723{ 724struct cache_ref_iterator *iter; 725struct ref_iterator *ref_iterator; 726struct cache_ref_iterator_level *level; 727 728 iter =xcalloc(1,sizeof(*iter)); 729 ref_iterator = &iter->base; 730base_ref_iterator_init(ref_iterator, &cache_ref_iterator_vtable); 731ALLOC_GROW(iter->levels,10, iter->levels_alloc); 732 733 iter->levels_nr =1; 734 level = &iter->levels[0]; 735 level->index = -1; 736 level->dir = dir; 737 738return ref_iterator; 739} 740 741struct nonmatching_ref_data { 742const struct string_list *skip; 743const char*conflicting_refname; 744}; 745 746static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 747{ 748struct nonmatching_ref_data *data = vdata; 749 750if(data->skip &&string_list_has_string(data->skip, entry->name)) 751return0; 752 753 data->conflicting_refname = entry->name; 754return1; 755} 756 757/* 758 * Return 0 if a reference named refname could be created without 759 * conflicting with the name of an existing reference in dir. 760 * See verify_refname_available for more information. 761 */ 762static intverify_refname_available_dir(const char*refname, 763const struct string_list *extras, 764const struct string_list *skip, 765struct ref_dir *dir, 766struct strbuf *err) 767{ 768const char*slash; 769const char*extra_refname; 770int pos; 771struct strbuf dirname = STRBUF_INIT; 772int ret = -1; 773 774/* 775 * For the sake of comments in this function, suppose that 776 * refname is "refs/foo/bar". 777 */ 778 779assert(err); 780 781strbuf_grow(&dirname,strlen(refname) +1); 782for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 783/* Expand dirname to the new prefix, not including the trailing slash: */ 784strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 785 786/* 787 * We are still at a leading dir of the refname (e.g., 788 * "refs/foo"; if there is a reference with that name, 789 * it is a conflict, *unless* it is in skip. 790 */ 791if(dir) { 792 pos =search_ref_dir(dir, dirname.buf, dirname.len); 793if(pos >=0&& 794(!skip || !string_list_has_string(skip, dirname.buf))) { 795/* 796 * We found a reference whose name is 797 * a proper prefix of refname; e.g., 798 * "refs/foo", and is not in skip. 799 */ 800strbuf_addf(err,"'%s' exists; cannot create '%s'", 801 dirname.buf, refname); 802goto cleanup; 803} 804} 805 806if(extras &&string_list_has_string(extras, dirname.buf) && 807(!skip || !string_list_has_string(skip, dirname.buf))) { 808strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 809 refname, dirname.buf); 810goto cleanup; 811} 812 813/* 814 * Otherwise, we can try to continue our search with 815 * the next component. So try to look up the 816 * directory, e.g., "refs/foo/". If we come up empty, 817 * we know there is nothing under this whole prefix, 818 * but even in that case we still have to continue the 819 * search for conflicts with extras. 820 */ 821strbuf_addch(&dirname,'/'); 822if(dir) { 823 pos =search_ref_dir(dir, dirname.buf, dirname.len); 824if(pos <0) { 825/* 826 * There was no directory "refs/foo/", 827 * so there is nothing under this 828 * whole prefix. So there is no need 829 * to continue looking for conflicting 830 * references. But we need to continue 831 * looking for conflicting extras. 832 */ 833 dir = NULL; 834}else{ 835 dir =get_ref_dir(dir->entries[pos]); 836} 837} 838} 839 840/* 841 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 842 * There is no point in searching for a reference with that 843 * name, because a refname isn't considered to conflict with 844 * itself. But we still need to check for references whose 845 * names are in the "refs/foo/bar/" namespace, because they 846 * *do* conflict. 847 */ 848strbuf_addstr(&dirname, refname + dirname.len); 849strbuf_addch(&dirname,'/'); 850 851if(dir) { 852 pos =search_ref_dir(dir, dirname.buf, dirname.len); 853 854if(pos >=0) { 855/* 856 * We found a directory named "$refname/" 857 * (e.g., "refs/foo/bar/"). It is a problem 858 * iff it contains any ref that is not in 859 * "skip". 860 */ 861struct nonmatching_ref_data data; 862 863 data.skip = skip; 864 data.conflicting_refname = NULL; 865 dir =get_ref_dir(dir->entries[pos]); 866sort_ref_dir(dir); 867if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 868strbuf_addf(err,"'%s' exists; cannot create '%s'", 869 data.conflicting_refname, refname); 870goto cleanup; 871} 872} 873} 874 875 extra_refname =find_descendant_ref(dirname.buf, extras, skip); 876if(extra_refname) 877strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 878 refname, extra_refname); 879else 880 ret =0; 881 882cleanup: 883strbuf_release(&dirname); 884return ret; 885} 886 887struct packed_ref_cache { 888struct ref_entry *root; 889 890/* 891 * Count of references to the data structure in this instance, 892 * including the pointer from files_ref_store::packed if any. 893 * The data will not be freed as long as the reference count 894 * is nonzero. 895 */ 896unsigned int referrers; 897 898/* 899 * Iff the packed-refs file associated with this instance is 900 * currently locked for writing, this points at the associated 901 * lock (which is owned by somebody else). The referrer count 902 * is also incremented when the file is locked and decremented 903 * when it is unlocked. 904 */ 905struct lock_file *lock; 906 907/* The metadata from when this packed-refs cache was read */ 908struct stat_validity validity; 909}; 910 911/* 912 * Future: need to be in "struct repository" 913 * when doing a full libification. 914 */ 915struct files_ref_store { 916struct ref_store base; 917unsigned int store_flags; 918 919char*gitdir; 920char*gitcommondir; 921char*packed_refs_path; 922 923struct ref_entry *loose; 924struct packed_ref_cache *packed; 925}; 926 927/* Lock used for the main packed-refs file: */ 928static struct lock_file packlock; 929 930/* 931 * Increment the reference count of *packed_refs. 932 */ 933static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 934{ 935 packed_refs->referrers++; 936} 937 938/* 939 * Decrease the reference count of *packed_refs. If it goes to zero, 940 * free *packed_refs and return true; otherwise return false. 941 */ 942static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 943{ 944if(!--packed_refs->referrers) { 945free_ref_entry(packed_refs->root); 946stat_validity_clear(&packed_refs->validity); 947free(packed_refs); 948return1; 949}else{ 950return0; 951} 952} 953 954static voidclear_packed_ref_cache(struct files_ref_store *refs) 955{ 956if(refs->packed) { 957struct packed_ref_cache *packed_refs = refs->packed; 958 959if(packed_refs->lock) 960die("internal error: packed-ref cache cleared while locked"); 961 refs->packed = NULL; 962release_packed_ref_cache(packed_refs); 963} 964} 965 966static voidclear_loose_ref_cache(struct files_ref_store *refs) 967{ 968if(refs->loose) { 969free_ref_entry(refs->loose); 970 refs->loose = NULL; 971} 972} 973 974/* 975 * Create a new submodule ref cache and add it to the internal 976 * set of caches. 977 */ 978static struct ref_store *files_ref_store_create(const char*gitdir, 979unsigned int flags) 980{ 981struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 982struct ref_store *ref_store = (struct ref_store *)refs; 983struct strbuf sb = STRBUF_INIT; 984 985base_ref_store_init(ref_store, &refs_be_files); 986 refs->store_flags = flags; 987 988 refs->gitdir =xstrdup(gitdir); 989get_common_dir_noenv(&sb, gitdir); 990 refs->gitcommondir =strbuf_detach(&sb, NULL); 991strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 992 refs->packed_refs_path =strbuf_detach(&sb, NULL); 993 994return ref_store; 995} 996 997/* 998 * Die if refs is not the main ref store. caller is used in any 999 * necessary error messages.1000 */1001static voidfiles_assert_main_repository(struct files_ref_store *refs,1002const char*caller)1003{1004if(refs->store_flags & REF_STORE_MAIN)1005return;10061007die("BUG: operation%sonly allowed for main ref store", caller);1008}10091010/*1011 * Downcast ref_store to files_ref_store. Die if ref_store is not a1012 * files_ref_store. required_flags is compared with ref_store's1013 * store_flags to ensure the ref_store has all required capabilities.1014 * "caller" is used in any necessary error messages.1015 */1016static struct files_ref_store *files_downcast(struct ref_store *ref_store,1017unsigned int required_flags,1018const char*caller)1019{1020struct files_ref_store *refs;10211022if(ref_store->be != &refs_be_files)1023die("BUG: ref_store is type\"%s\"not\"files\"in%s",1024 ref_store->be->name, caller);10251026 refs = (struct files_ref_store *)ref_store;10271028if((refs->store_flags & required_flags) != required_flags)1029die("BUG: operation%srequires abilities 0x%x, but only have 0x%x",1030 caller, required_flags, refs->store_flags);10311032return refs;1033}10341035/* The length of a peeled reference line in packed-refs, including EOL: */1036#define PEELED_LINE_LENGTH 4210371038/*1039 * The packed-refs header line that we write out. Perhaps other1040 * traits will be added later. The trailing space is required.1041 */1042static const char PACKED_REFS_HEADER[] =1043"# pack-refs with: peeled fully-peeled\n";10441045/*1046 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1047 * Return a pointer to the refname within the line (null-terminated),1048 * or NULL if there was a problem.1049 */1050static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1051{1052const char*ref;10531054/*1055 * 42: the answer to everything.1056 *1057 * In this case, it happens to be the answer to1058 * 40 (length of sha1 hex representation)1059 * +1 (space in between hex and name)1060 * +1 (newline at the end of the line)1061 */1062if(line->len <=42)1063return NULL;10641065if(get_sha1_hex(line->buf, sha1) <0)1066return NULL;1067if(!isspace(line->buf[40]))1068return NULL;10691070 ref = line->buf +41;1071if(isspace(*ref))1072return NULL;10731074if(line->buf[line->len -1] !='\n')1075return NULL;1076 line->buf[--line->len] =0;10771078return ref;1079}10801081/*1082 * Read f, which is a packed-refs file, into dir.1083 *1084 * A comment line of the form "# pack-refs with: " may contain zero or1085 * more traits. We interpret the traits as follows:1086 *1087 * No traits:1088 *1089 * Probably no references are peeled. But if the file contains a1090 * peeled value for a reference, we will use it.1091 *1092 * peeled:1093 *1094 * References under "refs/tags/", if they *can* be peeled, *are*1095 * peeled in this file. References outside of "refs/tags/" are1096 * probably not peeled even if they could have been, but if we find1097 * a peeled value for such a reference we will use it.1098 *1099 * fully-peeled:1100 *1101 * All references in the file that can be peeled are peeled.1102 * Inversely (and this is more important), any references in the1103 * file for which no peeled value is recorded is not peelable. This1104 * trait should typically be written alongside "peeled" for1105 * compatibility with older clients, but we do not require it1106 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1107 */1108static voidread_packed_refs(FILE*f,struct ref_dir *dir)1109{1110struct ref_entry *last = NULL;1111struct strbuf line = STRBUF_INIT;1112enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11131114while(strbuf_getwholeline(&line, f,'\n') != EOF) {1115unsigned char sha1[20];1116const char*refname;1117const char*traits;11181119if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1120if(strstr(traits," fully-peeled "))1121 peeled = PEELED_FULLY;1122else if(strstr(traits," peeled "))1123 peeled = PEELED_TAGS;1124/* perhaps other traits later as well */1125continue;1126}11271128 refname =parse_ref_line(&line, sha1);1129if(refname) {1130int flag = REF_ISPACKED;11311132if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1133if(!refname_is_safe(refname))1134die("packed refname is dangerous:%s", refname);1135hashclr(sha1);1136 flag |= REF_BAD_NAME | REF_ISBROKEN;1137}1138 last =create_ref_entry(refname, sha1, flag,0);1139if(peeled == PEELED_FULLY ||1140(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1141 last->flag |= REF_KNOWS_PEELED;1142add_ref(dir, last);1143continue;1144}1145if(last &&1146 line.buf[0] =='^'&&1147 line.len == PEELED_LINE_LENGTH &&1148 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1149!get_sha1_hex(line.buf +1, sha1)) {1150hashcpy(last->u.value.peeled.hash, sha1);1151/*1152 * Regardless of what the file header said,1153 * we definitely know the value of *this*1154 * reference:1155 */1156 last->flag |= REF_KNOWS_PEELED;1157}1158}11591160strbuf_release(&line);1161}11621163static const char*files_packed_refs_path(struct files_ref_store *refs)1164{1165return refs->packed_refs_path;1166}11671168static voidfiles_reflog_path(struct files_ref_store *refs,1169struct strbuf *sb,1170const char*refname)1171{1172if(!refname) {1173/*1174 * FIXME: of course this is wrong in multi worktree1175 * setting. To be fixed real soon.1176 */1177strbuf_addf(sb,"%s/logs", refs->gitcommondir);1178return;1179}11801181switch(ref_type(refname)) {1182case REF_TYPE_PER_WORKTREE:1183case REF_TYPE_PSEUDOREF:1184strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname);1185break;1186case REF_TYPE_NORMAL:1187strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname);1188break;1189default:1190die("BUG: unknown ref type%dof ref%s",1191ref_type(refname), refname);1192}1193}11941195static voidfiles_ref_path(struct files_ref_store *refs,1196struct strbuf *sb,1197const char*refname)1198{1199switch(ref_type(refname)) {1200case REF_TYPE_PER_WORKTREE:1201case REF_TYPE_PSEUDOREF:1202strbuf_addf(sb,"%s/%s", refs->gitdir, refname);1203break;1204case REF_TYPE_NORMAL:1205strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname);1206break;1207default:1208die("BUG: unknown ref type%dof ref%s",1209ref_type(refname), refname);1210}1211}12121213/*1214 * Get the packed_ref_cache for the specified files_ref_store,1215 * creating it if necessary.1216 */1217static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs)1218{1219const char*packed_refs_file =files_packed_refs_path(refs);12201221if(refs->packed &&1222!stat_validity_check(&refs->packed->validity, packed_refs_file))1223clear_packed_ref_cache(refs);12241225if(!refs->packed) {1226FILE*f;12271228 refs->packed =xcalloc(1,sizeof(*refs->packed));1229acquire_packed_ref_cache(refs->packed);1230 refs->packed->root =create_dir_entry(refs,"",0,0);1231 f =fopen(packed_refs_file,"r");1232if(f) {1233stat_validity_update(&refs->packed->validity,fileno(f));1234read_packed_refs(f,get_ref_dir(refs->packed->root));1235fclose(f);1236}1237}1238return refs->packed;1239}12401241static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1242{1243returnget_ref_dir(packed_ref_cache->root);1244}12451246static struct ref_dir *get_packed_refs(struct files_ref_store *refs)1247{1248returnget_packed_ref_dir(get_packed_ref_cache(refs));1249}12501251/*1252 * Add a reference to the in-memory packed reference cache. This may1253 * only be called while the packed-refs file is locked (see1254 * lock_packed_refs()). To actually write the packed-refs file, call1255 * commit_packed_refs().1256 */1257static voidadd_packed_ref(struct files_ref_store *refs,1258const char*refname,const unsigned char*sha1)1259{1260struct packed_ref_cache *packed_ref_cache =get_packed_ref_cache(refs);12611262if(!packed_ref_cache->lock)1263die("internal error: packed refs not locked");1264add_ref(get_packed_ref_dir(packed_ref_cache),1265create_ref_entry(refname, sha1, REF_ISPACKED,1));1266}12671268/*1269 * Read the loose references from the namespace dirname into dir1270 * (without recursing). dirname must end with '/'. dir must be the1271 * directory entry corresponding to dirname.1272 */1273static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1274{1275struct files_ref_store *refs = dir->ref_store;1276DIR*d;1277struct dirent *de;1278int dirnamelen =strlen(dirname);1279struct strbuf refname;1280struct strbuf path = STRBUF_INIT;1281size_t path_baselen;12821283files_ref_path(refs, &path, dirname);1284 path_baselen = path.len;12851286 d =opendir(path.buf);1287if(!d) {1288strbuf_release(&path);1289return;1290}12911292strbuf_init(&refname, dirnamelen +257);1293strbuf_add(&refname, dirname, dirnamelen);12941295while((de =readdir(d)) != NULL) {1296unsigned char sha1[20];1297struct stat st;1298int flag;12991300if(de->d_name[0] =='.')1301continue;1302if(ends_with(de->d_name,".lock"))1303continue;1304strbuf_addstr(&refname, de->d_name);1305strbuf_addstr(&path, de->d_name);1306if(stat(path.buf, &st) <0) {1307;/* silently ignore */1308}else if(S_ISDIR(st.st_mode)) {1309strbuf_addch(&refname,'/');1310add_entry_to_dir(dir,1311create_dir_entry(refs, refname.buf,1312 refname.len,1));1313}else{1314if(!refs_resolve_ref_unsafe(&refs->base,1315 refname.buf,1316 RESOLVE_REF_READING,1317 sha1, &flag)) {1318hashclr(sha1);1319 flag |= REF_ISBROKEN;1320}else if(is_null_sha1(sha1)) {1321/*1322 * It is so astronomically unlikely1323 * that NULL_SHA1 is the SHA-1 of an1324 * actual object that we consider its1325 * appearance in a loose reference1326 * file to be repo corruption1327 * (probably due to a software bug).1328 */1329 flag |= REF_ISBROKEN;1330}13311332if(check_refname_format(refname.buf,1333 REFNAME_ALLOW_ONELEVEL)) {1334if(!refname_is_safe(refname.buf))1335die("loose refname is dangerous:%s", refname.buf);1336hashclr(sha1);1337 flag |= REF_BAD_NAME | REF_ISBROKEN;1338}1339add_entry_to_dir(dir,1340create_ref_entry(refname.buf, sha1, flag,0));1341}1342strbuf_setlen(&refname, dirnamelen);1343strbuf_setlen(&path, path_baselen);1344}1345strbuf_release(&refname);1346strbuf_release(&path);1347closedir(d);1348}13491350static struct ref_dir *get_loose_refs(struct files_ref_store *refs)1351{1352if(!refs->loose) {1353/*1354 * Mark the top-level directory complete because we1355 * are about to read the only subdirectory that can1356 * hold references:1357 */1358 refs->loose =create_dir_entry(refs,"",0,0);1359/*1360 * Create an incomplete entry for "refs/":1361 */1362add_entry_to_dir(get_ref_dir(refs->loose),1363create_dir_entry(refs,"refs/",5,1));1364}1365returnget_ref_dir(refs->loose);1366}13671368/*1369 * Return the ref_entry for the given refname from the packed1370 * references. If it does not exist, return NULL.1371 */1372static struct ref_entry *get_packed_ref(struct files_ref_store *refs,1373const char*refname)1374{1375returnfind_ref(get_packed_refs(refs), refname);1376}13771378/*1379 * A loose ref file doesn't exist; check for a packed ref.1380 */1381static intresolve_packed_ref(struct files_ref_store *refs,1382const char*refname,1383unsigned char*sha1,unsigned int*flags)1384{1385struct ref_entry *entry;13861387/*1388 * The loose reference file does not exist; check for a packed1389 * reference.1390 */1391 entry =get_packed_ref(refs, refname);1392if(entry) {1393hashcpy(sha1, entry->u.value.oid.hash);1394*flags |= REF_ISPACKED;1395return0;1396}1397/* refname is not a packed reference. */1398return-1;1399}14001401static intfiles_read_raw_ref(struct ref_store *ref_store,1402const char*refname,unsigned char*sha1,1403struct strbuf *referent,unsigned int*type)1404{1405struct files_ref_store *refs =1406files_downcast(ref_store, REF_STORE_READ,"read_raw_ref");1407struct strbuf sb_contents = STRBUF_INIT;1408struct strbuf sb_path = STRBUF_INIT;1409const char*path;1410const char*buf;1411struct stat st;1412int fd;1413int ret = -1;1414int save_errno;1415int remaining_retries =3;14161417*type =0;1418strbuf_reset(&sb_path);14191420files_ref_path(refs, &sb_path, refname);14211422 path = sb_path.buf;14231424stat_ref:1425/*1426 * We might have to loop back here to avoid a race1427 * condition: first we lstat() the file, then we try1428 * to read it as a link or as a file. But if somebody1429 * changes the type of the file (file <-> directory1430 * <-> symlink) between the lstat() and reading, then1431 * we don't want to report that as an error but rather1432 * try again starting with the lstat().1433 *1434 * We'll keep a count of the retries, though, just to avoid1435 * any confusing situation sending us into an infinite loop.1436 */14371438if(remaining_retries-- <=0)1439goto out;14401441if(lstat(path, &st) <0) {1442if(errno != ENOENT)1443goto out;1444if(resolve_packed_ref(refs, refname, sha1, type)) {1445 errno = ENOENT;1446goto out;1447}1448 ret =0;1449goto out;1450}14511452/* Follow "normalized" - ie "refs/.." symlinks by hand */1453if(S_ISLNK(st.st_mode)) {1454strbuf_reset(&sb_contents);1455if(strbuf_readlink(&sb_contents, path,0) <0) {1456if(errno == ENOENT || errno == EINVAL)1457/* inconsistent with lstat; retry */1458goto stat_ref;1459else1460goto out;1461}1462if(starts_with(sb_contents.buf,"refs/") &&1463!check_refname_format(sb_contents.buf,0)) {1464strbuf_swap(&sb_contents, referent);1465*type |= REF_ISSYMREF;1466 ret =0;1467goto out;1468}1469/*1470 * It doesn't look like a refname; fall through to just1471 * treating it like a non-symlink, and reading whatever it1472 * points to.1473 */1474}14751476/* Is it a directory? */1477if(S_ISDIR(st.st_mode)) {1478/*1479 * Even though there is a directory where the loose1480 * ref is supposed to be, there could still be a1481 * packed ref:1482 */1483if(resolve_packed_ref(refs, refname, sha1, type)) {1484 errno = EISDIR;1485goto out;1486}1487 ret =0;1488goto out;1489}14901491/*1492 * Anything else, just open it and try to use it as1493 * a ref1494 */1495 fd =open(path, O_RDONLY);1496if(fd <0) {1497if(errno == ENOENT && !S_ISLNK(st.st_mode))1498/* inconsistent with lstat; retry */1499goto stat_ref;1500else1501goto out;1502}1503strbuf_reset(&sb_contents);1504if(strbuf_read(&sb_contents, fd,256) <0) {1505int save_errno = errno;1506close(fd);1507 errno = save_errno;1508goto out;1509}1510close(fd);1511strbuf_rtrim(&sb_contents);1512 buf = sb_contents.buf;1513if(starts_with(buf,"ref:")) {1514 buf +=4;1515while(isspace(*buf))1516 buf++;15171518strbuf_reset(referent);1519strbuf_addstr(referent, buf);1520*type |= REF_ISSYMREF;1521 ret =0;1522goto out;1523}15241525/*1526 * Please note that FETCH_HEAD has additional1527 * data after the sha.1528 */1529if(get_sha1_hex(buf, sha1) ||1530(buf[40] !='\0'&& !isspace(buf[40]))) {1531*type |= REF_ISBROKEN;1532 errno = EINVAL;1533goto out;1534}15351536 ret =0;15371538out:1539 save_errno = errno;1540strbuf_release(&sb_path);1541strbuf_release(&sb_contents);1542 errno = save_errno;1543return ret;1544}15451546static voidunlock_ref(struct ref_lock *lock)1547{1548/* Do not free lock->lk -- atexit() still looks at them */1549if(lock->lk)1550rollback_lock_file(lock->lk);1551free(lock->ref_name);1552free(lock);1553}15541555/*1556 * Lock refname, without following symrefs, and set *lock_p to point1557 * at a newly-allocated lock object. Fill in lock->old_oid, referent,1558 * and type similarly to read_raw_ref().1559 *1560 * The caller must verify that refname is a "safe" reference name (in1561 * the sense of refname_is_safe()) before calling this function.1562 *1563 * If the reference doesn't already exist, verify that refname doesn't1564 * have a D/F conflict with any existing references. extras and skip1565 * are passed to verify_refname_available_dir() for this check.1566 *1567 * If mustexist is not set and the reference is not found or is1568 * broken, lock the reference anyway but clear sha1.1569 *1570 * Return 0 on success. On failure, write an error message to err and1571 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.1572 *1573 * Implementation note: This function is basically1574 *1575 * lock reference1576 * read_raw_ref()1577 *1578 * but it includes a lot more code to1579 * - Deal with possible races with other processes1580 * - Avoid calling verify_refname_available_dir() when it can be1581 * avoided, namely if we were successfully able to read the ref1582 * - Generate informative error messages in the case of failure1583 */1584static intlock_raw_ref(struct files_ref_store *refs,1585const char*refname,int mustexist,1586const struct string_list *extras,1587const struct string_list *skip,1588struct ref_lock **lock_p,1589struct strbuf *referent,1590unsigned int*type,1591struct strbuf *err)1592{1593struct ref_lock *lock;1594struct strbuf ref_file = STRBUF_INIT;1595int attempts_remaining =3;1596int ret = TRANSACTION_GENERIC_ERROR;15971598assert(err);1599files_assert_main_repository(refs,"lock_raw_ref");16001601*type =0;16021603/* First lock the file so it can't change out from under us. */16041605*lock_p = lock =xcalloc(1,sizeof(*lock));16061607 lock->ref_name =xstrdup(refname);1608files_ref_path(refs, &ref_file, refname);16091610retry:1611switch(safe_create_leading_directories(ref_file.buf)) {1612case SCLD_OK:1613break;/* success */1614case SCLD_EXISTS:1615/*1616 * Suppose refname is "refs/foo/bar". We just failed1617 * to create the containing directory, "refs/foo",1618 * because there was a non-directory in the way. This1619 * indicates a D/F conflict, probably because of1620 * another reference such as "refs/foo". There is no1621 * reason to expect this error to be transitory.1622 */1623if(refs_verify_refname_available(&refs->base, refname,1624 extras, skip, err)) {1625if(mustexist) {1626/*1627 * To the user the relevant error is1628 * that the "mustexist" reference is1629 * missing:1630 */1631strbuf_reset(err);1632strbuf_addf(err,"unable to resolve reference '%s'",1633 refname);1634}else{1635/*1636 * The error message set by1637 * verify_refname_available_dir() is OK.1638 */1639 ret = TRANSACTION_NAME_CONFLICT;1640}1641}else{1642/*1643 * The file that is in the way isn't a loose1644 * reference. Report it as a low-level1645 * failure.1646 */1647strbuf_addf(err,"unable to create lock file%s.lock; "1648"non-directory in the way",1649 ref_file.buf);1650}1651goto error_return;1652case SCLD_VANISHED:1653/* Maybe another process was tidying up. Try again. */1654if(--attempts_remaining >0)1655goto retry;1656/* fall through */1657default:1658strbuf_addf(err,"unable to create directory for%s",1659 ref_file.buf);1660goto error_return;1661}16621663if(!lock->lk)1664 lock->lk =xcalloc(1,sizeof(struct lock_file));16651666if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) {1667if(errno == ENOENT && --attempts_remaining >0) {1668/*1669 * Maybe somebody just deleted one of the1670 * directories leading to ref_file. Try1671 * again:1672 */1673goto retry;1674}else{1675unable_to_lock_message(ref_file.buf, errno, err);1676goto error_return;1677}1678}16791680/*1681 * Now we hold the lock and can read the reference without1682 * fear that its value will change.1683 */16841685if(files_read_raw_ref(&refs->base, refname,1686 lock->old_oid.hash, referent, type)) {1687if(errno == ENOENT) {1688if(mustexist) {1689/* Garden variety missing reference. */1690strbuf_addf(err,"unable to resolve reference '%s'",1691 refname);1692goto error_return;1693}else{1694/*1695 * Reference is missing, but that's OK. We1696 * know that there is not a conflict with1697 * another loose reference because1698 * (supposing that we are trying to lock1699 * reference "refs/foo/bar"):1700 *1701 * - We were successfully able to create1702 * the lockfile refs/foo/bar.lock, so we1703 * know there cannot be a loose reference1704 * named "refs/foo".1705 *1706 * - We got ENOENT and not EISDIR, so we1707 * know that there cannot be a loose1708 * reference named "refs/foo/bar/baz".1709 */1710}1711}else if(errno == EISDIR) {1712/*1713 * There is a directory in the way. It might have1714 * contained references that have been deleted. If1715 * we don't require that the reference already1716 * exists, try to remove the directory so that it1717 * doesn't cause trouble when we want to rename the1718 * lockfile into place later.1719 */1720if(mustexist) {1721/* Garden variety missing reference. */1722strbuf_addf(err,"unable to resolve reference '%s'",1723 refname);1724goto error_return;1725}else if(remove_dir_recursively(&ref_file,1726 REMOVE_DIR_EMPTY_ONLY)) {1727if(verify_refname_available_dir(1728 refname, extras, skip,1729get_loose_refs(refs),1730 err)) {1731/*1732 * The error message set by1733 * verify_refname_available() is OK.1734 */1735 ret = TRANSACTION_NAME_CONFLICT;1736goto error_return;1737}else{1738/*1739 * We can't delete the directory,1740 * but we also don't know of any1741 * references that it should1742 * contain.1743 */1744strbuf_addf(err,"there is a non-empty directory '%s' "1745"blocking reference '%s'",1746 ref_file.buf, refname);1747goto error_return;1748}1749}1750}else if(errno == EINVAL && (*type & REF_ISBROKEN)) {1751strbuf_addf(err,"unable to resolve reference '%s': "1752"reference broken", refname);1753goto error_return;1754}else{1755strbuf_addf(err,"unable to resolve reference '%s':%s",1756 refname,strerror(errno));1757goto error_return;1758}17591760/*1761 * If the ref did not exist and we are creating it,1762 * make sure there is no existing packed ref whose1763 * name begins with our refname, nor a packed ref1764 * whose name is a proper prefix of our refname.1765 */1766if(verify_refname_available_dir(1767 refname, extras, skip,1768get_packed_refs(refs),1769 err)) {1770goto error_return;1771}1772}17731774 ret =0;1775goto out;17761777error_return:1778unlock_ref(lock);1779*lock_p = NULL;17801781out:1782strbuf_release(&ref_file);1783return ret;1784}17851786/*1787 * Peel the entry (if possible) and return its new peel_status. If1788 * repeel is true, re-peel the entry even if there is an old peeled1789 * value that is already stored in it.1790 *1791 * It is OK to call this function with a packed reference entry that1792 * might be stale and might even refer to an object that has since1793 * been garbage-collected. In such a case, if the entry has1794 * REF_KNOWS_PEELED then leave the status unchanged and return1795 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1796 */1797static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1798{1799enum peel_status status;18001801if(entry->flag & REF_KNOWS_PEELED) {1802if(repeel) {1803 entry->flag &= ~REF_KNOWS_PEELED;1804oidclr(&entry->u.value.peeled);1805}else{1806returnis_null_oid(&entry->u.value.peeled) ?1807 PEEL_NON_TAG : PEEL_PEELED;1808}1809}1810if(entry->flag & REF_ISBROKEN)1811return PEEL_BROKEN;1812if(entry->flag & REF_ISSYMREF)1813return PEEL_IS_SYMREF;18141815 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1816if(status == PEEL_PEELED || status == PEEL_NON_TAG)1817 entry->flag |= REF_KNOWS_PEELED;1818return status;1819}18201821static intfiles_peel_ref(struct ref_store *ref_store,1822const char*refname,unsigned char*sha1)1823{1824struct files_ref_store *refs =1825files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,1826"peel_ref");1827int flag;1828unsigned char base[20];18291830if(current_ref_iter && current_ref_iter->refname == refname) {1831struct object_id peeled;18321833if(ref_iterator_peel(current_ref_iter, &peeled))1834return-1;1835hashcpy(sha1, peeled.hash);1836return0;1837}18381839if(refs_read_ref_full(ref_store, refname,1840 RESOLVE_REF_READING, base, &flag))1841return-1;18421843/*1844 * If the reference is packed, read its ref_entry from the1845 * cache in the hope that we already know its peeled value.1846 * We only try this optimization on packed references because1847 * (a) forcing the filling of the loose reference cache could1848 * be expensive and (b) loose references anyway usually do not1849 * have REF_KNOWS_PEELED.1850 */1851if(flag & REF_ISPACKED) {1852struct ref_entry *r =get_packed_ref(refs, refname);1853if(r) {1854if(peel_entry(r,0))1855return-1;1856hashcpy(sha1, r->u.value.peeled.hash);1857return0;1858}1859}18601861returnpeel_object(base, sha1);1862}18631864struct files_ref_iterator {1865struct ref_iterator base;18661867struct packed_ref_cache *packed_ref_cache;1868struct ref_iterator *iter0;1869unsigned int flags;1870};18711872static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1873{1874struct files_ref_iterator *iter =1875(struct files_ref_iterator *)ref_iterator;1876int ok;18771878while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1879if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1880ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1881continue;18821883if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1884!ref_resolves_to_object(iter->iter0->refname,1885 iter->iter0->oid,1886 iter->iter0->flags))1887continue;18881889 iter->base.refname = iter->iter0->refname;1890 iter->base.oid = iter->iter0->oid;1891 iter->base.flags = iter->iter0->flags;1892return ITER_OK;1893}18941895 iter->iter0 = NULL;1896if(ref_iterator_abort(ref_iterator) != ITER_DONE)1897 ok = ITER_ERROR;18981899return ok;1900}19011902static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1903struct object_id *peeled)1904{1905struct files_ref_iterator *iter =1906(struct files_ref_iterator *)ref_iterator;19071908returnref_iterator_peel(iter->iter0, peeled);1909}19101911static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1912{1913struct files_ref_iterator *iter =1914(struct files_ref_iterator *)ref_iterator;1915int ok = ITER_DONE;19161917if(iter->iter0)1918 ok =ref_iterator_abort(iter->iter0);19191920release_packed_ref_cache(iter->packed_ref_cache);1921base_ref_iterator_free(ref_iterator);1922return ok;1923}19241925static struct ref_iterator_vtable files_ref_iterator_vtable = {1926 files_ref_iterator_advance,1927 files_ref_iterator_peel,1928 files_ref_iterator_abort1929};19301931static struct ref_iterator *files_ref_iterator_begin(1932struct ref_store *ref_store,1933const char*prefix,unsigned int flags)1934{1935struct files_ref_store *refs;1936struct ref_dir *loose_dir, *packed_dir;1937struct ref_iterator *loose_iter, *packed_iter;1938struct files_ref_iterator *iter;1939struct ref_iterator *ref_iterator;19401941if(ref_paranoia <0)1942 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1943if(ref_paranoia)1944 flags |= DO_FOR_EACH_INCLUDE_BROKEN;19451946 refs =files_downcast(ref_store,1947 REF_STORE_READ | (ref_paranoia ?0: REF_STORE_ODB),1948"ref_iterator_begin");19491950 iter =xcalloc(1,sizeof(*iter));1951 ref_iterator = &iter->base;1952base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);19531954/*1955 * We must make sure that all loose refs are read before1956 * accessing the packed-refs file; this avoids a race1957 * condition if loose refs are migrated to the packed-refs1958 * file by a simultaneous process, but our in-memory view is1959 * from before the migration. We ensure this as follows:1960 * First, we call prime_ref_dir(), which pre-reads the loose1961 * references for the subtree into the cache. (If they've1962 * already been read, that's OK; we only need to guarantee1963 * that they're read before the packed refs, not *how much*1964 * before.) After that, we call get_packed_ref_cache(), which1965 * internally checks whether the packed-ref cache is up to1966 * date with what is on disk, and re-reads it if not.1967 */19681969 loose_dir =get_loose_refs(refs);19701971if(prefix && *prefix)1972 loose_dir =find_containing_dir(loose_dir, prefix,0);19731974if(loose_dir) {1975prime_ref_dir(loose_dir);1976 loose_iter =cache_ref_iterator_begin(loose_dir);1977}else{1978/* There's nothing to iterate over. */1979 loose_iter =empty_ref_iterator_begin();1980}19811982 iter->packed_ref_cache =get_packed_ref_cache(refs);1983acquire_packed_ref_cache(iter->packed_ref_cache);1984 packed_dir =get_packed_ref_dir(iter->packed_ref_cache);19851986if(prefix && *prefix)1987 packed_dir =find_containing_dir(packed_dir, prefix,0);19881989if(packed_dir) {1990 packed_iter =cache_ref_iterator_begin(packed_dir);1991}else{1992/* There's nothing to iterate over. */1993 packed_iter =empty_ref_iterator_begin();1994}19951996 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1997 iter->flags = flags;19981999return ref_iterator;2000}20012002/*2003 * Verify that the reference locked by lock has the value old_sha1.2004 * Fail if the reference doesn't exist and mustexist is set. Return 02005 * on success. On error, write an error message to err, set errno, and2006 * return a negative value.2007 */2008static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,2009const unsigned char*old_sha1,int mustexist,2010struct strbuf *err)2011{2012assert(err);20132014if(refs_read_ref_full(ref_store, lock->ref_name,2015 mustexist ? RESOLVE_REF_READING :0,2016 lock->old_oid.hash, NULL)) {2017if(old_sha1) {2018int save_errno = errno;2019strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);2020 errno = save_errno;2021return-1;2022}else{2023oidclr(&lock->old_oid);2024return0;2025}2026}2027if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {2028strbuf_addf(err,"ref '%s' is at%sbut expected%s",2029 lock->ref_name,2030oid_to_hex(&lock->old_oid),2031sha1_to_hex(old_sha1));2032 errno = EBUSY;2033return-1;2034}2035return0;2036}20372038static intremove_empty_directories(struct strbuf *path)2039{2040/*2041 * we want to create a file but there is a directory there;2042 * if that is an empty directory (or a directory that contains2043 * only empty directories), remove them.2044 */2045returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);2046}20472048static intcreate_reflock(const char*path,void*cb)2049{2050struct lock_file *lk = cb;20512052returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;2053}20542055/*2056 * Locks a ref returning the lock on success and NULL on failure.2057 * On failure errno is set to something meaningful.2058 */2059static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,2060const char*refname,2061const unsigned char*old_sha1,2062const struct string_list *extras,2063const struct string_list *skip,2064unsigned int flags,int*type,2065struct strbuf *err)2066{2067struct strbuf ref_file = STRBUF_INIT;2068struct ref_lock *lock;2069int last_errno =0;2070int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2071int resolve_flags = RESOLVE_REF_NO_RECURSE;2072int resolved;20732074files_assert_main_repository(refs,"lock_ref_sha1_basic");2075assert(err);20762077 lock =xcalloc(1,sizeof(struct ref_lock));20782079if(mustexist)2080 resolve_flags |= RESOLVE_REF_READING;2081if(flags & REF_DELETING)2082 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;20832084files_ref_path(refs, &ref_file, refname);2085 resolved = !!refs_resolve_ref_unsafe(&refs->base,2086 refname, resolve_flags,2087 lock->old_oid.hash, type);2088if(!resolved && errno == EISDIR) {2089/*2090 * we are trying to lock foo but we used to2091 * have foo/bar which now does not exist;2092 * it is normal for the empty directory 'foo'2093 * to remain.2094 */2095if(remove_empty_directories(&ref_file)) {2096 last_errno = errno;2097if(!verify_refname_available_dir(2098 refname, extras, skip,2099get_loose_refs(refs), err))2100strbuf_addf(err,"there are still refs under '%s'",2101 refname);2102goto error_return;2103}2104 resolved = !!refs_resolve_ref_unsafe(&refs->base,2105 refname, resolve_flags,2106 lock->old_oid.hash, type);2107}2108if(!resolved) {2109 last_errno = errno;2110if(last_errno != ENOTDIR ||2111!verify_refname_available_dir(2112 refname, extras, skip,2113get_loose_refs(refs), err))2114strbuf_addf(err,"unable to resolve reference '%s':%s",2115 refname,strerror(last_errno));21162117goto error_return;2118}21192120/*2121 * If the ref did not exist and we are creating it, make sure2122 * there is no existing packed ref whose name begins with our2123 * refname, nor a packed ref whose name is a proper prefix of2124 * our refname.2125 */2126if(is_null_oid(&lock->old_oid) &&2127verify_refname_available_dir(refname, extras, skip,2128get_packed_refs(refs),2129 err)) {2130 last_errno = ENOTDIR;2131goto error_return;2132}21332134 lock->lk =xcalloc(1,sizeof(struct lock_file));21352136 lock->ref_name =xstrdup(refname);21372138if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {2139 last_errno = errno;2140unable_to_lock_message(ref_file.buf, errno, err);2141goto error_return;2142}21432144if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {2145 last_errno = errno;2146goto error_return;2147}2148goto out;21492150 error_return:2151unlock_ref(lock);2152 lock = NULL;21532154 out:2155strbuf_release(&ref_file);2156 errno = last_errno;2157return lock;2158}21592160/*2161 * Write an entry to the packed-refs file for the specified refname.2162 * If peeled is non-NULL, write it as the entry's peeled value.2163 */2164static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2165unsigned char*peeled)2166{2167fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2168if(peeled)2169fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2170}21712172/*2173 * An each_ref_entry_fn that writes the entry to a packed-refs file.2174 */2175static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2176{2177enum peel_status peel_status =peel_entry(entry,0);21782179if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2180error("internal error:%sis not a valid packed reference!",2181 entry->name);2182write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2183 peel_status == PEEL_PEELED ?2184 entry->u.value.peeled.hash : NULL);2185return0;2186}21872188/*2189 * Lock the packed-refs file for writing. Flags is passed to2190 * hold_lock_file_for_update(). Return 0 on success. On errors, set2191 * errno appropriately and return a nonzero value.2192 */2193static intlock_packed_refs(struct files_ref_store *refs,int flags)2194{2195static int timeout_configured =0;2196static int timeout_value =1000;2197struct packed_ref_cache *packed_ref_cache;21982199files_assert_main_repository(refs,"lock_packed_refs");22002201if(!timeout_configured) {2202git_config_get_int("core.packedrefstimeout", &timeout_value);2203 timeout_configured =1;2204}22052206if(hold_lock_file_for_update_timeout(2207&packlock,files_packed_refs_path(refs),2208 flags, timeout_value) <0)2209return-1;2210/*2211 * Get the current packed-refs while holding the lock. If the2212 * packed-refs file has been modified since we last read it,2213 * this will automatically invalidate the cache and re-read2214 * the packed-refs file.2215 */2216 packed_ref_cache =get_packed_ref_cache(refs);2217 packed_ref_cache->lock = &packlock;2218/* Increment the reference count to prevent it from being freed: */2219acquire_packed_ref_cache(packed_ref_cache);2220return0;2221}22222223/*2224 * Write the current version of the packed refs cache from memory to2225 * disk. The packed-refs file must already be locked for writing (see2226 * lock_packed_refs()). Return zero on success. On errors, set errno2227 * and return a nonzero value2228 */2229static intcommit_packed_refs(struct files_ref_store *refs)2230{2231struct packed_ref_cache *packed_ref_cache =2232get_packed_ref_cache(refs);2233int error =0;2234int save_errno =0;2235FILE*out;22362237files_assert_main_repository(refs,"commit_packed_refs");22382239if(!packed_ref_cache->lock)2240die("internal error: packed-refs not locked");22412242 out =fdopen_lock_file(packed_ref_cache->lock,"w");2243if(!out)2244die_errno("unable to fdopen packed-refs descriptor");22452246fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2247do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),22480, write_packed_entry_fn, out);22492250if(commit_lock_file(packed_ref_cache->lock)) {2251 save_errno = errno;2252 error = -1;2253}2254 packed_ref_cache->lock = NULL;2255release_packed_ref_cache(packed_ref_cache);2256 errno = save_errno;2257return error;2258}22592260/*2261 * Rollback the lockfile for the packed-refs file, and discard the2262 * in-memory packed reference cache. (The packed-refs file will be2263 * read anew if it is needed again after this function is called.)2264 */2265static voidrollback_packed_refs(struct files_ref_store *refs)2266{2267struct packed_ref_cache *packed_ref_cache =2268get_packed_ref_cache(refs);22692270files_assert_main_repository(refs,"rollback_packed_refs");22712272if(!packed_ref_cache->lock)2273die("internal error: packed-refs not locked");2274rollback_lock_file(packed_ref_cache->lock);2275 packed_ref_cache->lock = NULL;2276release_packed_ref_cache(packed_ref_cache);2277clear_packed_ref_cache(refs);2278}22792280struct ref_to_prune {2281struct ref_to_prune *next;2282unsigned char sha1[20];2283char name[FLEX_ARRAY];2284};22852286struct pack_refs_cb_data {2287unsigned int flags;2288struct ref_dir *packed_refs;2289struct ref_to_prune *ref_to_prune;2290};22912292/*2293 * An each_ref_entry_fn that is run over loose references only. If2294 * the loose reference can be packed, add an entry in the packed ref2295 * cache. If the reference should be pruned, also add it to2296 * ref_to_prune in the pack_refs_cb_data.2297 */2298static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2299{2300struct pack_refs_cb_data *cb = cb_data;2301enum peel_status peel_status;2302struct ref_entry *packed_entry;2303int is_tag_ref =starts_with(entry->name,"refs/tags/");23042305/* Do not pack per-worktree refs: */2306if(ref_type(entry->name) != REF_TYPE_NORMAL)2307return0;23082309/* ALWAYS pack tags */2310if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2311return0;23122313/* Do not pack symbolic or broken refs: */2314if((entry->flag & REF_ISSYMREF) || !entry_resolves_to_object(entry))2315return0;23162317/* Add a packed ref cache entry equivalent to the loose entry. */2318 peel_status =peel_entry(entry,1);2319if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2320die("internal error peeling reference%s(%s)",2321 entry->name,oid_to_hex(&entry->u.value.oid));2322 packed_entry =find_ref(cb->packed_refs, entry->name);2323if(packed_entry) {2324/* Overwrite existing packed entry with info from loose entry */2325 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2326oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2327}else{2328 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2329 REF_ISPACKED | REF_KNOWS_PEELED,0);2330add_ref(cb->packed_refs, packed_entry);2331}2332oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);23332334/* Schedule the loose reference for pruning if requested. */2335if((cb->flags & PACK_REFS_PRUNE)) {2336struct ref_to_prune *n;2337FLEX_ALLOC_STR(n, name, entry->name);2338hashcpy(n->sha1, entry->u.value.oid.hash);2339 n->next = cb->ref_to_prune;2340 cb->ref_to_prune = n;2341}2342return0;2343}23442345enum{2346 REMOVE_EMPTY_PARENTS_REF =0x01,2347 REMOVE_EMPTY_PARENTS_REFLOG =0x022348};23492350/*2351 * Remove empty parent directories associated with the specified2352 * reference and/or its reflog, but spare [logs/]refs/ and immediate2353 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or2354 * REMOVE_EMPTY_PARENTS_REFLOG.2355 */2356static voidtry_remove_empty_parents(struct files_ref_store *refs,2357const char*refname,2358unsigned int flags)2359{2360struct strbuf buf = STRBUF_INIT;2361struct strbuf sb = STRBUF_INIT;2362char*p, *q;2363int i;23642365strbuf_addstr(&buf, refname);2366 p = buf.buf;2367for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2368while(*p && *p !='/')2369 p++;2370/* tolerate duplicate slashes; see check_refname_format() */2371while(*p =='/')2372 p++;2373}2374 q = buf.buf + buf.len;2375while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {2376while(q > p && *q !='/')2377 q--;2378while(q > p && *(q-1) =='/')2379 q--;2380if(q == p)2381break;2382strbuf_setlen(&buf, q - buf.buf);23832384strbuf_reset(&sb);2385files_ref_path(refs, &sb, buf.buf);2386if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))2387 flags &= ~REMOVE_EMPTY_PARENTS_REF;23882389strbuf_reset(&sb);2390files_reflog_path(refs, &sb, buf.buf);2391if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))2392 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;2393}2394strbuf_release(&buf);2395strbuf_release(&sb);2396}23972398/* make sure nobody touched the ref, and unlink */2399static voidprune_ref(struct files_ref_store *refs,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_store_transaction_begin(&refs->base, &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);2419}24202421static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)2422{2423while(r) {2424prune_ref(refs, r);2425 r = r->next;2426}2427}24282429static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)2430{2431struct files_ref_store *refs =2432files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,2433"pack_refs");2434struct pack_refs_cb_data cbdata;24352436memset(&cbdata,0,sizeof(cbdata));2437 cbdata.flags = flags;24382439lock_packed_refs(refs, LOCK_DIE_ON_ERROR);2440 cbdata.packed_refs =get_packed_refs(refs);24412442do_for_each_entry_in_dir(get_loose_refs(refs),0,2443 pack_if_possible_fn, &cbdata);24442445if(commit_packed_refs(refs))2446die_errno("unable to overwrite old ref-pack file");24472448prune_refs(refs, cbdata.ref_to_prune);2449return0;2450}24512452/*2453 * Rewrite the packed-refs file, omitting any refs listed in2454 * 'refnames'. On error, leave packed-refs unchanged, write an error2455 * message to 'err', and return a nonzero value.2456 *2457 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2458 */2459static intrepack_without_refs(struct files_ref_store *refs,2460struct string_list *refnames,struct strbuf *err)2461{2462struct ref_dir *packed;2463struct string_list_item *refname;2464int ret, needs_repacking =0, removed =0;24652466files_assert_main_repository(refs,"repack_without_refs");2467assert(err);24682469/* Look for a packed ref */2470for_each_string_list_item(refname, refnames) {2471if(get_packed_ref(refs, refname->string)) {2472 needs_repacking =1;2473break;2474}2475}24762477/* Avoid locking if we have nothing to do */2478if(!needs_repacking)2479return0;/* no refname exists in packed refs */24802481if(lock_packed_refs(refs,0)) {2482unable_to_lock_message(files_packed_refs_path(refs), errno, err);2483return-1;2484}2485 packed =get_packed_refs(refs);24862487/* Remove refnames from the cache */2488for_each_string_list_item(refname, refnames)2489if(remove_entry(packed, refname->string) != -1)2490 removed =1;2491if(!removed) {2492/*2493 * All packed entries disappeared while we were2494 * acquiring the lock.2495 */2496rollback_packed_refs(refs);2497return0;2498}24992500/* Write what remains */2501 ret =commit_packed_refs(refs);2502if(ret)2503strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2504strerror(errno));2505return ret;2506}25072508static intfiles_delete_refs(struct ref_store *ref_store,2509struct string_list *refnames,unsigned int flags)2510{2511struct files_ref_store *refs =2512files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");2513struct strbuf err = STRBUF_INIT;2514int i, result =0;25152516if(!refnames->nr)2517return0;25182519 result =repack_without_refs(refs, refnames, &err);2520if(result) {2521/*2522 * If we failed to rewrite the packed-refs file, then2523 * it is unsafe to try to remove loose refs, because2524 * doing so might expose an obsolete packed value for2525 * a reference that might even point at an object that2526 * has been garbage collected.2527 */2528if(refnames->nr ==1)2529error(_("could not delete reference%s:%s"),2530 refnames->items[0].string, err.buf);2531else2532error(_("could not delete references:%s"), err.buf);25332534goto out;2535}25362537for(i =0; i < refnames->nr; i++) {2538const char*refname = refnames->items[i].string;25392540if(refs_delete_ref(&refs->base, NULL, refname, NULL, flags))2541 result |=error(_("could not remove reference%s"), refname);2542}25432544out:2545strbuf_release(&err);2546return result;2547}25482549/*2550 * People using contrib's git-new-workdir have .git/logs/refs ->2551 * /some/other/path/.git/logs/refs, and that may live on another device.2552 *2553 * IOW, to avoid cross device rename errors, the temporary renamed log must2554 * live into logs/refs.2555 */2556#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"25572558struct rename_cb {2559const char*tmp_renamed_log;2560int true_errno;2561};25622563static intrename_tmp_log_callback(const char*path,void*cb_data)2564{2565struct rename_cb *cb = cb_data;25662567if(rename(cb->tmp_renamed_log, path)) {2568/*2569 * rename(a, b) when b is an existing directory ought2570 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.2571 * Sheesh. Record the true errno for error reporting,2572 * but report EISDIR to raceproof_create_file() so2573 * that it knows to retry.2574 */2575 cb->true_errno = errno;2576if(errno == ENOTDIR)2577 errno = EISDIR;2578return-1;2579}else{2580return0;2581}2582}25832584static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)2585{2586struct strbuf path = STRBUF_INIT;2587struct strbuf tmp = STRBUF_INIT;2588struct rename_cb cb;2589int ret;25902591files_reflog_path(refs, &path, newrefname);2592files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);2593 cb.tmp_renamed_log = tmp.buf;2594 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);2595if(ret) {2596if(errno == EISDIR)2597error("directory not empty:%s", path.buf);2598else2599error("unable to move logfile%sto%s:%s",2600 tmp.buf, path.buf,2601strerror(cb.true_errno));2602}26032604strbuf_release(&path);2605strbuf_release(&tmp);2606return ret;2607}26082609static intfiles_verify_refname_available(struct ref_store *ref_store,2610const char*newname,2611const struct string_list *extras,2612const struct string_list *skip,2613struct strbuf *err)2614{2615struct files_ref_store *refs =2616files_downcast(ref_store, REF_STORE_READ,"verify_refname_available");2617struct ref_dir *packed_refs =get_packed_refs(refs);2618struct ref_dir *loose_refs =get_loose_refs(refs);26192620if(verify_refname_available_dir(newname, extras, skip,2621 packed_refs, err) ||2622verify_refname_available_dir(newname, extras, skip,2623 loose_refs, err))2624return-1;26252626return0;2627}26282629static intwrite_ref_to_lockfile(struct ref_lock *lock,2630const unsigned char*sha1,struct strbuf *err);2631static intcommit_ref_update(struct files_ref_store *refs,2632struct ref_lock *lock,2633const unsigned char*sha1,const char*logmsg,2634struct strbuf *err);26352636static intfiles_rename_ref(struct ref_store *ref_store,2637const char*oldrefname,const char*newrefname,2638const char*logmsg)2639{2640struct files_ref_store *refs =2641files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");2642unsigned char sha1[20], orig_sha1[20];2643int flag =0, logmoved =0;2644struct ref_lock *lock;2645struct stat loginfo;2646struct strbuf sb_oldref = STRBUF_INIT;2647struct strbuf sb_newref = STRBUF_INIT;2648struct strbuf tmp_renamed_log = STRBUF_INIT;2649int log, ret;2650struct strbuf err = STRBUF_INIT;26512652files_reflog_path(refs, &sb_oldref, oldrefname);2653files_reflog_path(refs, &sb_newref, newrefname);2654files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);26552656 log = !lstat(sb_oldref.buf, &loginfo);2657if(log &&S_ISLNK(loginfo.st_mode)) {2658 ret =error("reflog for%sis a symlink", oldrefname);2659goto out;2660}26612662if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,2663 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2664 orig_sha1, &flag)) {2665 ret =error("refname%snot found", oldrefname);2666goto out;2667}26682669if(flag & REF_ISSYMREF) {2670 ret =error("refname%sis a symbolic ref, renaming it is not supported",2671 oldrefname);2672goto out;2673}2674if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {2675 ret =1;2676goto out;2677}26782679if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {2680 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",2681 oldrefname,strerror(errno));2682goto out;2683}26842685if(refs_delete_ref(&refs->base, logmsg, oldrefname,2686 orig_sha1, REF_NODEREF)) {2687error("unable to delete old%s", oldrefname);2688goto rollback;2689}26902691/*2692 * Since we are doing a shallow lookup, sha1 is not the2693 * correct value to pass to delete_ref as old_sha1. But that2694 * doesn't matter, because an old_sha1 check wouldn't add to2695 * the safety anyway; we want to delete the reference whatever2696 * its current value.2697 */2698if(!refs_read_ref_full(&refs->base, newrefname,2699 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2700 sha1, NULL) &&2701refs_delete_ref(&refs->base, NULL, newrefname,2702 NULL, REF_NODEREF)) {2703if(errno == EISDIR) {2704struct strbuf path = STRBUF_INIT;2705int result;27062707files_ref_path(refs, &path, newrefname);2708 result =remove_empty_directories(&path);2709strbuf_release(&path);27102711if(result) {2712error("Directory not empty:%s", newrefname);2713goto rollback;2714}2715}else{2716error("unable to delete existing%s", newrefname);2717goto rollback;2718}2719}27202721if(log &&rename_tmp_log(refs, newrefname))2722goto rollback;27232724 logmoved = log;27252726 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,2727 REF_NODEREF, NULL, &err);2728if(!lock) {2729error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2730strbuf_release(&err);2731goto rollback;2732}2733hashcpy(lock->old_oid.hash, orig_sha1);27342735if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2736commit_ref_update(refs, lock, orig_sha1, logmsg, &err)) {2737error("unable to write current sha1 into%s:%s", newrefname, err.buf);2738strbuf_release(&err);2739goto rollback;2740}27412742 ret =0;2743goto out;27442745 rollback:2746 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,2747 REF_NODEREF, NULL, &err);2748if(!lock) {2749error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2750strbuf_release(&err);2751goto rollbacklog;2752}27532754 flag = log_all_ref_updates;2755 log_all_ref_updates = LOG_REFS_NONE;2756if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2757commit_ref_update(refs, lock, orig_sha1, NULL, &err)) {2758error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2759strbuf_release(&err);2760}2761 log_all_ref_updates = flag;27622763 rollbacklog:2764if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))2765error("unable to restore logfile%sfrom%s:%s",2766 oldrefname, newrefname,strerror(errno));2767if(!logmoved && log &&2768rename(tmp_renamed_log.buf, sb_oldref.buf))2769error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",2770 oldrefname,strerror(errno));2771 ret =1;2772 out:2773strbuf_release(&sb_newref);2774strbuf_release(&sb_oldref);2775strbuf_release(&tmp_renamed_log);27762777return ret;2778}27792780static intclose_ref(struct ref_lock *lock)2781{2782if(close_lock_file(lock->lk))2783return-1;2784return0;2785}27862787static intcommit_ref(struct ref_lock *lock)2788{2789char*path =get_locked_file_path(lock->lk);2790struct stat st;27912792if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {2793/*2794 * There is a directory at the path we want to rename2795 * the lockfile to. Hopefully it is empty; try to2796 * delete it.2797 */2798size_t len =strlen(path);2799struct strbuf sb_path = STRBUF_INIT;28002801strbuf_attach(&sb_path, path, len, len);28022803/*2804 * If this fails, commit_lock_file() will also fail2805 * and will report the problem.2806 */2807remove_empty_directories(&sb_path);2808strbuf_release(&sb_path);2809}else{2810free(path);2811}28122813if(commit_lock_file(lock->lk))2814return-1;2815return0;2816}28172818static intopen_or_create_logfile(const char*path,void*cb)2819{2820int*fd = cb;28212822*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);2823return(*fd <0) ? -1:0;2824}28252826/*2827 * Create a reflog for a ref. If force_create = 0, only create the2828 * reflog for certain refs (those for which should_autocreate_reflog2829 * returns non-zero). Otherwise, create it regardless of the reference2830 * name. If the logfile already existed or was created, return 0 and2831 * set *logfd to the file descriptor opened for appending to the file.2832 * If no logfile exists and we decided not to create one, return 0 and2833 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and2834 * return -1.2835 */2836static intlog_ref_setup(struct files_ref_store *refs,2837const char*refname,int force_create,2838int*logfd,struct strbuf *err)2839{2840struct strbuf logfile_sb = STRBUF_INIT;2841char*logfile;28422843files_reflog_path(refs, &logfile_sb, refname);2844 logfile =strbuf_detach(&logfile_sb, NULL);28452846if(force_create ||should_autocreate_reflog(refname)) {2847if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {2848if(errno == ENOENT)2849strbuf_addf(err,"unable to create directory for '%s': "2850"%s", logfile,strerror(errno));2851else if(errno == EISDIR)2852strbuf_addf(err,"there are still logs under '%s'",2853 logfile);2854else2855strbuf_addf(err,"unable to append to '%s':%s",2856 logfile,strerror(errno));28572858goto error;2859}2860}else{2861*logfd =open(logfile, O_APPEND | O_WRONLY,0666);2862if(*logfd <0) {2863if(errno == ENOENT || errno == EISDIR) {2864/*2865 * The logfile doesn't already exist,2866 * but that is not an error; it only2867 * means that we won't write log2868 * entries to it.2869 */2870;2871}else{2872strbuf_addf(err,"unable to append to '%s':%s",2873 logfile,strerror(errno));2874goto error;2875}2876}2877}28782879if(*logfd >=0)2880adjust_shared_perm(logfile);28812882free(logfile);2883return0;28842885error:2886free(logfile);2887return-1;2888}28892890static intfiles_create_reflog(struct ref_store *ref_store,2891const char*refname,int force_create,2892struct strbuf *err)2893{2894struct files_ref_store *refs =2895files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2896int fd;28972898if(log_ref_setup(refs, refname, force_create, &fd, err))2899return-1;29002901if(fd >=0)2902close(fd);29032904return0;2905}29062907static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2908const unsigned char*new_sha1,2909const char*committer,const char*msg)2910{2911int msglen, written;2912unsigned maxlen, len;2913char*logrec;29142915 msglen = msg ?strlen(msg) :0;2916 maxlen =strlen(committer) + msglen +100;2917 logrec =xmalloc(maxlen);2918 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2919sha1_to_hex(old_sha1),2920sha1_to_hex(new_sha1),2921 committer);2922if(msglen)2923 len +=copy_reflog_msg(logrec + len -1, msg) -1;29242925 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2926free(logrec);2927if(written != len)2928return-1;29292930return0;2931}29322933static intfiles_log_ref_write(struct files_ref_store *refs,2934const char*refname,const unsigned char*old_sha1,2935const unsigned char*new_sha1,const char*msg,2936int flags,struct strbuf *err)2937{2938int logfd, result;29392940if(log_all_ref_updates == LOG_REFS_UNSET)2941 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;29422943 result =log_ref_setup(refs, refname,2944 flags & REF_FORCE_CREATE_REFLOG,2945&logfd, err);29462947if(result)2948return result;29492950if(logfd <0)2951return0;2952 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2953git_committer_info(0), msg);2954if(result) {2955struct strbuf sb = STRBUF_INIT;2956int save_errno = errno;29572958files_reflog_path(refs, &sb, refname);2959strbuf_addf(err,"unable to append to '%s':%s",2960 sb.buf,strerror(save_errno));2961strbuf_release(&sb);2962close(logfd);2963return-1;2964}2965if(close(logfd)) {2966struct strbuf sb = STRBUF_INIT;2967int save_errno = errno;29682969files_reflog_path(refs, &sb, refname);2970strbuf_addf(err,"unable to append to '%s':%s",2971 sb.buf,strerror(save_errno));2972strbuf_release(&sb);2973return-1;2974}2975return0;2976}29772978/*2979 * Write sha1 into the open lockfile, then close the lockfile. On2980 * errors, rollback the lockfile, fill in *err and2981 * return -1.2982 */2983static intwrite_ref_to_lockfile(struct ref_lock *lock,2984const unsigned char*sha1,struct strbuf *err)2985{2986static char term ='\n';2987struct object *o;2988int fd;29892990 o =parse_object(sha1);2991if(!o) {2992strbuf_addf(err,2993"trying to write ref '%s' with nonexistent object%s",2994 lock->ref_name,sha1_to_hex(sha1));2995unlock_ref(lock);2996return-1;2997}2998if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2999strbuf_addf(err,3000"trying to write non-commit object%sto branch '%s'",3001sha1_to_hex(sha1), lock->ref_name);3002unlock_ref(lock);3003return-1;3004}3005 fd =get_lock_file_fd(lock->lk);3006if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||3007write_in_full(fd, &term,1) !=1||3008close_ref(lock) <0) {3009strbuf_addf(err,3010"couldn't write '%s'",get_lock_file_path(lock->lk));3011unlock_ref(lock);3012return-1;3013}3014return0;3015}30163017/*3018 * Commit a change to a loose reference that has already been written3019 * to the loose reference lockfile. Also update the reflogs if3020 * necessary, using the specified lockmsg (which can be NULL).3021 */3022static intcommit_ref_update(struct files_ref_store *refs,3023struct ref_lock *lock,3024const unsigned char*sha1,const char*logmsg,3025struct strbuf *err)3026{3027files_assert_main_repository(refs,"commit_ref_update");30283029clear_loose_ref_cache(refs);3030if(files_log_ref_write(refs, lock->ref_name,3031 lock->old_oid.hash, sha1,3032 logmsg,0, err)) {3033char*old_msg =strbuf_detach(err, NULL);3034strbuf_addf(err,"cannot update the ref '%s':%s",3035 lock->ref_name, old_msg);3036free(old_msg);3037unlock_ref(lock);3038return-1;3039}30403041if(strcmp(lock->ref_name,"HEAD") !=0) {3042/*3043 * Special hack: If a branch is updated directly and HEAD3044 * points to it (may happen on the remote side of a push3045 * for example) then logically the HEAD reflog should be3046 * updated too.3047 * A generic solution implies reverse symref information,3048 * but finding all symrefs pointing to the given branch3049 * would be rather costly for this rare event (the direct3050 * update of a branch) to be worth it. So let's cheat and3051 * check with HEAD only which should cover 99% of all usage3052 * scenarios (even 100% of the default ones).3053 */3054unsigned char head_sha1[20];3055int head_flag;3056const char*head_ref;30573058 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",3059 RESOLVE_REF_READING,3060 head_sha1, &head_flag);3061if(head_ref && (head_flag & REF_ISSYMREF) &&3062!strcmp(head_ref, lock->ref_name)) {3063struct strbuf log_err = STRBUF_INIT;3064if(files_log_ref_write(refs,"HEAD",3065 lock->old_oid.hash, sha1,3066 logmsg,0, &log_err)) {3067error("%s", log_err.buf);3068strbuf_release(&log_err);3069}3070}3071}30723073if(commit_ref(lock)) {3074strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3075unlock_ref(lock);3076return-1;3077}30783079unlock_ref(lock);3080return0;3081}30823083static intcreate_ref_symlink(struct ref_lock *lock,const char*target)3084{3085int ret = -1;3086#ifndef NO_SYMLINK_HEAD3087char*ref_path =get_locked_file_path(lock->lk);3088unlink(ref_path);3089 ret =symlink(target, ref_path);3090free(ref_path);30913092if(ret)3093fprintf(stderr,"no symlink - falling back to symbolic ref\n");3094#endif3095return ret;3096}30973098static voidupdate_symref_reflog(struct files_ref_store *refs,3099struct ref_lock *lock,const char*refname,3100const char*target,const char*logmsg)3101{3102struct strbuf err = STRBUF_INIT;3103unsigned char new_sha1[20];3104if(logmsg &&3105!refs_read_ref_full(&refs->base, target,3106 RESOLVE_REF_READING, new_sha1, NULL) &&3107files_log_ref_write(refs, refname, lock->old_oid.hash,3108 new_sha1, logmsg,0, &err)) {3109error("%s", err.buf);3110strbuf_release(&err);3111}3112}31133114static intcreate_symref_locked(struct files_ref_store *refs,3115struct ref_lock *lock,const char*refname,3116const char*target,const char*logmsg)3117{3118if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {3119update_symref_reflog(refs, lock, refname, target, logmsg);3120return0;3121}31223123if(!fdopen_lock_file(lock->lk,"w"))3124returnerror("unable to fdopen%s:%s",3125 lock->lk->tempfile.filename.buf,strerror(errno));31263127update_symref_reflog(refs, lock, refname, target, logmsg);31283129/* no error check; commit_ref will check ferror */3130fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);3131if(commit_ref(lock) <0)3132returnerror("unable to write symref for%s:%s", refname,3133strerror(errno));3134return0;3135}31363137static intfiles_create_symref(struct ref_store *ref_store,3138const char*refname,const char*target,3139const char*logmsg)3140{3141struct files_ref_store *refs =3142files_downcast(ref_store, REF_STORE_WRITE,"create_symref");3143struct strbuf err = STRBUF_INIT;3144struct ref_lock *lock;3145int ret;31463147 lock =lock_ref_sha1_basic(refs, refname, NULL,3148 NULL, NULL, REF_NODEREF, NULL,3149&err);3150if(!lock) {3151error("%s", err.buf);3152strbuf_release(&err);3153return-1;3154}31553156 ret =create_symref_locked(refs, lock, refname, target, logmsg);3157unlock_ref(lock);3158return ret;3159}31603161intset_worktree_head_symref(const char*gitdir,const char*target,const char*logmsg)3162{3163/*3164 * FIXME: this obviously will not work well for future refs3165 * backends. This function needs to die.3166 */3167struct files_ref_store *refs =3168files_downcast(get_main_ref_store(),3169 REF_STORE_WRITE,3170"set_head_symref");31713172static struct lock_file head_lock;3173struct ref_lock *lock;3174struct strbuf head_path = STRBUF_INIT;3175const char*head_rel;3176int ret;31773178strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));3179if(hold_lock_file_for_update(&head_lock, head_path.buf,3180 LOCK_NO_DEREF) <0) {3181struct strbuf err = STRBUF_INIT;3182unable_to_lock_message(head_path.buf, errno, &err);3183error("%s", err.buf);3184strbuf_release(&err);3185strbuf_release(&head_path);3186return-1;3187}31883189/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for3190 linked trees */3191 head_rel =remove_leading_path(head_path.buf,3192absolute_path(get_git_common_dir()));3193/* to make use of create_symref_locked(), initialize ref_lock */3194 lock =xcalloc(1,sizeof(struct ref_lock));3195 lock->lk = &head_lock;3196 lock->ref_name =xstrdup(head_rel);31973198 ret =create_symref_locked(refs, lock, head_rel, target, logmsg);31993200unlock_ref(lock);/* will free lock */3201strbuf_release(&head_path);3202return ret;3203}32043205static intfiles_reflog_exists(struct ref_store *ref_store,3206const char*refname)3207{3208struct files_ref_store *refs =3209files_downcast(ref_store, REF_STORE_READ,"reflog_exists");3210struct strbuf sb = STRBUF_INIT;3211struct stat st;3212int ret;32133214files_reflog_path(refs, &sb, refname);3215 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);3216strbuf_release(&sb);3217return ret;3218}32193220static intfiles_delete_reflog(struct ref_store *ref_store,3221const char*refname)3222{3223struct files_ref_store *refs =3224files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");3225struct strbuf sb = STRBUF_INIT;3226int ret;32273228files_reflog_path(refs, &sb, refname);3229 ret =remove_path(sb.buf);3230strbuf_release(&sb);3231return ret;3232}32333234static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3235{3236struct object_id ooid, noid;3237char*email_end, *message;3238unsigned long timestamp;3239int tz;3240const char*p = sb->buf;32413242/* old SP new SP name <email> SP time TAB msg LF */3243if(!sb->len || sb->buf[sb->len -1] !='\n'||3244parse_oid_hex(p, &ooid, &p) || *p++ !=' '||3245parse_oid_hex(p, &noid, &p) || *p++ !=' '||3246!(email_end =strchr(p,'>')) ||3247 email_end[1] !=' '||3248!(timestamp =strtoul(email_end +2, &message,10)) ||3249!message || message[0] !=' '||3250(message[1] !='+'&& message[1] !='-') ||3251!isdigit(message[2]) || !isdigit(message[3]) ||3252!isdigit(message[4]) || !isdigit(message[5]))3253return0;/* corrupt? */3254 email_end[1] ='\0';3255 tz =strtol(message +1, NULL,10);3256if(message[6] !='\t')3257 message +=6;3258else3259 message +=7;3260returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);3261}32623263static char*find_beginning_of_line(char*bob,char*scan)3264{3265while(bob < scan && *(--scan) !='\n')3266;/* keep scanning backwards */3267/*3268 * Return either beginning of the buffer, or LF at the end of3269 * the previous line.3270 */3271return scan;3272}32733274static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,3275const char*refname,3276 each_reflog_ent_fn fn,3277void*cb_data)3278{3279struct files_ref_store *refs =3280files_downcast(ref_store, REF_STORE_READ,3281"for_each_reflog_ent_reverse");3282struct strbuf sb = STRBUF_INIT;3283FILE*logfp;3284long pos;3285int ret =0, at_tail =1;32863287files_reflog_path(refs, &sb, refname);3288 logfp =fopen(sb.buf,"r");3289strbuf_release(&sb);3290if(!logfp)3291return-1;32923293/* Jump to the end */3294if(fseek(logfp,0, SEEK_END) <0)3295returnerror("cannot seek back reflog for%s:%s",3296 refname,strerror(errno));3297 pos =ftell(logfp);3298while(!ret &&0< pos) {3299int cnt;3300size_t nread;3301char buf[BUFSIZ];3302char*endp, *scanp;33033304/* Fill next block from the end */3305 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3306if(fseek(logfp, pos - cnt, SEEK_SET))3307returnerror("cannot seek back reflog for%s:%s",3308 refname,strerror(errno));3309 nread =fread(buf, cnt,1, logfp);3310if(nread !=1)3311returnerror("cannot read%dbytes from reflog for%s:%s",3312 cnt, refname,strerror(errno));3313 pos -= cnt;33143315 scanp = endp = buf + cnt;3316if(at_tail && scanp[-1] =='\n')3317/* Looking at the final LF at the end of the file */3318 scanp--;3319 at_tail =0;33203321while(buf < scanp) {3322/*3323 * terminating LF of the previous line, or the beginning3324 * of the buffer.3325 */3326char*bp;33273328 bp =find_beginning_of_line(buf, scanp);33293330if(*bp =='\n') {3331/*3332 * The newline is the end of the previous line,3333 * so we know we have complete line starting3334 * at (bp + 1). Prefix it onto any prior data3335 * we collected for the line and process it.3336 */3337strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3338 scanp = bp;3339 endp = bp +1;3340 ret =show_one_reflog_ent(&sb, fn, cb_data);3341strbuf_reset(&sb);3342if(ret)3343break;3344}else if(!pos) {3345/*3346 * We are at the start of the buffer, and the3347 * start of the file; there is no previous3348 * line, and we have everything for this one.3349 * Process it, and we can end the loop.3350 */3351strbuf_splice(&sb,0,0, buf, endp - buf);3352 ret =show_one_reflog_ent(&sb, fn, cb_data);3353strbuf_reset(&sb);3354break;3355}33563357if(bp == buf) {3358/*3359 * We are at the start of the buffer, and there3360 * is more file to read backwards. Which means3361 * we are in the middle of a line. Note that we3362 * may get here even if *bp was a newline; that3363 * just means we are at the exact end of the3364 * previous line, rather than some spot in the3365 * middle.3366 *3367 * Save away what we have to be combined with3368 * the data from the next read.3369 */3370strbuf_splice(&sb,0,0, buf, endp - buf);3371break;3372}3373}33743375}3376if(!ret && sb.len)3377die("BUG: reverse reflog parser had leftover data");33783379fclose(logfp);3380strbuf_release(&sb);3381return ret;3382}33833384static intfiles_for_each_reflog_ent(struct ref_store *ref_store,3385const char*refname,3386 each_reflog_ent_fn fn,void*cb_data)3387{3388struct files_ref_store *refs =3389files_downcast(ref_store, REF_STORE_READ,3390"for_each_reflog_ent");3391FILE*logfp;3392struct strbuf sb = STRBUF_INIT;3393int ret =0;33943395files_reflog_path(refs, &sb, refname);3396 logfp =fopen(sb.buf,"r");3397strbuf_release(&sb);3398if(!logfp)3399return-1;34003401while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3402 ret =show_one_reflog_ent(&sb, fn, cb_data);3403fclose(logfp);3404strbuf_release(&sb);3405return ret;3406}34073408struct files_reflog_iterator {3409struct ref_iterator base;34103411struct ref_store *ref_store;3412struct dir_iterator *dir_iterator;3413struct object_id oid;3414};34153416static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)3417{3418struct files_reflog_iterator *iter =3419(struct files_reflog_iterator *)ref_iterator;3420struct dir_iterator *diter = iter->dir_iterator;3421int ok;34223423while((ok =dir_iterator_advance(diter)) == ITER_OK) {3424int flags;34253426if(!S_ISREG(diter->st.st_mode))3427continue;3428if(diter->basename[0] =='.')3429continue;3430if(ends_with(diter->basename,".lock"))3431continue;34323433if(refs_read_ref_full(iter->ref_store,3434 diter->relative_path,0,3435 iter->oid.hash, &flags)) {3436error("bad ref for%s", diter->path.buf);3437continue;3438}34393440 iter->base.refname = diter->relative_path;3441 iter->base.oid = &iter->oid;3442 iter->base.flags = flags;3443return ITER_OK;3444}34453446 iter->dir_iterator = NULL;3447if(ref_iterator_abort(ref_iterator) == ITER_ERROR)3448 ok = ITER_ERROR;3449return ok;3450}34513452static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,3453struct object_id *peeled)3454{3455die("BUG: ref_iterator_peel() called for reflog_iterator");3456}34573458static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)3459{3460struct files_reflog_iterator *iter =3461(struct files_reflog_iterator *)ref_iterator;3462int ok = ITER_DONE;34633464if(iter->dir_iterator)3465 ok =dir_iterator_abort(iter->dir_iterator);34663467base_ref_iterator_free(ref_iterator);3468return ok;3469}34703471static struct ref_iterator_vtable files_reflog_iterator_vtable = {3472 files_reflog_iterator_advance,3473 files_reflog_iterator_peel,3474 files_reflog_iterator_abort3475};34763477static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)3478{3479struct files_ref_store *refs =3480files_downcast(ref_store, REF_STORE_READ,3481"reflog_iterator_begin");3482struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));3483struct ref_iterator *ref_iterator = &iter->base;3484struct strbuf sb = STRBUF_INIT;34853486base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);3487files_reflog_path(refs, &sb, NULL);3488 iter->dir_iterator =dir_iterator_begin(sb.buf);3489 iter->ref_store = ref_store;3490strbuf_release(&sb);3491return ref_iterator;3492}34933494static intref_update_reject_duplicates(struct string_list *refnames,3495struct strbuf *err)3496{3497int i, n = refnames->nr;34983499assert(err);35003501for(i =1; i < n; i++)3502if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3503strbuf_addf(err,3504"multiple updates for ref '%s' not allowed.",3505 refnames->items[i].string);3506return1;3507}3508return0;3509}35103511/*3512 * If update is a direct update of head_ref (the reference pointed to3513 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.3514 */3515static intsplit_head_update(struct ref_update *update,3516struct ref_transaction *transaction,3517const char*head_ref,3518struct string_list *affected_refnames,3519struct strbuf *err)3520{3521struct string_list_item *item;3522struct ref_update *new_update;35233524if((update->flags & REF_LOG_ONLY) ||3525(update->flags & REF_ISPRUNING) ||3526(update->flags & REF_UPDATE_VIA_HEAD))3527return0;35283529if(strcmp(update->refname, head_ref))3530return0;35313532/*3533 * First make sure that HEAD is not already in the3534 * transaction. This insertion is O(N) in the transaction3535 * size, but it happens at most once per transaction.3536 */3537 item =string_list_insert(affected_refnames,"HEAD");3538if(item->util) {3539/* An entry already existed */3540strbuf_addf(err,3541"multiple updates for 'HEAD' (including one "3542"via its referent '%s') are not allowed",3543 update->refname);3544return TRANSACTION_NAME_CONFLICT;3545}35463547 new_update =ref_transaction_add_update(3548 transaction,"HEAD",3549 update->flags | REF_LOG_ONLY | REF_NODEREF,3550 update->new_sha1, update->old_sha1,3551 update->msg);35523553 item->util = new_update;35543555return0;3556}35573558/*3559 * update is for a symref that points at referent and doesn't have3560 * REF_NODEREF set. Split it into two updates:3561 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set3562 * - A new, separate update for the referent reference3563 * Note that the new update will itself be subject to splitting when3564 * the iteration gets to it.3565 */3566static intsplit_symref_update(struct files_ref_store *refs,3567struct ref_update *update,3568const char*referent,3569struct ref_transaction *transaction,3570struct string_list *affected_refnames,3571struct strbuf *err)3572{3573struct string_list_item *item;3574struct ref_update *new_update;3575unsigned int new_flags;35763577/*3578 * First make sure that referent is not already in the3579 * transaction. This insertion is O(N) in the transaction3580 * size, but it happens at most once per symref in a3581 * transaction.3582 */3583 item =string_list_insert(affected_refnames, referent);3584if(item->util) {3585/* An entry already existed */3586strbuf_addf(err,3587"multiple updates for '%s' (including one "3588"via symref '%s') are not allowed",3589 referent, update->refname);3590return TRANSACTION_NAME_CONFLICT;3591}35923593 new_flags = update->flags;3594if(!strcmp(update->refname,"HEAD")) {3595/*3596 * Record that the new update came via HEAD, so that3597 * when we process it, split_head_update() doesn't try3598 * to add another reflog update for HEAD. Note that3599 * this bit will be propagated if the new_update3600 * itself needs to be split.3601 */3602 new_flags |= REF_UPDATE_VIA_HEAD;3603}36043605 new_update =ref_transaction_add_update(3606 transaction, referent, new_flags,3607 update->new_sha1, update->old_sha1,3608 update->msg);36093610 new_update->parent_update = update;36113612/*3613 * Change the symbolic ref update to log only. Also, it3614 * doesn't need to check its old SHA-1 value, as that will be3615 * done when new_update is processed.3616 */3617 update->flags |= REF_LOG_ONLY | REF_NODEREF;3618 update->flags &= ~REF_HAVE_OLD;36193620 item->util = new_update;36213622return0;3623}36243625/*3626 * Return the refname under which update was originally requested.3627 */3628static const char*original_update_refname(struct ref_update *update)3629{3630while(update->parent_update)3631 update = update->parent_update;36323633return update->refname;3634}36353636/*3637 * Check whether the REF_HAVE_OLD and old_oid values stored in update3638 * are consistent with oid, which is the reference's current value. If3639 * everything is OK, return 0; otherwise, write an error message to3640 * err and return -1.3641 */3642static intcheck_old_oid(struct ref_update *update,struct object_id *oid,3643struct strbuf *err)3644{3645if(!(update->flags & REF_HAVE_OLD) ||3646!hashcmp(oid->hash, update->old_sha1))3647return0;36483649if(is_null_sha1(update->old_sha1))3650strbuf_addf(err,"cannot lock ref '%s': "3651"reference already exists",3652original_update_refname(update));3653else if(is_null_oid(oid))3654strbuf_addf(err,"cannot lock ref '%s': "3655"reference is missing but expected%s",3656original_update_refname(update),3657sha1_to_hex(update->old_sha1));3658else3659strbuf_addf(err,"cannot lock ref '%s': "3660"is at%sbut expected%s",3661original_update_refname(update),3662oid_to_hex(oid),3663sha1_to_hex(update->old_sha1));36643665return-1;3666}36673668/*3669 * Prepare for carrying out update:3670 * - Lock the reference referred to by update.3671 * - Read the reference under lock.3672 * - Check that its old SHA-1 value (if specified) is correct, and in3673 * any case record it in update->lock->old_oid for later use when3674 * writing the reflog.3675 * - If it is a symref update without REF_NODEREF, split it up into a3676 * REF_LOG_ONLY update of the symref and add a separate update for3677 * the referent to transaction.3678 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY3679 * update of HEAD.3680 */3681static intlock_ref_for_update(struct files_ref_store *refs,3682struct ref_update *update,3683struct ref_transaction *transaction,3684const char*head_ref,3685struct string_list *affected_refnames,3686struct strbuf *err)3687{3688struct strbuf referent = STRBUF_INIT;3689int mustexist = (update->flags & REF_HAVE_OLD) &&3690!is_null_sha1(update->old_sha1);3691int ret;3692struct ref_lock *lock;36933694files_assert_main_repository(refs,"lock_ref_for_update");36953696if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))3697 update->flags |= REF_DELETING;36983699if(head_ref) {3700 ret =split_head_update(update, transaction, head_ref,3701 affected_refnames, err);3702if(ret)3703return ret;3704}37053706 ret =lock_raw_ref(refs, update->refname, mustexist,3707 affected_refnames, NULL,3708&lock, &referent,3709&update->type, err);3710if(ret) {3711char*reason;37123713 reason =strbuf_detach(err, NULL);3714strbuf_addf(err,"cannot lock ref '%s':%s",3715original_update_refname(update), reason);3716free(reason);3717return ret;3718}37193720 update->backend_data = lock;37213722if(update->type & REF_ISSYMREF) {3723if(update->flags & REF_NODEREF) {3724/*3725 * We won't be reading the referent as part of3726 * the transaction, so we have to read it here3727 * to record and possibly check old_sha1:3728 */3729if(refs_read_ref_full(&refs->base,3730 referent.buf,0,3731 lock->old_oid.hash, NULL)) {3732if(update->flags & REF_HAVE_OLD) {3733strbuf_addf(err,"cannot lock ref '%s': "3734"error reading reference",3735original_update_refname(update));3736return-1;3737}3738}else if(check_old_oid(update, &lock->old_oid, err)) {3739return TRANSACTION_GENERIC_ERROR;3740}3741}else{3742/*3743 * Create a new update for the reference this3744 * symref is pointing at. Also, we will record3745 * and verify old_sha1 for this update as part3746 * of processing the split-off update, so we3747 * don't have to do it here.3748 */3749 ret =split_symref_update(refs, update,3750 referent.buf, transaction,3751 affected_refnames, err);3752if(ret)3753return ret;3754}3755}else{3756struct ref_update *parent_update;37573758if(check_old_oid(update, &lock->old_oid, err))3759return TRANSACTION_GENERIC_ERROR;37603761/*3762 * If this update is happening indirectly because of a3763 * symref update, record the old SHA-1 in the parent3764 * update:3765 */3766for(parent_update = update->parent_update;3767 parent_update;3768 parent_update = parent_update->parent_update) {3769struct ref_lock *parent_lock = parent_update->backend_data;3770oidcpy(&parent_lock->old_oid, &lock->old_oid);3771}3772}37733774if((update->flags & REF_HAVE_NEW) &&3775!(update->flags & REF_DELETING) &&3776!(update->flags & REF_LOG_ONLY)) {3777if(!(update->type & REF_ISSYMREF) &&3778!hashcmp(lock->old_oid.hash, update->new_sha1)) {3779/*3780 * The reference already has the desired3781 * value, so we don't need to write it.3782 */3783}else if(write_ref_to_lockfile(lock, update->new_sha1,3784 err)) {3785char*write_err =strbuf_detach(err, NULL);37863787/*3788 * The lock was freed upon failure of3789 * write_ref_to_lockfile():3790 */3791 update->backend_data = NULL;3792strbuf_addf(err,3793"cannot update ref '%s':%s",3794 update->refname, write_err);3795free(write_err);3796return TRANSACTION_GENERIC_ERROR;3797}else{3798 update->flags |= REF_NEEDS_COMMIT;3799}3800}3801if(!(update->flags & REF_NEEDS_COMMIT)) {3802/*3803 * We didn't call write_ref_to_lockfile(), so3804 * the lockfile is still open. Close it to3805 * free up the file descriptor:3806 */3807if(close_ref(lock)) {3808strbuf_addf(err,"couldn't close '%s.lock'",3809 update->refname);3810return TRANSACTION_GENERIC_ERROR;3811}3812}3813return0;3814}38153816static intfiles_transaction_commit(struct ref_store *ref_store,3817struct ref_transaction *transaction,3818struct strbuf *err)3819{3820struct files_ref_store *refs =3821files_downcast(ref_store, REF_STORE_WRITE,3822"ref_transaction_commit");3823int ret =0, i;3824struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3825struct string_list_item *ref_to_delete;3826struct string_list affected_refnames = STRING_LIST_INIT_NODUP;3827char*head_ref = NULL;3828int head_type;3829struct object_id head_oid;3830struct strbuf sb = STRBUF_INIT;38313832assert(err);38333834if(transaction->state != REF_TRANSACTION_OPEN)3835die("BUG: commit called for transaction that is not open");38363837if(!transaction->nr) {3838 transaction->state = REF_TRANSACTION_CLOSED;3839return0;3840}38413842/*3843 * Fail if a refname appears more than once in the3844 * transaction. (If we end up splitting up any updates using3845 * split_symref_update() or split_head_update(), those3846 * functions will check that the new updates don't have the3847 * same refname as any existing ones.)3848 */3849for(i =0; i < transaction->nr; i++) {3850struct ref_update *update = transaction->updates[i];3851struct string_list_item *item =3852string_list_append(&affected_refnames, update->refname);38533854/*3855 * We store a pointer to update in item->util, but at3856 * the moment we never use the value of this field3857 * except to check whether it is non-NULL.3858 */3859 item->util = update;3860}3861string_list_sort(&affected_refnames);3862if(ref_update_reject_duplicates(&affected_refnames, err)) {3863 ret = TRANSACTION_GENERIC_ERROR;3864goto cleanup;3865}38663867/*3868 * Special hack: If a branch is updated directly and HEAD3869 * points to it (may happen on the remote side of a push3870 * for example) then logically the HEAD reflog should be3871 * updated too.3872 *3873 * A generic solution would require reverse symref lookups,3874 * but finding all symrefs pointing to a given branch would be3875 * rather costly for this rare event (the direct update of a3876 * branch) to be worth it. So let's cheat and check with HEAD3877 * only, which should cover 99% of all usage scenarios (even3878 * 100% of the default ones).3879 *3880 * So if HEAD is a symbolic reference, then record the name of3881 * the reference that it points to. If we see an update of3882 * head_ref within the transaction, then split_head_update()3883 * arranges for the reflog of HEAD to be updated, too.3884 */3885 head_ref =refs_resolve_refdup(ref_store,"HEAD",3886 RESOLVE_REF_NO_RECURSE,3887 head_oid.hash, &head_type);38883889if(head_ref && !(head_type & REF_ISSYMREF)) {3890free(head_ref);3891 head_ref = NULL;3892}38933894/*3895 * Acquire all locks, verify old values if provided, check3896 * that new values are valid, and write new values to the3897 * lockfiles, ready to be activated. Only keep one lockfile3898 * open at a time to avoid running out of file descriptors.3899 */3900for(i =0; i < transaction->nr; i++) {3901struct ref_update *update = transaction->updates[i];39023903 ret =lock_ref_for_update(refs, update, transaction,3904 head_ref, &affected_refnames, err);3905if(ret)3906goto cleanup;3907}39083909/* Perform updates first so live commits remain referenced */3910for(i =0; i < transaction->nr; i++) {3911struct ref_update *update = transaction->updates[i];3912struct ref_lock *lock = update->backend_data;39133914if(update->flags & REF_NEEDS_COMMIT ||3915 update->flags & REF_LOG_ONLY) {3916if(files_log_ref_write(refs,3917 lock->ref_name,3918 lock->old_oid.hash,3919 update->new_sha1,3920 update->msg, update->flags,3921 err)) {3922char*old_msg =strbuf_detach(err, NULL);39233924strbuf_addf(err,"cannot update the ref '%s':%s",3925 lock->ref_name, old_msg);3926free(old_msg);3927unlock_ref(lock);3928 update->backend_data = NULL;3929 ret = TRANSACTION_GENERIC_ERROR;3930goto cleanup;3931}3932}3933if(update->flags & REF_NEEDS_COMMIT) {3934clear_loose_ref_cache(refs);3935if(commit_ref(lock)) {3936strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3937unlock_ref(lock);3938 update->backend_data = NULL;3939 ret = TRANSACTION_GENERIC_ERROR;3940goto cleanup;3941}3942}3943}3944/* Perform deletes now that updates are safely completed */3945for(i =0; i < transaction->nr; i++) {3946struct ref_update *update = transaction->updates[i];3947struct ref_lock *lock = update->backend_data;39483949if(update->flags & REF_DELETING &&3950!(update->flags & REF_LOG_ONLY)) {3951if(!(update->type & REF_ISPACKED) ||3952 update->type & REF_ISSYMREF) {3953/* It is a loose reference. */3954strbuf_reset(&sb);3955files_ref_path(refs, &sb, lock->ref_name);3956if(unlink_or_msg(sb.buf, err)) {3957 ret = TRANSACTION_GENERIC_ERROR;3958goto cleanup;3959}3960 update->flags |= REF_DELETED_LOOSE;3961}39623963if(!(update->flags & REF_ISPRUNING))3964string_list_append(&refs_to_delete,3965 lock->ref_name);3966}3967}39683969if(repack_without_refs(refs, &refs_to_delete, err)) {3970 ret = TRANSACTION_GENERIC_ERROR;3971goto cleanup;3972}39733974/* Delete the reflogs of any references that were deleted: */3975for_each_string_list_item(ref_to_delete, &refs_to_delete) {3976strbuf_reset(&sb);3977files_reflog_path(refs, &sb, ref_to_delete->string);3978if(!unlink_or_warn(sb.buf))3979try_remove_empty_parents(refs, ref_to_delete->string,3980 REMOVE_EMPTY_PARENTS_REFLOG);3981}39823983clear_loose_ref_cache(refs);39843985cleanup:3986strbuf_release(&sb);3987 transaction->state = REF_TRANSACTION_CLOSED;39883989for(i =0; i < transaction->nr; i++) {3990struct ref_update *update = transaction->updates[i];3991struct ref_lock *lock = update->backend_data;39923993if(lock)3994unlock_ref(lock);39953996if(update->flags & REF_DELETED_LOOSE) {3997/*3998 * The loose reference was deleted. Delete any3999 * empty parent directories. (Note that this4000 * can only work because we have already4001 * removed the lockfile.)4002 */4003try_remove_empty_parents(refs, update->refname,4004 REMOVE_EMPTY_PARENTS_REF);4005}4006}40074008string_list_clear(&refs_to_delete,0);4009free(head_ref);4010string_list_clear(&affected_refnames,0);40114012return ret;4013}40144015static intref_present(const char*refname,4016const struct object_id *oid,int flags,void*cb_data)4017{4018struct string_list *affected_refnames = cb_data;40194020returnstring_list_has_string(affected_refnames, refname);4021}40224023static intfiles_initial_transaction_commit(struct ref_store *ref_store,4024struct ref_transaction *transaction,4025struct strbuf *err)4026{4027struct files_ref_store *refs =4028files_downcast(ref_store, REF_STORE_WRITE,4029"initial_ref_transaction_commit");4030int ret =0, i;4031struct string_list affected_refnames = STRING_LIST_INIT_NODUP;40324033assert(err);40344035if(transaction->state != REF_TRANSACTION_OPEN)4036die("BUG: commit called for transaction that is not open");40374038/* Fail if a refname appears more than once in the transaction: */4039for(i =0; i < transaction->nr; i++)4040string_list_append(&affected_refnames,4041 transaction->updates[i]->refname);4042string_list_sort(&affected_refnames);4043if(ref_update_reject_duplicates(&affected_refnames, err)) {4044 ret = TRANSACTION_GENERIC_ERROR;4045goto cleanup;4046}40474048/*4049 * It's really undefined to call this function in an active4050 * repository or when there are existing references: we are4051 * only locking and changing packed-refs, so (1) any4052 * simultaneous processes might try to change a reference at4053 * the same time we do, and (2) any existing loose versions of4054 * the references that we are setting would have precedence4055 * over our values. But some remote helpers create the remote4056 * "HEAD" and "master" branches before calling this function,4057 * so here we really only check that none of the references4058 * that we are creating already exists.4059 */4060if(refs_for_each_rawref(&refs->base, ref_present,4061&affected_refnames))4062die("BUG: initial ref transaction called with existing refs");40634064for(i =0; i < transaction->nr; i++) {4065struct ref_update *update = transaction->updates[i];40664067if((update->flags & REF_HAVE_OLD) &&4068!is_null_sha1(update->old_sha1))4069die("BUG: initial ref transaction with old_sha1 set");4070if(refs_verify_refname_available(&refs->base, update->refname,4071&affected_refnames, NULL,4072 err)) {4073 ret = TRANSACTION_NAME_CONFLICT;4074goto cleanup;4075}4076}40774078if(lock_packed_refs(refs,0)) {4079strbuf_addf(err,"unable to lock packed-refs file:%s",4080strerror(errno));4081 ret = TRANSACTION_GENERIC_ERROR;4082goto cleanup;4083}40844085for(i =0; i < transaction->nr; i++) {4086struct ref_update *update = transaction->updates[i];40874088if((update->flags & REF_HAVE_NEW) &&4089!is_null_sha1(update->new_sha1))4090add_packed_ref(refs, update->refname, update->new_sha1);4091}40924093if(commit_packed_refs(refs)) {4094strbuf_addf(err,"unable to commit packed-refs file:%s",4095strerror(errno));4096 ret = TRANSACTION_GENERIC_ERROR;4097goto cleanup;4098}40994100cleanup:4101 transaction->state = REF_TRANSACTION_CLOSED;4102string_list_clear(&affected_refnames,0);4103return ret;4104}41054106struct expire_reflog_cb {4107unsigned int flags;4108 reflog_expiry_should_prune_fn *should_prune_fn;4109void*policy_cb;4110FILE*newlog;4111struct object_id last_kept_oid;4112};41134114static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,4115const char*email,unsigned long timestamp,int tz,4116const char*message,void*cb_data)4117{4118struct expire_reflog_cb *cb = cb_data;4119struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;41204121if(cb->flags & EXPIRE_REFLOGS_REWRITE)4122 ooid = &cb->last_kept_oid;41234124if((*cb->should_prune_fn)(ooid->hash, noid->hash, email, timestamp, tz,4125 message, policy_cb)) {4126if(!cb->newlog)4127printf("would prune%s", message);4128else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4129printf("prune%s", message);4130}else{4131if(cb->newlog) {4132fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4133oid_to_hex(ooid),oid_to_hex(noid),4134 email, timestamp, tz, message);4135oidcpy(&cb->last_kept_oid, noid);4136}4137if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4138printf("keep%s", message);4139}4140return0;4141}41424143static intfiles_reflog_expire(struct ref_store *ref_store,4144const char*refname,const unsigned char*sha1,4145unsigned int flags,4146 reflog_expiry_prepare_fn prepare_fn,4147 reflog_expiry_should_prune_fn should_prune_fn,4148 reflog_expiry_cleanup_fn cleanup_fn,4149void*policy_cb_data)4150{4151struct files_ref_store *refs =4152files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");4153static struct lock_file reflog_lock;4154struct expire_reflog_cb cb;4155struct ref_lock *lock;4156struct strbuf log_file_sb = STRBUF_INIT;4157char*log_file;4158int status =0;4159int type;4160struct strbuf err = STRBUF_INIT;41614162memset(&cb,0,sizeof(cb));4163 cb.flags = flags;4164 cb.policy_cb = policy_cb_data;4165 cb.should_prune_fn = should_prune_fn;41664167/*4168 * The reflog file is locked by holding the lock on the4169 * reference itself, plus we might need to update the4170 * reference if --updateref was specified:4171 */4172 lock =lock_ref_sha1_basic(refs, refname, sha1,4173 NULL, NULL, REF_NODEREF,4174&type, &err);4175if(!lock) {4176error("cannot lock ref '%s':%s", refname, err.buf);4177strbuf_release(&err);4178return-1;4179}4180if(!refs_reflog_exists(ref_store, refname)) {4181unlock_ref(lock);4182return0;4183}41844185files_reflog_path(refs, &log_file_sb, refname);4186 log_file =strbuf_detach(&log_file_sb, NULL);4187if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4188/*4189 * Even though holding $GIT_DIR/logs/$reflog.lock has4190 * no locking implications, we use the lock_file4191 * machinery here anyway because it does a lot of the4192 * work we need, including cleaning up if the program4193 * exits unexpectedly.4194 */4195if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4196struct strbuf err = STRBUF_INIT;4197unable_to_lock_message(log_file, errno, &err);4198error("%s", err.buf);4199strbuf_release(&err);4200goto failure;4201}4202 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4203if(!cb.newlog) {4204error("cannot fdopen%s(%s)",4205get_lock_file_path(&reflog_lock),strerror(errno));4206goto failure;4207}4208}42094210(*prepare_fn)(refname, sha1, cb.policy_cb);4211refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);4212(*cleanup_fn)(cb.policy_cb);42134214if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4215/*4216 * It doesn't make sense to adjust a reference pointed4217 * to by a symbolic ref based on expiring entries in4218 * the symbolic reference's reflog. Nor can we update4219 * a reference if there are no remaining reflog4220 * entries.4221 */4222int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4223!(type & REF_ISSYMREF) &&4224!is_null_oid(&cb.last_kept_oid);42254226if(close_lock_file(&reflog_lock)) {4227 status |=error("couldn't write%s:%s", log_file,4228strerror(errno));4229}else if(update &&4230(write_in_full(get_lock_file_fd(lock->lk),4231oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||4232write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||4233close_ref(lock) <0)) {4234 status |=error("couldn't write%s",4235get_lock_file_path(lock->lk));4236rollback_lock_file(&reflog_lock);4237}else if(commit_lock_file(&reflog_lock)) {4238 status |=error("unable to write reflog '%s' (%s)",4239 log_file,strerror(errno));4240}else if(update &&commit_ref(lock)) {4241 status |=error("couldn't set%s", lock->ref_name);4242}4243}4244free(log_file);4245unlock_ref(lock);4246return status;42474248 failure:4249rollback_lock_file(&reflog_lock);4250free(log_file);4251unlock_ref(lock);4252return-1;4253}42544255static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)4256{4257struct files_ref_store *refs =4258files_downcast(ref_store, REF_STORE_WRITE,"init_db");4259struct strbuf sb = STRBUF_INIT;42604261/*4262 * Create .git/refs/{heads,tags}4263 */4264files_ref_path(refs, &sb,"refs/heads");4265safe_create_dir(sb.buf,1);42664267strbuf_reset(&sb);4268files_ref_path(refs, &sb,"refs/tags");4269safe_create_dir(sb.buf,1);42704271strbuf_release(&sb);4272return0;4273}42744275struct ref_storage_be refs_be_files = {4276 NULL,4277"files",4278 files_ref_store_create,4279 files_init_db,4280 files_transaction_commit,4281 files_initial_transaction_commit,42824283 files_pack_refs,4284 files_peel_ref,4285 files_create_symref,4286 files_delete_refs,4287 files_rename_ref,42884289 files_ref_iterator_begin,4290 files_read_raw_ref,4291 files_verify_refname_available,42924293 files_reflog_iterator_begin,4294 files_for_each_reflog_ent,4295 files_for_each_reflog_ent_reverse,4296 files_reflog_exists,4297 files_create_reflog,4298 files_delete_reflog,4299 files_reflog_expire4300};