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}13901391/*1392 * Read the specified reference from the filesystem or packed refs1393 * file, non-recursively. Set type to describe the reference, and:1394 *1395 * - If refname is the name of a normal reference, fill in sha11396 * (leaving referent unchanged).1397 *1398 * - If refname is the name of a symbolic reference, write the full1399 * name of the reference to which it refers (e.g.1400 * "refs/heads/master") to referent and set the REF_ISSYMREF bit in1401 * type (leaving sha1 unchanged). The caller is responsible for1402 * validating that referent is a valid reference name.1403 *1404 * WARNING: refname might be used as part of a filename, so it is1405 * important from a security standpoint that it be safe in the sense1406 * of refname_is_safe(). Moreover, for symrefs this function sets1407 * referent to whatever the repository says, which might not be a1408 * properly-formatted or even safe reference name. NEITHER INPUT NOR1409 * OUTPUT REFERENCE NAMES ARE VALIDATED WITHIN THIS FUNCTION.1410 *1411 * Return 0 on success. If the ref doesn't exist, set errno to ENOENT1412 * and return -1. If the ref exists but is neither a symbolic ref nor1413 * a sha1, it is broken; set REF_ISBROKEN in type, set errno to1414 * EINVAL, and return -1. If there is another error reading the ref,1415 * set errno appropriately and return -1.1416 *1417 * Backend-specific flags might be set in type as well, regardless of1418 * outcome.1419 *1420 * It is OK for refname to point into referent. If so:1421 *1422 * - if the function succeeds with REF_ISSYMREF, referent will be1423 * overwritten and the memory formerly pointed to by it might be1424 * changed or even freed.1425 *1426 * - in all other cases, referent will be untouched, and therefore1427 * refname will still be valid and unchanged.1428 */1429intread_raw_ref(const char*refname,unsigned char*sha1,1430struct strbuf *referent,unsigned int*type)1431{1432struct strbuf sb_contents = STRBUF_INIT;1433struct strbuf sb_path = STRBUF_INIT;1434const char*path;1435const char*buf;1436struct stat st;1437int fd;1438int ret = -1;1439int save_errno;14401441*type =0;1442strbuf_reset(&sb_path);1443strbuf_git_path(&sb_path,"%s", refname);1444 path = sb_path.buf;14451446stat_ref:1447/*1448 * We might have to loop back here to avoid a race1449 * condition: first we lstat() the file, then we try1450 * to read it as a link or as a file. But if somebody1451 * changes the type of the file (file <-> directory1452 * <-> symlink) between the lstat() and reading, then1453 * we don't want to report that as an error but rather1454 * try again starting with the lstat().1455 */14561457if(lstat(path, &st) <0) {1458if(errno != ENOENT)1459goto out;1460if(resolve_missing_loose_ref(refname, sha1, type)) {1461 errno = ENOENT;1462goto out;1463}1464 ret =0;1465goto out;1466}14671468/* Follow "normalized" - ie "refs/.." symlinks by hand */1469if(S_ISLNK(st.st_mode)) {1470strbuf_reset(&sb_contents);1471if(strbuf_readlink(&sb_contents, path,0) <0) {1472if(errno == ENOENT || errno == EINVAL)1473/* inconsistent with lstat; retry */1474goto stat_ref;1475else1476goto out;1477}1478if(starts_with(sb_contents.buf,"refs/") &&1479!check_refname_format(sb_contents.buf,0)) {1480strbuf_swap(&sb_contents, referent);1481*type |= REF_ISSYMREF;1482 ret =0;1483goto out;1484}1485}14861487/* Is it a directory? */1488if(S_ISDIR(st.st_mode)) {1489/*1490 * Even though there is a directory where the loose1491 * ref is supposed to be, there could still be a1492 * packed ref:1493 */1494if(resolve_missing_loose_ref(refname, sha1, type)) {1495 errno = EISDIR;1496goto out;1497}1498 ret =0;1499goto out;1500}15011502/*1503 * Anything else, just open it and try to use it as1504 * a ref1505 */1506 fd =open(path, O_RDONLY);1507if(fd <0) {1508if(errno == ENOENT)1509/* inconsistent with lstat; retry */1510goto stat_ref;1511else1512goto out;1513}1514strbuf_reset(&sb_contents);1515if(strbuf_read(&sb_contents, fd,256) <0) {1516int save_errno = errno;1517close(fd);1518 errno = save_errno;1519goto out;1520}1521close(fd);1522strbuf_rtrim(&sb_contents);1523 buf = sb_contents.buf;1524if(starts_with(buf,"ref:")) {1525 buf +=4;1526while(isspace(*buf))1527 buf++;15281529strbuf_reset(referent);1530strbuf_addstr(referent, buf);1531*type |= REF_ISSYMREF;1532 ret =0;1533goto out;1534}15351536/*1537 * Please note that FETCH_HEAD has additional1538 * data after the sha.1539 */1540if(get_sha1_hex(buf, sha1) ||1541(buf[40] !='\0'&& !isspace(buf[40]))) {1542*type |= REF_ISBROKEN;1543 errno = EINVAL;1544goto out;1545}15461547 ret =0;15481549out:1550 save_errno = errno;1551strbuf_release(&sb_path);1552strbuf_release(&sb_contents);1553 errno = save_errno;1554return ret;1555}15561557/*1558 * Peel the entry (if possible) and return its new peel_status. If1559 * repeel is true, re-peel the entry even if there is an old peeled1560 * value that is already stored in it.1561 *1562 * It is OK to call this function with a packed reference entry that1563 * might be stale and might even refer to an object that has since1564 * been garbage-collected. In such a case, if the entry has1565 * REF_KNOWS_PEELED then leave the status unchanged and return1566 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1567 */1568static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1569{1570enum peel_status status;15711572if(entry->flag & REF_KNOWS_PEELED) {1573if(repeel) {1574 entry->flag &= ~REF_KNOWS_PEELED;1575oidclr(&entry->u.value.peeled);1576}else{1577returnis_null_oid(&entry->u.value.peeled) ?1578 PEEL_NON_TAG : PEEL_PEELED;1579}1580}1581if(entry->flag & REF_ISBROKEN)1582return PEEL_BROKEN;1583if(entry->flag & REF_ISSYMREF)1584return PEEL_IS_SYMREF;15851586 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1587if(status == PEEL_PEELED || status == PEEL_NON_TAG)1588 entry->flag |= REF_KNOWS_PEELED;1589return status;1590}15911592intpeel_ref(const char*refname,unsigned char*sha1)1593{1594int flag;1595unsigned char base[20];15961597if(current_ref && (current_ref->name == refname1598|| !strcmp(current_ref->name, refname))) {1599if(peel_entry(current_ref,0))1600return-1;1601hashcpy(sha1, current_ref->u.value.peeled.hash);1602return0;1603}16041605if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1606return-1;16071608/*1609 * If the reference is packed, read its ref_entry from the1610 * cache in the hope that we already know its peeled value.1611 * We only try this optimization on packed references because1612 * (a) forcing the filling of the loose reference cache could1613 * be expensive and (b) loose references anyway usually do not1614 * have REF_KNOWS_PEELED.1615 */1616if(flag & REF_ISPACKED) {1617struct ref_entry *r =get_packed_ref(refname);1618if(r) {1619if(peel_entry(r,0))1620return-1;1621hashcpy(sha1, r->u.value.peeled.hash);1622return0;1623}1624}16251626returnpeel_object(base, sha1);1627}16281629/*1630 * Call fn for each reference in the specified ref_cache, omitting1631 * references not in the containing_dir of base. fn is called for all1632 * references, including broken ones. If fn ever returns a non-zero1633 * value, stop the iteration and return that value; otherwise, return1634 * 0.1635 */1636static intdo_for_each_entry(struct ref_cache *refs,const char*base,1637 each_ref_entry_fn fn,void*cb_data)1638{1639struct packed_ref_cache *packed_ref_cache;1640struct ref_dir *loose_dir;1641struct ref_dir *packed_dir;1642int retval =0;16431644/*1645 * We must make sure that all loose refs are read before accessing the1646 * packed-refs file; this avoids a race condition in which loose refs1647 * are migrated to the packed-refs file by a simultaneous process, but1648 * our in-memory view is from before the migration. get_packed_ref_cache()1649 * takes care of making sure our view is up to date with what is on1650 * disk.1651 */1652 loose_dir =get_loose_refs(refs);1653if(base && *base) {1654 loose_dir =find_containing_dir(loose_dir, base,0);1655}1656if(loose_dir)1657prime_ref_dir(loose_dir);16581659 packed_ref_cache =get_packed_ref_cache(refs);1660acquire_packed_ref_cache(packed_ref_cache);1661 packed_dir =get_packed_ref_dir(packed_ref_cache);1662if(base && *base) {1663 packed_dir =find_containing_dir(packed_dir, base,0);1664}16651666if(packed_dir && loose_dir) {1667sort_ref_dir(packed_dir);1668sort_ref_dir(loose_dir);1669 retval =do_for_each_entry_in_dirs(1670 packed_dir, loose_dir, fn, cb_data);1671}else if(packed_dir) {1672sort_ref_dir(packed_dir);1673 retval =do_for_each_entry_in_dir(1674 packed_dir,0, fn, cb_data);1675}else if(loose_dir) {1676sort_ref_dir(loose_dir);1677 retval =do_for_each_entry_in_dir(1678 loose_dir,0, fn, cb_data);1679}16801681release_packed_ref_cache(packed_ref_cache);1682return retval;1683}16841685/*1686 * Call fn for each reference in the specified ref_cache for which the1687 * refname begins with base. If trim is non-zero, then trim that many1688 * characters off the beginning of each refname before passing the1689 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1690 * broken references in the iteration. If fn ever returns a non-zero1691 * value, stop the iteration and return that value; otherwise, return1692 * 0.1693 */1694intdo_for_each_ref(const char*submodule,const char*base,1695 each_ref_fn fn,int trim,int flags,void*cb_data)1696{1697struct ref_entry_cb data;1698struct ref_cache *refs;16991700 refs =get_ref_cache(submodule);1701 data.base = base;1702 data.trim = trim;1703 data.flags = flags;1704 data.fn = fn;1705 data.cb_data = cb_data;17061707if(ref_paranoia <0)1708 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1709if(ref_paranoia)1710 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;17111712returndo_for_each_entry(refs, base, do_one_ref, &data);1713}17141715static voidunlock_ref(struct ref_lock *lock)1716{1717/* Do not free lock->lk -- atexit() still looks at them */1718if(lock->lk)1719rollback_lock_file(lock->lk);1720free(lock->ref_name);1721free(lock->orig_ref_name);1722free(lock);1723}17241725/*1726 * Verify that the reference locked by lock has the value old_sha1.1727 * Fail if the reference doesn't exist and mustexist is set. Return 01728 * on success. On error, write an error message to err, set errno, and1729 * return a negative value.1730 */1731static intverify_lock(struct ref_lock *lock,1732const unsigned char*old_sha1,int mustexist,1733struct strbuf *err)1734{1735assert(err);17361737if(read_ref_full(lock->ref_name,1738 mustexist ? RESOLVE_REF_READING :0,1739 lock->old_oid.hash, NULL)) {1740if(old_sha1) {1741int save_errno = errno;1742strbuf_addf(err,"can't verify ref%s", lock->ref_name);1743 errno = save_errno;1744return-1;1745}else{1746hashclr(lock->old_oid.hash);1747return0;1748}1749}1750if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1751strbuf_addf(err,"ref%sis at%sbut expected%s",1752 lock->ref_name,1753sha1_to_hex(lock->old_oid.hash),1754sha1_to_hex(old_sha1));1755 errno = EBUSY;1756return-1;1757}1758return0;1759}17601761static intremove_empty_directories(struct strbuf *path)1762{1763/*1764 * we want to create a file but there is a directory there;1765 * if that is an empty directory (or a directory that contains1766 * only empty directories), remove them.1767 */1768returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1769}17701771/*1772 * Locks a ref returning the lock on success and NULL on failure.1773 * On failure errno is set to something meaningful.1774 */1775static struct ref_lock *lock_ref_sha1_basic(const char*refname,1776const unsigned char*old_sha1,1777const struct string_list *extras,1778const struct string_list *skip,1779unsigned int flags,int*type_p,1780struct strbuf *err)1781{1782struct strbuf ref_file = STRBUF_INIT;1783struct strbuf orig_ref_file = STRBUF_INIT;1784const char*orig_refname = refname;1785struct ref_lock *lock;1786int last_errno =0;1787int type;1788int lflags =0;1789int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1790int resolve_flags =0;1791int attempts_remaining =3;17921793assert(err);17941795 lock =xcalloc(1,sizeof(struct ref_lock));17961797if(mustexist)1798 resolve_flags |= RESOLVE_REF_READING;1799if(flags & REF_DELETING)1800 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1801if(flags & REF_NODEREF) {1802 resolve_flags |= RESOLVE_REF_NO_RECURSE;1803 lflags |= LOCK_NO_DEREF;1804}18051806 refname =resolve_ref_unsafe(refname, resolve_flags,1807 lock->old_oid.hash, &type);1808if(!refname && errno == EISDIR) {1809/*1810 * we are trying to lock foo but we used to1811 * have foo/bar which now does not exist;1812 * it is normal for the empty directory 'foo'1813 * to remain.1814 */1815strbuf_git_path(&orig_ref_file,"%s", orig_refname);1816if(remove_empty_directories(&orig_ref_file)) {1817 last_errno = errno;1818if(!verify_refname_available_dir(orig_refname, extras, skip,1819get_loose_refs(&ref_cache), err))1820strbuf_addf(err,"there are still refs under '%s'",1821 orig_refname);1822goto error_return;1823}1824 refname =resolve_ref_unsafe(orig_refname, resolve_flags,1825 lock->old_oid.hash, &type);1826}1827if(type_p)1828*type_p = type;1829if(!refname) {1830 last_errno = errno;1831if(last_errno != ENOTDIR ||1832!verify_refname_available_dir(orig_refname, extras, skip,1833get_loose_refs(&ref_cache), err))1834strbuf_addf(err,"unable to resolve reference%s:%s",1835 orig_refname,strerror(last_errno));18361837goto error_return;1838}18391840if(flags & REF_NODEREF)1841 refname = orig_refname;18421843/*1844 * If the ref did not exist and we are creating it, make sure1845 * there is no existing packed ref whose name begins with our1846 * refname, nor a packed ref whose name is a proper prefix of1847 * our refname.1848 */1849if(is_null_oid(&lock->old_oid) &&1850verify_refname_available_dir(refname, extras, skip,1851get_packed_refs(&ref_cache), err)) {1852 last_errno = ENOTDIR;1853goto error_return;1854}18551856 lock->lk =xcalloc(1,sizeof(struct lock_file));18571858 lock->ref_name =xstrdup(refname);1859 lock->orig_ref_name =xstrdup(orig_refname);1860strbuf_git_path(&ref_file,"%s", refname);18611862 retry:1863switch(safe_create_leading_directories_const(ref_file.buf)) {1864case SCLD_OK:1865break;/* success */1866case SCLD_VANISHED:1867if(--attempts_remaining >0)1868goto retry;1869/* fall through */1870default:1871 last_errno = errno;1872strbuf_addf(err,"unable to create directory for%s",1873 ref_file.buf);1874goto error_return;1875}18761877if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {1878 last_errno = errno;1879if(errno == ENOENT && --attempts_remaining >0)1880/*1881 * Maybe somebody just deleted one of the1882 * directories leading to ref_file. Try1883 * again:1884 */1885goto retry;1886else{1887unable_to_lock_message(ref_file.buf, errno, err);1888goto error_return;1889}1890}1891if(verify_lock(lock, old_sha1, mustexist, err)) {1892 last_errno = errno;1893goto error_return;1894}1895goto out;18961897 error_return:1898unlock_ref(lock);1899 lock = NULL;19001901 out:1902strbuf_release(&ref_file);1903strbuf_release(&orig_ref_file);1904 errno = last_errno;1905return lock;1906}19071908/*1909 * Write an entry to the packed-refs file for the specified refname.1910 * If peeled is non-NULL, write it as the entry's peeled value.1911 */1912static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,1913unsigned char*peeled)1914{1915fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1916if(peeled)1917fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1918}19191920/*1921 * An each_ref_entry_fn that writes the entry to a packed-refs file.1922 */1923static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)1924{1925enum peel_status peel_status =peel_entry(entry,0);19261927if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1928error("internal error:%sis not a valid packed reference!",1929 entry->name);1930write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,1931 peel_status == PEEL_PEELED ?1932 entry->u.value.peeled.hash : NULL);1933return0;1934}19351936/*1937 * Lock the packed-refs file for writing. Flags is passed to1938 * hold_lock_file_for_update(). Return 0 on success. On errors, set1939 * errno appropriately and return a nonzero value.1940 */1941static intlock_packed_refs(int flags)1942{1943static int timeout_configured =0;1944static int timeout_value =1000;19451946struct packed_ref_cache *packed_ref_cache;19471948if(!timeout_configured) {1949git_config_get_int("core.packedrefstimeout", &timeout_value);1950 timeout_configured =1;1951}19521953if(hold_lock_file_for_update_timeout(1954&packlock,git_path("packed-refs"),1955 flags, timeout_value) <0)1956return-1;1957/*1958 * Get the current packed-refs while holding the lock. If the1959 * packed-refs file has been modified since we last read it,1960 * this will automatically invalidate the cache and re-read1961 * the packed-refs file.1962 */1963 packed_ref_cache =get_packed_ref_cache(&ref_cache);1964 packed_ref_cache->lock = &packlock;1965/* Increment the reference count to prevent it from being freed: */1966acquire_packed_ref_cache(packed_ref_cache);1967return0;1968}19691970/*1971 * Write the current version of the packed refs cache from memory to1972 * disk. The packed-refs file must already be locked for writing (see1973 * lock_packed_refs()). Return zero on success. On errors, set errno1974 * and return a nonzero value1975 */1976static intcommit_packed_refs(void)1977{1978struct packed_ref_cache *packed_ref_cache =1979get_packed_ref_cache(&ref_cache);1980int error =0;1981int save_errno =0;1982FILE*out;19831984if(!packed_ref_cache->lock)1985die("internal error: packed-refs not locked");19861987 out =fdopen_lock_file(packed_ref_cache->lock,"w");1988if(!out)1989die_errno("unable to fdopen packed-refs descriptor");19901991fprintf_or_die(out,"%s", PACKED_REFS_HEADER);1992do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),19930, write_packed_entry_fn, out);19941995if(commit_lock_file(packed_ref_cache->lock)) {1996 save_errno = errno;1997 error = -1;1998}1999 packed_ref_cache->lock = NULL;2000release_packed_ref_cache(packed_ref_cache);2001 errno = save_errno;2002return error;2003}20042005/*2006 * Rollback the lockfile for the packed-refs file, and discard the2007 * in-memory packed reference cache. (The packed-refs file will be2008 * read anew if it is needed again after this function is called.)2009 */2010static voidrollback_packed_refs(void)2011{2012struct packed_ref_cache *packed_ref_cache =2013get_packed_ref_cache(&ref_cache);20142015if(!packed_ref_cache->lock)2016die("internal error: packed-refs not locked");2017rollback_lock_file(packed_ref_cache->lock);2018 packed_ref_cache->lock = NULL;2019release_packed_ref_cache(packed_ref_cache);2020clear_packed_ref_cache(&ref_cache);2021}20222023struct ref_to_prune {2024struct ref_to_prune *next;2025unsigned char sha1[20];2026char name[FLEX_ARRAY];2027};20282029struct pack_refs_cb_data {2030unsigned int flags;2031struct ref_dir *packed_refs;2032struct ref_to_prune *ref_to_prune;2033};20342035/*2036 * An each_ref_entry_fn that is run over loose references only. If2037 * the loose reference can be packed, add an entry in the packed ref2038 * cache. If the reference should be pruned, also add it to2039 * ref_to_prune in the pack_refs_cb_data.2040 */2041static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2042{2043struct pack_refs_cb_data *cb = cb_data;2044enum peel_status peel_status;2045struct ref_entry *packed_entry;2046int is_tag_ref =starts_with(entry->name,"refs/tags/");20472048/* Do not pack per-worktree refs: */2049if(ref_type(entry->name) != REF_TYPE_NORMAL)2050return0;20512052/* ALWAYS pack tags */2053if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2054return0;20552056/* Do not pack symbolic or broken refs: */2057if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2058return0;20592060/* Add a packed ref cache entry equivalent to the loose entry. */2061 peel_status =peel_entry(entry,1);2062if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2063die("internal error peeling reference%s(%s)",2064 entry->name,oid_to_hex(&entry->u.value.oid));2065 packed_entry =find_ref(cb->packed_refs, entry->name);2066if(packed_entry) {2067/* Overwrite existing packed entry with info from loose entry */2068 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2069oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2070}else{2071 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2072 REF_ISPACKED | REF_KNOWS_PEELED,0);2073add_ref(cb->packed_refs, packed_entry);2074}2075oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);20762077/* Schedule the loose reference for pruning if requested. */2078if((cb->flags & PACK_REFS_PRUNE)) {2079struct ref_to_prune *n;2080FLEX_ALLOC_STR(n, name, entry->name);2081hashcpy(n->sha1, entry->u.value.oid.hash);2082 n->next = cb->ref_to_prune;2083 cb->ref_to_prune = n;2084}2085return0;2086}20872088/*2089 * Remove empty parents, but spare refs/ and immediate subdirs.2090 * Note: munges *name.2091 */2092static voidtry_remove_empty_parents(char*name)2093{2094char*p, *q;2095int i;2096 p = name;2097for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2098while(*p && *p !='/')2099 p++;2100/* tolerate duplicate slashes; see check_refname_format() */2101while(*p =='/')2102 p++;2103}2104for(q = p; *q; q++)2105;2106while(1) {2107while(q > p && *q !='/')2108 q--;2109while(q > p && *(q-1) =='/')2110 q--;2111if(q == p)2112break;2113*q ='\0';2114if(rmdir(git_path("%s", name)))2115break;2116}2117}21182119/* make sure nobody touched the ref, and unlink */2120static voidprune_ref(struct ref_to_prune *r)2121{2122struct ref_transaction *transaction;2123struct strbuf err = STRBUF_INIT;21242125if(check_refname_format(r->name,0))2126return;21272128 transaction =ref_transaction_begin(&err);2129if(!transaction ||2130ref_transaction_delete(transaction, r->name, r->sha1,2131 REF_ISPRUNING, NULL, &err) ||2132ref_transaction_commit(transaction, &err)) {2133ref_transaction_free(transaction);2134error("%s", err.buf);2135strbuf_release(&err);2136return;2137}2138ref_transaction_free(transaction);2139strbuf_release(&err);2140try_remove_empty_parents(r->name);2141}21422143static voidprune_refs(struct ref_to_prune *r)2144{2145while(r) {2146prune_ref(r);2147 r = r->next;2148}2149}21502151intpack_refs(unsigned int flags)2152{2153struct pack_refs_cb_data cbdata;21542155memset(&cbdata,0,sizeof(cbdata));2156 cbdata.flags = flags;21572158lock_packed_refs(LOCK_DIE_ON_ERROR);2159 cbdata.packed_refs =get_packed_refs(&ref_cache);21602161do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2162 pack_if_possible_fn, &cbdata);21632164if(commit_packed_refs())2165die_errno("unable to overwrite old ref-pack file");21662167prune_refs(cbdata.ref_to_prune);2168return0;2169}21702171/*2172 * Rewrite the packed-refs file, omitting any refs listed in2173 * 'refnames'. On error, leave packed-refs unchanged, write an error2174 * message to 'err', and return a nonzero value.2175 *2176 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2177 */2178static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2179{2180struct ref_dir *packed;2181struct string_list_item *refname;2182int ret, needs_repacking =0, removed =0;21832184assert(err);21852186/* Look for a packed ref */2187for_each_string_list_item(refname, refnames) {2188if(get_packed_ref(refname->string)) {2189 needs_repacking =1;2190break;2191}2192}21932194/* Avoid locking if we have nothing to do */2195if(!needs_repacking)2196return0;/* no refname exists in packed refs */21972198if(lock_packed_refs(0)) {2199unable_to_lock_message(git_path("packed-refs"), errno, err);2200return-1;2201}2202 packed =get_packed_refs(&ref_cache);22032204/* Remove refnames from the cache */2205for_each_string_list_item(refname, refnames)2206if(remove_entry(packed, refname->string) != -1)2207 removed =1;2208if(!removed) {2209/*2210 * All packed entries disappeared while we were2211 * acquiring the lock.2212 */2213rollback_packed_refs();2214return0;2215}22162217/* Write what remains */2218 ret =commit_packed_refs();2219if(ret)2220strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2221strerror(errno));2222return ret;2223}22242225static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2226{2227assert(err);22282229if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2230/*2231 * loose. The loose file name is the same as the2232 * lockfile name, minus ".lock":2233 */2234char*loose_filename =get_locked_file_path(lock->lk);2235int res =unlink_or_msg(loose_filename, err);2236free(loose_filename);2237if(res)2238return1;2239}2240return0;2241}22422243intdelete_refs(struct string_list *refnames)2244{2245struct strbuf err = STRBUF_INIT;2246int i, result =0;22472248if(!refnames->nr)2249return0;22502251 result =repack_without_refs(refnames, &err);2252if(result) {2253/*2254 * If we failed to rewrite the packed-refs file, then2255 * it is unsafe to try to remove loose refs, because2256 * doing so might expose an obsolete packed value for2257 * a reference that might even point at an object that2258 * has been garbage collected.2259 */2260if(refnames->nr ==1)2261error(_("could not delete reference%s:%s"),2262 refnames->items[0].string, err.buf);2263else2264error(_("could not delete references:%s"), err.buf);22652266goto out;2267}22682269for(i =0; i < refnames->nr; i++) {2270const char*refname = refnames->items[i].string;22712272if(delete_ref(refname, NULL,0))2273 result |=error(_("could not remove reference%s"), refname);2274}22752276out:2277strbuf_release(&err);2278return result;2279}22802281/*2282 * People using contrib's git-new-workdir have .git/logs/refs ->2283 * /some/other/path/.git/logs/refs, and that may live on another device.2284 *2285 * IOW, to avoid cross device rename errors, the temporary renamed log must2286 * live into logs/refs.2287 */2288#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"22892290static intrename_tmp_log(const char*newrefname)2291{2292int attempts_remaining =4;2293struct strbuf path = STRBUF_INIT;2294int ret = -1;22952296 retry:2297strbuf_reset(&path);2298strbuf_git_path(&path,"logs/%s", newrefname);2299switch(safe_create_leading_directories_const(path.buf)) {2300case SCLD_OK:2301break;/* success */2302case SCLD_VANISHED:2303if(--attempts_remaining >0)2304goto retry;2305/* fall through */2306default:2307error("unable to create directory for%s", newrefname);2308goto out;2309}23102311if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2312if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2313/*2314 * rename(a, b) when b is an existing2315 * directory ought to result in ISDIR, but2316 * Solaris 5.8 gives ENOTDIR. Sheesh.2317 */2318if(remove_empty_directories(&path)) {2319error("Directory not empty: logs/%s", newrefname);2320goto out;2321}2322goto retry;2323}else if(errno == ENOENT && --attempts_remaining >0) {2324/*2325 * Maybe another process just deleted one of2326 * the directories in the path to newrefname.2327 * Try again from the beginning.2328 */2329goto retry;2330}else{2331error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2332 newrefname,strerror(errno));2333goto out;2334}2335}2336 ret =0;2337out:2338strbuf_release(&path);2339return ret;2340}23412342intverify_refname_available(const char*newname,2343struct string_list *extras,2344struct string_list *skip,2345struct strbuf *err)2346{2347struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2348struct ref_dir *loose_refs =get_loose_refs(&ref_cache);23492350if(verify_refname_available_dir(newname, extras, skip,2351 packed_refs, err) ||2352verify_refname_available_dir(newname, extras, skip,2353 loose_refs, err))2354return-1;23552356return0;2357}23582359static intwrite_ref_to_lockfile(struct ref_lock *lock,2360const unsigned char*sha1,struct strbuf *err);2361static intcommit_ref_update(struct ref_lock *lock,2362const unsigned char*sha1,const char*logmsg,2363int flags,struct strbuf *err);23642365intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2366{2367unsigned char sha1[20], orig_sha1[20];2368int flag =0, logmoved =0;2369struct ref_lock *lock;2370struct stat loginfo;2371int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2372struct strbuf err = STRBUF_INIT;23732374if(log &&S_ISLNK(loginfo.st_mode))2375returnerror("reflog for%sis a symlink", oldrefname);23762377if(!resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING, orig_sha1, &flag))2378returnerror("refname%snot found", oldrefname);23792380if(flag & REF_ISSYMREF)2381returnerror("refname%sis a symbolic ref, renaming it is not supported",2382 oldrefname);2383if(!rename_ref_available(oldrefname, newrefname))2384return1;23852386if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2387returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2388 oldrefname,strerror(errno));23892390if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2391error("unable to delete old%s", oldrefname);2392goto rollback;2393}23942395if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2396delete_ref(newrefname, sha1, REF_NODEREF)) {2397if(errno==EISDIR) {2398struct strbuf path = STRBUF_INIT;2399int result;24002401strbuf_git_path(&path,"%s", newrefname);2402 result =remove_empty_directories(&path);2403strbuf_release(&path);24042405if(result) {2406error("Directory not empty:%s", newrefname);2407goto rollback;2408}2409}else{2410error("unable to delete existing%s", newrefname);2411goto rollback;2412}2413}24142415if(log &&rename_tmp_log(newrefname))2416goto rollback;24172418 logmoved = log;24192420 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2421if(!lock) {2422error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2423strbuf_release(&err);2424goto rollback;2425}2426hashcpy(lock->old_oid.hash, orig_sha1);24272428if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2429commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2430error("unable to write current sha1 into%s:%s", newrefname, err.buf);2431strbuf_release(&err);2432goto rollback;2433}24342435return0;24362437 rollback:2438 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2439if(!lock) {2440error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2441strbuf_release(&err);2442goto rollbacklog;2443}24442445 flag = log_all_ref_updates;2446 log_all_ref_updates =0;2447if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2448commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2449error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2450strbuf_release(&err);2451}2452 log_all_ref_updates = flag;24532454 rollbacklog:2455if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2456error("unable to restore logfile%sfrom%s:%s",2457 oldrefname, newrefname,strerror(errno));2458if(!logmoved && log &&2459rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2460error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2461 oldrefname,strerror(errno));24622463return1;2464}24652466static intclose_ref(struct ref_lock *lock)2467{2468if(close_lock_file(lock->lk))2469return-1;2470return0;2471}24722473static intcommit_ref(struct ref_lock *lock)2474{2475char*path =get_locked_file_path(lock->lk);2476struct stat st;24772478if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {2479/*2480 * There is a directory at the path we want to rename2481 * the lockfile to. Hopefully it is empty; try to2482 * delete it.2483 */2484size_t len =strlen(path);2485struct strbuf sb_path = STRBUF_INIT;24862487strbuf_attach(&sb_path, path, len, len);24882489/*2490 * If this fails, commit_lock_file() will also fail2491 * and will report the problem.2492 */2493remove_empty_directories(&sb_path);2494strbuf_release(&sb_path);2495}else{2496free(path);2497}24982499if(commit_lock_file(lock->lk))2500return-1;2501return0;2502}25032504/*2505 * Create a reflog for a ref. If force_create = 0, the reflog will2506 * only be created for certain refs (those for which2507 * should_autocreate_reflog returns non-zero. Otherwise, create it2508 * regardless of the ref name. Fill in *err and return -1 on failure.2509 */2510static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2511{2512int logfd, oflags = O_APPEND | O_WRONLY;25132514strbuf_git_path(logfile,"logs/%s", refname);2515if(force_create ||should_autocreate_reflog(refname)) {2516if(safe_create_leading_directories(logfile->buf) <0) {2517strbuf_addf(err,"unable to create directory for%s: "2518"%s", logfile->buf,strerror(errno));2519return-1;2520}2521 oflags |= O_CREAT;2522}25232524 logfd =open(logfile->buf, oflags,0666);2525if(logfd <0) {2526if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2527return0;25282529if(errno == EISDIR) {2530if(remove_empty_directories(logfile)) {2531strbuf_addf(err,"There are still logs under "2532"'%s'", logfile->buf);2533return-1;2534}2535 logfd =open(logfile->buf, oflags,0666);2536}25372538if(logfd <0) {2539strbuf_addf(err,"unable to append to%s:%s",2540 logfile->buf,strerror(errno));2541return-1;2542}2543}25442545adjust_shared_perm(logfile->buf);2546close(logfd);2547return0;2548}254925502551intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2552{2553int ret;2554struct strbuf sb = STRBUF_INIT;25552556 ret =log_ref_setup(refname, &sb, err, force_create);2557strbuf_release(&sb);2558return ret;2559}25602561static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2562const unsigned char*new_sha1,2563const char*committer,const char*msg)2564{2565int msglen, written;2566unsigned maxlen, len;2567char*logrec;25682569 msglen = msg ?strlen(msg) :0;2570 maxlen =strlen(committer) + msglen +100;2571 logrec =xmalloc(maxlen);2572 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2573sha1_to_hex(old_sha1),2574sha1_to_hex(new_sha1),2575 committer);2576if(msglen)2577 len +=copy_reflog_msg(logrec + len -1, msg) -1;25782579 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2580free(logrec);2581if(written != len)2582return-1;25832584return0;2585}25862587static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2588const unsigned char*new_sha1,const char*msg,2589struct strbuf *logfile,int flags,2590struct strbuf *err)2591{2592int logfd, result, oflags = O_APPEND | O_WRONLY;25932594if(log_all_ref_updates <0)2595 log_all_ref_updates = !is_bare_repository();25962597 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);25982599if(result)2600return result;26012602 logfd =open(logfile->buf, oflags);2603if(logfd <0)2604return0;2605 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2606git_committer_info(0), msg);2607if(result) {2608strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2609strerror(errno));2610close(logfd);2611return-1;2612}2613if(close(logfd)) {2614strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2615strerror(errno));2616return-1;2617}2618return0;2619}26202621static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2622const unsigned char*new_sha1,const char*msg,2623int flags,struct strbuf *err)2624{2625returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2626 err);2627}26282629intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2630const unsigned char*new_sha1,const char*msg,2631int flags,struct strbuf *err)2632{2633struct strbuf sb = STRBUF_INIT;2634int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2635 err);2636strbuf_release(&sb);2637return ret;2638}26392640/*2641 * Write sha1 into the open lockfile, then close the lockfile. On2642 * errors, rollback the lockfile, fill in *err and2643 * return -1.2644 */2645static intwrite_ref_to_lockfile(struct ref_lock *lock,2646const unsigned char*sha1,struct strbuf *err)2647{2648static char term ='\n';2649struct object *o;2650int fd;26512652 o =parse_object(sha1);2653if(!o) {2654strbuf_addf(err,2655"Trying to write ref%swith nonexistent object%s",2656 lock->ref_name,sha1_to_hex(sha1));2657unlock_ref(lock);2658return-1;2659}2660if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2661strbuf_addf(err,2662"Trying to write non-commit object%sto branch%s",2663sha1_to_hex(sha1), lock->ref_name);2664unlock_ref(lock);2665return-1;2666}2667 fd =get_lock_file_fd(lock->lk);2668if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2669write_in_full(fd, &term,1) !=1||2670close_ref(lock) <0) {2671strbuf_addf(err,2672"Couldn't write%s",get_lock_file_path(lock->lk));2673unlock_ref(lock);2674return-1;2675}2676return0;2677}26782679/*2680 * Commit a change to a loose reference that has already been written2681 * to the loose reference lockfile. Also update the reflogs if2682 * necessary, using the specified lockmsg (which can be NULL).2683 */2684static intcommit_ref_update(struct ref_lock *lock,2685const unsigned char*sha1,const char*logmsg,2686int flags,struct strbuf *err)2687{2688clear_loose_ref_cache(&ref_cache);2689if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2690(strcmp(lock->ref_name, lock->orig_ref_name) &&2691log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2692char*old_msg =strbuf_detach(err, NULL);2693strbuf_addf(err,"Cannot update the ref '%s':%s",2694 lock->ref_name, old_msg);2695free(old_msg);2696unlock_ref(lock);2697return-1;2698}2699if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2700/*2701 * Special hack: If a branch is updated directly and HEAD2702 * points to it (may happen on the remote side of a push2703 * for example) then logically the HEAD reflog should be2704 * updated too.2705 * A generic solution implies reverse symref information,2706 * but finding all symrefs pointing to the given branch2707 * would be rather costly for this rare event (the direct2708 * update of a branch) to be worth it. So let's cheat and2709 * check with HEAD only which should cover 99% of all usage2710 * scenarios (even 100% of the default ones).2711 */2712unsigned char head_sha1[20];2713int head_flag;2714const char*head_ref;2715 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2716 head_sha1, &head_flag);2717if(head_ref && (head_flag & REF_ISSYMREF) &&2718!strcmp(head_ref, lock->ref_name)) {2719struct strbuf log_err = STRBUF_INIT;2720if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2721 logmsg,0, &log_err)) {2722error("%s", log_err.buf);2723strbuf_release(&log_err);2724}2725}2726}2727if(commit_ref(lock)) {2728strbuf_addf(err,"Couldn't set%s", lock->ref_name);2729unlock_ref(lock);2730return-1;2731}27322733unlock_ref(lock);2734return0;2735}27362737static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2738{2739int ret = -1;2740#ifndef NO_SYMLINK_HEAD2741char*ref_path =get_locked_file_path(lock->lk);2742unlink(ref_path);2743 ret =symlink(target, ref_path);2744free(ref_path);27452746if(ret)2747fprintf(stderr,"no symlink - falling back to symbolic ref\n");2748#endif2749return ret;2750}27512752static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2753const char*target,const char*logmsg)2754{2755struct strbuf err = STRBUF_INIT;2756unsigned char new_sha1[20];2757if(logmsg && !read_ref(target, new_sha1) &&2758log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2759error("%s", err.buf);2760strbuf_release(&err);2761}2762}27632764static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2765const char*target,const char*logmsg)2766{2767if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2768update_symref_reflog(lock, refname, target, logmsg);2769return0;2770}27712772if(!fdopen_lock_file(lock->lk,"w"))2773returnerror("unable to fdopen%s:%s",2774 lock->lk->tempfile.filename.buf,strerror(errno));27752776update_symref_reflog(lock, refname, target, logmsg);27772778/* no error check; commit_ref will check ferror */2779fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2780if(commit_ref(lock) <0)2781returnerror("unable to write symref for%s:%s", refname,2782strerror(errno));2783return0;2784}27852786intcreate_symref(const char*refname,const char*target,const char*logmsg)2787{2788struct strbuf err = STRBUF_INIT;2789struct ref_lock *lock;2790int ret;27912792 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2793&err);2794if(!lock) {2795error("%s", err.buf);2796strbuf_release(&err);2797return-1;2798}27992800 ret =create_symref_locked(lock, refname, target, logmsg);2801unlock_ref(lock);2802return ret;2803}28042805intset_worktree_head_symref(const char*gitdir,const char*target)2806{2807static struct lock_file head_lock;2808struct ref_lock *lock;2809struct strbuf head_path = STRBUF_INIT;2810const char*head_rel;2811int ret;28122813strbuf_addf(&head_path,"%s/HEAD",absolute_path(gitdir));2814if(hold_lock_file_for_update(&head_lock, head_path.buf,2815 LOCK_NO_DEREF) <0) {2816struct strbuf err = STRBUF_INIT;2817unable_to_lock_message(head_path.buf, errno, &err);2818error("%s", err.buf);2819strbuf_release(&err);2820strbuf_release(&head_path);2821return-1;2822}28232824/* head_rel will be "HEAD" for the main tree, "worktrees/wt/HEAD" for2825 linked trees */2826 head_rel =remove_leading_path(head_path.buf,2827absolute_path(get_git_common_dir()));2828/* to make use of create_symref_locked(), initialize ref_lock */2829 lock =xcalloc(1,sizeof(struct ref_lock));2830 lock->lk = &head_lock;2831 lock->ref_name =xstrdup(head_rel);2832 lock->orig_ref_name =xstrdup(head_rel);28332834 ret =create_symref_locked(lock, head_rel, target, NULL);28352836unlock_ref(lock);/* will free lock */2837strbuf_release(&head_path);2838return ret;2839}28402841intreflog_exists(const char*refname)2842{2843struct stat st;28442845return!lstat(git_path("logs/%s", refname), &st) &&2846S_ISREG(st.st_mode);2847}28482849intdelete_reflog(const char*refname)2850{2851returnremove_path(git_path("logs/%s", refname));2852}28532854static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2855{2856unsigned char osha1[20], nsha1[20];2857char*email_end, *message;2858unsigned long timestamp;2859int tz;28602861/* old SP new SP name <email> SP time TAB msg LF */2862if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2863get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2864get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2865!(email_end =strchr(sb->buf +82,'>')) ||2866 email_end[1] !=' '||2867!(timestamp =strtoul(email_end +2, &message,10)) ||2868!message || message[0] !=' '||2869(message[1] !='+'&& message[1] !='-') ||2870!isdigit(message[2]) || !isdigit(message[3]) ||2871!isdigit(message[4]) || !isdigit(message[5]))2872return0;/* corrupt? */2873 email_end[1] ='\0';2874 tz =strtol(message +1, NULL,10);2875if(message[6] !='\t')2876 message +=6;2877else2878 message +=7;2879returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2880}28812882static char*find_beginning_of_line(char*bob,char*scan)2883{2884while(bob < scan && *(--scan) !='\n')2885;/* keep scanning backwards */2886/*2887 * Return either beginning of the buffer, or LF at the end of2888 * the previous line.2889 */2890return scan;2891}28922893intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2894{2895struct strbuf sb = STRBUF_INIT;2896FILE*logfp;2897long pos;2898int ret =0, at_tail =1;28992900 logfp =fopen(git_path("logs/%s", refname),"r");2901if(!logfp)2902return-1;29032904/* Jump to the end */2905if(fseek(logfp,0, SEEK_END) <0)2906returnerror("cannot seek back reflog for%s:%s",2907 refname,strerror(errno));2908 pos =ftell(logfp);2909while(!ret &&0< pos) {2910int cnt;2911size_t nread;2912char buf[BUFSIZ];2913char*endp, *scanp;29142915/* Fill next block from the end */2916 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2917if(fseek(logfp, pos - cnt, SEEK_SET))2918returnerror("cannot seek back reflog for%s:%s",2919 refname,strerror(errno));2920 nread =fread(buf, cnt,1, logfp);2921if(nread !=1)2922returnerror("cannot read%dbytes from reflog for%s:%s",2923 cnt, refname,strerror(errno));2924 pos -= cnt;29252926 scanp = endp = buf + cnt;2927if(at_tail && scanp[-1] =='\n')2928/* Looking at the final LF at the end of the file */2929 scanp--;2930 at_tail =0;29312932while(buf < scanp) {2933/*2934 * terminating LF of the previous line, or the beginning2935 * of the buffer.2936 */2937char*bp;29382939 bp =find_beginning_of_line(buf, scanp);29402941if(*bp =='\n') {2942/*2943 * The newline is the end of the previous line,2944 * so we know we have complete line starting2945 * at (bp + 1). Prefix it onto any prior data2946 * we collected for the line and process it.2947 */2948strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2949 scanp = bp;2950 endp = bp +1;2951 ret =show_one_reflog_ent(&sb, fn, cb_data);2952strbuf_reset(&sb);2953if(ret)2954break;2955}else if(!pos) {2956/*2957 * We are at the start of the buffer, and the2958 * start of the file; there is no previous2959 * line, and we have everything for this one.2960 * Process it, and we can end the loop.2961 */2962strbuf_splice(&sb,0,0, buf, endp - buf);2963 ret =show_one_reflog_ent(&sb, fn, cb_data);2964strbuf_reset(&sb);2965break;2966}29672968if(bp == buf) {2969/*2970 * We are at the start of the buffer, and there2971 * is more file to read backwards. Which means2972 * we are in the middle of a line. Note that we2973 * may get here even if *bp was a newline; that2974 * just means we are at the exact end of the2975 * previous line, rather than some spot in the2976 * middle.2977 *2978 * Save away what we have to be combined with2979 * the data from the next read.2980 */2981strbuf_splice(&sb,0,0, buf, endp - buf);2982break;2983}2984}29852986}2987if(!ret && sb.len)2988die("BUG: reverse reflog parser had leftover data");29892990fclose(logfp);2991strbuf_release(&sb);2992return ret;2993}29942995intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)2996{2997FILE*logfp;2998struct strbuf sb = STRBUF_INIT;2999int ret =0;30003001 logfp =fopen(git_path("logs/%s", refname),"r");3002if(!logfp)3003return-1;30043005while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3006 ret =show_one_reflog_ent(&sb, fn, cb_data);3007fclose(logfp);3008strbuf_release(&sb);3009return ret;3010}3011/*3012 * Call fn for each reflog in the namespace indicated by name. name3013 * must be empty or end with '/'. Name will be used as a scratch3014 * space, but its contents will be restored before return.3015 */3016static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3017{3018DIR*d =opendir(git_path("logs/%s", name->buf));3019int retval =0;3020struct dirent *de;3021int oldlen = name->len;30223023if(!d)3024return name->len ? errno :0;30253026while((de =readdir(d)) != NULL) {3027struct stat st;30283029if(de->d_name[0] =='.')3030continue;3031if(ends_with(de->d_name,".lock"))3032continue;3033strbuf_addstr(name, de->d_name);3034if(stat(git_path("logs/%s", name->buf), &st) <0) {3035;/* silently ignore */3036}else{3037if(S_ISDIR(st.st_mode)) {3038strbuf_addch(name,'/');3039 retval =do_for_each_reflog(name, fn, cb_data);3040}else{3041struct object_id oid;30423043if(read_ref_full(name->buf,0, oid.hash, NULL))3044 retval =error("bad ref for%s", name->buf);3045else3046 retval =fn(name->buf, &oid,0, cb_data);3047}3048if(retval)3049break;3050}3051strbuf_setlen(name, oldlen);3052}3053closedir(d);3054return retval;3055}30563057intfor_each_reflog(each_ref_fn fn,void*cb_data)3058{3059int retval;3060struct strbuf name;3061strbuf_init(&name, PATH_MAX);3062 retval =do_for_each_reflog(&name, fn, cb_data);3063strbuf_release(&name);3064return retval;3065}30663067static intref_update_reject_duplicates(struct string_list *refnames,3068struct strbuf *err)3069{3070int i, n = refnames->nr;30713072assert(err);30733074for(i =1; i < n; i++)3075if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3076strbuf_addf(err,3077"Multiple updates for ref '%s' not allowed.",3078 refnames->items[i].string);3079return1;3080}3081return0;3082}30833084intref_transaction_commit(struct ref_transaction *transaction,3085struct strbuf *err)3086{3087int ret =0, i;3088struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3089struct string_list_item *ref_to_delete;3090struct string_list affected_refnames = STRING_LIST_INIT_NODUP;30913092assert(err);30933094if(transaction->state != REF_TRANSACTION_OPEN)3095die("BUG: commit called for transaction that is not open");30963097if(!transaction->nr) {3098 transaction->state = REF_TRANSACTION_CLOSED;3099return0;3100}31013102/* Fail if a refname appears more than once in the transaction: */3103for(i =0; i < transaction->nr; i++)3104string_list_append(&affected_refnames,3105 transaction->updates[i]->refname);3106string_list_sort(&affected_refnames);3107if(ref_update_reject_duplicates(&affected_refnames, err)) {3108 ret = TRANSACTION_GENERIC_ERROR;3109goto cleanup;3110}31113112/*3113 * Acquire all locks, verify old values if provided, check3114 * that new values are valid, and write new values to the3115 * lockfiles, ready to be activated. Only keep one lockfile3116 * open at a time to avoid running out of file descriptors.3117 */3118for(i =0; i < transaction->nr; i++) {3119struct ref_update *update = transaction->updates[i];31203121if((update->flags & REF_HAVE_NEW) &&3122is_null_sha1(update->new_sha1))3123 update->flags |= REF_DELETING;3124 update->lock =lock_ref_sha1_basic(3125 update->refname,3126((update->flags & REF_HAVE_OLD) ?3127 update->old_sha1 : NULL),3128&affected_refnames, NULL,3129 update->flags,3130&update->type,3131 err);3132if(!update->lock) {3133char*reason;31343135 ret = (errno == ENOTDIR)3136? TRANSACTION_NAME_CONFLICT3137: TRANSACTION_GENERIC_ERROR;3138 reason =strbuf_detach(err, NULL);3139strbuf_addf(err,"cannot lock ref '%s':%s",3140 update->refname, reason);3141free(reason);3142goto cleanup;3143}3144if((update->flags & REF_HAVE_NEW) &&3145!(update->flags & REF_DELETING)) {3146int overwriting_symref = ((update->type & REF_ISSYMREF) &&3147(update->flags & REF_NODEREF));31483149if(!overwriting_symref &&3150!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3151/*3152 * The reference already has the desired3153 * value, so we don't need to write it.3154 */3155}else if(write_ref_to_lockfile(update->lock,3156 update->new_sha1,3157 err)) {3158char*write_err =strbuf_detach(err, NULL);31593160/*3161 * The lock was freed upon failure of3162 * write_ref_to_lockfile():3163 */3164 update->lock = NULL;3165strbuf_addf(err,3166"cannot update the ref '%s':%s",3167 update->refname, write_err);3168free(write_err);3169 ret = TRANSACTION_GENERIC_ERROR;3170goto cleanup;3171}else{3172 update->flags |= REF_NEEDS_COMMIT;3173}3174}3175if(!(update->flags & REF_NEEDS_COMMIT)) {3176/*3177 * We didn't have to write anything to the lockfile.3178 * Close it to free up the file descriptor:3179 */3180if(close_ref(update->lock)) {3181strbuf_addf(err,"Couldn't close%s.lock",3182 update->refname);3183goto cleanup;3184}3185}3186}31873188/* Perform updates first so live commits remain referenced */3189for(i =0; i < transaction->nr; i++) {3190struct ref_update *update = transaction->updates[i];31913192if(update->flags & REF_NEEDS_COMMIT) {3193if(commit_ref_update(update->lock,3194 update->new_sha1, update->msg,3195 update->flags, err)) {3196/* freed by commit_ref_update(): */3197 update->lock = NULL;3198 ret = TRANSACTION_GENERIC_ERROR;3199goto cleanup;3200}else{3201/* freed by commit_ref_update(): */3202 update->lock = NULL;3203}3204}3205}32063207/* Perform deletes now that updates are safely completed */3208for(i =0; i < transaction->nr; i++) {3209struct ref_update *update = transaction->updates[i];32103211if(update->flags & REF_DELETING) {3212if(delete_ref_loose(update->lock, update->type, err)) {3213 ret = TRANSACTION_GENERIC_ERROR;3214goto cleanup;3215}32163217if(!(update->flags & REF_ISPRUNING))3218string_list_append(&refs_to_delete,3219 update->lock->ref_name);3220}3221}32223223if(repack_without_refs(&refs_to_delete, err)) {3224 ret = TRANSACTION_GENERIC_ERROR;3225goto cleanup;3226}3227for_each_string_list_item(ref_to_delete, &refs_to_delete)3228unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3229clear_loose_ref_cache(&ref_cache);32303231cleanup:3232 transaction->state = REF_TRANSACTION_CLOSED;32333234for(i =0; i < transaction->nr; i++)3235if(transaction->updates[i]->lock)3236unlock_ref(transaction->updates[i]->lock);3237string_list_clear(&refs_to_delete,0);3238string_list_clear(&affected_refnames,0);3239return ret;3240}32413242static intref_present(const char*refname,3243const struct object_id *oid,int flags,void*cb_data)3244{3245struct string_list *affected_refnames = cb_data;32463247returnstring_list_has_string(affected_refnames, refname);3248}32493250intinitial_ref_transaction_commit(struct ref_transaction *transaction,3251struct strbuf *err)3252{3253int ret =0, i;3254struct string_list affected_refnames = STRING_LIST_INIT_NODUP;32553256assert(err);32573258if(transaction->state != REF_TRANSACTION_OPEN)3259die("BUG: commit called for transaction that is not open");32603261/* Fail if a refname appears more than once in the transaction: */3262for(i =0; i < transaction->nr; i++)3263string_list_append(&affected_refnames,3264 transaction->updates[i]->refname);3265string_list_sort(&affected_refnames);3266if(ref_update_reject_duplicates(&affected_refnames, err)) {3267 ret = TRANSACTION_GENERIC_ERROR;3268goto cleanup;3269}32703271/*3272 * It's really undefined to call this function in an active3273 * repository or when there are existing references: we are3274 * only locking and changing packed-refs, so (1) any3275 * simultaneous processes might try to change a reference at3276 * the same time we do, and (2) any existing loose versions of3277 * the references that we are setting would have precedence3278 * over our values. But some remote helpers create the remote3279 * "HEAD" and "master" branches before calling this function,3280 * so here we really only check that none of the references3281 * that we are creating already exists.3282 */3283if(for_each_rawref(ref_present, &affected_refnames))3284die("BUG: initial ref transaction called with existing refs");32853286for(i =0; i < transaction->nr; i++) {3287struct ref_update *update = transaction->updates[i];32883289if((update->flags & REF_HAVE_OLD) &&3290!is_null_sha1(update->old_sha1))3291die("BUG: initial ref transaction with old_sha1 set");3292if(verify_refname_available(update->refname,3293&affected_refnames, NULL,3294 err)) {3295 ret = TRANSACTION_NAME_CONFLICT;3296goto cleanup;3297}3298}32993300if(lock_packed_refs(0)) {3301strbuf_addf(err,"unable to lock packed-refs file:%s",3302strerror(errno));3303 ret = TRANSACTION_GENERIC_ERROR;3304goto cleanup;3305}33063307for(i =0; i < transaction->nr; i++) {3308struct ref_update *update = transaction->updates[i];33093310if((update->flags & REF_HAVE_NEW) &&3311!is_null_sha1(update->new_sha1))3312add_packed_ref(update->refname, update->new_sha1);3313}33143315if(commit_packed_refs()) {3316strbuf_addf(err,"unable to commit packed-refs file:%s",3317strerror(errno));3318 ret = TRANSACTION_GENERIC_ERROR;3319goto cleanup;3320}33213322cleanup:3323 transaction->state = REF_TRANSACTION_CLOSED;3324string_list_clear(&affected_refnames,0);3325return ret;3326}33273328struct expire_reflog_cb {3329unsigned int flags;3330 reflog_expiry_should_prune_fn *should_prune_fn;3331void*policy_cb;3332FILE*newlog;3333unsigned char last_kept_sha1[20];3334};33353336static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3337const char*email,unsigned long timestamp,int tz,3338const char*message,void*cb_data)3339{3340struct expire_reflog_cb *cb = cb_data;3341struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;33423343if(cb->flags & EXPIRE_REFLOGS_REWRITE)3344 osha1 = cb->last_kept_sha1;33453346if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3347 message, policy_cb)) {3348if(!cb->newlog)3349printf("would prune%s", message);3350else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3351printf("prune%s", message);3352}else{3353if(cb->newlog) {3354fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3355sha1_to_hex(osha1),sha1_to_hex(nsha1),3356 email, timestamp, tz, message);3357hashcpy(cb->last_kept_sha1, nsha1);3358}3359if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3360printf("keep%s", message);3361}3362return0;3363}33643365intreflog_expire(const char*refname,const unsigned char*sha1,3366unsigned int flags,3367 reflog_expiry_prepare_fn prepare_fn,3368 reflog_expiry_should_prune_fn should_prune_fn,3369 reflog_expiry_cleanup_fn cleanup_fn,3370void*policy_cb_data)3371{3372static struct lock_file reflog_lock;3373struct expire_reflog_cb cb;3374struct ref_lock *lock;3375char*log_file;3376int status =0;3377int type;3378struct strbuf err = STRBUF_INIT;33793380memset(&cb,0,sizeof(cb));3381 cb.flags = flags;3382 cb.policy_cb = policy_cb_data;3383 cb.should_prune_fn = should_prune_fn;33843385/*3386 * The reflog file is locked by holding the lock on the3387 * reference itself, plus we might need to update the3388 * reference if --updateref was specified:3389 */3390 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL, REF_NODEREF,3391&type, &err);3392if(!lock) {3393error("cannot lock ref '%s':%s", refname, err.buf);3394strbuf_release(&err);3395return-1;3396}3397if(!reflog_exists(refname)) {3398unlock_ref(lock);3399return0;3400}34013402 log_file =git_pathdup("logs/%s", refname);3403if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3404/*3405 * Even though holding $GIT_DIR/logs/$reflog.lock has3406 * no locking implications, we use the lock_file3407 * machinery here anyway because it does a lot of the3408 * work we need, including cleaning up if the program3409 * exits unexpectedly.3410 */3411if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3412struct strbuf err = STRBUF_INIT;3413unable_to_lock_message(log_file, errno, &err);3414error("%s", err.buf);3415strbuf_release(&err);3416goto failure;3417}3418 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3419if(!cb.newlog) {3420error("cannot fdopen%s(%s)",3421get_lock_file_path(&reflog_lock),strerror(errno));3422goto failure;3423}3424}34253426(*prepare_fn)(refname, sha1, cb.policy_cb);3427for_each_reflog_ent(refname, expire_reflog_ent, &cb);3428(*cleanup_fn)(cb.policy_cb);34293430if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3431/*3432 * It doesn't make sense to adjust a reference pointed3433 * to by a symbolic ref based on expiring entries in3434 * the symbolic reference's reflog. Nor can we update3435 * a reference if there are no remaining reflog3436 * entries.3437 */3438int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3439!(type & REF_ISSYMREF) &&3440!is_null_sha1(cb.last_kept_sha1);34413442if(close_lock_file(&reflog_lock)) {3443 status |=error("couldn't write%s:%s", log_file,3444strerror(errno));3445}else if(update &&3446(write_in_full(get_lock_file_fd(lock->lk),3447sha1_to_hex(cb.last_kept_sha1),40) !=40||3448write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3449close_ref(lock) <0)) {3450 status |=error("couldn't write%s",3451get_lock_file_path(lock->lk));3452rollback_lock_file(&reflog_lock);3453}else if(commit_lock_file(&reflog_lock)) {3454 status |=error("unable to write reflog '%s' (%s)",3455 log_file,strerror(errno));3456}else if(update &&commit_ref(lock)) {3457 status |=error("couldn't set%s", lock->ref_name);3458}3459}3460free(log_file);3461unlock_ref(lock);3462return status;34633464 failure:3465rollback_lock_file(&reflog_lock);3466free(log_file);3467unlock_ref(lock);3468return-1;3469}