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)) {1861int save_errno = errno;1862strbuf_addf(err,"can't verify ref%s", lock->ref_name);1863 errno = save_errno;1864return-1;1865}1866if(hashcmp(lock->old_oid.hash, old_sha1)) {1867strbuf_addf(err,"ref%sis at%sbut expected%s",1868 lock->ref_name,1869sha1_to_hex(lock->old_oid.hash),1870sha1_to_hex(old_sha1));1871 errno = EBUSY;1872return-1;1873}1874return0;1875}18761877static intremove_empty_directories(struct strbuf *path)1878{1879/*1880 * we want to create a file but there is a directory there;1881 * if that is an empty directory (or a directory that contains1882 * only empty directories), remove them.1883 */1884returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1885}18861887/*1888 * Locks a ref returning the lock on success and NULL on failure.1889 * On failure errno is set to something meaningful.1890 */1891static struct ref_lock *lock_ref_sha1_basic(const char*refname,1892const unsigned char*old_sha1,1893const struct string_list *extras,1894const struct string_list *skip,1895unsigned int flags,int*type_p,1896struct strbuf *err)1897{1898struct strbuf ref_file = STRBUF_INIT;1899struct strbuf orig_ref_file = STRBUF_INIT;1900const char*orig_refname = refname;1901struct ref_lock *lock;1902int last_errno =0;1903int type, lflags;1904int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1905int resolve_flags =0;1906int attempts_remaining =3;19071908assert(err);19091910 lock =xcalloc(1,sizeof(struct ref_lock));19111912if(mustexist)1913 resolve_flags |= RESOLVE_REF_READING;1914if(flags & REF_DELETING) {1915 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1916if(flags & REF_NODEREF)1917 resolve_flags |= RESOLVE_REF_NO_RECURSE;1918}19191920 refname =resolve_ref_unsafe(refname, resolve_flags,1921 lock->old_oid.hash, &type);1922if(!refname && errno == EISDIR) {1923/*1924 * we are trying to lock foo but we used to1925 * have foo/bar which now does not exist;1926 * it is normal for the empty directory 'foo'1927 * to remain.1928 */1929strbuf_git_path(&orig_ref_file,"%s", orig_refname);1930if(remove_empty_directories(&orig_ref_file)) {1931 last_errno = errno;1932if(!verify_refname_available_dir(orig_refname, extras, skip,1933get_loose_refs(&ref_cache), err))1934strbuf_addf(err,"there are still refs under '%s'",1935 orig_refname);1936goto error_return;1937}1938 refname =resolve_ref_unsafe(orig_refname, resolve_flags,1939 lock->old_oid.hash, &type);1940}1941if(type_p)1942*type_p = type;1943if(!refname) {1944 last_errno = errno;1945if(last_errno != ENOTDIR ||1946!verify_refname_available_dir(orig_refname, extras, skip,1947get_loose_refs(&ref_cache), err))1948strbuf_addf(err,"unable to resolve reference%s:%s",1949 orig_refname,strerror(last_errno));19501951goto error_return;1952}1953/*1954 * If the ref did not exist and we are creating it, make sure1955 * there is no existing packed ref whose name begins with our1956 * refname, nor a packed ref whose name is a proper prefix of1957 * our refname.1958 */1959if(is_null_oid(&lock->old_oid) &&1960verify_refname_available_dir(refname, extras, skip,1961get_packed_refs(&ref_cache), err)) {1962 last_errno = ENOTDIR;1963goto error_return;1964}19651966 lock->lk =xcalloc(1,sizeof(struct lock_file));19671968 lflags =0;1969if(flags & REF_NODEREF) {1970 refname = orig_refname;1971 lflags |= LOCK_NO_DEREF;1972}1973 lock->ref_name =xstrdup(refname);1974 lock->orig_ref_name =xstrdup(orig_refname);1975strbuf_git_path(&ref_file,"%s", refname);19761977 retry:1978switch(safe_create_leading_directories_const(ref_file.buf)) {1979case SCLD_OK:1980break;/* success */1981case SCLD_VANISHED:1982if(--attempts_remaining >0)1983goto retry;1984/* fall through */1985default:1986 last_errno = errno;1987strbuf_addf(err,"unable to create directory for%s",1988 ref_file.buf);1989goto error_return;1990}19911992if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {1993 last_errno = errno;1994if(errno == ENOENT && --attempts_remaining >0)1995/*1996 * Maybe somebody just deleted one of the1997 * directories leading to ref_file. Try1998 * again:1999 */2000goto retry;2001else{2002unable_to_lock_message(ref_file.buf, errno, err);2003goto error_return;2004}2005}2006if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2007 last_errno = errno;2008goto error_return;2009}2010goto out;20112012 error_return:2013unlock_ref(lock);2014 lock = NULL;20152016 out:2017strbuf_release(&ref_file);2018strbuf_release(&orig_ref_file);2019 errno = last_errno;2020return lock;2021}20222023/*2024 * Write an entry to the packed-refs file for the specified refname.2025 * If peeled is non-NULL, write it as the entry's peeled value.2026 */2027static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2028unsigned char*peeled)2029{2030fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2031if(peeled)2032fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2033}20342035/*2036 * An each_ref_entry_fn that writes the entry to a packed-refs file.2037 */2038static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2039{2040enum peel_status peel_status =peel_entry(entry,0);20412042if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2043error("internal error:%sis not a valid packed reference!",2044 entry->name);2045write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2046 peel_status == PEEL_PEELED ?2047 entry->u.value.peeled.hash : NULL);2048return0;2049}20502051/*2052 * Lock the packed-refs file for writing. Flags is passed to2053 * hold_lock_file_for_update(). Return 0 on success. On errors, set2054 * errno appropriately and return a nonzero value.2055 */2056static intlock_packed_refs(int flags)2057{2058static int timeout_configured =0;2059static int timeout_value =1000;20602061struct packed_ref_cache *packed_ref_cache;20622063if(!timeout_configured) {2064git_config_get_int("core.packedrefstimeout", &timeout_value);2065 timeout_configured =1;2066}20672068if(hold_lock_file_for_update_timeout(2069&packlock,git_path("packed-refs"),2070 flags, timeout_value) <0)2071return-1;2072/*2073 * Get the current packed-refs while holding the lock. If the2074 * packed-refs file has been modified since we last read it,2075 * this will automatically invalidate the cache and re-read2076 * the packed-refs file.2077 */2078 packed_ref_cache =get_packed_ref_cache(&ref_cache);2079 packed_ref_cache->lock = &packlock;2080/* Increment the reference count to prevent it from being freed: */2081acquire_packed_ref_cache(packed_ref_cache);2082return0;2083}20842085/*2086 * Write the current version of the packed refs cache from memory to2087 * disk. The packed-refs file must already be locked for writing (see2088 * lock_packed_refs()). Return zero on success. On errors, set errno2089 * and return a nonzero value2090 */2091static intcommit_packed_refs(void)2092{2093struct packed_ref_cache *packed_ref_cache =2094get_packed_ref_cache(&ref_cache);2095int error =0;2096int save_errno =0;2097FILE*out;20982099if(!packed_ref_cache->lock)2100die("internal error: packed-refs not locked");21012102 out =fdopen_lock_file(packed_ref_cache->lock,"w");2103if(!out)2104die_errno("unable to fdopen packed-refs descriptor");21052106fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2107do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),21080, write_packed_entry_fn, out);21092110if(commit_lock_file(packed_ref_cache->lock)) {2111 save_errno = errno;2112 error = -1;2113}2114 packed_ref_cache->lock = NULL;2115release_packed_ref_cache(packed_ref_cache);2116 errno = save_errno;2117return error;2118}21192120/*2121 * Rollback the lockfile for the packed-refs file, and discard the2122 * in-memory packed reference cache. (The packed-refs file will be2123 * read anew if it is needed again after this function is called.)2124 */2125static voidrollback_packed_refs(void)2126{2127struct packed_ref_cache *packed_ref_cache =2128get_packed_ref_cache(&ref_cache);21292130if(!packed_ref_cache->lock)2131die("internal error: packed-refs not locked");2132rollback_lock_file(packed_ref_cache->lock);2133 packed_ref_cache->lock = NULL;2134release_packed_ref_cache(packed_ref_cache);2135clear_packed_ref_cache(&ref_cache);2136}21372138struct ref_to_prune {2139struct ref_to_prune *next;2140unsigned char sha1[20];2141char name[FLEX_ARRAY];2142};21432144struct pack_refs_cb_data {2145unsigned int flags;2146struct ref_dir *packed_refs;2147struct ref_to_prune *ref_to_prune;2148};21492150/*2151 * An each_ref_entry_fn that is run over loose references only. If2152 * the loose reference can be packed, add an entry in the packed ref2153 * cache. If the reference should be pruned, also add it to2154 * ref_to_prune in the pack_refs_cb_data.2155 */2156static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2157{2158struct pack_refs_cb_data *cb = cb_data;2159enum peel_status peel_status;2160struct ref_entry *packed_entry;2161int is_tag_ref =starts_with(entry->name,"refs/tags/");21622163/* Do not pack per-worktree refs: */2164if(ref_type(entry->name) != REF_TYPE_NORMAL)2165return0;21662167/* ALWAYS pack tags */2168if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2169return0;21702171/* Do not pack symbolic or broken refs: */2172if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2173return0;21742175/* Add a packed ref cache entry equivalent to the loose entry. */2176 peel_status =peel_entry(entry,1);2177if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2178die("internal error peeling reference%s(%s)",2179 entry->name,oid_to_hex(&entry->u.value.oid));2180 packed_entry =find_ref(cb->packed_refs, entry->name);2181if(packed_entry) {2182/* Overwrite existing packed entry with info from loose entry */2183 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2184oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2185}else{2186 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2187 REF_ISPACKED | REF_KNOWS_PEELED,0);2188add_ref(cb->packed_refs, packed_entry);2189}2190oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);21912192/* Schedule the loose reference for pruning if requested. */2193if((cb->flags & PACK_REFS_PRUNE)) {2194int namelen =strlen(entry->name) +1;2195struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2196hashcpy(n->sha1, entry->u.value.oid.hash);2197memcpy(n->name, entry->name, namelen);/* includes NUL */2198 n->next = cb->ref_to_prune;2199 cb->ref_to_prune = n;2200}2201return0;2202}22032204/*2205 * Remove empty parents, but spare refs/ and immediate subdirs.2206 * Note: munges *name.2207 */2208static voidtry_remove_empty_parents(char*name)2209{2210char*p, *q;2211int i;2212 p = name;2213for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2214while(*p && *p !='/')2215 p++;2216/* tolerate duplicate slashes; see check_refname_format() */2217while(*p =='/')2218 p++;2219}2220for(q = p; *q; q++)2221;2222while(1) {2223while(q > p && *q !='/')2224 q--;2225while(q > p && *(q-1) =='/')2226 q--;2227if(q == p)2228break;2229*q ='\0';2230if(rmdir(git_path("%s", name)))2231break;2232}2233}22342235/* make sure nobody touched the ref, and unlink */2236static voidprune_ref(struct ref_to_prune *r)2237{2238struct ref_transaction *transaction;2239struct strbuf err = STRBUF_INIT;22402241if(check_refname_format(r->name,0))2242return;22432244 transaction =ref_transaction_begin(&err);2245if(!transaction ||2246ref_transaction_delete(transaction, r->name, r->sha1,2247 REF_ISPRUNING, NULL, &err) ||2248ref_transaction_commit(transaction, &err)) {2249ref_transaction_free(transaction);2250error("%s", err.buf);2251strbuf_release(&err);2252return;2253}2254ref_transaction_free(transaction);2255strbuf_release(&err);2256try_remove_empty_parents(r->name);2257}22582259static voidprune_refs(struct ref_to_prune *r)2260{2261while(r) {2262prune_ref(r);2263 r = r->next;2264}2265}22662267intpack_refs(unsigned int flags)2268{2269struct pack_refs_cb_data cbdata;22702271memset(&cbdata,0,sizeof(cbdata));2272 cbdata.flags = flags;22732274lock_packed_refs(LOCK_DIE_ON_ERROR);2275 cbdata.packed_refs =get_packed_refs(&ref_cache);22762277do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2278 pack_if_possible_fn, &cbdata);22792280if(commit_packed_refs())2281die_errno("unable to overwrite old ref-pack file");22822283prune_refs(cbdata.ref_to_prune);2284return0;2285}22862287/*2288 * Rewrite the packed-refs file, omitting any refs listed in2289 * 'refnames'. On error, leave packed-refs unchanged, write an error2290 * message to 'err', and return a nonzero value.2291 *2292 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2293 */2294static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2295{2296struct ref_dir *packed;2297struct string_list_item *refname;2298int ret, needs_repacking =0, removed =0;22992300assert(err);23012302/* Look for a packed ref */2303for_each_string_list_item(refname, refnames) {2304if(get_packed_ref(refname->string)) {2305 needs_repacking =1;2306break;2307}2308}23092310/* Avoid locking if we have nothing to do */2311if(!needs_repacking)2312return0;/* no refname exists in packed refs */23132314if(lock_packed_refs(0)) {2315unable_to_lock_message(git_path("packed-refs"), errno, err);2316return-1;2317}2318 packed =get_packed_refs(&ref_cache);23192320/* Remove refnames from the cache */2321for_each_string_list_item(refname, refnames)2322if(remove_entry(packed, refname->string) != -1)2323 removed =1;2324if(!removed) {2325/*2326 * All packed entries disappeared while we were2327 * acquiring the lock.2328 */2329rollback_packed_refs();2330return0;2331}23322333/* Write what remains */2334 ret =commit_packed_refs();2335if(ret)2336strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2337strerror(errno));2338return ret;2339}23402341static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2342{2343assert(err);23442345if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2346/*2347 * loose. The loose file name is the same as the2348 * lockfile name, minus ".lock":2349 */2350char*loose_filename =get_locked_file_path(lock->lk);2351int res =unlink_or_msg(loose_filename, err);2352free(loose_filename);2353if(res)2354return1;2355}2356return0;2357}23582359intdelete_refs(struct string_list *refnames)2360{2361struct strbuf err = STRBUF_INIT;2362int i, result =0;23632364if(!refnames->nr)2365return0;23662367 result =repack_without_refs(refnames, &err);2368if(result) {2369/*2370 * If we failed to rewrite the packed-refs file, then2371 * it is unsafe to try to remove loose refs, because2372 * doing so might expose an obsolete packed value for2373 * a reference that might even point at an object that2374 * has been garbage collected.2375 */2376if(refnames->nr ==1)2377error(_("could not delete reference%s:%s"),2378 refnames->items[0].string, err.buf);2379else2380error(_("could not delete references:%s"), err.buf);23812382goto out;2383}23842385for(i =0; i < refnames->nr; i++) {2386const char*refname = refnames->items[i].string;23872388if(delete_ref(refname, NULL,0))2389 result |=error(_("could not remove reference%s"), refname);2390}23912392out:2393strbuf_release(&err);2394return result;2395}23962397/*2398 * People using contrib's git-new-workdir have .git/logs/refs ->2399 * /some/other/path/.git/logs/refs, and that may live on another device.2400 *2401 * IOW, to avoid cross device rename errors, the temporary renamed log must2402 * live into logs/refs.2403 */2404#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"24052406static intrename_tmp_log(const char*newrefname)2407{2408int attempts_remaining =4;2409struct strbuf path = STRBUF_INIT;2410int ret = -1;24112412 retry:2413strbuf_reset(&path);2414strbuf_git_path(&path,"logs/%s", newrefname);2415switch(safe_create_leading_directories_const(path.buf)) {2416case SCLD_OK:2417break;/* success */2418case SCLD_VANISHED:2419if(--attempts_remaining >0)2420goto retry;2421/* fall through */2422default:2423error("unable to create directory for%s", newrefname);2424goto out;2425}24262427if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2428if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2429/*2430 * rename(a, b) when b is an existing2431 * directory ought to result in ISDIR, but2432 * Solaris 5.8 gives ENOTDIR. Sheesh.2433 */2434if(remove_empty_directories(&path)) {2435error("Directory not empty: logs/%s", newrefname);2436goto out;2437}2438goto retry;2439}else if(errno == ENOENT && --attempts_remaining >0) {2440/*2441 * Maybe another process just deleted one of2442 * the directories in the path to newrefname.2443 * Try again from the beginning.2444 */2445goto retry;2446}else{2447error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2448 newrefname,strerror(errno));2449goto out;2450}2451}2452 ret =0;2453out:2454strbuf_release(&path);2455return ret;2456}24572458intverify_refname_available(const char*newname,2459struct string_list *extras,2460struct string_list *skip,2461struct strbuf *err)2462{2463struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2464struct ref_dir *loose_refs =get_loose_refs(&ref_cache);24652466if(verify_refname_available_dir(newname, extras, skip,2467 packed_refs, err) ||2468verify_refname_available_dir(newname, extras, skip,2469 loose_refs, err))2470return-1;24712472return0;2473}24742475static intwrite_ref_to_lockfile(struct ref_lock *lock,2476const unsigned char*sha1,struct strbuf *err);2477static intcommit_ref_update(struct ref_lock *lock,2478const unsigned char*sha1,const char*logmsg,2479int flags,struct strbuf *err);24802481intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2482{2483unsigned char sha1[20], orig_sha1[20];2484int flag =0, logmoved =0;2485struct ref_lock *lock;2486struct stat loginfo;2487int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2488const char*symref = NULL;2489struct strbuf err = STRBUF_INIT;24902491if(log &&S_ISLNK(loginfo.st_mode))2492returnerror("reflog for%sis a symlink", oldrefname);24932494 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2495 orig_sha1, &flag);2496if(flag & REF_ISSYMREF)2497returnerror("refname%sis a symbolic ref, renaming it is not supported",2498 oldrefname);2499if(!symref)2500returnerror("refname%snot found", oldrefname);25012502if(!rename_ref_available(oldrefname, newrefname))2503return1;25042505if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2506returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2507 oldrefname,strerror(errno));25082509if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2510error("unable to delete old%s", oldrefname);2511goto rollback;2512}25132514if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2515delete_ref(newrefname, sha1, REF_NODEREF)) {2516if(errno==EISDIR) {2517struct strbuf path = STRBUF_INIT;2518int result;25192520strbuf_git_path(&path,"%s", newrefname);2521 result =remove_empty_directories(&path);2522strbuf_release(&path);25232524if(result) {2525error("Directory not empty:%s", newrefname);2526goto rollback;2527}2528}else{2529error("unable to delete existing%s", newrefname);2530goto rollback;2531}2532}25332534if(log &&rename_tmp_log(newrefname))2535goto rollback;25362537 logmoved = log;25382539 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2540if(!lock) {2541error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2542strbuf_release(&err);2543goto rollback;2544}2545hashcpy(lock->old_oid.hash, orig_sha1);25462547if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2548commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2549error("unable to write current sha1 into%s:%s", newrefname, err.buf);2550strbuf_release(&err);2551goto rollback;2552}25532554return0;25552556 rollback:2557 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2558if(!lock) {2559error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2560strbuf_release(&err);2561goto rollbacklog;2562}25632564 flag = log_all_ref_updates;2565 log_all_ref_updates =0;2566if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2567commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2568error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2569strbuf_release(&err);2570}2571 log_all_ref_updates = flag;25722573 rollbacklog:2574if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2575error("unable to restore logfile%sfrom%s:%s",2576 oldrefname, newrefname,strerror(errno));2577if(!logmoved && log &&2578rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2579error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2580 oldrefname,strerror(errno));25812582return1;2583}25842585static intclose_ref(struct ref_lock *lock)2586{2587if(close_lock_file(lock->lk))2588return-1;2589return0;2590}25912592static intcommit_ref(struct ref_lock *lock)2593{2594if(commit_lock_file(lock->lk))2595return-1;2596return0;2597}25982599/*2600 * Create a reflog for a ref. If force_create = 0, the reflog will2601 * only be created for certain refs (those for which2602 * should_autocreate_reflog returns non-zero. Otherwise, create it2603 * regardless of the ref name. Fill in *err and return -1 on failure.2604 */2605static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2606{2607int logfd, oflags = O_APPEND | O_WRONLY;26082609strbuf_git_path(logfile,"logs/%s", refname);2610if(force_create ||should_autocreate_reflog(refname)) {2611if(safe_create_leading_directories(logfile->buf) <0) {2612strbuf_addf(err,"unable to create directory for%s: "2613"%s", logfile->buf,strerror(errno));2614return-1;2615}2616 oflags |= O_CREAT;2617}26182619 logfd =open(logfile->buf, oflags,0666);2620if(logfd <0) {2621if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2622return0;26232624if(errno == EISDIR) {2625if(remove_empty_directories(logfile)) {2626strbuf_addf(err,"There are still logs under "2627"'%s'", logfile->buf);2628return-1;2629}2630 logfd =open(logfile->buf, oflags,0666);2631}26322633if(logfd <0) {2634strbuf_addf(err,"unable to append to%s:%s",2635 logfile->buf,strerror(errno));2636return-1;2637}2638}26392640adjust_shared_perm(logfile->buf);2641close(logfd);2642return0;2643}264426452646intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2647{2648int ret;2649struct strbuf sb = STRBUF_INIT;26502651 ret =log_ref_setup(refname, &sb, err, force_create);2652strbuf_release(&sb);2653return ret;2654}26552656static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2657const unsigned char*new_sha1,2658const char*committer,const char*msg)2659{2660int msglen, written;2661unsigned maxlen, len;2662char*logrec;26632664 msglen = msg ?strlen(msg) :0;2665 maxlen =strlen(committer) + msglen +100;2666 logrec =xmalloc(maxlen);2667 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2668sha1_to_hex(old_sha1),2669sha1_to_hex(new_sha1),2670 committer);2671if(msglen)2672 len +=copy_reflog_msg(logrec + len -1, msg) -1;26732674 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2675free(logrec);2676if(written != len)2677return-1;26782679return0;2680}26812682static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2683const unsigned char*new_sha1,const char*msg,2684struct strbuf *logfile,int flags,2685struct strbuf *err)2686{2687int logfd, result, oflags = O_APPEND | O_WRONLY;26882689if(log_all_ref_updates <0)2690 log_all_ref_updates = !is_bare_repository();26912692 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);26932694if(result)2695return result;26962697 logfd =open(logfile->buf, oflags);2698if(logfd <0)2699return0;2700 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2701git_committer_info(0), msg);2702if(result) {2703strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2704strerror(errno));2705close(logfd);2706return-1;2707}2708if(close(logfd)) {2709strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2710strerror(errno));2711return-1;2712}2713return0;2714}27152716static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2717const unsigned char*new_sha1,const char*msg,2718int flags,struct strbuf *err)2719{2720returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2721 err);2722}27232724intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2725const unsigned char*new_sha1,const char*msg,2726int flags,struct strbuf *err)2727{2728struct strbuf sb = STRBUF_INIT;2729int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2730 err);2731strbuf_release(&sb);2732return ret;2733}27342735/*2736 * Write sha1 into the open lockfile, then close the lockfile. On2737 * errors, rollback the lockfile, fill in *err and2738 * return -1.2739 */2740static intwrite_ref_to_lockfile(struct ref_lock *lock,2741const unsigned char*sha1,struct strbuf *err)2742{2743static char term ='\n';2744struct object *o;2745int fd;27462747 o =parse_object(sha1);2748if(!o) {2749strbuf_addf(err,2750"Trying to write ref%swith nonexistent object%s",2751 lock->ref_name,sha1_to_hex(sha1));2752unlock_ref(lock);2753return-1;2754}2755if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2756strbuf_addf(err,2757"Trying to write non-commit object%sto branch%s",2758sha1_to_hex(sha1), lock->ref_name);2759unlock_ref(lock);2760return-1;2761}2762 fd =get_lock_file_fd(lock->lk);2763if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2764write_in_full(fd, &term,1) !=1||2765close_ref(lock) <0) {2766strbuf_addf(err,2767"Couldn't write%s",get_lock_file_path(lock->lk));2768unlock_ref(lock);2769return-1;2770}2771return0;2772}27732774/*2775 * Commit a change to a loose reference that has already been written2776 * to the loose reference lockfile. Also update the reflogs if2777 * necessary, using the specified lockmsg (which can be NULL).2778 */2779static intcommit_ref_update(struct ref_lock *lock,2780const unsigned char*sha1,const char*logmsg,2781int flags,struct strbuf *err)2782{2783clear_loose_ref_cache(&ref_cache);2784if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2785(strcmp(lock->ref_name, lock->orig_ref_name) &&2786log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2787char*old_msg =strbuf_detach(err, NULL);2788strbuf_addf(err,"Cannot update the ref '%s':%s",2789 lock->ref_name, old_msg);2790free(old_msg);2791unlock_ref(lock);2792return-1;2793}2794if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2795/*2796 * Special hack: If a branch is updated directly and HEAD2797 * points to it (may happen on the remote side of a push2798 * for example) then logically the HEAD reflog should be2799 * updated too.2800 * A generic solution implies reverse symref information,2801 * but finding all symrefs pointing to the given branch2802 * would be rather costly for this rare event (the direct2803 * update of a branch) to be worth it. So let's cheat and2804 * check with HEAD only which should cover 99% of all usage2805 * scenarios (even 100% of the default ones).2806 */2807unsigned char head_sha1[20];2808int head_flag;2809const char*head_ref;2810 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2811 head_sha1, &head_flag);2812if(head_ref && (head_flag & REF_ISSYMREF) &&2813!strcmp(head_ref, lock->ref_name)) {2814struct strbuf log_err = STRBUF_INIT;2815if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2816 logmsg,0, &log_err)) {2817error("%s", log_err.buf);2818strbuf_release(&log_err);2819}2820}2821}2822if(commit_ref(lock)) {2823error("Couldn't set%s", lock->ref_name);2824unlock_ref(lock);2825return-1;2826}28272828unlock_ref(lock);2829return0;2830}28312832intcreate_symref(const char*ref_target,const char*refs_heads_master,2833const char*logmsg)2834{2835char*lockpath = NULL;2836char ref[1000];2837int fd, len, written;2838char*git_HEAD =git_pathdup("%s", ref_target);2839unsigned char old_sha1[20], new_sha1[20];2840struct strbuf err = STRBUF_INIT;28412842if(logmsg &&read_ref(ref_target, old_sha1))2843hashclr(old_sha1);28442845if(safe_create_leading_directories(git_HEAD) <0)2846returnerror("unable to create directory for%s", git_HEAD);28472848#ifndef NO_SYMLINK_HEAD2849if(prefer_symlink_refs) {2850unlink(git_HEAD);2851if(!symlink(refs_heads_master, git_HEAD))2852goto done;2853fprintf(stderr,"no symlink - falling back to symbolic ref\n");2854}2855#endif28562857 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);2858if(sizeof(ref) <= len) {2859error("refname too long:%s", refs_heads_master);2860goto error_free_return;2861}2862 lockpath =mkpathdup("%s.lock", git_HEAD);2863 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);2864if(fd <0) {2865error("Unable to open%sfor writing", lockpath);2866goto error_free_return;2867}2868 written =write_in_full(fd, ref, len);2869if(close(fd) !=0|| written != len) {2870error("Unable to write to%s", lockpath);2871goto error_unlink_return;2872}2873if(rename(lockpath, git_HEAD) <0) {2874error("Unable to create%s", git_HEAD);2875goto error_unlink_return;2876}2877if(adjust_shared_perm(git_HEAD)) {2878error("Unable to fix permissions on%s", lockpath);2879 error_unlink_return:2880unlink_or_warn(lockpath);2881 error_free_return:2882free(lockpath);2883free(git_HEAD);2884return-1;2885}2886free(lockpath);28872888#ifndef NO_SYMLINK_HEAD2889 done:2890#endif2891if(logmsg && !read_ref(refs_heads_master, new_sha1) &&2892log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {2893error("%s", err.buf);2894strbuf_release(&err);2895}28962897free(git_HEAD);2898return0;2899}29002901intreflog_exists(const char*refname)2902{2903struct stat st;29042905return!lstat(git_path("logs/%s", refname), &st) &&2906S_ISREG(st.st_mode);2907}29082909intdelete_reflog(const char*refname)2910{2911returnremove_path(git_path("logs/%s", refname));2912}29132914static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2915{2916unsigned char osha1[20], nsha1[20];2917char*email_end, *message;2918unsigned long timestamp;2919int tz;29202921/* old SP new SP name <email> SP time TAB msg LF */2922if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2923get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2924get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2925!(email_end =strchr(sb->buf +82,'>')) ||2926 email_end[1] !=' '||2927!(timestamp =strtoul(email_end +2, &message,10)) ||2928!message || message[0] !=' '||2929(message[1] !='+'&& message[1] !='-') ||2930!isdigit(message[2]) || !isdigit(message[3]) ||2931!isdigit(message[4]) || !isdigit(message[5]))2932return0;/* corrupt? */2933 email_end[1] ='\0';2934 tz =strtol(message +1, NULL,10);2935if(message[6] !='\t')2936 message +=6;2937else2938 message +=7;2939returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2940}29412942static char*find_beginning_of_line(char*bob,char*scan)2943{2944while(bob < scan && *(--scan) !='\n')2945;/* keep scanning backwards */2946/*2947 * Return either beginning of the buffer, or LF at the end of2948 * the previous line.2949 */2950return scan;2951}29522953intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2954{2955struct strbuf sb = STRBUF_INIT;2956FILE*logfp;2957long pos;2958int ret =0, at_tail =1;29592960 logfp =fopen(git_path("logs/%s", refname),"r");2961if(!logfp)2962return-1;29632964/* Jump to the end */2965if(fseek(logfp,0, SEEK_END) <0)2966returnerror("cannot seek back reflog for%s:%s",2967 refname,strerror(errno));2968 pos =ftell(logfp);2969while(!ret &&0< pos) {2970int cnt;2971size_t nread;2972char buf[BUFSIZ];2973char*endp, *scanp;29742975/* Fill next block from the end */2976 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2977if(fseek(logfp, pos - cnt, SEEK_SET))2978returnerror("cannot seek back reflog for%s:%s",2979 refname,strerror(errno));2980 nread =fread(buf, cnt,1, logfp);2981if(nread !=1)2982returnerror("cannot read%dbytes from reflog for%s:%s",2983 cnt, refname,strerror(errno));2984 pos -= cnt;29852986 scanp = endp = buf + cnt;2987if(at_tail && scanp[-1] =='\n')2988/* Looking at the final LF at the end of the file */2989 scanp--;2990 at_tail =0;29912992while(buf < scanp) {2993/*2994 * terminating LF of the previous line, or the beginning2995 * of the buffer.2996 */2997char*bp;29982999 bp =find_beginning_of_line(buf, scanp);30003001if(*bp =='\n') {3002/*3003 * The newline is the end of the previous line,3004 * so we know we have complete line starting3005 * at (bp + 1). Prefix it onto any prior data3006 * we collected for the line and process it.3007 */3008strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3009 scanp = bp;3010 endp = bp +1;3011 ret =show_one_reflog_ent(&sb, fn, cb_data);3012strbuf_reset(&sb);3013if(ret)3014break;3015}else if(!pos) {3016/*3017 * We are at the start of the buffer, and the3018 * start of the file; there is no previous3019 * line, and we have everything for this one.3020 * Process it, and we can end the loop.3021 */3022strbuf_splice(&sb,0,0, buf, endp - buf);3023 ret =show_one_reflog_ent(&sb, fn, cb_data);3024strbuf_reset(&sb);3025break;3026}30273028if(bp == buf) {3029/*3030 * We are at the start of the buffer, and there3031 * is more file to read backwards. Which means3032 * we are in the middle of a line. Note that we3033 * may get here even if *bp was a newline; that3034 * just means we are at the exact end of the3035 * previous line, rather than some spot in the3036 * middle.3037 *3038 * Save away what we have to be combined with3039 * the data from the next read.3040 */3041strbuf_splice(&sb,0,0, buf, endp - buf);3042break;3043}3044}30453046}3047if(!ret && sb.len)3048die("BUG: reverse reflog parser had leftover data");30493050fclose(logfp);3051strbuf_release(&sb);3052return ret;3053}30543055intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3056{3057FILE*logfp;3058struct strbuf sb = STRBUF_INIT;3059int ret =0;30603061 logfp =fopen(git_path("logs/%s", refname),"r");3062if(!logfp)3063return-1;30643065while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3066 ret =show_one_reflog_ent(&sb, fn, cb_data);3067fclose(logfp);3068strbuf_release(&sb);3069return ret;3070}3071/*3072 * Call fn for each reflog in the namespace indicated by name. name3073 * must be empty or end with '/'. Name will be used as a scratch3074 * space, but its contents will be restored before return.3075 */3076static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3077{3078DIR*d =opendir(git_path("logs/%s", name->buf));3079int retval =0;3080struct dirent *de;3081int oldlen = name->len;30823083if(!d)3084return name->len ? errno :0;30853086while((de =readdir(d)) != NULL) {3087struct stat st;30883089if(de->d_name[0] =='.')3090continue;3091if(ends_with(de->d_name,".lock"))3092continue;3093strbuf_addstr(name, de->d_name);3094if(stat(git_path("logs/%s", name->buf), &st) <0) {3095;/* silently ignore */3096}else{3097if(S_ISDIR(st.st_mode)) {3098strbuf_addch(name,'/');3099 retval =do_for_each_reflog(name, fn, cb_data);3100}else{3101struct object_id oid;31023103if(read_ref_full(name->buf,0, oid.hash, NULL))3104 retval =error("bad ref for%s", name->buf);3105else3106 retval =fn(name->buf, &oid,0, cb_data);3107}3108if(retval)3109break;3110}3111strbuf_setlen(name, oldlen);3112}3113closedir(d);3114return retval;3115}31163117intfor_each_reflog(each_ref_fn fn,void*cb_data)3118{3119int retval;3120struct strbuf name;3121strbuf_init(&name, PATH_MAX);3122 retval =do_for_each_reflog(&name, fn, cb_data);3123strbuf_release(&name);3124return retval;3125}31263127static intref_update_reject_duplicates(struct string_list *refnames,3128struct strbuf *err)3129{3130int i, n = refnames->nr;31313132assert(err);31333134for(i =1; i < n; i++)3135if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3136strbuf_addf(err,3137"Multiple updates for ref '%s' not allowed.",3138 refnames->items[i].string);3139return1;3140}3141return0;3142}31433144intref_transaction_commit(struct ref_transaction *transaction,3145struct strbuf *err)3146{3147int ret =0, i;3148int n = transaction->nr;3149struct ref_update **updates = transaction->updates;3150struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3151struct string_list_item *ref_to_delete;3152struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31533154assert(err);31553156if(transaction->state != REF_TRANSACTION_OPEN)3157die("BUG: commit called for transaction that is not open");31583159if(!n) {3160 transaction->state = REF_TRANSACTION_CLOSED;3161return0;3162}31633164/* Fail if a refname appears more than once in the transaction: */3165for(i =0; i < n; i++)3166string_list_append(&affected_refnames, updates[i]->refname);3167string_list_sort(&affected_refnames);3168if(ref_update_reject_duplicates(&affected_refnames, err)) {3169 ret = TRANSACTION_GENERIC_ERROR;3170goto cleanup;3171}31723173/*3174 * Acquire all locks, verify old values if provided, check3175 * that new values are valid, and write new values to the3176 * lockfiles, ready to be activated. Only keep one lockfile3177 * open at a time to avoid running out of file descriptors.3178 */3179for(i =0; i < n; i++) {3180struct ref_update *update = updates[i];31813182if((update->flags & REF_HAVE_NEW) &&3183is_null_sha1(update->new_sha1))3184 update->flags |= REF_DELETING;3185 update->lock =lock_ref_sha1_basic(3186 update->refname,3187((update->flags & REF_HAVE_OLD) ?3188 update->old_sha1 : NULL),3189&affected_refnames, NULL,3190 update->flags,3191&update->type,3192 err);3193if(!update->lock) {3194char*reason;31953196 ret = (errno == ENOTDIR)3197? TRANSACTION_NAME_CONFLICT3198: TRANSACTION_GENERIC_ERROR;3199 reason =strbuf_detach(err, NULL);3200strbuf_addf(err,"cannot lock ref '%s':%s",3201 update->refname, reason);3202free(reason);3203goto cleanup;3204}3205if((update->flags & REF_HAVE_NEW) &&3206!(update->flags & REF_DELETING)) {3207int overwriting_symref = ((update->type & REF_ISSYMREF) &&3208(update->flags & REF_NODEREF));32093210if(!overwriting_symref &&3211!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3212/*3213 * The reference already has the desired3214 * value, so we don't need to write it.3215 */3216}else if(write_ref_to_lockfile(update->lock,3217 update->new_sha1,3218 err)) {3219char*write_err =strbuf_detach(err, NULL);32203221/*3222 * The lock was freed upon failure of3223 * write_ref_to_lockfile():3224 */3225 update->lock = NULL;3226strbuf_addf(err,3227"cannot update the ref '%s':%s",3228 update->refname, write_err);3229free(write_err);3230 ret = TRANSACTION_GENERIC_ERROR;3231goto cleanup;3232}else{3233 update->flags |= REF_NEEDS_COMMIT;3234}3235}3236if(!(update->flags & REF_NEEDS_COMMIT)) {3237/*3238 * We didn't have to write anything to the lockfile.3239 * Close it to free up the file descriptor:3240 */3241if(close_ref(update->lock)) {3242strbuf_addf(err,"Couldn't close%s.lock",3243 update->refname);3244goto cleanup;3245}3246}3247}32483249/* Perform updates first so live commits remain referenced */3250for(i =0; i < n; i++) {3251struct ref_update *update = updates[i];32523253if(update->flags & REF_NEEDS_COMMIT) {3254if(commit_ref_update(update->lock,3255 update->new_sha1, update->msg,3256 update->flags, err)) {3257/* freed by commit_ref_update(): */3258 update->lock = NULL;3259 ret = TRANSACTION_GENERIC_ERROR;3260goto cleanup;3261}else{3262/* freed by commit_ref_update(): */3263 update->lock = NULL;3264}3265}3266}32673268/* Perform deletes now that updates are safely completed */3269for(i =0; i < n; i++) {3270struct ref_update *update = updates[i];32713272if(update->flags & REF_DELETING) {3273if(delete_ref_loose(update->lock, update->type, err)) {3274 ret = TRANSACTION_GENERIC_ERROR;3275goto cleanup;3276}32773278if(!(update->flags & REF_ISPRUNING))3279string_list_append(&refs_to_delete,3280 update->lock->ref_name);3281}3282}32833284if(repack_without_refs(&refs_to_delete, err)) {3285 ret = TRANSACTION_GENERIC_ERROR;3286goto cleanup;3287}3288for_each_string_list_item(ref_to_delete, &refs_to_delete)3289unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3290clear_loose_ref_cache(&ref_cache);32913292cleanup:3293 transaction->state = REF_TRANSACTION_CLOSED;32943295for(i =0; i < n; i++)3296if(updates[i]->lock)3297unlock_ref(updates[i]->lock);3298string_list_clear(&refs_to_delete,0);3299string_list_clear(&affected_refnames,0);3300return ret;3301}33023303static intref_present(const char*refname,3304const struct object_id *oid,int flags,void*cb_data)3305{3306struct string_list *affected_refnames = cb_data;33073308returnstring_list_has_string(affected_refnames, refname);3309}33103311intinitial_ref_transaction_commit(struct ref_transaction *transaction,3312struct strbuf *err)3313{3314int ret =0, i;3315int n = transaction->nr;3316struct ref_update **updates = transaction->updates;3317struct string_list affected_refnames = STRING_LIST_INIT_NODUP;33183319assert(err);33203321if(transaction->state != REF_TRANSACTION_OPEN)3322die("BUG: commit called for transaction that is not open");33233324/* Fail if a refname appears more than once in the transaction: */3325for(i =0; i < n; i++)3326string_list_append(&affected_refnames, updates[i]->refname);3327string_list_sort(&affected_refnames);3328if(ref_update_reject_duplicates(&affected_refnames, err)) {3329 ret = TRANSACTION_GENERIC_ERROR;3330goto cleanup;3331}33323333/*3334 * It's really undefined to call this function in an active3335 * repository or when there are existing references: we are3336 * only locking and changing packed-refs, so (1) any3337 * simultaneous processes might try to change a reference at3338 * the same time we do, and (2) any existing loose versions of3339 * the references that we are setting would have precedence3340 * over our values. But some remote helpers create the remote3341 * "HEAD" and "master" branches before calling this function,3342 * so here we really only check that none of the references3343 * that we are creating already exists.3344 */3345if(for_each_rawref(ref_present, &affected_refnames))3346die("BUG: initial ref transaction called with existing refs");33473348for(i =0; i < n; i++) {3349struct ref_update *update = updates[i];33503351if((update->flags & REF_HAVE_OLD) &&3352!is_null_sha1(update->old_sha1))3353die("BUG: initial ref transaction with old_sha1 set");3354if(verify_refname_available(update->refname,3355&affected_refnames, NULL,3356 err)) {3357 ret = TRANSACTION_NAME_CONFLICT;3358goto cleanup;3359}3360}33613362if(lock_packed_refs(0)) {3363strbuf_addf(err,"unable to lock packed-refs file:%s",3364strerror(errno));3365 ret = TRANSACTION_GENERIC_ERROR;3366goto cleanup;3367}33683369for(i =0; i < n; i++) {3370struct ref_update *update = updates[i];33713372if((update->flags & REF_HAVE_NEW) &&3373!is_null_sha1(update->new_sha1))3374add_packed_ref(update->refname, update->new_sha1);3375}33763377if(commit_packed_refs()) {3378strbuf_addf(err,"unable to commit packed-refs file:%s",3379strerror(errno));3380 ret = TRANSACTION_GENERIC_ERROR;3381goto cleanup;3382}33833384cleanup:3385 transaction->state = REF_TRANSACTION_CLOSED;3386string_list_clear(&affected_refnames,0);3387return ret;3388}33893390struct expire_reflog_cb {3391unsigned int flags;3392 reflog_expiry_should_prune_fn *should_prune_fn;3393void*policy_cb;3394FILE*newlog;3395unsigned char last_kept_sha1[20];3396};33973398static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3399const char*email,unsigned long timestamp,int tz,3400const char*message,void*cb_data)3401{3402struct expire_reflog_cb *cb = cb_data;3403struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;34043405if(cb->flags & EXPIRE_REFLOGS_REWRITE)3406 osha1 = cb->last_kept_sha1;34073408if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3409 message, policy_cb)) {3410if(!cb->newlog)3411printf("would prune%s", message);3412else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3413printf("prune%s", message);3414}else{3415if(cb->newlog) {3416fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3417sha1_to_hex(osha1),sha1_to_hex(nsha1),3418 email, timestamp, tz, message);3419hashcpy(cb->last_kept_sha1, nsha1);3420}3421if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3422printf("keep%s", message);3423}3424return0;3425}34263427intreflog_expire(const char*refname,const unsigned char*sha1,3428unsigned int flags,3429 reflog_expiry_prepare_fn prepare_fn,3430 reflog_expiry_should_prune_fn should_prune_fn,3431 reflog_expiry_cleanup_fn cleanup_fn,3432void*policy_cb_data)3433{3434static struct lock_file reflog_lock;3435struct expire_reflog_cb cb;3436struct ref_lock *lock;3437char*log_file;3438int status =0;3439int type;3440struct strbuf err = STRBUF_INIT;34413442memset(&cb,0,sizeof(cb));3443 cb.flags = flags;3444 cb.policy_cb = policy_cb_data;3445 cb.should_prune_fn = should_prune_fn;34463447/*3448 * The reflog file is locked by holding the lock on the3449 * reference itself, plus we might need to update the3450 * reference if --updateref was specified:3451 */3452 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);3453if(!lock) {3454error("cannot lock ref '%s':%s", refname, err.buf);3455strbuf_release(&err);3456return-1;3457}3458if(!reflog_exists(refname)) {3459unlock_ref(lock);3460return0;3461}34623463 log_file =git_pathdup("logs/%s", refname);3464if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3465/*3466 * Even though holding $GIT_DIR/logs/$reflog.lock has3467 * no locking implications, we use the lock_file3468 * machinery here anyway because it does a lot of the3469 * work we need, including cleaning up if the program3470 * exits unexpectedly.3471 */3472if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3473struct strbuf err = STRBUF_INIT;3474unable_to_lock_message(log_file, errno, &err);3475error("%s", err.buf);3476strbuf_release(&err);3477goto failure;3478}3479 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3480if(!cb.newlog) {3481error("cannot fdopen%s(%s)",3482get_lock_file_path(&reflog_lock),strerror(errno));3483goto failure;3484}3485}34863487(*prepare_fn)(refname, sha1, cb.policy_cb);3488for_each_reflog_ent(refname, expire_reflog_ent, &cb);3489(*cleanup_fn)(cb.policy_cb);34903491if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3492/*3493 * It doesn't make sense to adjust a reference pointed3494 * to by a symbolic ref based on expiring entries in3495 * the symbolic reference's reflog. Nor can we update3496 * a reference if there are no remaining reflog3497 * entries.3498 */3499int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3500!(type & REF_ISSYMREF) &&3501!is_null_sha1(cb.last_kept_sha1);35023503if(close_lock_file(&reflog_lock)) {3504 status |=error("couldn't write%s:%s", log_file,3505strerror(errno));3506}else if(update &&3507(write_in_full(get_lock_file_fd(lock->lk),3508sha1_to_hex(cb.last_kept_sha1),40) !=40||3509write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3510close_ref(lock) <0)) {3511 status |=error("couldn't write%s",3512get_lock_file_path(lock->lk));3513rollback_lock_file(&reflog_lock);3514}else if(commit_lock_file(&reflog_lock)) {3515 status |=error("unable to write reflog '%s' (%s)",3516 log_file,strerror(errno));3517}else if(update &&commit_ref(lock)) {3518 status |=error("couldn't set%s", lock->ref_name);3519}3520}3521free(log_file);3522unlock_ref(lock);3523return status;35243525 failure:3526rollback_lock_file(&reflog_lock);3527free(log_file);3528unlock_ref(lock);3529return-1;3530}