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#define MAXREFLEN (1024)12731274/*1275 * Called by resolve_gitlink_ref_recursive() after it failed to read1276 * from the loose refs in ref_cache refs. Find <refname> in the1277 * packed-refs file for the submodule.1278 */1279static intresolve_gitlink_packed_ref(struct ref_cache *refs,1280const char*refname,unsigned char*sha1)1281{1282struct ref_entry *ref;1283struct ref_dir *dir =get_packed_refs(refs);12841285 ref =find_ref(dir, refname);1286if(ref == NULL)1287return-1;12881289hashcpy(sha1, ref->u.value.oid.hash);1290return0;1291}12921293static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1294const char*refname,unsigned char*sha1,1295int recursion)1296{1297int fd, len;1298char buffer[128], *p;1299char*path;13001301if(recursion > SYMREF_MAXDEPTH ||strlen(refname) > MAXREFLEN)1302return-1;1303 path = *refs->name1304?git_pathdup_submodule(refs->name,"%s", refname)1305:git_pathdup("%s", refname);1306 fd =open(path, O_RDONLY);1307free(path);1308if(fd <0)1309returnresolve_gitlink_packed_ref(refs, refname, sha1);13101311 len =read(fd, buffer,sizeof(buffer)-1);1312close(fd);1313if(len <0)1314return-1;1315while(len &&isspace(buffer[len-1]))1316 len--;1317 buffer[len] =0;13181319/* Was it a detached head or an old-fashioned symlink? */1320if(!get_sha1_hex(buffer, sha1))1321return0;13221323/* Symref? */1324if(strncmp(buffer,"ref:",4))1325return-1;1326 p = buffer +4;1327while(isspace(*p))1328 p++;13291330returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1331}13321333intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1334{1335int len =strlen(path), retval;1336struct strbuf submodule = STRBUF_INIT;1337struct ref_cache *refs;13381339while(len && path[len-1] =='/')1340 len--;1341if(!len)1342return-1;13431344strbuf_add(&submodule, path, len);1345 refs =lookup_ref_cache(submodule.buf);1346if(!refs) {1347if(!is_nonbare_repository_dir(&submodule)) {1348strbuf_release(&submodule);1349return-1;1350}1351 refs =create_ref_cache(submodule.buf);1352}1353strbuf_release(&submodule);13541355 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1356return retval;1357}13581359/*1360 * Return the ref_entry for the given refname from the packed1361 * references. If it does not exist, return NULL.1362 */1363static struct ref_entry *get_packed_ref(const char*refname)1364{1365returnfind_ref(get_packed_refs(&ref_cache), refname);1366}13671368/*1369 * A loose ref file doesn't exist; check for a packed ref.1370 */1371static intresolve_missing_loose_ref(const char*refname,1372unsigned char*sha1,1373unsigned int*flags)1374{1375struct ref_entry *entry;13761377/*1378 * The loose reference file does not exist; check for a packed1379 * reference.1380 */1381 entry =get_packed_ref(refname);1382if(entry) {1383hashcpy(sha1, entry->u.value.oid.hash);1384*flags |= REF_ISPACKED;1385return0;1386}1387/* refname is not a packed reference. */1388return-1;1389}13901391intread_raw_ref(const char*refname,unsigned char*sha1,1392struct strbuf *referent,unsigned int*type)1393{1394struct strbuf sb_contents = STRBUF_INIT;1395struct strbuf sb_path = STRBUF_INIT;1396const char*path;1397const char*buf;1398struct stat st;1399int fd;1400int ret = -1;1401int save_errno;14021403*type =0;1404strbuf_reset(&sb_path);1405strbuf_git_path(&sb_path,"%s", refname);1406 path = sb_path.buf;14071408stat_ref:1409/*1410 * We might have to loop back here to avoid a race1411 * condition: first we lstat() the file, then we try1412 * to read it as a link or as a file. But if somebody1413 * changes the type of the file (file <-> directory1414 * <-> symlink) between the lstat() and reading, then1415 * we don't want to report that as an error but rather1416 * try again starting with the lstat().1417 */14181419if(lstat(path, &st) <0) {1420if(errno != ENOENT)1421goto out;1422if(resolve_missing_loose_ref(refname, sha1, type)) {1423 errno = ENOENT;1424goto out;1425}1426 ret =0;1427goto out;1428}14291430/* Follow "normalized" - ie "refs/.." symlinks by hand */1431if(S_ISLNK(st.st_mode)) {1432strbuf_reset(&sb_contents);1433if(strbuf_readlink(&sb_contents, path,0) <0) {1434if(errno == ENOENT || errno == EINVAL)1435/* inconsistent with lstat; retry */1436goto stat_ref;1437else1438goto out;1439}1440if(starts_with(sb_contents.buf,"refs/") &&1441!check_refname_format(sb_contents.buf,0)) {1442strbuf_swap(&sb_contents, referent);1443*type |= REF_ISSYMREF;1444 ret =0;1445goto out;1446}1447}14481449/* Is it a directory? */1450if(S_ISDIR(st.st_mode)) {1451/*1452 * Even though there is a directory where the loose1453 * ref is supposed to be, there could still be a1454 * packed ref:1455 */1456if(resolve_missing_loose_ref(refname, sha1, type)) {1457 errno = EISDIR;1458goto out;1459}1460 ret =0;1461goto out;1462}14631464/*1465 * Anything else, just open it and try to use it as1466 * a ref1467 */1468 fd =open(path, O_RDONLY);1469if(fd <0) {1470if(errno == ENOENT)1471/* inconsistent with lstat; retry */1472goto stat_ref;1473else1474goto out;1475}1476strbuf_reset(&sb_contents);1477if(strbuf_read(&sb_contents, fd,256) <0) {1478int save_errno = errno;1479close(fd);1480 errno = save_errno;1481goto out;1482}1483close(fd);1484strbuf_rtrim(&sb_contents);1485 buf = sb_contents.buf;1486if(starts_with(buf,"ref:")) {1487 buf +=4;1488while(isspace(*buf))1489 buf++;14901491strbuf_reset(referent);1492strbuf_addstr(referent, buf);1493*type |= REF_ISSYMREF;1494 ret =0;1495goto out;1496}14971498/*1499 * Please note that FETCH_HEAD has additional1500 * data after the sha.1501 */1502if(get_sha1_hex(buf, sha1) ||1503(buf[40] !='\0'&& !isspace(buf[40]))) {1504*type |= REF_ISBROKEN;1505 errno = EINVAL;1506goto out;1507}15081509 ret =0;15101511out:1512 save_errno = errno;1513strbuf_release(&sb_path);1514strbuf_release(&sb_contents);1515 errno = save_errno;1516return ret;1517}15181519/*1520 * Peel the entry (if possible) and return its new peel_status. If1521 * repeel is true, re-peel the entry even if there is an old peeled1522 * value that is already stored in it.1523 *1524 * It is OK to call this function with a packed reference entry that1525 * might be stale and might even refer to an object that has since1526 * been garbage-collected. In such a case, if the entry has1527 * REF_KNOWS_PEELED then leave the status unchanged and return1528 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1529 */1530static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1531{1532enum peel_status status;15331534if(entry->flag & REF_KNOWS_PEELED) {1535if(repeel) {1536 entry->flag &= ~REF_KNOWS_PEELED;1537oidclr(&entry->u.value.peeled);1538}else{1539returnis_null_oid(&entry->u.value.peeled) ?1540 PEEL_NON_TAG : PEEL_PEELED;1541}1542}1543if(entry->flag & REF_ISBROKEN)1544return PEEL_BROKEN;1545if(entry->flag & REF_ISSYMREF)1546return PEEL_IS_SYMREF;15471548 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1549if(status == PEEL_PEELED || status == PEEL_NON_TAG)1550 entry->flag |= REF_KNOWS_PEELED;1551return status;1552}15531554intpeel_ref(const char*refname,unsigned char*sha1)1555{1556int flag;1557unsigned char base[20];15581559if(current_ref && (current_ref->name == refname1560|| !strcmp(current_ref->name, refname))) {1561if(peel_entry(current_ref,0))1562return-1;1563hashcpy(sha1, current_ref->u.value.peeled.hash);1564return0;1565}15661567if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1568return-1;15691570/*1571 * If the reference is packed, read its ref_entry from the1572 * cache in the hope that we already know its peeled value.1573 * We only try this optimization on packed references because1574 * (a) forcing the filling of the loose reference cache could1575 * be expensive and (b) loose references anyway usually do not1576 * have REF_KNOWS_PEELED.1577 */1578if(flag & REF_ISPACKED) {1579struct ref_entry *r =get_packed_ref(refname);1580if(r) {1581if(peel_entry(r,0))1582return-1;1583hashcpy(sha1, r->u.value.peeled.hash);1584return0;1585}1586}15871588returnpeel_object(base, sha1);1589}15901591/*1592 * Call fn for each reference in the specified ref_cache, omitting1593 * references not in the containing_dir of base. fn is called for all1594 * references, including broken ones. If fn ever returns a non-zero1595 * value, stop the iteration and return that value; otherwise, return1596 * 0.1597 */1598static intdo_for_each_entry(struct ref_cache *refs,const char*base,1599 each_ref_entry_fn fn,void*cb_data)1600{1601struct packed_ref_cache *packed_ref_cache;1602struct ref_dir *loose_dir;1603struct ref_dir *packed_dir;1604int retval =0;16051606/*1607 * We must make sure that all loose refs are read before accessing the1608 * packed-refs file; this avoids a race condition in which loose refs1609 * are migrated to the packed-refs file by a simultaneous process, but1610 * our in-memory view is from before the migration. get_packed_ref_cache()1611 * takes care of making sure our view is up to date with what is on1612 * disk.1613 */1614 loose_dir =get_loose_refs(refs);1615if(base && *base) {1616 loose_dir =find_containing_dir(loose_dir, base,0);1617}1618if(loose_dir)1619prime_ref_dir(loose_dir);16201621 packed_ref_cache =get_packed_ref_cache(refs);1622acquire_packed_ref_cache(packed_ref_cache);1623 packed_dir =get_packed_ref_dir(packed_ref_cache);1624if(base && *base) {1625 packed_dir =find_containing_dir(packed_dir, base,0);1626}16271628if(packed_dir && loose_dir) {1629sort_ref_dir(packed_dir);1630sort_ref_dir(loose_dir);1631 retval =do_for_each_entry_in_dirs(1632 packed_dir, loose_dir, fn, cb_data);1633}else if(packed_dir) {1634sort_ref_dir(packed_dir);1635 retval =do_for_each_entry_in_dir(1636 packed_dir,0, fn, cb_data);1637}else if(loose_dir) {1638sort_ref_dir(loose_dir);1639 retval =do_for_each_entry_in_dir(1640 loose_dir,0, fn, cb_data);1641}16421643release_packed_ref_cache(packed_ref_cache);1644return retval;1645}16461647/*1648 * Call fn for each reference in the specified ref_cache for which the1649 * refname begins with base. If trim is non-zero, then trim that many1650 * characters off the beginning of each refname before passing the1651 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1652 * broken references in the iteration. If fn ever returns a non-zero1653 * value, stop the iteration and return that value; otherwise, return1654 * 0.1655 */1656intdo_for_each_ref(const char*submodule,const char*base,1657 each_ref_fn fn,int trim,int flags,void*cb_data)1658{1659struct ref_entry_cb data;1660struct ref_cache *refs;16611662 refs =get_ref_cache(submodule);1663 data.base = base;1664 data.trim = trim;1665 data.flags = flags;1666 data.fn = fn;1667 data.cb_data = cb_data;16681669if(ref_paranoia <0)1670 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1671if(ref_paranoia)1672 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;16731674returndo_for_each_entry(refs, base, do_one_ref, &data);1675}16761677static voidunlock_ref(struct ref_lock *lock)1678{1679/* Do not free lock->lk -- atexit() still looks at them */1680if(lock->lk)1681rollback_lock_file(lock->lk);1682free(lock->ref_name);1683free(lock->orig_ref_name);1684free(lock);1685}16861687/*1688 * Verify that the reference locked by lock has the value old_sha1.1689 * Fail if the reference doesn't exist and mustexist is set. Return 01690 * on success. On error, write an error message to err, set errno, and1691 * return a negative value.1692 */1693static intverify_lock(struct ref_lock *lock,1694const unsigned char*old_sha1,int mustexist,1695struct strbuf *err)1696{1697assert(err);16981699if(read_ref_full(lock->ref_name,1700 mustexist ? RESOLVE_REF_READING :0,1701 lock->old_oid.hash, NULL)) {1702if(old_sha1) {1703int save_errno = errno;1704strbuf_addf(err,"can't verify ref%s", lock->ref_name);1705 errno = save_errno;1706return-1;1707}else{1708hashclr(lock->old_oid.hash);1709return0;1710}1711}1712if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1713strbuf_addf(err,"ref%sis at%sbut expected%s",1714 lock->ref_name,1715sha1_to_hex(lock->old_oid.hash),1716sha1_to_hex(old_sha1));1717 errno = EBUSY;1718return-1;1719}1720return0;1721}17221723static intremove_empty_directories(struct strbuf *path)1724{1725/*1726 * we want to create a file but there is a directory there;1727 * if that is an empty directory (or a directory that contains1728 * only empty directories), remove them.1729 */1730returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1731}17321733/*1734 * Locks a ref returning the lock on success and NULL on failure.1735 * On failure errno is set to something meaningful.1736 */1737static struct ref_lock *lock_ref_sha1_basic(const char*refname,1738const unsigned char*old_sha1,1739const struct string_list *extras,1740const struct string_list *skip,1741unsigned int flags,int*type_p,1742struct strbuf *err)1743{1744struct strbuf ref_file = STRBUF_INIT;1745struct strbuf orig_ref_file = STRBUF_INIT;1746const char*orig_refname = refname;1747struct ref_lock *lock;1748int last_errno =0;1749int type;1750int lflags =0;1751int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1752int resolve_flags =0;1753int attempts_remaining =3;17541755assert(err);17561757 lock =xcalloc(1,sizeof(struct ref_lock));17581759if(mustexist)1760 resolve_flags |= RESOLVE_REF_READING;1761if(flags & REF_DELETING)1762 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1763if(flags & REF_NODEREF) {1764 resolve_flags |= RESOLVE_REF_NO_RECURSE;1765 lflags |= LOCK_NO_DEREF;1766}17671768 refname =resolve_ref_unsafe(refname, resolve_flags,1769 lock->old_oid.hash, &type);1770if(!refname && errno == EISDIR) {1771/*1772 * we are trying to lock foo but we used to1773 * have foo/bar which now does not exist;1774 * it is normal for the empty directory 'foo'1775 * to remain.1776 */1777strbuf_git_path(&orig_ref_file,"%s", orig_refname);1778if(remove_empty_directories(&orig_ref_file)) {1779 last_errno = errno;1780if(!verify_refname_available_dir(orig_refname, extras, skip,1781get_loose_refs(&ref_cache), err))1782strbuf_addf(err,"there are still refs under '%s'",1783 orig_refname);1784goto error_return;1785}1786 refname =resolve_ref_unsafe(orig_refname, resolve_flags,1787 lock->old_oid.hash, &type);1788}1789if(type_p)1790*type_p = type;1791if(!refname) {1792 last_errno = errno;1793if(last_errno != ENOTDIR ||1794!verify_refname_available_dir(orig_refname, extras, skip,1795get_loose_refs(&ref_cache), err))1796strbuf_addf(err,"unable to resolve reference%s:%s",1797 orig_refname,strerror(last_errno));17981799goto error_return;1800}18011802if(flags & REF_NODEREF)1803 refname = orig_refname;18041805/*1806 * If the ref did not exist and we are creating it, make sure1807 * there is no existing packed ref whose name begins with our1808 * refname, nor a packed ref whose name is a proper prefix of1809 * our refname.1810 */1811if(is_null_oid(&lock->old_oid) &&1812verify_refname_available_dir(refname, extras, skip,1813get_packed_refs(&ref_cache), err)) {1814 last_errno = ENOTDIR;1815goto error_return;1816}18171818 lock->lk =xcalloc(1,sizeof(struct lock_file));18191820 lock->ref_name =xstrdup(refname);1821 lock->orig_ref_name =xstrdup(orig_refname);1822strbuf_git_path(&ref_file,"%s", refname);18231824 retry:1825switch(safe_create_leading_directories_const(ref_file.buf)) {1826case SCLD_OK:1827break;/* success */1828case SCLD_VANISHED:1829if(--attempts_remaining >0)1830goto retry;1831/* fall through */1832default:1833 last_errno = errno;1834strbuf_addf(err,"unable to create directory for%s",1835 ref_file.buf);1836goto error_return;1837}18381839if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {1840 last_errno = errno;1841if(errno == ENOENT && --attempts_remaining >0)1842/*1843 * Maybe somebody just deleted one of the1844 * directories leading to ref_file. Try1845 * again:1846 */1847goto retry;1848else{1849unable_to_lock_message(ref_file.buf, errno, err);1850goto error_return;1851}1852}1853if(verify_lock(lock, old_sha1, mustexist, err)) {1854 last_errno = errno;1855goto error_return;1856}1857goto out;18581859 error_return:1860unlock_ref(lock);1861 lock = NULL;18621863 out:1864strbuf_release(&ref_file);1865strbuf_release(&orig_ref_file);1866 errno = last_errno;1867return lock;1868}18691870/*1871 * Write an entry to the packed-refs file for the specified refname.1872 * If peeled is non-NULL, write it as the entry's peeled value.1873 */1874static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,1875unsigned char*peeled)1876{1877fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1878if(peeled)1879fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1880}18811882/*1883 * An each_ref_entry_fn that writes the entry to a packed-refs file.1884 */1885static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)1886{1887enum peel_status peel_status =peel_entry(entry,0);18881889if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1890error("internal error:%sis not a valid packed reference!",1891 entry->name);1892write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,1893 peel_status == PEEL_PEELED ?1894 entry->u.value.peeled.hash : NULL);1895return0;1896}18971898/*1899 * Lock the packed-refs file for writing. Flags is passed to1900 * hold_lock_file_for_update(). Return 0 on success. On errors, set1901 * errno appropriately and return a nonzero value.1902 */1903static intlock_packed_refs(int flags)1904{1905static int timeout_configured =0;1906static int timeout_value =1000;19071908struct packed_ref_cache *packed_ref_cache;19091910if(!timeout_configured) {1911git_config_get_int("core.packedrefstimeout", &timeout_value);1912 timeout_configured =1;1913}19141915if(hold_lock_file_for_update_timeout(1916&packlock,git_path("packed-refs"),1917 flags, timeout_value) <0)1918return-1;1919/*1920 * Get the current packed-refs while holding the lock. If the1921 * packed-refs file has been modified since we last read it,1922 * this will automatically invalidate the cache and re-read1923 * the packed-refs file.1924 */1925 packed_ref_cache =get_packed_ref_cache(&ref_cache);1926 packed_ref_cache->lock = &packlock;1927/* Increment the reference count to prevent it from being freed: */1928acquire_packed_ref_cache(packed_ref_cache);1929return0;1930}19311932/*1933 * Write the current version of the packed refs cache from memory to1934 * disk. The packed-refs file must already be locked for writing (see1935 * lock_packed_refs()). Return zero on success. On errors, set errno1936 * and return a nonzero value1937 */1938static intcommit_packed_refs(void)1939{1940struct packed_ref_cache *packed_ref_cache =1941get_packed_ref_cache(&ref_cache);1942int error =0;1943int save_errno =0;1944FILE*out;19451946if(!packed_ref_cache->lock)1947die("internal error: packed-refs not locked");19481949 out =fdopen_lock_file(packed_ref_cache->lock,"w");1950if(!out)1951die_errno("unable to fdopen packed-refs descriptor");19521953fprintf_or_die(out,"%s", PACKED_REFS_HEADER);1954do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),19550, write_packed_entry_fn, out);19561957if(commit_lock_file(packed_ref_cache->lock)) {1958 save_errno = errno;1959 error = -1;1960}1961 packed_ref_cache->lock = NULL;1962release_packed_ref_cache(packed_ref_cache);1963 errno = save_errno;1964return error;1965}19661967/*1968 * Rollback the lockfile for the packed-refs file, and discard the1969 * in-memory packed reference cache. (The packed-refs file will be1970 * read anew if it is needed again after this function is called.)1971 */1972static voidrollback_packed_refs(void)1973{1974struct packed_ref_cache *packed_ref_cache =1975get_packed_ref_cache(&ref_cache);19761977if(!packed_ref_cache->lock)1978die("internal error: packed-refs not locked");1979rollback_lock_file(packed_ref_cache->lock);1980 packed_ref_cache->lock = NULL;1981release_packed_ref_cache(packed_ref_cache);1982clear_packed_ref_cache(&ref_cache);1983}19841985struct ref_to_prune {1986struct ref_to_prune *next;1987unsigned char sha1[20];1988char name[FLEX_ARRAY];1989};19901991struct pack_refs_cb_data {1992unsigned int flags;1993struct ref_dir *packed_refs;1994struct ref_to_prune *ref_to_prune;1995};19961997/*1998 * An each_ref_entry_fn that is run over loose references only. If1999 * the loose reference can be packed, add an entry in the packed ref2000 * cache. If the reference should be pruned, also add it to2001 * ref_to_prune in the pack_refs_cb_data.2002 */2003static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2004{2005struct pack_refs_cb_data *cb = cb_data;2006enum peel_status peel_status;2007struct ref_entry *packed_entry;2008int is_tag_ref =starts_with(entry->name,"refs/tags/");20092010/* Do not pack per-worktree refs: */2011if(ref_type(entry->name) != REF_TYPE_NORMAL)2012return0;20132014/* ALWAYS pack tags */2015if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2016return0;20172018/* Do not pack symbolic or broken refs: */2019if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2020return0;20212022/* Add a packed ref cache entry equivalent to the loose entry. */2023 peel_status =peel_entry(entry,1);2024if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2025die("internal error peeling reference%s(%s)",2026 entry->name,oid_to_hex(&entry->u.value.oid));2027 packed_entry =find_ref(cb->packed_refs, entry->name);2028if(packed_entry) {2029/* Overwrite existing packed entry with info from loose entry */2030 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2031oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2032}else{2033 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2034 REF_ISPACKED | REF_KNOWS_PEELED,0);2035add_ref(cb->packed_refs, packed_entry);2036}2037oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);20382039/* Schedule the loose reference for pruning if requested. */2040if((cb->flags & PACK_REFS_PRUNE)) {2041struct ref_to_prune *n;2042FLEX_ALLOC_STR(n, name, entry->name);2043hashcpy(n->sha1, entry->u.value.oid.hash);2044 n->next = cb->ref_to_prune;2045 cb->ref_to_prune = n;2046}2047return0;2048}20492050/*2051 * Remove empty parents, but spare refs/ and immediate subdirs.2052 * Note: munges *name.2053 */2054static voidtry_remove_empty_parents(char*name)2055{2056char*p, *q;2057int i;2058 p = name;2059for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2060while(*p && *p !='/')2061 p++;2062/* tolerate duplicate slashes; see check_refname_format() */2063while(*p =='/')2064 p++;2065}2066for(q = p; *q; q++)2067;2068while(1) {2069while(q > p && *q !='/')2070 q--;2071while(q > p && *(q-1) =='/')2072 q--;2073if(q == p)2074break;2075*q ='\0';2076if(rmdir(git_path("%s", name)))2077break;2078}2079}20802081/* make sure nobody touched the ref, and unlink */2082static voidprune_ref(struct ref_to_prune *r)2083{2084struct ref_transaction *transaction;2085struct strbuf err = STRBUF_INIT;20862087if(check_refname_format(r->name,0))2088return;20892090 transaction =ref_transaction_begin(&err);2091if(!transaction ||2092ref_transaction_delete(transaction, r->name, r->sha1,2093 REF_ISPRUNING, NULL, &err) ||2094ref_transaction_commit(transaction, &err)) {2095ref_transaction_free(transaction);2096error("%s", err.buf);2097strbuf_release(&err);2098return;2099}2100ref_transaction_free(transaction);2101strbuf_release(&err);2102try_remove_empty_parents(r->name);2103}21042105static voidprune_refs(struct ref_to_prune *r)2106{2107while(r) {2108prune_ref(r);2109 r = r->next;2110}2111}21122113intpack_refs(unsigned int flags)2114{2115struct pack_refs_cb_data cbdata;21162117memset(&cbdata,0,sizeof(cbdata));2118 cbdata.flags = flags;21192120lock_packed_refs(LOCK_DIE_ON_ERROR);2121 cbdata.packed_refs =get_packed_refs(&ref_cache);21222123do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2124 pack_if_possible_fn, &cbdata);21252126if(commit_packed_refs())2127die_errno("unable to overwrite old ref-pack file");21282129prune_refs(cbdata.ref_to_prune);2130return0;2131}21322133/*2134 * Rewrite the packed-refs file, omitting any refs listed in2135 * 'refnames'. On error, leave packed-refs unchanged, write an error2136 * message to 'err', and return a nonzero value.2137 *2138 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2139 */2140static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2141{2142struct ref_dir *packed;2143struct string_list_item *refname;2144int ret, needs_repacking =0, removed =0;21452146assert(err);21472148/* Look for a packed ref */2149for_each_string_list_item(refname, refnames) {2150if(get_packed_ref(refname->string)) {2151 needs_repacking =1;2152break;2153}2154}21552156/* Avoid locking if we have nothing to do */2157if(!needs_repacking)2158return0;/* no refname exists in packed refs */21592160if(lock_packed_refs(0)) {2161unable_to_lock_message(git_path("packed-refs"), errno, err);2162return-1;2163}2164 packed =get_packed_refs(&ref_cache);21652166/* Remove refnames from the cache */2167for_each_string_list_item(refname, refnames)2168if(remove_entry(packed, refname->string) != -1)2169 removed =1;2170if(!removed) {2171/*2172 * All packed entries disappeared while we were2173 * acquiring the lock.2174 */2175rollback_packed_refs();2176return0;2177}21782179/* Write what remains */2180 ret =commit_packed_refs();2181if(ret)2182strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2183strerror(errno));2184return ret;2185}21862187static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2188{2189assert(err);21902191if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2192/*2193 * loose. The loose file name is the same as the2194 * lockfile name, minus ".lock":2195 */2196char*loose_filename =get_locked_file_path(lock->lk);2197int res =unlink_or_msg(loose_filename, err);2198free(loose_filename);2199if(res)2200return1;2201}2202return0;2203}22042205intdelete_refs(struct string_list *refnames)2206{2207struct strbuf err = STRBUF_INIT;2208int i, result =0;22092210if(!refnames->nr)2211return0;22122213 result =repack_without_refs(refnames, &err);2214if(result) {2215/*2216 * If we failed to rewrite the packed-refs file, then2217 * it is unsafe to try to remove loose refs, because2218 * doing so might expose an obsolete packed value for2219 * a reference that might even point at an object that2220 * has been garbage collected.2221 */2222if(refnames->nr ==1)2223error(_("could not delete reference%s:%s"),2224 refnames->items[0].string, err.buf);2225else2226error(_("could not delete references:%s"), err.buf);22272228goto out;2229}22302231for(i =0; i < refnames->nr; i++) {2232const char*refname = refnames->items[i].string;22332234if(delete_ref(refname, NULL,0))2235 result |=error(_("could not remove reference%s"), refname);2236}22372238out:2239strbuf_release(&err);2240return result;2241}22422243/*2244 * People using contrib's git-new-workdir have .git/logs/refs ->2245 * /some/other/path/.git/logs/refs, and that may live on another device.2246 *2247 * IOW, to avoid cross device rename errors, the temporary renamed log must2248 * live into logs/refs.2249 */2250#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"22512252static intrename_tmp_log(const char*newrefname)2253{2254int attempts_remaining =4;2255struct strbuf path = STRBUF_INIT;2256int ret = -1;22572258 retry:2259strbuf_reset(&path);2260strbuf_git_path(&path,"logs/%s", newrefname);2261switch(safe_create_leading_directories_const(path.buf)) {2262case SCLD_OK:2263break;/* success */2264case SCLD_VANISHED:2265if(--attempts_remaining >0)2266goto retry;2267/* fall through */2268default:2269error("unable to create directory for%s", newrefname);2270goto out;2271}22722273if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2274if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2275/*2276 * rename(a, b) when b is an existing2277 * directory ought to result in ISDIR, but2278 * Solaris 5.8 gives ENOTDIR. Sheesh.2279 */2280if(remove_empty_directories(&path)) {2281error("Directory not empty: logs/%s", newrefname);2282goto out;2283}2284goto retry;2285}else if(errno == ENOENT && --attempts_remaining >0) {2286/*2287 * Maybe another process just deleted one of2288 * the directories in the path to newrefname.2289 * Try again from the beginning.2290 */2291goto retry;2292}else{2293error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2294 newrefname,strerror(errno));2295goto out;2296}2297}2298 ret =0;2299out:2300strbuf_release(&path);2301return ret;2302}23032304intverify_refname_available(const char*newname,2305struct string_list *extras,2306struct string_list *skip,2307struct strbuf *err)2308{2309struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2310struct ref_dir *loose_refs =get_loose_refs(&ref_cache);23112312if(verify_refname_available_dir(newname, extras, skip,2313 packed_refs, err) ||2314verify_refname_available_dir(newname, extras, skip,2315 loose_refs, err))2316return-1;23172318return0;2319}23202321static intwrite_ref_to_lockfile(struct ref_lock *lock,2322const unsigned char*sha1,struct strbuf *err);2323static intcommit_ref_update(struct ref_lock *lock,2324const unsigned char*sha1,const char*logmsg,2325int flags,struct strbuf *err);23262327intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2328{2329unsigned char sha1[20], orig_sha1[20];2330int flag =0, logmoved =0;2331struct ref_lock *lock;2332struct stat loginfo;2333int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2334struct strbuf err = STRBUF_INIT;23352336if(log &&S_ISLNK(loginfo.st_mode))2337returnerror("reflog for%sis a symlink", oldrefname);23382339if(!resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING, orig_sha1, &flag))2340returnerror("refname%snot found", oldrefname);23412342if(flag & REF_ISSYMREF)2343returnerror("refname%sis a symbolic ref, renaming it is not supported",2344 oldrefname);2345if(!rename_ref_available(oldrefname, newrefname))2346return1;23472348if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2349returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2350 oldrefname,strerror(errno));23512352if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2353error("unable to delete old%s", oldrefname);2354goto rollback;2355}23562357if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2358delete_ref(newrefname, sha1, REF_NODEREF)) {2359if(errno==EISDIR) {2360struct strbuf path = STRBUF_INIT;2361int result;23622363strbuf_git_path(&path,"%s", newrefname);2364 result =remove_empty_directories(&path);2365strbuf_release(&path);23662367if(result) {2368error("Directory not empty:%s", newrefname);2369goto rollback;2370}2371}else{2372error("unable to delete existing%s", newrefname);2373goto rollback;2374}2375}23762377if(log &&rename_tmp_log(newrefname))2378goto rollback;23792380 logmoved = log;23812382 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2383if(!lock) {2384error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2385strbuf_release(&err);2386goto rollback;2387}2388hashcpy(lock->old_oid.hash, orig_sha1);23892390if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2391commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2392error("unable to write current sha1 into%s:%s", newrefname, err.buf);2393strbuf_release(&err);2394goto rollback;2395}23962397return0;23982399 rollback:2400 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2401if(!lock) {2402error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2403strbuf_release(&err);2404goto rollbacklog;2405}24062407 flag = log_all_ref_updates;2408 log_all_ref_updates =0;2409if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2410commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2411error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2412strbuf_release(&err);2413}2414 log_all_ref_updates = flag;24152416 rollbacklog:2417if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2418error("unable to restore logfile%sfrom%s:%s",2419 oldrefname, newrefname,strerror(errno));2420if(!logmoved && log &&2421rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2422error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2423 oldrefname,strerror(errno));24242425return1;2426}24272428static intclose_ref(struct ref_lock *lock)2429{2430if(close_lock_file(lock->lk))2431return-1;2432return0;2433}24342435static intcommit_ref(struct ref_lock *lock)2436{2437char*path =get_locked_file_path(lock->lk);2438struct stat st;24392440if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {2441/*2442 * There is a directory at the path we want to rename2443 * the lockfile to. Hopefully it is empty; try to2444 * delete it.2445 */2446size_t len =strlen(path);2447struct strbuf sb_path = STRBUF_INIT;24482449strbuf_attach(&sb_path, path, len, len);24502451/*2452 * If this fails, commit_lock_file() will also fail2453 * and will report the problem.2454 */2455remove_empty_directories(&sb_path);2456strbuf_release(&sb_path);2457}else{2458free(path);2459}24602461if(commit_lock_file(lock->lk))2462return-1;2463return0;2464}24652466/*2467 * Create a reflog for a ref. If force_create = 0, the reflog will2468 * only be created for certain refs (those for which2469 * should_autocreate_reflog returns non-zero. Otherwise, create it2470 * regardless of the ref name. Fill in *err and return -1 on failure.2471 */2472static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2473{2474int logfd, oflags = O_APPEND | O_WRONLY;24752476strbuf_git_path(logfile,"logs/%s", refname);2477if(force_create ||should_autocreate_reflog(refname)) {2478if(safe_create_leading_directories(logfile->buf) <0) {2479strbuf_addf(err,"unable to create directory for%s: "2480"%s", logfile->buf,strerror(errno));2481return-1;2482}2483 oflags |= O_CREAT;2484}24852486 logfd =open(logfile->buf, oflags,0666);2487if(logfd <0) {2488if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2489return0;24902491if(errno == EISDIR) {2492if(remove_empty_directories(logfile)) {2493strbuf_addf(err,"There are still logs under "2494"'%s'", logfile->buf);2495return-1;2496}2497 logfd =open(logfile->buf, oflags,0666);2498}24992500if(logfd <0) {2501strbuf_addf(err,"unable to append to%s:%s",2502 logfile->buf,strerror(errno));2503return-1;2504}2505}25062507adjust_shared_perm(logfile->buf);2508close(logfd);2509return0;2510}251125122513intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2514{2515int ret;2516struct strbuf sb = STRBUF_INIT;25172518 ret =log_ref_setup(refname, &sb, err, force_create);2519strbuf_release(&sb);2520return ret;2521}25222523static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2524const unsigned char*new_sha1,2525const char*committer,const char*msg)2526{2527int msglen, written;2528unsigned maxlen, len;2529char*logrec;25302531 msglen = msg ?strlen(msg) :0;2532 maxlen =strlen(committer) + msglen +100;2533 logrec =xmalloc(maxlen);2534 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2535sha1_to_hex(old_sha1),2536sha1_to_hex(new_sha1),2537 committer);2538if(msglen)2539 len +=copy_reflog_msg(logrec + len -1, msg) -1;25402541 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2542free(logrec);2543if(written != len)2544return-1;25452546return0;2547}25482549static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2550const unsigned char*new_sha1,const char*msg,2551struct strbuf *logfile,int flags,2552struct strbuf *err)2553{2554int logfd, result, oflags = O_APPEND | O_WRONLY;25552556if(log_all_ref_updates <0)2557 log_all_ref_updates = !is_bare_repository();25582559 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);25602561if(result)2562return result;25632564 logfd =open(logfile->buf, oflags);2565if(logfd <0)2566return0;2567 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2568git_committer_info(0), msg);2569if(result) {2570strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2571strerror(errno));2572close(logfd);2573return-1;2574}2575if(close(logfd)) {2576strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2577strerror(errno));2578return-1;2579}2580return0;2581}25822583static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2584const unsigned char*new_sha1,const char*msg,2585int flags,struct strbuf *err)2586{2587returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2588 err);2589}25902591intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2592const unsigned char*new_sha1,const char*msg,2593int flags,struct strbuf *err)2594{2595struct strbuf sb = STRBUF_INIT;2596int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2597 err);2598strbuf_release(&sb);2599return ret;2600}26012602/*2603 * Write sha1 into the open lockfile, then close the lockfile. On2604 * errors, rollback the lockfile, fill in *err and2605 * return -1.2606 */2607static intwrite_ref_to_lockfile(struct ref_lock *lock,2608const unsigned char*sha1,struct strbuf *err)2609{2610static char term ='\n';2611struct object *o;2612int fd;26132614 o =parse_object(sha1);2615if(!o) {2616strbuf_addf(err,2617"Trying to write ref%swith nonexistent object%s",2618 lock->ref_name,sha1_to_hex(sha1));2619unlock_ref(lock);2620return-1;2621}2622if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2623strbuf_addf(err,2624"Trying to write non-commit object%sto branch%s",2625sha1_to_hex(sha1), lock->ref_name);2626unlock_ref(lock);2627return-1;2628}2629 fd =get_lock_file_fd(lock->lk);2630if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2631write_in_full(fd, &term,1) !=1||2632close_ref(lock) <0) {2633strbuf_addf(err,2634"Couldn't write%s",get_lock_file_path(lock->lk));2635unlock_ref(lock);2636return-1;2637}2638return0;2639}26402641/*2642 * Commit a change to a loose reference that has already been written2643 * to the loose reference lockfile. Also update the reflogs if2644 * necessary, using the specified lockmsg (which can be NULL).2645 */2646static intcommit_ref_update(struct ref_lock *lock,2647const unsigned char*sha1,const char*logmsg,2648int flags,struct strbuf *err)2649{2650clear_loose_ref_cache(&ref_cache);2651if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2652(strcmp(lock->ref_name, lock->orig_ref_name) &&2653log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2654char*old_msg =strbuf_detach(err, NULL);2655strbuf_addf(err,"Cannot update the ref '%s':%s",2656 lock->ref_name, old_msg);2657free(old_msg);2658unlock_ref(lock);2659return-1;2660}2661if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2662/*2663 * Special hack: If a branch is updated directly and HEAD2664 * points to it (may happen on the remote side of a push2665 * for example) then logically the HEAD reflog should be2666 * updated too.2667 * A generic solution implies reverse symref information,2668 * but finding all symrefs pointing to the given branch2669 * would be rather costly for this rare event (the direct2670 * update of a branch) to be worth it. So let's cheat and2671 * check with HEAD only which should cover 99% of all usage2672 * scenarios (even 100% of the default ones).2673 */2674unsigned char head_sha1[20];2675int head_flag;2676const char*head_ref;2677 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2678 head_sha1, &head_flag);2679if(head_ref && (head_flag & REF_ISSYMREF) &&2680!strcmp(head_ref, lock->ref_name)) {2681struct strbuf log_err = STRBUF_INIT;2682if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2683 logmsg,0, &log_err)) {2684error("%s", log_err.buf);2685strbuf_release(&log_err);2686}2687}2688}2689if(commit_ref(lock)) {2690strbuf_addf(err,"Couldn't set%s", lock->ref_name);2691unlock_ref(lock);2692return-1;2693}26942695unlock_ref(lock);2696return0;2697}26982699static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2700{2701int ret = -1;2702#ifndef NO_SYMLINK_HEAD2703char*ref_path =get_locked_file_path(lock->lk);2704unlink(ref_path);2705 ret =symlink(target, ref_path);2706free(ref_path);27072708if(ret)2709fprintf(stderr,"no symlink - falling back to symbolic ref\n");2710#endif2711return ret;2712}27132714static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2715const char*target,const char*logmsg)2716{2717struct strbuf err = STRBUF_INIT;2718unsigned char new_sha1[20];2719if(logmsg && !read_ref(target, new_sha1) &&2720log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2721error("%s", err.buf);2722strbuf_release(&err);2723}2724}27252726static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2727const char*target,const char*logmsg)2728{2729if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2730update_symref_reflog(lock, refname, target, logmsg);2731return0;2732}27332734if(!fdopen_lock_file(lock->lk,"w"))2735returnerror("unable to fdopen%s:%s",2736 lock->lk->tempfile.filename.buf,strerror(errno));27372738update_symref_reflog(lock, refname, target, logmsg);27392740/* no error check; commit_ref will check ferror */2741fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2742if(commit_ref(lock) <0)2743returnerror("unable to write symref for%s:%s", refname,2744strerror(errno));2745return0;2746}27472748intcreate_symref(const char*refname,const char*target,const char*logmsg)2749{2750struct strbuf err = STRBUF_INIT;2751struct ref_lock *lock;2752int ret;27532754 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2755&err);2756if(!lock) {2757error("%s", err.buf);2758strbuf_release(&err);2759return-1;2760}27612762 ret =create_symref_locked(lock, refname, target, logmsg);2763unlock_ref(lock);2764return ret;2765}27662767intset_worktree_head_symref(const char*gitdir,const char*target)2768{2769static struct lock_file head_lock;2770struct ref_lock *lock;2771struct strbuf head_path = STRBUF_INIT;2772const char*head_rel;2773int ret;27742775strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));2776if(hold_lock_file_for_update(&head_lock, head_path.buf,2777 LOCK_NO_DEREF) <0) {2778struct strbuf err = STRBUF_INIT;2779unable_to_lock_message(head_path.buf, errno, &err);2780error("%s", err.buf);2781strbuf_release(&err);2782strbuf_release(&head_path);2783return-1;2784}27852786/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for2787 linked trees */2788 head_rel =remove_leading_path(head_path.buf,2789absolute_path(get_git_common_dir()));2790/* to make use of create_symref_locked(), initialize ref_lock */2791 lock =xcalloc(1,sizeof(struct ref_lock));2792 lock->lk = &head_lock;2793 lock->ref_name =xstrdup(head_rel);2794 lock->orig_ref_name =xstrdup(head_rel);27952796 ret =create_symref_locked(lock, head_rel, target, NULL);27972798unlock_ref(lock);/* will free lock */2799strbuf_release(&head_path);2800return ret;2801}28022803intreflog_exists(const char*refname)2804{2805struct stat st;28062807return!lstat(git_path("logs/%s", refname), &st) &&2808S_ISREG(st.st_mode);2809}28102811intdelete_reflog(const char*refname)2812{2813returnremove_path(git_path("logs/%s", refname));2814}28152816static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2817{2818unsigned char osha1[20], nsha1[20];2819char*email_end, *message;2820unsigned long timestamp;2821int tz;28222823/* old SP new SP name <email> SP time TAB msg LF */2824if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2825get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2826get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2827!(email_end =strchr(sb->buf +82,'>')) ||2828 email_end[1] !=' '||2829!(timestamp =strtoul(email_end +2, &message,10)) ||2830!message || message[0] !=' '||2831(message[1] !='+'&& message[1] !='-') ||2832!isdigit(message[2]) || !isdigit(message[3]) ||2833!isdigit(message[4]) || !isdigit(message[5]))2834return0;/* corrupt? */2835 email_end[1] ='\0';2836 tz =strtol(message +1, NULL,10);2837if(message[6] !='\t')2838 message +=6;2839else2840 message +=7;2841returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2842}28432844static char*find_beginning_of_line(char*bob,char*scan)2845{2846while(bob < scan && *(--scan) !='\n')2847;/* keep scanning backwards */2848/*2849 * Return either beginning of the buffer, or LF at the end of2850 * the previous line.2851 */2852return scan;2853}28542855intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2856{2857struct strbuf sb = STRBUF_INIT;2858FILE*logfp;2859long pos;2860int ret =0, at_tail =1;28612862 logfp =fopen(git_path("logs/%s", refname),"r");2863if(!logfp)2864return-1;28652866/* Jump to the end */2867if(fseek(logfp,0, SEEK_END) <0)2868returnerror("cannot seek back reflog for%s:%s",2869 refname,strerror(errno));2870 pos =ftell(logfp);2871while(!ret &&0< pos) {2872int cnt;2873size_t nread;2874char buf[BUFSIZ];2875char*endp, *scanp;28762877/* Fill next block from the end */2878 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2879if(fseek(logfp, pos - cnt, SEEK_SET))2880returnerror("cannot seek back reflog for%s:%s",2881 refname,strerror(errno));2882 nread =fread(buf, cnt,1, logfp);2883if(nread !=1)2884returnerror("cannot read%dbytes from reflog for%s:%s",2885 cnt, refname,strerror(errno));2886 pos -= cnt;28872888 scanp = endp = buf + cnt;2889if(at_tail && scanp[-1] =='\n')2890/* Looking at the final LF at the end of the file */2891 scanp--;2892 at_tail =0;28932894while(buf < scanp) {2895/*2896 * terminating LF of the previous line, or the beginning2897 * of the buffer.2898 */2899char*bp;29002901 bp =find_beginning_of_line(buf, scanp);29022903if(*bp =='\n') {2904/*2905 * The newline is the end of the previous line,2906 * so we know we have complete line starting2907 * at (bp + 1). Prefix it onto any prior data2908 * we collected for the line and process it.2909 */2910strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2911 scanp = bp;2912 endp = bp +1;2913 ret =show_one_reflog_ent(&sb, fn, cb_data);2914strbuf_reset(&sb);2915if(ret)2916break;2917}else if(!pos) {2918/*2919 * We are at the start of the buffer, and the2920 * start of the file; there is no previous2921 * line, and we have everything for this one.2922 * Process it, and we can end the loop.2923 */2924strbuf_splice(&sb,0,0, buf, endp - buf);2925 ret =show_one_reflog_ent(&sb, fn, cb_data);2926strbuf_reset(&sb);2927break;2928}29292930if(bp == buf) {2931/*2932 * We are at the start of the buffer, and there2933 * is more file to read backwards. Which means2934 * we are in the middle of a line. Note that we2935 * may get here even if *bp was a newline; that2936 * just means we are at the exact end of the2937 * previous line, rather than some spot in the2938 * middle.2939 *2940 * Save away what we have to be combined with2941 * the data from the next read.2942 */2943strbuf_splice(&sb,0,0, buf, endp - buf);2944break;2945}2946}29472948}2949if(!ret && sb.len)2950die("BUG: reverse reflog parser had leftover data");29512952fclose(logfp);2953strbuf_release(&sb);2954return ret;2955}29562957intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)2958{2959FILE*logfp;2960struct strbuf sb = STRBUF_INIT;2961int ret =0;29622963 logfp =fopen(git_path("logs/%s", refname),"r");2964if(!logfp)2965return-1;29662967while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2968 ret =show_one_reflog_ent(&sb, fn, cb_data);2969fclose(logfp);2970strbuf_release(&sb);2971return ret;2972}2973/*2974 * Call fn for each reflog in the namespace indicated by name. name2975 * must be empty or end with '/'. Name will be used as a scratch2976 * space, but its contents will be restored before return.2977 */2978static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)2979{2980DIR*d =opendir(git_path("logs/%s", name->buf));2981int retval =0;2982struct dirent *de;2983int oldlen = name->len;29842985if(!d)2986return name->len ? errno :0;29872988while((de =readdir(d)) != NULL) {2989struct stat st;29902991if(de->d_name[0] =='.')2992continue;2993if(ends_with(de->d_name,".lock"))2994continue;2995strbuf_addstr(name, de->d_name);2996if(stat(git_path("logs/%s", name->buf), &st) <0) {2997;/* silently ignore */2998}else{2999if(S_ISDIR(st.st_mode)) {3000strbuf_addch(name,'/');3001 retval =do_for_each_reflog(name, fn, cb_data);3002}else{3003struct object_id oid;30043005if(read_ref_full(name->buf,0, oid.hash, NULL))3006 retval =error("bad ref for%s", name->buf);3007else3008 retval =fn(name->buf, &oid,0, cb_data);3009}3010if(retval)3011break;3012}3013strbuf_setlen(name, oldlen);3014}3015closedir(d);3016return retval;3017}30183019intfor_each_reflog(each_ref_fn fn,void*cb_data)3020{3021int retval;3022struct strbuf name;3023strbuf_init(&name, PATH_MAX);3024 retval =do_for_each_reflog(&name, fn, cb_data);3025strbuf_release(&name);3026return retval;3027}30283029static intref_update_reject_duplicates(struct string_list *refnames,3030struct strbuf *err)3031{3032int i, n = refnames->nr;30333034assert(err);30353036for(i =1; i < n; i++)3037if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3038strbuf_addf(err,3039"Multiple updates for ref '%s' not allowed.",3040 refnames->items[i].string);3041return1;3042}3043return0;3044}30453046intref_transaction_commit(struct ref_transaction *transaction,3047struct strbuf *err)3048{3049int ret =0, i;3050struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3051struct string_list_item *ref_to_delete;3052struct string_list affected_refnames = STRING_LIST_INIT_NODUP;30533054assert(err);30553056if(transaction->state != REF_TRANSACTION_OPEN)3057die("BUG: commit called for transaction that is not open");30583059if(!transaction->nr) {3060 transaction->state = REF_TRANSACTION_CLOSED;3061return0;3062}30633064/* Fail if a refname appears more than once in the transaction: */3065for(i =0; i < transaction->nr; i++)3066string_list_append(&affected_refnames,3067 transaction->updates[i]->refname);3068string_list_sort(&affected_refnames);3069if(ref_update_reject_duplicates(&affected_refnames, err)) {3070 ret = TRANSACTION_GENERIC_ERROR;3071goto cleanup;3072}30733074/*3075 * Acquire all locks, verify old values if provided, check3076 * that new values are valid, and write new values to the3077 * lockfiles, ready to be activated. Only keep one lockfile3078 * open at a time to avoid running out of file descriptors.3079 */3080for(i =0; i < transaction->nr; i++) {3081struct ref_update *update = transaction->updates[i];30823083if((update->flags & REF_HAVE_NEW) &&3084is_null_sha1(update->new_sha1))3085 update->flags |= REF_DELETING;3086 update->lock =lock_ref_sha1_basic(3087 update->refname,3088((update->flags & REF_HAVE_OLD) ?3089 update->old_sha1 : NULL),3090&affected_refnames, NULL,3091 update->flags,3092&update->type,3093 err);3094if(!update->lock) {3095char*reason;30963097 ret = (errno == ENOTDIR)3098? TRANSACTION_NAME_CONFLICT3099: TRANSACTION_GENERIC_ERROR;3100 reason =strbuf_detach(err, NULL);3101strbuf_addf(err,"cannot lock ref '%s':%s",3102 update->refname, reason);3103free(reason);3104goto cleanup;3105}3106if((update->flags & REF_HAVE_NEW) &&3107!(update->flags & REF_DELETING)) {3108int overwriting_symref = ((update->type & REF_ISSYMREF) &&3109(update->flags & REF_NODEREF));31103111if(!overwriting_symref &&3112!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3113/*3114 * The reference already has the desired3115 * value, so we don't need to write it.3116 */3117}else if(write_ref_to_lockfile(update->lock,3118 update->new_sha1,3119 err)) {3120char*write_err =strbuf_detach(err, NULL);31213122/*3123 * The lock was freed upon failure of3124 * write_ref_to_lockfile():3125 */3126 update->lock = NULL;3127strbuf_addf(err,3128"cannot update the ref '%s':%s",3129 update->refname, write_err);3130free(write_err);3131 ret = TRANSACTION_GENERIC_ERROR;3132goto cleanup;3133}else{3134 update->flags |= REF_NEEDS_COMMIT;3135}3136}3137if(!(update->flags & REF_NEEDS_COMMIT)) {3138/*3139 * We didn't have to write anything to the lockfile.3140 * Close it to free up the file descriptor:3141 */3142if(close_ref(update->lock)) {3143strbuf_addf(err,"Couldn't close%s.lock",3144 update->refname);3145goto cleanup;3146}3147}3148}31493150/* Perform updates first so live commits remain referenced */3151for(i =0; i < transaction->nr; i++) {3152struct ref_update *update = transaction->updates[i];31533154if(update->flags & REF_NEEDS_COMMIT) {3155if(commit_ref_update(update->lock,3156 update->new_sha1, update->msg,3157 update->flags, err)) {3158/* freed by commit_ref_update(): */3159 update->lock = NULL;3160 ret = TRANSACTION_GENERIC_ERROR;3161goto cleanup;3162}else{3163/* freed by commit_ref_update(): */3164 update->lock = NULL;3165}3166}3167}31683169/* Perform deletes now that updates are safely completed */3170for(i =0; i < transaction->nr; i++) {3171struct ref_update *update = transaction->updates[i];31723173if(update->flags & REF_DELETING) {3174if(delete_ref_loose(update->lock, update->type, err)) {3175 ret = TRANSACTION_GENERIC_ERROR;3176goto cleanup;3177}31783179if(!(update->flags & REF_ISPRUNING))3180string_list_append(&refs_to_delete,3181 update->lock->ref_name);3182}3183}31843185if(repack_without_refs(&refs_to_delete, err)) {3186 ret = TRANSACTION_GENERIC_ERROR;3187goto cleanup;3188}3189for_each_string_list_item(ref_to_delete, &refs_to_delete)3190unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3191clear_loose_ref_cache(&ref_cache);31923193cleanup:3194 transaction->state = REF_TRANSACTION_CLOSED;31953196for(i =0; i < transaction->nr; i++)3197if(transaction->updates[i]->lock)3198unlock_ref(transaction->updates[i]->lock);3199string_list_clear(&refs_to_delete,0);3200string_list_clear(&affected_refnames,0);3201return ret;3202}32033204static intref_present(const char*refname,3205const struct object_id *oid,int flags,void*cb_data)3206{3207struct string_list *affected_refnames = cb_data;32083209returnstring_list_has_string(affected_refnames, refname);3210}32113212intinitial_ref_transaction_commit(struct ref_transaction *transaction,3213struct strbuf *err)3214{3215int ret =0, i;3216struct string_list affected_refnames = STRING_LIST_INIT_NODUP;32173218assert(err);32193220if(transaction->state != REF_TRANSACTION_OPEN)3221die("BUG: commit called for transaction that is not open");32223223/* Fail if a refname appears more than once in the transaction: */3224for(i =0; i < transaction->nr; i++)3225string_list_append(&affected_refnames,3226 transaction->updates[i]->refname);3227string_list_sort(&affected_refnames);3228if(ref_update_reject_duplicates(&affected_refnames, err)) {3229 ret = TRANSACTION_GENERIC_ERROR;3230goto cleanup;3231}32323233/*3234 * It's really undefined to call this function in an active3235 * repository or when there are existing references: we are3236 * only locking and changing packed-refs, so (1) any3237 * simultaneous processes might try to change a reference at3238 * the same time we do, and (2) any existing loose versions of3239 * the references that we are setting would have precedence3240 * over our values. But some remote helpers create the remote3241 * "HEAD" and "master" branches before calling this function,3242 * so here we really only check that none of the references3243 * that we are creating already exists.3244 */3245if(for_each_rawref(ref_present, &affected_refnames))3246die("BUG: initial ref transaction called with existing refs");32473248for(i =0; i < transaction->nr; i++) {3249struct ref_update *update = transaction->updates[i];32503251if((update->flags & REF_HAVE_OLD) &&3252!is_null_sha1(update->old_sha1))3253die("BUG: initial ref transaction with old_sha1 set");3254if(verify_refname_available(update->refname,3255&affected_refnames, NULL,3256 err)) {3257 ret = TRANSACTION_NAME_CONFLICT;3258goto cleanup;3259}3260}32613262if(lock_packed_refs(0)) {3263strbuf_addf(err,"unable to lock packed-refs file:%s",3264strerror(errno));3265 ret = TRANSACTION_GENERIC_ERROR;3266goto cleanup;3267}32683269for(i =0; i < transaction->nr; i++) {3270struct ref_update *update = transaction->updates[i];32713272if((update->flags & REF_HAVE_NEW) &&3273!is_null_sha1(update->new_sha1))3274add_packed_ref(update->refname, update->new_sha1);3275}32763277if(commit_packed_refs()) {3278strbuf_addf(err,"unable to commit packed-refs file:%s",3279strerror(errno));3280 ret = TRANSACTION_GENERIC_ERROR;3281goto cleanup;3282}32833284cleanup:3285 transaction->state = REF_TRANSACTION_CLOSED;3286string_list_clear(&affected_refnames,0);3287return ret;3288}32893290struct expire_reflog_cb {3291unsigned int flags;3292 reflog_expiry_should_prune_fn *should_prune_fn;3293void*policy_cb;3294FILE*newlog;3295unsigned char last_kept_sha1[20];3296};32973298static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3299const char*email,unsigned long timestamp,int tz,3300const char*message,void*cb_data)3301{3302struct expire_reflog_cb *cb = cb_data;3303struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;33043305if(cb->flags & EXPIRE_REFLOGS_REWRITE)3306 osha1 = cb->last_kept_sha1;33073308if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3309 message, policy_cb)) {3310if(!cb->newlog)3311printf("would prune%s", message);3312else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3313printf("prune%s", message);3314}else{3315if(cb->newlog) {3316fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3317sha1_to_hex(osha1),sha1_to_hex(nsha1),3318 email, timestamp, tz, message);3319hashcpy(cb->last_kept_sha1, nsha1);3320}3321if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3322printf("keep%s", message);3323}3324return0;3325}33263327intreflog_expire(const char*refname,const unsigned char*sha1,3328unsigned int flags,3329 reflog_expiry_prepare_fn prepare_fn,3330 reflog_expiry_should_prune_fn should_prune_fn,3331 reflog_expiry_cleanup_fn cleanup_fn,3332void*policy_cb_data)3333{3334static struct lock_file reflog_lock;3335struct expire_reflog_cb cb;3336struct ref_lock *lock;3337char*log_file;3338int status =0;3339int type;3340struct strbuf err = STRBUF_INIT;33413342memset(&cb,0,sizeof(cb));3343 cb.flags = flags;3344 cb.policy_cb = policy_cb_data;3345 cb.should_prune_fn = should_prune_fn;33463347/*3348 * The reflog file is locked by holding the lock on the3349 * reference itself, plus we might need to update the3350 * reference if --updateref was specified:3351 */3352 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL, REF_NODEREF,3353&type, &err);3354if(!lock) {3355error("cannot lock ref '%s':%s", refname, err.buf);3356strbuf_release(&err);3357return-1;3358}3359if(!reflog_exists(refname)) {3360unlock_ref(lock);3361return0;3362}33633364 log_file =git_pathdup("logs/%s", refname);3365if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3366/*3367 * Even though holding $GIT_DIR/logs/$reflog.lock has3368 * no locking implications, we use the lock_file3369 * machinery here anyway because it does a lot of the3370 * work we need, including cleaning up if the program3371 * exits unexpectedly.3372 */3373if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3374struct strbuf err = STRBUF_INIT;3375unable_to_lock_message(log_file, errno, &err);3376error("%s", err.buf);3377strbuf_release(&err);3378goto failure;3379}3380 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3381if(!cb.newlog) {3382error("cannot fdopen%s(%s)",3383get_lock_file_path(&reflog_lock),strerror(errno));3384goto failure;3385}3386}33873388(*prepare_fn)(refname, sha1, cb.policy_cb);3389for_each_reflog_ent(refname, expire_reflog_ent, &cb);3390(*cleanup_fn)(cb.policy_cb);33913392if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3393/*3394 * It doesn't make sense to adjust a reference pointed3395 * to by a symbolic ref based on expiring entries in3396 * the symbolic reference's reflog. Nor can we update3397 * a reference if there are no remaining reflog3398 * entries.3399 */3400int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3401!(type & REF_ISSYMREF) &&3402!is_null_sha1(cb.last_kept_sha1);34033404if(close_lock_file(&reflog_lock)) {3405 status |=error("couldn't write%s:%s", log_file,3406strerror(errno));3407}else if(update &&3408(write_in_full(get_lock_file_fd(lock->lk),3409sha1_to_hex(cb.last_kept_sha1),40) !=40||3410write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3411close_ref(lock) <0)) {3412 status |=error("couldn't write%s",3413get_lock_file_path(lock->lk));3414rollback_lock_file(&reflog_lock);3415}else if(commit_lock_file(&reflog_lock)) {3416 status |=error("unable to write reflog '%s' (%s)",3417 log_file,strerror(errno));3418}else if(update &&commit_ref(lock)) {3419 status |=error("couldn't set%s", lock->ref_name);3420}3421}3422free(log_file);3423unlock_ref(lock);3424return status;34253426 failure:3427rollback_lock_file(&reflog_lock);3428free(log_file);3429unlock_ref(lock);3430return-1;3431}