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. The1372 * options are forwarded from resolve_safe_unsafe().1373 */1374static intresolve_missing_loose_ref(const char*refname,1375int resolve_flags,1376unsigned char*sha1,1377int*flags)1378{1379struct ref_entry *entry;13801381/*1382 * The loose reference file does not exist; check for a packed1383 * reference.1384 */1385 entry =get_packed_ref(refname);1386if(entry) {1387hashcpy(sha1, entry->u.value.oid.hash);1388if(flags)1389*flags |= REF_ISPACKED;1390return0;1391}1392/* The reference is not a packed reference, either. */1393if(resolve_flags & RESOLVE_REF_READING) {1394 errno = ENOENT;1395return-1;1396}else{1397hashclr(sha1);1398return0;1399}1400}14011402/* This function needs to return a meaningful errno on failure */1403static const char*resolve_ref_1(const char*refname,1404int resolve_flags,1405unsigned char*sha1,1406int*flags,1407struct strbuf *sb_refname,1408struct strbuf *sb_path,1409struct strbuf *sb_contents)1410{1411int depth = MAXDEPTH;1412int bad_name =0;14131414if(flags)1415*flags =0;14161417if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1418if(flags)1419*flags |= REF_BAD_NAME;14201421if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1422!refname_is_safe(refname)) {1423 errno = EINVAL;1424return NULL;1425}1426/*1427 * dwim_ref() uses REF_ISBROKEN to distinguish between1428 * missing refs and refs that were present but invalid,1429 * to complain about the latter to stderr.1430 *1431 * We don't know whether the ref exists, so don't set1432 * REF_ISBROKEN yet.1433 */1434 bad_name =1;1435}1436for(;;) {1437const char*path;1438struct stat st;1439char*buf;1440int fd;14411442if(--depth <0) {1443 errno = ELOOP;1444return NULL;1445}14461447strbuf_reset(sb_path);1448strbuf_git_path(sb_path,"%s", refname);1449 path = sb_path->buf;14501451/*1452 * We might have to loop back here to avoid a race1453 * condition: first we lstat() the file, then we try1454 * to read it as a link or as a file. But if somebody1455 * changes the type of the file (file <-> directory1456 * <-> symlink) between the lstat() and reading, then1457 * we don't want to report that as an error but rather1458 * try again starting with the lstat().1459 */1460 stat_ref:1461if(lstat(path, &st) <0) {1462if(errno != ENOENT)1463return NULL;1464if(resolve_missing_loose_ref(refname, resolve_flags,1465 sha1, flags))1466return NULL;1467if(bad_name) {1468hashclr(sha1);1469if(flags)1470*flags |= REF_ISBROKEN;1471}1472return refname;1473}14741475/* Follow "normalized" - ie "refs/.." symlinks by hand */1476if(S_ISLNK(st.st_mode)) {1477strbuf_reset(sb_contents);1478if(strbuf_readlink(sb_contents, path,0) <0) {1479if(errno == ENOENT || errno == EINVAL)1480/* inconsistent with lstat; retry */1481goto stat_ref;1482else1483return NULL;1484}1485if(starts_with(sb_contents->buf,"refs/") &&1486!check_refname_format(sb_contents->buf,0)) {1487strbuf_swap(sb_refname, sb_contents);1488 refname = sb_refname->buf;1489if(flags)1490*flags |= REF_ISSYMREF;1491if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1492hashclr(sha1);1493return refname;1494}1495continue;1496}1497}14981499/* Is it a directory? */1500if(S_ISDIR(st.st_mode)) {1501 errno = EISDIR;1502return NULL;1503}15041505/*1506 * Anything else, just open it and try to use it as1507 * a ref1508 */1509 fd =open(path, O_RDONLY);1510if(fd <0) {1511if(errno == ENOENT)1512/* inconsistent with lstat; retry */1513goto stat_ref;1514else1515return NULL;1516}1517strbuf_reset(sb_contents);1518if(strbuf_read(sb_contents, fd,256) <0) {1519int save_errno = errno;1520close(fd);1521 errno = save_errno;1522return NULL;1523}1524close(fd);1525strbuf_rtrim(sb_contents);15261527/*1528 * Is it a symbolic ref?1529 */1530if(!starts_with(sb_contents->buf,"ref:")) {1531/*1532 * Please note that FETCH_HEAD has a second1533 * line containing other data.1534 */1535if(get_sha1_hex(sb_contents->buf, sha1) ||1536(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1537if(flags)1538*flags |= REF_ISBROKEN;1539 errno = EINVAL;1540return NULL;1541}1542if(bad_name) {1543hashclr(sha1);1544if(flags)1545*flags |= REF_ISBROKEN;1546}1547return refname;1548}1549if(flags)1550*flags |= REF_ISSYMREF;1551 buf = sb_contents->buf +4;1552while(isspace(*buf))1553 buf++;1554strbuf_reset(sb_refname);1555strbuf_addstr(sb_refname, buf);1556 refname = sb_refname->buf;1557if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1558hashclr(sha1);1559return refname;1560}1561if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1562if(flags)1563*flags |= REF_ISBROKEN;15641565if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1566!refname_is_safe(buf)) {1567 errno = EINVAL;1568return NULL;1569}1570 bad_name =1;1571}1572}1573}15741575const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1576unsigned char*sha1,int*flags)1577{1578static struct strbuf sb_refname = STRBUF_INIT;1579struct strbuf sb_contents = STRBUF_INIT;1580struct strbuf sb_path = STRBUF_INIT;1581const char*ret;15821583 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1584&sb_refname, &sb_path, &sb_contents);1585strbuf_release(&sb_path);1586strbuf_release(&sb_contents);1587return ret;1588}15891590/*1591 * Peel the entry (if possible) and return its new peel_status. If1592 * repeel is true, re-peel the entry even if there is an old peeled1593 * value that is already stored in it.1594 *1595 * It is OK to call this function with a packed reference entry that1596 * might be stale and might even refer to an object that has since1597 * been garbage-collected. In such a case, if the entry has1598 * REF_KNOWS_PEELED then leave the status unchanged and return1599 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1600 */1601static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1602{1603enum peel_status status;16041605if(entry->flag & REF_KNOWS_PEELED) {1606if(repeel) {1607 entry->flag &= ~REF_KNOWS_PEELED;1608oidclr(&entry->u.value.peeled);1609}else{1610returnis_null_oid(&entry->u.value.peeled) ?1611 PEEL_NON_TAG : PEEL_PEELED;1612}1613}1614if(entry->flag & REF_ISBROKEN)1615return PEEL_BROKEN;1616if(entry->flag & REF_ISSYMREF)1617return PEEL_IS_SYMREF;16181619 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1620if(status == PEEL_PEELED || status == PEEL_NON_TAG)1621 entry->flag |= REF_KNOWS_PEELED;1622return status;1623}16241625intpeel_ref(const char*refname,unsigned char*sha1)1626{1627int flag;1628unsigned char base[20];16291630if(current_ref && (current_ref->name == refname1631|| !strcmp(current_ref->name, refname))) {1632if(peel_entry(current_ref,0))1633return-1;1634hashcpy(sha1, current_ref->u.value.peeled.hash);1635return0;1636}16371638if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1639return-1;16401641/*1642 * If the reference is packed, read its ref_entry from the1643 * cache in the hope that we already know its peeled value.1644 * We only try this optimization on packed references because1645 * (a) forcing the filling of the loose reference cache could1646 * be expensive and (b) loose references anyway usually do not1647 * have REF_KNOWS_PEELED.1648 */1649if(flag & REF_ISPACKED) {1650struct ref_entry *r =get_packed_ref(refname);1651if(r) {1652if(peel_entry(r,0))1653return-1;1654hashcpy(sha1, r->u.value.peeled.hash);1655return0;1656}1657}16581659returnpeel_object(base, sha1);1660}16611662/*1663 * Call fn for each reference in the specified ref_cache, omitting1664 * references not in the containing_dir of base. fn is called for all1665 * references, including broken ones. If fn ever returns a non-zero1666 * value, stop the iteration and return that value; otherwise, return1667 * 0.1668 */1669static intdo_for_each_entry(struct ref_cache *refs,const char*base,1670 each_ref_entry_fn fn,void*cb_data)1671{1672struct packed_ref_cache *packed_ref_cache;1673struct ref_dir *loose_dir;1674struct ref_dir *packed_dir;1675int retval =0;16761677/*1678 * We must make sure that all loose refs are read before accessing the1679 * packed-refs file; this avoids a race condition in which loose refs1680 * are migrated to the packed-refs file by a simultaneous process, but1681 * our in-memory view is from before the migration. get_packed_ref_cache()1682 * takes care of making sure our view is up to date with what is on1683 * disk.1684 */1685 loose_dir =get_loose_refs(refs);1686if(base && *base) {1687 loose_dir =find_containing_dir(loose_dir, base,0);1688}1689if(loose_dir)1690prime_ref_dir(loose_dir);16911692 packed_ref_cache =get_packed_ref_cache(refs);1693acquire_packed_ref_cache(packed_ref_cache);1694 packed_dir =get_packed_ref_dir(packed_ref_cache);1695if(base && *base) {1696 packed_dir =find_containing_dir(packed_dir, base,0);1697}16981699if(packed_dir && loose_dir) {1700sort_ref_dir(packed_dir);1701sort_ref_dir(loose_dir);1702 retval =do_for_each_entry_in_dirs(1703 packed_dir, loose_dir, fn, cb_data);1704}else if(packed_dir) {1705sort_ref_dir(packed_dir);1706 retval =do_for_each_entry_in_dir(1707 packed_dir,0, fn, cb_data);1708}else if(loose_dir) {1709sort_ref_dir(loose_dir);1710 retval =do_for_each_entry_in_dir(1711 loose_dir,0, fn, cb_data);1712}17131714release_packed_ref_cache(packed_ref_cache);1715return retval;1716}17171718/*1719 * Call fn for each reference in the specified ref_cache for which the1720 * refname begins with base. If trim is non-zero, then trim that many1721 * characters off the beginning of each refname before passing the1722 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1723 * broken references in the iteration. If fn ever returns a non-zero1724 * value, stop the iteration and return that value; otherwise, return1725 * 0.1726 */1727intdo_for_each_ref(const char*submodule,const char*base,1728 each_ref_fn fn,int trim,int flags,void*cb_data)1729{1730struct ref_entry_cb data;1731struct ref_cache *refs;17321733 refs =get_ref_cache(submodule);1734 data.base = base;1735 data.trim = trim;1736 data.flags = flags;1737 data.fn = fn;1738 data.cb_data = cb_data;17391740if(ref_paranoia <0)1741 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);1742if(ref_paranoia)1743 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;17441745returndo_for_each_entry(refs, base, do_one_ref, &data);1746}17471748static voidunlock_ref(struct ref_lock *lock)1749{1750/* Do not free lock->lk -- atexit() still looks at them */1751if(lock->lk)1752rollback_lock_file(lock->lk);1753free(lock->ref_name);1754free(lock->orig_ref_name);1755free(lock);1756}17571758/*1759 * Verify that the reference locked by lock has the value old_sha1.1760 * Fail if the reference doesn't exist and mustexist is set. Return 01761 * on success. On error, write an error message to err, set errno, and1762 * return a negative value.1763 */1764static intverify_lock(struct ref_lock *lock,1765const unsigned char*old_sha1,int mustexist,1766struct strbuf *err)1767{1768assert(err);17691770if(read_ref_full(lock->ref_name,1771 mustexist ? RESOLVE_REF_READING :0,1772 lock->old_oid.hash, NULL)) {1773if(old_sha1) {1774int save_errno = errno;1775strbuf_addf(err,"can't verify ref%s", lock->ref_name);1776 errno = save_errno;1777return-1;1778}else{1779hashclr(lock->old_oid.hash);1780return0;1781}1782}1783if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1784strbuf_addf(err,"ref%sis at%sbut expected%s",1785 lock->ref_name,1786sha1_to_hex(lock->old_oid.hash),1787sha1_to_hex(old_sha1));1788 errno = EBUSY;1789return-1;1790}1791return0;1792}17931794static intremove_empty_directories(struct strbuf *path)1795{1796/*1797 * we want to create a file but there is a directory there;1798 * if that is an empty directory (or a directory that contains1799 * only empty directories), remove them.1800 */1801returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1802}18031804/*1805 * Locks a ref returning the lock on success and NULL on failure.1806 * On failure errno is set to something meaningful.1807 */1808static struct ref_lock *lock_ref_sha1_basic(const char*refname,1809const unsigned char*old_sha1,1810const struct string_list *extras,1811const struct string_list *skip,1812unsigned int flags,int*type_p,1813struct strbuf *err)1814{1815struct strbuf ref_file = STRBUF_INIT;1816struct strbuf orig_ref_file = STRBUF_INIT;1817const char*orig_refname = refname;1818struct ref_lock *lock;1819int last_errno =0;1820int type;1821int lflags =0;1822int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1823int resolve_flags =0;1824int attempts_remaining =3;18251826assert(err);18271828 lock =xcalloc(1,sizeof(struct ref_lock));18291830if(mustexist)1831 resolve_flags |= RESOLVE_REF_READING;1832if(flags & REF_DELETING)1833 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;1834if(flags & REF_NODEREF) {1835 resolve_flags |= RESOLVE_REF_NO_RECURSE;1836 lflags |= LOCK_NO_DEREF;1837}18381839 refname =resolve_ref_unsafe(refname, resolve_flags,1840 lock->old_oid.hash, &type);1841if(!refname && errno == EISDIR) {1842/*1843 * we are trying to lock foo but we used to1844 * have foo/bar which now does not exist;1845 * it is normal for the empty directory 'foo'1846 * to remain.1847 */1848strbuf_git_path(&orig_ref_file,"%s", orig_refname);1849if(remove_empty_directories(&orig_ref_file)) {1850 last_errno = errno;1851if(!verify_refname_available_dir(orig_refname, extras, skip,1852get_loose_refs(&ref_cache), err))1853strbuf_addf(err,"there are still refs under '%s'",1854 orig_refname);1855goto error_return;1856}1857 refname =resolve_ref_unsafe(orig_refname, resolve_flags,1858 lock->old_oid.hash, &type);1859}1860if(type_p)1861*type_p = type;1862if(!refname) {1863 last_errno = errno;1864if(last_errno != ENOTDIR ||1865!verify_refname_available_dir(orig_refname, extras, skip,1866get_loose_refs(&ref_cache), err))1867strbuf_addf(err,"unable to resolve reference%s:%s",1868 orig_refname,strerror(last_errno));18691870goto error_return;1871}18721873if(flags & REF_NODEREF)1874 refname = orig_refname;18751876/*1877 * If the ref did not exist and we are creating it, make sure1878 * there is no existing packed ref whose name begins with our1879 * refname, nor a packed ref whose name is a proper prefix of1880 * our refname.1881 */1882if(is_null_oid(&lock->old_oid) &&1883verify_refname_available_dir(refname, extras, skip,1884get_packed_refs(&ref_cache), err)) {1885 last_errno = ENOTDIR;1886goto error_return;1887}18881889 lock->lk =xcalloc(1,sizeof(struct lock_file));18901891 lock->ref_name =xstrdup(refname);1892 lock->orig_ref_name =xstrdup(orig_refname);1893strbuf_git_path(&ref_file,"%s", refname);18941895 retry:1896switch(safe_create_leading_directories_const(ref_file.buf)) {1897case SCLD_OK:1898break;/* success */1899case SCLD_VANISHED:1900if(--attempts_remaining >0)1901goto retry;1902/* fall through */1903default:1904 last_errno = errno;1905strbuf_addf(err,"unable to create directory for%s",1906 ref_file.buf);1907goto error_return;1908}19091910if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {1911 last_errno = errno;1912if(errno == ENOENT && --attempts_remaining >0)1913/*1914 * Maybe somebody just deleted one of the1915 * directories leading to ref_file. Try1916 * again:1917 */1918goto retry;1919else{1920unable_to_lock_message(ref_file.buf, errno, err);1921goto error_return;1922}1923}1924if(verify_lock(lock, old_sha1, mustexist, err)) {1925 last_errno = errno;1926goto error_return;1927}1928goto out;19291930 error_return:1931unlock_ref(lock);1932 lock = NULL;19331934 out:1935strbuf_release(&ref_file);1936strbuf_release(&orig_ref_file);1937 errno = last_errno;1938return lock;1939}19401941/*1942 * Write an entry to the packed-refs file for the specified refname.1943 * If peeled is non-NULL, write it as the entry's peeled value.1944 */1945static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,1946unsigned char*peeled)1947{1948fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1949if(peeled)1950fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1951}19521953/*1954 * An each_ref_entry_fn that writes the entry to a packed-refs file.1955 */1956static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)1957{1958enum peel_status peel_status =peel_entry(entry,0);19591960if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)1961error("internal error:%sis not a valid packed reference!",1962 entry->name);1963write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,1964 peel_status == PEEL_PEELED ?1965 entry->u.value.peeled.hash : NULL);1966return0;1967}19681969/*1970 * Lock the packed-refs file for writing. Flags is passed to1971 * hold_lock_file_for_update(). Return 0 on success. On errors, set1972 * errno appropriately and return a nonzero value.1973 */1974static intlock_packed_refs(int flags)1975{1976static int timeout_configured =0;1977static int timeout_value =1000;19781979struct packed_ref_cache *packed_ref_cache;19801981if(!timeout_configured) {1982git_config_get_int("core.packedrefstimeout", &timeout_value);1983 timeout_configured =1;1984}19851986if(hold_lock_file_for_update_timeout(1987&packlock,git_path("packed-refs"),1988 flags, timeout_value) <0)1989return-1;1990/*1991 * Get the current packed-refs while holding the lock. If the1992 * packed-refs file has been modified since we last read it,1993 * this will automatically invalidate the cache and re-read1994 * the packed-refs file.1995 */1996 packed_ref_cache =get_packed_ref_cache(&ref_cache);1997 packed_ref_cache->lock = &packlock;1998/* Increment the reference count to prevent it from being freed: */1999acquire_packed_ref_cache(packed_ref_cache);2000return0;2001}20022003/*2004 * Write the current version of the packed refs cache from memory to2005 * disk. The packed-refs file must already be locked for writing (see2006 * lock_packed_refs()). Return zero on success. On errors, set errno2007 * and return a nonzero value2008 */2009static intcommit_packed_refs(void)2010{2011struct packed_ref_cache *packed_ref_cache =2012get_packed_ref_cache(&ref_cache);2013int error =0;2014int save_errno =0;2015FILE*out;20162017if(!packed_ref_cache->lock)2018die("internal error: packed-refs not locked");20192020 out =fdopen_lock_file(packed_ref_cache->lock,"w");2021if(!out)2022die_errno("unable to fdopen packed-refs descriptor");20232024fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2025do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),20260, write_packed_entry_fn, out);20272028if(commit_lock_file(packed_ref_cache->lock)) {2029 save_errno = errno;2030 error = -1;2031}2032 packed_ref_cache->lock = NULL;2033release_packed_ref_cache(packed_ref_cache);2034 errno = save_errno;2035return error;2036}20372038/*2039 * Rollback the lockfile for the packed-refs file, and discard the2040 * in-memory packed reference cache. (The packed-refs file will be2041 * read anew if it is needed again after this function is called.)2042 */2043static voidrollback_packed_refs(void)2044{2045struct packed_ref_cache *packed_ref_cache =2046get_packed_ref_cache(&ref_cache);20472048if(!packed_ref_cache->lock)2049die("internal error: packed-refs not locked");2050rollback_lock_file(packed_ref_cache->lock);2051 packed_ref_cache->lock = NULL;2052release_packed_ref_cache(packed_ref_cache);2053clear_packed_ref_cache(&ref_cache);2054}20552056struct ref_to_prune {2057struct ref_to_prune *next;2058unsigned char sha1[20];2059char name[FLEX_ARRAY];2060};20612062struct pack_refs_cb_data {2063unsigned int flags;2064struct ref_dir *packed_refs;2065struct ref_to_prune *ref_to_prune;2066};20672068/*2069 * An each_ref_entry_fn that is run over loose references only. If2070 * the loose reference can be packed, add an entry in the packed ref2071 * cache. If the reference should be pruned, also add it to2072 * ref_to_prune in the pack_refs_cb_data.2073 */2074static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2075{2076struct pack_refs_cb_data *cb = cb_data;2077enum peel_status peel_status;2078struct ref_entry *packed_entry;2079int is_tag_ref =starts_with(entry->name,"refs/tags/");20802081/* Do not pack per-worktree refs: */2082if(ref_type(entry->name) != REF_TYPE_NORMAL)2083return0;20842085/* ALWAYS pack tags */2086if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2087return0;20882089/* Do not pack symbolic or broken refs: */2090if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2091return0;20922093/* Add a packed ref cache entry equivalent to the loose entry. */2094 peel_status =peel_entry(entry,1);2095if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2096die("internal error peeling reference%s(%s)",2097 entry->name,oid_to_hex(&entry->u.value.oid));2098 packed_entry =find_ref(cb->packed_refs, entry->name);2099if(packed_entry) {2100/* Overwrite existing packed entry with info from loose entry */2101 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2102oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2103}else{2104 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2105 REF_ISPACKED | REF_KNOWS_PEELED,0);2106add_ref(cb->packed_refs, packed_entry);2107}2108oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);21092110/* Schedule the loose reference for pruning if requested. */2111if((cb->flags & PACK_REFS_PRUNE)) {2112struct ref_to_prune *n;2113FLEX_ALLOC_STR(n, name, entry->name);2114hashcpy(n->sha1, entry->u.value.oid.hash);2115 n->next = cb->ref_to_prune;2116 cb->ref_to_prune = n;2117}2118return0;2119}21202121/*2122 * Remove empty parents, but spare refs/ and immediate subdirs.2123 * Note: munges *name.2124 */2125static voidtry_remove_empty_parents(char*name)2126{2127char*p, *q;2128int i;2129 p = name;2130for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2131while(*p && *p !='/')2132 p++;2133/* tolerate duplicate slashes; see check_refname_format() */2134while(*p =='/')2135 p++;2136}2137for(q = p; *q; q++)2138;2139while(1) {2140while(q > p && *q !='/')2141 q--;2142while(q > p && *(q-1) =='/')2143 q--;2144if(q == p)2145break;2146*q ='\0';2147if(rmdir(git_path("%s", name)))2148break;2149}2150}21512152/* make sure nobody touched the ref, and unlink */2153static voidprune_ref(struct ref_to_prune *r)2154{2155struct ref_transaction *transaction;2156struct strbuf err = STRBUF_INIT;21572158if(check_refname_format(r->name,0))2159return;21602161 transaction =ref_transaction_begin(&err);2162if(!transaction ||2163ref_transaction_delete(transaction, r->name, r->sha1,2164 REF_ISPRUNING, NULL, &err) ||2165ref_transaction_commit(transaction, &err)) {2166ref_transaction_free(transaction);2167error("%s", err.buf);2168strbuf_release(&err);2169return;2170}2171ref_transaction_free(transaction);2172strbuf_release(&err);2173try_remove_empty_parents(r->name);2174}21752176static voidprune_refs(struct ref_to_prune *r)2177{2178while(r) {2179prune_ref(r);2180 r = r->next;2181}2182}21832184intpack_refs(unsigned int flags)2185{2186struct pack_refs_cb_data cbdata;21872188memset(&cbdata,0,sizeof(cbdata));2189 cbdata.flags = flags;21902191lock_packed_refs(LOCK_DIE_ON_ERROR);2192 cbdata.packed_refs =get_packed_refs(&ref_cache);21932194do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2195 pack_if_possible_fn, &cbdata);21962197if(commit_packed_refs())2198die_errno("unable to overwrite old ref-pack file");21992200prune_refs(cbdata.ref_to_prune);2201return0;2202}22032204/*2205 * Rewrite the packed-refs file, omitting any refs listed in2206 * 'refnames'. On error, leave packed-refs unchanged, write an error2207 * message to 'err', and return a nonzero value.2208 *2209 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2210 */2211static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2212{2213struct ref_dir *packed;2214struct string_list_item *refname;2215int ret, needs_repacking =0, removed =0;22162217assert(err);22182219/* Look for a packed ref */2220for_each_string_list_item(refname, refnames) {2221if(get_packed_ref(refname->string)) {2222 needs_repacking =1;2223break;2224}2225}22262227/* Avoid locking if we have nothing to do */2228if(!needs_repacking)2229return0;/* no refname exists in packed refs */22302231if(lock_packed_refs(0)) {2232unable_to_lock_message(git_path("packed-refs"), errno, err);2233return-1;2234}2235 packed =get_packed_refs(&ref_cache);22362237/* Remove refnames from the cache */2238for_each_string_list_item(refname, refnames)2239if(remove_entry(packed, refname->string) != -1)2240 removed =1;2241if(!removed) {2242/*2243 * All packed entries disappeared while we were2244 * acquiring the lock.2245 */2246rollback_packed_refs();2247return0;2248}22492250/* Write what remains */2251 ret =commit_packed_refs();2252if(ret)2253strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2254strerror(errno));2255return ret;2256}22572258static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2259{2260assert(err);22612262if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2263/*2264 * loose. The loose file name is the same as the2265 * lockfile name, minus ".lock":2266 */2267char*loose_filename =get_locked_file_path(lock->lk);2268int res =unlink_or_msg(loose_filename, err);2269free(loose_filename);2270if(res)2271return1;2272}2273return0;2274}22752276intdelete_refs(struct string_list *refnames)2277{2278struct strbuf err = STRBUF_INIT;2279int i, result =0;22802281if(!refnames->nr)2282return0;22832284 result =repack_without_refs(refnames, &err);2285if(result) {2286/*2287 * If we failed to rewrite the packed-refs file, then2288 * it is unsafe to try to remove loose refs, because2289 * doing so might expose an obsolete packed value for2290 * a reference that might even point at an object that2291 * has been garbage collected.2292 */2293if(refnames->nr ==1)2294error(_("could not delete reference%s:%s"),2295 refnames->items[0].string, err.buf);2296else2297error(_("could not delete references:%s"), err.buf);22982299goto out;2300}23012302for(i =0; i < refnames->nr; i++) {2303const char*refname = refnames->items[i].string;23042305if(delete_ref(refname, NULL,0))2306 result |=error(_("could not remove reference%s"), refname);2307}23082309out:2310strbuf_release(&err);2311return result;2312}23132314/*2315 * People using contrib's git-new-workdir have .git/logs/refs ->2316 * /some/other/path/.git/logs/refs, and that may live on another device.2317 *2318 * IOW, to avoid cross device rename errors, the temporary renamed log must2319 * live into logs/refs.2320 */2321#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"23222323static intrename_tmp_log(const char*newrefname)2324{2325int attempts_remaining =4;2326struct strbuf path = STRBUF_INIT;2327int ret = -1;23282329 retry:2330strbuf_reset(&path);2331strbuf_git_path(&path,"logs/%s", newrefname);2332switch(safe_create_leading_directories_const(path.buf)) {2333case SCLD_OK:2334break;/* success */2335case SCLD_VANISHED:2336if(--attempts_remaining >0)2337goto retry;2338/* fall through */2339default:2340error("unable to create directory for%s", newrefname);2341goto out;2342}23432344if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {2345if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2346/*2347 * rename(a, b) when b is an existing2348 * directory ought to result in ISDIR, but2349 * Solaris 5.8 gives ENOTDIR. Sheesh.2350 */2351if(remove_empty_directories(&path)) {2352error("Directory not empty: logs/%s", newrefname);2353goto out;2354}2355goto retry;2356}else if(errno == ENOENT && --attempts_remaining >0) {2357/*2358 * Maybe another process just deleted one of2359 * the directories in the path to newrefname.2360 * Try again from the beginning.2361 */2362goto retry;2363}else{2364error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2365 newrefname,strerror(errno));2366goto out;2367}2368}2369 ret =0;2370out:2371strbuf_release(&path);2372return ret;2373}23742375intverify_refname_available(const char*newname,2376struct string_list *extras,2377struct string_list *skip,2378struct strbuf *err)2379{2380struct ref_dir *packed_refs =get_packed_refs(&ref_cache);2381struct ref_dir *loose_refs =get_loose_refs(&ref_cache);23822383if(verify_refname_available_dir(newname, extras, skip,2384 packed_refs, err) ||2385verify_refname_available_dir(newname, extras, skip,2386 loose_refs, err))2387return-1;23882389return0;2390}23912392static intwrite_ref_to_lockfile(struct ref_lock *lock,2393const unsigned char*sha1,struct strbuf *err);2394static intcommit_ref_update(struct ref_lock *lock,2395const unsigned char*sha1,const char*logmsg,2396int flags,struct strbuf *err);23972398intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2399{2400unsigned char sha1[20], orig_sha1[20];2401int flag =0, logmoved =0;2402struct ref_lock *lock;2403struct stat loginfo;2404int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2405const char*symref = NULL;2406struct strbuf err = STRBUF_INIT;24072408if(log &&S_ISLNK(loginfo.st_mode))2409returnerror("reflog for%sis a symlink", oldrefname);24102411 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2412 orig_sha1, &flag);2413if(flag & REF_ISSYMREF)2414returnerror("refname%sis a symbolic ref, renaming it is not supported",2415 oldrefname);2416if(!symref)2417returnerror("refname%snot found", oldrefname);24182419if(!rename_ref_available(oldrefname, newrefname))2420return1;24212422if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2423returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2424 oldrefname,strerror(errno));24252426if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2427error("unable to delete old%s", oldrefname);2428goto rollback;2429}24302431if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2432delete_ref(newrefname, sha1, REF_NODEREF)) {2433if(errno==EISDIR) {2434struct strbuf path = STRBUF_INIT;2435int result;24362437strbuf_git_path(&path,"%s", newrefname);2438 result =remove_empty_directories(&path);2439strbuf_release(&path);24402441if(result) {2442error("Directory not empty:%s", newrefname);2443goto rollback;2444}2445}else{2446error("unable to delete existing%s", newrefname);2447goto rollback;2448}2449}24502451if(log &&rename_tmp_log(newrefname))2452goto rollback;24532454 logmoved = log;24552456 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2457if(!lock) {2458error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2459strbuf_release(&err);2460goto rollback;2461}2462hashcpy(lock->old_oid.hash, orig_sha1);24632464if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2465commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {2466error("unable to write current sha1 into%s:%s", newrefname, err.buf);2467strbuf_release(&err);2468goto rollback;2469}24702471return0;24722473 rollback:2474 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2475if(!lock) {2476error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2477strbuf_release(&err);2478goto rollbacklog;2479}24802481 flag = log_all_ref_updates;2482 log_all_ref_updates =0;2483if(write_ref_to_lockfile(lock, orig_sha1, &err) ||2484commit_ref_update(lock, orig_sha1, NULL,0, &err)) {2485error("unable to write current sha1 into%s:%s", oldrefname, err.buf);2486strbuf_release(&err);2487}2488 log_all_ref_updates = flag;24892490 rollbacklog:2491if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2492error("unable to restore logfile%sfrom%s:%s",2493 oldrefname, newrefname,strerror(errno));2494if(!logmoved && log &&2495rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2496error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2497 oldrefname,strerror(errno));24982499return1;2500}25012502static intclose_ref(struct ref_lock *lock)2503{2504if(close_lock_file(lock->lk))2505return-1;2506return0;2507}25082509static intcommit_ref(struct ref_lock *lock)2510{2511if(commit_lock_file(lock->lk))2512return-1;2513return0;2514}25152516/*2517 * Create a reflog for a ref. If force_create = 0, the reflog will2518 * only be created for certain refs (those for which2519 * should_autocreate_reflog returns non-zero. Otherwise, create it2520 * regardless of the ref name. Fill in *err and return -1 on failure.2521 */2522static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)2523{2524int logfd, oflags = O_APPEND | O_WRONLY;25252526strbuf_git_path(logfile,"logs/%s", refname);2527if(force_create ||should_autocreate_reflog(refname)) {2528if(safe_create_leading_directories(logfile->buf) <0) {2529strbuf_addf(err,"unable to create directory for%s: "2530"%s", logfile->buf,strerror(errno));2531return-1;2532}2533 oflags |= O_CREAT;2534}25352536 logfd =open(logfile->buf, oflags,0666);2537if(logfd <0) {2538if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2539return0;25402541if(errno == EISDIR) {2542if(remove_empty_directories(logfile)) {2543strbuf_addf(err,"There are still logs under "2544"'%s'", logfile->buf);2545return-1;2546}2547 logfd =open(logfile->buf, oflags,0666);2548}25492550if(logfd <0) {2551strbuf_addf(err,"unable to append to%s:%s",2552 logfile->buf,strerror(errno));2553return-1;2554}2555}25562557adjust_shared_perm(logfile->buf);2558close(logfd);2559return0;2560}256125622563intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)2564{2565int ret;2566struct strbuf sb = STRBUF_INIT;25672568 ret =log_ref_setup(refname, &sb, err, force_create);2569strbuf_release(&sb);2570return ret;2571}25722573static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,2574const unsigned char*new_sha1,2575const char*committer,const char*msg)2576{2577int msglen, written;2578unsigned maxlen, len;2579char*logrec;25802581 msglen = msg ?strlen(msg) :0;2582 maxlen =strlen(committer) + msglen +100;2583 logrec =xmalloc(maxlen);2584 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2585sha1_to_hex(old_sha1),2586sha1_to_hex(new_sha1),2587 committer);2588if(msglen)2589 len +=copy_reflog_msg(logrec + len -1, msg) -1;25902591 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2592free(logrec);2593if(written != len)2594return-1;25952596return0;2597}25982599static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,2600const unsigned char*new_sha1,const char*msg,2601struct strbuf *logfile,int flags,2602struct strbuf *err)2603{2604int logfd, result, oflags = O_APPEND | O_WRONLY;26052606if(log_all_ref_updates <0)2607 log_all_ref_updates = !is_bare_repository();26082609 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);26102611if(result)2612return result;26132614 logfd =open(logfile->buf, oflags);2615if(logfd <0)2616return0;2617 result =log_ref_write_fd(logfd, old_sha1, new_sha1,2618git_committer_info(0), msg);2619if(result) {2620strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2621strerror(errno));2622close(logfd);2623return-1;2624}2625if(close(logfd)) {2626strbuf_addf(err,"unable to append to%s:%s", logfile->buf,2627strerror(errno));2628return-1;2629}2630return0;2631}26322633static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2634const unsigned char*new_sha1,const char*msg,2635int flags,struct strbuf *err)2636{2637returnfiles_log_ref_write(refname, old_sha1, new_sha1, msg, flags,2638 err);2639}26402641intfiles_log_ref_write(const char*refname,const unsigned char*old_sha1,2642const unsigned char*new_sha1,const char*msg,2643int flags,struct strbuf *err)2644{2645struct strbuf sb = STRBUF_INIT;2646int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,2647 err);2648strbuf_release(&sb);2649return ret;2650}26512652/*2653 * Write sha1 into the open lockfile, then close the lockfile. On2654 * errors, rollback the lockfile, fill in *err and2655 * return -1.2656 */2657static intwrite_ref_to_lockfile(struct ref_lock *lock,2658const unsigned char*sha1,struct strbuf *err)2659{2660static char term ='\n';2661struct object *o;2662int fd;26632664 o =parse_object(sha1);2665if(!o) {2666strbuf_addf(err,2667"Trying to write ref%swith nonexistent object%s",2668 lock->ref_name,sha1_to_hex(sha1));2669unlock_ref(lock);2670return-1;2671}2672if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2673strbuf_addf(err,2674"Trying to write non-commit object%sto branch%s",2675sha1_to_hex(sha1), lock->ref_name);2676unlock_ref(lock);2677return-1;2678}2679 fd =get_lock_file_fd(lock->lk);2680if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||2681write_in_full(fd, &term,1) !=1||2682close_ref(lock) <0) {2683strbuf_addf(err,2684"Couldn't write%s",get_lock_file_path(lock->lk));2685unlock_ref(lock);2686return-1;2687}2688return0;2689}26902691/*2692 * Commit a change to a loose reference that has already been written2693 * to the loose reference lockfile. Also update the reflogs if2694 * necessary, using the specified lockmsg (which can be NULL).2695 */2696static intcommit_ref_update(struct ref_lock *lock,2697const unsigned char*sha1,const char*logmsg,2698int flags,struct strbuf *err)2699{2700clear_loose_ref_cache(&ref_cache);2701if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||2702(strcmp(lock->ref_name, lock->orig_ref_name) &&2703log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {2704char*old_msg =strbuf_detach(err, NULL);2705strbuf_addf(err,"Cannot update the ref '%s':%s",2706 lock->ref_name, old_msg);2707free(old_msg);2708unlock_ref(lock);2709return-1;2710}2711if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2712/*2713 * Special hack: If a branch is updated directly and HEAD2714 * points to it (may happen on the remote side of a push2715 * for example) then logically the HEAD reflog should be2716 * updated too.2717 * A generic solution implies reverse symref information,2718 * but finding all symrefs pointing to the given branch2719 * would be rather costly for this rare event (the direct2720 * update of a branch) to be worth it. So let's cheat and2721 * check with HEAD only which should cover 99% of all usage2722 * scenarios (even 100% of the default ones).2723 */2724unsigned char head_sha1[20];2725int head_flag;2726const char*head_ref;2727 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,2728 head_sha1, &head_flag);2729if(head_ref && (head_flag & REF_ISSYMREF) &&2730!strcmp(head_ref, lock->ref_name)) {2731struct strbuf log_err = STRBUF_INIT;2732if(log_ref_write("HEAD", lock->old_oid.hash, sha1,2733 logmsg,0, &log_err)) {2734error("%s", log_err.buf);2735strbuf_release(&log_err);2736}2737}2738}2739if(commit_ref(lock)) {2740error("Couldn't set%s", lock->ref_name);2741unlock_ref(lock);2742return-1;2743}27442745unlock_ref(lock);2746return0;2747}27482749static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2750{2751int ret = -1;2752#ifndef NO_SYMLINK_HEAD2753char*ref_path =get_locked_file_path(lock->lk);2754unlink(ref_path);2755 ret =symlink(target, ref_path);2756free(ref_path);27572758if(ret)2759fprintf(stderr,"no symlink - falling back to symbolic ref\n");2760#endif2761return ret;2762}27632764static voidupdate_symref_reflog(struct ref_lock *lock,const char*refname,2765const char*target,const char*logmsg)2766{2767struct strbuf err = STRBUF_INIT;2768unsigned char new_sha1[20];2769if(logmsg && !read_ref(target, new_sha1) &&2770log_ref_write(refname, lock->old_oid.hash, new_sha1, logmsg,0, &err)) {2771error("%s", err.buf);2772strbuf_release(&err);2773}2774}27752776static intcreate_symref_locked(struct ref_lock *lock,const char*refname,2777const char*target,const char*logmsg)2778{2779if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2780update_symref_reflog(lock, refname, target, logmsg);2781return0;2782}27832784if(!fdopen_lock_file(lock->lk,"w"))2785returnerror("unable to fdopen%s:%s",2786 lock->lk->tempfile.filename.buf,strerror(errno));27872788update_symref_reflog(lock, refname, target, logmsg);27892790/* no error check; commit_ref will check ferror */2791fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2792if(commit_ref(lock) <0)2793returnerror("unable to write symref for%s:%s", refname,2794strerror(errno));2795return0;2796}27972798intcreate_symref(const char*refname,const char*target,const char*logmsg)2799{2800struct strbuf err = STRBUF_INIT;2801struct ref_lock *lock;2802int ret;28032804 lock =lock_ref_sha1_basic(refname, NULL, NULL, NULL, REF_NODEREF, NULL,2805&err);2806if(!lock) {2807error("%s", err.buf);2808strbuf_release(&err);2809return-1;2810}28112812 ret =create_symref_locked(lock, refname, target, logmsg);2813unlock_ref(lock);2814return ret;2815}28162817intreflog_exists(const char*refname)2818{2819struct stat st;28202821return!lstat(git_path("logs/%s", refname), &st) &&2822S_ISREG(st.st_mode);2823}28242825intdelete_reflog(const char*refname)2826{2827returnremove_path(git_path("logs/%s", refname));2828}28292830static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2831{2832unsigned char osha1[20], nsha1[20];2833char*email_end, *message;2834unsigned long timestamp;2835int tz;28362837/* old SP new SP name <email> SP time TAB msg LF */2838if(sb->len <83|| sb->buf[sb->len -1] !='\n'||2839get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||2840get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||2841!(email_end =strchr(sb->buf +82,'>')) ||2842 email_end[1] !=' '||2843!(timestamp =strtoul(email_end +2, &message,10)) ||2844!message || message[0] !=' '||2845(message[1] !='+'&& message[1] !='-') ||2846!isdigit(message[2]) || !isdigit(message[3]) ||2847!isdigit(message[4]) || !isdigit(message[5]))2848return0;/* corrupt? */2849 email_end[1] ='\0';2850 tz =strtol(message +1, NULL,10);2851if(message[6] !='\t')2852 message +=6;2853else2854 message +=7;2855returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);2856}28572858static char*find_beginning_of_line(char*bob,char*scan)2859{2860while(bob < scan && *(--scan) !='\n')2861;/* keep scanning backwards */2862/*2863 * Return either beginning of the buffer, or LF at the end of2864 * the previous line.2865 */2866return scan;2867}28682869intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)2870{2871struct strbuf sb = STRBUF_INIT;2872FILE*logfp;2873long pos;2874int ret =0, at_tail =1;28752876 logfp =fopen(git_path("logs/%s", refname),"r");2877if(!logfp)2878return-1;28792880/* Jump to the end */2881if(fseek(logfp,0, SEEK_END) <0)2882returnerror("cannot seek back reflog for%s:%s",2883 refname,strerror(errno));2884 pos =ftell(logfp);2885while(!ret &&0< pos) {2886int cnt;2887size_t nread;2888char buf[BUFSIZ];2889char*endp, *scanp;28902891/* Fill next block from the end */2892 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2893if(fseek(logfp, pos - cnt, SEEK_SET))2894returnerror("cannot seek back reflog for%s:%s",2895 refname,strerror(errno));2896 nread =fread(buf, cnt,1, logfp);2897if(nread !=1)2898returnerror("cannot read%dbytes from reflog for%s:%s",2899 cnt, refname,strerror(errno));2900 pos -= cnt;29012902 scanp = endp = buf + cnt;2903if(at_tail && scanp[-1] =='\n')2904/* Looking at the final LF at the end of the file */2905 scanp--;2906 at_tail =0;29072908while(buf < scanp) {2909/*2910 * terminating LF of the previous line, or the beginning2911 * of the buffer.2912 */2913char*bp;29142915 bp =find_beginning_of_line(buf, scanp);29162917if(*bp =='\n') {2918/*2919 * The newline is the end of the previous line,2920 * so we know we have complete line starting2921 * at (bp + 1). Prefix it onto any prior data2922 * we collected for the line and process it.2923 */2924strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2925 scanp = bp;2926 endp = bp +1;2927 ret =show_one_reflog_ent(&sb, fn, cb_data);2928strbuf_reset(&sb);2929if(ret)2930break;2931}else if(!pos) {2932/*2933 * We are at the start of the buffer, and the2934 * start of the file; there is no previous2935 * line, and we have everything for this one.2936 * Process it, and we can end the loop.2937 */2938strbuf_splice(&sb,0,0, buf, endp - buf);2939 ret =show_one_reflog_ent(&sb, fn, cb_data);2940strbuf_reset(&sb);2941break;2942}29432944if(bp == buf) {2945/*2946 * We are at the start of the buffer, and there2947 * is more file to read backwards. Which means2948 * we are in the middle of a line. Note that we2949 * may get here even if *bp was a newline; that2950 * just means we are at the exact end of the2951 * previous line, rather than some spot in the2952 * middle.2953 *2954 * Save away what we have to be combined with2955 * the data from the next read.2956 */2957strbuf_splice(&sb,0,0, buf, endp - buf);2958break;2959}2960}29612962}2963if(!ret && sb.len)2964die("BUG: reverse reflog parser had leftover data");29652966fclose(logfp);2967strbuf_release(&sb);2968return ret;2969}29702971intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)2972{2973FILE*logfp;2974struct strbuf sb = STRBUF_INIT;2975int ret =0;29762977 logfp =fopen(git_path("logs/%s", refname),"r");2978if(!logfp)2979return-1;29802981while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2982 ret =show_one_reflog_ent(&sb, fn, cb_data);2983fclose(logfp);2984strbuf_release(&sb);2985return ret;2986}2987/*2988 * Call fn for each reflog in the namespace indicated by name. name2989 * must be empty or end with '/'. Name will be used as a scratch2990 * space, but its contents will be restored before return.2991 */2992static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)2993{2994DIR*d =opendir(git_path("logs/%s", name->buf));2995int retval =0;2996struct dirent *de;2997int oldlen = name->len;29982999if(!d)3000return name->len ? errno :0;30013002while((de =readdir(d)) != NULL) {3003struct stat st;30043005if(de->d_name[0] =='.')3006continue;3007if(ends_with(de->d_name,".lock"))3008continue;3009strbuf_addstr(name, de->d_name);3010if(stat(git_path("logs/%s", name->buf), &st) <0) {3011;/* silently ignore */3012}else{3013if(S_ISDIR(st.st_mode)) {3014strbuf_addch(name,'/');3015 retval =do_for_each_reflog(name, fn, cb_data);3016}else{3017struct object_id oid;30183019if(read_ref_full(name->buf,0, oid.hash, NULL))3020 retval =error("bad ref for%s", name->buf);3021else3022 retval =fn(name->buf, &oid,0, cb_data);3023}3024if(retval)3025break;3026}3027strbuf_setlen(name, oldlen);3028}3029closedir(d);3030return retval;3031}30323033intfor_each_reflog(each_ref_fn fn,void*cb_data)3034{3035int retval;3036struct strbuf name;3037strbuf_init(&name, PATH_MAX);3038 retval =do_for_each_reflog(&name, fn, cb_data);3039strbuf_release(&name);3040return retval;3041}30423043static intref_update_reject_duplicates(struct string_list *refnames,3044struct strbuf *err)3045{3046int i, n = refnames->nr;30473048assert(err);30493050for(i =1; i < n; i++)3051if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3052strbuf_addf(err,3053"Multiple updates for ref '%s' not allowed.",3054 refnames->items[i].string);3055return1;3056}3057return0;3058}30593060intref_transaction_commit(struct ref_transaction *transaction,3061struct strbuf *err)3062{3063int ret =0, i;3064int n = transaction->nr;3065struct ref_update **updates = transaction->updates;3066struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3067struct string_list_item *ref_to_delete;3068struct string_list affected_refnames = STRING_LIST_INIT_NODUP;30693070assert(err);30713072if(transaction->state != REF_TRANSACTION_OPEN)3073die("BUG: commit called for transaction that is not open");30743075if(!n) {3076 transaction->state = REF_TRANSACTION_CLOSED;3077return0;3078}30793080/* Fail if a refname appears more than once in the transaction: */3081for(i =0; i < n; i++)3082string_list_append(&affected_refnames, updates[i]->refname);3083string_list_sort(&affected_refnames);3084if(ref_update_reject_duplicates(&affected_refnames, err)) {3085 ret = TRANSACTION_GENERIC_ERROR;3086goto cleanup;3087}30883089/*3090 * Acquire all locks, verify old values if provided, check3091 * that new values are valid, and write new values to the3092 * lockfiles, ready to be activated. Only keep one lockfile3093 * open at a time to avoid running out of file descriptors.3094 */3095for(i =0; i < n; i++) {3096struct ref_update *update = updates[i];30973098if((update->flags & REF_HAVE_NEW) &&3099is_null_sha1(update->new_sha1))3100 update->flags |= REF_DELETING;3101 update->lock =lock_ref_sha1_basic(3102 update->refname,3103((update->flags & REF_HAVE_OLD) ?3104 update->old_sha1 : NULL),3105&affected_refnames, NULL,3106 update->flags,3107&update->type,3108 err);3109if(!update->lock) {3110char*reason;31113112 ret = (errno == ENOTDIR)3113? TRANSACTION_NAME_CONFLICT3114: TRANSACTION_GENERIC_ERROR;3115 reason =strbuf_detach(err, NULL);3116strbuf_addf(err,"cannot lock ref '%s':%s",3117 update->refname, reason);3118free(reason);3119goto cleanup;3120}3121if((update->flags & REF_HAVE_NEW) &&3122!(update->flags & REF_DELETING)) {3123int overwriting_symref = ((update->type & REF_ISSYMREF) &&3124(update->flags & REF_NODEREF));31253126if(!overwriting_symref &&3127!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3128/*3129 * The reference already has the desired3130 * value, so we don't need to write it.3131 */3132}else if(write_ref_to_lockfile(update->lock,3133 update->new_sha1,3134 err)) {3135char*write_err =strbuf_detach(err, NULL);31363137/*3138 * The lock was freed upon failure of3139 * write_ref_to_lockfile():3140 */3141 update->lock = NULL;3142strbuf_addf(err,3143"cannot update the ref '%s':%s",3144 update->refname, write_err);3145free(write_err);3146 ret = TRANSACTION_GENERIC_ERROR;3147goto cleanup;3148}else{3149 update->flags |= REF_NEEDS_COMMIT;3150}3151}3152if(!(update->flags & REF_NEEDS_COMMIT)) {3153/*3154 * We didn't have to write anything to the lockfile.3155 * Close it to free up the file descriptor:3156 */3157if(close_ref(update->lock)) {3158strbuf_addf(err,"Couldn't close%s.lock",3159 update->refname);3160goto cleanup;3161}3162}3163}31643165/* Perform updates first so live commits remain referenced */3166for(i =0; i < n; i++) {3167struct ref_update *update = updates[i];31683169if(update->flags & REF_NEEDS_COMMIT) {3170if(commit_ref_update(update->lock,3171 update->new_sha1, update->msg,3172 update->flags, err)) {3173/* freed by commit_ref_update(): */3174 update->lock = NULL;3175 ret = TRANSACTION_GENERIC_ERROR;3176goto cleanup;3177}else{3178/* freed by commit_ref_update(): */3179 update->lock = NULL;3180}3181}3182}31833184/* Perform deletes now that updates are safely completed */3185for(i =0; i < n; i++) {3186struct ref_update *update = updates[i];31873188if(update->flags & REF_DELETING) {3189if(delete_ref_loose(update->lock, update->type, err)) {3190 ret = TRANSACTION_GENERIC_ERROR;3191goto cleanup;3192}31933194if(!(update->flags & REF_ISPRUNING))3195string_list_append(&refs_to_delete,3196 update->lock->ref_name);3197}3198}31993200if(repack_without_refs(&refs_to_delete, err)) {3201 ret = TRANSACTION_GENERIC_ERROR;3202goto cleanup;3203}3204for_each_string_list_item(ref_to_delete, &refs_to_delete)3205unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3206clear_loose_ref_cache(&ref_cache);32073208cleanup:3209 transaction->state = REF_TRANSACTION_CLOSED;32103211for(i =0; i < n; i++)3212if(updates[i]->lock)3213unlock_ref(updates[i]->lock);3214string_list_clear(&refs_to_delete,0);3215string_list_clear(&affected_refnames,0);3216return ret;3217}32183219static intref_present(const char*refname,3220const struct object_id *oid,int flags,void*cb_data)3221{3222struct string_list *affected_refnames = cb_data;32233224returnstring_list_has_string(affected_refnames, refname);3225}32263227intinitial_ref_transaction_commit(struct ref_transaction *transaction,3228struct strbuf *err)3229{3230int ret =0, i;3231int n = transaction->nr;3232struct ref_update **updates = transaction->updates;3233struct string_list affected_refnames = STRING_LIST_INIT_NODUP;32343235assert(err);32363237if(transaction->state != REF_TRANSACTION_OPEN)3238die("BUG: commit called for transaction that is not open");32393240/* Fail if a refname appears more than once in the transaction: */3241for(i =0; i < n; i++)3242string_list_append(&affected_refnames, updates[i]->refname);3243string_list_sort(&affected_refnames);3244if(ref_update_reject_duplicates(&affected_refnames, err)) {3245 ret = TRANSACTION_GENERIC_ERROR;3246goto cleanup;3247}32483249/*3250 * It's really undefined to call this function in an active3251 * repository or when there are existing references: we are3252 * only locking and changing packed-refs, so (1) any3253 * simultaneous processes might try to change a reference at3254 * the same time we do, and (2) any existing loose versions of3255 * the references that we are setting would have precedence3256 * over our values. But some remote helpers create the remote3257 * "HEAD" and "master" branches before calling this function,3258 * so here we really only check that none of the references3259 * that we are creating already exists.3260 */3261if(for_each_rawref(ref_present, &affected_refnames))3262die("BUG: initial ref transaction called with existing refs");32633264for(i =0; i < n; i++) {3265struct ref_update *update = updates[i];32663267if((update->flags & REF_HAVE_OLD) &&3268!is_null_sha1(update->old_sha1))3269die("BUG: initial ref transaction with old_sha1 set");3270if(verify_refname_available(update->refname,3271&affected_refnames, NULL,3272 err)) {3273 ret = TRANSACTION_NAME_CONFLICT;3274goto cleanup;3275}3276}32773278if(lock_packed_refs(0)) {3279strbuf_addf(err,"unable to lock packed-refs file:%s",3280strerror(errno));3281 ret = TRANSACTION_GENERIC_ERROR;3282goto cleanup;3283}32843285for(i =0; i < n; i++) {3286struct ref_update *update = updates[i];32873288if((update->flags & REF_HAVE_NEW) &&3289!is_null_sha1(update->new_sha1))3290add_packed_ref(update->refname, update->new_sha1);3291}32923293if(commit_packed_refs()) {3294strbuf_addf(err,"unable to commit packed-refs file:%s",3295strerror(errno));3296 ret = TRANSACTION_GENERIC_ERROR;3297goto cleanup;3298}32993300cleanup:3301 transaction->state = REF_TRANSACTION_CLOSED;3302string_list_clear(&affected_refnames,0);3303return ret;3304}33053306struct expire_reflog_cb {3307unsigned int flags;3308 reflog_expiry_should_prune_fn *should_prune_fn;3309void*policy_cb;3310FILE*newlog;3311unsigned char last_kept_sha1[20];3312};33133314static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,3315const char*email,unsigned long timestamp,int tz,3316const char*message,void*cb_data)3317{3318struct expire_reflog_cb *cb = cb_data;3319struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;33203321if(cb->flags & EXPIRE_REFLOGS_REWRITE)3322 osha1 = cb->last_kept_sha1;33233324if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,3325 message, policy_cb)) {3326if(!cb->newlog)3327printf("would prune%s", message);3328else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3329printf("prune%s", message);3330}else{3331if(cb->newlog) {3332fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",3333sha1_to_hex(osha1),sha1_to_hex(nsha1),3334 email, timestamp, tz, message);3335hashcpy(cb->last_kept_sha1, nsha1);3336}3337if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3338printf("keep%s", message);3339}3340return0;3341}33423343intreflog_expire(const char*refname,const unsigned char*sha1,3344unsigned int flags,3345 reflog_expiry_prepare_fn prepare_fn,3346 reflog_expiry_should_prune_fn should_prune_fn,3347 reflog_expiry_cleanup_fn cleanup_fn,3348void*policy_cb_data)3349{3350static struct lock_file reflog_lock;3351struct expire_reflog_cb cb;3352struct ref_lock *lock;3353char*log_file;3354int status =0;3355int type;3356struct strbuf err = STRBUF_INIT;33573358memset(&cb,0,sizeof(cb));3359 cb.flags = flags;3360 cb.policy_cb = policy_cb_data;3361 cb.should_prune_fn = should_prune_fn;33623363/*3364 * The reflog file is locked by holding the lock on the3365 * reference itself, plus we might need to update the3366 * reference if --updateref was specified:3367 */3368 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);3369if(!lock) {3370error("cannot lock ref '%s':%s", refname, err.buf);3371strbuf_release(&err);3372return-1;3373}3374if(!reflog_exists(refname)) {3375unlock_ref(lock);3376return0;3377}33783379 log_file =git_pathdup("logs/%s", refname);3380if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3381/*3382 * Even though holding $GIT_DIR/logs/$reflog.lock has3383 * no locking implications, we use the lock_file3384 * machinery here anyway because it does a lot of the3385 * work we need, including cleaning up if the program3386 * exits unexpectedly.3387 */3388if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3389struct strbuf err = STRBUF_INIT;3390unable_to_lock_message(log_file, errno, &err);3391error("%s", err.buf);3392strbuf_release(&err);3393goto failure;3394}3395 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3396if(!cb.newlog) {3397error("cannot fdopen%s(%s)",3398get_lock_file_path(&reflog_lock),strerror(errno));3399goto failure;3400}3401}34023403(*prepare_fn)(refname, sha1, cb.policy_cb);3404for_each_reflog_ent(refname, expire_reflog_ent, &cb);3405(*cleanup_fn)(cb.policy_cb);34063407if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3408/*3409 * It doesn't make sense to adjust a reference pointed3410 * to by a symbolic ref based on expiring entries in3411 * the symbolic reference's reflog. Nor can we update3412 * a reference if there are no remaining reflog3413 * entries.3414 */3415int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3416!(type & REF_ISSYMREF) &&3417!is_null_sha1(cb.last_kept_sha1);34183419if(close_lock_file(&reflog_lock)) {3420 status |=error("couldn't write%s:%s", log_file,3421strerror(errno));3422}else if(update &&3423(write_in_full(get_lock_file_fd(lock->lk),3424sha1_to_hex(cb.last_kept_sha1),40) !=40||3425write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3426close_ref(lock) <0)) {3427 status |=error("couldn't write%s",3428get_lock_file_path(lock->lk));3429rollback_lock_file(&reflog_lock);3430}else if(commit_lock_file(&reflog_lock)) {3431 status |=error("unable to write reflog '%s' (%s)",3432 log_file,strerror(errno));3433}else if(update &&commit_ref(lock)) {3434 status |=error("couldn't set%s", lock->ref_name);3435}3436}3437free(log_file);3438unlock_ref(lock);3439return status;34403441 failure:3442rollback_lock_file(&reflog_lock);3443free(log_file);3444unlock_ref(lock);3445return-1;3446}