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 if refname, which has the specified oid and flags, can 517 * be resolved to an object in the database. If the referred-to object 518 * does not exist, emit a warning and return false. 519 */ 520static intref_resolves_to_object(const char*refname, 521const struct object_id *oid, 522unsigned int flags) 523{ 524if(flags & REF_ISBROKEN) 525return0; 526if(!has_sha1_file(oid->hash)) { 527error("%sdoes not point to a valid object!", refname); 528return0; 529} 530return1; 531} 532 533/* 534 * Return true if the reference described by entry can be resolved to 535 * an object in the database; otherwise, emit a warning and return 536 * false. 537 */ 538static intentry_resolves_to_object(struct ref_entry *entry) 539{ 540returnref_resolves_to_object(entry->name, 541&entry->u.value.oid, entry->flag); 542} 543 544/* 545 * current_ref is a performance hack: when iterating over references 546 * using the for_each_ref*() functions, current_ref is set to the 547 * current reference's entry before calling the callback function. If 548 * the callback function calls peel_ref(), then peel_ref() first 549 * checks whether the reference to be peeled is the current reference 550 * (it usually is) and if so, returns that reference's peeled version 551 * if it is available. This avoids a refname lookup in a common case. 552 */ 553static struct ref_entry *current_ref; 554 555typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 556 557struct ref_entry_cb { 558const char*prefix; 559int trim; 560int flags; 561 each_ref_fn *fn; 562void*cb_data; 563}; 564 565/* 566 * Handle one reference in a do_for_each_ref*()-style iteration, 567 * calling an each_ref_fn for each entry. 568 */ 569static intdo_one_ref(struct ref_entry *entry,void*cb_data) 570{ 571struct ref_entry_cb *data = cb_data; 572struct ref_entry *old_current_ref; 573int retval; 574 575if(!starts_with(entry->name, data->prefix)) 576return0; 577 578if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 579!entry_resolves_to_object(entry)) 580return0; 581 582/* Store the old value, in case this is a recursive call: */ 583 old_current_ref = current_ref; 584 current_ref = entry; 585 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 586 entry->flag, data->cb_data); 587 current_ref = old_current_ref; 588return retval; 589} 590 591/* 592 * Call fn for each reference in dir that has index in the range 593 * offset <= index < dir->nr. Recurse into subdirectories that are in 594 * that index range, sorting them before iterating. This function 595 * does not sort dir itself; it should be sorted beforehand. fn is 596 * called for all references, including broken ones. 597 */ 598static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 599 each_ref_entry_fn fn,void*cb_data) 600{ 601int i; 602assert(dir->sorted == dir->nr); 603for(i = offset; i < dir->nr; i++) { 604struct ref_entry *entry = dir->entries[i]; 605int retval; 606if(entry->flag & REF_DIR) { 607struct ref_dir *subdir =get_ref_dir(entry); 608sort_ref_dir(subdir); 609 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 610}else{ 611 retval =fn(entry, cb_data); 612} 613if(retval) 614return retval; 615} 616return0; 617} 618 619/* 620 * Call fn for each reference in the union of dir1 and dir2, in order 621 * by refname. Recurse into subdirectories. If a value entry appears 622 * in both dir1 and dir2, then only process the version that is in 623 * dir2. The input dirs must already be sorted, but subdirs will be 624 * sorted as needed. fn is called for all references, including 625 * broken ones. 626 */ 627static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 628struct ref_dir *dir2, 629 each_ref_entry_fn fn,void*cb_data) 630{ 631int retval; 632int i1 =0, i2 =0; 633 634assert(dir1->sorted == dir1->nr); 635assert(dir2->sorted == dir2->nr); 636while(1) { 637struct ref_entry *e1, *e2; 638int cmp; 639if(i1 == dir1->nr) { 640returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 641} 642if(i2 == dir2->nr) { 643returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 644} 645 e1 = dir1->entries[i1]; 646 e2 = dir2->entries[i2]; 647 cmp =strcmp(e1->name, e2->name); 648if(cmp ==0) { 649if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 650/* Both are directories; descend them in parallel. */ 651struct ref_dir *subdir1 =get_ref_dir(e1); 652struct ref_dir *subdir2 =get_ref_dir(e2); 653sort_ref_dir(subdir1); 654sort_ref_dir(subdir2); 655 retval =do_for_each_entry_in_dirs( 656 subdir1, subdir2, fn, cb_data); 657 i1++; 658 i2++; 659}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 660/* Both are references; ignore the one from dir1. */ 661 retval =fn(e2, cb_data); 662 i1++; 663 i2++; 664}else{ 665die("conflict between reference and directory:%s", 666 e1->name); 667} 668}else{ 669struct ref_entry *e; 670if(cmp <0) { 671 e = e1; 672 i1++; 673}else{ 674 e = e2; 675 i2++; 676} 677if(e->flag & REF_DIR) { 678struct ref_dir *subdir =get_ref_dir(e); 679sort_ref_dir(subdir); 680 retval =do_for_each_entry_in_dir( 681 subdir,0, fn, cb_data); 682}else{ 683 retval =fn(e, cb_data); 684} 685} 686if(retval) 687return retval; 688} 689} 690 691/* 692 * Load all of the refs from the dir into our in-memory cache. The hard work 693 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 694 * through all of the sub-directories. We do not even need to care about 695 * sorting, as traversal order does not matter to us. 696 */ 697static voidprime_ref_dir(struct ref_dir *dir) 698{ 699int i; 700for(i =0; i < dir->nr; i++) { 701struct ref_entry *entry = dir->entries[i]; 702if(entry->flag & REF_DIR) 703prime_ref_dir(get_ref_dir(entry)); 704} 705} 706 707struct nonmatching_ref_data { 708const struct string_list *skip; 709const char*conflicting_refname; 710}; 711 712static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 713{ 714struct nonmatching_ref_data *data = vdata; 715 716if(data->skip &&string_list_has_string(data->skip, entry->name)) 717return0; 718 719 data->conflicting_refname = entry->name; 720return1; 721} 722 723/* 724 * Return 0 if a reference named refname could be created without 725 * conflicting with the name of an existing reference in dir. 726 * See verify_refname_available for more information. 727 */ 728static intverify_refname_available_dir(const char*refname, 729const struct string_list *extras, 730const struct string_list *skip, 731struct ref_dir *dir, 732struct strbuf *err) 733{ 734const char*slash; 735const char*extra_refname; 736int pos; 737struct strbuf dirname = STRBUF_INIT; 738int ret = -1; 739 740/* 741 * For the sake of comments in this function, suppose that 742 * refname is "refs/foo/bar". 743 */ 744 745assert(err); 746 747strbuf_grow(&dirname,strlen(refname) +1); 748for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 749/* Expand dirname to the new prefix, not including the trailing slash: */ 750strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 751 752/* 753 * We are still at a leading dir of the refname (e.g., 754 * "refs/foo"; if there is a reference with that name, 755 * it is a conflict, *unless* it is in skip. 756 */ 757if(dir) { 758 pos =search_ref_dir(dir, dirname.buf, dirname.len); 759if(pos >=0&& 760(!skip || !string_list_has_string(skip, dirname.buf))) { 761/* 762 * We found a reference whose name is 763 * a proper prefix of refname; e.g., 764 * "refs/foo", and is not in skip. 765 */ 766strbuf_addf(err,"'%s' exists; cannot create '%s'", 767 dirname.buf, refname); 768goto cleanup; 769} 770} 771 772if(extras &&string_list_has_string(extras, dirname.buf) && 773(!skip || !string_list_has_string(skip, dirname.buf))) { 774strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 775 refname, dirname.buf); 776goto cleanup; 777} 778 779/* 780 * Otherwise, we can try to continue our search with 781 * the next component. So try to look up the 782 * directory, e.g., "refs/foo/". If we come up empty, 783 * we know there is nothing under this whole prefix, 784 * but even in that case we still have to continue the 785 * search for conflicts with extras. 786 */ 787strbuf_addch(&dirname,'/'); 788if(dir) { 789 pos =search_ref_dir(dir, dirname.buf, dirname.len); 790if(pos <0) { 791/* 792 * There was no directory "refs/foo/", 793 * so there is nothing under this 794 * whole prefix. So there is no need 795 * to continue looking for conflicting 796 * references. But we need to continue 797 * looking for conflicting extras. 798 */ 799 dir = NULL; 800}else{ 801 dir =get_ref_dir(dir->entries[pos]); 802} 803} 804} 805 806/* 807 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 808 * There is no point in searching for a reference with that 809 * name, because a refname isn't considered to conflict with 810 * itself. But we still need to check for references whose 811 * names are in the "refs/foo/bar/" namespace, because they 812 * *do* conflict. 813 */ 814strbuf_addstr(&dirname, refname + dirname.len); 815strbuf_addch(&dirname,'/'); 816 817if(dir) { 818 pos =search_ref_dir(dir, dirname.buf, dirname.len); 819 820if(pos >=0) { 821/* 822 * We found a directory named "$refname/" 823 * (e.g., "refs/foo/bar/"). It is a problem 824 * iff it contains any ref that is not in 825 * "skip". 826 */ 827struct nonmatching_ref_data data; 828 829 data.skip = skip; 830 data.conflicting_refname = NULL; 831 dir =get_ref_dir(dir->entries[pos]); 832sort_ref_dir(dir); 833if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 834strbuf_addf(err,"'%s' exists; cannot create '%s'", 835 data.conflicting_refname, refname); 836goto cleanup; 837} 838} 839} 840 841 extra_refname =find_descendant_ref(dirname.buf, extras, skip); 842if(extra_refname) 843strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 844 refname, extra_refname); 845else 846 ret =0; 847 848cleanup: 849strbuf_release(&dirname); 850return ret; 851} 852 853struct packed_ref_cache { 854struct ref_entry *root; 855 856/* 857 * Count of references to the data structure in this instance, 858 * including the pointer from ref_cache::packed if any. The 859 * data will not be freed as long as the reference count is 860 * nonzero. 861 */ 862unsigned int referrers; 863 864/* 865 * Iff the packed-refs file associated with this instance is 866 * currently locked for writing, this points at the associated 867 * lock (which is owned by somebody else). The referrer count 868 * is also incremented when the file is locked and decremented 869 * when it is unlocked. 870 */ 871struct lock_file *lock; 872 873/* The metadata from when this packed-refs cache was read */ 874struct stat_validity validity; 875}; 876 877/* 878 * Future: need to be in "struct repository" 879 * when doing a full libification. 880 */ 881static struct ref_cache { 882struct ref_cache *next; 883struct ref_entry *loose; 884struct packed_ref_cache *packed; 885/* 886 * The submodule name, or "" for the main repo. We allocate 887 * length 1 rather than FLEX_ARRAY so that the main ref_cache 888 * is initialized correctly. 889 */ 890char name[1]; 891} ref_cache, *submodule_ref_caches; 892 893/* Lock used for the main packed-refs file: */ 894static struct lock_file packlock; 895 896/* 897 * Increment the reference count of *packed_refs. 898 */ 899static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 900{ 901 packed_refs->referrers++; 902} 903 904/* 905 * Decrease the reference count of *packed_refs. If it goes to zero, 906 * free *packed_refs and return true; otherwise return false. 907 */ 908static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 909{ 910if(!--packed_refs->referrers) { 911free_ref_entry(packed_refs->root); 912stat_validity_clear(&packed_refs->validity); 913free(packed_refs); 914return1; 915}else{ 916return0; 917} 918} 919 920static voidclear_packed_ref_cache(struct ref_cache *refs) 921{ 922if(refs->packed) { 923struct packed_ref_cache *packed_refs = refs->packed; 924 925if(packed_refs->lock) 926die("internal error: packed-ref cache cleared while locked"); 927 refs->packed = NULL; 928release_packed_ref_cache(packed_refs); 929} 930} 931 932static voidclear_loose_ref_cache(struct ref_cache *refs) 933{ 934if(refs->loose) { 935free_ref_entry(refs->loose); 936 refs->loose = NULL; 937} 938} 939 940/* 941 * Create a new submodule ref cache and add it to the internal 942 * set of caches. 943 */ 944static struct ref_cache *create_ref_cache(const char*submodule) 945{ 946struct ref_cache *refs; 947if(!submodule) 948 submodule =""; 949FLEX_ALLOC_STR(refs, name, submodule); 950 refs->next = submodule_ref_caches; 951 submodule_ref_caches = refs; 952return refs; 953} 954 955static struct ref_cache *lookup_ref_cache(const char*submodule) 956{ 957struct ref_cache *refs; 958 959if(!submodule || !*submodule) 960return&ref_cache; 961 962for(refs = submodule_ref_caches; refs; refs = refs->next) 963if(!strcmp(submodule, refs->name)) 964return refs; 965return NULL; 966} 967 968/* 969 * Return a pointer to a ref_cache for the specified submodule. For 970 * the main repository, use submodule==NULL; such a call cannot fail. 971 * For a submodule, the submodule must exist and be a nonbare 972 * repository, otherwise return NULL. 973 * 974 * The returned structure will be allocated and initialized but not 975 * necessarily populated; it should not be freed. 976 */ 977static struct ref_cache *get_ref_cache(const char*submodule) 978{ 979struct ref_cache *refs =lookup_ref_cache(submodule); 980 981if(!refs) { 982struct strbuf submodule_sb = STRBUF_INIT; 983 984strbuf_addstr(&submodule_sb, submodule); 985if(is_nonbare_repository_dir(&submodule_sb)) 986 refs =create_ref_cache(submodule); 987strbuf_release(&submodule_sb); 988} 989 990return refs; 991} 992 993/* The length of a peeled reference line in packed-refs, including EOL: */ 994#define PEELED_LINE_LENGTH 42 995 996/* 997 * The packed-refs header line that we write out. Perhaps other 998 * traits will be added later. The trailing space is required. 999 */1000static const char PACKED_REFS_HEADER[] =1001"# pack-refs with: peeled fully-peeled\n";10021003/*1004 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1005 * Return a pointer to the refname within the line (null-terminated),1006 * or NULL if there was a problem.1007 */1008static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1009{1010const char*ref;10111012/*1013 * 42: the answer to everything.1014 *1015 * In this case, it happens to be the answer to1016 * 40 (length of sha1 hex representation)1017 * +1 (space in between hex and name)1018 * +1 (newline at the end of the line)1019 */1020if(line->len <=42)1021return NULL;10221023if(get_sha1_hex(line->buf, sha1) <0)1024return NULL;1025if(!isspace(line->buf[40]))1026return NULL;10271028 ref = line->buf +41;1029if(isspace(*ref))1030return NULL;10311032if(line->buf[line->len -1] !='\n')1033return NULL;1034 line->buf[--line->len] =0;10351036return ref;1037}10381039/*1040 * Read f, which is a packed-refs file, into dir.1041 *1042 * A comment line of the form "# pack-refs with: " may contain zero or1043 * more traits. We interpret the traits as follows:1044 *1045 * No traits:1046 *1047 * Probably no references are peeled. But if the file contains a1048 * peeled value for a reference, we will use it.1049 *1050 * peeled:1051 *1052 * References under "refs/tags/", if they *can* be peeled, *are*1053 * peeled in this file. References outside of "refs/tags/" are1054 * probably not peeled even if they could have been, but if we find1055 * a peeled value for such a reference we will use it.1056 *1057 * fully-peeled:1058 *1059 * All references in the file that can be peeled are peeled.1060 * Inversely (and this is more important), any references in the1061 * file for which no peeled value is recorded is not peelable. This1062 * trait should typically be written alongside "peeled" for1063 * compatibility with older clients, but we do not require it1064 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1065 */1066static voidread_packed_refs(FILE*f,struct ref_dir *dir)1067{1068struct ref_entry *last = NULL;1069struct strbuf line = STRBUF_INIT;1070enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10711072while(strbuf_getwholeline(&line, f,'\n') != EOF) {1073unsigned char sha1[20];1074const char*refname;1075const char*traits;10761077if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1078if(strstr(traits," fully-peeled "))1079 peeled = PEELED_FULLY;1080else if(strstr(traits," peeled "))1081 peeled = PEELED_TAGS;1082/* perhaps other traits later as well */1083continue;1084}10851086 refname =parse_ref_line(&line, sha1);1087if(refname) {1088int flag = REF_ISPACKED;10891090if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1091if(!refname_is_safe(refname))1092die("packed refname is dangerous:%s", refname);1093hashclr(sha1);1094 flag |= REF_BAD_NAME | REF_ISBROKEN;1095}1096 last =create_ref_entry(refname, sha1, flag,0);1097if(peeled == PEELED_FULLY ||1098(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1099 last->flag |= REF_KNOWS_PEELED;1100add_ref(dir, last);1101continue;1102}1103if(last &&1104 line.buf[0] =='^'&&1105 line.len == PEELED_LINE_LENGTH &&1106 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1107!get_sha1_hex(line.buf +1, sha1)) {1108hashcpy(last->u.value.peeled.hash, sha1);1109/*1110 * Regardless of what the file header said,1111 * we definitely know the value of *this*1112 * reference:1113 */1114 last->flag |= REF_KNOWS_PEELED;1115}1116}11171118strbuf_release(&line);1119}11201121/*1122 * Get the packed_ref_cache for the specified ref_cache, creating it1123 * if necessary.1124 */1125static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1126{1127char*packed_refs_file;11281129if(*refs->name)1130 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1131else1132 packed_refs_file =git_pathdup("packed-refs");11331134if(refs->packed &&1135!stat_validity_check(&refs->packed->validity, packed_refs_file))1136clear_packed_ref_cache(refs);11371138if(!refs->packed) {1139FILE*f;11401141 refs->packed =xcalloc(1,sizeof(*refs->packed));1142acquire_packed_ref_cache(refs->packed);1143 refs->packed->root =create_dir_entry(refs,"",0,0);1144 f =fopen(packed_refs_file,"r");1145if(f) {1146stat_validity_update(&refs->packed->validity,fileno(f));1147read_packed_refs(f,get_ref_dir(refs->packed->root));1148fclose(f);1149}1150}1151free(packed_refs_file);1152return refs->packed;1153}11541155static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1156{1157returnget_ref_dir(packed_ref_cache->root);1158}11591160static struct ref_dir *get_packed_refs(struct ref_cache *refs)1161{1162returnget_packed_ref_dir(get_packed_ref_cache(refs));1163}11641165/*1166 * Add a reference to the in-memory packed reference cache. This may1167 * only be called while the packed-refs file is locked (see1168 * lock_packed_refs()). To actually write the packed-refs file, call1169 * commit_packed_refs().1170 */1171static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1172{1173struct packed_ref_cache *packed_ref_cache =1174get_packed_ref_cache(&ref_cache);11751176if(!packed_ref_cache->lock)1177die("internal error: packed refs not locked");1178add_ref(get_packed_ref_dir(packed_ref_cache),1179create_ref_entry(refname, sha1, REF_ISPACKED,1));1180}11811182/*1183 * Read the loose references from the namespace dirname into dir1184 * (without recursing). dirname must end with '/'. dir must be the1185 * directory entry corresponding to dirname.1186 */1187static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1188{1189struct ref_cache *refs = dir->ref_cache;1190DIR*d;1191struct dirent *de;1192int dirnamelen =strlen(dirname);1193struct strbuf refname;1194struct strbuf path = STRBUF_INIT;1195size_t path_baselen;11961197if(*refs->name)1198strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1199else1200strbuf_git_path(&path,"%s", dirname);1201 path_baselen = path.len;12021203 d =opendir(path.buf);1204if(!d) {1205strbuf_release(&path);1206return;1207}12081209strbuf_init(&refname, dirnamelen +257);1210strbuf_add(&refname, dirname, dirnamelen);12111212while((de =readdir(d)) != NULL) {1213unsigned char sha1[20];1214struct stat st;1215int flag;12161217if(de->d_name[0] =='.')1218continue;1219if(ends_with(de->d_name,".lock"))1220continue;1221strbuf_addstr(&refname, de->d_name);1222strbuf_addstr(&path, de->d_name);1223if(stat(path.buf, &st) <0) {1224;/* silently ignore */1225}else if(S_ISDIR(st.st_mode)) {1226strbuf_addch(&refname,'/');1227add_entry_to_dir(dir,1228create_dir_entry(refs, refname.buf,1229 refname.len,1));1230}else{1231int read_ok;12321233if(*refs->name) {1234hashclr(sha1);1235 flag =0;1236 read_ok = !resolve_gitlink_ref(refs->name,1237 refname.buf, sha1);1238}else{1239 read_ok = !read_ref_full(refname.buf,1240 RESOLVE_REF_READING,1241 sha1, &flag);1242}12431244if(!read_ok) {1245hashclr(sha1);1246 flag |= REF_ISBROKEN;1247}else if(is_null_sha1(sha1)) {1248/*1249 * It is so astronomically unlikely1250 * that NULL_SHA1 is the SHA-1 of an1251 * actual object that we consider its1252 * appearance in a loose reference1253 * file to be repo corruption1254 * (probably due to a software bug).1255 */1256 flag |= REF_ISBROKEN;1257}12581259if(check_refname_format(refname.buf,1260 REFNAME_ALLOW_ONELEVEL)) {1261if(!refname_is_safe(refname.buf))1262die("loose refname is dangerous:%s", refname.buf);1263hashclr(sha1);1264 flag |= REF_BAD_NAME | REF_ISBROKEN;1265}1266add_entry_to_dir(dir,1267create_ref_entry(refname.buf, sha1, flag,0));1268}1269strbuf_setlen(&refname, dirnamelen);1270strbuf_setlen(&path, path_baselen);1271}1272strbuf_release(&refname);1273strbuf_release(&path);1274closedir(d);1275}12761277static struct ref_dir *get_loose_refs(struct ref_cache *refs)1278{1279if(!refs->loose) {1280/*1281 * Mark the top-level directory complete because we1282 * are about to read the only subdirectory that can1283 * hold references:1284 */1285 refs->loose =create_dir_entry(refs,"",0,0);1286/*1287 * Create an incomplete entry for "refs/":1288 */1289add_entry_to_dir(get_ref_dir(refs->loose),1290create_dir_entry(refs,"refs/",5,1));1291}1292returnget_ref_dir(refs->loose);1293}12941295#define MAXREFLEN (1024)12961297/*1298 * Called by resolve_gitlink_ref_recursive() after it failed to read1299 * from the loose refs in ref_cache refs. Find <refname> in the1300 * packed-refs file for the submodule.1301 */1302static intresolve_gitlink_packed_ref(struct ref_cache *refs,1303const char*refname,unsigned char*sha1)1304{1305struct ref_entry *ref;1306struct ref_dir *dir =get_packed_refs(refs);13071308 ref =find_ref(dir, refname);1309if(ref == NULL)1310return-1;13111312hashcpy(sha1, ref->u.value.oid.hash);1313return0;1314}13151316static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1317const char*refname,unsigned char*sha1,1318int recursion)1319{1320int fd, len;1321char buffer[128], *p;1322char*path;13231324if(recursion > SYMREF_MAXDEPTH ||strlen(refname) > MAXREFLEN)1325return-1;1326 path = *refs->name1327?git_pathdup_submodule(refs->name,"%s", refname)1328:git_pathdup("%s", refname);1329 fd =open(path, O_RDONLY);1330free(path);1331if(fd <0)1332returnresolve_gitlink_packed_ref(refs, refname, sha1);13331334 len =read(fd, buffer,sizeof(buffer)-1);1335close(fd);1336if(len <0)1337return-1;1338while(len &&isspace(buffer[len-1]))1339 len--;1340 buffer[len] =0;13411342/* Was it a detached head or an old-fashioned symlink? */1343if(!get_sha1_hex(buffer, sha1))1344return0;13451346/* Symref? */1347if(strncmp(buffer,"ref:",4))1348return-1;1349 p = buffer +4;1350while(isspace(*p))1351 p++;13521353returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1354}13551356intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1357{1358int len =strlen(path), retval;1359struct strbuf submodule = STRBUF_INIT;1360struct ref_cache *refs;13611362while(len && path[len-1] =='/')1363 len--;1364if(!len)1365return-1;13661367strbuf_add(&submodule, path, len);1368 refs =get_ref_cache(submodule.buf);1369if(!refs) {1370strbuf_release(&submodule);1371return-1;1372}1373strbuf_release(&submodule);13741375 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1376return retval;1377}13781379/*1380 * Return the ref_entry for the given refname from the packed1381 * references. If it does not exist, return NULL.1382 */1383static struct ref_entry *get_packed_ref(const char*refname)1384{1385returnfind_ref(get_packed_refs(&ref_cache), refname);1386}13871388/*1389 * A loose ref file doesn't exist; check for a packed ref.1390 */1391static intresolve_missing_loose_ref(const char*refname,1392unsigned char*sha1,1393unsigned int*flags)1394{1395struct ref_entry *entry;13961397/*1398 * The loose reference file does not exist; check for a packed1399 * reference.1400 */1401 entry =get_packed_ref(refname);1402if(entry) {1403hashcpy(sha1, entry->u.value.oid.hash);1404*flags |= REF_ISPACKED;1405return0;1406}1407/* refname is not a packed reference. */1408return-1;1409}14101411intread_raw_ref(const char*refname,unsigned char*sha1,1412struct strbuf *referent,unsigned int*type)1413{1414struct strbuf sb_contents = STRBUF_INIT;1415struct strbuf sb_path = STRBUF_INIT;1416const char*path;1417const char*buf;1418struct stat st;1419int fd;1420int ret = -1;1421int save_errno;14221423*type =0;1424strbuf_reset(&sb_path);1425strbuf_git_path(&sb_path,"%s", refname);1426 path = sb_path.buf;14271428stat_ref:1429/*1430 * We might have to loop back here to avoid a race1431 * condition: first we lstat() the file, then we try1432 * to read it as a link or as a file. But if somebody1433 * changes the type of the file (file <-> directory1434 * <-> symlink) between the lstat() and reading, then1435 * we don't want to report that as an error but rather1436 * try again starting with the lstat().1437 */14381439if(lstat(path, &st) <0) {1440if(errno != ENOENT)1441goto out;1442if(resolve_missing_loose_ref(refname, sha1, type)) {1443 errno = ENOENT;1444goto out;1445}1446 ret =0;1447goto out;1448}14491450/* Follow "normalized" - ie "refs/.." symlinks by hand */1451if(S_ISLNK(st.st_mode)) {1452strbuf_reset(&sb_contents);1453if(strbuf_readlink(&sb_contents, path,0) <0) {1454if(errno == ENOENT || errno == EINVAL)1455/* inconsistent with lstat; retry */1456goto stat_ref;1457else1458goto out;1459}1460if(starts_with(sb_contents.buf,"refs/") &&1461!check_refname_format(sb_contents.buf,0)) {1462strbuf_swap(&sb_contents, referent);1463*type |= REF_ISSYMREF;1464 ret =0;1465goto out;1466}1467}14681469/* Is it a directory? */1470if(S_ISDIR(st.st_mode)) {1471/*1472 * Even though there is a directory where the loose1473 * ref is supposed to be, there could still be a1474 * packed ref:1475 */1476if(resolve_missing_loose_ref(refname, sha1, type)) {1477 errno = EISDIR;1478goto out;1479}1480 ret =0;1481goto out;1482}14831484/*1485 * Anything else, just open it and try to use it as1486 * a ref1487 */1488 fd =open(path, O_RDONLY);1489if(fd <0) {1490if(errno == ENOENT)1491/* inconsistent with lstat; retry */1492goto stat_ref;1493else1494goto out;1495}1496strbuf_reset(&sb_contents);1497if(strbuf_read(&sb_contents, fd,256) <0) {1498int save_errno = errno;1499close(fd);1500 errno = save_errno;1501goto out;1502}1503close(fd);1504strbuf_rtrim(&sb_contents);1505 buf = sb_contents.buf;1506if(starts_with(buf,"ref:")) {1507 buf +=4;1508while(isspace(*buf))1509 buf++;15101511strbuf_reset(referent);1512strbuf_addstr(referent, buf);1513*type |= REF_ISSYMREF;1514 ret =0;1515goto out;1516}15171518/*1519 * Please note that FETCH_HEAD has additional1520 * data after the sha.1521 */1522if(get_sha1_hex(buf, sha1) ||1523(buf[40] !='\0'&& !isspace(buf[40]))) {1524*type |= REF_ISBROKEN;1525 errno = EINVAL;1526goto out;1527}15281529 ret =0;15301531out:1532 save_errno = errno;1533strbuf_release(&sb_path);1534strbuf_release(&sb_contents);1535 errno = save_errno;1536return ret;1537}15381539static voidunlock_ref(struct ref_lock *lock)1540{1541/* Do not free lock->lk -- atexit() still looks at them */1542if(lock->lk)1543rollback_lock_file(lock->lk);1544free(lock->ref_name);1545free(lock);1546}15471548/*1549 * Lock refname, without following symrefs, and set *lock_p to point1550 * at a newly-allocated lock object. Fill in lock->old_oid, referent,1551 * and type similarly to read_raw_ref().1552 *1553 * The caller must verify that refname is a "safe" reference name (in1554 * the sense of refname_is_safe()) before calling this function.1555 *1556 * If the reference doesn't already exist, verify that refname doesn't1557 * have a D/F conflict with any existing references. extras and skip1558 * are passed to verify_refname_available_dir() for this check.1559 *1560 * If mustexist is not set and the reference is not found or is1561 * broken, lock the reference anyway but clear sha1.1562 *1563 * Return 0 on success. On failure, write an error message to err and1564 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.1565 *1566 * Implementation note: This function is basically1567 *1568 * lock reference1569 * read_raw_ref()1570 *1571 * but it includes a lot more code to1572 * - Deal with possible races with other processes1573 * - Avoid calling verify_refname_available_dir() when it can be1574 * avoided, namely if we were successfully able to read the ref1575 * - Generate informative error messages in the case of failure1576 */1577static intlock_raw_ref(const char*refname,int mustexist,1578const struct string_list *extras,1579const struct string_list *skip,1580struct ref_lock **lock_p,1581struct strbuf *referent,1582unsigned int*type,1583struct strbuf *err)1584{1585struct ref_lock *lock;1586struct strbuf ref_file = STRBUF_INIT;1587int attempts_remaining =3;1588int ret = TRANSACTION_GENERIC_ERROR;15891590assert(err);1591*type =0;15921593/* First lock the file so it can't change out from under us. */15941595*lock_p = lock =xcalloc(1,sizeof(*lock));15961597 lock->ref_name =xstrdup(refname);1598strbuf_git_path(&ref_file,"%s", refname);15991600retry:1601switch(safe_create_leading_directories(ref_file.buf)) {1602case SCLD_OK:1603break;/* success */1604case SCLD_EXISTS:1605/*1606 * Suppose refname is "refs/foo/bar". We just failed1607 * to create the containing directory, "refs/foo",1608 * because there was a non-directory in the way. This1609 * indicates a D/F conflict, probably because of1610 * another reference such as "refs/foo". There is no1611 * reason to expect this error to be transitory.1612 */1613if(verify_refname_available(refname, extras, skip, err)) {1614if(mustexist) {1615/*1616 * To the user the relevant error is1617 * that the "mustexist" reference is1618 * missing:1619 */1620strbuf_reset(err);1621strbuf_addf(err,"unable to resolve reference '%s'",1622 refname);1623}else{1624/*1625 * The error message set by1626 * verify_refname_available_dir() is OK.1627 */1628 ret = TRANSACTION_NAME_CONFLICT;1629}1630}else{1631/*1632 * The file that is in the way isn't a loose1633 * reference. Report it as a low-level1634 * failure.1635 */1636strbuf_addf(err,"unable to create lock file%s.lock; "1637"non-directory in the way",1638 ref_file.buf);1639}1640goto error_return;1641case SCLD_VANISHED:1642/* Maybe another process was tidying up. Try again. */1643if(--attempts_remaining >0)1644goto retry;1645/* fall through */1646default:1647strbuf_addf(err,"unable to create directory for%s",1648 ref_file.buf);1649goto error_return;1650}16511652if(!lock->lk)1653 lock->lk =xcalloc(1,sizeof(struct lock_file));16541655if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) {1656if(errno == ENOENT && --attempts_remaining >0) {1657/*1658 * Maybe somebody just deleted one of the1659 * directories leading to ref_file. Try1660 * again:1661 */1662goto retry;1663}else{1664unable_to_lock_message(ref_file.buf, errno, err);1665goto error_return;1666}1667}16681669/*1670 * Now we hold the lock and can read the reference without1671 * fear that its value will change.1672 */16731674if(read_raw_ref(refname, lock->old_oid.hash, referent, type)) {1675if(errno == ENOENT) {1676if(mustexist) {1677/* Garden variety missing reference. */1678strbuf_addf(err,"unable to resolve reference '%s'",1679 refname);1680goto error_return;1681}else{1682/*1683 * Reference is missing, but that's OK. We1684 * know that there is not a conflict with1685 * another loose reference because1686 * (supposing that we are trying to lock1687 * reference "refs/foo/bar"):1688 *1689 * - We were successfully able to create1690 * the lockfile refs/foo/bar.lock, so we1691 * know there cannot be a loose reference1692 * named "refs/foo".1693 *1694 * - We got ENOENT and not EISDIR, so we1695 * know that there cannot be a loose1696 * reference named "refs/foo/bar/baz".1697 */1698}1699}else if(errno == EISDIR) {1700/*1701 * There is a directory in the way. It might have1702 * contained references that have been deleted. If1703 * we don't require that the reference already1704 * exists, try to remove the directory so that it1705 * doesn't cause trouble when we want to rename the1706 * lockfile into place later.1707 */1708if(mustexist) {1709/* Garden variety missing reference. */1710strbuf_addf(err,"unable to resolve reference '%s'",1711 refname);1712goto error_return;1713}else if(remove_dir_recursively(&ref_file,1714 REMOVE_DIR_EMPTY_ONLY)) {1715if(verify_refname_available_dir(1716 refname, extras, skip,1717get_loose_refs(&ref_cache),1718 err)) {1719/*1720 * The error message set by1721 * verify_refname_available() is OK.1722 */1723 ret = TRANSACTION_NAME_CONFLICT;1724goto error_return;1725}else{1726/*1727 * We can't delete the directory,1728 * but we also don't know of any1729 * references that it should1730 * contain.1731 */1732strbuf_addf(err,"there is a non-empty directory '%s' "1733"blocking reference '%s'",1734 ref_file.buf, refname);1735goto error_return;1736}1737}1738}else if(errno == EINVAL && (*type & REF_ISBROKEN)) {1739strbuf_addf(err,"unable to resolve reference '%s': "1740"reference broken", refname);1741goto error_return;1742}else{1743strbuf_addf(err,"unable to resolve reference '%s':%s",1744 refname,strerror(errno));1745goto error_return;1746}17471748/*1749 * If the ref did not exist and we are creating it,1750 * make sure there is no existing packed ref whose1751 * name begins with our refname, nor a packed ref1752 * whose name is a proper prefix of our refname.1753 */1754if(verify_refname_available_dir(1755 refname, extras, skip,1756get_packed_refs(&ref_cache),1757 err)) {1758goto error_return;1759}1760}17611762 ret =0;1763goto out;17641765error_return:1766unlock_ref(lock);1767*lock_p = NULL;17681769out:1770strbuf_release(&ref_file);1771return ret;1772}17731774/*1775 * Peel the entry (if possible) and return its new peel_status. If1776 * repeel is true, re-peel the entry even if there is an old peeled1777 * value that is already stored in it.1778 *1779 * It is OK to call this function with a packed reference entry that1780 * might be stale and might even refer to an object that has since1781 * been garbage-collected. In such a case, if the entry has1782 * REF_KNOWS_PEELED then leave the status unchanged and return1783 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1784 */1785static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1786{1787enum peel_status status;17881789if(entry->flag & REF_KNOWS_PEELED) {1790if(repeel) {1791 entry->flag &= ~REF_KNOWS_PEELED;1792oidclr(&entry->u.value.peeled);1793}else{1794returnis_null_oid(&entry->u.value.peeled) ?1795 PEEL_NON_TAG : PEEL_PEELED;1796}1797}1798if(entry->flag & REF_ISBROKEN)1799return PEEL_BROKEN;1800if(entry->flag & REF_ISSYMREF)1801return PEEL_IS_SYMREF;18021803 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1804if(status == PEEL_PEELED || status == PEEL_NON_TAG)1805 entry->flag |= REF_KNOWS_PEELED;1806return status;1807}18081809intpeel_ref(const char*refname,unsigned char*sha1)1810{1811int flag;1812unsigned char base[20];18131814if(current_ref && (current_ref->name == refname1815|| !strcmp(current_ref->name, refname))) {1816if(peel_entry(current_ref,0))1817return-1;1818hashcpy(sha1, current_ref->u.value.peeled.hash);1819return0;1820}18211822if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1823return-1;18241825/*1826 * If the reference is packed, read its ref_entry from the1827 * cache in the hope that we already know its peeled value.1828 * We only try this optimization on packed references because1829 * (a) forcing the filling of the loose reference cache could1830 * be expensive and (b) loose references anyway usually do not1831 * have REF_KNOWS_PEELED.1832 */1833if(flag & REF_ISPACKED) {1834struct ref_entry *r =get_packed_ref(refname);1835if(r) {1836if(peel_entry(r,0))1837return-1;1838hashcpy(sha1, r->u.value.peeled.hash);1839return0;1840}1841}18421843returnpeel_object(base, sha1);1844}18451846/*1847 * Call fn for each reference in the specified ref_cache, omitting1848 * references not in the containing_dir of prefix. Call fn for all1849 * references, including broken ones. If fn ever returns a non-zero1850 * value, stop the iteration and return that value; otherwise, return1851 * 0.1852 */1853static intdo_for_each_entry(struct ref_cache *refs,const char*prefix,1854 each_ref_entry_fn fn,void*cb_data)1855{1856struct packed_ref_cache *packed_ref_cache;1857struct ref_dir *loose_dir;1858struct ref_dir *packed_dir;1859int retval =0;18601861/*1862 * We must make sure that all loose refs are read before accessing the1863 * packed-refs file; this avoids a race condition in which loose refs1864 * are migrated to the packed-refs file by a simultaneous process, but1865 * our in-memory view is from before the migration. get_packed_ref_cache()1866 * takes care of making sure our view is up to date with what is on1867 * disk.1868 */1869 loose_dir =get_loose_refs(refs);1870if(prefix && *prefix) {1871 loose_dir =find_containing_dir(loose_dir, prefix,0);1872}1873if(loose_dir)1874prime_ref_dir(loose_dir);18751876 packed_ref_cache =get_packed_ref_cache(refs);1877acquire_packed_ref_cache(packed_ref_cache);1878 packed_dir =get_packed_ref_dir(packed_ref_cache);1879if(prefix && *prefix) {1880 packed_dir =find_containing_dir(packed_dir, prefix,0);1881}18821883if(packed_dir && loose_dir) {1884sort_ref_dir(packed_dir);1885sort_ref_dir(loose_dir);1886 retval =do_for_each_entry_in_dirs(1887 packed_dir, loose_dir, fn, cb_data);1888}else if(packed_dir) {1889sort_ref_dir(packed_dir);1890 retval =do_for_each_entry_in_dir(1891 packed_dir,0, fn, cb_data);1892}else if(loose_dir) {1893sort_ref_dir(loose_dir);1894 retval =do_for_each_entry_in_dir(1895 loose_dir,0, fn, cb_data);1896}18971898release_packed_ref_cache(packed_ref_cache);1899return retval;1900}19011902intdo_for_each_ref(const char*submodule,const char*prefix,1903 each_ref_fn fn,int trim,int flags,void*cb_data)1904{1905struct ref_entry_cb data;1906struct ref_cache *refs;19071908 refs =get_ref_cache(submodule);1909if(!refs)1910return0;19111912 data.prefix = prefix;1913 data.trim = trim;1914 data.flags = flags;1915 data.fn = fn;1916 data.cb_data = cb_data;19171918if(ref_paranoia <0)1919 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1920if(ref_paranoia)1921 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;19221923returndo_for_each_entry(refs, prefix, do_one_ref, &data);1924}19251926/*1927 * Verify that the reference locked by lock has the value old_sha1.1928 * Fail if the reference doesn't exist and mustexist is set. Return 01929 * on success. On error, write an error message to err, set errno, and1930 * return a negative value.1931 */1932static intverify_lock(struct ref_lock *lock,1933const unsigned char*old_sha1,int mustexist,1934struct strbuf *err)1935{1936assert(err);19371938if(read_ref_full(lock->ref_name,1939 mustexist ? RESOLVE_REF_READING :0,1940 lock->old_oid.hash, NULL)) {1941if(old_sha1) {1942int save_errno = errno;1943strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1944 errno = save_errno;1945return-1;1946}else{1947hashclr(lock->old_oid.hash);1948return0;1949}1950}1951if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1952strbuf_addf(err,"ref '%s' is at%sbut expected%s",1953 lock->ref_name,1954sha1_to_hex(lock->old_oid.hash),1955sha1_to_hex(old_sha1));1956 errno = EBUSY;1957return-1;1958}1959return0;1960}19611962static intremove_empty_directories(struct strbuf *path)1963{1964/*1965 * we want to create a file but there is a directory there;1966 * if that is an empty directory (or a directory that contains1967 * only empty directories), remove them.1968 */1969returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1970}19711972/*1973 * Locks a ref returning the lock on success and NULL on failure.1974 * On failure errno is set to something meaningful.1975 */1976static struct ref_lock *lock_ref_sha1_basic(const char*refname,1977const unsigned char*old_sha1,1978const struct string_list *extras,1979const struct string_list *skip,1980unsigned int flags,int*type,1981struct strbuf *err)1982{1983struct strbuf ref_file = STRBUF_INIT;1984struct ref_lock *lock;1985int last_errno =0;1986int lflags = LOCK_NO_DEREF;1987int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1988int resolve_flags = RESOLVE_REF_NO_RECURSE;1989int attempts_remaining =3;1990int resolved;19911992assert(err);19931994 lock =xcalloc(1,sizeof(struct ref_lock));19951996if(mustexist)1997 resolve_flags |= RESOLVE_REF_READING;1998if(flags & REF_DELETING)1999 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;20002001strbuf_git_path(&ref_file,"%s", refname);2002 resolved = !!resolve_ref_unsafe(refname, resolve_flags,2003 lock->old_oid.hash, type);2004if(!resolved && errno == EISDIR) {2005/*2006 * we are trying to lock foo but we used to2007 * have foo/bar which now does not exist;2008 * it is normal for the empty directory 'foo'2009 * to remain.2010 */2011if(remove_empty_directories(&ref_file)) {2012 last_errno = errno;2013if(!verify_refname_available_dir(refname, extras, skip,2014get_loose_refs(&ref_cache), err))2015strbuf_addf(err,"there are still refs under '%s'",2016 refname);2017goto error_return;2018}2019 resolved = !!resolve_ref_unsafe(refname, resolve_flags,2020 lock->old_oid.hash, type);2021}2022if(!resolved) {2023 last_errno = errno;2024if(last_errno != ENOTDIR ||2025!verify_refname_available_dir(refname, extras, skip,2026get_loose_refs(&ref_cache), err))2027strbuf_addf(err,"unable to resolve reference '%s':%s",2028 refname,strerror(last_errno));20292030goto error_return;2031}20322033/*2034 * If the ref did not exist and we are creating it, make sure2035 * there is no existing packed ref whose name begins with our2036 * refname, nor a packed ref whose name is a proper prefix of2037 * our refname.2038 */2039if(is_null_oid(&lock->old_oid) &&2040verify_refname_available_dir(refname, extras, skip,2041get_packed_refs(&ref_cache), err)) {2042 last_errno = ENOTDIR;2043goto error_return;2044}20452046 lock->lk =xcalloc(1,sizeof(struct lock_file));20472048 lock->ref_name =xstrdup(refname);20492050 retry:2051switch(safe_create_leading_directories_const(ref_file.buf)) {2052case SCLD_OK:2053break;/* success */2054case SCLD_VANISHED:2055if(--attempts_remaining >0)2056goto retry;2057/* fall through */2058default:2059 last_errno = errno;2060strbuf_addf(err,"unable to create directory for '%s'",2061 ref_file.buf);2062goto error_return;2063}20642065if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2066 last_errno = errno;2067if(errno == ENOENT && --attempts_remaining >0)2068/*2069 * Maybe somebody just deleted one of the2070 * directories leading to ref_file. Try2071 * again:2072 */2073goto retry;2074else{2075unable_to_lock_message(ref_file.buf, errno, err);2076goto error_return;2077}2078}2079if(verify_lock(lock, old_sha1, mustexist, err)) {2080 last_errno = errno;2081goto error_return;2082}2083goto out;20842085 error_return:2086unlock_ref(lock);2087 lock = NULL;20882089 out:2090strbuf_release(&ref_file);2091 errno = last_errno;2092return lock;2093}20942095/*2096 * Write an entry to the packed-refs file for the specified refname.2097 * If peeled is non-NULL, write it as the entry's peeled value.2098 */2099static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2100unsigned char*peeled)2101{2102fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2103if(peeled)2104fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2105}21062107/*2108 * An each_ref_entry_fn that writes the entry to a packed-refs file.2109 */2110static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2111{2112enum peel_status peel_status =peel_entry(entry,0);21132114if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2115error("internal error:%sis not a valid packed reference!",2116 entry->name);2117write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2118 peel_status == PEEL_PEELED ?2119 entry->u.value.peeled.hash : NULL);2120return0;2121}21222123/*2124 * Lock the packed-refs file for writing. Flags is passed to2125 * hold_lock_file_for_update(). Return 0 on success. On errors, set2126 * errno appropriately and return a nonzero value.2127 */2128static intlock_packed_refs(int flags)2129{2130static int timeout_configured =0;2131static int timeout_value =1000;21322133struct packed_ref_cache *packed_ref_cache;21342135if(!timeout_configured) {2136git_config_get_int("core.packedrefstimeout", &timeout_value);2137 timeout_configured =1;2138}21392140if(hold_lock_file_for_update_timeout(2141&packlock,git_path("packed-refs"),2142 flags, timeout_value) <0)2143return-1;2144/*2145 * Get the current packed-refs while holding the lock. If the2146 * packed-refs file has been modified since we last read it,2147 * this will automatically invalidate the cache and re-read2148 * the packed-refs file.2149 */2150 packed_ref_cache =get_packed_ref_cache(&ref_cache);2151 packed_ref_cache->lock = &packlock;2152/* Increment the reference count to prevent it from being freed: */2153acquire_packed_ref_cache(packed_ref_cache);2154return0;2155}21562157/*2158 * Write the current version of the packed refs cache from memory to2159 * disk. The packed-refs file must already be locked for writing (see2160 * lock_packed_refs()). Return zero on success. On errors, set errno2161 * and return a nonzero value2162 */2163static intcommit_packed_refs(void)2164{2165struct packed_ref_cache *packed_ref_cache =2166get_packed_ref_cache(&ref_cache);2167int error =0;2168int save_errno =0;2169FILE*out;21702171if(!packed_ref_cache->lock)2172die("internal error: packed-refs not locked");21732174 out =fdopen_lock_file(packed_ref_cache->lock,"w");2175if(!out)2176die_errno("unable to fdopen packed-refs descriptor");21772178fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2179do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),21800, write_packed_entry_fn, out);21812182if(commit_lock_file(packed_ref_cache->lock)) {2183 save_errno = errno;2184 error = -1;2185}2186 packed_ref_cache->lock = NULL;2187release_packed_ref_cache(packed_ref_cache);2188 errno = save_errno;2189return error;2190}21912192/*2193 * Rollback the lockfile for the packed-refs file, and discard the2194 * in-memory packed reference cache. (The packed-refs file will be2195 * read anew if it is needed again after this function is called.)2196 */2197static voidrollback_packed_refs(void)2198{2199struct packed_ref_cache *packed_ref_cache =2200get_packed_ref_cache(&ref_cache);22012202if(!packed_ref_cache->lock)2203die("internal error: packed-refs not locked");2204rollback_lock_file(packed_ref_cache->lock);2205 packed_ref_cache->lock = NULL;2206release_packed_ref_cache(packed_ref_cache);2207clear_packed_ref_cache(&ref_cache);2208}22092210struct ref_to_prune {2211struct ref_to_prune *next;2212unsigned char sha1[20];2213char name[FLEX_ARRAY];2214};22152216struct pack_refs_cb_data {2217unsigned int flags;2218struct ref_dir *packed_refs;2219struct ref_to_prune *ref_to_prune;2220};22212222/*2223 * An each_ref_entry_fn that is run over loose references only. If2224 * the loose reference can be packed, add an entry in the packed ref2225 * cache. If the reference should be pruned, also add it to2226 * ref_to_prune in the pack_refs_cb_data.2227 */2228static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2229{2230struct pack_refs_cb_data *cb = cb_data;2231enum peel_status peel_status;2232struct ref_entry *packed_entry;2233int is_tag_ref =starts_with(entry->name,"refs/tags/");22342235/* Do not pack per-worktree refs: */2236if(ref_type(entry->name) != REF_TYPE_NORMAL)2237return0;22382239/* ALWAYS pack tags */2240if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2241return0;22422243/* Do not pack symbolic or broken refs: */2244if((entry->flag & REF_ISSYMREF) || !entry_resolves_to_object(entry))2245return0;22462247/* Add a packed ref cache entry equivalent to the loose entry. */2248 peel_status =peel_entry(entry,1);2249if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2250die("internal error peeling reference%s(%s)",2251 entry->name,oid_to_hex(&entry->u.value.oid));2252 packed_entry =find_ref(cb->packed_refs, entry->name);2253if(packed_entry) {2254/* Overwrite existing packed entry with info from loose entry */2255 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2256oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2257}else{2258 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2259 REF_ISPACKED | REF_KNOWS_PEELED,0);2260add_ref(cb->packed_refs, packed_entry);2261}2262oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);22632264/* Schedule the loose reference for pruning if requested. */2265if((cb->flags & PACK_REFS_PRUNE)) {2266struct ref_to_prune *n;2267FLEX_ALLOC_STR(n, name, entry->name);2268hashcpy(n->sha1, entry->u.value.oid.hash);2269 n->next = cb->ref_to_prune;2270 cb->ref_to_prune = n;2271}2272return0;2273}22742275/*2276 * Remove empty parents, but spare refs/ and immediate subdirs.2277 * Note: munges *name.2278 */2279static voidtry_remove_empty_parents(char*name)2280{2281char*p, *q;2282int i;2283 p = name;2284for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2285while(*p && *p !='/')2286 p++;2287/* tolerate duplicate slashes; see check_refname_format() */2288while(*p =='/')2289 p++;2290}2291for(q = p; *q; q++)2292;2293while(1) {2294while(q > p && *q !='/')2295 q--;2296while(q > p && *(q-1) =='/')2297 q--;2298if(q == p)2299break;2300*q ='\0';2301if(rmdir(git_path("%s", name)))2302break;2303}2304}23052306/* make sure nobody touched the ref, and unlink */2307static voidprune_ref(struct ref_to_prune *r)2308{2309struct ref_transaction *transaction;2310struct strbuf err = STRBUF_INIT;23112312if(check_refname_format(r->name,0))2313return;23142315 transaction =ref_transaction_begin(&err);2316if(!transaction ||2317ref_transaction_delete(transaction, r->name, r->sha1,2318 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||2319ref_transaction_commit(transaction, &err)) {2320ref_transaction_free(transaction);2321error("%s", err.buf);2322strbuf_release(&err);2323return;2324}2325ref_transaction_free(transaction);2326strbuf_release(&err);2327try_remove_empty_parents(r->name);2328}23292330static voidprune_refs(struct ref_to_prune *r)2331{2332while(r) {2333prune_ref(r);2334 r = r->next;2335}2336}23372338intpack_refs(unsigned int flags)2339{2340struct pack_refs_cb_data cbdata;23412342memset(&cbdata,0,sizeof(cbdata));2343 cbdata.flags = flags;23442345lock_packed_refs(LOCK_DIE_ON_ERROR);2346 cbdata.packed_refs =get_packed_refs(&ref_cache);23472348do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2349 pack_if_possible_fn, &cbdata);23502351if(commit_packed_refs())2352die_errno("unable to overwrite old ref-pack file");23532354prune_refs(cbdata.ref_to_prune);2355return0;2356}23572358/*2359 * Rewrite the packed-refs file, omitting any refs listed in2360 * 'refnames'. On error, leave packed-refs unchanged, write an error2361 * message to 'err', and return a nonzero value.2362 *2363 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2364 */2365static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2366{2367struct ref_dir *packed;2368struct string_list_item *refname;2369int ret, needs_repacking =0, removed =0;23702371assert(err);23722373/* Look for a packed ref */2374for_each_string_list_item(refname, refnames) {2375if(get_packed_ref(refname->string)) {2376 needs_repacking =1;2377break;2378}2379}23802381/* Avoid locking if we have nothing to do */2382if(!needs_repacking)2383return0;/* no refname exists in packed refs */23842385if(lock_packed_refs(0)) {2386unable_to_lock_message(git_path("packed-refs"), errno, err);2387return-1;2388}2389 packed =get_packed_refs(&ref_cache);23902391/* Remove refnames from the cache */2392for_each_string_list_item(refname, refnames)2393if(remove_entry(packed, refname->string) != -1)2394 removed =1;2395if(!removed) {2396/*2397 * All packed entries disappeared while we were2398 * acquiring the lock.2399 */2400rollback_packed_refs();2401return0;2402}24032404/* Write what remains */2405 ret =commit_packed_refs();2406if(ret)2407strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2408strerror(errno));2409return ret;2410}24112412static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2413{2414assert(err);24152416if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2417/*2418 * loose. The loose file name is the same as the2419 * lockfile name, minus ".lock":2420 */2421char*loose_filename =get_locked_file_path(lock->lk);2422int res =unlink_or_msg(loose_filename, err);2423free(loose_filename);2424if(res)2425return1;2426}2427return0;2428}24292430intdelete_refs(struct string_list *refnames,unsigned int flags)2431{2432struct strbuf err = STRBUF_INIT;2433int i, result =0;24342435if(!refnames->nr)2436return0;24372438 result =repack_without_refs(refnames, &err);2439if(result) {2440/*2441 * If we failed to rewrite the packed-refs file, then2442 * it is unsafe to try to remove loose refs, because2443 * doing so might expose an obsolete packed value for2444 * a reference that might even point at an object that2445 * has been garbage collected.2446 */2447if(refnames->nr ==1)2448error(_("could not delete reference%s:%s"),2449 refnames->items[0].string, err.buf);2450else2451error(_("could not delete references:%s"), err.buf);24522453goto out;2454}24552456for(i =0; i < refnames->nr; i++) {2457const char*refname = refnames->items[i].string;24582459if(delete_ref(refname, NULL, flags))2460 result |=error(_("could not remove reference%s"), refname);2461}24622463out:2464strbuf_release(&err);2465return result;2466}24672468/*2469 * People using contrib's git-new-workdir have .git/logs/refs ->2470 * /some/other/path/.git/logs/refs, and that may live on another device.2471 *2472 * IOW, to avoid cross device rename errors, the temporary renamed log must2473 * live into logs/refs.2474 */2475#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"24762477static intrename_tmp_log(const char*newrefname)2478{2479int attempts_remaining =4;2480struct strbuf path = STRBUF_INIT;2481int ret = -1;24822483 retry:2484strbuf_reset(&path);2485strbuf_git_path(&path,"logs/%s", newrefname);2486switch(safe_create_leading_directories_const(path.buf)) {2487case SCLD_OK:2488break;/* success */2489case SCLD_VANISHED:2490if(--attempts_remaining >0)2491goto retry;2492/* fall through */2493default:2494error("unable to create directory for%s", newrefname);2495goto out;2496}24972498if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2499if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2500/*2501 * rename(a, b) when b is an existing2502 * directory ought to result in ISDIR, but2503 * Solaris 5.8 gives ENOTDIR. Sheesh.2504 */2505if(remove_empty_directories(&path)) {2506error("Directory not empty: logs/%s", newrefname);2507goto out;2508}2509goto retry;2510}else if(errno == ENOENT && --attempts_remaining >0) {2511/*2512 * Maybe another process just deleted one of2513 * the directories in the path to newrefname.2514 * Try again from the beginning.2515 */2516goto retry;2517}else{2518error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2519 newrefname,strerror(errno));2520goto out;2521}2522}2523 ret =0;2524out:2525strbuf_release(&path);2526return ret;2527}25282529intverify_refname_available(const char*newname,2530const struct string_list *extras,2531const struct string_list *skip,2532struct strbuf *err)2533{2534struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2535struct ref_dir *loose_refs =get_loose_refs(&ref_cache);25362537if(verify_refname_available_dir(newname, extras, skip,2538 packed_refs, err) ||2539verify_refname_available_dir(newname, extras, skip,2540 loose_refs, err))2541return-1;25422543return0;2544}25452546static intwrite_ref_to_lockfile(struct ref_lock *lock,2547const unsigned char*sha1,struct strbuf *err);2548static intcommit_ref_update(struct ref_lock *lock,2549const unsigned char*sha1,const char*logmsg,2550struct strbuf *err);25512552intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2553{2554unsigned char sha1[20], orig_sha1[20];2555int flag =0, logmoved =0;2556struct ref_lock *lock;2557struct stat loginfo;2558int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2559struct strbuf err = STRBUF_INIT;25602561if(log &&S_ISLNK(loginfo.st_mode))2562returnerror("reflog for%sis a symlink", oldrefname);25632564if(!resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2565 orig_sha1, &flag))2566returnerror("refname%snot found", oldrefname);25672568if(flag & REF_ISSYMREF)2569returnerror("refname%sis a symbolic ref, renaming it is not supported",2570 oldrefname);2571if(!rename_ref_available(oldrefname, newrefname))2572return1;25732574if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2575returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2576 oldrefname,strerror(errno));25772578if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2579error("unable to delete old%s", oldrefname);2580goto rollback;2581}25822583/*2584 * Since we are doing a shallow lookup, sha1 is not the2585 * correct value to pass to delete_ref as old_sha1. But that2586 * doesn't matter, because an old_sha1 check wouldn't add to2587 * the safety anyway; we want to delete the reference whatever2588 * its current value.2589 */2590if(!read_ref_full(newrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2591 sha1, NULL) &&2592delete_ref(newrefname, NULL, REF_NODEREF)) {2593if(errno==EISDIR) {2594struct strbuf path = STRBUF_INIT;2595int result;25962597strbuf_git_path(&path,"%s", newrefname);2598 result =remove_empty_directories(&path);2599strbuf_release(&path);26002601if(result) {2602error("Directory not empty:%s", newrefname);2603goto rollback;2604}2605}else{2606error("unable to delete existing%s", newrefname);2607goto rollback;2608}2609}26102611if(log &&rename_tmp_log(newrefname))2612goto rollback;26132614 logmoved = log;26152616 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, REF_NODEREF,2617 NULL, &err);2618if(!lock) {2619error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2620strbuf_release(&err);2621goto rollback;2622}2623hashcpy(lock->old_oid.hash, orig_sha1);26242625if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2626commit_ref_update(lock, orig_sha1, logmsg, &err)) {2627error("unable to write current sha1 into%s:%s", newrefname, err.buf);2628strbuf_release(&err);2629goto rollback;2630}26312632return0;26332634 rollback:2635 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, REF_NODEREF,2636 NULL, &err);2637if(!lock) {2638error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2639strbuf_release(&err);2640goto rollbacklog;2641}26422643 flag = log_all_ref_updates;2644 log_all_ref_updates =0;2645if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2646commit_ref_update(lock, orig_sha1, NULL, &err)) {2647error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2648strbuf_release(&err);2649}2650 log_all_ref_updates = flag;26512652 rollbacklog:2653if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2654error("unable to restore logfile%sfrom%s:%s",2655 oldrefname, newrefname,strerror(errno));2656if(!logmoved && log &&2657rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2658error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2659 oldrefname,strerror(errno));26602661return1;2662}26632664static intclose_ref(struct ref_lock *lock)2665{2666if(close_lock_file(lock->lk))2667return-1;2668return0;2669}26702671static intcommit_ref(struct ref_lock *lock)2672{2673char*path =get_locked_file_path(lock->lk);2674struct stat st;26752676if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {2677/*2678 * There is a directory at the path we want to rename2679 * the lockfile to. Hopefully it is empty; try to2680 * delete it.2681 */2682size_t len =strlen(path);2683struct strbuf sb_path = STRBUF_INIT;26842685strbuf_attach(&sb_path, path, len, len);26862687/*2688 * If this fails, commit_lock_file() will also fail2689 * and will report the problem.2690 */2691remove_empty_directories(&sb_path);2692strbuf_release(&sb_path);2693}else{2694free(path);2695}26962697if(commit_lock_file(lock->lk))2698return-1;2699return0;2700}27012702/*2703 * Create a reflog for a ref. If force_create = 0, the reflog will2704 * only be created for certain refs (those for which2705 * should_autocreate_reflog returns non-zero. Otherwise, create it2706 * regardless of the ref name. Fill in *err and return -1 on failure.2707 */2708static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2709{2710int logfd, oflags = O_APPEND | O_WRONLY;27112712strbuf_git_path(logfile,"logs/%s", refname);2713if(force_create ||should_autocreate_reflog(refname)) {2714if(safe_create_leading_directories(logfile->buf) <0) {2715strbuf_addf(err,"unable to create directory for '%s': "2716"%s", logfile->buf,strerror(errno));2717return-1;2718}2719 oflags |= O_CREAT;2720}27212722 logfd =open(logfile->buf, oflags,0666);2723if(logfd <0) {2724if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2725return0;27262727if(errno == EISDIR) {2728if(remove_empty_directories(logfile)) {2729strbuf_addf(err,"there are still logs under "2730"'%s'", logfile->buf);2731return-1;2732}2733 logfd =open(logfile->buf, oflags,0666);2734}27352736if(logfd <0) {2737strbuf_addf(err,"unable to append to '%s':%s",2738 logfile->buf,strerror(errno));2739return-1;2740}2741}27422743adjust_shared_perm(logfile->buf);2744close(logfd);2745return0;2746}274727482749intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2750{2751int ret;2752struct strbuf sb = STRBUF_INIT;27532754 ret =log_ref_setup(refname, &sb, err, force_create);2755strbuf_release(&sb);2756return ret;2757}27582759static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2760const unsigned char*new_sha1,2761const char*committer,const char*msg)2762{2763int msglen, written;2764unsigned maxlen, len;2765char*logrec;27662767 msglen = msg ?strlen(msg) :0;2768 maxlen =strlen(committer) + msglen +100;2769 logrec =xmalloc(maxlen);2770 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2771sha1_to_hex(old_sha1),2772sha1_to_hex(new_sha1),2773 committer);2774if(msglen)2775 len +=copy_reflog_msg(logrec + len -1, msg) -1;27762777 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2778free(logrec);2779if(written != len)2780return-1;27812782return0;2783}27842785static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2786const unsigned char*new_sha1,const char*msg,2787struct strbuf *logfile,int flags,2788struct strbuf *err)2789{2790int logfd, result, oflags = O_APPEND | O_WRONLY;27912792if(log_all_ref_updates <0)2793 log_all_ref_updates = !is_bare_repository();27942795 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);27962797if(result)2798return result;27992800 logfd =open(logfile->buf, oflags);2801if(logfd <0)2802return0;2803 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2804git_committer_info(0), msg);2805if(result) {2806strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,2807strerror(errno));2808close(logfd);2809return-1;2810}2811if(close(logfd)) {2812strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,2813strerror(errno));2814return-1;2815}2816return0;2817}28182819static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2820const unsigned char*new_sha1,const char*msg,2821int flags,struct strbuf *err)2822{2823returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2824 err);2825}28262827intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2828const unsigned char*new_sha1,const char*msg,2829int flags,struct strbuf *err)2830{2831struct strbuf sb = STRBUF_INIT;2832int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2833 err);2834strbuf_release(&sb);2835return ret;2836}28372838/*2839 * Write sha1 into the open lockfile, then close the lockfile. On2840 * errors, rollback the lockfile, fill in *err and2841 * return -1.2842 */2843static intwrite_ref_to_lockfile(struct ref_lock *lock,2844const unsigned char*sha1,struct strbuf *err)2845{2846static char term ='\n';2847struct object *o;2848int fd;28492850 o =parse_object(sha1);2851if(!o) {2852strbuf_addf(err,2853"trying to write ref '%s' with nonexistent object%s",2854 lock->ref_name,sha1_to_hex(sha1));2855unlock_ref(lock);2856return-1;2857}2858if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2859strbuf_addf(err,2860"trying to write non-commit object%sto branch '%s'",2861sha1_to_hex(sha1), lock->ref_name);2862unlock_ref(lock);2863return-1;2864}2865 fd =get_lock_file_fd(lock->lk);2866if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2867write_in_full(fd, &term,1) !=1||2868close_ref(lock) <0) {2869strbuf_addf(err,2870"couldn't write '%s'",get_lock_file_path(lock->lk));2871unlock_ref(lock);2872return-1;2873}2874return0;2875}28762877/*2878 * Commit a change to a loose reference that has already been written2879 * to the loose reference lockfile. Also update the reflogs if2880 * necessary, using the specified lockmsg (which can be NULL).2881 */2882static intcommit_ref_update(struct ref_lock *lock,2883const unsigned char*sha1,const char*logmsg,2884struct strbuf *err)2885{2886clear_loose_ref_cache(&ref_cache);2887if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg,0, err)) {2888char*old_msg =strbuf_detach(err, NULL);2889strbuf_addf(err,"cannot update the ref '%s':%s",2890 lock->ref_name, old_msg);2891free(old_msg);2892unlock_ref(lock);2893return-1;2894}28952896if(strcmp(lock->ref_name,"HEAD") !=0) {2897/*2898 * Special hack: If a branch is updated directly and HEAD2899 * points to it (may happen on the remote side of a push2900 * for example) then logically the HEAD reflog should be2901 * updated too.2902 * A generic solution implies reverse symref information,2903 * but finding all symrefs pointing to the given branch2904 * would be rather costly for this rare event (the direct2905 * update of a branch) to be worth it. So let's cheat and2906 * check with HEAD only which should cover 99% of all usage2907 * scenarios (even 100% of the default ones).2908 */2909unsigned char head_sha1[20];2910int head_flag;2911const char*head_ref;29122913 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2914 head_sha1, &head_flag);2915if(head_ref && (head_flag & REF_ISSYMREF) &&2916!strcmp(head_ref, lock->ref_name)) {2917struct strbuf log_err = STRBUF_INIT;2918if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2919 logmsg,0, &log_err)) {2920error("%s", log_err.buf);2921strbuf_release(&log_err);2922}2923}2924}29252926if(commit_ref(lock)) {2927strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2928unlock_ref(lock);2929return-1;2930}29312932unlock_ref(lock);2933return0;2934}29352936static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2937{2938int ret = -1;2939#ifndef NO_SYMLINK_HEAD2940char*ref_path =get_locked_file_path(lock->lk);2941unlink(ref_path);2942 ret =symlink(target, ref_path);2943free(ref_path);29442945if(ret)2946fprintf(stderr,"no symlink - falling back to symbolic ref\n");2947#endif2948return ret;2949}29502951static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2952const char*target,const char*logmsg)2953{2954struct strbuf err = STRBUF_INIT;2955unsigned char new_sha1[20];2956if(logmsg && !read_ref(target, new_sha1) &&2957log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2958error("%s", err.buf);2959strbuf_release(&err);2960}2961}29622963static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2964const char*target,const char*logmsg)2965{2966if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2967update_symref_reflog(lock, refname, target, logmsg);2968return0;2969}29702971if(!fdopen_lock_file(lock->lk,"w"))2972returnerror("unable to fdopen%s:%s",2973 lock->lk->tempfile.filename.buf,strerror(errno));29742975update_symref_reflog(lock, refname, target, logmsg);29762977/* no error check; commit_ref will check ferror */2978fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2979if(commit_ref(lock) <0)2980returnerror("unable to write symref for%s:%s", refname,2981strerror(errno));2982return0;2983}29842985intcreate_symref(const char*refname,const char*target,const char*logmsg)2986{2987struct strbuf err = STRBUF_INIT;2988struct ref_lock *lock;2989int ret;29902991 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2992&err);2993if(!lock) {2994error("%s", err.buf);2995strbuf_release(&err);2996return-1;2997}29982999 ret =create_symref_locked(lock, refname, target, logmsg);3000unlock_ref(lock);3001return ret;3002}30033004intset_worktree_head_symref(const char*gitdir,const char*target)3005{3006static struct lock_file head_lock;3007struct ref_lock *lock;3008struct strbuf head_path = STRBUF_INIT;3009const char*head_rel;3010int ret;30113012strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));3013if(hold_lock_file_for_update(&head_lock, head_path.buf,3014 LOCK_NO_DEREF) <0) {3015struct strbuf err = STRBUF_INIT;3016unable_to_lock_message(head_path.buf, errno, &err);3017error("%s", err.buf);3018strbuf_release(&err);3019strbuf_release(&head_path);3020return-1;3021}30223023/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for3024 linked trees */3025 head_rel =remove_leading_path(head_path.buf,3026absolute_path(get_git_common_dir()));3027/* to make use of create_symref_locked(), initialize ref_lock */3028 lock =xcalloc(1,sizeof(struct ref_lock));3029 lock->lk = &head_lock;3030 lock->ref_name =xstrdup(head_rel);30313032 ret =create_symref_locked(lock, head_rel, target, NULL);30333034unlock_ref(lock);/* will free lock */3035strbuf_release(&head_path);3036return ret;3037}30383039intreflog_exists(const char*refname)3040{3041struct stat st;30423043return!lstat(git_path("logs/%s", refname), &st) &&3044S_ISREG(st.st_mode);3045}30463047intdelete_reflog(const char*refname)3048{3049returnremove_path(git_path("logs/%s", refname));3050}30513052static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3053{3054unsigned char osha1[20], nsha1[20];3055char*email_end, *message;3056unsigned long timestamp;3057int tz;30583059/* old SP new SP name <email> SP time TAB msg LF */3060if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3061get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3062get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3063!(email_end =strchr(sb->buf +82,'>')) ||3064 email_end[1] !=' '||3065!(timestamp =strtoul(email_end +2, &message,10)) ||3066!message || message[0] !=' '||3067(message[1] !='+'&& message[1] !='-') ||3068!isdigit(message[2]) || !isdigit(message[3]) ||3069!isdigit(message[4]) || !isdigit(message[5]))3070return0;/* corrupt? */3071 email_end[1] ='\0';3072 tz =strtol(message +1, NULL,10);3073if(message[6] !='\t')3074 message +=6;3075else3076 message +=7;3077returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3078}30793080static char*find_beginning_of_line(char*bob,char*scan)3081{3082while(bob < scan && *(--scan) !='\n')3083;/* keep scanning backwards */3084/*3085 * Return either beginning of the buffer, or LF at the end of3086 * the previous line.3087 */3088return scan;3089}30903091intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3092{3093struct strbuf sb = STRBUF_INIT;3094FILE*logfp;3095long pos;3096int ret =0, at_tail =1;30973098 logfp =fopen(git_path("logs/%s", refname),"r");3099if(!logfp)3100return-1;31013102/* Jump to the end */3103if(fseek(logfp,0, SEEK_END) <0)3104returnerror("cannot seek back reflog for%s:%s",3105 refname,strerror(errno));3106 pos =ftell(logfp);3107while(!ret &&0< pos) {3108int cnt;3109size_t nread;3110char buf[BUFSIZ];3111char*endp, *scanp;31123113/* Fill next block from the end */3114 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3115if(fseek(logfp, pos - cnt, SEEK_SET))3116returnerror("cannot seek back reflog for%s:%s",3117 refname,strerror(errno));3118 nread =fread(buf, cnt,1, logfp);3119if(nread !=1)3120returnerror("cannot read%dbytes from reflog for%s:%s",3121 cnt, refname,strerror(errno));3122 pos -= cnt;31233124 scanp = endp = buf + cnt;3125if(at_tail && scanp[-1] =='\n')3126/* Looking at the final LF at the end of the file */3127 scanp--;3128 at_tail =0;31293130while(buf < scanp) {3131/*3132 * terminating LF of the previous line, or the beginning3133 * of the buffer.3134 */3135char*bp;31363137 bp =find_beginning_of_line(buf, scanp);31383139if(*bp =='\n') {3140/*3141 * The newline is the end of the previous line,3142 * so we know we have complete line starting3143 * at (bp + 1). Prefix it onto any prior data3144 * we collected for the line and process it.3145 */3146strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3147 scanp = bp;3148 endp = bp +1;3149 ret =show_one_reflog_ent(&sb, fn, cb_data);3150strbuf_reset(&sb);3151if(ret)3152break;3153}else if(!pos) {3154/*3155 * We are at the start of the buffer, and the3156 * start of the file; there is no previous3157 * line, and we have everything for this one.3158 * Process it, and we can end the loop.3159 */3160strbuf_splice(&sb,0,0, buf, endp - buf);3161 ret =show_one_reflog_ent(&sb, fn, cb_data);3162strbuf_reset(&sb);3163break;3164}31653166if(bp == buf) {3167/*3168 * We are at the start of the buffer, and there3169 * is more file to read backwards. Which means3170 * we are in the middle of a line. Note that we3171 * may get here even if *bp was a newline; that3172 * just means we are at the exact end of the3173 * previous line, rather than some spot in the3174 * middle.3175 *3176 * Save away what we have to be combined with3177 * the data from the next read.3178 */3179strbuf_splice(&sb,0,0, buf, endp - buf);3180break;3181}3182}31833184}3185if(!ret && sb.len)3186die("BUG: reverse reflog parser had leftover data");31873188fclose(logfp);3189strbuf_release(&sb);3190return ret;3191}31923193intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3194{3195FILE*logfp;3196struct strbuf sb = STRBUF_INIT;3197int ret =0;31983199 logfp =fopen(git_path("logs/%s", refname),"r");3200if(!logfp)3201return-1;32023203while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3204 ret =show_one_reflog_ent(&sb, fn, cb_data);3205fclose(logfp);3206strbuf_release(&sb);3207return ret;3208}3209/*3210 * Call fn for each reflog in the namespace indicated by name. name3211 * must be empty or end with '/'. Name will be used as a scratch3212 * space, but its contents will be restored before return.3213 */3214static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3215{3216DIR*d =opendir(git_path("logs/%s", name->buf));3217int retval =0;3218struct dirent *de;3219int oldlen = name->len;32203221if(!d)3222return name->len ? errno :0;32233224while((de =readdir(d)) != NULL) {3225struct stat st;32263227if(de->d_name[0] =='.')3228continue;3229if(ends_with(de->d_name,".lock"))3230continue;3231strbuf_addstr(name, de->d_name);3232if(stat(git_path("logs/%s", name->buf), &st) <0) {3233;/* silently ignore */3234}else{3235if(S_ISDIR(st.st_mode)) {3236strbuf_addch(name,'/');3237 retval =do_for_each_reflog(name, fn, cb_data);3238}else{3239struct object_id oid;32403241if(read_ref_full(name->buf,0, oid.hash, NULL))3242 retval =error("bad ref for%s", name->buf);3243else3244 retval =fn(name->buf, &oid,0, cb_data);3245}3246if(retval)3247break;3248}3249strbuf_setlen(name, oldlen);3250}3251closedir(d);3252return retval;3253}32543255intfor_each_reflog(each_ref_fn fn,void*cb_data)3256{3257int retval;3258struct strbuf name;3259strbuf_init(&name, PATH_MAX);3260 retval =do_for_each_reflog(&name, fn, cb_data);3261strbuf_release(&name);3262return retval;3263}32643265static intref_update_reject_duplicates(struct string_list *refnames,3266struct strbuf *err)3267{3268int i, n = refnames->nr;32693270assert(err);32713272for(i =1; i < n; i++)3273if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3274strbuf_addf(err,3275"multiple updates for ref '%s' not allowed.",3276 refnames->items[i].string);3277return1;3278}3279return0;3280}32813282/*3283 * If update is a direct update of head_ref (the reference pointed to3284 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.3285 */3286static intsplit_head_update(struct ref_update *update,3287struct ref_transaction *transaction,3288const char*head_ref,3289struct string_list *affected_refnames,3290struct strbuf *err)3291{3292struct string_list_item *item;3293struct ref_update *new_update;32943295if((update->flags & REF_LOG_ONLY) ||3296(update->flags & REF_ISPRUNING) ||3297(update->flags & REF_UPDATE_VIA_HEAD))3298return0;32993300if(strcmp(update->refname, head_ref))3301return0;33023303/*3304 * First make sure that HEAD is not already in the3305 * transaction. This insertion is O(N) in the transaction3306 * size, but it happens at most once per transaction.3307 */3308 item =string_list_insert(affected_refnames,"HEAD");3309if(item->util) {3310/* An entry already existed */3311strbuf_addf(err,3312"multiple updates for 'HEAD' (including one "3313"via its referent '%s') are not allowed",3314 update->refname);3315return TRANSACTION_NAME_CONFLICT;3316}33173318 new_update =ref_transaction_add_update(3319 transaction,"HEAD",3320 update->flags | REF_LOG_ONLY | REF_NODEREF,3321 update->new_sha1, update->old_sha1,3322 update->msg);33233324 item->util = new_update;33253326return0;3327}33283329/*3330 * update is for a symref that points at referent and doesn't have3331 * REF_NODEREF set. Split it into two updates:3332 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set3333 * - A new, separate update for the referent reference3334 * Note that the new update will itself be subject to splitting when3335 * the iteration gets to it.3336 */3337static intsplit_symref_update(struct ref_update *update,3338const char*referent,3339struct ref_transaction *transaction,3340struct string_list *affected_refnames,3341struct strbuf *err)3342{3343struct string_list_item *item;3344struct ref_update *new_update;3345unsigned int new_flags;33463347/*3348 * First make sure that referent is not already in the3349 * transaction. This insertion is O(N) in the transaction3350 * size, but it happens at most once per symref in a3351 * transaction.3352 */3353 item =string_list_insert(affected_refnames, referent);3354if(item->util) {3355/* An entry already existed */3356strbuf_addf(err,3357"multiple updates for '%s' (including one "3358"via symref '%s') are not allowed",3359 referent, update->refname);3360return TRANSACTION_NAME_CONFLICT;3361}33623363 new_flags = update->flags;3364if(!strcmp(update->refname,"HEAD")) {3365/*3366 * Record that the new update came via HEAD, so that3367 * when we process it, split_head_update() doesn't try3368 * to add another reflog update for HEAD. Note that3369 * this bit will be propagated if the new_update3370 * itself needs to be split.3371 */3372 new_flags |= REF_UPDATE_VIA_HEAD;3373}33743375 new_update =ref_transaction_add_update(3376 transaction, referent, new_flags,3377 update->new_sha1, update->old_sha1,3378 update->msg);33793380 new_update->parent_update = update;33813382/*3383 * Change the symbolic ref update to log only. Also, it3384 * doesn't need to check its old SHA-1 value, as that will be3385 * done when new_update is processed.3386 */3387 update->flags |= REF_LOG_ONLY | REF_NODEREF;3388 update->flags &= ~REF_HAVE_OLD;33893390 item->util = new_update;33913392return0;3393}33943395/*3396 * Return the refname under which update was originally requested.3397 */3398static const char*original_update_refname(struct ref_update *update)3399{3400while(update->parent_update)3401 update = update->parent_update;34023403return update->refname;3404}34053406/*3407 * Prepare for carrying out update:3408 * - Lock the reference referred to by update.3409 * - Read the reference under lock.3410 * - Check that its old SHA-1 value (if specified) is correct, and in3411 * any case record it in update->lock->old_oid for later use when3412 * writing the reflog.3413 * - If it is a symref update without REF_NODEREF, split it up into a3414 * REF_LOG_ONLY update of the symref and add a separate update for3415 * the referent to transaction.3416 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY3417 * update of HEAD.3418 */3419static intlock_ref_for_update(struct ref_update *update,3420struct ref_transaction *transaction,3421const char*head_ref,3422struct string_list *affected_refnames,3423struct strbuf *err)3424{3425struct strbuf referent = STRBUF_INIT;3426int mustexist = (update->flags & REF_HAVE_OLD) &&3427!is_null_sha1(update->old_sha1);3428int ret;3429struct ref_lock *lock;34303431if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))3432 update->flags |= REF_DELETING;34333434if(head_ref) {3435 ret =split_head_update(update, transaction, head_ref,3436 affected_refnames, err);3437if(ret)3438return ret;3439}34403441 ret =lock_raw_ref(update->refname, mustexist,3442 affected_refnames, NULL,3443&update->lock, &referent,3444&update->type, err);34453446if(ret) {3447char*reason;34483449 reason =strbuf_detach(err, NULL);3450strbuf_addf(err,"cannot lock ref '%s':%s",3451 update->refname, reason);3452free(reason);3453return ret;3454}34553456 lock = update->lock;34573458if(update->type & REF_ISSYMREF) {3459if(update->flags & REF_NODEREF) {3460/*3461 * We won't be reading the referent as part of3462 * the transaction, so we have to read it here3463 * to record and possibly check old_sha1:3464 */3465if(read_ref_full(update->refname,3466 mustexist ? RESOLVE_REF_READING :0,3467 lock->old_oid.hash, NULL)) {3468if(update->flags & REF_HAVE_OLD) {3469strbuf_addf(err,"cannot lock ref '%s': "3470"can't resolve old value",3471 update->refname);3472return TRANSACTION_GENERIC_ERROR;3473}else{3474hashclr(lock->old_oid.hash);3475}3476}3477if((update->flags & REF_HAVE_OLD) &&3478hashcmp(lock->old_oid.hash, update->old_sha1)) {3479strbuf_addf(err,"cannot lock ref '%s': "3480"is at%sbut expected%s",3481 update->refname,3482sha1_to_hex(lock->old_oid.hash),3483sha1_to_hex(update->old_sha1));3484return TRANSACTION_GENERIC_ERROR;3485}34863487}else{3488/*3489 * Create a new update for the reference this3490 * symref is pointing at. Also, we will record3491 * and verify old_sha1 for this update as part3492 * of processing the split-off update, so we3493 * don't have to do it here.3494 */3495 ret =split_symref_update(update, referent.buf, transaction,3496 affected_refnames, err);3497if(ret)3498return ret;3499}3500}else{3501struct ref_update *parent_update;35023503/*3504 * If this update is happening indirectly because of a3505 * symref update, record the old SHA-1 in the parent3506 * update:3507 */3508for(parent_update = update->parent_update;3509 parent_update;3510 parent_update = parent_update->parent_update) {3511oidcpy(&parent_update->lock->old_oid, &lock->old_oid);3512}35133514if((update->flags & REF_HAVE_OLD) &&3515hashcmp(lock->old_oid.hash, update->old_sha1)) {3516if(is_null_sha1(update->old_sha1))3517strbuf_addf(err,"cannot lock ref '%s': reference already exists",3518original_update_refname(update));3519else3520strbuf_addf(err,"cannot lock ref '%s': is at%sbut expected%s",3521original_update_refname(update),3522sha1_to_hex(lock->old_oid.hash),3523sha1_to_hex(update->old_sha1));35243525return TRANSACTION_GENERIC_ERROR;3526}3527}35283529if((update->flags & REF_HAVE_NEW) &&3530!(update->flags & REF_DELETING) &&3531!(update->flags & REF_LOG_ONLY)) {3532if(!(update->type & REF_ISSYMREF) &&3533!hashcmp(lock->old_oid.hash, update->new_sha1)) {3534/*3535 * The reference already has the desired3536 * value, so we don't need to write it.3537 */3538}else if(write_ref_to_lockfile(lock, update->new_sha1,3539 err)) {3540char*write_err =strbuf_detach(err, NULL);35413542/*3543 * The lock was freed upon failure of3544 * write_ref_to_lockfile():3545 */3546 update->lock = NULL;3547strbuf_addf(err,3548"cannot update the ref '%s':%s",3549 update->refname, write_err);3550free(write_err);3551return TRANSACTION_GENERIC_ERROR;3552}else{3553 update->flags |= REF_NEEDS_COMMIT;3554}3555}3556if(!(update->flags & REF_NEEDS_COMMIT)) {3557/*3558 * We didn't call write_ref_to_lockfile(), so3559 * the lockfile is still open. Close it to3560 * free up the file descriptor:3561 */3562if(close_ref(lock)) {3563strbuf_addf(err,"couldn't close '%s.lock'",3564 update->refname);3565return TRANSACTION_GENERIC_ERROR;3566}3567}3568return0;3569}35703571intref_transaction_commit(struct ref_transaction *transaction,3572struct strbuf *err)3573{3574int ret =0, i;3575struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3576struct string_list_item *ref_to_delete;3577struct string_list affected_refnames = STRING_LIST_INIT_NODUP;3578char*head_ref = NULL;3579int head_type;3580struct object_id head_oid;35813582assert(err);35833584if(transaction->state != REF_TRANSACTION_OPEN)3585die("BUG: commit called for transaction that is not open");35863587if(!transaction->nr) {3588 transaction->state = REF_TRANSACTION_CLOSED;3589return0;3590}35913592/*3593 * Fail if a refname appears more than once in the3594 * transaction. (If we end up splitting up any updates using3595 * split_symref_update() or split_head_update(), those3596 * functions will check that the new updates don't have the3597 * same refname as any existing ones.)3598 */3599for(i =0; i < transaction->nr; i++) {3600struct ref_update *update = transaction->updates[i];3601struct string_list_item *item =3602string_list_append(&affected_refnames, update->refname);36033604/*3605 * We store a pointer to update in item->util, but at3606 * the moment we never use the value of this field3607 * except to check whether it is non-NULL.3608 */3609 item->util = update;3610}3611string_list_sort(&affected_refnames);3612if(ref_update_reject_duplicates(&affected_refnames, err)) {3613 ret = TRANSACTION_GENERIC_ERROR;3614goto cleanup;3615}36163617/*3618 * Special hack: If a branch is updated directly and HEAD3619 * points to it (may happen on the remote side of a push3620 * for example) then logically the HEAD reflog should be3621 * updated too.3622 *3623 * A generic solution would require reverse symref lookups,3624 * but finding all symrefs pointing to a given branch would be3625 * rather costly for this rare event (the direct update of a3626 * branch) to be worth it. So let's cheat and check with HEAD3627 * only, which should cover 99% of all usage scenarios (even3628 * 100% of the default ones).3629 *3630 * So if HEAD is a symbolic reference, then record the name of3631 * the reference that it points to. If we see an update of3632 * head_ref within the transaction, then split_head_update()3633 * arranges for the reflog of HEAD to be updated, too.3634 */3635 head_ref =resolve_refdup("HEAD", RESOLVE_REF_NO_RECURSE,3636 head_oid.hash, &head_type);36373638if(head_ref && !(head_type & REF_ISSYMREF)) {3639free(head_ref);3640 head_ref = NULL;3641}36423643/*3644 * Acquire all locks, verify old values if provided, check3645 * that new values are valid, and write new values to the3646 * lockfiles, ready to be activated. Only keep one lockfile3647 * open at a time to avoid running out of file descriptors.3648 */3649for(i =0; i < transaction->nr; i++) {3650struct ref_update *update = transaction->updates[i];36513652 ret =lock_ref_for_update(update, transaction, head_ref,3653&affected_refnames, err);3654if(ret)3655goto cleanup;3656}36573658/* Perform updates first so live commits remain referenced */3659for(i =0; i < transaction->nr; i++) {3660struct ref_update *update = transaction->updates[i];3661struct ref_lock *lock = update->lock;36623663if(update->flags & REF_NEEDS_COMMIT ||3664 update->flags & REF_LOG_ONLY) {3665if(log_ref_write(lock->ref_name, lock->old_oid.hash,3666 update->new_sha1,3667 update->msg, update->flags, err)) {3668char*old_msg =strbuf_detach(err, NULL);36693670strbuf_addf(err,"cannot update the ref '%s':%s",3671 lock->ref_name, old_msg);3672free(old_msg);3673unlock_ref(lock);3674 update->lock = NULL;3675 ret = TRANSACTION_GENERIC_ERROR;3676goto cleanup;3677}3678}3679if(update->flags & REF_NEEDS_COMMIT) {3680clear_loose_ref_cache(&ref_cache);3681if(commit_ref(lock)) {3682strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3683unlock_ref(lock);3684 update->lock = NULL;3685 ret = TRANSACTION_GENERIC_ERROR;3686goto cleanup;3687}3688}3689}3690/* Perform deletes now that updates are safely completed */3691for(i =0; i < transaction->nr; i++) {3692struct ref_update *update = transaction->updates[i];36933694if(update->flags & REF_DELETING &&3695!(update->flags & REF_LOG_ONLY)) {3696if(delete_ref_loose(update->lock, update->type, err)) {3697 ret = TRANSACTION_GENERIC_ERROR;3698goto cleanup;3699}37003701if(!(update->flags & REF_ISPRUNING))3702string_list_append(&refs_to_delete,3703 update->lock->ref_name);3704}3705}37063707if(repack_without_refs(&refs_to_delete, err)) {3708 ret = TRANSACTION_GENERIC_ERROR;3709goto cleanup;3710}3711for_each_string_list_item(ref_to_delete, &refs_to_delete)3712unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3713clear_loose_ref_cache(&ref_cache);37143715cleanup:3716 transaction->state = REF_TRANSACTION_CLOSED;37173718for(i =0; i < transaction->nr; i++)3719if(transaction->updates[i]->lock)3720unlock_ref(transaction->updates[i]->lock);3721string_list_clear(&refs_to_delete,0);3722free(head_ref);3723string_list_clear(&affected_refnames,0);37243725return ret;3726}37273728static intref_present(const char*refname,3729const struct object_id *oid,int flags,void*cb_data)3730{3731struct string_list *affected_refnames = cb_data;37323733returnstring_list_has_string(affected_refnames, refname);3734}37353736intinitial_ref_transaction_commit(struct ref_transaction *transaction,3737struct strbuf *err)3738{3739int ret =0, i;3740struct string_list affected_refnames = STRING_LIST_INIT_NODUP;37413742assert(err);37433744if(transaction->state != REF_TRANSACTION_OPEN)3745die("BUG: commit called for transaction that is not open");37463747/* Fail if a refname appears more than once in the transaction: */3748for(i =0; i < transaction->nr; i++)3749string_list_append(&affected_refnames,3750 transaction->updates[i]->refname);3751string_list_sort(&affected_refnames);3752if(ref_update_reject_duplicates(&affected_refnames, err)) {3753 ret = TRANSACTION_GENERIC_ERROR;3754goto cleanup;3755}37563757/*3758 * It's really undefined to call this function in an active3759 * repository or when there are existing references: we are3760 * only locking and changing packed-refs, so (1) any3761 * simultaneous processes might try to change a reference at3762 * the same time we do, and (2) any existing loose versions of3763 * the references that we are setting would have precedence3764 * over our values. But some remote helpers create the remote3765 * "HEAD" and "master" branches before calling this function,3766 * so here we really only check that none of the references3767 * that we are creating already exists.3768 */3769if(for_each_rawref(ref_present, &affected_refnames))3770die("BUG: initial ref transaction called with existing refs");37713772for(i =0; i < transaction->nr; i++) {3773struct ref_update *update = transaction->updates[i];37743775if((update->flags & REF_HAVE_OLD) &&3776!is_null_sha1(update->old_sha1))3777die("BUG: initial ref transaction with old_sha1 set");3778if(verify_refname_available(update->refname,3779&affected_refnames, NULL,3780 err)) {3781 ret = TRANSACTION_NAME_CONFLICT;3782goto cleanup;3783}3784}37853786if(lock_packed_refs(0)) {3787strbuf_addf(err,"unable to lock packed-refs file:%s",3788strerror(errno));3789 ret = TRANSACTION_GENERIC_ERROR;3790goto cleanup;3791}37923793for(i =0; i < transaction->nr; i++) {3794struct ref_update *update = transaction->updates[i];37953796if((update->flags & REF_HAVE_NEW) &&3797!is_null_sha1(update->new_sha1))3798add_packed_ref(update->refname, update->new_sha1);3799}38003801if(commit_packed_refs()) {3802strbuf_addf(err,"unable to commit packed-refs file:%s",3803strerror(errno));3804 ret = TRANSACTION_GENERIC_ERROR;3805goto cleanup;3806}38073808cleanup:3809 transaction->state = REF_TRANSACTION_CLOSED;3810string_list_clear(&affected_refnames,0);3811return ret;3812}38133814struct expire_reflog_cb {3815unsigned int flags;3816 reflog_expiry_should_prune_fn *should_prune_fn;3817void*policy_cb;3818FILE*newlog;3819unsigned char last_kept_sha1[20];3820};38213822static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3823const char*email,unsigned long timestamp,int tz,3824const char*message,void*cb_data)3825{3826struct expire_reflog_cb *cb = cb_data;3827struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;38283829if(cb->flags & EXPIRE_REFLOGS_REWRITE)3830 osha1 = cb->last_kept_sha1;38313832if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3833 message, policy_cb)) {3834if(!cb->newlog)3835printf("would prune%s", message);3836else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3837printf("prune%s", message);3838}else{3839if(cb->newlog) {3840fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3841sha1_to_hex(osha1),sha1_to_hex(nsha1),3842 email, timestamp, tz, message);3843hashcpy(cb->last_kept_sha1, nsha1);3844}3845if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3846printf("keep%s", message);3847}3848return0;3849}38503851intreflog_expire(const char*refname,const unsigned char*sha1,3852unsigned int flags,3853 reflog_expiry_prepare_fn prepare_fn,3854 reflog_expiry_should_prune_fn should_prune_fn,3855 reflog_expiry_cleanup_fn cleanup_fn,3856void*policy_cb_data)3857{3858static struct lock_file reflog_lock;3859struct expire_reflog_cb cb;3860struct ref_lock *lock;3861char*log_file;3862int status =0;3863int type;3864struct strbuf err = STRBUF_INIT;38653866memset(&cb,0,sizeof(cb));3867 cb.flags = flags;3868 cb.policy_cb = policy_cb_data;3869 cb.should_prune_fn = should_prune_fn;38703871/*3872 * The reflog file is locked by holding the lock on the3873 * reference itself, plus we might need to update the3874 * reference if --updateref was specified:3875 */3876 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL, REF_NODEREF,3877&type, &err);3878if(!lock) {3879error("cannot lock ref '%s':%s", refname, err.buf);3880strbuf_release(&err);3881return-1;3882}3883if(!reflog_exists(refname)) {3884unlock_ref(lock);3885return0;3886}38873888 log_file =git_pathdup("logs/%s", refname);3889if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3890/*3891 * Even though holding $GIT_DIR/logs/$reflog.lock has3892 * no locking implications, we use the lock_file3893 * machinery here anyway because it does a lot of the3894 * work we need, including cleaning up if the program3895 * exits unexpectedly.3896 */3897if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3898struct strbuf err = STRBUF_INIT;3899unable_to_lock_message(log_file, errno, &err);3900error("%s", err.buf);3901strbuf_release(&err);3902goto failure;3903}3904 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3905if(!cb.newlog) {3906error("cannot fdopen%s(%s)",3907get_lock_file_path(&reflog_lock),strerror(errno));3908goto failure;3909}3910}39113912(*prepare_fn)(refname, sha1, cb.policy_cb);3913for_each_reflog_ent(refname, expire_reflog_ent, &cb);3914(*cleanup_fn)(cb.policy_cb);39153916if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3917/*3918 * It doesn't make sense to adjust a reference pointed3919 * to by a symbolic ref based on expiring entries in3920 * the symbolic reference's reflog. Nor can we update3921 * a reference if there are no remaining reflog3922 * entries.3923 */3924int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3925!(type & REF_ISSYMREF) &&3926!is_null_sha1(cb.last_kept_sha1);39273928if(close_lock_file(&reflog_lock)) {3929 status |=error("couldn't write%s:%s", log_file,3930strerror(errno));3931}else if(update &&3932(write_in_full(get_lock_file_fd(lock->lk),3933sha1_to_hex(cb.last_kept_sha1),40) !=40||3934write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3935close_ref(lock) <0)) {3936 status |=error("couldn't write%s",3937get_lock_file_path(lock->lk));3938rollback_lock_file(&reflog_lock);3939}else if(commit_lock_file(&reflog_lock)) {3940 status |=error("unable to write reflog '%s' (%s)",3941 log_file,strerror(errno));3942}else if(update &&commit_ref(lock)) {3943 status |=error("couldn't set%s", lock->ref_name);3944}3945}3946free(log_file);3947unlock_ref(lock);3948return status;39493950 failure:3951rollback_lock_file(&reflog_lock);3952free(log_file);3953unlock_ref(lock);3954return-1;3955}