1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"../iterator.h" 5#include"../lockfile.h" 6#include"../object.h" 7#include"../dir.h" 8 9struct ref_lock { 10char*ref_name; 11struct lock_file *lk; 12struct object_id old_oid; 13}; 14 15struct ref_entry; 16 17/* 18 * Information used (along with the information in ref_entry) to 19 * describe a single cached reference. This data structure only 20 * occurs embedded in a union in struct ref_entry, and only when 21 * (ref_entry->flag & REF_DIR) is zero. 22 */ 23struct ref_value { 24/* 25 * The name of the object to which this reference resolves 26 * (which may be a tag object). If REF_ISBROKEN, this is 27 * null. If REF_ISSYMREF, then this is the name of the object 28 * referred to by the last reference in the symlink chain. 29 */ 30struct object_id oid; 31 32/* 33 * If REF_KNOWS_PEELED, then this field holds the peeled value 34 * of this reference, or null if the reference is known not to 35 * be peelable. See the documentation for peel_ref() for an 36 * exact definition of "peelable". 37 */ 38struct object_id peeled; 39}; 40 41struct ref_cache; 42 43/* 44 * Information used (along with the information in ref_entry) to 45 * describe a level in the hierarchy of references. This data 46 * structure only occurs embedded in a union in struct ref_entry, and 47 * only when (ref_entry.flag & REF_DIR) is set. In that case, 48 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 49 * in the directory have already been read: 50 * 51 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 52 * or packed references, already read. 53 * 54 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 55 * references that hasn't been read yet (nor has any of its 56 * subdirectories). 57 * 58 * Entries within a directory are stored within a growable array of 59 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 60 * sorted are sorted by their component name in strcmp() order and the 61 * remaining entries are unsorted. 62 * 63 * Loose references are read lazily, one directory at a time. When a 64 * directory of loose references is read, then all of the references 65 * in that directory are stored, and REF_INCOMPLETE stubs are created 66 * for any subdirectories, but the subdirectories themselves are not 67 * read. The reading is triggered by get_ref_dir(). 68 */ 69struct ref_dir { 70int nr, alloc; 71 72/* 73 * Entries with index 0 <= i < sorted are sorted by name. New 74 * entries are appended to the list unsorted, and are sorted 75 * only when required; thus we avoid the need to sort the list 76 * after the addition of every reference. 77 */ 78int sorted; 79 80/* A pointer to the ref_cache that contains this ref_dir. */ 81struct ref_cache *ref_cache; 82 83struct ref_entry **entries; 84}; 85 86/* 87 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 88 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 89 * public values; see refs.h. 90 */ 91 92/* 93 * The field ref_entry->u.value.peeled of this value entry contains 94 * the correct peeled value for the reference, which might be 95 * null_sha1 if the reference is not a tag or if it is broken. 96 */ 97#define REF_KNOWS_PEELED 0x10 98 99/* ref_entry represents a directory of references */ 100#define REF_DIR 0x20 101 102/* 103 * Entry has not yet been read from disk (used only for REF_DIR 104 * entries representing loose references) 105 */ 106#define REF_INCOMPLETE 0x40 107 108/* 109 * A ref_entry represents either a reference or a "subdirectory" of 110 * references. 111 * 112 * Each directory in the reference namespace is represented by a 113 * ref_entry with (flags & REF_DIR) set and containing a subdir member 114 * that holds the entries in that directory that have been read so 115 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 116 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 117 * used for loose reference directories. 118 * 119 * References are represented by a ref_entry with (flags & REF_DIR) 120 * unset and a value member that describes the reference's value. The 121 * flag member is at the ref_entry level, but it is also needed to 122 * interpret the contents of the value field (in other words, a 123 * ref_value object is not very much use without the enclosing 124 * ref_entry). 125 * 126 * Reference names cannot end with slash and directories' names are 127 * always stored with a trailing slash (except for the top-level 128 * directory, which is always denoted by ""). This has two nice 129 * consequences: (1) when the entries in each subdir are sorted 130 * lexicographically by name (as they usually are), the references in 131 * a whole tree can be generated in lexicographic order by traversing 132 * the tree in left-to-right, depth-first order; (2) the names of 133 * references and subdirectories cannot conflict, and therefore the 134 * presence of an empty subdirectory does not block the creation of a 135 * similarly-named reference. (The fact that reference names with the 136 * same leading components can conflict *with each other* is a 137 * separate issue that is regulated by verify_refname_available().) 138 * 139 * Please note that the name field contains the fully-qualified 140 * reference (or subdirectory) name. Space could be saved by only 141 * storing the relative names. But that would require the full names 142 * to be generated on the fly when iterating in do_for_each_ref(), and 143 * would break callback functions, who have always been able to assume 144 * that the name strings that they are passed will not be freed during 145 * the iteration. 146 */ 147struct ref_entry { 148unsigned char flag;/* ISSYMREF? ISPACKED? */ 149union{ 150struct ref_value value;/* if not (flags&REF_DIR) */ 151struct ref_dir subdir;/* if (flags&REF_DIR) */ 152} u; 153/* 154 * The full name of the reference (e.g., "refs/heads/master") 155 * or the full name of the directory with a trailing slash 156 * (e.g., "refs/heads/"): 157 */ 158char name[FLEX_ARRAY]; 159}; 160 161static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 162static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len); 163static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 164const char*dirname,size_t len, 165int incomplete); 166static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry); 167 168static struct ref_dir *get_ref_dir(struct ref_entry *entry) 169{ 170struct ref_dir *dir; 171assert(entry->flag & REF_DIR); 172 dir = &entry->u.subdir; 173if(entry->flag & REF_INCOMPLETE) { 174read_loose_refs(entry->name, dir); 175 176/* 177 * Manually add refs/bisect, which, being 178 * per-worktree, might not appear in the directory 179 * listing for refs/ in the main repo. 180 */ 181if(!strcmp(entry->name,"refs/")) { 182int pos =search_ref_dir(dir,"refs/bisect/",12); 183if(pos <0) { 184struct ref_entry *child_entry; 185 child_entry =create_dir_entry(dir->ref_cache, 186"refs/bisect/", 18712,1); 188add_entry_to_dir(dir, child_entry); 189read_loose_refs("refs/bisect", 190&child_entry->u.subdir); 191} 192} 193 entry->flag &= ~REF_INCOMPLETE; 194} 195return dir; 196} 197 198static struct ref_entry *create_ref_entry(const char*refname, 199const unsigned char*sha1,int flag, 200int check_name) 201{ 202struct ref_entry *ref; 203 204if(check_name && 205check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 206die("Reference has invalid format: '%s'", refname); 207FLEX_ALLOC_STR(ref, name, refname); 208hashcpy(ref->u.value.oid.hash, sha1); 209oidclr(&ref->u.value.peeled); 210 ref->flag = flag; 211return ref; 212} 213 214static voidclear_ref_dir(struct ref_dir *dir); 215 216static voidfree_ref_entry(struct ref_entry *entry) 217{ 218if(entry->flag & REF_DIR) { 219/* 220 * Do not use get_ref_dir() here, as that might 221 * trigger the reading of loose refs. 222 */ 223clear_ref_dir(&entry->u.subdir); 224} 225free(entry); 226} 227 228/* 229 * Add a ref_entry to the end of dir (unsorted). Entry is always 230 * stored directly in dir; no recursion into subdirectories is 231 * done. 232 */ 233static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 234{ 235ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 236 dir->entries[dir->nr++] = entry; 237/* optimize for the case that entries are added in order */ 238if(dir->nr ==1|| 239(dir->nr == dir->sorted +1&& 240strcmp(dir->entries[dir->nr -2]->name, 241 dir->entries[dir->nr -1]->name) <0)) 242 dir->sorted = dir->nr; 243} 244 245/* 246 * Clear and free all entries in dir, recursively. 247 */ 248static voidclear_ref_dir(struct ref_dir *dir) 249{ 250int i; 251for(i =0; i < dir->nr; i++) 252free_ref_entry(dir->entries[i]); 253free(dir->entries); 254 dir->sorted = dir->nr = dir->alloc =0; 255 dir->entries = NULL; 256} 257 258/* 259 * Create a struct ref_entry object for the specified dirname. 260 * dirname is the name of the directory with a trailing slash (e.g., 261 * "refs/heads/") or "" for the top-level directory. 262 */ 263static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 264const char*dirname,size_t len, 265int incomplete) 266{ 267struct ref_entry *direntry; 268FLEX_ALLOC_MEM(direntry, name, dirname, len); 269 direntry->u.subdir.ref_cache = ref_cache; 270 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 271return direntry; 272} 273 274static intref_entry_cmp(const void*a,const void*b) 275{ 276struct ref_entry *one = *(struct ref_entry **)a; 277struct ref_entry *two = *(struct ref_entry **)b; 278returnstrcmp(one->name, two->name); 279} 280 281static voidsort_ref_dir(struct ref_dir *dir); 282 283struct string_slice { 284size_t len; 285const char*str; 286}; 287 288static intref_entry_cmp_sslice(const void*key_,const void*ent_) 289{ 290const struct string_slice *key = key_; 291const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 292int cmp =strncmp(key->str, ent->name, key->len); 293if(cmp) 294return cmp; 295return'\0'- (unsigned char)ent->name[key->len]; 296} 297 298/* 299 * Return the index of the entry with the given refname from the 300 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 301 * no such entry is found. dir must already be complete. 302 */ 303static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 304{ 305struct ref_entry **r; 306struct string_slice key; 307 308if(refname == NULL || !dir->nr) 309return-1; 310 311sort_ref_dir(dir); 312 key.len = len; 313 key.str = refname; 314 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 315 ref_entry_cmp_sslice); 316 317if(r == NULL) 318return-1; 319 320return r - dir->entries; 321} 322 323/* 324 * Search for a directory entry directly within dir (without 325 * recursing). Sort dir if necessary. subdirname must be a directory 326 * name (i.e., end in '/'). If mkdir is set, then create the 327 * directory if it is missing; otherwise, return NULL if the desired 328 * directory cannot be found. dir must already be complete. 329 */ 330static struct ref_dir *search_for_subdir(struct ref_dir *dir, 331const char*subdirname,size_t len, 332int mkdir) 333{ 334int entry_index =search_ref_dir(dir, subdirname, len); 335struct ref_entry *entry; 336if(entry_index == -1) { 337if(!mkdir) 338return NULL; 339/* 340 * Since dir is complete, the absence of a subdir 341 * means that the subdir really doesn't exist; 342 * therefore, create an empty record for it but mark 343 * the record complete. 344 */ 345 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 346add_entry_to_dir(dir, entry); 347}else{ 348 entry = dir->entries[entry_index]; 349} 350returnget_ref_dir(entry); 351} 352 353/* 354 * If refname is a reference name, find the ref_dir within the dir 355 * tree that should hold refname. If refname is a directory name 356 * (i.e., ends in '/'), then return that ref_dir itself. dir must 357 * represent the top-level directory and must already be complete. 358 * Sort ref_dirs and recurse into subdirectories as necessary. If 359 * mkdir is set, then create any missing directories; otherwise, 360 * return NULL if the desired directory cannot be found. 361 */ 362static struct ref_dir *find_containing_dir(struct ref_dir *dir, 363const char*refname,int mkdir) 364{ 365const char*slash; 366for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 367size_t dirnamelen = slash - refname +1; 368struct ref_dir *subdir; 369 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 370if(!subdir) { 371 dir = NULL; 372break; 373} 374 dir = subdir; 375} 376 377return dir; 378} 379 380/* 381 * Find the value entry with the given name in dir, sorting ref_dirs 382 * and recursing into subdirectories as necessary. If the name is not 383 * found or it corresponds to a directory entry, return NULL. 384 */ 385static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 386{ 387int entry_index; 388struct ref_entry *entry; 389 dir =find_containing_dir(dir, refname,0); 390if(!dir) 391return NULL; 392 entry_index =search_ref_dir(dir, refname,strlen(refname)); 393if(entry_index == -1) 394return NULL; 395 entry = dir->entries[entry_index]; 396return(entry->flag & REF_DIR) ? NULL : entry; 397} 398 399/* 400 * Remove the entry with the given name from dir, recursing into 401 * subdirectories as necessary. If refname is the name of a directory 402 * (i.e., ends with '/'), then remove the directory and its contents. 403 * If the removal was successful, return the number of entries 404 * remaining in the directory entry that contained the deleted entry. 405 * If the name was not found, return -1. Please note that this 406 * function only deletes the entry from the cache; it does not delete 407 * it from the filesystem or ensure that other cache entries (which 408 * might be symbolic references to the removed entry) are updated. 409 * Nor does it remove any containing dir entries that might be made 410 * empty by the removal. dir must represent the top-level directory 411 * and must already be complete. 412 */ 413static intremove_entry(struct ref_dir *dir,const char*refname) 414{ 415int refname_len =strlen(refname); 416int entry_index; 417struct ref_entry *entry; 418int is_dir = refname[refname_len -1] =='/'; 419if(is_dir) { 420/* 421 * refname represents a reference directory. Remove 422 * the trailing slash; otherwise we will get the 423 * directory *representing* refname rather than the 424 * one *containing* it. 425 */ 426char*dirname =xmemdupz(refname, refname_len -1); 427 dir =find_containing_dir(dir, dirname,0); 428free(dirname); 429}else{ 430 dir =find_containing_dir(dir, refname,0); 431} 432if(!dir) 433return-1; 434 entry_index =search_ref_dir(dir, refname, refname_len); 435if(entry_index == -1) 436return-1; 437 entry = dir->entries[entry_index]; 438 439memmove(&dir->entries[entry_index], 440&dir->entries[entry_index +1], 441(dir->nr - entry_index -1) *sizeof(*dir->entries) 442); 443 dir->nr--; 444if(dir->sorted > entry_index) 445 dir->sorted--; 446free_ref_entry(entry); 447return dir->nr; 448} 449 450/* 451 * Add a ref_entry to the ref_dir (unsorted), recursing into 452 * subdirectories as necessary. dir must represent the top-level 453 * directory. Return 0 on success. 454 */ 455static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 456{ 457 dir =find_containing_dir(dir, ref->name,1); 458if(!dir) 459return-1; 460add_entry_to_dir(dir, ref); 461return0; 462} 463 464/* 465 * Emit a warning and return true iff ref1 and ref2 have the same name 466 * and the same sha1. Die if they have the same name but different 467 * sha1s. 468 */ 469static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 470{ 471if(strcmp(ref1->name, ref2->name)) 472return0; 473 474/* Duplicate name; make sure that they don't conflict: */ 475 476if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 477/* This is impossible by construction */ 478die("Reference directory conflict:%s", ref1->name); 479 480if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 481die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 482 483warning("Duplicated ref:%s", ref1->name); 484return1; 485} 486 487/* 488 * Sort the entries in dir non-recursively (if they are not already 489 * sorted) and remove any duplicate entries. 490 */ 491static voidsort_ref_dir(struct ref_dir *dir) 492{ 493int i, j; 494struct ref_entry *last = NULL; 495 496/* 497 * This check also prevents passing a zero-length array to qsort(), 498 * which is a problem on some platforms. 499 */ 500if(dir->sorted == dir->nr) 501return; 502 503qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 504 505/* Remove any duplicates: */ 506for(i =0, j =0; j < dir->nr; j++) { 507struct ref_entry *entry = dir->entries[j]; 508if(last &&is_dup_ref(last, entry)) 509free_ref_entry(entry); 510else 511 last = dir->entries[i++] = entry; 512} 513 dir->sorted = dir->nr = i; 514} 515 516/* 517 * Return true if refname, which has the specified oid and flags, can 518 * be resolved to an object in the database. If the referred-to object 519 * does not exist, emit a warning and return false. 520 */ 521static intref_resolves_to_object(const char*refname, 522const struct object_id *oid, 523unsigned int flags) 524{ 525if(flags & REF_ISBROKEN) 526return0; 527if(!has_sha1_file(oid->hash)) { 528error("%sdoes not point to a valid object!", refname); 529return0; 530} 531return1; 532} 533 534/* 535 * Return true if the reference described by entry can be resolved to 536 * an object in the database; otherwise, emit a warning and return 537 * false. 538 */ 539static intentry_resolves_to_object(struct ref_entry *entry) 540{ 541returnref_resolves_to_object(entry->name, 542&entry->u.value.oid, entry->flag); 543} 544 545/* 546 * current_ref is a performance hack: when iterating over references 547 * using the for_each_ref*() functions, current_ref is set to the 548 * current reference's entry before calling the callback function. If 549 * the callback function calls peel_ref(), then peel_ref() first 550 * checks whether the reference to be peeled is the current reference 551 * (it usually is) and if so, returns that reference's peeled version 552 * if it is available. This avoids a refname lookup in a common case. 553 */ 554static struct ref_entry *current_ref; 555 556typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 557 558struct ref_entry_cb { 559const char*prefix; 560int trim; 561int flags; 562 each_ref_fn *fn; 563void*cb_data; 564}; 565 566/* 567 * Handle one reference in a do_for_each_ref*()-style iteration, 568 * calling an each_ref_fn for each entry. 569 */ 570static intdo_one_ref(struct ref_entry *entry,void*cb_data) 571{ 572struct ref_entry_cb *data = cb_data; 573struct ref_entry *old_current_ref; 574int retval; 575 576if(!starts_with(entry->name, data->prefix)) 577return0; 578 579if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 580!entry_resolves_to_object(entry)) 581return0; 582 583/* Store the old value, in case this is a recursive call: */ 584 old_current_ref = current_ref; 585 current_ref = entry; 586 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 587 entry->flag, data->cb_data); 588 current_ref = old_current_ref; 589return retval; 590} 591 592/* 593 * Call fn for each reference in dir that has index in the range 594 * offset <= index < dir->nr. Recurse into subdirectories that are in 595 * that index range, sorting them before iterating. This function 596 * does not sort dir itself; it should be sorted beforehand. fn is 597 * called for all references, including broken ones. 598 */ 599static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 600 each_ref_entry_fn fn,void*cb_data) 601{ 602int i; 603assert(dir->sorted == dir->nr); 604for(i = offset; i < dir->nr; i++) { 605struct ref_entry *entry = dir->entries[i]; 606int retval; 607if(entry->flag & REF_DIR) { 608struct ref_dir *subdir =get_ref_dir(entry); 609sort_ref_dir(subdir); 610 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 611}else{ 612 retval =fn(entry, cb_data); 613} 614if(retval) 615return retval; 616} 617return0; 618} 619 620/* 621 * Call fn for each reference in the union of dir1 and dir2, in order 622 * by refname. Recurse into subdirectories. If a value entry appears 623 * in both dir1 and dir2, then only process the version that is in 624 * dir2. The input dirs must already be sorted, but subdirs will be 625 * sorted as needed. fn is called for all references, including 626 * broken ones. 627 */ 628static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 629struct ref_dir *dir2, 630 each_ref_entry_fn fn,void*cb_data) 631{ 632int retval; 633int i1 =0, i2 =0; 634 635assert(dir1->sorted == dir1->nr); 636assert(dir2->sorted == dir2->nr); 637while(1) { 638struct ref_entry *e1, *e2; 639int cmp; 640if(i1 == dir1->nr) { 641returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 642} 643if(i2 == dir2->nr) { 644returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 645} 646 e1 = dir1->entries[i1]; 647 e2 = dir2->entries[i2]; 648 cmp =strcmp(e1->name, e2->name); 649if(cmp ==0) { 650if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 651/* Both are directories; descend them in parallel. */ 652struct ref_dir *subdir1 =get_ref_dir(e1); 653struct ref_dir *subdir2 =get_ref_dir(e2); 654sort_ref_dir(subdir1); 655sort_ref_dir(subdir2); 656 retval =do_for_each_entry_in_dirs( 657 subdir1, subdir2, fn, cb_data); 658 i1++; 659 i2++; 660}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 661/* Both are references; ignore the one from dir1. */ 662 retval =fn(e2, cb_data); 663 i1++; 664 i2++; 665}else{ 666die("conflict between reference and directory:%s", 667 e1->name); 668} 669}else{ 670struct ref_entry *e; 671if(cmp <0) { 672 e = e1; 673 i1++; 674}else{ 675 e = e2; 676 i2++; 677} 678if(e->flag & REF_DIR) { 679struct ref_dir *subdir =get_ref_dir(e); 680sort_ref_dir(subdir); 681 retval =do_for_each_entry_in_dir( 682 subdir,0, fn, cb_data); 683}else{ 684 retval =fn(e, cb_data); 685} 686} 687if(retval) 688return retval; 689} 690} 691 692/* 693 * Load all of the refs from the dir into our in-memory cache. The hard work 694 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 695 * through all of the sub-directories. We do not even need to care about 696 * sorting, as traversal order does not matter to us. 697 */ 698static voidprime_ref_dir(struct ref_dir *dir) 699{ 700int i; 701for(i =0; i < dir->nr; i++) { 702struct ref_entry *entry = dir->entries[i]; 703if(entry->flag & REF_DIR) 704prime_ref_dir(get_ref_dir(entry)); 705} 706} 707 708/* 709 * A level in the reference hierarchy that is currently being iterated 710 * through. 711 */ 712struct cache_ref_iterator_level { 713/* 714 * The ref_dir being iterated over at this level. The ref_dir 715 * is sorted before being stored here. 716 */ 717struct ref_dir *dir; 718 719/* 720 * The index of the current entry within dir (which might 721 * itself be a directory). If index == -1, then the iteration 722 * hasn't yet begun. If index == dir->nr, then the iteration 723 * through this level is over. 724 */ 725int index; 726}; 727 728/* 729 * Represent an iteration through a ref_dir in the memory cache. The 730 * iteration recurses through subdirectories. 731 */ 732struct cache_ref_iterator { 733struct ref_iterator base; 734 735/* 736 * The number of levels currently on the stack. This is always 737 * at least 1, because when it becomes zero the iteration is 738 * ended and this struct is freed. 739 */ 740size_t levels_nr; 741 742/* The number of levels that have been allocated on the stack */ 743size_t levels_alloc; 744 745/* 746 * A stack of levels. levels[0] is the uppermost level that is 747 * being iterated over in this iteration. (This is not 748 * necessary the top level in the references hierarchy. If we 749 * are iterating through a subtree, then levels[0] will hold 750 * the ref_dir for that subtree, and subsequent levels will go 751 * on from there.) 752 */ 753struct cache_ref_iterator_level *levels; 754}; 755 756static intcache_ref_iterator_advance(struct ref_iterator *ref_iterator) 757{ 758struct cache_ref_iterator *iter = 759(struct cache_ref_iterator *)ref_iterator; 760 761while(1) { 762struct cache_ref_iterator_level *level = 763&iter->levels[iter->levels_nr -1]; 764struct ref_dir *dir = level->dir; 765struct ref_entry *entry; 766 767if(level->index == -1) 768sort_ref_dir(dir); 769 770if(++level->index == level->dir->nr) { 771/* This level is exhausted; pop up a level */ 772if(--iter->levels_nr ==0) 773returnref_iterator_abort(ref_iterator); 774 775continue; 776} 777 778 entry = dir->entries[level->index]; 779 780if(entry->flag & REF_DIR) { 781/* push down a level */ 782ALLOC_GROW(iter->levels, iter->levels_nr +1, 783 iter->levels_alloc); 784 785 level = &iter->levels[iter->levels_nr++]; 786 level->dir =get_ref_dir(entry); 787 level->index = -1; 788}else{ 789 iter->base.refname = entry->name; 790 iter->base.oid = &entry->u.value.oid; 791 iter->base.flags = entry->flag; 792return ITER_OK; 793} 794} 795} 796 797static enum peel_status peel_entry(struct ref_entry *entry,int repeel); 798 799static intcache_ref_iterator_peel(struct ref_iterator *ref_iterator, 800struct object_id *peeled) 801{ 802struct cache_ref_iterator *iter = 803(struct cache_ref_iterator *)ref_iterator; 804struct cache_ref_iterator_level *level; 805struct ref_entry *entry; 806 807 level = &iter->levels[iter->levels_nr -1]; 808 809if(level->index == -1) 810die("BUG: peel called before advance for cache iterator"); 811 812 entry = level->dir->entries[level->index]; 813 814if(peel_entry(entry,0)) 815return-1; 816hashcpy(peeled->hash, entry->u.value.peeled.hash); 817return0; 818} 819 820static intcache_ref_iterator_abort(struct ref_iterator *ref_iterator) 821{ 822struct cache_ref_iterator *iter = 823(struct cache_ref_iterator *)ref_iterator; 824 825free(iter->levels); 826base_ref_iterator_free(ref_iterator); 827return ITER_DONE; 828} 829 830static struct ref_iterator_vtable cache_ref_iterator_vtable = { 831 cache_ref_iterator_advance, 832 cache_ref_iterator_peel, 833 cache_ref_iterator_abort 834}; 835 836static struct ref_iterator *cache_ref_iterator_begin(struct ref_dir *dir) 837{ 838struct cache_ref_iterator *iter; 839struct ref_iterator *ref_iterator; 840struct cache_ref_iterator_level *level; 841 842 iter =xcalloc(1,sizeof(*iter)); 843 ref_iterator = &iter->base; 844base_ref_iterator_init(ref_iterator, &cache_ref_iterator_vtable); 845ALLOC_GROW(iter->levels,10, iter->levels_alloc); 846 847 iter->levels_nr =1; 848 level = &iter->levels[0]; 849 level->index = -1; 850 level->dir = dir; 851 852return ref_iterator; 853} 854 855struct nonmatching_ref_data { 856const struct string_list *skip; 857const char*conflicting_refname; 858}; 859 860static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 861{ 862struct nonmatching_ref_data *data = vdata; 863 864if(data->skip &&string_list_has_string(data->skip, entry->name)) 865return0; 866 867 data->conflicting_refname = entry->name; 868return1; 869} 870 871/* 872 * Return 0 if a reference named refname could be created without 873 * conflicting with the name of an existing reference in dir. 874 * See verify_refname_available for more information. 875 */ 876static intverify_refname_available_dir(const char*refname, 877const struct string_list *extras, 878const struct string_list *skip, 879struct ref_dir *dir, 880struct strbuf *err) 881{ 882const char*slash; 883const char*extra_refname; 884int pos; 885struct strbuf dirname = STRBUF_INIT; 886int ret = -1; 887 888/* 889 * For the sake of comments in this function, suppose that 890 * refname is "refs/foo/bar". 891 */ 892 893assert(err); 894 895strbuf_grow(&dirname,strlen(refname) +1); 896for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 897/* Expand dirname to the new prefix, not including the trailing slash: */ 898strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 899 900/* 901 * We are still at a leading dir of the refname (e.g., 902 * "refs/foo"; if there is a reference with that name, 903 * it is a conflict, *unless* it is in skip. 904 */ 905if(dir) { 906 pos =search_ref_dir(dir, dirname.buf, dirname.len); 907if(pos >=0&& 908(!skip || !string_list_has_string(skip, dirname.buf))) { 909/* 910 * We found a reference whose name is 911 * a proper prefix of refname; e.g., 912 * "refs/foo", and is not in skip. 913 */ 914strbuf_addf(err,"'%s' exists; cannot create '%s'", 915 dirname.buf, refname); 916goto cleanup; 917} 918} 919 920if(extras &&string_list_has_string(extras, dirname.buf) && 921(!skip || !string_list_has_string(skip, dirname.buf))) { 922strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 923 refname, dirname.buf); 924goto cleanup; 925} 926 927/* 928 * Otherwise, we can try to continue our search with 929 * the next component. So try to look up the 930 * directory, e.g., "refs/foo/". If we come up empty, 931 * we know there is nothing under this whole prefix, 932 * but even in that case we still have to continue the 933 * search for conflicts with extras. 934 */ 935strbuf_addch(&dirname,'/'); 936if(dir) { 937 pos =search_ref_dir(dir, dirname.buf, dirname.len); 938if(pos <0) { 939/* 940 * There was no directory "refs/foo/", 941 * so there is nothing under this 942 * whole prefix. So there is no need 943 * to continue looking for conflicting 944 * references. But we need to continue 945 * looking for conflicting extras. 946 */ 947 dir = NULL; 948}else{ 949 dir =get_ref_dir(dir->entries[pos]); 950} 951} 952} 953 954/* 955 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 956 * There is no point in searching for a reference with that 957 * name, because a refname isn't considered to conflict with 958 * itself. But we still need to check for references whose 959 * names are in the "refs/foo/bar/" namespace, because they 960 * *do* conflict. 961 */ 962strbuf_addstr(&dirname, refname + dirname.len); 963strbuf_addch(&dirname,'/'); 964 965if(dir) { 966 pos =search_ref_dir(dir, dirname.buf, dirname.len); 967 968if(pos >=0) { 969/* 970 * We found a directory named "$refname/" 971 * (e.g., "refs/foo/bar/"). It is a problem 972 * iff it contains any ref that is not in 973 * "skip". 974 */ 975struct nonmatching_ref_data data; 976 977 data.skip = skip; 978 data.conflicting_refname = NULL; 979 dir =get_ref_dir(dir->entries[pos]); 980sort_ref_dir(dir); 981if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 982strbuf_addf(err,"'%s' exists; cannot create '%s'", 983 data.conflicting_refname, refname); 984goto cleanup; 985} 986} 987} 988 989 extra_refname =find_descendant_ref(dirname.buf, extras, skip); 990if(extra_refname) 991strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 992 refname, extra_refname); 993else 994 ret =0; 995 996cleanup: 997strbuf_release(&dirname); 998return ret; 999}10001001struct packed_ref_cache {1002struct ref_entry *root;10031004/*1005 * Count of references to the data structure in this instance,1006 * including the pointer from ref_cache::packed if any. The1007 * data will not be freed as long as the reference count is1008 * nonzero.1009 */1010unsigned int referrers;10111012/*1013 * Iff the packed-refs file associated with this instance is1014 * currently locked for writing, this points at the associated1015 * lock (which is owned by somebody else). The referrer count1016 * is also incremented when the file is locked and decremented1017 * when it is unlocked.1018 */1019struct lock_file *lock;10201021/* The metadata from when this packed-refs cache was read */1022struct stat_validity validity;1023};10241025/*1026 * Future: need to be in "struct repository"1027 * when doing a full libification.1028 */1029static struct ref_cache {1030struct ref_cache *next;1031struct ref_entry *loose;1032struct packed_ref_cache *packed;1033/*1034 * The submodule name, or "" for the main repo. We allocate1035 * length 1 rather than FLEX_ARRAY so that the main ref_cache1036 * is initialized correctly.1037 */1038char name[1];1039} ref_cache, *submodule_ref_caches;10401041/* Lock used for the main packed-refs file: */1042static struct lock_file packlock;10431044/*1045 * Increment the reference count of *packed_refs.1046 */1047static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1048{1049 packed_refs->referrers++;1050}10511052/*1053 * Decrease the reference count of *packed_refs. If it goes to zero,1054 * free *packed_refs and return true; otherwise return false.1055 */1056static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1057{1058if(!--packed_refs->referrers) {1059free_ref_entry(packed_refs->root);1060stat_validity_clear(&packed_refs->validity);1061free(packed_refs);1062return1;1063}else{1064return0;1065}1066}10671068static voidclear_packed_ref_cache(struct ref_cache *refs)1069{1070if(refs->packed) {1071struct packed_ref_cache *packed_refs = refs->packed;10721073if(packed_refs->lock)1074die("internal error: packed-ref cache cleared while locked");1075 refs->packed = NULL;1076release_packed_ref_cache(packed_refs);1077}1078}10791080static voidclear_loose_ref_cache(struct ref_cache *refs)1081{1082if(refs->loose) {1083free_ref_entry(refs->loose);1084 refs->loose = NULL;1085}1086}10871088/*1089 * Create a new submodule ref cache and add it to the internal1090 * set of caches.1091 */1092static struct ref_cache *create_ref_cache(const char*submodule)1093{1094struct ref_cache *refs;1095if(!submodule)1096 submodule ="";1097FLEX_ALLOC_STR(refs, name, submodule);1098 refs->next = submodule_ref_caches;1099 submodule_ref_caches = refs;1100return refs;1101}11021103static struct ref_cache *lookup_ref_cache(const char*submodule)1104{1105struct ref_cache *refs;11061107if(!submodule || !*submodule)1108return&ref_cache;11091110for(refs = submodule_ref_caches; refs; refs = refs->next)1111if(!strcmp(submodule, refs->name))1112return refs;1113return NULL;1114}11151116/*1117 * Return a pointer to a ref_cache for the specified submodule. For1118 * the main repository, use submodule==NULL; such a call cannot fail.1119 * For a submodule, the submodule must exist and be a nonbare1120 * repository, otherwise return NULL.1121 *1122 * The returned structure will be allocated and initialized but not1123 * necessarily populated; it should not be freed.1124 */1125static struct ref_cache *get_ref_cache(const char*submodule)1126{1127struct ref_cache *refs =lookup_ref_cache(submodule);11281129if(!refs) {1130struct strbuf submodule_sb = STRBUF_INIT;11311132strbuf_addstr(&submodule_sb, submodule);1133if(is_nonbare_repository_dir(&submodule_sb))1134 refs =create_ref_cache(submodule);1135strbuf_release(&submodule_sb);1136}11371138return refs;1139}11401141/* The length of a peeled reference line in packed-refs, including EOL: */1142#define PEELED_LINE_LENGTH 4211431144/*1145 * The packed-refs header line that we write out. Perhaps other1146 * traits will be added later. The trailing space is required.1147 */1148static const char PACKED_REFS_HEADER[] =1149"# pack-refs with: peeled fully-peeled\n";11501151/*1152 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1153 * Return a pointer to the refname within the line (null-terminated),1154 * or NULL if there was a problem.1155 */1156static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1157{1158const char*ref;11591160/*1161 * 42: the answer to everything.1162 *1163 * In this case, it happens to be the answer to1164 * 40 (length of sha1 hex representation)1165 * +1 (space in between hex and name)1166 * +1 (newline at the end of the line)1167 */1168if(line->len <=42)1169return NULL;11701171if(get_sha1_hex(line->buf, sha1) <0)1172return NULL;1173if(!isspace(line->buf[40]))1174return NULL;11751176 ref = line->buf +41;1177if(isspace(*ref))1178return NULL;11791180if(line->buf[line->len -1] !='\n')1181return NULL;1182 line->buf[--line->len] =0;11831184return ref;1185}11861187/*1188 * Read f, which is a packed-refs file, into dir.1189 *1190 * A comment line of the form "# pack-refs with: " may contain zero or1191 * more traits. We interpret the traits as follows:1192 *1193 * No traits:1194 *1195 * Probably no references are peeled. But if the file contains a1196 * peeled value for a reference, we will use it.1197 *1198 * peeled:1199 *1200 * References under "refs/tags/", if they *can* be peeled, *are*1201 * peeled in this file. References outside of "refs/tags/" are1202 * probably not peeled even if they could have been, but if we find1203 * a peeled value for such a reference we will use it.1204 *1205 * fully-peeled:1206 *1207 * All references in the file that can be peeled are peeled.1208 * Inversely (and this is more important), any references in the1209 * file for which no peeled value is recorded is not peelable. This1210 * trait should typically be written alongside "peeled" for1211 * compatibility with older clients, but we do not require it1212 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1213 */1214static voidread_packed_refs(FILE*f,struct ref_dir *dir)1215{1216struct ref_entry *last = NULL;1217struct strbuf line = STRBUF_INIT;1218enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12191220while(strbuf_getwholeline(&line, f,'\n') != EOF) {1221unsigned char sha1[20];1222const char*refname;1223const char*traits;12241225if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1226if(strstr(traits," fully-peeled "))1227 peeled = PEELED_FULLY;1228else if(strstr(traits," peeled "))1229 peeled = PEELED_TAGS;1230/* perhaps other traits later as well */1231continue;1232}12331234 refname =parse_ref_line(&line, sha1);1235if(refname) {1236int flag = REF_ISPACKED;12371238if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1239if(!refname_is_safe(refname))1240die("packed refname is dangerous:%s", refname);1241hashclr(sha1);1242 flag |= REF_BAD_NAME | REF_ISBROKEN;1243}1244 last =create_ref_entry(refname, sha1, flag,0);1245if(peeled == PEELED_FULLY ||1246(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1247 last->flag |= REF_KNOWS_PEELED;1248add_ref(dir, last);1249continue;1250}1251if(last &&1252 line.buf[0] =='^'&&1253 line.len == PEELED_LINE_LENGTH &&1254 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1255!get_sha1_hex(line.buf +1, sha1)) {1256hashcpy(last->u.value.peeled.hash, sha1);1257/*1258 * Regardless of what the file header said,1259 * we definitely know the value of *this*1260 * reference:1261 */1262 last->flag |= REF_KNOWS_PEELED;1263}1264}12651266strbuf_release(&line);1267}12681269/*1270 * Get the packed_ref_cache for the specified ref_cache, creating it1271 * if necessary.1272 */1273static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1274{1275char*packed_refs_file;12761277if(*refs->name)1278 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1279else1280 packed_refs_file =git_pathdup("packed-refs");12811282if(refs->packed &&1283!stat_validity_check(&refs->packed->validity, packed_refs_file))1284clear_packed_ref_cache(refs);12851286if(!refs->packed) {1287FILE*f;12881289 refs->packed =xcalloc(1,sizeof(*refs->packed));1290acquire_packed_ref_cache(refs->packed);1291 refs->packed->root =create_dir_entry(refs,"",0,0);1292 f =fopen(packed_refs_file,"r");1293if(f) {1294stat_validity_update(&refs->packed->validity,fileno(f));1295read_packed_refs(f,get_ref_dir(refs->packed->root));1296fclose(f);1297}1298}1299free(packed_refs_file);1300return refs->packed;1301}13021303static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1304{1305returnget_ref_dir(packed_ref_cache->root);1306}13071308static struct ref_dir *get_packed_refs(struct ref_cache *refs)1309{1310returnget_packed_ref_dir(get_packed_ref_cache(refs));1311}13121313/*1314 * Add a reference to the in-memory packed reference cache. This may1315 * only be called while the packed-refs file is locked (see1316 * lock_packed_refs()). To actually write the packed-refs file, call1317 * commit_packed_refs().1318 */1319static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1320{1321struct packed_ref_cache *packed_ref_cache =1322get_packed_ref_cache(&ref_cache);13231324if(!packed_ref_cache->lock)1325die("internal error: packed refs not locked");1326add_ref(get_packed_ref_dir(packed_ref_cache),1327create_ref_entry(refname, sha1, REF_ISPACKED,1));1328}13291330/*1331 * Read the loose references from the namespace dirname into dir1332 * (without recursing). dirname must end with '/'. dir must be the1333 * directory entry corresponding to dirname.1334 */1335static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1336{1337struct ref_cache *refs = dir->ref_cache;1338DIR*d;1339struct dirent *de;1340int dirnamelen =strlen(dirname);1341struct strbuf refname;1342struct strbuf path = STRBUF_INIT;1343size_t path_baselen;13441345if(*refs->name)1346strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1347else1348strbuf_git_path(&path,"%s", dirname);1349 path_baselen = path.len;13501351 d =opendir(path.buf);1352if(!d) {1353strbuf_release(&path);1354return;1355}13561357strbuf_init(&refname, dirnamelen +257);1358strbuf_add(&refname, dirname, dirnamelen);13591360while((de =readdir(d)) != NULL) {1361unsigned char sha1[20];1362struct stat st;1363int flag;13641365if(de->d_name[0] =='.')1366continue;1367if(ends_with(de->d_name,".lock"))1368continue;1369strbuf_addstr(&refname, de->d_name);1370strbuf_addstr(&path, de->d_name);1371if(stat(path.buf, &st) <0) {1372;/* silently ignore */1373}else if(S_ISDIR(st.st_mode)) {1374strbuf_addch(&refname,'/');1375add_entry_to_dir(dir,1376create_dir_entry(refs, refname.buf,1377 refname.len,1));1378}else{1379int read_ok;13801381if(*refs->name) {1382hashclr(sha1);1383 flag =0;1384 read_ok = !resolve_gitlink_ref(refs->name,1385 refname.buf, sha1);1386}else{1387 read_ok = !read_ref_full(refname.buf,1388 RESOLVE_REF_READING,1389 sha1, &flag);1390}13911392if(!read_ok) {1393hashclr(sha1);1394 flag |= REF_ISBROKEN;1395}else if(is_null_sha1(sha1)) {1396/*1397 * It is so astronomically unlikely1398 * that NULL_SHA1 is the SHA-1 of an1399 * actual object that we consider its1400 * appearance in a loose reference1401 * file to be repo corruption1402 * (probably due to a software bug).1403 */1404 flag |= REF_ISBROKEN;1405}14061407if(check_refname_format(refname.buf,1408 REFNAME_ALLOW_ONELEVEL)) {1409if(!refname_is_safe(refname.buf))1410die("loose refname is dangerous:%s", refname.buf);1411hashclr(sha1);1412 flag |= REF_BAD_NAME | REF_ISBROKEN;1413}1414add_entry_to_dir(dir,1415create_ref_entry(refname.buf, sha1, flag,0));1416}1417strbuf_setlen(&refname, dirnamelen);1418strbuf_setlen(&path, path_baselen);1419}1420strbuf_release(&refname);1421strbuf_release(&path);1422closedir(d);1423}14241425static struct ref_dir *get_loose_refs(struct ref_cache *refs)1426{1427if(!refs->loose) {1428/*1429 * Mark the top-level directory complete because we1430 * are about to read the only subdirectory that can1431 * hold references:1432 */1433 refs->loose =create_dir_entry(refs,"",0,0);1434/*1435 * Create an incomplete entry for "refs/":1436 */1437add_entry_to_dir(get_ref_dir(refs->loose),1438create_dir_entry(refs,"refs/",5,1));1439}1440returnget_ref_dir(refs->loose);1441}14421443#define MAXREFLEN (1024)14441445/*1446 * Called by resolve_gitlink_ref_recursive() after it failed to read1447 * from the loose refs in ref_cache refs. Find <refname> in the1448 * packed-refs file for the submodule.1449 */1450static intresolve_gitlink_packed_ref(struct ref_cache *refs,1451const char*refname,unsigned char*sha1)1452{1453struct ref_entry *ref;1454struct ref_dir *dir =get_packed_refs(refs);14551456 ref =find_ref(dir, refname);1457if(ref == NULL)1458return-1;14591460hashcpy(sha1, ref->u.value.oid.hash);1461return0;1462}14631464static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1465const char*refname,unsigned char*sha1,1466int recursion)1467{1468int fd, len;1469char buffer[128], *p;1470char*path;14711472if(recursion > SYMREF_MAXDEPTH ||strlen(refname) > MAXREFLEN)1473return-1;1474 path = *refs->name1475?git_pathdup_submodule(refs->name,"%s", refname)1476:git_pathdup("%s", refname);1477 fd =open(path, O_RDONLY);1478free(path);1479if(fd <0)1480returnresolve_gitlink_packed_ref(refs, refname, sha1);14811482 len =read(fd, buffer,sizeof(buffer)-1);1483close(fd);1484if(len <0)1485return-1;1486while(len &&isspace(buffer[len-1]))1487 len--;1488 buffer[len] =0;14891490/* Was it a detached head or an old-fashioned symlink? */1491if(!get_sha1_hex(buffer, sha1))1492return0;14931494/* Symref? */1495if(strncmp(buffer,"ref:",4))1496return-1;1497 p = buffer +4;1498while(isspace(*p))1499 p++;15001501returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1502}15031504intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1505{1506int len =strlen(path), retval;1507struct strbuf submodule = STRBUF_INIT;1508struct ref_cache *refs;15091510while(len && path[len-1] =='/')1511 len--;1512if(!len)1513return-1;15141515strbuf_add(&submodule, path, len);1516 refs =get_ref_cache(submodule.buf);1517if(!refs) {1518strbuf_release(&submodule);1519return-1;1520}1521strbuf_release(&submodule);15221523 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1524return retval;1525}15261527/*1528 * Return the ref_entry for the given refname from the packed1529 * references. If it does not exist, return NULL.1530 */1531static struct ref_entry *get_packed_ref(const char*refname)1532{1533returnfind_ref(get_packed_refs(&ref_cache), refname);1534}15351536/*1537 * A loose ref file doesn't exist; check for a packed ref.1538 */1539static intresolve_missing_loose_ref(const char*refname,1540unsigned char*sha1,1541unsigned int*flags)1542{1543struct ref_entry *entry;15441545/*1546 * The loose reference file does not exist; check for a packed1547 * reference.1548 */1549 entry =get_packed_ref(refname);1550if(entry) {1551hashcpy(sha1, entry->u.value.oid.hash);1552*flags |= REF_ISPACKED;1553return0;1554}1555/* refname is not a packed reference. */1556return-1;1557}15581559intread_raw_ref(const char*refname,unsigned char*sha1,1560struct strbuf *referent,unsigned int*type)1561{1562struct strbuf sb_contents = STRBUF_INIT;1563struct strbuf sb_path = STRBUF_INIT;1564const char*path;1565const char*buf;1566struct stat st;1567int fd;1568int ret = -1;1569int save_errno;15701571*type =0;1572strbuf_reset(&sb_path);1573strbuf_git_path(&sb_path,"%s", refname);1574 path = sb_path.buf;15751576stat_ref:1577/*1578 * We might have to loop back here to avoid a race1579 * condition: first we lstat() the file, then we try1580 * to read it as a link or as a file. But if somebody1581 * changes the type of the file (file <-> directory1582 * <-> symlink) between the lstat() and reading, then1583 * we don't want to report that as an error but rather1584 * try again starting with the lstat().1585 */15861587if(lstat(path, &st) <0) {1588if(errno != ENOENT)1589goto out;1590if(resolve_missing_loose_ref(refname, sha1, type)) {1591 errno = ENOENT;1592goto out;1593}1594 ret =0;1595goto out;1596}15971598/* Follow "normalized" - ie "refs/.." symlinks by hand */1599if(S_ISLNK(st.st_mode)) {1600strbuf_reset(&sb_contents);1601if(strbuf_readlink(&sb_contents, path,0) <0) {1602if(errno == ENOENT || errno == EINVAL)1603/* inconsistent with lstat; retry */1604goto stat_ref;1605else1606goto out;1607}1608if(starts_with(sb_contents.buf,"refs/") &&1609!check_refname_format(sb_contents.buf,0)) {1610strbuf_swap(&sb_contents, referent);1611*type |= REF_ISSYMREF;1612 ret =0;1613goto out;1614}1615}16161617/* Is it a directory? */1618if(S_ISDIR(st.st_mode)) {1619/*1620 * Even though there is a directory where the loose1621 * ref is supposed to be, there could still be a1622 * packed ref:1623 */1624if(resolve_missing_loose_ref(refname, sha1, type)) {1625 errno = EISDIR;1626goto out;1627}1628 ret =0;1629goto out;1630}16311632/*1633 * Anything else, just open it and try to use it as1634 * a ref1635 */1636 fd =open(path, O_RDONLY);1637if(fd <0) {1638if(errno == ENOENT)1639/* inconsistent with lstat; retry */1640goto stat_ref;1641else1642goto out;1643}1644strbuf_reset(&sb_contents);1645if(strbuf_read(&sb_contents, fd,256) <0) {1646int save_errno = errno;1647close(fd);1648 errno = save_errno;1649goto out;1650}1651close(fd);1652strbuf_rtrim(&sb_contents);1653 buf = sb_contents.buf;1654if(starts_with(buf,"ref:")) {1655 buf +=4;1656while(isspace(*buf))1657 buf++;16581659strbuf_reset(referent);1660strbuf_addstr(referent, buf);1661*type |= REF_ISSYMREF;1662 ret =0;1663goto out;1664}16651666/*1667 * Please note that FETCH_HEAD has additional1668 * data after the sha.1669 */1670if(get_sha1_hex(buf, sha1) ||1671(buf[40] !='\0'&& !isspace(buf[40]))) {1672*type |= REF_ISBROKEN;1673 errno = EINVAL;1674goto out;1675}16761677 ret =0;16781679out:1680 save_errno = errno;1681strbuf_release(&sb_path);1682strbuf_release(&sb_contents);1683 errno = save_errno;1684return ret;1685}16861687static voidunlock_ref(struct ref_lock *lock)1688{1689/* Do not free lock->lk -- atexit() still looks at them */1690if(lock->lk)1691rollback_lock_file(lock->lk);1692free(lock->ref_name);1693free(lock);1694}16951696/*1697 * Lock refname, without following symrefs, and set *lock_p to point1698 * at a newly-allocated lock object. Fill in lock->old_oid, referent,1699 * and type similarly to read_raw_ref().1700 *1701 * The caller must verify that refname is a "safe" reference name (in1702 * the sense of refname_is_safe()) before calling this function.1703 *1704 * If the reference doesn't already exist, verify that refname doesn't1705 * have a D/F conflict with any existing references. extras and skip1706 * are passed to verify_refname_available_dir() for this check.1707 *1708 * If mustexist is not set and the reference is not found or is1709 * broken, lock the reference anyway but clear sha1.1710 *1711 * Return 0 on success. On failure, write an error message to err and1712 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.1713 *1714 * Implementation note: This function is basically1715 *1716 * lock reference1717 * read_raw_ref()1718 *1719 * but it includes a lot more code to1720 * - Deal with possible races with other processes1721 * - Avoid calling verify_refname_available_dir() when it can be1722 * avoided, namely if we were successfully able to read the ref1723 * - Generate informative error messages in the case of failure1724 */1725static intlock_raw_ref(const char*refname,int mustexist,1726const struct string_list *extras,1727const struct string_list *skip,1728struct ref_lock **lock_p,1729struct strbuf *referent,1730unsigned int*type,1731struct strbuf *err)1732{1733struct ref_lock *lock;1734struct strbuf ref_file = STRBUF_INIT;1735int attempts_remaining =3;1736int ret = TRANSACTION_GENERIC_ERROR;17371738assert(err);1739*type =0;17401741/* First lock the file so it can't change out from under us. */17421743*lock_p = lock =xcalloc(1,sizeof(*lock));17441745 lock->ref_name =xstrdup(refname);1746strbuf_git_path(&ref_file,"%s", refname);17471748retry:1749switch(safe_create_leading_directories(ref_file.buf)) {1750case SCLD_OK:1751break;/* success */1752case SCLD_EXISTS:1753/*1754 * Suppose refname is "refs/foo/bar". We just failed1755 * to create the containing directory, "refs/foo",1756 * because there was a non-directory in the way. This1757 * indicates a D/F conflict, probably because of1758 * another reference such as "refs/foo". There is no1759 * reason to expect this error to be transitory.1760 */1761if(verify_refname_available(refname, extras, skip, err)) {1762if(mustexist) {1763/*1764 * To the user the relevant error is1765 * that the "mustexist" reference is1766 * missing:1767 */1768strbuf_reset(err);1769strbuf_addf(err,"unable to resolve reference '%s'",1770 refname);1771}else{1772/*1773 * The error message set by1774 * verify_refname_available_dir() is OK.1775 */1776 ret = TRANSACTION_NAME_CONFLICT;1777}1778}else{1779/*1780 * The file that is in the way isn't a loose1781 * reference. Report it as a low-level1782 * failure.1783 */1784strbuf_addf(err,"unable to create lock file%s.lock; "1785"non-directory in the way",1786 ref_file.buf);1787}1788goto error_return;1789case SCLD_VANISHED:1790/* Maybe another process was tidying up. Try again. */1791if(--attempts_remaining >0)1792goto retry;1793/* fall through */1794default:1795strbuf_addf(err,"unable to create directory for%s",1796 ref_file.buf);1797goto error_return;1798}17991800if(!lock->lk)1801 lock->lk =xcalloc(1,sizeof(struct lock_file));18021803if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) {1804if(errno == ENOENT && --attempts_remaining >0) {1805/*1806 * Maybe somebody just deleted one of the1807 * directories leading to ref_file. Try1808 * again:1809 */1810goto retry;1811}else{1812unable_to_lock_message(ref_file.buf, errno, err);1813goto error_return;1814}1815}18161817/*1818 * Now we hold the lock and can read the reference without1819 * fear that its value will change.1820 */18211822if(read_raw_ref(refname, lock->old_oid.hash, referent, type)) {1823if(errno == ENOENT) {1824if(mustexist) {1825/* Garden variety missing reference. */1826strbuf_addf(err,"unable to resolve reference '%s'",1827 refname);1828goto error_return;1829}else{1830/*1831 * Reference is missing, but that's OK. We1832 * know that there is not a conflict with1833 * another loose reference because1834 * (supposing that we are trying to lock1835 * reference "refs/foo/bar"):1836 *1837 * - We were successfully able to create1838 * the lockfile refs/foo/bar.lock, so we1839 * know there cannot be a loose reference1840 * named "refs/foo".1841 *1842 * - We got ENOENT and not EISDIR, so we1843 * know that there cannot be a loose1844 * reference named "refs/foo/bar/baz".1845 */1846}1847}else if(errno == EISDIR) {1848/*1849 * There is a directory in the way. It might have1850 * contained references that have been deleted. If1851 * we don't require that the reference already1852 * exists, try to remove the directory so that it1853 * doesn't cause trouble when we want to rename the1854 * lockfile into place later.1855 */1856if(mustexist) {1857/* Garden variety missing reference. */1858strbuf_addf(err,"unable to resolve reference '%s'",1859 refname);1860goto error_return;1861}else if(remove_dir_recursively(&ref_file,1862 REMOVE_DIR_EMPTY_ONLY)) {1863if(verify_refname_available_dir(1864 refname, extras, skip,1865get_loose_refs(&ref_cache),1866 err)) {1867/*1868 * The error message set by1869 * verify_refname_available() is OK.1870 */1871 ret = TRANSACTION_NAME_CONFLICT;1872goto error_return;1873}else{1874/*1875 * We can't delete the directory,1876 * but we also don't know of any1877 * references that it should1878 * contain.1879 */1880strbuf_addf(err,"there is a non-empty directory '%s' "1881"blocking reference '%s'",1882 ref_file.buf, refname);1883goto error_return;1884}1885}1886}else if(errno == EINVAL && (*type & REF_ISBROKEN)) {1887strbuf_addf(err,"unable to resolve reference '%s': "1888"reference broken", refname);1889goto error_return;1890}else{1891strbuf_addf(err,"unable to resolve reference '%s':%s",1892 refname,strerror(errno));1893goto error_return;1894}18951896/*1897 * If the ref did not exist and we are creating it,1898 * make sure there is no existing packed ref whose1899 * name begins with our refname, nor a packed ref1900 * whose name is a proper prefix of our refname.1901 */1902if(verify_refname_available_dir(1903 refname, extras, skip,1904get_packed_refs(&ref_cache),1905 err)) {1906goto error_return;1907}1908}19091910 ret =0;1911goto out;19121913error_return:1914unlock_ref(lock);1915*lock_p = NULL;19161917out:1918strbuf_release(&ref_file);1919return ret;1920}19211922/*1923 * Peel the entry (if possible) and return its new peel_status. If1924 * repeel is true, re-peel the entry even if there is an old peeled1925 * value that is already stored in it.1926 *1927 * It is OK to call this function with a packed reference entry that1928 * might be stale and might even refer to an object that has since1929 * been garbage-collected. In such a case, if the entry has1930 * REF_KNOWS_PEELED then leave the status unchanged and return1931 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1932 */1933static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1934{1935enum peel_status status;19361937if(entry->flag & REF_KNOWS_PEELED) {1938if(repeel) {1939 entry->flag &= ~REF_KNOWS_PEELED;1940oidclr(&entry->u.value.peeled);1941}else{1942returnis_null_oid(&entry->u.value.peeled) ?1943 PEEL_NON_TAG : PEEL_PEELED;1944}1945}1946if(entry->flag & REF_ISBROKEN)1947return PEEL_BROKEN;1948if(entry->flag & REF_ISSYMREF)1949return PEEL_IS_SYMREF;19501951 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1952if(status == PEEL_PEELED || status == PEEL_NON_TAG)1953 entry->flag |= REF_KNOWS_PEELED;1954return status;1955}19561957intpeel_ref(const char*refname,unsigned char*sha1)1958{1959int flag;1960unsigned char base[20];19611962if(current_ref && (current_ref->name == refname1963|| !strcmp(current_ref->name, refname))) {1964if(peel_entry(current_ref,0))1965return-1;1966hashcpy(sha1, current_ref->u.value.peeled.hash);1967return0;1968}19691970if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1971return-1;19721973/*1974 * If the reference is packed, read its ref_entry from the1975 * cache in the hope that we already know its peeled value.1976 * We only try this optimization on packed references because1977 * (a) forcing the filling of the loose reference cache could1978 * be expensive and (b) loose references anyway usually do not1979 * have REF_KNOWS_PEELED.1980 */1981if(flag & REF_ISPACKED) {1982struct ref_entry *r =get_packed_ref(refname);1983if(r) {1984if(peel_entry(r,0))1985return-1;1986hashcpy(sha1, r->u.value.peeled.hash);1987return0;1988}1989}19901991returnpeel_object(base, sha1);1992}19931994struct files_ref_iterator {1995struct ref_iterator base;19961997struct packed_ref_cache *packed_ref_cache;1998struct ref_iterator *iter0;1999unsigned int flags;2000};20012002static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)2003{2004struct files_ref_iterator *iter =2005(struct files_ref_iterator *)ref_iterator;2006int ok;20072008while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {2009if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&2010!ref_resolves_to_object(iter->iter0->refname,2011 iter->iter0->oid,2012 iter->iter0->flags))2013continue;20142015 iter->base.refname = iter->iter0->refname;2016 iter->base.oid = iter->iter0->oid;2017 iter->base.flags = iter->iter0->flags;2018return ITER_OK;2019}20202021 iter->iter0 = NULL;2022if(ref_iterator_abort(ref_iterator) != ITER_DONE)2023 ok = ITER_ERROR;20242025return ok;2026}20272028static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,2029struct object_id *peeled)2030{2031struct files_ref_iterator *iter =2032(struct files_ref_iterator *)ref_iterator;20332034returnref_iterator_peel(iter->iter0, peeled);2035}20362037static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)2038{2039struct files_ref_iterator *iter =2040(struct files_ref_iterator *)ref_iterator;2041int ok = ITER_DONE;20422043if(iter->iter0)2044 ok =ref_iterator_abort(iter->iter0);20452046release_packed_ref_cache(iter->packed_ref_cache);2047base_ref_iterator_free(ref_iterator);2048return ok;2049}20502051static struct ref_iterator_vtable files_ref_iterator_vtable = {2052 files_ref_iterator_advance,2053 files_ref_iterator_peel,2054 files_ref_iterator_abort2055};20562057struct ref_iterator *files_ref_iterator_begin(2058const char*submodule,2059const char*prefix,unsigned int flags)2060{2061struct ref_cache *refs =get_ref_cache(submodule);2062struct ref_dir *loose_dir, *packed_dir;2063struct ref_iterator *loose_iter, *packed_iter;2064struct files_ref_iterator *iter;2065struct ref_iterator *ref_iterator;20662067if(!refs)2068returnempty_ref_iterator_begin();20692070if(ref_paranoia <0)2071 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2072if(ref_paranoia)2073 flags |= DO_FOR_EACH_INCLUDE_BROKEN;20742075 iter =xcalloc(1,sizeof(*iter));2076 ref_iterator = &iter->base;2077base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);20782079/*2080 * We must make sure that all loose refs are read before2081 * accessing the packed-refs file; this avoids a race2082 * condition if loose refs are migrated to the packed-refs2083 * file by a simultaneous process, but our in-memory view is2084 * from before the migration. We ensure this as follows:2085 * First, we call prime_ref_dir(), which pre-reads the loose2086 * references for the subtree into the cache. (If they've2087 * already been read, that's OK; we only need to guarantee2088 * that they're read before the packed refs, not *how much*2089 * before.) After that, we call get_packed_ref_cache(), which2090 * internally checks whether the packed-ref cache is up to2091 * date with what is on disk, and re-reads it if not.2092 */20932094 loose_dir =get_loose_refs(refs);20952096if(prefix && *prefix)2097 loose_dir =find_containing_dir(loose_dir, prefix,0);20982099if(loose_dir) {2100prime_ref_dir(loose_dir);2101 loose_iter =cache_ref_iterator_begin(loose_dir);2102}else{2103/* There's nothing to iterate over. */2104 loose_iter =empty_ref_iterator_begin();2105}21062107 iter->packed_ref_cache =get_packed_ref_cache(refs);2108acquire_packed_ref_cache(iter->packed_ref_cache);2109 packed_dir =get_packed_ref_dir(iter->packed_ref_cache);21102111if(prefix && *prefix)2112 packed_dir =find_containing_dir(packed_dir, prefix,0);21132114if(packed_dir) {2115 packed_iter =cache_ref_iterator_begin(packed_dir);2116}else{2117/* There's nothing to iterate over. */2118 packed_iter =empty_ref_iterator_begin();2119}21202121 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);2122 iter->flags = flags;21232124return ref_iterator;2125}21262127/*2128 * Call fn for each reference in the specified ref_cache, omitting2129 * references not in the containing_dir of prefix. Call fn for all2130 * references, including broken ones. If fn ever returns a non-zero2131 * value, stop the iteration and return that value; otherwise, return2132 * 0.2133 */2134static intdo_for_each_entry(struct ref_cache *refs,const char*prefix,2135 each_ref_entry_fn fn,void*cb_data)2136{2137struct packed_ref_cache *packed_ref_cache;2138struct ref_dir *loose_dir;2139struct ref_dir *packed_dir;2140int retval =0;21412142/*2143 * We must make sure that all loose refs are read before accessing the2144 * packed-refs file; this avoids a race condition in which loose refs2145 * are migrated to the packed-refs file by a simultaneous process, but2146 * our in-memory view is from before the migration. get_packed_ref_cache()2147 * takes care of making sure our view is up to date with what is on2148 * disk.2149 */2150 loose_dir =get_loose_refs(refs);2151if(prefix && *prefix) {2152 loose_dir =find_containing_dir(loose_dir, prefix,0);2153}2154if(loose_dir)2155prime_ref_dir(loose_dir);21562157 packed_ref_cache =get_packed_ref_cache(refs);2158acquire_packed_ref_cache(packed_ref_cache);2159 packed_dir =get_packed_ref_dir(packed_ref_cache);2160if(prefix && *prefix) {2161 packed_dir =find_containing_dir(packed_dir, prefix,0);2162}21632164if(packed_dir && loose_dir) {2165sort_ref_dir(packed_dir);2166sort_ref_dir(loose_dir);2167 retval =do_for_each_entry_in_dirs(2168 packed_dir, loose_dir, fn, cb_data);2169}else if(packed_dir) {2170sort_ref_dir(packed_dir);2171 retval =do_for_each_entry_in_dir(2172 packed_dir,0, fn, cb_data);2173}else if(loose_dir) {2174sort_ref_dir(loose_dir);2175 retval =do_for_each_entry_in_dir(2176 loose_dir,0, fn, cb_data);2177}21782179release_packed_ref_cache(packed_ref_cache);2180return retval;2181}21822183intdo_for_each_ref(const char*submodule,const char*prefix,2184 each_ref_fn fn,int trim,int flags,void*cb_data)2185{2186struct ref_entry_cb data;2187struct ref_cache *refs;21882189 refs =get_ref_cache(submodule);2190if(!refs)2191return0;21922193 data.prefix = prefix;2194 data.trim = trim;2195 data.flags = flags;2196 data.fn = fn;2197 data.cb_data = cb_data;21982199if(ref_paranoia <0)2200 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2201if(ref_paranoia)2202 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;22032204returndo_for_each_entry(refs, prefix, do_one_ref, &data);2205}22062207/*2208 * Verify that the reference locked by lock has the value old_sha1.2209 * Fail if the reference doesn't exist and mustexist is set. Return 02210 * on success. On error, write an error message to err, set errno, and2211 * return a negative value.2212 */2213static intverify_lock(struct ref_lock *lock,2214const unsigned char*old_sha1,int mustexist,2215struct strbuf *err)2216{2217assert(err);22182219if(read_ref_full(lock->ref_name,2220 mustexist ? RESOLVE_REF_READING :0,2221 lock->old_oid.hash, NULL)) {2222if(old_sha1) {2223int save_errno = errno;2224strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);2225 errno = save_errno;2226return-1;2227}else{2228hashclr(lock->old_oid.hash);2229return0;2230}2231}2232if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {2233strbuf_addf(err,"ref '%s' is at%sbut expected%s",2234 lock->ref_name,2235sha1_to_hex(lock->old_oid.hash),2236sha1_to_hex(old_sha1));2237 errno = EBUSY;2238return-1;2239}2240return0;2241}22422243static intremove_empty_directories(struct strbuf *path)2244{2245/*2246 * we want to create a file but there is a directory there;2247 * if that is an empty directory (or a directory that contains2248 * only empty directories), remove them.2249 */2250returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);2251}22522253/*2254 * Locks a ref returning the lock on success and NULL on failure.2255 * On failure errno is set to something meaningful.2256 */2257static struct ref_lock *lock_ref_sha1_basic(const char*refname,2258const unsigned char*old_sha1,2259const struct string_list *extras,2260const struct string_list *skip,2261unsigned int flags,int*type,2262struct strbuf *err)2263{2264struct strbuf ref_file = STRBUF_INIT;2265struct ref_lock *lock;2266int last_errno =0;2267int lflags = LOCK_NO_DEREF;2268int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2269int resolve_flags = RESOLVE_REF_NO_RECURSE;2270int attempts_remaining =3;2271int resolved;22722273assert(err);22742275 lock =xcalloc(1,sizeof(struct ref_lock));22762277if(mustexist)2278 resolve_flags |= RESOLVE_REF_READING;2279if(flags & REF_DELETING)2280 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;22812282strbuf_git_path(&ref_file,"%s", refname);2283 resolved = !!resolve_ref_unsafe(refname, resolve_flags,2284 lock->old_oid.hash, type);2285if(!resolved && errno == EISDIR) {2286/*2287 * we are trying to lock foo but we used to2288 * have foo/bar which now does not exist;2289 * it is normal for the empty directory 'foo'2290 * to remain.2291 */2292if(remove_empty_directories(&ref_file)) {2293 last_errno = errno;2294if(!verify_refname_available_dir(refname, extras, skip,2295get_loose_refs(&ref_cache), err))2296strbuf_addf(err,"there are still refs under '%s'",2297 refname);2298goto error_return;2299}2300 resolved = !!resolve_ref_unsafe(refname, resolve_flags,2301 lock->old_oid.hash, type);2302}2303if(!resolved) {2304 last_errno = errno;2305if(last_errno != ENOTDIR ||2306!verify_refname_available_dir(refname, extras, skip,2307get_loose_refs(&ref_cache), err))2308strbuf_addf(err,"unable to resolve reference '%s':%s",2309 refname,strerror(last_errno));23102311goto error_return;2312}23132314/*2315 * If the ref did not exist and we are creating it, make sure2316 * there is no existing packed ref whose name begins with our2317 * refname, nor a packed ref whose name is a proper prefix of2318 * our refname.2319 */2320if(is_null_oid(&lock->old_oid) &&2321verify_refname_available_dir(refname, extras, skip,2322get_packed_refs(&ref_cache), err)) {2323 last_errno = ENOTDIR;2324goto error_return;2325}23262327 lock->lk =xcalloc(1,sizeof(struct lock_file));23282329 lock->ref_name =xstrdup(refname);23302331 retry:2332switch(safe_create_leading_directories_const(ref_file.buf)) {2333case SCLD_OK:2334break;/* success */2335case SCLD_VANISHED:2336if(--attempts_remaining >0)2337goto retry;2338/* fall through */2339default:2340 last_errno = errno;2341strbuf_addf(err,"unable to create directory for '%s'",2342 ref_file.buf);2343goto error_return;2344}23452346if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2347 last_errno = errno;2348if(errno == ENOENT && --attempts_remaining >0)2349/*2350 * Maybe somebody just deleted one of the2351 * directories leading to ref_file. Try2352 * again:2353 */2354goto retry;2355else{2356unable_to_lock_message(ref_file.buf, errno, err);2357goto error_return;2358}2359}2360if(verify_lock(lock, old_sha1, mustexist, err)) {2361 last_errno = errno;2362goto error_return;2363}2364goto out;23652366 error_return:2367unlock_ref(lock);2368 lock = NULL;23692370 out:2371strbuf_release(&ref_file);2372 errno = last_errno;2373return lock;2374}23752376/*2377 * Write an entry to the packed-refs file for the specified refname.2378 * If peeled is non-NULL, write it as the entry's peeled value.2379 */2380static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2381unsigned char*peeled)2382{2383fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2384if(peeled)2385fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2386}23872388/*2389 * An each_ref_entry_fn that writes the entry to a packed-refs file.2390 */2391static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2392{2393enum peel_status peel_status =peel_entry(entry,0);23942395if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2396error("internal error:%sis not a valid packed reference!",2397 entry->name);2398write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2399 peel_status == PEEL_PEELED ?2400 entry->u.value.peeled.hash : NULL);2401return0;2402}24032404/*2405 * Lock the packed-refs file for writing. Flags is passed to2406 * hold_lock_file_for_update(). Return 0 on success. On errors, set2407 * errno appropriately and return a nonzero value.2408 */2409static intlock_packed_refs(int flags)2410{2411static int timeout_configured =0;2412static int timeout_value =1000;24132414struct packed_ref_cache *packed_ref_cache;24152416if(!timeout_configured) {2417git_config_get_int("core.packedrefstimeout", &timeout_value);2418 timeout_configured =1;2419}24202421if(hold_lock_file_for_update_timeout(2422&packlock,git_path("packed-refs"),2423 flags, timeout_value) <0)2424return-1;2425/*2426 * Get the current packed-refs while holding the lock. If the2427 * packed-refs file has been modified since we last read it,2428 * this will automatically invalidate the cache and re-read2429 * the packed-refs file.2430 */2431 packed_ref_cache =get_packed_ref_cache(&ref_cache);2432 packed_ref_cache->lock = &packlock;2433/* Increment the reference count to prevent it from being freed: */2434acquire_packed_ref_cache(packed_ref_cache);2435return0;2436}24372438/*2439 * Write the current version of the packed refs cache from memory to2440 * disk. The packed-refs file must already be locked for writing (see2441 * lock_packed_refs()). Return zero on success. On errors, set errno2442 * and return a nonzero value2443 */2444static intcommit_packed_refs(void)2445{2446struct packed_ref_cache *packed_ref_cache =2447get_packed_ref_cache(&ref_cache);2448int error =0;2449int save_errno =0;2450FILE*out;24512452if(!packed_ref_cache->lock)2453die("internal error: packed-refs not locked");24542455 out =fdopen_lock_file(packed_ref_cache->lock,"w");2456if(!out)2457die_errno("unable to fdopen packed-refs descriptor");24582459fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2460do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),24610, write_packed_entry_fn, out);24622463if(commit_lock_file(packed_ref_cache->lock)) {2464 save_errno = errno;2465 error = -1;2466}2467 packed_ref_cache->lock = NULL;2468release_packed_ref_cache(packed_ref_cache);2469 errno = save_errno;2470return error;2471}24722473/*2474 * Rollback the lockfile for the packed-refs file, and discard the2475 * in-memory packed reference cache. (The packed-refs file will be2476 * read anew if it is needed again after this function is called.)2477 */2478static voidrollback_packed_refs(void)2479{2480struct packed_ref_cache *packed_ref_cache =2481get_packed_ref_cache(&ref_cache);24822483if(!packed_ref_cache->lock)2484die("internal error: packed-refs not locked");2485rollback_lock_file(packed_ref_cache->lock);2486 packed_ref_cache->lock = NULL;2487release_packed_ref_cache(packed_ref_cache);2488clear_packed_ref_cache(&ref_cache);2489}24902491struct ref_to_prune {2492struct ref_to_prune *next;2493unsigned char sha1[20];2494char name[FLEX_ARRAY];2495};24962497struct pack_refs_cb_data {2498unsigned int flags;2499struct ref_dir *packed_refs;2500struct ref_to_prune *ref_to_prune;2501};25022503/*2504 * An each_ref_entry_fn that is run over loose references only. If2505 * the loose reference can be packed, add an entry in the packed ref2506 * cache. If the reference should be pruned, also add it to2507 * ref_to_prune in the pack_refs_cb_data.2508 */2509static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2510{2511struct pack_refs_cb_data *cb = cb_data;2512enum peel_status peel_status;2513struct ref_entry *packed_entry;2514int is_tag_ref =starts_with(entry->name,"refs/tags/");25152516/* Do not pack per-worktree refs: */2517if(ref_type(entry->name) != REF_TYPE_NORMAL)2518return0;25192520/* ALWAYS pack tags */2521if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2522return0;25232524/* Do not pack symbolic or broken refs: */2525if((entry->flag & REF_ISSYMREF) || !entry_resolves_to_object(entry))2526return0;25272528/* Add a packed ref cache entry equivalent to the loose entry. */2529 peel_status =peel_entry(entry,1);2530if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2531die("internal error peeling reference%s(%s)",2532 entry->name,oid_to_hex(&entry->u.value.oid));2533 packed_entry =find_ref(cb->packed_refs, entry->name);2534if(packed_entry) {2535/* Overwrite existing packed entry with info from loose entry */2536 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2537oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2538}else{2539 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2540 REF_ISPACKED | REF_KNOWS_PEELED,0);2541add_ref(cb->packed_refs, packed_entry);2542}2543oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);25442545/* Schedule the loose reference for pruning if requested. */2546if((cb->flags & PACK_REFS_PRUNE)) {2547struct ref_to_prune *n;2548FLEX_ALLOC_STR(n, name, entry->name);2549hashcpy(n->sha1, entry->u.value.oid.hash);2550 n->next = cb->ref_to_prune;2551 cb->ref_to_prune = n;2552}2553return0;2554}25552556/*2557 * Remove empty parents, but spare refs/ and immediate subdirs.2558 * Note: munges *name.2559 */2560static voidtry_remove_empty_parents(char*name)2561{2562char*p, *q;2563int i;2564 p = name;2565for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2566while(*p && *p !='/')2567 p++;2568/* tolerate duplicate slashes; see check_refname_format() */2569while(*p =='/')2570 p++;2571}2572for(q = p; *q; q++)2573;2574while(1) {2575while(q > p && *q !='/')2576 q--;2577while(q > p && *(q-1) =='/')2578 q--;2579if(q == p)2580break;2581*q ='\0';2582if(rmdir(git_path("%s", name)))2583break;2584}2585}25862587/* make sure nobody touched the ref, and unlink */2588static voidprune_ref(struct ref_to_prune *r)2589{2590struct ref_transaction *transaction;2591struct strbuf err = STRBUF_INIT;25922593if(check_refname_format(r->name,0))2594return;25952596 transaction =ref_transaction_begin(&err);2597if(!transaction ||2598ref_transaction_delete(transaction, r->name, r->sha1,2599 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||2600ref_transaction_commit(transaction, &err)) {2601ref_transaction_free(transaction);2602error("%s", err.buf);2603strbuf_release(&err);2604return;2605}2606ref_transaction_free(transaction);2607strbuf_release(&err);2608try_remove_empty_parents(r->name);2609}26102611static voidprune_refs(struct ref_to_prune *r)2612{2613while(r) {2614prune_ref(r);2615 r = r->next;2616}2617}26182619intpack_refs(unsigned int flags)2620{2621struct pack_refs_cb_data cbdata;26222623memset(&cbdata,0,sizeof(cbdata));2624 cbdata.flags = flags;26252626lock_packed_refs(LOCK_DIE_ON_ERROR);2627 cbdata.packed_refs =get_packed_refs(&ref_cache);26282629do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2630 pack_if_possible_fn, &cbdata);26312632if(commit_packed_refs())2633die_errno("unable to overwrite old ref-pack file");26342635prune_refs(cbdata.ref_to_prune);2636return0;2637}26382639/*2640 * Rewrite the packed-refs file, omitting any refs listed in2641 * 'refnames'. On error, leave packed-refs unchanged, write an error2642 * message to 'err', and return a nonzero value.2643 *2644 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2645 */2646static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2647{2648struct ref_dir *packed;2649struct string_list_item *refname;2650int ret, needs_repacking =0, removed =0;26512652assert(err);26532654/* Look for a packed ref */2655for_each_string_list_item(refname, refnames) {2656if(get_packed_ref(refname->string)) {2657 needs_repacking =1;2658break;2659}2660}26612662/* Avoid locking if we have nothing to do */2663if(!needs_repacking)2664return0;/* no refname exists in packed refs */26652666if(lock_packed_refs(0)) {2667unable_to_lock_message(git_path("packed-refs"), errno, err);2668return-1;2669}2670 packed =get_packed_refs(&ref_cache);26712672/* Remove refnames from the cache */2673for_each_string_list_item(refname, refnames)2674if(remove_entry(packed, refname->string) != -1)2675 removed =1;2676if(!removed) {2677/*2678 * All packed entries disappeared while we were2679 * acquiring the lock.2680 */2681rollback_packed_refs();2682return0;2683}26842685/* Write what remains */2686 ret =commit_packed_refs();2687if(ret)2688strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2689strerror(errno));2690return ret;2691}26922693static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2694{2695assert(err);26962697if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2698/*2699 * loose. The loose file name is the same as the2700 * lockfile name, minus ".lock":2701 */2702char*loose_filename =get_locked_file_path(lock->lk);2703int res =unlink_or_msg(loose_filename, err);2704free(loose_filename);2705if(res)2706return1;2707}2708return0;2709}27102711intdelete_refs(struct string_list *refnames,unsigned int flags)2712{2713struct strbuf err = STRBUF_INIT;2714int i, result =0;27152716if(!refnames->nr)2717return0;27182719 result =repack_without_refs(refnames, &err);2720if(result) {2721/*2722 * If we failed to rewrite the packed-refs file, then2723 * it is unsafe to try to remove loose refs, because2724 * doing so might expose an obsolete packed value for2725 * a reference that might even point at an object that2726 * has been garbage collected.2727 */2728if(refnames->nr ==1)2729error(_("could not delete reference%s:%s"),2730 refnames->items[0].string, err.buf);2731else2732error(_("could not delete references:%s"), err.buf);27332734goto out;2735}27362737for(i =0; i < refnames->nr; i++) {2738const char*refname = refnames->items[i].string;27392740if(delete_ref(refname, NULL, flags))2741 result |=error(_("could not remove reference%s"), refname);2742}27432744out:2745strbuf_release(&err);2746return result;2747}27482749/*2750 * People using contrib's git-new-workdir have .git/logs/refs ->2751 * /some/other/path/.git/logs/refs, and that may live on another device.2752 *2753 * IOW, to avoid cross device rename errors, the temporary renamed log must2754 * live into logs/refs.2755 */2756#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"27572758static intrename_tmp_log(const char*newrefname)2759{2760int attempts_remaining =4;2761struct strbuf path = STRBUF_INIT;2762int ret = -1;27632764 retry:2765strbuf_reset(&path);2766strbuf_git_path(&path,"logs/%s", newrefname);2767switch(safe_create_leading_directories_const(path.buf)) {2768case SCLD_OK:2769break;/* success */2770case SCLD_VANISHED:2771if(--attempts_remaining >0)2772goto retry;2773/* fall through */2774default:2775error("unable to create directory for%s", newrefname);2776goto out;2777}27782779if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2780if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2781/*2782 * rename(a, b) when b is an existing2783 * directory ought to result in ISDIR, but2784 * Solaris 5.8 gives ENOTDIR. Sheesh.2785 */2786if(remove_empty_directories(&path)) {2787error("Directory not empty: logs/%s", newrefname);2788goto out;2789}2790goto retry;2791}else if(errno == ENOENT && --attempts_remaining >0) {2792/*2793 * Maybe another process just deleted one of2794 * the directories in the path to newrefname.2795 * Try again from the beginning.2796 */2797goto retry;2798}else{2799error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2800 newrefname,strerror(errno));2801goto out;2802}2803}2804 ret =0;2805out:2806strbuf_release(&path);2807return ret;2808}28092810intverify_refname_available(const char*newname,2811const struct string_list *extras,2812const struct string_list *skip,2813struct strbuf *err)2814{2815struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2816struct ref_dir *loose_refs =get_loose_refs(&ref_cache);28172818if(verify_refname_available_dir(newname, extras, skip,2819 packed_refs, err) ||2820verify_refname_available_dir(newname, extras, skip,2821 loose_refs, err))2822return-1;28232824return0;2825}28262827static intwrite_ref_to_lockfile(struct ref_lock *lock,2828const unsigned char*sha1,struct strbuf *err);2829static intcommit_ref_update(struct ref_lock *lock,2830const unsigned char*sha1,const char*logmsg,2831struct strbuf *err);28322833intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2834{2835unsigned char sha1[20], orig_sha1[20];2836int flag =0, logmoved =0;2837struct ref_lock *lock;2838struct stat loginfo;2839int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2840struct strbuf err = STRBUF_INIT;28412842if(log &&S_ISLNK(loginfo.st_mode))2843returnerror("reflog for%sis a symlink", oldrefname);28442845if(!resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2846 orig_sha1, &flag))2847returnerror("refname%snot found", oldrefname);28482849if(flag & REF_ISSYMREF)2850returnerror("refname%sis a symbolic ref, renaming it is not supported",2851 oldrefname);2852if(!rename_ref_available(oldrefname, newrefname))2853return1;28542855if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2856returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2857 oldrefname,strerror(errno));28582859if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2860error("unable to delete old%s", oldrefname);2861goto rollback;2862}28632864/*2865 * Since we are doing a shallow lookup, sha1 is not the2866 * correct value to pass to delete_ref as old_sha1. But that2867 * doesn't matter, because an old_sha1 check wouldn't add to2868 * the safety anyway; we want to delete the reference whatever2869 * its current value.2870 */2871if(!read_ref_full(newrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2872 sha1, NULL) &&2873delete_ref(newrefname, NULL, REF_NODEREF)) {2874if(errno==EISDIR) {2875struct strbuf path = STRBUF_INIT;2876int result;28772878strbuf_git_path(&path,"%s", newrefname);2879 result =remove_empty_directories(&path);2880strbuf_release(&path);28812882if(result) {2883error("Directory not empty:%s", newrefname);2884goto rollback;2885}2886}else{2887error("unable to delete existing%s", newrefname);2888goto rollback;2889}2890}28912892if(log &&rename_tmp_log(newrefname))2893goto rollback;28942895 logmoved = log;28962897 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, REF_NODEREF,2898 NULL, &err);2899if(!lock) {2900error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2901strbuf_release(&err);2902goto rollback;2903}2904hashcpy(lock->old_oid.hash, orig_sha1);29052906if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2907commit_ref_update(lock, orig_sha1, logmsg, &err)) {2908error("unable to write current sha1 into%s:%s", newrefname, err.buf);2909strbuf_release(&err);2910goto rollback;2911}29122913return0;29142915 rollback:2916 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, REF_NODEREF,2917 NULL, &err);2918if(!lock) {2919error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2920strbuf_release(&err);2921goto rollbacklog;2922}29232924 flag = log_all_ref_updates;2925 log_all_ref_updates =0;2926if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2927commit_ref_update(lock, orig_sha1, NULL, &err)) {2928error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2929strbuf_release(&err);2930}2931 log_all_ref_updates = flag;29322933 rollbacklog:2934if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2935error("unable to restore logfile%sfrom%s:%s",2936 oldrefname, newrefname,strerror(errno));2937if(!logmoved && log &&2938rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2939error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2940 oldrefname,strerror(errno));29412942return1;2943}29442945static intclose_ref(struct ref_lock *lock)2946{2947if(close_lock_file(lock->lk))2948return-1;2949return0;2950}29512952static intcommit_ref(struct ref_lock *lock)2953{2954char*path =get_locked_file_path(lock->lk);2955struct stat st;29562957if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {2958/*2959 * There is a directory at the path we want to rename2960 * the lockfile to. Hopefully it is empty; try to2961 * delete it.2962 */2963size_t len =strlen(path);2964struct strbuf sb_path = STRBUF_INIT;29652966strbuf_attach(&sb_path, path, len, len);29672968/*2969 * If this fails, commit_lock_file() will also fail2970 * and will report the problem.2971 */2972remove_empty_directories(&sb_path);2973strbuf_release(&sb_path);2974}else{2975free(path);2976}29772978if(commit_lock_file(lock->lk))2979return-1;2980return0;2981}29822983/*2984 * Create a reflog for a ref. If force_create = 0, the reflog will2985 * only be created for certain refs (those for which2986 * should_autocreate_reflog returns non-zero. Otherwise, create it2987 * regardless of the ref name. Fill in *err and return -1 on failure.2988 */2989static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2990{2991int logfd, oflags = O_APPEND | O_WRONLY;29922993strbuf_git_path(logfile,"logs/%s", refname);2994if(force_create ||should_autocreate_reflog(refname)) {2995if(safe_create_leading_directories(logfile->buf) <0) {2996strbuf_addf(err,"unable to create directory for '%s': "2997"%s", logfile->buf,strerror(errno));2998return-1;2999}3000 oflags |= O_CREAT;3001}30023003 logfd =open(logfile->buf, oflags,0666);3004if(logfd <0) {3005if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3006return0;30073008if(errno == EISDIR) {3009if(remove_empty_directories(logfile)) {3010strbuf_addf(err,"there are still logs under "3011"'%s'", logfile->buf);3012return-1;3013}3014 logfd =open(logfile->buf, oflags,0666);3015}30163017if(logfd <0) {3018strbuf_addf(err,"unable to append to '%s':%s",3019 logfile->buf,strerror(errno));3020return-1;3021}3022}30233024adjust_shared_perm(logfile->buf);3025close(logfd);3026return0;3027}302830293030intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3031{3032int ret;3033struct strbuf sb = STRBUF_INIT;30343035 ret =log_ref_setup(refname, &sb, err, force_create);3036strbuf_release(&sb);3037return ret;3038}30393040static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3041const unsigned char*new_sha1,3042const char*committer,const char*msg)3043{3044int msglen, written;3045unsigned maxlen, len;3046char*logrec;30473048 msglen = msg ?strlen(msg) :0;3049 maxlen =strlen(committer) + msglen +100;3050 logrec =xmalloc(maxlen);3051 len =xsnprintf(logrec, maxlen,"%s %s %s\n",3052sha1_to_hex(old_sha1),3053sha1_to_hex(new_sha1),3054 committer);3055if(msglen)3056 len +=copy_reflog_msg(logrec + len -1, msg) -1;30573058 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3059free(logrec);3060if(written != len)3061return-1;30623063return0;3064}30653066static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3067const unsigned char*new_sha1,const char*msg,3068struct strbuf *logfile,int flags,3069struct strbuf *err)3070{3071int logfd, result, oflags = O_APPEND | O_WRONLY;30723073if(log_all_ref_updates <0)3074 log_all_ref_updates = !is_bare_repository();30753076 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);30773078if(result)3079return result;30803081 logfd =open(logfile->buf, oflags);3082if(logfd <0)3083return0;3084 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3085git_committer_info(0), msg);3086if(result) {3087strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,3088strerror(errno));3089close(logfd);3090return-1;3091}3092if(close(logfd)) {3093strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,3094strerror(errno));3095return-1;3096}3097return0;3098}30993100static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3101const unsigned char*new_sha1,const char*msg,3102int flags,struct strbuf *err)3103{3104returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,3105 err);3106}31073108intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,3109const unsigned char*new_sha1,const char*msg,3110int flags,struct strbuf *err)3111{3112struct strbuf sb = STRBUF_INIT;3113int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3114 err);3115strbuf_release(&sb);3116return ret;3117}31183119/*3120 * Write sha1 into the open lockfile, then close the lockfile. On3121 * errors, rollback the lockfile, fill in *err and3122 * return -1.3123 */3124static intwrite_ref_to_lockfile(struct ref_lock *lock,3125const unsigned char*sha1,struct strbuf *err)3126{3127static char term ='\n';3128struct object *o;3129int fd;31303131 o =parse_object(sha1);3132if(!o) {3133strbuf_addf(err,3134"trying to write ref '%s' with nonexistent object%s",3135 lock->ref_name,sha1_to_hex(sha1));3136unlock_ref(lock);3137return-1;3138}3139if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3140strbuf_addf(err,3141"trying to write non-commit object%sto branch '%s'",3142sha1_to_hex(sha1), lock->ref_name);3143unlock_ref(lock);3144return-1;3145}3146 fd =get_lock_file_fd(lock->lk);3147if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||3148write_in_full(fd, &term,1) !=1||3149close_ref(lock) <0) {3150strbuf_addf(err,3151"couldn't write '%s'",get_lock_file_path(lock->lk));3152unlock_ref(lock);3153return-1;3154}3155return0;3156}31573158/*3159 * Commit a change to a loose reference that has already been written3160 * to the loose reference lockfile. Also update the reflogs if3161 * necessary, using the specified lockmsg (which can be NULL).3162 */3163static intcommit_ref_update(struct ref_lock *lock,3164const unsigned char*sha1,const char*logmsg,3165struct strbuf *err)3166{3167clear_loose_ref_cache(&ref_cache);3168if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg,0, err)) {3169char*old_msg =strbuf_detach(err, NULL);3170strbuf_addf(err,"cannot update the ref '%s':%s",3171 lock->ref_name, old_msg);3172free(old_msg);3173unlock_ref(lock);3174return-1;3175}31763177if(strcmp(lock->ref_name,"HEAD") !=0) {3178/*3179 * Special hack: If a branch is updated directly and HEAD3180 * points to it (may happen on the remote side of a push3181 * for example) then logically the HEAD reflog should be3182 * updated too.3183 * A generic solution implies reverse symref information,3184 * but finding all symrefs pointing to the given branch3185 * would be rather costly for this rare event (the direct3186 * update of a branch) to be worth it. So let's cheat and3187 * check with HEAD only which should cover 99% of all usage3188 * scenarios (even 100% of the default ones).3189 */3190unsigned char head_sha1[20];3191int head_flag;3192const char*head_ref;31933194 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3195 head_sha1, &head_flag);3196if(head_ref && (head_flag & REF_ISSYMREF) &&3197!strcmp(head_ref, lock->ref_name)) {3198struct strbuf log_err = STRBUF_INIT;3199if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3200 logmsg,0, &log_err)) {3201error("%s", log_err.buf);3202strbuf_release(&log_err);3203}3204}3205}32063207if(commit_ref(lock)) {3208strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3209unlock_ref(lock);3210return-1;3211}32123213unlock_ref(lock);3214return0;3215}32163217static intcreate_ref_symlink(struct ref_lock *lock,const char*target)3218{3219int ret = -1;3220#ifndef NO_SYMLINK_HEAD3221char*ref_path =get_locked_file_path(lock->lk);3222unlink(ref_path);3223 ret =symlink(target, ref_path);3224free(ref_path);32253226if(ret)3227fprintf(stderr,"no symlink - falling back to symbolic ref\n");3228#endif3229return ret;3230}32313232static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,3233const char*target,const char*logmsg)3234{3235struct strbuf err = STRBUF_INIT;3236unsigned char new_sha1[20];3237if(logmsg && !read_ref(target, new_sha1) &&3238log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {3239error("%s", err.buf);3240strbuf_release(&err);3241}3242}32433244static intcreate_symref_locked(struct ref_lock *lock,const char*refname,3245const char*target,const char*logmsg)3246{3247if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {3248update_symref_reflog(lock, refname, target, logmsg);3249return0;3250}32513252if(!fdopen_lock_file(lock->lk,"w"))3253returnerror("unable to fdopen%s:%s",3254 lock->lk->tempfile.filename.buf,strerror(errno));32553256update_symref_reflog(lock, refname, target, logmsg);32573258/* no error check; commit_ref will check ferror */3259fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);3260if(commit_ref(lock) <0)3261returnerror("unable to write symref for%s:%s", refname,3262strerror(errno));3263return0;3264}32653266intcreate_symref(const char*refname,const char*target,const char*logmsg)3267{3268struct strbuf err = STRBUF_INIT;3269struct ref_lock *lock;3270int ret;32713272 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,3273&err);3274if(!lock) {3275error("%s", err.buf);3276strbuf_release(&err);3277return-1;3278}32793280 ret =create_symref_locked(lock, refname, target, logmsg);3281unlock_ref(lock);3282return ret;3283}32843285intset_worktree_head_symref(const char*gitdir,const char*target)3286{3287static struct lock_file head_lock;3288struct ref_lock *lock;3289struct strbuf head_path = STRBUF_INIT;3290const char*head_rel;3291int ret;32923293strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));3294if(hold_lock_file_for_update(&head_lock, head_path.buf,3295 LOCK_NO_DEREF) <0) {3296struct strbuf err = STRBUF_INIT;3297unable_to_lock_message(head_path.buf, errno, &err);3298error("%s", err.buf);3299strbuf_release(&err);3300strbuf_release(&head_path);3301return-1;3302}33033304/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for3305 linked trees */3306 head_rel =remove_leading_path(head_path.buf,3307absolute_path(get_git_common_dir()));3308/* to make use of create_symref_locked(), initialize ref_lock */3309 lock =xcalloc(1,sizeof(struct ref_lock));3310 lock->lk = &head_lock;3311 lock->ref_name =xstrdup(head_rel);33123313 ret =create_symref_locked(lock, head_rel, target, NULL);33143315unlock_ref(lock);/* will free lock */3316strbuf_release(&head_path);3317return ret;3318}33193320intreflog_exists(const char*refname)3321{3322struct stat st;33233324return!lstat(git_path("logs/%s", refname), &st) &&3325S_ISREG(st.st_mode);3326}33273328intdelete_reflog(const char*refname)3329{3330returnremove_path(git_path("logs/%s", refname));3331}33323333static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3334{3335unsigned char osha1[20], nsha1[20];3336char*email_end, *message;3337unsigned long timestamp;3338int tz;33393340/* old SP new SP name <email> SP time TAB msg LF */3341if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3342get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3343get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3344!(email_end =strchr(sb->buf +82,'>')) ||3345 email_end[1] !=' '||3346!(timestamp =strtoul(email_end +2, &message,10)) ||3347!message || message[0] !=' '||3348(message[1] !='+'&& message[1] !='-') ||3349!isdigit(message[2]) || !isdigit(message[3]) ||3350!isdigit(message[4]) || !isdigit(message[5]))3351return0;/* corrupt? */3352 email_end[1] ='\0';3353 tz =strtol(message +1, NULL,10);3354if(message[6] !='\t')3355 message +=6;3356else3357 message +=7;3358returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3359}33603361static char*find_beginning_of_line(char*bob,char*scan)3362{3363while(bob < scan && *(--scan) !='\n')3364;/* keep scanning backwards */3365/*3366 * Return either beginning of the buffer, or LF at the end of3367 * the previous line.3368 */3369return scan;3370}33713372intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3373{3374struct strbuf sb = STRBUF_INIT;3375FILE*logfp;3376long pos;3377int ret =0, at_tail =1;33783379 logfp =fopen(git_path("logs/%s", refname),"r");3380if(!logfp)3381return-1;33823383/* Jump to the end */3384if(fseek(logfp,0, SEEK_END) <0)3385returnerror("cannot seek back reflog for%s:%s",3386 refname,strerror(errno));3387 pos =ftell(logfp);3388while(!ret &&0< pos) {3389int cnt;3390size_t nread;3391char buf[BUFSIZ];3392char*endp, *scanp;33933394/* Fill next block from the end */3395 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3396if(fseek(logfp, pos - cnt, SEEK_SET))3397returnerror("cannot seek back reflog for%s:%s",3398 refname,strerror(errno));3399 nread =fread(buf, cnt,1, logfp);3400if(nread !=1)3401returnerror("cannot read%dbytes from reflog for%s:%s",3402 cnt, refname,strerror(errno));3403 pos -= cnt;34043405 scanp = endp = buf + cnt;3406if(at_tail && scanp[-1] =='\n')3407/* Looking at the final LF at the end of the file */3408 scanp--;3409 at_tail =0;34103411while(buf < scanp) {3412/*3413 * terminating LF of the previous line, or the beginning3414 * of the buffer.3415 */3416char*bp;34173418 bp =find_beginning_of_line(buf, scanp);34193420if(*bp =='\n') {3421/*3422 * The newline is the end of the previous line,3423 * so we know we have complete line starting3424 * at (bp + 1). Prefix it onto any prior data3425 * we collected for the line and process it.3426 */3427strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3428 scanp = bp;3429 endp = bp +1;3430 ret =show_one_reflog_ent(&sb, fn, cb_data);3431strbuf_reset(&sb);3432if(ret)3433break;3434}else if(!pos) {3435/*3436 * We are at the start of the buffer, and the3437 * start of the file; there is no previous3438 * line, and we have everything for this one.3439 * Process it, and we can end the loop.3440 */3441strbuf_splice(&sb,0,0, buf, endp - buf);3442 ret =show_one_reflog_ent(&sb, fn, cb_data);3443strbuf_reset(&sb);3444break;3445}34463447if(bp == buf) {3448/*3449 * We are at the start of the buffer, and there3450 * is more file to read backwards. Which means3451 * we are in the middle of a line. Note that we3452 * may get here even if *bp was a newline; that3453 * just means we are at the exact end of the3454 * previous line, rather than some spot in the3455 * middle.3456 *3457 * Save away what we have to be combined with3458 * the data from the next read.3459 */3460strbuf_splice(&sb,0,0, buf, endp - buf);3461break;3462}3463}34643465}3466if(!ret && sb.len)3467die("BUG: reverse reflog parser had leftover data");34683469fclose(logfp);3470strbuf_release(&sb);3471return ret;3472}34733474intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3475{3476FILE*logfp;3477struct strbuf sb = STRBUF_INIT;3478int ret =0;34793480 logfp =fopen(git_path("logs/%s", refname),"r");3481if(!logfp)3482return-1;34833484while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3485 ret =show_one_reflog_ent(&sb, fn, cb_data);3486fclose(logfp);3487strbuf_release(&sb);3488return ret;3489}3490/*3491 * Call fn for each reflog in the namespace indicated by name. name3492 * must be empty or end with '/'. Name will be used as a scratch3493 * space, but its contents will be restored before return.3494 */3495static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3496{3497DIR*d =opendir(git_path("logs/%s", name->buf));3498int retval =0;3499struct dirent *de;3500int oldlen = name->len;35013502if(!d)3503return name->len ? errno :0;35043505while((de =readdir(d)) != NULL) {3506struct stat st;35073508if(de->d_name[0] =='.')3509continue;3510if(ends_with(de->d_name,".lock"))3511continue;3512strbuf_addstr(name, de->d_name);3513if(stat(git_path("logs/%s", name->buf), &st) <0) {3514;/* silently ignore */3515}else{3516if(S_ISDIR(st.st_mode)) {3517strbuf_addch(name,'/');3518 retval =do_for_each_reflog(name, fn, cb_data);3519}else{3520struct object_id oid;35213522if(read_ref_full(name->buf,0, oid.hash, NULL))3523 retval =error("bad ref for%s", name->buf);3524else3525 retval =fn(name->buf, &oid,0, cb_data);3526}3527if(retval)3528break;3529}3530strbuf_setlen(name, oldlen);3531}3532closedir(d);3533return retval;3534}35353536intfor_each_reflog(each_ref_fn fn,void*cb_data)3537{3538int retval;3539struct strbuf name;3540strbuf_init(&name, PATH_MAX);3541 retval =do_for_each_reflog(&name, fn, cb_data);3542strbuf_release(&name);3543return retval;3544}35453546static intref_update_reject_duplicates(struct string_list *refnames,3547struct strbuf *err)3548{3549int i, n = refnames->nr;35503551assert(err);35523553for(i =1; i < n; i++)3554if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3555strbuf_addf(err,3556"multiple updates for ref '%s' not allowed.",3557 refnames->items[i].string);3558return1;3559}3560return0;3561}35623563/*3564 * If update is a direct update of head_ref (the reference pointed to3565 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.3566 */3567static intsplit_head_update(struct ref_update *update,3568struct ref_transaction *transaction,3569const char*head_ref,3570struct string_list *affected_refnames,3571struct strbuf *err)3572{3573struct string_list_item *item;3574struct ref_update *new_update;35753576if((update->flags & REF_LOG_ONLY) ||3577(update->flags & REF_ISPRUNING) ||3578(update->flags & REF_UPDATE_VIA_HEAD))3579return0;35803581if(strcmp(update->refname, head_ref))3582return0;35833584/*3585 * First make sure that HEAD is not already in the3586 * transaction. This insertion is O(N) in the transaction3587 * size, but it happens at most once per transaction.3588 */3589 item =string_list_insert(affected_refnames,"HEAD");3590if(item->util) {3591/* An entry already existed */3592strbuf_addf(err,3593"multiple updates for 'HEAD' (including one "3594"via its referent '%s') are not allowed",3595 update->refname);3596return TRANSACTION_NAME_CONFLICT;3597}35983599 new_update =ref_transaction_add_update(3600 transaction,"HEAD",3601 update->flags | REF_LOG_ONLY | REF_NODEREF,3602 update->new_sha1, update->old_sha1,3603 update->msg);36043605 item->util = new_update;36063607return0;3608}36093610/*3611 * update is for a symref that points at referent and doesn't have3612 * REF_NODEREF set. Split it into two updates:3613 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set3614 * - A new, separate update for the referent reference3615 * Note that the new update will itself be subject to splitting when3616 * the iteration gets to it.3617 */3618static intsplit_symref_update(struct ref_update *update,3619const char*referent,3620struct ref_transaction *transaction,3621struct string_list *affected_refnames,3622struct strbuf *err)3623{3624struct string_list_item *item;3625struct ref_update *new_update;3626unsigned int new_flags;36273628/*3629 * First make sure that referent is not already in the3630 * transaction. This insertion is O(N) in the transaction3631 * size, but it happens at most once per symref in a3632 * transaction.3633 */3634 item =string_list_insert(affected_refnames, referent);3635if(item->util) {3636/* An entry already existed */3637strbuf_addf(err,3638"multiple updates for '%s' (including one "3639"via symref '%s') are not allowed",3640 referent, update->refname);3641return TRANSACTION_NAME_CONFLICT;3642}36433644 new_flags = update->flags;3645if(!strcmp(update->refname,"HEAD")) {3646/*3647 * Record that the new update came via HEAD, so that3648 * when we process it, split_head_update() doesn't try3649 * to add another reflog update for HEAD. Note that3650 * this bit will be propagated if the new_update3651 * itself needs to be split.3652 */3653 new_flags |= REF_UPDATE_VIA_HEAD;3654}36553656 new_update =ref_transaction_add_update(3657 transaction, referent, new_flags,3658 update->new_sha1, update->old_sha1,3659 update->msg);36603661 new_update->parent_update = update;36623663/*3664 * Change the symbolic ref update to log only. Also, it3665 * doesn't need to check its old SHA-1 value, as that will be3666 * done when new_update is processed.3667 */3668 update->flags |= REF_LOG_ONLY | REF_NODEREF;3669 update->flags &= ~REF_HAVE_OLD;36703671 item->util = new_update;36723673return0;3674}36753676/*3677 * Return the refname under which update was originally requested.3678 */3679static const char*original_update_refname(struct ref_update *update)3680{3681while(update->parent_update)3682 update = update->parent_update;36833684return update->refname;3685}36863687/*3688 * Prepare for carrying out update:3689 * - Lock the reference referred to by update.3690 * - Read the reference under lock.3691 * - Check that its old SHA-1 value (if specified) is correct, and in3692 * any case record it in update->lock->old_oid for later use when3693 * writing the reflog.3694 * - If it is a symref update without REF_NODEREF, split it up into a3695 * REF_LOG_ONLY update of the symref and add a separate update for3696 * the referent to transaction.3697 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY3698 * update of HEAD.3699 */3700static intlock_ref_for_update(struct ref_update *update,3701struct ref_transaction *transaction,3702const char*head_ref,3703struct string_list *affected_refnames,3704struct strbuf *err)3705{3706struct strbuf referent = STRBUF_INIT;3707int mustexist = (update->flags & REF_HAVE_OLD) &&3708!is_null_sha1(update->old_sha1);3709int ret;3710struct ref_lock *lock;37113712if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))3713 update->flags |= REF_DELETING;37143715if(head_ref) {3716 ret =split_head_update(update, transaction, head_ref,3717 affected_refnames, err);3718if(ret)3719return ret;3720}37213722 ret =lock_raw_ref(update->refname, mustexist,3723 affected_refnames, NULL,3724&update->lock, &referent,3725&update->type, err);37263727if(ret) {3728char*reason;37293730 reason =strbuf_detach(err, NULL);3731strbuf_addf(err,"cannot lock ref '%s':%s",3732 update->refname, reason);3733free(reason);3734return ret;3735}37363737 lock = update->lock;37383739if(update->type & REF_ISSYMREF) {3740if(update->flags & REF_NODEREF) {3741/*3742 * We won't be reading the referent as part of3743 * the transaction, so we have to read it here3744 * to record and possibly check old_sha1:3745 */3746if(read_ref_full(update->refname,3747 mustexist ? RESOLVE_REF_READING :0,3748 lock->old_oid.hash, NULL)) {3749if(update->flags & REF_HAVE_OLD) {3750strbuf_addf(err,"cannot lock ref '%s': "3751"can't resolve old value",3752 update->refname);3753return TRANSACTION_GENERIC_ERROR;3754}else{3755hashclr(lock->old_oid.hash);3756}3757}3758if((update->flags & REF_HAVE_OLD) &&3759hashcmp(lock->old_oid.hash, update->old_sha1)) {3760strbuf_addf(err,"cannot lock ref '%s': "3761"is at%sbut expected%s",3762 update->refname,3763sha1_to_hex(lock->old_oid.hash),3764sha1_to_hex(update->old_sha1));3765return TRANSACTION_GENERIC_ERROR;3766}37673768}else{3769/*3770 * Create a new update for the reference this3771 * symref is pointing at. Also, we will record3772 * and verify old_sha1 for this update as part3773 * of processing the split-off update, so we3774 * don't have to do it here.3775 */3776 ret =split_symref_update(update, referent.buf, transaction,3777 affected_refnames, err);3778if(ret)3779return ret;3780}3781}else{3782struct ref_update *parent_update;37833784/*3785 * If this update is happening indirectly because of a3786 * symref update, record the old SHA-1 in the parent3787 * update:3788 */3789for(parent_update = update->parent_update;3790 parent_update;3791 parent_update = parent_update->parent_update) {3792oidcpy(&parent_update->lock->old_oid, &lock->old_oid);3793}37943795if((update->flags & REF_HAVE_OLD) &&3796hashcmp(lock->old_oid.hash, update->old_sha1)) {3797if(is_null_sha1(update->old_sha1))3798strbuf_addf(err,"cannot lock ref '%s': reference already exists",3799original_update_refname(update));3800else3801strbuf_addf(err,"cannot lock ref '%s': is at%sbut expected%s",3802original_update_refname(update),3803sha1_to_hex(lock->old_oid.hash),3804sha1_to_hex(update->old_sha1));38053806return TRANSACTION_GENERIC_ERROR;3807}3808}38093810if((update->flags & REF_HAVE_NEW) &&3811!(update->flags & REF_DELETING) &&3812!(update->flags & REF_LOG_ONLY)) {3813if(!(update->type & REF_ISSYMREF) &&3814!hashcmp(lock->old_oid.hash, update->new_sha1)) {3815/*3816 * The reference already has the desired3817 * value, so we don't need to write it.3818 */3819}else if(write_ref_to_lockfile(lock, update->new_sha1,3820 err)) {3821char*write_err =strbuf_detach(err, NULL);38223823/*3824 * The lock was freed upon failure of3825 * write_ref_to_lockfile():3826 */3827 update->lock = NULL;3828strbuf_addf(err,3829"cannot update the ref '%s':%s",3830 update->refname, write_err);3831free(write_err);3832return TRANSACTION_GENERIC_ERROR;3833}else{3834 update->flags |= REF_NEEDS_COMMIT;3835}3836}3837if(!(update->flags & REF_NEEDS_COMMIT)) {3838/*3839 * We didn't call write_ref_to_lockfile(), so3840 * the lockfile is still open. Close it to3841 * free up the file descriptor:3842 */3843if(close_ref(lock)) {3844strbuf_addf(err,"couldn't close '%s.lock'",3845 update->refname);3846return TRANSACTION_GENERIC_ERROR;3847}3848}3849return0;3850}38513852intref_transaction_commit(struct ref_transaction *transaction,3853struct strbuf *err)3854{3855int ret =0, i;3856struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3857struct string_list_item *ref_to_delete;3858struct string_list affected_refnames = STRING_LIST_INIT_NODUP;3859char*head_ref = NULL;3860int head_type;3861struct object_id head_oid;38623863assert(err);38643865if(transaction->state != REF_TRANSACTION_OPEN)3866die("BUG: commit called for transaction that is not open");38673868if(!transaction->nr) {3869 transaction->state = REF_TRANSACTION_CLOSED;3870return0;3871}38723873/*3874 * Fail if a refname appears more than once in the3875 * transaction. (If we end up splitting up any updates using3876 * split_symref_update() or split_head_update(), those3877 * functions will check that the new updates don't have the3878 * same refname as any existing ones.)3879 */3880for(i =0; i < transaction->nr; i++) {3881struct ref_update *update = transaction->updates[i];3882struct string_list_item *item =3883string_list_append(&affected_refnames, update->refname);38843885/*3886 * We store a pointer to update in item->util, but at3887 * the moment we never use the value of this field3888 * except to check whether it is non-NULL.3889 */3890 item->util = update;3891}3892string_list_sort(&affected_refnames);3893if(ref_update_reject_duplicates(&affected_refnames, err)) {3894 ret = TRANSACTION_GENERIC_ERROR;3895goto cleanup;3896}38973898/*3899 * Special hack: If a branch is updated directly and HEAD3900 * points to it (may happen on the remote side of a push3901 * for example) then logically the HEAD reflog should be3902 * updated too.3903 *3904 * A generic solution would require reverse symref lookups,3905 * but finding all symrefs pointing to a given branch would be3906 * rather costly for this rare event (the direct update of a3907 * branch) to be worth it. So let's cheat and check with HEAD3908 * only, which should cover 99% of all usage scenarios (even3909 * 100% of the default ones).3910 *3911 * So if HEAD is a symbolic reference, then record the name of3912 * the reference that it points to. If we see an update of3913 * head_ref within the transaction, then split_head_update()3914 * arranges for the reflog of HEAD to be updated, too.3915 */3916 head_ref =resolve_refdup("HEAD", RESOLVE_REF_NO_RECURSE,3917 head_oid.hash, &head_type);39183919if(head_ref && !(head_type & REF_ISSYMREF)) {3920free(head_ref);3921 head_ref = NULL;3922}39233924/*3925 * Acquire all locks, verify old values if provided, check3926 * that new values are valid, and write new values to the3927 * lockfiles, ready to be activated. Only keep one lockfile3928 * open at a time to avoid running out of file descriptors.3929 */3930for(i =0; i < transaction->nr; i++) {3931struct ref_update *update = transaction->updates[i];39323933 ret =lock_ref_for_update(update, transaction, head_ref,3934&affected_refnames, err);3935if(ret)3936goto cleanup;3937}39383939/* Perform updates first so live commits remain referenced */3940for(i =0; i < transaction->nr; i++) {3941struct ref_update *update = transaction->updates[i];3942struct ref_lock *lock = update->lock;39433944if(update->flags & REF_NEEDS_COMMIT ||3945 update->flags & REF_LOG_ONLY) {3946if(log_ref_write(lock->ref_name, lock->old_oid.hash,3947 update->new_sha1,3948 update->msg, update->flags, err)) {3949char*old_msg =strbuf_detach(err, NULL);39503951strbuf_addf(err,"cannot update the ref '%s':%s",3952 lock->ref_name, old_msg);3953free(old_msg);3954unlock_ref(lock);3955 update->lock = NULL;3956 ret = TRANSACTION_GENERIC_ERROR;3957goto cleanup;3958}3959}3960if(update->flags & REF_NEEDS_COMMIT) {3961clear_loose_ref_cache(&ref_cache);3962if(commit_ref(lock)) {3963strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3964unlock_ref(lock);3965 update->lock = NULL;3966 ret = TRANSACTION_GENERIC_ERROR;3967goto cleanup;3968}3969}3970}3971/* Perform deletes now that updates are safely completed */3972for(i =0; i < transaction->nr; i++) {3973struct ref_update *update = transaction->updates[i];39743975if(update->flags & REF_DELETING &&3976!(update->flags & REF_LOG_ONLY)) {3977if(delete_ref_loose(update->lock, update->type, err)) {3978 ret = TRANSACTION_GENERIC_ERROR;3979goto cleanup;3980}39813982if(!(update->flags & REF_ISPRUNING))3983string_list_append(&refs_to_delete,3984 update->lock->ref_name);3985}3986}39873988if(repack_without_refs(&refs_to_delete, err)) {3989 ret = TRANSACTION_GENERIC_ERROR;3990goto cleanup;3991}3992for_each_string_list_item(ref_to_delete, &refs_to_delete)3993unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3994clear_loose_ref_cache(&ref_cache);39953996cleanup:3997 transaction->state = REF_TRANSACTION_CLOSED;39983999for(i =0; i < transaction->nr; i++)4000if(transaction->updates[i]->lock)4001unlock_ref(transaction->updates[i]->lock);4002string_list_clear(&refs_to_delete,0);4003free(head_ref);4004string_list_clear(&affected_refnames,0);40054006return ret;4007}40084009static intref_present(const char*refname,4010const struct object_id *oid,int flags,void*cb_data)4011{4012struct string_list *affected_refnames = cb_data;40134014returnstring_list_has_string(affected_refnames, refname);4015}40164017intinitial_ref_transaction_commit(struct ref_transaction *transaction,4018struct strbuf *err)4019{4020int ret =0, i;4021struct string_list affected_refnames = STRING_LIST_INIT_NODUP;40224023assert(err);40244025if(transaction->state != REF_TRANSACTION_OPEN)4026die("BUG: commit called for transaction that is not open");40274028/* Fail if a refname appears more than once in the transaction: */4029for(i =0; i < transaction->nr; i++)4030string_list_append(&affected_refnames,4031 transaction->updates[i]->refname);4032string_list_sort(&affected_refnames);4033if(ref_update_reject_duplicates(&affected_refnames, err)) {4034 ret = TRANSACTION_GENERIC_ERROR;4035goto cleanup;4036}40374038/*4039 * It's really undefined to call this function in an active4040 * repository or when there are existing references: we are4041 * only locking and changing packed-refs, so (1) any4042 * simultaneous processes might try to change a reference at4043 * the same time we do, and (2) any existing loose versions of4044 * the references that we are setting would have precedence4045 * over our values. But some remote helpers create the remote4046 * "HEAD" and "master" branches before calling this function,4047 * so here we really only check that none of the references4048 * that we are creating already exists.4049 */4050if(for_each_rawref(ref_present, &affected_refnames))4051die("BUG: initial ref transaction called with existing refs");40524053for(i =0; i < transaction->nr; i++) {4054struct ref_update *update = transaction->updates[i];40554056if((update->flags & REF_HAVE_OLD) &&4057!is_null_sha1(update->old_sha1))4058die("BUG: initial ref transaction with old_sha1 set");4059if(verify_refname_available(update->refname,4060&affected_refnames, NULL,4061 err)) {4062 ret = TRANSACTION_NAME_CONFLICT;4063goto cleanup;4064}4065}40664067if(lock_packed_refs(0)) {4068strbuf_addf(err,"unable to lock packed-refs file:%s",4069strerror(errno));4070 ret = TRANSACTION_GENERIC_ERROR;4071goto cleanup;4072}40734074for(i =0; i < transaction->nr; i++) {4075struct ref_update *update = transaction->updates[i];40764077if((update->flags & REF_HAVE_NEW) &&4078!is_null_sha1(update->new_sha1))4079add_packed_ref(update->refname, update->new_sha1);4080}40814082if(commit_packed_refs()) {4083strbuf_addf(err,"unable to commit packed-refs file:%s",4084strerror(errno));4085 ret = TRANSACTION_GENERIC_ERROR;4086goto cleanup;4087}40884089cleanup:4090 transaction->state = REF_TRANSACTION_CLOSED;4091string_list_clear(&affected_refnames,0);4092return ret;4093}40944095struct expire_reflog_cb {4096unsigned int flags;4097 reflog_expiry_should_prune_fn *should_prune_fn;4098void*policy_cb;4099FILE*newlog;4100unsigned char last_kept_sha1[20];4101};41024103static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4104const char*email,unsigned long timestamp,int tz,4105const char*message,void*cb_data)4106{4107struct expire_reflog_cb *cb = cb_data;4108struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;41094110if(cb->flags & EXPIRE_REFLOGS_REWRITE)4111 osha1 = cb->last_kept_sha1;41124113if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4114 message, policy_cb)) {4115if(!cb->newlog)4116printf("would prune%s", message);4117else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4118printf("prune%s", message);4119}else{4120if(cb->newlog) {4121fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4122sha1_to_hex(osha1),sha1_to_hex(nsha1),4123 email, timestamp, tz, message);4124hashcpy(cb->last_kept_sha1, nsha1);4125}4126if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4127printf("keep%s", message);4128}4129return0;4130}41314132intreflog_expire(const char*refname,const unsigned char*sha1,4133unsigned int flags,4134 reflog_expiry_prepare_fn prepare_fn,4135 reflog_expiry_should_prune_fn should_prune_fn,4136 reflog_expiry_cleanup_fn cleanup_fn,4137void*policy_cb_data)4138{4139static struct lock_file reflog_lock;4140struct expire_reflog_cb cb;4141struct ref_lock *lock;4142char*log_file;4143int status =0;4144int type;4145struct strbuf err = STRBUF_INIT;41464147memset(&cb,0,sizeof(cb));4148 cb.flags = flags;4149 cb.policy_cb = policy_cb_data;4150 cb.should_prune_fn = should_prune_fn;41514152/*4153 * The reflog file is locked by holding the lock on the4154 * reference itself, plus we might need to update the4155 * reference if --updateref was specified:4156 */4157 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL, REF_NODEREF,4158&type, &err);4159if(!lock) {4160error("cannot lock ref '%s':%s", refname, err.buf);4161strbuf_release(&err);4162return-1;4163}4164if(!reflog_exists(refname)) {4165unlock_ref(lock);4166return0;4167}41684169 log_file =git_pathdup("logs/%s", refname);4170if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4171/*4172 * Even though holding $GIT_DIR/logs/$reflog.lock has4173 * no locking implications, we use the lock_file4174 * machinery here anyway because it does a lot of the4175 * work we need, including cleaning up if the program4176 * exits unexpectedly.4177 */4178if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4179struct strbuf err = STRBUF_INIT;4180unable_to_lock_message(log_file, errno, &err);4181error("%s", err.buf);4182strbuf_release(&err);4183goto failure;4184}4185 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4186if(!cb.newlog) {4187error("cannot fdopen%s(%s)",4188get_lock_file_path(&reflog_lock),strerror(errno));4189goto failure;4190}4191}41924193(*prepare_fn)(refname, sha1, cb.policy_cb);4194for_each_reflog_ent(refname, expire_reflog_ent, &cb);4195(*cleanup_fn)(cb.policy_cb);41964197if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4198/*4199 * It doesn't make sense to adjust a reference pointed4200 * to by a symbolic ref based on expiring entries in4201 * the symbolic reference's reflog. Nor can we update4202 * a reference if there are no remaining reflog4203 * entries.4204 */4205int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4206!(type & REF_ISSYMREF) &&4207!is_null_sha1(cb.last_kept_sha1);42084209if(close_lock_file(&reflog_lock)) {4210 status |=error("couldn't write%s:%s", log_file,4211strerror(errno));4212}else if(update &&4213(write_in_full(get_lock_file_fd(lock->lk),4214sha1_to_hex(cb.last_kept_sha1),40) !=40||4215write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||4216close_ref(lock) <0)) {4217 status |=error("couldn't write%s",4218get_lock_file_path(lock->lk));4219rollback_lock_file(&reflog_lock);4220}else if(commit_lock_file(&reflog_lock)) {4221 status |=error("unable to write reflog '%s' (%s)",4222 log_file,strerror(errno));4223}else if(update &&commit_ref(lock)) {4224 status |=error("couldn't set%s", lock->ref_name);4225}4226}4227free(log_file);4228unlock_ref(lock);4229return status;42304231 failure:4232rollback_lock_file(&reflog_lock);4233free(log_file);4234unlock_ref(lock);4235return-1;4236}