1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"../lockfile.h" 5#include"../object.h" 6#include"../dir.h" 7 8struct ref_lock { 9char*ref_name; 10char*orig_ref_name; 11struct lock_file *lk; 12struct object_id old_oid; 13}; 14 15struct ref_entry; 16 17/* 18 * Information used (along with the information in ref_entry) to 19 * describe a single cached reference. This data structure only 20 * occurs embedded in a union in struct ref_entry, and only when 21 * (ref_entry->flag & REF_DIR) is zero. 22 */ 23struct ref_value { 24/* 25 * The name of the object to which this reference resolves 26 * (which may be a tag object). If REF_ISBROKEN, this is 27 * null. If REF_ISSYMREF, then this is the name of the object 28 * referred to by the last reference in the symlink chain. 29 */ 30struct object_id oid; 31 32/* 33 * If REF_KNOWS_PEELED, then this field holds the peeled value 34 * of this reference, or null if the reference is known not to 35 * be peelable. See the documentation for peel_ref() for an 36 * exact definition of "peelable". 37 */ 38struct object_id peeled; 39}; 40 41struct ref_cache; 42 43/* 44 * Information used (along with the information in ref_entry) to 45 * describe a level in the hierarchy of references. This data 46 * structure only occurs embedded in a union in struct ref_entry, and 47 * only when (ref_entry.flag & REF_DIR) is set. In that case, 48 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 49 * in the directory have already been read: 50 * 51 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 52 * or packed references, already read. 53 * 54 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 55 * references that hasn't been read yet (nor has any of its 56 * subdirectories). 57 * 58 * Entries within a directory are stored within a growable array of 59 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 60 * sorted are sorted by their component name in strcmp() order and the 61 * remaining entries are unsorted. 62 * 63 * Loose references are read lazily, one directory at a time. When a 64 * directory of loose references is read, then all of the references 65 * in that directory are stored, and REF_INCOMPLETE stubs are created 66 * for any subdirectories, but the subdirectories themselves are not 67 * read. The reading is triggered by get_ref_dir(). 68 */ 69struct ref_dir { 70int nr, alloc; 71 72/* 73 * Entries with index 0 <= i < sorted are sorted by name. New 74 * entries are appended to the list unsorted, and are sorted 75 * only when required; thus we avoid the need to sort the list 76 * after the addition of every reference. 77 */ 78int sorted; 79 80/* A pointer to the ref_cache that contains this ref_dir. */ 81struct ref_cache *ref_cache; 82 83struct ref_entry **entries; 84}; 85 86/* 87 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 88 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 89 * public values; see refs.h. 90 */ 91 92/* 93 * The field ref_entry->u.value.peeled of this value entry contains 94 * the correct peeled value for the reference, which might be 95 * null_sha1 if the reference is not a tag or if it is broken. 96 */ 97#define REF_KNOWS_PEELED 0x10 98 99/* ref_entry represents a directory of references */ 100#define REF_DIR 0x20 101 102/* 103 * Entry has not yet been read from disk (used only for REF_DIR 104 * entries representing loose references) 105 */ 106#define REF_INCOMPLETE 0x40 107 108/* 109 * A ref_entry represents either a reference or a "subdirectory" of 110 * references. 111 * 112 * Each directory in the reference namespace is represented by a 113 * ref_entry with (flags & REF_DIR) set and containing a subdir member 114 * that holds the entries in that directory that have been read so 115 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 116 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 117 * used for loose reference directories. 118 * 119 * References are represented by a ref_entry with (flags & REF_DIR) 120 * unset and a value member that describes the reference's value. The 121 * flag member is at the ref_entry level, but it is also needed to 122 * interpret the contents of the value field (in other words, a 123 * ref_value object is not very much use without the enclosing 124 * ref_entry). 125 * 126 * Reference names cannot end with slash and directories' names are 127 * always stored with a trailing slash (except for the top-level 128 * directory, which is always denoted by ""). This has two nice 129 * consequences: (1) when the entries in each subdir are sorted 130 * lexicographically by name (as they usually are), the references in 131 * a whole tree can be generated in lexicographic order by traversing 132 * the tree in left-to-right, depth-first order; (2) the names of 133 * references and subdirectories cannot conflict, and therefore the 134 * presence of an empty subdirectory does not block the creation of a 135 * similarly-named reference. (The fact that reference names with the 136 * same leading components can conflict *with each other* is a 137 * separate issue that is regulated by verify_refname_available().) 138 * 139 * Please note that the name field contains the fully-qualified 140 * reference (or subdirectory) name. Space could be saved by only 141 * storing the relative names. But that would require the full names 142 * to be generated on the fly when iterating in do_for_each_ref(), and 143 * would break callback functions, who have always been able to assume 144 * that the name strings that they are passed will not be freed during 145 * the iteration. 146 */ 147struct ref_entry { 148unsigned char flag;/* ISSYMREF? ISPACKED? */ 149union{ 150struct ref_value value;/* if not (flags&REF_DIR) */ 151struct ref_dir subdir;/* if (flags&REF_DIR) */ 152} u; 153/* 154 * The full name of the reference (e.g., "refs/heads/master") 155 * or the full name of the directory with a trailing slash 156 * (e.g., "refs/heads/"): 157 */ 158char name[FLEX_ARRAY]; 159}; 160 161static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 162static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len); 163static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 164const char*dirname,size_t len, 165int incomplete); 166static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry); 167 168static struct ref_dir *get_ref_dir(struct ref_entry *entry) 169{ 170struct ref_dir *dir; 171assert(entry->flag & REF_DIR); 172 dir = &entry->u.subdir; 173if(entry->flag & REF_INCOMPLETE) { 174read_loose_refs(entry->name, dir); 175 176/* 177 * Manually add refs/bisect, which, being 178 * per-worktree, might not appear in the directory 179 * listing for refs/ in the main repo. 180 */ 181if(!strcmp(entry->name,"refs/")) { 182int pos =search_ref_dir(dir,"refs/bisect/",12); 183if(pos <0) { 184struct ref_entry *child_entry; 185 child_entry =create_dir_entry(dir->ref_cache, 186"refs/bisect/", 18712,1); 188add_entry_to_dir(dir, child_entry); 189read_loose_refs("refs/bisect", 190&child_entry->u.subdir); 191} 192} 193 entry->flag &= ~REF_INCOMPLETE; 194} 195return dir; 196} 197 198static struct ref_entry *create_ref_entry(const char*refname, 199const unsigned char*sha1,int flag, 200int check_name) 201{ 202struct ref_entry *ref; 203 204if(check_name && 205check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 206die("Reference has invalid format: '%s'", refname); 207FLEX_ALLOC_STR(ref, name, refname); 208hashcpy(ref->u.value.oid.hash, sha1); 209oidclr(&ref->u.value.peeled); 210 ref->flag = flag; 211return ref; 212} 213 214static voidclear_ref_dir(struct ref_dir *dir); 215 216static voidfree_ref_entry(struct ref_entry *entry) 217{ 218if(entry->flag & REF_DIR) { 219/* 220 * Do not use get_ref_dir() here, as that might 221 * trigger the reading of loose refs. 222 */ 223clear_ref_dir(&entry->u.subdir); 224} 225free(entry); 226} 227 228/* 229 * Add a ref_entry to the end of dir (unsorted). Entry is always 230 * stored directly in dir; no recursion into subdirectories is 231 * done. 232 */ 233static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 234{ 235ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 236 dir->entries[dir->nr++] = entry; 237/* optimize for the case that entries are added in order */ 238if(dir->nr ==1|| 239(dir->nr == dir->sorted +1&& 240strcmp(dir->entries[dir->nr -2]->name, 241 dir->entries[dir->nr -1]->name) <0)) 242 dir->sorted = dir->nr; 243} 244 245/* 246 * Clear and free all entries in dir, recursively. 247 */ 248static voidclear_ref_dir(struct ref_dir *dir) 249{ 250int i; 251for(i =0; i < dir->nr; i++) 252free_ref_entry(dir->entries[i]); 253free(dir->entries); 254 dir->sorted = dir->nr = dir->alloc =0; 255 dir->entries = NULL; 256} 257 258/* 259 * Create a struct ref_entry object for the specified dirname. 260 * dirname is the name of the directory with a trailing slash (e.g., 261 * "refs/heads/") or "" for the top-level directory. 262 */ 263static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 264const char*dirname,size_t len, 265int incomplete) 266{ 267struct ref_entry *direntry; 268FLEX_ALLOC_MEM(direntry, name, dirname, len); 269 direntry->u.subdir.ref_cache = ref_cache; 270 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 271return direntry; 272} 273 274static intref_entry_cmp(const void*a,const void*b) 275{ 276struct ref_entry *one = *(struct ref_entry **)a; 277struct ref_entry *two = *(struct ref_entry **)b; 278returnstrcmp(one->name, two->name); 279} 280 281static voidsort_ref_dir(struct ref_dir *dir); 282 283struct string_slice { 284size_t len; 285const char*str; 286}; 287 288static intref_entry_cmp_sslice(const void*key_,const void*ent_) 289{ 290const struct string_slice *key = key_; 291const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 292int cmp =strncmp(key->str, ent->name, key->len); 293if(cmp) 294return cmp; 295return'\0'- (unsigned char)ent->name[key->len]; 296} 297 298/* 299 * Return the index of the entry with the given refname from the 300 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 301 * no such entry is found. dir must already be complete. 302 */ 303static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 304{ 305struct ref_entry **r; 306struct string_slice key; 307 308if(refname == NULL || !dir->nr) 309return-1; 310 311sort_ref_dir(dir); 312 key.len = len; 313 key.str = refname; 314 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 315 ref_entry_cmp_sslice); 316 317if(r == NULL) 318return-1; 319 320return r - dir->entries; 321} 322 323/* 324 * Search for a directory entry directly within dir (without 325 * recursing). Sort dir if necessary. subdirname must be a directory 326 * name (i.e., end in '/'). If mkdir is set, then create the 327 * directory if it is missing; otherwise, return NULL if the desired 328 * directory cannot be found. dir must already be complete. 329 */ 330static struct ref_dir *search_for_subdir(struct ref_dir *dir, 331const char*subdirname,size_t len, 332int mkdir) 333{ 334int entry_index =search_ref_dir(dir, subdirname, len); 335struct ref_entry *entry; 336if(entry_index == -1) { 337if(!mkdir) 338return NULL; 339/* 340 * Since dir is complete, the absence of a subdir 341 * means that the subdir really doesn't exist; 342 * therefore, create an empty record for it but mark 343 * the record complete. 344 */ 345 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 346add_entry_to_dir(dir, entry); 347}else{ 348 entry = dir->entries[entry_index]; 349} 350returnget_ref_dir(entry); 351} 352 353/* 354 * If refname is a reference name, find the ref_dir within the dir 355 * tree that should hold refname. If refname is a directory name 356 * (i.e., ends in '/'), then return that ref_dir itself. dir must 357 * represent the top-level directory and must already be complete. 358 * Sort ref_dirs and recurse into subdirectories as necessary. If 359 * mkdir is set, then create any missing directories; otherwise, 360 * return NULL if the desired directory cannot be found. 361 */ 362static struct ref_dir *find_containing_dir(struct ref_dir *dir, 363const char*refname,int mkdir) 364{ 365const char*slash; 366for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 367size_t dirnamelen = slash - refname +1; 368struct ref_dir *subdir; 369 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 370if(!subdir) { 371 dir = NULL; 372break; 373} 374 dir = subdir; 375} 376 377return dir; 378} 379 380/* 381 * Find the value entry with the given name in dir, sorting ref_dirs 382 * and recursing into subdirectories as necessary. If the name is not 383 * found or it corresponds to a directory entry, return NULL. 384 */ 385static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 386{ 387int entry_index; 388struct ref_entry *entry; 389 dir =find_containing_dir(dir, refname,0); 390if(!dir) 391return NULL; 392 entry_index =search_ref_dir(dir, refname,strlen(refname)); 393if(entry_index == -1) 394return NULL; 395 entry = dir->entries[entry_index]; 396return(entry->flag & REF_DIR) ? NULL : entry; 397} 398 399/* 400 * Remove the entry with the given name from dir, recursing into 401 * subdirectories as necessary. If refname is the name of a directory 402 * (i.e., ends with '/'), then remove the directory and its contents. 403 * If the removal was successful, return the number of entries 404 * remaining in the directory entry that contained the deleted entry. 405 * If the name was not found, return -1. Please note that this 406 * function only deletes the entry from the cache; it does not delete 407 * it from the filesystem or ensure that other cache entries (which 408 * might be symbolic references to the removed entry) are updated. 409 * Nor does it remove any containing dir entries that might be made 410 * empty by the removal. dir must represent the top-level directory 411 * and must already be complete. 412 */ 413static intremove_entry(struct ref_dir *dir,const char*refname) 414{ 415int refname_len =strlen(refname); 416int entry_index; 417struct ref_entry *entry; 418int is_dir = refname[refname_len -1] =='/'; 419if(is_dir) { 420/* 421 * refname represents a reference directory. Remove 422 * the trailing slash; otherwise we will get the 423 * directory *representing* refname rather than the 424 * one *containing* it. 425 */ 426char*dirname =xmemdupz(refname, refname_len -1); 427 dir =find_containing_dir(dir, dirname,0); 428free(dirname); 429}else{ 430 dir =find_containing_dir(dir, refname,0); 431} 432if(!dir) 433return-1; 434 entry_index =search_ref_dir(dir, refname, refname_len); 435if(entry_index == -1) 436return-1; 437 entry = dir->entries[entry_index]; 438 439memmove(&dir->entries[entry_index], 440&dir->entries[entry_index +1], 441(dir->nr - entry_index -1) *sizeof(*dir->entries) 442); 443 dir->nr--; 444if(dir->sorted > entry_index) 445 dir->sorted--; 446free_ref_entry(entry); 447return dir->nr; 448} 449 450/* 451 * Add a ref_entry to the ref_dir (unsorted), recursing into 452 * subdirectories as necessary. dir must represent the top-level 453 * directory. Return 0 on success. 454 */ 455static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 456{ 457 dir =find_containing_dir(dir, ref->name,1); 458if(!dir) 459return-1; 460add_entry_to_dir(dir, ref); 461return0; 462} 463 464/* 465 * Emit a warning and return true iff ref1 and ref2 have the same name 466 * and the same sha1. Die if they have the same name but different 467 * sha1s. 468 */ 469static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 470{ 471if(strcmp(ref1->name, ref2->name)) 472return0; 473 474/* Duplicate name; make sure that they don't conflict: */ 475 476if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 477/* This is impossible by construction */ 478die("Reference directory conflict:%s", ref1->name); 479 480if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 481die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 482 483warning("Duplicated ref:%s", ref1->name); 484return1; 485} 486 487/* 488 * Sort the entries in dir non-recursively (if they are not already 489 * sorted) and remove any duplicate entries. 490 */ 491static voidsort_ref_dir(struct ref_dir *dir) 492{ 493int i, j; 494struct ref_entry *last = NULL; 495 496/* 497 * This check also prevents passing a zero-length array to qsort(), 498 * which is a problem on some platforms. 499 */ 500if(dir->sorted == dir->nr) 501return; 502 503qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 504 505/* Remove any duplicates: */ 506for(i =0, j =0; j < dir->nr; j++) { 507struct ref_entry *entry = dir->entries[j]; 508if(last &&is_dup_ref(last, entry)) 509free_ref_entry(entry); 510else 511 last = dir->entries[i++] = entry; 512} 513 dir->sorted = dir->nr = i; 514} 515 516/* 517 * Return true iff the reference described by entry can be resolved to 518 * an object in the database. Emit a warning if the referred-to 519 * object does not exist. 520 */ 521static intref_resolves_to_object(struct ref_entry *entry) 522{ 523if(entry->flag & REF_ISBROKEN) 524return0; 525if(!has_sha1_file(entry->u.value.oid.hash)) { 526error("%sdoes not point to a valid object!", entry->name); 527return0; 528} 529return1; 530} 531 532/* 533 * current_ref is a performance hack: when iterating over references 534 * using the for_each_ref*() functions, current_ref is set to the 535 * current reference's entry before calling the callback function. If 536 * the callback function calls peel_ref(), then peel_ref() first 537 * checks whether the reference to be peeled is the current reference 538 * (it usually is) and if so, returns that reference's peeled version 539 * if it is available. This avoids a refname lookup in a common case. 540 */ 541static struct ref_entry *current_ref; 542 543typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 544 545struct ref_entry_cb { 546const char*base; 547int trim; 548int flags; 549 each_ref_fn *fn; 550void*cb_data; 551}; 552 553/* 554 * Handle one reference in a do_for_each_ref*()-style iteration, 555 * calling an each_ref_fn for each entry. 556 */ 557static intdo_one_ref(struct ref_entry *entry,void*cb_data) 558{ 559struct ref_entry_cb *data = cb_data; 560struct ref_entry *old_current_ref; 561int retval; 562 563if(!starts_with(entry->name, data->base)) 564return0; 565 566if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 567!ref_resolves_to_object(entry)) 568return0; 569 570/* Store the old value, in case this is a recursive call: */ 571 old_current_ref = current_ref; 572 current_ref = entry; 573 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 574 entry->flag, data->cb_data); 575 current_ref = old_current_ref; 576return retval; 577} 578 579/* 580 * Call fn for each reference in dir that has index in the range 581 * offset <= index < dir->nr. Recurse into subdirectories that are in 582 * that index range, sorting them before iterating. This function 583 * does not sort dir itself; it should be sorted beforehand. fn is 584 * called for all references, including broken ones. 585 */ 586static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 587 each_ref_entry_fn fn,void*cb_data) 588{ 589int i; 590assert(dir->sorted == dir->nr); 591for(i = offset; i < dir->nr; i++) { 592struct ref_entry *entry = dir->entries[i]; 593int retval; 594if(entry->flag & REF_DIR) { 595struct ref_dir *subdir =get_ref_dir(entry); 596sort_ref_dir(subdir); 597 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 598}else{ 599 retval =fn(entry, cb_data); 600} 601if(retval) 602return retval; 603} 604return0; 605} 606 607/* 608 * Call fn for each reference in the union of dir1 and dir2, in order 609 * by refname. Recurse into subdirectories. If a value entry appears 610 * in both dir1 and dir2, then only process the version that is in 611 * dir2. The input dirs must already be sorted, but subdirs will be 612 * sorted as needed. fn is called for all references, including 613 * broken ones. 614 */ 615static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 616struct ref_dir *dir2, 617 each_ref_entry_fn fn,void*cb_data) 618{ 619int retval; 620int i1 =0, i2 =0; 621 622assert(dir1->sorted == dir1->nr); 623assert(dir2->sorted == dir2->nr); 624while(1) { 625struct ref_entry *e1, *e2; 626int cmp; 627if(i1 == dir1->nr) { 628returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 629} 630if(i2 == dir2->nr) { 631returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 632} 633 e1 = dir1->entries[i1]; 634 e2 = dir2->entries[i2]; 635 cmp =strcmp(e1->name, e2->name); 636if(cmp ==0) { 637if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 638/* Both are directories; descend them in parallel. */ 639struct ref_dir *subdir1 =get_ref_dir(e1); 640struct ref_dir *subdir2 =get_ref_dir(e2); 641sort_ref_dir(subdir1); 642sort_ref_dir(subdir2); 643 retval =do_for_each_entry_in_dirs( 644 subdir1, subdir2, fn, cb_data); 645 i1++; 646 i2++; 647}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 648/* Both are references; ignore the one from dir1. */ 649 retval =fn(e2, cb_data); 650 i1++; 651 i2++; 652}else{ 653die("conflict between reference and directory:%s", 654 e1->name); 655} 656}else{ 657struct ref_entry *e; 658if(cmp <0) { 659 e = e1; 660 i1++; 661}else{ 662 e = e2; 663 i2++; 664} 665if(e->flag & REF_DIR) { 666struct ref_dir *subdir =get_ref_dir(e); 667sort_ref_dir(subdir); 668 retval =do_for_each_entry_in_dir( 669 subdir,0, fn, cb_data); 670}else{ 671 retval =fn(e, cb_data); 672} 673} 674if(retval) 675return retval; 676} 677} 678 679/* 680 * Load all of the refs from the dir into our in-memory cache. The hard work 681 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 682 * through all of the sub-directories. We do not even need to care about 683 * sorting, as traversal order does not matter to us. 684 */ 685static voidprime_ref_dir(struct ref_dir *dir) 686{ 687int i; 688for(i =0; i < dir->nr; i++) { 689struct ref_entry *entry = dir->entries[i]; 690if(entry->flag & REF_DIR) 691prime_ref_dir(get_ref_dir(entry)); 692} 693} 694 695struct nonmatching_ref_data { 696const struct string_list *skip; 697const char*conflicting_refname; 698}; 699 700static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 701{ 702struct nonmatching_ref_data *data = vdata; 703 704if(data->skip &&string_list_has_string(data->skip, entry->name)) 705return0; 706 707 data->conflicting_refname = entry->name; 708return1; 709} 710 711/* 712 * Return 0 if a reference named refname could be created without 713 * conflicting with the name of an existing reference in dir. 714 * See verify_refname_available for more information. 715 */ 716static intverify_refname_available_dir(const char*refname, 717const struct string_list *extras, 718const struct string_list *skip, 719struct ref_dir *dir, 720struct strbuf *err) 721{ 722const char*slash; 723const char*extra_refname; 724int pos; 725struct strbuf dirname = STRBUF_INIT; 726int ret = -1; 727 728/* 729 * For the sake of comments in this function, suppose that 730 * refname is "refs/foo/bar". 731 */ 732 733assert(err); 734 735strbuf_grow(&dirname,strlen(refname) +1); 736for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 737/* Expand dirname to the new prefix, not including the trailing slash: */ 738strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 739 740/* 741 * We are still at a leading dir of the refname (e.g., 742 * "refs/foo"; if there is a reference with that name, 743 * it is a conflict, *unless* it is in skip. 744 */ 745if(dir) { 746 pos =search_ref_dir(dir, dirname.buf, dirname.len); 747if(pos >=0&& 748(!skip || !string_list_has_string(skip, dirname.buf))) { 749/* 750 * We found a reference whose name is 751 * a proper prefix of refname; e.g., 752 * "refs/foo", and is not in skip. 753 */ 754strbuf_addf(err,"'%s' exists; cannot create '%s'", 755 dirname.buf, refname); 756goto cleanup; 757} 758} 759 760if(extras &&string_list_has_string(extras, dirname.buf) && 761(!skip || !string_list_has_string(skip, dirname.buf))) { 762strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 763 refname, dirname.buf); 764goto cleanup; 765} 766 767/* 768 * Otherwise, we can try to continue our search with 769 * the next component. So try to look up the 770 * directory, e.g., "refs/foo/". If we come up empty, 771 * we know there is nothing under this whole prefix, 772 * but even in that case we still have to continue the 773 * search for conflicts with extras. 774 */ 775strbuf_addch(&dirname,'/'); 776if(dir) { 777 pos =search_ref_dir(dir, dirname.buf, dirname.len); 778if(pos <0) { 779/* 780 * There was no directory "refs/foo/", 781 * so there is nothing under this 782 * whole prefix. So there is no need 783 * to continue looking for conflicting 784 * references. But we need to continue 785 * looking for conflicting extras. 786 */ 787 dir = NULL; 788}else{ 789 dir =get_ref_dir(dir->entries[pos]); 790} 791} 792} 793 794/* 795 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 796 * There is no point in searching for a reference with that 797 * name, because a refname isn't considered to conflict with 798 * itself. But we still need to check for references whose 799 * names are in the "refs/foo/bar/" namespace, because they 800 * *do* conflict. 801 */ 802strbuf_addstr(&dirname, refname + dirname.len); 803strbuf_addch(&dirname,'/'); 804 805if(dir) { 806 pos =search_ref_dir(dir, dirname.buf, dirname.len); 807 808if(pos >=0) { 809/* 810 * We found a directory named "$refname/" 811 * (e.g., "refs/foo/bar/"). It is a problem 812 * iff it contains any ref that is not in 813 * "skip". 814 */ 815struct nonmatching_ref_data data; 816 817 data.skip = skip; 818 data.conflicting_refname = NULL; 819 dir =get_ref_dir(dir->entries[pos]); 820sort_ref_dir(dir); 821if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 822strbuf_addf(err,"'%s' exists; cannot create '%s'", 823 data.conflicting_refname, refname); 824goto cleanup; 825} 826} 827} 828 829 extra_refname =find_descendant_ref(dirname.buf, extras, skip); 830if(extra_refname) 831strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 832 refname, extra_refname); 833else 834 ret =0; 835 836cleanup: 837strbuf_release(&dirname); 838return ret; 839} 840 841struct packed_ref_cache { 842struct ref_entry *root; 843 844/* 845 * Count of references to the data structure in this instance, 846 * including the pointer from ref_cache::packed if any. The 847 * data will not be freed as long as the reference count is 848 * nonzero. 849 */ 850unsigned int referrers; 851 852/* 853 * Iff the packed-refs file associated with this instance is 854 * currently locked for writing, this points at the associated 855 * lock (which is owned by somebody else). The referrer count 856 * is also incremented when the file is locked and decremented 857 * when it is unlocked. 858 */ 859struct lock_file *lock; 860 861/* The metadata from when this packed-refs cache was read */ 862struct stat_validity validity; 863}; 864 865/* 866 * Future: need to be in "struct repository" 867 * when doing a full libification. 868 */ 869static struct ref_cache { 870struct ref_cache *next; 871struct ref_entry *loose; 872struct packed_ref_cache *packed; 873/* 874 * The submodule name, or "" for the main repo. We allocate 875 * length 1 rather than FLEX_ARRAY so that the main ref_cache 876 * is initialized correctly. 877 */ 878char name[1]; 879} ref_cache, *submodule_ref_caches; 880 881/* Lock used for the main packed-refs file: */ 882static struct lock_file packlock; 883 884/* 885 * Increment the reference count of *packed_refs. 886 */ 887static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 888{ 889 packed_refs->referrers++; 890} 891 892/* 893 * Decrease the reference count of *packed_refs. If it goes to zero, 894 * free *packed_refs and return true; otherwise return false. 895 */ 896static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 897{ 898if(!--packed_refs->referrers) { 899free_ref_entry(packed_refs->root); 900stat_validity_clear(&packed_refs->validity); 901free(packed_refs); 902return1; 903}else{ 904return0; 905} 906} 907 908static voidclear_packed_ref_cache(struct ref_cache *refs) 909{ 910if(refs->packed) { 911struct packed_ref_cache *packed_refs = refs->packed; 912 913if(packed_refs->lock) 914die("internal error: packed-ref cache cleared while locked"); 915 refs->packed = NULL; 916release_packed_ref_cache(packed_refs); 917} 918} 919 920static voidclear_loose_ref_cache(struct ref_cache *refs) 921{ 922if(refs->loose) { 923free_ref_entry(refs->loose); 924 refs->loose = NULL; 925} 926} 927 928/* 929 * Create a new submodule ref cache and add it to the internal 930 * set of caches. 931 */ 932static struct ref_cache *create_ref_cache(const char*submodule) 933{ 934struct ref_cache *refs; 935if(!submodule) 936 submodule =""; 937FLEX_ALLOC_STR(refs, name, submodule); 938 refs->next = submodule_ref_caches; 939 submodule_ref_caches = refs; 940return refs; 941} 942 943static struct ref_cache *lookup_ref_cache(const char*submodule) 944{ 945struct ref_cache *refs; 946 947if(!submodule || !*submodule) 948return&ref_cache; 949 950for(refs = submodule_ref_caches; refs; refs = refs->next) 951if(!strcmp(submodule, refs->name)) 952return refs; 953return NULL; 954} 955 956/* 957 * Return a pointer to a ref_cache for the specified submodule. For 958 * the main repository, use submodule==NULL. The returned structure 959 * will be allocated and initialized but not necessarily populated; it 960 * should not be freed. 961 */ 962static struct ref_cache *get_ref_cache(const char*submodule) 963{ 964struct ref_cache *refs =lookup_ref_cache(submodule); 965if(!refs) 966 refs =create_ref_cache(submodule); 967return refs; 968} 969 970/* The length of a peeled reference line in packed-refs, including EOL: */ 971#define PEELED_LINE_LENGTH 42 972 973/* 974 * The packed-refs header line that we write out. Perhaps other 975 * traits will be added later. The trailing space is required. 976 */ 977static const char PACKED_REFS_HEADER[] = 978"# pack-refs with: peeled fully-peeled\n"; 979 980/* 981 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 982 * Return a pointer to the refname within the line (null-terminated), 983 * or NULL if there was a problem. 984 */ 985static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1) 986{ 987const char*ref; 988 989/* 990 * 42: the answer to everything. 991 * 992 * In this case, it happens to be the answer to 993 * 40 (length of sha1 hex representation) 994 * +1 (space in between hex and name) 995 * +1 (newline at the end of the line) 996 */ 997if(line->len <=42) 998return NULL; 9991000if(get_sha1_hex(line->buf, sha1) <0)1001return NULL;1002if(!isspace(line->buf[40]))1003return NULL;10041005 ref = line->buf +41;1006if(isspace(*ref))1007return NULL;10081009if(line->buf[line->len -1] !='\n')1010return NULL;1011 line->buf[--line->len] =0;10121013return ref;1014}10151016/*1017 * Read f, which is a packed-refs file, into dir.1018 *1019 * A comment line of the form "# pack-refs with: " may contain zero or1020 * more traits. We interpret the traits as follows:1021 *1022 * No traits:1023 *1024 * Probably no references are peeled. But if the file contains a1025 * peeled value for a reference, we will use it.1026 *1027 * peeled:1028 *1029 * References under "refs/tags/", if they *can* be peeled, *are*1030 * peeled in this file. References outside of "refs/tags/" are1031 * probably not peeled even if they could have been, but if we find1032 * a peeled value for such a reference we will use it.1033 *1034 * fully-peeled:1035 *1036 * All references in the file that can be peeled are peeled.1037 * Inversely (and this is more important), any references in the1038 * file for which no peeled value is recorded is not peelable. This1039 * trait should typically be written alongside "peeled" for1040 * compatibility with older clients, but we do not require it1041 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1042 */1043static voidread_packed_refs(FILE*f,struct ref_dir *dir)1044{1045struct ref_entry *last = NULL;1046struct strbuf line = STRBUF_INIT;1047enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10481049while(strbuf_getwholeline(&line, f,'\n') != EOF) {1050unsigned char sha1[20];1051const char*refname;1052const char*traits;10531054if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1055if(strstr(traits," fully-peeled "))1056 peeled = PEELED_FULLY;1057else if(strstr(traits," peeled "))1058 peeled = PEELED_TAGS;1059/* perhaps other traits later as well */1060continue;1061}10621063 refname =parse_ref_line(&line, sha1);1064if(refname) {1065int flag = REF_ISPACKED;10661067if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1068if(!refname_is_safe(refname))1069die("packed refname is dangerous:%s", refname);1070hashclr(sha1);1071 flag |= REF_BAD_NAME | REF_ISBROKEN;1072}1073 last =create_ref_entry(refname, sha1, flag,0);1074if(peeled == PEELED_FULLY ||1075(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1076 last->flag |= REF_KNOWS_PEELED;1077add_ref(dir, last);1078continue;1079}1080if(last &&1081 line.buf[0] =='^'&&1082 line.len == PEELED_LINE_LENGTH &&1083 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1084!get_sha1_hex(line.buf +1, sha1)) {1085hashcpy(last->u.value.peeled.hash, sha1);1086/*1087 * Regardless of what the file header said,1088 * we definitely know the value of *this*1089 * reference:1090 */1091 last->flag |= REF_KNOWS_PEELED;1092}1093}10941095strbuf_release(&line);1096}10971098/*1099 * Get the packed_ref_cache for the specified ref_cache, creating it1100 * if necessary.1101 */1102static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1103{1104char*packed_refs_file;11051106if(*refs->name)1107 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1108else1109 packed_refs_file =git_pathdup("packed-refs");11101111if(refs->packed &&1112!stat_validity_check(&refs->packed->validity, packed_refs_file))1113clear_packed_ref_cache(refs);11141115if(!refs->packed) {1116FILE*f;11171118 refs->packed =xcalloc(1,sizeof(*refs->packed));1119acquire_packed_ref_cache(refs->packed);1120 refs->packed->root =create_dir_entry(refs,"",0,0);1121 f =fopen(packed_refs_file,"r");1122if(f) {1123stat_validity_update(&refs->packed->validity,fileno(f));1124read_packed_refs(f,get_ref_dir(refs->packed->root));1125fclose(f);1126}1127}1128free(packed_refs_file);1129return refs->packed;1130}11311132static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1133{1134returnget_ref_dir(packed_ref_cache->root);1135}11361137static struct ref_dir *get_packed_refs(struct ref_cache *refs)1138{1139returnget_packed_ref_dir(get_packed_ref_cache(refs));1140}11411142/*1143 * Add a reference to the in-memory packed reference cache. This may1144 * only be called while the packed-refs file is locked (see1145 * lock_packed_refs()). To actually write the packed-refs file, call1146 * commit_packed_refs().1147 */1148static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1149{1150struct packed_ref_cache *packed_ref_cache =1151get_packed_ref_cache(&ref_cache);11521153if(!packed_ref_cache->lock)1154die("internal error: packed refs not locked");1155add_ref(get_packed_ref_dir(packed_ref_cache),1156create_ref_entry(refname, sha1, REF_ISPACKED,1));1157}11581159/*1160 * Read the loose references from the namespace dirname into dir1161 * (without recursing). dirname must end with '/'. dir must be the1162 * directory entry corresponding to dirname.1163 */1164static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1165{1166struct ref_cache *refs = dir->ref_cache;1167DIR*d;1168struct dirent *de;1169int dirnamelen =strlen(dirname);1170struct strbuf refname;1171struct strbuf path = STRBUF_INIT;1172size_t path_baselen;11731174if(*refs->name)1175strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1176else1177strbuf_git_path(&path,"%s", dirname);1178 path_baselen = path.len;11791180 d =opendir(path.buf);1181if(!d) {1182strbuf_release(&path);1183return;1184}11851186strbuf_init(&refname, dirnamelen +257);1187strbuf_add(&refname, dirname, dirnamelen);11881189while((de =readdir(d)) != NULL) {1190unsigned char sha1[20];1191struct stat st;1192int flag;11931194if(de->d_name[0] =='.')1195continue;1196if(ends_with(de->d_name,".lock"))1197continue;1198strbuf_addstr(&refname, de->d_name);1199strbuf_addstr(&path, de->d_name);1200if(stat(path.buf, &st) <0) {1201;/* silently ignore */1202}else if(S_ISDIR(st.st_mode)) {1203strbuf_addch(&refname,'/');1204add_entry_to_dir(dir,1205create_dir_entry(refs, refname.buf,1206 refname.len,1));1207}else{1208int read_ok;12091210if(*refs->name) {1211hashclr(sha1);1212 flag =0;1213 read_ok = !resolve_gitlink_ref(refs->name,1214 refname.buf, sha1);1215}else{1216 read_ok = !read_ref_full(refname.buf,1217 RESOLVE_REF_READING,1218 sha1, &flag);1219}12201221if(!read_ok) {1222hashclr(sha1);1223 flag |= REF_ISBROKEN;1224}else if(is_null_sha1(sha1)) {1225/*1226 * It is so astronomically unlikely1227 * that NULL_SHA1 is the SHA-1 of an1228 * actual object that we consider its1229 * appearance in a loose reference1230 * file to be repo corruption1231 * (probably due to a software bug).1232 */1233 flag |= REF_ISBROKEN;1234}12351236if(check_refname_format(refname.buf,1237 REFNAME_ALLOW_ONELEVEL)) {1238if(!refname_is_safe(refname.buf))1239die("loose refname is dangerous:%s", refname.buf);1240hashclr(sha1);1241 flag |= REF_BAD_NAME | REF_ISBROKEN;1242}1243add_entry_to_dir(dir,1244create_ref_entry(refname.buf, sha1, flag,0));1245}1246strbuf_setlen(&refname, dirnamelen);1247strbuf_setlen(&path, path_baselen);1248}1249strbuf_release(&refname);1250strbuf_release(&path);1251closedir(d);1252}12531254static struct ref_dir *get_loose_refs(struct ref_cache *refs)1255{1256if(!refs->loose) {1257/*1258 * Mark the top-level directory complete because we1259 * are about to read the only subdirectory that can1260 * hold references:1261 */1262 refs->loose =create_dir_entry(refs,"",0,0);1263/*1264 * Create an incomplete entry for "refs/":1265 */1266add_entry_to_dir(get_ref_dir(refs->loose),1267create_dir_entry(refs,"refs/",5,1));1268}1269returnget_ref_dir(refs->loose);1270}12711272/* We allow "recursive" symbolic refs. Only within reason, though */1273#define MAXDEPTH 51274#define MAXREFLEN (1024)12751276/*1277 * Called by resolve_gitlink_ref_recursive() after it failed to read1278 * from the loose refs in ref_cache refs. Find <refname> in the1279 * packed-refs file for the submodule.1280 */1281static intresolve_gitlink_packed_ref(struct ref_cache *refs,1282const char*refname,unsigned char*sha1)1283{1284struct ref_entry *ref;1285struct ref_dir *dir =get_packed_refs(refs);12861287 ref =find_ref(dir, refname);1288if(ref == NULL)1289return-1;12901291hashcpy(sha1, ref->u.value.oid.hash);1292return0;1293}12941295static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1296const char*refname,unsigned char*sha1,1297int recursion)1298{1299int fd, len;1300char buffer[128], *p;1301char*path;13021303if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1304return-1;1305 path = *refs->name1306?git_pathdup_submodule(refs->name,"%s", refname)1307:git_pathdup("%s", refname);1308 fd =open(path, O_RDONLY);1309free(path);1310if(fd <0)1311returnresolve_gitlink_packed_ref(refs, refname, sha1);13121313 len =read(fd, buffer,sizeof(buffer)-1);1314close(fd);1315if(len <0)1316return-1;1317while(len &&isspace(buffer[len-1]))1318 len--;1319 buffer[len] =0;13201321/* Was it a detached head or an old-fashioned symlink? */1322if(!get_sha1_hex(buffer, sha1))1323return0;13241325/* Symref? */1326if(strncmp(buffer,"ref:",4))1327return-1;1328 p = buffer +4;1329while(isspace(*p))1330 p++;13311332returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1333}13341335intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1336{1337int len =strlen(path), retval;1338struct strbuf submodule = STRBUF_INIT;1339struct ref_cache *refs;13401341while(len && path[len-1] =='/')1342 len--;1343if(!len)1344return-1;13451346strbuf_add(&submodule, path, len);1347 refs =lookup_ref_cache(submodule.buf);1348if(!refs) {1349if(!is_nonbare_repository_dir(&submodule)) {1350strbuf_release(&submodule);1351return-1;1352}1353 refs =create_ref_cache(submodule.buf);1354}1355strbuf_release(&submodule);13561357 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1358return retval;1359}13601361/*1362 * Return the ref_entry for the given refname from the packed1363 * references. If it does not exist, return NULL.1364 */1365static struct ref_entry *get_packed_ref(const char*refname)1366{1367returnfind_ref(get_packed_refs(&ref_cache), refname);1368}13691370/*1371 * A loose ref file doesn't exist; check for a packed ref.1372 */1373static intresolve_missing_loose_ref(const char*refname,1374unsigned char*sha1,1375int*flags)1376{1377struct ref_entry *entry;13781379/*1380 * The loose reference file does not exist; check for a packed1381 * reference.1382 */1383 entry =get_packed_ref(refname);1384if(entry) {1385hashcpy(sha1, entry->u.value.oid.hash);1386if(flags)1387*flags |= REF_ISPACKED;1388return0;1389}1390/* refname is not a packed reference. */1391return-1;1392}13931394/* This function needs to return a meaningful errno on failure */1395static const char*resolve_ref_1(const char*refname,1396int resolve_flags,1397unsigned char*sha1,1398int*flags,1399struct strbuf *sb_refname,1400struct strbuf *sb_path,1401struct strbuf *sb_contents)1402{1403int bad_name =0;1404int symref_count;14051406if(flags)1407*flags =0;14081409if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1410if(flags)1411*flags |= REF_BAD_NAME;14121413if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1414!refname_is_safe(refname)) {1415 errno = EINVAL;1416return NULL;1417}1418/*1419 * dwim_ref() uses REF_ISBROKEN to distinguish between1420 * missing refs and refs that were present but invalid,1421 * to complain about the latter to stderr.1422 *1423 * We don't know whether the ref exists, so don't set1424 * REF_ISBROKEN yet.1425 */1426 bad_name =1;1427}14281429for(symref_count =0; symref_count < MAXDEPTH; symref_count++) {1430const char*path;1431struct stat st;1432char*buf;1433int fd;14341435strbuf_reset(sb_path);1436strbuf_git_path(sb_path,"%s", refname);1437 path = sb_path->buf;14381439/*1440 * We might have to loop back here to avoid a race1441 * condition: first we lstat() the file, then we try1442 * to read it as a link or as a file. But if somebody1443 * changes the type of the file (file <-> directory1444 * <-> symlink) between the lstat() and reading, then1445 * we don't want to report that as an error but rather1446 * try again starting with the lstat().1447 */1448 stat_ref:1449if(lstat(path, &st) <0) {1450if(errno != ENOENT)1451return NULL;1452if(resolve_missing_loose_ref(refname, sha1, flags)) {1453if(resolve_flags & RESOLVE_REF_READING) {1454 errno = ENOENT;1455return NULL;1456}1457hashclr(sha1);1458}1459if(bad_name) {1460hashclr(sha1);1461if(flags)1462*flags |= REF_ISBROKEN;1463}1464return refname;1465}14661467/* Follow "normalized" - ie "refs/.." symlinks by hand */1468if(S_ISLNK(st.st_mode)) {1469strbuf_reset(sb_contents);1470if(strbuf_readlink(sb_contents, path,0) <0) {1471if(errno == ENOENT || errno == EINVAL)1472/* inconsistent with lstat; retry */1473goto stat_ref;1474else1475return NULL;1476}1477if(starts_with(sb_contents->buf,"refs/") &&1478!check_refname_format(sb_contents->buf,0)) {1479strbuf_swap(sb_refname, sb_contents);1480 refname = sb_refname->buf;1481if(flags)1482*flags |= REF_ISSYMREF;1483if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1484hashclr(sha1);1485return refname;1486}1487continue;1488}1489}14901491/* Is it a directory? */1492if(S_ISDIR(st.st_mode)) {1493 errno = EISDIR;1494return NULL;1495}14961497/*1498 * Anything else, just open it and try to use it as1499 * a ref1500 */1501 fd =open(path, O_RDONLY);1502if(fd <0) {1503if(errno == ENOENT)1504/* inconsistent with lstat; retry */1505goto stat_ref;1506else1507return NULL;1508}1509strbuf_reset(sb_contents);1510if(strbuf_read(sb_contents, fd,256) <0) {1511int save_errno = errno;1512close(fd);1513 errno = save_errno;1514return NULL;1515}1516close(fd);1517strbuf_rtrim(sb_contents);15181519/*1520 * Is it a symbolic ref?1521 */1522if(!starts_with(sb_contents->buf,"ref:")) {1523/*1524 * Please note that FETCH_HEAD has a second1525 * line containing other data.1526 */1527if(get_sha1_hex(sb_contents->buf, sha1) ||1528(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1529if(flags)1530*flags |= REF_ISBROKEN;1531 errno = EINVAL;1532return NULL;1533}1534if(bad_name) {1535hashclr(sha1);1536if(flags)1537*flags |= REF_ISBROKEN;1538}1539return refname;1540}1541if(flags)1542*flags |= REF_ISSYMREF;1543 buf = sb_contents->buf +4;1544while(isspace(*buf))1545 buf++;1546strbuf_reset(sb_refname);1547strbuf_addstr(sb_refname, buf);1548 refname = sb_refname->buf;1549if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1550hashclr(sha1);1551return refname;1552}1553if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1554if(flags)1555*flags |= REF_ISBROKEN;15561557if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1558!refname_is_safe(buf)) {1559 errno = EINVAL;1560return NULL;1561}1562 bad_name =1;1563}1564}15651566 errno = ELOOP;1567return NULL;1568}15691570const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1571unsigned char*sha1,int*flags)1572{1573static struct strbuf sb_refname = STRBUF_INIT;1574struct strbuf sb_contents = STRBUF_INIT;1575struct strbuf sb_path = STRBUF_INIT;1576const char*ret;15771578 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1579&sb_refname, &sb_path, &sb_contents);1580strbuf_release(&sb_path);1581strbuf_release(&sb_contents);1582return ret;1583}15841585/*1586 * Peel the entry (if possible) and return its new peel_status. If1587 * repeel is true, re-peel the entry even if there is an old peeled1588 * value that is already stored in it.1589 *1590 * It is OK to call this function with a packed reference entry that1591 * might be stale and might even refer to an object that has since1592 * been garbage-collected. In such a case, if the entry has1593 * REF_KNOWS_PEELED then leave the status unchanged and return1594 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1595 */1596static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1597{1598enum peel_status status;15991600if(entry->flag & REF_KNOWS_PEELED) {1601if(repeel) {1602 entry->flag &= ~REF_KNOWS_PEELED;1603oidclr(&entry->u.value.peeled);1604}else{1605returnis_null_oid(&entry->u.value.peeled) ?1606 PEEL_NON_TAG : PEEL_PEELED;1607}1608}1609if(entry->flag & REF_ISBROKEN)1610return PEEL_BROKEN;1611if(entry->flag & REF_ISSYMREF)1612return PEEL_IS_SYMREF;16131614 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1615if(status == PEEL_PEELED || status == PEEL_NON_TAG)1616 entry->flag |= REF_KNOWS_PEELED;1617return status;1618}16191620intpeel_ref(const char*refname,unsigned char*sha1)1621{1622int flag;1623unsigned char base[20];16241625if(current_ref && (current_ref->name == refname1626|| !strcmp(current_ref->name, refname))) {1627if(peel_entry(current_ref,0))1628return-1;1629hashcpy(sha1, current_ref->u.value.peeled.hash);1630return0;1631}16321633if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1634return-1;16351636/*1637 * If the reference is packed, read its ref_entry from the1638 * cache in the hope that we already know its peeled value.1639 * We only try this optimization on packed references because1640 * (a) forcing the filling of the loose reference cache could1641 * be expensive and (b) loose references anyway usually do not1642 * have REF_KNOWS_PEELED.1643 */1644if(flag & REF_ISPACKED) {1645struct ref_entry *r =get_packed_ref(refname);1646if(r) {1647if(peel_entry(r,0))1648return-1;1649hashcpy(sha1, r->u.value.peeled.hash);1650return0;1651}1652}16531654returnpeel_object(base, sha1);1655}16561657/*1658 * Call fn for each reference in the specified ref_cache, omitting1659 * references not in the containing_dir of base. fn is called for all1660 * references, including broken ones. If fn ever returns a non-zero1661 * value, stop the iteration and return that value; otherwise, return1662 * 0.1663 */1664static intdo_for_each_entry(struct ref_cache *refs,const char*base,1665 each_ref_entry_fn fn,void*cb_data)1666{1667struct packed_ref_cache *packed_ref_cache;1668struct ref_dir *loose_dir;1669struct ref_dir *packed_dir;1670int retval =0;16711672/*1673 * We must make sure that all loose refs are read before accessing the1674 * packed-refs file; this avoids a race condition in which loose refs1675 * are migrated to the packed-refs file by a simultaneous process, but1676 * our in-memory view is from before the migration. get_packed_ref_cache()1677 * takes care of making sure our view is up to date with what is on1678 * disk.1679 */1680 loose_dir =get_loose_refs(refs);1681if(base && *base) {1682 loose_dir =find_containing_dir(loose_dir, base,0);1683}1684if(loose_dir)1685prime_ref_dir(loose_dir);16861687 packed_ref_cache =get_packed_ref_cache(refs);1688acquire_packed_ref_cache(packed_ref_cache);1689 packed_dir =get_packed_ref_dir(packed_ref_cache);1690if(base && *base) {1691 packed_dir =find_containing_dir(packed_dir, base,0);1692}16931694if(packed_dir && loose_dir) {1695sort_ref_dir(packed_dir);1696sort_ref_dir(loose_dir);1697 retval =do_for_each_entry_in_dirs(1698 packed_dir, loose_dir, fn, cb_data);1699}else if(packed_dir) {1700sort_ref_dir(packed_dir);1701 retval =do_for_each_entry_in_dir(1702 packed_dir,0, fn, cb_data);1703}else if(loose_dir) {1704sort_ref_dir(loose_dir);1705 retval =do_for_each_entry_in_dir(1706 loose_dir,0, fn, cb_data);1707}17081709release_packed_ref_cache(packed_ref_cache);1710return retval;1711}17121713/*1714 * Call fn for each reference in the specified ref_cache for which the1715 * refname begins with base. If trim is non-zero, then trim that many1716 * characters off the beginning of each refname before passing the1717 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1718 * broken references in the iteration. If fn ever returns a non-zero1719 * value, stop the iteration and return that value; otherwise, return1720 * 0.1721 */1722intdo_for_each_ref(const char*submodule,const char*base,1723 each_ref_fn fn,int trim,int flags,void*cb_data)1724{1725struct ref_entry_cb data;1726struct ref_cache *refs;17271728 refs =get_ref_cache(submodule);1729 data.base = base;1730 data.trim = trim;1731 data.flags = flags;1732 data.fn = fn;1733 data.cb_data = cb_data;17341735if(ref_paranoia <0)1736 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1737if(ref_paranoia)1738 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;17391740returndo_for_each_entry(refs, base, do_one_ref, &data);1741}17421743static voidunlock_ref(struct ref_lock *lock)1744{1745/* Do not free lock->lk -- atexit() still looks at them */1746if(lock->lk)1747rollback_lock_file(lock->lk);1748free(lock->ref_name);1749free(lock->orig_ref_name);1750free(lock);1751}17521753/*1754 * Verify that the reference locked by lock has the value old_sha1.1755 * Fail if the reference doesn't exist and mustexist is set. Return 01756 * on success. On error, write an error message to err, set errno, and1757 * return a negative value.1758 */1759static intverify_lock(struct ref_lock *lock,1760const unsigned char*old_sha1,int mustexist,1761struct strbuf *err)1762{1763assert(err);17641765if(read_ref_full(lock->ref_name,1766 mustexist ? RESOLVE_REF_READING :0,1767 lock->old_oid.hash, NULL)) {1768if(old_sha1) {1769int save_errno = errno;1770strbuf_addf(err,"can't verify ref%s", lock->ref_name);1771 errno = save_errno;1772return-1;1773}else{1774hashclr(lock->old_oid.hash);1775return0;1776}1777}1778if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1779strbuf_addf(err,"ref%sis at%sbut expected%s",1780 lock->ref_name,1781sha1_to_hex(lock->old_oid.hash),1782sha1_to_hex(old_sha1));1783 errno = EBUSY;1784return-1;1785}1786return0;1787}17881789static intremove_empty_directories(struct strbuf *path)1790{1791/*1792 * we want to create a file but there is a directory there;1793 * if that is an empty directory (or a directory that contains1794 * only empty directories), remove them.1795 */1796returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1797}17981799/*1800 * Locks a ref returning the lock on success and NULL on failure.1801 * On failure errno is set to something meaningful.1802 */1803static struct ref_lock *lock_ref_sha1_basic(const char*refname,1804const unsigned char*old_sha1,1805const struct string_list *extras,1806const struct string_list *skip,1807unsigned int flags,int*type_p,1808struct strbuf *err)1809{1810struct strbuf ref_file = STRBUF_INIT;1811struct strbuf orig_ref_file = STRBUF_INIT;1812const char*orig_refname = refname;1813struct ref_lock *lock;1814int last_errno =0;1815int type;1816int lflags =0;1817int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1818int resolve_flags =0;1819int attempts_remaining =3;18201821assert(err);18221823 lock =xcalloc(1,sizeof(struct ref_lock));18241825if(mustexist)1826 resolve_flags |= RESOLVE_REF_READING;1827if(flags & REF_DELETING)1828 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1829if(flags & REF_NODEREF) {1830 resolve_flags |= RESOLVE_REF_NO_RECURSE;1831 lflags |= LOCK_NO_DEREF;1832}18331834 refname =resolve_ref_unsafe(refname, resolve_flags,1835 lock->old_oid.hash, &type);1836if(!refname && errno == EISDIR) {1837/*1838 * we are trying to lock foo but we used to1839 * have foo/bar which now does not exist;1840 * it is normal for the empty directory 'foo'1841 * to remain.1842 */1843strbuf_git_path(&orig_ref_file,"%s", orig_refname);1844if(remove_empty_directories(&orig_ref_file)) {1845 last_errno = errno;1846if(!verify_refname_available_dir(orig_refname, extras, skip,1847get_loose_refs(&ref_cache), err))1848strbuf_addf(err,"there are still refs under '%s'",1849 orig_refname);1850goto error_return;1851}1852 refname =resolve_ref_unsafe(orig_refname, resolve_flags,1853 lock->old_oid.hash, &type);1854}1855if(type_p)1856*type_p = type;1857if(!refname) {1858 last_errno = errno;1859if(last_errno != ENOTDIR ||1860!verify_refname_available_dir(orig_refname, extras, skip,1861get_loose_refs(&ref_cache), err))1862strbuf_addf(err,"unable to resolve reference%s:%s",1863 orig_refname,strerror(last_errno));18641865goto error_return;1866}18671868if(flags & REF_NODEREF)1869 refname = orig_refname;18701871/*1872 * If the ref did not exist and we are creating it, make sure1873 * there is no existing packed ref whose name begins with our1874 * refname, nor a packed ref whose name is a proper prefix of1875 * our refname.1876 */1877if(is_null_oid(&lock->old_oid) &&1878verify_refname_available_dir(refname, extras, skip,1879get_packed_refs(&ref_cache), err)) {1880 last_errno = ENOTDIR;1881goto error_return;1882}18831884 lock->lk =xcalloc(1,sizeof(struct lock_file));18851886 lock->ref_name =xstrdup(refname);1887 lock->orig_ref_name =xstrdup(orig_refname);1888strbuf_git_path(&ref_file,"%s", refname);18891890 retry:1891switch(safe_create_leading_directories_const(ref_file.buf)) {1892case SCLD_OK:1893break;/* success */1894case SCLD_VANISHED:1895if(--attempts_remaining >0)1896goto retry;1897/* fall through */1898default:1899 last_errno = errno;1900strbuf_addf(err,"unable to create directory for%s",1901 ref_file.buf);1902goto error_return;1903}19041905if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {1906 last_errno = errno;1907if(errno == ENOENT && --attempts_remaining >0)1908/*1909 * Maybe somebody just deleted one of the1910 * directories leading to ref_file. Try1911 * again:1912 */1913goto retry;1914else{1915unable_to_lock_message(ref_file.buf, errno, err);1916goto error_return;1917}1918}1919if(verify_lock(lock, old_sha1, mustexist, err)) {1920 last_errno = errno;1921goto error_return;1922}1923goto out;19241925 error_return:1926unlock_ref(lock);1927 lock = NULL;19281929 out:1930strbuf_release(&ref_file);1931strbuf_release(&orig_ref_file);1932 errno = last_errno;1933return lock;1934}19351936/*1937 * Write an entry to the packed-refs file for the specified refname.1938 * If peeled is non-NULL, write it as the entry's peeled value.1939 */1940static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,1941unsigned char*peeled)1942{1943fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1944if(peeled)1945fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1946}19471948/*1949 * An each_ref_entry_fn that writes the entry to a packed-refs file.1950 */1951static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)1952{1953enum peel_status peel_status =peel_entry(entry,0);19541955if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1956error("internal error:%sis not a valid packed reference!",1957 entry->name);1958write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,1959 peel_status == PEEL_PEELED ?1960 entry->u.value.peeled.hash : NULL);1961return0;1962}19631964/*1965 * Lock the packed-refs file for writing. Flags is passed to1966 * hold_lock_file_for_update(). Return 0 on success. On errors, set1967 * errno appropriately and return a nonzero value.1968 */1969static intlock_packed_refs(int flags)1970{1971static int timeout_configured =0;1972static int timeout_value =1000;19731974struct packed_ref_cache *packed_ref_cache;19751976if(!timeout_configured) {1977git_config_get_int("core.packedrefstimeout", &timeout_value);1978 timeout_configured =1;1979}19801981if(hold_lock_file_for_update_timeout(1982&packlock,git_path("packed-refs"),1983 flags, timeout_value) <0)1984return-1;1985/*1986 * Get the current packed-refs while holding the lock. If the1987 * packed-refs file has been modified since we last read it,1988 * this will automatically invalidate the cache and re-read1989 * the packed-refs file.1990 */1991 packed_ref_cache =get_packed_ref_cache(&ref_cache);1992 packed_ref_cache->lock = &packlock;1993/* Increment the reference count to prevent it from being freed: */1994acquire_packed_ref_cache(packed_ref_cache);1995return0;1996}19971998/*1999 * Write the current version of the packed refs cache from memory to2000 * disk. The packed-refs file must already be locked for writing (see2001 * lock_packed_refs()). Return zero on success. On errors, set errno2002 * and return a nonzero value2003 */2004static intcommit_packed_refs(void)2005{2006struct packed_ref_cache *packed_ref_cache =2007get_packed_ref_cache(&ref_cache);2008int error =0;2009int save_errno =0;2010FILE*out;20112012if(!packed_ref_cache->lock)2013die("internal error: packed-refs not locked");20142015 out =fdopen_lock_file(packed_ref_cache->lock,"w");2016if(!out)2017die_errno("unable to fdopen packed-refs descriptor");20182019fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2020do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),20210, write_packed_entry_fn, out);20222023if(commit_lock_file(packed_ref_cache->lock)) {2024 save_errno = errno;2025 error = -1;2026}2027 packed_ref_cache->lock = NULL;2028release_packed_ref_cache(packed_ref_cache);2029 errno = save_errno;2030return error;2031}20322033/*2034 * Rollback the lockfile for the packed-refs file, and discard the2035 * in-memory packed reference cache. (The packed-refs file will be2036 * read anew if it is needed again after this function is called.)2037 */2038static voidrollback_packed_refs(void)2039{2040struct packed_ref_cache *packed_ref_cache =2041get_packed_ref_cache(&ref_cache);20422043if(!packed_ref_cache->lock)2044die("internal error: packed-refs not locked");2045rollback_lock_file(packed_ref_cache->lock);2046 packed_ref_cache->lock = NULL;2047release_packed_ref_cache(packed_ref_cache);2048clear_packed_ref_cache(&ref_cache);2049}20502051struct ref_to_prune {2052struct ref_to_prune *next;2053unsigned char sha1[20];2054char name[FLEX_ARRAY];2055};20562057struct pack_refs_cb_data {2058unsigned int flags;2059struct ref_dir *packed_refs;2060struct ref_to_prune *ref_to_prune;2061};20622063/*2064 * An each_ref_entry_fn that is run over loose references only. If2065 * the loose reference can be packed, add an entry in the packed ref2066 * cache. If the reference should be pruned, also add it to2067 * ref_to_prune in the pack_refs_cb_data.2068 */2069static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2070{2071struct pack_refs_cb_data *cb = cb_data;2072enum peel_status peel_status;2073struct ref_entry *packed_entry;2074int is_tag_ref =starts_with(entry->name,"refs/tags/");20752076/* Do not pack per-worktree refs: */2077if(ref_type(entry->name) != REF_TYPE_NORMAL)2078return0;20792080/* ALWAYS pack tags */2081if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2082return0;20832084/* Do not pack symbolic or broken refs: */2085if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2086return0;20872088/* Add a packed ref cache entry equivalent to the loose entry. */2089 peel_status =peel_entry(entry,1);2090if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2091die("internal error peeling reference%s(%s)",2092 entry->name,oid_to_hex(&entry->u.value.oid));2093 packed_entry =find_ref(cb->packed_refs, entry->name);2094if(packed_entry) {2095/* Overwrite existing packed entry with info from loose entry */2096 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2097oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2098}else{2099 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2100 REF_ISPACKED | REF_KNOWS_PEELED,0);2101add_ref(cb->packed_refs, packed_entry);2102}2103oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);21042105/* Schedule the loose reference for pruning if requested. */2106if((cb->flags & PACK_REFS_PRUNE)) {2107struct ref_to_prune *n;2108FLEX_ALLOC_STR(n, name, entry->name);2109hashcpy(n->sha1, entry->u.value.oid.hash);2110 n->next = cb->ref_to_prune;2111 cb->ref_to_prune = n;2112}2113return0;2114}21152116/*2117 * Remove empty parents, but spare refs/ and immediate subdirs.2118 * Note: munges *name.2119 */2120static voidtry_remove_empty_parents(char*name)2121{2122char*p, *q;2123int i;2124 p = name;2125for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2126while(*p && *p !='/')2127 p++;2128/* tolerate duplicate slashes; see check_refname_format() */2129while(*p =='/')2130 p++;2131}2132for(q = p; *q; q++)2133;2134while(1) {2135while(q > p && *q !='/')2136 q--;2137while(q > p && *(q-1) =='/')2138 q--;2139if(q == p)2140break;2141*q ='\0';2142if(rmdir(git_path("%s", name)))2143break;2144}2145}21462147/* make sure nobody touched the ref, and unlink */2148static voidprune_ref(struct ref_to_prune *r)2149{2150struct ref_transaction *transaction;2151struct strbuf err = STRBUF_INIT;21522153if(check_refname_format(r->name,0))2154return;21552156 transaction =ref_transaction_begin(&err);2157if(!transaction ||2158ref_transaction_delete(transaction, r->name, r->sha1,2159 REF_ISPRUNING, NULL, &err) ||2160ref_transaction_commit(transaction, &err)) {2161ref_transaction_free(transaction);2162error("%s", err.buf);2163strbuf_release(&err);2164return;2165}2166ref_transaction_free(transaction);2167strbuf_release(&err);2168try_remove_empty_parents(r->name);2169}21702171static voidprune_refs(struct ref_to_prune *r)2172{2173while(r) {2174prune_ref(r);2175 r = r->next;2176}2177}21782179intpack_refs(unsigned int flags)2180{2181struct pack_refs_cb_data cbdata;21822183memset(&cbdata,0,sizeof(cbdata));2184 cbdata.flags = flags;21852186lock_packed_refs(LOCK_DIE_ON_ERROR);2187 cbdata.packed_refs =get_packed_refs(&ref_cache);21882189do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2190 pack_if_possible_fn, &cbdata);21912192if(commit_packed_refs())2193die_errno("unable to overwrite old ref-pack file");21942195prune_refs(cbdata.ref_to_prune);2196return0;2197}21982199/*2200 * Rewrite the packed-refs file, omitting any refs listed in2201 * 'refnames'. On error, leave packed-refs unchanged, write an error2202 * message to 'err', and return a nonzero value.2203 *2204 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2205 */2206static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2207{2208struct ref_dir *packed;2209struct string_list_item *refname;2210int ret, needs_repacking =0, removed =0;22112212assert(err);22132214/* Look for a packed ref */2215for_each_string_list_item(refname, refnames) {2216if(get_packed_ref(refname->string)) {2217 needs_repacking =1;2218break;2219}2220}22212222/* Avoid locking if we have nothing to do */2223if(!needs_repacking)2224return0;/* no refname exists in packed refs */22252226if(lock_packed_refs(0)) {2227unable_to_lock_message(git_path("packed-refs"), errno, err);2228return-1;2229}2230 packed =get_packed_refs(&ref_cache);22312232/* Remove refnames from the cache */2233for_each_string_list_item(refname, refnames)2234if(remove_entry(packed, refname->string) != -1)2235 removed =1;2236if(!removed) {2237/*2238 * All packed entries disappeared while we were2239 * acquiring the lock.2240 */2241rollback_packed_refs();2242return0;2243}22442245/* Write what remains */2246 ret =commit_packed_refs();2247if(ret)2248strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2249strerror(errno));2250return ret;2251}22522253static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2254{2255assert(err);22562257if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2258/*2259 * loose. The loose file name is the same as the2260 * lockfile name, minus ".lock":2261 */2262char*loose_filename =get_locked_file_path(lock->lk);2263int res =unlink_or_msg(loose_filename, err);2264free(loose_filename);2265if(res)2266return1;2267}2268return0;2269}22702271intdelete_refs(struct string_list *refnames)2272{2273struct strbuf err = STRBUF_INIT;2274int i, result =0;22752276if(!refnames->nr)2277return0;22782279 result =repack_without_refs(refnames, &err);2280if(result) {2281/*2282 * If we failed to rewrite the packed-refs file, then2283 * it is unsafe to try to remove loose refs, because2284 * doing so might expose an obsolete packed value for2285 * a reference that might even point at an object that2286 * has been garbage collected.2287 */2288if(refnames->nr ==1)2289error(_("could not delete reference%s:%s"),2290 refnames->items[0].string, err.buf);2291else2292error(_("could not delete references:%s"), err.buf);22932294goto out;2295}22962297for(i =0; i < refnames->nr; i++) {2298const char*refname = refnames->items[i].string;22992300if(delete_ref(refname, NULL,0))2301 result |=error(_("could not remove reference%s"), refname);2302}23032304out:2305strbuf_release(&err);2306return result;2307}23082309/*2310 * People using contrib's git-new-workdir have .git/logs/refs ->2311 * /some/other/path/.git/logs/refs, and that may live on another device.2312 *2313 * IOW, to avoid cross device rename errors, the temporary renamed log must2314 * live into logs/refs.2315 */2316#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"23172318static intrename_tmp_log(const char*newrefname)2319{2320int attempts_remaining =4;2321struct strbuf path = STRBUF_INIT;2322int ret = -1;23232324 retry:2325strbuf_reset(&path);2326strbuf_git_path(&path,"logs/%s", newrefname);2327switch(safe_create_leading_directories_const(path.buf)) {2328case SCLD_OK:2329break;/* success */2330case SCLD_VANISHED:2331if(--attempts_remaining >0)2332goto retry;2333/* fall through */2334default:2335error("unable to create directory for%s", newrefname);2336goto out;2337}23382339if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2340if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2341/*2342 * rename(a, b) when b is an existing2343 * directory ought to result in ISDIR, but2344 * Solaris 5.8 gives ENOTDIR. Sheesh.2345 */2346if(remove_empty_directories(&path)) {2347error("Directory not empty: logs/%s", newrefname);2348goto out;2349}2350goto retry;2351}else if(errno == ENOENT && --attempts_remaining >0) {2352/*2353 * Maybe another process just deleted one of2354 * the directories in the path to newrefname.2355 * Try again from the beginning.2356 */2357goto retry;2358}else{2359error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2360 newrefname,strerror(errno));2361goto out;2362}2363}2364 ret =0;2365out:2366strbuf_release(&path);2367return ret;2368}23692370intverify_refname_available(const char*newname,2371struct string_list *extras,2372struct string_list *skip,2373struct strbuf *err)2374{2375struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2376struct ref_dir *loose_refs =get_loose_refs(&ref_cache);23772378if(verify_refname_available_dir(newname, extras, skip,2379 packed_refs, err) ||2380verify_refname_available_dir(newname, extras, skip,2381 loose_refs, err))2382return-1;23832384return0;2385}23862387static intwrite_ref_to_lockfile(struct ref_lock *lock,2388const unsigned char*sha1,struct strbuf *err);2389static intcommit_ref_update(struct ref_lock *lock,2390const unsigned char*sha1,const char*logmsg,2391int flags,struct strbuf *err);23922393intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2394{2395unsigned char sha1[20], orig_sha1[20];2396int flag =0, logmoved =0;2397struct ref_lock *lock;2398struct stat loginfo;2399int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2400const char*symref = NULL;2401struct strbuf err = STRBUF_INIT;24022403if(log &&S_ISLNK(loginfo.st_mode))2404returnerror("reflog for%sis a symlink", oldrefname);24052406 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2407 orig_sha1, &flag);2408if(flag & REF_ISSYMREF)2409returnerror("refname%sis a symbolic ref, renaming it is not supported",2410 oldrefname);2411if(!symref)2412returnerror("refname%snot found", oldrefname);24132414if(!rename_ref_available(oldrefname, newrefname))2415return1;24162417if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2418returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2419 oldrefname,strerror(errno));24202421if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2422error("unable to delete old%s", oldrefname);2423goto rollback;2424}24252426if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2427delete_ref(newrefname, sha1, REF_NODEREF)) {2428if(errno==EISDIR) {2429struct strbuf path = STRBUF_INIT;2430int result;24312432strbuf_git_path(&path,"%s", newrefname);2433 result =remove_empty_directories(&path);2434strbuf_release(&path);24352436if(result) {2437error("Directory not empty:%s", newrefname);2438goto rollback;2439}2440}else{2441error("unable to delete existing%s", newrefname);2442goto rollback;2443}2444}24452446if(log &&rename_tmp_log(newrefname))2447goto rollback;24482449 logmoved = log;24502451 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2452if(!lock) {2453error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2454strbuf_release(&err);2455goto rollback;2456}2457hashcpy(lock->old_oid.hash, orig_sha1);24582459if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2460commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2461error("unable to write current sha1 into%s:%s", newrefname, err.buf);2462strbuf_release(&err);2463goto rollback;2464}24652466return0;24672468 rollback:2469 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2470if(!lock) {2471error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2472strbuf_release(&err);2473goto rollbacklog;2474}24752476 flag = log_all_ref_updates;2477 log_all_ref_updates =0;2478if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2479commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2480error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2481strbuf_release(&err);2482}2483 log_all_ref_updates = flag;24842485 rollbacklog:2486if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2487error("unable to restore logfile%sfrom%s:%s",2488 oldrefname, newrefname,strerror(errno));2489if(!logmoved && log &&2490rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2491error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2492 oldrefname,strerror(errno));24932494return1;2495}24962497static intclose_ref(struct ref_lock *lock)2498{2499if(close_lock_file(lock->lk))2500return-1;2501return0;2502}25032504static intcommit_ref(struct ref_lock *lock)2505{2506if(commit_lock_file(lock->lk))2507return-1;2508return0;2509}25102511/*2512 * Create a reflog for a ref. If force_create = 0, the reflog will2513 * only be created for certain refs (those for which2514 * should_autocreate_reflog returns non-zero. Otherwise, create it2515 * regardless of the ref name. Fill in *err and return -1 on failure.2516 */2517static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2518{2519int logfd, oflags = O_APPEND | O_WRONLY;25202521strbuf_git_path(logfile,"logs/%s", refname);2522if(force_create ||should_autocreate_reflog(refname)) {2523if(safe_create_leading_directories(logfile->buf) <0) {2524strbuf_addf(err,"unable to create directory for%s: "2525"%s", logfile->buf,strerror(errno));2526return-1;2527}2528 oflags |= O_CREAT;2529}25302531 logfd =open(logfile->buf, oflags,0666);2532if(logfd <0) {2533if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2534return0;25352536if(errno == EISDIR) {2537if(remove_empty_directories(logfile)) {2538strbuf_addf(err,"There are still logs under "2539"'%s'", logfile->buf);2540return-1;2541}2542 logfd =open(logfile->buf, oflags,0666);2543}25442545if(logfd <0) {2546strbuf_addf(err,"unable to append to%s:%s",2547 logfile->buf,strerror(errno));2548return-1;2549}2550}25512552adjust_shared_perm(logfile->buf);2553close(logfd);2554return0;2555}255625572558intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2559{2560int ret;2561struct strbuf sb = STRBUF_INIT;25622563 ret =log_ref_setup(refname, &sb, err, force_create);2564strbuf_release(&sb);2565return ret;2566}25672568static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2569const unsigned char*new_sha1,2570const char*committer,const char*msg)2571{2572int msglen, written;2573unsigned maxlen, len;2574char*logrec;25752576 msglen = msg ?strlen(msg) :0;2577 maxlen =strlen(committer) + msglen +100;2578 logrec =xmalloc(maxlen);2579 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2580sha1_to_hex(old_sha1),2581sha1_to_hex(new_sha1),2582 committer);2583if(msglen)2584 len +=copy_reflog_msg(logrec + len -1, msg) -1;25852586 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2587free(logrec);2588if(written != len)2589return-1;25902591return0;2592}25932594static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2595const unsigned char*new_sha1,const char*msg,2596struct strbuf *logfile,int flags,2597struct strbuf *err)2598{2599int logfd, result, oflags = O_APPEND | O_WRONLY;26002601if(log_all_ref_updates <0)2602 log_all_ref_updates = !is_bare_repository();26032604 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);26052606if(result)2607return result;26082609 logfd =open(logfile->buf, oflags);2610if(logfd <0)2611return0;2612 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2613git_committer_info(0), msg);2614if(result) {2615strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2616strerror(errno));2617close(logfd);2618return-1;2619}2620if(close(logfd)) {2621strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2622strerror(errno));2623return-1;2624}2625return0;2626}26272628static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2629const unsigned char*new_sha1,const char*msg,2630int flags,struct strbuf *err)2631{2632returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2633 err);2634}26352636intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2637const unsigned char*new_sha1,const char*msg,2638int flags,struct strbuf *err)2639{2640struct strbuf sb = STRBUF_INIT;2641int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2642 err);2643strbuf_release(&sb);2644return ret;2645}26462647/*2648 * Write sha1 into the open lockfile, then close the lockfile. On2649 * errors, rollback the lockfile, fill in *err and2650 * return -1.2651 */2652static intwrite_ref_to_lockfile(struct ref_lock *lock,2653const unsigned char*sha1,struct strbuf *err)2654{2655static char term ='\n';2656struct object *o;2657int fd;26582659 o =parse_object(sha1);2660if(!o) {2661strbuf_addf(err,2662"Trying to write ref%swith nonexistent object%s",2663 lock->ref_name,sha1_to_hex(sha1));2664unlock_ref(lock);2665return-1;2666}2667if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2668strbuf_addf(err,2669"Trying to write non-commit object%sto branch%s",2670sha1_to_hex(sha1), lock->ref_name);2671unlock_ref(lock);2672return-1;2673}2674 fd =get_lock_file_fd(lock->lk);2675if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2676write_in_full(fd, &term,1) !=1||2677close_ref(lock) <0) {2678strbuf_addf(err,2679"Couldn't write%s",get_lock_file_path(lock->lk));2680unlock_ref(lock);2681return-1;2682}2683return0;2684}26852686/*2687 * Commit a change to a loose reference that has already been written2688 * to the loose reference lockfile. Also update the reflogs if2689 * necessary, using the specified lockmsg (which can be NULL).2690 */2691static intcommit_ref_update(struct ref_lock *lock,2692const unsigned char*sha1,const char*logmsg,2693int flags,struct strbuf *err)2694{2695clear_loose_ref_cache(&ref_cache);2696if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2697(strcmp(lock->ref_name, lock->orig_ref_name) &&2698log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2699char*old_msg =strbuf_detach(err, NULL);2700strbuf_addf(err,"Cannot update the ref '%s':%s",2701 lock->ref_name, old_msg);2702free(old_msg);2703unlock_ref(lock);2704return-1;2705}2706if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2707/*2708 * Special hack: If a branch is updated directly and HEAD2709 * points to it (may happen on the remote side of a push2710 * for example) then logically the HEAD reflog should be2711 * updated too.2712 * A generic solution implies reverse symref information,2713 * but finding all symrefs pointing to the given branch2714 * would be rather costly for this rare event (the direct2715 * update of a branch) to be worth it. So let's cheat and2716 * check with HEAD only which should cover 99% of all usage2717 * scenarios (even 100% of the default ones).2718 */2719unsigned char head_sha1[20];2720int head_flag;2721const char*head_ref;2722 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2723 head_sha1, &head_flag);2724if(head_ref && (head_flag & REF_ISSYMREF) &&2725!strcmp(head_ref, lock->ref_name)) {2726struct strbuf log_err = STRBUF_INIT;2727if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2728 logmsg,0, &log_err)) {2729error("%s", log_err.buf);2730strbuf_release(&log_err);2731}2732}2733}2734if(commit_ref(lock)) {2735error("Couldn't set%s", lock->ref_name);2736unlock_ref(lock);2737return-1;2738}27392740unlock_ref(lock);2741return0;2742}27432744static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2745{2746int ret = -1;2747#ifndef NO_SYMLINK_HEAD2748char*ref_path =get_locked_file_path(lock->lk);2749unlink(ref_path);2750 ret =symlink(target, ref_path);2751free(ref_path);27522753if(ret)2754fprintf(stderr,"no symlink - falling back to symbolic ref\n");2755#endif2756return ret;2757}27582759static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2760const char*target,const char*logmsg)2761{2762struct strbuf err = STRBUF_INIT;2763unsigned char new_sha1[20];2764if(logmsg && !read_ref(target, new_sha1) &&2765log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2766error("%s", err.buf);2767strbuf_release(&err);2768}2769}27702771static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2772const char*target,const char*logmsg)2773{2774if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2775update_symref_reflog(lock, refname, target, logmsg);2776return0;2777}27782779if(!fdopen_lock_file(lock->lk,"w"))2780returnerror("unable to fdopen%s:%s",2781 lock->lk->tempfile.filename.buf,strerror(errno));27822783update_symref_reflog(lock, refname, target, logmsg);27842785/* no error check; commit_ref will check ferror */2786fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2787if(commit_ref(lock) <0)2788returnerror("unable to write symref for%s:%s", refname,2789strerror(errno));2790return0;2791}27922793intcreate_symref(const char*refname,const char*target,const char*logmsg)2794{2795struct strbuf err = STRBUF_INIT;2796struct ref_lock *lock;2797int ret;27982799 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2800&err);2801if(!lock) {2802error("%s", err.buf);2803strbuf_release(&err);2804return-1;2805}28062807 ret =create_symref_locked(lock, refname, target, logmsg);2808unlock_ref(lock);2809return ret;2810}28112812intreflog_exists(const char*refname)2813{2814struct stat st;28152816return!lstat(git_path("logs/%s", refname), &st) &&2817S_ISREG(st.st_mode);2818}28192820intdelete_reflog(const char*refname)2821{2822returnremove_path(git_path("logs/%s", refname));2823}28242825static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2826{2827unsigned char osha1[20], nsha1[20];2828char*email_end, *message;2829unsigned long timestamp;2830int tz;28312832/* old SP new SP name <email> SP time TAB msg LF */2833if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2834get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2835get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2836!(email_end =strchr(sb->buf +82,'>')) ||2837 email_end[1] !=' '||2838!(timestamp =strtoul(email_end +2, &message,10)) ||2839!message || message[0] !=' '||2840(message[1] !='+'&& message[1] !='-') ||2841!isdigit(message[2]) || !isdigit(message[3]) ||2842!isdigit(message[4]) || !isdigit(message[5]))2843return0;/* corrupt? */2844 email_end[1] ='\0';2845 tz =strtol(message +1, NULL,10);2846if(message[6] !='\t')2847 message +=6;2848else2849 message +=7;2850returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2851}28522853static char*find_beginning_of_line(char*bob,char*scan)2854{2855while(bob < scan && *(--scan) !='\n')2856;/* keep scanning backwards */2857/*2858 * Return either beginning of the buffer, or LF at the end of2859 * the previous line.2860 */2861return scan;2862}28632864intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2865{2866struct strbuf sb = STRBUF_INIT;2867FILE*logfp;2868long pos;2869int ret =0, at_tail =1;28702871 logfp =fopen(git_path("logs/%s", refname),"r");2872if(!logfp)2873return-1;28742875/* Jump to the end */2876if(fseek(logfp,0, SEEK_END) <0)2877returnerror("cannot seek back reflog for%s:%s",2878 refname,strerror(errno));2879 pos =ftell(logfp);2880while(!ret &&0< pos) {2881int cnt;2882size_t nread;2883char buf[BUFSIZ];2884char*endp, *scanp;28852886/* Fill next block from the end */2887 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2888if(fseek(logfp, pos - cnt, SEEK_SET))2889returnerror("cannot seek back reflog for%s:%s",2890 refname,strerror(errno));2891 nread =fread(buf, cnt,1, logfp);2892if(nread !=1)2893returnerror("cannot read%dbytes from reflog for%s:%s",2894 cnt, refname,strerror(errno));2895 pos -= cnt;28962897 scanp = endp = buf + cnt;2898if(at_tail && scanp[-1] =='\n')2899/* Looking at the final LF at the end of the file */2900 scanp--;2901 at_tail =0;29022903while(buf < scanp) {2904/*2905 * terminating LF of the previous line, or the beginning2906 * of the buffer.2907 */2908char*bp;29092910 bp =find_beginning_of_line(buf, scanp);29112912if(*bp =='\n') {2913/*2914 * The newline is the end of the previous line,2915 * so we know we have complete line starting2916 * at (bp + 1). Prefix it onto any prior data2917 * we collected for the line and process it.2918 */2919strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2920 scanp = bp;2921 endp = bp +1;2922 ret =show_one_reflog_ent(&sb, fn, cb_data);2923strbuf_reset(&sb);2924if(ret)2925break;2926}else if(!pos) {2927/*2928 * We are at the start of the buffer, and the2929 * start of the file; there is no previous2930 * line, and we have everything for this one.2931 * Process it, and we can end the loop.2932 */2933strbuf_splice(&sb,0,0, buf, endp - buf);2934 ret =show_one_reflog_ent(&sb, fn, cb_data);2935strbuf_reset(&sb);2936break;2937}29382939if(bp == buf) {2940/*2941 * We are at the start of the buffer, and there2942 * is more file to read backwards. Which means2943 * we are in the middle of a line. Note that we2944 * may get here even if *bp was a newline; that2945 * just means we are at the exact end of the2946 * previous line, rather than some spot in the2947 * middle.2948 *2949 * Save away what we have to be combined with2950 * the data from the next read.2951 */2952strbuf_splice(&sb,0,0, buf, endp - buf);2953break;2954}2955}29562957}2958if(!ret && sb.len)2959die("BUG: reverse reflog parser had leftover data");29602961fclose(logfp);2962strbuf_release(&sb);2963return ret;2964}29652966intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)2967{2968FILE*logfp;2969struct strbuf sb = STRBUF_INIT;2970int ret =0;29712972 logfp =fopen(git_path("logs/%s", refname),"r");2973if(!logfp)2974return-1;29752976while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2977 ret =show_one_reflog_ent(&sb, fn, cb_data);2978fclose(logfp);2979strbuf_release(&sb);2980return ret;2981}2982/*2983 * Call fn for each reflog in the namespace indicated by name. name2984 * must be empty or end with '/'. Name will be used as a scratch2985 * space, but its contents will be restored before return.2986 */2987static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)2988{2989DIR*d =opendir(git_path("logs/%s", name->buf));2990int retval =0;2991struct dirent *de;2992int oldlen = name->len;29932994if(!d)2995return name->len ? errno :0;29962997while((de =readdir(d)) != NULL) {2998struct stat st;29993000if(de->d_name[0] =='.')3001continue;3002if(ends_with(de->d_name,".lock"))3003continue;3004strbuf_addstr(name, de->d_name);3005if(stat(git_path("logs/%s", name->buf), &st) <0) {3006;/* silently ignore */3007}else{3008if(S_ISDIR(st.st_mode)) {3009strbuf_addch(name,'/');3010 retval =do_for_each_reflog(name, fn, cb_data);3011}else{3012struct object_id oid;30133014if(read_ref_full(name->buf,0, oid.hash, NULL))3015 retval =error("bad ref for%s", name->buf);3016else3017 retval =fn(name->buf, &oid,0, cb_data);3018}3019if(retval)3020break;3021}3022strbuf_setlen(name, oldlen);3023}3024closedir(d);3025return retval;3026}30273028intfor_each_reflog(each_ref_fn fn,void*cb_data)3029{3030int retval;3031struct strbuf name;3032strbuf_init(&name, PATH_MAX);3033 retval =do_for_each_reflog(&name, fn, cb_data);3034strbuf_release(&name);3035return retval;3036}30373038static intref_update_reject_duplicates(struct string_list *refnames,3039struct strbuf *err)3040{3041int i, n = refnames->nr;30423043assert(err);30443045for(i =1; i < n; i++)3046if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3047strbuf_addf(err,3048"Multiple updates for ref '%s' not allowed.",3049 refnames->items[i].string);3050return1;3051}3052return0;3053}30543055intref_transaction_commit(struct ref_transaction *transaction,3056struct strbuf *err)3057{3058int ret =0, i;3059int n = transaction->nr;3060struct ref_update **updates = transaction->updates;3061struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3062struct string_list_item *ref_to_delete;3063struct string_list affected_refnames = STRING_LIST_INIT_NODUP;30643065assert(err);30663067if(transaction->state != REF_TRANSACTION_OPEN)3068die("BUG: commit called for transaction that is not open");30693070if(!n) {3071 transaction->state = REF_TRANSACTION_CLOSED;3072return0;3073}30743075/* Fail if a refname appears more than once in the transaction: */3076for(i =0; i < n; i++)3077string_list_append(&affected_refnames, updates[i]->refname);3078string_list_sort(&affected_refnames);3079if(ref_update_reject_duplicates(&affected_refnames, err)) {3080 ret = TRANSACTION_GENERIC_ERROR;3081goto cleanup;3082}30833084/*3085 * Acquire all locks, verify old values if provided, check3086 * that new values are valid, and write new values to the3087 * lockfiles, ready to be activated. Only keep one lockfile3088 * open at a time to avoid running out of file descriptors.3089 */3090for(i =0; i < n; i++) {3091struct ref_update *update = updates[i];30923093if((update->flags & REF_HAVE_NEW) &&3094is_null_sha1(update->new_sha1))3095 update->flags |= REF_DELETING;3096 update->lock =lock_ref_sha1_basic(3097 update->refname,3098((update->flags & REF_HAVE_OLD) ?3099 update->old_sha1 : NULL),3100&affected_refnames, NULL,3101 update->flags,3102&update->type,3103 err);3104if(!update->lock) {3105char*reason;31063107 ret = (errno == ENOTDIR)3108? TRANSACTION_NAME_CONFLICT3109: TRANSACTION_GENERIC_ERROR;3110 reason =strbuf_detach(err, NULL);3111strbuf_addf(err,"cannot lock ref '%s':%s",3112 update->refname, reason);3113free(reason);3114goto cleanup;3115}3116if((update->flags & REF_HAVE_NEW) &&3117!(update->flags & REF_DELETING)) {3118int overwriting_symref = ((update->type & REF_ISSYMREF) &&3119(update->flags & REF_NODEREF));31203121if(!overwriting_symref &&3122!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3123/*3124 * The reference already has the desired3125 * value, so we don't need to write it.3126 */3127}else if(write_ref_to_lockfile(update->lock,3128 update->new_sha1,3129 err)) {3130char*write_err =strbuf_detach(err, NULL);31313132/*3133 * The lock was freed upon failure of3134 * write_ref_to_lockfile():3135 */3136 update->lock = NULL;3137strbuf_addf(err,3138"cannot update the ref '%s':%s",3139 update->refname, write_err);3140free(write_err);3141 ret = TRANSACTION_GENERIC_ERROR;3142goto cleanup;3143}else{3144 update->flags |= REF_NEEDS_COMMIT;3145}3146}3147if(!(update->flags & REF_NEEDS_COMMIT)) {3148/*3149 * We didn't have to write anything to the lockfile.3150 * Close it to free up the file descriptor:3151 */3152if(close_ref(update->lock)) {3153strbuf_addf(err,"Couldn't close%s.lock",3154 update->refname);3155goto cleanup;3156}3157}3158}31593160/* Perform updates first so live commits remain referenced */3161for(i =0; i < n; i++) {3162struct ref_update *update = updates[i];31633164if(update->flags & REF_NEEDS_COMMIT) {3165if(commit_ref_update(update->lock,3166 update->new_sha1, update->msg,3167 update->flags, err)) {3168/* freed by commit_ref_update(): */3169 update->lock = NULL;3170 ret = TRANSACTION_GENERIC_ERROR;3171goto cleanup;3172}else{3173/* freed by commit_ref_update(): */3174 update->lock = NULL;3175}3176}3177}31783179/* Perform deletes now that updates are safely completed */3180for(i =0; i < n; i++) {3181struct ref_update *update = updates[i];31823183if(update->flags & REF_DELETING) {3184if(delete_ref_loose(update->lock, update->type, err)) {3185 ret = TRANSACTION_GENERIC_ERROR;3186goto cleanup;3187}31883189if(!(update->flags & REF_ISPRUNING))3190string_list_append(&refs_to_delete,3191 update->lock->ref_name);3192}3193}31943195if(repack_without_refs(&refs_to_delete, err)) {3196 ret = TRANSACTION_GENERIC_ERROR;3197goto cleanup;3198}3199for_each_string_list_item(ref_to_delete, &refs_to_delete)3200unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3201clear_loose_ref_cache(&ref_cache);32023203cleanup:3204 transaction->state = REF_TRANSACTION_CLOSED;32053206for(i =0; i < n; i++)3207if(updates[i]->lock)3208unlock_ref(updates[i]->lock);3209string_list_clear(&refs_to_delete,0);3210string_list_clear(&affected_refnames,0);3211return ret;3212}32133214static intref_present(const char*refname,3215const struct object_id *oid,int flags,void*cb_data)3216{3217struct string_list *affected_refnames = cb_data;32183219returnstring_list_has_string(affected_refnames, refname);3220}32213222intinitial_ref_transaction_commit(struct ref_transaction *transaction,3223struct strbuf *err)3224{3225int ret =0, i;3226int n = transaction->nr;3227struct ref_update **updates = transaction->updates;3228struct string_list affected_refnames = STRING_LIST_INIT_NODUP;32293230assert(err);32313232if(transaction->state != REF_TRANSACTION_OPEN)3233die("BUG: commit called for transaction that is not open");32343235/* Fail if a refname appears more than once in the transaction: */3236for(i =0; i < n; i++)3237string_list_append(&affected_refnames, updates[i]->refname);3238string_list_sort(&affected_refnames);3239if(ref_update_reject_duplicates(&affected_refnames, err)) {3240 ret = TRANSACTION_GENERIC_ERROR;3241goto cleanup;3242}32433244/*3245 * It's really undefined to call this function in an active3246 * repository or when there are existing references: we are3247 * only locking and changing packed-refs, so (1) any3248 * simultaneous processes might try to change a reference at3249 * the same time we do, and (2) any existing loose versions of3250 * the references that we are setting would have precedence3251 * over our values. But some remote helpers create the remote3252 * "HEAD" and "master" branches before calling this function,3253 * so here we really only check that none of the references3254 * that we are creating already exists.3255 */3256if(for_each_rawref(ref_present, &affected_refnames))3257die("BUG: initial ref transaction called with existing refs");32583259for(i =0; i < n; i++) {3260struct ref_update *update = updates[i];32613262if((update->flags & REF_HAVE_OLD) &&3263!is_null_sha1(update->old_sha1))3264die("BUG: initial ref transaction with old_sha1 set");3265if(verify_refname_available(update->refname,3266&affected_refnames, NULL,3267 err)) {3268 ret = TRANSACTION_NAME_CONFLICT;3269goto cleanup;3270}3271}32723273if(lock_packed_refs(0)) {3274strbuf_addf(err,"unable to lock packed-refs file:%s",3275strerror(errno));3276 ret = TRANSACTION_GENERIC_ERROR;3277goto cleanup;3278}32793280for(i =0; i < n; i++) {3281struct ref_update *update = updates[i];32823283if((update->flags & REF_HAVE_NEW) &&3284!is_null_sha1(update->new_sha1))3285add_packed_ref(update->refname, update->new_sha1);3286}32873288if(commit_packed_refs()) {3289strbuf_addf(err,"unable to commit packed-refs file:%s",3290strerror(errno));3291 ret = TRANSACTION_GENERIC_ERROR;3292goto cleanup;3293}32943295cleanup:3296 transaction->state = REF_TRANSACTION_CLOSED;3297string_list_clear(&affected_refnames,0);3298return ret;3299}33003301struct expire_reflog_cb {3302unsigned int flags;3303 reflog_expiry_should_prune_fn *should_prune_fn;3304void*policy_cb;3305FILE*newlog;3306unsigned char last_kept_sha1[20];3307};33083309static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3310const char*email,unsigned long timestamp,int tz,3311const char*message,void*cb_data)3312{3313struct expire_reflog_cb *cb = cb_data;3314struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;33153316if(cb->flags & EXPIRE_REFLOGS_REWRITE)3317 osha1 = cb->last_kept_sha1;33183319if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3320 message, policy_cb)) {3321if(!cb->newlog)3322printf("would prune%s", message);3323else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3324printf("prune%s", message);3325}else{3326if(cb->newlog) {3327fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3328sha1_to_hex(osha1),sha1_to_hex(nsha1),3329 email, timestamp, tz, message);3330hashcpy(cb->last_kept_sha1, nsha1);3331}3332if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3333printf("keep%s", message);3334}3335return0;3336}33373338intreflog_expire(const char*refname,const unsigned char*sha1,3339unsigned int flags,3340 reflog_expiry_prepare_fn prepare_fn,3341 reflog_expiry_should_prune_fn should_prune_fn,3342 reflog_expiry_cleanup_fn cleanup_fn,3343void*policy_cb_data)3344{3345static struct lock_file reflog_lock;3346struct expire_reflog_cb cb;3347struct ref_lock *lock;3348char*log_file;3349int status =0;3350int type;3351struct strbuf err = STRBUF_INIT;33523353memset(&cb,0,sizeof(cb));3354 cb.flags = flags;3355 cb.policy_cb = policy_cb_data;3356 cb.should_prune_fn = should_prune_fn;33573358/*3359 * The reflog file is locked by holding the lock on the3360 * reference itself, plus we might need to update the3361 * reference if --updateref was specified:3362 */3363 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);3364if(!lock) {3365error("cannot lock ref '%s':%s", refname, err.buf);3366strbuf_release(&err);3367return-1;3368}3369if(!reflog_exists(refname)) {3370unlock_ref(lock);3371return0;3372}33733374 log_file =git_pathdup("logs/%s", refname);3375if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3376/*3377 * Even though holding $GIT_DIR/logs/$reflog.lock has3378 * no locking implications, we use the lock_file3379 * machinery here anyway because it does a lot of the3380 * work we need, including cleaning up if the program3381 * exits unexpectedly.3382 */3383if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3384struct strbuf err = STRBUF_INIT;3385unable_to_lock_message(log_file, errno, &err);3386error("%s", err.buf);3387strbuf_release(&err);3388goto failure;3389}3390 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3391if(!cb.newlog) {3392error("cannot fdopen%s(%s)",3393get_lock_file_path(&reflog_lock),strerror(errno));3394goto failure;3395}3396}33973398(*prepare_fn)(refname, sha1, cb.policy_cb);3399for_each_reflog_ent(refname, expire_reflog_ent, &cb);3400(*cleanup_fn)(cb.policy_cb);34013402if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3403/*3404 * It doesn't make sense to adjust a reference pointed3405 * to by a symbolic ref based on expiring entries in3406 * the symbolic reference's reflog. Nor can we update3407 * a reference if there are no remaining reflog3408 * entries.3409 */3410int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3411!(type & REF_ISSYMREF) &&3412!is_null_sha1(cb.last_kept_sha1);34133414if(close_lock_file(&reflog_lock)) {3415 status |=error("couldn't write%s:%s", log_file,3416strerror(errno));3417}else if(update &&3418(write_in_full(get_lock_file_fd(lock->lk),3419sha1_to_hex(cb.last_kept_sha1),40) !=40||3420write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3421close_ref(lock) <0)) {3422 status |=error("couldn't write%s",3423get_lock_file_path(lock->lk));3424rollback_lock_file(&reflog_lock);3425}else if(commit_lock_file(&reflog_lock)) {3426 status |=error("unable to write reflog '%s' (%s)",3427 log_file,strerror(errno));3428}else if(update &&commit_ref(lock)) {3429 status |=error("couldn't set%s", lock->ref_name);3430}3431}3432free(log_file);3433unlock_ref(lock);3434return status;34353436 failure:3437rollback_lock_file(&reflog_lock);3438free(log_file);3439unlock_ref(lock);3440return-1;3441}