1#include"cache.h" 2#include"lockfile.h" 3#include"refs.h" 4#include"refs/refs-internal.h" 5#include"object.h" 6#include"tag.h" 7#include"dir.h" 8#include"string-list.h" 9 10struct ref_lock { 11char*ref_name; 12char*orig_ref_name; 13struct lock_file *lk; 14struct object_id old_oid; 15}; 16 17/* 18 * How to handle various characters in refnames: 19 * 0: An acceptable character for refs 20 * 1: End-of-component 21 * 2: ., look for a preceding . to reject .. in refs 22 * 3: {, look for a preceding @ to reject @{ in refs 23 * 4: A bad character: ASCII control characters, and 24 * ":", "?", "[", "\", "^", "~", SP, or TAB 25 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set 26 */ 27static unsigned char refname_disposition[256] = { 281,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 294,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 304,0,0,0,0,0,0,0,0,0,5,0,0,0,2,1, 310,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 320,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 330,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 340,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 350,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 36}; 37 38/* 39 * Try to read one refname component from the front of refname. 40 * Return the length of the component found, or -1 if the component is 41 * not legal. It is legal if it is something reasonable to have under 42 * ".git/refs/"; We do not like it if: 43 * 44 * - any path component of it begins with ".", or 45 * - it has double dots "..", or 46 * - it has ASCII control characters, or 47 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or 48 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or 49 * - it ends with a "/", or 50 * - it ends with ".lock", or 51 * - it contains a "@{" portion 52 */ 53static intcheck_refname_component(const char*refname,int*flags) 54{ 55const char*cp; 56char last ='\0'; 57 58for(cp = refname; ; cp++) { 59int ch = *cp &255; 60unsigned char disp = refname_disposition[ch]; 61switch(disp) { 62case1: 63goto out; 64case2: 65if(last =='.') 66return-1;/* Refname contains "..". */ 67break; 68case3: 69if(last =='@') 70return-1;/* Refname contains "@{". */ 71break; 72case4: 73return-1; 74case5: 75if(!(*flags & REFNAME_REFSPEC_PATTERN)) 76return-1;/* refspec can't be a pattern */ 77 78/* 79 * Unset the pattern flag so that we only accept 80 * a single asterisk for one side of refspec. 81 */ 82*flags &= ~ REFNAME_REFSPEC_PATTERN; 83break; 84} 85 last = ch; 86} 87out: 88if(cp == refname) 89return0;/* Component has zero length. */ 90if(refname[0] =='.') 91return-1;/* Component starts with '.'. */ 92if(cp - refname >= LOCK_SUFFIX_LEN && 93!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 94return-1;/* Refname ends with ".lock". */ 95return cp - refname; 96} 97 98intcheck_refname_format(const char*refname,int flags) 99{ 100int component_len, component_count =0; 101 102if(!strcmp(refname,"@")) 103/* Refname is a single character '@'. */ 104return-1; 105 106while(1) { 107/* We are at the start of a path component. */ 108 component_len =check_refname_component(refname, &flags); 109if(component_len <=0) 110return-1; 111 112 component_count++; 113if(refname[component_len] =='\0') 114break; 115/* Skip to next component. */ 116 refname += component_len +1; 117} 118 119if(refname[component_len -1] =='.') 120return-1;/* Refname ends with '.'. */ 121if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 122return-1;/* Refname has only one component. */ 123return0; 124} 125 126struct ref_entry; 127 128/* 129 * Information used (along with the information in ref_entry) to 130 * describe a single cached reference. This data structure only 131 * occurs embedded in a union in struct ref_entry, and only when 132 * (ref_entry->flag & REF_DIR) is zero. 133 */ 134struct ref_value { 135/* 136 * The name of the object to which this reference resolves 137 * (which may be a tag object). If REF_ISBROKEN, this is 138 * null. If REF_ISSYMREF, then this is the name of the object 139 * referred to by the last reference in the symlink chain. 140 */ 141struct object_id oid; 142 143/* 144 * If REF_KNOWS_PEELED, then this field holds the peeled value 145 * of this reference, or null if the reference is known not to 146 * be peelable. See the documentation for peel_ref() for an 147 * exact definition of "peelable". 148 */ 149struct object_id peeled; 150}; 151 152struct ref_cache; 153 154/* 155 * Information used (along with the information in ref_entry) to 156 * describe a level in the hierarchy of references. This data 157 * structure only occurs embedded in a union in struct ref_entry, and 158 * only when (ref_entry.flag & REF_DIR) is set. In that case, 159 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 160 * in the directory have already been read: 161 * 162 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 163 * or packed references, already read. 164 * 165 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 166 * references that hasn't been read yet (nor has any of its 167 * subdirectories). 168 * 169 * Entries within a directory are stored within a growable array of 170 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 171 * sorted are sorted by their component name in strcmp() order and the 172 * remaining entries are unsorted. 173 * 174 * Loose references are read lazily, one directory at a time. When a 175 * directory of loose references is read, then all of the references 176 * in that directory are stored, and REF_INCOMPLETE stubs are created 177 * for any subdirectories, but the subdirectories themselves are not 178 * read. The reading is triggered by get_ref_dir(). 179 */ 180struct ref_dir { 181int nr, alloc; 182 183/* 184 * Entries with index 0 <= i < sorted are sorted by name. New 185 * entries are appended to the list unsorted, and are sorted 186 * only when required; thus we avoid the need to sort the list 187 * after the addition of every reference. 188 */ 189int sorted; 190 191/* A pointer to the ref_cache that contains this ref_dir. */ 192struct ref_cache *ref_cache; 193 194struct ref_entry **entries; 195}; 196 197/* 198 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 199 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 200 * public values; see refs.h. 201 */ 202 203/* 204 * The field ref_entry->u.value.peeled of this value entry contains 205 * the correct peeled value for the reference, which might be 206 * null_sha1 if the reference is not a tag or if it is broken. 207 */ 208#define REF_KNOWS_PEELED 0x10 209 210/* ref_entry represents a directory of references */ 211#define REF_DIR 0x20 212 213/* 214 * Entry has not yet been read from disk (used only for REF_DIR 215 * entries representing loose references) 216 */ 217#define REF_INCOMPLETE 0x40 218 219/* 220 * A ref_entry represents either a reference or a "subdirectory" of 221 * references. 222 * 223 * Each directory in the reference namespace is represented by a 224 * ref_entry with (flags & REF_DIR) set and containing a subdir member 225 * that holds the entries in that directory that have been read so 226 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 227 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 228 * used for loose reference directories. 229 * 230 * References are represented by a ref_entry with (flags & REF_DIR) 231 * unset and a value member that describes the reference's value. The 232 * flag member is at the ref_entry level, but it is also needed to 233 * interpret the contents of the value field (in other words, a 234 * ref_value object is not very much use without the enclosing 235 * ref_entry). 236 * 237 * Reference names cannot end with slash and directories' names are 238 * always stored with a trailing slash (except for the top-level 239 * directory, which is always denoted by ""). This has two nice 240 * consequences: (1) when the entries in each subdir are sorted 241 * lexicographically by name (as they usually are), the references in 242 * a whole tree can be generated in lexicographic order by traversing 243 * the tree in left-to-right, depth-first order; (2) the names of 244 * references and subdirectories cannot conflict, and therefore the 245 * presence of an empty subdirectory does not block the creation of a 246 * similarly-named reference. (The fact that reference names with the 247 * same leading components can conflict *with each other* is a 248 * separate issue that is regulated by verify_refname_available().) 249 * 250 * Please note that the name field contains the fully-qualified 251 * reference (or subdirectory) name. Space could be saved by only 252 * storing the relative names. But that would require the full names 253 * to be generated on the fly when iterating in do_for_each_ref(), and 254 * would break callback functions, who have always been able to assume 255 * that the name strings that they are passed will not be freed during 256 * the iteration. 257 */ 258struct ref_entry { 259unsigned char flag;/* ISSYMREF? ISPACKED? */ 260union{ 261struct ref_value value;/* if not (flags&REF_DIR) */ 262struct ref_dir subdir;/* if (flags&REF_DIR) */ 263} u; 264/* 265 * The full name of the reference (e.g., "refs/heads/master") 266 * or the full name of the directory with a trailing slash 267 * (e.g., "refs/heads/"): 268 */ 269char name[FLEX_ARRAY]; 270}; 271 272static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 273static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len); 274static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 275const char*dirname,size_t len, 276int incomplete); 277static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry); 278 279static struct ref_dir *get_ref_dir(struct ref_entry *entry) 280{ 281struct ref_dir *dir; 282assert(entry->flag & REF_DIR); 283 dir = &entry->u.subdir; 284if(entry->flag & REF_INCOMPLETE) { 285read_loose_refs(entry->name, dir); 286 287/* 288 * Manually add refs/bisect, which, being 289 * per-worktree, might not appear in the directory 290 * listing for refs/ in the main repo. 291 */ 292if(!strcmp(entry->name,"refs/")) { 293int pos =search_ref_dir(dir,"refs/bisect/",12); 294if(pos <0) { 295struct ref_entry *child_entry; 296 child_entry =create_dir_entry(dir->ref_cache, 297"refs/bisect/", 29812,1); 299add_entry_to_dir(dir, child_entry); 300read_loose_refs("refs/bisect", 301&child_entry->u.subdir); 302} 303} 304 entry->flag &= ~REF_INCOMPLETE; 305} 306return dir; 307} 308 309intrefname_is_safe(const char*refname) 310{ 311if(starts_with(refname,"refs/")) { 312char*buf; 313int result; 314 315 buf =xmalloc(strlen(refname) +1); 316/* 317 * Does the refname try to escape refs/? 318 * For example: refs/foo/../bar is safe but refs/foo/../../bar 319 * is not. 320 */ 321 result = !normalize_path_copy(buf, refname +strlen("refs/")); 322free(buf); 323return result; 324} 325while(*refname) { 326if(!isupper(*refname) && *refname !='_') 327return0; 328 refname++; 329} 330return1; 331} 332 333static struct ref_entry *create_ref_entry(const char*refname, 334const unsigned char*sha1,int flag, 335int check_name) 336{ 337int len; 338struct ref_entry *ref; 339 340if(check_name && 341check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 342die("Reference has invalid format: '%s'", refname); 343 len =strlen(refname) +1; 344 ref =xmalloc(sizeof(struct ref_entry) + len); 345hashcpy(ref->u.value.oid.hash, sha1); 346oidclr(&ref->u.value.peeled); 347memcpy(ref->name, refname, len); 348 ref->flag = flag; 349return ref; 350} 351 352static voidclear_ref_dir(struct ref_dir *dir); 353 354static voidfree_ref_entry(struct ref_entry *entry) 355{ 356if(entry->flag & REF_DIR) { 357/* 358 * Do not use get_ref_dir() here, as that might 359 * trigger the reading of loose refs. 360 */ 361clear_ref_dir(&entry->u.subdir); 362} 363free(entry); 364} 365 366/* 367 * Add a ref_entry to the end of dir (unsorted). Entry is always 368 * stored directly in dir; no recursion into subdirectories is 369 * done. 370 */ 371static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 372{ 373ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 374 dir->entries[dir->nr++] = entry; 375/* optimize for the case that entries are added in order */ 376if(dir->nr ==1|| 377(dir->nr == dir->sorted +1&& 378strcmp(dir->entries[dir->nr -2]->name, 379 dir->entries[dir->nr -1]->name) <0)) 380 dir->sorted = dir->nr; 381} 382 383/* 384 * Clear and free all entries in dir, recursively. 385 */ 386static voidclear_ref_dir(struct ref_dir *dir) 387{ 388int i; 389for(i =0; i < dir->nr; i++) 390free_ref_entry(dir->entries[i]); 391free(dir->entries); 392 dir->sorted = dir->nr = dir->alloc =0; 393 dir->entries = NULL; 394} 395 396/* 397 * Create a struct ref_entry object for the specified dirname. 398 * dirname is the name of the directory with a trailing slash (e.g., 399 * "refs/heads/") or "" for the top-level directory. 400 */ 401static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 402const char*dirname,size_t len, 403int incomplete) 404{ 405struct ref_entry *direntry; 406 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 407memcpy(direntry->name, dirname, len); 408 direntry->name[len] ='\0'; 409 direntry->u.subdir.ref_cache = ref_cache; 410 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 411return direntry; 412} 413 414static intref_entry_cmp(const void*a,const void*b) 415{ 416struct ref_entry *one = *(struct ref_entry **)a; 417struct ref_entry *two = *(struct ref_entry **)b; 418returnstrcmp(one->name, two->name); 419} 420 421static voidsort_ref_dir(struct ref_dir *dir); 422 423struct string_slice { 424size_t len; 425const char*str; 426}; 427 428static intref_entry_cmp_sslice(const void*key_,const void*ent_) 429{ 430const struct string_slice *key = key_; 431const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 432int cmp =strncmp(key->str, ent->name, key->len); 433if(cmp) 434return cmp; 435return'\0'- (unsigned char)ent->name[key->len]; 436} 437 438/* 439 * Return the index of the entry with the given refname from the 440 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 441 * no such entry is found. dir must already be complete. 442 */ 443static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 444{ 445struct ref_entry **r; 446struct string_slice key; 447 448if(refname == NULL || !dir->nr) 449return-1; 450 451sort_ref_dir(dir); 452 key.len = len; 453 key.str = refname; 454 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 455 ref_entry_cmp_sslice); 456 457if(r == NULL) 458return-1; 459 460return r - dir->entries; 461} 462 463/* 464 * Search for a directory entry directly within dir (without 465 * recursing). Sort dir if necessary. subdirname must be a directory 466 * name (i.e., end in '/'). If mkdir is set, then create the 467 * directory if it is missing; otherwise, return NULL if the desired 468 * directory cannot be found. dir must already be complete. 469 */ 470static struct ref_dir *search_for_subdir(struct ref_dir *dir, 471const char*subdirname,size_t len, 472int mkdir) 473{ 474int entry_index =search_ref_dir(dir, subdirname, len); 475struct ref_entry *entry; 476if(entry_index == -1) { 477if(!mkdir) 478return NULL; 479/* 480 * Since dir is complete, the absence of a subdir 481 * means that the subdir really doesn't exist; 482 * therefore, create an empty record for it but mark 483 * the record complete. 484 */ 485 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 486add_entry_to_dir(dir, entry); 487}else{ 488 entry = dir->entries[entry_index]; 489} 490returnget_ref_dir(entry); 491} 492 493/* 494 * If refname is a reference name, find the ref_dir within the dir 495 * tree that should hold refname. If refname is a directory name 496 * (i.e., ends in '/'), then return that ref_dir itself. dir must 497 * represent the top-level directory and must already be complete. 498 * Sort ref_dirs and recurse into subdirectories as necessary. If 499 * mkdir is set, then create any missing directories; otherwise, 500 * return NULL if the desired directory cannot be found. 501 */ 502static struct ref_dir *find_containing_dir(struct ref_dir *dir, 503const char*refname,int mkdir) 504{ 505const char*slash; 506for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 507size_t dirnamelen = slash - refname +1; 508struct ref_dir *subdir; 509 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 510if(!subdir) { 511 dir = NULL; 512break; 513} 514 dir = subdir; 515} 516 517return dir; 518} 519 520/* 521 * Find the value entry with the given name in dir, sorting ref_dirs 522 * and recursing into subdirectories as necessary. If the name is not 523 * found or it corresponds to a directory entry, return NULL. 524 */ 525static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 526{ 527int entry_index; 528struct ref_entry *entry; 529 dir =find_containing_dir(dir, refname,0); 530if(!dir) 531return NULL; 532 entry_index =search_ref_dir(dir, refname,strlen(refname)); 533if(entry_index == -1) 534return NULL; 535 entry = dir->entries[entry_index]; 536return(entry->flag & REF_DIR) ? NULL : entry; 537} 538 539/* 540 * Remove the entry with the given name from dir, recursing into 541 * subdirectories as necessary. If refname is the name of a directory 542 * (i.e., ends with '/'), then remove the directory and its contents. 543 * If the removal was successful, return the number of entries 544 * remaining in the directory entry that contained the deleted entry. 545 * If the name was not found, return -1. Please note that this 546 * function only deletes the entry from the cache; it does not delete 547 * it from the filesystem or ensure that other cache entries (which 548 * might be symbolic references to the removed entry) are updated. 549 * Nor does it remove any containing dir entries that might be made 550 * empty by the removal. dir must represent the top-level directory 551 * and must already be complete. 552 */ 553static intremove_entry(struct ref_dir *dir,const char*refname) 554{ 555int refname_len =strlen(refname); 556int entry_index; 557struct ref_entry *entry; 558int is_dir = refname[refname_len -1] =='/'; 559if(is_dir) { 560/* 561 * refname represents a reference directory. Remove 562 * the trailing slash; otherwise we will get the 563 * directory *representing* refname rather than the 564 * one *containing* it. 565 */ 566char*dirname =xmemdupz(refname, refname_len -1); 567 dir =find_containing_dir(dir, dirname,0); 568free(dirname); 569}else{ 570 dir =find_containing_dir(dir, refname,0); 571} 572if(!dir) 573return-1; 574 entry_index =search_ref_dir(dir, refname, refname_len); 575if(entry_index == -1) 576return-1; 577 entry = dir->entries[entry_index]; 578 579memmove(&dir->entries[entry_index], 580&dir->entries[entry_index +1], 581(dir->nr - entry_index -1) *sizeof(*dir->entries) 582); 583 dir->nr--; 584if(dir->sorted > entry_index) 585 dir->sorted--; 586free_ref_entry(entry); 587return dir->nr; 588} 589 590/* 591 * Add a ref_entry to the ref_dir (unsorted), recursing into 592 * subdirectories as necessary. dir must represent the top-level 593 * directory. Return 0 on success. 594 */ 595static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 596{ 597 dir =find_containing_dir(dir, ref->name,1); 598if(!dir) 599return-1; 600add_entry_to_dir(dir, ref); 601return0; 602} 603 604/* 605 * Emit a warning and return true iff ref1 and ref2 have the same name 606 * and the same sha1. Die if they have the same name but different 607 * sha1s. 608 */ 609static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 610{ 611if(strcmp(ref1->name, ref2->name)) 612return0; 613 614/* Duplicate name; make sure that they don't conflict: */ 615 616if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 617/* This is impossible by construction */ 618die("Reference directory conflict:%s", ref1->name); 619 620if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 621die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 622 623warning("Duplicated ref:%s", ref1->name); 624return1; 625} 626 627/* 628 * Sort the entries in dir non-recursively (if they are not already 629 * sorted) and remove any duplicate entries. 630 */ 631static voidsort_ref_dir(struct ref_dir *dir) 632{ 633int i, j; 634struct ref_entry *last = NULL; 635 636/* 637 * This check also prevents passing a zero-length array to qsort(), 638 * which is a problem on some platforms. 639 */ 640if(dir->sorted == dir->nr) 641return; 642 643qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 644 645/* Remove any duplicates: */ 646for(i =0, j =0; j < dir->nr; j++) { 647struct ref_entry *entry = dir->entries[j]; 648if(last &&is_dup_ref(last, entry)) 649free_ref_entry(entry); 650else 651 last = dir->entries[i++] = entry; 652} 653 dir->sorted = dir->nr = i; 654} 655 656/* Include broken references in a do_for_each_ref*() iteration: */ 657#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 658 659/* 660 * Return true iff the reference described by entry can be resolved to 661 * an object in the database. Emit a warning if the referred-to 662 * object does not exist. 663 */ 664static intref_resolves_to_object(struct ref_entry *entry) 665{ 666if(entry->flag & REF_ISBROKEN) 667return0; 668if(!has_sha1_file(entry->u.value.oid.hash)) { 669error("%sdoes not point to a valid object!", entry->name); 670return0; 671} 672return1; 673} 674 675/* 676 * current_ref is a performance hack: when iterating over references 677 * using the for_each_ref*() functions, current_ref is set to the 678 * current reference's entry before calling the callback function. If 679 * the callback function calls peel_ref(), then peel_ref() first 680 * checks whether the reference to be peeled is the current reference 681 * (it usually is) and if so, returns that reference's peeled version 682 * if it is available. This avoids a refname lookup in a common case. 683 */ 684static struct ref_entry *current_ref; 685 686typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 687 688struct ref_entry_cb { 689const char*base; 690int trim; 691int flags; 692 each_ref_fn *fn; 693void*cb_data; 694}; 695 696/* 697 * Handle one reference in a do_for_each_ref*()-style iteration, 698 * calling an each_ref_fn for each entry. 699 */ 700static intdo_one_ref(struct ref_entry *entry,void*cb_data) 701{ 702struct ref_entry_cb *data = cb_data; 703struct ref_entry *old_current_ref; 704int retval; 705 706if(!starts_with(entry->name, data->base)) 707return0; 708 709if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 710!ref_resolves_to_object(entry)) 711return0; 712 713/* Store the old value, in case this is a recursive call: */ 714 old_current_ref = current_ref; 715 current_ref = entry; 716 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 717 entry->flag, data->cb_data); 718 current_ref = old_current_ref; 719return retval; 720} 721 722/* 723 * Call fn for each reference in dir that has index in the range 724 * offset <= index < dir->nr. Recurse into subdirectories that are in 725 * that index range, sorting them before iterating. This function 726 * does not sort dir itself; it should be sorted beforehand. fn is 727 * called for all references, including broken ones. 728 */ 729static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 730 each_ref_entry_fn fn,void*cb_data) 731{ 732int i; 733assert(dir->sorted == dir->nr); 734for(i = offset; i < dir->nr; i++) { 735struct ref_entry *entry = dir->entries[i]; 736int retval; 737if(entry->flag & REF_DIR) { 738struct ref_dir *subdir =get_ref_dir(entry); 739sort_ref_dir(subdir); 740 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 741}else{ 742 retval =fn(entry, cb_data); 743} 744if(retval) 745return retval; 746} 747return0; 748} 749 750/* 751 * Call fn for each reference in the union of dir1 and dir2, in order 752 * by refname. Recurse into subdirectories. If a value entry appears 753 * in both dir1 and dir2, then only process the version that is in 754 * dir2. The input dirs must already be sorted, but subdirs will be 755 * sorted as needed. fn is called for all references, including 756 * broken ones. 757 */ 758static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 759struct ref_dir *dir2, 760 each_ref_entry_fn fn,void*cb_data) 761{ 762int retval; 763int i1 =0, i2 =0; 764 765assert(dir1->sorted == dir1->nr); 766assert(dir2->sorted == dir2->nr); 767while(1) { 768struct ref_entry *e1, *e2; 769int cmp; 770if(i1 == dir1->nr) { 771returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 772} 773if(i2 == dir2->nr) { 774returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 775} 776 e1 = dir1->entries[i1]; 777 e2 = dir2->entries[i2]; 778 cmp =strcmp(e1->name, e2->name); 779if(cmp ==0) { 780if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 781/* Both are directories; descend them in parallel. */ 782struct ref_dir *subdir1 =get_ref_dir(e1); 783struct ref_dir *subdir2 =get_ref_dir(e2); 784sort_ref_dir(subdir1); 785sort_ref_dir(subdir2); 786 retval =do_for_each_entry_in_dirs( 787 subdir1, subdir2, fn, cb_data); 788 i1++; 789 i2++; 790}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 791/* Both are references; ignore the one from dir1. */ 792 retval =fn(e2, cb_data); 793 i1++; 794 i2++; 795}else{ 796die("conflict between reference and directory:%s", 797 e1->name); 798} 799}else{ 800struct ref_entry *e; 801if(cmp <0) { 802 e = e1; 803 i1++; 804}else{ 805 e = e2; 806 i2++; 807} 808if(e->flag & REF_DIR) { 809struct ref_dir *subdir =get_ref_dir(e); 810sort_ref_dir(subdir); 811 retval =do_for_each_entry_in_dir( 812 subdir,0, fn, cb_data); 813}else{ 814 retval =fn(e, cb_data); 815} 816} 817if(retval) 818return retval; 819} 820} 821 822/* 823 * Load all of the refs from the dir into our in-memory cache. The hard work 824 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 825 * through all of the sub-directories. We do not even need to care about 826 * sorting, as traversal order does not matter to us. 827 */ 828static voidprime_ref_dir(struct ref_dir *dir) 829{ 830int i; 831for(i =0; i < dir->nr; i++) { 832struct ref_entry *entry = dir->entries[i]; 833if(entry->flag & REF_DIR) 834prime_ref_dir(get_ref_dir(entry)); 835} 836} 837 838struct nonmatching_ref_data { 839const struct string_list *skip; 840const char*conflicting_refname; 841}; 842 843static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 844{ 845struct nonmatching_ref_data *data = vdata; 846 847if(data->skip &&string_list_has_string(data->skip, entry->name)) 848return0; 849 850 data->conflicting_refname = entry->name; 851return1; 852} 853 854/* 855 * Return 0 if a reference named refname could be created without 856 * conflicting with the name of an existing reference in dir. 857 * See verify_refname_available for more information. 858 */ 859static intverify_refname_available_dir(const char*refname, 860const struct string_list *extras, 861const struct string_list *skip, 862struct ref_dir *dir, 863struct strbuf *err) 864{ 865const char*slash; 866int pos; 867struct strbuf dirname = STRBUF_INIT; 868int ret = -1; 869 870/* 871 * For the sake of comments in this function, suppose that 872 * refname is "refs/foo/bar". 873 */ 874 875assert(err); 876 877strbuf_grow(&dirname,strlen(refname) +1); 878for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 879/* Expand dirname to the new prefix, not including the trailing slash: */ 880strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 881 882/* 883 * We are still at a leading dir of the refname (e.g., 884 * "refs/foo"; if there is a reference with that name, 885 * it is a conflict, *unless* it is in skip. 886 */ 887if(dir) { 888 pos =search_ref_dir(dir, dirname.buf, dirname.len); 889if(pos >=0&& 890(!skip || !string_list_has_string(skip, dirname.buf))) { 891/* 892 * We found a reference whose name is 893 * a proper prefix of refname; e.g., 894 * "refs/foo", and is not in skip. 895 */ 896strbuf_addf(err,"'%s' exists; cannot create '%s'", 897 dirname.buf, refname); 898goto cleanup; 899} 900} 901 902if(extras &&string_list_has_string(extras, dirname.buf) && 903(!skip || !string_list_has_string(skip, dirname.buf))) { 904strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 905 refname, dirname.buf); 906goto cleanup; 907} 908 909/* 910 * Otherwise, we can try to continue our search with 911 * the next component. So try to look up the 912 * directory, e.g., "refs/foo/". If we come up empty, 913 * we know there is nothing under this whole prefix, 914 * but even in that case we still have to continue the 915 * search for conflicts with extras. 916 */ 917strbuf_addch(&dirname,'/'); 918if(dir) { 919 pos =search_ref_dir(dir, dirname.buf, dirname.len); 920if(pos <0) { 921/* 922 * There was no directory "refs/foo/", 923 * so there is nothing under this 924 * whole prefix. So there is no need 925 * to continue looking for conflicting 926 * references. But we need to continue 927 * looking for conflicting extras. 928 */ 929 dir = NULL; 930}else{ 931 dir =get_ref_dir(dir->entries[pos]); 932} 933} 934} 935 936/* 937 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 938 * There is no point in searching for a reference with that 939 * name, because a refname isn't considered to conflict with 940 * itself. But we still need to check for references whose 941 * names are in the "refs/foo/bar/" namespace, because they 942 * *do* conflict. 943 */ 944strbuf_addstr(&dirname, refname + dirname.len); 945strbuf_addch(&dirname,'/'); 946 947if(dir) { 948 pos =search_ref_dir(dir, dirname.buf, dirname.len); 949 950if(pos >=0) { 951/* 952 * We found a directory named "$refname/" 953 * (e.g., "refs/foo/bar/"). It is a problem 954 * iff it contains any ref that is not in 955 * "skip". 956 */ 957struct nonmatching_ref_data data; 958 959 data.skip = skip; 960 data.conflicting_refname = NULL; 961 dir =get_ref_dir(dir->entries[pos]); 962sort_ref_dir(dir); 963if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 964strbuf_addf(err,"'%s' exists; cannot create '%s'", 965 data.conflicting_refname, refname); 966goto cleanup; 967} 968} 969} 970 971if(extras) { 972/* 973 * Check for entries in extras that start with 974 * "$refname/". We do that by looking for the place 975 * where "$refname/" would be inserted in extras. If 976 * there is an entry at that position that starts with 977 * "$refname/" and is not in skip, then we have a 978 * conflict. 979 */ 980for(pos =string_list_find_insert_index(extras, dirname.buf,0); 981 pos < extras->nr; pos++) { 982const char*extra_refname = extras->items[pos].string; 983 984if(!starts_with(extra_refname, dirname.buf)) 985break; 986 987if(!skip || !string_list_has_string(skip, extra_refname)) { 988strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 989 refname, extra_refname); 990goto cleanup; 991} 992} 993} 994 995/* No conflicts were found */ 996 ret =0; 997 998cleanup: 999strbuf_release(&dirname);1000return ret;1001}10021003struct packed_ref_cache {1004struct ref_entry *root;10051006/*1007 * Count of references to the data structure in this instance,1008 * including the pointer from ref_cache::packed if any. The1009 * data will not be freed as long as the reference count is1010 * nonzero.1011 */1012unsigned int referrers;10131014/*1015 * Iff the packed-refs file associated with this instance is1016 * currently locked for writing, this points at the associated1017 * lock (which is owned by somebody else). The referrer count1018 * is also incremented when the file is locked and decremented1019 * when it is unlocked.1020 */1021struct lock_file *lock;10221023/* The metadata from when this packed-refs cache was read */1024struct stat_validity validity;1025};10261027/*1028 * Future: need to be in "struct repository"1029 * when doing a full libification.1030 */1031static struct ref_cache {1032struct ref_cache *next;1033struct ref_entry *loose;1034struct packed_ref_cache *packed;1035/*1036 * The submodule name, or "" for the main repo. We allocate1037 * length 1 rather than FLEX_ARRAY so that the main ref_cache1038 * is initialized correctly.1039 */1040char name[1];1041} ref_cache, *submodule_ref_caches;10421043/* Lock used for the main packed-refs file: */1044static struct lock_file packlock;10451046/*1047 * Increment the reference count of *packed_refs.1048 */1049static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1050{1051 packed_refs->referrers++;1052}10531054/*1055 * Decrease the reference count of *packed_refs. If it goes to zero,1056 * free *packed_refs and return true; otherwise return false.1057 */1058static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1059{1060if(!--packed_refs->referrers) {1061free_ref_entry(packed_refs->root);1062stat_validity_clear(&packed_refs->validity);1063free(packed_refs);1064return1;1065}else{1066return0;1067}1068}10691070static voidclear_packed_ref_cache(struct ref_cache *refs)1071{1072if(refs->packed) {1073struct packed_ref_cache *packed_refs = refs->packed;10741075if(packed_refs->lock)1076die("internal error: packed-ref cache cleared while locked");1077 refs->packed = NULL;1078release_packed_ref_cache(packed_refs);1079}1080}10811082static voidclear_loose_ref_cache(struct ref_cache *refs)1083{1084if(refs->loose) {1085free_ref_entry(refs->loose);1086 refs->loose = NULL;1087}1088}10891090static struct ref_cache *create_ref_cache(const char*submodule)1091{1092int len;1093struct ref_cache *refs;1094if(!submodule)1095 submodule ="";1096 len =strlen(submodule) +1;1097 refs =xcalloc(1,sizeof(struct ref_cache) + len);1098memcpy(refs->name, submodule, len);1099return refs;1100}11011102/*1103 * Return a pointer to a ref_cache for the specified submodule. For1104 * the main repository, use submodule==NULL. The returned structure1105 * will be allocated and initialized but not necessarily populated; it1106 * should not be freed.1107 */1108static struct ref_cache *get_ref_cache(const char*submodule)1109{1110struct ref_cache *refs;11111112if(!submodule || !*submodule)1113return&ref_cache;11141115for(refs = submodule_ref_caches; refs; refs = refs->next)1116if(!strcmp(submodule, refs->name))1117return refs;11181119 refs =create_ref_cache(submodule);1120 refs->next = submodule_ref_caches;1121 submodule_ref_caches = refs;1122return refs;1123}11241125/* The length of a peeled reference line in packed-refs, including EOL: */1126#define PEELED_LINE_LENGTH 4211271128/*1129 * The packed-refs header line that we write out. Perhaps other1130 * traits will be added later. The trailing space is required.1131 */1132static const char PACKED_REFS_HEADER[] =1133"# pack-refs with: peeled fully-peeled\n";11341135/*1136 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1137 * Return a pointer to the refname within the line (null-terminated),1138 * or NULL if there was a problem.1139 */1140static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1141{1142const char*ref;11431144/*1145 * 42: the answer to everything.1146 *1147 * In this case, it happens to be the answer to1148 * 40 (length of sha1 hex representation)1149 * +1 (space in between hex and name)1150 * +1 (newline at the end of the line)1151 */1152if(line->len <=42)1153return NULL;11541155if(get_sha1_hex(line->buf, sha1) <0)1156return NULL;1157if(!isspace(line->buf[40]))1158return NULL;11591160 ref = line->buf +41;1161if(isspace(*ref))1162return NULL;11631164if(line->buf[line->len -1] !='\n')1165return NULL;1166 line->buf[--line->len] =0;11671168return ref;1169}11701171/*1172 * Read f, which is a packed-refs file, into dir.1173 *1174 * A comment line of the form "# pack-refs with: " may contain zero or1175 * more traits. We interpret the traits as follows:1176 *1177 * No traits:1178 *1179 * Probably no references are peeled. But if the file contains a1180 * peeled value for a reference, we will use it.1181 *1182 * peeled:1183 *1184 * References under "refs/tags/", if they *can* be peeled, *are*1185 * peeled in this file. References outside of "refs/tags/" are1186 * probably not peeled even if they could have been, but if we find1187 * a peeled value for such a reference we will use it.1188 *1189 * fully-peeled:1190 *1191 * All references in the file that can be peeled are peeled.1192 * Inversely (and this is more important), any references in the1193 * file for which no peeled value is recorded is not peelable. This1194 * trait should typically be written alongside "peeled" for1195 * compatibility with older clients, but we do not require it1196 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1197 */1198static voidread_packed_refs(FILE*f,struct ref_dir *dir)1199{1200struct ref_entry *last = NULL;1201struct strbuf line = STRBUF_INIT;1202enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12031204while(strbuf_getwholeline(&line, f,'\n') != EOF) {1205unsigned char sha1[20];1206const char*refname;1207const char*traits;12081209if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1210if(strstr(traits," fully-peeled "))1211 peeled = PEELED_FULLY;1212else if(strstr(traits," peeled "))1213 peeled = PEELED_TAGS;1214/* perhaps other traits later as well */1215continue;1216}12171218 refname =parse_ref_line(&line, sha1);1219if(refname) {1220int flag = REF_ISPACKED;12211222if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1223if(!refname_is_safe(refname))1224die("packed refname is dangerous:%s", refname);1225hashclr(sha1);1226 flag |= REF_BAD_NAME | REF_ISBROKEN;1227}1228 last =create_ref_entry(refname, sha1, flag,0);1229if(peeled == PEELED_FULLY ||1230(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1231 last->flag |= REF_KNOWS_PEELED;1232add_ref(dir, last);1233continue;1234}1235if(last &&1236 line.buf[0] =='^'&&1237 line.len == PEELED_LINE_LENGTH &&1238 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1239!get_sha1_hex(line.buf +1, sha1)) {1240hashcpy(last->u.value.peeled.hash, sha1);1241/*1242 * Regardless of what the file header said,1243 * we definitely know the value of *this*1244 * reference:1245 */1246 last->flag |= REF_KNOWS_PEELED;1247}1248}12491250strbuf_release(&line);1251}12521253/*1254 * Get the packed_ref_cache for the specified ref_cache, creating it1255 * if necessary.1256 */1257static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1258{1259char*packed_refs_file;12601261if(*refs->name)1262 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1263else1264 packed_refs_file =git_pathdup("packed-refs");12651266if(refs->packed &&1267!stat_validity_check(&refs->packed->validity, packed_refs_file))1268clear_packed_ref_cache(refs);12691270if(!refs->packed) {1271FILE*f;12721273 refs->packed =xcalloc(1,sizeof(*refs->packed));1274acquire_packed_ref_cache(refs->packed);1275 refs->packed->root =create_dir_entry(refs,"",0,0);1276 f =fopen(packed_refs_file,"r");1277if(f) {1278stat_validity_update(&refs->packed->validity,fileno(f));1279read_packed_refs(f,get_ref_dir(refs->packed->root));1280fclose(f);1281}1282}1283free(packed_refs_file);1284return refs->packed;1285}12861287static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1288{1289returnget_ref_dir(packed_ref_cache->root);1290}12911292static struct ref_dir *get_packed_refs(struct ref_cache *refs)1293{1294returnget_packed_ref_dir(get_packed_ref_cache(refs));1295}12961297/*1298 * Add a reference to the in-memory packed reference cache. This may1299 * only be called while the packed-refs file is locked (see1300 * lock_packed_refs()). To actually write the packed-refs file, call1301 * commit_packed_refs().1302 */1303static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1304{1305struct packed_ref_cache *packed_ref_cache =1306get_packed_ref_cache(&ref_cache);13071308if(!packed_ref_cache->lock)1309die("internal error: packed refs not locked");1310add_ref(get_packed_ref_dir(packed_ref_cache),1311create_ref_entry(refname, sha1, REF_ISPACKED,1));1312}13131314/*1315 * Read the loose references from the namespace dirname into dir1316 * (without recursing). dirname must end with '/'. dir must be the1317 * directory entry corresponding to dirname.1318 */1319static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1320{1321struct ref_cache *refs = dir->ref_cache;1322DIR*d;1323struct dirent *de;1324int dirnamelen =strlen(dirname);1325struct strbuf refname;1326struct strbuf path = STRBUF_INIT;1327size_t path_baselen;13281329if(*refs->name)1330strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1331else1332strbuf_git_path(&path,"%s", dirname);1333 path_baselen = path.len;13341335 d =opendir(path.buf);1336if(!d) {1337strbuf_release(&path);1338return;1339}13401341strbuf_init(&refname, dirnamelen +257);1342strbuf_add(&refname, dirname, dirnamelen);13431344while((de =readdir(d)) != NULL) {1345unsigned char sha1[20];1346struct stat st;1347int flag;13481349if(de->d_name[0] =='.')1350continue;1351if(ends_with(de->d_name,".lock"))1352continue;1353strbuf_addstr(&refname, de->d_name);1354strbuf_addstr(&path, de->d_name);1355if(stat(path.buf, &st) <0) {1356;/* silently ignore */1357}else if(S_ISDIR(st.st_mode)) {1358strbuf_addch(&refname,'/');1359add_entry_to_dir(dir,1360create_dir_entry(refs, refname.buf,1361 refname.len,1));1362}else{1363int read_ok;13641365if(*refs->name) {1366hashclr(sha1);1367 flag =0;1368 read_ok = !resolve_gitlink_ref(refs->name,1369 refname.buf, sha1);1370}else{1371 read_ok = !read_ref_full(refname.buf,1372 RESOLVE_REF_READING,1373 sha1, &flag);1374}13751376if(!read_ok) {1377hashclr(sha1);1378 flag |= REF_ISBROKEN;1379}else if(is_null_sha1(sha1)) {1380/*1381 * It is so astronomically unlikely1382 * that NULL_SHA1 is the SHA-1 of an1383 * actual object that we consider its1384 * appearance in a loose reference1385 * file to be repo corruption1386 * (probably due to a software bug).1387 */1388 flag |= REF_ISBROKEN;1389}13901391if(check_refname_format(refname.buf,1392 REFNAME_ALLOW_ONELEVEL)) {1393if(!refname_is_safe(refname.buf))1394die("loose refname is dangerous:%s", refname.buf);1395hashclr(sha1);1396 flag |= REF_BAD_NAME | REF_ISBROKEN;1397}1398add_entry_to_dir(dir,1399create_ref_entry(refname.buf, sha1, flag,0));1400}1401strbuf_setlen(&refname, dirnamelen);1402strbuf_setlen(&path, path_baselen);1403}1404strbuf_release(&refname);1405strbuf_release(&path);1406closedir(d);1407}14081409static struct ref_dir *get_loose_refs(struct ref_cache *refs)1410{1411if(!refs->loose) {1412/*1413 * Mark the top-level directory complete because we1414 * are about to read the only subdirectory that can1415 * hold references:1416 */1417 refs->loose =create_dir_entry(refs,"",0,0);1418/*1419 * Create an incomplete entry for "refs/":1420 */1421add_entry_to_dir(get_ref_dir(refs->loose),1422create_dir_entry(refs,"refs/",5,1));1423}1424returnget_ref_dir(refs->loose);1425}14261427/* We allow "recursive" symbolic refs. Only within reason, though */1428#define MAXDEPTH 51429#define MAXREFLEN (1024)14301431/*1432 * Called by resolve_gitlink_ref_recursive() after it failed to read1433 * from the loose refs in ref_cache refs. Find <refname> in the1434 * packed-refs file for the submodule.1435 */1436static intresolve_gitlink_packed_ref(struct ref_cache *refs,1437const char*refname,unsigned char*sha1)1438{1439struct ref_entry *ref;1440struct ref_dir *dir =get_packed_refs(refs);14411442 ref =find_ref(dir, refname);1443if(ref == NULL)1444return-1;14451446hashcpy(sha1, ref->u.value.oid.hash);1447return0;1448}14491450static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1451const char*refname,unsigned char*sha1,1452int recursion)1453{1454int fd, len;1455char buffer[128], *p;1456char*path;14571458if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1459return-1;1460 path = *refs->name1461?git_pathdup_submodule(refs->name,"%s", refname)1462:git_pathdup("%s", refname);1463 fd =open(path, O_RDONLY);1464free(path);1465if(fd <0)1466returnresolve_gitlink_packed_ref(refs, refname, sha1);14671468 len =read(fd, buffer,sizeof(buffer)-1);1469close(fd);1470if(len <0)1471return-1;1472while(len &&isspace(buffer[len-1]))1473 len--;1474 buffer[len] =0;14751476/* Was it a detached head or an old-fashioned symlink? */1477if(!get_sha1_hex(buffer, sha1))1478return0;14791480/* Symref? */1481if(strncmp(buffer,"ref:",4))1482return-1;1483 p = buffer +4;1484while(isspace(*p))1485 p++;14861487returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1488}14891490intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1491{1492int len =strlen(path), retval;1493char*submodule;1494struct ref_cache *refs;14951496while(len && path[len-1] =='/')1497 len--;1498if(!len)1499return-1;1500 submodule =xstrndup(path, len);1501 refs =get_ref_cache(submodule);1502free(submodule);15031504 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1505return retval;1506}15071508/*1509 * Return the ref_entry for the given refname from the packed1510 * references. If it does not exist, return NULL.1511 */1512static struct ref_entry *get_packed_ref(const char*refname)1513{1514returnfind_ref(get_packed_refs(&ref_cache), refname);1515}15161517/*1518 * A loose ref file doesn't exist; check for a packed ref. The1519 * options are forwarded from resolve_safe_unsafe().1520 */1521static intresolve_missing_loose_ref(const char*refname,1522int resolve_flags,1523unsigned char*sha1,1524int*flags)1525{1526struct ref_entry *entry;15271528/*1529 * The loose reference file does not exist; check for a packed1530 * reference.1531 */1532 entry =get_packed_ref(refname);1533if(entry) {1534hashcpy(sha1, entry->u.value.oid.hash);1535if(flags)1536*flags |= REF_ISPACKED;1537return0;1538}1539/* The reference is not a packed reference, either. */1540if(resolve_flags & RESOLVE_REF_READING) {1541 errno = ENOENT;1542return-1;1543}else{1544hashclr(sha1);1545return0;1546}1547}15481549/* This function needs to return a meaningful errno on failure */1550static const char*resolve_ref_1(const char*refname,1551int resolve_flags,1552unsigned char*sha1,1553int*flags,1554struct strbuf *sb_refname,1555struct strbuf *sb_path,1556struct strbuf *sb_contents)1557{1558int depth = MAXDEPTH;1559int bad_name =0;15601561if(flags)1562*flags =0;15631564if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1565if(flags)1566*flags |= REF_BAD_NAME;15671568if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1569!refname_is_safe(refname)) {1570 errno = EINVAL;1571return NULL;1572}1573/*1574 * dwim_ref() uses REF_ISBROKEN to distinguish between1575 * missing refs and refs that were present but invalid,1576 * to complain about the latter to stderr.1577 *1578 * We don't know whether the ref exists, so don't set1579 * REF_ISBROKEN yet.1580 */1581 bad_name =1;1582}1583for(;;) {1584const char*path;1585struct stat st;1586char*buf;1587int fd;15881589if(--depth <0) {1590 errno = ELOOP;1591return NULL;1592}15931594strbuf_reset(sb_path);1595strbuf_git_path(sb_path,"%s", refname);1596 path = sb_path->buf;15971598/*1599 * We might have to loop back here to avoid a race1600 * condition: first we lstat() the file, then we try1601 * to read it as a link or as a file. But if somebody1602 * changes the type of the file (file <-> directory1603 * <-> symlink) between the lstat() and reading, then1604 * we don't want to report that as an error but rather1605 * try again starting with the lstat().1606 */1607 stat_ref:1608if(lstat(path, &st) <0) {1609if(errno != ENOENT)1610return NULL;1611if(resolve_missing_loose_ref(refname, resolve_flags,1612 sha1, flags))1613return NULL;1614if(bad_name) {1615hashclr(sha1);1616if(flags)1617*flags |= REF_ISBROKEN;1618}1619return refname;1620}16211622/* Follow "normalized" - ie "refs/.." symlinks by hand */1623if(S_ISLNK(st.st_mode)) {1624strbuf_reset(sb_contents);1625if(strbuf_readlink(sb_contents, path,0) <0) {1626if(errno == ENOENT || errno == EINVAL)1627/* inconsistent with lstat; retry */1628goto stat_ref;1629else1630return NULL;1631}1632if(starts_with(sb_contents->buf,"refs/") &&1633!check_refname_format(sb_contents->buf,0)) {1634strbuf_swap(sb_refname, sb_contents);1635 refname = sb_refname->buf;1636if(flags)1637*flags |= REF_ISSYMREF;1638if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1639hashclr(sha1);1640return refname;1641}1642continue;1643}1644}16451646/* Is it a directory? */1647if(S_ISDIR(st.st_mode)) {1648 errno = EISDIR;1649return NULL;1650}16511652/*1653 * Anything else, just open it and try to use it as1654 * a ref1655 */1656 fd =open(path, O_RDONLY);1657if(fd <0) {1658if(errno == ENOENT)1659/* inconsistent with lstat; retry */1660goto stat_ref;1661else1662return NULL;1663}1664strbuf_reset(sb_contents);1665if(strbuf_read(sb_contents, fd,256) <0) {1666int save_errno = errno;1667close(fd);1668 errno = save_errno;1669return NULL;1670}1671close(fd);1672strbuf_rtrim(sb_contents);16731674/*1675 * Is it a symbolic ref?1676 */1677if(!starts_with(sb_contents->buf,"ref:")) {1678/*1679 * Please note that FETCH_HEAD has a second1680 * line containing other data.1681 */1682if(get_sha1_hex(sb_contents->buf, sha1) ||1683(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1684if(flags)1685*flags |= REF_ISBROKEN;1686 errno = EINVAL;1687return NULL;1688}1689if(bad_name) {1690hashclr(sha1);1691if(flags)1692*flags |= REF_ISBROKEN;1693}1694return refname;1695}1696if(flags)1697*flags |= REF_ISSYMREF;1698 buf = sb_contents->buf +4;1699while(isspace(*buf))1700 buf++;1701strbuf_reset(sb_refname);1702strbuf_addstr(sb_refname, buf);1703 refname = sb_refname->buf;1704if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1705hashclr(sha1);1706return refname;1707}1708if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1709if(flags)1710*flags |= REF_ISBROKEN;17111712if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1713!refname_is_safe(buf)) {1714 errno = EINVAL;1715return NULL;1716}1717 bad_name =1;1718}1719}1720}17211722const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1723unsigned char*sha1,int*flags)1724{1725static struct strbuf sb_refname = STRBUF_INIT;1726struct strbuf sb_contents = STRBUF_INIT;1727struct strbuf sb_path = STRBUF_INIT;1728const char*ret;17291730 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1731&sb_refname, &sb_path, &sb_contents);1732strbuf_release(&sb_path);1733strbuf_release(&sb_contents);1734return ret;1735}17361737char*resolve_refdup(const char*refname,int resolve_flags,1738unsigned char*sha1,int*flags)1739{1740returnxstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1741 sha1, flags));1742}17431744/* The argument to filter_refs */1745struct ref_filter {1746const char*pattern;1747 each_ref_fn *fn;1748void*cb_data;1749};17501751intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1752{1753if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1754return0;1755return-1;1756}17571758intread_ref(const char*refname,unsigned char*sha1)1759{1760returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1761}17621763intref_exists(const char*refname)1764{1765unsigned char sha1[20];1766return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1767}17681769static intfilter_refs(const char*refname,const struct object_id *oid,1770int flags,void*data)1771{1772struct ref_filter *filter = (struct ref_filter *)data;17731774if(wildmatch(filter->pattern, refname,0, NULL))1775return0;1776return filter->fn(refname, oid, flags, filter->cb_data);1777}17781779enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1780{1781struct object *o =lookup_unknown_object(name);17821783if(o->type == OBJ_NONE) {1784int type =sha1_object_info(name, NULL);1785if(type <0|| !object_as_type(o, type,0))1786return PEEL_INVALID;1787}17881789if(o->type != OBJ_TAG)1790return PEEL_NON_TAG;17911792 o =deref_tag_noverify(o);1793if(!o)1794return PEEL_INVALID;17951796hashcpy(sha1, o->sha1);1797return PEEL_PEELED;1798}17991800/*1801 * Peel the entry (if possible) and return its new peel_status. If1802 * repeel is true, re-peel the entry even if there is an old peeled1803 * value that is already stored in it.1804 *1805 * It is OK to call this function with a packed reference entry that1806 * might be stale and might even refer to an object that has since1807 * been garbage-collected. In such a case, if the entry has1808 * REF_KNOWS_PEELED then leave the status unchanged and return1809 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1810 */1811static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1812{1813enum peel_status status;18141815if(entry->flag & REF_KNOWS_PEELED) {1816if(repeel) {1817 entry->flag &= ~REF_KNOWS_PEELED;1818oidclr(&entry->u.value.peeled);1819}else{1820returnis_null_oid(&entry->u.value.peeled) ?1821 PEEL_NON_TAG : PEEL_PEELED;1822}1823}1824if(entry->flag & REF_ISBROKEN)1825return PEEL_BROKEN;1826if(entry->flag & REF_ISSYMREF)1827return PEEL_IS_SYMREF;18281829 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1830if(status == PEEL_PEELED || status == PEEL_NON_TAG)1831 entry->flag |= REF_KNOWS_PEELED;1832return status;1833}18341835intpeel_ref(const char*refname,unsigned char*sha1)1836{1837int flag;1838unsigned char base[20];18391840if(current_ref && (current_ref->name == refname1841|| !strcmp(current_ref->name, refname))) {1842if(peel_entry(current_ref,0))1843return-1;1844hashcpy(sha1, current_ref->u.value.peeled.hash);1845return0;1846}18471848if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1849return-1;18501851/*1852 * If the reference is packed, read its ref_entry from the1853 * cache in the hope that we already know its peeled value.1854 * We only try this optimization on packed references because1855 * (a) forcing the filling of the loose reference cache could1856 * be expensive and (b) loose references anyway usually do not1857 * have REF_KNOWS_PEELED.1858 */1859if(flag & REF_ISPACKED) {1860struct ref_entry *r =get_packed_ref(refname);1861if(r) {1862if(peel_entry(r,0))1863return-1;1864hashcpy(sha1, r->u.value.peeled.hash);1865return0;1866}1867}18681869returnpeel_object(base, sha1);1870}18711872struct warn_if_dangling_data {1873FILE*fp;1874const char*refname;1875const struct string_list *refnames;1876const char*msg_fmt;1877};18781879static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1880int flags,void*cb_data)1881{1882struct warn_if_dangling_data *d = cb_data;1883const char*resolves_to;1884struct object_id junk;18851886if(!(flags & REF_ISSYMREF))1887return0;18881889 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1890if(!resolves_to1891|| (d->refname1892?strcmp(resolves_to, d->refname)1893: !string_list_has_string(d->refnames, resolves_to))) {1894return0;1895}18961897fprintf(d->fp, d->msg_fmt, refname);1898fputc('\n', d->fp);1899return0;1900}19011902voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1903{1904struct warn_if_dangling_data data;19051906 data.fp = fp;1907 data.refname = refname;1908 data.refnames = NULL;1909 data.msg_fmt = msg_fmt;1910for_each_rawref(warn_if_dangling_symref, &data);1911}19121913voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1914{1915struct warn_if_dangling_data data;19161917 data.fp = fp;1918 data.refname = NULL;1919 data.refnames = refnames;1920 data.msg_fmt = msg_fmt;1921for_each_rawref(warn_if_dangling_symref, &data);1922}19231924/*1925 * Call fn for each reference in the specified ref_cache, omitting1926 * references not in the containing_dir of base. fn is called for all1927 * references, including broken ones. If fn ever returns a non-zero1928 * value, stop the iteration and return that value; otherwise, return1929 * 0.1930 */1931static intdo_for_each_entry(struct ref_cache *refs,const char*base,1932 each_ref_entry_fn fn,void*cb_data)1933{1934struct packed_ref_cache *packed_ref_cache;1935struct ref_dir *loose_dir;1936struct ref_dir *packed_dir;1937int retval =0;19381939/*1940 * We must make sure that all loose refs are read before accessing the1941 * packed-refs file; this avoids a race condition in which loose refs1942 * are migrated to the packed-refs file by a simultaneous process, but1943 * our in-memory view is from before the migration. get_packed_ref_cache()1944 * takes care of making sure our view is up to date with what is on1945 * disk.1946 */1947 loose_dir =get_loose_refs(refs);1948if(base && *base) {1949 loose_dir =find_containing_dir(loose_dir, base,0);1950}1951if(loose_dir)1952prime_ref_dir(loose_dir);19531954 packed_ref_cache =get_packed_ref_cache(refs);1955acquire_packed_ref_cache(packed_ref_cache);1956 packed_dir =get_packed_ref_dir(packed_ref_cache);1957if(base && *base) {1958 packed_dir =find_containing_dir(packed_dir, base,0);1959}19601961if(packed_dir && loose_dir) {1962sort_ref_dir(packed_dir);1963sort_ref_dir(loose_dir);1964 retval =do_for_each_entry_in_dirs(1965 packed_dir, loose_dir, fn, cb_data);1966}else if(packed_dir) {1967sort_ref_dir(packed_dir);1968 retval =do_for_each_entry_in_dir(1969 packed_dir,0, fn, cb_data);1970}else if(loose_dir) {1971sort_ref_dir(loose_dir);1972 retval =do_for_each_entry_in_dir(1973 loose_dir,0, fn, cb_data);1974}19751976release_packed_ref_cache(packed_ref_cache);1977return retval;1978}19791980/*1981 * Call fn for each reference in the specified ref_cache for which the1982 * refname begins with base. If trim is non-zero, then trim that many1983 * characters off the beginning of each refname before passing the1984 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1985 * broken references in the iteration. If fn ever returns a non-zero1986 * value, stop the iteration and return that value; otherwise, return1987 * 0.1988 */1989static intdo_for_each_ref(struct ref_cache *refs,const char*base,1990 each_ref_fn fn,int trim,int flags,void*cb_data)1991{1992struct ref_entry_cb data;1993 data.base = base;1994 data.trim = trim;1995 data.flags = flags;1996 data.fn = fn;1997 data.cb_data = cb_data;19981999if(ref_paranoia <0)2000 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2001if(ref_paranoia)2002 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20032004returndo_for_each_entry(refs, base, do_one_ref, &data);2005}20062007static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2008{2009struct object_id oid;2010int flag;20112012if(submodule) {2013if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2014returnfn("HEAD", &oid,0, cb_data);20152016return0;2017}20182019if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2020returnfn("HEAD", &oid, flag, cb_data);20212022return0;2023}20242025inthead_ref(each_ref_fn fn,void*cb_data)2026{2027returndo_head_ref(NULL, fn, cb_data);2028}20292030inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2031{2032returndo_head_ref(submodule, fn, cb_data);2033}20342035intfor_each_ref(each_ref_fn fn,void*cb_data)2036{2037returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2038}20392040intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2041{2042returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2043}20442045intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2046{2047returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2048}20492050intfor_each_fullref_in(const char*prefix, each_ref_fn fn,void*cb_data,unsigned int broken)2051{2052unsigned int flag =0;20532054if(broken)2055 flag = DO_FOR_EACH_INCLUDE_BROKEN;2056returndo_for_each_ref(&ref_cache, prefix, fn,0, flag, cb_data);2057}20582059intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2060 each_ref_fn fn,void*cb_data)2061{2062returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2063}20642065intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2066{2067returnfor_each_ref_in("refs/tags/", fn, cb_data);2068}20692070intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2071{2072returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2073}20742075intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2076{2077returnfor_each_ref_in("refs/heads/", fn, cb_data);2078}20792080intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2081{2082returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2083}20842085intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2086{2087returnfor_each_ref_in("refs/remotes/", fn, cb_data);2088}20892090intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2091{2092returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2093}20942095intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2096{2097returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,2098strlen(git_replace_ref_base),0, cb_data);2099}21002101inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2102{2103struct strbuf buf = STRBUF_INIT;2104int ret =0;2105struct object_id oid;2106int flag;21072108strbuf_addf(&buf,"%sHEAD",get_git_namespace());2109if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2110 ret =fn(buf.buf, &oid, flag, cb_data);2111strbuf_release(&buf);21122113return ret;2114}21152116intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2117{2118struct strbuf buf = STRBUF_INIT;2119int ret;2120strbuf_addf(&buf,"%srefs/",get_git_namespace());2121 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2122strbuf_release(&buf);2123return ret;2124}21252126intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2127const char*prefix,void*cb_data)2128{2129struct strbuf real_pattern = STRBUF_INIT;2130struct ref_filter filter;2131int ret;21322133if(!prefix && !starts_with(pattern,"refs/"))2134strbuf_addstr(&real_pattern,"refs/");2135else if(prefix)2136strbuf_addstr(&real_pattern, prefix);2137strbuf_addstr(&real_pattern, pattern);21382139if(!has_glob_specials(pattern)) {2140/* Append implied '/' '*' if not present. */2141strbuf_complete(&real_pattern,'/');2142/* No need to check for '*', there is none. */2143strbuf_addch(&real_pattern,'*');2144}21452146 filter.pattern = real_pattern.buf;2147 filter.fn = fn;2148 filter.cb_data = cb_data;2149 ret =for_each_ref(filter_refs, &filter);21502151strbuf_release(&real_pattern);2152return ret;2153}21542155intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2156{2157returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2158}21592160intfor_each_rawref(each_ref_fn fn,void*cb_data)2161{2162returndo_for_each_ref(&ref_cache,"", fn,0,2163 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2164}21652166const char*prettify_refname(const char*name)2167{2168return name + (2169starts_with(name,"refs/heads/") ?11:2170starts_with(name,"refs/tags/") ?10:2171starts_with(name,"refs/remotes/") ?13:21720);2173}21742175static const char*ref_rev_parse_rules[] = {2176"%.*s",2177"refs/%.*s",2178"refs/tags/%.*s",2179"refs/heads/%.*s",2180"refs/remotes/%.*s",2181"refs/remotes/%.*s/HEAD",2182 NULL2183};21842185intrefname_match(const char*abbrev_name,const char*full_name)2186{2187const char**p;2188const int abbrev_name_len =strlen(abbrev_name);21892190for(p = ref_rev_parse_rules; *p; p++) {2191if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2192return1;2193}2194}21952196return0;2197}21982199static voidunlock_ref(struct ref_lock *lock)2200{2201/* Do not free lock->lk -- atexit() still looks at them */2202if(lock->lk)2203rollback_lock_file(lock->lk);2204free(lock->ref_name);2205free(lock->orig_ref_name);2206free(lock);2207}22082209/*2210 * Verify that the reference locked by lock has the value old_sha1.2211 * Fail if the reference doesn't exist and mustexist is set. Return 02212 * on success. On error, write an error message to err, set errno, and2213 * return a negative value.2214 */2215static intverify_lock(struct ref_lock *lock,2216const unsigned char*old_sha1,int mustexist,2217struct strbuf *err)2218{2219assert(err);22202221if(read_ref_full(lock->ref_name,2222 mustexist ? RESOLVE_REF_READING :0,2223 lock->old_oid.hash, NULL)) {2224int save_errno = errno;2225strbuf_addf(err,"can't verify ref%s", lock->ref_name);2226 errno = save_errno;2227return-1;2228}2229if(hashcmp(lock->old_oid.hash, old_sha1)) {2230strbuf_addf(err,"ref%sis at%sbut expected%s",2231 lock->ref_name,2232sha1_to_hex(lock->old_oid.hash),2233sha1_to_hex(old_sha1));2234 errno = EBUSY;2235return-1;2236}2237return0;2238}22392240static intremove_empty_directories(struct strbuf *path)2241{2242/*2243 * we want to create a file but there is a directory there;2244 * if that is an empty directory (or a directory that contains2245 * only empty directories), remove them.2246 */2247returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);2248}22492250/*2251 * *string and *len will only be substituted, and *string returned (for2252 * later free()ing) if the string passed in is a magic short-hand form2253 * to name a branch.2254 */2255static char*substitute_branch_name(const char**string,int*len)2256{2257struct strbuf buf = STRBUF_INIT;2258int ret =interpret_branch_name(*string, *len, &buf);22592260if(ret == *len) {2261size_t size;2262*string =strbuf_detach(&buf, &size);2263*len = size;2264return(char*)*string;2265}22662267return NULL;2268}22692270intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2271{2272char*last_branch =substitute_branch_name(&str, &len);2273const char**p, *r;2274int refs_found =0;22752276*ref = NULL;2277for(p = ref_rev_parse_rules; *p; p++) {2278char fullref[PATH_MAX];2279unsigned char sha1_from_ref[20];2280unsigned char*this_result;2281int flag;22822283 this_result = refs_found ? sha1_from_ref : sha1;2284mksnpath(fullref,sizeof(fullref), *p, len, str);2285 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2286 this_result, &flag);2287if(r) {2288if(!refs_found++)2289*ref =xstrdup(r);2290if(!warn_ambiguous_refs)2291break;2292}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2293warning("ignoring dangling symref%s.", fullref);2294}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2295warning("ignoring broken ref%s.", fullref);2296}2297}2298free(last_branch);2299return refs_found;2300}23012302intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2303{2304char*last_branch =substitute_branch_name(&str, &len);2305const char**p;2306int logs_found =0;23072308*log = NULL;2309for(p = ref_rev_parse_rules; *p; p++) {2310unsigned char hash[20];2311char path[PATH_MAX];2312const char*ref, *it;23132314mksnpath(path,sizeof(path), *p, len, str);2315 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2316 hash, NULL);2317if(!ref)2318continue;2319if(reflog_exists(path))2320 it = path;2321else if(strcmp(ref, path) &&reflog_exists(ref))2322 it = ref;2323else2324continue;2325if(!logs_found++) {2326*log =xstrdup(it);2327hashcpy(sha1, hash);2328}2329if(!warn_ambiguous_refs)2330break;2331}2332free(last_branch);2333return logs_found;2334}23352336/*2337 * Locks a ref returning the lock on success and NULL on failure.2338 * On failure errno is set to something meaningful.2339 */2340static struct ref_lock *lock_ref_sha1_basic(const char*refname,2341const unsigned char*old_sha1,2342const struct string_list *extras,2343const struct string_list *skip,2344unsigned int flags,int*type_p,2345struct strbuf *err)2346{2347struct strbuf ref_file = STRBUF_INIT;2348struct strbuf orig_ref_file = STRBUF_INIT;2349const char*orig_refname = refname;2350struct ref_lock *lock;2351int last_errno =0;2352int type, lflags;2353int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2354int resolve_flags =0;2355int attempts_remaining =3;23562357assert(err);23582359 lock =xcalloc(1,sizeof(struct ref_lock));23602361if(mustexist)2362 resolve_flags |= RESOLVE_REF_READING;2363if(flags & REF_DELETING) {2364 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2365if(flags & REF_NODEREF)2366 resolve_flags |= RESOLVE_REF_NO_RECURSE;2367}23682369 refname =resolve_ref_unsafe(refname, resolve_flags,2370 lock->old_oid.hash, &type);2371if(!refname && errno == EISDIR) {2372/*2373 * we are trying to lock foo but we used to2374 * have foo/bar which now does not exist;2375 * it is normal for the empty directory 'foo'2376 * to remain.2377 */2378strbuf_git_path(&orig_ref_file,"%s", orig_refname);2379if(remove_empty_directories(&orig_ref_file)) {2380 last_errno = errno;2381if(!verify_refname_available_dir(orig_refname, extras, skip,2382get_loose_refs(&ref_cache), err))2383strbuf_addf(err,"there are still refs under '%s'",2384 orig_refname);2385goto error_return;2386}2387 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2388 lock->old_oid.hash, &type);2389}2390if(type_p)2391*type_p = type;2392if(!refname) {2393 last_errno = errno;2394if(last_errno != ENOTDIR ||2395!verify_refname_available_dir(orig_refname, extras, skip,2396get_loose_refs(&ref_cache), err))2397strbuf_addf(err,"unable to resolve reference%s:%s",2398 orig_refname,strerror(last_errno));23992400goto error_return;2401}2402/*2403 * If the ref did not exist and we are creating it, make sure2404 * there is no existing packed ref whose name begins with our2405 * refname, nor a packed ref whose name is a proper prefix of2406 * our refname.2407 */2408if(is_null_oid(&lock->old_oid) &&2409verify_refname_available_dir(refname, extras, skip,2410get_packed_refs(&ref_cache), err)) {2411 last_errno = ENOTDIR;2412goto error_return;2413}24142415 lock->lk =xcalloc(1,sizeof(struct lock_file));24162417 lflags =0;2418if(flags & REF_NODEREF) {2419 refname = orig_refname;2420 lflags |= LOCK_NO_DEREF;2421}2422 lock->ref_name =xstrdup(refname);2423 lock->orig_ref_name =xstrdup(orig_refname);2424strbuf_git_path(&ref_file,"%s", refname);24252426 retry:2427switch(safe_create_leading_directories_const(ref_file.buf)) {2428case SCLD_OK:2429break;/* success */2430case SCLD_VANISHED:2431if(--attempts_remaining >0)2432goto retry;2433/* fall through */2434default:2435 last_errno = errno;2436strbuf_addf(err,"unable to create directory for%s",2437 ref_file.buf);2438goto error_return;2439}24402441if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2442 last_errno = errno;2443if(errno == ENOENT && --attempts_remaining >0)2444/*2445 * Maybe somebody just deleted one of the2446 * directories leading to ref_file. Try2447 * again:2448 */2449goto retry;2450else{2451unable_to_lock_message(ref_file.buf, errno, err);2452goto error_return;2453}2454}2455if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2456 last_errno = errno;2457goto error_return;2458}2459goto out;24602461 error_return:2462unlock_ref(lock);2463 lock = NULL;24642465 out:2466strbuf_release(&ref_file);2467strbuf_release(&orig_ref_file);2468 errno = last_errno;2469return lock;2470}24712472/*2473 * Write an entry to the packed-refs file for the specified refname.2474 * If peeled is non-NULL, write it as the entry's peeled value.2475 */2476static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2477unsigned char*peeled)2478{2479fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2480if(peeled)2481fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2482}24832484/*2485 * An each_ref_entry_fn that writes the entry to a packed-refs file.2486 */2487static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2488{2489enum peel_status peel_status =peel_entry(entry,0);24902491if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2492error("internal error:%sis not a valid packed reference!",2493 entry->name);2494write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2495 peel_status == PEEL_PEELED ?2496 entry->u.value.peeled.hash : NULL);2497return0;2498}24992500/*2501 * Lock the packed-refs file for writing. Flags is passed to2502 * hold_lock_file_for_update(). Return 0 on success. On errors, set2503 * errno appropriately and return a nonzero value.2504 */2505static intlock_packed_refs(int flags)2506{2507static int timeout_configured =0;2508static int timeout_value =1000;25092510struct packed_ref_cache *packed_ref_cache;25112512if(!timeout_configured) {2513git_config_get_int("core.packedrefstimeout", &timeout_value);2514 timeout_configured =1;2515}25162517if(hold_lock_file_for_update_timeout(2518&packlock,git_path("packed-refs"),2519 flags, timeout_value) <0)2520return-1;2521/*2522 * Get the current packed-refs while holding the lock. If the2523 * packed-refs file has been modified since we last read it,2524 * this will automatically invalidate the cache and re-read2525 * the packed-refs file.2526 */2527 packed_ref_cache =get_packed_ref_cache(&ref_cache);2528 packed_ref_cache->lock = &packlock;2529/* Increment the reference count to prevent it from being freed: */2530acquire_packed_ref_cache(packed_ref_cache);2531return0;2532}25332534/*2535 * Write the current version of the packed refs cache from memory to2536 * disk. The packed-refs file must already be locked for writing (see2537 * lock_packed_refs()). Return zero on success. On errors, set errno2538 * and return a nonzero value2539 */2540static intcommit_packed_refs(void)2541{2542struct packed_ref_cache *packed_ref_cache =2543get_packed_ref_cache(&ref_cache);2544int error =0;2545int save_errno =0;2546FILE*out;25472548if(!packed_ref_cache->lock)2549die("internal error: packed-refs not locked");25502551 out =fdopen_lock_file(packed_ref_cache->lock,"w");2552if(!out)2553die_errno("unable to fdopen packed-refs descriptor");25542555fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2556do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),25570, write_packed_entry_fn, out);25582559if(commit_lock_file(packed_ref_cache->lock)) {2560 save_errno = errno;2561 error = -1;2562}2563 packed_ref_cache->lock = NULL;2564release_packed_ref_cache(packed_ref_cache);2565 errno = save_errno;2566return error;2567}25682569/*2570 * Rollback the lockfile for the packed-refs file, and discard the2571 * in-memory packed reference cache. (The packed-refs file will be2572 * read anew if it is needed again after this function is called.)2573 */2574static voidrollback_packed_refs(void)2575{2576struct packed_ref_cache *packed_ref_cache =2577get_packed_ref_cache(&ref_cache);25782579if(!packed_ref_cache->lock)2580die("internal error: packed-refs not locked");2581rollback_lock_file(packed_ref_cache->lock);2582 packed_ref_cache->lock = NULL;2583release_packed_ref_cache(packed_ref_cache);2584clear_packed_ref_cache(&ref_cache);2585}25862587struct ref_to_prune {2588struct ref_to_prune *next;2589unsigned char sha1[20];2590char name[FLEX_ARRAY];2591};25922593struct pack_refs_cb_data {2594unsigned int flags;2595struct ref_dir *packed_refs;2596struct ref_to_prune *ref_to_prune;2597};25982599/*2600 * An each_ref_entry_fn that is run over loose references only. If2601 * the loose reference can be packed, add an entry in the packed ref2602 * cache. If the reference should be pruned, also add it to2603 * ref_to_prune in the pack_refs_cb_data.2604 */2605static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2606{2607struct pack_refs_cb_data *cb = cb_data;2608enum peel_status peel_status;2609struct ref_entry *packed_entry;2610int is_tag_ref =starts_with(entry->name,"refs/tags/");26112612/* Do not pack per-worktree refs: */2613if(ref_type(entry->name) != REF_TYPE_NORMAL)2614return0;26152616/* ALWAYS pack tags */2617if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2618return0;26192620/* Do not pack symbolic or broken refs: */2621if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2622return0;26232624/* Add a packed ref cache entry equivalent to the loose entry. */2625 peel_status =peel_entry(entry,1);2626if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2627die("internal error peeling reference%s(%s)",2628 entry->name,oid_to_hex(&entry->u.value.oid));2629 packed_entry =find_ref(cb->packed_refs, entry->name);2630if(packed_entry) {2631/* Overwrite existing packed entry with info from loose entry */2632 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2633oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2634}else{2635 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2636 REF_ISPACKED | REF_KNOWS_PEELED,0);2637add_ref(cb->packed_refs, packed_entry);2638}2639oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);26402641/* Schedule the loose reference for pruning if requested. */2642if((cb->flags & PACK_REFS_PRUNE)) {2643int namelen =strlen(entry->name) +1;2644struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2645hashcpy(n->sha1, entry->u.value.oid.hash);2646memcpy(n->name, entry->name, namelen);/* includes NUL */2647 n->next = cb->ref_to_prune;2648 cb->ref_to_prune = n;2649}2650return0;2651}26522653/*2654 * Remove empty parents, but spare refs/ and immediate subdirs.2655 * Note: munges *name.2656 */2657static voidtry_remove_empty_parents(char*name)2658{2659char*p, *q;2660int i;2661 p = name;2662for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2663while(*p && *p !='/')2664 p++;2665/* tolerate duplicate slashes; see check_refname_format() */2666while(*p =='/')2667 p++;2668}2669for(q = p; *q; q++)2670;2671while(1) {2672while(q > p && *q !='/')2673 q--;2674while(q > p && *(q-1) =='/')2675 q--;2676if(q == p)2677break;2678*q ='\0';2679if(rmdir(git_path("%s", name)))2680break;2681}2682}26832684/* make sure nobody touched the ref, and unlink */2685static voidprune_ref(struct ref_to_prune *r)2686{2687struct ref_transaction *transaction;2688struct strbuf err = STRBUF_INIT;26892690if(check_refname_format(r->name,0))2691return;26922693 transaction =ref_transaction_begin(&err);2694if(!transaction ||2695ref_transaction_delete(transaction, r->name, r->sha1,2696 REF_ISPRUNING, NULL, &err) ||2697ref_transaction_commit(transaction, &err)) {2698ref_transaction_free(transaction);2699error("%s", err.buf);2700strbuf_release(&err);2701return;2702}2703ref_transaction_free(transaction);2704strbuf_release(&err);2705try_remove_empty_parents(r->name);2706}27072708static voidprune_refs(struct ref_to_prune *r)2709{2710while(r) {2711prune_ref(r);2712 r = r->next;2713}2714}27152716intpack_refs(unsigned int flags)2717{2718struct pack_refs_cb_data cbdata;27192720memset(&cbdata,0,sizeof(cbdata));2721 cbdata.flags = flags;27222723lock_packed_refs(LOCK_DIE_ON_ERROR);2724 cbdata.packed_refs =get_packed_refs(&ref_cache);27252726do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2727 pack_if_possible_fn, &cbdata);27282729if(commit_packed_refs())2730die_errno("unable to overwrite old ref-pack file");27312732prune_refs(cbdata.ref_to_prune);2733return0;2734}27352736/*2737 * Rewrite the packed-refs file, omitting any refs listed in2738 * 'refnames'. On error, leave packed-refs unchanged, write an error2739 * message to 'err', and return a nonzero value.2740 *2741 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2742 */2743static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2744{2745struct ref_dir *packed;2746struct string_list_item *refname;2747int ret, needs_repacking =0, removed =0;27482749assert(err);27502751/* Look for a packed ref */2752for_each_string_list_item(refname, refnames) {2753if(get_packed_ref(refname->string)) {2754 needs_repacking =1;2755break;2756}2757}27582759/* Avoid locking if we have nothing to do */2760if(!needs_repacking)2761return0;/* no refname exists in packed refs */27622763if(lock_packed_refs(0)) {2764unable_to_lock_message(git_path("packed-refs"), errno, err);2765return-1;2766}2767 packed =get_packed_refs(&ref_cache);27682769/* Remove refnames from the cache */2770for_each_string_list_item(refname, refnames)2771if(remove_entry(packed, refname->string) != -1)2772 removed =1;2773if(!removed) {2774/*2775 * All packed entries disappeared while we were2776 * acquiring the lock.2777 */2778rollback_packed_refs();2779return0;2780}27812782/* Write what remains */2783 ret =commit_packed_refs();2784if(ret)2785strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2786strerror(errno));2787return ret;2788}27892790static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2791{2792assert(err);27932794if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2795/*2796 * loose. The loose file name is the same as the2797 * lockfile name, minus ".lock":2798 */2799char*loose_filename =get_locked_file_path(lock->lk);2800int res =unlink_or_msg(loose_filename, err);2801free(loose_filename);2802if(res)2803return1;2804}2805return0;2806}28072808static intis_per_worktree_ref(const char*refname)2809{2810return!strcmp(refname,"HEAD") ||2811starts_with(refname,"refs/bisect/");2812}28132814static intis_pseudoref_syntax(const char*refname)2815{2816const char*c;28172818for(c = refname; *c; c++) {2819if(!isupper(*c) && *c !='-'&& *c !='_')2820return0;2821}28222823return1;2824}28252826enum ref_type ref_type(const char*refname)2827{2828if(is_per_worktree_ref(refname))2829return REF_TYPE_PER_WORKTREE;2830if(is_pseudoref_syntax(refname))2831return REF_TYPE_PSEUDOREF;2832return REF_TYPE_NORMAL;2833}28342835static intwrite_pseudoref(const char*pseudoref,const unsigned char*sha1,2836const unsigned char*old_sha1,struct strbuf *err)2837{2838const char*filename;2839int fd;2840static struct lock_file lock;2841struct strbuf buf = STRBUF_INIT;2842int ret = -1;28432844strbuf_addf(&buf,"%s\n",sha1_to_hex(sha1));28452846 filename =git_path("%s", pseudoref);2847 fd =hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);2848if(fd <0) {2849strbuf_addf(err,"Could not open '%s' for writing:%s",2850 filename,strerror(errno));2851return-1;2852}28532854if(old_sha1) {2855unsigned char actual_old_sha1[20];28562857if(read_ref(pseudoref, actual_old_sha1))2858die("could not read ref '%s'", pseudoref);2859if(hashcmp(actual_old_sha1, old_sha1)) {2860strbuf_addf(err,"Unexpected sha1 when writing%s", pseudoref);2861rollback_lock_file(&lock);2862goto done;2863}2864}28652866if(write_in_full(fd, buf.buf, buf.len) != buf.len) {2867strbuf_addf(err,"Could not write to '%s'", filename);2868rollback_lock_file(&lock);2869goto done;2870}28712872commit_lock_file(&lock);2873 ret =0;2874done:2875strbuf_release(&buf);2876return ret;2877}28782879static intdelete_pseudoref(const char*pseudoref,const unsigned char*old_sha1)2880{2881static struct lock_file lock;2882const char*filename;28832884 filename =git_path("%s", pseudoref);28852886if(old_sha1 && !is_null_sha1(old_sha1)) {2887int fd;2888unsigned char actual_old_sha1[20];28892890 fd =hold_lock_file_for_update(&lock, filename,2891 LOCK_DIE_ON_ERROR);2892if(fd <0)2893die_errno(_("Could not open '%s' for writing"), filename);2894if(read_ref(pseudoref, actual_old_sha1))2895die("could not read ref '%s'", pseudoref);2896if(hashcmp(actual_old_sha1, old_sha1)) {2897warning("Unexpected sha1 when deleting%s", pseudoref);2898rollback_lock_file(&lock);2899return-1;2900}29012902unlink(filename);2903rollback_lock_file(&lock);2904}else{2905unlink(filename);2906}29072908return0;2909}29102911intdelete_ref(const char*refname,const unsigned char*old_sha1,2912unsigned int flags)2913{2914struct ref_transaction *transaction;2915struct strbuf err = STRBUF_INIT;29162917if(ref_type(refname) == REF_TYPE_PSEUDOREF)2918returndelete_pseudoref(refname, old_sha1);29192920 transaction =ref_transaction_begin(&err);2921if(!transaction ||2922ref_transaction_delete(transaction, refname, old_sha1,2923 flags, NULL, &err) ||2924ref_transaction_commit(transaction, &err)) {2925error("%s", err.buf);2926ref_transaction_free(transaction);2927strbuf_release(&err);2928return1;2929}2930ref_transaction_free(transaction);2931strbuf_release(&err);2932return0;2933}29342935intdelete_refs(struct string_list *refnames)2936{2937struct strbuf err = STRBUF_INIT;2938int i, result =0;29392940if(!refnames->nr)2941return0;29422943 result =repack_without_refs(refnames, &err);2944if(result) {2945/*2946 * If we failed to rewrite the packed-refs file, then2947 * it is unsafe to try to remove loose refs, because2948 * doing so might expose an obsolete packed value for2949 * a reference that might even point at an object that2950 * has been garbage collected.2951 */2952if(refnames->nr ==1)2953error(_("could not delete reference%s:%s"),2954 refnames->items[0].string, err.buf);2955else2956error(_("could not delete references:%s"), err.buf);29572958goto out;2959}29602961for(i =0; i < refnames->nr; i++) {2962const char*refname = refnames->items[i].string;29632964if(delete_ref(refname, NULL,0))2965 result |=error(_("could not remove reference%s"), refname);2966}29672968out:2969strbuf_release(&err);2970return result;2971}29722973/*2974 * People using contrib's git-new-workdir have .git/logs/refs ->2975 * /some/other/path/.git/logs/refs, and that may live on another device.2976 *2977 * IOW, to avoid cross device rename errors, the temporary renamed log must2978 * live into logs/refs.2979 */2980#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"29812982static intrename_tmp_log(const char*newrefname)2983{2984int attempts_remaining =4;2985struct strbuf path = STRBUF_INIT;2986int ret = -1;29872988 retry:2989strbuf_reset(&path);2990strbuf_git_path(&path,"logs/%s", newrefname);2991switch(safe_create_leading_directories_const(path.buf)) {2992case SCLD_OK:2993break;/* success */2994case SCLD_VANISHED:2995if(--attempts_remaining >0)2996goto retry;2997/* fall through */2998default:2999error("unable to create directory for%s", newrefname);3000goto out;3001}30023003if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {3004if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {3005/*3006 * rename(a, b) when b is an existing3007 * directory ought to result in ISDIR, but3008 * Solaris 5.8 gives ENOTDIR. Sheesh.3009 */3010if(remove_empty_directories(&path)) {3011error("Directory not empty: logs/%s", newrefname);3012goto out;3013}3014goto retry;3015}else if(errno == ENOENT && --attempts_remaining >0) {3016/*3017 * Maybe another process just deleted one of3018 * the directories in the path to newrefname.3019 * Try again from the beginning.3020 */3021goto retry;3022}else{3023error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",3024 newrefname,strerror(errno));3025goto out;3026}3027}3028 ret =0;3029out:3030strbuf_release(&path);3031return ret;3032}30333034intverify_refname_available(const char*newname,3035struct string_list *extras,3036struct string_list *skip,3037struct strbuf *err)3038{3039struct ref_dir *packed_refs =get_packed_refs(&ref_cache);3040struct ref_dir *loose_refs =get_loose_refs(&ref_cache);30413042if(verify_refname_available_dir(newname, extras, skip,3043 packed_refs, err) ||3044verify_refname_available_dir(newname, extras, skip,3045 loose_refs, err))3046return-1;30473048return0;3049}30503051static intrename_ref_available(const char*oldname,const char*newname)3052{3053struct string_list skip = STRING_LIST_INIT_NODUP;3054struct strbuf err = STRBUF_INIT;3055int ret;30563057string_list_insert(&skip, oldname);3058 ret = !verify_refname_available(newname, NULL, &skip, &err);3059if(!ret)3060error("%s", err.buf);30613062string_list_clear(&skip,0);3063strbuf_release(&err);3064return ret;3065}30663067static intwrite_ref_to_lockfile(struct ref_lock *lock,3068const unsigned char*sha1,struct strbuf *err);3069static intcommit_ref_update(struct ref_lock *lock,3070const unsigned char*sha1,const char*logmsg,3071int flags,struct strbuf *err);30723073intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)3074{3075unsigned char sha1[20], orig_sha1[20];3076int flag =0, logmoved =0;3077struct ref_lock *lock;3078struct stat loginfo;3079int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);3080const char*symref = NULL;3081struct strbuf err = STRBUF_INIT;30823083if(log &&S_ISLNK(loginfo.st_mode))3084returnerror("reflog for%sis a symlink", oldrefname);30853086 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3087 orig_sha1, &flag);3088if(flag & REF_ISSYMREF)3089returnerror("refname%sis a symbolic ref, renaming it is not supported",3090 oldrefname);3091if(!symref)3092returnerror("refname%snot found", oldrefname);30933094if(!rename_ref_available(oldrefname, newrefname))3095return1;30963097if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3098returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3099 oldrefname,strerror(errno));31003101if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3102error("unable to delete old%s", oldrefname);3103goto rollback;3104}31053106if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3107delete_ref(newrefname, sha1, REF_NODEREF)) {3108if(errno==EISDIR) {3109struct strbuf path = STRBUF_INIT;3110int result;31113112strbuf_git_path(&path,"%s", newrefname);3113 result =remove_empty_directories(&path);3114strbuf_release(&path);31153116if(result) {3117error("Directory not empty:%s", newrefname);3118goto rollback;3119}3120}else{3121error("unable to delete existing%s", newrefname);3122goto rollback;3123}3124}31253126if(log &&rename_tmp_log(newrefname))3127goto rollback;31283129 logmoved = log;31303131 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3132if(!lock) {3133error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3134strbuf_release(&err);3135goto rollback;3136}3137hashcpy(lock->old_oid.hash, orig_sha1);31383139if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3140commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {3141error("unable to write current sha1 into%s:%s", newrefname, err.buf);3142strbuf_release(&err);3143goto rollback;3144}31453146return0;31473148 rollback:3149 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3150if(!lock) {3151error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3152strbuf_release(&err);3153goto rollbacklog;3154}31553156 flag = log_all_ref_updates;3157 log_all_ref_updates =0;3158if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3159commit_ref_update(lock, orig_sha1, NULL,0, &err)) {3160error("unable to write current sha1 into%s:%s", oldrefname, err.buf);3161strbuf_release(&err);3162}3163 log_all_ref_updates = flag;31643165 rollbacklog:3166if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3167error("unable to restore logfile%sfrom%s:%s",3168 oldrefname, newrefname,strerror(errno));3169if(!logmoved && log &&3170rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3171error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3172 oldrefname,strerror(errno));31733174return1;3175}31763177static intclose_ref(struct ref_lock *lock)3178{3179if(close_lock_file(lock->lk))3180return-1;3181return0;3182}31833184static intcommit_ref(struct ref_lock *lock)3185{3186if(commit_lock_file(lock->lk))3187return-1;3188return0;3189}31903191intcopy_reflog_msg(char*buf,const char*msg)3192{3193char*cp = buf;3194char c;3195int wasspace =1;31963197*cp++ ='\t';3198while((c = *msg++)) {3199if(wasspace &&isspace(c))3200continue;3201 wasspace =isspace(c);3202if(wasspace)3203 c =' ';3204*cp++ = c;3205}3206while(buf < cp &&isspace(cp[-1]))3207 cp--;3208*cp++ ='\n';3209return cp - buf;3210}32113212intshould_autocreate_reflog(const char*refname)3213{3214if(!log_all_ref_updates)3215return0;3216returnstarts_with(refname,"refs/heads/") ||3217starts_with(refname,"refs/remotes/") ||3218starts_with(refname,"refs/notes/") ||3219!strcmp(refname,"HEAD");3220}32213222/*3223 * Create a reflog for a ref. If force_create = 0, the reflog will3224 * only be created for certain refs (those for which3225 * should_autocreate_reflog returns non-zero. Otherwise, create it3226 * regardless of the ref name. Fill in *err and return -1 on failure.3227 */3228static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)3229{3230int logfd, oflags = O_APPEND | O_WRONLY;32313232strbuf_git_path(logfile,"logs/%s", refname);3233if(force_create ||should_autocreate_reflog(refname)) {3234if(safe_create_leading_directories(logfile->buf) <0) {3235strbuf_addf(err,"unable to create directory for%s: "3236"%s", logfile->buf,strerror(errno));3237return-1;3238}3239 oflags |= O_CREAT;3240}32413242 logfd =open(logfile->buf, oflags,0666);3243if(logfd <0) {3244if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3245return0;32463247if(errno == EISDIR) {3248if(remove_empty_directories(logfile)) {3249strbuf_addf(err,"There are still logs under "3250"'%s'", logfile->buf);3251return-1;3252}3253 logfd =open(logfile->buf, oflags,0666);3254}32553256if(logfd <0) {3257strbuf_addf(err,"unable to append to%s:%s",3258 logfile->buf,strerror(errno));3259return-1;3260}3261}32623263adjust_shared_perm(logfile->buf);3264close(logfd);3265return0;3266}326732683269intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3270{3271int ret;3272struct strbuf sb = STRBUF_INIT;32733274 ret =log_ref_setup(refname, &sb, err, force_create);3275strbuf_release(&sb);3276return ret;3277}32783279static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3280const unsigned char*new_sha1,3281const char*committer,const char*msg)3282{3283int msglen, written;3284unsigned maxlen, len;3285char*logrec;32863287 msglen = msg ?strlen(msg) :0;3288 maxlen =strlen(committer) + msglen +100;3289 logrec =xmalloc(maxlen);3290 len =xsnprintf(logrec, maxlen,"%s %s %s\n",3291sha1_to_hex(old_sha1),3292sha1_to_hex(new_sha1),3293 committer);3294if(msglen)3295 len +=copy_reflog_msg(logrec + len -1, msg) -1;32963297 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3298free(logrec);3299if(written != len)3300return-1;33013302return0;3303}33043305static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3306const unsigned char*new_sha1,const char*msg,3307struct strbuf *logfile,int flags,3308struct strbuf *err)3309{3310int logfd, result, oflags = O_APPEND | O_WRONLY;33113312if(log_all_ref_updates <0)3313 log_all_ref_updates = !is_bare_repository();33143315 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);33163317if(result)3318return result;33193320 logfd =open(logfile->buf, oflags);3321if(logfd <0)3322return0;3323 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3324git_committer_info(0), msg);3325if(result) {3326strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3327strerror(errno));3328close(logfd);3329return-1;3330}3331if(close(logfd)) {3332strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3333strerror(errno));3334return-1;3335}3336return0;3337}33383339static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3340const unsigned char*new_sha1,const char*msg,3341int flags,struct strbuf *err)3342{3343struct strbuf sb = STRBUF_INIT;3344int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3345 err);3346strbuf_release(&sb);3347return ret;3348}33493350intis_branch(const char*refname)3351{3352return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3353}33543355/*3356 * Write sha1 into the open lockfile, then close the lockfile. On3357 * errors, rollback the lockfile, fill in *err and3358 * return -1.3359 */3360static intwrite_ref_to_lockfile(struct ref_lock *lock,3361const unsigned char*sha1,struct strbuf *err)3362{3363static char term ='\n';3364struct object *o;3365int fd;33663367 o =parse_object(sha1);3368if(!o) {3369strbuf_addf(err,3370"Trying to write ref%swith nonexistent object%s",3371 lock->ref_name,sha1_to_hex(sha1));3372unlock_ref(lock);3373return-1;3374}3375if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3376strbuf_addf(err,3377"Trying to write non-commit object%sto branch%s",3378sha1_to_hex(sha1), lock->ref_name);3379unlock_ref(lock);3380return-1;3381}3382 fd =get_lock_file_fd(lock->lk);3383if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||3384write_in_full(fd, &term,1) !=1||3385close_ref(lock) <0) {3386strbuf_addf(err,3387"Couldn't write%s",get_lock_file_path(lock->lk));3388unlock_ref(lock);3389return-1;3390}3391return0;3392}33933394/*3395 * Commit a change to a loose reference that has already been written3396 * to the loose reference lockfile. Also update the reflogs if3397 * necessary, using the specified lockmsg (which can be NULL).3398 */3399static intcommit_ref_update(struct ref_lock *lock,3400const unsigned char*sha1,const char*logmsg,3401int flags,struct strbuf *err)3402{3403clear_loose_ref_cache(&ref_cache);3404if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||3405(strcmp(lock->ref_name, lock->orig_ref_name) &&3406log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {3407char*old_msg =strbuf_detach(err, NULL);3408strbuf_addf(err,"Cannot update the ref '%s':%s",3409 lock->ref_name, old_msg);3410free(old_msg);3411unlock_ref(lock);3412return-1;3413}3414if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3415/*3416 * Special hack: If a branch is updated directly and HEAD3417 * points to it (may happen on the remote side of a push3418 * for example) then logically the HEAD reflog should be3419 * updated too.3420 * A generic solution implies reverse symref information,3421 * but finding all symrefs pointing to the given branch3422 * would be rather costly for this rare event (the direct3423 * update of a branch) to be worth it. So let's cheat and3424 * check with HEAD only which should cover 99% of all usage3425 * scenarios (even 100% of the default ones).3426 */3427unsigned char head_sha1[20];3428int head_flag;3429const char*head_ref;3430 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3431 head_sha1, &head_flag);3432if(head_ref && (head_flag & REF_ISSYMREF) &&3433!strcmp(head_ref, lock->ref_name)) {3434struct strbuf log_err = STRBUF_INIT;3435if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3436 logmsg,0, &log_err)) {3437error("%s", log_err.buf);3438strbuf_release(&log_err);3439}3440}3441}3442if(commit_ref(lock)) {3443error("Couldn't set%s", lock->ref_name);3444unlock_ref(lock);3445return-1;3446}34473448unlock_ref(lock);3449return0;3450}34513452intcreate_symref(const char*ref_target,const char*refs_heads_master,3453const char*logmsg)3454{3455char*lockpath = NULL;3456char ref[1000];3457int fd, len, written;3458char*git_HEAD =git_pathdup("%s", ref_target);3459unsigned char old_sha1[20], new_sha1[20];3460struct strbuf err = STRBUF_INIT;34613462if(logmsg &&read_ref(ref_target, old_sha1))3463hashclr(old_sha1);34643465if(safe_create_leading_directories(git_HEAD) <0)3466returnerror("unable to create directory for%s", git_HEAD);34673468#ifndef NO_SYMLINK_HEAD3469if(prefer_symlink_refs) {3470unlink(git_HEAD);3471if(!symlink(refs_heads_master, git_HEAD))3472goto done;3473fprintf(stderr,"no symlink - falling back to symbolic ref\n");3474}3475#endif34763477 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3478if(sizeof(ref) <= len) {3479error("refname too long:%s", refs_heads_master);3480goto error_free_return;3481}3482 lockpath =mkpathdup("%s.lock", git_HEAD);3483 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3484if(fd <0) {3485error("Unable to open%sfor writing", lockpath);3486goto error_free_return;3487}3488 written =write_in_full(fd, ref, len);3489if(close(fd) !=0|| written != len) {3490error("Unable to write to%s", lockpath);3491goto error_unlink_return;3492}3493if(rename(lockpath, git_HEAD) <0) {3494error("Unable to create%s", git_HEAD);3495goto error_unlink_return;3496}3497if(adjust_shared_perm(git_HEAD)) {3498error("Unable to fix permissions on%s", lockpath);3499 error_unlink_return:3500unlink_or_warn(lockpath);3501 error_free_return:3502free(lockpath);3503free(git_HEAD);3504return-1;3505}3506free(lockpath);35073508#ifndef NO_SYMLINK_HEAD3509 done:3510#endif3511if(logmsg && !read_ref(refs_heads_master, new_sha1) &&3512log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {3513error("%s", err.buf);3514strbuf_release(&err);3515}35163517free(git_HEAD);3518return0;3519}35203521struct read_ref_at_cb {3522const char*refname;3523unsigned long at_time;3524int cnt;3525int reccnt;3526unsigned char*sha1;3527int found_it;35283529unsigned char osha1[20];3530unsigned char nsha1[20];3531int tz;3532unsigned long date;3533char**msg;3534unsigned long*cutoff_time;3535int*cutoff_tz;3536int*cutoff_cnt;3537};35383539static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3540const char*email,unsigned long timestamp,int tz,3541const char*message,void*cb_data)3542{3543struct read_ref_at_cb *cb = cb_data;35443545 cb->reccnt++;3546 cb->tz = tz;3547 cb->date = timestamp;35483549if(timestamp <= cb->at_time || cb->cnt ==0) {3550if(cb->msg)3551*cb->msg =xstrdup(message);3552if(cb->cutoff_time)3553*cb->cutoff_time = timestamp;3554if(cb->cutoff_tz)3555*cb->cutoff_tz = tz;3556if(cb->cutoff_cnt)3557*cb->cutoff_cnt = cb->reccnt -1;3558/*3559 * we have not yet updated cb->[n|o]sha1 so they still3560 * hold the values for the previous record.3561 */3562if(!is_null_sha1(cb->osha1)) {3563hashcpy(cb->sha1, nsha1);3564if(hashcmp(cb->osha1, nsha1))3565warning("Log for ref%shas gap after%s.",3566 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3567}3568else if(cb->date == cb->at_time)3569hashcpy(cb->sha1, nsha1);3570else if(hashcmp(nsha1, cb->sha1))3571warning("Log for ref%sunexpectedly ended on%s.",3572 cb->refname,show_date(cb->date, cb->tz,3573DATE_MODE(RFC2822)));3574hashcpy(cb->osha1, osha1);3575hashcpy(cb->nsha1, nsha1);3576 cb->found_it =1;3577return1;3578}3579hashcpy(cb->osha1, osha1);3580hashcpy(cb->nsha1, nsha1);3581if(cb->cnt >0)3582 cb->cnt--;3583return0;3584}35853586static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3587const char*email,unsigned long timestamp,3588int tz,const char*message,void*cb_data)3589{3590struct read_ref_at_cb *cb = cb_data;35913592if(cb->msg)3593*cb->msg =xstrdup(message);3594if(cb->cutoff_time)3595*cb->cutoff_time = timestamp;3596if(cb->cutoff_tz)3597*cb->cutoff_tz = tz;3598if(cb->cutoff_cnt)3599*cb->cutoff_cnt = cb->reccnt;3600hashcpy(cb->sha1, osha1);3601if(is_null_sha1(cb->sha1))3602hashcpy(cb->sha1, nsha1);3603/* We just want the first entry */3604return1;3605}36063607intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3608unsigned char*sha1,char**msg,3609unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3610{3611struct read_ref_at_cb cb;36123613memset(&cb,0,sizeof(cb));3614 cb.refname = refname;3615 cb.at_time = at_time;3616 cb.cnt = cnt;3617 cb.msg = msg;3618 cb.cutoff_time = cutoff_time;3619 cb.cutoff_tz = cutoff_tz;3620 cb.cutoff_cnt = cutoff_cnt;3621 cb.sha1 = sha1;36223623for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);36243625if(!cb.reccnt) {3626if(flags & GET_SHA1_QUIETLY)3627exit(128);3628else3629die("Log for%sis empty.", refname);3630}3631if(cb.found_it)3632return0;36333634for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);36353636return1;3637}36383639intreflog_exists(const char*refname)3640{3641struct stat st;36423643return!lstat(git_path("logs/%s", refname), &st) &&3644S_ISREG(st.st_mode);3645}36463647intdelete_reflog(const char*refname)3648{3649returnremove_path(git_path("logs/%s", refname));3650}36513652static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3653{3654unsigned char osha1[20], nsha1[20];3655char*email_end, *message;3656unsigned long timestamp;3657int tz;36583659/* old SP new SP name <email> SP time TAB msg LF */3660if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3661get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3662get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3663!(email_end =strchr(sb->buf +82,'>')) ||3664 email_end[1] !=' '||3665!(timestamp =strtoul(email_end +2, &message,10)) ||3666!message || message[0] !=' '||3667(message[1] !='+'&& message[1] !='-') ||3668!isdigit(message[2]) || !isdigit(message[3]) ||3669!isdigit(message[4]) || !isdigit(message[5]))3670return0;/* corrupt? */3671 email_end[1] ='\0';3672 tz =strtol(message +1, NULL,10);3673if(message[6] !='\t')3674 message +=6;3675else3676 message +=7;3677returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3678}36793680static char*find_beginning_of_line(char*bob,char*scan)3681{3682while(bob < scan && *(--scan) !='\n')3683;/* keep scanning backwards */3684/*3685 * Return either beginning of the buffer, or LF at the end of3686 * the previous line.3687 */3688return scan;3689}36903691intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3692{3693struct strbuf sb = STRBUF_INIT;3694FILE*logfp;3695long pos;3696int ret =0, at_tail =1;36973698 logfp =fopen(git_path("logs/%s", refname),"r");3699if(!logfp)3700return-1;37013702/* Jump to the end */3703if(fseek(logfp,0, SEEK_END) <0)3704returnerror("cannot seek back reflog for%s:%s",3705 refname,strerror(errno));3706 pos =ftell(logfp);3707while(!ret &&0< pos) {3708int cnt;3709size_t nread;3710char buf[BUFSIZ];3711char*endp, *scanp;37123713/* Fill next block from the end */3714 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3715if(fseek(logfp, pos - cnt, SEEK_SET))3716returnerror("cannot seek back reflog for%s:%s",3717 refname,strerror(errno));3718 nread =fread(buf, cnt,1, logfp);3719if(nread !=1)3720returnerror("cannot read%dbytes from reflog for%s:%s",3721 cnt, refname,strerror(errno));3722 pos -= cnt;37233724 scanp = endp = buf + cnt;3725if(at_tail && scanp[-1] =='\n')3726/* Looking at the final LF at the end of the file */3727 scanp--;3728 at_tail =0;37293730while(buf < scanp) {3731/*3732 * terminating LF of the previous line, or the beginning3733 * of the buffer.3734 */3735char*bp;37363737 bp =find_beginning_of_line(buf, scanp);37383739if(*bp =='\n') {3740/*3741 * The newline is the end of the previous line,3742 * so we know we have complete line starting3743 * at (bp + 1). Prefix it onto any prior data3744 * we collected for the line and process it.3745 */3746strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3747 scanp = bp;3748 endp = bp +1;3749 ret =show_one_reflog_ent(&sb, fn, cb_data);3750strbuf_reset(&sb);3751if(ret)3752break;3753}else if(!pos) {3754/*3755 * We are at the start of the buffer, and the3756 * start of the file; there is no previous3757 * line, and we have everything for this one.3758 * Process it, and we can end the loop.3759 */3760strbuf_splice(&sb,0,0, buf, endp - buf);3761 ret =show_one_reflog_ent(&sb, fn, cb_data);3762strbuf_reset(&sb);3763break;3764}37653766if(bp == buf) {3767/*3768 * We are at the start of the buffer, and there3769 * is more file to read backwards. Which means3770 * we are in the middle of a line. Note that we3771 * may get here even if *bp was a newline; that3772 * just means we are at the exact end of the3773 * previous line, rather than some spot in the3774 * middle.3775 *3776 * Save away what we have to be combined with3777 * the data from the next read.3778 */3779strbuf_splice(&sb,0,0, buf, endp - buf);3780break;3781}3782}37833784}3785if(!ret && sb.len)3786die("BUG: reverse reflog parser had leftover data");37873788fclose(logfp);3789strbuf_release(&sb);3790return ret;3791}37923793intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3794{3795FILE*logfp;3796struct strbuf sb = STRBUF_INIT;3797int ret =0;37983799 logfp =fopen(git_path("logs/%s", refname),"r");3800if(!logfp)3801return-1;38023803while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3804 ret =show_one_reflog_ent(&sb, fn, cb_data);3805fclose(logfp);3806strbuf_release(&sb);3807return ret;3808}3809/*3810 * Call fn for each reflog in the namespace indicated by name. name3811 * must be empty or end with '/'. Name will be used as a scratch3812 * space, but its contents will be restored before return.3813 */3814static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3815{3816DIR*d =opendir(git_path("logs/%s", name->buf));3817int retval =0;3818struct dirent *de;3819int oldlen = name->len;38203821if(!d)3822return name->len ? errno :0;38233824while((de =readdir(d)) != NULL) {3825struct stat st;38263827if(de->d_name[0] =='.')3828continue;3829if(ends_with(de->d_name,".lock"))3830continue;3831strbuf_addstr(name, de->d_name);3832if(stat(git_path("logs/%s", name->buf), &st) <0) {3833;/* silently ignore */3834}else{3835if(S_ISDIR(st.st_mode)) {3836strbuf_addch(name,'/');3837 retval =do_for_each_reflog(name, fn, cb_data);3838}else{3839struct object_id oid;38403841if(read_ref_full(name->buf,0, oid.hash, NULL))3842 retval =error("bad ref for%s", name->buf);3843else3844 retval =fn(name->buf, &oid,0, cb_data);3845}3846if(retval)3847break;3848}3849strbuf_setlen(name, oldlen);3850}3851closedir(d);3852return retval;3853}38543855intfor_each_reflog(each_ref_fn fn,void*cb_data)3856{3857int retval;3858struct strbuf name;3859strbuf_init(&name, PATH_MAX);3860 retval =do_for_each_reflog(&name, fn, cb_data);3861strbuf_release(&name);3862return retval;3863}38643865struct ref_transaction *ref_transaction_begin(struct strbuf *err)3866{3867assert(err);38683869returnxcalloc(1,sizeof(struct ref_transaction));3870}38713872voidref_transaction_free(struct ref_transaction *transaction)3873{3874int i;38753876if(!transaction)3877return;38783879for(i =0; i < transaction->nr; i++) {3880free(transaction->updates[i]->msg);3881free(transaction->updates[i]);3882}3883free(transaction->updates);3884free(transaction);3885}38863887static struct ref_update *add_update(struct ref_transaction *transaction,3888const char*refname)3889{3890size_t len =strlen(refname) +1;3891struct ref_update *update =xcalloc(1,sizeof(*update) + len);38923893memcpy((char*)update->refname, refname, len);/* includes NUL */3894ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3895 transaction->updates[transaction->nr++] = update;3896return update;3897}38983899intref_transaction_update(struct ref_transaction *transaction,3900const char*refname,3901const unsigned char*new_sha1,3902const unsigned char*old_sha1,3903unsigned int flags,const char*msg,3904struct strbuf *err)3905{3906struct ref_update *update;39073908assert(err);39093910if(transaction->state != REF_TRANSACTION_OPEN)3911die("BUG: update called for transaction that is not open");39123913if(new_sha1 && !is_null_sha1(new_sha1) &&3914check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3915strbuf_addf(err,"refusing to update ref with bad name%s",3916 refname);3917return-1;3918}39193920 update =add_update(transaction, refname);3921if(new_sha1) {3922hashcpy(update->new_sha1, new_sha1);3923 flags |= REF_HAVE_NEW;3924}3925if(old_sha1) {3926hashcpy(update->old_sha1, old_sha1);3927 flags |= REF_HAVE_OLD;3928}3929 update->flags = flags;3930if(msg)3931 update->msg =xstrdup(msg);3932return0;3933}39343935intref_transaction_create(struct ref_transaction *transaction,3936const char*refname,3937const unsigned char*new_sha1,3938unsigned int flags,const char*msg,3939struct strbuf *err)3940{3941if(!new_sha1 ||is_null_sha1(new_sha1))3942die("BUG: create called without valid new_sha1");3943returnref_transaction_update(transaction, refname, new_sha1,3944 null_sha1, flags, msg, err);3945}39463947intref_transaction_delete(struct ref_transaction *transaction,3948const char*refname,3949const unsigned char*old_sha1,3950unsigned int flags,const char*msg,3951struct strbuf *err)3952{3953if(old_sha1 &&is_null_sha1(old_sha1))3954die("BUG: delete called with old_sha1 set to zeros");3955returnref_transaction_update(transaction, refname,3956 null_sha1, old_sha1,3957 flags, msg, err);3958}39593960intref_transaction_verify(struct ref_transaction *transaction,3961const char*refname,3962const unsigned char*old_sha1,3963unsigned int flags,3964struct strbuf *err)3965{3966if(!old_sha1)3967die("BUG: verify called with old_sha1 set to NULL");3968returnref_transaction_update(transaction, refname,3969 NULL, old_sha1,3970 flags, NULL, err);3971}39723973intupdate_ref(const char*msg,const char*refname,3974const unsigned char*new_sha1,const unsigned char*old_sha1,3975unsigned int flags,enum action_on_err onerr)3976{3977struct ref_transaction *t = NULL;3978struct strbuf err = STRBUF_INIT;3979int ret =0;39803981if(ref_type(refname) == REF_TYPE_PSEUDOREF) {3982 ret =write_pseudoref(refname, new_sha1, old_sha1, &err);3983}else{3984 t =ref_transaction_begin(&err);3985if(!t ||3986ref_transaction_update(t, refname, new_sha1, old_sha1,3987 flags, msg, &err) ||3988ref_transaction_commit(t, &err)) {3989 ret =1;3990ref_transaction_free(t);3991}3992}3993if(ret) {3994const char*str ="update_ref failed for ref '%s':%s";39953996switch(onerr) {3997case UPDATE_REFS_MSG_ON_ERR:3998error(str, refname, err.buf);3999break;4000case UPDATE_REFS_DIE_ON_ERR:4001die(str, refname, err.buf);4002break;4003case UPDATE_REFS_QUIET_ON_ERR:4004break;4005}4006strbuf_release(&err);4007return1;4008}4009strbuf_release(&err);4010if(t)4011ref_transaction_free(t);4012return0;4013}40144015static intref_update_reject_duplicates(struct string_list *refnames,4016struct strbuf *err)4017{4018int i, n = refnames->nr;40194020assert(err);40214022for(i =1; i < n; i++)4023if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {4024strbuf_addf(err,4025"Multiple updates for ref '%s' not allowed.",4026 refnames->items[i].string);4027return1;4028}4029return0;4030}40314032intref_transaction_commit(struct ref_transaction *transaction,4033struct strbuf *err)4034{4035int ret =0, i;4036int n = transaction->nr;4037struct ref_update **updates = transaction->updates;4038struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4039struct string_list_item *ref_to_delete;4040struct string_list affected_refnames = STRING_LIST_INIT_NODUP;40414042assert(err);40434044if(transaction->state != REF_TRANSACTION_OPEN)4045die("BUG: commit called for transaction that is not open");40464047if(!n) {4048 transaction->state = REF_TRANSACTION_CLOSED;4049return0;4050}40514052/* Fail if a refname appears more than once in the transaction: */4053for(i =0; i < n; i++)4054string_list_append(&affected_refnames, updates[i]->refname);4055string_list_sort(&affected_refnames);4056if(ref_update_reject_duplicates(&affected_refnames, err)) {4057 ret = TRANSACTION_GENERIC_ERROR;4058goto cleanup;4059}40604061/*4062 * Acquire all locks, verify old values if provided, check4063 * that new values are valid, and write new values to the4064 * lockfiles, ready to be activated. Only keep one lockfile4065 * open at a time to avoid running out of file descriptors.4066 */4067for(i =0; i < n; i++) {4068struct ref_update *update = updates[i];40694070if((update->flags & REF_HAVE_NEW) &&4071is_null_sha1(update->new_sha1))4072 update->flags |= REF_DELETING;4073 update->lock =lock_ref_sha1_basic(4074 update->refname,4075((update->flags & REF_HAVE_OLD) ?4076 update->old_sha1 : NULL),4077&affected_refnames, NULL,4078 update->flags,4079&update->type,4080 err);4081if(!update->lock) {4082char*reason;40834084 ret = (errno == ENOTDIR)4085? TRANSACTION_NAME_CONFLICT4086: TRANSACTION_GENERIC_ERROR;4087 reason =strbuf_detach(err, NULL);4088strbuf_addf(err,"cannot lock ref '%s':%s",4089 update->refname, reason);4090free(reason);4091goto cleanup;4092}4093if((update->flags & REF_HAVE_NEW) &&4094!(update->flags & REF_DELETING)) {4095int overwriting_symref = ((update->type & REF_ISSYMREF) &&4096(update->flags & REF_NODEREF));40974098if(!overwriting_symref &&4099!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4100/*4101 * The reference already has the desired4102 * value, so we don't need to write it.4103 */4104}else if(write_ref_to_lockfile(update->lock,4105 update->new_sha1,4106 err)) {4107char*write_err =strbuf_detach(err, NULL);41084109/*4110 * The lock was freed upon failure of4111 * write_ref_to_lockfile():4112 */4113 update->lock = NULL;4114strbuf_addf(err,4115"cannot update the ref '%s':%s",4116 update->refname, write_err);4117free(write_err);4118 ret = TRANSACTION_GENERIC_ERROR;4119goto cleanup;4120}else{4121 update->flags |= REF_NEEDS_COMMIT;4122}4123}4124if(!(update->flags & REF_NEEDS_COMMIT)) {4125/*4126 * We didn't have to write anything to the lockfile.4127 * Close it to free up the file descriptor:4128 */4129if(close_ref(update->lock)) {4130strbuf_addf(err,"Couldn't close%s.lock",4131 update->refname);4132goto cleanup;4133}4134}4135}41364137/* Perform updates first so live commits remain referenced */4138for(i =0; i < n; i++) {4139struct ref_update *update = updates[i];41404141if(update->flags & REF_NEEDS_COMMIT) {4142if(commit_ref_update(update->lock,4143 update->new_sha1, update->msg,4144 update->flags, err)) {4145/* freed by commit_ref_update(): */4146 update->lock = NULL;4147 ret = TRANSACTION_GENERIC_ERROR;4148goto cleanup;4149}else{4150/* freed by commit_ref_update(): */4151 update->lock = NULL;4152}4153}4154}41554156/* Perform deletes now that updates are safely completed */4157for(i =0; i < n; i++) {4158struct ref_update *update = updates[i];41594160if(update->flags & REF_DELETING) {4161if(delete_ref_loose(update->lock, update->type, err)) {4162 ret = TRANSACTION_GENERIC_ERROR;4163goto cleanup;4164}41654166if(!(update->flags & REF_ISPRUNING))4167string_list_append(&refs_to_delete,4168 update->lock->ref_name);4169}4170}41714172if(repack_without_refs(&refs_to_delete, err)) {4173 ret = TRANSACTION_GENERIC_ERROR;4174goto cleanup;4175}4176for_each_string_list_item(ref_to_delete, &refs_to_delete)4177unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4178clear_loose_ref_cache(&ref_cache);41794180cleanup:4181 transaction->state = REF_TRANSACTION_CLOSED;41824183for(i =0; i < n; i++)4184if(updates[i]->lock)4185unlock_ref(updates[i]->lock);4186string_list_clear(&refs_to_delete,0);4187string_list_clear(&affected_refnames,0);4188return ret;4189}41904191static intref_present(const char*refname,4192const struct object_id *oid,int flags,void*cb_data)4193{4194struct string_list *affected_refnames = cb_data;41954196returnstring_list_has_string(affected_refnames, refname);4197}41984199intinitial_ref_transaction_commit(struct ref_transaction *transaction,4200struct strbuf *err)4201{4202int ret =0, i;4203int n = transaction->nr;4204struct ref_update **updates = transaction->updates;4205struct string_list affected_refnames = STRING_LIST_INIT_NODUP;42064207assert(err);42084209if(transaction->state != REF_TRANSACTION_OPEN)4210die("BUG: commit called for transaction that is not open");42114212/* Fail if a refname appears more than once in the transaction: */4213for(i =0; i < n; i++)4214string_list_append(&affected_refnames, updates[i]->refname);4215string_list_sort(&affected_refnames);4216if(ref_update_reject_duplicates(&affected_refnames, err)) {4217 ret = TRANSACTION_GENERIC_ERROR;4218goto cleanup;4219}42204221/*4222 * It's really undefined to call this function in an active4223 * repository or when there are existing references: we are4224 * only locking and changing packed-refs, so (1) any4225 * simultaneous processes might try to change a reference at4226 * the same time we do, and (2) any existing loose versions of4227 * the references that we are setting would have precedence4228 * over our values. But some remote helpers create the remote4229 * "HEAD" and "master" branches before calling this function,4230 * so here we really only check that none of the references4231 * that we are creating already exists.4232 */4233if(for_each_rawref(ref_present, &affected_refnames))4234die("BUG: initial ref transaction called with existing refs");42354236for(i =0; i < n; i++) {4237struct ref_update *update = updates[i];42384239if((update->flags & REF_HAVE_OLD) &&4240!is_null_sha1(update->old_sha1))4241die("BUG: initial ref transaction with old_sha1 set");4242if(verify_refname_available(update->refname,4243&affected_refnames, NULL,4244 err)) {4245 ret = TRANSACTION_NAME_CONFLICT;4246goto cleanup;4247}4248}42494250if(lock_packed_refs(0)) {4251strbuf_addf(err,"unable to lock packed-refs file:%s",4252strerror(errno));4253 ret = TRANSACTION_GENERIC_ERROR;4254goto cleanup;4255}42564257for(i =0; i < n; i++) {4258struct ref_update *update = updates[i];42594260if((update->flags & REF_HAVE_NEW) &&4261!is_null_sha1(update->new_sha1))4262add_packed_ref(update->refname, update->new_sha1);4263}42644265if(commit_packed_refs()) {4266strbuf_addf(err,"unable to commit packed-refs file:%s",4267strerror(errno));4268 ret = TRANSACTION_GENERIC_ERROR;4269goto cleanup;4270}42714272cleanup:4273 transaction->state = REF_TRANSACTION_CLOSED;4274string_list_clear(&affected_refnames,0);4275return ret;4276}42774278char*shorten_unambiguous_ref(const char*refname,int strict)4279{4280int i;4281static char**scanf_fmts;4282static int nr_rules;4283char*short_name;42844285if(!nr_rules) {4286/*4287 * Pre-generate scanf formats from ref_rev_parse_rules[].4288 * Generate a format suitable for scanf from a4289 * ref_rev_parse_rules rule by interpolating "%s" at the4290 * location of the "%.*s".4291 */4292size_t total_len =0;4293size_t offset =0;42944295/* the rule list is NULL terminated, count them first */4296for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4297/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4298 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;42994300 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);43014302 offset =0;4303for(i =0; i < nr_rules; i++) {4304assert(offset < total_len);4305 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4306 offset +=snprintf(scanf_fmts[i], total_len - offset,4307 ref_rev_parse_rules[i],2,"%s") +1;4308}4309}43104311/* bail out if there are no rules */4312if(!nr_rules)4313returnxstrdup(refname);43144315/* buffer for scanf result, at most refname must fit */4316 short_name =xstrdup(refname);43174318/* skip first rule, it will always match */4319for(i = nr_rules -1; i >0; --i) {4320int j;4321int rules_to_fail = i;4322int short_name_len;43234324if(1!=sscanf(refname, scanf_fmts[i], short_name))4325continue;43264327 short_name_len =strlen(short_name);43284329/*4330 * in strict mode, all (except the matched one) rules4331 * must fail to resolve to a valid non-ambiguous ref4332 */4333if(strict)4334 rules_to_fail = nr_rules;43354336/*4337 * check if the short name resolves to a valid ref,4338 * but use only rules prior to the matched one4339 */4340for(j =0; j < rules_to_fail; j++) {4341const char*rule = ref_rev_parse_rules[j];4342char refname[PATH_MAX];43434344/* skip matched rule */4345if(i == j)4346continue;43474348/*4349 * the short name is ambiguous, if it resolves4350 * (with this previous rule) to a valid ref4351 * read_ref() returns 0 on success4352 */4353mksnpath(refname,sizeof(refname),4354 rule, short_name_len, short_name);4355if(ref_exists(refname))4356break;4357}43584359/*4360 * short name is non-ambiguous if all previous rules4361 * haven't resolved to a valid ref4362 */4363if(j == rules_to_fail)4364return short_name;4365}43664367free(short_name);4368returnxstrdup(refname);4369}43704371static struct string_list *hide_refs;43724373intparse_hide_refs_config(const char*var,const char*value,const char*section)4374{4375if(!strcmp("transfer.hiderefs", var) ||4376/* NEEDSWORK: use parse_config_key() once both are merged */4377(starts_with(var, section) && var[strlen(section)] =='.'&&4378!strcmp(var +strlen(section),".hiderefs"))) {4379char*ref;4380int len;43814382if(!value)4383returnconfig_error_nonbool(var);4384 ref =xstrdup(value);4385 len =strlen(ref);4386while(len && ref[len -1] =='/')4387 ref[--len] ='\0';4388if(!hide_refs) {4389 hide_refs =xcalloc(1,sizeof(*hide_refs));4390 hide_refs->strdup_strings =1;4391}4392string_list_append(hide_refs, ref);4393}4394return0;4395}43964397intref_is_hidden(const char*refname)4398{4399int i;44004401if(!hide_refs)4402return0;4403for(i = hide_refs->nr -1; i >=0; i--) {4404const char*match = hide_refs->items[i].string;4405int neg =0;4406int len;44074408if(*match =='!') {4409 neg =1;4410 match++;4411}44124413if(!starts_with(refname, match))4414continue;4415 len =strlen(match);4416if(!refname[len] || refname[len] =='/')4417return!neg;4418}4419return0;4420}44214422struct expire_reflog_cb {4423unsigned int flags;4424 reflog_expiry_should_prune_fn *should_prune_fn;4425void*policy_cb;4426FILE*newlog;4427unsigned char last_kept_sha1[20];4428};44294430static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4431const char*email,unsigned long timestamp,int tz,4432const char*message,void*cb_data)4433{4434struct expire_reflog_cb *cb = cb_data;4435struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;44364437if(cb->flags & EXPIRE_REFLOGS_REWRITE)4438 osha1 = cb->last_kept_sha1;44394440if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4441 message, policy_cb)) {4442if(!cb->newlog)4443printf("would prune%s", message);4444else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4445printf("prune%s", message);4446}else{4447if(cb->newlog) {4448fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4449sha1_to_hex(osha1),sha1_to_hex(nsha1),4450 email, timestamp, tz, message);4451hashcpy(cb->last_kept_sha1, nsha1);4452}4453if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4454printf("keep%s", message);4455}4456return0;4457}44584459intreflog_expire(const char*refname,const unsigned char*sha1,4460unsigned int flags,4461 reflog_expiry_prepare_fn prepare_fn,4462 reflog_expiry_should_prune_fn should_prune_fn,4463 reflog_expiry_cleanup_fn cleanup_fn,4464void*policy_cb_data)4465{4466static struct lock_file reflog_lock;4467struct expire_reflog_cb cb;4468struct ref_lock *lock;4469char*log_file;4470int status =0;4471int type;4472struct strbuf err = STRBUF_INIT;44734474memset(&cb,0,sizeof(cb));4475 cb.flags = flags;4476 cb.policy_cb = policy_cb_data;4477 cb.should_prune_fn = should_prune_fn;44784479/*4480 * The reflog file is locked by holding the lock on the4481 * reference itself, plus we might need to update the4482 * reference if --updateref was specified:4483 */4484 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4485if(!lock) {4486error("cannot lock ref '%s':%s", refname, err.buf);4487strbuf_release(&err);4488return-1;4489}4490if(!reflog_exists(refname)) {4491unlock_ref(lock);4492return0;4493}44944495 log_file =git_pathdup("logs/%s", refname);4496if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4497/*4498 * Even though holding $GIT_DIR/logs/$reflog.lock has4499 * no locking implications, we use the lock_file4500 * machinery here anyway because it does a lot of the4501 * work we need, including cleaning up if the program4502 * exits unexpectedly.4503 */4504if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4505struct strbuf err = STRBUF_INIT;4506unable_to_lock_message(log_file, errno, &err);4507error("%s", err.buf);4508strbuf_release(&err);4509goto failure;4510}4511 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4512if(!cb.newlog) {4513error("cannot fdopen%s(%s)",4514get_lock_file_path(&reflog_lock),strerror(errno));4515goto failure;4516}4517}45184519(*prepare_fn)(refname, sha1, cb.policy_cb);4520for_each_reflog_ent(refname, expire_reflog_ent, &cb);4521(*cleanup_fn)(cb.policy_cb);45224523if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4524/*4525 * It doesn't make sense to adjust a reference pointed4526 * to by a symbolic ref based on expiring entries in4527 * the symbolic reference's reflog. Nor can we update4528 * a reference if there are no remaining reflog4529 * entries.4530 */4531int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4532!(type & REF_ISSYMREF) &&4533!is_null_sha1(cb.last_kept_sha1);45344535if(close_lock_file(&reflog_lock)) {4536 status |=error("couldn't write%s:%s", log_file,4537strerror(errno));4538}else if(update &&4539(write_in_full(get_lock_file_fd(lock->lk),4540sha1_to_hex(cb.last_kept_sha1),40) !=40||4541write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||4542close_ref(lock) <0)) {4543 status |=error("couldn't write%s",4544get_lock_file_path(lock->lk));4545rollback_lock_file(&reflog_lock);4546}else if(commit_lock_file(&reflog_lock)) {4547 status |=error("unable to commit reflog '%s' (%s)",4548 log_file,strerror(errno));4549}else if(update &&commit_ref(lock)) {4550 status |=error("couldn't set%s", lock->ref_name);4551}4552}4553free(log_file);4554unlock_ref(lock);4555return status;45564557 failure:4558rollback_lock_file(&reflog_lock);4559free(log_file);4560unlock_ref(lock);4561return-1;4562}