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 936/* 937 * Create a new submodule ref cache and add it to the internal 938 * set of caches. 939 */ 940static struct ref_cache *create_ref_cache(const char*submodule) 941{ 942int len; 943struct ref_cache *refs; 944if(!submodule) 945 submodule =""; 946 len =strlen(submodule) +1; 947 refs =xcalloc(1,sizeof(struct ref_cache) + len); 948memcpy(refs->name, submodule, len); 949 refs->next = submodule_ref_caches; 950 submodule_ref_caches = refs; 951return refs; 952} 953 954static struct ref_cache *lookup_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; 964return NULL; 965} 966 967/* 968 * Return a pointer to a ref_cache for the specified submodule. For 969 * the main repository, use submodule==NULL. The returned structure 970 * will be allocated and initialized but not necessarily populated; it 971 * should not be freed. 972 */ 973static struct ref_cache *get_ref_cache(const char*submodule) 974{ 975struct ref_cache *refs =lookup_ref_cache(submodule); 976if(!refs) 977 refs =create_ref_cache(submodule); 978return refs; 979} 980 981/* The length of a peeled reference line in packed-refs, including EOL: */ 982#define PEELED_LINE_LENGTH 42 983 984/* 985 * The packed-refs header line that we write out. Perhaps other 986 * traits will be added later. The trailing space is required. 987 */ 988static const char PACKED_REFS_HEADER[] = 989"# pack-refs with: peeled fully-peeled\n"; 990 991/* 992 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 993 * Return a pointer to the refname within the line (null-terminated), 994 * or NULL if there was a problem. 995 */ 996static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 997{ 998const char*ref; 9991000/*1001 * 42: the answer to everything.1002 *1003 * In this case, it happens to be the answer to1004 * 40 (length of sha1 hex representation)1005 * +1 (space in between hex and name)1006 * +1 (newline at the end of the line)1007 */1008if(line->len <=42)1009return NULL;10101011if(get_sha1_hex(line->buf, sha1) <0)1012return NULL;1013if(!isspace(line->buf[40]))1014return NULL;10151016 ref = line->buf +41;1017if(isspace(*ref))1018return NULL;10191020if(line->buf[line->len -1] !='\n')1021return NULL;1022 line->buf[--line->len] =0;10231024return ref;1025}10261027/*1028 * Read f, which is a packed-refs file, into dir.1029 *1030 * A comment line of the form "# pack-refs with: " may contain zero or1031 * more traits. We interpret the traits as follows:1032 *1033 * No traits:1034 *1035 * Probably no references are peeled. But if the file contains a1036 * peeled value for a reference, we will use it.1037 *1038 * peeled:1039 *1040 * References under "refs/tags/", if they *can* be peeled, *are*1041 * peeled in this file. References outside of "refs/tags/" are1042 * probably not peeled even if they could have been, but if we find1043 * a peeled value for such a reference we will use it.1044 *1045 * fully-peeled:1046 *1047 * All references in the file that can be peeled are peeled.1048 * Inversely (and this is more important), any references in the1049 * file for which no peeled value is recorded is not peelable. This1050 * trait should typically be written alongside "peeled" for1051 * compatibility with older clients, but we do not require it1052 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1053 */1054static voidread_packed_refs(FILE*f,struct ref_dir *dir)1055{1056struct ref_entry *last = NULL;1057struct strbuf line = STRBUF_INIT;1058enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10591060while(strbuf_getwholeline(&line, f,'\n') != EOF) {1061unsigned char sha1[20];1062const char*refname;1063const char*traits;10641065if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1066if(strstr(traits," fully-peeled "))1067 peeled = PEELED_FULLY;1068else if(strstr(traits," peeled "))1069 peeled = PEELED_TAGS;1070/* perhaps other traits later as well */1071continue;1072}10731074 refname =parse_ref_line(&line, sha1);1075if(refname) {1076int flag = REF_ISPACKED;10771078if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1079if(!refname_is_safe(refname))1080die("packed refname is dangerous:%s", refname);1081hashclr(sha1);1082 flag |= REF_BAD_NAME | REF_ISBROKEN;1083}1084 last =create_ref_entry(refname, sha1, flag,0);1085if(peeled == PEELED_FULLY ||1086(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1087 last->flag |= REF_KNOWS_PEELED;1088add_ref(dir, last);1089continue;1090}1091if(last &&1092 line.buf[0] =='^'&&1093 line.len == PEELED_LINE_LENGTH &&1094 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1095!get_sha1_hex(line.buf +1, sha1)) {1096hashcpy(last->u.value.peeled.hash, sha1);1097/*1098 * Regardless of what the file header said,1099 * we definitely know the value of *this*1100 * reference:1101 */1102 last->flag |= REF_KNOWS_PEELED;1103}1104}11051106strbuf_release(&line);1107}11081109/*1110 * Get the packed_ref_cache for the specified ref_cache, creating it1111 * if necessary.1112 */1113static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1114{1115char*packed_refs_file;11161117if(*refs->name)1118 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1119else1120 packed_refs_file =git_pathdup("packed-refs");11211122if(refs->packed &&1123!stat_validity_check(&refs->packed->validity, packed_refs_file))1124clear_packed_ref_cache(refs);11251126if(!refs->packed) {1127FILE*f;11281129 refs->packed =xcalloc(1,sizeof(*refs->packed));1130acquire_packed_ref_cache(refs->packed);1131 refs->packed->root =create_dir_entry(refs,"",0,0);1132 f =fopen(packed_refs_file,"r");1133if(f) {1134stat_validity_update(&refs->packed->validity,fileno(f));1135read_packed_refs(f,get_ref_dir(refs->packed->root));1136fclose(f);1137}1138}1139free(packed_refs_file);1140return refs->packed;1141}11421143static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1144{1145returnget_ref_dir(packed_ref_cache->root);1146}11471148static struct ref_dir *get_packed_refs(struct ref_cache *refs)1149{1150returnget_packed_ref_dir(get_packed_ref_cache(refs));1151}11521153/*1154 * Add a reference to the in-memory packed reference cache. This may1155 * only be called while the packed-refs file is locked (see1156 * lock_packed_refs()). To actually write the packed-refs file, call1157 * commit_packed_refs().1158 */1159static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1160{1161struct packed_ref_cache *packed_ref_cache =1162get_packed_ref_cache(&ref_cache);11631164if(!packed_ref_cache->lock)1165die("internal error: packed refs not locked");1166add_ref(get_packed_ref_dir(packed_ref_cache),1167create_ref_entry(refname, sha1, REF_ISPACKED,1));1168}11691170/*1171 * Read the loose references from the namespace dirname into dir1172 * (without recursing). dirname must end with '/'. dir must be the1173 * directory entry corresponding to dirname.1174 */1175static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1176{1177struct ref_cache *refs = dir->ref_cache;1178DIR*d;1179struct dirent *de;1180int dirnamelen =strlen(dirname);1181struct strbuf refname;1182struct strbuf path = STRBUF_INIT;1183size_t path_baselen;11841185if(*refs->name)1186strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1187else1188strbuf_git_path(&path,"%s", dirname);1189 path_baselen = path.len;11901191 d =opendir(path.buf);1192if(!d) {1193strbuf_release(&path);1194return;1195}11961197strbuf_init(&refname, dirnamelen +257);1198strbuf_add(&refname, dirname, dirnamelen);11991200while((de =readdir(d)) != NULL) {1201unsigned char sha1[20];1202struct stat st;1203int flag;12041205if(de->d_name[0] =='.')1206continue;1207if(ends_with(de->d_name,".lock"))1208continue;1209strbuf_addstr(&refname, de->d_name);1210strbuf_addstr(&path, de->d_name);1211if(stat(path.buf, &st) <0) {1212;/* silently ignore */1213}else if(S_ISDIR(st.st_mode)) {1214strbuf_addch(&refname,'/');1215add_entry_to_dir(dir,1216create_dir_entry(refs, refname.buf,1217 refname.len,1));1218}else{1219int read_ok;12201221if(*refs->name) {1222hashclr(sha1);1223 flag =0;1224 read_ok = !resolve_gitlink_ref(refs->name,1225 refname.buf, sha1);1226}else{1227 read_ok = !read_ref_full(refname.buf,1228 RESOLVE_REF_READING,1229 sha1, &flag);1230}12311232if(!read_ok) {1233hashclr(sha1);1234 flag |= REF_ISBROKEN;1235}else if(is_null_sha1(sha1)) {1236/*1237 * It is so astronomically unlikely1238 * that NULL_SHA1 is the SHA-1 of an1239 * actual object that we consider its1240 * appearance in a loose reference1241 * file to be repo corruption1242 * (probably due to a software bug).1243 */1244 flag |= REF_ISBROKEN;1245}12461247if(check_refname_format(refname.buf,1248 REFNAME_ALLOW_ONELEVEL)) {1249if(!refname_is_safe(refname.buf))1250die("loose refname is dangerous:%s", refname.buf);1251hashclr(sha1);1252 flag |= REF_BAD_NAME | REF_ISBROKEN;1253}1254add_entry_to_dir(dir,1255create_ref_entry(refname.buf, sha1, flag,0));1256}1257strbuf_setlen(&refname, dirnamelen);1258strbuf_setlen(&path, path_baselen);1259}1260strbuf_release(&refname);1261strbuf_release(&path);1262closedir(d);1263}12641265static struct ref_dir *get_loose_refs(struct ref_cache *refs)1266{1267if(!refs->loose) {1268/*1269 * Mark the top-level directory complete because we1270 * are about to read the only subdirectory that can1271 * hold references:1272 */1273 refs->loose =create_dir_entry(refs,"",0,0);1274/*1275 * Create an incomplete entry for "refs/":1276 */1277add_entry_to_dir(get_ref_dir(refs->loose),1278create_dir_entry(refs,"refs/",5,1));1279}1280returnget_ref_dir(refs->loose);1281}12821283/* We allow "recursive" symbolic refs. Only within reason, though */1284#define MAXDEPTH 51285#define MAXREFLEN (1024)12861287/*1288 * Called by resolve_gitlink_ref_recursive() after it failed to read1289 * from the loose refs in ref_cache refs. Find <refname> in the1290 * packed-refs file for the submodule.1291 */1292static intresolve_gitlink_packed_ref(struct ref_cache *refs,1293const char*refname,unsigned char*sha1)1294{1295struct ref_entry *ref;1296struct ref_dir *dir =get_packed_refs(refs);12971298 ref =find_ref(dir, refname);1299if(ref == NULL)1300return-1;13011302hashcpy(sha1, ref->u.value.oid.hash);1303return0;1304}13051306static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1307const char*refname,unsigned char*sha1,1308int recursion)1309{1310int fd, len;1311char buffer[128], *p;1312char*path;13131314if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1315return-1;1316 path = *refs->name1317?git_pathdup_submodule(refs->name,"%s", refname)1318:git_pathdup("%s", refname);1319 fd =open(path, O_RDONLY);1320free(path);1321if(fd <0)1322returnresolve_gitlink_packed_ref(refs, refname, sha1);13231324 len =read(fd, buffer,sizeof(buffer)-1);1325close(fd);1326if(len <0)1327return-1;1328while(len &&isspace(buffer[len-1]))1329 len--;1330 buffer[len] =0;13311332/* Was it a detached head or an old-fashioned symlink? */1333if(!get_sha1_hex(buffer, sha1))1334return0;13351336/* Symref? */1337if(strncmp(buffer,"ref:",4))1338return-1;1339 p = buffer +4;1340while(isspace(*p))1341 p++;13421343returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1344}13451346intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1347{1348int len =strlen(path), retval;1349struct strbuf submodule = STRBUF_INIT;1350struct ref_cache *refs;13511352while(len && path[len-1] =='/')1353 len--;1354if(!len)1355return-1;13561357strbuf_add(&submodule, path, len);1358 refs =lookup_ref_cache(submodule.buf);1359if(!refs) {1360if(!is_nonbare_repository_dir(&submodule)) {1361strbuf_release(&submodule);1362return-1;1363}1364 refs =create_ref_cache(submodule.buf);1365}1366strbuf_release(&submodule);13671368 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1369return retval;1370}13711372/*1373 * Return the ref_entry for the given refname from the packed1374 * references. If it does not exist, return NULL.1375 */1376static struct ref_entry *get_packed_ref(const char*refname)1377{1378returnfind_ref(get_packed_refs(&ref_cache), refname);1379}13801381/*1382 * A loose ref file doesn't exist; check for a packed ref. The1383 * options are forwarded from resolve_safe_unsafe().1384 */1385static intresolve_missing_loose_ref(const char*refname,1386int resolve_flags,1387unsigned char*sha1,1388int*flags)1389{1390struct ref_entry *entry;13911392/*1393 * The loose reference file does not exist; check for a packed1394 * reference.1395 */1396 entry =get_packed_ref(refname);1397if(entry) {1398hashcpy(sha1, entry->u.value.oid.hash);1399if(flags)1400*flags |= REF_ISPACKED;1401return0;1402}1403/* The reference is not a packed reference, either. */1404if(resolve_flags & RESOLVE_REF_READING) {1405 errno = ENOENT;1406return-1;1407}else{1408hashclr(sha1);1409return0;1410}1411}14121413/* This function needs to return a meaningful errno on failure */1414static const char*resolve_ref_1(const char*refname,1415int resolve_flags,1416unsigned char*sha1,1417int*flags,1418struct strbuf *sb_refname,1419struct strbuf *sb_path,1420struct strbuf *sb_contents)1421{1422int depth = MAXDEPTH;1423int bad_name =0;14241425if(flags)1426*flags =0;14271428if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1429if(flags)1430*flags |= REF_BAD_NAME;14311432if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1433!refname_is_safe(refname)) {1434 errno = EINVAL;1435return NULL;1436}1437/*1438 * dwim_ref() uses REF_ISBROKEN to distinguish between1439 * missing refs and refs that were present but invalid,1440 * to complain about the latter to stderr.1441 *1442 * We don't know whether the ref exists, so don't set1443 * REF_ISBROKEN yet.1444 */1445 bad_name =1;1446}1447for(;;) {1448const char*path;1449struct stat st;1450char*buf;1451int fd;14521453if(--depth <0) {1454 errno = ELOOP;1455return NULL;1456}14571458strbuf_reset(sb_path);1459strbuf_git_path(sb_path,"%s", refname);1460 path = sb_path->buf;14611462/*1463 * We might have to loop back here to avoid a race1464 * condition: first we lstat() the file, then we try1465 * to read it as a link or as a file. But if somebody1466 * changes the type of the file (file <-> directory1467 * <-> symlink) between the lstat() and reading, then1468 * we don't want to report that as an error but rather1469 * try again starting with the lstat().1470 */1471 stat_ref:1472if(lstat(path, &st) <0) {1473if(errno != ENOENT)1474return NULL;1475if(resolve_missing_loose_ref(refname, resolve_flags,1476 sha1, flags))1477return NULL;1478if(bad_name) {1479hashclr(sha1);1480if(flags)1481*flags |= REF_ISBROKEN;1482}1483return refname;1484}14851486/* Follow "normalized" - ie "refs/.." symlinks by hand */1487if(S_ISLNK(st.st_mode)) {1488strbuf_reset(sb_contents);1489if(strbuf_readlink(sb_contents, path,0) <0) {1490if(errno == ENOENT || errno == EINVAL)1491/* inconsistent with lstat; retry */1492goto stat_ref;1493else1494return NULL;1495}1496if(starts_with(sb_contents->buf,"refs/") &&1497!check_refname_format(sb_contents->buf,0)) {1498strbuf_swap(sb_refname, sb_contents);1499 refname = sb_refname->buf;1500if(flags)1501*flags |= REF_ISSYMREF;1502if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1503hashclr(sha1);1504return refname;1505}1506continue;1507}1508}15091510/* Is it a directory? */1511if(S_ISDIR(st.st_mode)) {1512 errno = EISDIR;1513return NULL;1514}15151516/*1517 * Anything else, just open it and try to use it as1518 * a ref1519 */1520 fd =open(path, O_RDONLY);1521if(fd <0) {1522if(errno == ENOENT)1523/* inconsistent with lstat; retry */1524goto stat_ref;1525else1526return NULL;1527}1528strbuf_reset(sb_contents);1529if(strbuf_read(sb_contents, fd,256) <0) {1530int save_errno = errno;1531close(fd);1532 errno = save_errno;1533return NULL;1534}1535close(fd);1536strbuf_rtrim(sb_contents);15371538/*1539 * Is it a symbolic ref?1540 */1541if(!starts_with(sb_contents->buf,"ref:")) {1542/*1543 * Please note that FETCH_HEAD has a second1544 * line containing other data.1545 */1546if(get_sha1_hex(sb_contents->buf, sha1) ||1547(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1548if(flags)1549*flags |= REF_ISBROKEN;1550 errno = EINVAL;1551return NULL;1552}1553if(bad_name) {1554hashclr(sha1);1555if(flags)1556*flags |= REF_ISBROKEN;1557}1558return refname;1559}1560if(flags)1561*flags |= REF_ISSYMREF;1562 buf = sb_contents->buf +4;1563while(isspace(*buf))1564 buf++;1565strbuf_reset(sb_refname);1566strbuf_addstr(sb_refname, buf);1567 refname = sb_refname->buf;1568if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1569hashclr(sha1);1570return refname;1571}1572if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1573if(flags)1574*flags |= REF_ISBROKEN;15751576if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1577!refname_is_safe(buf)) {1578 errno = EINVAL;1579return NULL;1580}1581 bad_name =1;1582}1583}1584}15851586const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1587unsigned char*sha1,int*flags)1588{1589static struct strbuf sb_refname = STRBUF_INIT;1590struct strbuf sb_contents = STRBUF_INIT;1591struct strbuf sb_path = STRBUF_INIT;1592const char*ret;15931594 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1595&sb_refname, &sb_path, &sb_contents);1596strbuf_release(&sb_path);1597strbuf_release(&sb_contents);1598return ret;1599}16001601/*1602 * Peel the entry (if possible) and return its new peel_status. If1603 * repeel is true, re-peel the entry even if there is an old peeled1604 * value that is already stored in it.1605 *1606 * It is OK to call this function with a packed reference entry that1607 * might be stale and might even refer to an object that has since1608 * been garbage-collected. In such a case, if the entry has1609 * REF_KNOWS_PEELED then leave the status unchanged and return1610 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1611 */1612static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1613{1614enum peel_status status;16151616if(entry->flag & REF_KNOWS_PEELED) {1617if(repeel) {1618 entry->flag &= ~REF_KNOWS_PEELED;1619oidclr(&entry->u.value.peeled);1620}else{1621returnis_null_oid(&entry->u.value.peeled) ?1622 PEEL_NON_TAG : PEEL_PEELED;1623}1624}1625if(entry->flag & REF_ISBROKEN)1626return PEEL_BROKEN;1627if(entry->flag & REF_ISSYMREF)1628return PEEL_IS_SYMREF;16291630 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1631if(status == PEEL_PEELED || status == PEEL_NON_TAG)1632 entry->flag |= REF_KNOWS_PEELED;1633return status;1634}16351636intpeel_ref(const char*refname,unsigned char*sha1)1637{1638int flag;1639unsigned char base[20];16401641if(current_ref && (current_ref->name == refname1642|| !strcmp(current_ref->name, refname))) {1643if(peel_entry(current_ref,0))1644return-1;1645hashcpy(sha1, current_ref->u.value.peeled.hash);1646return0;1647}16481649if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1650return-1;16511652/*1653 * If the reference is packed, read its ref_entry from the1654 * cache in the hope that we already know its peeled value.1655 * We only try this optimization on packed references because1656 * (a) forcing the filling of the loose reference cache could1657 * be expensive and (b) loose references anyway usually do not1658 * have REF_KNOWS_PEELED.1659 */1660if(flag & REF_ISPACKED) {1661struct ref_entry *r =get_packed_ref(refname);1662if(r) {1663if(peel_entry(r,0))1664return-1;1665hashcpy(sha1, r->u.value.peeled.hash);1666return0;1667}1668}16691670returnpeel_object(base, sha1);1671}16721673/*1674 * Call fn for each reference in the specified ref_cache, omitting1675 * references not in the containing_dir of base. fn is called for all1676 * references, including broken ones. If fn ever returns a non-zero1677 * value, stop the iteration and return that value; otherwise, return1678 * 0.1679 */1680static intdo_for_each_entry(struct ref_cache *refs,const char*base,1681 each_ref_entry_fn fn,void*cb_data)1682{1683struct packed_ref_cache *packed_ref_cache;1684struct ref_dir *loose_dir;1685struct ref_dir *packed_dir;1686int retval =0;16871688/*1689 * We must make sure that all loose refs are read before accessing the1690 * packed-refs file; this avoids a race condition in which loose refs1691 * are migrated to the packed-refs file by a simultaneous process, but1692 * our in-memory view is from before the migration. get_packed_ref_cache()1693 * takes care of making sure our view is up to date with what is on1694 * disk.1695 */1696 loose_dir =get_loose_refs(refs);1697if(base && *base) {1698 loose_dir =find_containing_dir(loose_dir, base,0);1699}1700if(loose_dir)1701prime_ref_dir(loose_dir);17021703 packed_ref_cache =get_packed_ref_cache(refs);1704acquire_packed_ref_cache(packed_ref_cache);1705 packed_dir =get_packed_ref_dir(packed_ref_cache);1706if(base && *base) {1707 packed_dir =find_containing_dir(packed_dir, base,0);1708}17091710if(packed_dir && loose_dir) {1711sort_ref_dir(packed_dir);1712sort_ref_dir(loose_dir);1713 retval =do_for_each_entry_in_dirs(1714 packed_dir, loose_dir, fn, cb_data);1715}else if(packed_dir) {1716sort_ref_dir(packed_dir);1717 retval =do_for_each_entry_in_dir(1718 packed_dir,0, fn, cb_data);1719}else if(loose_dir) {1720sort_ref_dir(loose_dir);1721 retval =do_for_each_entry_in_dir(1722 loose_dir,0, fn, cb_data);1723}17241725release_packed_ref_cache(packed_ref_cache);1726return retval;1727}17281729/*1730 * Call fn for each reference in the specified ref_cache for which the1731 * refname begins with base. If trim is non-zero, then trim that many1732 * characters off the beginning of each refname before passing the1733 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1734 * broken references in the iteration. If fn ever returns a non-zero1735 * value, stop the iteration and return that value; otherwise, return1736 * 0.1737 */1738static intdo_for_each_ref(struct ref_cache *refs,const char*base,1739 each_ref_fn fn,int trim,int flags,void*cb_data)1740{1741struct ref_entry_cb data;1742 data.base = base;1743 data.trim = trim;1744 data.flags = flags;1745 data.fn = fn;1746 data.cb_data = cb_data;17471748if(ref_paranoia <0)1749 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1750if(ref_paranoia)1751 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;17521753returndo_for_each_entry(refs, base, do_one_ref, &data);1754}17551756static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1757{1758struct object_id oid;1759int flag;17601761if(submodule) {1762if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)1763returnfn("HEAD", &oid,0, cb_data);17641765return0;1766}17671768if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))1769returnfn("HEAD", &oid, flag, cb_data);17701771return0;1772}17731774inthead_ref(each_ref_fn fn,void*cb_data)1775{1776returndo_head_ref(NULL, fn, cb_data);1777}17781779inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1780{1781returndo_head_ref(submodule, fn, cb_data);1782}17831784intfor_each_ref(each_ref_fn fn,void*cb_data)1785{1786returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1787}17881789intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1790{1791returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1792}17931794intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1795{1796returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1797}17981799intfor_each_fullref_in(const char*prefix, each_ref_fn fn,void*cb_data,unsigned int broken)1800{1801unsigned int flag =0;18021803if(broken)1804 flag = DO_FOR_EACH_INCLUDE_BROKEN;1805returndo_for_each_ref(&ref_cache, prefix, fn,0, flag, cb_data);1806}18071808intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1809 each_ref_fn fn,void*cb_data)1810{1811returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1812}18131814intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1815{1816returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,1817strlen(git_replace_ref_base),0, cb_data);1818}18191820intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1821{1822struct strbuf buf = STRBUF_INIT;1823int ret;1824strbuf_addf(&buf,"%srefs/",get_git_namespace());1825 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);1826strbuf_release(&buf);1827return ret;1828}18291830intfor_each_rawref(each_ref_fn fn,void*cb_data)1831{1832returndo_for_each_ref(&ref_cache,"", fn,0,1833 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1834}18351836static voidunlock_ref(struct ref_lock *lock)1837{1838/* Do not free lock->lk -- atexit() still looks at them */1839if(lock->lk)1840rollback_lock_file(lock->lk);1841free(lock->ref_name);1842free(lock->orig_ref_name);1843free(lock);1844}18451846/*1847 * Verify that the reference locked by lock has the value old_sha1.1848 * Fail if the reference doesn't exist and mustexist is set. Return 01849 * on success. On error, write an error message to err, set errno, and1850 * return a negative value.1851 */1852static intverify_lock(struct ref_lock *lock,1853const unsigned char*old_sha1,int mustexist,1854struct strbuf *err)1855{1856assert(err);18571858if(read_ref_full(lock->ref_name,1859 mustexist ? RESOLVE_REF_READING :0,1860 lock->old_oid.hash, NULL)) {1861if(old_sha1) {1862int save_errno = errno;1863strbuf_addf(err,"can't verify ref%s", lock->ref_name);1864 errno = save_errno;1865return-1;1866}else{1867hashclr(lock->old_oid.hash);1868return0;1869}1870}1871if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1872strbuf_addf(err,"ref%sis at%sbut expected%s",1873 lock->ref_name,1874sha1_to_hex(lock->old_oid.hash),1875sha1_to_hex(old_sha1));1876 errno = EBUSY;1877return-1;1878}1879return0;1880}18811882static intremove_empty_directories(struct strbuf *path)1883{1884/*1885 * we want to create a file but there is a directory there;1886 * if that is an empty directory (or a directory that contains1887 * only empty directories), remove them.1888 */1889returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1890}18911892/*1893 * Locks a ref returning the lock on success and NULL on failure.1894 * On failure errno is set to something meaningful.1895 */1896static struct ref_lock *lock_ref_sha1_basic(const char*refname,1897const unsigned char*old_sha1,1898const struct string_list *extras,1899const struct string_list *skip,1900unsigned int flags,int*type_p,1901struct strbuf *err)1902{1903struct strbuf ref_file = STRBUF_INIT;1904struct strbuf orig_ref_file = STRBUF_INIT;1905const char*orig_refname = refname;1906struct ref_lock *lock;1907int last_errno =0;1908int type;1909int lflags =0;1910int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1911int resolve_flags =0;1912int attempts_remaining =3;19131914assert(err);19151916 lock =xcalloc(1,sizeof(struct ref_lock));19171918if(mustexist)1919 resolve_flags |= RESOLVE_REF_READING;1920if(flags & REF_DELETING)1921 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1922if(flags & REF_NODEREF) {1923 resolve_flags |= RESOLVE_REF_NO_RECURSE;1924 lflags |= LOCK_NO_DEREF;1925}19261927 refname =resolve_ref_unsafe(refname, resolve_flags,1928 lock->old_oid.hash, &type);1929if(!refname && errno == EISDIR) {1930/*1931 * we are trying to lock foo but we used to1932 * have foo/bar which now does not exist;1933 * it is normal for the empty directory 'foo'1934 * to remain.1935 */1936strbuf_git_path(&orig_ref_file,"%s", orig_refname);1937if(remove_empty_directories(&orig_ref_file)) {1938 last_errno = errno;1939if(!verify_refname_available_dir(orig_refname, extras, skip,1940get_loose_refs(&ref_cache), err))1941strbuf_addf(err,"there are still refs under '%s'",1942 orig_refname);1943goto error_return;1944}1945 refname =resolve_ref_unsafe(orig_refname, resolve_flags,1946 lock->old_oid.hash, &type);1947}1948if(type_p)1949*type_p = type;1950if(!refname) {1951 last_errno = errno;1952if(last_errno != ENOTDIR ||1953!verify_refname_available_dir(orig_refname, extras, skip,1954get_loose_refs(&ref_cache), err))1955strbuf_addf(err,"unable to resolve reference%s:%s",1956 orig_refname,strerror(last_errno));19571958goto error_return;1959}19601961if(flags & REF_NODEREF)1962 refname = orig_refname;19631964/*1965 * If the ref did not exist and we are creating it, make sure1966 * there is no existing packed ref whose name begins with our1967 * refname, nor a packed ref whose name is a proper prefix of1968 * our refname.1969 */1970if(is_null_oid(&lock->old_oid) &&1971verify_refname_available_dir(refname, extras, skip,1972get_packed_refs(&ref_cache), err)) {1973 last_errno = ENOTDIR;1974goto error_return;1975}19761977 lock->lk =xcalloc(1,sizeof(struct lock_file));19781979 lock->ref_name =xstrdup(refname);1980 lock->orig_ref_name =xstrdup(orig_refname);1981strbuf_git_path(&ref_file,"%s", refname);19821983 retry:1984switch(safe_create_leading_directories_const(ref_file.buf)) {1985case SCLD_OK:1986break;/* success */1987case SCLD_VANISHED:1988if(--attempts_remaining >0)1989goto retry;1990/* fall through */1991default:1992 last_errno = errno;1993strbuf_addf(err,"unable to create directory for%s",1994 ref_file.buf);1995goto error_return;1996}19971998if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {1999 last_errno = errno;2000if(errno == ENOENT && --attempts_remaining >0)2001/*2002 * Maybe somebody just deleted one of the2003 * directories leading to ref_file. Try2004 * again:2005 */2006goto retry;2007else{2008unable_to_lock_message(ref_file.buf, errno, err);2009goto error_return;2010}2011}2012if(verify_lock(lock, old_sha1, mustexist, err)) {2013 last_errno = errno;2014goto error_return;2015}2016goto out;20172018 error_return:2019unlock_ref(lock);2020 lock = NULL;20212022 out:2023strbuf_release(&ref_file);2024strbuf_release(&orig_ref_file);2025 errno = last_errno;2026return lock;2027}20282029/*2030 * Write an entry to the packed-refs file for the specified refname.2031 * If peeled is non-NULL, write it as the entry's peeled value.2032 */2033static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2034unsigned char*peeled)2035{2036fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2037if(peeled)2038fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2039}20402041/*2042 * An each_ref_entry_fn that writes the entry to a packed-refs file.2043 */2044static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2045{2046enum peel_status peel_status =peel_entry(entry,0);20472048if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2049error("internal error:%sis not a valid packed reference!",2050 entry->name);2051write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2052 peel_status == PEEL_PEELED ?2053 entry->u.value.peeled.hash : NULL);2054return0;2055}20562057/*2058 * Lock the packed-refs file for writing. Flags is passed to2059 * hold_lock_file_for_update(). Return 0 on success. On errors, set2060 * errno appropriately and return a nonzero value.2061 */2062static intlock_packed_refs(int flags)2063{2064static int timeout_configured =0;2065static int timeout_value =1000;20662067struct packed_ref_cache *packed_ref_cache;20682069if(!timeout_configured) {2070git_config_get_int("core.packedrefstimeout", &timeout_value);2071 timeout_configured =1;2072}20732074if(hold_lock_file_for_update_timeout(2075&packlock,git_path("packed-refs"),2076 flags, timeout_value) <0)2077return-1;2078/*2079 * Get the current packed-refs while holding the lock. If the2080 * packed-refs file has been modified since we last read it,2081 * this will automatically invalidate the cache and re-read2082 * the packed-refs file.2083 */2084 packed_ref_cache =get_packed_ref_cache(&ref_cache);2085 packed_ref_cache->lock = &packlock;2086/* Increment the reference count to prevent it from being freed: */2087acquire_packed_ref_cache(packed_ref_cache);2088return0;2089}20902091/*2092 * Write the current version of the packed refs cache from memory to2093 * disk. The packed-refs file must already be locked for writing (see2094 * lock_packed_refs()). Return zero on success. On errors, set errno2095 * and return a nonzero value2096 */2097static intcommit_packed_refs(void)2098{2099struct packed_ref_cache *packed_ref_cache =2100get_packed_ref_cache(&ref_cache);2101int error =0;2102int save_errno =0;2103FILE*out;21042105if(!packed_ref_cache->lock)2106die("internal error: packed-refs not locked");21072108 out =fdopen_lock_file(packed_ref_cache->lock,"w");2109if(!out)2110die_errno("unable to fdopen packed-refs descriptor");21112112fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2113do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),21140, write_packed_entry_fn, out);21152116if(commit_lock_file(packed_ref_cache->lock)) {2117 save_errno = errno;2118 error = -1;2119}2120 packed_ref_cache->lock = NULL;2121release_packed_ref_cache(packed_ref_cache);2122 errno = save_errno;2123return error;2124}21252126/*2127 * Rollback the lockfile for the packed-refs file, and discard the2128 * in-memory packed reference cache. (The packed-refs file will be2129 * read anew if it is needed again after this function is called.)2130 */2131static voidrollback_packed_refs(void)2132{2133struct packed_ref_cache *packed_ref_cache =2134get_packed_ref_cache(&ref_cache);21352136if(!packed_ref_cache->lock)2137die("internal error: packed-refs not locked");2138rollback_lock_file(packed_ref_cache->lock);2139 packed_ref_cache->lock = NULL;2140release_packed_ref_cache(packed_ref_cache);2141clear_packed_ref_cache(&ref_cache);2142}21432144struct ref_to_prune {2145struct ref_to_prune *next;2146unsigned char sha1[20];2147char name[FLEX_ARRAY];2148};21492150struct pack_refs_cb_data {2151unsigned int flags;2152struct ref_dir *packed_refs;2153struct ref_to_prune *ref_to_prune;2154};21552156/*2157 * An each_ref_entry_fn that is run over loose references only. If2158 * the loose reference can be packed, add an entry in the packed ref2159 * cache. If the reference should be pruned, also add it to2160 * ref_to_prune in the pack_refs_cb_data.2161 */2162static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2163{2164struct pack_refs_cb_data *cb = cb_data;2165enum peel_status peel_status;2166struct ref_entry *packed_entry;2167int is_tag_ref =starts_with(entry->name,"refs/tags/");21682169/* Do not pack per-worktree refs: */2170if(ref_type(entry->name) != REF_TYPE_NORMAL)2171return0;21722173/* ALWAYS pack tags */2174if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2175return0;21762177/* Do not pack symbolic or broken refs: */2178if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2179return0;21802181/* Add a packed ref cache entry equivalent to the loose entry. */2182 peel_status =peel_entry(entry,1);2183if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2184die("internal error peeling reference%s(%s)",2185 entry->name,oid_to_hex(&entry->u.value.oid));2186 packed_entry =find_ref(cb->packed_refs, entry->name);2187if(packed_entry) {2188/* Overwrite existing packed entry with info from loose entry */2189 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2190oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2191}else{2192 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2193 REF_ISPACKED | REF_KNOWS_PEELED,0);2194add_ref(cb->packed_refs, packed_entry);2195}2196oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);21972198/* Schedule the loose reference for pruning if requested. */2199if((cb->flags & PACK_REFS_PRUNE)) {2200int namelen =strlen(entry->name) +1;2201struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2202hashcpy(n->sha1, entry->u.value.oid.hash);2203memcpy(n->name, entry->name, namelen);/* includes NUL */2204 n->next = cb->ref_to_prune;2205 cb->ref_to_prune = n;2206}2207return0;2208}22092210/*2211 * Remove empty parents, but spare refs/ and immediate subdirs.2212 * Note: munges *name.2213 */2214static voidtry_remove_empty_parents(char*name)2215{2216char*p, *q;2217int i;2218 p = name;2219for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2220while(*p && *p !='/')2221 p++;2222/* tolerate duplicate slashes; see check_refname_format() */2223while(*p =='/')2224 p++;2225}2226for(q = p; *q; q++)2227;2228while(1) {2229while(q > p && *q !='/')2230 q--;2231while(q > p && *(q-1) =='/')2232 q--;2233if(q == p)2234break;2235*q ='\0';2236if(rmdir(git_path("%s", name)))2237break;2238}2239}22402241/* make sure nobody touched the ref, and unlink */2242static voidprune_ref(struct ref_to_prune *r)2243{2244struct ref_transaction *transaction;2245struct strbuf err = STRBUF_INIT;22462247if(check_refname_format(r->name,0))2248return;22492250 transaction =ref_transaction_begin(&err);2251if(!transaction ||2252ref_transaction_delete(transaction, r->name, r->sha1,2253 REF_ISPRUNING, NULL, &err) ||2254ref_transaction_commit(transaction, &err)) {2255ref_transaction_free(transaction);2256error("%s", err.buf);2257strbuf_release(&err);2258return;2259}2260ref_transaction_free(transaction);2261strbuf_release(&err);2262try_remove_empty_parents(r->name);2263}22642265static voidprune_refs(struct ref_to_prune *r)2266{2267while(r) {2268prune_ref(r);2269 r = r->next;2270}2271}22722273intpack_refs(unsigned int flags)2274{2275struct pack_refs_cb_data cbdata;22762277memset(&cbdata,0,sizeof(cbdata));2278 cbdata.flags = flags;22792280lock_packed_refs(LOCK_DIE_ON_ERROR);2281 cbdata.packed_refs =get_packed_refs(&ref_cache);22822283do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2284 pack_if_possible_fn, &cbdata);22852286if(commit_packed_refs())2287die_errno("unable to overwrite old ref-pack file");22882289prune_refs(cbdata.ref_to_prune);2290return0;2291}22922293/*2294 * Rewrite the packed-refs file, omitting any refs listed in2295 * 'refnames'. On error, leave packed-refs unchanged, write an error2296 * message to 'err', and return a nonzero value.2297 *2298 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2299 */2300static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2301{2302struct ref_dir *packed;2303struct string_list_item *refname;2304int ret, needs_repacking =0, removed =0;23052306assert(err);23072308/* Look for a packed ref */2309for_each_string_list_item(refname, refnames) {2310if(get_packed_ref(refname->string)) {2311 needs_repacking =1;2312break;2313}2314}23152316/* Avoid locking if we have nothing to do */2317if(!needs_repacking)2318return0;/* no refname exists in packed refs */23192320if(lock_packed_refs(0)) {2321unable_to_lock_message(git_path("packed-refs"), errno, err);2322return-1;2323}2324 packed =get_packed_refs(&ref_cache);23252326/* Remove refnames from the cache */2327for_each_string_list_item(refname, refnames)2328if(remove_entry(packed, refname->string) != -1)2329 removed =1;2330if(!removed) {2331/*2332 * All packed entries disappeared while we were2333 * acquiring the lock.2334 */2335rollback_packed_refs();2336return0;2337}23382339/* Write what remains */2340 ret =commit_packed_refs();2341if(ret)2342strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2343strerror(errno));2344return ret;2345}23462347static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2348{2349assert(err);23502351if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2352/*2353 * loose. The loose file name is the same as the2354 * lockfile name, minus ".lock":2355 */2356char*loose_filename =get_locked_file_path(lock->lk);2357int res =unlink_or_msg(loose_filename, err);2358free(loose_filename);2359if(res)2360return1;2361}2362return0;2363}23642365intdelete_refs(struct string_list *refnames)2366{2367struct strbuf err = STRBUF_INIT;2368int i, result =0;23692370if(!refnames->nr)2371return0;23722373 result =repack_without_refs(refnames, &err);2374if(result) {2375/*2376 * If we failed to rewrite the packed-refs file, then2377 * it is unsafe to try to remove loose refs, because2378 * doing so might expose an obsolete packed value for2379 * a reference that might even point at an object that2380 * has been garbage collected.2381 */2382if(refnames->nr ==1)2383error(_("could not delete reference%s:%s"),2384 refnames->items[0].string, err.buf);2385else2386error(_("could not delete references:%s"), err.buf);23872388goto out;2389}23902391for(i =0; i < refnames->nr; i++) {2392const char*refname = refnames->items[i].string;23932394if(delete_ref(refname, NULL,0))2395 result |=error(_("could not remove reference%s"), refname);2396}23972398out:2399strbuf_release(&err);2400return result;2401}24022403/*2404 * People using contrib's git-new-workdir have .git/logs/refs ->2405 * /some/other/path/.git/logs/refs, and that may live on another device.2406 *2407 * IOW, to avoid cross device rename errors, the temporary renamed log must2408 * live into logs/refs.2409 */2410#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"24112412static intrename_tmp_log(const char*newrefname)2413{2414int attempts_remaining =4;2415struct strbuf path = STRBUF_INIT;2416int ret = -1;24172418 retry:2419strbuf_reset(&path);2420strbuf_git_path(&path,"logs/%s", newrefname);2421switch(safe_create_leading_directories_const(path.buf)) {2422case SCLD_OK:2423break;/* success */2424case SCLD_VANISHED:2425if(--attempts_remaining >0)2426goto retry;2427/* fall through */2428default:2429error("unable to create directory for%s", newrefname);2430goto out;2431}24322433if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2434if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2435/*2436 * rename(a, b) when b is an existing2437 * directory ought to result in ISDIR, but2438 * Solaris 5.8 gives ENOTDIR. Sheesh.2439 */2440if(remove_empty_directories(&path)) {2441error("Directory not empty: logs/%s", newrefname);2442goto out;2443}2444goto retry;2445}else if(errno == ENOENT && --attempts_remaining >0) {2446/*2447 * Maybe another process just deleted one of2448 * the directories in the path to newrefname.2449 * Try again from the beginning.2450 */2451goto retry;2452}else{2453error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2454 newrefname,strerror(errno));2455goto out;2456}2457}2458 ret =0;2459out:2460strbuf_release(&path);2461return ret;2462}24632464intverify_refname_available(const char*newname,2465struct string_list *extras,2466struct string_list *skip,2467struct strbuf *err)2468{2469struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2470struct ref_dir *loose_refs =get_loose_refs(&ref_cache);24712472if(verify_refname_available_dir(newname, extras, skip,2473 packed_refs, err) ||2474verify_refname_available_dir(newname, extras, skip,2475 loose_refs, err))2476return-1;24772478return0;2479}24802481static intwrite_ref_to_lockfile(struct ref_lock *lock,2482const unsigned char*sha1,struct strbuf *err);2483static intcommit_ref_update(struct ref_lock *lock,2484const unsigned char*sha1,const char*logmsg,2485int flags,struct strbuf *err);24862487intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2488{2489unsigned char sha1[20], orig_sha1[20];2490int flag =0, logmoved =0;2491struct ref_lock *lock;2492struct stat loginfo;2493int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2494const char*symref = NULL;2495struct strbuf err = STRBUF_INIT;24962497if(log &&S_ISLNK(loginfo.st_mode))2498returnerror("reflog for%sis a symlink", oldrefname);24992500 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2501 orig_sha1, &flag);2502if(flag & REF_ISSYMREF)2503returnerror("refname%sis a symbolic ref, renaming it is not supported",2504 oldrefname);2505if(!symref)2506returnerror("refname%snot found", oldrefname);25072508if(!rename_ref_available(oldrefname, newrefname))2509return1;25102511if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2512returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2513 oldrefname,strerror(errno));25142515if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2516error("unable to delete old%s", oldrefname);2517goto rollback;2518}25192520if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2521delete_ref(newrefname, sha1, REF_NODEREF)) {2522if(errno==EISDIR) {2523struct strbuf path = STRBUF_INIT;2524int result;25252526strbuf_git_path(&path,"%s", newrefname);2527 result =remove_empty_directories(&path);2528strbuf_release(&path);25292530if(result) {2531error("Directory not empty:%s", newrefname);2532goto rollback;2533}2534}else{2535error("unable to delete existing%s", newrefname);2536goto rollback;2537}2538}25392540if(log &&rename_tmp_log(newrefname))2541goto rollback;25422543 logmoved = log;25442545 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2546if(!lock) {2547error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2548strbuf_release(&err);2549goto rollback;2550}2551hashcpy(lock->old_oid.hash, orig_sha1);25522553if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2554commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2555error("unable to write current sha1 into%s:%s", newrefname, err.buf);2556strbuf_release(&err);2557goto rollback;2558}25592560return0;25612562 rollback:2563 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2564if(!lock) {2565error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2566strbuf_release(&err);2567goto rollbacklog;2568}25692570 flag = log_all_ref_updates;2571 log_all_ref_updates =0;2572if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2573commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2574error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2575strbuf_release(&err);2576}2577 log_all_ref_updates = flag;25782579 rollbacklog:2580if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2581error("unable to restore logfile%sfrom%s:%s",2582 oldrefname, newrefname,strerror(errno));2583if(!logmoved && log &&2584rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2585error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2586 oldrefname,strerror(errno));25872588return1;2589}25902591static intclose_ref(struct ref_lock *lock)2592{2593if(close_lock_file(lock->lk))2594return-1;2595return0;2596}25972598static intcommit_ref(struct ref_lock *lock)2599{2600if(commit_lock_file(lock->lk))2601return-1;2602return0;2603}26042605/*2606 * Create a reflog for a ref. If force_create = 0, the reflog will2607 * only be created for certain refs (those for which2608 * should_autocreate_reflog returns non-zero. Otherwise, create it2609 * regardless of the ref name. Fill in *err and return -1 on failure.2610 */2611static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2612{2613int logfd, oflags = O_APPEND | O_WRONLY;26142615strbuf_git_path(logfile,"logs/%s", refname);2616if(force_create ||should_autocreate_reflog(refname)) {2617if(safe_create_leading_directories(logfile->buf) <0) {2618strbuf_addf(err,"unable to create directory for%s: "2619"%s", logfile->buf,strerror(errno));2620return-1;2621}2622 oflags |= O_CREAT;2623}26242625 logfd =open(logfile->buf, oflags,0666);2626if(logfd <0) {2627if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2628return0;26292630if(errno == EISDIR) {2631if(remove_empty_directories(logfile)) {2632strbuf_addf(err,"There are still logs under "2633"'%s'", logfile->buf);2634return-1;2635}2636 logfd =open(logfile->buf, oflags,0666);2637}26382639if(logfd <0) {2640strbuf_addf(err,"unable to append to%s:%s",2641 logfile->buf,strerror(errno));2642return-1;2643}2644}26452646adjust_shared_perm(logfile->buf);2647close(logfd);2648return0;2649}265026512652intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2653{2654int ret;2655struct strbuf sb = STRBUF_INIT;26562657 ret =log_ref_setup(refname, &sb, err, force_create);2658strbuf_release(&sb);2659return ret;2660}26612662static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2663const unsigned char*new_sha1,2664const char*committer,const char*msg)2665{2666int msglen, written;2667unsigned maxlen, len;2668char*logrec;26692670 msglen = msg ?strlen(msg) :0;2671 maxlen =strlen(committer) + msglen +100;2672 logrec =xmalloc(maxlen);2673 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2674sha1_to_hex(old_sha1),2675sha1_to_hex(new_sha1),2676 committer);2677if(msglen)2678 len +=copy_reflog_msg(logrec + len -1, msg) -1;26792680 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2681free(logrec);2682if(written != len)2683return-1;26842685return0;2686}26872688static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2689const unsigned char*new_sha1,const char*msg,2690struct strbuf *logfile,int flags,2691struct strbuf *err)2692{2693int logfd, result, oflags = O_APPEND | O_WRONLY;26942695if(log_all_ref_updates <0)2696 log_all_ref_updates = !is_bare_repository();26972698 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);26992700if(result)2701return result;27022703 logfd =open(logfile->buf, oflags);2704if(logfd <0)2705return0;2706 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2707git_committer_info(0), msg);2708if(result) {2709strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2710strerror(errno));2711close(logfd);2712return-1;2713}2714if(close(logfd)) {2715strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2716strerror(errno));2717return-1;2718}2719return0;2720}27212722static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2723const unsigned char*new_sha1,const char*msg,2724int flags,struct strbuf *err)2725{2726returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2727 err);2728}27292730intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2731const unsigned char*new_sha1,const char*msg,2732int flags,struct strbuf *err)2733{2734struct strbuf sb = STRBUF_INIT;2735int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2736 err);2737strbuf_release(&sb);2738return ret;2739}27402741/*2742 * Write sha1 into the open lockfile, then close the lockfile. On2743 * errors, rollback the lockfile, fill in *err and2744 * return -1.2745 */2746static intwrite_ref_to_lockfile(struct ref_lock *lock,2747const unsigned char*sha1,struct strbuf *err)2748{2749static char term ='\n';2750struct object *o;2751int fd;27522753 o =parse_object(sha1);2754if(!o) {2755strbuf_addf(err,2756"Trying to write ref%swith nonexistent object%s",2757 lock->ref_name,sha1_to_hex(sha1));2758unlock_ref(lock);2759return-1;2760}2761if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2762strbuf_addf(err,2763"Trying to write non-commit object%sto branch%s",2764sha1_to_hex(sha1), lock->ref_name);2765unlock_ref(lock);2766return-1;2767}2768 fd =get_lock_file_fd(lock->lk);2769if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2770write_in_full(fd, &term,1) !=1||2771close_ref(lock) <0) {2772strbuf_addf(err,2773"Couldn't write%s",get_lock_file_path(lock->lk));2774unlock_ref(lock);2775return-1;2776}2777return0;2778}27792780/*2781 * Commit a change to a loose reference that has already been written2782 * to the loose reference lockfile. Also update the reflogs if2783 * necessary, using the specified lockmsg (which can be NULL).2784 */2785static intcommit_ref_update(struct ref_lock *lock,2786const unsigned char*sha1,const char*logmsg,2787int flags,struct strbuf *err)2788{2789clear_loose_ref_cache(&ref_cache);2790if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2791(strcmp(lock->ref_name, lock->orig_ref_name) &&2792log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2793char*old_msg =strbuf_detach(err, NULL);2794strbuf_addf(err,"Cannot update the ref '%s':%s",2795 lock->ref_name, old_msg);2796free(old_msg);2797unlock_ref(lock);2798return-1;2799}2800if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2801/*2802 * Special hack: If a branch is updated directly and HEAD2803 * points to it (may happen on the remote side of a push2804 * for example) then logically the HEAD reflog should be2805 * updated too.2806 * A generic solution implies reverse symref information,2807 * but finding all symrefs pointing to the given branch2808 * would be rather costly for this rare event (the direct2809 * update of a branch) to be worth it. So let's cheat and2810 * check with HEAD only which should cover 99% of all usage2811 * scenarios (even 100% of the default ones).2812 */2813unsigned char head_sha1[20];2814int head_flag;2815const char*head_ref;2816 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2817 head_sha1, &head_flag);2818if(head_ref && (head_flag & REF_ISSYMREF) &&2819!strcmp(head_ref, lock->ref_name)) {2820struct strbuf log_err = STRBUF_INIT;2821if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2822 logmsg,0, &log_err)) {2823error("%s", log_err.buf);2824strbuf_release(&log_err);2825}2826}2827}2828if(commit_ref(lock)) {2829error("Couldn't set%s", lock->ref_name);2830unlock_ref(lock);2831return-1;2832}28332834unlock_ref(lock);2835return0;2836}28372838static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2839{2840int ret = -1;2841#ifndef NO_SYMLINK_HEAD2842char*ref_path =get_locked_file_path(lock->lk);2843unlink(ref_path);2844 ret =symlink(target, ref_path);2845free(ref_path);28462847if(ret)2848fprintf(stderr,"no symlink - falling back to symbolic ref\n");2849#endif2850return ret;2851}28522853static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2854const char*target,const char*logmsg)2855{2856struct strbuf err = STRBUF_INIT;2857unsigned char new_sha1[20];2858if(logmsg && !read_ref(target, new_sha1) &&2859log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2860error("%s", err.buf);2861strbuf_release(&err);2862}2863}28642865static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2866const char*target,const char*logmsg)2867{2868if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2869update_symref_reflog(lock, refname, target, logmsg);2870return0;2871}28722873if(!fdopen_lock_file(lock->lk,"w"))2874returnerror("unable to fdopen%s:%s",2875 lock->lk->tempfile.filename.buf,strerror(errno));28762877update_symref_reflog(lock, refname, target, logmsg);28782879/* no error check; commit_ref will check ferror */2880fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2881if(commit_ref(lock) <0)2882returnerror("unable to write symref for%s:%s", refname,2883strerror(errno));2884return0;2885}28862887intcreate_symref(const char*refname,const char*target,const char*logmsg)2888{2889struct strbuf err = STRBUF_INIT;2890struct ref_lock *lock;2891int ret;28922893 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2894&err);2895if(!lock) {2896error("%s", err.buf);2897strbuf_release(&err);2898return-1;2899}29002901 ret =create_symref_locked(lock, refname, target, logmsg);2902unlock_ref(lock);2903return ret;2904}29052906intreflog_exists(const char*refname)2907{2908struct stat st;29092910return!lstat(git_path("logs/%s", refname), &st) &&2911S_ISREG(st.st_mode);2912}29132914intdelete_reflog(const char*refname)2915{2916returnremove_path(git_path("logs/%s", refname));2917}29182919static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2920{2921unsigned char osha1[20], nsha1[20];2922char*email_end, *message;2923unsigned long timestamp;2924int tz;29252926/* old SP new SP name <email> SP time TAB msg LF */2927if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2928get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2929get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2930!(email_end =strchr(sb->buf +82,'>')) ||2931 email_end[1] !=' '||2932!(timestamp =strtoul(email_end +2, &message,10)) ||2933!message || message[0] !=' '||2934(message[1] !='+'&& message[1] !='-') ||2935!isdigit(message[2]) || !isdigit(message[3]) ||2936!isdigit(message[4]) || !isdigit(message[5]))2937return0;/* corrupt? */2938 email_end[1] ='\0';2939 tz =strtol(message +1, NULL,10);2940if(message[6] !='\t')2941 message +=6;2942else2943 message +=7;2944returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2945}29462947static char*find_beginning_of_line(char*bob,char*scan)2948{2949while(bob < scan && *(--scan) !='\n')2950;/* keep scanning backwards */2951/*2952 * Return either beginning of the buffer, or LF at the end of2953 * the previous line.2954 */2955return scan;2956}29572958intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2959{2960struct strbuf sb = STRBUF_INIT;2961FILE*logfp;2962long pos;2963int ret =0, at_tail =1;29642965 logfp =fopen(git_path("logs/%s", refname),"r");2966if(!logfp)2967return-1;29682969/* Jump to the end */2970if(fseek(logfp,0, SEEK_END) <0)2971returnerror("cannot seek back reflog for%s:%s",2972 refname,strerror(errno));2973 pos =ftell(logfp);2974while(!ret &&0< pos) {2975int cnt;2976size_t nread;2977char buf[BUFSIZ];2978char*endp, *scanp;29792980/* Fill next block from the end */2981 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2982if(fseek(logfp, pos - cnt, SEEK_SET))2983returnerror("cannot seek back reflog for%s:%s",2984 refname,strerror(errno));2985 nread =fread(buf, cnt,1, logfp);2986if(nread !=1)2987returnerror("cannot read%dbytes from reflog for%s:%s",2988 cnt, refname,strerror(errno));2989 pos -= cnt;29902991 scanp = endp = buf + cnt;2992if(at_tail && scanp[-1] =='\n')2993/* Looking at the final LF at the end of the file */2994 scanp--;2995 at_tail =0;29962997while(buf < scanp) {2998/*2999 * terminating LF of the previous line, or the beginning3000 * of the buffer.3001 */3002char*bp;30033004 bp =find_beginning_of_line(buf, scanp);30053006if(*bp =='\n') {3007/*3008 * The newline is the end of the previous line,3009 * so we know we have complete line starting3010 * at (bp + 1). Prefix it onto any prior data3011 * we collected for the line and process it.3012 */3013strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3014 scanp = bp;3015 endp = bp +1;3016 ret =show_one_reflog_ent(&sb, fn, cb_data);3017strbuf_reset(&sb);3018if(ret)3019break;3020}else if(!pos) {3021/*3022 * We are at the start of the buffer, and the3023 * start of the file; there is no previous3024 * line, and we have everything for this one.3025 * Process it, and we can end the loop.3026 */3027strbuf_splice(&sb,0,0, buf, endp - buf);3028 ret =show_one_reflog_ent(&sb, fn, cb_data);3029strbuf_reset(&sb);3030break;3031}30323033if(bp == buf) {3034/*3035 * We are at the start of the buffer, and there3036 * is more file to read backwards. Which means3037 * we are in the middle of a line. Note that we3038 * may get here even if *bp was a newline; that3039 * just means we are at the exact end of the3040 * previous line, rather than some spot in the3041 * middle.3042 *3043 * Save away what we have to be combined with3044 * the data from the next read.3045 */3046strbuf_splice(&sb,0,0, buf, endp - buf);3047break;3048}3049}30503051}3052if(!ret && sb.len)3053die("BUG: reverse reflog parser had leftover data");30543055fclose(logfp);3056strbuf_release(&sb);3057return ret;3058}30593060intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3061{3062FILE*logfp;3063struct strbuf sb = STRBUF_INIT;3064int ret =0;30653066 logfp =fopen(git_path("logs/%s", refname),"r");3067if(!logfp)3068return-1;30693070while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3071 ret =show_one_reflog_ent(&sb, fn, cb_data);3072fclose(logfp);3073strbuf_release(&sb);3074return ret;3075}3076/*3077 * Call fn for each reflog in the namespace indicated by name. name3078 * must be empty or end with '/'. Name will be used as a scratch3079 * space, but its contents will be restored before return.3080 */3081static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3082{3083DIR*d =opendir(git_path("logs/%s", name->buf));3084int retval =0;3085struct dirent *de;3086int oldlen = name->len;30873088if(!d)3089return name->len ? errno :0;30903091while((de =readdir(d)) != NULL) {3092struct stat st;30933094if(de->d_name[0] =='.')3095continue;3096if(ends_with(de->d_name,".lock"))3097continue;3098strbuf_addstr(name, de->d_name);3099if(stat(git_path("logs/%s", name->buf), &st) <0) {3100;/* silently ignore */3101}else{3102if(S_ISDIR(st.st_mode)) {3103strbuf_addch(name,'/');3104 retval =do_for_each_reflog(name, fn, cb_data);3105}else{3106struct object_id oid;31073108if(read_ref_full(name->buf,0, oid.hash, NULL))3109 retval =error("bad ref for%s", name->buf);3110else3111 retval =fn(name->buf, &oid,0, cb_data);3112}3113if(retval)3114break;3115}3116strbuf_setlen(name, oldlen);3117}3118closedir(d);3119return retval;3120}31213122intfor_each_reflog(each_ref_fn fn,void*cb_data)3123{3124int retval;3125struct strbuf name;3126strbuf_init(&name, PATH_MAX);3127 retval =do_for_each_reflog(&name, fn, cb_data);3128strbuf_release(&name);3129return retval;3130}31313132static intref_update_reject_duplicates(struct string_list *refnames,3133struct strbuf *err)3134{3135int i, n = refnames->nr;31363137assert(err);31383139for(i =1; i < n; i++)3140if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3141strbuf_addf(err,3142"Multiple updates for ref '%s' not allowed.",3143 refnames->items[i].string);3144return1;3145}3146return0;3147}31483149intref_transaction_commit(struct ref_transaction *transaction,3150struct strbuf *err)3151{3152int ret =0, i;3153int n = transaction->nr;3154struct ref_update **updates = transaction->updates;3155struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3156struct string_list_item *ref_to_delete;3157struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31583159assert(err);31603161if(transaction->state != REF_TRANSACTION_OPEN)3162die("BUG: commit called for transaction that is not open");31633164if(!n) {3165 transaction->state = REF_TRANSACTION_CLOSED;3166return0;3167}31683169/* Fail if a refname appears more than once in the transaction: */3170for(i =0; i < n; i++)3171string_list_append(&affected_refnames, updates[i]->refname);3172string_list_sort(&affected_refnames);3173if(ref_update_reject_duplicates(&affected_refnames, err)) {3174 ret = TRANSACTION_GENERIC_ERROR;3175goto cleanup;3176}31773178/*3179 * Acquire all locks, verify old values if provided, check3180 * that new values are valid, and write new values to the3181 * lockfiles, ready to be activated. Only keep one lockfile3182 * open at a time to avoid running out of file descriptors.3183 */3184for(i =0; i < n; i++) {3185struct ref_update *update = updates[i];31863187if((update->flags & REF_HAVE_NEW) &&3188is_null_sha1(update->new_sha1))3189 update->flags |= REF_DELETING;3190 update->lock =lock_ref_sha1_basic(3191 update->refname,3192((update->flags & REF_HAVE_OLD) ?3193 update->old_sha1 : NULL),3194&affected_refnames, NULL,3195 update->flags,3196&update->type,3197 err);3198if(!update->lock) {3199char*reason;32003201 ret = (errno == ENOTDIR)3202? TRANSACTION_NAME_CONFLICT3203: TRANSACTION_GENERIC_ERROR;3204 reason =strbuf_detach(err, NULL);3205strbuf_addf(err,"cannot lock ref '%s':%s",3206 update->refname, reason);3207free(reason);3208goto cleanup;3209}3210if((update->flags & REF_HAVE_NEW) &&3211!(update->flags & REF_DELETING)) {3212int overwriting_symref = ((update->type & REF_ISSYMREF) &&3213(update->flags & REF_NODEREF));32143215if(!overwriting_symref &&3216!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3217/*3218 * The reference already has the desired3219 * value, so we don't need to write it.3220 */3221}else if(write_ref_to_lockfile(update->lock,3222 update->new_sha1,3223 err)) {3224char*write_err =strbuf_detach(err, NULL);32253226/*3227 * The lock was freed upon failure of3228 * write_ref_to_lockfile():3229 */3230 update->lock = NULL;3231strbuf_addf(err,3232"cannot update the ref '%s':%s",3233 update->refname, write_err);3234free(write_err);3235 ret = TRANSACTION_GENERIC_ERROR;3236goto cleanup;3237}else{3238 update->flags |= REF_NEEDS_COMMIT;3239}3240}3241if(!(update->flags & REF_NEEDS_COMMIT)) {3242/*3243 * We didn't have to write anything to the lockfile.3244 * Close it to free up the file descriptor:3245 */3246if(close_ref(update->lock)) {3247strbuf_addf(err,"Couldn't close%s.lock",3248 update->refname);3249goto cleanup;3250}3251}3252}32533254/* Perform updates first so live commits remain referenced */3255for(i =0; i < n; i++) {3256struct ref_update *update = updates[i];32573258if(update->flags & REF_NEEDS_COMMIT) {3259if(commit_ref_update(update->lock,3260 update->new_sha1, update->msg,3261 update->flags, err)) {3262/* freed by commit_ref_update(): */3263 update->lock = NULL;3264 ret = TRANSACTION_GENERIC_ERROR;3265goto cleanup;3266}else{3267/* freed by commit_ref_update(): */3268 update->lock = NULL;3269}3270}3271}32723273/* Perform deletes now that updates are safely completed */3274for(i =0; i < n; i++) {3275struct ref_update *update = updates[i];32763277if(update->flags & REF_DELETING) {3278if(delete_ref_loose(update->lock, update->type, err)) {3279 ret = TRANSACTION_GENERIC_ERROR;3280goto cleanup;3281}32823283if(!(update->flags & REF_ISPRUNING))3284string_list_append(&refs_to_delete,3285 update->lock->ref_name);3286}3287}32883289if(repack_without_refs(&refs_to_delete, err)) {3290 ret = TRANSACTION_GENERIC_ERROR;3291goto cleanup;3292}3293for_each_string_list_item(ref_to_delete, &refs_to_delete)3294unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3295clear_loose_ref_cache(&ref_cache);32963297cleanup:3298 transaction->state = REF_TRANSACTION_CLOSED;32993300for(i =0; i < n; i++)3301if(updates[i]->lock)3302unlock_ref(updates[i]->lock);3303string_list_clear(&refs_to_delete,0);3304string_list_clear(&affected_refnames,0);3305return ret;3306}33073308static intref_present(const char*refname,3309const struct object_id *oid,int flags,void*cb_data)3310{3311struct string_list *affected_refnames = cb_data;33123313returnstring_list_has_string(affected_refnames, refname);3314}33153316intinitial_ref_transaction_commit(struct ref_transaction *transaction,3317struct strbuf *err)3318{3319int ret =0, i;3320int n = transaction->nr;3321struct ref_update **updates = transaction->updates;3322struct string_list affected_refnames = STRING_LIST_INIT_NODUP;33233324assert(err);33253326if(transaction->state != REF_TRANSACTION_OPEN)3327die("BUG: commit called for transaction that is not open");33283329/* Fail if a refname appears more than once in the transaction: */3330for(i =0; i < n; i++)3331string_list_append(&affected_refnames, updates[i]->refname);3332string_list_sort(&affected_refnames);3333if(ref_update_reject_duplicates(&affected_refnames, err)) {3334 ret = TRANSACTION_GENERIC_ERROR;3335goto cleanup;3336}33373338/*3339 * It's really undefined to call this function in an active3340 * repository or when there are existing references: we are3341 * only locking and changing packed-refs, so (1) any3342 * simultaneous processes might try to change a reference at3343 * the same time we do, and (2) any existing loose versions of3344 * the references that we are setting would have precedence3345 * over our values. But some remote helpers create the remote3346 * "HEAD" and "master" branches before calling this function,3347 * so here we really only check that none of the references3348 * that we are creating already exists.3349 */3350if(for_each_rawref(ref_present, &affected_refnames))3351die("BUG: initial ref transaction called with existing refs");33523353for(i =0; i < n; i++) {3354struct ref_update *update = updates[i];33553356if((update->flags & REF_HAVE_OLD) &&3357!is_null_sha1(update->old_sha1))3358die("BUG: initial ref transaction with old_sha1 set");3359if(verify_refname_available(update->refname,3360&affected_refnames, NULL,3361 err)) {3362 ret = TRANSACTION_NAME_CONFLICT;3363goto cleanup;3364}3365}33663367if(lock_packed_refs(0)) {3368strbuf_addf(err,"unable to lock packed-refs file:%s",3369strerror(errno));3370 ret = TRANSACTION_GENERIC_ERROR;3371goto cleanup;3372}33733374for(i =0; i < n; i++) {3375struct ref_update *update = updates[i];33763377if((update->flags & REF_HAVE_NEW) &&3378!is_null_sha1(update->new_sha1))3379add_packed_ref(update->refname, update->new_sha1);3380}33813382if(commit_packed_refs()) {3383strbuf_addf(err,"unable to commit packed-refs file:%s",3384strerror(errno));3385 ret = TRANSACTION_GENERIC_ERROR;3386goto cleanup;3387}33883389cleanup:3390 transaction->state = REF_TRANSACTION_CLOSED;3391string_list_clear(&affected_refnames,0);3392return ret;3393}33943395struct expire_reflog_cb {3396unsigned int flags;3397 reflog_expiry_should_prune_fn *should_prune_fn;3398void*policy_cb;3399FILE*newlog;3400unsigned char last_kept_sha1[20];3401};34023403static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3404const char*email,unsigned long timestamp,int tz,3405const char*message,void*cb_data)3406{3407struct expire_reflog_cb *cb = cb_data;3408struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;34093410if(cb->flags & EXPIRE_REFLOGS_REWRITE)3411 osha1 = cb->last_kept_sha1;34123413if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3414 message, policy_cb)) {3415if(!cb->newlog)3416printf("would prune%s", message);3417else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3418printf("prune%s", message);3419}else{3420if(cb->newlog) {3421fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3422sha1_to_hex(osha1),sha1_to_hex(nsha1),3423 email, timestamp, tz, message);3424hashcpy(cb->last_kept_sha1, nsha1);3425}3426if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3427printf("keep%s", message);3428}3429return0;3430}34313432intreflog_expire(const char*refname,const unsigned char*sha1,3433unsigned int flags,3434 reflog_expiry_prepare_fn prepare_fn,3435 reflog_expiry_should_prune_fn should_prune_fn,3436 reflog_expiry_cleanup_fn cleanup_fn,3437void*policy_cb_data)3438{3439static struct lock_file reflog_lock;3440struct expire_reflog_cb cb;3441struct ref_lock *lock;3442char*log_file;3443int status =0;3444int type;3445struct strbuf err = STRBUF_INIT;34463447memset(&cb,0,sizeof(cb));3448 cb.flags = flags;3449 cb.policy_cb = policy_cb_data;3450 cb.should_prune_fn = should_prune_fn;34513452/*3453 * The reflog file is locked by holding the lock on the3454 * reference itself, plus we might need to update the3455 * reference if --updateref was specified:3456 */3457 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);3458if(!lock) {3459error("cannot lock ref '%s':%s", refname, err.buf);3460strbuf_release(&err);3461return-1;3462}3463if(!reflog_exists(refname)) {3464unlock_ref(lock);3465return0;3466}34673468 log_file =git_pathdup("logs/%s", refname);3469if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3470/*3471 * Even though holding $GIT_DIR/logs/$reflog.lock has3472 * no locking implications, we use the lock_file3473 * machinery here anyway because it does a lot of the3474 * work we need, including cleaning up if the program3475 * exits unexpectedly.3476 */3477if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3478struct strbuf err = STRBUF_INIT;3479unable_to_lock_message(log_file, errno, &err);3480error("%s", err.buf);3481strbuf_release(&err);3482goto failure;3483}3484 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3485if(!cb.newlog) {3486error("cannot fdopen%s(%s)",3487get_lock_file_path(&reflog_lock),strerror(errno));3488goto failure;3489}3490}34913492(*prepare_fn)(refname, sha1, cb.policy_cb);3493for_each_reflog_ent(refname, expire_reflog_ent, &cb);3494(*cleanup_fn)(cb.policy_cb);34953496if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3497/*3498 * It doesn't make sense to adjust a reference pointed3499 * to by a symbolic ref based on expiring entries in3500 * the symbolic reference's reflog. Nor can we update3501 * a reference if there are no remaining reflog3502 * entries.3503 */3504int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3505!(type & REF_ISSYMREF) &&3506!is_null_sha1(cb.last_kept_sha1);35073508if(close_lock_file(&reflog_lock)) {3509 status |=error("couldn't write%s:%s", log_file,3510strerror(errno));3511}else if(update &&3512(write_in_full(get_lock_file_fd(lock->lk),3513sha1_to_hex(cb.last_kept_sha1),40) !=40||3514write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3515close_ref(lock) <0)) {3516 status |=error("couldn't write%s",3517get_lock_file_path(lock->lk));3518rollback_lock_file(&reflog_lock);3519}else if(commit_lock_file(&reflog_lock)) {3520 status |=error("unable to write reflog '%s' (%s)",3521 log_file,strerror(errno));3522}else if(update &&commit_ref(lock)) {3523 status |=error("couldn't set%s", lock->ref_name);3524}3525}3526free(log_file);3527unlock_ref(lock);3528return status;35293530 failure:3531rollback_lock_file(&reflog_lock);3532free(log_file);3533unlock_ref(lock);3534return-1;3535}