1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"../lockfile.h" 5#include"../object.h" 6#include"../dir.h" 7 8struct ref_lock { 9char*ref_name; 10char*orig_ref_name; 11struct lock_file *lk; 12struct object_id old_oid; 13}; 14 15struct ref_entry; 16 17/* 18 * Information used (along with the information in ref_entry) to 19 * describe a single cached reference. This data structure only 20 * occurs embedded in a union in struct ref_entry, and only when 21 * (ref_entry->flag & REF_DIR) is zero. 22 */ 23struct ref_value { 24/* 25 * The name of the object to which this reference resolves 26 * (which may be a tag object). If REF_ISBROKEN, this is 27 * null. If REF_ISSYMREF, then this is the name of the object 28 * referred to by the last reference in the symlink chain. 29 */ 30struct object_id oid; 31 32/* 33 * If REF_KNOWS_PEELED, then this field holds the peeled value 34 * of this reference, or null if the reference is known not to 35 * be peelable. See the documentation for peel_ref() for an 36 * exact definition of "peelable". 37 */ 38struct object_id peeled; 39}; 40 41struct ref_cache; 42 43/* 44 * Information used (along with the information in ref_entry) to 45 * describe a level in the hierarchy of references. This data 46 * structure only occurs embedded in a union in struct ref_entry, and 47 * only when (ref_entry.flag & REF_DIR) is set. In that case, 48 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 49 * in the directory have already been read: 50 * 51 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 52 * or packed references, already read. 53 * 54 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 55 * references that hasn't been read yet (nor has any of its 56 * subdirectories). 57 * 58 * Entries within a directory are stored within a growable array of 59 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 60 * sorted are sorted by their component name in strcmp() order and the 61 * remaining entries are unsorted. 62 * 63 * Loose references are read lazily, one directory at a time. When a 64 * directory of loose references is read, then all of the references 65 * in that directory are stored, and REF_INCOMPLETE stubs are created 66 * for any subdirectories, but the subdirectories themselves are not 67 * read. The reading is triggered by get_ref_dir(). 68 */ 69struct ref_dir { 70int nr, alloc; 71 72/* 73 * Entries with index 0 <= i < sorted are sorted by name. New 74 * entries are appended to the list unsorted, and are sorted 75 * only when required; thus we avoid the need to sort the list 76 * after the addition of every reference. 77 */ 78int sorted; 79 80/* A pointer to the ref_cache that contains this ref_dir. */ 81struct ref_cache *ref_cache; 82 83struct ref_entry **entries; 84}; 85 86/* 87 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 88 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 89 * public values; see refs.h. 90 */ 91 92/* 93 * The field ref_entry->u.value.peeled of this value entry contains 94 * the correct peeled value for the reference, which might be 95 * null_sha1 if the reference is not a tag or if it is broken. 96 */ 97#define REF_KNOWS_PEELED 0x10 98 99/* ref_entry represents a directory of references */ 100#define REF_DIR 0x20 101 102/* 103 * Entry has not yet been read from disk (used only for REF_DIR 104 * entries representing loose references) 105 */ 106#define REF_INCOMPLETE 0x40 107 108/* 109 * A ref_entry represents either a reference or a "subdirectory" of 110 * references. 111 * 112 * Each directory in the reference namespace is represented by a 113 * ref_entry with (flags & REF_DIR) set and containing a subdir member 114 * that holds the entries in that directory that have been read so 115 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 116 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 117 * used for loose reference directories. 118 * 119 * References are represented by a ref_entry with (flags & REF_DIR) 120 * unset and a value member that describes the reference's value. The 121 * flag member is at the ref_entry level, but it is also needed to 122 * interpret the contents of the value field (in other words, a 123 * ref_value object is not very much use without the enclosing 124 * ref_entry). 125 * 126 * Reference names cannot end with slash and directories' names are 127 * always stored with a trailing slash (except for the top-level 128 * directory, which is always denoted by ""). This has two nice 129 * consequences: (1) when the entries in each subdir are sorted 130 * lexicographically by name (as they usually are), the references in 131 * a whole tree can be generated in lexicographic order by traversing 132 * the tree in left-to-right, depth-first order; (2) the names of 133 * references and subdirectories cannot conflict, and therefore the 134 * presence of an empty subdirectory does not block the creation of a 135 * similarly-named reference. (The fact that reference names with the 136 * same leading components can conflict *with each other* is a 137 * separate issue that is regulated by verify_refname_available().) 138 * 139 * Please note that the name field contains the fully-qualified 140 * reference (or subdirectory) name. Space could be saved by only 141 * storing the relative names. But that would require the full names 142 * to be generated on the fly when iterating in do_for_each_ref(), and 143 * would break callback functions, who have always been able to assume 144 * that the name strings that they are passed will not be freed during 145 * the iteration. 146 */ 147struct ref_entry { 148unsigned char flag;/* ISSYMREF? ISPACKED? */ 149union{ 150struct ref_value value;/* if not (flags&REF_DIR) */ 151struct ref_dir subdir;/* if (flags&REF_DIR) */ 152} u; 153/* 154 * The full name of the reference (e.g., "refs/heads/master") 155 * or the full name of the directory with a trailing slash 156 * (e.g., "refs/heads/"): 157 */ 158char name[FLEX_ARRAY]; 159}; 160 161static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 162static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len); 163static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 164const char*dirname,size_t len, 165int incomplete); 166static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry); 167 168static struct ref_dir *get_ref_dir(struct ref_entry *entry) 169{ 170struct ref_dir *dir; 171assert(entry->flag & REF_DIR); 172 dir = &entry->u.subdir; 173if(entry->flag & REF_INCOMPLETE) { 174read_loose_refs(entry->name, dir); 175 176/* 177 * Manually add refs/bisect, which, being 178 * per-worktree, might not appear in the directory 179 * listing for refs/ in the main repo. 180 */ 181if(!strcmp(entry->name,"refs/")) { 182int pos =search_ref_dir(dir,"refs/bisect/",12); 183if(pos <0) { 184struct ref_entry *child_entry; 185 child_entry =create_dir_entry(dir->ref_cache, 186"refs/bisect/", 18712,1); 188add_entry_to_dir(dir, child_entry); 189read_loose_refs("refs/bisect", 190&child_entry->u.subdir); 191} 192} 193 entry->flag &= ~REF_INCOMPLETE; 194} 195return dir; 196} 197 198static struct ref_entry *create_ref_entry(const char*refname, 199const unsigned char*sha1,int flag, 200int check_name) 201{ 202struct ref_entry *ref; 203 204if(check_name && 205check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 206die("Reference has invalid format: '%s'", refname); 207FLEX_ALLOC_STR(ref, name, refname); 208hashcpy(ref->u.value.oid.hash, sha1); 209oidclr(&ref->u.value.peeled); 210 ref->flag = flag; 211return ref; 212} 213 214static voidclear_ref_dir(struct ref_dir *dir); 215 216static voidfree_ref_entry(struct ref_entry *entry) 217{ 218if(entry->flag & REF_DIR) { 219/* 220 * Do not use get_ref_dir() here, as that might 221 * trigger the reading of loose refs. 222 */ 223clear_ref_dir(&entry->u.subdir); 224} 225free(entry); 226} 227 228/* 229 * Add a ref_entry to the end of dir (unsorted). Entry is always 230 * stored directly in dir; no recursion into subdirectories is 231 * done. 232 */ 233static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 234{ 235ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 236 dir->entries[dir->nr++] = entry; 237/* optimize for the case that entries are added in order */ 238if(dir->nr ==1|| 239(dir->nr == dir->sorted +1&& 240strcmp(dir->entries[dir->nr -2]->name, 241 dir->entries[dir->nr -1]->name) <0)) 242 dir->sorted = dir->nr; 243} 244 245/* 246 * Clear and free all entries in dir, recursively. 247 */ 248static voidclear_ref_dir(struct ref_dir *dir) 249{ 250int i; 251for(i =0; i < dir->nr; i++) 252free_ref_entry(dir->entries[i]); 253free(dir->entries); 254 dir->sorted = dir->nr = dir->alloc =0; 255 dir->entries = NULL; 256} 257 258/* 259 * Create a struct ref_entry object for the specified dirname. 260 * dirname is the name of the directory with a trailing slash (e.g., 261 * "refs/heads/") or "" for the top-level directory. 262 */ 263static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 264const char*dirname,size_t len, 265int incomplete) 266{ 267struct ref_entry *direntry; 268FLEX_ALLOC_MEM(direntry, name, dirname, len); 269 direntry->u.subdir.ref_cache = ref_cache; 270 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 271return direntry; 272} 273 274static intref_entry_cmp(const void*a,const void*b) 275{ 276struct ref_entry *one = *(struct ref_entry **)a; 277struct ref_entry *two = *(struct ref_entry **)b; 278returnstrcmp(one->name, two->name); 279} 280 281static voidsort_ref_dir(struct ref_dir *dir); 282 283struct string_slice { 284size_t len; 285const char*str; 286}; 287 288static intref_entry_cmp_sslice(const void*key_,const void*ent_) 289{ 290const struct string_slice *key = key_; 291const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 292int cmp =strncmp(key->str, ent->name, key->len); 293if(cmp) 294return cmp; 295return'\0'- (unsigned char)ent->name[key->len]; 296} 297 298/* 299 * Return the index of the entry with the given refname from the 300 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 301 * no such entry is found. dir must already be complete. 302 */ 303static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 304{ 305struct ref_entry **r; 306struct string_slice key; 307 308if(refname == NULL || !dir->nr) 309return-1; 310 311sort_ref_dir(dir); 312 key.len = len; 313 key.str = refname; 314 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 315 ref_entry_cmp_sslice); 316 317if(r == NULL) 318return-1; 319 320return r - dir->entries; 321} 322 323/* 324 * Search for a directory entry directly within dir (without 325 * recursing). Sort dir if necessary. subdirname must be a directory 326 * name (i.e., end in '/'). If mkdir is set, then create the 327 * directory if it is missing; otherwise, return NULL if the desired 328 * directory cannot be found. dir must already be complete. 329 */ 330static struct ref_dir *search_for_subdir(struct ref_dir *dir, 331const char*subdirname,size_t len, 332int mkdir) 333{ 334int entry_index =search_ref_dir(dir, subdirname, len); 335struct ref_entry *entry; 336if(entry_index == -1) { 337if(!mkdir) 338return NULL; 339/* 340 * Since dir is complete, the absence of a subdir 341 * means that the subdir really doesn't exist; 342 * therefore, create an empty record for it but mark 343 * the record complete. 344 */ 345 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 346add_entry_to_dir(dir, entry); 347}else{ 348 entry = dir->entries[entry_index]; 349} 350returnget_ref_dir(entry); 351} 352 353/* 354 * If refname is a reference name, find the ref_dir within the dir 355 * tree that should hold refname. If refname is a directory name 356 * (i.e., ends in '/'), then return that ref_dir itself. dir must 357 * represent the top-level directory and must already be complete. 358 * Sort ref_dirs and recurse into subdirectories as necessary. If 359 * mkdir is set, then create any missing directories; otherwise, 360 * return NULL if the desired directory cannot be found. 361 */ 362static struct ref_dir *find_containing_dir(struct ref_dir *dir, 363const char*refname,int mkdir) 364{ 365const char*slash; 366for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 367size_t dirnamelen = slash - refname +1; 368struct ref_dir *subdir; 369 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 370if(!subdir) { 371 dir = NULL; 372break; 373} 374 dir = subdir; 375} 376 377return dir; 378} 379 380/* 381 * Find the value entry with the given name in dir, sorting ref_dirs 382 * and recursing into subdirectories as necessary. If the name is not 383 * found or it corresponds to a directory entry, return NULL. 384 */ 385static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 386{ 387int entry_index; 388struct ref_entry *entry; 389 dir =find_containing_dir(dir, refname,0); 390if(!dir) 391return NULL; 392 entry_index =search_ref_dir(dir, refname,strlen(refname)); 393if(entry_index == -1) 394return NULL; 395 entry = dir->entries[entry_index]; 396return(entry->flag & REF_DIR) ? NULL : entry; 397} 398 399/* 400 * Remove the entry with the given name from dir, recursing into 401 * subdirectories as necessary. If refname is the name of a directory 402 * (i.e., ends with '/'), then remove the directory and its contents. 403 * If the removal was successful, return the number of entries 404 * remaining in the directory entry that contained the deleted entry. 405 * If the name was not found, return -1. Please note that this 406 * function only deletes the entry from the cache; it does not delete 407 * it from the filesystem or ensure that other cache entries (which 408 * might be symbolic references to the removed entry) are updated. 409 * Nor does it remove any containing dir entries that might be made 410 * empty by the removal. dir must represent the top-level directory 411 * and must already be complete. 412 */ 413static intremove_entry(struct ref_dir *dir,const char*refname) 414{ 415int refname_len =strlen(refname); 416int entry_index; 417struct ref_entry *entry; 418int is_dir = refname[refname_len -1] =='/'; 419if(is_dir) { 420/* 421 * refname represents a reference directory. Remove 422 * the trailing slash; otherwise we will get the 423 * directory *representing* refname rather than the 424 * one *containing* it. 425 */ 426char*dirname =xmemdupz(refname, refname_len -1); 427 dir =find_containing_dir(dir, dirname,0); 428free(dirname); 429}else{ 430 dir =find_containing_dir(dir, refname,0); 431} 432if(!dir) 433return-1; 434 entry_index =search_ref_dir(dir, refname, refname_len); 435if(entry_index == -1) 436return-1; 437 entry = dir->entries[entry_index]; 438 439memmove(&dir->entries[entry_index], 440&dir->entries[entry_index +1], 441(dir->nr - entry_index -1) *sizeof(*dir->entries) 442); 443 dir->nr--; 444if(dir->sorted > entry_index) 445 dir->sorted--; 446free_ref_entry(entry); 447return dir->nr; 448} 449 450/* 451 * Add a ref_entry to the ref_dir (unsorted), recursing into 452 * subdirectories as necessary. dir must represent the top-level 453 * directory. Return 0 on success. 454 */ 455static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 456{ 457 dir =find_containing_dir(dir, ref->name,1); 458if(!dir) 459return-1; 460add_entry_to_dir(dir, ref); 461return0; 462} 463 464/* 465 * Emit a warning and return true iff ref1 and ref2 have the same name 466 * and the same sha1. Die if they have the same name but different 467 * sha1s. 468 */ 469static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 470{ 471if(strcmp(ref1->name, ref2->name)) 472return0; 473 474/* Duplicate name; make sure that they don't conflict: */ 475 476if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 477/* This is impossible by construction */ 478die("Reference directory conflict:%s", ref1->name); 479 480if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 481die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 482 483warning("Duplicated ref:%s", ref1->name); 484return1; 485} 486 487/* 488 * Sort the entries in dir non-recursively (if they are not already 489 * sorted) and remove any duplicate entries. 490 */ 491static voidsort_ref_dir(struct ref_dir *dir) 492{ 493int i, j; 494struct ref_entry *last = NULL; 495 496/* 497 * This check also prevents passing a zero-length array to qsort(), 498 * which is a problem on some platforms. 499 */ 500if(dir->sorted == dir->nr) 501return; 502 503qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 504 505/* Remove any duplicates: */ 506for(i =0, j =0; j < dir->nr; j++) { 507struct ref_entry *entry = dir->entries[j]; 508if(last &&is_dup_ref(last, entry)) 509free_ref_entry(entry); 510else 511 last = dir->entries[i++] = entry; 512} 513 dir->sorted = dir->nr = i; 514} 515 516/* Include broken references in a do_for_each_ref*() iteration: */ 517#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 518 519/* 520 * Return true iff the reference described by entry can be resolved to 521 * an object in the database. Emit a warning if the referred-to 522 * object does not exist. 523 */ 524static intref_resolves_to_object(struct ref_entry *entry) 525{ 526if(entry->flag & REF_ISBROKEN) 527return0; 528if(!has_sha1_file(entry->u.value.oid.hash)) { 529error("%sdoes not point to a valid object!", entry->name); 530return0; 531} 532return1; 533} 534 535/* 536 * current_ref is a performance hack: when iterating over references 537 * using the for_each_ref*() functions, current_ref is set to the 538 * current reference's entry before calling the callback function. If 539 * the callback function calls peel_ref(), then peel_ref() first 540 * checks whether the reference to be peeled is the current reference 541 * (it usually is) and if so, returns that reference's peeled version 542 * if it is available. This avoids a refname lookup in a common case. 543 */ 544static struct ref_entry *current_ref; 545 546typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 547 548struct ref_entry_cb { 549const char*base; 550int trim; 551int flags; 552 each_ref_fn *fn; 553void*cb_data; 554}; 555 556/* 557 * Handle one reference in a do_for_each_ref*()-style iteration, 558 * calling an each_ref_fn for each entry. 559 */ 560static intdo_one_ref(struct ref_entry *entry,void*cb_data) 561{ 562struct ref_entry_cb *data = cb_data; 563struct ref_entry *old_current_ref; 564int retval; 565 566if(!starts_with(entry->name, data->base)) 567return0; 568 569if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 570!ref_resolves_to_object(entry)) 571return0; 572 573/* Store the old value, in case this is a recursive call: */ 574 old_current_ref = current_ref; 575 current_ref = entry; 576 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 577 entry->flag, data->cb_data); 578 current_ref = old_current_ref; 579return retval; 580} 581 582/* 583 * Call fn for each reference in dir that has index in the range 584 * offset <= index < dir->nr. Recurse into subdirectories that are in 585 * that index range, sorting them before iterating. This function 586 * does not sort dir itself; it should be sorted beforehand. fn is 587 * called for all references, including broken ones. 588 */ 589static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 590 each_ref_entry_fn fn,void*cb_data) 591{ 592int i; 593assert(dir->sorted == dir->nr); 594for(i = offset; i < dir->nr; i++) { 595struct ref_entry *entry = dir->entries[i]; 596int retval; 597if(entry->flag & REF_DIR) { 598struct ref_dir *subdir =get_ref_dir(entry); 599sort_ref_dir(subdir); 600 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 601}else{ 602 retval =fn(entry, cb_data); 603} 604if(retval) 605return retval; 606} 607return0; 608} 609 610/* 611 * Call fn for each reference in the union of dir1 and dir2, in order 612 * by refname. Recurse into subdirectories. If a value entry appears 613 * in both dir1 and dir2, then only process the version that is in 614 * dir2. The input dirs must already be sorted, but subdirs will be 615 * sorted as needed. fn is called for all references, including 616 * broken ones. 617 */ 618static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 619struct ref_dir *dir2, 620 each_ref_entry_fn fn,void*cb_data) 621{ 622int retval; 623int i1 =0, i2 =0; 624 625assert(dir1->sorted == dir1->nr); 626assert(dir2->sorted == dir2->nr); 627while(1) { 628struct ref_entry *e1, *e2; 629int cmp; 630if(i1 == dir1->nr) { 631returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 632} 633if(i2 == dir2->nr) { 634returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 635} 636 e1 = dir1->entries[i1]; 637 e2 = dir2->entries[i2]; 638 cmp =strcmp(e1->name, e2->name); 639if(cmp ==0) { 640if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 641/* Both are directories; descend them in parallel. */ 642struct ref_dir *subdir1 =get_ref_dir(e1); 643struct ref_dir *subdir2 =get_ref_dir(e2); 644sort_ref_dir(subdir1); 645sort_ref_dir(subdir2); 646 retval =do_for_each_entry_in_dirs( 647 subdir1, subdir2, fn, cb_data); 648 i1++; 649 i2++; 650}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 651/* Both are references; ignore the one from dir1. */ 652 retval =fn(e2, cb_data); 653 i1++; 654 i2++; 655}else{ 656die("conflict between reference and directory:%s", 657 e1->name); 658} 659}else{ 660struct ref_entry *e; 661if(cmp <0) { 662 e = e1; 663 i1++; 664}else{ 665 e = e2; 666 i2++; 667} 668if(e->flag & REF_DIR) { 669struct ref_dir *subdir =get_ref_dir(e); 670sort_ref_dir(subdir); 671 retval =do_for_each_entry_in_dir( 672 subdir,0, fn, cb_data); 673}else{ 674 retval =fn(e, cb_data); 675} 676} 677if(retval) 678return retval; 679} 680} 681 682/* 683 * Load all of the refs from the dir into our in-memory cache. The hard work 684 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 685 * through all of the sub-directories. We do not even need to care about 686 * sorting, as traversal order does not matter to us. 687 */ 688static voidprime_ref_dir(struct ref_dir *dir) 689{ 690int i; 691for(i =0; i < dir->nr; i++) { 692struct ref_entry *entry = dir->entries[i]; 693if(entry->flag & REF_DIR) 694prime_ref_dir(get_ref_dir(entry)); 695} 696} 697 698struct nonmatching_ref_data { 699const struct string_list *skip; 700const char*conflicting_refname; 701}; 702 703static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 704{ 705struct nonmatching_ref_data *data = vdata; 706 707if(data->skip &&string_list_has_string(data->skip, entry->name)) 708return0; 709 710 data->conflicting_refname = entry->name; 711return1; 712} 713 714/* 715 * Return 0 if a reference named refname could be created without 716 * conflicting with the name of an existing reference in dir. 717 * See verify_refname_available for more information. 718 */ 719static intverify_refname_available_dir(const char*refname, 720const struct string_list *extras, 721const struct string_list *skip, 722struct ref_dir *dir, 723struct strbuf *err) 724{ 725const char*slash; 726const char*extra_refname; 727int pos; 728struct strbuf dirname = STRBUF_INIT; 729int ret = -1; 730 731/* 732 * For the sake of comments in this function, suppose that 733 * refname is "refs/foo/bar". 734 */ 735 736assert(err); 737 738strbuf_grow(&dirname,strlen(refname) +1); 739for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 740/* Expand dirname to the new prefix, not including the trailing slash: */ 741strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 742 743/* 744 * We are still at a leading dir of the refname (e.g., 745 * "refs/foo"; if there is a reference with that name, 746 * it is a conflict, *unless* it is in skip. 747 */ 748if(dir) { 749 pos =search_ref_dir(dir, dirname.buf, dirname.len); 750if(pos >=0&& 751(!skip || !string_list_has_string(skip, dirname.buf))) { 752/* 753 * We found a reference whose name is 754 * a proper prefix of refname; e.g., 755 * "refs/foo", and is not in skip. 756 */ 757strbuf_addf(err,"'%s' exists; cannot create '%s'", 758 dirname.buf, refname); 759goto cleanup; 760} 761} 762 763if(extras &&string_list_has_string(extras, dirname.buf) && 764(!skip || !string_list_has_string(skip, dirname.buf))) { 765strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 766 refname, dirname.buf); 767goto cleanup; 768} 769 770/* 771 * Otherwise, we can try to continue our search with 772 * the next component. So try to look up the 773 * directory, e.g., "refs/foo/". If we come up empty, 774 * we know there is nothing under this whole prefix, 775 * but even in that case we still have to continue the 776 * search for conflicts with extras. 777 */ 778strbuf_addch(&dirname,'/'); 779if(dir) { 780 pos =search_ref_dir(dir, dirname.buf, dirname.len); 781if(pos <0) { 782/* 783 * There was no directory "refs/foo/", 784 * so there is nothing under this 785 * whole prefix. So there is no need 786 * to continue looking for conflicting 787 * references. But we need to continue 788 * looking for conflicting extras. 789 */ 790 dir = NULL; 791}else{ 792 dir =get_ref_dir(dir->entries[pos]); 793} 794} 795} 796 797/* 798 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 799 * There is no point in searching for a reference with that 800 * name, because a refname isn't considered to conflict with 801 * itself. But we still need to check for references whose 802 * names are in the "refs/foo/bar/" namespace, because they 803 * *do* conflict. 804 */ 805strbuf_addstr(&dirname, refname + dirname.len); 806strbuf_addch(&dirname,'/'); 807 808if(dir) { 809 pos =search_ref_dir(dir, dirname.buf, dirname.len); 810 811if(pos >=0) { 812/* 813 * We found a directory named "$refname/" 814 * (e.g., "refs/foo/bar/"). It is a problem 815 * iff it contains any ref that is not in 816 * "skip". 817 */ 818struct nonmatching_ref_data data; 819 820 data.skip = skip; 821 data.conflicting_refname = NULL; 822 dir =get_ref_dir(dir->entries[pos]); 823sort_ref_dir(dir); 824if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 825strbuf_addf(err,"'%s' exists; cannot create '%s'", 826 data.conflicting_refname, refname); 827goto cleanup; 828} 829} 830} 831 832 extra_refname =find_descendant_ref(dirname.buf, extras, skip); 833if(extra_refname) 834strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 835 refname, extra_refname); 836else 837 ret =0; 838 839cleanup: 840strbuf_release(&dirname); 841return ret; 842} 843 844struct packed_ref_cache { 845struct ref_entry *root; 846 847/* 848 * Count of references to the data structure in this instance, 849 * including the pointer from ref_cache::packed if any. The 850 * data will not be freed as long as the reference count is 851 * nonzero. 852 */ 853unsigned int referrers; 854 855/* 856 * Iff the packed-refs file associated with this instance is 857 * currently locked for writing, this points at the associated 858 * lock (which is owned by somebody else). The referrer count 859 * is also incremented when the file is locked and decremented 860 * when it is unlocked. 861 */ 862struct lock_file *lock; 863 864/* The metadata from when this packed-refs cache was read */ 865struct stat_validity validity; 866}; 867 868/* 869 * Future: need to be in "struct repository" 870 * when doing a full libification. 871 */ 872static struct ref_cache { 873struct ref_cache *next; 874struct ref_entry *loose; 875struct packed_ref_cache *packed; 876/* 877 * The submodule name, or "" for the main repo. We allocate 878 * length 1 rather than FLEX_ARRAY so that the main ref_cache 879 * is initialized correctly. 880 */ 881char name[1]; 882} ref_cache, *submodule_ref_caches; 883 884/* Lock used for the main packed-refs file: */ 885static struct lock_file packlock; 886 887/* 888 * Increment the reference count of *packed_refs. 889 */ 890static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 891{ 892 packed_refs->referrers++; 893} 894 895/* 896 * Decrease the reference count of *packed_refs. If it goes to zero, 897 * free *packed_refs and return true; otherwise return false. 898 */ 899static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 900{ 901if(!--packed_refs->referrers) { 902free_ref_entry(packed_refs->root); 903stat_validity_clear(&packed_refs->validity); 904free(packed_refs); 905return1; 906}else{ 907return0; 908} 909} 910 911static voidclear_packed_ref_cache(struct ref_cache *refs) 912{ 913if(refs->packed) { 914struct packed_ref_cache *packed_refs = refs->packed; 915 916if(packed_refs->lock) 917die("internal error: packed-ref cache cleared while locked"); 918 refs->packed = NULL; 919release_packed_ref_cache(packed_refs); 920} 921} 922 923static voidclear_loose_ref_cache(struct ref_cache *refs) 924{ 925if(refs->loose) { 926free_ref_entry(refs->loose); 927 refs->loose = NULL; 928} 929} 930 931/* 932 * Create a new submodule ref cache and add it to the internal 933 * set of caches. 934 */ 935static struct ref_cache *create_ref_cache(const char*submodule) 936{ 937struct ref_cache *refs; 938if(!submodule) 939 submodule =""; 940FLEX_ALLOC_STR(refs, name, submodule); 941 refs->next = submodule_ref_caches; 942 submodule_ref_caches = refs; 943return refs; 944} 945 946static struct ref_cache *lookup_ref_cache(const char*submodule) 947{ 948struct ref_cache *refs; 949 950if(!submodule || !*submodule) 951return&ref_cache; 952 953for(refs = submodule_ref_caches; refs; refs = refs->next) 954if(!strcmp(submodule, refs->name)) 955return refs; 956return NULL; 957} 958 959/* 960 * Return a pointer to a ref_cache for the specified submodule. For 961 * the main repository, use submodule==NULL. The returned structure 962 * will be allocated and initialized but not necessarily populated; it 963 * should not be freed. 964 */ 965static struct ref_cache *get_ref_cache(const char*submodule) 966{ 967struct ref_cache *refs =lookup_ref_cache(submodule); 968if(!refs) 969 refs =create_ref_cache(submodule); 970return refs; 971} 972 973/* The length of a peeled reference line in packed-refs, including EOL: */ 974#define PEELED_LINE_LENGTH 42 975 976/* 977 * The packed-refs header line that we write out. Perhaps other 978 * traits will be added later. The trailing space is required. 979 */ 980static const char PACKED_REFS_HEADER[] = 981"# pack-refs with: peeled fully-peeled\n"; 982 983/* 984 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 985 * Return a pointer to the refname within the line (null-terminated), 986 * or NULL if there was a problem. 987 */ 988static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 989{ 990const char*ref; 991 992/* 993 * 42: the answer to everything. 994 * 995 * In this case, it happens to be the answer to 996 * 40 (length of sha1 hex representation) 997 * +1 (space in between hex and name) 998 * +1 (newline at the end of the line) 999 */1000if(line->len <=42)1001return NULL;10021003if(get_sha1_hex(line->buf, sha1) <0)1004return NULL;1005if(!isspace(line->buf[40]))1006return NULL;10071008 ref = line->buf +41;1009if(isspace(*ref))1010return NULL;10111012if(line->buf[line->len -1] !='\n')1013return NULL;1014 line->buf[--line->len] =0;10151016return ref;1017}10181019/*1020 * Read f, which is a packed-refs file, into dir.1021 *1022 * A comment line of the form "# pack-refs with: " may contain zero or1023 * more traits. We interpret the traits as follows:1024 *1025 * No traits:1026 *1027 * Probably no references are peeled. But if the file contains a1028 * peeled value for a reference, we will use it.1029 *1030 * peeled:1031 *1032 * References under "refs/tags/", if they *can* be peeled, *are*1033 * peeled in this file. References outside of "refs/tags/" are1034 * probably not peeled even if they could have been, but if we find1035 * a peeled value for such a reference we will use it.1036 *1037 * fully-peeled:1038 *1039 * All references in the file that can be peeled are peeled.1040 * Inversely (and this is more important), any references in the1041 * file for which no peeled value is recorded is not peelable. This1042 * trait should typically be written alongside "peeled" for1043 * compatibility with older clients, but we do not require it1044 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1045 */1046static voidread_packed_refs(FILE*f,struct ref_dir *dir)1047{1048struct ref_entry *last = NULL;1049struct strbuf line = STRBUF_INIT;1050enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10511052while(strbuf_getwholeline(&line, f,'\n') != EOF) {1053unsigned char sha1[20];1054const char*refname;1055const char*traits;10561057if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1058if(strstr(traits," fully-peeled "))1059 peeled = PEELED_FULLY;1060else if(strstr(traits," peeled "))1061 peeled = PEELED_TAGS;1062/* perhaps other traits later as well */1063continue;1064}10651066 refname =parse_ref_line(&line, sha1);1067if(refname) {1068int flag = REF_ISPACKED;10691070if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1071if(!refname_is_safe(refname))1072die("packed refname is dangerous:%s", refname);1073hashclr(sha1);1074 flag |= REF_BAD_NAME | REF_ISBROKEN;1075}1076 last =create_ref_entry(refname, sha1, flag,0);1077if(peeled == PEELED_FULLY ||1078(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1079 last->flag |= REF_KNOWS_PEELED;1080add_ref(dir, last);1081continue;1082}1083if(last &&1084 line.buf[0] =='^'&&1085 line.len == PEELED_LINE_LENGTH &&1086 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1087!get_sha1_hex(line.buf +1, sha1)) {1088hashcpy(last->u.value.peeled.hash, sha1);1089/*1090 * Regardless of what the file header said,1091 * we definitely know the value of *this*1092 * reference:1093 */1094 last->flag |= REF_KNOWS_PEELED;1095}1096}10971098strbuf_release(&line);1099}11001101/*1102 * Get the packed_ref_cache for the specified ref_cache, creating it1103 * if necessary.1104 */1105static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1106{1107char*packed_refs_file;11081109if(*refs->name)1110 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1111else1112 packed_refs_file =git_pathdup("packed-refs");11131114if(refs->packed &&1115!stat_validity_check(&refs->packed->validity, packed_refs_file))1116clear_packed_ref_cache(refs);11171118if(!refs->packed) {1119FILE*f;11201121 refs->packed =xcalloc(1,sizeof(*refs->packed));1122acquire_packed_ref_cache(refs->packed);1123 refs->packed->root =create_dir_entry(refs,"",0,0);1124 f =fopen(packed_refs_file,"r");1125if(f) {1126stat_validity_update(&refs->packed->validity,fileno(f));1127read_packed_refs(f,get_ref_dir(refs->packed->root));1128fclose(f);1129}1130}1131free(packed_refs_file);1132return refs->packed;1133}11341135static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1136{1137returnget_ref_dir(packed_ref_cache->root);1138}11391140static struct ref_dir *get_packed_refs(struct ref_cache *refs)1141{1142returnget_packed_ref_dir(get_packed_ref_cache(refs));1143}11441145/*1146 * Add a reference to the in-memory packed reference cache. This may1147 * only be called while the packed-refs file is locked (see1148 * lock_packed_refs()). To actually write the packed-refs file, call1149 * commit_packed_refs().1150 */1151static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1152{1153struct packed_ref_cache *packed_ref_cache =1154get_packed_ref_cache(&ref_cache);11551156if(!packed_ref_cache->lock)1157die("internal error: packed refs not locked");1158add_ref(get_packed_ref_dir(packed_ref_cache),1159create_ref_entry(refname, sha1, REF_ISPACKED,1));1160}11611162/*1163 * Read the loose references from the namespace dirname into dir1164 * (without recursing). dirname must end with '/'. dir must be the1165 * directory entry corresponding to dirname.1166 */1167static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1168{1169struct ref_cache *refs = dir->ref_cache;1170DIR*d;1171struct dirent *de;1172int dirnamelen =strlen(dirname);1173struct strbuf refname;1174struct strbuf path = STRBUF_INIT;1175size_t path_baselen;11761177if(*refs->name)1178strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1179else1180strbuf_git_path(&path,"%s", dirname);1181 path_baselen = path.len;11821183 d =opendir(path.buf);1184if(!d) {1185strbuf_release(&path);1186return;1187}11881189strbuf_init(&refname, dirnamelen +257);1190strbuf_add(&refname, dirname, dirnamelen);11911192while((de =readdir(d)) != NULL) {1193unsigned char sha1[20];1194struct stat st;1195int flag;11961197if(de->d_name[0] =='.')1198continue;1199if(ends_with(de->d_name,".lock"))1200continue;1201strbuf_addstr(&refname, de->d_name);1202strbuf_addstr(&path, de->d_name);1203if(stat(path.buf, &st) <0) {1204;/* silently ignore */1205}else if(S_ISDIR(st.st_mode)) {1206strbuf_addch(&refname,'/');1207add_entry_to_dir(dir,1208create_dir_entry(refs, refname.buf,1209 refname.len,1));1210}else{1211int read_ok;12121213if(*refs->name) {1214hashclr(sha1);1215 flag =0;1216 read_ok = !resolve_gitlink_ref(refs->name,1217 refname.buf, sha1);1218}else{1219 read_ok = !read_ref_full(refname.buf,1220 RESOLVE_REF_READING,1221 sha1, &flag);1222}12231224if(!read_ok) {1225hashclr(sha1);1226 flag |= REF_ISBROKEN;1227}else if(is_null_sha1(sha1)) {1228/*1229 * It is so astronomically unlikely1230 * that NULL_SHA1 is the SHA-1 of an1231 * actual object that we consider its1232 * appearance in a loose reference1233 * file to be repo corruption1234 * (probably due to a software bug).1235 */1236 flag |= REF_ISBROKEN;1237}12381239if(check_refname_format(refname.buf,1240 REFNAME_ALLOW_ONELEVEL)) {1241if(!refname_is_safe(refname.buf))1242die("loose refname is dangerous:%s", refname.buf);1243hashclr(sha1);1244 flag |= REF_BAD_NAME | REF_ISBROKEN;1245}1246add_entry_to_dir(dir,1247create_ref_entry(refname.buf, sha1, flag,0));1248}1249strbuf_setlen(&refname, dirnamelen);1250strbuf_setlen(&path, path_baselen);1251}1252strbuf_release(&refname);1253strbuf_release(&path);1254closedir(d);1255}12561257static struct ref_dir *get_loose_refs(struct ref_cache *refs)1258{1259if(!refs->loose) {1260/*1261 * Mark the top-level directory complete because we1262 * are about to read the only subdirectory that can1263 * hold references:1264 */1265 refs->loose =create_dir_entry(refs,"",0,0);1266/*1267 * Create an incomplete entry for "refs/":1268 */1269add_entry_to_dir(get_ref_dir(refs->loose),1270create_dir_entry(refs,"refs/",5,1));1271}1272returnget_ref_dir(refs->loose);1273}12741275/* We allow "recursive" symbolic refs. Only within reason, though */1276#define MAXDEPTH 51277#define MAXREFLEN (1024)12781279/*1280 * Called by resolve_gitlink_ref_recursive() after it failed to read1281 * from the loose refs in ref_cache refs. Find <refname> in the1282 * packed-refs file for the submodule.1283 */1284static intresolve_gitlink_packed_ref(struct ref_cache *refs,1285const char*refname,unsigned char*sha1)1286{1287struct ref_entry *ref;1288struct ref_dir *dir =get_packed_refs(refs);12891290 ref =find_ref(dir, refname);1291if(ref == NULL)1292return-1;12931294hashcpy(sha1, ref->u.value.oid.hash);1295return0;1296}12971298static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1299const char*refname,unsigned char*sha1,1300int recursion)1301{1302int fd, len;1303char buffer[128], *p;1304char*path;13051306if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1307return-1;1308 path = *refs->name1309?git_pathdup_submodule(refs->name,"%s", refname)1310:git_pathdup("%s", refname);1311 fd =open(path, O_RDONLY);1312free(path);1313if(fd <0)1314returnresolve_gitlink_packed_ref(refs, refname, sha1);13151316 len =read(fd, buffer,sizeof(buffer)-1);1317close(fd);1318if(len <0)1319return-1;1320while(len &&isspace(buffer[len-1]))1321 len--;1322 buffer[len] =0;13231324/* Was it a detached head or an old-fashioned symlink? */1325if(!get_sha1_hex(buffer, sha1))1326return0;13271328/* Symref? */1329if(strncmp(buffer,"ref:",4))1330return-1;1331 p = buffer +4;1332while(isspace(*p))1333 p++;13341335returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1336}13371338intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1339{1340int len =strlen(path), retval;1341struct strbuf submodule = STRBUF_INIT;1342struct ref_cache *refs;13431344while(len && path[len-1] =='/')1345 len--;1346if(!len)1347return-1;13481349strbuf_add(&submodule, path, len);1350 refs =lookup_ref_cache(submodule.buf);1351if(!refs) {1352if(!is_nonbare_repository_dir(&submodule)) {1353strbuf_release(&submodule);1354return-1;1355}1356 refs =create_ref_cache(submodule.buf);1357}1358strbuf_release(&submodule);13591360 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1361return retval;1362}13631364/*1365 * Return the ref_entry for the given refname from the packed1366 * references. If it does not exist, return NULL.1367 */1368static struct ref_entry *get_packed_ref(const char*refname)1369{1370returnfind_ref(get_packed_refs(&ref_cache), refname);1371}13721373/*1374 * A loose ref file doesn't exist; check for a packed ref. The1375 * options are forwarded from resolve_safe_unsafe().1376 */1377static intresolve_missing_loose_ref(const char*refname,1378int resolve_flags,1379unsigned char*sha1,1380int*flags)1381{1382struct ref_entry *entry;13831384/*1385 * The loose reference file does not exist; check for a packed1386 * reference.1387 */1388 entry =get_packed_ref(refname);1389if(entry) {1390hashcpy(sha1, entry->u.value.oid.hash);1391if(flags)1392*flags |= REF_ISPACKED;1393return0;1394}1395/* The reference is not a packed reference, either. */1396if(resolve_flags & RESOLVE_REF_READING) {1397 errno = ENOENT;1398return-1;1399}else{1400hashclr(sha1);1401return0;1402}1403}14041405/* This function needs to return a meaningful errno on failure */1406static const char*resolve_ref_1(const char*refname,1407int resolve_flags,1408unsigned char*sha1,1409int*flags,1410struct strbuf *sb_refname,1411struct strbuf *sb_path,1412struct strbuf *sb_contents)1413{1414int depth = MAXDEPTH;1415int bad_name =0;14161417if(flags)1418*flags =0;14191420if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1421if(flags)1422*flags |= REF_BAD_NAME;14231424if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1425!refname_is_safe(refname)) {1426 errno = EINVAL;1427return NULL;1428}1429/*1430 * dwim_ref() uses REF_ISBROKEN to distinguish between1431 * missing refs and refs that were present but invalid,1432 * to complain about the latter to stderr.1433 *1434 * We don't know whether the ref exists, so don't set1435 * REF_ISBROKEN yet.1436 */1437 bad_name =1;1438}1439for(;;) {1440const char*path;1441struct stat st;1442char*buf;1443int fd;14441445if(--depth <0) {1446 errno = ELOOP;1447return NULL;1448}14491450strbuf_reset(sb_path);1451strbuf_git_path(sb_path,"%s", refname);1452 path = sb_path->buf;14531454/*1455 * We might have to loop back here to avoid a race1456 * condition: first we lstat() the file, then we try1457 * to read it as a link or as a file. But if somebody1458 * changes the type of the file (file <-> directory1459 * <-> symlink) between the lstat() and reading, then1460 * we don't want to report that as an error but rather1461 * try again starting with the lstat().1462 */1463 stat_ref:1464if(lstat(path, &st) <0) {1465if(errno != ENOENT)1466return NULL;1467if(resolve_missing_loose_ref(refname, resolve_flags,1468 sha1, flags))1469return NULL;1470if(bad_name) {1471hashclr(sha1);1472if(flags)1473*flags |= REF_ISBROKEN;1474}1475return refname;1476}14771478/* Follow "normalized" - ie "refs/.." symlinks by hand */1479if(S_ISLNK(st.st_mode)) {1480strbuf_reset(sb_contents);1481if(strbuf_readlink(sb_contents, path,0) <0) {1482if(errno == ENOENT || errno == EINVAL)1483/* inconsistent with lstat; retry */1484goto stat_ref;1485else1486return NULL;1487}1488if(starts_with(sb_contents->buf,"refs/") &&1489!check_refname_format(sb_contents->buf,0)) {1490strbuf_swap(sb_refname, sb_contents);1491 refname = sb_refname->buf;1492if(flags)1493*flags |= REF_ISSYMREF;1494if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1495hashclr(sha1);1496return refname;1497}1498continue;1499}1500}15011502/* Is it a directory? */1503if(S_ISDIR(st.st_mode)) {1504 errno = EISDIR;1505return NULL;1506}15071508/*1509 * Anything else, just open it and try to use it as1510 * a ref1511 */1512 fd =open(path, O_RDONLY);1513if(fd <0) {1514if(errno == ENOENT)1515/* inconsistent with lstat; retry */1516goto stat_ref;1517else1518return NULL;1519}1520strbuf_reset(sb_contents);1521if(strbuf_read(sb_contents, fd,256) <0) {1522int save_errno = errno;1523close(fd);1524 errno = save_errno;1525return NULL;1526}1527close(fd);1528strbuf_rtrim(sb_contents);15291530/*1531 * Is it a symbolic ref?1532 */1533if(!starts_with(sb_contents->buf,"ref:")) {1534/*1535 * Please note that FETCH_HEAD has a second1536 * line containing other data.1537 */1538if(get_sha1_hex(sb_contents->buf, sha1) ||1539(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1540if(flags)1541*flags |= REF_ISBROKEN;1542 errno = EINVAL;1543return NULL;1544}1545if(bad_name) {1546hashclr(sha1);1547if(flags)1548*flags |= REF_ISBROKEN;1549}1550return refname;1551}1552if(flags)1553*flags |= REF_ISSYMREF;1554 buf = sb_contents->buf +4;1555while(isspace(*buf))1556 buf++;1557strbuf_reset(sb_refname);1558strbuf_addstr(sb_refname, buf);1559 refname = sb_refname->buf;1560if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1561hashclr(sha1);1562return refname;1563}1564if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1565if(flags)1566*flags |= REF_ISBROKEN;15671568if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1569!refname_is_safe(buf)) {1570 errno = EINVAL;1571return NULL;1572}1573 bad_name =1;1574}1575}1576}15771578const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1579unsigned char*sha1,int*flags)1580{1581static struct strbuf sb_refname = STRBUF_INIT;1582struct strbuf sb_contents = STRBUF_INIT;1583struct strbuf sb_path = STRBUF_INIT;1584const char*ret;15851586 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1587&sb_refname, &sb_path, &sb_contents);1588strbuf_release(&sb_path);1589strbuf_release(&sb_contents);1590return ret;1591}15921593/*1594 * Peel the entry (if possible) and return its new peel_status. If1595 * repeel is true, re-peel the entry even if there is an old peeled1596 * value that is already stored in it.1597 *1598 * It is OK to call this function with a packed reference entry that1599 * might be stale and might even refer to an object that has since1600 * been garbage-collected. In such a case, if the entry has1601 * REF_KNOWS_PEELED then leave the status unchanged and return1602 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1603 */1604static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1605{1606enum peel_status status;16071608if(entry->flag & REF_KNOWS_PEELED) {1609if(repeel) {1610 entry->flag &= ~REF_KNOWS_PEELED;1611oidclr(&entry->u.value.peeled);1612}else{1613returnis_null_oid(&entry->u.value.peeled) ?1614 PEEL_NON_TAG : PEEL_PEELED;1615}1616}1617if(entry->flag & REF_ISBROKEN)1618return PEEL_BROKEN;1619if(entry->flag & REF_ISSYMREF)1620return PEEL_IS_SYMREF;16211622 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1623if(status == PEEL_PEELED || status == PEEL_NON_TAG)1624 entry->flag |= REF_KNOWS_PEELED;1625return status;1626}16271628intpeel_ref(const char*refname,unsigned char*sha1)1629{1630int flag;1631unsigned char base[20];16321633if(current_ref && (current_ref->name == refname1634|| !strcmp(current_ref->name, refname))) {1635if(peel_entry(current_ref,0))1636return-1;1637hashcpy(sha1, current_ref->u.value.peeled.hash);1638return0;1639}16401641if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1642return-1;16431644/*1645 * If the reference is packed, read its ref_entry from the1646 * cache in the hope that we already know its peeled value.1647 * We only try this optimization on packed references because1648 * (a) forcing the filling of the loose reference cache could1649 * be expensive and (b) loose references anyway usually do not1650 * have REF_KNOWS_PEELED.1651 */1652if(flag & REF_ISPACKED) {1653struct ref_entry *r =get_packed_ref(refname);1654if(r) {1655if(peel_entry(r,0))1656return-1;1657hashcpy(sha1, r->u.value.peeled.hash);1658return0;1659}1660}16611662returnpeel_object(base, sha1);1663}16641665/*1666 * Call fn for each reference in the specified ref_cache, omitting1667 * references not in the containing_dir of base. fn is called for all1668 * references, including broken ones. If fn ever returns a non-zero1669 * value, stop the iteration and return that value; otherwise, return1670 * 0.1671 */1672static intdo_for_each_entry(struct ref_cache *refs,const char*base,1673 each_ref_entry_fn fn,void*cb_data)1674{1675struct packed_ref_cache *packed_ref_cache;1676struct ref_dir *loose_dir;1677struct ref_dir *packed_dir;1678int retval =0;16791680/*1681 * We must make sure that all loose refs are read before accessing the1682 * packed-refs file; this avoids a race condition in which loose refs1683 * are migrated to the packed-refs file by a simultaneous process, but1684 * our in-memory view is from before the migration. get_packed_ref_cache()1685 * takes care of making sure our view is up to date with what is on1686 * disk.1687 */1688 loose_dir =get_loose_refs(refs);1689if(base && *base) {1690 loose_dir =find_containing_dir(loose_dir, base,0);1691}1692if(loose_dir)1693prime_ref_dir(loose_dir);16941695 packed_ref_cache =get_packed_ref_cache(refs);1696acquire_packed_ref_cache(packed_ref_cache);1697 packed_dir =get_packed_ref_dir(packed_ref_cache);1698if(base && *base) {1699 packed_dir =find_containing_dir(packed_dir, base,0);1700}17011702if(packed_dir && loose_dir) {1703sort_ref_dir(packed_dir);1704sort_ref_dir(loose_dir);1705 retval =do_for_each_entry_in_dirs(1706 packed_dir, loose_dir, fn, cb_data);1707}else if(packed_dir) {1708sort_ref_dir(packed_dir);1709 retval =do_for_each_entry_in_dir(1710 packed_dir,0, fn, cb_data);1711}else if(loose_dir) {1712sort_ref_dir(loose_dir);1713 retval =do_for_each_entry_in_dir(1714 loose_dir,0, fn, cb_data);1715}17161717release_packed_ref_cache(packed_ref_cache);1718return retval;1719}17201721/*1722 * Call fn for each reference in the specified ref_cache for which the1723 * refname begins with base. If trim is non-zero, then trim that many1724 * characters off the beginning of each refname before passing the1725 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1726 * broken references in the iteration. If fn ever returns a non-zero1727 * value, stop the iteration and return that value; otherwise, return1728 * 0.1729 */1730static intdo_for_each_ref(struct ref_cache *refs,const char*base,1731 each_ref_fn fn,int trim,int flags,void*cb_data)1732{1733struct ref_entry_cb data;1734 data.base = base;1735 data.trim = trim;1736 data.flags = flags;1737 data.fn = fn;1738 data.cb_data = cb_data;17391740if(ref_paranoia <0)1741 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1742if(ref_paranoia)1743 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;17441745returndo_for_each_entry(refs, base, do_one_ref, &data);1746}17471748static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1749{1750struct object_id oid;1751int flag;17521753if(submodule) {1754if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)1755returnfn("HEAD", &oid,0, cb_data);17561757return0;1758}17591760if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))1761returnfn("HEAD", &oid, flag, cb_data);17621763return0;1764}17651766inthead_ref(each_ref_fn fn,void*cb_data)1767{1768returndo_head_ref(NULL, fn, cb_data);1769}17701771inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1772{1773returndo_head_ref(submodule, fn, cb_data);1774}17751776intfor_each_ref(each_ref_fn fn,void*cb_data)1777{1778returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1779}17801781intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1782{1783returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1784}17851786intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1787{1788returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1789}17901791intfor_each_fullref_in(const char*prefix, each_ref_fn fn,void*cb_data,unsigned int broken)1792{1793unsigned int flag =0;17941795if(broken)1796 flag = DO_FOR_EACH_INCLUDE_BROKEN;1797returndo_for_each_ref(&ref_cache, prefix, fn,0, flag, cb_data);1798}17991800intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1801 each_ref_fn fn,void*cb_data)1802{1803returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1804}18051806intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1807{1808returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,1809strlen(git_replace_ref_base),0, cb_data);1810}18111812intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1813{1814struct strbuf buf = STRBUF_INIT;1815int ret;1816strbuf_addf(&buf,"%srefs/",get_git_namespace());1817 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);1818strbuf_release(&buf);1819return ret;1820}18211822intfor_each_rawref(each_ref_fn fn,void*cb_data)1823{1824returndo_for_each_ref(&ref_cache,"", fn,0,1825 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1826}18271828static voidunlock_ref(struct ref_lock *lock)1829{1830/* Do not free lock->lk -- atexit() still looks at them */1831if(lock->lk)1832rollback_lock_file(lock->lk);1833free(lock->ref_name);1834free(lock->orig_ref_name);1835free(lock);1836}18371838/*1839 * Verify that the reference locked by lock has the value old_sha1.1840 * Fail if the reference doesn't exist and mustexist is set. Return 01841 * on success. On error, write an error message to err, set errno, and1842 * return a negative value.1843 */1844static intverify_lock(struct ref_lock *lock,1845const unsigned char*old_sha1,int mustexist,1846struct strbuf *err)1847{1848assert(err);18491850if(read_ref_full(lock->ref_name,1851 mustexist ? RESOLVE_REF_READING :0,1852 lock->old_oid.hash, NULL)) {1853if(old_sha1) {1854int save_errno = errno;1855strbuf_addf(err,"can't verify ref%s", lock->ref_name);1856 errno = save_errno;1857return-1;1858}else{1859hashclr(lock->old_oid.hash);1860return0;1861}1862}1863if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1864strbuf_addf(err,"ref%sis at%sbut expected%s",1865 lock->ref_name,1866sha1_to_hex(lock->old_oid.hash),1867sha1_to_hex(old_sha1));1868 errno = EBUSY;1869return-1;1870}1871return0;1872}18731874static intremove_empty_directories(struct strbuf *path)1875{1876/*1877 * we want to create a file but there is a directory there;1878 * if that is an empty directory (or a directory that contains1879 * only empty directories), remove them.1880 */1881returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1882}18831884/*1885 * Locks a ref returning the lock on success and NULL on failure.1886 * On failure errno is set to something meaningful.1887 */1888static struct ref_lock *lock_ref_sha1_basic(const char*refname,1889const unsigned char*old_sha1,1890const struct string_list *extras,1891const struct string_list *skip,1892unsigned int flags,int*type_p,1893struct strbuf *err)1894{1895struct strbuf ref_file = STRBUF_INIT;1896struct strbuf orig_ref_file = STRBUF_INIT;1897const char*orig_refname = refname;1898struct ref_lock *lock;1899int last_errno =0;1900int type;1901int lflags =0;1902int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1903int resolve_flags =0;1904int attempts_remaining =3;19051906assert(err);19071908 lock =xcalloc(1,sizeof(struct ref_lock));19091910if(mustexist)1911 resolve_flags |= RESOLVE_REF_READING;1912if(flags & REF_DELETING)1913 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1914if(flags & REF_NODEREF) {1915 resolve_flags |= RESOLVE_REF_NO_RECURSE;1916 lflags |= LOCK_NO_DEREF;1917}19181919 refname =resolve_ref_unsafe(refname, resolve_flags,1920 lock->old_oid.hash, &type);1921if(!refname && errno == EISDIR) {1922/*1923 * we are trying to lock foo but we used to1924 * have foo/bar which now does not exist;1925 * it is normal for the empty directory 'foo'1926 * to remain.1927 */1928strbuf_git_path(&orig_ref_file,"%s", orig_refname);1929if(remove_empty_directories(&orig_ref_file)) {1930 last_errno = errno;1931if(!verify_refname_available_dir(orig_refname, extras, skip,1932get_loose_refs(&ref_cache), err))1933strbuf_addf(err,"there are still refs under '%s'",1934 orig_refname);1935goto error_return;1936}1937 refname =resolve_ref_unsafe(orig_refname, resolve_flags,1938 lock->old_oid.hash, &type);1939}1940if(type_p)1941*type_p = type;1942if(!refname) {1943 last_errno = errno;1944if(last_errno != ENOTDIR ||1945!verify_refname_available_dir(orig_refname, extras, skip,1946get_loose_refs(&ref_cache), err))1947strbuf_addf(err,"unable to resolve reference%s:%s",1948 orig_refname,strerror(last_errno));19491950goto error_return;1951}19521953if(flags & REF_NODEREF)1954 refname = orig_refname;19551956/*1957 * If the ref did not exist and we are creating it, make sure1958 * there is no existing packed ref whose name begins with our1959 * refname, nor a packed ref whose name is a proper prefix of1960 * our refname.1961 */1962if(is_null_oid(&lock->old_oid) &&1963verify_refname_available_dir(refname, extras, skip,1964get_packed_refs(&ref_cache), err)) {1965 last_errno = ENOTDIR;1966goto error_return;1967}19681969 lock->lk =xcalloc(1,sizeof(struct lock_file));19701971 lock->ref_name =xstrdup(refname);1972 lock->orig_ref_name =xstrdup(orig_refname);1973strbuf_git_path(&ref_file,"%s", refname);19741975 retry:1976switch(safe_create_leading_directories_const(ref_file.buf)) {1977case SCLD_OK:1978break;/* success */1979case SCLD_VANISHED:1980if(--attempts_remaining >0)1981goto retry;1982/* fall through */1983default:1984 last_errno = errno;1985strbuf_addf(err,"unable to create directory for%s",1986 ref_file.buf);1987goto error_return;1988}19891990if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {1991 last_errno = errno;1992if(errno == ENOENT && --attempts_remaining >0)1993/*1994 * Maybe somebody just deleted one of the1995 * directories leading to ref_file. Try1996 * again:1997 */1998goto retry;1999else{2000unable_to_lock_message(ref_file.buf, errno, err);2001goto error_return;2002}2003}2004if(verify_lock(lock, old_sha1, mustexist, err)) {2005 last_errno = errno;2006goto error_return;2007}2008goto out;20092010 error_return:2011unlock_ref(lock);2012 lock = NULL;20132014 out:2015strbuf_release(&ref_file);2016strbuf_release(&orig_ref_file);2017 errno = last_errno;2018return lock;2019}20202021/*2022 * Write an entry to the packed-refs file for the specified refname.2023 * If peeled is non-NULL, write it as the entry's peeled value.2024 */2025static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2026unsigned char*peeled)2027{2028fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2029if(peeled)2030fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2031}20322033/*2034 * An each_ref_entry_fn that writes the entry to a packed-refs file.2035 */2036static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2037{2038enum peel_status peel_status =peel_entry(entry,0);20392040if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2041error("internal error:%sis not a valid packed reference!",2042 entry->name);2043write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2044 peel_status == PEEL_PEELED ?2045 entry->u.value.peeled.hash : NULL);2046return0;2047}20482049/*2050 * Lock the packed-refs file for writing. Flags is passed to2051 * hold_lock_file_for_update(). Return 0 on success. On errors, set2052 * errno appropriately and return a nonzero value.2053 */2054static intlock_packed_refs(int flags)2055{2056static int timeout_configured =0;2057static int timeout_value =1000;20582059struct packed_ref_cache *packed_ref_cache;20602061if(!timeout_configured) {2062git_config_get_int("core.packedrefstimeout", &timeout_value);2063 timeout_configured =1;2064}20652066if(hold_lock_file_for_update_timeout(2067&packlock,git_path("packed-refs"),2068 flags, timeout_value) <0)2069return-1;2070/*2071 * Get the current packed-refs while holding the lock. If the2072 * packed-refs file has been modified since we last read it,2073 * this will automatically invalidate the cache and re-read2074 * the packed-refs file.2075 */2076 packed_ref_cache =get_packed_ref_cache(&ref_cache);2077 packed_ref_cache->lock = &packlock;2078/* Increment the reference count to prevent it from being freed: */2079acquire_packed_ref_cache(packed_ref_cache);2080return0;2081}20822083/*2084 * Write the current version of the packed refs cache from memory to2085 * disk. The packed-refs file must already be locked for writing (see2086 * lock_packed_refs()). Return zero on success. On errors, set errno2087 * and return a nonzero value2088 */2089static intcommit_packed_refs(void)2090{2091struct packed_ref_cache *packed_ref_cache =2092get_packed_ref_cache(&ref_cache);2093int error =0;2094int save_errno =0;2095FILE*out;20962097if(!packed_ref_cache->lock)2098die("internal error: packed-refs not locked");20992100 out =fdopen_lock_file(packed_ref_cache->lock,"w");2101if(!out)2102die_errno("unable to fdopen packed-refs descriptor");21032104fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2105do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),21060, write_packed_entry_fn, out);21072108if(commit_lock_file(packed_ref_cache->lock)) {2109 save_errno = errno;2110 error = -1;2111}2112 packed_ref_cache->lock = NULL;2113release_packed_ref_cache(packed_ref_cache);2114 errno = save_errno;2115return error;2116}21172118/*2119 * Rollback the lockfile for the packed-refs file, and discard the2120 * in-memory packed reference cache. (The packed-refs file will be2121 * read anew if it is needed again after this function is called.)2122 */2123static voidrollback_packed_refs(void)2124{2125struct packed_ref_cache *packed_ref_cache =2126get_packed_ref_cache(&ref_cache);21272128if(!packed_ref_cache->lock)2129die("internal error: packed-refs not locked");2130rollback_lock_file(packed_ref_cache->lock);2131 packed_ref_cache->lock = NULL;2132release_packed_ref_cache(packed_ref_cache);2133clear_packed_ref_cache(&ref_cache);2134}21352136struct ref_to_prune {2137struct ref_to_prune *next;2138unsigned char sha1[20];2139char name[FLEX_ARRAY];2140};21412142struct pack_refs_cb_data {2143unsigned int flags;2144struct ref_dir *packed_refs;2145struct ref_to_prune *ref_to_prune;2146};21472148/*2149 * An each_ref_entry_fn that is run over loose references only. If2150 * the loose reference can be packed, add an entry in the packed ref2151 * cache. If the reference should be pruned, also add it to2152 * ref_to_prune in the pack_refs_cb_data.2153 */2154static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2155{2156struct pack_refs_cb_data *cb = cb_data;2157enum peel_status peel_status;2158struct ref_entry *packed_entry;2159int is_tag_ref =starts_with(entry->name,"refs/tags/");21602161/* Do not pack per-worktree refs: */2162if(ref_type(entry->name) != REF_TYPE_NORMAL)2163return0;21642165/* ALWAYS pack tags */2166if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2167return0;21682169/* Do not pack symbolic or broken refs: */2170if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2171return0;21722173/* Add a packed ref cache entry equivalent to the loose entry. */2174 peel_status =peel_entry(entry,1);2175if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2176die("internal error peeling reference%s(%s)",2177 entry->name,oid_to_hex(&entry->u.value.oid));2178 packed_entry =find_ref(cb->packed_refs, entry->name);2179if(packed_entry) {2180/* Overwrite existing packed entry with info from loose entry */2181 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2182oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2183}else{2184 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2185 REF_ISPACKED | REF_KNOWS_PEELED,0);2186add_ref(cb->packed_refs, packed_entry);2187}2188oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);21892190/* Schedule the loose reference for pruning if requested. */2191if((cb->flags & PACK_REFS_PRUNE)) {2192struct ref_to_prune *n;2193FLEX_ALLOC_STR(n, name, entry->name);2194hashcpy(n->sha1, entry->u.value.oid.hash);2195 n->next = cb->ref_to_prune;2196 cb->ref_to_prune = n;2197}2198return0;2199}22002201/*2202 * Remove empty parents, but spare refs/ and immediate subdirs.2203 * Note: munges *name.2204 */2205static voidtry_remove_empty_parents(char*name)2206{2207char*p, *q;2208int i;2209 p = name;2210for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2211while(*p && *p !='/')2212 p++;2213/* tolerate duplicate slashes; see check_refname_format() */2214while(*p =='/')2215 p++;2216}2217for(q = p; *q; q++)2218;2219while(1) {2220while(q > p && *q !='/')2221 q--;2222while(q > p && *(q-1) =='/')2223 q--;2224if(q == p)2225break;2226*q ='\0';2227if(rmdir(git_path("%s", name)))2228break;2229}2230}22312232/* make sure nobody touched the ref, and unlink */2233static voidprune_ref(struct ref_to_prune *r)2234{2235struct ref_transaction *transaction;2236struct strbuf err = STRBUF_INIT;22372238if(check_refname_format(r->name,0))2239return;22402241 transaction =ref_transaction_begin(&err);2242if(!transaction ||2243ref_transaction_delete(transaction, r->name, r->sha1,2244 REF_ISPRUNING, NULL, &err) ||2245ref_transaction_commit(transaction, &err)) {2246ref_transaction_free(transaction);2247error("%s", err.buf);2248strbuf_release(&err);2249return;2250}2251ref_transaction_free(transaction);2252strbuf_release(&err);2253try_remove_empty_parents(r->name);2254}22552256static voidprune_refs(struct ref_to_prune *r)2257{2258while(r) {2259prune_ref(r);2260 r = r->next;2261}2262}22632264intpack_refs(unsigned int flags)2265{2266struct pack_refs_cb_data cbdata;22672268memset(&cbdata,0,sizeof(cbdata));2269 cbdata.flags = flags;22702271lock_packed_refs(LOCK_DIE_ON_ERROR);2272 cbdata.packed_refs =get_packed_refs(&ref_cache);22732274do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2275 pack_if_possible_fn, &cbdata);22762277if(commit_packed_refs())2278die_errno("unable to overwrite old ref-pack file");22792280prune_refs(cbdata.ref_to_prune);2281return0;2282}22832284/*2285 * Rewrite the packed-refs file, omitting any refs listed in2286 * 'refnames'. On error, leave packed-refs unchanged, write an error2287 * message to 'err', and return a nonzero value.2288 *2289 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2290 */2291static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2292{2293struct ref_dir *packed;2294struct string_list_item *refname;2295int ret, needs_repacking =0, removed =0;22962297assert(err);22982299/* Look for a packed ref */2300for_each_string_list_item(refname, refnames) {2301if(get_packed_ref(refname->string)) {2302 needs_repacking =1;2303break;2304}2305}23062307/* Avoid locking if we have nothing to do */2308if(!needs_repacking)2309return0;/* no refname exists in packed refs */23102311if(lock_packed_refs(0)) {2312unable_to_lock_message(git_path("packed-refs"), errno, err);2313return-1;2314}2315 packed =get_packed_refs(&ref_cache);23162317/* Remove refnames from the cache */2318for_each_string_list_item(refname, refnames)2319if(remove_entry(packed, refname->string) != -1)2320 removed =1;2321if(!removed) {2322/*2323 * All packed entries disappeared while we were2324 * acquiring the lock.2325 */2326rollback_packed_refs();2327return0;2328}23292330/* Write what remains */2331 ret =commit_packed_refs();2332if(ret)2333strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2334strerror(errno));2335return ret;2336}23372338static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2339{2340assert(err);23412342if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2343/*2344 * loose. The loose file name is the same as the2345 * lockfile name, minus ".lock":2346 */2347char*loose_filename =get_locked_file_path(lock->lk);2348int res =unlink_or_msg(loose_filename, err);2349free(loose_filename);2350if(res)2351return1;2352}2353return0;2354}23552356intdelete_refs(struct string_list *refnames)2357{2358struct strbuf err = STRBUF_INIT;2359int i, result =0;23602361if(!refnames->nr)2362return0;23632364 result =repack_without_refs(refnames, &err);2365if(result) {2366/*2367 * If we failed to rewrite the packed-refs file, then2368 * it is unsafe to try to remove loose refs, because2369 * doing so might expose an obsolete packed value for2370 * a reference that might even point at an object that2371 * has been garbage collected.2372 */2373if(refnames->nr ==1)2374error(_("could not delete reference%s:%s"),2375 refnames->items[0].string, err.buf);2376else2377error(_("could not delete references:%s"), err.buf);23782379goto out;2380}23812382for(i =0; i < refnames->nr; i++) {2383const char*refname = refnames->items[i].string;23842385if(delete_ref(refname, NULL,0))2386 result |=error(_("could not remove reference%s"), refname);2387}23882389out:2390strbuf_release(&err);2391return result;2392}23932394/*2395 * People using contrib's git-new-workdir have .git/logs/refs ->2396 * /some/other/path/.git/logs/refs, and that may live on another device.2397 *2398 * IOW, to avoid cross device rename errors, the temporary renamed log must2399 * live into logs/refs.2400 */2401#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"24022403static intrename_tmp_log(const char*newrefname)2404{2405int attempts_remaining =4;2406struct strbuf path = STRBUF_INIT;2407int ret = -1;24082409 retry:2410strbuf_reset(&path);2411strbuf_git_path(&path,"logs/%s", newrefname);2412switch(safe_create_leading_directories_const(path.buf)) {2413case SCLD_OK:2414break;/* success */2415case SCLD_VANISHED:2416if(--attempts_remaining >0)2417goto retry;2418/* fall through */2419default:2420error("unable to create directory for%s", newrefname);2421goto out;2422}24232424if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2425if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2426/*2427 * rename(a, b) when b is an existing2428 * directory ought to result in ISDIR, but2429 * Solaris 5.8 gives ENOTDIR. Sheesh.2430 */2431if(remove_empty_directories(&path)) {2432error("Directory not empty: logs/%s", newrefname);2433goto out;2434}2435goto retry;2436}else if(errno == ENOENT && --attempts_remaining >0) {2437/*2438 * Maybe another process just deleted one of2439 * the directories in the path to newrefname.2440 * Try again from the beginning.2441 */2442goto retry;2443}else{2444error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2445 newrefname,strerror(errno));2446goto out;2447}2448}2449 ret =0;2450out:2451strbuf_release(&path);2452return ret;2453}24542455intverify_refname_available(const char*newname,2456struct string_list *extras,2457struct string_list *skip,2458struct strbuf *err)2459{2460struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2461struct ref_dir *loose_refs =get_loose_refs(&ref_cache);24622463if(verify_refname_available_dir(newname, extras, skip,2464 packed_refs, err) ||2465verify_refname_available_dir(newname, extras, skip,2466 loose_refs, err))2467return-1;24682469return0;2470}24712472static intwrite_ref_to_lockfile(struct ref_lock *lock,2473const unsigned char*sha1,struct strbuf *err);2474static intcommit_ref_update(struct ref_lock *lock,2475const unsigned char*sha1,const char*logmsg,2476int flags,struct strbuf *err);24772478intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2479{2480unsigned char sha1[20], orig_sha1[20];2481int flag =0, logmoved =0;2482struct ref_lock *lock;2483struct stat loginfo;2484int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2485const char*symref = NULL;2486struct strbuf err = STRBUF_INIT;24872488if(log &&S_ISLNK(loginfo.st_mode))2489returnerror("reflog for%sis a symlink", oldrefname);24902491 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2492 orig_sha1, &flag);2493if(flag & REF_ISSYMREF)2494returnerror("refname%sis a symbolic ref, renaming it is not supported",2495 oldrefname);2496if(!symref)2497returnerror("refname%snot found", oldrefname);24982499if(!rename_ref_available(oldrefname, newrefname))2500return1;25012502if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2503returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2504 oldrefname,strerror(errno));25052506if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2507error("unable to delete old%s", oldrefname);2508goto rollback;2509}25102511if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2512delete_ref(newrefname, sha1, REF_NODEREF)) {2513if(errno==EISDIR) {2514struct strbuf path = STRBUF_INIT;2515int result;25162517strbuf_git_path(&path,"%s", newrefname);2518 result =remove_empty_directories(&path);2519strbuf_release(&path);25202521if(result) {2522error("Directory not empty:%s", newrefname);2523goto rollback;2524}2525}else{2526error("unable to delete existing%s", newrefname);2527goto rollback;2528}2529}25302531if(log &&rename_tmp_log(newrefname))2532goto rollback;25332534 logmoved = log;25352536 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2537if(!lock) {2538error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2539strbuf_release(&err);2540goto rollback;2541}2542hashcpy(lock->old_oid.hash, orig_sha1);25432544if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2545commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2546error("unable to write current sha1 into%s:%s", newrefname, err.buf);2547strbuf_release(&err);2548goto rollback;2549}25502551return0;25522553 rollback:2554 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2555if(!lock) {2556error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2557strbuf_release(&err);2558goto rollbacklog;2559}25602561 flag = log_all_ref_updates;2562 log_all_ref_updates =0;2563if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2564commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2565error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2566strbuf_release(&err);2567}2568 log_all_ref_updates = flag;25692570 rollbacklog:2571if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2572error("unable to restore logfile%sfrom%s:%s",2573 oldrefname, newrefname,strerror(errno));2574if(!logmoved && log &&2575rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2576error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2577 oldrefname,strerror(errno));25782579return1;2580}25812582static intclose_ref(struct ref_lock *lock)2583{2584if(close_lock_file(lock->lk))2585return-1;2586return0;2587}25882589static intcommit_ref(struct ref_lock *lock)2590{2591if(commit_lock_file(lock->lk))2592return-1;2593return0;2594}25952596/*2597 * Create a reflog for a ref. If force_create = 0, the reflog will2598 * only be created for certain refs (those for which2599 * should_autocreate_reflog returns non-zero. Otherwise, create it2600 * regardless of the ref name. Fill in *err and return -1 on failure.2601 */2602static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2603{2604int logfd, oflags = O_APPEND | O_WRONLY;26052606strbuf_git_path(logfile,"logs/%s", refname);2607if(force_create ||should_autocreate_reflog(refname)) {2608if(safe_create_leading_directories(logfile->buf) <0) {2609strbuf_addf(err,"unable to create directory for%s: "2610"%s", logfile->buf,strerror(errno));2611return-1;2612}2613 oflags |= O_CREAT;2614}26152616 logfd =open(logfile->buf, oflags,0666);2617if(logfd <0) {2618if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2619return0;26202621if(errno == EISDIR) {2622if(remove_empty_directories(logfile)) {2623strbuf_addf(err,"There are still logs under "2624"'%s'", logfile->buf);2625return-1;2626}2627 logfd =open(logfile->buf, oflags,0666);2628}26292630if(logfd <0) {2631strbuf_addf(err,"unable to append to%s:%s",2632 logfile->buf,strerror(errno));2633return-1;2634}2635}26362637adjust_shared_perm(logfile->buf);2638close(logfd);2639return0;2640}264126422643intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2644{2645int ret;2646struct strbuf sb = STRBUF_INIT;26472648 ret =log_ref_setup(refname, &sb, err, force_create);2649strbuf_release(&sb);2650return ret;2651}26522653static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2654const unsigned char*new_sha1,2655const char*committer,const char*msg)2656{2657int msglen, written;2658unsigned maxlen, len;2659char*logrec;26602661 msglen = msg ?strlen(msg) :0;2662 maxlen =strlen(committer) + msglen +100;2663 logrec =xmalloc(maxlen);2664 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2665sha1_to_hex(old_sha1),2666sha1_to_hex(new_sha1),2667 committer);2668if(msglen)2669 len +=copy_reflog_msg(logrec + len -1, msg) -1;26702671 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2672free(logrec);2673if(written != len)2674return-1;26752676return0;2677}26782679static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2680const unsigned char*new_sha1,const char*msg,2681struct strbuf *logfile,int flags,2682struct strbuf *err)2683{2684int logfd, result, oflags = O_APPEND | O_WRONLY;26852686if(log_all_ref_updates <0)2687 log_all_ref_updates = !is_bare_repository();26882689 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);26902691if(result)2692return result;26932694 logfd =open(logfile->buf, oflags);2695if(logfd <0)2696return0;2697 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2698git_committer_info(0), msg);2699if(result) {2700strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2701strerror(errno));2702close(logfd);2703return-1;2704}2705if(close(logfd)) {2706strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2707strerror(errno));2708return-1;2709}2710return0;2711}27122713static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2714const unsigned char*new_sha1,const char*msg,2715int flags,struct strbuf *err)2716{2717returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2718 err);2719}27202721intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2722const unsigned char*new_sha1,const char*msg,2723int flags,struct strbuf *err)2724{2725struct strbuf sb = STRBUF_INIT;2726int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2727 err);2728strbuf_release(&sb);2729return ret;2730}27312732/*2733 * Write sha1 into the open lockfile, then close the lockfile. On2734 * errors, rollback the lockfile, fill in *err and2735 * return -1.2736 */2737static intwrite_ref_to_lockfile(struct ref_lock *lock,2738const unsigned char*sha1,struct strbuf *err)2739{2740static char term ='\n';2741struct object *o;2742int fd;27432744 o =parse_object(sha1);2745if(!o) {2746strbuf_addf(err,2747"Trying to write ref%swith nonexistent object%s",2748 lock->ref_name,sha1_to_hex(sha1));2749unlock_ref(lock);2750return-1;2751}2752if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2753strbuf_addf(err,2754"Trying to write non-commit object%sto branch%s",2755sha1_to_hex(sha1), lock->ref_name);2756unlock_ref(lock);2757return-1;2758}2759 fd =get_lock_file_fd(lock->lk);2760if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2761write_in_full(fd, &term,1) !=1||2762close_ref(lock) <0) {2763strbuf_addf(err,2764"Couldn't write%s",get_lock_file_path(lock->lk));2765unlock_ref(lock);2766return-1;2767}2768return0;2769}27702771/*2772 * Commit a change to a loose reference that has already been written2773 * to the loose reference lockfile. Also update the reflogs if2774 * necessary, using the specified lockmsg (which can be NULL).2775 */2776static intcommit_ref_update(struct ref_lock *lock,2777const unsigned char*sha1,const char*logmsg,2778int flags,struct strbuf *err)2779{2780clear_loose_ref_cache(&ref_cache);2781if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2782(strcmp(lock->ref_name, lock->orig_ref_name) &&2783log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2784char*old_msg =strbuf_detach(err, NULL);2785strbuf_addf(err,"Cannot update the ref '%s':%s",2786 lock->ref_name, old_msg);2787free(old_msg);2788unlock_ref(lock);2789return-1;2790}2791if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2792/*2793 * Special hack: If a branch is updated directly and HEAD2794 * points to it (may happen on the remote side of a push2795 * for example) then logically the HEAD reflog should be2796 * updated too.2797 * A generic solution implies reverse symref information,2798 * but finding all symrefs pointing to the given branch2799 * would be rather costly for this rare event (the direct2800 * update of a branch) to be worth it. So let's cheat and2801 * check with HEAD only which should cover 99% of all usage2802 * scenarios (even 100% of the default ones).2803 */2804unsigned char head_sha1[20];2805int head_flag;2806const char*head_ref;2807 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2808 head_sha1, &head_flag);2809if(head_ref && (head_flag & REF_ISSYMREF) &&2810!strcmp(head_ref, lock->ref_name)) {2811struct strbuf log_err = STRBUF_INIT;2812if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2813 logmsg,0, &log_err)) {2814error("%s", log_err.buf);2815strbuf_release(&log_err);2816}2817}2818}2819if(commit_ref(lock)) {2820error("Couldn't set%s", lock->ref_name);2821unlock_ref(lock);2822return-1;2823}28242825unlock_ref(lock);2826return0;2827}28282829static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2830{2831int ret = -1;2832#ifndef NO_SYMLINK_HEAD2833char*ref_path =get_locked_file_path(lock->lk);2834unlink(ref_path);2835 ret =symlink(target, ref_path);2836free(ref_path);28372838if(ret)2839fprintf(stderr,"no symlink - falling back to symbolic ref\n");2840#endif2841return ret;2842}28432844static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2845const char*target,const char*logmsg)2846{2847struct strbuf err = STRBUF_INIT;2848unsigned char new_sha1[20];2849if(logmsg && !read_ref(target, new_sha1) &&2850log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2851error("%s", err.buf);2852strbuf_release(&err);2853}2854}28552856static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2857const char*target,const char*logmsg)2858{2859if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2860update_symref_reflog(lock, refname, target, logmsg);2861return0;2862}28632864if(!fdopen_lock_file(lock->lk,"w"))2865returnerror("unable to fdopen%s:%s",2866 lock->lk->tempfile.filename.buf,strerror(errno));28672868update_symref_reflog(lock, refname, target, logmsg);28692870/* no error check; commit_ref will check ferror */2871fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2872if(commit_ref(lock) <0)2873returnerror("unable to write symref for%s:%s", refname,2874strerror(errno));2875return0;2876}28772878intcreate_symref(const char*refname,const char*target,const char*logmsg)2879{2880struct strbuf err = STRBUF_INIT;2881struct ref_lock *lock;2882int ret;28832884 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2885&err);2886if(!lock) {2887error("%s", err.buf);2888strbuf_release(&err);2889return-1;2890}28912892 ret =create_symref_locked(lock, refname, target, logmsg);2893unlock_ref(lock);2894return ret;2895}28962897intset_worktree_head_symref(const char*gitdir,const char*target)2898{2899static struct lock_file head_lock;2900struct ref_lock *lock;2901struct strbuf head_path = STRBUF_INIT;2902const char*head_rel;2903int ret;29042905strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));2906if(hold_lock_file_for_update(&head_lock, head_path.buf,2907 LOCK_NO_DEREF) <0) {2908struct strbuf err = STRBUF_INIT;2909unable_to_lock_message(head_path.buf, errno, &err);2910error("%s", err.buf);2911strbuf_release(&err);2912strbuf_release(&head_path);2913return-1;2914}29152916/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for2917 linked trees */2918 head_rel =remove_leading_path(head_path.buf,2919absolute_path(get_git_common_dir()));2920/* to make use of create_symref_locked(), initialize ref_lock */2921 lock =xcalloc(1,sizeof(struct ref_lock));2922 lock->lk = &head_lock;2923 lock->ref_name =xstrdup(head_rel);2924 lock->orig_ref_name =xstrdup(head_rel);29252926 ret =create_symref_locked(lock, head_rel, target, NULL);29272928unlock_ref(lock);/* will free lock */2929strbuf_release(&head_path);2930return ret;2931}29322933intreflog_exists(const char*refname)2934{2935struct stat st;29362937return!lstat(git_path("logs/%s", refname), &st) &&2938S_ISREG(st.st_mode);2939}29402941intdelete_reflog(const char*refname)2942{2943returnremove_path(git_path("logs/%s", refname));2944}29452946static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2947{2948unsigned char osha1[20], nsha1[20];2949char*email_end, *message;2950unsigned long timestamp;2951int tz;29522953/* old SP new SP name <email> SP time TAB msg LF */2954if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2955get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2956get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2957!(email_end =strchr(sb->buf +82,'>')) ||2958 email_end[1] !=' '||2959!(timestamp =strtoul(email_end +2, &message,10)) ||2960!message || message[0] !=' '||2961(message[1] !='+'&& message[1] !='-') ||2962!isdigit(message[2]) || !isdigit(message[3]) ||2963!isdigit(message[4]) || !isdigit(message[5]))2964return0;/* corrupt? */2965 email_end[1] ='\0';2966 tz =strtol(message +1, NULL,10);2967if(message[6] !='\t')2968 message +=6;2969else2970 message +=7;2971returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2972}29732974static char*find_beginning_of_line(char*bob,char*scan)2975{2976while(bob < scan && *(--scan) !='\n')2977;/* keep scanning backwards */2978/*2979 * Return either beginning of the buffer, or LF at the end of2980 * the previous line.2981 */2982return scan;2983}29842985intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2986{2987struct strbuf sb = STRBUF_INIT;2988FILE*logfp;2989long pos;2990int ret =0, at_tail =1;29912992 logfp =fopen(git_path("logs/%s", refname),"r");2993if(!logfp)2994return-1;29952996/* Jump to the end */2997if(fseek(logfp,0, SEEK_END) <0)2998returnerror("cannot seek back reflog for%s:%s",2999 refname,strerror(errno));3000 pos =ftell(logfp);3001while(!ret &&0< pos) {3002int cnt;3003size_t nread;3004char buf[BUFSIZ];3005char*endp, *scanp;30063007/* Fill next block from the end */3008 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3009if(fseek(logfp, pos - cnt, SEEK_SET))3010returnerror("cannot seek back reflog for%s:%s",3011 refname,strerror(errno));3012 nread =fread(buf, cnt,1, logfp);3013if(nread !=1)3014returnerror("cannot read%dbytes from reflog for%s:%s",3015 cnt, refname,strerror(errno));3016 pos -= cnt;30173018 scanp = endp = buf + cnt;3019if(at_tail && scanp[-1] =='\n')3020/* Looking at the final LF at the end of the file */3021 scanp--;3022 at_tail =0;30233024while(buf < scanp) {3025/*3026 * terminating LF of the previous line, or the beginning3027 * of the buffer.3028 */3029char*bp;30303031 bp =find_beginning_of_line(buf, scanp);30323033if(*bp =='\n') {3034/*3035 * The newline is the end of the previous line,3036 * so we know we have complete line starting3037 * at (bp + 1). Prefix it onto any prior data3038 * we collected for the line and process it.3039 */3040strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3041 scanp = bp;3042 endp = bp +1;3043 ret =show_one_reflog_ent(&sb, fn, cb_data);3044strbuf_reset(&sb);3045if(ret)3046break;3047}else if(!pos) {3048/*3049 * We are at the start of the buffer, and the3050 * start of the file; there is no previous3051 * line, and we have everything for this one.3052 * Process it, and we can end the loop.3053 */3054strbuf_splice(&sb,0,0, buf, endp - buf);3055 ret =show_one_reflog_ent(&sb, fn, cb_data);3056strbuf_reset(&sb);3057break;3058}30593060if(bp == buf) {3061/*3062 * We are at the start of the buffer, and there3063 * is more file to read backwards. Which means3064 * we are in the middle of a line. Note that we3065 * may get here even if *bp was a newline; that3066 * just means we are at the exact end of the3067 * previous line, rather than some spot in the3068 * middle.3069 *3070 * Save away what we have to be combined with3071 * the data from the next read.3072 */3073strbuf_splice(&sb,0,0, buf, endp - buf);3074break;3075}3076}30773078}3079if(!ret && sb.len)3080die("BUG: reverse reflog parser had leftover data");30813082fclose(logfp);3083strbuf_release(&sb);3084return ret;3085}30863087intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3088{3089FILE*logfp;3090struct strbuf sb = STRBUF_INIT;3091int ret =0;30923093 logfp =fopen(git_path("logs/%s", refname),"r");3094if(!logfp)3095return-1;30963097while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3098 ret =show_one_reflog_ent(&sb, fn, cb_data);3099fclose(logfp);3100strbuf_release(&sb);3101return ret;3102}3103/*3104 * Call fn for each reflog in the namespace indicated by name. name3105 * must be empty or end with '/'. Name will be used as a scratch3106 * space, but its contents will be restored before return.3107 */3108static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3109{3110DIR*d =opendir(git_path("logs/%s", name->buf));3111int retval =0;3112struct dirent *de;3113int oldlen = name->len;31143115if(!d)3116return name->len ? errno :0;31173118while((de =readdir(d)) != NULL) {3119struct stat st;31203121if(de->d_name[0] =='.')3122continue;3123if(ends_with(de->d_name,".lock"))3124continue;3125strbuf_addstr(name, de->d_name);3126if(stat(git_path("logs/%s", name->buf), &st) <0) {3127;/* silently ignore */3128}else{3129if(S_ISDIR(st.st_mode)) {3130strbuf_addch(name,'/');3131 retval =do_for_each_reflog(name, fn, cb_data);3132}else{3133struct object_id oid;31343135if(read_ref_full(name->buf,0, oid.hash, NULL))3136 retval =error("bad ref for%s", name->buf);3137else3138 retval =fn(name->buf, &oid,0, cb_data);3139}3140if(retval)3141break;3142}3143strbuf_setlen(name, oldlen);3144}3145closedir(d);3146return retval;3147}31483149intfor_each_reflog(each_ref_fn fn,void*cb_data)3150{3151int retval;3152struct strbuf name;3153strbuf_init(&name, PATH_MAX);3154 retval =do_for_each_reflog(&name, fn, cb_data);3155strbuf_release(&name);3156return retval;3157}31583159static intref_update_reject_duplicates(struct string_list *refnames,3160struct strbuf *err)3161{3162int i, n = refnames->nr;31633164assert(err);31653166for(i =1; i < n; i++)3167if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3168strbuf_addf(err,3169"Multiple updates for ref '%s' not allowed.",3170 refnames->items[i].string);3171return1;3172}3173return0;3174}31753176intref_transaction_commit(struct ref_transaction *transaction,3177struct strbuf *err)3178{3179int ret =0, i;3180int n = transaction->nr;3181struct ref_update **updates = transaction->updates;3182struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3183struct string_list_item *ref_to_delete;3184struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31853186assert(err);31873188if(transaction->state != REF_TRANSACTION_OPEN)3189die("BUG: commit called for transaction that is not open");31903191if(!n) {3192 transaction->state = REF_TRANSACTION_CLOSED;3193return0;3194}31953196/* Fail if a refname appears more than once in the transaction: */3197for(i =0; i < n; i++)3198string_list_append(&affected_refnames, updates[i]->refname);3199string_list_sort(&affected_refnames);3200if(ref_update_reject_duplicates(&affected_refnames, err)) {3201 ret = TRANSACTION_GENERIC_ERROR;3202goto cleanup;3203}32043205/*3206 * Acquire all locks, verify old values if provided, check3207 * that new values are valid, and write new values to the3208 * lockfiles, ready to be activated. Only keep one lockfile3209 * open at a time to avoid running out of file descriptors.3210 */3211for(i =0; i < n; i++) {3212struct ref_update *update = updates[i];32133214if((update->flags & REF_HAVE_NEW) &&3215is_null_sha1(update->new_sha1))3216 update->flags |= REF_DELETING;3217 update->lock =lock_ref_sha1_basic(3218 update->refname,3219((update->flags & REF_HAVE_OLD) ?3220 update->old_sha1 : NULL),3221&affected_refnames, NULL,3222 update->flags,3223&update->type,3224 err);3225if(!update->lock) {3226char*reason;32273228 ret = (errno == ENOTDIR)3229? TRANSACTION_NAME_CONFLICT3230: TRANSACTION_GENERIC_ERROR;3231 reason =strbuf_detach(err, NULL);3232strbuf_addf(err,"cannot lock ref '%s':%s",3233 update->refname, reason);3234free(reason);3235goto cleanup;3236}3237if((update->flags & REF_HAVE_NEW) &&3238!(update->flags & REF_DELETING)) {3239int overwriting_symref = ((update->type & REF_ISSYMREF) &&3240(update->flags & REF_NODEREF));32413242if(!overwriting_symref &&3243!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3244/*3245 * The reference already has the desired3246 * value, so we don't need to write it.3247 */3248}else if(write_ref_to_lockfile(update->lock,3249 update->new_sha1,3250 err)) {3251char*write_err =strbuf_detach(err, NULL);32523253/*3254 * The lock was freed upon failure of3255 * write_ref_to_lockfile():3256 */3257 update->lock = NULL;3258strbuf_addf(err,3259"cannot update the ref '%s':%s",3260 update->refname, write_err);3261free(write_err);3262 ret = TRANSACTION_GENERIC_ERROR;3263goto cleanup;3264}else{3265 update->flags |= REF_NEEDS_COMMIT;3266}3267}3268if(!(update->flags & REF_NEEDS_COMMIT)) {3269/*3270 * We didn't have to write anything to the lockfile.3271 * Close it to free up the file descriptor:3272 */3273if(close_ref(update->lock)) {3274strbuf_addf(err,"Couldn't close%s.lock",3275 update->refname);3276goto cleanup;3277}3278}3279}32803281/* Perform updates first so live commits remain referenced */3282for(i =0; i < n; i++) {3283struct ref_update *update = updates[i];32843285if(update->flags & REF_NEEDS_COMMIT) {3286if(commit_ref_update(update->lock,3287 update->new_sha1, update->msg,3288 update->flags, err)) {3289/* freed by commit_ref_update(): */3290 update->lock = NULL;3291 ret = TRANSACTION_GENERIC_ERROR;3292goto cleanup;3293}else{3294/* freed by commit_ref_update(): */3295 update->lock = NULL;3296}3297}3298}32993300/* Perform deletes now that updates are safely completed */3301for(i =0; i < n; i++) {3302struct ref_update *update = updates[i];33033304if(update->flags & REF_DELETING) {3305if(delete_ref_loose(update->lock, update->type, err)) {3306 ret = TRANSACTION_GENERIC_ERROR;3307goto cleanup;3308}33093310if(!(update->flags & REF_ISPRUNING))3311string_list_append(&refs_to_delete,3312 update->lock->ref_name);3313}3314}33153316if(repack_without_refs(&refs_to_delete, err)) {3317 ret = TRANSACTION_GENERIC_ERROR;3318goto cleanup;3319}3320for_each_string_list_item(ref_to_delete, &refs_to_delete)3321unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3322clear_loose_ref_cache(&ref_cache);33233324cleanup:3325 transaction->state = REF_TRANSACTION_CLOSED;33263327for(i =0; i < n; i++)3328if(updates[i]->lock)3329unlock_ref(updates[i]->lock);3330string_list_clear(&refs_to_delete,0);3331string_list_clear(&affected_refnames,0);3332return ret;3333}33343335static intref_present(const char*refname,3336const struct object_id *oid,int flags,void*cb_data)3337{3338struct string_list *affected_refnames = cb_data;33393340returnstring_list_has_string(affected_refnames, refname);3341}33423343intinitial_ref_transaction_commit(struct ref_transaction *transaction,3344struct strbuf *err)3345{3346int ret =0, i;3347int n = transaction->nr;3348struct ref_update **updates = transaction->updates;3349struct string_list affected_refnames = STRING_LIST_INIT_NODUP;33503351assert(err);33523353if(transaction->state != REF_TRANSACTION_OPEN)3354die("BUG: commit called for transaction that is not open");33553356/* Fail if a refname appears more than once in the transaction: */3357for(i =0; i < n; i++)3358string_list_append(&affected_refnames, updates[i]->refname);3359string_list_sort(&affected_refnames);3360if(ref_update_reject_duplicates(&affected_refnames, err)) {3361 ret = TRANSACTION_GENERIC_ERROR;3362goto cleanup;3363}33643365/*3366 * It's really undefined to call this function in an active3367 * repository or when there are existing references: we are3368 * only locking and changing packed-refs, so (1) any3369 * simultaneous processes might try to change a reference at3370 * the same time we do, and (2) any existing loose versions of3371 * the references that we are setting would have precedence3372 * over our values. But some remote helpers create the remote3373 * "HEAD" and "master" branches before calling this function,3374 * so here we really only check that none of the references3375 * that we are creating already exists.3376 */3377if(for_each_rawref(ref_present, &affected_refnames))3378die("BUG: initial ref transaction called with existing refs");33793380for(i =0; i < n; i++) {3381struct ref_update *update = updates[i];33823383if((update->flags & REF_HAVE_OLD) &&3384!is_null_sha1(update->old_sha1))3385die("BUG: initial ref transaction with old_sha1 set");3386if(verify_refname_available(update->refname,3387&affected_refnames, NULL,3388 err)) {3389 ret = TRANSACTION_NAME_CONFLICT;3390goto cleanup;3391}3392}33933394if(lock_packed_refs(0)) {3395strbuf_addf(err,"unable to lock packed-refs file:%s",3396strerror(errno));3397 ret = TRANSACTION_GENERIC_ERROR;3398goto cleanup;3399}34003401for(i =0; i < n; i++) {3402struct ref_update *update = updates[i];34033404if((update->flags & REF_HAVE_NEW) &&3405!is_null_sha1(update->new_sha1))3406add_packed_ref(update->refname, update->new_sha1);3407}34083409if(commit_packed_refs()) {3410strbuf_addf(err,"unable to commit packed-refs file:%s",3411strerror(errno));3412 ret = TRANSACTION_GENERIC_ERROR;3413goto cleanup;3414}34153416cleanup:3417 transaction->state = REF_TRANSACTION_CLOSED;3418string_list_clear(&affected_refnames,0);3419return ret;3420}34213422struct expire_reflog_cb {3423unsigned int flags;3424 reflog_expiry_should_prune_fn *should_prune_fn;3425void*policy_cb;3426FILE*newlog;3427unsigned char last_kept_sha1[20];3428};34293430static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3431const char*email,unsigned long timestamp,int tz,3432const char*message,void*cb_data)3433{3434struct expire_reflog_cb *cb = cb_data;3435struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;34363437if(cb->flags & EXPIRE_REFLOGS_REWRITE)3438 osha1 = cb->last_kept_sha1;34393440if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3441 message, policy_cb)) {3442if(!cb->newlog)3443printf("would prune%s", message);3444else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3445printf("prune%s", message);3446}else{3447if(cb->newlog) {3448fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3449sha1_to_hex(osha1),sha1_to_hex(nsha1),3450 email, timestamp, tz, message);3451hashcpy(cb->last_kept_sha1, nsha1);3452}3453if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3454printf("keep%s", message);3455}3456return0;3457}34583459intreflog_expire(const char*refname,const unsigned char*sha1,3460unsigned int flags,3461 reflog_expiry_prepare_fn prepare_fn,3462 reflog_expiry_should_prune_fn should_prune_fn,3463 reflog_expiry_cleanup_fn cleanup_fn,3464void*policy_cb_data)3465{3466static struct lock_file reflog_lock;3467struct expire_reflog_cb cb;3468struct ref_lock *lock;3469char*log_file;3470int status =0;3471int type;3472struct strbuf err = STRBUF_INIT;34733474memset(&cb,0,sizeof(cb));3475 cb.flags = flags;3476 cb.policy_cb = policy_cb_data;3477 cb.should_prune_fn = should_prune_fn;34783479/*3480 * The reflog file is locked by holding the lock on the3481 * reference itself, plus we might need to update the3482 * reference if --updateref was specified:3483 */3484 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);3485if(!lock) {3486error("cannot lock ref '%s':%s", refname, err.buf);3487strbuf_release(&err);3488return-1;3489}3490if(!reflog_exists(refname)) {3491unlock_ref(lock);3492return0;3493}34943495 log_file =git_pathdup("logs/%s", refname);3496if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3497/*3498 * Even though holding $GIT_DIR/logs/$reflog.lock has3499 * no locking implications, we use the lock_file3500 * machinery here anyway because it does a lot of the3501 * work we need, including cleaning up if the program3502 * exits unexpectedly.3503 */3504if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3505struct strbuf err = STRBUF_INIT;3506unable_to_lock_message(log_file, errno, &err);3507error("%s", err.buf);3508strbuf_release(&err);3509goto failure;3510}3511 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3512if(!cb.newlog) {3513error("cannot fdopen%s(%s)",3514get_lock_file_path(&reflog_lock),strerror(errno));3515goto failure;3516}3517}35183519(*prepare_fn)(refname, sha1, cb.policy_cb);3520for_each_reflog_ent(refname, expire_reflog_ent, &cb);3521(*cleanup_fn)(cb.policy_cb);35223523if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3524/*3525 * It doesn't make sense to adjust a reference pointed3526 * to by a symbolic ref based on expiring entries in3527 * the symbolic reference's reflog. Nor can we update3528 * a reference if there are no remaining reflog3529 * entries.3530 */3531int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3532!(type & REF_ISSYMREF) &&3533!is_null_sha1(cb.last_kept_sha1);35343535if(close_lock_file(&reflog_lock)) {3536 status |=error("couldn't write%s:%s", log_file,3537strerror(errno));3538}else if(update &&3539(write_in_full(get_lock_file_fd(lock->lk),3540sha1_to_hex(cb.last_kept_sha1),40) !=40||3541write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3542close_ref(lock) <0)) {3543 status |=error("couldn't write%s",3544get_lock_file_path(lock->lk));3545rollback_lock_file(&reflog_lock);3546}else if(commit_lock_file(&reflog_lock)) {3547 status |=error("unable to write reflog '%s' (%s)",3548 log_file,strerror(errno));3549}else if(update &&commit_ref(lock)) {3550 status |=error("couldn't set%s", lock->ref_name);3551}3552}3553free(log_file);3554unlock_ref(lock);3555return status;35563557 failure:3558rollback_lock_file(&reflog_lock);3559free(log_file);3560unlock_ref(lock);3561return-1;3562}