1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"../lockfile.h" 5#include"../object.h" 6#include"../dir.h" 7 8struct ref_lock { 9char*ref_name; 10struct lock_file *lk; 11struct object_id old_oid; 12}; 13 14struct ref_entry; 15 16/* 17 * Information used (along with the information in ref_entry) to 18 * describe a single cached reference. This data structure only 19 * occurs embedded in a union in struct ref_entry, and only when 20 * (ref_entry->flag & REF_DIR) is zero. 21 */ 22struct ref_value { 23/* 24 * The name of the object to which this reference resolves 25 * (which may be a tag object). If REF_ISBROKEN, this is 26 * null. If REF_ISSYMREF, then this is the name of the object 27 * referred to by the last reference in the symlink chain. 28 */ 29struct object_id oid; 30 31/* 32 * If REF_KNOWS_PEELED, then this field holds the peeled value 33 * of this reference, or null if the reference is known not to 34 * be peelable. See the documentation for peel_ref() for an 35 * exact definition of "peelable". 36 */ 37struct object_id peeled; 38}; 39 40struct ref_cache; 41 42/* 43 * Information used (along with the information in ref_entry) to 44 * describe a level in the hierarchy of references. This data 45 * structure only occurs embedded in a union in struct ref_entry, and 46 * only when (ref_entry.flag & REF_DIR) is set. In that case, 47 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 48 * in the directory have already been read: 49 * 50 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 51 * or packed references, already read. 52 * 53 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 54 * references that hasn't been read yet (nor has any of its 55 * subdirectories). 56 * 57 * Entries within a directory are stored within a growable array of 58 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 59 * sorted are sorted by their component name in strcmp() order and the 60 * remaining entries are unsorted. 61 * 62 * Loose references are read lazily, one directory at a time. When a 63 * directory of loose references is read, then all of the references 64 * in that directory are stored, and REF_INCOMPLETE stubs are created 65 * for any subdirectories, but the subdirectories themselves are not 66 * read. The reading is triggered by get_ref_dir(). 67 */ 68struct ref_dir { 69int nr, alloc; 70 71/* 72 * Entries with index 0 <= i < sorted are sorted by name. New 73 * entries are appended to the list unsorted, and are sorted 74 * only when required; thus we avoid the need to sort the list 75 * after the addition of every reference. 76 */ 77int sorted; 78 79/* A pointer to the ref_cache that contains this ref_dir. */ 80struct ref_cache *ref_cache; 81 82struct ref_entry **entries; 83}; 84 85/* 86 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 87 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 88 * public values; see refs.h. 89 */ 90 91/* 92 * The field ref_entry->u.value.peeled of this value entry contains 93 * the correct peeled value for the reference, which might be 94 * null_sha1 if the reference is not a tag or if it is broken. 95 */ 96#define REF_KNOWS_PEELED 0x10 97 98/* ref_entry represents a directory of references */ 99#define REF_DIR 0x20 100 101/* 102 * Entry has not yet been read from disk (used only for REF_DIR 103 * entries representing loose references) 104 */ 105#define REF_INCOMPLETE 0x40 106 107/* 108 * A ref_entry represents either a reference or a "subdirectory" of 109 * references. 110 * 111 * Each directory in the reference namespace is represented by a 112 * ref_entry with (flags & REF_DIR) set and containing a subdir member 113 * that holds the entries in that directory that have been read so 114 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 115 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 116 * used for loose reference directories. 117 * 118 * References are represented by a ref_entry with (flags & REF_DIR) 119 * unset and a value member that describes the reference's value. The 120 * flag member is at the ref_entry level, but it is also needed to 121 * interpret the contents of the value field (in other words, a 122 * ref_value object is not very much use without the enclosing 123 * ref_entry). 124 * 125 * Reference names cannot end with slash and directories' names are 126 * always stored with a trailing slash (except for the top-level 127 * directory, which is always denoted by ""). This has two nice 128 * consequences: (1) when the entries in each subdir are sorted 129 * lexicographically by name (as they usually are), the references in 130 * a whole tree can be generated in lexicographic order by traversing 131 * the tree in left-to-right, depth-first order; (2) the names of 132 * references and subdirectories cannot conflict, and therefore the 133 * presence of an empty subdirectory does not block the creation of a 134 * similarly-named reference. (The fact that reference names with the 135 * same leading components can conflict *with each other* is a 136 * separate issue that is regulated by verify_refname_available().) 137 * 138 * Please note that the name field contains the fully-qualified 139 * reference (or subdirectory) name. Space could be saved by only 140 * storing the relative names. But that would require the full names 141 * to be generated on the fly when iterating in do_for_each_ref(), and 142 * would break callback functions, who have always been able to assume 143 * that the name strings that they are passed will not be freed during 144 * the iteration. 145 */ 146struct ref_entry { 147unsigned char flag;/* ISSYMREF? ISPACKED? */ 148union{ 149struct ref_value value;/* if not (flags&REF_DIR) */ 150struct ref_dir subdir;/* if (flags&REF_DIR) */ 151} u; 152/* 153 * The full name of the reference (e.g., "refs/heads/master") 154 * or the full name of the directory with a trailing slash 155 * (e.g., "refs/heads/"): 156 */ 157char name[FLEX_ARRAY]; 158}; 159 160static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 161static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len); 162static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 163const char*dirname,size_t len, 164int incomplete); 165static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry); 166 167static struct ref_dir *get_ref_dir(struct ref_entry *entry) 168{ 169struct ref_dir *dir; 170assert(entry->flag & REF_DIR); 171 dir = &entry->u.subdir; 172if(entry->flag & REF_INCOMPLETE) { 173read_loose_refs(entry->name, dir); 174 175/* 176 * Manually add refs/bisect, which, being 177 * per-worktree, might not appear in the directory 178 * listing for refs/ in the main repo. 179 */ 180if(!strcmp(entry->name,"refs/")) { 181int pos =search_ref_dir(dir,"refs/bisect/",12); 182if(pos <0) { 183struct ref_entry *child_entry; 184 child_entry =create_dir_entry(dir->ref_cache, 185"refs/bisect/", 18612,1); 187add_entry_to_dir(dir, child_entry); 188read_loose_refs("refs/bisect", 189&child_entry->u.subdir); 190} 191} 192 entry->flag &= ~REF_INCOMPLETE; 193} 194return dir; 195} 196 197static struct ref_entry *create_ref_entry(const char*refname, 198const unsigned char*sha1,int flag, 199int check_name) 200{ 201struct ref_entry *ref; 202 203if(check_name && 204check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 205die("Reference has invalid format: '%s'", refname); 206FLEX_ALLOC_STR(ref, name, refname); 207hashcpy(ref->u.value.oid.hash, sha1); 208oidclr(&ref->u.value.peeled); 209 ref->flag = flag; 210return ref; 211} 212 213static voidclear_ref_dir(struct ref_dir *dir); 214 215static voidfree_ref_entry(struct ref_entry *entry) 216{ 217if(entry->flag & REF_DIR) { 218/* 219 * Do not use get_ref_dir() here, as that might 220 * trigger the reading of loose refs. 221 */ 222clear_ref_dir(&entry->u.subdir); 223} 224free(entry); 225} 226 227/* 228 * Add a ref_entry to the end of dir (unsorted). Entry is always 229 * stored directly in dir; no recursion into subdirectories is 230 * done. 231 */ 232static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 233{ 234ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 235 dir->entries[dir->nr++] = entry; 236/* optimize for the case that entries are added in order */ 237if(dir->nr ==1|| 238(dir->nr == dir->sorted +1&& 239strcmp(dir->entries[dir->nr -2]->name, 240 dir->entries[dir->nr -1]->name) <0)) 241 dir->sorted = dir->nr; 242} 243 244/* 245 * Clear and free all entries in dir, recursively. 246 */ 247static voidclear_ref_dir(struct ref_dir *dir) 248{ 249int i; 250for(i =0; i < dir->nr; i++) 251free_ref_entry(dir->entries[i]); 252free(dir->entries); 253 dir->sorted = dir->nr = dir->alloc =0; 254 dir->entries = NULL; 255} 256 257/* 258 * Create a struct ref_entry object for the specified dirname. 259 * dirname is the name of the directory with a trailing slash (e.g., 260 * "refs/heads/") or "" for the top-level directory. 261 */ 262static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 263const char*dirname,size_t len, 264int incomplete) 265{ 266struct ref_entry *direntry; 267FLEX_ALLOC_MEM(direntry, name, dirname, len); 268 direntry->u.subdir.ref_cache = ref_cache; 269 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 270return direntry; 271} 272 273static intref_entry_cmp(const void*a,const void*b) 274{ 275struct ref_entry *one = *(struct ref_entry **)a; 276struct ref_entry *two = *(struct ref_entry **)b; 277returnstrcmp(one->name, two->name); 278} 279 280static voidsort_ref_dir(struct ref_dir *dir); 281 282struct string_slice { 283size_t len; 284const char*str; 285}; 286 287static intref_entry_cmp_sslice(const void*key_,const void*ent_) 288{ 289const struct string_slice *key = key_; 290const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 291int cmp =strncmp(key->str, ent->name, key->len); 292if(cmp) 293return cmp; 294return'\0'- (unsigned char)ent->name[key->len]; 295} 296 297/* 298 * Return the index of the entry with the given refname from the 299 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 300 * no such entry is found. dir must already be complete. 301 */ 302static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 303{ 304struct ref_entry **r; 305struct string_slice key; 306 307if(refname == NULL || !dir->nr) 308return-1; 309 310sort_ref_dir(dir); 311 key.len = len; 312 key.str = refname; 313 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 314 ref_entry_cmp_sslice); 315 316if(r == NULL) 317return-1; 318 319return r - dir->entries; 320} 321 322/* 323 * Search for a directory entry directly within dir (without 324 * recursing). Sort dir if necessary. subdirname must be a directory 325 * name (i.e., end in '/'). If mkdir is set, then create the 326 * directory if it is missing; otherwise, return NULL if the desired 327 * directory cannot be found. dir must already be complete. 328 */ 329static struct ref_dir *search_for_subdir(struct ref_dir *dir, 330const char*subdirname,size_t len, 331int mkdir) 332{ 333int entry_index =search_ref_dir(dir, subdirname, len); 334struct ref_entry *entry; 335if(entry_index == -1) { 336if(!mkdir) 337return NULL; 338/* 339 * Since dir is complete, the absence of a subdir 340 * means that the subdir really doesn't exist; 341 * therefore, create an empty record for it but mark 342 * the record complete. 343 */ 344 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 345add_entry_to_dir(dir, entry); 346}else{ 347 entry = dir->entries[entry_index]; 348} 349returnget_ref_dir(entry); 350} 351 352/* 353 * If refname is a reference name, find the ref_dir within the dir 354 * tree that should hold refname. If refname is a directory name 355 * (i.e., ends in '/'), then return that ref_dir itself. dir must 356 * represent the top-level directory and must already be complete. 357 * Sort ref_dirs and recurse into subdirectories as necessary. If 358 * mkdir is set, then create any missing directories; otherwise, 359 * return NULL if the desired directory cannot be found. 360 */ 361static struct ref_dir *find_containing_dir(struct ref_dir *dir, 362const char*refname,int mkdir) 363{ 364const char*slash; 365for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 366size_t dirnamelen = slash - refname +1; 367struct ref_dir *subdir; 368 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 369if(!subdir) { 370 dir = NULL; 371break; 372} 373 dir = subdir; 374} 375 376return dir; 377} 378 379/* 380 * Find the value entry with the given name in dir, sorting ref_dirs 381 * and recursing into subdirectories as necessary. If the name is not 382 * found or it corresponds to a directory entry, return NULL. 383 */ 384static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 385{ 386int entry_index; 387struct ref_entry *entry; 388 dir =find_containing_dir(dir, refname,0); 389if(!dir) 390return NULL; 391 entry_index =search_ref_dir(dir, refname,strlen(refname)); 392if(entry_index == -1) 393return NULL; 394 entry = dir->entries[entry_index]; 395return(entry->flag & REF_DIR) ? NULL : entry; 396} 397 398/* 399 * Remove the entry with the given name from dir, recursing into 400 * subdirectories as necessary. If refname is the name of a directory 401 * (i.e., ends with '/'), then remove the directory and its contents. 402 * If the removal was successful, return the number of entries 403 * remaining in the directory entry that contained the deleted entry. 404 * If the name was not found, return -1. Please note that this 405 * function only deletes the entry from the cache; it does not delete 406 * it from the filesystem or ensure that other cache entries (which 407 * might be symbolic references to the removed entry) are updated. 408 * Nor does it remove any containing dir entries that might be made 409 * empty by the removal. dir must represent the top-level directory 410 * and must already be complete. 411 */ 412static intremove_entry(struct ref_dir *dir,const char*refname) 413{ 414int refname_len =strlen(refname); 415int entry_index; 416struct ref_entry *entry; 417int is_dir = refname[refname_len -1] =='/'; 418if(is_dir) { 419/* 420 * refname represents a reference directory. Remove 421 * the trailing slash; otherwise we will get the 422 * directory *representing* refname rather than the 423 * one *containing* it. 424 */ 425char*dirname =xmemdupz(refname, refname_len -1); 426 dir =find_containing_dir(dir, dirname,0); 427free(dirname); 428}else{ 429 dir =find_containing_dir(dir, refname,0); 430} 431if(!dir) 432return-1; 433 entry_index =search_ref_dir(dir, refname, refname_len); 434if(entry_index == -1) 435return-1; 436 entry = dir->entries[entry_index]; 437 438memmove(&dir->entries[entry_index], 439&dir->entries[entry_index +1], 440(dir->nr - entry_index -1) *sizeof(*dir->entries) 441); 442 dir->nr--; 443if(dir->sorted > entry_index) 444 dir->sorted--; 445free_ref_entry(entry); 446return dir->nr; 447} 448 449/* 450 * Add a ref_entry to the ref_dir (unsorted), recursing into 451 * subdirectories as necessary. dir must represent the top-level 452 * directory. Return 0 on success. 453 */ 454static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 455{ 456 dir =find_containing_dir(dir, ref->name,1); 457if(!dir) 458return-1; 459add_entry_to_dir(dir, ref); 460return0; 461} 462 463/* 464 * Emit a warning and return true iff ref1 and ref2 have the same name 465 * and the same sha1. Die if they have the same name but different 466 * sha1s. 467 */ 468static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 469{ 470if(strcmp(ref1->name, ref2->name)) 471return0; 472 473/* Duplicate name; make sure that they don't conflict: */ 474 475if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 476/* This is impossible by construction */ 477die("Reference directory conflict:%s", ref1->name); 478 479if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 480die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 481 482warning("Duplicated ref:%s", ref1->name); 483return1; 484} 485 486/* 487 * Sort the entries in dir non-recursively (if they are not already 488 * sorted) and remove any duplicate entries. 489 */ 490static voidsort_ref_dir(struct ref_dir *dir) 491{ 492int i, j; 493struct ref_entry *last = NULL; 494 495/* 496 * This check also prevents passing a zero-length array to qsort(), 497 * which is a problem on some platforms. 498 */ 499if(dir->sorted == dir->nr) 500return; 501 502qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 503 504/* Remove any duplicates: */ 505for(i =0, j =0; j < dir->nr; j++) { 506struct ref_entry *entry = dir->entries[j]; 507if(last &&is_dup_ref(last, entry)) 508free_ref_entry(entry); 509else 510 last = dir->entries[i++] = entry; 511} 512 dir->sorted = dir->nr = i; 513} 514 515/* 516 * Return true iff the reference described by entry can be resolved to 517 * an object in the database. Emit a warning if the referred-to 518 * object does not exist. 519 */ 520static intref_resolves_to_object(struct ref_entry *entry) 521{ 522if(entry->flag & REF_ISBROKEN) 523return0; 524if(!has_sha1_file(entry->u.value.oid.hash)) { 525error("%sdoes not point to a valid object!", entry->name); 526return0; 527} 528return1; 529} 530 531/* 532 * current_ref is a performance hack: when iterating over references 533 * using the for_each_ref*() functions, current_ref is set to the 534 * current reference's entry before calling the callback function. If 535 * the callback function calls peel_ref(), then peel_ref() first 536 * checks whether the reference to be peeled is the current reference 537 * (it usually is) and if so, returns that reference's peeled version 538 * if it is available. This avoids a refname lookup in a common case. 539 */ 540static struct ref_entry *current_ref; 541 542typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 543 544struct ref_entry_cb { 545const char*prefix; 546int trim; 547int flags; 548 each_ref_fn *fn; 549void*cb_data; 550}; 551 552/* 553 * Handle one reference in a do_for_each_ref*()-style iteration, 554 * calling an each_ref_fn for each entry. 555 */ 556static intdo_one_ref(struct ref_entry *entry,void*cb_data) 557{ 558struct ref_entry_cb *data = cb_data; 559struct ref_entry *old_current_ref; 560int retval; 561 562if(!starts_with(entry->name, data->prefix)) 563return0; 564 565if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 566!ref_resolves_to_object(entry)) 567return0; 568 569/* Store the old value, in case this is a recursive call: */ 570 old_current_ref = current_ref; 571 current_ref = entry; 572 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 573 entry->flag, data->cb_data); 574 current_ref = old_current_ref; 575return retval; 576} 577 578/* 579 * Call fn for each reference in dir that has index in the range 580 * offset <= index < dir->nr. Recurse into subdirectories that are in 581 * that index range, sorting them before iterating. This function 582 * does not sort dir itself; it should be sorted beforehand. fn is 583 * called for all references, including broken ones. 584 */ 585static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 586 each_ref_entry_fn fn,void*cb_data) 587{ 588int i; 589assert(dir->sorted == dir->nr); 590for(i = offset; i < dir->nr; i++) { 591struct ref_entry *entry = dir->entries[i]; 592int retval; 593if(entry->flag & REF_DIR) { 594struct ref_dir *subdir =get_ref_dir(entry); 595sort_ref_dir(subdir); 596 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 597}else{ 598 retval =fn(entry, cb_data); 599} 600if(retval) 601return retval; 602} 603return0; 604} 605 606/* 607 * Call fn for each reference in the union of dir1 and dir2, in order 608 * by refname. Recurse into subdirectories. If a value entry appears 609 * in both dir1 and dir2, then only process the version that is in 610 * dir2. The input dirs must already be sorted, but subdirs will be 611 * sorted as needed. fn is called for all references, including 612 * broken ones. 613 */ 614static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 615struct ref_dir *dir2, 616 each_ref_entry_fn fn,void*cb_data) 617{ 618int retval; 619int i1 =0, i2 =0; 620 621assert(dir1->sorted == dir1->nr); 622assert(dir2->sorted == dir2->nr); 623while(1) { 624struct ref_entry *e1, *e2; 625int cmp; 626if(i1 == dir1->nr) { 627returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 628} 629if(i2 == dir2->nr) { 630returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 631} 632 e1 = dir1->entries[i1]; 633 e2 = dir2->entries[i2]; 634 cmp =strcmp(e1->name, e2->name); 635if(cmp ==0) { 636if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 637/* Both are directories; descend them in parallel. */ 638struct ref_dir *subdir1 =get_ref_dir(e1); 639struct ref_dir *subdir2 =get_ref_dir(e2); 640sort_ref_dir(subdir1); 641sort_ref_dir(subdir2); 642 retval =do_for_each_entry_in_dirs( 643 subdir1, subdir2, fn, cb_data); 644 i1++; 645 i2++; 646}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 647/* Both are references; ignore the one from dir1. */ 648 retval =fn(e2, cb_data); 649 i1++; 650 i2++; 651}else{ 652die("conflict between reference and directory:%s", 653 e1->name); 654} 655}else{ 656struct ref_entry *e; 657if(cmp <0) { 658 e = e1; 659 i1++; 660}else{ 661 e = e2; 662 i2++; 663} 664if(e->flag & REF_DIR) { 665struct ref_dir *subdir =get_ref_dir(e); 666sort_ref_dir(subdir); 667 retval =do_for_each_entry_in_dir( 668 subdir,0, fn, cb_data); 669}else{ 670 retval =fn(e, cb_data); 671} 672} 673if(retval) 674return retval; 675} 676} 677 678/* 679 * Load all of the refs from the dir into our in-memory cache. The hard work 680 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 681 * through all of the sub-directories. We do not even need to care about 682 * sorting, as traversal order does not matter to us. 683 */ 684static voidprime_ref_dir(struct ref_dir *dir) 685{ 686int i; 687for(i =0; i < dir->nr; i++) { 688struct ref_entry *entry = dir->entries[i]; 689if(entry->flag & REF_DIR) 690prime_ref_dir(get_ref_dir(entry)); 691} 692} 693 694struct nonmatching_ref_data { 695const struct string_list *skip; 696const char*conflicting_refname; 697}; 698 699static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 700{ 701struct nonmatching_ref_data *data = vdata; 702 703if(data->skip &&string_list_has_string(data->skip, entry->name)) 704return0; 705 706 data->conflicting_refname = entry->name; 707return1; 708} 709 710/* 711 * Return 0 if a reference named refname could be created without 712 * conflicting with the name of an existing reference in dir. 713 * See verify_refname_available for more information. 714 */ 715static intverify_refname_available_dir(const char*refname, 716const struct string_list *extras, 717const struct string_list *skip, 718struct ref_dir *dir, 719struct strbuf *err) 720{ 721const char*slash; 722const char*extra_refname; 723int pos; 724struct strbuf dirname = STRBUF_INIT; 725int ret = -1; 726 727/* 728 * For the sake of comments in this function, suppose that 729 * refname is "refs/foo/bar". 730 */ 731 732assert(err); 733 734strbuf_grow(&dirname,strlen(refname) +1); 735for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 736/* Expand dirname to the new prefix, not including the trailing slash: */ 737strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 738 739/* 740 * We are still at a leading dir of the refname (e.g., 741 * "refs/foo"; if there is a reference with that name, 742 * it is a conflict, *unless* it is in skip. 743 */ 744if(dir) { 745 pos =search_ref_dir(dir, dirname.buf, dirname.len); 746if(pos >=0&& 747(!skip || !string_list_has_string(skip, dirname.buf))) { 748/* 749 * We found a reference whose name is 750 * a proper prefix of refname; e.g., 751 * "refs/foo", and is not in skip. 752 */ 753strbuf_addf(err,"'%s' exists; cannot create '%s'", 754 dirname.buf, refname); 755goto cleanup; 756} 757} 758 759if(extras &&string_list_has_string(extras, dirname.buf) && 760(!skip || !string_list_has_string(skip, dirname.buf))) { 761strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 762 refname, dirname.buf); 763goto cleanup; 764} 765 766/* 767 * Otherwise, we can try to continue our search with 768 * the next component. So try to look up the 769 * directory, e.g., "refs/foo/". If we come up empty, 770 * we know there is nothing under this whole prefix, 771 * but even in that case we still have to continue the 772 * search for conflicts with extras. 773 */ 774strbuf_addch(&dirname,'/'); 775if(dir) { 776 pos =search_ref_dir(dir, dirname.buf, dirname.len); 777if(pos <0) { 778/* 779 * There was no directory "refs/foo/", 780 * so there is nothing under this 781 * whole prefix. So there is no need 782 * to continue looking for conflicting 783 * references. But we need to continue 784 * looking for conflicting extras. 785 */ 786 dir = NULL; 787}else{ 788 dir =get_ref_dir(dir->entries[pos]); 789} 790} 791} 792 793/* 794 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 795 * There is no point in searching for a reference with that 796 * name, because a refname isn't considered to conflict with 797 * itself. But we still need to check for references whose 798 * names are in the "refs/foo/bar/" namespace, because they 799 * *do* conflict. 800 */ 801strbuf_addstr(&dirname, refname + dirname.len); 802strbuf_addch(&dirname,'/'); 803 804if(dir) { 805 pos =search_ref_dir(dir, dirname.buf, dirname.len); 806 807if(pos >=0) { 808/* 809 * We found a directory named "$refname/" 810 * (e.g., "refs/foo/bar/"). It is a problem 811 * iff it contains any ref that is not in 812 * "skip". 813 */ 814struct nonmatching_ref_data data; 815 816 data.skip = skip; 817 data.conflicting_refname = NULL; 818 dir =get_ref_dir(dir->entries[pos]); 819sort_ref_dir(dir); 820if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 821strbuf_addf(err,"'%s' exists; cannot create '%s'", 822 data.conflicting_refname, refname); 823goto cleanup; 824} 825} 826} 827 828 extra_refname =find_descendant_ref(dirname.buf, extras, skip); 829if(extra_refname) 830strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 831 refname, extra_refname); 832else 833 ret =0; 834 835cleanup: 836strbuf_release(&dirname); 837return ret; 838} 839 840struct packed_ref_cache { 841struct ref_entry *root; 842 843/* 844 * Count of references to the data structure in this instance, 845 * including the pointer from ref_cache::packed if any. The 846 * data will not be freed as long as the reference count is 847 * nonzero. 848 */ 849unsigned int referrers; 850 851/* 852 * Iff the packed-refs file associated with this instance is 853 * currently locked for writing, this points at the associated 854 * lock (which is owned by somebody else). The referrer count 855 * is also incremented when the file is locked and decremented 856 * when it is unlocked. 857 */ 858struct lock_file *lock; 859 860/* The metadata from when this packed-refs cache was read */ 861struct stat_validity validity; 862}; 863 864/* 865 * Future: need to be in "struct repository" 866 * when doing a full libification. 867 */ 868static struct ref_cache { 869struct ref_cache *next; 870struct ref_entry *loose; 871struct packed_ref_cache *packed; 872/* 873 * The submodule name, or "" for the main repo. We allocate 874 * length 1 rather than FLEX_ARRAY so that the main ref_cache 875 * is initialized correctly. 876 */ 877char name[1]; 878} ref_cache, *submodule_ref_caches; 879 880/* Lock used for the main packed-refs file: */ 881static struct lock_file packlock; 882 883/* 884 * Increment the reference count of *packed_refs. 885 */ 886static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 887{ 888 packed_refs->referrers++; 889} 890 891/* 892 * Decrease the reference count of *packed_refs. If it goes to zero, 893 * free *packed_refs and return true; otherwise return false. 894 */ 895static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 896{ 897if(!--packed_refs->referrers) { 898free_ref_entry(packed_refs->root); 899stat_validity_clear(&packed_refs->validity); 900free(packed_refs); 901return1; 902}else{ 903return0; 904} 905} 906 907static voidclear_packed_ref_cache(struct ref_cache *refs) 908{ 909if(refs->packed) { 910struct packed_ref_cache *packed_refs = refs->packed; 911 912if(packed_refs->lock) 913die("internal error: packed-ref cache cleared while locked"); 914 refs->packed = NULL; 915release_packed_ref_cache(packed_refs); 916} 917} 918 919static voidclear_loose_ref_cache(struct ref_cache *refs) 920{ 921if(refs->loose) { 922free_ref_entry(refs->loose); 923 refs->loose = NULL; 924} 925} 926 927/* 928 * Create a new submodule ref cache and add it to the internal 929 * set of caches. 930 */ 931static struct ref_cache *create_ref_cache(const char*submodule) 932{ 933struct ref_cache *refs; 934if(!submodule) 935 submodule =""; 936FLEX_ALLOC_STR(refs, name, submodule); 937 refs->next = submodule_ref_caches; 938 submodule_ref_caches = refs; 939return refs; 940} 941 942static struct ref_cache *lookup_ref_cache(const char*submodule) 943{ 944struct ref_cache *refs; 945 946if(!submodule || !*submodule) 947return&ref_cache; 948 949for(refs = submodule_ref_caches; refs; refs = refs->next) 950if(!strcmp(submodule, refs->name)) 951return refs; 952return NULL; 953} 954 955/* 956 * Return a pointer to a ref_cache for the specified submodule. For 957 * the main repository, use submodule==NULL; such a call cannot fail. 958 * For a submodule, the submodule must exist and be a nonbare 959 * repository, otherwise return NULL. 960 * 961 * The returned structure will be allocated and initialized but not 962 * necessarily populated; it should not be freed. 963 */ 964static struct ref_cache *get_ref_cache(const char*submodule) 965{ 966struct ref_cache *refs =lookup_ref_cache(submodule); 967 968if(!refs) { 969struct strbuf submodule_sb = STRBUF_INIT; 970 971strbuf_addstr(&submodule_sb, submodule); 972if(is_nonbare_repository_dir(&submodule_sb)) 973 refs =create_ref_cache(submodule); 974strbuf_release(&submodule_sb); 975} 976 977return refs; 978} 979 980/* The length of a peeled reference line in packed-refs, including EOL: */ 981#define PEELED_LINE_LENGTH 42 982 983/* 984 * The packed-refs header line that we write out. Perhaps other 985 * traits will be added later. The trailing space is required. 986 */ 987static const char PACKED_REFS_HEADER[] = 988"# pack-refs with: peeled fully-peeled\n"; 989 990/* 991 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 992 * Return a pointer to the refname within the line (null-terminated), 993 * or NULL if there was a problem. 994 */ 995static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 996{ 997const char*ref; 998 999/*1000 * 42: the answer to everything.1001 *1002 * In this case, it happens to be the answer to1003 * 40 (length of sha1 hex representation)1004 * +1 (space in between hex and name)1005 * +1 (newline at the end of the line)1006 */1007if(line->len <=42)1008return NULL;10091010if(get_sha1_hex(line->buf, sha1) <0)1011return NULL;1012if(!isspace(line->buf[40]))1013return NULL;10141015 ref = line->buf +41;1016if(isspace(*ref))1017return NULL;10181019if(line->buf[line->len -1] !='\n')1020return NULL;1021 line->buf[--line->len] =0;10221023return ref;1024}10251026/*1027 * Read f, which is a packed-refs file, into dir.1028 *1029 * A comment line of the form "# pack-refs with: " may contain zero or1030 * more traits. We interpret the traits as follows:1031 *1032 * No traits:1033 *1034 * Probably no references are peeled. But if the file contains a1035 * peeled value for a reference, we will use it.1036 *1037 * peeled:1038 *1039 * References under "refs/tags/", if they *can* be peeled, *are*1040 * peeled in this file. References outside of "refs/tags/" are1041 * probably not peeled even if they could have been, but if we find1042 * a peeled value for such a reference we will use it.1043 *1044 * fully-peeled:1045 *1046 * All references in the file that can be peeled are peeled.1047 * Inversely (and this is more important), any references in the1048 * file for which no peeled value is recorded is not peelable. This1049 * trait should typically be written alongside "peeled" for1050 * compatibility with older clients, but we do not require it1051 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1052 */1053static voidread_packed_refs(FILE*f,struct ref_dir *dir)1054{1055struct ref_entry *last = NULL;1056struct strbuf line = STRBUF_INIT;1057enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10581059while(strbuf_getwholeline(&line, f,'\n') != EOF) {1060unsigned char sha1[20];1061const char*refname;1062const char*traits;10631064if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1065if(strstr(traits," fully-peeled "))1066 peeled = PEELED_FULLY;1067else if(strstr(traits," peeled "))1068 peeled = PEELED_TAGS;1069/* perhaps other traits later as well */1070continue;1071}10721073 refname =parse_ref_line(&line, sha1);1074if(refname) {1075int flag = REF_ISPACKED;10761077if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1078if(!refname_is_safe(refname))1079die("packed refname is dangerous:%s", refname);1080hashclr(sha1);1081 flag |= REF_BAD_NAME | REF_ISBROKEN;1082}1083 last =create_ref_entry(refname, sha1, flag,0);1084if(peeled == PEELED_FULLY ||1085(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1086 last->flag |= REF_KNOWS_PEELED;1087add_ref(dir, last);1088continue;1089}1090if(last &&1091 line.buf[0] =='^'&&1092 line.len == PEELED_LINE_LENGTH &&1093 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1094!get_sha1_hex(line.buf +1, sha1)) {1095hashcpy(last->u.value.peeled.hash, sha1);1096/*1097 * Regardless of what the file header said,1098 * we definitely know the value of *this*1099 * reference:1100 */1101 last->flag |= REF_KNOWS_PEELED;1102}1103}11041105strbuf_release(&line);1106}11071108/*1109 * Get the packed_ref_cache for the specified ref_cache, creating it1110 * if necessary.1111 */1112static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1113{1114char*packed_refs_file;11151116if(*refs->name)1117 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1118else1119 packed_refs_file =git_pathdup("packed-refs");11201121if(refs->packed &&1122!stat_validity_check(&refs->packed->validity, packed_refs_file))1123clear_packed_ref_cache(refs);11241125if(!refs->packed) {1126FILE*f;11271128 refs->packed =xcalloc(1,sizeof(*refs->packed));1129acquire_packed_ref_cache(refs->packed);1130 refs->packed->root =create_dir_entry(refs,"",0,0);1131 f =fopen(packed_refs_file,"r");1132if(f) {1133stat_validity_update(&refs->packed->validity,fileno(f));1134read_packed_refs(f,get_ref_dir(refs->packed->root));1135fclose(f);1136}1137}1138free(packed_refs_file);1139return refs->packed;1140}11411142static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1143{1144returnget_ref_dir(packed_ref_cache->root);1145}11461147static struct ref_dir *get_packed_refs(struct ref_cache *refs)1148{1149returnget_packed_ref_dir(get_packed_ref_cache(refs));1150}11511152/*1153 * Add a reference to the in-memory packed reference cache. This may1154 * only be called while the packed-refs file is locked (see1155 * lock_packed_refs()). To actually write the packed-refs file, call1156 * commit_packed_refs().1157 */1158static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1159{1160struct packed_ref_cache *packed_ref_cache =1161get_packed_ref_cache(&ref_cache);11621163if(!packed_ref_cache->lock)1164die("internal error: packed refs not locked");1165add_ref(get_packed_ref_dir(packed_ref_cache),1166create_ref_entry(refname, sha1, REF_ISPACKED,1));1167}11681169/*1170 * Read the loose references from the namespace dirname into dir1171 * (without recursing). dirname must end with '/'. dir must be the1172 * directory entry corresponding to dirname.1173 */1174static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1175{1176struct ref_cache *refs = dir->ref_cache;1177DIR*d;1178struct dirent *de;1179int dirnamelen =strlen(dirname);1180struct strbuf refname;1181struct strbuf path = STRBUF_INIT;1182size_t path_baselen;11831184if(*refs->name)1185strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1186else1187strbuf_git_path(&path,"%s", dirname);1188 path_baselen = path.len;11891190 d =opendir(path.buf);1191if(!d) {1192strbuf_release(&path);1193return;1194}11951196strbuf_init(&refname, dirnamelen +257);1197strbuf_add(&refname, dirname, dirnamelen);11981199while((de =readdir(d)) != NULL) {1200unsigned char sha1[20];1201struct stat st;1202int flag;12031204if(de->d_name[0] =='.')1205continue;1206if(ends_with(de->d_name,".lock"))1207continue;1208strbuf_addstr(&refname, de->d_name);1209strbuf_addstr(&path, de->d_name);1210if(stat(path.buf, &st) <0) {1211;/* silently ignore */1212}else if(S_ISDIR(st.st_mode)) {1213strbuf_addch(&refname,'/');1214add_entry_to_dir(dir,1215create_dir_entry(refs, refname.buf,1216 refname.len,1));1217}else{1218int read_ok;12191220if(*refs->name) {1221hashclr(sha1);1222 flag =0;1223 read_ok = !resolve_gitlink_ref(refs->name,1224 refname.buf, sha1);1225}else{1226 read_ok = !read_ref_full(refname.buf,1227 RESOLVE_REF_READING,1228 sha1, &flag);1229}12301231if(!read_ok) {1232hashclr(sha1);1233 flag |= REF_ISBROKEN;1234}else if(is_null_sha1(sha1)) {1235/*1236 * It is so astronomically unlikely1237 * that NULL_SHA1 is the SHA-1 of an1238 * actual object that we consider its1239 * appearance in a loose reference1240 * file to be repo corruption1241 * (probably due to a software bug).1242 */1243 flag |= REF_ISBROKEN;1244}12451246if(check_refname_format(refname.buf,1247 REFNAME_ALLOW_ONELEVEL)) {1248if(!refname_is_safe(refname.buf))1249die("loose refname is dangerous:%s", refname.buf);1250hashclr(sha1);1251 flag |= REF_BAD_NAME | REF_ISBROKEN;1252}1253add_entry_to_dir(dir,1254create_ref_entry(refname.buf, sha1, flag,0));1255}1256strbuf_setlen(&refname, dirnamelen);1257strbuf_setlen(&path, path_baselen);1258}1259strbuf_release(&refname);1260strbuf_release(&path);1261closedir(d);1262}12631264static struct ref_dir *get_loose_refs(struct ref_cache *refs)1265{1266if(!refs->loose) {1267/*1268 * Mark the top-level directory complete because we1269 * are about to read the only subdirectory that can1270 * hold references:1271 */1272 refs->loose =create_dir_entry(refs,"",0,0);1273/*1274 * Create an incomplete entry for "refs/":1275 */1276add_entry_to_dir(get_ref_dir(refs->loose),1277create_dir_entry(refs,"refs/",5,1));1278}1279returnget_ref_dir(refs->loose);1280}12811282#define MAXREFLEN (1024)12831284/*1285 * Called by resolve_gitlink_ref_recursive() after it failed to read1286 * from the loose refs in ref_cache refs. Find <refname> in the1287 * packed-refs file for the submodule.1288 */1289static intresolve_gitlink_packed_ref(struct ref_cache *refs,1290const char*refname,unsigned char*sha1)1291{1292struct ref_entry *ref;1293struct ref_dir *dir =get_packed_refs(refs);12941295 ref =find_ref(dir, refname);1296if(ref == NULL)1297return-1;12981299hashcpy(sha1, ref->u.value.oid.hash);1300return0;1301}13021303static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1304const char*refname,unsigned char*sha1,1305int recursion)1306{1307int fd, len;1308char buffer[128], *p;1309char*path;13101311if(recursion > SYMREF_MAXDEPTH ||strlen(refname) > MAXREFLEN)1312return-1;1313 path = *refs->name1314?git_pathdup_submodule(refs->name,"%s", refname)1315:git_pathdup("%s", refname);1316 fd =open(path, O_RDONLY);1317free(path);1318if(fd <0)1319returnresolve_gitlink_packed_ref(refs, refname, sha1);13201321 len =read(fd, buffer,sizeof(buffer)-1);1322close(fd);1323if(len <0)1324return-1;1325while(len &&isspace(buffer[len-1]))1326 len--;1327 buffer[len] =0;13281329/* Was it a detached head or an old-fashioned symlink? */1330if(!get_sha1_hex(buffer, sha1))1331return0;13321333/* Symref? */1334if(strncmp(buffer,"ref:",4))1335return-1;1336 p = buffer +4;1337while(isspace(*p))1338 p++;13391340returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1341}13421343intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1344{1345int len =strlen(path), retval;1346struct strbuf submodule = STRBUF_INIT;1347struct ref_cache *refs;13481349while(len && path[len-1] =='/')1350 len--;1351if(!len)1352return-1;13531354strbuf_add(&submodule, path, len);1355 refs =get_ref_cache(submodule.buf);1356if(!refs) {1357strbuf_release(&submodule);1358return-1;1359}1360strbuf_release(&submodule);13611362 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1363return retval;1364}13651366/*1367 * Return the ref_entry for the given refname from the packed1368 * references. If it does not exist, return NULL.1369 */1370static struct ref_entry *get_packed_ref(const char*refname)1371{1372returnfind_ref(get_packed_refs(&ref_cache), refname);1373}13741375/*1376 * A loose ref file doesn't exist; check for a packed ref.1377 */1378static intresolve_missing_loose_ref(const char*refname,1379unsigned char*sha1,1380unsigned int*flags)1381{1382struct ref_entry *entry;13831384/*1385 * The loose reference file does not exist; check for a packed1386 * reference.1387 */1388 entry =get_packed_ref(refname);1389if(entry) {1390hashcpy(sha1, entry->u.value.oid.hash);1391*flags |= REF_ISPACKED;1392return0;1393}1394/* refname is not a packed reference. */1395return-1;1396}13971398intread_raw_ref(const char*refname,unsigned char*sha1,1399struct strbuf *referent,unsigned int*type)1400{1401struct strbuf sb_contents = STRBUF_INIT;1402struct strbuf sb_path = STRBUF_INIT;1403const char*path;1404const char*buf;1405struct stat st;1406int fd;1407int ret = -1;1408int save_errno;14091410*type =0;1411strbuf_reset(&sb_path);1412strbuf_git_path(&sb_path,"%s", refname);1413 path = sb_path.buf;14141415stat_ref:1416/*1417 * We might have to loop back here to avoid a race1418 * condition: first we lstat() the file, then we try1419 * to read it as a link or as a file. But if somebody1420 * changes the type of the file (file <-> directory1421 * <-> symlink) between the lstat() and reading, then1422 * we don't want to report that as an error but rather1423 * try again starting with the lstat().1424 */14251426if(lstat(path, &st) <0) {1427if(errno != ENOENT)1428goto out;1429if(resolve_missing_loose_ref(refname, sha1, type)) {1430 errno = ENOENT;1431goto out;1432}1433 ret =0;1434goto out;1435}14361437/* Follow "normalized" - ie "refs/.." symlinks by hand */1438if(S_ISLNK(st.st_mode)) {1439strbuf_reset(&sb_contents);1440if(strbuf_readlink(&sb_contents, path,0) <0) {1441if(errno == ENOENT || errno == EINVAL)1442/* inconsistent with lstat; retry */1443goto stat_ref;1444else1445goto out;1446}1447if(starts_with(sb_contents.buf,"refs/") &&1448!check_refname_format(sb_contents.buf,0)) {1449strbuf_swap(&sb_contents, referent);1450*type |= REF_ISSYMREF;1451 ret =0;1452goto out;1453}1454}14551456/* Is it a directory? */1457if(S_ISDIR(st.st_mode)) {1458/*1459 * Even though there is a directory where the loose1460 * ref is supposed to be, there could still be a1461 * packed ref:1462 */1463if(resolve_missing_loose_ref(refname, sha1, type)) {1464 errno = EISDIR;1465goto out;1466}1467 ret =0;1468goto out;1469}14701471/*1472 * Anything else, just open it and try to use it as1473 * a ref1474 */1475 fd =open(path, O_RDONLY);1476if(fd <0) {1477if(errno == ENOENT)1478/* inconsistent with lstat; retry */1479goto stat_ref;1480else1481goto out;1482}1483strbuf_reset(&sb_contents);1484if(strbuf_read(&sb_contents, fd,256) <0) {1485int save_errno = errno;1486close(fd);1487 errno = save_errno;1488goto out;1489}1490close(fd);1491strbuf_rtrim(&sb_contents);1492 buf = sb_contents.buf;1493if(starts_with(buf,"ref:")) {1494 buf +=4;1495while(isspace(*buf))1496 buf++;14971498strbuf_reset(referent);1499strbuf_addstr(referent, buf);1500*type |= REF_ISSYMREF;1501 ret =0;1502goto out;1503}15041505/*1506 * Please note that FETCH_HEAD has additional1507 * data after the sha.1508 */1509if(get_sha1_hex(buf, sha1) ||1510(buf[40] !='\0'&& !isspace(buf[40]))) {1511*type |= REF_ISBROKEN;1512 errno = EINVAL;1513goto out;1514}15151516 ret =0;15171518out:1519 save_errno = errno;1520strbuf_release(&sb_path);1521strbuf_release(&sb_contents);1522 errno = save_errno;1523return ret;1524}15251526static voidunlock_ref(struct ref_lock *lock)1527{1528/* Do not free lock->lk -- atexit() still looks at them */1529if(lock->lk)1530rollback_lock_file(lock->lk);1531free(lock->ref_name);1532free(lock);1533}15341535/*1536 * Lock refname, without following symrefs, and set *lock_p to point1537 * at a newly-allocated lock object. Fill in lock->old_oid, referent,1538 * and type similarly to read_raw_ref().1539 *1540 * The caller must verify that refname is a "safe" reference name (in1541 * the sense of refname_is_safe()) before calling this function.1542 *1543 * If the reference doesn't already exist, verify that refname doesn't1544 * have a D/F conflict with any existing references. extras and skip1545 * are passed to verify_refname_available_dir() for this check.1546 *1547 * If mustexist is not set and the reference is not found or is1548 * broken, lock the reference anyway but clear sha1.1549 *1550 * Return 0 on success. On failure, write an error message to err and1551 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.1552 *1553 * Implementation note: This function is basically1554 *1555 * lock reference1556 * read_raw_ref()1557 *1558 * but it includes a lot more code to1559 * - Deal with possible races with other processes1560 * - Avoid calling verify_refname_available_dir() when it can be1561 * avoided, namely if we were successfully able to read the ref1562 * - Generate informative error messages in the case of failure1563 */1564static intlock_raw_ref(const char*refname,int mustexist,1565const struct string_list *extras,1566const struct string_list *skip,1567struct ref_lock **lock_p,1568struct strbuf *referent,1569unsigned int*type,1570struct strbuf *err)1571{1572struct ref_lock *lock;1573struct strbuf ref_file = STRBUF_INIT;1574int attempts_remaining =3;1575int ret = TRANSACTION_GENERIC_ERROR;15761577assert(err);1578*type =0;15791580/* First lock the file so it can't change out from under us. */15811582*lock_p = lock =xcalloc(1,sizeof(*lock));15831584 lock->ref_name =xstrdup(refname);1585strbuf_git_path(&ref_file,"%s", refname);15861587retry:1588switch(safe_create_leading_directories(ref_file.buf)) {1589case SCLD_OK:1590break;/* success */1591case SCLD_EXISTS:1592/*1593 * Suppose refname is "refs/foo/bar". We just failed1594 * to create the containing directory, "refs/foo",1595 * because there was a non-directory in the way. This1596 * indicates a D/F conflict, probably because of1597 * another reference such as "refs/foo". There is no1598 * reason to expect this error to be transitory.1599 */1600if(verify_refname_available(refname, extras, skip, err)) {1601if(mustexist) {1602/*1603 * To the user the relevant error is1604 * that the "mustexist" reference is1605 * missing:1606 */1607strbuf_reset(err);1608strbuf_addf(err,"unable to resolve reference '%s'",1609 refname);1610}else{1611/*1612 * The error message set by1613 * verify_refname_available_dir() is OK.1614 */1615 ret = TRANSACTION_NAME_CONFLICT;1616}1617}else{1618/*1619 * The file that is in the way isn't a loose1620 * reference. Report it as a low-level1621 * failure.1622 */1623strbuf_addf(err,"unable to create lock file%s.lock; "1624"non-directory in the way",1625 ref_file.buf);1626}1627goto error_return;1628case SCLD_VANISHED:1629/* Maybe another process was tidying up. Try again. */1630if(--attempts_remaining >0)1631goto retry;1632/* fall through */1633default:1634strbuf_addf(err,"unable to create directory for%s",1635 ref_file.buf);1636goto error_return;1637}16381639if(!lock->lk)1640 lock->lk =xcalloc(1,sizeof(struct lock_file));16411642if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) {1643if(errno == ENOENT && --attempts_remaining >0) {1644/*1645 * Maybe somebody just deleted one of the1646 * directories leading to ref_file. Try1647 * again:1648 */1649goto retry;1650}else{1651unable_to_lock_message(ref_file.buf, errno, err);1652goto error_return;1653}1654}16551656/*1657 * Now we hold the lock and can read the reference without1658 * fear that its value will change.1659 */16601661if(read_raw_ref(refname, lock->old_oid.hash, referent, type)) {1662if(errno == ENOENT) {1663if(mustexist) {1664/* Garden variety missing reference. */1665strbuf_addf(err,"unable to resolve reference '%s'",1666 refname);1667goto error_return;1668}else{1669/*1670 * Reference is missing, but that's OK. We1671 * know that there is not a conflict with1672 * another loose reference because1673 * (supposing that we are trying to lock1674 * reference "refs/foo/bar"):1675 *1676 * - We were successfully able to create1677 * the lockfile refs/foo/bar.lock, so we1678 * know there cannot be a loose reference1679 * named "refs/foo".1680 *1681 * - We got ENOENT and not EISDIR, so we1682 * know that there cannot be a loose1683 * reference named "refs/foo/bar/baz".1684 */1685}1686}else if(errno == EISDIR) {1687/*1688 * There is a directory in the way. It might have1689 * contained references that have been deleted. If1690 * we don't require that the reference already1691 * exists, try to remove the directory so that it1692 * doesn't cause trouble when we want to rename the1693 * lockfile into place later.1694 */1695if(mustexist) {1696/* Garden variety missing reference. */1697strbuf_addf(err,"unable to resolve reference '%s'",1698 refname);1699goto error_return;1700}else if(remove_dir_recursively(&ref_file,1701 REMOVE_DIR_EMPTY_ONLY)) {1702if(verify_refname_available_dir(1703 refname, extras, skip,1704get_loose_refs(&ref_cache),1705 err)) {1706/*1707 * The error message set by1708 * verify_refname_available() is OK.1709 */1710 ret = TRANSACTION_NAME_CONFLICT;1711goto error_return;1712}else{1713/*1714 * We can't delete the directory,1715 * but we also don't know of any1716 * references that it should1717 * contain.1718 */1719strbuf_addf(err,"there is a non-empty directory '%s' "1720"blocking reference '%s'",1721 ref_file.buf, refname);1722goto error_return;1723}1724}1725}else if(errno == EINVAL && (*type & REF_ISBROKEN)) {1726strbuf_addf(err,"unable to resolve reference '%s': "1727"reference broken", refname);1728goto error_return;1729}else{1730strbuf_addf(err,"unable to resolve reference '%s':%s",1731 refname,strerror(errno));1732goto error_return;1733}17341735/*1736 * If the ref did not exist and we are creating it,1737 * make sure there is no existing packed ref whose1738 * name begins with our refname, nor a packed ref1739 * whose name is a proper prefix of our refname.1740 */1741if(verify_refname_available_dir(1742 refname, extras, skip,1743get_packed_refs(&ref_cache),1744 err)) {1745goto error_return;1746}1747}17481749 ret =0;1750goto out;17511752error_return:1753unlock_ref(lock);1754*lock_p = NULL;17551756out:1757strbuf_release(&ref_file);1758return ret;1759}17601761/*1762 * Peel the entry (if possible) and return its new peel_status. If1763 * repeel is true, re-peel the entry even if there is an old peeled1764 * value that is already stored in it.1765 *1766 * It is OK to call this function with a packed reference entry that1767 * might be stale and might even refer to an object that has since1768 * been garbage-collected. In such a case, if the entry has1769 * REF_KNOWS_PEELED then leave the status unchanged and return1770 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1771 */1772static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1773{1774enum peel_status status;17751776if(entry->flag & REF_KNOWS_PEELED) {1777if(repeel) {1778 entry->flag &= ~REF_KNOWS_PEELED;1779oidclr(&entry->u.value.peeled);1780}else{1781returnis_null_oid(&entry->u.value.peeled) ?1782 PEEL_NON_TAG : PEEL_PEELED;1783}1784}1785if(entry->flag & REF_ISBROKEN)1786return PEEL_BROKEN;1787if(entry->flag & REF_ISSYMREF)1788return PEEL_IS_SYMREF;17891790 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1791if(status == PEEL_PEELED || status == PEEL_NON_TAG)1792 entry->flag |= REF_KNOWS_PEELED;1793return status;1794}17951796intpeel_ref(const char*refname,unsigned char*sha1)1797{1798int flag;1799unsigned char base[20];18001801if(current_ref && (current_ref->name == refname1802|| !strcmp(current_ref->name, refname))) {1803if(peel_entry(current_ref,0))1804return-1;1805hashcpy(sha1, current_ref->u.value.peeled.hash);1806return0;1807}18081809if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1810return-1;18111812/*1813 * If the reference is packed, read its ref_entry from the1814 * cache in the hope that we already know its peeled value.1815 * We only try this optimization on packed references because1816 * (a) forcing the filling of the loose reference cache could1817 * be expensive and (b) loose references anyway usually do not1818 * have REF_KNOWS_PEELED.1819 */1820if(flag & REF_ISPACKED) {1821struct ref_entry *r =get_packed_ref(refname);1822if(r) {1823if(peel_entry(r,0))1824return-1;1825hashcpy(sha1, r->u.value.peeled.hash);1826return0;1827}1828}18291830returnpeel_object(base, sha1);1831}18321833/*1834 * Call fn for each reference in the specified ref_cache, omitting1835 * references not in the containing_dir of prefix. Call fn for all1836 * references, including broken ones. If fn ever returns a non-zero1837 * value, stop the iteration and return that value; otherwise, return1838 * 0.1839 */1840static intdo_for_each_entry(struct ref_cache *refs,const char*prefix,1841 each_ref_entry_fn fn,void*cb_data)1842{1843struct packed_ref_cache *packed_ref_cache;1844struct ref_dir *loose_dir;1845struct ref_dir *packed_dir;1846int retval =0;18471848/*1849 * We must make sure that all loose refs are read before accessing the1850 * packed-refs file; this avoids a race condition in which loose refs1851 * are migrated to the packed-refs file by a simultaneous process, but1852 * our in-memory view is from before the migration. get_packed_ref_cache()1853 * takes care of making sure our view is up to date with what is on1854 * disk.1855 */1856 loose_dir =get_loose_refs(refs);1857if(prefix && *prefix) {1858 loose_dir =find_containing_dir(loose_dir, prefix,0);1859}1860if(loose_dir)1861prime_ref_dir(loose_dir);18621863 packed_ref_cache =get_packed_ref_cache(refs);1864acquire_packed_ref_cache(packed_ref_cache);1865 packed_dir =get_packed_ref_dir(packed_ref_cache);1866if(prefix && *prefix) {1867 packed_dir =find_containing_dir(packed_dir, prefix,0);1868}18691870if(packed_dir && loose_dir) {1871sort_ref_dir(packed_dir);1872sort_ref_dir(loose_dir);1873 retval =do_for_each_entry_in_dirs(1874 packed_dir, loose_dir, fn, cb_data);1875}else if(packed_dir) {1876sort_ref_dir(packed_dir);1877 retval =do_for_each_entry_in_dir(1878 packed_dir,0, fn, cb_data);1879}else if(loose_dir) {1880sort_ref_dir(loose_dir);1881 retval =do_for_each_entry_in_dir(1882 loose_dir,0, fn, cb_data);1883}18841885release_packed_ref_cache(packed_ref_cache);1886return retval;1887}18881889intdo_for_each_ref(const char*submodule,const char*prefix,1890 each_ref_fn fn,int trim,int flags,void*cb_data)1891{1892struct ref_entry_cb data;1893struct ref_cache *refs;18941895 refs =get_ref_cache(submodule);1896if(!refs)1897return0;18981899 data.prefix = prefix;1900 data.trim = trim;1901 data.flags = flags;1902 data.fn = fn;1903 data.cb_data = cb_data;19041905if(ref_paranoia <0)1906 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1907if(ref_paranoia)1908 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;19091910returndo_for_each_entry(refs, prefix, do_one_ref, &data);1911}19121913/*1914 * Verify that the reference locked by lock has the value old_sha1.1915 * Fail if the reference doesn't exist and mustexist is set. Return 01916 * on success. On error, write an error message to err, set errno, and1917 * return a negative value.1918 */1919static intverify_lock(struct ref_lock *lock,1920const unsigned char*old_sha1,int mustexist,1921struct strbuf *err)1922{1923assert(err);19241925if(read_ref_full(lock->ref_name,1926 mustexist ? RESOLVE_REF_READING :0,1927 lock->old_oid.hash, NULL)) {1928if(old_sha1) {1929int save_errno = errno;1930strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1931 errno = save_errno;1932return-1;1933}else{1934hashclr(lock->old_oid.hash);1935return0;1936}1937}1938if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1939strbuf_addf(err,"ref '%s' is at%sbut expected%s",1940 lock->ref_name,1941sha1_to_hex(lock->old_oid.hash),1942sha1_to_hex(old_sha1));1943 errno = EBUSY;1944return-1;1945}1946return0;1947}19481949static intremove_empty_directories(struct strbuf *path)1950{1951/*1952 * we want to create a file but there is a directory there;1953 * if that is an empty directory (or a directory that contains1954 * only empty directories), remove them.1955 */1956returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1957}19581959/*1960 * Locks a ref returning the lock on success and NULL on failure.1961 * On failure errno is set to something meaningful.1962 */1963static struct ref_lock *lock_ref_sha1_basic(const char*refname,1964const unsigned char*old_sha1,1965const struct string_list *extras,1966const struct string_list *skip,1967unsigned int flags,int*type,1968struct strbuf *err)1969{1970struct strbuf ref_file = STRBUF_INIT;1971struct ref_lock *lock;1972int last_errno =0;1973int lflags = LOCK_NO_DEREF;1974int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1975int resolve_flags = RESOLVE_REF_NO_RECURSE;1976int attempts_remaining =3;1977int resolved;19781979assert(err);19801981 lock =xcalloc(1,sizeof(struct ref_lock));19821983if(mustexist)1984 resolve_flags |= RESOLVE_REF_READING;1985if(flags & REF_DELETING)1986 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;19871988strbuf_git_path(&ref_file,"%s", refname);1989 resolved = !!resolve_ref_unsafe(refname, resolve_flags,1990 lock->old_oid.hash, type);1991if(!resolved && errno == EISDIR) {1992/*1993 * we are trying to lock foo but we used to1994 * have foo/bar which now does not exist;1995 * it is normal for the empty directory 'foo'1996 * to remain.1997 */1998if(remove_empty_directories(&ref_file)) {1999 last_errno = errno;2000if(!verify_refname_available_dir(refname, extras, skip,2001get_loose_refs(&ref_cache), err))2002strbuf_addf(err,"there are still refs under '%s'",2003 refname);2004goto error_return;2005}2006 resolved = !!resolve_ref_unsafe(refname, resolve_flags,2007 lock->old_oid.hash, type);2008}2009if(!resolved) {2010 last_errno = errno;2011if(last_errno != ENOTDIR ||2012!verify_refname_available_dir(refname, extras, skip,2013get_loose_refs(&ref_cache), err))2014strbuf_addf(err,"unable to resolve reference '%s':%s",2015 refname,strerror(last_errno));20162017goto error_return;2018}20192020/*2021 * If the ref did not exist and we are creating it, make sure2022 * there is no existing packed ref whose name begins with our2023 * refname, nor a packed ref whose name is a proper prefix of2024 * our refname.2025 */2026if(is_null_oid(&lock->old_oid) &&2027verify_refname_available_dir(refname, extras, skip,2028get_packed_refs(&ref_cache), err)) {2029 last_errno = ENOTDIR;2030goto error_return;2031}20322033 lock->lk =xcalloc(1,sizeof(struct lock_file));20342035 lock->ref_name =xstrdup(refname);20362037 retry:2038switch(safe_create_leading_directories_const(ref_file.buf)) {2039case SCLD_OK:2040break;/* success */2041case SCLD_VANISHED:2042if(--attempts_remaining >0)2043goto retry;2044/* fall through */2045default:2046 last_errno = errno;2047strbuf_addf(err,"unable to create directory for '%s'",2048 ref_file.buf);2049goto error_return;2050}20512052if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2053 last_errno = errno;2054if(errno == ENOENT && --attempts_remaining >0)2055/*2056 * Maybe somebody just deleted one of the2057 * directories leading to ref_file. Try2058 * again:2059 */2060goto retry;2061else{2062unable_to_lock_message(ref_file.buf, errno, err);2063goto error_return;2064}2065}2066if(verify_lock(lock, old_sha1, mustexist, err)) {2067 last_errno = errno;2068goto error_return;2069}2070goto out;20712072 error_return:2073unlock_ref(lock);2074 lock = NULL;20752076 out:2077strbuf_release(&ref_file);2078 errno = last_errno;2079return lock;2080}20812082/*2083 * Write an entry to the packed-refs file for the specified refname.2084 * If peeled is non-NULL, write it as the entry's peeled value.2085 */2086static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2087unsigned char*peeled)2088{2089fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2090if(peeled)2091fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2092}20932094/*2095 * An each_ref_entry_fn that writes the entry to a packed-refs file.2096 */2097static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2098{2099enum peel_status peel_status =peel_entry(entry,0);21002101if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2102error("internal error:%sis not a valid packed reference!",2103 entry->name);2104write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2105 peel_status == PEEL_PEELED ?2106 entry->u.value.peeled.hash : NULL);2107return0;2108}21092110/*2111 * Lock the packed-refs file for writing. Flags is passed to2112 * hold_lock_file_for_update(). Return 0 on success. On errors, set2113 * errno appropriately and return a nonzero value.2114 */2115static intlock_packed_refs(int flags)2116{2117static int timeout_configured =0;2118static int timeout_value =1000;21192120struct packed_ref_cache *packed_ref_cache;21212122if(!timeout_configured) {2123git_config_get_int("core.packedrefstimeout", &timeout_value);2124 timeout_configured =1;2125}21262127if(hold_lock_file_for_update_timeout(2128&packlock,git_path("packed-refs"),2129 flags, timeout_value) <0)2130return-1;2131/*2132 * Get the current packed-refs while holding the lock. If the2133 * packed-refs file has been modified since we last read it,2134 * this will automatically invalidate the cache and re-read2135 * the packed-refs file.2136 */2137 packed_ref_cache =get_packed_ref_cache(&ref_cache);2138 packed_ref_cache->lock = &packlock;2139/* Increment the reference count to prevent it from being freed: */2140acquire_packed_ref_cache(packed_ref_cache);2141return0;2142}21432144/*2145 * Write the current version of the packed refs cache from memory to2146 * disk. The packed-refs file must already be locked for writing (see2147 * lock_packed_refs()). Return zero on success. On errors, set errno2148 * and return a nonzero value2149 */2150static intcommit_packed_refs(void)2151{2152struct packed_ref_cache *packed_ref_cache =2153get_packed_ref_cache(&ref_cache);2154int error =0;2155int save_errno =0;2156FILE*out;21572158if(!packed_ref_cache->lock)2159die("internal error: packed-refs not locked");21602161 out =fdopen_lock_file(packed_ref_cache->lock,"w");2162if(!out)2163die_errno("unable to fdopen packed-refs descriptor");21642165fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2166do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),21670, write_packed_entry_fn, out);21682169if(commit_lock_file(packed_ref_cache->lock)) {2170 save_errno = errno;2171 error = -1;2172}2173 packed_ref_cache->lock = NULL;2174release_packed_ref_cache(packed_ref_cache);2175 errno = save_errno;2176return error;2177}21782179/*2180 * Rollback the lockfile for the packed-refs file, and discard the2181 * in-memory packed reference cache. (The packed-refs file will be2182 * read anew if it is needed again after this function is called.)2183 */2184static voidrollback_packed_refs(void)2185{2186struct packed_ref_cache *packed_ref_cache =2187get_packed_ref_cache(&ref_cache);21882189if(!packed_ref_cache->lock)2190die("internal error: packed-refs not locked");2191rollback_lock_file(packed_ref_cache->lock);2192 packed_ref_cache->lock = NULL;2193release_packed_ref_cache(packed_ref_cache);2194clear_packed_ref_cache(&ref_cache);2195}21962197struct ref_to_prune {2198struct ref_to_prune *next;2199unsigned char sha1[20];2200char name[FLEX_ARRAY];2201};22022203struct pack_refs_cb_data {2204unsigned int flags;2205struct ref_dir *packed_refs;2206struct ref_to_prune *ref_to_prune;2207};22082209/*2210 * An each_ref_entry_fn that is run over loose references only. If2211 * the loose reference can be packed, add an entry in the packed ref2212 * cache. If the reference should be pruned, also add it to2213 * ref_to_prune in the pack_refs_cb_data.2214 */2215static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2216{2217struct pack_refs_cb_data *cb = cb_data;2218enum peel_status peel_status;2219struct ref_entry *packed_entry;2220int is_tag_ref =starts_with(entry->name,"refs/tags/");22212222/* Do not pack per-worktree refs: */2223if(ref_type(entry->name) != REF_TYPE_NORMAL)2224return0;22252226/* ALWAYS pack tags */2227if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2228return0;22292230/* Do not pack symbolic or broken refs: */2231if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2232return0;22332234/* Add a packed ref cache entry equivalent to the loose entry. */2235 peel_status =peel_entry(entry,1);2236if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2237die("internal error peeling reference%s(%s)",2238 entry->name,oid_to_hex(&entry->u.value.oid));2239 packed_entry =find_ref(cb->packed_refs, entry->name);2240if(packed_entry) {2241/* Overwrite existing packed entry with info from loose entry */2242 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2243oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2244}else{2245 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2246 REF_ISPACKED | REF_KNOWS_PEELED,0);2247add_ref(cb->packed_refs, packed_entry);2248}2249oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);22502251/* Schedule the loose reference for pruning if requested. */2252if((cb->flags & PACK_REFS_PRUNE)) {2253struct ref_to_prune *n;2254FLEX_ALLOC_STR(n, name, entry->name);2255hashcpy(n->sha1, entry->u.value.oid.hash);2256 n->next = cb->ref_to_prune;2257 cb->ref_to_prune = n;2258}2259return0;2260}22612262/*2263 * Remove empty parents, but spare refs/ and immediate subdirs.2264 * Note: munges *name.2265 */2266static voidtry_remove_empty_parents(char*name)2267{2268char*p, *q;2269int i;2270 p = name;2271for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2272while(*p && *p !='/')2273 p++;2274/* tolerate duplicate slashes; see check_refname_format() */2275while(*p =='/')2276 p++;2277}2278for(q = p; *q; q++)2279;2280while(1) {2281while(q > p && *q !='/')2282 q--;2283while(q > p && *(q-1) =='/')2284 q--;2285if(q == p)2286break;2287*q ='\0';2288if(rmdir(git_path("%s", name)))2289break;2290}2291}22922293/* make sure nobody touched the ref, and unlink */2294static voidprune_ref(struct ref_to_prune *r)2295{2296struct ref_transaction *transaction;2297struct strbuf err = STRBUF_INIT;22982299if(check_refname_format(r->name,0))2300return;23012302 transaction =ref_transaction_begin(&err);2303if(!transaction ||2304ref_transaction_delete(transaction, r->name, r->sha1,2305 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||2306ref_transaction_commit(transaction, &err)) {2307ref_transaction_free(transaction);2308error("%s", err.buf);2309strbuf_release(&err);2310return;2311}2312ref_transaction_free(transaction);2313strbuf_release(&err);2314try_remove_empty_parents(r->name);2315}23162317static voidprune_refs(struct ref_to_prune *r)2318{2319while(r) {2320prune_ref(r);2321 r = r->next;2322}2323}23242325intpack_refs(unsigned int flags)2326{2327struct pack_refs_cb_data cbdata;23282329memset(&cbdata,0,sizeof(cbdata));2330 cbdata.flags = flags;23312332lock_packed_refs(LOCK_DIE_ON_ERROR);2333 cbdata.packed_refs =get_packed_refs(&ref_cache);23342335do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2336 pack_if_possible_fn, &cbdata);23372338if(commit_packed_refs())2339die_errno("unable to overwrite old ref-pack file");23402341prune_refs(cbdata.ref_to_prune);2342return0;2343}23442345/*2346 * Rewrite the packed-refs file, omitting any refs listed in2347 * 'refnames'. On error, leave packed-refs unchanged, write an error2348 * message to 'err', and return a nonzero value.2349 *2350 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2351 */2352static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2353{2354struct ref_dir *packed;2355struct string_list_item *refname;2356int ret, needs_repacking =0, removed =0;23572358assert(err);23592360/* Look for a packed ref */2361for_each_string_list_item(refname, refnames) {2362if(get_packed_ref(refname->string)) {2363 needs_repacking =1;2364break;2365}2366}23672368/* Avoid locking if we have nothing to do */2369if(!needs_repacking)2370return0;/* no refname exists in packed refs */23712372if(lock_packed_refs(0)) {2373unable_to_lock_message(git_path("packed-refs"), errno, err);2374return-1;2375}2376 packed =get_packed_refs(&ref_cache);23772378/* Remove refnames from the cache */2379for_each_string_list_item(refname, refnames)2380if(remove_entry(packed, refname->string) != -1)2381 removed =1;2382if(!removed) {2383/*2384 * All packed entries disappeared while we were2385 * acquiring the lock.2386 */2387rollback_packed_refs();2388return0;2389}23902391/* Write what remains */2392 ret =commit_packed_refs();2393if(ret)2394strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2395strerror(errno));2396return ret;2397}23982399static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2400{2401assert(err);24022403if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2404/*2405 * loose. The loose file name is the same as the2406 * lockfile name, minus ".lock":2407 */2408char*loose_filename =get_locked_file_path(lock->lk);2409int res =unlink_or_msg(loose_filename, err);2410free(loose_filename);2411if(res)2412return1;2413}2414return0;2415}24162417intdelete_refs(struct string_list *refnames,unsigned int flags)2418{2419struct strbuf err = STRBUF_INIT;2420int i, result =0;24212422if(!refnames->nr)2423return0;24242425 result =repack_without_refs(refnames, &err);2426if(result) {2427/*2428 * If we failed to rewrite the packed-refs file, then2429 * it is unsafe to try to remove loose refs, because2430 * doing so might expose an obsolete packed value for2431 * a reference that might even point at an object that2432 * has been garbage collected.2433 */2434if(refnames->nr ==1)2435error(_("could not delete reference%s:%s"),2436 refnames->items[0].string, err.buf);2437else2438error(_("could not delete references:%s"), err.buf);24392440goto out;2441}24422443for(i =0; i < refnames->nr; i++) {2444const char*refname = refnames->items[i].string;24452446if(delete_ref(refname, NULL, flags))2447 result |=error(_("could not remove reference%s"), refname);2448}24492450out:2451strbuf_release(&err);2452return result;2453}24542455/*2456 * People using contrib's git-new-workdir have .git/logs/refs ->2457 * /some/other/path/.git/logs/refs, and that may live on another device.2458 *2459 * IOW, to avoid cross device rename errors, the temporary renamed log must2460 * live into logs/refs.2461 */2462#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"24632464static intrename_tmp_log(const char*newrefname)2465{2466int attempts_remaining =4;2467struct strbuf path = STRBUF_INIT;2468int ret = -1;24692470 retry:2471strbuf_reset(&path);2472strbuf_git_path(&path,"logs/%s", newrefname);2473switch(safe_create_leading_directories_const(path.buf)) {2474case SCLD_OK:2475break;/* success */2476case SCLD_VANISHED:2477if(--attempts_remaining >0)2478goto retry;2479/* fall through */2480default:2481error("unable to create directory for%s", newrefname);2482goto out;2483}24842485if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2486if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2487/*2488 * rename(a, b) when b is an existing2489 * directory ought to result in ISDIR, but2490 * Solaris 5.8 gives ENOTDIR. Sheesh.2491 */2492if(remove_empty_directories(&path)) {2493error("Directory not empty: logs/%s", newrefname);2494goto out;2495}2496goto retry;2497}else if(errno == ENOENT && --attempts_remaining >0) {2498/*2499 * Maybe another process just deleted one of2500 * the directories in the path to newrefname.2501 * Try again from the beginning.2502 */2503goto retry;2504}else{2505error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2506 newrefname,strerror(errno));2507goto out;2508}2509}2510 ret =0;2511out:2512strbuf_release(&path);2513return ret;2514}25152516intverify_refname_available(const char*newname,2517const struct string_list *extras,2518const struct string_list *skip,2519struct strbuf *err)2520{2521struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2522struct ref_dir *loose_refs =get_loose_refs(&ref_cache);25232524if(verify_refname_available_dir(newname, extras, skip,2525 packed_refs, err) ||2526verify_refname_available_dir(newname, extras, skip,2527 loose_refs, err))2528return-1;25292530return0;2531}25322533static intwrite_ref_to_lockfile(struct ref_lock *lock,2534const unsigned char*sha1,struct strbuf *err);2535static intcommit_ref_update(struct ref_lock *lock,2536const unsigned char*sha1,const char*logmsg,2537struct strbuf *err);25382539intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2540{2541unsigned char sha1[20], orig_sha1[20];2542int flag =0, logmoved =0;2543struct ref_lock *lock;2544struct stat loginfo;2545int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2546struct strbuf err = STRBUF_INIT;25472548if(log &&S_ISLNK(loginfo.st_mode))2549returnerror("reflog for%sis a symlink", oldrefname);25502551if(!resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2552 orig_sha1, &flag))2553returnerror("refname%snot found", oldrefname);25542555if(flag & REF_ISSYMREF)2556returnerror("refname%sis a symbolic ref, renaming it is not supported",2557 oldrefname);2558if(!rename_ref_available(oldrefname, newrefname))2559return1;25602561if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2562returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2563 oldrefname,strerror(errno));25642565if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2566error("unable to delete old%s", oldrefname);2567goto rollback;2568}25692570/*2571 * Since we are doing a shallow lookup, sha1 is not the2572 * correct value to pass to delete_ref as old_sha1. But that2573 * doesn't matter, because an old_sha1 check wouldn't add to2574 * the safety anyway; we want to delete the reference whatever2575 * its current value.2576 */2577if(!read_ref_full(newrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2578 sha1, NULL) &&2579delete_ref(newrefname, NULL, REF_NODEREF)) {2580if(errno==EISDIR) {2581struct strbuf path = STRBUF_INIT;2582int result;25832584strbuf_git_path(&path,"%s", newrefname);2585 result =remove_empty_directories(&path);2586strbuf_release(&path);25872588if(result) {2589error("Directory not empty:%s", newrefname);2590goto rollback;2591}2592}else{2593error("unable to delete existing%s", newrefname);2594goto rollback;2595}2596}25972598if(log &&rename_tmp_log(newrefname))2599goto rollback;26002601 logmoved = log;26022603 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, REF_NODEREF,2604 NULL, &err);2605if(!lock) {2606error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2607strbuf_release(&err);2608goto rollback;2609}2610hashcpy(lock->old_oid.hash, orig_sha1);26112612if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2613commit_ref_update(lock, orig_sha1, logmsg, &err)) {2614error("unable to write current sha1 into%s:%s", newrefname, err.buf);2615strbuf_release(&err);2616goto rollback;2617}26182619return0;26202621 rollback:2622 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, REF_NODEREF,2623 NULL, &err);2624if(!lock) {2625error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2626strbuf_release(&err);2627goto rollbacklog;2628}26292630 flag = log_all_ref_updates;2631 log_all_ref_updates =0;2632if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2633commit_ref_update(lock, orig_sha1, NULL, &err)) {2634error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2635strbuf_release(&err);2636}2637 log_all_ref_updates = flag;26382639 rollbacklog:2640if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2641error("unable to restore logfile%sfrom%s:%s",2642 oldrefname, newrefname,strerror(errno));2643if(!logmoved && log &&2644rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2645error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2646 oldrefname,strerror(errno));26472648return1;2649}26502651static intclose_ref(struct ref_lock *lock)2652{2653if(close_lock_file(lock->lk))2654return-1;2655return0;2656}26572658static intcommit_ref(struct ref_lock *lock)2659{2660char*path =get_locked_file_path(lock->lk);2661struct stat st;26622663if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {2664/*2665 * There is a directory at the path we want to rename2666 * the lockfile to. Hopefully it is empty; try to2667 * delete it.2668 */2669size_t len =strlen(path);2670struct strbuf sb_path = STRBUF_INIT;26712672strbuf_attach(&sb_path, path, len, len);26732674/*2675 * If this fails, commit_lock_file() will also fail2676 * and will report the problem.2677 */2678remove_empty_directories(&sb_path);2679strbuf_release(&sb_path);2680}else{2681free(path);2682}26832684if(commit_lock_file(lock->lk))2685return-1;2686return0;2687}26882689/*2690 * Create a reflog for a ref. If force_create = 0, the reflog will2691 * only be created for certain refs (those for which2692 * should_autocreate_reflog returns non-zero. Otherwise, create it2693 * regardless of the ref name. Fill in *err and return -1 on failure.2694 */2695static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2696{2697int logfd, oflags = O_APPEND | O_WRONLY;26982699strbuf_git_path(logfile,"logs/%s", refname);2700if(force_create ||should_autocreate_reflog(refname)) {2701if(safe_create_leading_directories(logfile->buf) <0) {2702strbuf_addf(err,"unable to create directory for '%s': "2703"%s", logfile->buf,strerror(errno));2704return-1;2705}2706 oflags |= O_CREAT;2707}27082709 logfd =open(logfile->buf, oflags,0666);2710if(logfd <0) {2711if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2712return0;27132714if(errno == EISDIR) {2715if(remove_empty_directories(logfile)) {2716strbuf_addf(err,"there are still logs under "2717"'%s'", logfile->buf);2718return-1;2719}2720 logfd =open(logfile->buf, oflags,0666);2721}27222723if(logfd <0) {2724strbuf_addf(err,"unable to append to '%s':%s",2725 logfile->buf,strerror(errno));2726return-1;2727}2728}27292730adjust_shared_perm(logfile->buf);2731close(logfd);2732return0;2733}273427352736intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2737{2738int ret;2739struct strbuf sb = STRBUF_INIT;27402741 ret =log_ref_setup(refname, &sb, err, force_create);2742strbuf_release(&sb);2743return ret;2744}27452746static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2747const unsigned char*new_sha1,2748const char*committer,const char*msg)2749{2750int msglen, written;2751unsigned maxlen, len;2752char*logrec;27532754 msglen = msg ?strlen(msg) :0;2755 maxlen =strlen(committer) + msglen +100;2756 logrec =xmalloc(maxlen);2757 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2758sha1_to_hex(old_sha1),2759sha1_to_hex(new_sha1),2760 committer);2761if(msglen)2762 len +=copy_reflog_msg(logrec + len -1, msg) -1;27632764 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2765free(logrec);2766if(written != len)2767return-1;27682769return0;2770}27712772static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2773const unsigned char*new_sha1,const char*msg,2774struct strbuf *logfile,int flags,2775struct strbuf *err)2776{2777int logfd, result, oflags = O_APPEND | O_WRONLY;27782779if(log_all_ref_updates <0)2780 log_all_ref_updates = !is_bare_repository();27812782 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);27832784if(result)2785return result;27862787 logfd =open(logfile->buf, oflags);2788if(logfd <0)2789return0;2790 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2791git_committer_info(0), msg);2792if(result) {2793strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,2794strerror(errno));2795close(logfd);2796return-1;2797}2798if(close(logfd)) {2799strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,2800strerror(errno));2801return-1;2802}2803return0;2804}28052806static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2807const unsigned char*new_sha1,const char*msg,2808int flags,struct strbuf *err)2809{2810returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2811 err);2812}28132814intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2815const unsigned char*new_sha1,const char*msg,2816int flags,struct strbuf *err)2817{2818struct strbuf sb = STRBUF_INIT;2819int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2820 err);2821strbuf_release(&sb);2822return ret;2823}28242825/*2826 * Write sha1 into the open lockfile, then close the lockfile. On2827 * errors, rollback the lockfile, fill in *err and2828 * return -1.2829 */2830static intwrite_ref_to_lockfile(struct ref_lock *lock,2831const unsigned char*sha1,struct strbuf *err)2832{2833static char term ='\n';2834struct object *o;2835int fd;28362837 o =parse_object(sha1);2838if(!o) {2839strbuf_addf(err,2840"trying to write ref '%s' with nonexistent object%s",2841 lock->ref_name,sha1_to_hex(sha1));2842unlock_ref(lock);2843return-1;2844}2845if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2846strbuf_addf(err,2847"trying to write non-commit object%sto branch '%s'",2848sha1_to_hex(sha1), lock->ref_name);2849unlock_ref(lock);2850return-1;2851}2852 fd =get_lock_file_fd(lock->lk);2853if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2854write_in_full(fd, &term,1) !=1||2855close_ref(lock) <0) {2856strbuf_addf(err,2857"couldn't write '%s'",get_lock_file_path(lock->lk));2858unlock_ref(lock);2859return-1;2860}2861return0;2862}28632864/*2865 * Commit a change to a loose reference that has already been written2866 * to the loose reference lockfile. Also update the reflogs if2867 * necessary, using the specified lockmsg (which can be NULL).2868 */2869static intcommit_ref_update(struct ref_lock *lock,2870const unsigned char*sha1,const char*logmsg,2871struct strbuf *err)2872{2873clear_loose_ref_cache(&ref_cache);2874if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg,0, err)) {2875char*old_msg =strbuf_detach(err, NULL);2876strbuf_addf(err,"cannot update the ref '%s':%s",2877 lock->ref_name, old_msg);2878free(old_msg);2879unlock_ref(lock);2880return-1;2881}28822883if(strcmp(lock->ref_name,"HEAD") !=0) {2884/*2885 * Special hack: If a branch is updated directly and HEAD2886 * points to it (may happen on the remote side of a push2887 * for example) then logically the HEAD reflog should be2888 * updated too.2889 * A generic solution implies reverse symref information,2890 * but finding all symrefs pointing to the given branch2891 * would be rather costly for this rare event (the direct2892 * update of a branch) to be worth it. So let's cheat and2893 * check with HEAD only which should cover 99% of all usage2894 * scenarios (even 100% of the default ones).2895 */2896unsigned char head_sha1[20];2897int head_flag;2898const char*head_ref;28992900 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2901 head_sha1, &head_flag);2902if(head_ref && (head_flag & REF_ISSYMREF) &&2903!strcmp(head_ref, lock->ref_name)) {2904struct strbuf log_err = STRBUF_INIT;2905if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2906 logmsg,0, &log_err)) {2907error("%s", log_err.buf);2908strbuf_release(&log_err);2909}2910}2911}29122913if(commit_ref(lock)) {2914strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2915unlock_ref(lock);2916return-1;2917}29182919unlock_ref(lock);2920return0;2921}29222923static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2924{2925int ret = -1;2926#ifndef NO_SYMLINK_HEAD2927char*ref_path =get_locked_file_path(lock->lk);2928unlink(ref_path);2929 ret =symlink(target, ref_path);2930free(ref_path);29312932if(ret)2933fprintf(stderr,"no symlink - falling back to symbolic ref\n");2934#endif2935return ret;2936}29372938static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2939const char*target,const char*logmsg)2940{2941struct strbuf err = STRBUF_INIT;2942unsigned char new_sha1[20];2943if(logmsg && !read_ref(target, new_sha1) &&2944log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2945error("%s", err.buf);2946strbuf_release(&err);2947}2948}29492950static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2951const char*target,const char*logmsg)2952{2953if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2954update_symref_reflog(lock, refname, target, logmsg);2955return0;2956}29572958if(!fdopen_lock_file(lock->lk,"w"))2959returnerror("unable to fdopen%s:%s",2960 lock->lk->tempfile.filename.buf,strerror(errno));29612962update_symref_reflog(lock, refname, target, logmsg);29632964/* no error check; commit_ref will check ferror */2965fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2966if(commit_ref(lock) <0)2967returnerror("unable to write symref for%s:%s", refname,2968strerror(errno));2969return0;2970}29712972intcreate_symref(const char*refname,const char*target,const char*logmsg)2973{2974struct strbuf err = STRBUF_INIT;2975struct ref_lock *lock;2976int ret;29772978 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2979&err);2980if(!lock) {2981error("%s", err.buf);2982strbuf_release(&err);2983return-1;2984}29852986 ret =create_symref_locked(lock, refname, target, logmsg);2987unlock_ref(lock);2988return ret;2989}29902991intset_worktree_head_symref(const char*gitdir,const char*target)2992{2993static struct lock_file head_lock;2994struct ref_lock *lock;2995struct strbuf head_path = STRBUF_INIT;2996const char*head_rel;2997int ret;29982999strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));3000if(hold_lock_file_for_update(&head_lock, head_path.buf,3001 LOCK_NO_DEREF) <0) {3002struct strbuf err = STRBUF_INIT;3003unable_to_lock_message(head_path.buf, errno, &err);3004error("%s", err.buf);3005strbuf_release(&err);3006strbuf_release(&head_path);3007return-1;3008}30093010/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for3011 linked trees */3012 head_rel =remove_leading_path(head_path.buf,3013absolute_path(get_git_common_dir()));3014/* to make use of create_symref_locked(), initialize ref_lock */3015 lock =xcalloc(1,sizeof(struct ref_lock));3016 lock->lk = &head_lock;3017 lock->ref_name =xstrdup(head_rel);30183019 ret =create_symref_locked(lock, head_rel, target, NULL);30203021unlock_ref(lock);/* will free lock */3022strbuf_release(&head_path);3023return ret;3024}30253026intreflog_exists(const char*refname)3027{3028struct stat st;30293030return!lstat(git_path("logs/%s", refname), &st) &&3031S_ISREG(st.st_mode);3032}30333034intdelete_reflog(const char*refname)3035{3036returnremove_path(git_path("logs/%s", refname));3037}30383039static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3040{3041unsigned char osha1[20], nsha1[20];3042char*email_end, *message;3043unsigned long timestamp;3044int tz;30453046/* old SP new SP name <email> SP time TAB msg LF */3047if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3048get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3049get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3050!(email_end =strchr(sb->buf +82,'>')) ||3051 email_end[1] !=' '||3052!(timestamp =strtoul(email_end +2, &message,10)) ||3053!message || message[0] !=' '||3054(message[1] !='+'&& message[1] !='-') ||3055!isdigit(message[2]) || !isdigit(message[3]) ||3056!isdigit(message[4]) || !isdigit(message[5]))3057return0;/* corrupt? */3058 email_end[1] ='\0';3059 tz =strtol(message +1, NULL,10);3060if(message[6] !='\t')3061 message +=6;3062else3063 message +=7;3064returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3065}30663067static char*find_beginning_of_line(char*bob,char*scan)3068{3069while(bob < scan && *(--scan) !='\n')3070;/* keep scanning backwards */3071/*3072 * Return either beginning of the buffer, or LF at the end of3073 * the previous line.3074 */3075return scan;3076}30773078intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3079{3080struct strbuf sb = STRBUF_INIT;3081FILE*logfp;3082long pos;3083int ret =0, at_tail =1;30843085 logfp =fopen(git_path("logs/%s", refname),"r");3086if(!logfp)3087return-1;30883089/* Jump to the end */3090if(fseek(logfp,0, SEEK_END) <0)3091returnerror("cannot seek back reflog for%s:%s",3092 refname,strerror(errno));3093 pos =ftell(logfp);3094while(!ret &&0< pos) {3095int cnt;3096size_t nread;3097char buf[BUFSIZ];3098char*endp, *scanp;30993100/* Fill next block from the end */3101 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3102if(fseek(logfp, pos - cnt, SEEK_SET))3103returnerror("cannot seek back reflog for%s:%s",3104 refname,strerror(errno));3105 nread =fread(buf, cnt,1, logfp);3106if(nread !=1)3107returnerror("cannot read%dbytes from reflog for%s:%s",3108 cnt, refname,strerror(errno));3109 pos -= cnt;31103111 scanp = endp = buf + cnt;3112if(at_tail && scanp[-1] =='\n')3113/* Looking at the final LF at the end of the file */3114 scanp--;3115 at_tail =0;31163117while(buf < scanp) {3118/*3119 * terminating LF of the previous line, or the beginning3120 * of the buffer.3121 */3122char*bp;31233124 bp =find_beginning_of_line(buf, scanp);31253126if(*bp =='\n') {3127/*3128 * The newline is the end of the previous line,3129 * so we know we have complete line starting3130 * at (bp + 1). Prefix it onto any prior data3131 * we collected for the line and process it.3132 */3133strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3134 scanp = bp;3135 endp = bp +1;3136 ret =show_one_reflog_ent(&sb, fn, cb_data);3137strbuf_reset(&sb);3138if(ret)3139break;3140}else if(!pos) {3141/*3142 * We are at the start of the buffer, and the3143 * start of the file; there is no previous3144 * line, and we have everything for this one.3145 * Process it, and we can end the loop.3146 */3147strbuf_splice(&sb,0,0, buf, endp - buf);3148 ret =show_one_reflog_ent(&sb, fn, cb_data);3149strbuf_reset(&sb);3150break;3151}31523153if(bp == buf) {3154/*3155 * We are at the start of the buffer, and there3156 * is more file to read backwards. Which means3157 * we are in the middle of a line. Note that we3158 * may get here even if *bp was a newline; that3159 * just means we are at the exact end of the3160 * previous line, rather than some spot in the3161 * middle.3162 *3163 * Save away what we have to be combined with3164 * the data from the next read.3165 */3166strbuf_splice(&sb,0,0, buf, endp - buf);3167break;3168}3169}31703171}3172if(!ret && sb.len)3173die("BUG: reverse reflog parser had leftover data");31743175fclose(logfp);3176strbuf_release(&sb);3177return ret;3178}31793180intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3181{3182FILE*logfp;3183struct strbuf sb = STRBUF_INIT;3184int ret =0;31853186 logfp =fopen(git_path("logs/%s", refname),"r");3187if(!logfp)3188return-1;31893190while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3191 ret =show_one_reflog_ent(&sb, fn, cb_data);3192fclose(logfp);3193strbuf_release(&sb);3194return ret;3195}3196/*3197 * Call fn for each reflog in the namespace indicated by name. name3198 * must be empty or end with '/'. Name will be used as a scratch3199 * space, but its contents will be restored before return.3200 */3201static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3202{3203DIR*d =opendir(git_path("logs/%s", name->buf));3204int retval =0;3205struct dirent *de;3206int oldlen = name->len;32073208if(!d)3209return name->len ? errno :0;32103211while((de =readdir(d)) != NULL) {3212struct stat st;32133214if(de->d_name[0] =='.')3215continue;3216if(ends_with(de->d_name,".lock"))3217continue;3218strbuf_addstr(name, de->d_name);3219if(stat(git_path("logs/%s", name->buf), &st) <0) {3220;/* silently ignore */3221}else{3222if(S_ISDIR(st.st_mode)) {3223strbuf_addch(name,'/');3224 retval =do_for_each_reflog(name, fn, cb_data);3225}else{3226struct object_id oid;32273228if(read_ref_full(name->buf,0, oid.hash, NULL))3229 retval =error("bad ref for%s", name->buf);3230else3231 retval =fn(name->buf, &oid,0, cb_data);3232}3233if(retval)3234break;3235}3236strbuf_setlen(name, oldlen);3237}3238closedir(d);3239return retval;3240}32413242intfor_each_reflog(each_ref_fn fn,void*cb_data)3243{3244int retval;3245struct strbuf name;3246strbuf_init(&name, PATH_MAX);3247 retval =do_for_each_reflog(&name, fn, cb_data);3248strbuf_release(&name);3249return retval;3250}32513252static intref_update_reject_duplicates(struct string_list *refnames,3253struct strbuf *err)3254{3255int i, n = refnames->nr;32563257assert(err);32583259for(i =1; i < n; i++)3260if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3261strbuf_addf(err,3262"multiple updates for ref '%s' not allowed.",3263 refnames->items[i].string);3264return1;3265}3266return0;3267}32683269/*3270 * If update is a direct update of head_ref (the reference pointed to3271 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.3272 */3273static intsplit_head_update(struct ref_update *update,3274struct ref_transaction *transaction,3275const char*head_ref,3276struct string_list *affected_refnames,3277struct strbuf *err)3278{3279struct string_list_item *item;3280struct ref_update *new_update;32813282if((update->flags & REF_LOG_ONLY) ||3283(update->flags & REF_ISPRUNING) ||3284(update->flags & REF_UPDATE_VIA_HEAD))3285return0;32863287if(strcmp(update->refname, head_ref))3288return0;32893290/*3291 * First make sure that HEAD is not already in the3292 * transaction. This insertion is O(N) in the transaction3293 * size, but it happens at most once per transaction.3294 */3295 item =string_list_insert(affected_refnames,"HEAD");3296if(item->util) {3297/* An entry already existed */3298strbuf_addf(err,3299"multiple updates for 'HEAD' (including one "3300"via its referent '%s') are not allowed",3301 update->refname);3302return TRANSACTION_NAME_CONFLICT;3303}33043305 new_update =ref_transaction_add_update(3306 transaction,"HEAD",3307 update->flags | REF_LOG_ONLY | REF_NODEREF,3308 update->new_sha1, update->old_sha1,3309 update->msg);33103311 item->util = new_update;33123313return0;3314}33153316/*3317 * update is for a symref that points at referent and doesn't have3318 * REF_NODEREF set. Split it into two updates:3319 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set3320 * - A new, separate update for the referent reference3321 * Note that the new update will itself be subject to splitting when3322 * the iteration gets to it.3323 */3324static intsplit_symref_update(struct ref_update *update,3325const char*referent,3326struct ref_transaction *transaction,3327struct string_list *affected_refnames,3328struct strbuf *err)3329{3330struct string_list_item *item;3331struct ref_update *new_update;3332unsigned int new_flags;33333334/*3335 * First make sure that referent is not already in the3336 * transaction. This insertion is O(N) in the transaction3337 * size, but it happens at most once per symref in a3338 * transaction.3339 */3340 item =string_list_insert(affected_refnames, referent);3341if(item->util) {3342/* An entry already existed */3343strbuf_addf(err,3344"multiple updates for '%s' (including one "3345"via symref '%s') are not allowed",3346 referent, update->refname);3347return TRANSACTION_NAME_CONFLICT;3348}33493350 new_flags = update->flags;3351if(!strcmp(update->refname,"HEAD")) {3352/*3353 * Record that the new update came via HEAD, so that3354 * when we process it, split_head_update() doesn't try3355 * to add another reflog update for HEAD. Note that3356 * this bit will be propagated if the new_update3357 * itself needs to be split.3358 */3359 new_flags |= REF_UPDATE_VIA_HEAD;3360}33613362 new_update =ref_transaction_add_update(3363 transaction, referent, new_flags,3364 update->new_sha1, update->old_sha1,3365 update->msg);33663367 new_update->parent_update = update;33683369/*3370 * Change the symbolic ref update to log only. Also, it3371 * doesn't need to check its old SHA-1 value, as that will be3372 * done when new_update is processed.3373 */3374 update->flags |= REF_LOG_ONLY | REF_NODEREF;3375 update->flags &= ~REF_HAVE_OLD;33763377 item->util = new_update;33783379return0;3380}33813382/*3383 * Return the refname under which update was originally requested.3384 */3385static const char*original_update_refname(struct ref_update *update)3386{3387while(update->parent_update)3388 update = update->parent_update;33893390return update->refname;3391}33923393/*3394 * Prepare for carrying out update:3395 * - Lock the reference referred to by update.3396 * - Read the reference under lock.3397 * - Check that its old SHA-1 value (if specified) is correct, and in3398 * any case record it in update->lock->old_oid for later use when3399 * writing the reflog.3400 * - If it is a symref update without REF_NODEREF, split it up into a3401 * REF_LOG_ONLY update of the symref and add a separate update for3402 * the referent to transaction.3403 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY3404 * update of HEAD.3405 */3406static intlock_ref_for_update(struct ref_update *update,3407struct ref_transaction *transaction,3408const char*head_ref,3409struct string_list *affected_refnames,3410struct strbuf *err)3411{3412struct strbuf referent = STRBUF_INIT;3413int mustexist = (update->flags & REF_HAVE_OLD) &&3414!is_null_sha1(update->old_sha1);3415int ret;3416struct ref_lock *lock;34173418if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))3419 update->flags |= REF_DELETING;34203421if(head_ref) {3422 ret =split_head_update(update, transaction, head_ref,3423 affected_refnames, err);3424if(ret)3425return ret;3426}34273428 ret =lock_raw_ref(update->refname, mustexist,3429 affected_refnames, NULL,3430&update->lock, &referent,3431&update->type, err);34323433if(ret) {3434char*reason;34353436 reason =strbuf_detach(err, NULL);3437strbuf_addf(err,"cannot lock ref '%s':%s",3438 update->refname, reason);3439free(reason);3440return ret;3441}34423443 lock = update->lock;34443445if(update->type & REF_ISSYMREF) {3446if(update->flags & REF_NODEREF) {3447/*3448 * We won't be reading the referent as part of3449 * the transaction, so we have to read it here3450 * to record and possibly check old_sha1:3451 */3452if(read_ref_full(update->refname,3453 mustexist ? RESOLVE_REF_READING :0,3454 lock->old_oid.hash, NULL)) {3455if(update->flags & REF_HAVE_OLD) {3456strbuf_addf(err,"cannot lock ref '%s': "3457"can't resolve old value",3458 update->refname);3459return TRANSACTION_GENERIC_ERROR;3460}else{3461hashclr(lock->old_oid.hash);3462}3463}3464if((update->flags & REF_HAVE_OLD) &&3465hashcmp(lock->old_oid.hash, update->old_sha1)) {3466strbuf_addf(err,"cannot lock ref '%s': "3467"is at%sbut expected%s",3468 update->refname,3469sha1_to_hex(lock->old_oid.hash),3470sha1_to_hex(update->old_sha1));3471return TRANSACTION_GENERIC_ERROR;3472}34733474}else{3475/*3476 * Create a new update for the reference this3477 * symref is pointing at. Also, we will record3478 * and verify old_sha1 for this update as part3479 * of processing the split-off update, so we3480 * don't have to do it here.3481 */3482 ret =split_symref_update(update, referent.buf, transaction,3483 affected_refnames, err);3484if(ret)3485return ret;3486}3487}else{3488struct ref_update *parent_update;34893490/*3491 * If this update is happening indirectly because of a3492 * symref update, record the old SHA-1 in the parent3493 * update:3494 */3495for(parent_update = update->parent_update;3496 parent_update;3497 parent_update = parent_update->parent_update) {3498oidcpy(&parent_update->lock->old_oid, &lock->old_oid);3499}35003501if((update->flags & REF_HAVE_OLD) &&3502hashcmp(lock->old_oid.hash, update->old_sha1)) {3503if(is_null_sha1(update->old_sha1))3504strbuf_addf(err,"cannot lock ref '%s': reference already exists",3505original_update_refname(update));3506else3507strbuf_addf(err,"cannot lock ref '%s': is at%sbut expected%s",3508original_update_refname(update),3509sha1_to_hex(lock->old_oid.hash),3510sha1_to_hex(update->old_sha1));35113512return TRANSACTION_GENERIC_ERROR;3513}3514}35153516if((update->flags & REF_HAVE_NEW) &&3517!(update->flags & REF_DELETING) &&3518!(update->flags & REF_LOG_ONLY)) {3519if(!(update->type & REF_ISSYMREF) &&3520!hashcmp(lock->old_oid.hash, update->new_sha1)) {3521/*3522 * The reference already has the desired3523 * value, so we don't need to write it.3524 */3525}else if(write_ref_to_lockfile(lock, update->new_sha1,3526 err)) {3527char*write_err =strbuf_detach(err, NULL);35283529/*3530 * The lock was freed upon failure of3531 * write_ref_to_lockfile():3532 */3533 update->lock = NULL;3534strbuf_addf(err,3535"cannot update the ref '%s':%s",3536 update->refname, write_err);3537free(write_err);3538return TRANSACTION_GENERIC_ERROR;3539}else{3540 update->flags |= REF_NEEDS_COMMIT;3541}3542}3543if(!(update->flags & REF_NEEDS_COMMIT)) {3544/*3545 * We didn't call write_ref_to_lockfile(), so3546 * the lockfile is still open. Close it to3547 * free up the file descriptor:3548 */3549if(close_ref(lock)) {3550strbuf_addf(err,"couldn't close '%s.lock'",3551 update->refname);3552return TRANSACTION_GENERIC_ERROR;3553}3554}3555return0;3556}35573558intref_transaction_commit(struct ref_transaction *transaction,3559struct strbuf *err)3560{3561int ret =0, i;3562struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3563struct string_list_item *ref_to_delete;3564struct string_list affected_refnames = STRING_LIST_INIT_NODUP;3565char*head_ref = NULL;3566int head_type;3567struct object_id head_oid;35683569assert(err);35703571if(transaction->state != REF_TRANSACTION_OPEN)3572die("BUG: commit called for transaction that is not open");35733574if(!transaction->nr) {3575 transaction->state = REF_TRANSACTION_CLOSED;3576return0;3577}35783579/*3580 * Fail if a refname appears more than once in the3581 * transaction. (If we end up splitting up any updates using3582 * split_symref_update() or split_head_update(), those3583 * functions will check that the new updates don't have the3584 * same refname as any existing ones.)3585 */3586for(i =0; i < transaction->nr; i++) {3587struct ref_update *update = transaction->updates[i];3588struct string_list_item *item =3589string_list_append(&affected_refnames, update->refname);35903591/*3592 * We store a pointer to update in item->util, but at3593 * the moment we never use the value of this field3594 * except to check whether it is non-NULL.3595 */3596 item->util = update;3597}3598string_list_sort(&affected_refnames);3599if(ref_update_reject_duplicates(&affected_refnames, err)) {3600 ret = TRANSACTION_GENERIC_ERROR;3601goto cleanup;3602}36033604/*3605 * Special hack: If a branch is updated directly and HEAD3606 * points to it (may happen on the remote side of a push3607 * for example) then logically the HEAD reflog should be3608 * updated too.3609 *3610 * A generic solution would require reverse symref lookups,3611 * but finding all symrefs pointing to a given branch would be3612 * rather costly for this rare event (the direct update of a3613 * branch) to be worth it. So let's cheat and check with HEAD3614 * only, which should cover 99% of all usage scenarios (even3615 * 100% of the default ones).3616 *3617 * So if HEAD is a symbolic reference, then record the name of3618 * the reference that it points to. If we see an update of3619 * head_ref within the transaction, then split_head_update()3620 * arranges for the reflog of HEAD to be updated, too.3621 */3622 head_ref =resolve_refdup("HEAD", RESOLVE_REF_NO_RECURSE,3623 head_oid.hash, &head_type);36243625if(head_ref && !(head_type & REF_ISSYMREF)) {3626free(head_ref);3627 head_ref = NULL;3628}36293630/*3631 * Acquire all locks, verify old values if provided, check3632 * that new values are valid, and write new values to the3633 * lockfiles, ready to be activated. Only keep one lockfile3634 * open at a time to avoid running out of file descriptors.3635 */3636for(i =0; i < transaction->nr; i++) {3637struct ref_update *update = transaction->updates[i];36383639 ret =lock_ref_for_update(update, transaction, head_ref,3640&affected_refnames, err);3641if(ret)3642goto cleanup;3643}36443645/* Perform updates first so live commits remain referenced */3646for(i =0; i < transaction->nr; i++) {3647struct ref_update *update = transaction->updates[i];3648struct ref_lock *lock = update->lock;36493650if(update->flags & REF_NEEDS_COMMIT ||3651 update->flags & REF_LOG_ONLY) {3652if(log_ref_write(lock->ref_name, lock->old_oid.hash,3653 update->new_sha1,3654 update->msg, update->flags, err)) {3655char*old_msg =strbuf_detach(err, NULL);36563657strbuf_addf(err,"cannot update the ref '%s':%s",3658 lock->ref_name, old_msg);3659free(old_msg);3660unlock_ref(lock);3661 update->lock = NULL;3662 ret = TRANSACTION_GENERIC_ERROR;3663goto cleanup;3664}3665}3666if(update->flags & REF_NEEDS_COMMIT) {3667clear_loose_ref_cache(&ref_cache);3668if(commit_ref(lock)) {3669strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3670unlock_ref(lock);3671 update->lock = NULL;3672 ret = TRANSACTION_GENERIC_ERROR;3673goto cleanup;3674}3675}3676}3677/* Perform deletes now that updates are safely completed */3678for(i =0; i < transaction->nr; i++) {3679struct ref_update *update = transaction->updates[i];36803681if(update->flags & REF_DELETING &&3682!(update->flags & REF_LOG_ONLY)) {3683if(delete_ref_loose(update->lock, update->type, err)) {3684 ret = TRANSACTION_GENERIC_ERROR;3685goto cleanup;3686}36873688if(!(update->flags & REF_ISPRUNING))3689string_list_append(&refs_to_delete,3690 update->lock->ref_name);3691}3692}36933694if(repack_without_refs(&refs_to_delete, err)) {3695 ret = TRANSACTION_GENERIC_ERROR;3696goto cleanup;3697}3698for_each_string_list_item(ref_to_delete, &refs_to_delete)3699unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3700clear_loose_ref_cache(&ref_cache);37013702cleanup:3703 transaction->state = REF_TRANSACTION_CLOSED;37043705for(i =0; i < transaction->nr; i++)3706if(transaction->updates[i]->lock)3707unlock_ref(transaction->updates[i]->lock);3708string_list_clear(&refs_to_delete,0);3709free(head_ref);3710string_list_clear(&affected_refnames,0);37113712return ret;3713}37143715static intref_present(const char*refname,3716const struct object_id *oid,int flags,void*cb_data)3717{3718struct string_list *affected_refnames = cb_data;37193720returnstring_list_has_string(affected_refnames, refname);3721}37223723intinitial_ref_transaction_commit(struct ref_transaction *transaction,3724struct strbuf *err)3725{3726int ret =0, i;3727struct string_list affected_refnames = STRING_LIST_INIT_NODUP;37283729assert(err);37303731if(transaction->state != REF_TRANSACTION_OPEN)3732die("BUG: commit called for transaction that is not open");37333734/* Fail if a refname appears more than once in the transaction: */3735for(i =0; i < transaction->nr; i++)3736string_list_append(&affected_refnames,3737 transaction->updates[i]->refname);3738string_list_sort(&affected_refnames);3739if(ref_update_reject_duplicates(&affected_refnames, err)) {3740 ret = TRANSACTION_GENERIC_ERROR;3741goto cleanup;3742}37433744/*3745 * It's really undefined to call this function in an active3746 * repository or when there are existing references: we are3747 * only locking and changing packed-refs, so (1) any3748 * simultaneous processes might try to change a reference at3749 * the same time we do, and (2) any existing loose versions of3750 * the references that we are setting would have precedence3751 * over our values. But some remote helpers create the remote3752 * "HEAD" and "master" branches before calling this function,3753 * so here we really only check that none of the references3754 * that we are creating already exists.3755 */3756if(for_each_rawref(ref_present, &affected_refnames))3757die("BUG: initial ref transaction called with existing refs");37583759for(i =0; i < transaction->nr; i++) {3760struct ref_update *update = transaction->updates[i];37613762if((update->flags & REF_HAVE_OLD) &&3763!is_null_sha1(update->old_sha1))3764die("BUG: initial ref transaction with old_sha1 set");3765if(verify_refname_available(update->refname,3766&affected_refnames, NULL,3767 err)) {3768 ret = TRANSACTION_NAME_CONFLICT;3769goto cleanup;3770}3771}37723773if(lock_packed_refs(0)) {3774strbuf_addf(err,"unable to lock packed-refs file:%s",3775strerror(errno));3776 ret = TRANSACTION_GENERIC_ERROR;3777goto cleanup;3778}37793780for(i =0; i < transaction->nr; i++) {3781struct ref_update *update = transaction->updates[i];37823783if((update->flags & REF_HAVE_NEW) &&3784!is_null_sha1(update->new_sha1))3785add_packed_ref(update->refname, update->new_sha1);3786}37873788if(commit_packed_refs()) {3789strbuf_addf(err,"unable to commit packed-refs file:%s",3790strerror(errno));3791 ret = TRANSACTION_GENERIC_ERROR;3792goto cleanup;3793}37943795cleanup:3796 transaction->state = REF_TRANSACTION_CLOSED;3797string_list_clear(&affected_refnames,0);3798return ret;3799}38003801struct expire_reflog_cb {3802unsigned int flags;3803 reflog_expiry_should_prune_fn *should_prune_fn;3804void*policy_cb;3805FILE*newlog;3806unsigned char last_kept_sha1[20];3807};38083809static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3810const char*email,unsigned long timestamp,int tz,3811const char*message,void*cb_data)3812{3813struct expire_reflog_cb *cb = cb_data;3814struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;38153816if(cb->flags & EXPIRE_REFLOGS_REWRITE)3817 osha1 = cb->last_kept_sha1;38183819if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3820 message, policy_cb)) {3821if(!cb->newlog)3822printf("would prune%s", message);3823else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3824printf("prune%s", message);3825}else{3826if(cb->newlog) {3827fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3828sha1_to_hex(osha1),sha1_to_hex(nsha1),3829 email, timestamp, tz, message);3830hashcpy(cb->last_kept_sha1, nsha1);3831}3832if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3833printf("keep%s", message);3834}3835return0;3836}38373838intreflog_expire(const char*refname,const unsigned char*sha1,3839unsigned int flags,3840 reflog_expiry_prepare_fn prepare_fn,3841 reflog_expiry_should_prune_fn should_prune_fn,3842 reflog_expiry_cleanup_fn cleanup_fn,3843void*policy_cb_data)3844{3845static struct lock_file reflog_lock;3846struct expire_reflog_cb cb;3847struct ref_lock *lock;3848char*log_file;3849int status =0;3850int type;3851struct strbuf err = STRBUF_INIT;38523853memset(&cb,0,sizeof(cb));3854 cb.flags = flags;3855 cb.policy_cb = policy_cb_data;3856 cb.should_prune_fn = should_prune_fn;38573858/*3859 * The reflog file is locked by holding the lock on the3860 * reference itself, plus we might need to update the3861 * reference if --updateref was specified:3862 */3863 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL, REF_NODEREF,3864&type, &err);3865if(!lock) {3866error("cannot lock ref '%s':%s", refname, err.buf);3867strbuf_release(&err);3868return-1;3869}3870if(!reflog_exists(refname)) {3871unlock_ref(lock);3872return0;3873}38743875 log_file =git_pathdup("logs/%s", refname);3876if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3877/*3878 * Even though holding $GIT_DIR/logs/$reflog.lock has3879 * no locking implications, we use the lock_file3880 * machinery here anyway because it does a lot of the3881 * work we need, including cleaning up if the program3882 * exits unexpectedly.3883 */3884if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3885struct strbuf err = STRBUF_INIT;3886unable_to_lock_message(log_file, errno, &err);3887error("%s", err.buf);3888strbuf_release(&err);3889goto failure;3890}3891 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3892if(!cb.newlog) {3893error("cannot fdopen%s(%s)",3894get_lock_file_path(&reflog_lock),strerror(errno));3895goto failure;3896}3897}38983899(*prepare_fn)(refname, sha1, cb.policy_cb);3900for_each_reflog_ent(refname, expire_reflog_ent, &cb);3901(*cleanup_fn)(cb.policy_cb);39023903if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3904/*3905 * It doesn't make sense to adjust a reference pointed3906 * to by a symbolic ref based on expiring entries in3907 * the symbolic reference's reflog. Nor can we update3908 * a reference if there are no remaining reflog3909 * entries.3910 */3911int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3912!(type & REF_ISSYMREF) &&3913!is_null_sha1(cb.last_kept_sha1);39143915if(close_lock_file(&reflog_lock)) {3916 status |=error("couldn't write%s:%s", log_file,3917strerror(errno));3918}else if(update &&3919(write_in_full(get_lock_file_fd(lock->lk),3920sha1_to_hex(cb.last_kept_sha1),40) !=40||3921write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3922close_ref(lock) <0)) {3923 status |=error("couldn't write%s",3924get_lock_file_path(lock->lk));3925rollback_lock_file(&reflog_lock);3926}else if(commit_lock_file(&reflog_lock)) {3927 status |=error("unable to write reflog '%s' (%s)",3928 log_file,strerror(errno));3929}else if(update &&commit_ref(lock)) {3930 status |=error("couldn't set%s", lock->ref_name);3931}3932}3933free(log_file);3934unlock_ref(lock);3935return status;39363937 failure:3938rollback_lock_file(&reflog_lock);3939free(log_file);3940unlock_ref(lock);3941return-1;3942}