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{ 202int len; 203struct ref_entry *ref; 204 205if(check_name && 206check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 207die("Reference has invalid format: '%s'", refname); 208 len =strlen(refname) +1; 209 ref =xmalloc(sizeof(struct ref_entry) + len); 210hashcpy(ref->u.value.oid.hash, sha1); 211oidclr(&ref->u.value.peeled); 212memcpy(ref->name, refname, len); 213 ref->flag = flag; 214return ref; 215} 216 217static voidclear_ref_dir(struct ref_dir *dir); 218 219static voidfree_ref_entry(struct ref_entry *entry) 220{ 221if(entry->flag & REF_DIR) { 222/* 223 * Do not use get_ref_dir() here, as that might 224 * trigger the reading of loose refs. 225 */ 226clear_ref_dir(&entry->u.subdir); 227} 228free(entry); 229} 230 231/* 232 * Add a ref_entry to the end of dir (unsorted). Entry is always 233 * stored directly in dir; no recursion into subdirectories is 234 * done. 235 */ 236static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 237{ 238ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 239 dir->entries[dir->nr++] = entry; 240/* optimize for the case that entries are added in order */ 241if(dir->nr ==1|| 242(dir->nr == dir->sorted +1&& 243strcmp(dir->entries[dir->nr -2]->name, 244 dir->entries[dir->nr -1]->name) <0)) 245 dir->sorted = dir->nr; 246} 247 248/* 249 * Clear and free all entries in dir, recursively. 250 */ 251static voidclear_ref_dir(struct ref_dir *dir) 252{ 253int i; 254for(i =0; i < dir->nr; i++) 255free_ref_entry(dir->entries[i]); 256free(dir->entries); 257 dir->sorted = dir->nr = dir->alloc =0; 258 dir->entries = NULL; 259} 260 261/* 262 * Create a struct ref_entry object for the specified dirname. 263 * dirname is the name of the directory with a trailing slash (e.g., 264 * "refs/heads/") or "" for the top-level directory. 265 */ 266static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 267const char*dirname,size_t len, 268int incomplete) 269{ 270struct ref_entry *direntry; 271 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 272memcpy(direntry->name, dirname, len); 273 direntry->name[len] ='\0'; 274 direntry->u.subdir.ref_cache = ref_cache; 275 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 276return direntry; 277} 278 279static intref_entry_cmp(const void*a,const void*b) 280{ 281struct ref_entry *one = *(struct ref_entry **)a; 282struct ref_entry *two = *(struct ref_entry **)b; 283returnstrcmp(one->name, two->name); 284} 285 286static voidsort_ref_dir(struct ref_dir *dir); 287 288struct string_slice { 289size_t len; 290const char*str; 291}; 292 293static intref_entry_cmp_sslice(const void*key_,const void*ent_) 294{ 295const struct string_slice *key = key_; 296const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 297int cmp =strncmp(key->str, ent->name, key->len); 298if(cmp) 299return cmp; 300return'\0'- (unsigned char)ent->name[key->len]; 301} 302 303/* 304 * Return the index of the entry with the given refname from the 305 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 306 * no such entry is found. dir must already be complete. 307 */ 308static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 309{ 310struct ref_entry **r; 311struct string_slice key; 312 313if(refname == NULL || !dir->nr) 314return-1; 315 316sort_ref_dir(dir); 317 key.len = len; 318 key.str = refname; 319 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 320 ref_entry_cmp_sslice); 321 322if(r == NULL) 323return-1; 324 325return r - dir->entries; 326} 327 328/* 329 * Search for a directory entry directly within dir (without 330 * recursing). Sort dir if necessary. subdirname must be a directory 331 * name (i.e., end in '/'). If mkdir is set, then create the 332 * directory if it is missing; otherwise, return NULL if the desired 333 * directory cannot be found. dir must already be complete. 334 */ 335static struct ref_dir *search_for_subdir(struct ref_dir *dir, 336const char*subdirname,size_t len, 337int mkdir) 338{ 339int entry_index =search_ref_dir(dir, subdirname, len); 340struct ref_entry *entry; 341if(entry_index == -1) { 342if(!mkdir) 343return NULL; 344/* 345 * Since dir is complete, the absence of a subdir 346 * means that the subdir really doesn't exist; 347 * therefore, create an empty record for it but mark 348 * the record complete. 349 */ 350 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 351add_entry_to_dir(dir, entry); 352}else{ 353 entry = dir->entries[entry_index]; 354} 355returnget_ref_dir(entry); 356} 357 358/* 359 * If refname is a reference name, find the ref_dir within the dir 360 * tree that should hold refname. If refname is a directory name 361 * (i.e., ends in '/'), then return that ref_dir itself. dir must 362 * represent the top-level directory and must already be complete. 363 * Sort ref_dirs and recurse into subdirectories as necessary. If 364 * mkdir is set, then create any missing directories; otherwise, 365 * return NULL if the desired directory cannot be found. 366 */ 367static struct ref_dir *find_containing_dir(struct ref_dir *dir, 368const char*refname,int mkdir) 369{ 370const char*slash; 371for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 372size_t dirnamelen = slash - refname +1; 373struct ref_dir *subdir; 374 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 375if(!subdir) { 376 dir = NULL; 377break; 378} 379 dir = subdir; 380} 381 382return dir; 383} 384 385/* 386 * Find the value entry with the given name in dir, sorting ref_dirs 387 * and recursing into subdirectories as necessary. If the name is not 388 * found or it corresponds to a directory entry, return NULL. 389 */ 390static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 391{ 392int entry_index; 393struct ref_entry *entry; 394 dir =find_containing_dir(dir, refname,0); 395if(!dir) 396return NULL; 397 entry_index =search_ref_dir(dir, refname,strlen(refname)); 398if(entry_index == -1) 399return NULL; 400 entry = dir->entries[entry_index]; 401return(entry->flag & REF_DIR) ? NULL : entry; 402} 403 404/* 405 * Remove the entry with the given name from dir, recursing into 406 * subdirectories as necessary. If refname is the name of a directory 407 * (i.e., ends with '/'), then remove the directory and its contents. 408 * If the removal was successful, return the number of entries 409 * remaining in the directory entry that contained the deleted entry. 410 * If the name was not found, return -1. Please note that this 411 * function only deletes the entry from the cache; it does not delete 412 * it from the filesystem or ensure that other cache entries (which 413 * might be symbolic references to the removed entry) are updated. 414 * Nor does it remove any containing dir entries that might be made 415 * empty by the removal. dir must represent the top-level directory 416 * and must already be complete. 417 */ 418static intremove_entry(struct ref_dir *dir,const char*refname) 419{ 420int refname_len =strlen(refname); 421int entry_index; 422struct ref_entry *entry; 423int is_dir = refname[refname_len -1] =='/'; 424if(is_dir) { 425/* 426 * refname represents a reference directory. Remove 427 * the trailing slash; otherwise we will get the 428 * directory *representing* refname rather than the 429 * one *containing* it. 430 */ 431char*dirname =xmemdupz(refname, refname_len -1); 432 dir =find_containing_dir(dir, dirname,0); 433free(dirname); 434}else{ 435 dir =find_containing_dir(dir, refname,0); 436} 437if(!dir) 438return-1; 439 entry_index =search_ref_dir(dir, refname, refname_len); 440if(entry_index == -1) 441return-1; 442 entry = dir->entries[entry_index]; 443 444memmove(&dir->entries[entry_index], 445&dir->entries[entry_index +1], 446(dir->nr - entry_index -1) *sizeof(*dir->entries) 447); 448 dir->nr--; 449if(dir->sorted > entry_index) 450 dir->sorted--; 451free_ref_entry(entry); 452return dir->nr; 453} 454 455/* 456 * Add a ref_entry to the ref_dir (unsorted), recursing into 457 * subdirectories as necessary. dir must represent the top-level 458 * directory. Return 0 on success. 459 */ 460static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 461{ 462 dir =find_containing_dir(dir, ref->name,1); 463if(!dir) 464return-1; 465add_entry_to_dir(dir, ref); 466return0; 467} 468 469/* 470 * Emit a warning and return true iff ref1 and ref2 have the same name 471 * and the same sha1. Die if they have the same name but different 472 * sha1s. 473 */ 474static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 475{ 476if(strcmp(ref1->name, ref2->name)) 477return0; 478 479/* Duplicate name; make sure that they don't conflict: */ 480 481if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 482/* This is impossible by construction */ 483die("Reference directory conflict:%s", ref1->name); 484 485if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 486die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 487 488warning("Duplicated ref:%s", ref1->name); 489return1; 490} 491 492/* 493 * Sort the entries in dir non-recursively (if they are not already 494 * sorted) and remove any duplicate entries. 495 */ 496static voidsort_ref_dir(struct ref_dir *dir) 497{ 498int i, j; 499struct ref_entry *last = NULL; 500 501/* 502 * This check also prevents passing a zero-length array to qsort(), 503 * which is a problem on some platforms. 504 */ 505if(dir->sorted == dir->nr) 506return; 507 508qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 509 510/* Remove any duplicates: */ 511for(i =0, j =0; j < dir->nr; j++) { 512struct ref_entry *entry = dir->entries[j]; 513if(last &&is_dup_ref(last, entry)) 514free_ref_entry(entry); 515else 516 last = dir->entries[i++] = entry; 517} 518 dir->sorted = dir->nr = i; 519} 520 521/* Include broken references in a do_for_each_ref*() iteration: */ 522#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 523 524/* 525 * Return true iff the reference described by entry can be resolved to 526 * an object in the database. Emit a warning if the referred-to 527 * object does not exist. 528 */ 529static intref_resolves_to_object(struct ref_entry *entry) 530{ 531if(entry->flag & REF_ISBROKEN) 532return0; 533if(!has_sha1_file(entry->u.value.oid.hash)) { 534error("%sdoes not point to a valid object!", entry->name); 535return0; 536} 537return1; 538} 539 540/* 541 * current_ref is a performance hack: when iterating over references 542 * using the for_each_ref*() functions, current_ref is set to the 543 * current reference's entry before calling the callback function. If 544 * the callback function calls peel_ref(), then peel_ref() first 545 * checks whether the reference to be peeled is the current reference 546 * (it usually is) and if so, returns that reference's peeled version 547 * if it is available. This avoids a refname lookup in a common case. 548 */ 549static struct ref_entry *current_ref; 550 551typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 552 553struct ref_entry_cb { 554const char*base; 555int trim; 556int flags; 557 each_ref_fn *fn; 558void*cb_data; 559}; 560 561/* 562 * Handle one reference in a do_for_each_ref*()-style iteration, 563 * calling an each_ref_fn for each entry. 564 */ 565static intdo_one_ref(struct ref_entry *entry,void*cb_data) 566{ 567struct ref_entry_cb *data = cb_data; 568struct ref_entry *old_current_ref; 569int retval; 570 571if(!starts_with(entry->name, data->base)) 572return0; 573 574if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 575!ref_resolves_to_object(entry)) 576return0; 577 578/* Store the old value, in case this is a recursive call: */ 579 old_current_ref = current_ref; 580 current_ref = entry; 581 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 582 entry->flag, data->cb_data); 583 current_ref = old_current_ref; 584return retval; 585} 586 587/* 588 * Call fn for each reference in dir that has index in the range 589 * offset <= index < dir->nr. Recurse into subdirectories that are in 590 * that index range, sorting them before iterating. This function 591 * does not sort dir itself; it should be sorted beforehand. fn is 592 * called for all references, including broken ones. 593 */ 594static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 595 each_ref_entry_fn fn,void*cb_data) 596{ 597int i; 598assert(dir->sorted == dir->nr); 599for(i = offset; i < dir->nr; i++) { 600struct ref_entry *entry = dir->entries[i]; 601int retval; 602if(entry->flag & REF_DIR) { 603struct ref_dir *subdir =get_ref_dir(entry); 604sort_ref_dir(subdir); 605 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 606}else{ 607 retval =fn(entry, cb_data); 608} 609if(retval) 610return retval; 611} 612return0; 613} 614 615/* 616 * Call fn for each reference in the union of dir1 and dir2, in order 617 * by refname. Recurse into subdirectories. If a value entry appears 618 * in both dir1 and dir2, then only process the version that is in 619 * dir2. The input dirs must already be sorted, but subdirs will be 620 * sorted as needed. fn is called for all references, including 621 * broken ones. 622 */ 623static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 624struct ref_dir *dir2, 625 each_ref_entry_fn fn,void*cb_data) 626{ 627int retval; 628int i1 =0, i2 =0; 629 630assert(dir1->sorted == dir1->nr); 631assert(dir2->sorted == dir2->nr); 632while(1) { 633struct ref_entry *e1, *e2; 634int cmp; 635if(i1 == dir1->nr) { 636returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 637} 638if(i2 == dir2->nr) { 639returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 640} 641 e1 = dir1->entries[i1]; 642 e2 = dir2->entries[i2]; 643 cmp =strcmp(e1->name, e2->name); 644if(cmp ==0) { 645if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 646/* Both are directories; descend them in parallel. */ 647struct ref_dir *subdir1 =get_ref_dir(e1); 648struct ref_dir *subdir2 =get_ref_dir(e2); 649sort_ref_dir(subdir1); 650sort_ref_dir(subdir2); 651 retval =do_for_each_entry_in_dirs( 652 subdir1, subdir2, fn, cb_data); 653 i1++; 654 i2++; 655}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 656/* Both are references; ignore the one from dir1. */ 657 retval =fn(e2, cb_data); 658 i1++; 659 i2++; 660}else{ 661die("conflict between reference and directory:%s", 662 e1->name); 663} 664}else{ 665struct ref_entry *e; 666if(cmp <0) { 667 e = e1; 668 i1++; 669}else{ 670 e = e2; 671 i2++; 672} 673if(e->flag & REF_DIR) { 674struct ref_dir *subdir =get_ref_dir(e); 675sort_ref_dir(subdir); 676 retval =do_for_each_entry_in_dir( 677 subdir,0, fn, cb_data); 678}else{ 679 retval =fn(e, cb_data); 680} 681} 682if(retval) 683return retval; 684} 685} 686 687/* 688 * Load all of the refs from the dir into our in-memory cache. The hard work 689 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 690 * through all of the sub-directories. We do not even need to care about 691 * sorting, as traversal order does not matter to us. 692 */ 693static voidprime_ref_dir(struct ref_dir *dir) 694{ 695int i; 696for(i =0; i < dir->nr; i++) { 697struct ref_entry *entry = dir->entries[i]; 698if(entry->flag & REF_DIR) 699prime_ref_dir(get_ref_dir(entry)); 700} 701} 702 703struct nonmatching_ref_data { 704const struct string_list *skip; 705const char*conflicting_refname; 706}; 707 708static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 709{ 710struct nonmatching_ref_data *data = vdata; 711 712if(data->skip &&string_list_has_string(data->skip, entry->name)) 713return0; 714 715 data->conflicting_refname = entry->name; 716return1; 717} 718 719/* 720 * Return 0 if a reference named refname could be created without 721 * conflicting with the name of an existing reference in dir. 722 * See verify_refname_available for more information. 723 */ 724static intverify_refname_available_dir(const char*refname, 725const struct string_list *extras, 726const struct string_list *skip, 727struct ref_dir *dir, 728struct strbuf *err) 729{ 730const char*slash; 731const char*extra_refname; 732int pos; 733struct strbuf dirname = STRBUF_INIT; 734int ret = -1; 735 736/* 737 * For the sake of comments in this function, suppose that 738 * refname is "refs/foo/bar". 739 */ 740 741assert(err); 742 743strbuf_grow(&dirname,strlen(refname) +1); 744for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 745/* Expand dirname to the new prefix, not including the trailing slash: */ 746strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 747 748/* 749 * We are still at a leading dir of the refname (e.g., 750 * "refs/foo"; if there is a reference with that name, 751 * it is a conflict, *unless* it is in skip. 752 */ 753if(dir) { 754 pos =search_ref_dir(dir, dirname.buf, dirname.len); 755if(pos >=0&& 756(!skip || !string_list_has_string(skip, dirname.buf))) { 757/* 758 * We found a reference whose name is 759 * a proper prefix of refname; e.g., 760 * "refs/foo", and is not in skip. 761 */ 762strbuf_addf(err,"'%s' exists; cannot create '%s'", 763 dirname.buf, refname); 764goto cleanup; 765} 766} 767 768if(extras &&string_list_has_string(extras, dirname.buf) && 769(!skip || !string_list_has_string(skip, dirname.buf))) { 770strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 771 refname, dirname.buf); 772goto cleanup; 773} 774 775/* 776 * Otherwise, we can try to continue our search with 777 * the next component. So try to look up the 778 * directory, e.g., "refs/foo/". If we come up empty, 779 * we know there is nothing under this whole prefix, 780 * but even in that case we still have to continue the 781 * search for conflicts with extras. 782 */ 783strbuf_addch(&dirname,'/'); 784if(dir) { 785 pos =search_ref_dir(dir, dirname.buf, dirname.len); 786if(pos <0) { 787/* 788 * There was no directory "refs/foo/", 789 * so there is nothing under this 790 * whole prefix. So there is no need 791 * to continue looking for conflicting 792 * references. But we need to continue 793 * looking for conflicting extras. 794 */ 795 dir = NULL; 796}else{ 797 dir =get_ref_dir(dir->entries[pos]); 798} 799} 800} 801 802/* 803 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 804 * There is no point in searching for a reference with that 805 * name, because a refname isn't considered to conflict with 806 * itself. But we still need to check for references whose 807 * names are in the "refs/foo/bar/" namespace, because they 808 * *do* conflict. 809 */ 810strbuf_addstr(&dirname, refname + dirname.len); 811strbuf_addch(&dirname,'/'); 812 813if(dir) { 814 pos =search_ref_dir(dir, dirname.buf, dirname.len); 815 816if(pos >=0) { 817/* 818 * We found a directory named "$refname/" 819 * (e.g., "refs/foo/bar/"). It is a problem 820 * iff it contains any ref that is not in 821 * "skip". 822 */ 823struct nonmatching_ref_data data; 824 825 data.skip = skip; 826 data.conflicting_refname = NULL; 827 dir =get_ref_dir(dir->entries[pos]); 828sort_ref_dir(dir); 829if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 830strbuf_addf(err,"'%s' exists; cannot create '%s'", 831 data.conflicting_refname, refname); 832goto cleanup; 833} 834} 835} 836 837 extra_refname =find_descendant_ref(dirname.buf, extras, skip); 838if(extra_refname) 839strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 840 refname, extra_refname); 841else 842 ret =0; 843 844cleanup: 845strbuf_release(&dirname); 846return ret; 847} 848 849struct packed_ref_cache { 850struct ref_entry *root; 851 852/* 853 * Count of references to the data structure in this instance, 854 * including the pointer from ref_cache::packed if any. The 855 * data will not be freed as long as the reference count is 856 * nonzero. 857 */ 858unsigned int referrers; 859 860/* 861 * Iff the packed-refs file associated with this instance is 862 * currently locked for writing, this points at the associated 863 * lock (which is owned by somebody else). The referrer count 864 * is also incremented when the file is locked and decremented 865 * when it is unlocked. 866 */ 867struct lock_file *lock; 868 869/* The metadata from when this packed-refs cache was read */ 870struct stat_validity validity; 871}; 872 873/* 874 * Future: need to be in "struct repository" 875 * when doing a full libification. 876 */ 877static struct ref_cache { 878struct ref_cache *next; 879struct ref_entry *loose; 880struct packed_ref_cache *packed; 881/* 882 * The submodule name, or "" for the main repo. We allocate 883 * length 1 rather than FLEX_ARRAY so that the main ref_cache 884 * is initialized correctly. 885 */ 886char name[1]; 887} ref_cache, *submodule_ref_caches; 888 889/* Lock used for the main packed-refs file: */ 890static struct lock_file packlock; 891 892/* 893 * Increment the reference count of *packed_refs. 894 */ 895static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 896{ 897 packed_refs->referrers++; 898} 899 900/* 901 * Decrease the reference count of *packed_refs. If it goes to zero, 902 * free *packed_refs and return true; otherwise return false. 903 */ 904static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 905{ 906if(!--packed_refs->referrers) { 907free_ref_entry(packed_refs->root); 908stat_validity_clear(&packed_refs->validity); 909free(packed_refs); 910return1; 911}else{ 912return0; 913} 914} 915 916static voidclear_packed_ref_cache(struct ref_cache *refs) 917{ 918if(refs->packed) { 919struct packed_ref_cache *packed_refs = refs->packed; 920 921if(packed_refs->lock) 922die("internal error: packed-ref cache cleared while locked"); 923 refs->packed = NULL; 924release_packed_ref_cache(packed_refs); 925} 926} 927 928static voidclear_loose_ref_cache(struct ref_cache *refs) 929{ 930if(refs->loose) { 931free_ref_entry(refs->loose); 932 refs->loose = NULL; 933} 934} 935 936static struct ref_cache *create_ref_cache(const char*submodule) 937{ 938int len; 939struct ref_cache *refs; 940if(!submodule) 941 submodule =""; 942 len =strlen(submodule) +1; 943 refs =xcalloc(1,sizeof(struct ref_cache) + len); 944memcpy(refs->name, submodule, len); 945return refs; 946} 947 948/* 949 * Return a pointer to a ref_cache for the specified submodule. For 950 * the main repository, use submodule==NULL. The returned structure 951 * will be allocated and initialized but not necessarily populated; it 952 * should not be freed. 953 */ 954static struct ref_cache *get_ref_cache(const char*submodule) 955{ 956struct ref_cache *refs; 957 958if(!submodule || !*submodule) 959return&ref_cache; 960 961for(refs = submodule_ref_caches; refs; refs = refs->next) 962if(!strcmp(submodule, refs->name)) 963return refs; 964 965 refs =create_ref_cache(submodule); 966 refs->next = submodule_ref_caches; 967 submodule_ref_caches = refs; 968return refs; 969} 970 971/* The length of a peeled reference line in packed-refs, including EOL: */ 972#define PEELED_LINE_LENGTH 42 973 974/* 975 * The packed-refs header line that we write out. Perhaps other 976 * traits will be added later. The trailing space is required. 977 */ 978static const char PACKED_REFS_HEADER[] = 979"# pack-refs with: peeled fully-peeled\n"; 980 981/* 982 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 983 * Return a pointer to the refname within the line (null-terminated), 984 * or NULL if there was a problem. 985 */ 986static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 987{ 988const char*ref; 989 990/* 991 * 42: the answer to everything. 992 * 993 * In this case, it happens to be the answer to 994 * 40 (length of sha1 hex representation) 995 * +1 (space in between hex and name) 996 * +1 (newline at the end of the line) 997 */ 998if(line->len <=42) 999return NULL;10001001if(get_sha1_hex(line->buf, sha1) <0)1002return NULL;1003if(!isspace(line->buf[40]))1004return NULL;10051006 ref = line->buf +41;1007if(isspace(*ref))1008return NULL;10091010if(line->buf[line->len -1] !='\n')1011return NULL;1012 line->buf[--line->len] =0;10131014return ref;1015}10161017/*1018 * Read f, which is a packed-refs file, into dir.1019 *1020 * A comment line of the form "# pack-refs with: " may contain zero or1021 * more traits. We interpret the traits as follows:1022 *1023 * No traits:1024 *1025 * Probably no references are peeled. But if the file contains a1026 * peeled value for a reference, we will use it.1027 *1028 * peeled:1029 *1030 * References under "refs/tags/", if they *can* be peeled, *are*1031 * peeled in this file. References outside of "refs/tags/" are1032 * probably not peeled even if they could have been, but if we find1033 * a peeled value for such a reference we will use it.1034 *1035 * fully-peeled:1036 *1037 * All references in the file that can be peeled are peeled.1038 * Inversely (and this is more important), any references in the1039 * file for which no peeled value is recorded is not peelable. This1040 * trait should typically be written alongside "peeled" for1041 * compatibility with older clients, but we do not require it1042 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1043 */1044static voidread_packed_refs(FILE*f,struct ref_dir *dir)1045{1046struct ref_entry *last = NULL;1047struct strbuf line = STRBUF_INIT;1048enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10491050while(strbuf_getwholeline(&line, f,'\n') != EOF) {1051unsigned char sha1[20];1052const char*refname;1053const char*traits;10541055if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1056if(strstr(traits," fully-peeled "))1057 peeled = PEELED_FULLY;1058else if(strstr(traits," peeled "))1059 peeled = PEELED_TAGS;1060/* perhaps other traits later as well */1061continue;1062}10631064 refname =parse_ref_line(&line, sha1);1065if(refname) {1066int flag = REF_ISPACKED;10671068if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1069if(!refname_is_safe(refname))1070die("packed refname is dangerous:%s", refname);1071hashclr(sha1);1072 flag |= REF_BAD_NAME | REF_ISBROKEN;1073}1074 last =create_ref_entry(refname, sha1, flag,0);1075if(peeled == PEELED_FULLY ||1076(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1077 last->flag |= REF_KNOWS_PEELED;1078add_ref(dir, last);1079continue;1080}1081if(last &&1082 line.buf[0] =='^'&&1083 line.len == PEELED_LINE_LENGTH &&1084 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1085!get_sha1_hex(line.buf +1, sha1)) {1086hashcpy(last->u.value.peeled.hash, sha1);1087/*1088 * Regardless of what the file header said,1089 * we definitely know the value of *this*1090 * reference:1091 */1092 last->flag |= REF_KNOWS_PEELED;1093}1094}10951096strbuf_release(&line);1097}10981099/*1100 * Get the packed_ref_cache for the specified ref_cache, creating it1101 * if necessary.1102 */1103static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1104{1105char*packed_refs_file;11061107if(*refs->name)1108 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1109else1110 packed_refs_file =git_pathdup("packed-refs");11111112if(refs->packed &&1113!stat_validity_check(&refs->packed->validity, packed_refs_file))1114clear_packed_ref_cache(refs);11151116if(!refs->packed) {1117FILE*f;11181119 refs->packed =xcalloc(1,sizeof(*refs->packed));1120acquire_packed_ref_cache(refs->packed);1121 refs->packed->root =create_dir_entry(refs,"",0,0);1122 f =fopen(packed_refs_file,"r");1123if(f) {1124stat_validity_update(&refs->packed->validity,fileno(f));1125read_packed_refs(f,get_ref_dir(refs->packed->root));1126fclose(f);1127}1128}1129free(packed_refs_file);1130return refs->packed;1131}11321133static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1134{1135returnget_ref_dir(packed_ref_cache->root);1136}11371138static struct ref_dir *get_packed_refs(struct ref_cache *refs)1139{1140returnget_packed_ref_dir(get_packed_ref_cache(refs));1141}11421143/*1144 * Add a reference to the in-memory packed reference cache. This may1145 * only be called while the packed-refs file is locked (see1146 * lock_packed_refs()). To actually write the packed-refs file, call1147 * commit_packed_refs().1148 */1149static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1150{1151struct packed_ref_cache *packed_ref_cache =1152get_packed_ref_cache(&ref_cache);11531154if(!packed_ref_cache->lock)1155die("internal error: packed refs not locked");1156add_ref(get_packed_ref_dir(packed_ref_cache),1157create_ref_entry(refname, sha1, REF_ISPACKED,1));1158}11591160/*1161 * Read the loose references from the namespace dirname into dir1162 * (without recursing). dirname must end with '/'. dir must be the1163 * directory entry corresponding to dirname.1164 */1165static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1166{1167struct ref_cache *refs = dir->ref_cache;1168DIR*d;1169struct dirent *de;1170int dirnamelen =strlen(dirname);1171struct strbuf refname;1172struct strbuf path = STRBUF_INIT;1173size_t path_baselen;11741175if(*refs->name)1176strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1177else1178strbuf_git_path(&path,"%s", dirname);1179 path_baselen = path.len;11801181 d =opendir(path.buf);1182if(!d) {1183strbuf_release(&path);1184return;1185}11861187strbuf_init(&refname, dirnamelen +257);1188strbuf_add(&refname, dirname, dirnamelen);11891190while((de =readdir(d)) != NULL) {1191unsigned char sha1[20];1192struct stat st;1193int flag;11941195if(de->d_name[0] =='.')1196continue;1197if(ends_with(de->d_name,".lock"))1198continue;1199strbuf_addstr(&refname, de->d_name);1200strbuf_addstr(&path, de->d_name);1201if(stat(path.buf, &st) <0) {1202;/* silently ignore */1203}else if(S_ISDIR(st.st_mode)) {1204strbuf_addch(&refname,'/');1205add_entry_to_dir(dir,1206create_dir_entry(refs, refname.buf,1207 refname.len,1));1208}else{1209int read_ok;12101211if(*refs->name) {1212hashclr(sha1);1213 flag =0;1214 read_ok = !resolve_gitlink_ref(refs->name,1215 refname.buf, sha1);1216}else{1217 read_ok = !read_ref_full(refname.buf,1218 RESOLVE_REF_READING,1219 sha1, &flag);1220}12211222if(!read_ok) {1223hashclr(sha1);1224 flag |= REF_ISBROKEN;1225}else if(is_null_sha1(sha1)) {1226/*1227 * It is so astronomically unlikely1228 * that NULL_SHA1 is the SHA-1 of an1229 * actual object that we consider its1230 * appearance in a loose reference1231 * file to be repo corruption1232 * (probably due to a software bug).1233 */1234 flag |= REF_ISBROKEN;1235}12361237if(check_refname_format(refname.buf,1238 REFNAME_ALLOW_ONELEVEL)) {1239if(!refname_is_safe(refname.buf))1240die("loose refname is dangerous:%s", refname.buf);1241hashclr(sha1);1242 flag |= REF_BAD_NAME | REF_ISBROKEN;1243}1244add_entry_to_dir(dir,1245create_ref_entry(refname.buf, sha1, flag,0));1246}1247strbuf_setlen(&refname, dirnamelen);1248strbuf_setlen(&path, path_baselen);1249}1250strbuf_release(&refname);1251strbuf_release(&path);1252closedir(d);1253}12541255static struct ref_dir *get_loose_refs(struct ref_cache *refs)1256{1257if(!refs->loose) {1258/*1259 * Mark the top-level directory complete because we1260 * are about to read the only subdirectory that can1261 * hold references:1262 */1263 refs->loose =create_dir_entry(refs,"",0,0);1264/*1265 * Create an incomplete entry for "refs/":1266 */1267add_entry_to_dir(get_ref_dir(refs->loose),1268create_dir_entry(refs,"refs/",5,1));1269}1270returnget_ref_dir(refs->loose);1271}12721273/* We allow "recursive" symbolic refs. Only within reason, though */1274#define MAXDEPTH 51275#define MAXREFLEN (1024)12761277/*1278 * Called by resolve_gitlink_ref_recursive() after it failed to read1279 * from the loose refs in ref_cache refs. Find <refname> in the1280 * packed-refs file for the submodule.1281 */1282static intresolve_gitlink_packed_ref(struct ref_cache *refs,1283const char*refname,unsigned char*sha1)1284{1285struct ref_entry *ref;1286struct ref_dir *dir =get_packed_refs(refs);12871288 ref =find_ref(dir, refname);1289if(ref == NULL)1290return-1;12911292hashcpy(sha1, ref->u.value.oid.hash);1293return0;1294}12951296static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1297const char*refname,unsigned char*sha1,1298int recursion)1299{1300int fd, len;1301char buffer[128], *p;1302char*path;13031304if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1305return-1;1306 path = *refs->name1307?git_pathdup_submodule(refs->name,"%s", refname)1308:git_pathdup("%s", refname);1309 fd =open(path, O_RDONLY);1310free(path);1311if(fd <0)1312returnresolve_gitlink_packed_ref(refs, refname, sha1);13131314 len =read(fd, buffer,sizeof(buffer)-1);1315close(fd);1316if(len <0)1317return-1;1318while(len &&isspace(buffer[len-1]))1319 len--;1320 buffer[len] =0;13211322/* Was it a detached head or an old-fashioned symlink? */1323if(!get_sha1_hex(buffer, sha1))1324return0;13251326/* Symref? */1327if(strncmp(buffer,"ref:",4))1328return-1;1329 p = buffer +4;1330while(isspace(*p))1331 p++;13321333returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1334}13351336intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1337{1338int len =strlen(path), retval;1339char*submodule;1340struct ref_cache *refs;13411342while(len && path[len-1] =='/')1343 len--;1344if(!len)1345return-1;1346 submodule =xstrndup(path, len);1347 refs =get_ref_cache(submodule);1348free(submodule);13491350 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1351return retval;1352}13531354/*1355 * Return the ref_entry for the given refname from the packed1356 * references. If it does not exist, return NULL.1357 */1358static struct ref_entry *get_packed_ref(const char*refname)1359{1360returnfind_ref(get_packed_refs(&ref_cache), refname);1361}13621363/*1364 * A loose ref file doesn't exist; check for a packed ref. The1365 * options are forwarded from resolve_safe_unsafe().1366 */1367static intresolve_missing_loose_ref(const char*refname,1368int resolve_flags,1369unsigned char*sha1,1370int*flags)1371{1372struct ref_entry *entry;13731374/*1375 * The loose reference file does not exist; check for a packed1376 * reference.1377 */1378 entry =get_packed_ref(refname);1379if(entry) {1380hashcpy(sha1, entry->u.value.oid.hash);1381if(flags)1382*flags |= REF_ISPACKED;1383return0;1384}1385/* The reference is not a packed reference, either. */1386if(resolve_flags & RESOLVE_REF_READING) {1387 errno = ENOENT;1388return-1;1389}else{1390hashclr(sha1);1391return0;1392}1393}13941395/* This function needs to return a meaningful errno on failure */1396static const char*resolve_ref_1(const char*refname,1397int resolve_flags,1398unsigned char*sha1,1399int*flags,1400struct strbuf *sb_refname,1401struct strbuf *sb_path,1402struct strbuf *sb_contents)1403{1404int depth = MAXDEPTH;1405int bad_name =0;14061407if(flags)1408*flags =0;14091410if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1411if(flags)1412*flags |= REF_BAD_NAME;14131414if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1415!refname_is_safe(refname)) {1416 errno = EINVAL;1417return NULL;1418}1419/*1420 * dwim_ref() uses REF_ISBROKEN to distinguish between1421 * missing refs and refs that were present but invalid,1422 * to complain about the latter to stderr.1423 *1424 * We don't know whether the ref exists, so don't set1425 * REF_ISBROKEN yet.1426 */1427 bad_name =1;1428}1429for(;;) {1430const char*path;1431struct stat st;1432char*buf;1433int fd;14341435if(--depth <0) {1436 errno = ELOOP;1437return NULL;1438}14391440strbuf_reset(sb_path);1441strbuf_git_path(sb_path,"%s", refname);1442 path = sb_path->buf;14431444/*1445 * We might have to loop back here to avoid a race1446 * condition: first we lstat() the file, then we try1447 * to read it as a link or as a file. But if somebody1448 * changes the type of the file (file <-> directory1449 * <-> symlink) between the lstat() and reading, then1450 * we don't want to report that as an error but rather1451 * try again starting with the lstat().1452 */1453 stat_ref:1454if(lstat(path, &st) <0) {1455if(errno != ENOENT)1456return NULL;1457if(resolve_missing_loose_ref(refname, resolve_flags,1458 sha1, flags))1459return NULL;1460if(bad_name) {1461hashclr(sha1);1462if(flags)1463*flags |= REF_ISBROKEN;1464}1465return refname;1466}14671468/* Follow "normalized" - ie "refs/.." symlinks by hand */1469if(S_ISLNK(st.st_mode)) {1470strbuf_reset(sb_contents);1471if(strbuf_readlink(sb_contents, path,0) <0) {1472if(errno == ENOENT || errno == EINVAL)1473/* inconsistent with lstat; retry */1474goto stat_ref;1475else1476return NULL;1477}1478if(starts_with(sb_contents->buf,"refs/") &&1479!check_refname_format(sb_contents->buf,0)) {1480strbuf_swap(sb_refname, sb_contents);1481 refname = sb_refname->buf;1482if(flags)1483*flags |= REF_ISSYMREF;1484if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1485hashclr(sha1);1486return refname;1487}1488continue;1489}1490}14911492/* Is it a directory? */1493if(S_ISDIR(st.st_mode)) {1494 errno = EISDIR;1495return NULL;1496}14971498/*1499 * Anything else, just open it and try to use it as1500 * a ref1501 */1502 fd =open(path, O_RDONLY);1503if(fd <0) {1504if(errno == ENOENT)1505/* inconsistent with lstat; retry */1506goto stat_ref;1507else1508return NULL;1509}1510strbuf_reset(sb_contents);1511if(strbuf_read(sb_contents, fd,256) <0) {1512int save_errno = errno;1513close(fd);1514 errno = save_errno;1515return NULL;1516}1517close(fd);1518strbuf_rtrim(sb_contents);15191520/*1521 * Is it a symbolic ref?1522 */1523if(!starts_with(sb_contents->buf,"ref:")) {1524/*1525 * Please note that FETCH_HEAD has a second1526 * line containing other data.1527 */1528if(get_sha1_hex(sb_contents->buf, sha1) ||1529(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1530if(flags)1531*flags |= REF_ISBROKEN;1532 errno = EINVAL;1533return NULL;1534}1535if(bad_name) {1536hashclr(sha1);1537if(flags)1538*flags |= REF_ISBROKEN;1539}1540return refname;1541}1542if(flags)1543*flags |= REF_ISSYMREF;1544 buf = sb_contents->buf +4;1545while(isspace(*buf))1546 buf++;1547strbuf_reset(sb_refname);1548strbuf_addstr(sb_refname, buf);1549 refname = sb_refname->buf;1550if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1551hashclr(sha1);1552return refname;1553}1554if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1555if(flags)1556*flags |= REF_ISBROKEN;15571558if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1559!refname_is_safe(buf)) {1560 errno = EINVAL;1561return NULL;1562}1563 bad_name =1;1564}1565}1566}15671568const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1569unsigned char*sha1,int*flags)1570{1571static struct strbuf sb_refname = STRBUF_INIT;1572struct strbuf sb_contents = STRBUF_INIT;1573struct strbuf sb_path = STRBUF_INIT;1574const char*ret;15751576 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1577&sb_refname, &sb_path, &sb_contents);1578strbuf_release(&sb_path);1579strbuf_release(&sb_contents);1580return ret;1581}15821583/*1584 * Peel the entry (if possible) and return its new peel_status. If1585 * repeel is true, re-peel the entry even if there is an old peeled1586 * value that is already stored in it.1587 *1588 * It is OK to call this function with a packed reference entry that1589 * might be stale and might even refer to an object that has since1590 * been garbage-collected. In such a case, if the entry has1591 * REF_KNOWS_PEELED then leave the status unchanged and return1592 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1593 */1594static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1595{1596enum peel_status status;15971598if(entry->flag & REF_KNOWS_PEELED) {1599if(repeel) {1600 entry->flag &= ~REF_KNOWS_PEELED;1601oidclr(&entry->u.value.peeled);1602}else{1603returnis_null_oid(&entry->u.value.peeled) ?1604 PEEL_NON_TAG : PEEL_PEELED;1605}1606}1607if(entry->flag & REF_ISBROKEN)1608return PEEL_BROKEN;1609if(entry->flag & REF_ISSYMREF)1610return PEEL_IS_SYMREF;16111612 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1613if(status == PEEL_PEELED || status == PEEL_NON_TAG)1614 entry->flag |= REF_KNOWS_PEELED;1615return status;1616}16171618intpeel_ref(const char*refname,unsigned char*sha1)1619{1620int flag;1621unsigned char base[20];16221623if(current_ref && (current_ref->name == refname1624|| !strcmp(current_ref->name, refname))) {1625if(peel_entry(current_ref,0))1626return-1;1627hashcpy(sha1, current_ref->u.value.peeled.hash);1628return0;1629}16301631if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1632return-1;16331634/*1635 * If the reference is packed, read its ref_entry from the1636 * cache in the hope that we already know its peeled value.1637 * We only try this optimization on packed references because1638 * (a) forcing the filling of the loose reference cache could1639 * be expensive and (b) loose references anyway usually do not1640 * have REF_KNOWS_PEELED.1641 */1642if(flag & REF_ISPACKED) {1643struct ref_entry *r =get_packed_ref(refname);1644if(r) {1645if(peel_entry(r,0))1646return-1;1647hashcpy(sha1, r->u.value.peeled.hash);1648return0;1649}1650}16511652returnpeel_object(base, sha1);1653}16541655/*1656 * Call fn for each reference in the specified ref_cache, omitting1657 * references not in the containing_dir of base. fn is called for all1658 * references, including broken ones. If fn ever returns a non-zero1659 * value, stop the iteration and return that value; otherwise, return1660 * 0.1661 */1662static intdo_for_each_entry(struct ref_cache *refs,const char*base,1663 each_ref_entry_fn fn,void*cb_data)1664{1665struct packed_ref_cache *packed_ref_cache;1666struct ref_dir *loose_dir;1667struct ref_dir *packed_dir;1668int retval =0;16691670/*1671 * We must make sure that all loose refs are read before accessing the1672 * packed-refs file; this avoids a race condition in which loose refs1673 * are migrated to the packed-refs file by a simultaneous process, but1674 * our in-memory view is from before the migration. get_packed_ref_cache()1675 * takes care of making sure our view is up to date with what is on1676 * disk.1677 */1678 loose_dir =get_loose_refs(refs);1679if(base && *base) {1680 loose_dir =find_containing_dir(loose_dir, base,0);1681}1682if(loose_dir)1683prime_ref_dir(loose_dir);16841685 packed_ref_cache =get_packed_ref_cache(refs);1686acquire_packed_ref_cache(packed_ref_cache);1687 packed_dir =get_packed_ref_dir(packed_ref_cache);1688if(base && *base) {1689 packed_dir =find_containing_dir(packed_dir, base,0);1690}16911692if(packed_dir && loose_dir) {1693sort_ref_dir(packed_dir);1694sort_ref_dir(loose_dir);1695 retval =do_for_each_entry_in_dirs(1696 packed_dir, loose_dir, fn, cb_data);1697}else if(packed_dir) {1698sort_ref_dir(packed_dir);1699 retval =do_for_each_entry_in_dir(1700 packed_dir,0, fn, cb_data);1701}else if(loose_dir) {1702sort_ref_dir(loose_dir);1703 retval =do_for_each_entry_in_dir(1704 loose_dir,0, fn, cb_data);1705}17061707release_packed_ref_cache(packed_ref_cache);1708return retval;1709}17101711/*1712 * Call fn for each reference in the specified ref_cache for which the1713 * refname begins with base. If trim is non-zero, then trim that many1714 * characters off the beginning of each refname before passing the1715 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1716 * broken references in the iteration. If fn ever returns a non-zero1717 * value, stop the iteration and return that value; otherwise, return1718 * 0.1719 */1720static intdo_for_each_ref(struct ref_cache *refs,const char*base,1721 each_ref_fn fn,int trim,int flags,void*cb_data)1722{1723struct ref_entry_cb data;1724 data.base = base;1725 data.trim = trim;1726 data.flags = flags;1727 data.fn = fn;1728 data.cb_data = cb_data;17291730if(ref_paranoia <0)1731 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1732if(ref_paranoia)1733 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;17341735returndo_for_each_entry(refs, base, do_one_ref, &data);1736}17371738static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1739{1740struct object_id oid;1741int flag;17421743if(submodule) {1744if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)1745returnfn("HEAD", &oid,0, cb_data);17461747return0;1748}17491750if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))1751returnfn("HEAD", &oid, flag, cb_data);17521753return0;1754}17551756inthead_ref(each_ref_fn fn,void*cb_data)1757{1758returndo_head_ref(NULL, fn, cb_data);1759}17601761inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1762{1763returndo_head_ref(submodule, fn, cb_data);1764}17651766intfor_each_ref(each_ref_fn fn,void*cb_data)1767{1768returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1769}17701771intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1772{1773returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1774}17751776intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1777{1778returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1779}17801781intfor_each_fullref_in(const char*prefix, each_ref_fn fn,void*cb_data,unsigned int broken)1782{1783unsigned int flag =0;17841785if(broken)1786 flag = DO_FOR_EACH_INCLUDE_BROKEN;1787returndo_for_each_ref(&ref_cache, prefix, fn,0, flag, cb_data);1788}17891790intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1791 each_ref_fn fn,void*cb_data)1792{1793returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1794}17951796intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1797{1798returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,1799strlen(git_replace_ref_base),0, cb_data);1800}18011802intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1803{1804struct strbuf buf = STRBUF_INIT;1805int ret;1806strbuf_addf(&buf,"%srefs/",get_git_namespace());1807 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);1808strbuf_release(&buf);1809return ret;1810}18111812intfor_each_rawref(each_ref_fn fn,void*cb_data)1813{1814returndo_for_each_ref(&ref_cache,"", fn,0,1815 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1816}18171818static voidunlock_ref(struct ref_lock *lock)1819{1820/* Do not free lock->lk -- atexit() still looks at them */1821if(lock->lk)1822rollback_lock_file(lock->lk);1823free(lock->ref_name);1824free(lock->orig_ref_name);1825free(lock);1826}18271828/*1829 * Verify that the reference locked by lock has the value old_sha1.1830 * Fail if the reference doesn't exist and mustexist is set. Return 01831 * on success. On error, write an error message to err, set errno, and1832 * return a negative value.1833 */1834static intverify_lock(struct ref_lock *lock,1835const unsigned char*old_sha1,int mustexist,1836struct strbuf *err)1837{1838assert(err);18391840if(read_ref_full(lock->ref_name,1841 mustexist ? RESOLVE_REF_READING :0,1842 lock->old_oid.hash, NULL)) {1843if(old_sha1) {1844int save_errno = errno;1845strbuf_addf(err,"can't verify ref%s", lock->ref_name);1846 errno = save_errno;1847return-1;1848}else{1849hashclr(lock->old_oid.hash);1850return0;1851}1852}1853if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1854strbuf_addf(err,"ref%sis at%sbut expected%s",1855 lock->ref_name,1856sha1_to_hex(lock->old_oid.hash),1857sha1_to_hex(old_sha1));1858 errno = EBUSY;1859return-1;1860}1861return0;1862}18631864static intremove_empty_directories(struct strbuf *path)1865{1866/*1867 * we want to create a file but there is a directory there;1868 * if that is an empty directory (or a directory that contains1869 * only empty directories), remove them.1870 */1871returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1872}18731874/*1875 * Locks a ref returning the lock on success and NULL on failure.1876 * On failure errno is set to something meaningful.1877 */1878static struct ref_lock *lock_ref_sha1_basic(const char*refname,1879const unsigned char*old_sha1,1880const struct string_list *extras,1881const struct string_list *skip,1882unsigned int flags,int*type_p,1883struct strbuf *err)1884{1885struct strbuf ref_file = STRBUF_INIT;1886struct strbuf orig_ref_file = STRBUF_INIT;1887const char*orig_refname = refname;1888struct ref_lock *lock;1889int last_errno =0;1890int type;1891int lflags =0;1892int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1893int resolve_flags =0;1894int attempts_remaining =3;18951896assert(err);18971898 lock =xcalloc(1,sizeof(struct ref_lock));18991900if(mustexist)1901 resolve_flags |= RESOLVE_REF_READING;1902if(flags & REF_DELETING)1903 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1904if(flags & REF_NODEREF) {1905 resolve_flags |= RESOLVE_REF_NO_RECURSE;1906 lflags |= LOCK_NO_DEREF;1907}19081909 refname =resolve_ref_unsafe(refname, resolve_flags,1910 lock->old_oid.hash, &type);1911if(!refname && errno == EISDIR) {1912/*1913 * we are trying to lock foo but we used to1914 * have foo/bar which now does not exist;1915 * it is normal for the empty directory 'foo'1916 * to remain.1917 */1918strbuf_git_path(&orig_ref_file,"%s", orig_refname);1919if(remove_empty_directories(&orig_ref_file)) {1920 last_errno = errno;1921if(!verify_refname_available_dir(orig_refname, extras, skip,1922get_loose_refs(&ref_cache), err))1923strbuf_addf(err,"there are still refs under '%s'",1924 orig_refname);1925goto error_return;1926}1927 refname =resolve_ref_unsafe(orig_refname, resolve_flags,1928 lock->old_oid.hash, &type);1929}1930if(type_p)1931*type_p = type;1932if(!refname) {1933 last_errno = errno;1934if(last_errno != ENOTDIR ||1935!verify_refname_available_dir(orig_refname, extras, skip,1936get_loose_refs(&ref_cache), err))1937strbuf_addf(err,"unable to resolve reference%s:%s",1938 orig_refname,strerror(last_errno));19391940goto error_return;1941}19421943if(flags & REF_NODEREF)1944 refname = orig_refname;19451946/*1947 * If the ref did not exist and we are creating it, make sure1948 * there is no existing packed ref whose name begins with our1949 * refname, nor a packed ref whose name is a proper prefix of1950 * our refname.1951 */1952if(is_null_oid(&lock->old_oid) &&1953verify_refname_available_dir(refname, extras, skip,1954get_packed_refs(&ref_cache), err)) {1955 last_errno = ENOTDIR;1956goto error_return;1957}19581959 lock->lk =xcalloc(1,sizeof(struct lock_file));19601961 lock->ref_name =xstrdup(refname);1962 lock->orig_ref_name =xstrdup(orig_refname);1963strbuf_git_path(&ref_file,"%s", refname);19641965 retry:1966switch(safe_create_leading_directories_const(ref_file.buf)) {1967case SCLD_OK:1968break;/* success */1969case SCLD_VANISHED:1970if(--attempts_remaining >0)1971goto retry;1972/* fall through */1973default:1974 last_errno = errno;1975strbuf_addf(err,"unable to create directory for%s",1976 ref_file.buf);1977goto error_return;1978}19791980if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {1981 last_errno = errno;1982if(errno == ENOENT && --attempts_remaining >0)1983/*1984 * Maybe somebody just deleted one of the1985 * directories leading to ref_file. Try1986 * again:1987 */1988goto retry;1989else{1990unable_to_lock_message(ref_file.buf, errno, err);1991goto error_return;1992}1993}1994if(verify_lock(lock, old_sha1, mustexist, err)) {1995 last_errno = errno;1996goto error_return;1997}1998goto out;19992000 error_return:2001unlock_ref(lock);2002 lock = NULL;20032004 out:2005strbuf_release(&ref_file);2006strbuf_release(&orig_ref_file);2007 errno = last_errno;2008return lock;2009}20102011/*2012 * Write an entry to the packed-refs file for the specified refname.2013 * If peeled is non-NULL, write it as the entry's peeled value.2014 */2015static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2016unsigned char*peeled)2017{2018fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2019if(peeled)2020fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2021}20222023/*2024 * An each_ref_entry_fn that writes the entry to a packed-refs file.2025 */2026static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2027{2028enum peel_status peel_status =peel_entry(entry,0);20292030if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2031error("internal error:%sis not a valid packed reference!",2032 entry->name);2033write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2034 peel_status == PEEL_PEELED ?2035 entry->u.value.peeled.hash : NULL);2036return0;2037}20382039/*2040 * Lock the packed-refs file for writing. Flags is passed to2041 * hold_lock_file_for_update(). Return 0 on success. On errors, set2042 * errno appropriately and return a nonzero value.2043 */2044static intlock_packed_refs(int flags)2045{2046static int timeout_configured =0;2047static int timeout_value =1000;20482049struct packed_ref_cache *packed_ref_cache;20502051if(!timeout_configured) {2052git_config_get_int("core.packedrefstimeout", &timeout_value);2053 timeout_configured =1;2054}20552056if(hold_lock_file_for_update_timeout(2057&packlock,git_path("packed-refs"),2058 flags, timeout_value) <0)2059return-1;2060/*2061 * Get the current packed-refs while holding the lock. If the2062 * packed-refs file has been modified since we last read it,2063 * this will automatically invalidate the cache and re-read2064 * the packed-refs file.2065 */2066 packed_ref_cache =get_packed_ref_cache(&ref_cache);2067 packed_ref_cache->lock = &packlock;2068/* Increment the reference count to prevent it from being freed: */2069acquire_packed_ref_cache(packed_ref_cache);2070return0;2071}20722073/*2074 * Write the current version of the packed refs cache from memory to2075 * disk. The packed-refs file must already be locked for writing (see2076 * lock_packed_refs()). Return zero on success. On errors, set errno2077 * and return a nonzero value2078 */2079static intcommit_packed_refs(void)2080{2081struct packed_ref_cache *packed_ref_cache =2082get_packed_ref_cache(&ref_cache);2083int error =0;2084int save_errno =0;2085FILE*out;20862087if(!packed_ref_cache->lock)2088die("internal error: packed-refs not locked");20892090 out =fdopen_lock_file(packed_ref_cache->lock,"w");2091if(!out)2092die_errno("unable to fdopen packed-refs descriptor");20932094fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2095do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),20960, write_packed_entry_fn, out);20972098if(commit_lock_file(packed_ref_cache->lock)) {2099 save_errno = errno;2100 error = -1;2101}2102 packed_ref_cache->lock = NULL;2103release_packed_ref_cache(packed_ref_cache);2104 errno = save_errno;2105return error;2106}21072108/*2109 * Rollback the lockfile for the packed-refs file, and discard the2110 * in-memory packed reference cache. (The packed-refs file will be2111 * read anew if it is needed again after this function is called.)2112 */2113static voidrollback_packed_refs(void)2114{2115struct packed_ref_cache *packed_ref_cache =2116get_packed_ref_cache(&ref_cache);21172118if(!packed_ref_cache->lock)2119die("internal error: packed-refs not locked");2120rollback_lock_file(packed_ref_cache->lock);2121 packed_ref_cache->lock = NULL;2122release_packed_ref_cache(packed_ref_cache);2123clear_packed_ref_cache(&ref_cache);2124}21252126struct ref_to_prune {2127struct ref_to_prune *next;2128unsigned char sha1[20];2129char name[FLEX_ARRAY];2130};21312132struct pack_refs_cb_data {2133unsigned int flags;2134struct ref_dir *packed_refs;2135struct ref_to_prune *ref_to_prune;2136};21372138/*2139 * An each_ref_entry_fn that is run over loose references only. If2140 * the loose reference can be packed, add an entry in the packed ref2141 * cache. If the reference should be pruned, also add it to2142 * ref_to_prune in the pack_refs_cb_data.2143 */2144static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2145{2146struct pack_refs_cb_data *cb = cb_data;2147enum peel_status peel_status;2148struct ref_entry *packed_entry;2149int is_tag_ref =starts_with(entry->name,"refs/tags/");21502151/* Do not pack per-worktree refs: */2152if(ref_type(entry->name) != REF_TYPE_NORMAL)2153return0;21542155/* ALWAYS pack tags */2156if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2157return0;21582159/* Do not pack symbolic or broken refs: */2160if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2161return0;21622163/* Add a packed ref cache entry equivalent to the loose entry. */2164 peel_status =peel_entry(entry,1);2165if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2166die("internal error peeling reference%s(%s)",2167 entry->name,oid_to_hex(&entry->u.value.oid));2168 packed_entry =find_ref(cb->packed_refs, entry->name);2169if(packed_entry) {2170/* Overwrite existing packed entry with info from loose entry */2171 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2172oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2173}else{2174 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2175 REF_ISPACKED | REF_KNOWS_PEELED,0);2176add_ref(cb->packed_refs, packed_entry);2177}2178oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);21792180/* Schedule the loose reference for pruning if requested. */2181if((cb->flags & PACK_REFS_PRUNE)) {2182int namelen =strlen(entry->name) +1;2183struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2184hashcpy(n->sha1, entry->u.value.oid.hash);2185memcpy(n->name, entry->name, namelen);/* includes NUL */2186 n->next = cb->ref_to_prune;2187 cb->ref_to_prune = n;2188}2189return0;2190}21912192/*2193 * Remove empty parents, but spare refs/ and immediate subdirs.2194 * Note: munges *name.2195 */2196static voidtry_remove_empty_parents(char*name)2197{2198char*p, *q;2199int i;2200 p = name;2201for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2202while(*p && *p !='/')2203 p++;2204/* tolerate duplicate slashes; see check_refname_format() */2205while(*p =='/')2206 p++;2207}2208for(q = p; *q; q++)2209;2210while(1) {2211while(q > p && *q !='/')2212 q--;2213while(q > p && *(q-1) =='/')2214 q--;2215if(q == p)2216break;2217*q ='\0';2218if(rmdir(git_path("%s", name)))2219break;2220}2221}22222223/* make sure nobody touched the ref, and unlink */2224static voidprune_ref(struct ref_to_prune *r)2225{2226struct ref_transaction *transaction;2227struct strbuf err = STRBUF_INIT;22282229if(check_refname_format(r->name,0))2230return;22312232 transaction =ref_transaction_begin(&err);2233if(!transaction ||2234ref_transaction_delete(transaction, r->name, r->sha1,2235 REF_ISPRUNING, NULL, &err) ||2236ref_transaction_commit(transaction, &err)) {2237ref_transaction_free(transaction);2238error("%s", err.buf);2239strbuf_release(&err);2240return;2241}2242ref_transaction_free(transaction);2243strbuf_release(&err);2244try_remove_empty_parents(r->name);2245}22462247static voidprune_refs(struct ref_to_prune *r)2248{2249while(r) {2250prune_ref(r);2251 r = r->next;2252}2253}22542255intpack_refs(unsigned int flags)2256{2257struct pack_refs_cb_data cbdata;22582259memset(&cbdata,0,sizeof(cbdata));2260 cbdata.flags = flags;22612262lock_packed_refs(LOCK_DIE_ON_ERROR);2263 cbdata.packed_refs =get_packed_refs(&ref_cache);22642265do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2266 pack_if_possible_fn, &cbdata);22672268if(commit_packed_refs())2269die_errno("unable to overwrite old ref-pack file");22702271prune_refs(cbdata.ref_to_prune);2272return0;2273}22742275/*2276 * Rewrite the packed-refs file, omitting any refs listed in2277 * 'refnames'. On error, leave packed-refs unchanged, write an error2278 * message to 'err', and return a nonzero value.2279 *2280 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2281 */2282static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2283{2284struct ref_dir *packed;2285struct string_list_item *refname;2286int ret, needs_repacking =0, removed =0;22872288assert(err);22892290/* Look for a packed ref */2291for_each_string_list_item(refname, refnames) {2292if(get_packed_ref(refname->string)) {2293 needs_repacking =1;2294break;2295}2296}22972298/* Avoid locking if we have nothing to do */2299if(!needs_repacking)2300return0;/* no refname exists in packed refs */23012302if(lock_packed_refs(0)) {2303unable_to_lock_message(git_path("packed-refs"), errno, err);2304return-1;2305}2306 packed =get_packed_refs(&ref_cache);23072308/* Remove refnames from the cache */2309for_each_string_list_item(refname, refnames)2310if(remove_entry(packed, refname->string) != -1)2311 removed =1;2312if(!removed) {2313/*2314 * All packed entries disappeared while we were2315 * acquiring the lock.2316 */2317rollback_packed_refs();2318return0;2319}23202321/* Write what remains */2322 ret =commit_packed_refs();2323if(ret)2324strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2325strerror(errno));2326return ret;2327}23282329static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2330{2331assert(err);23322333if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2334/*2335 * loose. The loose file name is the same as the2336 * lockfile name, minus ".lock":2337 */2338char*loose_filename =get_locked_file_path(lock->lk);2339int res =unlink_or_msg(loose_filename, err);2340free(loose_filename);2341if(res)2342return1;2343}2344return0;2345}23462347intdelete_refs(struct string_list *refnames)2348{2349struct strbuf err = STRBUF_INIT;2350int i, result =0;23512352if(!refnames->nr)2353return0;23542355 result =repack_without_refs(refnames, &err);2356if(result) {2357/*2358 * If we failed to rewrite the packed-refs file, then2359 * it is unsafe to try to remove loose refs, because2360 * doing so might expose an obsolete packed value for2361 * a reference that might even point at an object that2362 * has been garbage collected.2363 */2364if(refnames->nr ==1)2365error(_("could not delete reference%s:%s"),2366 refnames->items[0].string, err.buf);2367else2368error(_("could not delete references:%s"), err.buf);23692370goto out;2371}23722373for(i =0; i < refnames->nr; i++) {2374const char*refname = refnames->items[i].string;23752376if(delete_ref(refname, NULL,0))2377 result |=error(_("could not remove reference%s"), refname);2378}23792380out:2381strbuf_release(&err);2382return result;2383}23842385/*2386 * People using contrib's git-new-workdir have .git/logs/refs ->2387 * /some/other/path/.git/logs/refs, and that may live on another device.2388 *2389 * IOW, to avoid cross device rename errors, the temporary renamed log must2390 * live into logs/refs.2391 */2392#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"23932394static intrename_tmp_log(const char*newrefname)2395{2396int attempts_remaining =4;2397struct strbuf path = STRBUF_INIT;2398int ret = -1;23992400 retry:2401strbuf_reset(&path);2402strbuf_git_path(&path,"logs/%s", newrefname);2403switch(safe_create_leading_directories_const(path.buf)) {2404case SCLD_OK:2405break;/* success */2406case SCLD_VANISHED:2407if(--attempts_remaining >0)2408goto retry;2409/* fall through */2410default:2411error("unable to create directory for%s", newrefname);2412goto out;2413}24142415if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2416if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2417/*2418 * rename(a, b) when b is an existing2419 * directory ought to result in ISDIR, but2420 * Solaris 5.8 gives ENOTDIR. Sheesh.2421 */2422if(remove_empty_directories(&path)) {2423error("Directory not empty: logs/%s", newrefname);2424goto out;2425}2426goto retry;2427}else if(errno == ENOENT && --attempts_remaining >0) {2428/*2429 * Maybe another process just deleted one of2430 * the directories in the path to newrefname.2431 * Try again from the beginning.2432 */2433goto retry;2434}else{2435error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2436 newrefname,strerror(errno));2437goto out;2438}2439}2440 ret =0;2441out:2442strbuf_release(&path);2443return ret;2444}24452446intverify_refname_available(const char*newname,2447struct string_list *extras,2448struct string_list *skip,2449struct strbuf *err)2450{2451struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2452struct ref_dir *loose_refs =get_loose_refs(&ref_cache);24532454if(verify_refname_available_dir(newname, extras, skip,2455 packed_refs, err) ||2456verify_refname_available_dir(newname, extras, skip,2457 loose_refs, err))2458return-1;24592460return0;2461}24622463static intwrite_ref_to_lockfile(struct ref_lock *lock,2464const unsigned char*sha1,struct strbuf *err);2465static intcommit_ref_update(struct ref_lock *lock,2466const unsigned char*sha1,const char*logmsg,2467int flags,struct strbuf *err);24682469intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2470{2471unsigned char sha1[20], orig_sha1[20];2472int flag =0, logmoved =0;2473struct ref_lock *lock;2474struct stat loginfo;2475int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2476const char*symref = NULL;2477struct strbuf err = STRBUF_INIT;24782479if(log &&S_ISLNK(loginfo.st_mode))2480returnerror("reflog for%sis a symlink", oldrefname);24812482 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2483 orig_sha1, &flag);2484if(flag & REF_ISSYMREF)2485returnerror("refname%sis a symbolic ref, renaming it is not supported",2486 oldrefname);2487if(!symref)2488returnerror("refname%snot found", oldrefname);24892490if(!rename_ref_available(oldrefname, newrefname))2491return1;24922493if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2494returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2495 oldrefname,strerror(errno));24962497if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2498error("unable to delete old%s", oldrefname);2499goto rollback;2500}25012502if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2503delete_ref(newrefname, sha1, REF_NODEREF)) {2504if(errno==EISDIR) {2505struct strbuf path = STRBUF_INIT;2506int result;25072508strbuf_git_path(&path,"%s", newrefname);2509 result =remove_empty_directories(&path);2510strbuf_release(&path);25112512if(result) {2513error("Directory not empty:%s", newrefname);2514goto rollback;2515}2516}else{2517error("unable to delete existing%s", newrefname);2518goto rollback;2519}2520}25212522if(log &&rename_tmp_log(newrefname))2523goto rollback;25242525 logmoved = log;25262527 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2528if(!lock) {2529error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2530strbuf_release(&err);2531goto rollback;2532}2533hashcpy(lock->old_oid.hash, orig_sha1);25342535if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2536commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2537error("unable to write current sha1 into%s:%s", newrefname, err.buf);2538strbuf_release(&err);2539goto rollback;2540}25412542return0;25432544 rollback:2545 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2546if(!lock) {2547error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2548strbuf_release(&err);2549goto rollbacklog;2550}25512552 flag = log_all_ref_updates;2553 log_all_ref_updates =0;2554if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2555commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2556error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2557strbuf_release(&err);2558}2559 log_all_ref_updates = flag;25602561 rollbacklog:2562if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2563error("unable to restore logfile%sfrom%s:%s",2564 oldrefname, newrefname,strerror(errno));2565if(!logmoved && log &&2566rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2567error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2568 oldrefname,strerror(errno));25692570return1;2571}25722573static intclose_ref(struct ref_lock *lock)2574{2575if(close_lock_file(lock->lk))2576return-1;2577return0;2578}25792580static intcommit_ref(struct ref_lock *lock)2581{2582if(commit_lock_file(lock->lk))2583return-1;2584return0;2585}25862587/*2588 * Create a reflog for a ref. If force_create = 0, the reflog will2589 * only be created for certain refs (those for which2590 * should_autocreate_reflog returns non-zero. Otherwise, create it2591 * regardless of the ref name. Fill in *err and return -1 on failure.2592 */2593static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2594{2595int logfd, oflags = O_APPEND | O_WRONLY;25962597strbuf_git_path(logfile,"logs/%s", refname);2598if(force_create ||should_autocreate_reflog(refname)) {2599if(safe_create_leading_directories(logfile->buf) <0) {2600strbuf_addf(err,"unable to create directory for%s: "2601"%s", logfile->buf,strerror(errno));2602return-1;2603}2604 oflags |= O_CREAT;2605}26062607 logfd =open(logfile->buf, oflags,0666);2608if(logfd <0) {2609if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2610return0;26112612if(errno == EISDIR) {2613if(remove_empty_directories(logfile)) {2614strbuf_addf(err,"There are still logs under "2615"'%s'", logfile->buf);2616return-1;2617}2618 logfd =open(logfile->buf, oflags,0666);2619}26202621if(logfd <0) {2622strbuf_addf(err,"unable to append to%s:%s",2623 logfile->buf,strerror(errno));2624return-1;2625}2626}26272628adjust_shared_perm(logfile->buf);2629close(logfd);2630return0;2631}263226332634intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2635{2636int ret;2637struct strbuf sb = STRBUF_INIT;26382639 ret =log_ref_setup(refname, &sb, err, force_create);2640strbuf_release(&sb);2641return ret;2642}26432644static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2645const unsigned char*new_sha1,2646const char*committer,const char*msg)2647{2648int msglen, written;2649unsigned maxlen, len;2650char*logrec;26512652 msglen = msg ?strlen(msg) :0;2653 maxlen =strlen(committer) + msglen +100;2654 logrec =xmalloc(maxlen);2655 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2656sha1_to_hex(old_sha1),2657sha1_to_hex(new_sha1),2658 committer);2659if(msglen)2660 len +=copy_reflog_msg(logrec + len -1, msg) -1;26612662 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2663free(logrec);2664if(written != len)2665return-1;26662667return0;2668}26692670static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2671const unsigned char*new_sha1,const char*msg,2672struct strbuf *logfile,int flags,2673struct strbuf *err)2674{2675int logfd, result, oflags = O_APPEND | O_WRONLY;26762677if(log_all_ref_updates <0)2678 log_all_ref_updates = !is_bare_repository();26792680 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);26812682if(result)2683return result;26842685 logfd =open(logfile->buf, oflags);2686if(logfd <0)2687return0;2688 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2689git_committer_info(0), msg);2690if(result) {2691strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2692strerror(errno));2693close(logfd);2694return-1;2695}2696if(close(logfd)) {2697strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2698strerror(errno));2699return-1;2700}2701return0;2702}27032704static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2705const unsigned char*new_sha1,const char*msg,2706int flags,struct strbuf *err)2707{2708returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2709 err);2710}27112712intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2713const unsigned char*new_sha1,const char*msg,2714int flags,struct strbuf *err)2715{2716struct strbuf sb = STRBUF_INIT;2717int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2718 err);2719strbuf_release(&sb);2720return ret;2721}27222723/*2724 * Write sha1 into the open lockfile, then close the lockfile. On2725 * errors, rollback the lockfile, fill in *err and2726 * return -1.2727 */2728static intwrite_ref_to_lockfile(struct ref_lock *lock,2729const unsigned char*sha1,struct strbuf *err)2730{2731static char term ='\n';2732struct object *o;2733int fd;27342735 o =parse_object(sha1);2736if(!o) {2737strbuf_addf(err,2738"Trying to write ref%swith nonexistent object%s",2739 lock->ref_name,sha1_to_hex(sha1));2740unlock_ref(lock);2741return-1;2742}2743if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2744strbuf_addf(err,2745"Trying to write non-commit object%sto branch%s",2746sha1_to_hex(sha1), lock->ref_name);2747unlock_ref(lock);2748return-1;2749}2750 fd =get_lock_file_fd(lock->lk);2751if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2752write_in_full(fd, &term,1) !=1||2753close_ref(lock) <0) {2754strbuf_addf(err,2755"Couldn't write%s",get_lock_file_path(lock->lk));2756unlock_ref(lock);2757return-1;2758}2759return0;2760}27612762/*2763 * Commit a change to a loose reference that has already been written2764 * to the loose reference lockfile. Also update the reflogs if2765 * necessary, using the specified lockmsg (which can be NULL).2766 */2767static intcommit_ref_update(struct ref_lock *lock,2768const unsigned char*sha1,const char*logmsg,2769int flags,struct strbuf *err)2770{2771clear_loose_ref_cache(&ref_cache);2772if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2773(strcmp(lock->ref_name, lock->orig_ref_name) &&2774log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2775char*old_msg =strbuf_detach(err, NULL);2776strbuf_addf(err,"Cannot update the ref '%s':%s",2777 lock->ref_name, old_msg);2778free(old_msg);2779unlock_ref(lock);2780return-1;2781}2782if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2783/*2784 * Special hack: If a branch is updated directly and HEAD2785 * points to it (may happen on the remote side of a push2786 * for example) then logically the HEAD reflog should be2787 * updated too.2788 * A generic solution implies reverse symref information,2789 * but finding all symrefs pointing to the given branch2790 * would be rather costly for this rare event (the direct2791 * update of a branch) to be worth it. So let's cheat and2792 * check with HEAD only which should cover 99% of all usage2793 * scenarios (even 100% of the default ones).2794 */2795unsigned char head_sha1[20];2796int head_flag;2797const char*head_ref;2798 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2799 head_sha1, &head_flag);2800if(head_ref && (head_flag & REF_ISSYMREF) &&2801!strcmp(head_ref, lock->ref_name)) {2802struct strbuf log_err = STRBUF_INIT;2803if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2804 logmsg,0, &log_err)) {2805error("%s", log_err.buf);2806strbuf_release(&log_err);2807}2808}2809}2810if(commit_ref(lock)) {2811error("Couldn't set%s", lock->ref_name);2812unlock_ref(lock);2813return-1;2814}28152816unlock_ref(lock);2817return0;2818}28192820static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2821{2822int ret = -1;2823#ifndef NO_SYMLINK_HEAD2824char*ref_path =get_locked_file_path(lock->lk);2825unlink(ref_path);2826 ret =symlink(target, ref_path);2827free(ref_path);28282829if(ret)2830fprintf(stderr,"no symlink - falling back to symbolic ref\n");2831#endif2832return ret;2833}28342835static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2836const char*target,const char*logmsg)2837{2838struct strbuf err = STRBUF_INIT;2839unsigned char new_sha1[20];2840if(logmsg && !read_ref(target, new_sha1) &&2841log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2842error("%s", err.buf);2843strbuf_release(&err);2844}2845}28462847static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2848const char*target,const char*logmsg)2849{2850if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2851update_symref_reflog(lock, refname, target, logmsg);2852return0;2853}28542855if(!fdopen_lock_file(lock->lk,"w"))2856returnerror("unable to fdopen%s:%s",2857 lock->lk->tempfile.filename.buf,strerror(errno));28582859update_symref_reflog(lock, refname, target, logmsg);28602861/* no error check; commit_ref will check ferror */2862fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2863if(commit_ref(lock) <0)2864returnerror("unable to write symref for%s:%s", refname,2865strerror(errno));2866return0;2867}28682869intcreate_symref(const char*refname,const char*target,const char*logmsg)2870{2871struct strbuf err = STRBUF_INIT;2872struct ref_lock *lock;2873int ret;28742875 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2876&err);2877if(!lock) {2878error("%s", err.buf);2879strbuf_release(&err);2880return-1;2881}28822883 ret =create_symref_locked(lock, refname, target, logmsg);2884unlock_ref(lock);2885return ret;2886}28872888intreflog_exists(const char*refname)2889{2890struct stat st;28912892return!lstat(git_path("logs/%s", refname), &st) &&2893S_ISREG(st.st_mode);2894}28952896intdelete_reflog(const char*refname)2897{2898returnremove_path(git_path("logs/%s", refname));2899}29002901static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2902{2903unsigned char osha1[20], nsha1[20];2904char*email_end, *message;2905unsigned long timestamp;2906int tz;29072908/* old SP new SP name <email> SP time TAB msg LF */2909if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2910get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2911get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2912!(email_end =strchr(sb->buf +82,'>')) ||2913 email_end[1] !=' '||2914!(timestamp =strtoul(email_end +2, &message,10)) ||2915!message || message[0] !=' '||2916(message[1] !='+'&& message[1] !='-') ||2917!isdigit(message[2]) || !isdigit(message[3]) ||2918!isdigit(message[4]) || !isdigit(message[5]))2919return0;/* corrupt? */2920 email_end[1] ='\0';2921 tz =strtol(message +1, NULL,10);2922if(message[6] !='\t')2923 message +=6;2924else2925 message +=7;2926returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2927}29282929static char*find_beginning_of_line(char*bob,char*scan)2930{2931while(bob < scan && *(--scan) !='\n')2932;/* keep scanning backwards */2933/*2934 * Return either beginning of the buffer, or LF at the end of2935 * the previous line.2936 */2937return scan;2938}29392940intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2941{2942struct strbuf sb = STRBUF_INIT;2943FILE*logfp;2944long pos;2945int ret =0, at_tail =1;29462947 logfp =fopen(git_path("logs/%s", refname),"r");2948if(!logfp)2949return-1;29502951/* Jump to the end */2952if(fseek(logfp,0, SEEK_END) <0)2953returnerror("cannot seek back reflog for%s:%s",2954 refname,strerror(errno));2955 pos =ftell(logfp);2956while(!ret &&0< pos) {2957int cnt;2958size_t nread;2959char buf[BUFSIZ];2960char*endp, *scanp;29612962/* Fill next block from the end */2963 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2964if(fseek(logfp, pos - cnt, SEEK_SET))2965returnerror("cannot seek back reflog for%s:%s",2966 refname,strerror(errno));2967 nread =fread(buf, cnt,1, logfp);2968if(nread !=1)2969returnerror("cannot read%dbytes from reflog for%s:%s",2970 cnt, refname,strerror(errno));2971 pos -= cnt;29722973 scanp = endp = buf + cnt;2974if(at_tail && scanp[-1] =='\n')2975/* Looking at the final LF at the end of the file */2976 scanp--;2977 at_tail =0;29782979while(buf < scanp) {2980/*2981 * terminating LF of the previous line, or the beginning2982 * of the buffer.2983 */2984char*bp;29852986 bp =find_beginning_of_line(buf, scanp);29872988if(*bp =='\n') {2989/*2990 * The newline is the end of the previous line,2991 * so we know we have complete line starting2992 * at (bp + 1). Prefix it onto any prior data2993 * we collected for the line and process it.2994 */2995strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2996 scanp = bp;2997 endp = bp +1;2998 ret =show_one_reflog_ent(&sb, fn, cb_data);2999strbuf_reset(&sb);3000if(ret)3001break;3002}else if(!pos) {3003/*3004 * We are at the start of the buffer, and the3005 * start of the file; there is no previous3006 * line, and we have everything for this one.3007 * Process it, and we can end the loop.3008 */3009strbuf_splice(&sb,0,0, buf, endp - buf);3010 ret =show_one_reflog_ent(&sb, fn, cb_data);3011strbuf_reset(&sb);3012break;3013}30143015if(bp == buf) {3016/*3017 * We are at the start of the buffer, and there3018 * is more file to read backwards. Which means3019 * we are in the middle of a line. Note that we3020 * may get here even if *bp was a newline; that3021 * just means we are at the exact end of the3022 * previous line, rather than some spot in the3023 * middle.3024 *3025 * Save away what we have to be combined with3026 * the data from the next read.3027 */3028strbuf_splice(&sb,0,0, buf, endp - buf);3029break;3030}3031}30323033}3034if(!ret && sb.len)3035die("BUG: reverse reflog parser had leftover data");30363037fclose(logfp);3038strbuf_release(&sb);3039return ret;3040}30413042intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3043{3044FILE*logfp;3045struct strbuf sb = STRBUF_INIT;3046int ret =0;30473048 logfp =fopen(git_path("logs/%s", refname),"r");3049if(!logfp)3050return-1;30513052while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3053 ret =show_one_reflog_ent(&sb, fn, cb_data);3054fclose(logfp);3055strbuf_release(&sb);3056return ret;3057}3058/*3059 * Call fn for each reflog in the namespace indicated by name. name3060 * must be empty or end with '/'. Name will be used as a scratch3061 * space, but its contents will be restored before return.3062 */3063static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3064{3065DIR*d =opendir(git_path("logs/%s", name->buf));3066int retval =0;3067struct dirent *de;3068int oldlen = name->len;30693070if(!d)3071return name->len ? errno :0;30723073while((de =readdir(d)) != NULL) {3074struct stat st;30753076if(de->d_name[0] =='.')3077continue;3078if(ends_with(de->d_name,".lock"))3079continue;3080strbuf_addstr(name, de->d_name);3081if(stat(git_path("logs/%s", name->buf), &st) <0) {3082;/* silently ignore */3083}else{3084if(S_ISDIR(st.st_mode)) {3085strbuf_addch(name,'/');3086 retval =do_for_each_reflog(name, fn, cb_data);3087}else{3088struct object_id oid;30893090if(read_ref_full(name->buf,0, oid.hash, NULL))3091 retval =error("bad ref for%s", name->buf);3092else3093 retval =fn(name->buf, &oid,0, cb_data);3094}3095if(retval)3096break;3097}3098strbuf_setlen(name, oldlen);3099}3100closedir(d);3101return retval;3102}31033104intfor_each_reflog(each_ref_fn fn,void*cb_data)3105{3106int retval;3107struct strbuf name;3108strbuf_init(&name, PATH_MAX);3109 retval =do_for_each_reflog(&name, fn, cb_data);3110strbuf_release(&name);3111return retval;3112}31133114static intref_update_reject_duplicates(struct string_list *refnames,3115struct strbuf *err)3116{3117int i, n = refnames->nr;31183119assert(err);31203121for(i =1; i < n; i++)3122if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3123strbuf_addf(err,3124"Multiple updates for ref '%s' not allowed.",3125 refnames->items[i].string);3126return1;3127}3128return0;3129}31303131intref_transaction_commit(struct ref_transaction *transaction,3132struct strbuf *err)3133{3134int ret =0, i;3135int n = transaction->nr;3136struct ref_update **updates = transaction->updates;3137struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3138struct string_list_item *ref_to_delete;3139struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31403141assert(err);31423143if(transaction->state != REF_TRANSACTION_OPEN)3144die("BUG: commit called for transaction that is not open");31453146if(!n) {3147 transaction->state = REF_TRANSACTION_CLOSED;3148return0;3149}31503151/* Fail if a refname appears more than once in the transaction: */3152for(i =0; i < n; i++)3153string_list_append(&affected_refnames, updates[i]->refname);3154string_list_sort(&affected_refnames);3155if(ref_update_reject_duplicates(&affected_refnames, err)) {3156 ret = TRANSACTION_GENERIC_ERROR;3157goto cleanup;3158}31593160/*3161 * Acquire all locks, verify old values if provided, check3162 * that new values are valid, and write new values to the3163 * lockfiles, ready to be activated. Only keep one lockfile3164 * open at a time to avoid running out of file descriptors.3165 */3166for(i =0; i < n; i++) {3167struct ref_update *update = updates[i];31683169if((update->flags & REF_HAVE_NEW) &&3170is_null_sha1(update->new_sha1))3171 update->flags |= REF_DELETING;3172 update->lock =lock_ref_sha1_basic(3173 update->refname,3174((update->flags & REF_HAVE_OLD) ?3175 update->old_sha1 : NULL),3176&affected_refnames, NULL,3177 update->flags,3178&update->type,3179 err);3180if(!update->lock) {3181char*reason;31823183 ret = (errno == ENOTDIR)3184? TRANSACTION_NAME_CONFLICT3185: TRANSACTION_GENERIC_ERROR;3186 reason =strbuf_detach(err, NULL);3187strbuf_addf(err,"cannot lock ref '%s':%s",3188 update->refname, reason);3189free(reason);3190goto cleanup;3191}3192if((update->flags & REF_HAVE_NEW) &&3193!(update->flags & REF_DELETING)) {3194int overwriting_symref = ((update->type & REF_ISSYMREF) &&3195(update->flags & REF_NODEREF));31963197if(!overwriting_symref &&3198!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3199/*3200 * The reference already has the desired3201 * value, so we don't need to write it.3202 */3203}else if(write_ref_to_lockfile(update->lock,3204 update->new_sha1,3205 err)) {3206char*write_err =strbuf_detach(err, NULL);32073208/*3209 * The lock was freed upon failure of3210 * write_ref_to_lockfile():3211 */3212 update->lock = NULL;3213strbuf_addf(err,3214"cannot update the ref '%s':%s",3215 update->refname, write_err);3216free(write_err);3217 ret = TRANSACTION_GENERIC_ERROR;3218goto cleanup;3219}else{3220 update->flags |= REF_NEEDS_COMMIT;3221}3222}3223if(!(update->flags & REF_NEEDS_COMMIT)) {3224/*3225 * We didn't have to write anything to the lockfile.3226 * Close it to free up the file descriptor:3227 */3228if(close_ref(update->lock)) {3229strbuf_addf(err,"Couldn't close%s.lock",3230 update->refname);3231goto cleanup;3232}3233}3234}32353236/* Perform updates first so live commits remain referenced */3237for(i =0; i < n; i++) {3238struct ref_update *update = updates[i];32393240if(update->flags & REF_NEEDS_COMMIT) {3241if(commit_ref_update(update->lock,3242 update->new_sha1, update->msg,3243 update->flags, err)) {3244/* freed by commit_ref_update(): */3245 update->lock = NULL;3246 ret = TRANSACTION_GENERIC_ERROR;3247goto cleanup;3248}else{3249/* freed by commit_ref_update(): */3250 update->lock = NULL;3251}3252}3253}32543255/* Perform deletes now that updates are safely completed */3256for(i =0; i < n; i++) {3257struct ref_update *update = updates[i];32583259if(update->flags & REF_DELETING) {3260if(delete_ref_loose(update->lock, update->type, err)) {3261 ret = TRANSACTION_GENERIC_ERROR;3262goto cleanup;3263}32643265if(!(update->flags & REF_ISPRUNING))3266string_list_append(&refs_to_delete,3267 update->lock->ref_name);3268}3269}32703271if(repack_without_refs(&refs_to_delete, err)) {3272 ret = TRANSACTION_GENERIC_ERROR;3273goto cleanup;3274}3275for_each_string_list_item(ref_to_delete, &refs_to_delete)3276unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3277clear_loose_ref_cache(&ref_cache);32783279cleanup:3280 transaction->state = REF_TRANSACTION_CLOSED;32813282for(i =0; i < n; i++)3283if(updates[i]->lock)3284unlock_ref(updates[i]->lock);3285string_list_clear(&refs_to_delete,0);3286string_list_clear(&affected_refnames,0);3287return ret;3288}32893290static intref_present(const char*refname,3291const struct object_id *oid,int flags,void*cb_data)3292{3293struct string_list *affected_refnames = cb_data;32943295returnstring_list_has_string(affected_refnames, refname);3296}32973298intinitial_ref_transaction_commit(struct ref_transaction *transaction,3299struct strbuf *err)3300{3301int ret =0, i;3302int n = transaction->nr;3303struct ref_update **updates = transaction->updates;3304struct string_list affected_refnames = STRING_LIST_INIT_NODUP;33053306assert(err);33073308if(transaction->state != REF_TRANSACTION_OPEN)3309die("BUG: commit called for transaction that is not open");33103311/* Fail if a refname appears more than once in the transaction: */3312for(i =0; i < n; i++)3313string_list_append(&affected_refnames, updates[i]->refname);3314string_list_sort(&affected_refnames);3315if(ref_update_reject_duplicates(&affected_refnames, err)) {3316 ret = TRANSACTION_GENERIC_ERROR;3317goto cleanup;3318}33193320/*3321 * It's really undefined to call this function in an active3322 * repository or when there are existing references: we are3323 * only locking and changing packed-refs, so (1) any3324 * simultaneous processes might try to change a reference at3325 * the same time we do, and (2) any existing loose versions of3326 * the references that we are setting would have precedence3327 * over our values. But some remote helpers create the remote3328 * "HEAD" and "master" branches before calling this function,3329 * so here we really only check that none of the references3330 * that we are creating already exists.3331 */3332if(for_each_rawref(ref_present, &affected_refnames))3333die("BUG: initial ref transaction called with existing refs");33343335for(i =0; i < n; i++) {3336struct ref_update *update = updates[i];33373338if((update->flags & REF_HAVE_OLD) &&3339!is_null_sha1(update->old_sha1))3340die("BUG: initial ref transaction with old_sha1 set");3341if(verify_refname_available(update->refname,3342&affected_refnames, NULL,3343 err)) {3344 ret = TRANSACTION_NAME_CONFLICT;3345goto cleanup;3346}3347}33483349if(lock_packed_refs(0)) {3350strbuf_addf(err,"unable to lock packed-refs file:%s",3351strerror(errno));3352 ret = TRANSACTION_GENERIC_ERROR;3353goto cleanup;3354}33553356for(i =0; i < n; i++) {3357struct ref_update *update = updates[i];33583359if((update->flags & REF_HAVE_NEW) &&3360!is_null_sha1(update->new_sha1))3361add_packed_ref(update->refname, update->new_sha1);3362}33633364if(commit_packed_refs()) {3365strbuf_addf(err,"unable to commit packed-refs file:%s",3366strerror(errno));3367 ret = TRANSACTION_GENERIC_ERROR;3368goto cleanup;3369}33703371cleanup:3372 transaction->state = REF_TRANSACTION_CLOSED;3373string_list_clear(&affected_refnames,0);3374return ret;3375}33763377struct expire_reflog_cb {3378unsigned int flags;3379 reflog_expiry_should_prune_fn *should_prune_fn;3380void*policy_cb;3381FILE*newlog;3382unsigned char last_kept_sha1[20];3383};33843385static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3386const char*email,unsigned long timestamp,int tz,3387const char*message,void*cb_data)3388{3389struct expire_reflog_cb *cb = cb_data;3390struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;33913392if(cb->flags & EXPIRE_REFLOGS_REWRITE)3393 osha1 = cb->last_kept_sha1;33943395if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3396 message, policy_cb)) {3397if(!cb->newlog)3398printf("would prune%s", message);3399else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3400printf("prune%s", message);3401}else{3402if(cb->newlog) {3403fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3404sha1_to_hex(osha1),sha1_to_hex(nsha1),3405 email, timestamp, tz, message);3406hashcpy(cb->last_kept_sha1, nsha1);3407}3408if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3409printf("keep%s", message);3410}3411return0;3412}34133414intreflog_expire(const char*refname,const unsigned char*sha1,3415unsigned int flags,3416 reflog_expiry_prepare_fn prepare_fn,3417 reflog_expiry_should_prune_fn should_prune_fn,3418 reflog_expiry_cleanup_fn cleanup_fn,3419void*policy_cb_data)3420{3421static struct lock_file reflog_lock;3422struct expire_reflog_cb cb;3423struct ref_lock *lock;3424char*log_file;3425int status =0;3426int type;3427struct strbuf err = STRBUF_INIT;34283429memset(&cb,0,sizeof(cb));3430 cb.flags = flags;3431 cb.policy_cb = policy_cb_data;3432 cb.should_prune_fn = should_prune_fn;34333434/*3435 * The reflog file is locked by holding the lock on the3436 * reference itself, plus we might need to update the3437 * reference if --updateref was specified:3438 */3439 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);3440if(!lock) {3441error("cannot lock ref '%s':%s", refname, err.buf);3442strbuf_release(&err);3443return-1;3444}3445if(!reflog_exists(refname)) {3446unlock_ref(lock);3447return0;3448}34493450 log_file =git_pathdup("logs/%s", refname);3451if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3452/*3453 * Even though holding $GIT_DIR/logs/$reflog.lock has3454 * no locking implications, we use the lock_file3455 * machinery here anyway because it does a lot of the3456 * work we need, including cleaning up if the program3457 * exits unexpectedly.3458 */3459if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3460struct strbuf err = STRBUF_INIT;3461unable_to_lock_message(log_file, errno, &err);3462error("%s", err.buf);3463strbuf_release(&err);3464goto failure;3465}3466 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3467if(!cb.newlog) {3468error("cannot fdopen%s(%s)",3469get_lock_file_path(&reflog_lock),strerror(errno));3470goto failure;3471}3472}34733474(*prepare_fn)(refname, sha1, cb.policy_cb);3475for_each_reflog_ent(refname, expire_reflog_ent, &cb);3476(*cleanup_fn)(cb.policy_cb);34773478if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3479/*3480 * It doesn't make sense to adjust a reference pointed3481 * to by a symbolic ref based on expiring entries in3482 * the symbolic reference's reflog. Nor can we update3483 * a reference if there are no remaining reflog3484 * entries.3485 */3486int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3487!(type & REF_ISSYMREF) &&3488!is_null_sha1(cb.last_kept_sha1);34893490if(close_lock_file(&reflog_lock)) {3491 status |=error("couldn't write%s:%s", log_file,3492strerror(errno));3493}else if(update &&3494(write_in_full(get_lock_file_fd(lock->lk),3495sha1_to_hex(cb.last_kept_sha1),40) !=40||3496write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3497close_ref(lock) <0)) {3498 status |=error("couldn't write%s",3499get_lock_file_path(lock->lk));3500rollback_lock_file(&reflog_lock);3501}else if(commit_lock_file(&reflog_lock)) {3502 status |=error("unable to write reflog '%s' (%s)",3503 log_file,strerror(errno));3504}else if(update &&commit_ref(lock)) {3505 status |=error("couldn't set%s", lock->ref_name);3506}3507}3508free(log_file);3509unlock_ref(lock);3510return status;35113512 failure:3513rollback_lock_file(&reflog_lock);3514free(log_file);3515unlock_ref(lock);3516return-1;3517}