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. The returned structure 958 * will be allocated and initialized but not necessarily populated; it 959 * should not be freed. 960 */ 961static struct ref_cache *get_ref_cache(const char*submodule) 962{ 963struct ref_cache *refs =lookup_ref_cache(submodule); 964if(!refs) 965 refs =create_ref_cache(submodule); 966return refs; 967} 968 969/* The length of a peeled reference line in packed-refs, including EOL: */ 970#define PEELED_LINE_LENGTH 42 971 972/* 973 * The packed-refs header line that we write out. Perhaps other 974 * traits will be added later. The trailing space is required. 975 */ 976static const char PACKED_REFS_HEADER[] = 977"# pack-refs with: peeled fully-peeled\n"; 978 979/* 980 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 981 * Return a pointer to the refname within the line (null-terminated), 982 * or NULL if there was a problem. 983 */ 984static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 985{ 986const char*ref; 987 988/* 989 * 42: the answer to everything. 990 * 991 * In this case, it happens to be the answer to 992 * 40 (length of sha1 hex representation) 993 * +1 (space in between hex and name) 994 * +1 (newline at the end of the line) 995 */ 996if(line->len <=42) 997return NULL; 998 999if(get_sha1_hex(line->buf, sha1) <0)1000return NULL;1001if(!isspace(line->buf[40]))1002return NULL;10031004 ref = line->buf +41;1005if(isspace(*ref))1006return NULL;10071008if(line->buf[line->len -1] !='\n')1009return NULL;1010 line->buf[--line->len] =0;10111012return ref;1013}10141015/*1016 * Read f, which is a packed-refs file, into dir.1017 *1018 * A comment line of the form "# pack-refs with: " may contain zero or1019 * more traits. We interpret the traits as follows:1020 *1021 * No traits:1022 *1023 * Probably no references are peeled. But if the file contains a1024 * peeled value for a reference, we will use it.1025 *1026 * peeled:1027 *1028 * References under "refs/tags/", if they *can* be peeled, *are*1029 * peeled in this file. References outside of "refs/tags/" are1030 * probably not peeled even if they could have been, but if we find1031 * a peeled value for such a reference we will use it.1032 *1033 * fully-peeled:1034 *1035 * All references in the file that can be peeled are peeled.1036 * Inversely (and this is more important), any references in the1037 * file for which no peeled value is recorded is not peelable. This1038 * trait should typically be written alongside "peeled" for1039 * compatibility with older clients, but we do not require it1040 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1041 */1042static voidread_packed_refs(FILE*f,struct ref_dir *dir)1043{1044struct ref_entry *last = NULL;1045struct strbuf line = STRBUF_INIT;1046enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10471048while(strbuf_getwholeline(&line, f,'\n') != EOF) {1049unsigned char sha1[20];1050const char*refname;1051const char*traits;10521053if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1054if(strstr(traits," fully-peeled "))1055 peeled = PEELED_FULLY;1056else if(strstr(traits," peeled "))1057 peeled = PEELED_TAGS;1058/* perhaps other traits later as well */1059continue;1060}10611062 refname =parse_ref_line(&line, sha1);1063if(refname) {1064int flag = REF_ISPACKED;10651066if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1067if(!refname_is_safe(refname))1068die("packed refname is dangerous:%s", refname);1069hashclr(sha1);1070 flag |= REF_BAD_NAME | REF_ISBROKEN;1071}1072 last =create_ref_entry(refname, sha1, flag,0);1073if(peeled == PEELED_FULLY ||1074(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1075 last->flag |= REF_KNOWS_PEELED;1076add_ref(dir, last);1077continue;1078}1079if(last &&1080 line.buf[0] =='^'&&1081 line.len == PEELED_LINE_LENGTH &&1082 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1083!get_sha1_hex(line.buf +1, sha1)) {1084hashcpy(last->u.value.peeled.hash, sha1);1085/*1086 * Regardless of what the file header said,1087 * we definitely know the value of *this*1088 * reference:1089 */1090 last->flag |= REF_KNOWS_PEELED;1091}1092}10931094strbuf_release(&line);1095}10961097/*1098 * Get the packed_ref_cache for the specified ref_cache, creating it1099 * if necessary.1100 */1101static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1102{1103char*packed_refs_file;11041105if(*refs->name)1106 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1107else1108 packed_refs_file =git_pathdup("packed-refs");11091110if(refs->packed &&1111!stat_validity_check(&refs->packed->validity, packed_refs_file))1112clear_packed_ref_cache(refs);11131114if(!refs->packed) {1115FILE*f;11161117 refs->packed =xcalloc(1,sizeof(*refs->packed));1118acquire_packed_ref_cache(refs->packed);1119 refs->packed->root =create_dir_entry(refs,"",0,0);1120 f =fopen(packed_refs_file,"r");1121if(f) {1122stat_validity_update(&refs->packed->validity,fileno(f));1123read_packed_refs(f,get_ref_dir(refs->packed->root));1124fclose(f);1125}1126}1127free(packed_refs_file);1128return refs->packed;1129}11301131static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1132{1133returnget_ref_dir(packed_ref_cache->root);1134}11351136static struct ref_dir *get_packed_refs(struct ref_cache *refs)1137{1138returnget_packed_ref_dir(get_packed_ref_cache(refs));1139}11401141/*1142 * Add a reference to the in-memory packed reference cache. This may1143 * only be called while the packed-refs file is locked (see1144 * lock_packed_refs()). To actually write the packed-refs file, call1145 * commit_packed_refs().1146 */1147static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1148{1149struct packed_ref_cache *packed_ref_cache =1150get_packed_ref_cache(&ref_cache);11511152if(!packed_ref_cache->lock)1153die("internal error: packed refs not locked");1154add_ref(get_packed_ref_dir(packed_ref_cache),1155create_ref_entry(refname, sha1, REF_ISPACKED,1));1156}11571158/*1159 * Read the loose references from the namespace dirname into dir1160 * (without recursing). dirname must end with '/'. dir must be the1161 * directory entry corresponding to dirname.1162 */1163static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1164{1165struct ref_cache *refs = dir->ref_cache;1166DIR*d;1167struct dirent *de;1168int dirnamelen =strlen(dirname);1169struct strbuf refname;1170struct strbuf path = STRBUF_INIT;1171size_t path_baselen;11721173if(*refs->name)1174strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1175else1176strbuf_git_path(&path,"%s", dirname);1177 path_baselen = path.len;11781179 d =opendir(path.buf);1180if(!d) {1181strbuf_release(&path);1182return;1183}11841185strbuf_init(&refname, dirnamelen +257);1186strbuf_add(&refname, dirname, dirnamelen);11871188while((de =readdir(d)) != NULL) {1189unsigned char sha1[20];1190struct stat st;1191int flag;11921193if(de->d_name[0] =='.')1194continue;1195if(ends_with(de->d_name,".lock"))1196continue;1197strbuf_addstr(&refname, de->d_name);1198strbuf_addstr(&path, de->d_name);1199if(stat(path.buf, &st) <0) {1200;/* silently ignore */1201}else if(S_ISDIR(st.st_mode)) {1202strbuf_addch(&refname,'/');1203add_entry_to_dir(dir,1204create_dir_entry(refs, refname.buf,1205 refname.len,1));1206}else{1207int read_ok;12081209if(*refs->name) {1210hashclr(sha1);1211 flag =0;1212 read_ok = !resolve_gitlink_ref(refs->name,1213 refname.buf, sha1);1214}else{1215 read_ok = !read_ref_full(refname.buf,1216 RESOLVE_REF_READING,1217 sha1, &flag);1218}12191220if(!read_ok) {1221hashclr(sha1);1222 flag |= REF_ISBROKEN;1223}else if(is_null_sha1(sha1)) {1224/*1225 * It is so astronomically unlikely1226 * that NULL_SHA1 is the SHA-1 of an1227 * actual object that we consider its1228 * appearance in a loose reference1229 * file to be repo corruption1230 * (probably due to a software bug).1231 */1232 flag |= REF_ISBROKEN;1233}12341235if(check_refname_format(refname.buf,1236 REFNAME_ALLOW_ONELEVEL)) {1237if(!refname_is_safe(refname.buf))1238die("loose refname is dangerous:%s", refname.buf);1239hashclr(sha1);1240 flag |= REF_BAD_NAME | REF_ISBROKEN;1241}1242add_entry_to_dir(dir,1243create_ref_entry(refname.buf, sha1, flag,0));1244}1245strbuf_setlen(&refname, dirnamelen);1246strbuf_setlen(&path, path_baselen);1247}1248strbuf_release(&refname);1249strbuf_release(&path);1250closedir(d);1251}12521253static struct ref_dir *get_loose_refs(struct ref_cache *refs)1254{1255if(!refs->loose) {1256/*1257 * Mark the top-level directory complete because we1258 * are about to read the only subdirectory that can1259 * hold references:1260 */1261 refs->loose =create_dir_entry(refs,"",0,0);1262/*1263 * Create an incomplete entry for "refs/":1264 */1265add_entry_to_dir(get_ref_dir(refs->loose),1266create_dir_entry(refs,"refs/",5,1));1267}1268returnget_ref_dir(refs->loose);1269}12701271#define MAXREFLEN (1024)12721273/*1274 * Called by resolve_gitlink_ref_recursive() after it failed to read1275 * from the loose refs in ref_cache refs. Find <refname> in the1276 * packed-refs file for the submodule.1277 */1278static intresolve_gitlink_packed_ref(struct ref_cache *refs,1279const char*refname,unsigned char*sha1)1280{1281struct ref_entry *ref;1282struct ref_dir *dir =get_packed_refs(refs);12831284 ref =find_ref(dir, refname);1285if(ref == NULL)1286return-1;12871288hashcpy(sha1, ref->u.value.oid.hash);1289return0;1290}12911292static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1293const char*refname,unsigned char*sha1,1294int recursion)1295{1296int fd, len;1297char buffer[128], *p;1298char*path;12991300if(recursion > SYMREF_MAXDEPTH ||strlen(refname) > MAXREFLEN)1301return-1;1302 path = *refs->name1303?git_pathdup_submodule(refs->name,"%s", refname)1304:git_pathdup("%s", refname);1305 fd =open(path, O_RDONLY);1306free(path);1307if(fd <0)1308returnresolve_gitlink_packed_ref(refs, refname, sha1);13091310 len =read(fd, buffer,sizeof(buffer)-1);1311close(fd);1312if(len <0)1313return-1;1314while(len &&isspace(buffer[len-1]))1315 len--;1316 buffer[len] =0;13171318/* Was it a detached head or an old-fashioned symlink? */1319if(!get_sha1_hex(buffer, sha1))1320return0;13211322/* Symref? */1323if(strncmp(buffer,"ref:",4))1324return-1;1325 p = buffer +4;1326while(isspace(*p))1327 p++;13281329returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1330}13311332intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1333{1334int len =strlen(path), retval;1335struct strbuf submodule = STRBUF_INIT;1336struct ref_cache *refs;13371338while(len && path[len-1] =='/')1339 len--;1340if(!len)1341return-1;13421343strbuf_add(&submodule, path, len);1344 refs =lookup_ref_cache(submodule.buf);1345if(!refs) {1346if(!is_nonbare_repository_dir(&submodule)) {1347strbuf_release(&submodule);1348return-1;1349}1350 refs =create_ref_cache(submodule.buf);1351}1352strbuf_release(&submodule);13531354 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1355return retval;1356}13571358/*1359 * Return the ref_entry for the given refname from the packed1360 * references. If it does not exist, return NULL.1361 */1362static struct ref_entry *get_packed_ref(const char*refname)1363{1364returnfind_ref(get_packed_refs(&ref_cache), refname);1365}13661367/*1368 * A loose ref file doesn't exist; check for a packed ref.1369 */1370static intresolve_missing_loose_ref(const char*refname,1371unsigned char*sha1,1372unsigned int*flags)1373{1374struct ref_entry *entry;13751376/*1377 * The loose reference file does not exist; check for a packed1378 * reference.1379 */1380 entry =get_packed_ref(refname);1381if(entry) {1382hashcpy(sha1, entry->u.value.oid.hash);1383*flags |= REF_ISPACKED;1384return0;1385}1386/* refname is not a packed reference. */1387return-1;1388}13891390intread_raw_ref(const char*refname,unsigned char*sha1,1391struct strbuf *referent,unsigned int*type)1392{1393struct strbuf sb_contents = STRBUF_INIT;1394struct strbuf sb_path = STRBUF_INIT;1395const char*path;1396const char*buf;1397struct stat st;1398int fd;1399int ret = -1;1400int save_errno;14011402*type =0;1403strbuf_reset(&sb_path);1404strbuf_git_path(&sb_path,"%s", refname);1405 path = sb_path.buf;14061407stat_ref:1408/*1409 * We might have to loop back here to avoid a race1410 * condition: first we lstat() the file, then we try1411 * to read it as a link or as a file. But if somebody1412 * changes the type of the file (file <-> directory1413 * <-> symlink) between the lstat() and reading, then1414 * we don't want to report that as an error but rather1415 * try again starting with the lstat().1416 */14171418if(lstat(path, &st) <0) {1419if(errno != ENOENT)1420goto out;1421if(resolve_missing_loose_ref(refname, sha1, type)) {1422 errno = ENOENT;1423goto out;1424}1425 ret =0;1426goto out;1427}14281429/* Follow "normalized" - ie "refs/.." symlinks by hand */1430if(S_ISLNK(st.st_mode)) {1431strbuf_reset(&sb_contents);1432if(strbuf_readlink(&sb_contents, path,0) <0) {1433if(errno == ENOENT || errno == EINVAL)1434/* inconsistent with lstat; retry */1435goto stat_ref;1436else1437goto out;1438}1439if(starts_with(sb_contents.buf,"refs/") &&1440!check_refname_format(sb_contents.buf,0)) {1441strbuf_swap(&sb_contents, referent);1442*type |= REF_ISSYMREF;1443 ret =0;1444goto out;1445}1446}14471448/* Is it a directory? */1449if(S_ISDIR(st.st_mode)) {1450/*1451 * Even though there is a directory where the loose1452 * ref is supposed to be, there could still be a1453 * packed ref:1454 */1455if(resolve_missing_loose_ref(refname, sha1, type)) {1456 errno = EISDIR;1457goto out;1458}1459 ret =0;1460goto out;1461}14621463/*1464 * Anything else, just open it and try to use it as1465 * a ref1466 */1467 fd =open(path, O_RDONLY);1468if(fd <0) {1469if(errno == ENOENT)1470/* inconsistent with lstat; retry */1471goto stat_ref;1472else1473goto out;1474}1475strbuf_reset(&sb_contents);1476if(strbuf_read(&sb_contents, fd,256) <0) {1477int save_errno = errno;1478close(fd);1479 errno = save_errno;1480goto out;1481}1482close(fd);1483strbuf_rtrim(&sb_contents);1484 buf = sb_contents.buf;1485if(starts_with(buf,"ref:")) {1486 buf +=4;1487while(isspace(*buf))1488 buf++;14891490strbuf_reset(referent);1491strbuf_addstr(referent, buf);1492*type |= REF_ISSYMREF;1493 ret =0;1494goto out;1495}14961497/*1498 * Please note that FETCH_HEAD has additional1499 * data after the sha.1500 */1501if(get_sha1_hex(buf, sha1) ||1502(buf[40] !='\0'&& !isspace(buf[40]))) {1503*type |= REF_ISBROKEN;1504 errno = EINVAL;1505goto out;1506}15071508 ret =0;15091510out:1511 save_errno = errno;1512strbuf_release(&sb_path);1513strbuf_release(&sb_contents);1514 errno = save_errno;1515return ret;1516}15171518static voidunlock_ref(struct ref_lock *lock)1519{1520/* Do not free lock->lk -- atexit() still looks at them */1521if(lock->lk)1522rollback_lock_file(lock->lk);1523free(lock->ref_name);1524free(lock);1525}15261527/*1528 * Lock refname, without following symrefs, and set *lock_p to point1529 * at a newly-allocated lock object. Fill in lock->old_oid, referent,1530 * and type similarly to read_raw_ref().1531 *1532 * The caller must verify that refname is a "safe" reference name (in1533 * the sense of refname_is_safe()) before calling this function.1534 *1535 * If the reference doesn't already exist, verify that refname doesn't1536 * have a D/F conflict with any existing references. extras and skip1537 * are passed to verify_refname_available_dir() for this check.1538 *1539 * If mustexist is not set and the reference is not found or is1540 * broken, lock the reference anyway but clear sha1.1541 *1542 * Return 0 on success. On failure, write an error message to err and1543 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.1544 *1545 * Implementation note: This function is basically1546 *1547 * lock reference1548 * read_raw_ref()1549 *1550 * but it includes a lot more code to1551 * - Deal with possible races with other processes1552 * - Avoid calling verify_refname_available_dir() when it can be1553 * avoided, namely if we were successfully able to read the ref1554 * - Generate informative error messages in the case of failure1555 */1556static intlock_raw_ref(const char*refname,int mustexist,1557const struct string_list *extras,1558const struct string_list *skip,1559struct ref_lock **lock_p,1560struct strbuf *referent,1561unsigned int*type,1562struct strbuf *err)1563{1564struct ref_lock *lock;1565struct strbuf ref_file = STRBUF_INIT;1566int attempts_remaining =3;1567int ret = TRANSACTION_GENERIC_ERROR;15681569assert(err);1570*type =0;15711572/* First lock the file so it can't change out from under us. */15731574*lock_p = lock =xcalloc(1,sizeof(*lock));15751576 lock->ref_name =xstrdup(refname);1577strbuf_git_path(&ref_file,"%s", refname);15781579retry:1580switch(safe_create_leading_directories(ref_file.buf)) {1581case SCLD_OK:1582break;/* success */1583case SCLD_EXISTS:1584/*1585 * Suppose refname is "refs/foo/bar". We just failed1586 * to create the containing directory, "refs/foo",1587 * because there was a non-directory in the way. This1588 * indicates a D/F conflict, probably because of1589 * another reference such as "refs/foo". There is no1590 * reason to expect this error to be transitory.1591 */1592if(verify_refname_available(refname, extras, skip, err)) {1593if(mustexist) {1594/*1595 * To the user the relevant error is1596 * that the "mustexist" reference is1597 * missing:1598 */1599strbuf_reset(err);1600strbuf_addf(err,"unable to resolve reference '%s'",1601 refname);1602}else{1603/*1604 * The error message set by1605 * verify_refname_available_dir() is OK.1606 */1607 ret = TRANSACTION_NAME_CONFLICT;1608}1609}else{1610/*1611 * The file that is in the way isn't a loose1612 * reference. Report it as a low-level1613 * failure.1614 */1615strbuf_addf(err,"unable to create lock file%s.lock; "1616"non-directory in the way",1617 ref_file.buf);1618}1619goto error_return;1620case SCLD_VANISHED:1621/* Maybe another process was tidying up. Try again. */1622if(--attempts_remaining >0)1623goto retry;1624/* fall through */1625default:1626strbuf_addf(err,"unable to create directory for%s",1627 ref_file.buf);1628goto error_return;1629}16301631if(!lock->lk)1632 lock->lk =xcalloc(1,sizeof(struct lock_file));16331634if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) {1635if(errno == ENOENT && --attempts_remaining >0) {1636/*1637 * Maybe somebody just deleted one of the1638 * directories leading to ref_file. Try1639 * again:1640 */1641goto retry;1642}else{1643unable_to_lock_message(ref_file.buf, errno, err);1644goto error_return;1645}1646}16471648/*1649 * Now we hold the lock and can read the reference without1650 * fear that its value will change.1651 */16521653if(read_raw_ref(refname, lock->old_oid.hash, referent, type)) {1654if(errno == ENOENT) {1655if(mustexist) {1656/* Garden variety missing reference. */1657strbuf_addf(err,"unable to resolve reference '%s'",1658 refname);1659goto error_return;1660}else{1661/*1662 * Reference is missing, but that's OK. We1663 * know that there is not a conflict with1664 * another loose reference because1665 * (supposing that we are trying to lock1666 * reference "refs/foo/bar"):1667 *1668 * - We were successfully able to create1669 * the lockfile refs/foo/bar.lock, so we1670 * know there cannot be a loose reference1671 * named "refs/foo".1672 *1673 * - We got ENOENT and not EISDIR, so we1674 * know that there cannot be a loose1675 * reference named "refs/foo/bar/baz".1676 */1677}1678}else if(errno == EISDIR) {1679/*1680 * There is a directory in the way. It might have1681 * contained references that have been deleted. If1682 * we don't require that the reference already1683 * exists, try to remove the directory so that it1684 * doesn't cause trouble when we want to rename the1685 * lockfile into place later.1686 */1687if(mustexist) {1688/* Garden variety missing reference. */1689strbuf_addf(err,"unable to resolve reference '%s'",1690 refname);1691goto error_return;1692}else if(remove_dir_recursively(&ref_file,1693 REMOVE_DIR_EMPTY_ONLY)) {1694if(verify_refname_available_dir(1695 refname, extras, skip,1696get_loose_refs(&ref_cache),1697 err)) {1698/*1699 * The error message set by1700 * verify_refname_available() is OK.1701 */1702 ret = TRANSACTION_NAME_CONFLICT;1703goto error_return;1704}else{1705/*1706 * We can't delete the directory,1707 * but we also don't know of any1708 * references that it should1709 * contain.1710 */1711strbuf_addf(err,"there is a non-empty directory '%s' "1712"blocking reference '%s'",1713 ref_file.buf, refname);1714goto error_return;1715}1716}1717}else if(errno == EINVAL && (*type & REF_ISBROKEN)) {1718strbuf_addf(err,"unable to resolve reference '%s': "1719"reference broken", refname);1720goto error_return;1721}else{1722strbuf_addf(err,"unable to resolve reference '%s':%s",1723 refname,strerror(errno));1724goto error_return;1725}17261727/*1728 * If the ref did not exist and we are creating it,1729 * make sure there is no existing packed ref whose1730 * name begins with our refname, nor a packed ref1731 * whose name is a proper prefix of our refname.1732 */1733if(verify_refname_available_dir(1734 refname, extras, skip,1735get_packed_refs(&ref_cache),1736 err)) {1737goto error_return;1738}1739}17401741 ret =0;1742goto out;17431744error_return:1745unlock_ref(lock);1746*lock_p = NULL;17471748out:1749strbuf_release(&ref_file);1750return ret;1751}17521753/*1754 * Peel the entry (if possible) and return its new peel_status. If1755 * repeel is true, re-peel the entry even if there is an old peeled1756 * value that is already stored in it.1757 *1758 * It is OK to call this function with a packed reference entry that1759 * might be stale and might even refer to an object that has since1760 * been garbage-collected. In such a case, if the entry has1761 * REF_KNOWS_PEELED then leave the status unchanged and return1762 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1763 */1764static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1765{1766enum peel_status status;17671768if(entry->flag & REF_KNOWS_PEELED) {1769if(repeel) {1770 entry->flag &= ~REF_KNOWS_PEELED;1771oidclr(&entry->u.value.peeled);1772}else{1773returnis_null_oid(&entry->u.value.peeled) ?1774 PEEL_NON_TAG : PEEL_PEELED;1775}1776}1777if(entry->flag & REF_ISBROKEN)1778return PEEL_BROKEN;1779if(entry->flag & REF_ISSYMREF)1780return PEEL_IS_SYMREF;17811782 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1783if(status == PEEL_PEELED || status == PEEL_NON_TAG)1784 entry->flag |= REF_KNOWS_PEELED;1785return status;1786}17871788intpeel_ref(const char*refname,unsigned char*sha1)1789{1790int flag;1791unsigned char base[20];17921793if(current_ref && (current_ref->name == refname1794|| !strcmp(current_ref->name, refname))) {1795if(peel_entry(current_ref,0))1796return-1;1797hashcpy(sha1, current_ref->u.value.peeled.hash);1798return0;1799}18001801if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1802return-1;18031804/*1805 * If the reference is packed, read its ref_entry from the1806 * cache in the hope that we already know its peeled value.1807 * We only try this optimization on packed references because1808 * (a) forcing the filling of the loose reference cache could1809 * be expensive and (b) loose references anyway usually do not1810 * have REF_KNOWS_PEELED.1811 */1812if(flag & REF_ISPACKED) {1813struct ref_entry *r =get_packed_ref(refname);1814if(r) {1815if(peel_entry(r,0))1816return-1;1817hashcpy(sha1, r->u.value.peeled.hash);1818return0;1819}1820}18211822returnpeel_object(base, sha1);1823}18241825/*1826 * Call fn for each reference in the specified ref_cache, omitting1827 * references not in the containing_dir of prefix. Call fn for all1828 * references, including broken ones. If fn ever returns a non-zero1829 * value, stop the iteration and return that value; otherwise, return1830 * 0.1831 */1832static intdo_for_each_entry(struct ref_cache *refs,const char*prefix,1833 each_ref_entry_fn fn,void*cb_data)1834{1835struct packed_ref_cache *packed_ref_cache;1836struct ref_dir *loose_dir;1837struct ref_dir *packed_dir;1838int retval =0;18391840/*1841 * We must make sure that all loose refs are read before accessing the1842 * packed-refs file; this avoids a race condition in which loose refs1843 * are migrated to the packed-refs file by a simultaneous process, but1844 * our in-memory view is from before the migration. get_packed_ref_cache()1845 * takes care of making sure our view is up to date with what is on1846 * disk.1847 */1848 loose_dir =get_loose_refs(refs);1849if(prefix && *prefix) {1850 loose_dir =find_containing_dir(loose_dir, prefix,0);1851}1852if(loose_dir)1853prime_ref_dir(loose_dir);18541855 packed_ref_cache =get_packed_ref_cache(refs);1856acquire_packed_ref_cache(packed_ref_cache);1857 packed_dir =get_packed_ref_dir(packed_ref_cache);1858if(prefix && *prefix) {1859 packed_dir =find_containing_dir(packed_dir, prefix,0);1860}18611862if(packed_dir && loose_dir) {1863sort_ref_dir(packed_dir);1864sort_ref_dir(loose_dir);1865 retval =do_for_each_entry_in_dirs(1866 packed_dir, loose_dir, fn, cb_data);1867}else if(packed_dir) {1868sort_ref_dir(packed_dir);1869 retval =do_for_each_entry_in_dir(1870 packed_dir,0, fn, cb_data);1871}else if(loose_dir) {1872sort_ref_dir(loose_dir);1873 retval =do_for_each_entry_in_dir(1874 loose_dir,0, fn, cb_data);1875}18761877release_packed_ref_cache(packed_ref_cache);1878return retval;1879}18801881intdo_for_each_ref(const char*submodule,const char*prefix,1882 each_ref_fn fn,int trim,int flags,void*cb_data)1883{1884struct ref_entry_cb data;1885struct ref_cache *refs;18861887 refs =get_ref_cache(submodule);1888 data.prefix = prefix;1889 data.trim = trim;1890 data.flags = flags;1891 data.fn = fn;1892 data.cb_data = cb_data;18931894if(ref_paranoia <0)1895 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1896if(ref_paranoia)1897 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;18981899returndo_for_each_entry(refs, prefix, do_one_ref, &data);1900}19011902/*1903 * Verify that the reference locked by lock has the value old_sha1.1904 * Fail if the reference doesn't exist and mustexist is set. Return 01905 * on success. On error, write an error message to err, set errno, and1906 * return a negative value.1907 */1908static intverify_lock(struct ref_lock *lock,1909const unsigned char*old_sha1,int mustexist,1910struct strbuf *err)1911{1912assert(err);19131914if(read_ref_full(lock->ref_name,1915 mustexist ? RESOLVE_REF_READING :0,1916 lock->old_oid.hash, NULL)) {1917if(old_sha1) {1918int save_errno = errno;1919strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1920 errno = save_errno;1921return-1;1922}else{1923hashclr(lock->old_oid.hash);1924return0;1925}1926}1927if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1928strbuf_addf(err,"ref '%s' is at%sbut expected%s",1929 lock->ref_name,1930sha1_to_hex(lock->old_oid.hash),1931sha1_to_hex(old_sha1));1932 errno = EBUSY;1933return-1;1934}1935return0;1936}19371938static intremove_empty_directories(struct strbuf *path)1939{1940/*1941 * we want to create a file but there is a directory there;1942 * if that is an empty directory (or a directory that contains1943 * only empty directories), remove them.1944 */1945returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1946}19471948/*1949 * Locks a ref returning the lock on success and NULL on failure.1950 * On failure errno is set to something meaningful.1951 */1952static struct ref_lock *lock_ref_sha1_basic(const char*refname,1953const unsigned char*old_sha1,1954const struct string_list *extras,1955const struct string_list *skip,1956unsigned int flags,int*type,1957struct strbuf *err)1958{1959struct strbuf ref_file = STRBUF_INIT;1960struct ref_lock *lock;1961int last_errno =0;1962int lflags = LOCK_NO_DEREF;1963int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1964int resolve_flags = RESOLVE_REF_NO_RECURSE;1965int attempts_remaining =3;1966int resolved;19671968assert(err);19691970 lock =xcalloc(1,sizeof(struct ref_lock));19711972if(mustexist)1973 resolve_flags |= RESOLVE_REF_READING;1974if(flags & REF_DELETING)1975 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;19761977strbuf_git_path(&ref_file,"%s", refname);1978 resolved = !!resolve_ref_unsafe(refname, resolve_flags,1979 lock->old_oid.hash, type);1980if(!resolved && errno == EISDIR) {1981/*1982 * we are trying to lock foo but we used to1983 * have foo/bar which now does not exist;1984 * it is normal for the empty directory 'foo'1985 * to remain.1986 */1987if(remove_empty_directories(&ref_file)) {1988 last_errno = errno;1989if(!verify_refname_available_dir(refname, extras, skip,1990get_loose_refs(&ref_cache), err))1991strbuf_addf(err,"there are still refs under '%s'",1992 refname);1993goto error_return;1994}1995 resolved = !!resolve_ref_unsafe(refname, resolve_flags,1996 lock->old_oid.hash, type);1997}1998if(!resolved) {1999 last_errno = errno;2000if(last_errno != ENOTDIR ||2001!verify_refname_available_dir(refname, extras, skip,2002get_loose_refs(&ref_cache), err))2003strbuf_addf(err,"unable to resolve reference '%s':%s",2004 refname,strerror(last_errno));20052006goto error_return;2007}20082009/*2010 * If the ref did not exist and we are creating it, make sure2011 * there is no existing packed ref whose name begins with our2012 * refname, nor a packed ref whose name is a proper prefix of2013 * our refname.2014 */2015if(is_null_oid(&lock->old_oid) &&2016verify_refname_available_dir(refname, extras, skip,2017get_packed_refs(&ref_cache), err)) {2018 last_errno = ENOTDIR;2019goto error_return;2020}20212022 lock->lk =xcalloc(1,sizeof(struct lock_file));20232024 lock->ref_name =xstrdup(refname);20252026 retry:2027switch(safe_create_leading_directories_const(ref_file.buf)) {2028case SCLD_OK:2029break;/* success */2030case SCLD_VANISHED:2031if(--attempts_remaining >0)2032goto retry;2033/* fall through */2034default:2035 last_errno = errno;2036strbuf_addf(err,"unable to create directory for '%s'",2037 ref_file.buf);2038goto error_return;2039}20402041if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2042 last_errno = errno;2043if(errno == ENOENT && --attempts_remaining >0)2044/*2045 * Maybe somebody just deleted one of the2046 * directories leading to ref_file. Try2047 * again:2048 */2049goto retry;2050else{2051unable_to_lock_message(ref_file.buf, errno, err);2052goto error_return;2053}2054}2055if(verify_lock(lock, old_sha1, mustexist, err)) {2056 last_errno = errno;2057goto error_return;2058}2059goto out;20602061 error_return:2062unlock_ref(lock);2063 lock = NULL;20642065 out:2066strbuf_release(&ref_file);2067 errno = last_errno;2068return lock;2069}20702071/*2072 * Write an entry to the packed-refs file for the specified refname.2073 * If peeled is non-NULL, write it as the entry's peeled value.2074 */2075static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2076unsigned char*peeled)2077{2078fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2079if(peeled)2080fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2081}20822083/*2084 * An each_ref_entry_fn that writes the entry to a packed-refs file.2085 */2086static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2087{2088enum peel_status peel_status =peel_entry(entry,0);20892090if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2091error("internal error:%sis not a valid packed reference!",2092 entry->name);2093write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2094 peel_status == PEEL_PEELED ?2095 entry->u.value.peeled.hash : NULL);2096return0;2097}20982099/*2100 * Lock the packed-refs file for writing. Flags is passed to2101 * hold_lock_file_for_update(). Return 0 on success. On errors, set2102 * errno appropriately and return a nonzero value.2103 */2104static intlock_packed_refs(int flags)2105{2106static int timeout_configured =0;2107static int timeout_value =1000;21082109struct packed_ref_cache *packed_ref_cache;21102111if(!timeout_configured) {2112git_config_get_int("core.packedrefstimeout", &timeout_value);2113 timeout_configured =1;2114}21152116if(hold_lock_file_for_update_timeout(2117&packlock,git_path("packed-refs"),2118 flags, timeout_value) <0)2119return-1;2120/*2121 * Get the current packed-refs while holding the lock. If the2122 * packed-refs file has been modified since we last read it,2123 * this will automatically invalidate the cache and re-read2124 * the packed-refs file.2125 */2126 packed_ref_cache =get_packed_ref_cache(&ref_cache);2127 packed_ref_cache->lock = &packlock;2128/* Increment the reference count to prevent it from being freed: */2129acquire_packed_ref_cache(packed_ref_cache);2130return0;2131}21322133/*2134 * Write the current version of the packed refs cache from memory to2135 * disk. The packed-refs file must already be locked for writing (see2136 * lock_packed_refs()). Return zero on success. On errors, set errno2137 * and return a nonzero value2138 */2139static intcommit_packed_refs(void)2140{2141struct packed_ref_cache *packed_ref_cache =2142get_packed_ref_cache(&ref_cache);2143int error =0;2144int save_errno =0;2145FILE*out;21462147if(!packed_ref_cache->lock)2148die("internal error: packed-refs not locked");21492150 out =fdopen_lock_file(packed_ref_cache->lock,"w");2151if(!out)2152die_errno("unable to fdopen packed-refs descriptor");21532154fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2155do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),21560, write_packed_entry_fn, out);21572158if(commit_lock_file(packed_ref_cache->lock)) {2159 save_errno = errno;2160 error = -1;2161}2162 packed_ref_cache->lock = NULL;2163release_packed_ref_cache(packed_ref_cache);2164 errno = save_errno;2165return error;2166}21672168/*2169 * Rollback the lockfile for the packed-refs file, and discard the2170 * in-memory packed reference cache. (The packed-refs file will be2171 * read anew if it is needed again after this function is called.)2172 */2173static voidrollback_packed_refs(void)2174{2175struct packed_ref_cache *packed_ref_cache =2176get_packed_ref_cache(&ref_cache);21772178if(!packed_ref_cache->lock)2179die("internal error: packed-refs not locked");2180rollback_lock_file(packed_ref_cache->lock);2181 packed_ref_cache->lock = NULL;2182release_packed_ref_cache(packed_ref_cache);2183clear_packed_ref_cache(&ref_cache);2184}21852186struct ref_to_prune {2187struct ref_to_prune *next;2188unsigned char sha1[20];2189char name[FLEX_ARRAY];2190};21912192struct pack_refs_cb_data {2193unsigned int flags;2194struct ref_dir *packed_refs;2195struct ref_to_prune *ref_to_prune;2196};21972198/*2199 * An each_ref_entry_fn that is run over loose references only. If2200 * the loose reference can be packed, add an entry in the packed ref2201 * cache. If the reference should be pruned, also add it to2202 * ref_to_prune in the pack_refs_cb_data.2203 */2204static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2205{2206struct pack_refs_cb_data *cb = cb_data;2207enum peel_status peel_status;2208struct ref_entry *packed_entry;2209int is_tag_ref =starts_with(entry->name,"refs/tags/");22102211/* Do not pack per-worktree refs: */2212if(ref_type(entry->name) != REF_TYPE_NORMAL)2213return0;22142215/* ALWAYS pack tags */2216if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2217return0;22182219/* Do not pack symbolic or broken refs: */2220if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2221return0;22222223/* Add a packed ref cache entry equivalent to the loose entry. */2224 peel_status =peel_entry(entry,1);2225if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2226die("internal error peeling reference%s(%s)",2227 entry->name,oid_to_hex(&entry->u.value.oid));2228 packed_entry =find_ref(cb->packed_refs, entry->name);2229if(packed_entry) {2230/* Overwrite existing packed entry with info from loose entry */2231 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2232oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2233}else{2234 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2235 REF_ISPACKED | REF_KNOWS_PEELED,0);2236add_ref(cb->packed_refs, packed_entry);2237}2238oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);22392240/* Schedule the loose reference for pruning if requested. */2241if((cb->flags & PACK_REFS_PRUNE)) {2242struct ref_to_prune *n;2243FLEX_ALLOC_STR(n, name, entry->name);2244hashcpy(n->sha1, entry->u.value.oid.hash);2245 n->next = cb->ref_to_prune;2246 cb->ref_to_prune = n;2247}2248return0;2249}22502251/*2252 * Remove empty parents, but spare refs/ and immediate subdirs.2253 * Note: munges *name.2254 */2255static voidtry_remove_empty_parents(char*name)2256{2257char*p, *q;2258int i;2259 p = name;2260for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2261while(*p && *p !='/')2262 p++;2263/* tolerate duplicate slashes; see check_refname_format() */2264while(*p =='/')2265 p++;2266}2267for(q = p; *q; q++)2268;2269while(1) {2270while(q > p && *q !='/')2271 q--;2272while(q > p && *(q-1) =='/')2273 q--;2274if(q == p)2275break;2276*q ='\0';2277if(rmdir(git_path("%s", name)))2278break;2279}2280}22812282/* make sure nobody touched the ref, and unlink */2283static voidprune_ref(struct ref_to_prune *r)2284{2285struct ref_transaction *transaction;2286struct strbuf err = STRBUF_INIT;22872288if(check_refname_format(r->name,0))2289return;22902291 transaction =ref_transaction_begin(&err);2292if(!transaction ||2293ref_transaction_delete(transaction, r->name, r->sha1,2294 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||2295ref_transaction_commit(transaction, &err)) {2296ref_transaction_free(transaction);2297error("%s", err.buf);2298strbuf_release(&err);2299return;2300}2301ref_transaction_free(transaction);2302strbuf_release(&err);2303try_remove_empty_parents(r->name);2304}23052306static voidprune_refs(struct ref_to_prune *r)2307{2308while(r) {2309prune_ref(r);2310 r = r->next;2311}2312}23132314intpack_refs(unsigned int flags)2315{2316struct pack_refs_cb_data cbdata;23172318memset(&cbdata,0,sizeof(cbdata));2319 cbdata.flags = flags;23202321lock_packed_refs(LOCK_DIE_ON_ERROR);2322 cbdata.packed_refs =get_packed_refs(&ref_cache);23232324do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2325 pack_if_possible_fn, &cbdata);23262327if(commit_packed_refs())2328die_errno("unable to overwrite old ref-pack file");23292330prune_refs(cbdata.ref_to_prune);2331return0;2332}23332334/*2335 * Rewrite the packed-refs file, omitting any refs listed in2336 * 'refnames'. On error, leave packed-refs unchanged, write an error2337 * message to 'err', and return a nonzero value.2338 *2339 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2340 */2341static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2342{2343struct ref_dir *packed;2344struct string_list_item *refname;2345int ret, needs_repacking =0, removed =0;23462347assert(err);23482349/* Look for a packed ref */2350for_each_string_list_item(refname, refnames) {2351if(get_packed_ref(refname->string)) {2352 needs_repacking =1;2353break;2354}2355}23562357/* Avoid locking if we have nothing to do */2358if(!needs_repacking)2359return0;/* no refname exists in packed refs */23602361if(lock_packed_refs(0)) {2362unable_to_lock_message(git_path("packed-refs"), errno, err);2363return-1;2364}2365 packed =get_packed_refs(&ref_cache);23662367/* Remove refnames from the cache */2368for_each_string_list_item(refname, refnames)2369if(remove_entry(packed, refname->string) != -1)2370 removed =1;2371if(!removed) {2372/*2373 * All packed entries disappeared while we were2374 * acquiring the lock.2375 */2376rollback_packed_refs();2377return0;2378}23792380/* Write what remains */2381 ret =commit_packed_refs();2382if(ret)2383strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2384strerror(errno));2385return ret;2386}23872388static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2389{2390assert(err);23912392if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2393/*2394 * loose. The loose file name is the same as the2395 * lockfile name, minus ".lock":2396 */2397char*loose_filename =get_locked_file_path(lock->lk);2398int res =unlink_or_msg(loose_filename, err);2399free(loose_filename);2400if(res)2401return1;2402}2403return0;2404}24052406intdelete_refs(struct string_list *refnames,unsigned int flags)2407{2408struct strbuf err = STRBUF_INIT;2409int i, result =0;24102411if(!refnames->nr)2412return0;24132414 result =repack_without_refs(refnames, &err);2415if(result) {2416/*2417 * If we failed to rewrite the packed-refs file, then2418 * it is unsafe to try to remove loose refs, because2419 * doing so might expose an obsolete packed value for2420 * a reference that might even point at an object that2421 * has been garbage collected.2422 */2423if(refnames->nr ==1)2424error(_("could not delete reference%s:%s"),2425 refnames->items[0].string, err.buf);2426else2427error(_("could not delete references:%s"), err.buf);24282429goto out;2430}24312432for(i =0; i < refnames->nr; i++) {2433const char*refname = refnames->items[i].string;24342435if(delete_ref(refname, NULL, flags))2436 result |=error(_("could not remove reference%s"), refname);2437}24382439out:2440strbuf_release(&err);2441return result;2442}24432444/*2445 * People using contrib's git-new-workdir have .git/logs/refs ->2446 * /some/other/path/.git/logs/refs, and that may live on another device.2447 *2448 * IOW, to avoid cross device rename errors, the temporary renamed log must2449 * live into logs/refs.2450 */2451#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"24522453static intrename_tmp_log(const char*newrefname)2454{2455int attempts_remaining =4;2456struct strbuf path = STRBUF_INIT;2457int ret = -1;24582459 retry:2460strbuf_reset(&path);2461strbuf_git_path(&path,"logs/%s", newrefname);2462switch(safe_create_leading_directories_const(path.buf)) {2463case SCLD_OK:2464break;/* success */2465case SCLD_VANISHED:2466if(--attempts_remaining >0)2467goto retry;2468/* fall through */2469default:2470error("unable to create directory for%s", newrefname);2471goto out;2472}24732474if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2475if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2476/*2477 * rename(a, b) when b is an existing2478 * directory ought to result in ISDIR, but2479 * Solaris 5.8 gives ENOTDIR. Sheesh.2480 */2481if(remove_empty_directories(&path)) {2482error("Directory not empty: logs/%s", newrefname);2483goto out;2484}2485goto retry;2486}else if(errno == ENOENT && --attempts_remaining >0) {2487/*2488 * Maybe another process just deleted one of2489 * the directories in the path to newrefname.2490 * Try again from the beginning.2491 */2492goto retry;2493}else{2494error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2495 newrefname,strerror(errno));2496goto out;2497}2498}2499 ret =0;2500out:2501strbuf_release(&path);2502return ret;2503}25042505intverify_refname_available(const char*newname,2506const struct string_list *extras,2507const struct string_list *skip,2508struct strbuf *err)2509{2510struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2511struct ref_dir *loose_refs =get_loose_refs(&ref_cache);25122513if(verify_refname_available_dir(newname, extras, skip,2514 packed_refs, err) ||2515verify_refname_available_dir(newname, extras, skip,2516 loose_refs, err))2517return-1;25182519return0;2520}25212522static intwrite_ref_to_lockfile(struct ref_lock *lock,2523const unsigned char*sha1,struct strbuf *err);2524static intcommit_ref_update(struct ref_lock *lock,2525const unsigned char*sha1,const char*logmsg,2526struct strbuf *err);25272528intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2529{2530unsigned char sha1[20], orig_sha1[20];2531int flag =0, logmoved =0;2532struct ref_lock *lock;2533struct stat loginfo;2534int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2535struct strbuf err = STRBUF_INIT;25362537if(log &&S_ISLNK(loginfo.st_mode))2538returnerror("reflog for%sis a symlink", oldrefname);25392540if(!resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2541 orig_sha1, &flag))2542returnerror("refname%snot found", oldrefname);25432544if(flag & REF_ISSYMREF)2545returnerror("refname%sis a symbolic ref, renaming it is not supported",2546 oldrefname);2547if(!rename_ref_available(oldrefname, newrefname))2548return1;25492550if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2551returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2552 oldrefname,strerror(errno));25532554if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2555error("unable to delete old%s", oldrefname);2556goto rollback;2557}25582559/*2560 * Since we are doing a shallow lookup, sha1 is not the2561 * correct value to pass to delete_ref as old_sha1. But that2562 * doesn't matter, because an old_sha1 check wouldn't add to2563 * the safety anyway; we want to delete the reference whatever2564 * its current value.2565 */2566if(!read_ref_full(newrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2567 sha1, NULL) &&2568delete_ref(newrefname, NULL, REF_NODEREF)) {2569if(errno==EISDIR) {2570struct strbuf path = STRBUF_INIT;2571int result;25722573strbuf_git_path(&path,"%s", newrefname);2574 result =remove_empty_directories(&path);2575strbuf_release(&path);25762577if(result) {2578error("Directory not empty:%s", newrefname);2579goto rollback;2580}2581}else{2582error("unable to delete existing%s", newrefname);2583goto rollback;2584}2585}25862587if(log &&rename_tmp_log(newrefname))2588goto rollback;25892590 logmoved = log;25912592 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, REF_NODEREF,2593 NULL, &err);2594if(!lock) {2595error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2596strbuf_release(&err);2597goto rollback;2598}2599hashcpy(lock->old_oid.hash, orig_sha1);26002601if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2602commit_ref_update(lock, orig_sha1, logmsg, &err)) {2603error("unable to write current sha1 into%s:%s", newrefname, err.buf);2604strbuf_release(&err);2605goto rollback;2606}26072608return0;26092610 rollback:2611 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, REF_NODEREF,2612 NULL, &err);2613if(!lock) {2614error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2615strbuf_release(&err);2616goto rollbacklog;2617}26182619 flag = log_all_ref_updates;2620 log_all_ref_updates =0;2621if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2622commit_ref_update(lock, orig_sha1, NULL, &err)) {2623error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2624strbuf_release(&err);2625}2626 log_all_ref_updates = flag;26272628 rollbacklog:2629if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2630error("unable to restore logfile%sfrom%s:%s",2631 oldrefname, newrefname,strerror(errno));2632if(!logmoved && log &&2633rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2634error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2635 oldrefname,strerror(errno));26362637return1;2638}26392640static intclose_ref(struct ref_lock *lock)2641{2642if(close_lock_file(lock->lk))2643return-1;2644return0;2645}26462647static intcommit_ref(struct ref_lock *lock)2648{2649char*path =get_locked_file_path(lock->lk);2650struct stat st;26512652if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {2653/*2654 * There is a directory at the path we want to rename2655 * the lockfile to. Hopefully it is empty; try to2656 * delete it.2657 */2658size_t len =strlen(path);2659struct strbuf sb_path = STRBUF_INIT;26602661strbuf_attach(&sb_path, path, len, len);26622663/*2664 * If this fails, commit_lock_file() will also fail2665 * and will report the problem.2666 */2667remove_empty_directories(&sb_path);2668strbuf_release(&sb_path);2669}else{2670free(path);2671}26722673if(commit_lock_file(lock->lk))2674return-1;2675return0;2676}26772678/*2679 * Create a reflog for a ref. If force_create = 0, the reflog will2680 * only be created for certain refs (those for which2681 * should_autocreate_reflog returns non-zero. Otherwise, create it2682 * regardless of the ref name. Fill in *err and return -1 on failure.2683 */2684static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2685{2686int logfd, oflags = O_APPEND | O_WRONLY;26872688strbuf_git_path(logfile,"logs/%s", refname);2689if(force_create ||should_autocreate_reflog(refname)) {2690if(safe_create_leading_directories(logfile->buf) <0) {2691strbuf_addf(err,"unable to create directory for '%s': "2692"%s", logfile->buf,strerror(errno));2693return-1;2694}2695 oflags |= O_CREAT;2696}26972698 logfd =open(logfile->buf, oflags,0666);2699if(logfd <0) {2700if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2701return0;27022703if(errno == EISDIR) {2704if(remove_empty_directories(logfile)) {2705strbuf_addf(err,"there are still logs under "2706"'%s'", logfile->buf);2707return-1;2708}2709 logfd =open(logfile->buf, oflags,0666);2710}27112712if(logfd <0) {2713strbuf_addf(err,"unable to append to '%s':%s",2714 logfile->buf,strerror(errno));2715return-1;2716}2717}27182719adjust_shared_perm(logfile->buf);2720close(logfd);2721return0;2722}272327242725intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2726{2727int ret;2728struct strbuf sb = STRBUF_INIT;27292730 ret =log_ref_setup(refname, &sb, err, force_create);2731strbuf_release(&sb);2732return ret;2733}27342735static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2736const unsigned char*new_sha1,2737const char*committer,const char*msg)2738{2739int msglen, written;2740unsigned maxlen, len;2741char*logrec;27422743 msglen = msg ?strlen(msg) :0;2744 maxlen =strlen(committer) + msglen +100;2745 logrec =xmalloc(maxlen);2746 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2747sha1_to_hex(old_sha1),2748sha1_to_hex(new_sha1),2749 committer);2750if(msglen)2751 len +=copy_reflog_msg(logrec + len -1, msg) -1;27522753 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2754free(logrec);2755if(written != len)2756return-1;27572758return0;2759}27602761static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2762const unsigned char*new_sha1,const char*msg,2763struct strbuf *logfile,int flags,2764struct strbuf *err)2765{2766int logfd, result, oflags = O_APPEND | O_WRONLY;27672768if(log_all_ref_updates <0)2769 log_all_ref_updates = !is_bare_repository();27702771 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);27722773if(result)2774return result;27752776 logfd =open(logfile->buf, oflags);2777if(logfd <0)2778return0;2779 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2780git_committer_info(0), msg);2781if(result) {2782strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,2783strerror(errno));2784close(logfd);2785return-1;2786}2787if(close(logfd)) {2788strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,2789strerror(errno));2790return-1;2791}2792return0;2793}27942795static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2796const unsigned char*new_sha1,const char*msg,2797int flags,struct strbuf *err)2798{2799returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2800 err);2801}28022803intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2804const unsigned char*new_sha1,const char*msg,2805int flags,struct strbuf *err)2806{2807struct strbuf sb = STRBUF_INIT;2808int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2809 err);2810strbuf_release(&sb);2811return ret;2812}28132814/*2815 * Write sha1 into the open lockfile, then close the lockfile. On2816 * errors, rollback the lockfile, fill in *err and2817 * return -1.2818 */2819static intwrite_ref_to_lockfile(struct ref_lock *lock,2820const unsigned char*sha1,struct strbuf *err)2821{2822static char term ='\n';2823struct object *o;2824int fd;28252826 o =parse_object(sha1);2827if(!o) {2828strbuf_addf(err,2829"trying to write ref '%s' with nonexistent object%s",2830 lock->ref_name,sha1_to_hex(sha1));2831unlock_ref(lock);2832return-1;2833}2834if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2835strbuf_addf(err,2836"trying to write non-commit object%sto branch '%s'",2837sha1_to_hex(sha1), lock->ref_name);2838unlock_ref(lock);2839return-1;2840}2841 fd =get_lock_file_fd(lock->lk);2842if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2843write_in_full(fd, &term,1) !=1||2844close_ref(lock) <0) {2845strbuf_addf(err,2846"couldn't write '%s'",get_lock_file_path(lock->lk));2847unlock_ref(lock);2848return-1;2849}2850return0;2851}28522853/*2854 * Commit a change to a loose reference that has already been written2855 * to the loose reference lockfile. Also update the reflogs if2856 * necessary, using the specified lockmsg (which can be NULL).2857 */2858static intcommit_ref_update(struct ref_lock *lock,2859const unsigned char*sha1,const char*logmsg,2860struct strbuf *err)2861{2862clear_loose_ref_cache(&ref_cache);2863if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg,0, err)) {2864char*old_msg =strbuf_detach(err, NULL);2865strbuf_addf(err,"cannot update the ref '%s':%s",2866 lock->ref_name, old_msg);2867free(old_msg);2868unlock_ref(lock);2869return-1;2870}28712872if(strcmp(lock->ref_name,"HEAD") !=0) {2873/*2874 * Special hack: If a branch is updated directly and HEAD2875 * points to it (may happen on the remote side of a push2876 * for example) then logically the HEAD reflog should be2877 * updated too.2878 * A generic solution implies reverse symref information,2879 * but finding all symrefs pointing to the given branch2880 * would be rather costly for this rare event (the direct2881 * update of a branch) to be worth it. So let's cheat and2882 * check with HEAD only which should cover 99% of all usage2883 * scenarios (even 100% of the default ones).2884 */2885unsigned char head_sha1[20];2886int head_flag;2887const char*head_ref;28882889 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2890 head_sha1, &head_flag);2891if(head_ref && (head_flag & REF_ISSYMREF) &&2892!strcmp(head_ref, lock->ref_name)) {2893struct strbuf log_err = STRBUF_INIT;2894if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2895 logmsg,0, &log_err)) {2896error("%s", log_err.buf);2897strbuf_release(&log_err);2898}2899}2900}29012902if(commit_ref(lock)) {2903strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2904unlock_ref(lock);2905return-1;2906}29072908unlock_ref(lock);2909return0;2910}29112912static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2913{2914int ret = -1;2915#ifndef NO_SYMLINK_HEAD2916char*ref_path =get_locked_file_path(lock->lk);2917unlink(ref_path);2918 ret =symlink(target, ref_path);2919free(ref_path);29202921if(ret)2922fprintf(stderr,"no symlink - falling back to symbolic ref\n");2923#endif2924return ret;2925}29262927static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2928const char*target,const char*logmsg)2929{2930struct strbuf err = STRBUF_INIT;2931unsigned char new_sha1[20];2932if(logmsg && !read_ref(target, new_sha1) &&2933log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2934error("%s", err.buf);2935strbuf_release(&err);2936}2937}29382939static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2940const char*target,const char*logmsg)2941{2942if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2943update_symref_reflog(lock, refname, target, logmsg);2944return0;2945}29462947if(!fdopen_lock_file(lock->lk,"w"))2948returnerror("unable to fdopen%s:%s",2949 lock->lk->tempfile.filename.buf,strerror(errno));29502951update_symref_reflog(lock, refname, target, logmsg);29522953/* no error check; commit_ref will check ferror */2954fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2955if(commit_ref(lock) <0)2956returnerror("unable to write symref for%s:%s", refname,2957strerror(errno));2958return0;2959}29602961intcreate_symref(const char*refname,const char*target,const char*logmsg)2962{2963struct strbuf err = STRBUF_INIT;2964struct ref_lock *lock;2965int ret;29662967 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2968&err);2969if(!lock) {2970error("%s", err.buf);2971strbuf_release(&err);2972return-1;2973}29742975 ret =create_symref_locked(lock, refname, target, logmsg);2976unlock_ref(lock);2977return ret;2978}29792980intset_worktree_head_symref(const char*gitdir,const char*target)2981{2982static struct lock_file head_lock;2983struct ref_lock *lock;2984struct strbuf head_path = STRBUF_INIT;2985const char*head_rel;2986int ret;29872988strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));2989if(hold_lock_file_for_update(&head_lock, head_path.buf,2990 LOCK_NO_DEREF) <0) {2991struct strbuf err = STRBUF_INIT;2992unable_to_lock_message(head_path.buf, errno, &err);2993error("%s", err.buf);2994strbuf_release(&err);2995strbuf_release(&head_path);2996return-1;2997}29982999/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for3000 linked trees */3001 head_rel =remove_leading_path(head_path.buf,3002absolute_path(get_git_common_dir()));3003/* to make use of create_symref_locked(), initialize ref_lock */3004 lock =xcalloc(1,sizeof(struct ref_lock));3005 lock->lk = &head_lock;3006 lock->ref_name =xstrdup(head_rel);30073008 ret =create_symref_locked(lock, head_rel, target, NULL);30093010unlock_ref(lock);/* will free lock */3011strbuf_release(&head_path);3012return ret;3013}30143015intreflog_exists(const char*refname)3016{3017struct stat st;30183019return!lstat(git_path("logs/%s", refname), &st) &&3020S_ISREG(st.st_mode);3021}30223023intdelete_reflog(const char*refname)3024{3025returnremove_path(git_path("logs/%s", refname));3026}30273028static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3029{3030unsigned char osha1[20], nsha1[20];3031char*email_end, *message;3032unsigned long timestamp;3033int tz;30343035/* old SP new SP name <email> SP time TAB msg LF */3036if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3037get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3038get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3039!(email_end =strchr(sb->buf +82,'>')) ||3040 email_end[1] !=' '||3041!(timestamp =strtoul(email_end +2, &message,10)) ||3042!message || message[0] !=' '||3043(message[1] !='+'&& message[1] !='-') ||3044!isdigit(message[2]) || !isdigit(message[3]) ||3045!isdigit(message[4]) || !isdigit(message[5]))3046return0;/* corrupt? */3047 email_end[1] ='\0';3048 tz =strtol(message +1, NULL,10);3049if(message[6] !='\t')3050 message +=6;3051else3052 message +=7;3053returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3054}30553056static char*find_beginning_of_line(char*bob,char*scan)3057{3058while(bob < scan && *(--scan) !='\n')3059;/* keep scanning backwards */3060/*3061 * Return either beginning of the buffer, or LF at the end of3062 * the previous line.3063 */3064return scan;3065}30663067intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3068{3069struct strbuf sb = STRBUF_INIT;3070FILE*logfp;3071long pos;3072int ret =0, at_tail =1;30733074 logfp =fopen(git_path("logs/%s", refname),"r");3075if(!logfp)3076return-1;30773078/* Jump to the end */3079if(fseek(logfp,0, SEEK_END) <0)3080returnerror("cannot seek back reflog for%s:%s",3081 refname,strerror(errno));3082 pos =ftell(logfp);3083while(!ret &&0< pos) {3084int cnt;3085size_t nread;3086char buf[BUFSIZ];3087char*endp, *scanp;30883089/* Fill next block from the end */3090 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3091if(fseek(logfp, pos - cnt, SEEK_SET))3092returnerror("cannot seek back reflog for%s:%s",3093 refname,strerror(errno));3094 nread =fread(buf, cnt,1, logfp);3095if(nread !=1)3096returnerror("cannot read%dbytes from reflog for%s:%s",3097 cnt, refname,strerror(errno));3098 pos -= cnt;30993100 scanp = endp = buf + cnt;3101if(at_tail && scanp[-1] =='\n')3102/* Looking at the final LF at the end of the file */3103 scanp--;3104 at_tail =0;31053106while(buf < scanp) {3107/*3108 * terminating LF of the previous line, or the beginning3109 * of the buffer.3110 */3111char*bp;31123113 bp =find_beginning_of_line(buf, scanp);31143115if(*bp =='\n') {3116/*3117 * The newline is the end of the previous line,3118 * so we know we have complete line starting3119 * at (bp + 1). Prefix it onto any prior data3120 * we collected for the line and process it.3121 */3122strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3123 scanp = bp;3124 endp = bp +1;3125 ret =show_one_reflog_ent(&sb, fn, cb_data);3126strbuf_reset(&sb);3127if(ret)3128break;3129}else if(!pos) {3130/*3131 * We are at the start of the buffer, and the3132 * start of the file; there is no previous3133 * line, and we have everything for this one.3134 * Process it, and we can end the loop.3135 */3136strbuf_splice(&sb,0,0, buf, endp - buf);3137 ret =show_one_reflog_ent(&sb, fn, cb_data);3138strbuf_reset(&sb);3139break;3140}31413142if(bp == buf) {3143/*3144 * We are at the start of the buffer, and there3145 * is more file to read backwards. Which means3146 * we are in the middle of a line. Note that we3147 * may get here even if *bp was a newline; that3148 * just means we are at the exact end of the3149 * previous line, rather than some spot in the3150 * middle.3151 *3152 * Save away what we have to be combined with3153 * the data from the next read.3154 */3155strbuf_splice(&sb,0,0, buf, endp - buf);3156break;3157}3158}31593160}3161if(!ret && sb.len)3162die("BUG: reverse reflog parser had leftover data");31633164fclose(logfp);3165strbuf_release(&sb);3166return ret;3167}31683169intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3170{3171FILE*logfp;3172struct strbuf sb = STRBUF_INIT;3173int ret =0;31743175 logfp =fopen(git_path("logs/%s", refname),"r");3176if(!logfp)3177return-1;31783179while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3180 ret =show_one_reflog_ent(&sb, fn, cb_data);3181fclose(logfp);3182strbuf_release(&sb);3183return ret;3184}3185/*3186 * Call fn for each reflog in the namespace indicated by name. name3187 * must be empty or end with '/'. Name will be used as a scratch3188 * space, but its contents will be restored before return.3189 */3190static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3191{3192DIR*d =opendir(git_path("logs/%s", name->buf));3193int retval =0;3194struct dirent *de;3195int oldlen = name->len;31963197if(!d)3198return name->len ? errno :0;31993200while((de =readdir(d)) != NULL) {3201struct stat st;32023203if(de->d_name[0] =='.')3204continue;3205if(ends_with(de->d_name,".lock"))3206continue;3207strbuf_addstr(name, de->d_name);3208if(stat(git_path("logs/%s", name->buf), &st) <0) {3209;/* silently ignore */3210}else{3211if(S_ISDIR(st.st_mode)) {3212strbuf_addch(name,'/');3213 retval =do_for_each_reflog(name, fn, cb_data);3214}else{3215struct object_id oid;32163217if(read_ref_full(name->buf,0, oid.hash, NULL))3218 retval =error("bad ref for%s", name->buf);3219else3220 retval =fn(name->buf, &oid,0, cb_data);3221}3222if(retval)3223break;3224}3225strbuf_setlen(name, oldlen);3226}3227closedir(d);3228return retval;3229}32303231intfor_each_reflog(each_ref_fn fn,void*cb_data)3232{3233int retval;3234struct strbuf name;3235strbuf_init(&name, PATH_MAX);3236 retval =do_for_each_reflog(&name, fn, cb_data);3237strbuf_release(&name);3238return retval;3239}32403241static intref_update_reject_duplicates(struct string_list *refnames,3242struct strbuf *err)3243{3244int i, n = refnames->nr;32453246assert(err);32473248for(i =1; i < n; i++)3249if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3250strbuf_addf(err,3251"multiple updates for ref '%s' not allowed.",3252 refnames->items[i].string);3253return1;3254}3255return0;3256}32573258/*3259 * If update is a direct update of head_ref (the reference pointed to3260 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.3261 */3262static intsplit_head_update(struct ref_update *update,3263struct ref_transaction *transaction,3264const char*head_ref,3265struct string_list *affected_refnames,3266struct strbuf *err)3267{3268struct string_list_item *item;3269struct ref_update *new_update;32703271if((update->flags & REF_LOG_ONLY) ||3272(update->flags & REF_ISPRUNING) ||3273(update->flags & REF_UPDATE_VIA_HEAD))3274return0;32753276if(strcmp(update->refname, head_ref))3277return0;32783279/*3280 * First make sure that HEAD is not already in the3281 * transaction. This insertion is O(N) in the transaction3282 * size, but it happens at most once per transaction.3283 */3284 item =string_list_insert(affected_refnames,"HEAD");3285if(item->util) {3286/* An entry already existed */3287strbuf_addf(err,3288"multiple updates for 'HEAD' (including one "3289"via its referent '%s') are not allowed",3290 update->refname);3291return TRANSACTION_NAME_CONFLICT;3292}32933294 new_update =ref_transaction_add_update(3295 transaction,"HEAD",3296 update->flags | REF_LOG_ONLY | REF_NODEREF,3297 update->new_sha1, update->old_sha1,3298 update->msg);32993300 item->util = new_update;33013302return0;3303}33043305/*3306 * update is for a symref that points at referent and doesn't have3307 * REF_NODEREF set. Split it into two updates:3308 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set3309 * - A new, separate update for the referent reference3310 * Note that the new update will itself be subject to splitting when3311 * the iteration gets to it.3312 */3313static intsplit_symref_update(struct ref_update *update,3314const char*referent,3315struct ref_transaction *transaction,3316struct string_list *affected_refnames,3317struct strbuf *err)3318{3319struct string_list_item *item;3320struct ref_update *new_update;3321unsigned int new_flags;33223323/*3324 * First make sure that referent is not already in the3325 * transaction. This insertion is O(N) in the transaction3326 * size, but it happens at most once per symref in a3327 * transaction.3328 */3329 item =string_list_insert(affected_refnames, referent);3330if(item->util) {3331/* An entry already existed */3332strbuf_addf(err,3333"multiple updates for '%s' (including one "3334"via symref '%s') are not allowed",3335 referent, update->refname);3336return TRANSACTION_NAME_CONFLICT;3337}33383339 new_flags = update->flags;3340if(!strcmp(update->refname,"HEAD")) {3341/*3342 * Record that the new update came via HEAD, so that3343 * when we process it, split_head_update() doesn't try3344 * to add another reflog update for HEAD. Note that3345 * this bit will be propagated if the new_update3346 * itself needs to be split.3347 */3348 new_flags |= REF_UPDATE_VIA_HEAD;3349}33503351 new_update =ref_transaction_add_update(3352 transaction, referent, new_flags,3353 update->new_sha1, update->old_sha1,3354 update->msg);33553356 new_update->parent_update = update;33573358/*3359 * Change the symbolic ref update to log only. Also, it3360 * doesn't need to check its old SHA-1 value, as that will be3361 * done when new_update is processed.3362 */3363 update->flags |= REF_LOG_ONLY | REF_NODEREF;3364 update->flags &= ~REF_HAVE_OLD;33653366 item->util = new_update;33673368return0;3369}33703371/*3372 * Return the refname under which update was originally requested.3373 */3374static const char*original_update_refname(struct ref_update *update)3375{3376while(update->parent_update)3377 update = update->parent_update;33783379return update->refname;3380}33813382/*3383 * Prepare for carrying out update:3384 * - Lock the reference referred to by update.3385 * - Read the reference under lock.3386 * - Check that its old SHA-1 value (if specified) is correct, and in3387 * any case record it in update->lock->old_oid for later use when3388 * writing the reflog.3389 * - If it is a symref update without REF_NODEREF, split it up into a3390 * REF_LOG_ONLY update of the symref and add a separate update for3391 * the referent to transaction.3392 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY3393 * update of HEAD.3394 */3395static intlock_ref_for_update(struct ref_update *update,3396struct ref_transaction *transaction,3397const char*head_ref,3398struct string_list *affected_refnames,3399struct strbuf *err)3400{3401struct strbuf referent = STRBUF_INIT;3402int mustexist = (update->flags & REF_HAVE_OLD) &&3403!is_null_sha1(update->old_sha1);3404int ret;3405struct ref_lock *lock;34063407if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))3408 update->flags |= REF_DELETING;34093410if(head_ref) {3411 ret =split_head_update(update, transaction, head_ref,3412 affected_refnames, err);3413if(ret)3414return ret;3415}34163417 ret =lock_raw_ref(update->refname, mustexist,3418 affected_refnames, NULL,3419&update->lock, &referent,3420&update->type, err);34213422if(ret) {3423char*reason;34243425 reason =strbuf_detach(err, NULL);3426strbuf_addf(err,"cannot lock ref '%s':%s",3427 update->refname, reason);3428free(reason);3429return ret;3430}34313432 lock = update->lock;34333434if(update->type & REF_ISSYMREF) {3435if(update->flags & REF_NODEREF) {3436/*3437 * We won't be reading the referent as part of3438 * the transaction, so we have to read it here3439 * to record and possibly check old_sha1:3440 */3441if(read_ref_full(update->refname,3442 mustexist ? RESOLVE_REF_READING :0,3443 lock->old_oid.hash, NULL)) {3444if(update->flags & REF_HAVE_OLD) {3445strbuf_addf(err,"cannot lock ref '%s': "3446"can't resolve old value",3447 update->refname);3448return TRANSACTION_GENERIC_ERROR;3449}else{3450hashclr(lock->old_oid.hash);3451}3452}3453if((update->flags & REF_HAVE_OLD) &&3454hashcmp(lock->old_oid.hash, update->old_sha1)) {3455strbuf_addf(err,"cannot lock ref '%s': "3456"is at%sbut expected%s",3457 update->refname,3458sha1_to_hex(lock->old_oid.hash),3459sha1_to_hex(update->old_sha1));3460return TRANSACTION_GENERIC_ERROR;3461}34623463}else{3464/*3465 * Create a new update for the reference this3466 * symref is pointing at. Also, we will record3467 * and verify old_sha1 for this update as part3468 * of processing the split-off update, so we3469 * don't have to do it here.3470 */3471 ret =split_symref_update(update, referent.buf, transaction,3472 affected_refnames, err);3473if(ret)3474return ret;3475}3476}else{3477struct ref_update *parent_update;34783479/*3480 * If this update is happening indirectly because of a3481 * symref update, record the old SHA-1 in the parent3482 * update:3483 */3484for(parent_update = update->parent_update;3485 parent_update;3486 parent_update = parent_update->parent_update) {3487oidcpy(&parent_update->lock->old_oid, &lock->old_oid);3488}34893490if((update->flags & REF_HAVE_OLD) &&3491hashcmp(lock->old_oid.hash, update->old_sha1)) {3492if(is_null_sha1(update->old_sha1))3493strbuf_addf(err,"cannot lock ref '%s': reference already exists",3494original_update_refname(update));3495else3496strbuf_addf(err,"cannot lock ref '%s': is at%sbut expected%s",3497original_update_refname(update),3498sha1_to_hex(lock->old_oid.hash),3499sha1_to_hex(update->old_sha1));35003501return TRANSACTION_GENERIC_ERROR;3502}3503}35043505if((update->flags & REF_HAVE_NEW) &&3506!(update->flags & REF_DELETING) &&3507!(update->flags & REF_LOG_ONLY)) {3508if(!(update->type & REF_ISSYMREF) &&3509!hashcmp(lock->old_oid.hash, update->new_sha1)) {3510/*3511 * The reference already has the desired3512 * value, so we don't need to write it.3513 */3514}else if(write_ref_to_lockfile(lock, update->new_sha1,3515 err)) {3516char*write_err =strbuf_detach(err, NULL);35173518/*3519 * The lock was freed upon failure of3520 * write_ref_to_lockfile():3521 */3522 update->lock = NULL;3523strbuf_addf(err,3524"cannot update the ref '%s':%s",3525 update->refname, write_err);3526free(write_err);3527return TRANSACTION_GENERIC_ERROR;3528}else{3529 update->flags |= REF_NEEDS_COMMIT;3530}3531}3532if(!(update->flags & REF_NEEDS_COMMIT)) {3533/*3534 * We didn't call write_ref_to_lockfile(), so3535 * the lockfile is still open. Close it to3536 * free up the file descriptor:3537 */3538if(close_ref(lock)) {3539strbuf_addf(err,"couldn't close '%s.lock'",3540 update->refname);3541return TRANSACTION_GENERIC_ERROR;3542}3543}3544return0;3545}35463547intref_transaction_commit(struct ref_transaction *transaction,3548struct strbuf *err)3549{3550int ret =0, i;3551struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3552struct string_list_item *ref_to_delete;3553struct string_list affected_refnames = STRING_LIST_INIT_NODUP;3554char*head_ref = NULL;3555int head_type;3556struct object_id head_oid;35573558assert(err);35593560if(transaction->state != REF_TRANSACTION_OPEN)3561die("BUG: commit called for transaction that is not open");35623563if(!transaction->nr) {3564 transaction->state = REF_TRANSACTION_CLOSED;3565return0;3566}35673568/*3569 * Fail if a refname appears more than once in the3570 * transaction. (If we end up splitting up any updates using3571 * split_symref_update() or split_head_update(), those3572 * functions will check that the new updates don't have the3573 * same refname as any existing ones.)3574 */3575for(i =0; i < transaction->nr; i++) {3576struct ref_update *update = transaction->updates[i];3577struct string_list_item *item =3578string_list_append(&affected_refnames, update->refname);35793580/*3581 * We store a pointer to update in item->util, but at3582 * the moment we never use the value of this field3583 * except to check whether it is non-NULL.3584 */3585 item->util = update;3586}3587string_list_sort(&affected_refnames);3588if(ref_update_reject_duplicates(&affected_refnames, err)) {3589 ret = TRANSACTION_GENERIC_ERROR;3590goto cleanup;3591}35923593/*3594 * Special hack: If a branch is updated directly and HEAD3595 * points to it (may happen on the remote side of a push3596 * for example) then logically the HEAD reflog should be3597 * updated too.3598 *3599 * A generic solution would require reverse symref lookups,3600 * but finding all symrefs pointing to a given branch would be3601 * rather costly for this rare event (the direct update of a3602 * branch) to be worth it. So let's cheat and check with HEAD3603 * only, which should cover 99% of all usage scenarios (even3604 * 100% of the default ones).3605 *3606 * So if HEAD is a symbolic reference, then record the name of3607 * the reference that it points to. If we see an update of3608 * head_ref within the transaction, then split_head_update()3609 * arranges for the reflog of HEAD to be updated, too.3610 */3611 head_ref =resolve_refdup("HEAD", RESOLVE_REF_NO_RECURSE,3612 head_oid.hash, &head_type);36133614if(head_ref && !(head_type & REF_ISSYMREF)) {3615free(head_ref);3616 head_ref = NULL;3617}36183619/*3620 * Acquire all locks, verify old values if provided, check3621 * that new values are valid, and write new values to the3622 * lockfiles, ready to be activated. Only keep one lockfile3623 * open at a time to avoid running out of file descriptors.3624 */3625for(i =0; i < transaction->nr; i++) {3626struct ref_update *update = transaction->updates[i];36273628 ret =lock_ref_for_update(update, transaction, head_ref,3629&affected_refnames, err);3630if(ret)3631goto cleanup;3632}36333634/* Perform updates first so live commits remain referenced */3635for(i =0; i < transaction->nr; i++) {3636struct ref_update *update = transaction->updates[i];3637struct ref_lock *lock = update->lock;36383639if(update->flags & REF_NEEDS_COMMIT ||3640 update->flags & REF_LOG_ONLY) {3641if(log_ref_write(lock->ref_name, lock->old_oid.hash,3642 update->new_sha1,3643 update->msg, update->flags, err)) {3644char*old_msg =strbuf_detach(err, NULL);36453646strbuf_addf(err,"cannot update the ref '%s':%s",3647 lock->ref_name, old_msg);3648free(old_msg);3649unlock_ref(lock);3650 update->lock = NULL;3651 ret = TRANSACTION_GENERIC_ERROR;3652goto cleanup;3653}3654}3655if(update->flags & REF_NEEDS_COMMIT) {3656clear_loose_ref_cache(&ref_cache);3657if(commit_ref(lock)) {3658strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3659unlock_ref(lock);3660 update->lock = NULL;3661 ret = TRANSACTION_GENERIC_ERROR;3662goto cleanup;3663}3664}3665}3666/* Perform deletes now that updates are safely completed */3667for(i =0; i < transaction->nr; i++) {3668struct ref_update *update = transaction->updates[i];36693670if(update->flags & REF_DELETING &&3671!(update->flags & REF_LOG_ONLY)) {3672if(delete_ref_loose(update->lock, update->type, err)) {3673 ret = TRANSACTION_GENERIC_ERROR;3674goto cleanup;3675}36763677if(!(update->flags & REF_ISPRUNING))3678string_list_append(&refs_to_delete,3679 update->lock->ref_name);3680}3681}36823683if(repack_without_refs(&refs_to_delete, err)) {3684 ret = TRANSACTION_GENERIC_ERROR;3685goto cleanup;3686}3687for_each_string_list_item(ref_to_delete, &refs_to_delete)3688unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3689clear_loose_ref_cache(&ref_cache);36903691cleanup:3692 transaction->state = REF_TRANSACTION_CLOSED;36933694for(i =0; i < transaction->nr; i++)3695if(transaction->updates[i]->lock)3696unlock_ref(transaction->updates[i]->lock);3697string_list_clear(&refs_to_delete,0);3698free(head_ref);3699string_list_clear(&affected_refnames,0);37003701return ret;3702}37033704static intref_present(const char*refname,3705const struct object_id *oid,int flags,void*cb_data)3706{3707struct string_list *affected_refnames = cb_data;37083709returnstring_list_has_string(affected_refnames, refname);3710}37113712intinitial_ref_transaction_commit(struct ref_transaction *transaction,3713struct strbuf *err)3714{3715int ret =0, i;3716struct string_list affected_refnames = STRING_LIST_INIT_NODUP;37173718assert(err);37193720if(transaction->state != REF_TRANSACTION_OPEN)3721die("BUG: commit called for transaction that is not open");37223723/* Fail if a refname appears more than once in the transaction: */3724for(i =0; i < transaction->nr; i++)3725string_list_append(&affected_refnames,3726 transaction->updates[i]->refname);3727string_list_sort(&affected_refnames);3728if(ref_update_reject_duplicates(&affected_refnames, err)) {3729 ret = TRANSACTION_GENERIC_ERROR;3730goto cleanup;3731}37323733/*3734 * It's really undefined to call this function in an active3735 * repository or when there are existing references: we are3736 * only locking and changing packed-refs, so (1) any3737 * simultaneous processes might try to change a reference at3738 * the same time we do, and (2) any existing loose versions of3739 * the references that we are setting would have precedence3740 * over our values. But some remote helpers create the remote3741 * "HEAD" and "master" branches before calling this function,3742 * so here we really only check that none of the references3743 * that we are creating already exists.3744 */3745if(for_each_rawref(ref_present, &affected_refnames))3746die("BUG: initial ref transaction called with existing refs");37473748for(i =0; i < transaction->nr; i++) {3749struct ref_update *update = transaction->updates[i];37503751if((update->flags & REF_HAVE_OLD) &&3752!is_null_sha1(update->old_sha1))3753die("BUG: initial ref transaction with old_sha1 set");3754if(verify_refname_available(update->refname,3755&affected_refnames, NULL,3756 err)) {3757 ret = TRANSACTION_NAME_CONFLICT;3758goto cleanup;3759}3760}37613762if(lock_packed_refs(0)) {3763strbuf_addf(err,"unable to lock packed-refs file:%s",3764strerror(errno));3765 ret = TRANSACTION_GENERIC_ERROR;3766goto cleanup;3767}37683769for(i =0; i < transaction->nr; i++) {3770struct ref_update *update = transaction->updates[i];37713772if((update->flags & REF_HAVE_NEW) &&3773!is_null_sha1(update->new_sha1))3774add_packed_ref(update->refname, update->new_sha1);3775}37763777if(commit_packed_refs()) {3778strbuf_addf(err,"unable to commit packed-refs file:%s",3779strerror(errno));3780 ret = TRANSACTION_GENERIC_ERROR;3781goto cleanup;3782}37833784cleanup:3785 transaction->state = REF_TRANSACTION_CLOSED;3786string_list_clear(&affected_refnames,0);3787return ret;3788}37893790struct expire_reflog_cb {3791unsigned int flags;3792 reflog_expiry_should_prune_fn *should_prune_fn;3793void*policy_cb;3794FILE*newlog;3795unsigned char last_kept_sha1[20];3796};37973798static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3799const char*email,unsigned long timestamp,int tz,3800const char*message,void*cb_data)3801{3802struct expire_reflog_cb *cb = cb_data;3803struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;38043805if(cb->flags & EXPIRE_REFLOGS_REWRITE)3806 osha1 = cb->last_kept_sha1;38073808if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3809 message, policy_cb)) {3810if(!cb->newlog)3811printf("would prune%s", message);3812else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3813printf("prune%s", message);3814}else{3815if(cb->newlog) {3816fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3817sha1_to_hex(osha1),sha1_to_hex(nsha1),3818 email, timestamp, tz, message);3819hashcpy(cb->last_kept_sha1, nsha1);3820}3821if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3822printf("keep%s", message);3823}3824return0;3825}38263827intreflog_expire(const char*refname,const unsigned char*sha1,3828unsigned int flags,3829 reflog_expiry_prepare_fn prepare_fn,3830 reflog_expiry_should_prune_fn should_prune_fn,3831 reflog_expiry_cleanup_fn cleanup_fn,3832void*policy_cb_data)3833{3834static struct lock_file reflog_lock;3835struct expire_reflog_cb cb;3836struct ref_lock *lock;3837char*log_file;3838int status =0;3839int type;3840struct strbuf err = STRBUF_INIT;38413842memset(&cb,0,sizeof(cb));3843 cb.flags = flags;3844 cb.policy_cb = policy_cb_data;3845 cb.should_prune_fn = should_prune_fn;38463847/*3848 * The reflog file is locked by holding the lock on the3849 * reference itself, plus we might need to update the3850 * reference if --updateref was specified:3851 */3852 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL, REF_NODEREF,3853&type, &err);3854if(!lock) {3855error("cannot lock ref '%s':%s", refname, err.buf);3856strbuf_release(&err);3857return-1;3858}3859if(!reflog_exists(refname)) {3860unlock_ref(lock);3861return0;3862}38633864 log_file =git_pathdup("logs/%s", refname);3865if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3866/*3867 * Even though holding $GIT_DIR/logs/$reflog.lock has3868 * no locking implications, we use the lock_file3869 * machinery here anyway because it does a lot of the3870 * work we need, including cleaning up if the program3871 * exits unexpectedly.3872 */3873if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3874struct strbuf err = STRBUF_INIT;3875unable_to_lock_message(log_file, errno, &err);3876error("%s", err.buf);3877strbuf_release(&err);3878goto failure;3879}3880 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3881if(!cb.newlog) {3882error("cannot fdopen%s(%s)",3883get_lock_file_path(&reflog_lock),strerror(errno));3884goto failure;3885}3886}38873888(*prepare_fn)(refname, sha1, cb.policy_cb);3889for_each_reflog_ent(refname, expire_reflog_ent, &cb);3890(*cleanup_fn)(cb.policy_cb);38913892if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3893/*3894 * It doesn't make sense to adjust a reference pointed3895 * to by a symbolic ref based on expiring entries in3896 * the symbolic reference's reflog. Nor can we update3897 * a reference if there are no remaining reflog3898 * entries.3899 */3900int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3901!(type & REF_ISSYMREF) &&3902!is_null_sha1(cb.last_kept_sha1);39033904if(close_lock_file(&reflog_lock)) {3905 status |=error("couldn't write%s:%s", log_file,3906strerror(errno));3907}else if(update &&3908(write_in_full(get_lock_file_fd(lock->lk),3909sha1_to_hex(cb.last_kept_sha1),40) !=40||3910write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3911close_ref(lock) <0)) {3912 status |=error("couldn't write%s",3913get_lock_file_path(lock->lk));3914rollback_lock_file(&reflog_lock);3915}else if(commit_lock_file(&reflog_lock)) {3916 status |=error("unable to write reflog '%s' (%s)",3917 log_file,strerror(errno));3918}else if(update &&commit_ref(lock)) {3919 status |=error("couldn't set%s", lock->ref_name);3920}3921}3922free(log_file);3923unlock_ref(lock);3924return status;39253926 failure:3927rollback_lock_file(&reflog_lock);3928free(log_file);3929unlock_ref(lock);3930return-1;3931}