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; 10char*orig_ref_name; 11struct lock_file *lk; 12struct object_id old_oid; 13}; 14 15struct ref_entry; 16 17/* 18 * Information used (along with the information in ref_entry) to 19 * describe a single cached reference. This data structure only 20 * occurs embedded in a union in struct ref_entry, and only when 21 * (ref_entry->flag & REF_DIR) is zero. 22 */ 23struct ref_value { 24/* 25 * The name of the object to which this reference resolves 26 * (which may be a tag object). If REF_ISBROKEN, this is 27 * null. If REF_ISSYMREF, then this is the name of the object 28 * referred to by the last reference in the symlink chain. 29 */ 30struct object_id oid; 31 32/* 33 * If REF_KNOWS_PEELED, then this field holds the peeled value 34 * of this reference, or null if the reference is known not to 35 * be peelable. See the documentation for peel_ref() for an 36 * exact definition of "peelable". 37 */ 38struct object_id peeled; 39}; 40 41struct ref_cache; 42 43/* 44 * Information used (along with the information in ref_entry) to 45 * describe a level in the hierarchy of references. This data 46 * structure only occurs embedded in a union in struct ref_entry, and 47 * only when (ref_entry.flag & REF_DIR) is set. In that case, 48 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 49 * in the directory have already been read: 50 * 51 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 52 * or packed references, already read. 53 * 54 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 55 * references that hasn't been read yet (nor has any of its 56 * subdirectories). 57 * 58 * Entries within a directory are stored within a growable array of 59 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 60 * sorted are sorted by their component name in strcmp() order and the 61 * remaining entries are unsorted. 62 * 63 * Loose references are read lazily, one directory at a time. When a 64 * directory of loose references is read, then all of the references 65 * in that directory are stored, and REF_INCOMPLETE stubs are created 66 * for any subdirectories, but the subdirectories themselves are not 67 * read. The reading is triggered by get_ref_dir(). 68 */ 69struct ref_dir { 70int nr, alloc; 71 72/* 73 * Entries with index 0 <= i < sorted are sorted by name. New 74 * entries are appended to the list unsorted, and are sorted 75 * only when required; thus we avoid the need to sort the list 76 * after the addition of every reference. 77 */ 78int sorted; 79 80/* A pointer to the ref_cache that contains this ref_dir. */ 81struct ref_cache *ref_cache; 82 83struct ref_entry **entries; 84}; 85 86/* 87 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 88 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 89 * public values; see refs.h. 90 */ 91 92/* 93 * The field ref_entry->u.value.peeled of this value entry contains 94 * the correct peeled value for the reference, which might be 95 * null_sha1 if the reference is not a tag or if it is broken. 96 */ 97#define REF_KNOWS_PEELED 0x10 98 99/* ref_entry represents a directory of references */ 100#define REF_DIR 0x20 101 102/* 103 * Entry has not yet been read from disk (used only for REF_DIR 104 * entries representing loose references) 105 */ 106#define REF_INCOMPLETE 0x40 107 108/* 109 * A ref_entry represents either a reference or a "subdirectory" of 110 * references. 111 * 112 * Each directory in the reference namespace is represented by a 113 * ref_entry with (flags & REF_DIR) set and containing a subdir member 114 * that holds the entries in that directory that have been read so 115 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 116 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 117 * used for loose reference directories. 118 * 119 * References are represented by a ref_entry with (flags & REF_DIR) 120 * unset and a value member that describes the reference's value. The 121 * flag member is at the ref_entry level, but it is also needed to 122 * interpret the contents of the value field (in other words, a 123 * ref_value object is not very much use without the enclosing 124 * ref_entry). 125 * 126 * Reference names cannot end with slash and directories' names are 127 * always stored with a trailing slash (except for the top-level 128 * directory, which is always denoted by ""). This has two nice 129 * consequences: (1) when the entries in each subdir are sorted 130 * lexicographically by name (as they usually are), the references in 131 * a whole tree can be generated in lexicographic order by traversing 132 * the tree in left-to-right, depth-first order; (2) the names of 133 * references and subdirectories cannot conflict, and therefore the 134 * presence of an empty subdirectory does not block the creation of a 135 * similarly-named reference. (The fact that reference names with the 136 * same leading components can conflict *with each other* is a 137 * separate issue that is regulated by verify_refname_available().) 138 * 139 * Please note that the name field contains the fully-qualified 140 * reference (or subdirectory) name. Space could be saved by only 141 * storing the relative names. But that would require the full names 142 * to be generated on the fly when iterating in do_for_each_ref(), and 143 * would break callback functions, who have always been able to assume 144 * that the name strings that they are passed will not be freed during 145 * the iteration. 146 */ 147struct ref_entry { 148unsigned char flag;/* ISSYMREF? ISPACKED? */ 149union{ 150struct ref_value value;/* if not (flags&REF_DIR) */ 151struct ref_dir subdir;/* if (flags&REF_DIR) */ 152} u; 153/* 154 * The full name of the reference (e.g., "refs/heads/master") 155 * or the full name of the directory with a trailing slash 156 * (e.g., "refs/heads/"): 157 */ 158char name[FLEX_ARRAY]; 159}; 160 161static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 162static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len); 163static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 164const char*dirname,size_t len, 165int incomplete); 166static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry); 167 168static struct ref_dir *get_ref_dir(struct ref_entry *entry) 169{ 170struct ref_dir *dir; 171assert(entry->flag & REF_DIR); 172 dir = &entry->u.subdir; 173if(entry->flag & REF_INCOMPLETE) { 174read_loose_refs(entry->name, dir); 175 176/* 177 * Manually add refs/bisect, which, being 178 * per-worktree, might not appear in the directory 179 * listing for refs/ in the main repo. 180 */ 181if(!strcmp(entry->name,"refs/")) { 182int pos =search_ref_dir(dir,"refs/bisect/",12); 183if(pos <0) { 184struct ref_entry *child_entry; 185 child_entry =create_dir_entry(dir->ref_cache, 186"refs/bisect/", 18712,1); 188add_entry_to_dir(dir, child_entry); 189read_loose_refs("refs/bisect", 190&child_entry->u.subdir); 191} 192} 193 entry->flag &= ~REF_INCOMPLETE; 194} 195return dir; 196} 197 198static struct ref_entry *create_ref_entry(const char*refname, 199const unsigned char*sha1,int flag, 200int check_name) 201{ 202struct ref_entry *ref; 203 204if(check_name && 205check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 206die("Reference has invalid format: '%s'", refname); 207FLEX_ALLOC_STR(ref, name, refname); 208hashcpy(ref->u.value.oid.hash, sha1); 209oidclr(&ref->u.value.peeled); 210 ref->flag = flag; 211return ref; 212} 213 214static voidclear_ref_dir(struct ref_dir *dir); 215 216static voidfree_ref_entry(struct ref_entry *entry) 217{ 218if(entry->flag & REF_DIR) { 219/* 220 * Do not use get_ref_dir() here, as that might 221 * trigger the reading of loose refs. 222 */ 223clear_ref_dir(&entry->u.subdir); 224} 225free(entry); 226} 227 228/* 229 * Add a ref_entry to the end of dir (unsorted). Entry is always 230 * stored directly in dir; no recursion into subdirectories is 231 * done. 232 */ 233static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 234{ 235ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 236 dir->entries[dir->nr++] = entry; 237/* optimize for the case that entries are added in order */ 238if(dir->nr ==1|| 239(dir->nr == dir->sorted +1&& 240strcmp(dir->entries[dir->nr -2]->name, 241 dir->entries[dir->nr -1]->name) <0)) 242 dir->sorted = dir->nr; 243} 244 245/* 246 * Clear and free all entries in dir, recursively. 247 */ 248static voidclear_ref_dir(struct ref_dir *dir) 249{ 250int i; 251for(i =0; i < dir->nr; i++) 252free_ref_entry(dir->entries[i]); 253free(dir->entries); 254 dir->sorted = dir->nr = dir->alloc =0; 255 dir->entries = NULL; 256} 257 258/* 259 * Create a struct ref_entry object for the specified dirname. 260 * dirname is the name of the directory with a trailing slash (e.g., 261 * "refs/heads/") or "" for the top-level directory. 262 */ 263static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 264const char*dirname,size_t len, 265int incomplete) 266{ 267struct ref_entry *direntry; 268FLEX_ALLOC_MEM(direntry, name, dirname, len); 269 direntry->u.subdir.ref_cache = ref_cache; 270 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 271return direntry; 272} 273 274static intref_entry_cmp(const void*a,const void*b) 275{ 276struct ref_entry *one = *(struct ref_entry **)a; 277struct ref_entry *two = *(struct ref_entry **)b; 278returnstrcmp(one->name, two->name); 279} 280 281static voidsort_ref_dir(struct ref_dir *dir); 282 283struct string_slice { 284size_t len; 285const char*str; 286}; 287 288static intref_entry_cmp_sslice(const void*key_,const void*ent_) 289{ 290const struct string_slice *key = key_; 291const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 292int cmp =strncmp(key->str, ent->name, key->len); 293if(cmp) 294return cmp; 295return'\0'- (unsigned char)ent->name[key->len]; 296} 297 298/* 299 * Return the index of the entry with the given refname from the 300 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 301 * no such entry is found. dir must already be complete. 302 */ 303static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 304{ 305struct ref_entry **r; 306struct string_slice key; 307 308if(refname == NULL || !dir->nr) 309return-1; 310 311sort_ref_dir(dir); 312 key.len = len; 313 key.str = refname; 314 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 315 ref_entry_cmp_sslice); 316 317if(r == NULL) 318return-1; 319 320return r - dir->entries; 321} 322 323/* 324 * Search for a directory entry directly within dir (without 325 * recursing). Sort dir if necessary. subdirname must be a directory 326 * name (i.e., end in '/'). If mkdir is set, then create the 327 * directory if it is missing; otherwise, return NULL if the desired 328 * directory cannot be found. dir must already be complete. 329 */ 330static struct ref_dir *search_for_subdir(struct ref_dir *dir, 331const char*subdirname,size_t len, 332int mkdir) 333{ 334int entry_index =search_ref_dir(dir, subdirname, len); 335struct ref_entry *entry; 336if(entry_index == -1) { 337if(!mkdir) 338return NULL; 339/* 340 * Since dir is complete, the absence of a subdir 341 * means that the subdir really doesn't exist; 342 * therefore, create an empty record for it but mark 343 * the record complete. 344 */ 345 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 346add_entry_to_dir(dir, entry); 347}else{ 348 entry = dir->entries[entry_index]; 349} 350returnget_ref_dir(entry); 351} 352 353/* 354 * If refname is a reference name, find the ref_dir within the dir 355 * tree that should hold refname. If refname is a directory name 356 * (i.e., ends in '/'), then return that ref_dir itself. dir must 357 * represent the top-level directory and must already be complete. 358 * Sort ref_dirs and recurse into subdirectories as necessary. If 359 * mkdir is set, then create any missing directories; otherwise, 360 * return NULL if the desired directory cannot be found. 361 */ 362static struct ref_dir *find_containing_dir(struct ref_dir *dir, 363const char*refname,int mkdir) 364{ 365const char*slash; 366for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 367size_t dirnamelen = slash - refname +1; 368struct ref_dir *subdir; 369 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 370if(!subdir) { 371 dir = NULL; 372break; 373} 374 dir = subdir; 375} 376 377return dir; 378} 379 380/* 381 * Find the value entry with the given name in dir, sorting ref_dirs 382 * and recursing into subdirectories as necessary. If the name is not 383 * found or it corresponds to a directory entry, return NULL. 384 */ 385static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 386{ 387int entry_index; 388struct ref_entry *entry; 389 dir =find_containing_dir(dir, refname,0); 390if(!dir) 391return NULL; 392 entry_index =search_ref_dir(dir, refname,strlen(refname)); 393if(entry_index == -1) 394return NULL; 395 entry = dir->entries[entry_index]; 396return(entry->flag & REF_DIR) ? NULL : entry; 397} 398 399/* 400 * Remove the entry with the given name from dir, recursing into 401 * subdirectories as necessary. If refname is the name of a directory 402 * (i.e., ends with '/'), then remove the directory and its contents. 403 * If the removal was successful, return the number of entries 404 * remaining in the directory entry that contained the deleted entry. 405 * If the name was not found, return -1. Please note that this 406 * function only deletes the entry from the cache; it does not delete 407 * it from the filesystem or ensure that other cache entries (which 408 * might be symbolic references to the removed entry) are updated. 409 * Nor does it remove any containing dir entries that might be made 410 * empty by the removal. dir must represent the top-level directory 411 * and must already be complete. 412 */ 413static intremove_entry(struct ref_dir *dir,const char*refname) 414{ 415int refname_len =strlen(refname); 416int entry_index; 417struct ref_entry *entry; 418int is_dir = refname[refname_len -1] =='/'; 419if(is_dir) { 420/* 421 * refname represents a reference directory. Remove 422 * the trailing slash; otherwise we will get the 423 * directory *representing* refname rather than the 424 * one *containing* it. 425 */ 426char*dirname =xmemdupz(refname, refname_len -1); 427 dir =find_containing_dir(dir, dirname,0); 428free(dirname); 429}else{ 430 dir =find_containing_dir(dir, refname,0); 431} 432if(!dir) 433return-1; 434 entry_index =search_ref_dir(dir, refname, refname_len); 435if(entry_index == -1) 436return-1; 437 entry = dir->entries[entry_index]; 438 439memmove(&dir->entries[entry_index], 440&dir->entries[entry_index +1], 441(dir->nr - entry_index -1) *sizeof(*dir->entries) 442); 443 dir->nr--; 444if(dir->sorted > entry_index) 445 dir->sorted--; 446free_ref_entry(entry); 447return dir->nr; 448} 449 450/* 451 * Add a ref_entry to the ref_dir (unsorted), recursing into 452 * subdirectories as necessary. dir must represent the top-level 453 * directory. Return 0 on success. 454 */ 455static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 456{ 457 dir =find_containing_dir(dir, ref->name,1); 458if(!dir) 459return-1; 460add_entry_to_dir(dir, ref); 461return0; 462} 463 464/* 465 * Emit a warning and return true iff ref1 and ref2 have the same name 466 * and the same sha1. Die if they have the same name but different 467 * sha1s. 468 */ 469static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 470{ 471if(strcmp(ref1->name, ref2->name)) 472return0; 473 474/* Duplicate name; make sure that they don't conflict: */ 475 476if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 477/* This is impossible by construction */ 478die("Reference directory conflict:%s", ref1->name); 479 480if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 481die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 482 483warning("Duplicated ref:%s", ref1->name); 484return1; 485} 486 487/* 488 * Sort the entries in dir non-recursively (if they are not already 489 * sorted) and remove any duplicate entries. 490 */ 491static voidsort_ref_dir(struct ref_dir *dir) 492{ 493int i, j; 494struct ref_entry *last = NULL; 495 496/* 497 * This check also prevents passing a zero-length array to qsort(), 498 * which is a problem on some platforms. 499 */ 500if(dir->sorted == dir->nr) 501return; 502 503qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 504 505/* Remove any duplicates: */ 506for(i =0, j =0; j < dir->nr; j++) { 507struct ref_entry *entry = dir->entries[j]; 508if(last &&is_dup_ref(last, entry)) 509free_ref_entry(entry); 510else 511 last = dir->entries[i++] = entry; 512} 513 dir->sorted = dir->nr = i; 514} 515 516/* 517 * Return true iff the reference described by entry can be resolved to 518 * an object in the database. Emit a warning if the referred-to 519 * object does not exist. 520 */ 521static intref_resolves_to_object(struct ref_entry *entry) 522{ 523if(entry->flag & REF_ISBROKEN) 524return0; 525if(!has_sha1_file(entry->u.value.oid.hash)) { 526error("%sdoes not point to a valid object!", entry->name); 527return0; 528} 529return1; 530} 531 532/* 533 * current_ref is a performance hack: when iterating over references 534 * using the for_each_ref*() functions, current_ref is set to the 535 * current reference's entry before calling the callback function. If 536 * the callback function calls peel_ref(), then peel_ref() first 537 * checks whether the reference to be peeled is the current reference 538 * (it usually is) and if so, returns that reference's peeled version 539 * if it is available. This avoids a refname lookup in a common case. 540 */ 541static struct ref_entry *current_ref; 542 543typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 544 545struct ref_entry_cb { 546const char*base; 547int trim; 548int flags; 549 each_ref_fn *fn; 550void*cb_data; 551}; 552 553/* 554 * Handle one reference in a do_for_each_ref*()-style iteration, 555 * calling an each_ref_fn for each entry. 556 */ 557static intdo_one_ref(struct ref_entry *entry,void*cb_data) 558{ 559struct ref_entry_cb *data = cb_data; 560struct ref_entry *old_current_ref; 561int retval; 562 563if(!starts_with(entry->name, data->base)) 564return0; 565 566if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 567!ref_resolves_to_object(entry)) 568return0; 569 570/* Store the old value, in case this is a recursive call: */ 571 old_current_ref = current_ref; 572 current_ref = entry; 573 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 574 entry->flag, data->cb_data); 575 current_ref = old_current_ref; 576return retval; 577} 578 579/* 580 * Call fn for each reference in dir that has index in the range 581 * offset <= index < dir->nr. Recurse into subdirectories that are in 582 * that index range, sorting them before iterating. This function 583 * does not sort dir itself; it should be sorted beforehand. fn is 584 * called for all references, including broken ones. 585 */ 586static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 587 each_ref_entry_fn fn,void*cb_data) 588{ 589int i; 590assert(dir->sorted == dir->nr); 591for(i = offset; i < dir->nr; i++) { 592struct ref_entry *entry = dir->entries[i]; 593int retval; 594if(entry->flag & REF_DIR) { 595struct ref_dir *subdir =get_ref_dir(entry); 596sort_ref_dir(subdir); 597 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 598}else{ 599 retval =fn(entry, cb_data); 600} 601if(retval) 602return retval; 603} 604return0; 605} 606 607/* 608 * Call fn for each reference in the union of dir1 and dir2, in order 609 * by refname. Recurse into subdirectories. If a value entry appears 610 * in both dir1 and dir2, then only process the version that is in 611 * dir2. The input dirs must already be sorted, but subdirs will be 612 * sorted as needed. fn is called for all references, including 613 * broken ones. 614 */ 615static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 616struct ref_dir *dir2, 617 each_ref_entry_fn fn,void*cb_data) 618{ 619int retval; 620int i1 =0, i2 =0; 621 622assert(dir1->sorted == dir1->nr); 623assert(dir2->sorted == dir2->nr); 624while(1) { 625struct ref_entry *e1, *e2; 626int cmp; 627if(i1 == dir1->nr) { 628returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 629} 630if(i2 == dir2->nr) { 631returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 632} 633 e1 = dir1->entries[i1]; 634 e2 = dir2->entries[i2]; 635 cmp =strcmp(e1->name, e2->name); 636if(cmp ==0) { 637if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 638/* Both are directories; descend them in parallel. */ 639struct ref_dir *subdir1 =get_ref_dir(e1); 640struct ref_dir *subdir2 =get_ref_dir(e2); 641sort_ref_dir(subdir1); 642sort_ref_dir(subdir2); 643 retval =do_for_each_entry_in_dirs( 644 subdir1, subdir2, fn, cb_data); 645 i1++; 646 i2++; 647}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 648/* Both are references; ignore the one from dir1. */ 649 retval =fn(e2, cb_data); 650 i1++; 651 i2++; 652}else{ 653die("conflict between reference and directory:%s", 654 e1->name); 655} 656}else{ 657struct ref_entry *e; 658if(cmp <0) { 659 e = e1; 660 i1++; 661}else{ 662 e = e2; 663 i2++; 664} 665if(e->flag & REF_DIR) { 666struct ref_dir *subdir =get_ref_dir(e); 667sort_ref_dir(subdir); 668 retval =do_for_each_entry_in_dir( 669 subdir,0, fn, cb_data); 670}else{ 671 retval =fn(e, cb_data); 672} 673} 674if(retval) 675return retval; 676} 677} 678 679/* 680 * Load all of the refs from the dir into our in-memory cache. The hard work 681 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 682 * through all of the sub-directories. We do not even need to care about 683 * sorting, as traversal order does not matter to us. 684 */ 685static voidprime_ref_dir(struct ref_dir *dir) 686{ 687int i; 688for(i =0; i < dir->nr; i++) { 689struct ref_entry *entry = dir->entries[i]; 690if(entry->flag & REF_DIR) 691prime_ref_dir(get_ref_dir(entry)); 692} 693} 694 695struct nonmatching_ref_data { 696const struct string_list *skip; 697const char*conflicting_refname; 698}; 699 700static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 701{ 702struct nonmatching_ref_data *data = vdata; 703 704if(data->skip &&string_list_has_string(data->skip, entry->name)) 705return0; 706 707 data->conflicting_refname = entry->name; 708return1; 709} 710 711/* 712 * Return 0 if a reference named refname could be created without 713 * conflicting with the name of an existing reference in dir. 714 * See verify_refname_available for more information. 715 */ 716static intverify_refname_available_dir(const char*refname, 717const struct string_list *extras, 718const struct string_list *skip, 719struct ref_dir *dir, 720struct strbuf *err) 721{ 722const char*slash; 723const char*extra_refname; 724int pos; 725struct strbuf dirname = STRBUF_INIT; 726int ret = -1; 727 728/* 729 * For the sake of comments in this function, suppose that 730 * refname is "refs/foo/bar". 731 */ 732 733assert(err); 734 735strbuf_grow(&dirname,strlen(refname) +1); 736for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 737/* Expand dirname to the new prefix, not including the trailing slash: */ 738strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 739 740/* 741 * We are still at a leading dir of the refname (e.g., 742 * "refs/foo"; if there is a reference with that name, 743 * it is a conflict, *unless* it is in skip. 744 */ 745if(dir) { 746 pos =search_ref_dir(dir, dirname.buf, dirname.len); 747if(pos >=0&& 748(!skip || !string_list_has_string(skip, dirname.buf))) { 749/* 750 * We found a reference whose name is 751 * a proper prefix of refname; e.g., 752 * "refs/foo", and is not in skip. 753 */ 754strbuf_addf(err,"'%s' exists; cannot create '%s'", 755 dirname.buf, refname); 756goto cleanup; 757} 758} 759 760if(extras &&string_list_has_string(extras, dirname.buf) && 761(!skip || !string_list_has_string(skip, dirname.buf))) { 762strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 763 refname, dirname.buf); 764goto cleanup; 765} 766 767/* 768 * Otherwise, we can try to continue our search with 769 * the next component. So try to look up the 770 * directory, e.g., "refs/foo/". If we come up empty, 771 * we know there is nothing under this whole prefix, 772 * but even in that case we still have to continue the 773 * search for conflicts with extras. 774 */ 775strbuf_addch(&dirname,'/'); 776if(dir) { 777 pos =search_ref_dir(dir, dirname.buf, dirname.len); 778if(pos <0) { 779/* 780 * There was no directory "refs/foo/", 781 * so there is nothing under this 782 * whole prefix. So there is no need 783 * to continue looking for conflicting 784 * references. But we need to continue 785 * looking for conflicting extras. 786 */ 787 dir = NULL; 788}else{ 789 dir =get_ref_dir(dir->entries[pos]); 790} 791} 792} 793 794/* 795 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 796 * There is no point in searching for a reference with that 797 * name, because a refname isn't considered to conflict with 798 * itself. But we still need to check for references whose 799 * names are in the "refs/foo/bar/" namespace, because they 800 * *do* conflict. 801 */ 802strbuf_addstr(&dirname, refname + dirname.len); 803strbuf_addch(&dirname,'/'); 804 805if(dir) { 806 pos =search_ref_dir(dir, dirname.buf, dirname.len); 807 808if(pos >=0) { 809/* 810 * We found a directory named "$refname/" 811 * (e.g., "refs/foo/bar/"). It is a problem 812 * iff it contains any ref that is not in 813 * "skip". 814 */ 815struct nonmatching_ref_data data; 816 817 data.skip = skip; 818 data.conflicting_refname = NULL; 819 dir =get_ref_dir(dir->entries[pos]); 820sort_ref_dir(dir); 821if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 822strbuf_addf(err,"'%s' exists; cannot create '%s'", 823 data.conflicting_refname, refname); 824goto cleanup; 825} 826} 827} 828 829 extra_refname =find_descendant_ref(dirname.buf, extras, skip); 830if(extra_refname) 831strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 832 refname, extra_refname); 833else 834 ret =0; 835 836cleanup: 837strbuf_release(&dirname); 838return ret; 839} 840 841struct packed_ref_cache { 842struct ref_entry *root; 843 844/* 845 * Count of references to the data structure in this instance, 846 * including the pointer from ref_cache::packed if any. The 847 * data will not be freed as long as the reference count is 848 * nonzero. 849 */ 850unsigned int referrers; 851 852/* 853 * Iff the packed-refs file associated with this instance is 854 * currently locked for writing, this points at the associated 855 * lock (which is owned by somebody else). The referrer count 856 * is also incremented when the file is locked and decremented 857 * when it is unlocked. 858 */ 859struct lock_file *lock; 860 861/* The metadata from when this packed-refs cache was read */ 862struct stat_validity validity; 863}; 864 865/* 866 * Future: need to be in "struct repository" 867 * when doing a full libification. 868 */ 869static struct ref_cache { 870struct ref_cache *next; 871struct ref_entry *loose; 872struct packed_ref_cache *packed; 873/* 874 * The submodule name, or "" for the main repo. We allocate 875 * length 1 rather than FLEX_ARRAY so that the main ref_cache 876 * is initialized correctly. 877 */ 878char name[1]; 879} ref_cache, *submodule_ref_caches; 880 881/* Lock used for the main packed-refs file: */ 882static struct lock_file packlock; 883 884/* 885 * Increment the reference count of *packed_refs. 886 */ 887static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 888{ 889 packed_refs->referrers++; 890} 891 892/* 893 * Decrease the reference count of *packed_refs. If it goes to zero, 894 * free *packed_refs and return true; otherwise return false. 895 */ 896static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 897{ 898if(!--packed_refs->referrers) { 899free_ref_entry(packed_refs->root); 900stat_validity_clear(&packed_refs->validity); 901free(packed_refs); 902return1; 903}else{ 904return0; 905} 906} 907 908static voidclear_packed_ref_cache(struct ref_cache *refs) 909{ 910if(refs->packed) { 911struct packed_ref_cache *packed_refs = refs->packed; 912 913if(packed_refs->lock) 914die("internal error: packed-ref cache cleared while locked"); 915 refs->packed = NULL; 916release_packed_ref_cache(packed_refs); 917} 918} 919 920static voidclear_loose_ref_cache(struct ref_cache *refs) 921{ 922if(refs->loose) { 923free_ref_entry(refs->loose); 924 refs->loose = NULL; 925} 926} 927 928/* 929 * Create a new submodule ref cache and add it to the internal 930 * set of caches. 931 */ 932static struct ref_cache *create_ref_cache(const char*submodule) 933{ 934struct ref_cache *refs; 935if(!submodule) 936 submodule =""; 937FLEX_ALLOC_STR(refs, name, submodule); 938 refs->next = submodule_ref_caches; 939 submodule_ref_caches = refs; 940return refs; 941} 942 943static struct ref_cache *lookup_ref_cache(const char*submodule) 944{ 945struct ref_cache *refs; 946 947if(!submodule || !*submodule) 948return&ref_cache; 949 950for(refs = submodule_ref_caches; refs; refs = refs->next) 951if(!strcmp(submodule, refs->name)) 952return refs; 953return NULL; 954} 955 956/* 957 * Return a pointer to a ref_cache for the specified submodule. For 958 * the main repository, use submodule==NULL. The returned structure 959 * will be allocated and initialized but not necessarily populated; it 960 * should not be freed. 961 */ 962static struct ref_cache *get_ref_cache(const char*submodule) 963{ 964struct ref_cache *refs =lookup_ref_cache(submodule); 965if(!refs) 966 refs =create_ref_cache(submodule); 967return refs; 968} 969 970/* The length of a peeled reference line in packed-refs, including EOL: */ 971#define PEELED_LINE_LENGTH 42 972 973/* 974 * The packed-refs header line that we write out. Perhaps other 975 * traits will be added later. The trailing space is required. 976 */ 977static const char PACKED_REFS_HEADER[] = 978"# pack-refs with: peeled fully-peeled\n"; 979 980/* 981 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 982 * Return a pointer to the refname within the line (null-terminated), 983 * or NULL if there was a problem. 984 */ 985static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 986{ 987const char*ref; 988 989/* 990 * 42: the answer to everything. 991 * 992 * In this case, it happens to be the answer to 993 * 40 (length of sha1 hex representation) 994 * +1 (space in between hex and name) 995 * +1 (newline at the end of the line) 996 */ 997if(line->len <=42) 998return NULL; 9991000if(get_sha1_hex(line->buf, sha1) <0)1001return NULL;1002if(!isspace(line->buf[40]))1003return NULL;10041005 ref = line->buf +41;1006if(isspace(*ref))1007return NULL;10081009if(line->buf[line->len -1] !='\n')1010return NULL;1011 line->buf[--line->len] =0;10121013return ref;1014}10151016/*1017 * Read f, which is a packed-refs file, into dir.1018 *1019 * A comment line of the form "# pack-refs with: " may contain zero or1020 * more traits. We interpret the traits as follows:1021 *1022 * No traits:1023 *1024 * Probably no references are peeled. But if the file contains a1025 * peeled value for a reference, we will use it.1026 *1027 * peeled:1028 *1029 * References under "refs/tags/", if they *can* be peeled, *are*1030 * peeled in this file. References outside of "refs/tags/" are1031 * probably not peeled even if they could have been, but if we find1032 * a peeled value for such a reference we will use it.1033 *1034 * fully-peeled:1035 *1036 * All references in the file that can be peeled are peeled.1037 * Inversely (and this is more important), any references in the1038 * file for which no peeled value is recorded is not peelable. This1039 * trait should typically be written alongside "peeled" for1040 * compatibility with older clients, but we do not require it1041 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1042 */1043static voidread_packed_refs(FILE*f,struct ref_dir *dir)1044{1045struct ref_entry *last = NULL;1046struct strbuf line = STRBUF_INIT;1047enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10481049while(strbuf_getwholeline(&line, f,'\n') != EOF) {1050unsigned char sha1[20];1051const char*refname;1052const char*traits;10531054if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1055if(strstr(traits," fully-peeled "))1056 peeled = PEELED_FULLY;1057else if(strstr(traits," peeled "))1058 peeled = PEELED_TAGS;1059/* perhaps other traits later as well */1060continue;1061}10621063 refname =parse_ref_line(&line, sha1);1064if(refname) {1065int flag = REF_ISPACKED;10661067if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1068if(!refname_is_safe(refname))1069die("packed refname is dangerous:%s", refname);1070hashclr(sha1);1071 flag |= REF_BAD_NAME | REF_ISBROKEN;1072}1073 last =create_ref_entry(refname, sha1, flag,0);1074if(peeled == PEELED_FULLY ||1075(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1076 last->flag |= REF_KNOWS_PEELED;1077add_ref(dir, last);1078continue;1079}1080if(last &&1081 line.buf[0] =='^'&&1082 line.len == PEELED_LINE_LENGTH &&1083 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1084!get_sha1_hex(line.buf +1, sha1)) {1085hashcpy(last->u.value.peeled.hash, sha1);1086/*1087 * Regardless of what the file header said,1088 * we definitely know the value of *this*1089 * reference:1090 */1091 last->flag |= REF_KNOWS_PEELED;1092}1093}10941095strbuf_release(&line);1096}10971098/*1099 * Get the packed_ref_cache for the specified ref_cache, creating it1100 * if necessary.1101 */1102static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1103{1104char*packed_refs_file;11051106if(*refs->name)1107 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1108else1109 packed_refs_file =git_pathdup("packed-refs");11101111if(refs->packed &&1112!stat_validity_check(&refs->packed->validity, packed_refs_file))1113clear_packed_ref_cache(refs);11141115if(!refs->packed) {1116FILE*f;11171118 refs->packed =xcalloc(1,sizeof(*refs->packed));1119acquire_packed_ref_cache(refs->packed);1120 refs->packed->root =create_dir_entry(refs,"",0,0);1121 f =fopen(packed_refs_file,"r");1122if(f) {1123stat_validity_update(&refs->packed->validity,fileno(f));1124read_packed_refs(f,get_ref_dir(refs->packed->root));1125fclose(f);1126}1127}1128free(packed_refs_file);1129return refs->packed;1130}11311132static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1133{1134returnget_ref_dir(packed_ref_cache->root);1135}11361137static struct ref_dir *get_packed_refs(struct ref_cache *refs)1138{1139returnget_packed_ref_dir(get_packed_ref_cache(refs));1140}11411142/*1143 * Add a reference to the in-memory packed reference cache. This may1144 * only be called while the packed-refs file is locked (see1145 * lock_packed_refs()). To actually write the packed-refs file, call1146 * commit_packed_refs().1147 */1148static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1149{1150struct packed_ref_cache *packed_ref_cache =1151get_packed_ref_cache(&ref_cache);11521153if(!packed_ref_cache->lock)1154die("internal error: packed refs not locked");1155add_ref(get_packed_ref_dir(packed_ref_cache),1156create_ref_entry(refname, sha1, REF_ISPACKED,1));1157}11581159/*1160 * Read the loose references from the namespace dirname into dir1161 * (without recursing). dirname must end with '/'. dir must be the1162 * directory entry corresponding to dirname.1163 */1164static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1165{1166struct ref_cache *refs = dir->ref_cache;1167DIR*d;1168struct dirent *de;1169int dirnamelen =strlen(dirname);1170struct strbuf refname;1171struct strbuf path = STRBUF_INIT;1172size_t path_baselen;11731174if(*refs->name)1175strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1176else1177strbuf_git_path(&path,"%s", dirname);1178 path_baselen = path.len;11791180 d =opendir(path.buf);1181if(!d) {1182strbuf_release(&path);1183return;1184}11851186strbuf_init(&refname, dirnamelen +257);1187strbuf_add(&refname, dirname, dirnamelen);11881189while((de =readdir(d)) != NULL) {1190unsigned char sha1[20];1191struct stat st;1192int flag;11931194if(de->d_name[0] =='.')1195continue;1196if(ends_with(de->d_name,".lock"))1197continue;1198strbuf_addstr(&refname, de->d_name);1199strbuf_addstr(&path, de->d_name);1200if(stat(path.buf, &st) <0) {1201;/* silently ignore */1202}else if(S_ISDIR(st.st_mode)) {1203strbuf_addch(&refname,'/');1204add_entry_to_dir(dir,1205create_dir_entry(refs, refname.buf,1206 refname.len,1));1207}else{1208int read_ok;12091210if(*refs->name) {1211hashclr(sha1);1212 flag =0;1213 read_ok = !resolve_gitlink_ref(refs->name,1214 refname.buf, sha1);1215}else{1216 read_ok = !read_ref_full(refname.buf,1217 RESOLVE_REF_READING,1218 sha1, &flag);1219}12201221if(!read_ok) {1222hashclr(sha1);1223 flag |= REF_ISBROKEN;1224}else if(is_null_sha1(sha1)) {1225/*1226 * It is so astronomically unlikely1227 * that NULL_SHA1 is the SHA-1 of an1228 * actual object that we consider its1229 * appearance in a loose reference1230 * file to be repo corruption1231 * (probably due to a software bug).1232 */1233 flag |= REF_ISBROKEN;1234}12351236if(check_refname_format(refname.buf,1237 REFNAME_ALLOW_ONELEVEL)) {1238if(!refname_is_safe(refname.buf))1239die("loose refname is dangerous:%s", refname.buf);1240hashclr(sha1);1241 flag |= REF_BAD_NAME | REF_ISBROKEN;1242}1243add_entry_to_dir(dir,1244create_ref_entry(refname.buf, sha1, flag,0));1245}1246strbuf_setlen(&refname, dirnamelen);1247strbuf_setlen(&path, path_baselen);1248}1249strbuf_release(&refname);1250strbuf_release(&path);1251closedir(d);1252}12531254static struct ref_dir *get_loose_refs(struct ref_cache *refs)1255{1256if(!refs->loose) {1257/*1258 * Mark the top-level directory complete because we1259 * are about to read the only subdirectory that can1260 * hold references:1261 */1262 refs->loose =create_dir_entry(refs,"",0,0);1263/*1264 * Create an incomplete entry for "refs/":1265 */1266add_entry_to_dir(get_ref_dir(refs->loose),1267create_dir_entry(refs,"refs/",5,1));1268}1269returnget_ref_dir(refs->loose);1270}12711272#define MAXREFLEN (1024)12731274/*1275 * Called by resolve_gitlink_ref_recursive() after it failed to read1276 * from the loose refs in ref_cache refs. Find <refname> in the1277 * packed-refs file for the submodule.1278 */1279static intresolve_gitlink_packed_ref(struct ref_cache *refs,1280const char*refname,unsigned char*sha1)1281{1282struct ref_entry *ref;1283struct ref_dir *dir =get_packed_refs(refs);12841285 ref =find_ref(dir, refname);1286if(ref == NULL)1287return-1;12881289hashcpy(sha1, ref->u.value.oid.hash);1290return0;1291}12921293static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1294const char*refname,unsigned char*sha1,1295int recursion)1296{1297int fd, len;1298char buffer[128], *p;1299char*path;13001301if(recursion > SYMREF_MAXDEPTH ||strlen(refname) > MAXREFLEN)1302return-1;1303 path = *refs->name1304?git_pathdup_submodule(refs->name,"%s", refname)1305:git_pathdup("%s", refname);1306 fd =open(path, O_RDONLY);1307free(path);1308if(fd <0)1309returnresolve_gitlink_packed_ref(refs, refname, sha1);13101311 len =read(fd, buffer,sizeof(buffer)-1);1312close(fd);1313if(len <0)1314return-1;1315while(len &&isspace(buffer[len-1]))1316 len--;1317 buffer[len] =0;13181319/* Was it a detached head or an old-fashioned symlink? */1320if(!get_sha1_hex(buffer, sha1))1321return0;13221323/* Symref? */1324if(strncmp(buffer,"ref:",4))1325return-1;1326 p = buffer +4;1327while(isspace(*p))1328 p++;13291330returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1331}13321333intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1334{1335int len =strlen(path), retval;1336struct strbuf submodule = STRBUF_INIT;1337struct ref_cache *refs;13381339while(len && path[len-1] =='/')1340 len--;1341if(!len)1342return-1;13431344strbuf_add(&submodule, path, len);1345 refs =lookup_ref_cache(submodule.buf);1346if(!refs) {1347if(!is_nonbare_repository_dir(&submodule)) {1348strbuf_release(&submodule);1349return-1;1350}1351 refs =create_ref_cache(submodule.buf);1352}1353strbuf_release(&submodule);13541355 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1356return retval;1357}13581359/*1360 * Return the ref_entry for the given refname from the packed1361 * references. If it does not exist, return NULL.1362 */1363static struct ref_entry *get_packed_ref(const char*refname)1364{1365returnfind_ref(get_packed_refs(&ref_cache), refname);1366}13671368/*1369 * A loose ref file doesn't exist; check for a packed ref.1370 */1371static intresolve_missing_loose_ref(const char*refname,1372unsigned char*sha1,1373unsigned int*flags)1374{1375struct ref_entry *entry;13761377/*1378 * The loose reference file does not exist; check for a packed1379 * reference.1380 */1381 entry =get_packed_ref(refname);1382if(entry) {1383hashcpy(sha1, entry->u.value.oid.hash);1384*flags |= REF_ISPACKED;1385return0;1386}1387/* refname is not a packed reference. */1388return-1;1389}13901391intread_raw_ref(const char*refname,unsigned char*sha1,1392struct strbuf *referent,unsigned int*type)1393{1394struct strbuf sb_contents = STRBUF_INIT;1395struct strbuf sb_path = STRBUF_INIT;1396const char*path;1397const char*buf;1398struct stat st;1399int fd;1400int ret = -1;1401int save_errno;14021403*type =0;1404strbuf_reset(&sb_path);1405strbuf_git_path(&sb_path,"%s", refname);1406 path = sb_path.buf;14071408stat_ref:1409/*1410 * We might have to loop back here to avoid a race1411 * condition: first we lstat() the file, then we try1412 * to read it as a link or as a file. But if somebody1413 * changes the type of the file (file <-> directory1414 * <-> symlink) between the lstat() and reading, then1415 * we don't want to report that as an error but rather1416 * try again starting with the lstat().1417 */14181419if(lstat(path, &st) <0) {1420if(errno != ENOENT)1421goto out;1422if(resolve_missing_loose_ref(refname, sha1, type)) {1423 errno = ENOENT;1424goto out;1425}1426 ret =0;1427goto out;1428}14291430/* Follow "normalized" - ie "refs/.." symlinks by hand */1431if(S_ISLNK(st.st_mode)) {1432strbuf_reset(&sb_contents);1433if(strbuf_readlink(&sb_contents, path,0) <0) {1434if(errno == ENOENT || errno == EINVAL)1435/* inconsistent with lstat; retry */1436goto stat_ref;1437else1438goto out;1439}1440if(starts_with(sb_contents.buf,"refs/") &&1441!check_refname_format(sb_contents.buf,0)) {1442strbuf_swap(&sb_contents, referent);1443*type |= REF_ISSYMREF;1444 ret =0;1445goto out;1446}1447}14481449/* Is it a directory? */1450if(S_ISDIR(st.st_mode)) {1451/*1452 * Even though there is a directory where the loose1453 * ref is supposed to be, there could still be a1454 * packed ref:1455 */1456if(resolve_missing_loose_ref(refname, sha1, type)) {1457 errno = EISDIR;1458goto out;1459}1460 ret =0;1461goto out;1462}14631464/*1465 * Anything else, just open it and try to use it as1466 * a ref1467 */1468 fd =open(path, O_RDONLY);1469if(fd <0) {1470if(errno == ENOENT)1471/* inconsistent with lstat; retry */1472goto stat_ref;1473else1474goto out;1475}1476strbuf_reset(&sb_contents);1477if(strbuf_read(&sb_contents, fd,256) <0) {1478int save_errno = errno;1479close(fd);1480 errno = save_errno;1481goto out;1482}1483close(fd);1484strbuf_rtrim(&sb_contents);1485 buf = sb_contents.buf;1486if(starts_with(buf,"ref:")) {1487 buf +=4;1488while(isspace(*buf))1489 buf++;14901491strbuf_reset(referent);1492strbuf_addstr(referent, buf);1493*type |= REF_ISSYMREF;1494 ret =0;1495goto out;1496}14971498/*1499 * Please note that FETCH_HEAD has additional1500 * data after the sha.1501 */1502if(get_sha1_hex(buf, sha1) ||1503(buf[40] !='\0'&& !isspace(buf[40]))) {1504*type |= REF_ISBROKEN;1505 errno = EINVAL;1506goto out;1507}15081509 ret =0;15101511out:1512 save_errno = errno;1513strbuf_release(&sb_path);1514strbuf_release(&sb_contents);1515 errno = save_errno;1516return ret;1517}15181519static voidunlock_ref(struct ref_lock *lock)1520{1521/* Do not free lock->lk -- atexit() still looks at them */1522if(lock->lk)1523rollback_lock_file(lock->lk);1524free(lock->ref_name);1525free(lock->orig_ref_name);1526free(lock);1527}15281529/*1530 * Lock refname, without following symrefs, and set *lock_p to point1531 * at a newly-allocated lock object. Fill in lock->old_oid, referent,1532 * and type similarly to read_raw_ref().1533 *1534 * The caller must verify that refname is a "safe" reference name (in1535 * the sense of refname_is_safe()) before calling this function.1536 *1537 * If the reference doesn't already exist, verify that refname doesn't1538 * have a D/F conflict with any existing references. extras and skip1539 * are passed to verify_refname_available_dir() for this check.1540 *1541 * If mustexist is not set and the reference is not found or is1542 * broken, lock the reference anyway but clear sha1.1543 *1544 * Return 0 on success. On failure, write an error message to err and1545 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR.1546 *1547 * Implementation note: This function is basically1548 *1549 * lock reference1550 * read_raw_ref()1551 *1552 * but it includes a lot more code to1553 * - Deal with possible races with other processes1554 * - Avoid calling verify_refname_available_dir() when it can be1555 * avoided, namely if we were successfully able to read the ref1556 * - Generate informative error messages in the case of failure1557 */1558static intlock_raw_ref(const char*refname,int mustexist,1559const struct string_list *extras,1560const struct string_list *skip,1561struct ref_lock **lock_p,1562struct strbuf *referent,1563unsigned int*type,1564struct strbuf *err)1565{1566struct ref_lock *lock;1567struct strbuf ref_file = STRBUF_INIT;1568int attempts_remaining =3;1569int ret = TRANSACTION_GENERIC_ERROR;15701571assert(err);1572*type =0;15731574/* First lock the file so it can't change out from under us. */15751576*lock_p = lock =xcalloc(1,sizeof(*lock));15771578 lock->ref_name =xstrdup(refname);1579 lock->orig_ref_name =xstrdup(refname);1580strbuf_git_path(&ref_file,"%s", refname);15811582retry:1583switch(safe_create_leading_directories(ref_file.buf)) {1584case SCLD_OK:1585break;/* success */1586case SCLD_EXISTS:1587/*1588 * Suppose refname is "refs/foo/bar". We just failed1589 * to create the containing directory, "refs/foo",1590 * because there was a non-directory in the way. This1591 * indicates a D/F conflict, probably because of1592 * another reference such as "refs/foo". There is no1593 * reason to expect this error to be transitory.1594 */1595if(verify_refname_available(refname, extras, skip, err)) {1596if(mustexist) {1597/*1598 * To the user the relevant error is1599 * that the "mustexist" reference is1600 * missing:1601 */1602strbuf_reset(err);1603strbuf_addf(err,"unable to resolve reference '%s'",1604 refname);1605}else{1606/*1607 * The error message set by1608 * verify_refname_available_dir() is OK.1609 */1610 ret = TRANSACTION_NAME_CONFLICT;1611}1612}else{1613/*1614 * The file that is in the way isn't a loose1615 * reference. Report it as a low-level1616 * failure.1617 */1618strbuf_addf(err,"unable to create lock file%s.lock; "1619"non-directory in the way",1620 ref_file.buf);1621}1622goto error_return;1623case SCLD_VANISHED:1624/* Maybe another process was tidying up. Try again. */1625if(--attempts_remaining >0)1626goto retry;1627/* fall through */1628default:1629strbuf_addf(err,"unable to create directory for%s",1630 ref_file.buf);1631goto error_return;1632}16331634if(!lock->lk)1635 lock->lk =xcalloc(1,sizeof(struct lock_file));16361637if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) {1638if(errno == ENOENT && --attempts_remaining >0) {1639/*1640 * Maybe somebody just deleted one of the1641 * directories leading to ref_file. Try1642 * again:1643 */1644goto retry;1645}else{1646unable_to_lock_message(ref_file.buf, errno, err);1647goto error_return;1648}1649}16501651/*1652 * Now we hold the lock and can read the reference without1653 * fear that its value will change.1654 */16551656if(read_raw_ref(refname, lock->old_oid.hash, referent, type)) {1657if(errno == ENOENT) {1658if(mustexist) {1659/* Garden variety missing reference. */1660strbuf_addf(err,"unable to resolve reference '%s'",1661 refname);1662goto error_return;1663}else{1664/*1665 * Reference is missing, but that's OK. We1666 * know that there is not a conflict with1667 * another loose reference because1668 * (supposing that we are trying to lock1669 * reference "refs/foo/bar"):1670 *1671 * - We were successfully able to create1672 * the lockfile refs/foo/bar.lock, so we1673 * know there cannot be a loose reference1674 * named "refs/foo".1675 *1676 * - We got ENOENT and not EISDIR, so we1677 * know that there cannot be a loose1678 * reference named "refs/foo/bar/baz".1679 */1680}1681}else if(errno == EISDIR) {1682/*1683 * There is a directory in the way. It might have1684 * contained references that have been deleted. If1685 * we don't require that the reference already1686 * exists, try to remove the directory so that it1687 * doesn't cause trouble when we want to rename the1688 * lockfile into place later.1689 */1690if(mustexist) {1691/* Garden variety missing reference. */1692strbuf_addf(err,"unable to resolve reference '%s'",1693 refname);1694goto error_return;1695}else if(remove_dir_recursively(&ref_file,1696 REMOVE_DIR_EMPTY_ONLY)) {1697if(verify_refname_available_dir(1698 refname, extras, skip,1699get_loose_refs(&ref_cache),1700 err)) {1701/*1702 * The error message set by1703 * verify_refname_available() is OK.1704 */1705 ret = TRANSACTION_NAME_CONFLICT;1706goto error_return;1707}else{1708/*1709 * We can't delete the directory,1710 * but we also don't know of any1711 * references that it should1712 * contain.1713 */1714strbuf_addf(err,"there is a non-empty directory '%s' "1715"blocking reference '%s'",1716 ref_file.buf, refname);1717goto error_return;1718}1719}1720}else if(errno == EINVAL && (*type & REF_ISBROKEN)) {1721strbuf_addf(err,"unable to resolve reference '%s': "1722"reference broken", refname);1723goto error_return;1724}else{1725strbuf_addf(err,"unable to resolve reference '%s':%s",1726 refname,strerror(errno));1727goto error_return;1728}17291730/*1731 * If the ref did not exist and we are creating it,1732 * make sure there is no existing packed ref whose1733 * name begins with our refname, nor a packed ref1734 * whose name is a proper prefix of our refname.1735 */1736if(verify_refname_available_dir(1737 refname, extras, skip,1738get_packed_refs(&ref_cache),1739 err)) {1740goto error_return;1741}1742}17431744 ret =0;1745goto out;17461747error_return:1748unlock_ref(lock);1749*lock_p = NULL;17501751out:1752strbuf_release(&ref_file);1753return ret;1754}17551756/*1757 * Peel the entry (if possible) and return its new peel_status. If1758 * repeel is true, re-peel the entry even if there is an old peeled1759 * value that is already stored in it.1760 *1761 * It is OK to call this function with a packed reference entry that1762 * might be stale and might even refer to an object that has since1763 * been garbage-collected. In such a case, if the entry has1764 * REF_KNOWS_PEELED then leave the status unchanged and return1765 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1766 */1767static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1768{1769enum peel_status status;17701771if(entry->flag & REF_KNOWS_PEELED) {1772if(repeel) {1773 entry->flag &= ~REF_KNOWS_PEELED;1774oidclr(&entry->u.value.peeled);1775}else{1776returnis_null_oid(&entry->u.value.peeled) ?1777 PEEL_NON_TAG : PEEL_PEELED;1778}1779}1780if(entry->flag & REF_ISBROKEN)1781return PEEL_BROKEN;1782if(entry->flag & REF_ISSYMREF)1783return PEEL_IS_SYMREF;17841785 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1786if(status == PEEL_PEELED || status == PEEL_NON_TAG)1787 entry->flag |= REF_KNOWS_PEELED;1788return status;1789}17901791intpeel_ref(const char*refname,unsigned char*sha1)1792{1793int flag;1794unsigned char base[20];17951796if(current_ref && (current_ref->name == refname1797|| !strcmp(current_ref->name, refname))) {1798if(peel_entry(current_ref,0))1799return-1;1800hashcpy(sha1, current_ref->u.value.peeled.hash);1801return0;1802}18031804if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1805return-1;18061807/*1808 * If the reference is packed, read its ref_entry from the1809 * cache in the hope that we already know its peeled value.1810 * We only try this optimization on packed references because1811 * (a) forcing the filling of the loose reference cache could1812 * be expensive and (b) loose references anyway usually do not1813 * have REF_KNOWS_PEELED.1814 */1815if(flag & REF_ISPACKED) {1816struct ref_entry *r =get_packed_ref(refname);1817if(r) {1818if(peel_entry(r,0))1819return-1;1820hashcpy(sha1, r->u.value.peeled.hash);1821return0;1822}1823}18241825returnpeel_object(base, sha1);1826}18271828/*1829 * Call fn for each reference in the specified ref_cache, omitting1830 * references not in the containing_dir of base. fn is called for all1831 * references, including broken ones. If fn ever returns a non-zero1832 * value, stop the iteration and return that value; otherwise, return1833 * 0.1834 */1835static intdo_for_each_entry(struct ref_cache *refs,const char*base,1836 each_ref_entry_fn fn,void*cb_data)1837{1838struct packed_ref_cache *packed_ref_cache;1839struct ref_dir *loose_dir;1840struct ref_dir *packed_dir;1841int retval =0;18421843/*1844 * We must make sure that all loose refs are read before accessing the1845 * packed-refs file; this avoids a race condition in which loose refs1846 * are migrated to the packed-refs file by a simultaneous process, but1847 * our in-memory view is from before the migration. get_packed_ref_cache()1848 * takes care of making sure our view is up to date with what is on1849 * disk.1850 */1851 loose_dir =get_loose_refs(refs);1852if(base && *base) {1853 loose_dir =find_containing_dir(loose_dir, base,0);1854}1855if(loose_dir)1856prime_ref_dir(loose_dir);18571858 packed_ref_cache =get_packed_ref_cache(refs);1859acquire_packed_ref_cache(packed_ref_cache);1860 packed_dir =get_packed_ref_dir(packed_ref_cache);1861if(base && *base) {1862 packed_dir =find_containing_dir(packed_dir, base,0);1863}18641865if(packed_dir && loose_dir) {1866sort_ref_dir(packed_dir);1867sort_ref_dir(loose_dir);1868 retval =do_for_each_entry_in_dirs(1869 packed_dir, loose_dir, fn, cb_data);1870}else if(packed_dir) {1871sort_ref_dir(packed_dir);1872 retval =do_for_each_entry_in_dir(1873 packed_dir,0, fn, cb_data);1874}else if(loose_dir) {1875sort_ref_dir(loose_dir);1876 retval =do_for_each_entry_in_dir(1877 loose_dir,0, fn, cb_data);1878}18791880release_packed_ref_cache(packed_ref_cache);1881return retval;1882}18831884/*1885 * Call fn for each reference in the specified ref_cache for which the1886 * refname begins with base. If trim is non-zero, then trim that many1887 * characters off the beginning of each refname before passing the1888 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1889 * broken references in the iteration. If fn ever returns a non-zero1890 * value, stop the iteration and return that value; otherwise, return1891 * 0.1892 */1893intdo_for_each_ref(const char*submodule,const char*base,1894 each_ref_fn fn,int trim,int flags,void*cb_data)1895{1896struct ref_entry_cb data;1897struct ref_cache *refs;18981899 refs =get_ref_cache(submodule);1900 data.base = base;1901 data.trim = trim;1902 data.flags = flags;1903 data.fn = fn;1904 data.cb_data = cb_data;19051906if(ref_paranoia <0)1907 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1908if(ref_paranoia)1909 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;19101911returndo_for_each_entry(refs, base, do_one_ref, &data);1912}19131914/*1915 * Verify that the reference locked by lock has the value old_sha1.1916 * Fail if the reference doesn't exist and mustexist is set. Return 01917 * on success. On error, write an error message to err, set errno, and1918 * return a negative value.1919 */1920static intverify_lock(struct ref_lock *lock,1921const unsigned char*old_sha1,int mustexist,1922struct strbuf *err)1923{1924assert(err);19251926if(read_ref_full(lock->ref_name,1927 mustexist ? RESOLVE_REF_READING :0,1928 lock->old_oid.hash, NULL)) {1929if(old_sha1) {1930int save_errno = errno;1931strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1932 errno = save_errno;1933return-1;1934}else{1935hashclr(lock->old_oid.hash);1936return0;1937}1938}1939if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1940strbuf_addf(err,"ref '%s' is at%sbut expected%s",1941 lock->ref_name,1942sha1_to_hex(lock->old_oid.hash),1943sha1_to_hex(old_sha1));1944 errno = EBUSY;1945return-1;1946}1947return0;1948}19491950static intremove_empty_directories(struct strbuf *path)1951{1952/*1953 * we want to create a file but there is a directory there;1954 * if that is an empty directory (or a directory that contains1955 * only empty directories), remove them.1956 */1957returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1958}19591960/*1961 * Locks a ref returning the lock on success and NULL on failure.1962 * On failure errno is set to something meaningful.1963 */1964static struct ref_lock *lock_ref_sha1_basic(const char*refname,1965const unsigned char*old_sha1,1966const struct string_list *extras,1967const struct string_list *skip,1968unsigned int flags,int*type,1969struct strbuf *err)1970{1971struct strbuf ref_file = STRBUF_INIT;1972struct strbuf orig_ref_file = STRBUF_INIT;1973const char*orig_refname = refname;1974struct ref_lock *lock;1975int last_errno =0;1976int lflags =0;1977int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1978int resolve_flags =0;1979int attempts_remaining =3;19801981assert(err);19821983 lock =xcalloc(1,sizeof(struct ref_lock));19841985if(mustexist)1986 resolve_flags |= RESOLVE_REF_READING;1987if(flags & REF_DELETING)1988 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1989if(flags & REF_NODEREF) {1990 resolve_flags |= RESOLVE_REF_NO_RECURSE;1991 lflags |= LOCK_NO_DEREF;1992}19931994 refname =resolve_ref_unsafe(refname, resolve_flags,1995 lock->old_oid.hash, type);1996if(!refname && errno == EISDIR) {1997/*1998 * we are trying to lock foo but we used to1999 * have foo/bar which now does not exist;2000 * it is normal for the empty directory 'foo'2001 * to remain.2002 */2003strbuf_git_path(&orig_ref_file,"%s", orig_refname);2004if(remove_empty_directories(&orig_ref_file)) {2005 last_errno = errno;2006if(!verify_refname_available_dir(orig_refname, extras, skip,2007get_loose_refs(&ref_cache), err))2008strbuf_addf(err,"there are still refs under '%s'",2009 orig_refname);2010goto error_return;2011}2012 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2013 lock->old_oid.hash, type);2014}2015if(!refname) {2016 last_errno = errno;2017if(last_errno != ENOTDIR ||2018!verify_refname_available_dir(orig_refname, extras, skip,2019get_loose_refs(&ref_cache), err))2020strbuf_addf(err,"unable to resolve reference '%s':%s",2021 orig_refname,strerror(last_errno));20222023goto error_return;2024}20252026if(flags & REF_NODEREF)2027 refname = orig_refname;20282029/*2030 * If the ref did not exist and we are creating it, make sure2031 * there is no existing packed ref whose name begins with our2032 * refname, nor a packed ref whose name is a proper prefix of2033 * our refname.2034 */2035if(is_null_oid(&lock->old_oid) &&2036verify_refname_available_dir(refname, extras, skip,2037get_packed_refs(&ref_cache), err)) {2038 last_errno = ENOTDIR;2039goto error_return;2040}20412042 lock->lk =xcalloc(1,sizeof(struct lock_file));20432044 lock->ref_name =xstrdup(refname);2045 lock->orig_ref_name =xstrdup(orig_refname);2046strbuf_git_path(&ref_file,"%s", refname);20472048 retry:2049switch(safe_create_leading_directories_const(ref_file.buf)) {2050case SCLD_OK:2051break;/* success */2052case SCLD_VANISHED:2053if(--attempts_remaining >0)2054goto retry;2055/* fall through */2056default:2057 last_errno = errno;2058strbuf_addf(err,"unable to create directory for '%s'",2059 ref_file.buf);2060goto error_return;2061}20622063if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2064 last_errno = errno;2065if(errno == ENOENT && --attempts_remaining >0)2066/*2067 * Maybe somebody just deleted one of the2068 * directories leading to ref_file. Try2069 * again:2070 */2071goto retry;2072else{2073unable_to_lock_message(ref_file.buf, errno, err);2074goto error_return;2075}2076}2077if(verify_lock(lock, old_sha1, mustexist, err)) {2078 last_errno = errno;2079goto error_return;2080}2081goto out;20822083 error_return:2084unlock_ref(lock);2085 lock = NULL;20862087 out:2088strbuf_release(&ref_file);2089strbuf_release(&orig_ref_file);2090 errno = last_errno;2091return lock;2092}20932094/*2095 * Write an entry to the packed-refs file for the specified refname.2096 * If peeled is non-NULL, write it as the entry's peeled value.2097 */2098static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2099unsigned char*peeled)2100{2101fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2102if(peeled)2103fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2104}21052106/*2107 * An each_ref_entry_fn that writes the entry to a packed-refs file.2108 */2109static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2110{2111enum peel_status peel_status =peel_entry(entry,0);21122113if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2114error("internal error:%sis not a valid packed reference!",2115 entry->name);2116write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2117 peel_status == PEEL_PEELED ?2118 entry->u.value.peeled.hash : NULL);2119return0;2120}21212122/*2123 * Lock the packed-refs file for writing. Flags is passed to2124 * hold_lock_file_for_update(). Return 0 on success. On errors, set2125 * errno appropriately and return a nonzero value.2126 */2127static intlock_packed_refs(int flags)2128{2129static int timeout_configured =0;2130static int timeout_value =1000;21312132struct packed_ref_cache *packed_ref_cache;21332134if(!timeout_configured) {2135git_config_get_int("core.packedrefstimeout", &timeout_value);2136 timeout_configured =1;2137}21382139if(hold_lock_file_for_update_timeout(2140&packlock,git_path("packed-refs"),2141 flags, timeout_value) <0)2142return-1;2143/*2144 * Get the current packed-refs while holding the lock. If the2145 * packed-refs file has been modified since we last read it,2146 * this will automatically invalidate the cache and re-read2147 * the packed-refs file.2148 */2149 packed_ref_cache =get_packed_ref_cache(&ref_cache);2150 packed_ref_cache->lock = &packlock;2151/* Increment the reference count to prevent it from being freed: */2152acquire_packed_ref_cache(packed_ref_cache);2153return0;2154}21552156/*2157 * Write the current version of the packed refs cache from memory to2158 * disk. The packed-refs file must already be locked for writing (see2159 * lock_packed_refs()). Return zero on success. On errors, set errno2160 * and return a nonzero value2161 */2162static intcommit_packed_refs(void)2163{2164struct packed_ref_cache *packed_ref_cache =2165get_packed_ref_cache(&ref_cache);2166int error =0;2167int save_errno =0;2168FILE*out;21692170if(!packed_ref_cache->lock)2171die("internal error: packed-refs not locked");21722173 out =fdopen_lock_file(packed_ref_cache->lock,"w");2174if(!out)2175die_errno("unable to fdopen packed-refs descriptor");21762177fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2178do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),21790, write_packed_entry_fn, out);21802181if(commit_lock_file(packed_ref_cache->lock)) {2182 save_errno = errno;2183 error = -1;2184}2185 packed_ref_cache->lock = NULL;2186release_packed_ref_cache(packed_ref_cache);2187 errno = save_errno;2188return error;2189}21902191/*2192 * Rollback the lockfile for the packed-refs file, and discard the2193 * in-memory packed reference cache. (The packed-refs file will be2194 * read anew if it is needed again after this function is called.)2195 */2196static voidrollback_packed_refs(void)2197{2198struct packed_ref_cache *packed_ref_cache =2199get_packed_ref_cache(&ref_cache);22002201if(!packed_ref_cache->lock)2202die("internal error: packed-refs not locked");2203rollback_lock_file(packed_ref_cache->lock);2204 packed_ref_cache->lock = NULL;2205release_packed_ref_cache(packed_ref_cache);2206clear_packed_ref_cache(&ref_cache);2207}22082209struct ref_to_prune {2210struct ref_to_prune *next;2211unsigned char sha1[20];2212char name[FLEX_ARRAY];2213};22142215struct pack_refs_cb_data {2216unsigned int flags;2217struct ref_dir *packed_refs;2218struct ref_to_prune *ref_to_prune;2219};22202221/*2222 * An each_ref_entry_fn that is run over loose references only. If2223 * the loose reference can be packed, add an entry in the packed ref2224 * cache. If the reference should be pruned, also add it to2225 * ref_to_prune in the pack_refs_cb_data.2226 */2227static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2228{2229struct pack_refs_cb_data *cb = cb_data;2230enum peel_status peel_status;2231struct ref_entry *packed_entry;2232int is_tag_ref =starts_with(entry->name,"refs/tags/");22332234/* Do not pack per-worktree refs: */2235if(ref_type(entry->name) != REF_TYPE_NORMAL)2236return0;22372238/* ALWAYS pack tags */2239if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2240return0;22412242/* Do not pack symbolic or broken refs: */2243if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2244return0;22452246/* Add a packed ref cache entry equivalent to the loose entry. */2247 peel_status =peel_entry(entry,1);2248if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2249die("internal error peeling reference%s(%s)",2250 entry->name,oid_to_hex(&entry->u.value.oid));2251 packed_entry =find_ref(cb->packed_refs, entry->name);2252if(packed_entry) {2253/* Overwrite existing packed entry with info from loose entry */2254 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2255oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2256}else{2257 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2258 REF_ISPACKED | REF_KNOWS_PEELED,0);2259add_ref(cb->packed_refs, packed_entry);2260}2261oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);22622263/* Schedule the loose reference for pruning if requested. */2264if((cb->flags & PACK_REFS_PRUNE)) {2265struct ref_to_prune *n;2266FLEX_ALLOC_STR(n, name, entry->name);2267hashcpy(n->sha1, entry->u.value.oid.hash);2268 n->next = cb->ref_to_prune;2269 cb->ref_to_prune = n;2270}2271return0;2272}22732274/*2275 * Remove empty parents, but spare refs/ and immediate subdirs.2276 * Note: munges *name.2277 */2278static voidtry_remove_empty_parents(char*name)2279{2280char*p, *q;2281int i;2282 p = name;2283for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2284while(*p && *p !='/')2285 p++;2286/* tolerate duplicate slashes; see check_refname_format() */2287while(*p =='/')2288 p++;2289}2290for(q = p; *q; q++)2291;2292while(1) {2293while(q > p && *q !='/')2294 q--;2295while(q > p && *(q-1) =='/')2296 q--;2297if(q == p)2298break;2299*q ='\0';2300if(rmdir(git_path("%s", name)))2301break;2302}2303}23042305/* make sure nobody touched the ref, and unlink */2306static voidprune_ref(struct ref_to_prune *r)2307{2308struct ref_transaction *transaction;2309struct strbuf err = STRBUF_INIT;23102311if(check_refname_format(r->name,0))2312return;23132314 transaction =ref_transaction_begin(&err);2315if(!transaction ||2316ref_transaction_delete(transaction, r->name, r->sha1,2317 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||2318ref_transaction_commit(transaction, &err)) {2319ref_transaction_free(transaction);2320error("%s", err.buf);2321strbuf_release(&err);2322return;2323}2324ref_transaction_free(transaction);2325strbuf_release(&err);2326try_remove_empty_parents(r->name);2327}23282329static voidprune_refs(struct ref_to_prune *r)2330{2331while(r) {2332prune_ref(r);2333 r = r->next;2334}2335}23362337intpack_refs(unsigned int flags)2338{2339struct pack_refs_cb_data cbdata;23402341memset(&cbdata,0,sizeof(cbdata));2342 cbdata.flags = flags;23432344lock_packed_refs(LOCK_DIE_ON_ERROR);2345 cbdata.packed_refs =get_packed_refs(&ref_cache);23462347do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2348 pack_if_possible_fn, &cbdata);23492350if(commit_packed_refs())2351die_errno("unable to overwrite old ref-pack file");23522353prune_refs(cbdata.ref_to_prune);2354return0;2355}23562357/*2358 * Rewrite the packed-refs file, omitting any refs listed in2359 * 'refnames'. On error, leave packed-refs unchanged, write an error2360 * message to 'err', and return a nonzero value.2361 *2362 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2363 */2364static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2365{2366struct ref_dir *packed;2367struct string_list_item *refname;2368int ret, needs_repacking =0, removed =0;23692370assert(err);23712372/* Look for a packed ref */2373for_each_string_list_item(refname, refnames) {2374if(get_packed_ref(refname->string)) {2375 needs_repacking =1;2376break;2377}2378}23792380/* Avoid locking if we have nothing to do */2381if(!needs_repacking)2382return0;/* no refname exists in packed refs */23832384if(lock_packed_refs(0)) {2385unable_to_lock_message(git_path("packed-refs"), errno, err);2386return-1;2387}2388 packed =get_packed_refs(&ref_cache);23892390/* Remove refnames from the cache */2391for_each_string_list_item(refname, refnames)2392if(remove_entry(packed, refname->string) != -1)2393 removed =1;2394if(!removed) {2395/*2396 * All packed entries disappeared while we were2397 * acquiring the lock.2398 */2399rollback_packed_refs();2400return0;2401}24022403/* Write what remains */2404 ret =commit_packed_refs();2405if(ret)2406strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2407strerror(errno));2408return ret;2409}24102411static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2412{2413assert(err);24142415if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2416/*2417 * loose. The loose file name is the same as the2418 * lockfile name, minus ".lock":2419 */2420char*loose_filename =get_locked_file_path(lock->lk);2421int res =unlink_or_msg(loose_filename, err);2422free(loose_filename);2423if(res)2424return1;2425}2426return0;2427}24282429intdelete_refs(struct string_list *refnames)2430{2431struct strbuf err = STRBUF_INIT;2432int i, result =0;24332434if(!refnames->nr)2435return0;24362437 result =repack_without_refs(refnames, &err);2438if(result) {2439/*2440 * If we failed to rewrite the packed-refs file, then2441 * it is unsafe to try to remove loose refs, because2442 * doing so might expose an obsolete packed value for2443 * a reference that might even point at an object that2444 * has been garbage collected.2445 */2446if(refnames->nr ==1)2447error(_("could not delete reference%s:%s"),2448 refnames->items[0].string, err.buf);2449else2450error(_("could not delete references:%s"), err.buf);24512452goto out;2453}24542455for(i =0; i < refnames->nr; i++) {2456const char*refname = refnames->items[i].string;24572458if(delete_ref(refname, NULL,0))2459 result |=error(_("could not remove reference%s"), refname);2460}24612462out:2463strbuf_release(&err);2464return result;2465}24662467/*2468 * People using contrib's git-new-workdir have .git/logs/refs ->2469 * /some/other/path/.git/logs/refs, and that may live on another device.2470 *2471 * IOW, to avoid cross device rename errors, the temporary renamed log must2472 * live into logs/refs.2473 */2474#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"24752476static intrename_tmp_log(const char*newrefname)2477{2478int attempts_remaining =4;2479struct strbuf path = STRBUF_INIT;2480int ret = -1;24812482 retry:2483strbuf_reset(&path);2484strbuf_git_path(&path,"logs/%s", newrefname);2485switch(safe_create_leading_directories_const(path.buf)) {2486case SCLD_OK:2487break;/* success */2488case SCLD_VANISHED:2489if(--attempts_remaining >0)2490goto retry;2491/* fall through */2492default:2493error("unable to create directory for%s", newrefname);2494goto out;2495}24962497if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2498if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2499/*2500 * rename(a, b) when b is an existing2501 * directory ought to result in ISDIR, but2502 * Solaris 5.8 gives ENOTDIR. Sheesh.2503 */2504if(remove_empty_directories(&path)) {2505error("Directory not empty: logs/%s", newrefname);2506goto out;2507}2508goto retry;2509}else if(errno == ENOENT && --attempts_remaining >0) {2510/*2511 * Maybe another process just deleted one of2512 * the directories in the path to newrefname.2513 * Try again from the beginning.2514 */2515goto retry;2516}else{2517error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2518 newrefname,strerror(errno));2519goto out;2520}2521}2522 ret =0;2523out:2524strbuf_release(&path);2525return ret;2526}25272528intverify_refname_available(const char*newname,2529const struct string_list *extras,2530const struct string_list *skip,2531struct strbuf *err)2532{2533struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2534struct ref_dir *loose_refs =get_loose_refs(&ref_cache);25352536if(verify_refname_available_dir(newname, extras, skip,2537 packed_refs, err) ||2538verify_refname_available_dir(newname, extras, skip,2539 loose_refs, err))2540return-1;25412542return0;2543}25442545static intwrite_ref_to_lockfile(struct ref_lock *lock,2546const unsigned char*sha1,struct strbuf *err);2547static intcommit_ref_update(struct ref_lock *lock,2548const unsigned char*sha1,const char*logmsg,2549int flags,struct strbuf *err);25502551intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2552{2553unsigned char sha1[20], orig_sha1[20];2554int flag =0, logmoved =0;2555struct ref_lock *lock;2556struct stat loginfo;2557int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2558struct strbuf err = STRBUF_INIT;25592560if(log &&S_ISLNK(loginfo.st_mode))2561returnerror("reflog for%sis a symlink", oldrefname);25622563if(!resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2564 orig_sha1, &flag))2565returnerror("refname%snot found", oldrefname);25662567if(flag & REF_ISSYMREF)2568returnerror("refname%sis a symbolic ref, renaming it is not supported",2569 oldrefname);2570if(!rename_ref_available(oldrefname, newrefname))2571return1;25722573if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2574returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2575 oldrefname,strerror(errno));25762577if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2578error("unable to delete old%s", oldrefname);2579goto rollback;2580}25812582/*2583 * Since we are doing a shallow lookup, sha1 is not the2584 * correct value to pass to delete_ref as old_sha1. But that2585 * doesn't matter, because an old_sha1 check wouldn't add to2586 * the safety anyway; we want to delete the reference whatever2587 * its current value.2588 */2589if(!read_ref_full(newrefname, RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,2590 sha1, NULL) &&2591delete_ref(newrefname, NULL, REF_NODEREF)) {2592if(errno==EISDIR) {2593struct strbuf path = STRBUF_INIT;2594int result;25952596strbuf_git_path(&path,"%s", newrefname);2597 result =remove_empty_directories(&path);2598strbuf_release(&path);25992600if(result) {2601error("Directory not empty:%s", newrefname);2602goto rollback;2603}2604}else{2605error("unable to delete existing%s", newrefname);2606goto rollback;2607}2608}26092610if(log &&rename_tmp_log(newrefname))2611goto rollback;26122613 logmoved = log;26142615 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL, REF_NODEREF,2616 NULL, &err);2617if(!lock) {2618error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2619strbuf_release(&err);2620goto rollback;2621}2622hashcpy(lock->old_oid.hash, orig_sha1);26232624if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2625commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2626error("unable to write current sha1 into%s:%s", newrefname, err.buf);2627strbuf_release(&err);2628goto rollback;2629}26302631return0;26322633 rollback:2634 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL, REF_NODEREF,2635 NULL, &err);2636if(!lock) {2637error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2638strbuf_release(&err);2639goto rollbacklog;2640}26412642 flag = log_all_ref_updates;2643 log_all_ref_updates =0;2644if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2645commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2646error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2647strbuf_release(&err);2648}2649 log_all_ref_updates = flag;26502651 rollbacklog:2652if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2653error("unable to restore logfile%sfrom%s:%s",2654 oldrefname, newrefname,strerror(errno));2655if(!logmoved && log &&2656rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2657error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2658 oldrefname,strerror(errno));26592660return1;2661}26622663static intclose_ref(struct ref_lock *lock)2664{2665if(close_lock_file(lock->lk))2666return-1;2667return0;2668}26692670static intcommit_ref(struct ref_lock *lock)2671{2672char*path =get_locked_file_path(lock->lk);2673struct stat st;26742675if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {2676/*2677 * There is a directory at the path we want to rename2678 * the lockfile to. Hopefully it is empty; try to2679 * delete it.2680 */2681size_t len =strlen(path);2682struct strbuf sb_path = STRBUF_INIT;26832684strbuf_attach(&sb_path, path, len, len);26852686/*2687 * If this fails, commit_lock_file() will also fail2688 * and will report the problem.2689 */2690remove_empty_directories(&sb_path);2691strbuf_release(&sb_path);2692}else{2693free(path);2694}26952696if(commit_lock_file(lock->lk))2697return-1;2698return0;2699}27002701/*2702 * Create a reflog for a ref. If force_create = 0, the reflog will2703 * only be created for certain refs (those for which2704 * should_autocreate_reflog returns non-zero. Otherwise, create it2705 * regardless of the ref name. Fill in *err and return -1 on failure.2706 */2707static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2708{2709int logfd, oflags = O_APPEND | O_WRONLY;27102711strbuf_git_path(logfile,"logs/%s", refname);2712if(force_create ||should_autocreate_reflog(refname)) {2713if(safe_create_leading_directories(logfile->buf) <0) {2714strbuf_addf(err,"unable to create directory for '%s': "2715"%s", logfile->buf,strerror(errno));2716return-1;2717}2718 oflags |= O_CREAT;2719}27202721 logfd =open(logfile->buf, oflags,0666);2722if(logfd <0) {2723if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2724return0;27252726if(errno == EISDIR) {2727if(remove_empty_directories(logfile)) {2728strbuf_addf(err,"there are still logs under "2729"'%s'", logfile->buf);2730return-1;2731}2732 logfd =open(logfile->buf, oflags,0666);2733}27342735if(logfd <0) {2736strbuf_addf(err,"unable to append to '%s':%s",2737 logfile->buf,strerror(errno));2738return-1;2739}2740}27412742adjust_shared_perm(logfile->buf);2743close(logfd);2744return0;2745}274627472748intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2749{2750int ret;2751struct strbuf sb = STRBUF_INIT;27522753 ret =log_ref_setup(refname, &sb, err, force_create);2754strbuf_release(&sb);2755return ret;2756}27572758static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2759const unsigned char*new_sha1,2760const char*committer,const char*msg)2761{2762int msglen, written;2763unsigned maxlen, len;2764char*logrec;27652766 msglen = msg ?strlen(msg) :0;2767 maxlen =strlen(committer) + msglen +100;2768 logrec =xmalloc(maxlen);2769 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2770sha1_to_hex(old_sha1),2771sha1_to_hex(new_sha1),2772 committer);2773if(msglen)2774 len +=copy_reflog_msg(logrec + len -1, msg) -1;27752776 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2777free(logrec);2778if(written != len)2779return-1;27802781return0;2782}27832784static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2785const unsigned char*new_sha1,const char*msg,2786struct strbuf *logfile,int flags,2787struct strbuf *err)2788{2789int logfd, result, oflags = O_APPEND | O_WRONLY;27902791if(log_all_ref_updates <0)2792 log_all_ref_updates = !is_bare_repository();27932794 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);27952796if(result)2797return result;27982799 logfd =open(logfile->buf, oflags);2800if(logfd <0)2801return0;2802 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2803git_committer_info(0), msg);2804if(result) {2805strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,2806strerror(errno));2807close(logfd);2808return-1;2809}2810if(close(logfd)) {2811strbuf_addf(err,"unable to append to '%s':%s", logfile->buf,2812strerror(errno));2813return-1;2814}2815return0;2816}28172818static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2819const unsigned char*new_sha1,const char*msg,2820int flags,struct strbuf *err)2821{2822returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2823 err);2824}28252826intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2827const unsigned char*new_sha1,const char*msg,2828int flags,struct strbuf *err)2829{2830struct strbuf sb = STRBUF_INIT;2831int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2832 err);2833strbuf_release(&sb);2834return ret;2835}28362837/*2838 * Write sha1 into the open lockfile, then close the lockfile. On2839 * errors, rollback the lockfile, fill in *err and2840 * return -1.2841 */2842static intwrite_ref_to_lockfile(struct ref_lock *lock,2843const unsigned char*sha1,struct strbuf *err)2844{2845static char term ='\n';2846struct object *o;2847int fd;28482849 o =parse_object(sha1);2850if(!o) {2851strbuf_addf(err,2852"trying to write ref '%s' with nonexistent object%s",2853 lock->ref_name,sha1_to_hex(sha1));2854unlock_ref(lock);2855return-1;2856}2857if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2858strbuf_addf(err,2859"trying to write non-commit object%sto branch '%s'",2860sha1_to_hex(sha1), lock->ref_name);2861unlock_ref(lock);2862return-1;2863}2864 fd =get_lock_file_fd(lock->lk);2865if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2866write_in_full(fd, &term,1) !=1||2867close_ref(lock) <0) {2868strbuf_addf(err,2869"couldn't write '%s'",get_lock_file_path(lock->lk));2870unlock_ref(lock);2871return-1;2872}2873return0;2874}28752876/*2877 * Commit a change to a loose reference that has already been written2878 * to the loose reference lockfile. Also update the reflogs if2879 * necessary, using the specified lockmsg (which can be NULL).2880 */2881static intcommit_ref_update(struct ref_lock *lock,2882const unsigned char*sha1,const char*logmsg,2883int flags,struct strbuf *err)2884{2885clear_loose_ref_cache(&ref_cache);2886if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2887(strcmp(lock->ref_name, lock->orig_ref_name) &&2888log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2889char*old_msg =strbuf_detach(err, NULL);2890strbuf_addf(err,"cannot update the ref '%s':%s",2891 lock->ref_name, old_msg);2892free(old_msg);2893unlock_ref(lock);2894return-1;2895}2896if(strcmp(lock->orig_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;2912 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2913 head_sha1, &head_flag);2914if(head_ref && (head_flag & REF_ISSYMREF) &&2915!strcmp(head_ref, lock->ref_name)) {2916struct strbuf log_err = STRBUF_INIT;2917if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2918 logmsg,0, &log_err)) {2919error("%s", log_err.buf);2920strbuf_release(&log_err);2921}2922}2923}2924if(!(flags & REF_LOG_ONLY) &&commit_ref(lock)) {2925strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2926unlock_ref(lock);2927return-1;2928}29292930unlock_ref(lock);2931return0;2932}29332934static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2935{2936int ret = -1;2937#ifndef NO_SYMLINK_HEAD2938char*ref_path =get_locked_file_path(lock->lk);2939unlink(ref_path);2940 ret =symlink(target, ref_path);2941free(ref_path);29422943if(ret)2944fprintf(stderr,"no symlink - falling back to symbolic ref\n");2945#endif2946return ret;2947}29482949static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2950const char*target,const char*logmsg)2951{2952struct strbuf err = STRBUF_INIT;2953unsigned char new_sha1[20];2954if(logmsg && !read_ref(target, new_sha1) &&2955log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2956error("%s", err.buf);2957strbuf_release(&err);2958}2959}29602961static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2962const char*target,const char*logmsg)2963{2964if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2965update_symref_reflog(lock, refname, target, logmsg);2966return0;2967}29682969if(!fdopen_lock_file(lock->lk,"w"))2970returnerror("unable to fdopen%s:%s",2971 lock->lk->tempfile.filename.buf,strerror(errno));29722973update_symref_reflog(lock, refname, target, logmsg);29742975/* no error check; commit_ref will check ferror */2976fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2977if(commit_ref(lock) <0)2978returnerror("unable to write symref for%s:%s", refname,2979strerror(errno));2980return0;2981}29822983intcreate_symref(const char*refname,const char*target,const char*logmsg)2984{2985struct strbuf err = STRBUF_INIT;2986struct ref_lock *lock;2987int ret;29882989 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2990&err);2991if(!lock) {2992error("%s", err.buf);2993strbuf_release(&err);2994return-1;2995}29962997 ret =create_symref_locked(lock, refname, target, logmsg);2998unlock_ref(lock);2999return ret;3000}30013002intset_worktree_head_symref(const char*gitdir,const char*target)3003{3004static struct lock_file head_lock;3005struct ref_lock *lock;3006struct strbuf head_path = STRBUF_INIT;3007const char*head_rel;3008int ret;30093010strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));3011if(hold_lock_file_for_update(&head_lock, head_path.buf,3012 LOCK_NO_DEREF) <0) {3013struct strbuf err = STRBUF_INIT;3014unable_to_lock_message(head_path.buf, errno, &err);3015error("%s", err.buf);3016strbuf_release(&err);3017strbuf_release(&head_path);3018return-1;3019}30203021/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for3022 linked trees */3023 head_rel =remove_leading_path(head_path.buf,3024absolute_path(get_git_common_dir()));3025/* to make use of create_symref_locked(), initialize ref_lock */3026 lock =xcalloc(1,sizeof(struct ref_lock));3027 lock->lk = &head_lock;3028 lock->ref_name =xstrdup(head_rel);3029 lock->orig_ref_name =xstrdup(head_rel);30303031 ret =create_symref_locked(lock, head_rel, target, NULL);30323033unlock_ref(lock);/* will free lock */3034strbuf_release(&head_path);3035return ret;3036}30373038intreflog_exists(const char*refname)3039{3040struct stat st;30413042return!lstat(git_path("logs/%s", refname), &st) &&3043S_ISREG(st.st_mode);3044}30453046intdelete_reflog(const char*refname)3047{3048returnremove_path(git_path("logs/%s", refname));3049}30503051static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3052{3053unsigned char osha1[20], nsha1[20];3054char*email_end, *message;3055unsigned long timestamp;3056int tz;30573058/* old SP new SP name <email> SP time TAB msg LF */3059if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3060get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3061get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3062!(email_end =strchr(sb->buf +82,'>')) ||3063 email_end[1] !=' '||3064!(timestamp =strtoul(email_end +2, &message,10)) ||3065!message || message[0] !=' '||3066(message[1] !='+'&& message[1] !='-') ||3067!isdigit(message[2]) || !isdigit(message[3]) ||3068!isdigit(message[4]) || !isdigit(message[5]))3069return0;/* corrupt? */3070 email_end[1] ='\0';3071 tz =strtol(message +1, NULL,10);3072if(message[6] !='\t')3073 message +=6;3074else3075 message +=7;3076returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3077}30783079static char*find_beginning_of_line(char*bob,char*scan)3080{3081while(bob < scan && *(--scan) !='\n')3082;/* keep scanning backwards */3083/*3084 * Return either beginning of the buffer, or LF at the end of3085 * the previous line.3086 */3087return scan;3088}30893090intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3091{3092struct strbuf sb = STRBUF_INIT;3093FILE*logfp;3094long pos;3095int ret =0, at_tail =1;30963097 logfp =fopen(git_path("logs/%s", refname),"r");3098if(!logfp)3099return-1;31003101/* Jump to the end */3102if(fseek(logfp,0, SEEK_END) <0)3103returnerror("cannot seek back reflog for%s:%s",3104 refname,strerror(errno));3105 pos =ftell(logfp);3106while(!ret &&0< pos) {3107int cnt;3108size_t nread;3109char buf[BUFSIZ];3110char*endp, *scanp;31113112/* Fill next block from the end */3113 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3114if(fseek(logfp, pos - cnt, SEEK_SET))3115returnerror("cannot seek back reflog for%s:%s",3116 refname,strerror(errno));3117 nread =fread(buf, cnt,1, logfp);3118if(nread !=1)3119returnerror("cannot read%dbytes from reflog for%s:%s",3120 cnt, refname,strerror(errno));3121 pos -= cnt;31223123 scanp = endp = buf + cnt;3124if(at_tail && scanp[-1] =='\n')3125/* Looking at the final LF at the end of the file */3126 scanp--;3127 at_tail =0;31283129while(buf < scanp) {3130/*3131 * terminating LF of the previous line, or the beginning3132 * of the buffer.3133 */3134char*bp;31353136 bp =find_beginning_of_line(buf, scanp);31373138if(*bp =='\n') {3139/*3140 * The newline is the end of the previous line,3141 * so we know we have complete line starting3142 * at (bp + 1). Prefix it onto any prior data3143 * we collected for the line and process it.3144 */3145strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3146 scanp = bp;3147 endp = bp +1;3148 ret =show_one_reflog_ent(&sb, fn, cb_data);3149strbuf_reset(&sb);3150if(ret)3151break;3152}else if(!pos) {3153/*3154 * We are at the start of the buffer, and the3155 * start of the file; there is no previous3156 * line, and we have everything for this one.3157 * Process it, and we can end the loop.3158 */3159strbuf_splice(&sb,0,0, buf, endp - buf);3160 ret =show_one_reflog_ent(&sb, fn, cb_data);3161strbuf_reset(&sb);3162break;3163}31643165if(bp == buf) {3166/*3167 * We are at the start of the buffer, and there3168 * is more file to read backwards. Which means3169 * we are in the middle of a line. Note that we3170 * may get here even if *bp was a newline; that3171 * just means we are at the exact end of the3172 * previous line, rather than some spot in the3173 * middle.3174 *3175 * Save away what we have to be combined with3176 * the data from the next read.3177 */3178strbuf_splice(&sb,0,0, buf, endp - buf);3179break;3180}3181}31823183}3184if(!ret && sb.len)3185die("BUG: reverse reflog parser had leftover data");31863187fclose(logfp);3188strbuf_release(&sb);3189return ret;3190}31913192intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3193{3194FILE*logfp;3195struct strbuf sb = STRBUF_INIT;3196int ret =0;31973198 logfp =fopen(git_path("logs/%s", refname),"r");3199if(!logfp)3200return-1;32013202while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3203 ret =show_one_reflog_ent(&sb, fn, cb_data);3204fclose(logfp);3205strbuf_release(&sb);3206return ret;3207}3208/*3209 * Call fn for each reflog in the namespace indicated by name. name3210 * must be empty or end with '/'. Name will be used as a scratch3211 * space, but its contents will be restored before return.3212 */3213static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3214{3215DIR*d =opendir(git_path("logs/%s", name->buf));3216int retval =0;3217struct dirent *de;3218int oldlen = name->len;32193220if(!d)3221return name->len ? errno :0;32223223while((de =readdir(d)) != NULL) {3224struct stat st;32253226if(de->d_name[0] =='.')3227continue;3228if(ends_with(de->d_name,".lock"))3229continue;3230strbuf_addstr(name, de->d_name);3231if(stat(git_path("logs/%s", name->buf), &st) <0) {3232;/* silently ignore */3233}else{3234if(S_ISDIR(st.st_mode)) {3235strbuf_addch(name,'/');3236 retval =do_for_each_reflog(name, fn, cb_data);3237}else{3238struct object_id oid;32393240if(read_ref_full(name->buf,0, oid.hash, NULL))3241 retval =error("bad ref for%s", name->buf);3242else3243 retval =fn(name->buf, &oid,0, cb_data);3244}3245if(retval)3246break;3247}3248strbuf_setlen(name, oldlen);3249}3250closedir(d);3251return retval;3252}32533254intfor_each_reflog(each_ref_fn fn,void*cb_data)3255{3256int retval;3257struct strbuf name;3258strbuf_init(&name, PATH_MAX);3259 retval =do_for_each_reflog(&name, fn, cb_data);3260strbuf_release(&name);3261return retval;3262}32633264static intref_update_reject_duplicates(struct string_list *refnames,3265struct strbuf *err)3266{3267int i, n = refnames->nr;32683269assert(err);32703271for(i =1; i < n; i++)3272if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3273strbuf_addf(err,3274"multiple updates for ref '%s' not allowed.",3275 refnames->items[i].string);3276return1;3277}3278return0;3279}32803281/*3282 * If update is a direct update of head_ref (the reference pointed to3283 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.3284 */3285static intsplit_head_update(struct ref_update *update,3286struct ref_transaction *transaction,3287const char*head_ref,3288struct string_list *affected_refnames,3289struct strbuf *err)3290{3291struct string_list_item *item;3292struct ref_update *new_update;32933294if((update->flags & REF_LOG_ONLY) ||3295(update->flags & REF_ISPRUNING) ||3296(update->flags & REF_UPDATE_VIA_HEAD))3297return0;32983299if(strcmp(update->refname, head_ref))3300return0;33013302/*3303 * First make sure that HEAD is not already in the3304 * transaction. This insertion is O(N) in the transaction3305 * size, but it happens at most once per transaction.3306 */3307 item =string_list_insert(affected_refnames,"HEAD");3308if(item->util) {3309/* An entry already existed */3310strbuf_addf(err,3311"multiple updates for 'HEAD' (including one "3312"via its referent '%s') are not allowed",3313 update->refname);3314return TRANSACTION_NAME_CONFLICT;3315}33163317 new_update =ref_transaction_add_update(3318 transaction,"HEAD",3319 update->flags | REF_LOG_ONLY | REF_NODEREF,3320 update->new_sha1, update->old_sha1,3321 update->msg);33223323 item->util = new_update;33243325return0;3326}33273328/*3329 * update is for a symref that points at referent and doesn't have3330 * REF_NODEREF set. Split it into two updates:3331 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set3332 * - A new, separate update for the referent reference3333 * Note that the new update will itself be subject to splitting when3334 * the iteration gets to it.3335 */3336static intsplit_symref_update(struct ref_update *update,3337const char*referent,3338struct ref_transaction *transaction,3339struct string_list *affected_refnames,3340struct strbuf *err)3341{3342struct string_list_item *item;3343struct ref_update *new_update;3344unsigned int new_flags;33453346/*3347 * First make sure that referent is not already in the3348 * transaction. This insertion is O(N) in the transaction3349 * size, but it happens at most once per symref in a3350 * transaction.3351 */3352 item =string_list_insert(affected_refnames, referent);3353if(item->util) {3354/* An entry already existed */3355strbuf_addf(err,3356"multiple updates for '%s' (including one "3357"via symref '%s') are not allowed",3358 referent, update->refname);3359return TRANSACTION_NAME_CONFLICT;3360}33613362 new_flags = update->flags;3363if(!strcmp(update->refname,"HEAD")) {3364/*3365 * Record that the new update came via HEAD, so that3366 * when we process it, split_head_update() doesn't try3367 * to add another reflog update for HEAD. Note that3368 * this bit will be propagated if the new_update3369 * itself needs to be split.3370 */3371 new_flags |= REF_UPDATE_VIA_HEAD;3372}33733374 new_update =ref_transaction_add_update(3375 transaction, referent, new_flags,3376 update->new_sha1, update->old_sha1,3377 update->msg);33783379/* Change the symbolic ref update to log only: */3380 update->flags |= REF_LOG_ONLY | REF_NODEREF;33813382 item->util = new_update;33833384return0;3385}33863387/*3388 * Prepare for carrying out update:3389 * - Lock the reference referred to by update.3390 * - Read the reference under lock.3391 * - Check that its old SHA-1 value (if specified) is correct, and in3392 * any case record it in update->lock->old_oid for later use when3393 * writing the reflog.3394 * - If it is a symref update without REF_NODEREF, split it up into a3395 * REF_LOG_ONLY update of the symref and add a separate update for3396 * the referent to transaction.3397 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY3398 * update of HEAD.3399 */3400static intlock_ref_for_update(struct ref_update *update,3401struct ref_transaction *transaction,3402const char*head_ref,3403struct string_list *affected_refnames,3404struct strbuf *err)3405{3406struct strbuf referent = STRBUF_INIT;3407int mustexist = (update->flags & REF_HAVE_OLD) &&3408!is_null_sha1(update->old_sha1);3409int ret;3410struct ref_lock *lock;34113412if((update->flags & REF_HAVE_NEW) &&is_null_sha1(update->new_sha1))3413 update->flags |= REF_DELETING;34143415if(head_ref) {3416 ret =split_head_update(update, transaction, head_ref,3417 affected_refnames, err);3418if(ret)3419return ret;3420}34213422 ret =lock_raw_ref(update->refname, mustexist,3423 affected_refnames, NULL,3424&update->lock, &referent,3425&update->type, err);34263427if(ret) {3428char*reason;34293430 reason =strbuf_detach(err, NULL);3431strbuf_addf(err,"cannot lock ref '%s':%s",3432 update->refname, reason);3433free(reason);3434return ret;3435}34363437 lock = update->lock;34383439if(update->type & REF_ISSYMREF) {3440if(read_ref_full(update->refname,3441 mustexist ? RESOLVE_REF_READING :0,3442 lock->old_oid.hash, NULL)) {3443if(update->flags & REF_HAVE_OLD) {3444strbuf_addf(err,"cannot lock ref '%s': can't resolve old value",3445 update->refname);3446return TRANSACTION_GENERIC_ERROR;3447}else{3448hashclr(lock->old_oid.hash);3449}3450}3451if((update->flags & REF_HAVE_OLD) &&3452hashcmp(lock->old_oid.hash, update->old_sha1)) {3453strbuf_addf(err,"cannot lock ref '%s': is at%sbut expected%s",3454 update->refname,3455sha1_to_hex(lock->old_oid.hash),3456sha1_to_hex(update->old_sha1));3457return TRANSACTION_GENERIC_ERROR;3458}34593460if(!(update->flags & REF_NODEREF)) {3461 ret =split_symref_update(update, referent.buf, transaction,3462 affected_refnames, err);3463if(ret)3464return ret;3465}3466}else if((update->flags & REF_HAVE_OLD) &&3467hashcmp(lock->old_oid.hash, update->old_sha1)) {3468if(is_null_sha1(update->old_sha1))3469strbuf_addf(err,"cannot lock ref '%s': reference already exists",3470 update->refname);3471else3472strbuf_addf(err,"cannot lock ref '%s': is at%sbut expected%s",3473 update->refname,3474sha1_to_hex(lock->old_oid.hash),3475sha1_to_hex(update->old_sha1));34763477return TRANSACTION_GENERIC_ERROR;3478}34793480if((update->flags & REF_HAVE_NEW) &&3481!(update->flags & REF_DELETING) &&3482!(update->flags & REF_LOG_ONLY)) {3483if(!(update->type & REF_ISSYMREF) &&3484!hashcmp(lock->old_oid.hash, update->new_sha1)) {3485/*3486 * The reference already has the desired3487 * value, so we don't need to write it.3488 */3489}else if(write_ref_to_lockfile(lock, update->new_sha1,3490 err)) {3491char*write_err =strbuf_detach(err, NULL);34923493/*3494 * The lock was freed upon failure of3495 * write_ref_to_lockfile():3496 */3497 update->lock = NULL;3498strbuf_addf(err,3499"cannot update the ref '%s':%s",3500 update->refname, write_err);3501free(write_err);3502return TRANSACTION_GENERIC_ERROR;3503}else{3504 update->flags |= REF_NEEDS_COMMIT;3505}3506}3507if(!(update->flags & REF_NEEDS_COMMIT)) {3508/*3509 * We didn't call write_ref_to_lockfile(), so3510 * the lockfile is still open. Close it to3511 * free up the file descriptor:3512 */3513if(close_ref(lock)) {3514strbuf_addf(err,"couldn't close '%s.lock'",3515 update->refname);3516return TRANSACTION_GENERIC_ERROR;3517}3518}3519return0;3520}35213522intref_transaction_commit(struct ref_transaction *transaction,3523struct strbuf *err)3524{3525int ret =0, i;3526struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3527struct string_list_item *ref_to_delete;3528struct string_list affected_refnames = STRING_LIST_INIT_NODUP;3529char*head_ref = NULL;3530int head_type;3531struct object_id head_oid;35323533assert(err);35343535if(transaction->state != REF_TRANSACTION_OPEN)3536die("BUG: commit called for transaction that is not open");35373538if(!transaction->nr) {3539 transaction->state = REF_TRANSACTION_CLOSED;3540return0;3541}35423543/*3544 * Fail if a refname appears more than once in the3545 * transaction. (If we end up splitting up any updates using3546 * split_symref_update() or split_head_update(), those3547 * functions will check that the new updates don't have the3548 * same refname as any existing ones.)3549 */3550for(i =0; i < transaction->nr; i++) {3551struct ref_update *update = transaction->updates[i];3552struct string_list_item *item =3553string_list_append(&affected_refnames, update->refname);35543555/*3556 * We store a pointer to update in item->util, but at3557 * the moment we never use the value of this field3558 * except to check whether it is non-NULL.3559 */3560 item->util = update;3561}3562string_list_sort(&affected_refnames);3563if(ref_update_reject_duplicates(&affected_refnames, err)) {3564 ret = TRANSACTION_GENERIC_ERROR;3565goto cleanup;3566}35673568/*3569 * Special hack: If a branch is updated directly and HEAD3570 * points to it (may happen on the remote side of a push3571 * for example) then logically the HEAD reflog should be3572 * updated too.3573 *3574 * A generic solution would require reverse symref lookups,3575 * but finding all symrefs pointing to a given branch would be3576 * rather costly for this rare event (the direct update of a3577 * branch) to be worth it. So let's cheat and check with HEAD3578 * only, which should cover 99% of all usage scenarios (even3579 * 100% of the default ones).3580 *3581 * So if HEAD is a symbolic reference, then record the name of3582 * the reference that it points to. If we see an update of3583 * head_ref within the transaction, then split_head_update()3584 * arranges for the reflog of HEAD to be updated, too.3585 */3586 head_ref =resolve_refdup("HEAD", RESOLVE_REF_NO_RECURSE,3587 head_oid.hash, &head_type);35883589if(head_ref && !(head_type & REF_ISSYMREF)) {3590free(head_ref);3591 head_ref = NULL;3592}35933594/*3595 * Acquire all locks, verify old values if provided, check3596 * that new values are valid, and write new values to the3597 * lockfiles, ready to be activated. Only keep one lockfile3598 * open at a time to avoid running out of file descriptors.3599 */3600for(i =0; i < transaction->nr; i++) {3601struct ref_update *update = transaction->updates[i];36023603 ret =lock_ref_for_update(update, transaction, head_ref,3604&affected_refnames, err);3605if(ret)3606goto cleanup;3607}36083609/* Perform updates first so live commits remain referenced */3610for(i =0; i < transaction->nr; i++) {3611struct ref_update *update = transaction->updates[i];3612struct ref_lock *lock = update->lock;36133614if(update->flags & REF_NEEDS_COMMIT ||3615 update->flags & REF_LOG_ONLY) {3616if(log_ref_write(lock->ref_name, lock->old_oid.hash,3617 update->new_sha1,3618 update->msg, update->flags, err)) {3619char*old_msg =strbuf_detach(err, NULL);36203621strbuf_addf(err,"cannot update the ref '%s':%s",3622 lock->ref_name, old_msg);3623free(old_msg);3624unlock_ref(lock);3625 update->lock = NULL;3626 ret = TRANSACTION_GENERIC_ERROR;3627goto cleanup;3628}3629}3630if(update->flags & REF_NEEDS_COMMIT) {3631clear_loose_ref_cache(&ref_cache);3632if(commit_ref(lock)) {3633strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3634unlock_ref(lock);3635 update->lock = NULL;3636 ret = TRANSACTION_GENERIC_ERROR;3637goto cleanup;3638}3639}3640}3641/* Perform deletes now that updates are safely completed */3642for(i =0; i < transaction->nr; i++) {3643struct ref_update *update = transaction->updates[i];36443645if(update->flags & REF_DELETING &&3646!(update->flags & REF_LOG_ONLY)) {3647if(delete_ref_loose(update->lock, update->type, err)) {3648 ret = TRANSACTION_GENERIC_ERROR;3649goto cleanup;3650}36513652if(!(update->flags & REF_ISPRUNING))3653string_list_append(&refs_to_delete,3654 update->lock->ref_name);3655}3656}36573658if(repack_without_refs(&refs_to_delete, err)) {3659 ret = TRANSACTION_GENERIC_ERROR;3660goto cleanup;3661}3662for_each_string_list_item(ref_to_delete, &refs_to_delete)3663unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3664clear_loose_ref_cache(&ref_cache);36653666cleanup:3667 transaction->state = REF_TRANSACTION_CLOSED;36683669for(i =0; i < transaction->nr; i++)3670if(transaction->updates[i]->lock)3671unlock_ref(transaction->updates[i]->lock);3672string_list_clear(&refs_to_delete,0);3673free(head_ref);3674string_list_clear(&affected_refnames,0);36753676return ret;3677}36783679static intref_present(const char*refname,3680const struct object_id *oid,int flags,void*cb_data)3681{3682struct string_list *affected_refnames = cb_data;36833684returnstring_list_has_string(affected_refnames, refname);3685}36863687intinitial_ref_transaction_commit(struct ref_transaction *transaction,3688struct strbuf *err)3689{3690int ret =0, i;3691struct string_list affected_refnames = STRING_LIST_INIT_NODUP;36923693assert(err);36943695if(transaction->state != REF_TRANSACTION_OPEN)3696die("BUG: commit called for transaction that is not open");36973698/* Fail if a refname appears more than once in the transaction: */3699for(i =0; i < transaction->nr; i++)3700string_list_append(&affected_refnames,3701 transaction->updates[i]->refname);3702string_list_sort(&affected_refnames);3703if(ref_update_reject_duplicates(&affected_refnames, err)) {3704 ret = TRANSACTION_GENERIC_ERROR;3705goto cleanup;3706}37073708/*3709 * It's really undefined to call this function in an active3710 * repository or when there are existing references: we are3711 * only locking and changing packed-refs, so (1) any3712 * simultaneous processes might try to change a reference at3713 * the same time we do, and (2) any existing loose versions of3714 * the references that we are setting would have precedence3715 * over our values. But some remote helpers create the remote3716 * "HEAD" and "master" branches before calling this function,3717 * so here we really only check that none of the references3718 * that we are creating already exists.3719 */3720if(for_each_rawref(ref_present, &affected_refnames))3721die("BUG: initial ref transaction called with existing refs");37223723for(i =0; i < transaction->nr; i++) {3724struct ref_update *update = transaction->updates[i];37253726if((update->flags & REF_HAVE_OLD) &&3727!is_null_sha1(update->old_sha1))3728die("BUG: initial ref transaction with old_sha1 set");3729if(verify_refname_available(update->refname,3730&affected_refnames, NULL,3731 err)) {3732 ret = TRANSACTION_NAME_CONFLICT;3733goto cleanup;3734}3735}37363737if(lock_packed_refs(0)) {3738strbuf_addf(err,"unable to lock packed-refs file:%s",3739strerror(errno));3740 ret = TRANSACTION_GENERIC_ERROR;3741goto cleanup;3742}37433744for(i =0; i < transaction->nr; i++) {3745struct ref_update *update = transaction->updates[i];37463747if((update->flags & REF_HAVE_NEW) &&3748!is_null_sha1(update->new_sha1))3749add_packed_ref(update->refname, update->new_sha1);3750}37513752if(commit_packed_refs()) {3753strbuf_addf(err,"unable to commit packed-refs file:%s",3754strerror(errno));3755 ret = TRANSACTION_GENERIC_ERROR;3756goto cleanup;3757}37583759cleanup:3760 transaction->state = REF_TRANSACTION_CLOSED;3761string_list_clear(&affected_refnames,0);3762return ret;3763}37643765struct expire_reflog_cb {3766unsigned int flags;3767 reflog_expiry_should_prune_fn *should_prune_fn;3768void*policy_cb;3769FILE*newlog;3770unsigned char last_kept_sha1[20];3771};37723773static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3774const char*email,unsigned long timestamp,int tz,3775const char*message,void*cb_data)3776{3777struct expire_reflog_cb *cb = cb_data;3778struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;37793780if(cb->flags & EXPIRE_REFLOGS_REWRITE)3781 osha1 = cb->last_kept_sha1;37823783if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3784 message, policy_cb)) {3785if(!cb->newlog)3786printf("would prune%s", message);3787else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3788printf("prune%s", message);3789}else{3790if(cb->newlog) {3791fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3792sha1_to_hex(osha1),sha1_to_hex(nsha1),3793 email, timestamp, tz, message);3794hashcpy(cb->last_kept_sha1, nsha1);3795}3796if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3797printf("keep%s", message);3798}3799return0;3800}38013802intreflog_expire(const char*refname,const unsigned char*sha1,3803unsigned int flags,3804 reflog_expiry_prepare_fn prepare_fn,3805 reflog_expiry_should_prune_fn should_prune_fn,3806 reflog_expiry_cleanup_fn cleanup_fn,3807void*policy_cb_data)3808{3809static struct lock_file reflog_lock;3810struct expire_reflog_cb cb;3811struct ref_lock *lock;3812char*log_file;3813int status =0;3814int type;3815struct strbuf err = STRBUF_INIT;38163817memset(&cb,0,sizeof(cb));3818 cb.flags = flags;3819 cb.policy_cb = policy_cb_data;3820 cb.should_prune_fn = should_prune_fn;38213822/*3823 * The reflog file is locked by holding the lock on the3824 * reference itself, plus we might need to update the3825 * reference if --updateref was specified:3826 */3827 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL, REF_NODEREF,3828&type, &err);3829if(!lock) {3830error("cannot lock ref '%s':%s", refname, err.buf);3831strbuf_release(&err);3832return-1;3833}3834if(!reflog_exists(refname)) {3835unlock_ref(lock);3836return0;3837}38383839 log_file =git_pathdup("logs/%s", refname);3840if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3841/*3842 * Even though holding $GIT_DIR/logs/$reflog.lock has3843 * no locking implications, we use the lock_file3844 * machinery here anyway because it does a lot of the3845 * work we need, including cleaning up if the program3846 * exits unexpectedly.3847 */3848if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3849struct strbuf err = STRBUF_INIT;3850unable_to_lock_message(log_file, errno, &err);3851error("%s", err.buf);3852strbuf_release(&err);3853goto failure;3854}3855 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3856if(!cb.newlog) {3857error("cannot fdopen%s(%s)",3858get_lock_file_path(&reflog_lock),strerror(errno));3859goto failure;3860}3861}38623863(*prepare_fn)(refname, sha1, cb.policy_cb);3864for_each_reflog_ent(refname, expire_reflog_ent, &cb);3865(*cleanup_fn)(cb.policy_cb);38663867if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3868/*3869 * It doesn't make sense to adjust a reference pointed3870 * to by a symbolic ref based on expiring entries in3871 * the symbolic reference's reflog. Nor can we update3872 * a reference if there are no remaining reflog3873 * entries.3874 */3875int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3876!(type & REF_ISSYMREF) &&3877!is_null_sha1(cb.last_kept_sha1);38783879if(close_lock_file(&reflog_lock)) {3880 status |=error("couldn't write%s:%s", log_file,3881strerror(errno));3882}else if(update &&3883(write_in_full(get_lock_file_fd(lock->lk),3884sha1_to_hex(cb.last_kept_sha1),40) !=40||3885write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3886close_ref(lock) <0)) {3887 status |=error("couldn't write%s",3888get_lock_file_path(lock->lk));3889rollback_lock_file(&reflog_lock);3890}else if(commit_lock_file(&reflog_lock)) {3891 status |=error("unable to write reflog '%s' (%s)",3892 log_file,strerror(errno));3893}else if(update &&commit_ref(lock)) {3894 status |=error("couldn't set%s", lock->ref_name);3895}3896}3897free(log_file);3898unlock_ref(lock);3899return status;39003901 failure:3902rollback_lock_file(&reflog_lock);3903free(log_file);3904unlock_ref(lock);3905return-1;3906}