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/* 517 * Return true iff the reference described by entry can be resolved to 518 * an object in the database. Emit a warning if the referred-to 519 * object does not exist. 520 */ 521static intref_resolves_to_object(struct ref_entry *entry) 522{ 523if(entry->flag & REF_ISBROKEN) 524return0; 525if(!has_sha1_file(entry->u.value.oid.hash)) { 526error("%sdoes not point to a valid object!", entry->name); 527return0; 528} 529return1; 530} 531 532/* 533 * current_ref is a performance hack: when iterating over references 534 * using the for_each_ref*() functions, current_ref is set to the 535 * current reference's entry before calling the callback function. If 536 * the callback function calls peel_ref(), then peel_ref() first 537 * checks whether the reference to be peeled is the current reference 538 * (it usually is) and if so, returns that reference's peeled version 539 * if it is available. This avoids a refname lookup in a common case. 540 */ 541static struct ref_entry *current_ref; 542 543typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 544 545struct ref_entry_cb { 546const char*base; 547int trim; 548int flags; 549 each_ref_fn *fn; 550void*cb_data; 551}; 552 553/* 554 * Handle one reference in a do_for_each_ref*()-style iteration, 555 * calling an each_ref_fn for each entry. 556 */ 557static intdo_one_ref(struct ref_entry *entry,void*cb_data) 558{ 559struct ref_entry_cb *data = cb_data; 560struct ref_entry *old_current_ref; 561int retval; 562 563if(!starts_with(entry->name, data->base)) 564return0; 565 566if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 567!ref_resolves_to_object(entry)) 568return0; 569 570/* Store the old value, in case this is a recursive call: */ 571 old_current_ref = current_ref; 572 current_ref = entry; 573 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 574 entry->flag, data->cb_data); 575 current_ref = old_current_ref; 576return retval; 577} 578 579/* 580 * Call fn for each reference in dir that has index in the range 581 * offset <= index < dir->nr. Recurse into subdirectories that are in 582 * that index range, sorting them before iterating. This function 583 * does not sort dir itself; it should be sorted beforehand. fn is 584 * called for all references, including broken ones. 585 */ 586static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 587 each_ref_entry_fn fn,void*cb_data) 588{ 589int i; 590assert(dir->sorted == dir->nr); 591for(i = offset; i < dir->nr; i++) { 592struct ref_entry *entry = dir->entries[i]; 593int retval; 594if(entry->flag & REF_DIR) { 595struct ref_dir *subdir =get_ref_dir(entry); 596sort_ref_dir(subdir); 597 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 598}else{ 599 retval =fn(entry, cb_data); 600} 601if(retval) 602return retval; 603} 604return0; 605} 606 607/* 608 * Call fn for each reference in the union of dir1 and dir2, in order 609 * by refname. Recurse into subdirectories. If a value entry appears 610 * in both dir1 and dir2, then only process the version that is in 611 * dir2. The input dirs must already be sorted, but subdirs will be 612 * sorted as needed. fn is called for all references, including 613 * broken ones. 614 */ 615static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 616struct ref_dir *dir2, 617 each_ref_entry_fn fn,void*cb_data) 618{ 619int retval; 620int i1 =0, i2 =0; 621 622assert(dir1->sorted == dir1->nr); 623assert(dir2->sorted == dir2->nr); 624while(1) { 625struct ref_entry *e1, *e2; 626int cmp; 627if(i1 == dir1->nr) { 628returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 629} 630if(i2 == dir2->nr) { 631returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 632} 633 e1 = dir1->entries[i1]; 634 e2 = dir2->entries[i2]; 635 cmp =strcmp(e1->name, e2->name); 636if(cmp ==0) { 637if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 638/* Both are directories; descend them in parallel. */ 639struct ref_dir *subdir1 =get_ref_dir(e1); 640struct ref_dir *subdir2 =get_ref_dir(e2); 641sort_ref_dir(subdir1); 642sort_ref_dir(subdir2); 643 retval =do_for_each_entry_in_dirs( 644 subdir1, subdir2, fn, cb_data); 645 i1++; 646 i2++; 647}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 648/* Both are references; ignore the one from dir1. */ 649 retval =fn(e2, cb_data); 650 i1++; 651 i2++; 652}else{ 653die("conflict between reference and directory:%s", 654 e1->name); 655} 656}else{ 657struct ref_entry *e; 658if(cmp <0) { 659 e = e1; 660 i1++; 661}else{ 662 e = e2; 663 i2++; 664} 665if(e->flag & REF_DIR) { 666struct ref_dir *subdir =get_ref_dir(e); 667sort_ref_dir(subdir); 668 retval =do_for_each_entry_in_dir( 669 subdir,0, fn, cb_data); 670}else{ 671 retval =fn(e, cb_data); 672} 673} 674if(retval) 675return retval; 676} 677} 678 679/* 680 * Load all of the refs from the dir into our in-memory cache. The hard work 681 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 682 * through all of the sub-directories. We do not even need to care about 683 * sorting, as traversal order does not matter to us. 684 */ 685static voidprime_ref_dir(struct ref_dir *dir) 686{ 687int i; 688for(i =0; i < dir->nr; i++) { 689struct ref_entry *entry = dir->entries[i]; 690if(entry->flag & REF_DIR) 691prime_ref_dir(get_ref_dir(entry)); 692} 693} 694 695struct nonmatching_ref_data { 696const struct string_list *skip; 697const char*conflicting_refname; 698}; 699 700static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 701{ 702struct nonmatching_ref_data *data = vdata; 703 704if(data->skip &&string_list_has_string(data->skip, entry->name)) 705return0; 706 707 data->conflicting_refname = entry->name; 708return1; 709} 710 711/* 712 * Return 0 if a reference named refname could be created without 713 * conflicting with the name of an existing reference in dir. 714 * See verify_refname_available for more information. 715 */ 716static intverify_refname_available_dir(const char*refname, 717const struct string_list *extras, 718const struct string_list *skip, 719struct ref_dir *dir, 720struct strbuf *err) 721{ 722const char*slash; 723const char*extra_refname; 724int pos; 725struct strbuf dirname = STRBUF_INIT; 726int ret = -1; 727 728/* 729 * For the sake of comments in this function, suppose that 730 * refname is "refs/foo/bar". 731 */ 732 733assert(err); 734 735strbuf_grow(&dirname,strlen(refname) +1); 736for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 737/* Expand dirname to the new prefix, not including the trailing slash: */ 738strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 739 740/* 741 * We are still at a leading dir of the refname (e.g., 742 * "refs/foo"; if there is a reference with that name, 743 * it is a conflict, *unless* it is in skip. 744 */ 745if(dir) { 746 pos =search_ref_dir(dir, dirname.buf, dirname.len); 747if(pos >=0&& 748(!skip || !string_list_has_string(skip, dirname.buf))) { 749/* 750 * We found a reference whose name is 751 * a proper prefix of refname; e.g., 752 * "refs/foo", and is not in skip. 753 */ 754strbuf_addf(err,"'%s' exists; cannot create '%s'", 755 dirname.buf, refname); 756goto cleanup; 757} 758} 759 760if(extras &&string_list_has_string(extras, dirname.buf) && 761(!skip || !string_list_has_string(skip, dirname.buf))) { 762strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 763 refname, dirname.buf); 764goto cleanup; 765} 766 767/* 768 * Otherwise, we can try to continue our search with 769 * the next component. So try to look up the 770 * directory, e.g., "refs/foo/". If we come up empty, 771 * we know there is nothing under this whole prefix, 772 * but even in that case we still have to continue the 773 * search for conflicts with extras. 774 */ 775strbuf_addch(&dirname,'/'); 776if(dir) { 777 pos =search_ref_dir(dir, dirname.buf, dirname.len); 778if(pos <0) { 779/* 780 * There was no directory "refs/foo/", 781 * so there is nothing under this 782 * whole prefix. So there is no need 783 * to continue looking for conflicting 784 * references. But we need to continue 785 * looking for conflicting extras. 786 */ 787 dir = NULL; 788}else{ 789 dir =get_ref_dir(dir->entries[pos]); 790} 791} 792} 793 794/* 795 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 796 * There is no point in searching for a reference with that 797 * name, because a refname isn't considered to conflict with 798 * itself. But we still need to check for references whose 799 * names are in the "refs/foo/bar/" namespace, because they 800 * *do* conflict. 801 */ 802strbuf_addstr(&dirname, refname + dirname.len); 803strbuf_addch(&dirname,'/'); 804 805if(dir) { 806 pos =search_ref_dir(dir, dirname.buf, dirname.len); 807 808if(pos >=0) { 809/* 810 * We found a directory named "$refname/" 811 * (e.g., "refs/foo/bar/"). It is a problem 812 * iff it contains any ref that is not in 813 * "skip". 814 */ 815struct nonmatching_ref_data data; 816 817 data.skip = skip; 818 data.conflicting_refname = NULL; 819 dir =get_ref_dir(dir->entries[pos]); 820sort_ref_dir(dir); 821if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 822strbuf_addf(err,"'%s' exists; cannot create '%s'", 823 data.conflicting_refname, refname); 824goto cleanup; 825} 826} 827} 828 829 extra_refname =find_descendant_ref(dirname.buf, extras, skip); 830if(extra_refname) 831strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 832 refname, extra_refname); 833else 834 ret =0; 835 836cleanup: 837strbuf_release(&dirname); 838return ret; 839} 840 841struct packed_ref_cache { 842struct ref_entry *root; 843 844/* 845 * Count of references to the data structure in this instance, 846 * including the pointer from ref_cache::packed if any. The 847 * data will not be freed as long as the reference count is 848 * nonzero. 849 */ 850unsigned int referrers; 851 852/* 853 * Iff the packed-refs file associated with this instance is 854 * currently locked for writing, this points at the associated 855 * lock (which is owned by somebody else). The referrer count 856 * is also incremented when the file is locked and decremented 857 * when it is unlocked. 858 */ 859struct lock_file *lock; 860 861/* The metadata from when this packed-refs cache was read */ 862struct stat_validity validity; 863}; 864 865/* 866 * Future: need to be in "struct repository" 867 * when doing a full libification. 868 */ 869static struct ref_cache { 870struct ref_cache *next; 871struct ref_entry *loose; 872struct packed_ref_cache *packed; 873/* 874 * The submodule name, or "" for the main repo. We allocate 875 * length 1 rather than FLEX_ARRAY so that the main ref_cache 876 * is initialized correctly. 877 */ 878char name[1]; 879} ref_cache, *submodule_ref_caches; 880 881/* Lock used for the main packed-refs file: */ 882static struct lock_file packlock; 883 884/* 885 * Increment the reference count of *packed_refs. 886 */ 887static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 888{ 889 packed_refs->referrers++; 890} 891 892/* 893 * Decrease the reference count of *packed_refs. If it goes to zero, 894 * free *packed_refs and return true; otherwise return false. 895 */ 896static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 897{ 898if(!--packed_refs->referrers) { 899free_ref_entry(packed_refs->root); 900stat_validity_clear(&packed_refs->validity); 901free(packed_refs); 902return1; 903}else{ 904return0; 905} 906} 907 908static voidclear_packed_ref_cache(struct ref_cache *refs) 909{ 910if(refs->packed) { 911struct packed_ref_cache *packed_refs = refs->packed; 912 913if(packed_refs->lock) 914die("internal error: packed-ref cache cleared while locked"); 915 refs->packed = NULL; 916release_packed_ref_cache(packed_refs); 917} 918} 919 920static voidclear_loose_ref_cache(struct ref_cache *refs) 921{ 922if(refs->loose) { 923free_ref_entry(refs->loose); 924 refs->loose = NULL; 925} 926} 927 928/* 929 * Create a new submodule ref cache and add it to the internal 930 * set of caches. 931 */ 932static struct ref_cache *create_ref_cache(const char*submodule) 933{ 934struct ref_cache *refs; 935if(!submodule) 936 submodule =""; 937FLEX_ALLOC_STR(refs, name, submodule); 938 refs->next = submodule_ref_caches; 939 submodule_ref_caches = refs; 940return refs; 941} 942 943static struct ref_cache *lookup_ref_cache(const char*submodule) 944{ 945struct ref_cache *refs; 946 947if(!submodule || !*submodule) 948return&ref_cache; 949 950for(refs = submodule_ref_caches; refs; refs = refs->next) 951if(!strcmp(submodule, refs->name)) 952return refs; 953return NULL; 954} 955 956/* 957 * Return a pointer to a ref_cache for the specified submodule. For 958 * the main repository, use submodule==NULL. The returned structure 959 * will be allocated and initialized but not necessarily populated; it 960 * should not be freed. 961 */ 962static struct ref_cache *get_ref_cache(const char*submodule) 963{ 964struct ref_cache *refs =lookup_ref_cache(submodule); 965if(!refs) 966 refs =create_ref_cache(submodule); 967return refs; 968} 969 970/* The length of a peeled reference line in packed-refs, including EOL: */ 971#define PEELED_LINE_LENGTH 42 972 973/* 974 * The packed-refs header line that we write out. Perhaps other 975 * traits will be added later. The trailing space is required. 976 */ 977static const char PACKED_REFS_HEADER[] = 978"# pack-refs with: peeled fully-peeled\n"; 979 980/* 981 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 982 * Return a pointer to the refname within the line (null-terminated), 983 * or NULL if there was a problem. 984 */ 985static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 986{ 987const char*ref; 988 989/* 990 * 42: the answer to everything. 991 * 992 * In this case, it happens to be the answer to 993 * 40 (length of sha1 hex representation) 994 * +1 (space in between hex and name) 995 * +1 (newline at the end of the line) 996 */ 997if(line->len <=42) 998return NULL; 9991000if(get_sha1_hex(line->buf, sha1) <0)1001return NULL;1002if(!isspace(line->buf[40]))1003return NULL;10041005 ref = line->buf +41;1006if(isspace(*ref))1007return NULL;10081009if(line->buf[line->len -1] !='\n')1010return NULL;1011 line->buf[--line->len] =0;10121013return ref;1014}10151016/*1017 * Read f, which is a packed-refs file, into dir.1018 *1019 * A comment line of the form "# pack-refs with: " may contain zero or1020 * more traits. We interpret the traits as follows:1021 *1022 * No traits:1023 *1024 * Probably no references are peeled. But if the file contains a1025 * peeled value for a reference, we will use it.1026 *1027 * peeled:1028 *1029 * References under "refs/tags/", if they *can* be peeled, *are*1030 * peeled in this file. References outside of "refs/tags/" are1031 * probably not peeled even if they could have been, but if we find1032 * a peeled value for such a reference we will use it.1033 *1034 * fully-peeled:1035 *1036 * All references in the file that can be peeled are peeled.1037 * Inversely (and this is more important), any references in the1038 * file for which no peeled value is recorded is not peelable. This1039 * trait should typically be written alongside "peeled" for1040 * compatibility with older clients, but we do not require it1041 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1042 */1043static voidread_packed_refs(FILE*f,struct ref_dir *dir)1044{1045struct ref_entry *last = NULL;1046struct strbuf line = STRBUF_INIT;1047enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10481049while(strbuf_getwholeline(&line, f,'\n') != EOF) {1050unsigned char sha1[20];1051const char*refname;1052const char*traits;10531054if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1055if(strstr(traits," fully-peeled "))1056 peeled = PEELED_FULLY;1057else if(strstr(traits," peeled "))1058 peeled = PEELED_TAGS;1059/* perhaps other traits later as well */1060continue;1061}10621063 refname =parse_ref_line(&line, sha1);1064if(refname) {1065int flag = REF_ISPACKED;10661067if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1068if(!refname_is_safe(refname))1069die("packed refname is dangerous:%s", refname);1070hashclr(sha1);1071 flag |= REF_BAD_NAME | REF_ISBROKEN;1072}1073 last =create_ref_entry(refname, sha1, flag,0);1074if(peeled == PEELED_FULLY ||1075(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1076 last->flag |= REF_KNOWS_PEELED;1077add_ref(dir, last);1078continue;1079}1080if(last &&1081 line.buf[0] =='^'&&1082 line.len == PEELED_LINE_LENGTH &&1083 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1084!get_sha1_hex(line.buf +1, sha1)) {1085hashcpy(last->u.value.peeled.hash, sha1);1086/*1087 * Regardless of what the file header said,1088 * we definitely know the value of *this*1089 * reference:1090 */1091 last->flag |= REF_KNOWS_PEELED;1092}1093}10941095strbuf_release(&line);1096}10971098/*1099 * Get the packed_ref_cache for the specified ref_cache, creating it1100 * if necessary.1101 */1102static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1103{1104char*packed_refs_file;11051106if(*refs->name)1107 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1108else1109 packed_refs_file =git_pathdup("packed-refs");11101111if(refs->packed &&1112!stat_validity_check(&refs->packed->validity, packed_refs_file))1113clear_packed_ref_cache(refs);11141115if(!refs->packed) {1116FILE*f;11171118 refs->packed =xcalloc(1,sizeof(*refs->packed));1119acquire_packed_ref_cache(refs->packed);1120 refs->packed->root =create_dir_entry(refs,"",0,0);1121 f =fopen(packed_refs_file,"r");1122if(f) {1123stat_validity_update(&refs->packed->validity,fileno(f));1124read_packed_refs(f,get_ref_dir(refs->packed->root));1125fclose(f);1126}1127}1128free(packed_refs_file);1129return refs->packed;1130}11311132static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1133{1134returnget_ref_dir(packed_ref_cache->root);1135}11361137static struct ref_dir *get_packed_refs(struct ref_cache *refs)1138{1139returnget_packed_ref_dir(get_packed_ref_cache(refs));1140}11411142/*1143 * Add a reference to the in-memory packed reference cache. This may1144 * only be called while the packed-refs file is locked (see1145 * lock_packed_refs()). To actually write the packed-refs file, call1146 * commit_packed_refs().1147 */1148static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1149{1150struct packed_ref_cache *packed_ref_cache =1151get_packed_ref_cache(&ref_cache);11521153if(!packed_ref_cache->lock)1154die("internal error: packed refs not locked");1155add_ref(get_packed_ref_dir(packed_ref_cache),1156create_ref_entry(refname, sha1, REF_ISPACKED,1));1157}11581159/*1160 * Read the loose references from the namespace dirname into dir1161 * (without recursing). dirname must end with '/'. dir must be the1162 * directory entry corresponding to dirname.1163 */1164static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1165{1166struct ref_cache *refs = dir->ref_cache;1167DIR*d;1168struct dirent *de;1169int dirnamelen =strlen(dirname);1170struct strbuf refname;1171struct strbuf path = STRBUF_INIT;1172size_t path_baselen;11731174if(*refs->name)1175strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1176else1177strbuf_git_path(&path,"%s", dirname);1178 path_baselen = path.len;11791180 d =opendir(path.buf);1181if(!d) {1182strbuf_release(&path);1183return;1184}11851186strbuf_init(&refname, dirnamelen +257);1187strbuf_add(&refname, dirname, dirnamelen);11881189while((de =readdir(d)) != NULL) {1190unsigned char sha1[20];1191struct stat st;1192int flag;11931194if(de->d_name[0] =='.')1195continue;1196if(ends_with(de->d_name,".lock"))1197continue;1198strbuf_addstr(&refname, de->d_name);1199strbuf_addstr(&path, de->d_name);1200if(stat(path.buf, &st) <0) {1201;/* silently ignore */1202}else if(S_ISDIR(st.st_mode)) {1203strbuf_addch(&refname,'/');1204add_entry_to_dir(dir,1205create_dir_entry(refs, refname.buf,1206 refname.len,1));1207}else{1208int read_ok;12091210if(*refs->name) {1211hashclr(sha1);1212 flag =0;1213 read_ok = !resolve_gitlink_ref(refs->name,1214 refname.buf, sha1);1215}else{1216 read_ok = !read_ref_full(refname.buf,1217 RESOLVE_REF_READING,1218 sha1, &flag);1219}12201221if(!read_ok) {1222hashclr(sha1);1223 flag |= REF_ISBROKEN;1224}else if(is_null_sha1(sha1)) {1225/*1226 * It is so astronomically unlikely1227 * that NULL_SHA1 is the SHA-1 of an1228 * actual object that we consider its1229 * appearance in a loose reference1230 * file to be repo corruption1231 * (probably due to a software bug).1232 */1233 flag |= REF_ISBROKEN;1234}12351236if(check_refname_format(refname.buf,1237 REFNAME_ALLOW_ONELEVEL)) {1238if(!refname_is_safe(refname.buf))1239die("loose refname is dangerous:%s", refname.buf);1240hashclr(sha1);1241 flag |= REF_BAD_NAME | REF_ISBROKEN;1242}1243add_entry_to_dir(dir,1244create_ref_entry(refname.buf, sha1, flag,0));1245}1246strbuf_setlen(&refname, dirnamelen);1247strbuf_setlen(&path, path_baselen);1248}1249strbuf_release(&refname);1250strbuf_release(&path);1251closedir(d);1252}12531254static struct ref_dir *get_loose_refs(struct ref_cache *refs)1255{1256if(!refs->loose) {1257/*1258 * Mark the top-level directory complete because we1259 * are about to read the only subdirectory that can1260 * hold references:1261 */1262 refs->loose =create_dir_entry(refs,"",0,0);1263/*1264 * Create an incomplete entry for "refs/":1265 */1266add_entry_to_dir(get_ref_dir(refs->loose),1267create_dir_entry(refs,"refs/",5,1));1268}1269returnget_ref_dir(refs->loose);1270}12711272/* We allow "recursive" symbolic refs. Only within reason, though */1273#define MAXDEPTH 51274#define MAXREFLEN (1024)12751276/*1277 * Called by resolve_gitlink_ref_recursive() after it failed to read1278 * from the loose refs in ref_cache refs. Find <refname> in the1279 * packed-refs file for the submodule.1280 */1281static intresolve_gitlink_packed_ref(struct ref_cache *refs,1282const char*refname,unsigned char*sha1)1283{1284struct ref_entry *ref;1285struct ref_dir *dir =get_packed_refs(refs);12861287 ref =find_ref(dir, refname);1288if(ref == NULL)1289return-1;12901291hashcpy(sha1, ref->u.value.oid.hash);1292return0;1293}12941295static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1296const char*refname,unsigned char*sha1,1297int recursion)1298{1299int fd, len;1300char buffer[128], *p;1301char*path;13021303if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1304return-1;1305 path = *refs->name1306?git_pathdup_submodule(refs->name,"%s", refname)1307:git_pathdup("%s", refname);1308 fd =open(path, O_RDONLY);1309free(path);1310if(fd <0)1311returnresolve_gitlink_packed_ref(refs, refname, sha1);13121313 len =read(fd, buffer,sizeof(buffer)-1);1314close(fd);1315if(len <0)1316return-1;1317while(len &&isspace(buffer[len-1]))1318 len--;1319 buffer[len] =0;13201321/* Was it a detached head or an old-fashioned symlink? */1322if(!get_sha1_hex(buffer, sha1))1323return0;13241325/* Symref? */1326if(strncmp(buffer,"ref:",4))1327return-1;1328 p = buffer +4;1329while(isspace(*p))1330 p++;13311332returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1333}13341335intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1336{1337int len =strlen(path), retval;1338struct strbuf submodule = STRBUF_INIT;1339struct ref_cache *refs;13401341while(len && path[len-1] =='/')1342 len--;1343if(!len)1344return-1;13451346strbuf_add(&submodule, path, len);1347 refs =lookup_ref_cache(submodule.buf);1348if(!refs) {1349if(!is_nonbare_repository_dir(&submodule)) {1350strbuf_release(&submodule);1351return-1;1352}1353 refs =create_ref_cache(submodule.buf);1354}1355strbuf_release(&submodule);13561357 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1358return retval;1359}13601361/*1362 * Return the ref_entry for the given refname from the packed1363 * references. If it does not exist, return NULL.1364 */1365static struct ref_entry *get_packed_ref(const char*refname)1366{1367returnfind_ref(get_packed_refs(&ref_cache), refname);1368}13691370/*1371 * A loose ref file doesn't exist; check for a packed ref.1372 */1373static intresolve_missing_loose_ref(const char*refname,1374unsigned char*sha1,1375int*flags)1376{1377struct ref_entry *entry;13781379/*1380 * The loose reference file does not exist; check for a packed1381 * reference.1382 */1383 entry =get_packed_ref(refname);1384if(entry) {1385hashcpy(sha1, entry->u.value.oid.hash);1386*flags |= REF_ISPACKED;1387return0;1388}1389/* refname is not a packed reference. */1390return-1;1391}13921393/*1394 * Read a raw ref from the filesystem or packed refs file.1395 *1396 * If the ref is a sha1, fill in sha1 and return 0.1397 *1398 * If the ref is symbolic, fill in *symref with the referrent1399 * (e.g. "refs/heads/master") and return 0. The caller is responsible1400 * for validating the referrent. Set REF_ISSYMREF in flags.1401 *1402 * If the ref doesn't exist, set errno to ENOENT and return -1.1403 *1404 * If the ref exists but is neither a symbolic ref nor a sha1, it is1405 * broken. Set REF_ISBROKEN in flags, set errno to EINVAL, and return1406 * -1.1407 *1408 * If there is another error reading the ref, set errno appropriately and1409 * return -1.1410 *1411 * Backend-specific flags might be set in flags as well, regardless of1412 * outcome.1413 *1414 * sb_path is workspace: the caller should allocate and free it.1415 *1416 * It is OK for refname to point into symref. In this case:1417 * - if the function succeeds with REF_ISSYMREF, symref will be1418 * overwritten and the memory pointed to by refname might be changed1419 * or even freed.1420 * - in all other cases, symref will be untouched, and therefore1421 * refname will still be valid and unchanged.1422 */1423static intread_raw_ref(const char*refname,unsigned char*sha1,1424struct strbuf *symref,struct strbuf *sb_path,1425struct strbuf *sb_contents,int*flags)1426{1427const char*path;1428const char*buf;1429struct stat st;1430int fd;14311432strbuf_reset(sb_path);1433strbuf_git_path(sb_path,"%s", refname);1434 path = sb_path->buf;14351436stat_ref:1437/*1438 * We might have to loop back here to avoid a race1439 * condition: first we lstat() the file, then we try1440 * to read it as a link or as a file. But if somebody1441 * changes the type of the file (file <-> directory1442 * <-> symlink) between the lstat() and reading, then1443 * we don't want to report that as an error but rather1444 * try again starting with the lstat().1445 */14461447if(lstat(path, &st) <0) {1448if(errno != ENOENT)1449return-1;1450if(resolve_missing_loose_ref(refname, sha1, flags)) {1451 errno = ENOENT;1452return-1;1453}1454return0;1455}14561457/* Follow "normalized" - ie "refs/.." symlinks by hand */1458if(S_ISLNK(st.st_mode)) {1459strbuf_reset(sb_contents);1460if(strbuf_readlink(sb_contents, path,0) <0) {1461if(errno == ENOENT || errno == EINVAL)1462/* inconsistent with lstat; retry */1463goto stat_ref;1464else1465return-1;1466}1467if(starts_with(sb_contents->buf,"refs/") &&1468!check_refname_format(sb_contents->buf,0)) {1469strbuf_swap(sb_contents, symref);1470*flags |= REF_ISSYMREF;1471return0;1472}1473}14741475/* Is it a directory? */1476if(S_ISDIR(st.st_mode)) {1477 errno = EISDIR;1478return-1;1479}14801481/*1482 * Anything else, just open it and try to use it as1483 * a ref1484 */1485 fd =open(path, O_RDONLY);1486if(fd <0) {1487if(errno == ENOENT)1488/* inconsistent with lstat; retry */1489goto stat_ref;1490else1491return-1;1492}1493strbuf_reset(sb_contents);1494if(strbuf_read(sb_contents, fd,256) <0) {1495int save_errno = errno;1496close(fd);1497 errno = save_errno;1498return-1;1499}1500close(fd);1501strbuf_rtrim(sb_contents);1502 buf = sb_contents->buf;1503if(starts_with(buf,"ref:")) {1504 buf +=4;1505while(isspace(*buf))1506 buf++;15071508strbuf_reset(symref);1509strbuf_addstr(symref, buf);1510*flags |= REF_ISSYMREF;1511return0;1512}15131514/*1515 * Please note that FETCH_HEAD has additional1516 * data after the sha.1517 */1518if(get_sha1_hex(buf, sha1) ||1519(buf[40] !='\0'&& !isspace(buf[40]))) {1520*flags |= REF_ISBROKEN;1521 errno = EINVAL;1522return-1;1523}15241525return0;1526}15271528/* This function needs to return a meaningful errno on failure */1529static const char*resolve_ref_1(const char*refname,1530int resolve_flags,1531unsigned char*sha1,1532int*flags,1533struct strbuf *sb_refname,1534struct strbuf *sb_path,1535struct strbuf *sb_contents)1536{1537int symref_count;15381539*flags =0;15401541if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1542if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1543!refname_is_safe(refname)) {1544 errno = EINVAL;1545return NULL;1546}15471548/*1549 * dwim_ref() uses REF_ISBROKEN to distinguish between1550 * missing refs and refs that were present but invalid,1551 * to complain about the latter to stderr.1552 *1553 * We don't know whether the ref exists, so don't set1554 * REF_ISBROKEN yet.1555 */1556*flags |= REF_BAD_NAME;1557}15581559for(symref_count =0; symref_count < MAXDEPTH; symref_count++) {1560int read_flags =0;15611562if(read_raw_ref(refname, sha1, sb_refname,1563 sb_path, sb_contents, &read_flags)) {1564*flags |= read_flags;1565if(errno != ENOENT || (resolve_flags & RESOLVE_REF_READING))1566return NULL;1567hashclr(sha1);1568if(*flags & REF_BAD_NAME)1569*flags |= REF_ISBROKEN;1570return refname;1571}15721573*flags |= read_flags;15741575if(!(read_flags & REF_ISSYMREF)) {1576if(*flags & REF_BAD_NAME) {1577hashclr(sha1);1578*flags |= REF_ISBROKEN;1579}1580return refname;1581}15821583 refname = sb_refname->buf;1584if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1585hashclr(sha1);1586return refname;1587}1588if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1589if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1590!refname_is_safe(refname)) {1591 errno = EINVAL;1592return NULL;1593}15941595*flags |= REF_ISBROKEN | REF_BAD_NAME;1596}1597}15981599 errno = ELOOP;1600return NULL;1601}16021603const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1604unsigned char*sha1,int*flags)1605{1606static struct strbuf sb_refname = STRBUF_INIT;1607struct strbuf sb_contents = STRBUF_INIT;1608struct strbuf sb_path = STRBUF_INIT;1609int unused_flags;1610const char*ret;16111612if(!flags)1613 flags = &unused_flags;16141615 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1616&sb_refname, &sb_path, &sb_contents);1617strbuf_release(&sb_path);1618strbuf_release(&sb_contents);1619return ret;1620}16211622/*1623 * Peel the entry (if possible) and return its new peel_status. If1624 * repeel is true, re-peel the entry even if there is an old peeled1625 * value that is already stored in it.1626 *1627 * It is OK to call this function with a packed reference entry that1628 * might be stale and might even refer to an object that has since1629 * been garbage-collected. In such a case, if the entry has1630 * REF_KNOWS_PEELED then leave the status unchanged and return1631 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1632 */1633static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1634{1635enum peel_status status;16361637if(entry->flag & REF_KNOWS_PEELED) {1638if(repeel) {1639 entry->flag &= ~REF_KNOWS_PEELED;1640oidclr(&entry->u.value.peeled);1641}else{1642returnis_null_oid(&entry->u.value.peeled) ?1643 PEEL_NON_TAG : PEEL_PEELED;1644}1645}1646if(entry->flag & REF_ISBROKEN)1647return PEEL_BROKEN;1648if(entry->flag & REF_ISSYMREF)1649return PEEL_IS_SYMREF;16501651 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1652if(status == PEEL_PEELED || status == PEEL_NON_TAG)1653 entry->flag |= REF_KNOWS_PEELED;1654return status;1655}16561657intpeel_ref(const char*refname,unsigned char*sha1)1658{1659int flag;1660unsigned char base[20];16611662if(current_ref && (current_ref->name == refname1663|| !strcmp(current_ref->name, refname))) {1664if(peel_entry(current_ref,0))1665return-1;1666hashcpy(sha1, current_ref->u.value.peeled.hash);1667return0;1668}16691670if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1671return-1;16721673/*1674 * If the reference is packed, read its ref_entry from the1675 * cache in the hope that we already know its peeled value.1676 * We only try this optimization on packed references because1677 * (a) forcing the filling of the loose reference cache could1678 * be expensive and (b) loose references anyway usually do not1679 * have REF_KNOWS_PEELED.1680 */1681if(flag & REF_ISPACKED) {1682struct ref_entry *r =get_packed_ref(refname);1683if(r) {1684if(peel_entry(r,0))1685return-1;1686hashcpy(sha1, r->u.value.peeled.hash);1687return0;1688}1689}16901691returnpeel_object(base, sha1);1692}16931694/*1695 * Call fn for each reference in the specified ref_cache, omitting1696 * references not in the containing_dir of base. fn is called for all1697 * references, including broken ones. If fn ever returns a non-zero1698 * value, stop the iteration and return that value; otherwise, return1699 * 0.1700 */1701static intdo_for_each_entry(struct ref_cache *refs,const char*base,1702 each_ref_entry_fn fn,void*cb_data)1703{1704struct packed_ref_cache *packed_ref_cache;1705struct ref_dir *loose_dir;1706struct ref_dir *packed_dir;1707int retval =0;17081709/*1710 * We must make sure that all loose refs are read before accessing the1711 * packed-refs file; this avoids a race condition in which loose refs1712 * are migrated to the packed-refs file by a simultaneous process, but1713 * our in-memory view is from before the migration. get_packed_ref_cache()1714 * takes care of making sure our view is up to date with what is on1715 * disk.1716 */1717 loose_dir =get_loose_refs(refs);1718if(base && *base) {1719 loose_dir =find_containing_dir(loose_dir, base,0);1720}1721if(loose_dir)1722prime_ref_dir(loose_dir);17231724 packed_ref_cache =get_packed_ref_cache(refs);1725acquire_packed_ref_cache(packed_ref_cache);1726 packed_dir =get_packed_ref_dir(packed_ref_cache);1727if(base && *base) {1728 packed_dir =find_containing_dir(packed_dir, base,0);1729}17301731if(packed_dir && loose_dir) {1732sort_ref_dir(packed_dir);1733sort_ref_dir(loose_dir);1734 retval =do_for_each_entry_in_dirs(1735 packed_dir, loose_dir, fn, cb_data);1736}else if(packed_dir) {1737sort_ref_dir(packed_dir);1738 retval =do_for_each_entry_in_dir(1739 packed_dir,0, fn, cb_data);1740}else if(loose_dir) {1741sort_ref_dir(loose_dir);1742 retval =do_for_each_entry_in_dir(1743 loose_dir,0, fn, cb_data);1744}17451746release_packed_ref_cache(packed_ref_cache);1747return retval;1748}17491750/*1751 * Call fn for each reference in the specified ref_cache for which the1752 * refname begins with base. If trim is non-zero, then trim that many1753 * characters off the beginning of each refname before passing the1754 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1755 * broken references in the iteration. If fn ever returns a non-zero1756 * value, stop the iteration and return that value; otherwise, return1757 * 0.1758 */1759intdo_for_each_ref(const char*submodule,const char*base,1760 each_ref_fn fn,int trim,int flags,void*cb_data)1761{1762struct ref_entry_cb data;1763struct ref_cache *refs;17641765 refs =get_ref_cache(submodule);1766 data.base = base;1767 data.trim = trim;1768 data.flags = flags;1769 data.fn = fn;1770 data.cb_data = cb_data;17711772if(ref_paranoia <0)1773 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1774if(ref_paranoia)1775 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;17761777returndo_for_each_entry(refs, base, do_one_ref, &data);1778}17791780static voidunlock_ref(struct ref_lock *lock)1781{1782/* Do not free lock->lk -- atexit() still looks at them */1783if(lock->lk)1784rollback_lock_file(lock->lk);1785free(lock->ref_name);1786free(lock->orig_ref_name);1787free(lock);1788}17891790/*1791 * Verify that the reference locked by lock has the value old_sha1.1792 * Fail if the reference doesn't exist and mustexist is set. Return 01793 * on success. On error, write an error message to err, set errno, and1794 * return a negative value.1795 */1796static intverify_lock(struct ref_lock *lock,1797const unsigned char*old_sha1,int mustexist,1798struct strbuf *err)1799{1800assert(err);18011802if(read_ref_full(lock->ref_name,1803 mustexist ? RESOLVE_REF_READING :0,1804 lock->old_oid.hash, NULL)) {1805if(old_sha1) {1806int save_errno = errno;1807strbuf_addf(err,"can't verify ref%s", lock->ref_name);1808 errno = save_errno;1809return-1;1810}else{1811hashclr(lock->old_oid.hash);1812return0;1813}1814}1815if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1816strbuf_addf(err,"ref%sis at%sbut expected%s",1817 lock->ref_name,1818sha1_to_hex(lock->old_oid.hash),1819sha1_to_hex(old_sha1));1820 errno = EBUSY;1821return-1;1822}1823return0;1824}18251826static intremove_empty_directories(struct strbuf *path)1827{1828/*1829 * we want to create a file but there is a directory there;1830 * if that is an empty directory (or a directory that contains1831 * only empty directories), remove them.1832 */1833returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1834}18351836/*1837 * Locks a ref returning the lock on success and NULL on failure.1838 * On failure errno is set to something meaningful.1839 */1840static struct ref_lock *lock_ref_sha1_basic(const char*refname,1841const unsigned char*old_sha1,1842const struct string_list *extras,1843const struct string_list *skip,1844unsigned int flags,int*type_p,1845struct strbuf *err)1846{1847struct strbuf ref_file = STRBUF_INIT;1848struct strbuf orig_ref_file = STRBUF_INIT;1849const char*orig_refname = refname;1850struct ref_lock *lock;1851int last_errno =0;1852int type;1853int lflags =0;1854int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1855int resolve_flags =0;1856int attempts_remaining =3;18571858assert(err);18591860 lock =xcalloc(1,sizeof(struct ref_lock));18611862if(mustexist)1863 resolve_flags |= RESOLVE_REF_READING;1864if(flags & REF_DELETING)1865 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1866if(flags & REF_NODEREF) {1867 resolve_flags |= RESOLVE_REF_NO_RECURSE;1868 lflags |= LOCK_NO_DEREF;1869}18701871 refname =resolve_ref_unsafe(refname, resolve_flags,1872 lock->old_oid.hash, &type);1873if(!refname && errno == EISDIR) {1874/*1875 * we are trying to lock foo but we used to1876 * have foo/bar which now does not exist;1877 * it is normal for the empty directory 'foo'1878 * to remain.1879 */1880strbuf_git_path(&orig_ref_file,"%s", orig_refname);1881if(remove_empty_directories(&orig_ref_file)) {1882 last_errno = errno;1883if(!verify_refname_available_dir(orig_refname, extras, skip,1884get_loose_refs(&ref_cache), err))1885strbuf_addf(err,"there are still refs under '%s'",1886 orig_refname);1887goto error_return;1888}1889 refname =resolve_ref_unsafe(orig_refname, resolve_flags,1890 lock->old_oid.hash, &type);1891}1892if(type_p)1893*type_p = type;1894if(!refname) {1895 last_errno = errno;1896if(last_errno != ENOTDIR ||1897!verify_refname_available_dir(orig_refname, extras, skip,1898get_loose_refs(&ref_cache), err))1899strbuf_addf(err,"unable to resolve reference%s:%s",1900 orig_refname,strerror(last_errno));19011902goto error_return;1903}19041905if(flags & REF_NODEREF)1906 refname = orig_refname;19071908/*1909 * If the ref did not exist and we are creating it, make sure1910 * there is no existing packed ref whose name begins with our1911 * refname, nor a packed ref whose name is a proper prefix of1912 * our refname.1913 */1914if(is_null_oid(&lock->old_oid) &&1915verify_refname_available_dir(refname, extras, skip,1916get_packed_refs(&ref_cache), err)) {1917 last_errno = ENOTDIR;1918goto error_return;1919}19201921 lock->lk =xcalloc(1,sizeof(struct lock_file));19221923 lock->ref_name =xstrdup(refname);1924 lock->orig_ref_name =xstrdup(orig_refname);1925strbuf_git_path(&ref_file,"%s", refname);19261927 retry:1928switch(safe_create_leading_directories_const(ref_file.buf)) {1929case SCLD_OK:1930break;/* success */1931case SCLD_VANISHED:1932if(--attempts_remaining >0)1933goto retry;1934/* fall through */1935default:1936 last_errno = errno;1937strbuf_addf(err,"unable to create directory for%s",1938 ref_file.buf);1939goto error_return;1940}19411942if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {1943 last_errno = errno;1944if(errno == ENOENT && --attempts_remaining >0)1945/*1946 * Maybe somebody just deleted one of the1947 * directories leading to ref_file. Try1948 * again:1949 */1950goto retry;1951else{1952unable_to_lock_message(ref_file.buf, errno, err);1953goto error_return;1954}1955}1956if(verify_lock(lock, old_sha1, mustexist, err)) {1957 last_errno = errno;1958goto error_return;1959}1960goto out;19611962 error_return:1963unlock_ref(lock);1964 lock = NULL;19651966 out:1967strbuf_release(&ref_file);1968strbuf_release(&orig_ref_file);1969 errno = last_errno;1970return lock;1971}19721973/*1974 * Write an entry to the packed-refs file for the specified refname.1975 * If peeled is non-NULL, write it as the entry's peeled value.1976 */1977static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,1978unsigned char*peeled)1979{1980fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1981if(peeled)1982fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1983}19841985/*1986 * An each_ref_entry_fn that writes the entry to a packed-refs file.1987 */1988static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)1989{1990enum peel_status peel_status =peel_entry(entry,0);19911992if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1993error("internal error:%sis not a valid packed reference!",1994 entry->name);1995write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,1996 peel_status == PEEL_PEELED ?1997 entry->u.value.peeled.hash : NULL);1998return0;1999}20002001/*2002 * Lock the packed-refs file for writing. Flags is passed to2003 * hold_lock_file_for_update(). Return 0 on success. On errors, set2004 * errno appropriately and return a nonzero value.2005 */2006static intlock_packed_refs(int flags)2007{2008static int timeout_configured =0;2009static int timeout_value =1000;20102011struct packed_ref_cache *packed_ref_cache;20122013if(!timeout_configured) {2014git_config_get_int("core.packedrefstimeout", &timeout_value);2015 timeout_configured =1;2016}20172018if(hold_lock_file_for_update_timeout(2019&packlock,git_path("packed-refs"),2020 flags, timeout_value) <0)2021return-1;2022/*2023 * Get the current packed-refs while holding the lock. If the2024 * packed-refs file has been modified since we last read it,2025 * this will automatically invalidate the cache and re-read2026 * the packed-refs file.2027 */2028 packed_ref_cache =get_packed_ref_cache(&ref_cache);2029 packed_ref_cache->lock = &packlock;2030/* Increment the reference count to prevent it from being freed: */2031acquire_packed_ref_cache(packed_ref_cache);2032return0;2033}20342035/*2036 * Write the current version of the packed refs cache from memory to2037 * disk. The packed-refs file must already be locked for writing (see2038 * lock_packed_refs()). Return zero on success. On errors, set errno2039 * and return a nonzero value2040 */2041static intcommit_packed_refs(void)2042{2043struct packed_ref_cache *packed_ref_cache =2044get_packed_ref_cache(&ref_cache);2045int error =0;2046int save_errno =0;2047FILE*out;20482049if(!packed_ref_cache->lock)2050die("internal error: packed-refs not locked");20512052 out =fdopen_lock_file(packed_ref_cache->lock,"w");2053if(!out)2054die_errno("unable to fdopen packed-refs descriptor");20552056fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2057do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),20580, write_packed_entry_fn, out);20592060if(commit_lock_file(packed_ref_cache->lock)) {2061 save_errno = errno;2062 error = -1;2063}2064 packed_ref_cache->lock = NULL;2065release_packed_ref_cache(packed_ref_cache);2066 errno = save_errno;2067return error;2068}20692070/*2071 * Rollback the lockfile for the packed-refs file, and discard the2072 * in-memory packed reference cache. (The packed-refs file will be2073 * read anew if it is needed again after this function is called.)2074 */2075static voidrollback_packed_refs(void)2076{2077struct packed_ref_cache *packed_ref_cache =2078get_packed_ref_cache(&ref_cache);20792080if(!packed_ref_cache->lock)2081die("internal error: packed-refs not locked");2082rollback_lock_file(packed_ref_cache->lock);2083 packed_ref_cache->lock = NULL;2084release_packed_ref_cache(packed_ref_cache);2085clear_packed_ref_cache(&ref_cache);2086}20872088struct ref_to_prune {2089struct ref_to_prune *next;2090unsigned char sha1[20];2091char name[FLEX_ARRAY];2092};20932094struct pack_refs_cb_data {2095unsigned int flags;2096struct ref_dir *packed_refs;2097struct ref_to_prune *ref_to_prune;2098};20992100/*2101 * An each_ref_entry_fn that is run over loose references only. If2102 * the loose reference can be packed, add an entry in the packed ref2103 * cache. If the reference should be pruned, also add it to2104 * ref_to_prune in the pack_refs_cb_data.2105 */2106static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2107{2108struct pack_refs_cb_data *cb = cb_data;2109enum peel_status peel_status;2110struct ref_entry *packed_entry;2111int is_tag_ref =starts_with(entry->name,"refs/tags/");21122113/* Do not pack per-worktree refs: */2114if(ref_type(entry->name) != REF_TYPE_NORMAL)2115return0;21162117/* ALWAYS pack tags */2118if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2119return0;21202121/* Do not pack symbolic or broken refs: */2122if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2123return0;21242125/* Add a packed ref cache entry equivalent to the loose entry. */2126 peel_status =peel_entry(entry,1);2127if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2128die("internal error peeling reference%s(%s)",2129 entry->name,oid_to_hex(&entry->u.value.oid));2130 packed_entry =find_ref(cb->packed_refs, entry->name);2131if(packed_entry) {2132/* Overwrite existing packed entry with info from loose entry */2133 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2134oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2135}else{2136 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2137 REF_ISPACKED | REF_KNOWS_PEELED,0);2138add_ref(cb->packed_refs, packed_entry);2139}2140oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);21412142/* Schedule the loose reference for pruning if requested. */2143if((cb->flags & PACK_REFS_PRUNE)) {2144struct ref_to_prune *n;2145FLEX_ALLOC_STR(n, name, entry->name);2146hashcpy(n->sha1, entry->u.value.oid.hash);2147 n->next = cb->ref_to_prune;2148 cb->ref_to_prune = n;2149}2150return0;2151}21522153/*2154 * Remove empty parents, but spare refs/ and immediate subdirs.2155 * Note: munges *name.2156 */2157static voidtry_remove_empty_parents(char*name)2158{2159char*p, *q;2160int i;2161 p = name;2162for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2163while(*p && *p !='/')2164 p++;2165/* tolerate duplicate slashes; see check_refname_format() */2166while(*p =='/')2167 p++;2168}2169for(q = p; *q; q++)2170;2171while(1) {2172while(q > p && *q !='/')2173 q--;2174while(q > p && *(q-1) =='/')2175 q--;2176if(q == p)2177break;2178*q ='\0';2179if(rmdir(git_path("%s", name)))2180break;2181}2182}21832184/* make sure nobody touched the ref, and unlink */2185static voidprune_ref(struct ref_to_prune *r)2186{2187struct ref_transaction *transaction;2188struct strbuf err = STRBUF_INIT;21892190if(check_refname_format(r->name,0))2191return;21922193 transaction =ref_transaction_begin(&err);2194if(!transaction ||2195ref_transaction_delete(transaction, r->name, r->sha1,2196 REF_ISPRUNING, NULL, &err) ||2197ref_transaction_commit(transaction, &err)) {2198ref_transaction_free(transaction);2199error("%s", err.buf);2200strbuf_release(&err);2201return;2202}2203ref_transaction_free(transaction);2204strbuf_release(&err);2205try_remove_empty_parents(r->name);2206}22072208static voidprune_refs(struct ref_to_prune *r)2209{2210while(r) {2211prune_ref(r);2212 r = r->next;2213}2214}22152216intpack_refs(unsigned int flags)2217{2218struct pack_refs_cb_data cbdata;22192220memset(&cbdata,0,sizeof(cbdata));2221 cbdata.flags = flags;22222223lock_packed_refs(LOCK_DIE_ON_ERROR);2224 cbdata.packed_refs =get_packed_refs(&ref_cache);22252226do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2227 pack_if_possible_fn, &cbdata);22282229if(commit_packed_refs())2230die_errno("unable to overwrite old ref-pack file");22312232prune_refs(cbdata.ref_to_prune);2233return0;2234}22352236/*2237 * Rewrite the packed-refs file, omitting any refs listed in2238 * 'refnames'. On error, leave packed-refs unchanged, write an error2239 * message to 'err', and return a nonzero value.2240 *2241 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2242 */2243static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2244{2245struct ref_dir *packed;2246struct string_list_item *refname;2247int ret, needs_repacking =0, removed =0;22482249assert(err);22502251/* Look for a packed ref */2252for_each_string_list_item(refname, refnames) {2253if(get_packed_ref(refname->string)) {2254 needs_repacking =1;2255break;2256}2257}22582259/* Avoid locking if we have nothing to do */2260if(!needs_repacking)2261return0;/* no refname exists in packed refs */22622263if(lock_packed_refs(0)) {2264unable_to_lock_message(git_path("packed-refs"), errno, err);2265return-1;2266}2267 packed =get_packed_refs(&ref_cache);22682269/* Remove refnames from the cache */2270for_each_string_list_item(refname, refnames)2271if(remove_entry(packed, refname->string) != -1)2272 removed =1;2273if(!removed) {2274/*2275 * All packed entries disappeared while we were2276 * acquiring the lock.2277 */2278rollback_packed_refs();2279return0;2280}22812282/* Write what remains */2283 ret =commit_packed_refs();2284if(ret)2285strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2286strerror(errno));2287return ret;2288}22892290static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2291{2292assert(err);22932294if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2295/*2296 * loose. The loose file name is the same as the2297 * lockfile name, minus ".lock":2298 */2299char*loose_filename =get_locked_file_path(lock->lk);2300int res =unlink_or_msg(loose_filename, err);2301free(loose_filename);2302if(res)2303return1;2304}2305return0;2306}23072308intdelete_refs(struct string_list *refnames)2309{2310struct strbuf err = STRBUF_INIT;2311int i, result =0;23122313if(!refnames->nr)2314return0;23152316 result =repack_without_refs(refnames, &err);2317if(result) {2318/*2319 * If we failed to rewrite the packed-refs file, then2320 * it is unsafe to try to remove loose refs, because2321 * doing so might expose an obsolete packed value for2322 * a reference that might even point at an object that2323 * has been garbage collected.2324 */2325if(refnames->nr ==1)2326error(_("could not delete reference%s:%s"),2327 refnames->items[0].string, err.buf);2328else2329error(_("could not delete references:%s"), err.buf);23302331goto out;2332}23332334for(i =0; i < refnames->nr; i++) {2335const char*refname = refnames->items[i].string;23362337if(delete_ref(refname, NULL,0))2338 result |=error(_("could not remove reference%s"), refname);2339}23402341out:2342strbuf_release(&err);2343return result;2344}23452346/*2347 * People using contrib's git-new-workdir have .git/logs/refs ->2348 * /some/other/path/.git/logs/refs, and that may live on another device.2349 *2350 * IOW, to avoid cross device rename errors, the temporary renamed log must2351 * live into logs/refs.2352 */2353#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"23542355static intrename_tmp_log(const char*newrefname)2356{2357int attempts_remaining =4;2358struct strbuf path = STRBUF_INIT;2359int ret = -1;23602361 retry:2362strbuf_reset(&path);2363strbuf_git_path(&path,"logs/%s", newrefname);2364switch(safe_create_leading_directories_const(path.buf)) {2365case SCLD_OK:2366break;/* success */2367case SCLD_VANISHED:2368if(--attempts_remaining >0)2369goto retry;2370/* fall through */2371default:2372error("unable to create directory for%s", newrefname);2373goto out;2374}23752376if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2377if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2378/*2379 * rename(a, b) when b is an existing2380 * directory ought to result in ISDIR, but2381 * Solaris 5.8 gives ENOTDIR. Sheesh.2382 */2383if(remove_empty_directories(&path)) {2384error("Directory not empty: logs/%s", newrefname);2385goto out;2386}2387goto retry;2388}else if(errno == ENOENT && --attempts_remaining >0) {2389/*2390 * Maybe another process just deleted one of2391 * the directories in the path to newrefname.2392 * Try again from the beginning.2393 */2394goto retry;2395}else{2396error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2397 newrefname,strerror(errno));2398goto out;2399}2400}2401 ret =0;2402out:2403strbuf_release(&path);2404return ret;2405}24062407intverify_refname_available(const char*newname,2408struct string_list *extras,2409struct string_list *skip,2410struct strbuf *err)2411{2412struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2413struct ref_dir *loose_refs =get_loose_refs(&ref_cache);24142415if(verify_refname_available_dir(newname, extras, skip,2416 packed_refs, err) ||2417verify_refname_available_dir(newname, extras, skip,2418 loose_refs, err))2419return-1;24202421return0;2422}24232424static intwrite_ref_to_lockfile(struct ref_lock *lock,2425const unsigned char*sha1,struct strbuf *err);2426static intcommit_ref_update(struct ref_lock *lock,2427const unsigned char*sha1,const char*logmsg,2428int flags,struct strbuf *err);24292430intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2431{2432unsigned char sha1[20], orig_sha1[20];2433int flag =0, logmoved =0;2434struct ref_lock *lock;2435struct stat loginfo;2436int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2437const char*symref = NULL;2438struct strbuf err = STRBUF_INIT;24392440if(log &&S_ISLNK(loginfo.st_mode))2441returnerror("reflog for%sis a symlink", oldrefname);24422443 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2444 orig_sha1, &flag);2445if(flag & REF_ISSYMREF)2446returnerror("refname%sis a symbolic ref, renaming it is not supported",2447 oldrefname);2448if(!symref)2449returnerror("refname%snot found", oldrefname);24502451if(!rename_ref_available(oldrefname, newrefname))2452return1;24532454if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2455returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2456 oldrefname,strerror(errno));24572458if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2459error("unable to delete old%s", oldrefname);2460goto rollback;2461}24622463if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2464delete_ref(newrefname, sha1, REF_NODEREF)) {2465if(errno==EISDIR) {2466struct strbuf path = STRBUF_INIT;2467int result;24682469strbuf_git_path(&path,"%s", newrefname);2470 result =remove_empty_directories(&path);2471strbuf_release(&path);24722473if(result) {2474error("Directory not empty:%s", newrefname);2475goto rollback;2476}2477}else{2478error("unable to delete existing%s", newrefname);2479goto rollback;2480}2481}24822483if(log &&rename_tmp_log(newrefname))2484goto rollback;24852486 logmoved = log;24872488 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2489if(!lock) {2490error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2491strbuf_release(&err);2492goto rollback;2493}2494hashcpy(lock->old_oid.hash, orig_sha1);24952496if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2497commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2498error("unable to write current sha1 into%s:%s", newrefname, err.buf);2499strbuf_release(&err);2500goto rollback;2501}25022503return0;25042505 rollback:2506 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2507if(!lock) {2508error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2509strbuf_release(&err);2510goto rollbacklog;2511}25122513 flag = log_all_ref_updates;2514 log_all_ref_updates =0;2515if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2516commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2517error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2518strbuf_release(&err);2519}2520 log_all_ref_updates = flag;25212522 rollbacklog:2523if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2524error("unable to restore logfile%sfrom%s:%s",2525 oldrefname, newrefname,strerror(errno));2526if(!logmoved && log &&2527rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2528error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2529 oldrefname,strerror(errno));25302531return1;2532}25332534static intclose_ref(struct ref_lock *lock)2535{2536if(close_lock_file(lock->lk))2537return-1;2538return0;2539}25402541static intcommit_ref(struct ref_lock *lock)2542{2543if(commit_lock_file(lock->lk))2544return-1;2545return0;2546}25472548/*2549 * Create a reflog for a ref. If force_create = 0, the reflog will2550 * only be created for certain refs (those for which2551 * should_autocreate_reflog returns non-zero. Otherwise, create it2552 * regardless of the ref name. Fill in *err and return -1 on failure.2553 */2554static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2555{2556int logfd, oflags = O_APPEND | O_WRONLY;25572558strbuf_git_path(logfile,"logs/%s", refname);2559if(force_create ||should_autocreate_reflog(refname)) {2560if(safe_create_leading_directories(logfile->buf) <0) {2561strbuf_addf(err,"unable to create directory for%s: "2562"%s", logfile->buf,strerror(errno));2563return-1;2564}2565 oflags |= O_CREAT;2566}25672568 logfd =open(logfile->buf, oflags,0666);2569if(logfd <0) {2570if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2571return0;25722573if(errno == EISDIR) {2574if(remove_empty_directories(logfile)) {2575strbuf_addf(err,"There are still logs under "2576"'%s'", logfile->buf);2577return-1;2578}2579 logfd =open(logfile->buf, oflags,0666);2580}25812582if(logfd <0) {2583strbuf_addf(err,"unable to append to%s:%s",2584 logfile->buf,strerror(errno));2585return-1;2586}2587}25882589adjust_shared_perm(logfile->buf);2590close(logfd);2591return0;2592}259325942595intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2596{2597int ret;2598struct strbuf sb = STRBUF_INIT;25992600 ret =log_ref_setup(refname, &sb, err, force_create);2601strbuf_release(&sb);2602return ret;2603}26042605static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2606const unsigned char*new_sha1,2607const char*committer,const char*msg)2608{2609int msglen, written;2610unsigned maxlen, len;2611char*logrec;26122613 msglen = msg ?strlen(msg) :0;2614 maxlen =strlen(committer) + msglen +100;2615 logrec =xmalloc(maxlen);2616 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2617sha1_to_hex(old_sha1),2618sha1_to_hex(new_sha1),2619 committer);2620if(msglen)2621 len +=copy_reflog_msg(logrec + len -1, msg) -1;26222623 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2624free(logrec);2625if(written != len)2626return-1;26272628return0;2629}26302631static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2632const unsigned char*new_sha1,const char*msg,2633struct strbuf *logfile,int flags,2634struct strbuf *err)2635{2636int logfd, result, oflags = O_APPEND | O_WRONLY;26372638if(log_all_ref_updates <0)2639 log_all_ref_updates = !is_bare_repository();26402641 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);26422643if(result)2644return result;26452646 logfd =open(logfile->buf, oflags);2647if(logfd <0)2648return0;2649 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2650git_committer_info(0), msg);2651if(result) {2652strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2653strerror(errno));2654close(logfd);2655return-1;2656}2657if(close(logfd)) {2658strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2659strerror(errno));2660return-1;2661}2662return0;2663}26642665static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2666const unsigned char*new_sha1,const char*msg,2667int flags,struct strbuf *err)2668{2669returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2670 err);2671}26722673intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2674const unsigned char*new_sha1,const char*msg,2675int flags,struct strbuf *err)2676{2677struct strbuf sb = STRBUF_INIT;2678int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2679 err);2680strbuf_release(&sb);2681return ret;2682}26832684/*2685 * Write sha1 into the open lockfile, then close the lockfile. On2686 * errors, rollback the lockfile, fill in *err and2687 * return -1.2688 */2689static intwrite_ref_to_lockfile(struct ref_lock *lock,2690const unsigned char*sha1,struct strbuf *err)2691{2692static char term ='\n';2693struct object *o;2694int fd;26952696 o =parse_object(sha1);2697if(!o) {2698strbuf_addf(err,2699"Trying to write ref%swith nonexistent object%s",2700 lock->ref_name,sha1_to_hex(sha1));2701unlock_ref(lock);2702return-1;2703}2704if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2705strbuf_addf(err,2706"Trying to write non-commit object%sto branch%s",2707sha1_to_hex(sha1), lock->ref_name);2708unlock_ref(lock);2709return-1;2710}2711 fd =get_lock_file_fd(lock->lk);2712if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2713write_in_full(fd, &term,1) !=1||2714close_ref(lock) <0) {2715strbuf_addf(err,2716"Couldn't write%s",get_lock_file_path(lock->lk));2717unlock_ref(lock);2718return-1;2719}2720return0;2721}27222723/*2724 * Commit a change to a loose reference that has already been written2725 * to the loose reference lockfile. Also update the reflogs if2726 * necessary, using the specified lockmsg (which can be NULL).2727 */2728static intcommit_ref_update(struct ref_lock *lock,2729const unsigned char*sha1,const char*logmsg,2730int flags,struct strbuf *err)2731{2732clear_loose_ref_cache(&ref_cache);2733if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2734(strcmp(lock->ref_name, lock->orig_ref_name) &&2735log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2736char*old_msg =strbuf_detach(err, NULL);2737strbuf_addf(err,"Cannot update the ref '%s':%s",2738 lock->ref_name, old_msg);2739free(old_msg);2740unlock_ref(lock);2741return-1;2742}2743if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2744/*2745 * Special hack: If a branch is updated directly and HEAD2746 * points to it (may happen on the remote side of a push2747 * for example) then logically the HEAD reflog should be2748 * updated too.2749 * A generic solution implies reverse symref information,2750 * but finding all symrefs pointing to the given branch2751 * would be rather costly for this rare event (the direct2752 * update of a branch) to be worth it. So let's cheat and2753 * check with HEAD only which should cover 99% of all usage2754 * scenarios (even 100% of the default ones).2755 */2756unsigned char head_sha1[20];2757int head_flag;2758const char*head_ref;2759 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2760 head_sha1, &head_flag);2761if(head_ref && (head_flag & REF_ISSYMREF) &&2762!strcmp(head_ref, lock->ref_name)) {2763struct strbuf log_err = STRBUF_INIT;2764if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2765 logmsg,0, &log_err)) {2766error("%s", log_err.buf);2767strbuf_release(&log_err);2768}2769}2770}2771if(commit_ref(lock)) {2772error("Couldn't set%s", lock->ref_name);2773unlock_ref(lock);2774return-1;2775}27762777unlock_ref(lock);2778return0;2779}27802781static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2782{2783int ret = -1;2784#ifndef NO_SYMLINK_HEAD2785char*ref_path =get_locked_file_path(lock->lk);2786unlink(ref_path);2787 ret =symlink(target, ref_path);2788free(ref_path);27892790if(ret)2791fprintf(stderr,"no symlink - falling back to symbolic ref\n");2792#endif2793return ret;2794}27952796static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2797const char*target,const char*logmsg)2798{2799struct strbuf err = STRBUF_INIT;2800unsigned char new_sha1[20];2801if(logmsg && !read_ref(target, new_sha1) &&2802log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2803error("%s", err.buf);2804strbuf_release(&err);2805}2806}28072808static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2809const char*target,const char*logmsg)2810{2811if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2812update_symref_reflog(lock, refname, target, logmsg);2813return0;2814}28152816if(!fdopen_lock_file(lock->lk,"w"))2817returnerror("unable to fdopen%s:%s",2818 lock->lk->tempfile.filename.buf,strerror(errno));28192820update_symref_reflog(lock, refname, target, logmsg);28212822/* no error check; commit_ref will check ferror */2823fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2824if(commit_ref(lock) <0)2825returnerror("unable to write symref for%s:%s", refname,2826strerror(errno));2827return0;2828}28292830intcreate_symref(const char*refname,const char*target,const char*logmsg)2831{2832struct strbuf err = STRBUF_INIT;2833struct ref_lock *lock;2834int ret;28352836 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2837&err);2838if(!lock) {2839error("%s", err.buf);2840strbuf_release(&err);2841return-1;2842}28432844 ret =create_symref_locked(lock, refname, target, logmsg);2845unlock_ref(lock);2846return ret;2847}28482849intreflog_exists(const char*refname)2850{2851struct stat st;28522853return!lstat(git_path("logs/%s", refname), &st) &&2854S_ISREG(st.st_mode);2855}28562857intdelete_reflog(const char*refname)2858{2859returnremove_path(git_path("logs/%s", refname));2860}28612862static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2863{2864unsigned char osha1[20], nsha1[20];2865char*email_end, *message;2866unsigned long timestamp;2867int tz;28682869/* old SP new SP name <email> SP time TAB msg LF */2870if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2871get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2872get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2873!(email_end =strchr(sb->buf +82,'>')) ||2874 email_end[1] !=' '||2875!(timestamp =strtoul(email_end +2, &message,10)) ||2876!message || message[0] !=' '||2877(message[1] !='+'&& message[1] !='-') ||2878!isdigit(message[2]) || !isdigit(message[3]) ||2879!isdigit(message[4]) || !isdigit(message[5]))2880return0;/* corrupt? */2881 email_end[1] ='\0';2882 tz =strtol(message +1, NULL,10);2883if(message[6] !='\t')2884 message +=6;2885else2886 message +=7;2887returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2888}28892890static char*find_beginning_of_line(char*bob,char*scan)2891{2892while(bob < scan && *(--scan) !='\n')2893;/* keep scanning backwards */2894/*2895 * Return either beginning of the buffer, or LF at the end of2896 * the previous line.2897 */2898return scan;2899}29002901intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2902{2903struct strbuf sb = STRBUF_INIT;2904FILE*logfp;2905long pos;2906int ret =0, at_tail =1;29072908 logfp =fopen(git_path("logs/%s", refname),"r");2909if(!logfp)2910return-1;29112912/* Jump to the end */2913if(fseek(logfp,0, SEEK_END) <0)2914returnerror("cannot seek back reflog for%s:%s",2915 refname,strerror(errno));2916 pos =ftell(logfp);2917while(!ret &&0< pos) {2918int cnt;2919size_t nread;2920char buf[BUFSIZ];2921char*endp, *scanp;29222923/* Fill next block from the end */2924 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2925if(fseek(logfp, pos - cnt, SEEK_SET))2926returnerror("cannot seek back reflog for%s:%s",2927 refname,strerror(errno));2928 nread =fread(buf, cnt,1, logfp);2929if(nread !=1)2930returnerror("cannot read%dbytes from reflog for%s:%s",2931 cnt, refname,strerror(errno));2932 pos -= cnt;29332934 scanp = endp = buf + cnt;2935if(at_tail && scanp[-1] =='\n')2936/* Looking at the final LF at the end of the file */2937 scanp--;2938 at_tail =0;29392940while(buf < scanp) {2941/*2942 * terminating LF of the previous line, or the beginning2943 * of the buffer.2944 */2945char*bp;29462947 bp =find_beginning_of_line(buf, scanp);29482949if(*bp =='\n') {2950/*2951 * The newline is the end of the previous line,2952 * so we know we have complete line starting2953 * at (bp + 1). Prefix it onto any prior data2954 * we collected for the line and process it.2955 */2956strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2957 scanp = bp;2958 endp = bp +1;2959 ret =show_one_reflog_ent(&sb, fn, cb_data);2960strbuf_reset(&sb);2961if(ret)2962break;2963}else if(!pos) {2964/*2965 * We are at the start of the buffer, and the2966 * start of the file; there is no previous2967 * line, and we have everything for this one.2968 * Process it, and we can end the loop.2969 */2970strbuf_splice(&sb,0,0, buf, endp - buf);2971 ret =show_one_reflog_ent(&sb, fn, cb_data);2972strbuf_reset(&sb);2973break;2974}29752976if(bp == buf) {2977/*2978 * We are at the start of the buffer, and there2979 * is more file to read backwards. Which means2980 * we are in the middle of a line. Note that we2981 * may get here even if *bp was a newline; that2982 * just means we are at the exact end of the2983 * previous line, rather than some spot in the2984 * middle.2985 *2986 * Save away what we have to be combined with2987 * the data from the next read.2988 */2989strbuf_splice(&sb,0,0, buf, endp - buf);2990break;2991}2992}29932994}2995if(!ret && sb.len)2996die("BUG: reverse reflog parser had leftover data");29972998fclose(logfp);2999strbuf_release(&sb);3000return ret;3001}30023003intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3004{3005FILE*logfp;3006struct strbuf sb = STRBUF_INIT;3007int ret =0;30083009 logfp =fopen(git_path("logs/%s", refname),"r");3010if(!logfp)3011return-1;30123013while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3014 ret =show_one_reflog_ent(&sb, fn, cb_data);3015fclose(logfp);3016strbuf_release(&sb);3017return ret;3018}3019/*3020 * Call fn for each reflog in the namespace indicated by name. name3021 * must be empty or end with '/'. Name will be used as a scratch3022 * space, but its contents will be restored before return.3023 */3024static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3025{3026DIR*d =opendir(git_path("logs/%s", name->buf));3027int retval =0;3028struct dirent *de;3029int oldlen = name->len;30303031if(!d)3032return name->len ? errno :0;30333034while((de =readdir(d)) != NULL) {3035struct stat st;30363037if(de->d_name[0] =='.')3038continue;3039if(ends_with(de->d_name,".lock"))3040continue;3041strbuf_addstr(name, de->d_name);3042if(stat(git_path("logs/%s", name->buf), &st) <0) {3043;/* silently ignore */3044}else{3045if(S_ISDIR(st.st_mode)) {3046strbuf_addch(name,'/');3047 retval =do_for_each_reflog(name, fn, cb_data);3048}else{3049struct object_id oid;30503051if(read_ref_full(name->buf,0, oid.hash, NULL))3052 retval =error("bad ref for%s", name->buf);3053else3054 retval =fn(name->buf, &oid,0, cb_data);3055}3056if(retval)3057break;3058}3059strbuf_setlen(name, oldlen);3060}3061closedir(d);3062return retval;3063}30643065intfor_each_reflog(each_ref_fn fn,void*cb_data)3066{3067int retval;3068struct strbuf name;3069strbuf_init(&name, PATH_MAX);3070 retval =do_for_each_reflog(&name, fn, cb_data);3071strbuf_release(&name);3072return retval;3073}30743075static intref_update_reject_duplicates(struct string_list *refnames,3076struct strbuf *err)3077{3078int i, n = refnames->nr;30793080assert(err);30813082for(i =1; i < n; i++)3083if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3084strbuf_addf(err,3085"Multiple updates for ref '%s' not allowed.",3086 refnames->items[i].string);3087return1;3088}3089return0;3090}30913092intref_transaction_commit(struct ref_transaction *transaction,3093struct strbuf *err)3094{3095int ret =0, i;3096int n = transaction->nr;3097struct ref_update **updates = transaction->updates;3098struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3099struct string_list_item *ref_to_delete;3100struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31013102assert(err);31033104if(transaction->state != REF_TRANSACTION_OPEN)3105die("BUG: commit called for transaction that is not open");31063107if(!n) {3108 transaction->state = REF_TRANSACTION_CLOSED;3109return0;3110}31113112/* Fail if a refname appears more than once in the transaction: */3113for(i =0; i < n; i++)3114string_list_append(&affected_refnames, updates[i]->refname);3115string_list_sort(&affected_refnames);3116if(ref_update_reject_duplicates(&affected_refnames, err)) {3117 ret = TRANSACTION_GENERIC_ERROR;3118goto cleanup;3119}31203121/*3122 * Acquire all locks, verify old values if provided, check3123 * that new values are valid, and write new values to the3124 * lockfiles, ready to be activated. Only keep one lockfile3125 * open at a time to avoid running out of file descriptors.3126 */3127for(i =0; i < n; i++) {3128struct ref_update *update = updates[i];31293130if((update->flags & REF_HAVE_NEW) &&3131is_null_sha1(update->new_sha1))3132 update->flags |= REF_DELETING;3133 update->lock =lock_ref_sha1_basic(3134 update->refname,3135((update->flags & REF_HAVE_OLD) ?3136 update->old_sha1 : NULL),3137&affected_refnames, NULL,3138 update->flags,3139&update->type,3140 err);3141if(!update->lock) {3142char*reason;31433144 ret = (errno == ENOTDIR)3145? TRANSACTION_NAME_CONFLICT3146: TRANSACTION_GENERIC_ERROR;3147 reason =strbuf_detach(err, NULL);3148strbuf_addf(err,"cannot lock ref '%s':%s",3149 update->refname, reason);3150free(reason);3151goto cleanup;3152}3153if((update->flags & REF_HAVE_NEW) &&3154!(update->flags & REF_DELETING)) {3155int overwriting_symref = ((update->type & REF_ISSYMREF) &&3156(update->flags & REF_NODEREF));31573158if(!overwriting_symref &&3159!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3160/*3161 * The reference already has the desired3162 * value, so we don't need to write it.3163 */3164}else if(write_ref_to_lockfile(update->lock,3165 update->new_sha1,3166 err)) {3167char*write_err =strbuf_detach(err, NULL);31683169/*3170 * The lock was freed upon failure of3171 * write_ref_to_lockfile():3172 */3173 update->lock = NULL;3174strbuf_addf(err,3175"cannot update the ref '%s':%s",3176 update->refname, write_err);3177free(write_err);3178 ret = TRANSACTION_GENERIC_ERROR;3179goto cleanup;3180}else{3181 update->flags |= REF_NEEDS_COMMIT;3182}3183}3184if(!(update->flags & REF_NEEDS_COMMIT)) {3185/*3186 * We didn't have to write anything to the lockfile.3187 * Close it to free up the file descriptor:3188 */3189if(close_ref(update->lock)) {3190strbuf_addf(err,"Couldn't close%s.lock",3191 update->refname);3192goto cleanup;3193}3194}3195}31963197/* Perform updates first so live commits remain referenced */3198for(i =0; i < n; i++) {3199struct ref_update *update = updates[i];32003201if(update->flags & REF_NEEDS_COMMIT) {3202if(commit_ref_update(update->lock,3203 update->new_sha1, update->msg,3204 update->flags, err)) {3205/* freed by commit_ref_update(): */3206 update->lock = NULL;3207 ret = TRANSACTION_GENERIC_ERROR;3208goto cleanup;3209}else{3210/* freed by commit_ref_update(): */3211 update->lock = NULL;3212}3213}3214}32153216/* Perform deletes now that updates are safely completed */3217for(i =0; i < n; i++) {3218struct ref_update *update = updates[i];32193220if(update->flags & REF_DELETING) {3221if(delete_ref_loose(update->lock, update->type, err)) {3222 ret = TRANSACTION_GENERIC_ERROR;3223goto cleanup;3224}32253226if(!(update->flags & REF_ISPRUNING))3227string_list_append(&refs_to_delete,3228 update->lock->ref_name);3229}3230}32313232if(repack_without_refs(&refs_to_delete, err)) {3233 ret = TRANSACTION_GENERIC_ERROR;3234goto cleanup;3235}3236for_each_string_list_item(ref_to_delete, &refs_to_delete)3237unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3238clear_loose_ref_cache(&ref_cache);32393240cleanup:3241 transaction->state = REF_TRANSACTION_CLOSED;32423243for(i =0; i < n; i++)3244if(updates[i]->lock)3245unlock_ref(updates[i]->lock);3246string_list_clear(&refs_to_delete,0);3247string_list_clear(&affected_refnames,0);3248return ret;3249}32503251static intref_present(const char*refname,3252const struct object_id *oid,int flags,void*cb_data)3253{3254struct string_list *affected_refnames = cb_data;32553256returnstring_list_has_string(affected_refnames, refname);3257}32583259intinitial_ref_transaction_commit(struct ref_transaction *transaction,3260struct strbuf *err)3261{3262int ret =0, i;3263int n = transaction->nr;3264struct ref_update **updates = transaction->updates;3265struct string_list affected_refnames = STRING_LIST_INIT_NODUP;32663267assert(err);32683269if(transaction->state != REF_TRANSACTION_OPEN)3270die("BUG: commit called for transaction that is not open");32713272/* Fail if a refname appears more than once in the transaction: */3273for(i =0; i < n; i++)3274string_list_append(&affected_refnames, updates[i]->refname);3275string_list_sort(&affected_refnames);3276if(ref_update_reject_duplicates(&affected_refnames, err)) {3277 ret = TRANSACTION_GENERIC_ERROR;3278goto cleanup;3279}32803281/*3282 * It's really undefined to call this function in an active3283 * repository or when there are existing references: we are3284 * only locking and changing packed-refs, so (1) any3285 * simultaneous processes might try to change a reference at3286 * the same time we do, and (2) any existing loose versions of3287 * the references that we are setting would have precedence3288 * over our values. But some remote helpers create the remote3289 * "HEAD" and "master" branches before calling this function,3290 * so here we really only check that none of the references3291 * that we are creating already exists.3292 */3293if(for_each_rawref(ref_present, &affected_refnames))3294die("BUG: initial ref transaction called with existing refs");32953296for(i =0; i < n; i++) {3297struct ref_update *update = updates[i];32983299if((update->flags & REF_HAVE_OLD) &&3300!is_null_sha1(update->old_sha1))3301die("BUG: initial ref transaction with old_sha1 set");3302if(verify_refname_available(update->refname,3303&affected_refnames, NULL,3304 err)) {3305 ret = TRANSACTION_NAME_CONFLICT;3306goto cleanup;3307}3308}33093310if(lock_packed_refs(0)) {3311strbuf_addf(err,"unable to lock packed-refs file:%s",3312strerror(errno));3313 ret = TRANSACTION_GENERIC_ERROR;3314goto cleanup;3315}33163317for(i =0; i < n; i++) {3318struct ref_update *update = updates[i];33193320if((update->flags & REF_HAVE_NEW) &&3321!is_null_sha1(update->new_sha1))3322add_packed_ref(update->refname, update->new_sha1);3323}33243325if(commit_packed_refs()) {3326strbuf_addf(err,"unable to commit packed-refs file:%s",3327strerror(errno));3328 ret = TRANSACTION_GENERIC_ERROR;3329goto cleanup;3330}33313332cleanup:3333 transaction->state = REF_TRANSACTION_CLOSED;3334string_list_clear(&affected_refnames,0);3335return ret;3336}33373338struct expire_reflog_cb {3339unsigned int flags;3340 reflog_expiry_should_prune_fn *should_prune_fn;3341void*policy_cb;3342FILE*newlog;3343unsigned char last_kept_sha1[20];3344};33453346static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3347const char*email,unsigned long timestamp,int tz,3348const char*message,void*cb_data)3349{3350struct expire_reflog_cb *cb = cb_data;3351struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;33523353if(cb->flags & EXPIRE_REFLOGS_REWRITE)3354 osha1 = cb->last_kept_sha1;33553356if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3357 message, policy_cb)) {3358if(!cb->newlog)3359printf("would prune%s", message);3360else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3361printf("prune%s", message);3362}else{3363if(cb->newlog) {3364fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3365sha1_to_hex(osha1),sha1_to_hex(nsha1),3366 email, timestamp, tz, message);3367hashcpy(cb->last_kept_sha1, nsha1);3368}3369if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3370printf("keep%s", message);3371}3372return0;3373}33743375intreflog_expire(const char*refname,const unsigned char*sha1,3376unsigned int flags,3377 reflog_expiry_prepare_fn prepare_fn,3378 reflog_expiry_should_prune_fn should_prune_fn,3379 reflog_expiry_cleanup_fn cleanup_fn,3380void*policy_cb_data)3381{3382static struct lock_file reflog_lock;3383struct expire_reflog_cb cb;3384struct ref_lock *lock;3385char*log_file;3386int status =0;3387int type;3388struct strbuf err = STRBUF_INIT;33893390memset(&cb,0,sizeof(cb));3391 cb.flags = flags;3392 cb.policy_cb = policy_cb_data;3393 cb.should_prune_fn = should_prune_fn;33943395/*3396 * The reflog file is locked by holding the lock on the3397 * reference itself, plus we might need to update the3398 * reference if --updateref was specified:3399 */3400 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);3401if(!lock) {3402error("cannot lock ref '%s':%s", refname, err.buf);3403strbuf_release(&err);3404return-1;3405}3406if(!reflog_exists(refname)) {3407unlock_ref(lock);3408return0;3409}34103411 log_file =git_pathdup("logs/%s", refname);3412if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3413/*3414 * Even though holding $GIT_DIR/logs/$reflog.lock has3415 * no locking implications, we use the lock_file3416 * machinery here anyway because it does a lot of the3417 * work we need, including cleaning up if the program3418 * exits unexpectedly.3419 */3420if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3421struct strbuf err = STRBUF_INIT;3422unable_to_lock_message(log_file, errno, &err);3423error("%s", err.buf);3424strbuf_release(&err);3425goto failure;3426}3427 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3428if(!cb.newlog) {3429error("cannot fdopen%s(%s)",3430get_lock_file_path(&reflog_lock),strerror(errno));3431goto failure;3432}3433}34343435(*prepare_fn)(refname, sha1, cb.policy_cb);3436for_each_reflog_ent(refname, expire_reflog_ent, &cb);3437(*cleanup_fn)(cb.policy_cb);34383439if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3440/*3441 * It doesn't make sense to adjust a reference pointed3442 * to by a symbolic ref based on expiring entries in3443 * the symbolic reference's reflog. Nor can we update3444 * a reference if there are no remaining reflog3445 * entries.3446 */3447int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3448!(type & REF_ISSYMREF) &&3449!is_null_sha1(cb.last_kept_sha1);34503451if(close_lock_file(&reflog_lock)) {3452 status |=error("couldn't write%s:%s", log_file,3453strerror(errno));3454}else if(update &&3455(write_in_full(get_lock_file_fd(lock->lk),3456sha1_to_hex(cb.last_kept_sha1),40) !=40||3457write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3458close_ref(lock) <0)) {3459 status |=error("couldn't write%s",3460get_lock_file_path(lock->lk));3461rollback_lock_file(&reflog_lock);3462}else if(commit_lock_file(&reflog_lock)) {3463 status |=error("unable to write reflog '%s' (%s)",3464 log_file,strerror(errno));3465}else if(update &&commit_ref(lock)) {3466 status |=error("couldn't set%s", lock->ref_name);3467}3468}3469free(log_file);3470unlock_ref(lock);3471return status;34723473 failure:3474rollback_lock_file(&reflog_lock);3475free(log_file);3476unlock_ref(lock);3477return-1;3478}