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; 731int pos; 732struct strbuf dirname = STRBUF_INIT; 733int ret = -1; 734 735/* 736 * For the sake of comments in this function, suppose that 737 * refname is "refs/foo/bar". 738 */ 739 740assert(err); 741 742strbuf_grow(&dirname,strlen(refname) +1); 743for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 744/* Expand dirname to the new prefix, not including the trailing slash: */ 745strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 746 747/* 748 * We are still at a leading dir of the refname (e.g., 749 * "refs/foo"; if there is a reference with that name, 750 * it is a conflict, *unless* it is in skip. 751 */ 752if(dir) { 753 pos =search_ref_dir(dir, dirname.buf, dirname.len); 754if(pos >=0&& 755(!skip || !string_list_has_string(skip, dirname.buf))) { 756/* 757 * We found a reference whose name is 758 * a proper prefix of refname; e.g., 759 * "refs/foo", and is not in skip. 760 */ 761strbuf_addf(err,"'%s' exists; cannot create '%s'", 762 dirname.buf, refname); 763goto cleanup; 764} 765} 766 767if(extras &&string_list_has_string(extras, dirname.buf) && 768(!skip || !string_list_has_string(skip, dirname.buf))) { 769strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 770 refname, dirname.buf); 771goto cleanup; 772} 773 774/* 775 * Otherwise, we can try to continue our search with 776 * the next component. So try to look up the 777 * directory, e.g., "refs/foo/". If we come up empty, 778 * we know there is nothing under this whole prefix, 779 * but even in that case we still have to continue the 780 * search for conflicts with extras. 781 */ 782strbuf_addch(&dirname,'/'); 783if(dir) { 784 pos =search_ref_dir(dir, dirname.buf, dirname.len); 785if(pos <0) { 786/* 787 * There was no directory "refs/foo/", 788 * so there is nothing under this 789 * whole prefix. So there is no need 790 * to continue looking for conflicting 791 * references. But we need to continue 792 * looking for conflicting extras. 793 */ 794 dir = NULL; 795}else{ 796 dir =get_ref_dir(dir->entries[pos]); 797} 798} 799} 800 801/* 802 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 803 * There is no point in searching for a reference with that 804 * name, because a refname isn't considered to conflict with 805 * itself. But we still need to check for references whose 806 * names are in the "refs/foo/bar/" namespace, because they 807 * *do* conflict. 808 */ 809strbuf_addstr(&dirname, refname + dirname.len); 810strbuf_addch(&dirname,'/'); 811 812if(dir) { 813 pos =search_ref_dir(dir, dirname.buf, dirname.len); 814 815if(pos >=0) { 816/* 817 * We found a directory named "$refname/" 818 * (e.g., "refs/foo/bar/"). It is a problem 819 * iff it contains any ref that is not in 820 * "skip". 821 */ 822struct nonmatching_ref_data data; 823 824 data.skip = skip; 825 data.conflicting_refname = NULL; 826 dir =get_ref_dir(dir->entries[pos]); 827sort_ref_dir(dir); 828if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 829strbuf_addf(err,"'%s' exists; cannot create '%s'", 830 data.conflicting_refname, refname); 831goto cleanup; 832} 833} 834} 835 836if(extras) { 837/* 838 * Check for entries in extras that start with 839 * "$refname/". We do that by looking for the place 840 * where "$refname/" would be inserted in extras. If 841 * there is an entry at that position that starts with 842 * "$refname/" and is not in skip, then we have a 843 * conflict. 844 */ 845for(pos =string_list_find_insert_index(extras, dirname.buf,0); 846 pos < extras->nr; pos++) { 847const char*extra_refname = extras->items[pos].string; 848 849if(!starts_with(extra_refname, dirname.buf)) 850break; 851 852if(!skip || !string_list_has_string(skip, extra_refname)) { 853strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 854 refname, extra_refname); 855goto cleanup; 856} 857} 858} 859 860/* No conflicts were found */ 861 ret =0; 862 863cleanup: 864strbuf_release(&dirname); 865return ret; 866} 867 868struct packed_ref_cache { 869struct ref_entry *root; 870 871/* 872 * Count of references to the data structure in this instance, 873 * including the pointer from ref_cache::packed if any. The 874 * data will not be freed as long as the reference count is 875 * nonzero. 876 */ 877unsigned int referrers; 878 879/* 880 * Iff the packed-refs file associated with this instance is 881 * currently locked for writing, this points at the associated 882 * lock (which is owned by somebody else). The referrer count 883 * is also incremented when the file is locked and decremented 884 * when it is unlocked. 885 */ 886struct lock_file *lock; 887 888/* The metadata from when this packed-refs cache was read */ 889struct stat_validity validity; 890}; 891 892/* 893 * Future: need to be in "struct repository" 894 * when doing a full libification. 895 */ 896static struct ref_cache { 897struct ref_cache *next; 898struct ref_entry *loose; 899struct packed_ref_cache *packed; 900/* 901 * The submodule name, or "" for the main repo. We allocate 902 * length 1 rather than FLEX_ARRAY so that the main ref_cache 903 * is initialized correctly. 904 */ 905char name[1]; 906} ref_cache, *submodule_ref_caches; 907 908/* Lock used for the main packed-refs file: */ 909static struct lock_file packlock; 910 911/* 912 * Increment the reference count of *packed_refs. 913 */ 914static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 915{ 916 packed_refs->referrers++; 917} 918 919/* 920 * Decrease the reference count of *packed_refs. If it goes to zero, 921 * free *packed_refs and return true; otherwise return false. 922 */ 923static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 924{ 925if(!--packed_refs->referrers) { 926free_ref_entry(packed_refs->root); 927stat_validity_clear(&packed_refs->validity); 928free(packed_refs); 929return1; 930}else{ 931return0; 932} 933} 934 935static voidclear_packed_ref_cache(struct ref_cache *refs) 936{ 937if(refs->packed) { 938struct packed_ref_cache *packed_refs = refs->packed; 939 940if(packed_refs->lock) 941die("internal error: packed-ref cache cleared while locked"); 942 refs->packed = NULL; 943release_packed_ref_cache(packed_refs); 944} 945} 946 947static voidclear_loose_ref_cache(struct ref_cache *refs) 948{ 949if(refs->loose) { 950free_ref_entry(refs->loose); 951 refs->loose = NULL; 952} 953} 954 955static struct ref_cache *create_ref_cache(const char*submodule) 956{ 957int len; 958struct ref_cache *refs; 959if(!submodule) 960 submodule =""; 961 len =strlen(submodule) +1; 962 refs =xcalloc(1,sizeof(struct ref_cache) + len); 963memcpy(refs->name, submodule, len); 964return refs; 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; 976 977if(!submodule || !*submodule) 978return&ref_cache; 979 980for(refs = submodule_ref_caches; refs; refs = refs->next) 981if(!strcmp(submodule, refs->name)) 982return refs; 983 984 refs =create_ref_cache(submodule); 985 refs->next = submodule_ref_caches; 986 submodule_ref_caches = refs; 987return refs; 988} 989 990/* The length of a peeled reference line in packed-refs, including EOL: */ 991#define PEELED_LINE_LENGTH 42 992 993/* 994 * The packed-refs header line that we write out. Perhaps other 995 * traits will be added later. The trailing space is required. 996 */ 997static const char PACKED_REFS_HEADER[] = 998"# pack-refs with: peeled fully-peeled\n"; 9991000/*1001 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1002 * Return a pointer to the refname within the line (null-terminated),1003 * or NULL if there was a problem.1004 */1005static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1006{1007const char*ref;10081009/*1010 * 42: the answer to everything.1011 *1012 * In this case, it happens to be the answer to1013 * 40 (length of sha1 hex representation)1014 * +1 (space in between hex and name)1015 * +1 (newline at the end of the line)1016 */1017if(line->len <=42)1018return NULL;10191020if(get_sha1_hex(line->buf, sha1) <0)1021return NULL;1022if(!isspace(line->buf[40]))1023return NULL;10241025 ref = line->buf +41;1026if(isspace(*ref))1027return NULL;10281029if(line->buf[line->len -1] !='\n')1030return NULL;1031 line->buf[--line->len] =0;10321033return ref;1034}10351036/*1037 * Read f, which is a packed-refs file, into dir.1038 *1039 * A comment line of the form "# pack-refs with: " may contain zero or1040 * more traits. We interpret the traits as follows:1041 *1042 * No traits:1043 *1044 * Probably no references are peeled. But if the file contains a1045 * peeled value for a reference, we will use it.1046 *1047 * peeled:1048 *1049 * References under "refs/tags/", if they *can* be peeled, *are*1050 * peeled in this file. References outside of "refs/tags/" are1051 * probably not peeled even if they could have been, but if we find1052 * a peeled value for such a reference we will use it.1053 *1054 * fully-peeled:1055 *1056 * All references in the file that can be peeled are peeled.1057 * Inversely (and this is more important), any references in the1058 * file for which no peeled value is recorded is not peelable. This1059 * trait should typically be written alongside "peeled" for1060 * compatibility with older clients, but we do not require it1061 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1062 */1063static voidread_packed_refs(FILE*f,struct ref_dir *dir)1064{1065struct ref_entry *last = NULL;1066struct strbuf line = STRBUF_INIT;1067enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10681069while(strbuf_getwholeline(&line, f,'\n') != EOF) {1070unsigned char sha1[20];1071const char*refname;1072const char*traits;10731074if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1075if(strstr(traits," fully-peeled "))1076 peeled = PEELED_FULLY;1077else if(strstr(traits," peeled "))1078 peeled = PEELED_TAGS;1079/* perhaps other traits later as well */1080continue;1081}10821083 refname =parse_ref_line(&line, sha1);1084if(refname) {1085int flag = REF_ISPACKED;10861087if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1088if(!refname_is_safe(refname))1089die("packed refname is dangerous:%s", refname);1090hashclr(sha1);1091 flag |= REF_BAD_NAME | REF_ISBROKEN;1092}1093 last =create_ref_entry(refname, sha1, flag,0);1094if(peeled == PEELED_FULLY ||1095(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1096 last->flag |= REF_KNOWS_PEELED;1097add_ref(dir, last);1098continue;1099}1100if(last &&1101 line.buf[0] =='^'&&1102 line.len == PEELED_LINE_LENGTH &&1103 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1104!get_sha1_hex(line.buf +1, sha1)) {1105hashcpy(last->u.value.peeled.hash, sha1);1106/*1107 * Regardless of what the file header said,1108 * we definitely know the value of *this*1109 * reference:1110 */1111 last->flag |= REF_KNOWS_PEELED;1112}1113}11141115strbuf_release(&line);1116}11171118/*1119 * Get the packed_ref_cache for the specified ref_cache, creating it1120 * if necessary.1121 */1122static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1123{1124char*packed_refs_file;11251126if(*refs->name)1127 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1128else1129 packed_refs_file =git_pathdup("packed-refs");11301131if(refs->packed &&1132!stat_validity_check(&refs->packed->validity, packed_refs_file))1133clear_packed_ref_cache(refs);11341135if(!refs->packed) {1136FILE*f;11371138 refs->packed =xcalloc(1,sizeof(*refs->packed));1139acquire_packed_ref_cache(refs->packed);1140 refs->packed->root =create_dir_entry(refs,"",0,0);1141 f =fopen(packed_refs_file,"r");1142if(f) {1143stat_validity_update(&refs->packed->validity,fileno(f));1144read_packed_refs(f,get_ref_dir(refs->packed->root));1145fclose(f);1146}1147}1148free(packed_refs_file);1149return refs->packed;1150}11511152static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1153{1154returnget_ref_dir(packed_ref_cache->root);1155}11561157static struct ref_dir *get_packed_refs(struct ref_cache *refs)1158{1159returnget_packed_ref_dir(get_packed_ref_cache(refs));1160}11611162/*1163 * Add a reference to the in-memory packed reference cache. This may1164 * only be called while the packed-refs file is locked (see1165 * lock_packed_refs()). To actually write the packed-refs file, call1166 * commit_packed_refs().1167 */1168static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1169{1170struct packed_ref_cache *packed_ref_cache =1171get_packed_ref_cache(&ref_cache);11721173if(!packed_ref_cache->lock)1174die("internal error: packed refs not locked");1175add_ref(get_packed_ref_dir(packed_ref_cache),1176create_ref_entry(refname, sha1, REF_ISPACKED,1));1177}11781179/*1180 * Read the loose references from the namespace dirname into dir1181 * (without recursing). dirname must end with '/'. dir must be the1182 * directory entry corresponding to dirname.1183 */1184static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1185{1186struct ref_cache *refs = dir->ref_cache;1187DIR*d;1188struct dirent *de;1189int dirnamelen =strlen(dirname);1190struct strbuf refname;1191struct strbuf path = STRBUF_INIT;1192size_t path_baselen;11931194if(*refs->name)1195strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1196else1197strbuf_git_path(&path,"%s", dirname);1198 path_baselen = path.len;11991200 d =opendir(path.buf);1201if(!d) {1202strbuf_release(&path);1203return;1204}12051206strbuf_init(&refname, dirnamelen +257);1207strbuf_add(&refname, dirname, dirnamelen);12081209while((de =readdir(d)) != NULL) {1210unsigned char sha1[20];1211struct stat st;1212int flag;12131214if(de->d_name[0] =='.')1215continue;1216if(ends_with(de->d_name,".lock"))1217continue;1218strbuf_addstr(&refname, de->d_name);1219strbuf_addstr(&path, de->d_name);1220if(stat(path.buf, &st) <0) {1221;/* silently ignore */1222}else if(S_ISDIR(st.st_mode)) {1223strbuf_addch(&refname,'/');1224add_entry_to_dir(dir,1225create_dir_entry(refs, refname.buf,1226 refname.len,1));1227}else{1228int read_ok;12291230if(*refs->name) {1231hashclr(sha1);1232 flag =0;1233 read_ok = !resolve_gitlink_ref(refs->name,1234 refname.buf, sha1);1235}else{1236 read_ok = !read_ref_full(refname.buf,1237 RESOLVE_REF_READING,1238 sha1, &flag);1239}12401241if(!read_ok) {1242hashclr(sha1);1243 flag |= REF_ISBROKEN;1244}else if(is_null_sha1(sha1)) {1245/*1246 * It is so astronomically unlikely1247 * that NULL_SHA1 is the SHA-1 of an1248 * actual object that we consider its1249 * appearance in a loose reference1250 * file to be repo corruption1251 * (probably due to a software bug).1252 */1253 flag |= REF_ISBROKEN;1254}12551256if(check_refname_format(refname.buf,1257 REFNAME_ALLOW_ONELEVEL)) {1258if(!refname_is_safe(refname.buf))1259die("loose refname is dangerous:%s", refname.buf);1260hashclr(sha1);1261 flag |= REF_BAD_NAME | REF_ISBROKEN;1262}1263add_entry_to_dir(dir,1264create_ref_entry(refname.buf, sha1, flag,0));1265}1266strbuf_setlen(&refname, dirnamelen);1267strbuf_setlen(&path, path_baselen);1268}1269strbuf_release(&refname);1270strbuf_release(&path);1271closedir(d);1272}12731274static struct ref_dir *get_loose_refs(struct ref_cache *refs)1275{1276if(!refs->loose) {1277/*1278 * Mark the top-level directory complete because we1279 * are about to read the only subdirectory that can1280 * hold references:1281 */1282 refs->loose =create_dir_entry(refs,"",0,0);1283/*1284 * Create an incomplete entry for "refs/":1285 */1286add_entry_to_dir(get_ref_dir(refs->loose),1287create_dir_entry(refs,"refs/",5,1));1288}1289returnget_ref_dir(refs->loose);1290}12911292/* We allow "recursive" symbolic refs. Only within reason, though */1293#define MAXDEPTH 51294#define MAXREFLEN (1024)12951296/*1297 * Called by resolve_gitlink_ref_recursive() after it failed to read1298 * from the loose refs in ref_cache refs. Find <refname> in the1299 * packed-refs file for the submodule.1300 */1301static intresolve_gitlink_packed_ref(struct ref_cache *refs,1302const char*refname,unsigned char*sha1)1303{1304struct ref_entry *ref;1305struct ref_dir *dir =get_packed_refs(refs);13061307 ref =find_ref(dir, refname);1308if(ref == NULL)1309return-1;13101311hashcpy(sha1, ref->u.value.oid.hash);1312return0;1313}13141315static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1316const char*refname,unsigned char*sha1,1317int recursion)1318{1319int fd, len;1320char buffer[128], *p;1321char*path;13221323if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1324return-1;1325 path = *refs->name1326?git_pathdup_submodule(refs->name,"%s", refname)1327:git_pathdup("%s", refname);1328 fd =open(path, O_RDONLY);1329free(path);1330if(fd <0)1331returnresolve_gitlink_packed_ref(refs, refname, sha1);13321333 len =read(fd, buffer,sizeof(buffer)-1);1334close(fd);1335if(len <0)1336return-1;1337while(len &&isspace(buffer[len-1]))1338 len--;1339 buffer[len] =0;13401341/* Was it a detached head or an old-fashioned symlink? */1342if(!get_sha1_hex(buffer, sha1))1343return0;13441345/* Symref? */1346if(strncmp(buffer,"ref:",4))1347return-1;1348 p = buffer +4;1349while(isspace(*p))1350 p++;13511352returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1353}13541355intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1356{1357int len =strlen(path), retval;1358char*submodule;1359struct ref_cache *refs;13601361while(len && path[len-1] =='/')1362 len--;1363if(!len)1364return-1;1365 submodule =xstrndup(path, len);1366 refs =get_ref_cache(submodule);1367free(submodule);13681369 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1370return retval;1371}13721373/*1374 * Return the ref_entry for the given refname from the packed1375 * references. If it does not exist, return NULL.1376 */1377static struct ref_entry *get_packed_ref(const char*refname)1378{1379returnfind_ref(get_packed_refs(&ref_cache), refname);1380}13811382/*1383 * A loose ref file doesn't exist; check for a packed ref. The1384 * options are forwarded from resolve_safe_unsafe().1385 */1386static intresolve_missing_loose_ref(const char*refname,1387int resolve_flags,1388unsigned char*sha1,1389int*flags)1390{1391struct ref_entry *entry;13921393/*1394 * The loose reference file does not exist; check for a packed1395 * reference.1396 */1397 entry =get_packed_ref(refname);1398if(entry) {1399hashcpy(sha1, entry->u.value.oid.hash);1400if(flags)1401*flags |= REF_ISPACKED;1402return0;1403}1404/* The reference is not a packed reference, either. */1405if(resolve_flags & RESOLVE_REF_READING) {1406 errno = ENOENT;1407return-1;1408}else{1409hashclr(sha1);1410return0;1411}1412}14131414/* This function needs to return a meaningful errno on failure */1415static const char*resolve_ref_1(const char*refname,1416int resolve_flags,1417unsigned char*sha1,1418int*flags,1419struct strbuf *sb_refname,1420struct strbuf *sb_path,1421struct strbuf *sb_contents)1422{1423int depth = MAXDEPTH;1424int bad_name =0;14251426if(flags)1427*flags =0;14281429if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1430if(flags)1431*flags |= REF_BAD_NAME;14321433if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1434!refname_is_safe(refname)) {1435 errno = EINVAL;1436return NULL;1437}1438/*1439 * dwim_ref() uses REF_ISBROKEN to distinguish between1440 * missing refs and refs that were present but invalid,1441 * to complain about the latter to stderr.1442 *1443 * We don't know whether the ref exists, so don't set1444 * REF_ISBROKEN yet.1445 */1446 bad_name =1;1447}1448for(;;) {1449const char*path;1450struct stat st;1451char*buf;1452int fd;14531454if(--depth <0) {1455 errno = ELOOP;1456return NULL;1457}14581459strbuf_reset(sb_path);1460strbuf_git_path(sb_path,"%s", refname);1461 path = sb_path->buf;14621463/*1464 * We might have to loop back here to avoid a race1465 * condition: first we lstat() the file, then we try1466 * to read it as a link or as a file. But if somebody1467 * changes the type of the file (file <-> directory1468 * <-> symlink) between the lstat() and reading, then1469 * we don't want to report that as an error but rather1470 * try again starting with the lstat().1471 */1472 stat_ref:1473if(lstat(path, &st) <0) {1474if(errno != ENOENT)1475return NULL;1476if(resolve_missing_loose_ref(refname, resolve_flags,1477 sha1, flags))1478return NULL;1479if(bad_name) {1480hashclr(sha1);1481if(flags)1482*flags |= REF_ISBROKEN;1483}1484return refname;1485}14861487/* Follow "normalized" - ie "refs/.." symlinks by hand */1488if(S_ISLNK(st.st_mode)) {1489strbuf_reset(sb_contents);1490if(strbuf_readlink(sb_contents, path,0) <0) {1491if(errno == ENOENT || errno == EINVAL)1492/* inconsistent with lstat; retry */1493goto stat_ref;1494else1495return NULL;1496}1497if(starts_with(sb_contents->buf,"refs/") &&1498!check_refname_format(sb_contents->buf,0)) {1499strbuf_swap(sb_refname, sb_contents);1500 refname = sb_refname->buf;1501if(flags)1502*flags |= REF_ISSYMREF;1503if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1504hashclr(sha1);1505return refname;1506}1507continue;1508}1509}15101511/* Is it a directory? */1512if(S_ISDIR(st.st_mode)) {1513 errno = EISDIR;1514return NULL;1515}15161517/*1518 * Anything else, just open it and try to use it as1519 * a ref1520 */1521 fd =open(path, O_RDONLY);1522if(fd <0) {1523if(errno == ENOENT)1524/* inconsistent with lstat; retry */1525goto stat_ref;1526else1527return NULL;1528}1529strbuf_reset(sb_contents);1530if(strbuf_read(sb_contents, fd,256) <0) {1531int save_errno = errno;1532close(fd);1533 errno = save_errno;1534return NULL;1535}1536close(fd);1537strbuf_rtrim(sb_contents);15381539/*1540 * Is it a symbolic ref?1541 */1542if(!starts_with(sb_contents->buf,"ref:")) {1543/*1544 * Please note that FETCH_HEAD has a second1545 * line containing other data.1546 */1547if(get_sha1_hex(sb_contents->buf, sha1) ||1548(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1549if(flags)1550*flags |= REF_ISBROKEN;1551 errno = EINVAL;1552return NULL;1553}1554if(bad_name) {1555hashclr(sha1);1556if(flags)1557*flags |= REF_ISBROKEN;1558}1559return refname;1560}1561if(flags)1562*flags |= REF_ISSYMREF;1563 buf = sb_contents->buf +4;1564while(isspace(*buf))1565 buf++;1566strbuf_reset(sb_refname);1567strbuf_addstr(sb_refname, buf);1568 refname = sb_refname->buf;1569if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1570hashclr(sha1);1571return refname;1572}1573if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1574if(flags)1575*flags |= REF_ISBROKEN;15761577if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1578!refname_is_safe(buf)) {1579 errno = EINVAL;1580return NULL;1581}1582 bad_name =1;1583}1584}1585}15861587const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1588unsigned char*sha1,int*flags)1589{1590static struct strbuf sb_refname = STRBUF_INIT;1591struct strbuf sb_contents = STRBUF_INIT;1592struct strbuf sb_path = STRBUF_INIT;1593const char*ret;15941595 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1596&sb_refname, &sb_path, &sb_contents);1597strbuf_release(&sb_path);1598strbuf_release(&sb_contents);1599return ret;1600}16011602/*1603 * Peel the entry (if possible) and return its new peel_status. If1604 * repeel is true, re-peel the entry even if there is an old peeled1605 * value that is already stored in it.1606 *1607 * It is OK to call this function with a packed reference entry that1608 * might be stale and might even refer to an object that has since1609 * been garbage-collected. In such a case, if the entry has1610 * REF_KNOWS_PEELED then leave the status unchanged and return1611 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1612 */1613static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1614{1615enum peel_status status;16161617if(entry->flag & REF_KNOWS_PEELED) {1618if(repeel) {1619 entry->flag &= ~REF_KNOWS_PEELED;1620oidclr(&entry->u.value.peeled);1621}else{1622returnis_null_oid(&entry->u.value.peeled) ?1623 PEEL_NON_TAG : PEEL_PEELED;1624}1625}1626if(entry->flag & REF_ISBROKEN)1627return PEEL_BROKEN;1628if(entry->flag & REF_ISSYMREF)1629return PEEL_IS_SYMREF;16301631 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1632if(status == PEEL_PEELED || status == PEEL_NON_TAG)1633 entry->flag |= REF_KNOWS_PEELED;1634return status;1635}16361637intpeel_ref(const char*refname,unsigned char*sha1)1638{1639int flag;1640unsigned char base[20];16411642if(current_ref && (current_ref->name == refname1643|| !strcmp(current_ref->name, refname))) {1644if(peel_entry(current_ref,0))1645return-1;1646hashcpy(sha1, current_ref->u.value.peeled.hash);1647return0;1648}16491650if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1651return-1;16521653/*1654 * If the reference is packed, read its ref_entry from the1655 * cache in the hope that we already know its peeled value.1656 * We only try this optimization on packed references because1657 * (a) forcing the filling of the loose reference cache could1658 * be expensive and (b) loose references anyway usually do not1659 * have REF_KNOWS_PEELED.1660 */1661if(flag & REF_ISPACKED) {1662struct ref_entry *r =get_packed_ref(refname);1663if(r) {1664if(peel_entry(r,0))1665return-1;1666hashcpy(sha1, r->u.value.peeled.hash);1667return0;1668}1669}16701671returnpeel_object(base, sha1);1672}16731674/*1675 * Call fn for each reference in the specified ref_cache, omitting1676 * references not in the containing_dir of base. fn is called for all1677 * references, including broken ones. If fn ever returns a non-zero1678 * value, stop the iteration and return that value; otherwise, return1679 * 0.1680 */1681static intdo_for_each_entry(struct ref_cache *refs,const char*base,1682 each_ref_entry_fn fn,void*cb_data)1683{1684struct packed_ref_cache *packed_ref_cache;1685struct ref_dir *loose_dir;1686struct ref_dir *packed_dir;1687int retval =0;16881689/*1690 * We must make sure that all loose refs are read before accessing the1691 * packed-refs file; this avoids a race condition in which loose refs1692 * are migrated to the packed-refs file by a simultaneous process, but1693 * our in-memory view is from before the migration. get_packed_ref_cache()1694 * takes care of making sure our view is up to date with what is on1695 * disk.1696 */1697 loose_dir =get_loose_refs(refs);1698if(base && *base) {1699 loose_dir =find_containing_dir(loose_dir, base,0);1700}1701if(loose_dir)1702prime_ref_dir(loose_dir);17031704 packed_ref_cache =get_packed_ref_cache(refs);1705acquire_packed_ref_cache(packed_ref_cache);1706 packed_dir =get_packed_ref_dir(packed_ref_cache);1707if(base && *base) {1708 packed_dir =find_containing_dir(packed_dir, base,0);1709}17101711if(packed_dir && loose_dir) {1712sort_ref_dir(packed_dir);1713sort_ref_dir(loose_dir);1714 retval =do_for_each_entry_in_dirs(1715 packed_dir, loose_dir, fn, cb_data);1716}else if(packed_dir) {1717sort_ref_dir(packed_dir);1718 retval =do_for_each_entry_in_dir(1719 packed_dir,0, fn, cb_data);1720}else if(loose_dir) {1721sort_ref_dir(loose_dir);1722 retval =do_for_each_entry_in_dir(1723 loose_dir,0, fn, cb_data);1724}17251726release_packed_ref_cache(packed_ref_cache);1727return retval;1728}17291730/*1731 * Call fn for each reference in the specified ref_cache for which the1732 * refname begins with base. If trim is non-zero, then trim that many1733 * characters off the beginning of each refname before passing the1734 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1735 * broken references in the iteration. If fn ever returns a non-zero1736 * value, stop the iteration and return that value; otherwise, return1737 * 0.1738 */1739static intdo_for_each_ref(struct ref_cache *refs,const char*base,1740 each_ref_fn fn,int trim,int flags,void*cb_data)1741{1742struct ref_entry_cb data;1743 data.base = base;1744 data.trim = trim;1745 data.flags = flags;1746 data.fn = fn;1747 data.cb_data = cb_data;17481749if(ref_paranoia <0)1750 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1751if(ref_paranoia)1752 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;17531754returndo_for_each_entry(refs, base, do_one_ref, &data);1755}17561757static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1758{1759struct object_id oid;1760int flag;17611762if(submodule) {1763if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)1764returnfn("HEAD", &oid,0, cb_data);17651766return0;1767}17681769if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))1770returnfn("HEAD", &oid, flag, cb_data);17711772return0;1773}17741775inthead_ref(each_ref_fn fn,void*cb_data)1776{1777returndo_head_ref(NULL, fn, cb_data);1778}17791780inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1781{1782returndo_head_ref(submodule, fn, cb_data);1783}17841785intfor_each_ref(each_ref_fn fn,void*cb_data)1786{1787returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1788}17891790intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1791{1792returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1793}17941795intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1796{1797returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1798}17991800intfor_each_fullref_in(const char*prefix, each_ref_fn fn,void*cb_data,unsigned int broken)1801{1802unsigned int flag =0;18031804if(broken)1805 flag = DO_FOR_EACH_INCLUDE_BROKEN;1806returndo_for_each_ref(&ref_cache, prefix, fn,0, flag, cb_data);1807}18081809intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1810 each_ref_fn fn,void*cb_data)1811{1812returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1813}18141815intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1816{1817returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,1818strlen(git_replace_ref_base),0, cb_data);1819}18201821intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1822{1823struct strbuf buf = STRBUF_INIT;1824int ret;1825strbuf_addf(&buf,"%srefs/",get_git_namespace());1826 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);1827strbuf_release(&buf);1828return ret;1829}18301831intfor_each_rawref(each_ref_fn fn,void*cb_data)1832{1833returndo_for_each_ref(&ref_cache,"", fn,0,1834 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1835}18361837static voidunlock_ref(struct ref_lock *lock)1838{1839/* Do not free lock->lk -- atexit() still looks at them */1840if(lock->lk)1841rollback_lock_file(lock->lk);1842free(lock->ref_name);1843free(lock->orig_ref_name);1844free(lock);1845}18461847/*1848 * Verify that the reference locked by lock has the value old_sha1.1849 * Fail if the reference doesn't exist and mustexist is set. Return 01850 * on success. On error, write an error message to err, set errno, and1851 * return a negative value.1852 */1853static intverify_lock(struct ref_lock *lock,1854const unsigned char*old_sha1,int mustexist,1855struct strbuf *err)1856{1857assert(err);18581859if(read_ref_full(lock->ref_name,1860 mustexist ? RESOLVE_REF_READING :0,1861 lock->old_oid.hash, NULL)) {1862int save_errno = errno;1863strbuf_addf(err,"can't verify ref%s", lock->ref_name);1864 errno = save_errno;1865return-1;1866}1867if(hashcmp(lock->old_oid.hash, old_sha1)) {1868strbuf_addf(err,"ref%sis at%sbut expected%s",1869 lock->ref_name,1870sha1_to_hex(lock->old_oid.hash),1871sha1_to_hex(old_sha1));1872 errno = EBUSY;1873return-1;1874}1875return0;1876}18771878static intremove_empty_directories(struct strbuf *path)1879{1880/*1881 * we want to create a file but there is a directory there;1882 * if that is an empty directory (or a directory that contains1883 * only empty directories), remove them.1884 */1885returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1886}18871888/*1889 * Locks a ref returning the lock on success and NULL on failure.1890 * On failure errno is set to something meaningful.1891 */1892static struct ref_lock *lock_ref_sha1_basic(const char*refname,1893const unsigned char*old_sha1,1894const struct string_list *extras,1895const struct string_list *skip,1896unsigned int flags,int*type_p,1897struct strbuf *err)1898{1899struct strbuf ref_file = STRBUF_INIT;1900struct strbuf orig_ref_file = STRBUF_INIT;1901const char*orig_refname = refname;1902struct ref_lock *lock;1903int last_errno =0;1904int type, lflags;1905int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1906int resolve_flags =0;1907int attempts_remaining =3;19081909assert(err);19101911 lock =xcalloc(1,sizeof(struct ref_lock));19121913if(mustexist)1914 resolve_flags |= RESOLVE_REF_READING;1915if(flags & REF_DELETING) {1916 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1917if(flags & REF_NODEREF)1918 resolve_flags |= RESOLVE_REF_NO_RECURSE;1919}19201921 refname =resolve_ref_unsafe(refname, resolve_flags,1922 lock->old_oid.hash, &type);1923if(!refname && errno == EISDIR) {1924/*1925 * we are trying to lock foo but we used to1926 * have foo/bar which now does not exist;1927 * it is normal for the empty directory 'foo'1928 * to remain.1929 */1930strbuf_git_path(&orig_ref_file,"%s", orig_refname);1931if(remove_empty_directories(&orig_ref_file)) {1932 last_errno = errno;1933if(!verify_refname_available_dir(orig_refname, extras, skip,1934get_loose_refs(&ref_cache), err))1935strbuf_addf(err,"there are still refs under '%s'",1936 orig_refname);1937goto error_return;1938}1939 refname =resolve_ref_unsafe(orig_refname, resolve_flags,1940 lock->old_oid.hash, &type);1941}1942if(type_p)1943*type_p = type;1944if(!refname) {1945 last_errno = errno;1946if(last_errno != ENOTDIR ||1947!verify_refname_available_dir(orig_refname, extras, skip,1948get_loose_refs(&ref_cache), err))1949strbuf_addf(err,"unable to resolve reference%s:%s",1950 orig_refname,strerror(last_errno));19511952goto error_return;1953}1954/*1955 * If the ref did not exist and we are creating it, make sure1956 * there is no existing packed ref whose name begins with our1957 * refname, nor a packed ref whose name is a proper prefix of1958 * our refname.1959 */1960if(is_null_oid(&lock->old_oid) &&1961verify_refname_available_dir(refname, extras, skip,1962get_packed_refs(&ref_cache), err)) {1963 last_errno = ENOTDIR;1964goto error_return;1965}19661967 lock->lk =xcalloc(1,sizeof(struct lock_file));19681969 lflags =0;1970if(flags & REF_NODEREF) {1971 refname = orig_refname;1972 lflags |= LOCK_NO_DEREF;1973}1974 lock->ref_name =xstrdup(refname);1975 lock->orig_ref_name =xstrdup(orig_refname);1976strbuf_git_path(&ref_file,"%s", refname);19771978 retry:1979switch(safe_create_leading_directories_const(ref_file.buf)) {1980case SCLD_OK:1981break;/* success */1982case SCLD_VANISHED:1983if(--attempts_remaining >0)1984goto retry;1985/* fall through */1986default:1987 last_errno = errno;1988strbuf_addf(err,"unable to create directory for%s",1989 ref_file.buf);1990goto error_return;1991}19921993if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {1994 last_errno = errno;1995if(errno == ENOENT && --attempts_remaining >0)1996/*1997 * Maybe somebody just deleted one of the1998 * directories leading to ref_file. Try1999 * again:2000 */2001goto retry;2002else{2003unable_to_lock_message(ref_file.buf, errno, err);2004goto error_return;2005}2006}2007if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2008 last_errno = errno;2009goto error_return;2010}2011goto out;20122013 error_return:2014unlock_ref(lock);2015 lock = NULL;20162017 out:2018strbuf_release(&ref_file);2019strbuf_release(&orig_ref_file);2020 errno = last_errno;2021return lock;2022}20232024/*2025 * Write an entry to the packed-refs file for the specified refname.2026 * If peeled is non-NULL, write it as the entry's peeled value.2027 */2028static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2029unsigned char*peeled)2030{2031fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2032if(peeled)2033fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2034}20352036/*2037 * An each_ref_entry_fn that writes the entry to a packed-refs file.2038 */2039static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2040{2041enum peel_status peel_status =peel_entry(entry,0);20422043if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2044error("internal error:%sis not a valid packed reference!",2045 entry->name);2046write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2047 peel_status == PEEL_PEELED ?2048 entry->u.value.peeled.hash : NULL);2049return0;2050}20512052/*2053 * Lock the packed-refs file for writing. Flags is passed to2054 * hold_lock_file_for_update(). Return 0 on success. On errors, set2055 * errno appropriately and return a nonzero value.2056 */2057static intlock_packed_refs(int flags)2058{2059static int timeout_configured =0;2060static int timeout_value =1000;20612062struct packed_ref_cache *packed_ref_cache;20632064if(!timeout_configured) {2065git_config_get_int("core.packedrefstimeout", &timeout_value);2066 timeout_configured =1;2067}20682069if(hold_lock_file_for_update_timeout(2070&packlock,git_path("packed-refs"),2071 flags, timeout_value) <0)2072return-1;2073/*2074 * Get the current packed-refs while holding the lock. If the2075 * packed-refs file has been modified since we last read it,2076 * this will automatically invalidate the cache and re-read2077 * the packed-refs file.2078 */2079 packed_ref_cache =get_packed_ref_cache(&ref_cache);2080 packed_ref_cache->lock = &packlock;2081/* Increment the reference count to prevent it from being freed: */2082acquire_packed_ref_cache(packed_ref_cache);2083return0;2084}20852086/*2087 * Write the current version of the packed refs cache from memory to2088 * disk. The packed-refs file must already be locked for writing (see2089 * lock_packed_refs()). Return zero on success. On errors, set errno2090 * and return a nonzero value2091 */2092static intcommit_packed_refs(void)2093{2094struct packed_ref_cache *packed_ref_cache =2095get_packed_ref_cache(&ref_cache);2096int error =0;2097int save_errno =0;2098FILE*out;20992100if(!packed_ref_cache->lock)2101die("internal error: packed-refs not locked");21022103 out =fdopen_lock_file(packed_ref_cache->lock,"w");2104if(!out)2105die_errno("unable to fdopen packed-refs descriptor");21062107fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2108do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),21090, write_packed_entry_fn, out);21102111if(commit_lock_file(packed_ref_cache->lock)) {2112 save_errno = errno;2113 error = -1;2114}2115 packed_ref_cache->lock = NULL;2116release_packed_ref_cache(packed_ref_cache);2117 errno = save_errno;2118return error;2119}21202121/*2122 * Rollback the lockfile for the packed-refs file, and discard the2123 * in-memory packed reference cache. (The packed-refs file will be2124 * read anew if it is needed again after this function is called.)2125 */2126static voidrollback_packed_refs(void)2127{2128struct packed_ref_cache *packed_ref_cache =2129get_packed_ref_cache(&ref_cache);21302131if(!packed_ref_cache->lock)2132die("internal error: packed-refs not locked");2133rollback_lock_file(packed_ref_cache->lock);2134 packed_ref_cache->lock = NULL;2135release_packed_ref_cache(packed_ref_cache);2136clear_packed_ref_cache(&ref_cache);2137}21382139struct ref_to_prune {2140struct ref_to_prune *next;2141unsigned char sha1[20];2142char name[FLEX_ARRAY];2143};21442145struct pack_refs_cb_data {2146unsigned int flags;2147struct ref_dir *packed_refs;2148struct ref_to_prune *ref_to_prune;2149};21502151/*2152 * An each_ref_entry_fn that is run over loose references only. If2153 * the loose reference can be packed, add an entry in the packed ref2154 * cache. If the reference should be pruned, also add it to2155 * ref_to_prune in the pack_refs_cb_data.2156 */2157static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2158{2159struct pack_refs_cb_data *cb = cb_data;2160enum peel_status peel_status;2161struct ref_entry *packed_entry;2162int is_tag_ref =starts_with(entry->name,"refs/tags/");21632164/* Do not pack per-worktree refs: */2165if(ref_type(entry->name) != REF_TYPE_NORMAL)2166return0;21672168/* ALWAYS pack tags */2169if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2170return0;21712172/* Do not pack symbolic or broken refs: */2173if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2174return0;21752176/* Add a packed ref cache entry equivalent to the loose entry. */2177 peel_status =peel_entry(entry,1);2178if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2179die("internal error peeling reference%s(%s)",2180 entry->name,oid_to_hex(&entry->u.value.oid));2181 packed_entry =find_ref(cb->packed_refs, entry->name);2182if(packed_entry) {2183/* Overwrite existing packed entry with info from loose entry */2184 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2185oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2186}else{2187 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2188 REF_ISPACKED | REF_KNOWS_PEELED,0);2189add_ref(cb->packed_refs, packed_entry);2190}2191oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);21922193/* Schedule the loose reference for pruning if requested. */2194if((cb->flags & PACK_REFS_PRUNE)) {2195int namelen =strlen(entry->name) +1;2196struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2197hashcpy(n->sha1, entry->u.value.oid.hash);2198memcpy(n->name, entry->name, namelen);/* includes NUL */2199 n->next = cb->ref_to_prune;2200 cb->ref_to_prune = n;2201}2202return0;2203}22042205/*2206 * Remove empty parents, but spare refs/ and immediate subdirs.2207 * Note: munges *name.2208 */2209static voidtry_remove_empty_parents(char*name)2210{2211char*p, *q;2212int i;2213 p = name;2214for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2215while(*p && *p !='/')2216 p++;2217/* tolerate duplicate slashes; see check_refname_format() */2218while(*p =='/')2219 p++;2220}2221for(q = p; *q; q++)2222;2223while(1) {2224while(q > p && *q !='/')2225 q--;2226while(q > p && *(q-1) =='/')2227 q--;2228if(q == p)2229break;2230*q ='\0';2231if(rmdir(git_path("%s", name)))2232break;2233}2234}22352236/* make sure nobody touched the ref, and unlink */2237static voidprune_ref(struct ref_to_prune *r)2238{2239struct ref_transaction *transaction;2240struct strbuf err = STRBUF_INIT;22412242if(check_refname_format(r->name,0))2243return;22442245 transaction =ref_transaction_begin(&err);2246if(!transaction ||2247ref_transaction_delete(transaction, r->name, r->sha1,2248 REF_ISPRUNING, NULL, &err) ||2249ref_transaction_commit(transaction, &err)) {2250ref_transaction_free(transaction);2251error("%s", err.buf);2252strbuf_release(&err);2253return;2254}2255ref_transaction_free(transaction);2256strbuf_release(&err);2257try_remove_empty_parents(r->name);2258}22592260static voidprune_refs(struct ref_to_prune *r)2261{2262while(r) {2263prune_ref(r);2264 r = r->next;2265}2266}22672268intpack_refs(unsigned int flags)2269{2270struct pack_refs_cb_data cbdata;22712272memset(&cbdata,0,sizeof(cbdata));2273 cbdata.flags = flags;22742275lock_packed_refs(LOCK_DIE_ON_ERROR);2276 cbdata.packed_refs =get_packed_refs(&ref_cache);22772278do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2279 pack_if_possible_fn, &cbdata);22802281if(commit_packed_refs())2282die_errno("unable to overwrite old ref-pack file");22832284prune_refs(cbdata.ref_to_prune);2285return0;2286}22872288/*2289 * Rewrite the packed-refs file, omitting any refs listed in2290 * 'refnames'. On error, leave packed-refs unchanged, write an error2291 * message to 'err', and return a nonzero value.2292 *2293 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2294 */2295static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2296{2297struct ref_dir *packed;2298struct string_list_item *refname;2299int ret, needs_repacking =0, removed =0;23002301assert(err);23022303/* Look for a packed ref */2304for_each_string_list_item(refname, refnames) {2305if(get_packed_ref(refname->string)) {2306 needs_repacking =1;2307break;2308}2309}23102311/* Avoid locking if we have nothing to do */2312if(!needs_repacking)2313return0;/* no refname exists in packed refs */23142315if(lock_packed_refs(0)) {2316unable_to_lock_message(git_path("packed-refs"), errno, err);2317return-1;2318}2319 packed =get_packed_refs(&ref_cache);23202321/* Remove refnames from the cache */2322for_each_string_list_item(refname, refnames)2323if(remove_entry(packed, refname->string) != -1)2324 removed =1;2325if(!removed) {2326/*2327 * All packed entries disappeared while we were2328 * acquiring the lock.2329 */2330rollback_packed_refs();2331return0;2332}23332334/* Write what remains */2335 ret =commit_packed_refs();2336if(ret)2337strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2338strerror(errno));2339return ret;2340}23412342static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2343{2344assert(err);23452346if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2347/*2348 * loose. The loose file name is the same as the2349 * lockfile name, minus ".lock":2350 */2351char*loose_filename =get_locked_file_path(lock->lk);2352int res =unlink_or_msg(loose_filename, err);2353free(loose_filename);2354if(res)2355return1;2356}2357return0;2358}23592360intdelete_refs(struct string_list *refnames)2361{2362struct strbuf err = STRBUF_INIT;2363int i, result =0;23642365if(!refnames->nr)2366return0;23672368 result =repack_without_refs(refnames, &err);2369if(result) {2370/*2371 * If we failed to rewrite the packed-refs file, then2372 * it is unsafe to try to remove loose refs, because2373 * doing so might expose an obsolete packed value for2374 * a reference that might even point at an object that2375 * has been garbage collected.2376 */2377if(refnames->nr ==1)2378error(_("could not delete reference%s:%s"),2379 refnames->items[0].string, err.buf);2380else2381error(_("could not delete references:%s"), err.buf);23822383goto out;2384}23852386for(i =0; i < refnames->nr; i++) {2387const char*refname = refnames->items[i].string;23882389if(delete_ref(refname, NULL,0))2390 result |=error(_("could not remove reference%s"), refname);2391}23922393out:2394strbuf_release(&err);2395return result;2396}23972398/*2399 * People using contrib's git-new-workdir have .git/logs/refs ->2400 * /some/other/path/.git/logs/refs, and that may live on another device.2401 *2402 * IOW, to avoid cross device rename errors, the temporary renamed log must2403 * live into logs/refs.2404 */2405#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"24062407static intrename_tmp_log(const char*newrefname)2408{2409int attempts_remaining =4;2410struct strbuf path = STRBUF_INIT;2411int ret = -1;24122413 retry:2414strbuf_reset(&path);2415strbuf_git_path(&path,"logs/%s", newrefname);2416switch(safe_create_leading_directories_const(path.buf)) {2417case SCLD_OK:2418break;/* success */2419case SCLD_VANISHED:2420if(--attempts_remaining >0)2421goto retry;2422/* fall through */2423default:2424error("unable to create directory for%s", newrefname);2425goto out;2426}24272428if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2429if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2430/*2431 * rename(a, b) when b is an existing2432 * directory ought to result in ISDIR, but2433 * Solaris 5.8 gives ENOTDIR. Sheesh.2434 */2435if(remove_empty_directories(&path)) {2436error("Directory not empty: logs/%s", newrefname);2437goto out;2438}2439goto retry;2440}else if(errno == ENOENT && --attempts_remaining >0) {2441/*2442 * Maybe another process just deleted one of2443 * the directories in the path to newrefname.2444 * Try again from the beginning.2445 */2446goto retry;2447}else{2448error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2449 newrefname,strerror(errno));2450goto out;2451}2452}2453 ret =0;2454out:2455strbuf_release(&path);2456return ret;2457}24582459intverify_refname_available(const char*newname,2460struct string_list *extras,2461struct string_list *skip,2462struct strbuf *err)2463{2464struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2465struct ref_dir *loose_refs =get_loose_refs(&ref_cache);24662467if(verify_refname_available_dir(newname, extras, skip,2468 packed_refs, err) ||2469verify_refname_available_dir(newname, extras, skip,2470 loose_refs, err))2471return-1;24722473return0;2474}24752476static intrename_ref_available(const char*oldname,const char*newname)2477{2478struct string_list skip = STRING_LIST_INIT_NODUP;2479struct strbuf err = STRBUF_INIT;2480int ret;24812482string_list_insert(&skip, oldname);2483 ret = !verify_refname_available(newname, NULL, &skip, &err);2484if(!ret)2485error("%s", err.buf);24862487string_list_clear(&skip,0);2488strbuf_release(&err);2489return ret;2490}24912492static intwrite_ref_to_lockfile(struct ref_lock *lock,2493const unsigned char*sha1,struct strbuf *err);2494static intcommit_ref_update(struct ref_lock *lock,2495const unsigned char*sha1,const char*logmsg,2496int flags,struct strbuf *err);24972498intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2499{2500unsigned char sha1[20], orig_sha1[20];2501int flag =0, logmoved =0;2502struct ref_lock *lock;2503struct stat loginfo;2504int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2505const char*symref = NULL;2506struct strbuf err = STRBUF_INIT;25072508if(log &&S_ISLNK(loginfo.st_mode))2509returnerror("reflog for%sis a symlink", oldrefname);25102511 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2512 orig_sha1, &flag);2513if(flag & REF_ISSYMREF)2514returnerror("refname%sis a symbolic ref, renaming it is not supported",2515 oldrefname);2516if(!symref)2517returnerror("refname%snot found", oldrefname);25182519if(!rename_ref_available(oldrefname, newrefname))2520return1;25212522if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2523returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2524 oldrefname,strerror(errno));25252526if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2527error("unable to delete old%s", oldrefname);2528goto rollback;2529}25302531if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2532delete_ref(newrefname, sha1, REF_NODEREF)) {2533if(errno==EISDIR) {2534struct strbuf path = STRBUF_INIT;2535int result;25362537strbuf_git_path(&path,"%s", newrefname);2538 result =remove_empty_directories(&path);2539strbuf_release(&path);25402541if(result) {2542error("Directory not empty:%s", newrefname);2543goto rollback;2544}2545}else{2546error("unable to delete existing%s", newrefname);2547goto rollback;2548}2549}25502551if(log &&rename_tmp_log(newrefname))2552goto rollback;25532554 logmoved = log;25552556 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2557if(!lock) {2558error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2559strbuf_release(&err);2560goto rollback;2561}2562hashcpy(lock->old_oid.hash, orig_sha1);25632564if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2565commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2566error("unable to write current sha1 into%s:%s", newrefname, err.buf);2567strbuf_release(&err);2568goto rollback;2569}25702571return0;25722573 rollback:2574 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2575if(!lock) {2576error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2577strbuf_release(&err);2578goto rollbacklog;2579}25802581 flag = log_all_ref_updates;2582 log_all_ref_updates =0;2583if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2584commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2585error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2586strbuf_release(&err);2587}2588 log_all_ref_updates = flag;25892590 rollbacklog:2591if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2592error("unable to restore logfile%sfrom%s:%s",2593 oldrefname, newrefname,strerror(errno));2594if(!logmoved && log &&2595rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2596error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2597 oldrefname,strerror(errno));25982599return1;2600}26012602static intclose_ref(struct ref_lock *lock)2603{2604if(close_lock_file(lock->lk))2605return-1;2606return0;2607}26082609static intcommit_ref(struct ref_lock *lock)2610{2611if(commit_lock_file(lock->lk))2612return-1;2613return0;2614}26152616/*2617 * Create a reflog for a ref. If force_create = 0, the reflog will2618 * only be created for certain refs (those for which2619 * should_autocreate_reflog returns non-zero. Otherwise, create it2620 * regardless of the ref name. Fill in *err and return -1 on failure.2621 */2622static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2623{2624int logfd, oflags = O_APPEND | O_WRONLY;26252626strbuf_git_path(logfile,"logs/%s", refname);2627if(force_create ||should_autocreate_reflog(refname)) {2628if(safe_create_leading_directories(logfile->buf) <0) {2629strbuf_addf(err,"unable to create directory for%s: "2630"%s", logfile->buf,strerror(errno));2631return-1;2632}2633 oflags |= O_CREAT;2634}26352636 logfd =open(logfile->buf, oflags,0666);2637if(logfd <0) {2638if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2639return0;26402641if(errno == EISDIR) {2642if(remove_empty_directories(logfile)) {2643strbuf_addf(err,"There are still logs under "2644"'%s'", logfile->buf);2645return-1;2646}2647 logfd =open(logfile->buf, oflags,0666);2648}26492650if(logfd <0) {2651strbuf_addf(err,"unable to append to%s:%s",2652 logfile->buf,strerror(errno));2653return-1;2654}2655}26562657adjust_shared_perm(logfile->buf);2658close(logfd);2659return0;2660}266126622663intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2664{2665int ret;2666struct strbuf sb = STRBUF_INIT;26672668 ret =log_ref_setup(refname, &sb, err, force_create);2669strbuf_release(&sb);2670return ret;2671}26722673static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2674const unsigned char*new_sha1,2675const char*committer,const char*msg)2676{2677int msglen, written;2678unsigned maxlen, len;2679char*logrec;26802681 msglen = msg ?strlen(msg) :0;2682 maxlen =strlen(committer) + msglen +100;2683 logrec =xmalloc(maxlen);2684 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2685sha1_to_hex(old_sha1),2686sha1_to_hex(new_sha1),2687 committer);2688if(msglen)2689 len +=copy_reflog_msg(logrec + len -1, msg) -1;26902691 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2692free(logrec);2693if(written != len)2694return-1;26952696return0;2697}26982699static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2700const unsigned char*new_sha1,const char*msg,2701struct strbuf *logfile,int flags,2702struct strbuf *err)2703{2704int logfd, result, oflags = O_APPEND | O_WRONLY;27052706if(log_all_ref_updates <0)2707 log_all_ref_updates = !is_bare_repository();27082709 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);27102711if(result)2712return result;27132714 logfd =open(logfile->buf, oflags);2715if(logfd <0)2716return0;2717 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2718git_committer_info(0), msg);2719if(result) {2720strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2721strerror(errno));2722close(logfd);2723return-1;2724}2725if(close(logfd)) {2726strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2727strerror(errno));2728return-1;2729}2730return0;2731}27322733static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2734const unsigned char*new_sha1,const char*msg,2735int flags,struct strbuf *err)2736{2737returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2738 err);2739}27402741intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2742const unsigned char*new_sha1,const char*msg,2743int flags,struct strbuf *err)2744{2745struct strbuf sb = STRBUF_INIT;2746int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2747 err);2748strbuf_release(&sb);2749return ret;2750}27512752/*2753 * Write sha1 into the open lockfile, then close the lockfile. On2754 * errors, rollback the lockfile, fill in *err and2755 * return -1.2756 */2757static intwrite_ref_to_lockfile(struct ref_lock *lock,2758const unsigned char*sha1,struct strbuf *err)2759{2760static char term ='\n';2761struct object *o;2762int fd;27632764 o =parse_object(sha1);2765if(!o) {2766strbuf_addf(err,2767"Trying to write ref%swith nonexistent object%s",2768 lock->ref_name,sha1_to_hex(sha1));2769unlock_ref(lock);2770return-1;2771}2772if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2773strbuf_addf(err,2774"Trying to write non-commit object%sto branch%s",2775sha1_to_hex(sha1), lock->ref_name);2776unlock_ref(lock);2777return-1;2778}2779 fd =get_lock_file_fd(lock->lk);2780if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2781write_in_full(fd, &term,1) !=1||2782close_ref(lock) <0) {2783strbuf_addf(err,2784"Couldn't write%s",get_lock_file_path(lock->lk));2785unlock_ref(lock);2786return-1;2787}2788return0;2789}27902791/*2792 * Commit a change to a loose reference that has already been written2793 * to the loose reference lockfile. Also update the reflogs if2794 * necessary, using the specified lockmsg (which can be NULL).2795 */2796static intcommit_ref_update(struct ref_lock *lock,2797const unsigned char*sha1,const char*logmsg,2798int flags,struct strbuf *err)2799{2800clear_loose_ref_cache(&ref_cache);2801if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2802(strcmp(lock->ref_name, lock->orig_ref_name) &&2803log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2804char*old_msg =strbuf_detach(err, NULL);2805strbuf_addf(err,"Cannot update the ref '%s':%s",2806 lock->ref_name, old_msg);2807free(old_msg);2808unlock_ref(lock);2809return-1;2810}2811if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2812/*2813 * Special hack: If a branch is updated directly and HEAD2814 * points to it (may happen on the remote side of a push2815 * for example) then logically the HEAD reflog should be2816 * updated too.2817 * A generic solution implies reverse symref information,2818 * but finding all symrefs pointing to the given branch2819 * would be rather costly for this rare event (the direct2820 * update of a branch) to be worth it. So let's cheat and2821 * check with HEAD only which should cover 99% of all usage2822 * scenarios (even 100% of the default ones).2823 */2824unsigned char head_sha1[20];2825int head_flag;2826const char*head_ref;2827 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2828 head_sha1, &head_flag);2829if(head_ref && (head_flag & REF_ISSYMREF) &&2830!strcmp(head_ref, lock->ref_name)) {2831struct strbuf log_err = STRBUF_INIT;2832if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2833 logmsg,0, &log_err)) {2834error("%s", log_err.buf);2835strbuf_release(&log_err);2836}2837}2838}2839if(commit_ref(lock)) {2840error("Couldn't set%s", lock->ref_name);2841unlock_ref(lock);2842return-1;2843}28442845unlock_ref(lock);2846return0;2847}28482849intcreate_symref(const char*ref_target,const char*refs_heads_master,2850const char*logmsg)2851{2852char*lockpath = NULL;2853char ref[1000];2854int fd, len, written;2855char*git_HEAD =git_pathdup("%s", ref_target);2856unsigned char old_sha1[20], new_sha1[20];2857struct strbuf err = STRBUF_INIT;28582859if(logmsg &&read_ref(ref_target, old_sha1))2860hashclr(old_sha1);28612862if(safe_create_leading_directories(git_HEAD) <0)2863returnerror("unable to create directory for%s", git_HEAD);28642865#ifndef NO_SYMLINK_HEAD2866if(prefer_symlink_refs) {2867unlink(git_HEAD);2868if(!symlink(refs_heads_master, git_HEAD))2869goto done;2870fprintf(stderr,"no symlink - falling back to symbolic ref\n");2871}2872#endif28732874 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);2875if(sizeof(ref) <= len) {2876error("refname too long:%s", refs_heads_master);2877goto error_free_return;2878}2879 lockpath =mkpathdup("%s.lock", git_HEAD);2880 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);2881if(fd <0) {2882error("Unable to open%sfor writing", lockpath);2883goto error_free_return;2884}2885 written =write_in_full(fd, ref, len);2886if(close(fd) !=0|| written != len) {2887error("Unable to write to%s", lockpath);2888goto error_unlink_return;2889}2890if(rename(lockpath, git_HEAD) <0) {2891error("Unable to create%s", git_HEAD);2892goto error_unlink_return;2893}2894if(adjust_shared_perm(git_HEAD)) {2895error("Unable to fix permissions on%s", lockpath);2896 error_unlink_return:2897unlink_or_warn(lockpath);2898 error_free_return:2899free(lockpath);2900free(git_HEAD);2901return-1;2902}2903free(lockpath);29042905#ifndef NO_SYMLINK_HEAD2906 done:2907#endif2908if(logmsg && !read_ref(refs_heads_master, new_sha1) &&2909log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {2910error("%s", err.buf);2911strbuf_release(&err);2912}29132914free(git_HEAD);2915return0;2916}29172918intreflog_exists(const char*refname)2919{2920struct stat st;29212922return!lstat(git_path("logs/%s", refname), &st) &&2923S_ISREG(st.st_mode);2924}29252926intdelete_reflog(const char*refname)2927{2928returnremove_path(git_path("logs/%s", refname));2929}29302931static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2932{2933unsigned char osha1[20], nsha1[20];2934char*email_end, *message;2935unsigned long timestamp;2936int tz;29372938/* old SP new SP name <email> SP time TAB msg LF */2939if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2940get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2941get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2942!(email_end =strchr(sb->buf +82,'>')) ||2943 email_end[1] !=' '||2944!(timestamp =strtoul(email_end +2, &message,10)) ||2945!message || message[0] !=' '||2946(message[1] !='+'&& message[1] !='-') ||2947!isdigit(message[2]) || !isdigit(message[3]) ||2948!isdigit(message[4]) || !isdigit(message[5]))2949return0;/* corrupt? */2950 email_end[1] ='\0';2951 tz =strtol(message +1, NULL,10);2952if(message[6] !='\t')2953 message +=6;2954else2955 message +=7;2956returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2957}29582959static char*find_beginning_of_line(char*bob,char*scan)2960{2961while(bob < scan && *(--scan) !='\n')2962;/* keep scanning backwards */2963/*2964 * Return either beginning of the buffer, or LF at the end of2965 * the previous line.2966 */2967return scan;2968}29692970intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2971{2972struct strbuf sb = STRBUF_INIT;2973FILE*logfp;2974long pos;2975int ret =0, at_tail =1;29762977 logfp =fopen(git_path("logs/%s", refname),"r");2978if(!logfp)2979return-1;29802981/* Jump to the end */2982if(fseek(logfp,0, SEEK_END) <0)2983returnerror("cannot seek back reflog for%s:%s",2984 refname,strerror(errno));2985 pos =ftell(logfp);2986while(!ret &&0< pos) {2987int cnt;2988size_t nread;2989char buf[BUFSIZ];2990char*endp, *scanp;29912992/* Fill next block from the end */2993 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2994if(fseek(logfp, pos - cnt, SEEK_SET))2995returnerror("cannot seek back reflog for%s:%s",2996 refname,strerror(errno));2997 nread =fread(buf, cnt,1, logfp);2998if(nread !=1)2999returnerror("cannot read%dbytes from reflog for%s:%s",3000 cnt, refname,strerror(errno));3001 pos -= cnt;30023003 scanp = endp = buf + cnt;3004if(at_tail && scanp[-1] =='\n')3005/* Looking at the final LF at the end of the file */3006 scanp--;3007 at_tail =0;30083009while(buf < scanp) {3010/*3011 * terminating LF of the previous line, or the beginning3012 * of the buffer.3013 */3014char*bp;30153016 bp =find_beginning_of_line(buf, scanp);30173018if(*bp =='\n') {3019/*3020 * The newline is the end of the previous line,3021 * so we know we have complete line starting3022 * at (bp + 1). Prefix it onto any prior data3023 * we collected for the line and process it.3024 */3025strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3026 scanp = bp;3027 endp = bp +1;3028 ret =show_one_reflog_ent(&sb, fn, cb_data);3029strbuf_reset(&sb);3030if(ret)3031break;3032}else if(!pos) {3033/*3034 * We are at the start of the buffer, and the3035 * start of the file; there is no previous3036 * line, and we have everything for this one.3037 * Process it, and we can end the loop.3038 */3039strbuf_splice(&sb,0,0, buf, endp - buf);3040 ret =show_one_reflog_ent(&sb, fn, cb_data);3041strbuf_reset(&sb);3042break;3043}30443045if(bp == buf) {3046/*3047 * We are at the start of the buffer, and there3048 * is more file to read backwards. Which means3049 * we are in the middle of a line. Note that we3050 * may get here even if *bp was a newline; that3051 * just means we are at the exact end of the3052 * previous line, rather than some spot in the3053 * middle.3054 *3055 * Save away what we have to be combined with3056 * the data from the next read.3057 */3058strbuf_splice(&sb,0,0, buf, endp - buf);3059break;3060}3061}30623063}3064if(!ret && sb.len)3065die("BUG: reverse reflog parser had leftover data");30663067fclose(logfp);3068strbuf_release(&sb);3069return ret;3070}30713072intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3073{3074FILE*logfp;3075struct strbuf sb = STRBUF_INIT;3076int ret =0;30773078 logfp =fopen(git_path("logs/%s", refname),"r");3079if(!logfp)3080return-1;30813082while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3083 ret =show_one_reflog_ent(&sb, fn, cb_data);3084fclose(logfp);3085strbuf_release(&sb);3086return ret;3087}3088/*3089 * Call fn for each reflog in the namespace indicated by name. name3090 * must be empty or end with '/'. Name will be used as a scratch3091 * space, but its contents will be restored before return.3092 */3093static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3094{3095DIR*d =opendir(git_path("logs/%s", name->buf));3096int retval =0;3097struct dirent *de;3098int oldlen = name->len;30993100if(!d)3101return name->len ? errno :0;31023103while((de =readdir(d)) != NULL) {3104struct stat st;31053106if(de->d_name[0] =='.')3107continue;3108if(ends_with(de->d_name,".lock"))3109continue;3110strbuf_addstr(name, de->d_name);3111if(stat(git_path("logs/%s", name->buf), &st) <0) {3112;/* silently ignore */3113}else{3114if(S_ISDIR(st.st_mode)) {3115strbuf_addch(name,'/');3116 retval =do_for_each_reflog(name, fn, cb_data);3117}else{3118struct object_id oid;31193120if(read_ref_full(name->buf,0, oid.hash, NULL))3121 retval =error("bad ref for%s", name->buf);3122else3123 retval =fn(name->buf, &oid,0, cb_data);3124}3125if(retval)3126break;3127}3128strbuf_setlen(name, oldlen);3129}3130closedir(d);3131return retval;3132}31333134intfor_each_reflog(each_ref_fn fn,void*cb_data)3135{3136int retval;3137struct strbuf name;3138strbuf_init(&name, PATH_MAX);3139 retval =do_for_each_reflog(&name, fn, cb_data);3140strbuf_release(&name);3141return retval;3142}31433144static intref_update_reject_duplicates(struct string_list *refnames,3145struct strbuf *err)3146{3147int i, n = refnames->nr;31483149assert(err);31503151for(i =1; i < n; i++)3152if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3153strbuf_addf(err,3154"Multiple updates for ref '%s' not allowed.",3155 refnames->items[i].string);3156return1;3157}3158return0;3159}31603161intref_transaction_commit(struct ref_transaction *transaction,3162struct strbuf *err)3163{3164int ret =0, i;3165int n = transaction->nr;3166struct ref_update **updates = transaction->updates;3167struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3168struct string_list_item *ref_to_delete;3169struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31703171assert(err);31723173if(transaction->state != REF_TRANSACTION_OPEN)3174die("BUG: commit called for transaction that is not open");31753176if(!n) {3177 transaction->state = REF_TRANSACTION_CLOSED;3178return0;3179}31803181/* Fail if a refname appears more than once in the transaction: */3182for(i =0; i < n; i++)3183string_list_append(&affected_refnames, updates[i]->refname);3184string_list_sort(&affected_refnames);3185if(ref_update_reject_duplicates(&affected_refnames, err)) {3186 ret = TRANSACTION_GENERIC_ERROR;3187goto cleanup;3188}31893190/*3191 * Acquire all locks, verify old values if provided, check3192 * that new values are valid, and write new values to the3193 * lockfiles, ready to be activated. Only keep one lockfile3194 * open at a time to avoid running out of file descriptors.3195 */3196for(i =0; i < n; i++) {3197struct ref_update *update = updates[i];31983199if((update->flags & REF_HAVE_NEW) &&3200is_null_sha1(update->new_sha1))3201 update->flags |= REF_DELETING;3202 update->lock =lock_ref_sha1_basic(3203 update->refname,3204((update->flags & REF_HAVE_OLD) ?3205 update->old_sha1 : NULL),3206&affected_refnames, NULL,3207 update->flags,3208&update->type,3209 err);3210if(!update->lock) {3211char*reason;32123213 ret = (errno == ENOTDIR)3214? TRANSACTION_NAME_CONFLICT3215: TRANSACTION_GENERIC_ERROR;3216 reason =strbuf_detach(err, NULL);3217strbuf_addf(err,"cannot lock ref '%s':%s",3218 update->refname, reason);3219free(reason);3220goto cleanup;3221}3222if((update->flags & REF_HAVE_NEW) &&3223!(update->flags & REF_DELETING)) {3224int overwriting_symref = ((update->type & REF_ISSYMREF) &&3225(update->flags & REF_NODEREF));32263227if(!overwriting_symref &&3228!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3229/*3230 * The reference already has the desired3231 * value, so we don't need to write it.3232 */3233}else if(write_ref_to_lockfile(update->lock,3234 update->new_sha1,3235 err)) {3236char*write_err =strbuf_detach(err, NULL);32373238/*3239 * The lock was freed upon failure of3240 * write_ref_to_lockfile():3241 */3242 update->lock = NULL;3243strbuf_addf(err,3244"cannot update the ref '%s':%s",3245 update->refname, write_err);3246free(write_err);3247 ret = TRANSACTION_GENERIC_ERROR;3248goto cleanup;3249}else{3250 update->flags |= REF_NEEDS_COMMIT;3251}3252}3253if(!(update->flags & REF_NEEDS_COMMIT)) {3254/*3255 * We didn't have to write anything to the lockfile.3256 * Close it to free up the file descriptor:3257 */3258if(close_ref(update->lock)) {3259strbuf_addf(err,"Couldn't close%s.lock",3260 update->refname);3261goto cleanup;3262}3263}3264}32653266/* Perform updates first so live commits remain referenced */3267for(i =0; i < n; i++) {3268struct ref_update *update = updates[i];32693270if(update->flags & REF_NEEDS_COMMIT) {3271if(commit_ref_update(update->lock,3272 update->new_sha1, update->msg,3273 update->flags, err)) {3274/* freed by commit_ref_update(): */3275 update->lock = NULL;3276 ret = TRANSACTION_GENERIC_ERROR;3277goto cleanup;3278}else{3279/* freed by commit_ref_update(): */3280 update->lock = NULL;3281}3282}3283}32843285/* Perform deletes now that updates are safely completed */3286for(i =0; i < n; i++) {3287struct ref_update *update = updates[i];32883289if(update->flags & REF_DELETING) {3290if(delete_ref_loose(update->lock, update->type, err)) {3291 ret = TRANSACTION_GENERIC_ERROR;3292goto cleanup;3293}32943295if(!(update->flags & REF_ISPRUNING))3296string_list_append(&refs_to_delete,3297 update->lock->ref_name);3298}3299}33003301if(repack_without_refs(&refs_to_delete, err)) {3302 ret = TRANSACTION_GENERIC_ERROR;3303goto cleanup;3304}3305for_each_string_list_item(ref_to_delete, &refs_to_delete)3306unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3307clear_loose_ref_cache(&ref_cache);33083309cleanup:3310 transaction->state = REF_TRANSACTION_CLOSED;33113312for(i =0; i < n; i++)3313if(updates[i]->lock)3314unlock_ref(updates[i]->lock);3315string_list_clear(&refs_to_delete,0);3316string_list_clear(&affected_refnames,0);3317return ret;3318}33193320static intref_present(const char*refname,3321const struct object_id *oid,int flags,void*cb_data)3322{3323struct string_list *affected_refnames = cb_data;33243325returnstring_list_has_string(affected_refnames, refname);3326}33273328intinitial_ref_transaction_commit(struct ref_transaction *transaction,3329struct strbuf *err)3330{3331int ret =0, i;3332int n = transaction->nr;3333struct ref_update **updates = transaction->updates;3334struct string_list affected_refnames = STRING_LIST_INIT_NODUP;33353336assert(err);33373338if(transaction->state != REF_TRANSACTION_OPEN)3339die("BUG: commit called for transaction that is not open");33403341/* Fail if a refname appears more than once in the transaction: */3342for(i =0; i < n; i++)3343string_list_append(&affected_refnames, updates[i]->refname);3344string_list_sort(&affected_refnames);3345if(ref_update_reject_duplicates(&affected_refnames, err)) {3346 ret = TRANSACTION_GENERIC_ERROR;3347goto cleanup;3348}33493350/*3351 * It's really undefined to call this function in an active3352 * repository or when there are existing references: we are3353 * only locking and changing packed-refs, so (1) any3354 * simultaneous processes might try to change a reference at3355 * the same time we do, and (2) any existing loose versions of3356 * the references that we are setting would have precedence3357 * over our values. But some remote helpers create the remote3358 * "HEAD" and "master" branches before calling this function,3359 * so here we really only check that none of the references3360 * that we are creating already exists.3361 */3362if(for_each_rawref(ref_present, &affected_refnames))3363die("BUG: initial ref transaction called with existing refs");33643365for(i =0; i < n; i++) {3366struct ref_update *update = updates[i];33673368if((update->flags & REF_HAVE_OLD) &&3369!is_null_sha1(update->old_sha1))3370die("BUG: initial ref transaction with old_sha1 set");3371if(verify_refname_available(update->refname,3372&affected_refnames, NULL,3373 err)) {3374 ret = TRANSACTION_NAME_CONFLICT;3375goto cleanup;3376}3377}33783379if(lock_packed_refs(0)) {3380strbuf_addf(err,"unable to lock packed-refs file:%s",3381strerror(errno));3382 ret = TRANSACTION_GENERIC_ERROR;3383goto cleanup;3384}33853386for(i =0; i < n; i++) {3387struct ref_update *update = updates[i];33883389if((update->flags & REF_HAVE_NEW) &&3390!is_null_sha1(update->new_sha1))3391add_packed_ref(update->refname, update->new_sha1);3392}33933394if(commit_packed_refs()) {3395strbuf_addf(err,"unable to commit packed-refs file:%s",3396strerror(errno));3397 ret = TRANSACTION_GENERIC_ERROR;3398goto cleanup;3399}34003401cleanup:3402 transaction->state = REF_TRANSACTION_CLOSED;3403string_list_clear(&affected_refnames,0);3404return ret;3405}34063407struct expire_reflog_cb {3408unsigned int flags;3409 reflog_expiry_should_prune_fn *should_prune_fn;3410void*policy_cb;3411FILE*newlog;3412unsigned char last_kept_sha1[20];3413};34143415static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3416const char*email,unsigned long timestamp,int tz,3417const char*message,void*cb_data)3418{3419struct expire_reflog_cb *cb = cb_data;3420struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;34213422if(cb->flags & EXPIRE_REFLOGS_REWRITE)3423 osha1 = cb->last_kept_sha1;34243425if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3426 message, policy_cb)) {3427if(!cb->newlog)3428printf("would prune%s", message);3429else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3430printf("prune%s", message);3431}else{3432if(cb->newlog) {3433fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3434sha1_to_hex(osha1),sha1_to_hex(nsha1),3435 email, timestamp, tz, message);3436hashcpy(cb->last_kept_sha1, nsha1);3437}3438if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3439printf("keep%s", message);3440}3441return0;3442}34433444intreflog_expire(const char*refname,const unsigned char*sha1,3445unsigned int flags,3446 reflog_expiry_prepare_fn prepare_fn,3447 reflog_expiry_should_prune_fn should_prune_fn,3448 reflog_expiry_cleanup_fn cleanup_fn,3449void*policy_cb_data)3450{3451static struct lock_file reflog_lock;3452struct expire_reflog_cb cb;3453struct ref_lock *lock;3454char*log_file;3455int status =0;3456int type;3457struct strbuf err = STRBUF_INIT;34583459memset(&cb,0,sizeof(cb));3460 cb.flags = flags;3461 cb.policy_cb = policy_cb_data;3462 cb.should_prune_fn = should_prune_fn;34633464/*3465 * The reflog file is locked by holding the lock on the3466 * reference itself, plus we might need to update the3467 * reference if --updateref was specified:3468 */3469 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);3470if(!lock) {3471error("cannot lock ref '%s':%s", refname, err.buf);3472strbuf_release(&err);3473return-1;3474}3475if(!reflog_exists(refname)) {3476unlock_ref(lock);3477return0;3478}34793480 log_file =git_pathdup("logs/%s", refname);3481if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3482/*3483 * Even though holding $GIT_DIR/logs/$reflog.lock has3484 * no locking implications, we use the lock_file3485 * machinery here anyway because it does a lot of the3486 * work we need, including cleaning up if the program3487 * exits unexpectedly.3488 */3489if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3490struct strbuf err = STRBUF_INIT;3491unable_to_lock_message(log_file, errno, &err);3492error("%s", err.buf);3493strbuf_release(&err);3494goto failure;3495}3496 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3497if(!cb.newlog) {3498error("cannot fdopen%s(%s)",3499get_lock_file_path(&reflog_lock),strerror(errno));3500goto failure;3501}3502}35033504(*prepare_fn)(refname, sha1, cb.policy_cb);3505for_each_reflog_ent(refname, expire_reflog_ent, &cb);3506(*cleanup_fn)(cb.policy_cb);35073508if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3509/*3510 * It doesn't make sense to adjust a reference pointed3511 * to by a symbolic ref based on expiring entries in3512 * the symbolic reference's reflog. Nor can we update3513 * a reference if there are no remaining reflog3514 * entries.3515 */3516int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3517!(type & REF_ISSYMREF) &&3518!is_null_sha1(cb.last_kept_sha1);35193520if(close_lock_file(&reflog_lock)) {3521 status |=error("couldn't write%s:%s", log_file,3522strerror(errno));3523}else if(update &&3524(write_in_full(get_lock_file_fd(lock->lk),3525sha1_to_hex(cb.last_kept_sha1),40) !=40||3526write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3527close_ref(lock) <0)) {3528 status |=error("couldn't write%s",3529get_lock_file_path(lock->lk));3530rollback_lock_file(&reflog_lock);3531}else if(commit_lock_file(&reflog_lock)) {3532 status |=error("unable to commit reflog '%s' (%s)",3533 log_file,strerror(errno));3534}else if(update &&commit_ref(lock)) {3535 status |=error("couldn't set%s", lock->ref_name);3536}3537}3538free(log_file);3539unlock_ref(lock);3540return status;35413542 failure:3543rollback_lock_file(&reflog_lock);3544free(log_file);3545unlock_ref(lock);3546return-1;3547}