1#include"cache.h" 2#include"refs.h" 3#include"object.h" 4#include"tag.h" 5#include"dir.h" 6#include"string-list.h" 7 8/* 9 * How to handle various characters in refnames: 10 * 0: An acceptable character for refs 11 * 1: End-of-component 12 * 2: ., look for a preceding . to reject .. in refs 13 * 3: {, look for a preceding @ to reject @{ in refs 14 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 15 */ 16static unsigned char refname_disposition[256] = { 171,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 184,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 194,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 200,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 210,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 220,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 230,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 240,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 25}; 26 27/* 28 * Try to read one refname component from the front of refname. 29 * Return the length of the component found, or -1 if the component is 30 * not legal. It is legal if it is something reasonable to have under 31 * ".git/refs/"; We do not like it if: 32 * 33 * - any path component of it begins with ".", or 34 * - it has double dots "..", or 35 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 36 * - it ends with a "/". 37 * - it ends with ".lock" 38 * - it contains a "\" (backslash) 39 */ 40static intcheck_refname_component(const char*refname,int flags) 41{ 42const char*cp; 43char last ='\0'; 44 45for(cp = refname; ; cp++) { 46int ch = *cp &255; 47unsigned char disp = refname_disposition[ch]; 48switch(disp) { 49case1: 50goto out; 51case2: 52if(last =='.') 53return-1;/* Refname contains "..". */ 54break; 55case3: 56if(last =='@') 57return-1;/* Refname contains "@{". */ 58break; 59case4: 60return-1; 61} 62 last = ch; 63} 64out: 65if(cp == refname) 66return0;/* Component has zero length. */ 67if(refname[0] =='.') { 68if(!(flags & REFNAME_DOT_COMPONENT)) 69return-1;/* Component starts with '.'. */ 70/* 71 * Even if leading dots are allowed, don't allow "." 72 * as a component (".." is prevented by a rule above). 73 */ 74if(refname[1] =='\0') 75return-1;/* Component equals ".". */ 76} 77if(cp - refname >=5&& !memcmp(cp -5,".lock",5)) 78return-1;/* Refname ends with ".lock". */ 79return cp - refname; 80} 81 82intcheck_refname_format(const char*refname,int flags) 83{ 84int component_len, component_count =0; 85 86if(!strcmp(refname,"@")) 87/* Refname is a single character '@'. */ 88return-1; 89 90while(1) { 91/* We are at the start of a path component. */ 92 component_len =check_refname_component(refname, flags); 93if(component_len <=0) { 94if((flags & REFNAME_REFSPEC_PATTERN) && 95 refname[0] =='*'&& 96(refname[1] =='\0'|| refname[1] =='/')) { 97/* Accept one wildcard as a full refname component. */ 98 flags &= ~REFNAME_REFSPEC_PATTERN; 99 component_len =1; 100}else{ 101return-1; 102} 103} 104 component_count++; 105if(refname[component_len] =='\0') 106break; 107/* Skip to next component. */ 108 refname += component_len +1; 109} 110 111if(refname[component_len -1] =='.') 112return-1;/* Refname ends with '.'. */ 113if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 114return-1;/* Refname has only one component. */ 115return0; 116} 117 118struct ref_entry; 119 120/* 121 * Information used (along with the information in ref_entry) to 122 * describe a single cached reference. This data structure only 123 * occurs embedded in a union in struct ref_entry, and only when 124 * (ref_entry->flag & REF_DIR) is zero. 125 */ 126struct ref_value { 127/* 128 * The name of the object to which this reference resolves 129 * (which may be a tag object). If REF_ISBROKEN, this is 130 * null. If REF_ISSYMREF, then this is the name of the object 131 * referred to by the last reference in the symlink chain. 132 */ 133unsigned char sha1[20]; 134 135/* 136 * If REF_KNOWS_PEELED, then this field holds the peeled value 137 * of this reference, or null if the reference is known not to 138 * be peelable. See the documentation for peel_ref() for an 139 * exact definition of "peelable". 140 */ 141unsigned char peeled[20]; 142}; 143 144struct ref_cache; 145 146/* 147 * Information used (along with the information in ref_entry) to 148 * describe a level in the hierarchy of references. This data 149 * structure only occurs embedded in a union in struct ref_entry, and 150 * only when (ref_entry.flag & REF_DIR) is set. In that case, 151 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 152 * in the directory have already been read: 153 * 154 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 155 * or packed references, already read. 156 * 157 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 158 * references that hasn't been read yet (nor has any of its 159 * subdirectories). 160 * 161 * Entries within a directory are stored within a growable array of 162 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 163 * sorted are sorted by their component name in strcmp() order and the 164 * remaining entries are unsorted. 165 * 166 * Loose references are read lazily, one directory at a time. When a 167 * directory of loose references is read, then all of the references 168 * in that directory are stored, and REF_INCOMPLETE stubs are created 169 * for any subdirectories, but the subdirectories themselves are not 170 * read. The reading is triggered by get_ref_dir(). 171 */ 172struct ref_dir { 173int nr, alloc; 174 175/* 176 * Entries with index 0 <= i < sorted are sorted by name. New 177 * entries are appended to the list unsorted, and are sorted 178 * only when required; thus we avoid the need to sort the list 179 * after the addition of every reference. 180 */ 181int sorted; 182 183/* A pointer to the ref_cache that contains this ref_dir. */ 184struct ref_cache *ref_cache; 185 186struct ref_entry **entries; 187}; 188 189/* 190 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 191 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see 192 * refs.h. 193 */ 194 195/* 196 * The field ref_entry->u.value.peeled of this value entry contains 197 * the correct peeled value for the reference, which might be 198 * null_sha1 if the reference is not a tag or if it is broken. 199 */ 200#define REF_KNOWS_PEELED 0x08 201 202/* ref_entry represents a directory of references */ 203#define REF_DIR 0x10 204 205/* 206 * Entry has not yet been read from disk (used only for REF_DIR 207 * entries representing loose references) 208 */ 209#define REF_INCOMPLETE 0x20 210 211/* 212 * A ref_entry represents either a reference or a "subdirectory" of 213 * references. 214 * 215 * Each directory in the reference namespace is represented by a 216 * ref_entry with (flags & REF_DIR) set and containing a subdir member 217 * that holds the entries in that directory that have been read so 218 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 219 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 220 * used for loose reference directories. 221 * 222 * References are represented by a ref_entry with (flags & REF_DIR) 223 * unset and a value member that describes the reference's value. The 224 * flag member is at the ref_entry level, but it is also needed to 225 * interpret the contents of the value field (in other words, a 226 * ref_value object is not very much use without the enclosing 227 * ref_entry). 228 * 229 * Reference names cannot end with slash and directories' names are 230 * always stored with a trailing slash (except for the top-level 231 * directory, which is always denoted by ""). This has two nice 232 * consequences: (1) when the entries in each subdir are sorted 233 * lexicographically by name (as they usually are), the references in 234 * a whole tree can be generated in lexicographic order by traversing 235 * the tree in left-to-right, depth-first order; (2) the names of 236 * references and subdirectories cannot conflict, and therefore the 237 * presence of an empty subdirectory does not block the creation of a 238 * similarly-named reference. (The fact that reference names with the 239 * same leading components can conflict *with each other* is a 240 * separate issue that is regulated by is_refname_available().) 241 * 242 * Please note that the name field contains the fully-qualified 243 * reference (or subdirectory) name. Space could be saved by only 244 * storing the relative names. But that would require the full names 245 * to be generated on the fly when iterating in do_for_each_ref(), and 246 * would break callback functions, who have always been able to assume 247 * that the name strings that they are passed will not be freed during 248 * the iteration. 249 */ 250struct ref_entry { 251unsigned char flag;/* ISSYMREF? ISPACKED? */ 252union{ 253struct ref_value value;/* if not (flags&REF_DIR) */ 254struct ref_dir subdir;/* if (flags&REF_DIR) */ 255} u; 256/* 257 * The full name of the reference (e.g., "refs/heads/master") 258 * or the full name of the directory with a trailing slash 259 * (e.g., "refs/heads/"): 260 */ 261char name[FLEX_ARRAY]; 262}; 263 264static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 265 266static struct ref_dir *get_ref_dir(struct ref_entry *entry) 267{ 268struct ref_dir *dir; 269assert(entry->flag & REF_DIR); 270 dir = &entry->u.subdir; 271if(entry->flag & REF_INCOMPLETE) { 272read_loose_refs(entry->name, dir); 273 entry->flag &= ~REF_INCOMPLETE; 274} 275return dir; 276} 277 278static struct ref_entry *create_ref_entry(const char*refname, 279const unsigned char*sha1,int flag, 280int check_name) 281{ 282int len; 283struct ref_entry *ref; 284 285if(check_name && 286check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) 287die("Reference has invalid format: '%s'", refname); 288 len =strlen(refname) +1; 289 ref =xmalloc(sizeof(struct ref_entry) + len); 290hashcpy(ref->u.value.sha1, sha1); 291hashclr(ref->u.value.peeled); 292memcpy(ref->name, refname, len); 293 ref->flag = flag; 294return ref; 295} 296 297static voidclear_ref_dir(struct ref_dir *dir); 298 299static voidfree_ref_entry(struct ref_entry *entry) 300{ 301if(entry->flag & REF_DIR) { 302/* 303 * Do not use get_ref_dir() here, as that might 304 * trigger the reading of loose refs. 305 */ 306clear_ref_dir(&entry->u.subdir); 307} 308free(entry); 309} 310 311/* 312 * Add a ref_entry to the end of dir (unsorted). Entry is always 313 * stored directly in dir; no recursion into subdirectories is 314 * done. 315 */ 316static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 317{ 318ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 319 dir->entries[dir->nr++] = entry; 320/* optimize for the case that entries are added in order */ 321if(dir->nr ==1|| 322(dir->nr == dir->sorted +1&& 323strcmp(dir->entries[dir->nr -2]->name, 324 dir->entries[dir->nr -1]->name) <0)) 325 dir->sorted = dir->nr; 326} 327 328/* 329 * Clear and free all entries in dir, recursively. 330 */ 331static voidclear_ref_dir(struct ref_dir *dir) 332{ 333int i; 334for(i =0; i < dir->nr; i++) 335free_ref_entry(dir->entries[i]); 336free(dir->entries); 337 dir->sorted = dir->nr = dir->alloc =0; 338 dir->entries = NULL; 339} 340 341/* 342 * Create a struct ref_entry object for the specified dirname. 343 * dirname is the name of the directory with a trailing slash (e.g., 344 * "refs/heads/") or "" for the top-level directory. 345 */ 346static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 347const char*dirname,size_t len, 348int incomplete) 349{ 350struct ref_entry *direntry; 351 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 352memcpy(direntry->name, dirname, len); 353 direntry->name[len] ='\0'; 354 direntry->u.subdir.ref_cache = ref_cache; 355 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 356return direntry; 357} 358 359static intref_entry_cmp(const void*a,const void*b) 360{ 361struct ref_entry *one = *(struct ref_entry **)a; 362struct ref_entry *two = *(struct ref_entry **)b; 363returnstrcmp(one->name, two->name); 364} 365 366static voidsort_ref_dir(struct ref_dir *dir); 367 368struct string_slice { 369size_t len; 370const char*str; 371}; 372 373static intref_entry_cmp_sslice(const void*key_,const void*ent_) 374{ 375const struct string_slice *key = key_; 376const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 377int cmp =strncmp(key->str, ent->name, key->len); 378if(cmp) 379return cmp; 380return'\0'- (unsigned char)ent->name[key->len]; 381} 382 383/* 384 * Return the index of the entry with the given refname from the 385 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 386 * no such entry is found. dir must already be complete. 387 */ 388static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 389{ 390struct ref_entry **r; 391struct string_slice key; 392 393if(refname == NULL || !dir->nr) 394return-1; 395 396sort_ref_dir(dir); 397 key.len = len; 398 key.str = refname; 399 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 400 ref_entry_cmp_sslice); 401 402if(r == NULL) 403return-1; 404 405return r - dir->entries; 406} 407 408/* 409 * Search for a directory entry directly within dir (without 410 * recursing). Sort dir if necessary. subdirname must be a directory 411 * name (i.e., end in '/'). If mkdir is set, then create the 412 * directory if it is missing; otherwise, return NULL if the desired 413 * directory cannot be found. dir must already be complete. 414 */ 415static struct ref_dir *search_for_subdir(struct ref_dir *dir, 416const char*subdirname,size_t len, 417int mkdir) 418{ 419int entry_index =search_ref_dir(dir, subdirname, len); 420struct ref_entry *entry; 421if(entry_index == -1) { 422if(!mkdir) 423return NULL; 424/* 425 * Since dir is complete, the absence of a subdir 426 * means that the subdir really doesn't exist; 427 * therefore, create an empty record for it but mark 428 * the record complete. 429 */ 430 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 431add_entry_to_dir(dir, entry); 432}else{ 433 entry = dir->entries[entry_index]; 434} 435returnget_ref_dir(entry); 436} 437 438/* 439 * If refname is a reference name, find the ref_dir within the dir 440 * tree that should hold refname. If refname is a directory name 441 * (i.e., ends in '/'), then return that ref_dir itself. dir must 442 * represent the top-level directory and must already be complete. 443 * Sort ref_dirs and recurse into subdirectories as necessary. If 444 * mkdir is set, then create any missing directories; otherwise, 445 * return NULL if the desired directory cannot be found. 446 */ 447static struct ref_dir *find_containing_dir(struct ref_dir *dir, 448const char*refname,int mkdir) 449{ 450const char*slash; 451for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 452size_t dirnamelen = slash - refname +1; 453struct ref_dir *subdir; 454 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 455if(!subdir) { 456 dir = NULL; 457break; 458} 459 dir = subdir; 460} 461 462return dir; 463} 464 465/* 466 * Find the value entry with the given name in dir, sorting ref_dirs 467 * and recursing into subdirectories as necessary. If the name is not 468 * found or it corresponds to a directory entry, return NULL. 469 */ 470static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 471{ 472int entry_index; 473struct ref_entry *entry; 474 dir =find_containing_dir(dir, refname,0); 475if(!dir) 476return NULL; 477 entry_index =search_ref_dir(dir, refname,strlen(refname)); 478if(entry_index == -1) 479return NULL; 480 entry = dir->entries[entry_index]; 481return(entry->flag & REF_DIR) ? NULL : entry; 482} 483 484/* 485 * Remove the entry with the given name from dir, recursing into 486 * subdirectories as necessary. If refname is the name of a directory 487 * (i.e., ends with '/'), then remove the directory and its contents. 488 * If the removal was successful, return the number of entries 489 * remaining in the directory entry that contained the deleted entry. 490 * If the name was not found, return -1. Please note that this 491 * function only deletes the entry from the cache; it does not delete 492 * it from the filesystem or ensure that other cache entries (which 493 * might be symbolic references to the removed entry) are updated. 494 * Nor does it remove any containing dir entries that might be made 495 * empty by the removal. dir must represent the top-level directory 496 * and must already be complete. 497 */ 498static intremove_entry(struct ref_dir *dir,const char*refname) 499{ 500int refname_len =strlen(refname); 501int entry_index; 502struct ref_entry *entry; 503int is_dir = refname[refname_len -1] =='/'; 504if(is_dir) { 505/* 506 * refname represents a reference directory. Remove 507 * the trailing slash; otherwise we will get the 508 * directory *representing* refname rather than the 509 * one *containing* it. 510 */ 511char*dirname =xmemdupz(refname, refname_len -1); 512 dir =find_containing_dir(dir, dirname,0); 513free(dirname); 514}else{ 515 dir =find_containing_dir(dir, refname,0); 516} 517if(!dir) 518return-1; 519 entry_index =search_ref_dir(dir, refname, refname_len); 520if(entry_index == -1) 521return-1; 522 entry = dir->entries[entry_index]; 523 524memmove(&dir->entries[entry_index], 525&dir->entries[entry_index +1], 526(dir->nr - entry_index -1) *sizeof(*dir->entries) 527); 528 dir->nr--; 529if(dir->sorted > entry_index) 530 dir->sorted--; 531free_ref_entry(entry); 532return dir->nr; 533} 534 535/* 536 * Add a ref_entry to the ref_dir (unsorted), recursing into 537 * subdirectories as necessary. dir must represent the top-level 538 * directory. Return 0 on success. 539 */ 540static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 541{ 542 dir =find_containing_dir(dir, ref->name,1); 543if(!dir) 544return-1; 545add_entry_to_dir(dir, ref); 546return0; 547} 548 549/* 550 * Emit a warning and return true iff ref1 and ref2 have the same name 551 * and the same sha1. Die if they have the same name but different 552 * sha1s. 553 */ 554static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 555{ 556if(strcmp(ref1->name, ref2->name)) 557return0; 558 559/* Duplicate name; make sure that they don't conflict: */ 560 561if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 562/* This is impossible by construction */ 563die("Reference directory conflict:%s", ref1->name); 564 565if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 566die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 567 568warning("Duplicated ref:%s", ref1->name); 569return1; 570} 571 572/* 573 * Sort the entries in dir non-recursively (if they are not already 574 * sorted) and remove any duplicate entries. 575 */ 576static voidsort_ref_dir(struct ref_dir *dir) 577{ 578int i, j; 579struct ref_entry *last = NULL; 580 581/* 582 * This check also prevents passing a zero-length array to qsort(), 583 * which is a problem on some platforms. 584 */ 585if(dir->sorted == dir->nr) 586return; 587 588qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 589 590/* Remove any duplicates: */ 591for(i =0, j =0; j < dir->nr; j++) { 592struct ref_entry *entry = dir->entries[j]; 593if(last &&is_dup_ref(last, entry)) 594free_ref_entry(entry); 595else 596 last = dir->entries[i++] = entry; 597} 598 dir->sorted = dir->nr = i; 599} 600 601/* Include broken references in a do_for_each_ref*() iteration: */ 602#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 603 604/* 605 * Return true iff the reference described by entry can be resolved to 606 * an object in the database. Emit a warning if the referred-to 607 * object does not exist. 608 */ 609static intref_resolves_to_object(struct ref_entry *entry) 610{ 611if(entry->flag & REF_ISBROKEN) 612return0; 613if(!has_sha1_file(entry->u.value.sha1)) { 614error("%sdoes not point to a valid object!", entry->name); 615return0; 616} 617return1; 618} 619 620/* 621 * current_ref is a performance hack: when iterating over references 622 * using the for_each_ref*() functions, current_ref is set to the 623 * current reference's entry before calling the callback function. If 624 * the callback function calls peel_ref(), then peel_ref() first 625 * checks whether the reference to be peeled is the current reference 626 * (it usually is) and if so, returns that reference's peeled version 627 * if it is available. This avoids a refname lookup in a common case. 628 */ 629static struct ref_entry *current_ref; 630 631typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 632 633struct ref_entry_cb { 634const char*base; 635int trim; 636int flags; 637 each_ref_fn *fn; 638void*cb_data; 639}; 640 641/* 642 * Handle one reference in a do_for_each_ref*()-style iteration, 643 * calling an each_ref_fn for each entry. 644 */ 645static intdo_one_ref(struct ref_entry *entry,void*cb_data) 646{ 647struct ref_entry_cb *data = cb_data; 648struct ref_entry *old_current_ref; 649int retval; 650 651if(!starts_with(entry->name, data->base)) 652return0; 653 654if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 655!ref_resolves_to_object(entry)) 656return0; 657 658/* Store the old value, in case this is a recursive call: */ 659 old_current_ref = current_ref; 660 current_ref = entry; 661 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 662 entry->flag, data->cb_data); 663 current_ref = old_current_ref; 664return retval; 665} 666 667/* 668 * Call fn for each reference in dir that has index in the range 669 * offset <= index < dir->nr. Recurse into subdirectories that are in 670 * that index range, sorting them before iterating. This function 671 * does not sort dir itself; it should be sorted beforehand. fn is 672 * called for all references, including broken ones. 673 */ 674static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 675 each_ref_entry_fn fn,void*cb_data) 676{ 677int i; 678assert(dir->sorted == dir->nr); 679for(i = offset; i < dir->nr; i++) { 680struct ref_entry *entry = dir->entries[i]; 681int retval; 682if(entry->flag & REF_DIR) { 683struct ref_dir *subdir =get_ref_dir(entry); 684sort_ref_dir(subdir); 685 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 686}else{ 687 retval =fn(entry, cb_data); 688} 689if(retval) 690return retval; 691} 692return0; 693} 694 695/* 696 * Call fn for each reference in the union of dir1 and dir2, in order 697 * by refname. Recurse into subdirectories. If a value entry appears 698 * in both dir1 and dir2, then only process the version that is in 699 * dir2. The input dirs must already be sorted, but subdirs will be 700 * sorted as needed. fn is called for all references, including 701 * broken ones. 702 */ 703static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 704struct ref_dir *dir2, 705 each_ref_entry_fn fn,void*cb_data) 706{ 707int retval; 708int i1 =0, i2 =0; 709 710assert(dir1->sorted == dir1->nr); 711assert(dir2->sorted == dir2->nr); 712while(1) { 713struct ref_entry *e1, *e2; 714int cmp; 715if(i1 == dir1->nr) { 716returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 717} 718if(i2 == dir2->nr) { 719returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 720} 721 e1 = dir1->entries[i1]; 722 e2 = dir2->entries[i2]; 723 cmp =strcmp(e1->name, e2->name); 724if(cmp ==0) { 725if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 726/* Both are directories; descend them in parallel. */ 727struct ref_dir *subdir1 =get_ref_dir(e1); 728struct ref_dir *subdir2 =get_ref_dir(e2); 729sort_ref_dir(subdir1); 730sort_ref_dir(subdir2); 731 retval =do_for_each_entry_in_dirs( 732 subdir1, subdir2, fn, cb_data); 733 i1++; 734 i2++; 735}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 736/* Both are references; ignore the one from dir1. */ 737 retval =fn(e2, cb_data); 738 i1++; 739 i2++; 740}else{ 741die("conflict between reference and directory:%s", 742 e1->name); 743} 744}else{ 745struct ref_entry *e; 746if(cmp <0) { 747 e = e1; 748 i1++; 749}else{ 750 e = e2; 751 i2++; 752} 753if(e->flag & REF_DIR) { 754struct ref_dir *subdir =get_ref_dir(e); 755sort_ref_dir(subdir); 756 retval =do_for_each_entry_in_dir( 757 subdir,0, fn, cb_data); 758}else{ 759 retval =fn(e, cb_data); 760} 761} 762if(retval) 763return retval; 764} 765} 766 767/* 768 * Load all of the refs from the dir into our in-memory cache. The hard work 769 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 770 * through all of the sub-directories. We do not even need to care about 771 * sorting, as traversal order does not matter to us. 772 */ 773static voidprime_ref_dir(struct ref_dir *dir) 774{ 775int i; 776for(i =0; i < dir->nr; i++) { 777struct ref_entry *entry = dir->entries[i]; 778if(entry->flag & REF_DIR) 779prime_ref_dir(get_ref_dir(entry)); 780} 781} 782/* 783 * Return true iff refname1 and refname2 conflict with each other. 784 * Two reference names conflict if one of them exactly matches the 785 * leading components of the other; e.g., "foo/bar" conflicts with 786 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 787 * "foo/barbados". 788 */ 789static intnames_conflict(const char*refname1,const char*refname2) 790{ 791for(; *refname1 && *refname1 == *refname2; refname1++, refname2++) 792; 793return(*refname1 =='\0'&& *refname2 =='/') 794|| (*refname1 =='/'&& *refname2 =='\0'); 795} 796 797struct name_conflict_cb { 798const char*refname; 799const char*oldrefname; 800const char*conflicting_refname; 801}; 802 803static intname_conflict_fn(struct ref_entry *entry,void*cb_data) 804{ 805struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data; 806if(data->oldrefname && !strcmp(data->oldrefname, entry->name)) 807return0; 808if(names_conflict(data->refname, entry->name)) { 809 data->conflicting_refname = entry->name; 810return1; 811} 812return0; 813} 814 815/* 816 * Return true iff a reference named refname could be created without 817 * conflicting with the name of an existing reference in dir. If 818 * oldrefname is non-NULL, ignore potential conflicts with oldrefname 819 * (e.g., because oldrefname is scheduled for deletion in the same 820 * operation). 821 */ 822static intis_refname_available(const char*refname,const char*oldrefname, 823struct ref_dir *dir) 824{ 825struct name_conflict_cb data; 826 data.refname = refname; 827 data.oldrefname = oldrefname; 828 data.conflicting_refname = NULL; 829 830sort_ref_dir(dir); 831if(do_for_each_entry_in_dir(dir,0, name_conflict_fn, &data)) { 832error("'%s' exists; cannot create '%s'", 833 data.conflicting_refname, refname); 834return0; 835} 836return1; 837} 838 839struct packed_ref_cache { 840struct ref_entry *root; 841 842/* 843 * Count of references to the data structure in this instance, 844 * including the pointer from ref_cache::packed if any. The 845 * data will not be freed as long as the reference count is 846 * nonzero. 847 */ 848unsigned int referrers; 849 850/* 851 * Iff the packed-refs file associated with this instance is 852 * currently locked for writing, this points at the associated 853 * lock (which is owned by somebody else). The referrer count 854 * is also incremented when the file is locked and decremented 855 * when it is unlocked. 856 */ 857struct lock_file *lock; 858 859/* The metadata from when this packed-refs cache was read */ 860struct stat_validity validity; 861}; 862 863/* 864 * Future: need to be in "struct repository" 865 * when doing a full libification. 866 */ 867static struct ref_cache { 868struct ref_cache *next; 869struct ref_entry *loose; 870struct packed_ref_cache *packed; 871/* 872 * The submodule name, or "" for the main repo. We allocate 873 * length 1 rather than FLEX_ARRAY so that the main ref_cache 874 * is initialized correctly. 875 */ 876char name[1]; 877} ref_cache, *submodule_ref_caches; 878 879/* Lock used for the main packed-refs file: */ 880static struct lock_file packlock; 881 882/* 883 * Increment the reference count of *packed_refs. 884 */ 885static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 886{ 887 packed_refs->referrers++; 888} 889 890/* 891 * Decrease the reference count of *packed_refs. If it goes to zero, 892 * free *packed_refs and return true; otherwise return false. 893 */ 894static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 895{ 896if(!--packed_refs->referrers) { 897free_ref_entry(packed_refs->root); 898stat_validity_clear(&packed_refs->validity); 899free(packed_refs); 900return1; 901}else{ 902return0; 903} 904} 905 906static voidclear_packed_ref_cache(struct ref_cache *refs) 907{ 908if(refs->packed) { 909struct packed_ref_cache *packed_refs = refs->packed; 910 911if(packed_refs->lock) 912die("internal error: packed-ref cache cleared while locked"); 913 refs->packed = NULL; 914release_packed_ref_cache(packed_refs); 915} 916} 917 918static voidclear_loose_ref_cache(struct ref_cache *refs) 919{ 920if(refs->loose) { 921free_ref_entry(refs->loose); 922 refs->loose = NULL; 923} 924} 925 926static struct ref_cache *create_ref_cache(const char*submodule) 927{ 928int len; 929struct ref_cache *refs; 930if(!submodule) 931 submodule =""; 932 len =strlen(submodule) +1; 933 refs =xcalloc(1,sizeof(struct ref_cache) + len); 934memcpy(refs->name, submodule, len); 935return refs; 936} 937 938/* 939 * Return a pointer to a ref_cache for the specified submodule. For 940 * the main repository, use submodule==NULL. The returned structure 941 * will be allocated and initialized but not necessarily populated; it 942 * should not be freed. 943 */ 944static struct ref_cache *get_ref_cache(const char*submodule) 945{ 946struct ref_cache *refs; 947 948if(!submodule || !*submodule) 949return&ref_cache; 950 951for(refs = submodule_ref_caches; refs; refs = refs->next) 952if(!strcmp(submodule, refs->name)) 953return refs; 954 955 refs =create_ref_cache(submodule); 956 refs->next = submodule_ref_caches; 957 submodule_ref_caches = refs; 958return refs; 959} 960 961/* The length of a peeled reference line in packed-refs, including EOL: */ 962#define PEELED_LINE_LENGTH 42 963 964/* 965 * The packed-refs header line that we write out. Perhaps other 966 * traits will be added later. The trailing space is required. 967 */ 968static const char PACKED_REFS_HEADER[] = 969"# pack-refs with: peeled fully-peeled\n"; 970 971/* 972 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 973 * Return a pointer to the refname within the line (null-terminated), 974 * or NULL if there was a problem. 975 */ 976static const char*parse_ref_line(char*line,unsigned char*sha1) 977{ 978/* 979 * 42: the answer to everything. 980 * 981 * In this case, it happens to be the answer to 982 * 40 (length of sha1 hex representation) 983 * +1 (space in between hex and name) 984 * +1 (newline at the end of the line) 985 */ 986int len =strlen(line) -42; 987 988if(len <=0) 989return NULL; 990if(get_sha1_hex(line, sha1) <0) 991return NULL; 992if(!isspace(line[40])) 993return NULL; 994 line +=41; 995if(isspace(*line)) 996return NULL; 997if(line[len] !='\n') 998return NULL; 999 line[len] =0;10001001return line;1002}10031004/*1005 * Read f, which is a packed-refs file, into dir.1006 *1007 * A comment line of the form "# pack-refs with: " may contain zero or1008 * more traits. We interpret the traits as follows:1009 *1010 * No traits:1011 *1012 * Probably no references are peeled. But if the file contains a1013 * peeled value for a reference, we will use it.1014 *1015 * peeled:1016 *1017 * References under "refs/tags/", if they *can* be peeled, *are*1018 * peeled in this file. References outside of "refs/tags/" are1019 * probably not peeled even if they could have been, but if we find1020 * a peeled value for such a reference we will use it.1021 *1022 * fully-peeled:1023 *1024 * All references in the file that can be peeled are peeled.1025 * Inversely (and this is more important), any references in the1026 * file for which no peeled value is recorded is not peelable. This1027 * trait should typically be written alongside "peeled" for1028 * compatibility with older clients, but we do not require it1029 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1030 */1031static voidread_packed_refs(FILE*f,struct ref_dir *dir)1032{1033struct ref_entry *last = NULL;1034struct strbuf line = STRBUF_INIT;1035enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10361037while(strbuf_getwholeline(&line, f,'\n') != EOF) {1038unsigned char sha1[20];1039const char*refname;1040static const char header[] ="# pack-refs with:";10411042if(!strncmp(line.buf, header,sizeof(header)-1)) {1043const char*traits = line.buf +sizeof(header) -1;1044if(strstr(traits," fully-peeled "))1045 peeled = PEELED_FULLY;1046else if(strstr(traits," peeled "))1047 peeled = PEELED_TAGS;1048/* perhaps other traits later as well */1049continue;1050}10511052 refname =parse_ref_line(line.buf, sha1);1053if(refname) {1054 last =create_ref_entry(refname, sha1, REF_ISPACKED,1);1055if(peeled == PEELED_FULLY ||1056(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1057 last->flag |= REF_KNOWS_PEELED;1058add_ref(dir, last);1059continue;1060}1061if(last &&1062 line.buf[0] =='^'&&1063 line.len == PEELED_LINE_LENGTH &&1064 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1065!get_sha1_hex(line.buf +1, sha1)) {1066hashcpy(last->u.value.peeled, sha1);1067/*1068 * Regardless of what the file header said,1069 * we definitely know the value of *this*1070 * reference:1071 */1072 last->flag |= REF_KNOWS_PEELED;1073}1074}10751076strbuf_release(&line);1077}10781079/*1080 * Get the packed_ref_cache for the specified ref_cache, creating it1081 * if necessary.1082 */1083static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1084{1085const char*packed_refs_file;10861087if(*refs->name)1088 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1089else1090 packed_refs_file =git_path("packed-refs");10911092if(refs->packed &&1093!stat_validity_check(&refs->packed->validity, packed_refs_file))1094clear_packed_ref_cache(refs);10951096if(!refs->packed) {1097FILE*f;10981099 refs->packed =xcalloc(1,sizeof(*refs->packed));1100acquire_packed_ref_cache(refs->packed);1101 refs->packed->root =create_dir_entry(refs,"",0,0);1102 f =fopen(packed_refs_file,"r");1103if(f) {1104stat_validity_update(&refs->packed->validity,fileno(f));1105read_packed_refs(f,get_ref_dir(refs->packed->root));1106fclose(f);1107}1108}1109return refs->packed;1110}11111112static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1113{1114returnget_ref_dir(packed_ref_cache->root);1115}11161117static struct ref_dir *get_packed_refs(struct ref_cache *refs)1118{1119returnget_packed_ref_dir(get_packed_ref_cache(refs));1120}11211122voidadd_packed_ref(const char*refname,const unsigned char*sha1)1123{1124struct packed_ref_cache *packed_ref_cache =1125get_packed_ref_cache(&ref_cache);11261127if(!packed_ref_cache->lock)1128die("internal error: packed refs not locked");1129add_ref(get_packed_ref_dir(packed_ref_cache),1130create_ref_entry(refname, sha1, REF_ISPACKED,1));1131}11321133/*1134 * Read the loose references from the namespace dirname into dir1135 * (without recursing). dirname must end with '/'. dir must be the1136 * directory entry corresponding to dirname.1137 */1138static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1139{1140struct ref_cache *refs = dir->ref_cache;1141DIR*d;1142const char*path;1143struct dirent *de;1144int dirnamelen =strlen(dirname);1145struct strbuf refname;11461147if(*refs->name)1148 path =git_path_submodule(refs->name,"%s", dirname);1149else1150 path =git_path("%s", dirname);11511152 d =opendir(path);1153if(!d)1154return;11551156strbuf_init(&refname, dirnamelen +257);1157strbuf_add(&refname, dirname, dirnamelen);11581159while((de =readdir(d)) != NULL) {1160unsigned char sha1[20];1161struct stat st;1162int flag;1163const char*refdir;11641165if(de->d_name[0] =='.')1166continue;1167if(ends_with(de->d_name,".lock"))1168continue;1169strbuf_addstr(&refname, de->d_name);1170 refdir = *refs->name1171?git_path_submodule(refs->name,"%s", refname.buf)1172:git_path("%s", refname.buf);1173if(stat(refdir, &st) <0) {1174;/* silently ignore */1175}else if(S_ISDIR(st.st_mode)) {1176strbuf_addch(&refname,'/');1177add_entry_to_dir(dir,1178create_dir_entry(refs, refname.buf,1179 refname.len,1));1180}else{1181if(*refs->name) {1182hashclr(sha1);1183 flag =0;1184if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1185hashclr(sha1);1186 flag |= REF_ISBROKEN;1187}1188}else if(read_ref_full(refname.buf, sha1,1, &flag)) {1189hashclr(sha1);1190 flag |= REF_ISBROKEN;1191}1192add_entry_to_dir(dir,1193create_ref_entry(refname.buf, sha1, flag,1));1194}1195strbuf_setlen(&refname, dirnamelen);1196}1197strbuf_release(&refname);1198closedir(d);1199}12001201static struct ref_dir *get_loose_refs(struct ref_cache *refs)1202{1203if(!refs->loose) {1204/*1205 * Mark the top-level directory complete because we1206 * are about to read the only subdirectory that can1207 * hold references:1208 */1209 refs->loose =create_dir_entry(refs,"",0,0);1210/*1211 * Create an incomplete entry for "refs/":1212 */1213add_entry_to_dir(get_ref_dir(refs->loose),1214create_dir_entry(refs,"refs/",5,1));1215}1216returnget_ref_dir(refs->loose);1217}12181219/* We allow "recursive" symbolic refs. Only within reason, though */1220#define MAXDEPTH 51221#define MAXREFLEN (1024)12221223/*1224 * Called by resolve_gitlink_ref_recursive() after it failed to read1225 * from the loose refs in ref_cache refs. Find <refname> in the1226 * packed-refs file for the submodule.1227 */1228static intresolve_gitlink_packed_ref(struct ref_cache *refs,1229const char*refname,unsigned char*sha1)1230{1231struct ref_entry *ref;1232struct ref_dir *dir =get_packed_refs(refs);12331234 ref =find_ref(dir, refname);1235if(ref == NULL)1236return-1;12371238hashcpy(sha1, ref->u.value.sha1);1239return0;1240}12411242static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1243const char*refname,unsigned char*sha1,1244int recursion)1245{1246int fd, len;1247char buffer[128], *p;1248char*path;12491250if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1251return-1;1252 path = *refs->name1253?git_path_submodule(refs->name,"%s", refname)1254:git_path("%s", refname);1255 fd =open(path, O_RDONLY);1256if(fd <0)1257returnresolve_gitlink_packed_ref(refs, refname, sha1);12581259 len =read(fd, buffer,sizeof(buffer)-1);1260close(fd);1261if(len <0)1262return-1;1263while(len &&isspace(buffer[len-1]))1264 len--;1265 buffer[len] =0;12661267/* Was it a detached head or an old-fashioned symlink? */1268if(!get_sha1_hex(buffer, sha1))1269return0;12701271/* Symref? */1272if(strncmp(buffer,"ref:",4))1273return-1;1274 p = buffer +4;1275while(isspace(*p))1276 p++;12771278returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1279}12801281intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1282{1283int len =strlen(path), retval;1284char*submodule;1285struct ref_cache *refs;12861287while(len && path[len-1] =='/')1288 len--;1289if(!len)1290return-1;1291 submodule =xstrndup(path, len);1292 refs =get_ref_cache(submodule);1293free(submodule);12941295 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1296return retval;1297}12981299/*1300 * Return the ref_entry for the given refname from the packed1301 * references. If it does not exist, return NULL.1302 */1303static struct ref_entry *get_packed_ref(const char*refname)1304{1305returnfind_ref(get_packed_refs(&ref_cache), refname);1306}13071308/*1309 * A loose ref file doesn't exist; check for a packed ref. The1310 * options are forwarded from resolve_safe_unsafe().1311 */1312static const char*handle_missing_loose_ref(const char*refname,1313unsigned char*sha1,1314int reading,1315int*flag)1316{1317struct ref_entry *entry;13181319/*1320 * The loose reference file does not exist; check for a packed1321 * reference.1322 */1323 entry =get_packed_ref(refname);1324if(entry) {1325hashcpy(sha1, entry->u.value.sha1);1326if(flag)1327*flag |= REF_ISPACKED;1328return refname;1329}1330/* The reference is not a packed reference, either. */1331if(reading) {1332return NULL;1333}else{1334hashclr(sha1);1335return refname;1336}1337}13381339/* This function needs to return a meaningful errno on failure */1340const char*resolve_ref_unsafe(const char*refname,unsigned char*sha1,int reading,int*flag)1341{1342int depth = MAXDEPTH;1343 ssize_t len;1344char buffer[256];1345static char refname_buffer[256];13461347if(flag)1348*flag =0;13491350if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1351 errno = EINVAL;1352return NULL;1353}13541355for(;;) {1356char path[PATH_MAX];1357struct stat st;1358char*buf;1359int fd;13601361if(--depth <0) {1362 errno = ELOOP;1363return NULL;1364}13651366git_snpath(path,sizeof(path),"%s", refname);13671368/*1369 * We might have to loop back here to avoid a race1370 * condition: first we lstat() the file, then we try1371 * to read it as a link or as a file. But if somebody1372 * changes the type of the file (file <-> directory1373 * <-> symlink) between the lstat() and reading, then1374 * we don't want to report that as an error but rather1375 * try again starting with the lstat().1376 */1377 stat_ref:1378if(lstat(path, &st) <0) {1379if(errno == ENOENT)1380returnhandle_missing_loose_ref(refname, sha1,1381 reading, flag);1382else1383return NULL;1384}13851386/* Follow "normalized" - ie "refs/.." symlinks by hand */1387if(S_ISLNK(st.st_mode)) {1388 len =readlink(path, buffer,sizeof(buffer)-1);1389if(len <0) {1390if(errno == ENOENT || errno == EINVAL)1391/* inconsistent with lstat; retry */1392goto stat_ref;1393else1394return NULL;1395}1396 buffer[len] =0;1397if(starts_with(buffer,"refs/") &&1398!check_refname_format(buffer,0)) {1399strcpy(refname_buffer, buffer);1400 refname = refname_buffer;1401if(flag)1402*flag |= REF_ISSYMREF;1403continue;1404}1405}14061407/* Is it a directory? */1408if(S_ISDIR(st.st_mode)) {1409 errno = EISDIR;1410return NULL;1411}14121413/*1414 * Anything else, just open it and try to use it as1415 * a ref1416 */1417 fd =open(path, O_RDONLY);1418if(fd <0) {1419if(errno == ENOENT)1420/* inconsistent with lstat; retry */1421goto stat_ref;1422else1423return NULL;1424}1425 len =read_in_full(fd, buffer,sizeof(buffer)-1);1426if(len <0) {1427int save_errno = errno;1428close(fd);1429 errno = save_errno;1430return NULL;1431}1432close(fd);1433while(len &&isspace(buffer[len-1]))1434 len--;1435 buffer[len] ='\0';14361437/*1438 * Is it a symbolic ref?1439 */1440if(!starts_with(buffer,"ref:")) {1441/*1442 * Please note that FETCH_HEAD has a second1443 * line containing other data.1444 */1445if(get_sha1_hex(buffer, sha1) ||1446(buffer[40] !='\0'&& !isspace(buffer[40]))) {1447if(flag)1448*flag |= REF_ISBROKEN;1449 errno = EINVAL;1450return NULL;1451}1452return refname;1453}1454if(flag)1455*flag |= REF_ISSYMREF;1456 buf = buffer +4;1457while(isspace(*buf))1458 buf++;1459if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1460if(flag)1461*flag |= REF_ISBROKEN;1462 errno = EINVAL;1463return NULL;1464}1465 refname =strcpy(refname_buffer, buf);1466}1467}14681469char*resolve_refdup(const char*ref,unsigned char*sha1,int reading,int*flag)1470{1471const char*ret =resolve_ref_unsafe(ref, sha1, reading, flag);1472return ret ?xstrdup(ret) : NULL;1473}14741475/* The argument to filter_refs */1476struct ref_filter {1477const char*pattern;1478 each_ref_fn *fn;1479void*cb_data;1480};14811482intread_ref_full(const char*refname,unsigned char*sha1,int reading,int*flags)1483{1484if(resolve_ref_unsafe(refname, sha1, reading, flags))1485return0;1486return-1;1487}14881489intread_ref(const char*refname,unsigned char*sha1)1490{1491returnread_ref_full(refname, sha1,1, NULL);1492}14931494intref_exists(const char*refname)1495{1496unsigned char sha1[20];1497return!!resolve_ref_unsafe(refname, sha1,1, NULL);1498}14991500static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1501void*data)1502{1503struct ref_filter *filter = (struct ref_filter *)data;1504if(wildmatch(filter->pattern, refname,0, NULL))1505return0;1506return filter->fn(refname, sha1, flags, filter->cb_data);1507}15081509enum peel_status {1510/* object was peeled successfully: */1511 PEEL_PEELED =0,15121513/*1514 * object cannot be peeled because the named object (or an1515 * object referred to by a tag in the peel chain), does not1516 * exist.1517 */1518 PEEL_INVALID = -1,15191520/* object cannot be peeled because it is not a tag: */1521 PEEL_NON_TAG = -2,15221523/* ref_entry contains no peeled value because it is a symref: */1524 PEEL_IS_SYMREF = -3,15251526/*1527 * ref_entry cannot be peeled because it is broken (i.e., the1528 * symbolic reference cannot even be resolved to an object1529 * name):1530 */1531 PEEL_BROKEN = -41532};15331534/*1535 * Peel the named object; i.e., if the object is a tag, resolve the1536 * tag recursively until a non-tag is found. If successful, store the1537 * result to sha1 and return PEEL_PEELED. If the object is not a tag1538 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1539 * and leave sha1 unchanged.1540 */1541static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1542{1543struct object *o =lookup_unknown_object(name);15441545if(o->type == OBJ_NONE) {1546int type =sha1_object_info(name, NULL);1547if(type <0|| !object_as_type(o, type,0))1548return PEEL_INVALID;1549}15501551if(o->type != OBJ_TAG)1552return PEEL_NON_TAG;15531554 o =deref_tag_noverify(o);1555if(!o)1556return PEEL_INVALID;15571558hashcpy(sha1, o->sha1);1559return PEEL_PEELED;1560}15611562/*1563 * Peel the entry (if possible) and return its new peel_status. If1564 * repeel is true, re-peel the entry even if there is an old peeled1565 * value that is already stored in it.1566 *1567 * It is OK to call this function with a packed reference entry that1568 * might be stale and might even refer to an object that has since1569 * been garbage-collected. In such a case, if the entry has1570 * REF_KNOWS_PEELED then leave the status unchanged and return1571 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1572 */1573static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1574{1575enum peel_status status;15761577if(entry->flag & REF_KNOWS_PEELED) {1578if(repeel) {1579 entry->flag &= ~REF_KNOWS_PEELED;1580hashclr(entry->u.value.peeled);1581}else{1582returnis_null_sha1(entry->u.value.peeled) ?1583 PEEL_NON_TAG : PEEL_PEELED;1584}1585}1586if(entry->flag & REF_ISBROKEN)1587return PEEL_BROKEN;1588if(entry->flag & REF_ISSYMREF)1589return PEEL_IS_SYMREF;15901591 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1592if(status == PEEL_PEELED || status == PEEL_NON_TAG)1593 entry->flag |= REF_KNOWS_PEELED;1594return status;1595}15961597intpeel_ref(const char*refname,unsigned char*sha1)1598{1599int flag;1600unsigned char base[20];16011602if(current_ref && (current_ref->name == refname1603|| !strcmp(current_ref->name, refname))) {1604if(peel_entry(current_ref,0))1605return-1;1606hashcpy(sha1, current_ref->u.value.peeled);1607return0;1608}16091610if(read_ref_full(refname, base,1, &flag))1611return-1;16121613/*1614 * If the reference is packed, read its ref_entry from the1615 * cache in the hope that we already know its peeled value.1616 * We only try this optimization on packed references because1617 * (a) forcing the filling of the loose reference cache could1618 * be expensive and (b) loose references anyway usually do not1619 * have REF_KNOWS_PEELED.1620 */1621if(flag & REF_ISPACKED) {1622struct ref_entry *r =get_packed_ref(refname);1623if(r) {1624if(peel_entry(r,0))1625return-1;1626hashcpy(sha1, r->u.value.peeled);1627return0;1628}1629}16301631returnpeel_object(base, sha1);1632}16331634struct warn_if_dangling_data {1635FILE*fp;1636const char*refname;1637const struct string_list *refnames;1638const char*msg_fmt;1639};16401641static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1642int flags,void*cb_data)1643{1644struct warn_if_dangling_data *d = cb_data;1645const char*resolves_to;1646unsigned char junk[20];16471648if(!(flags & REF_ISSYMREF))1649return0;16501651 resolves_to =resolve_ref_unsafe(refname, junk,0, NULL);1652if(!resolves_to1653|| (d->refname1654?strcmp(resolves_to, d->refname)1655: !string_list_has_string(d->refnames, resolves_to))) {1656return0;1657}16581659fprintf(d->fp, d->msg_fmt, refname);1660fputc('\n', d->fp);1661return0;1662}16631664voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1665{1666struct warn_if_dangling_data data;16671668 data.fp = fp;1669 data.refname = refname;1670 data.refnames = NULL;1671 data.msg_fmt = msg_fmt;1672for_each_rawref(warn_if_dangling_symref, &data);1673}16741675voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1676{1677struct warn_if_dangling_data data;16781679 data.fp = fp;1680 data.refname = NULL;1681 data.refnames = refnames;1682 data.msg_fmt = msg_fmt;1683for_each_rawref(warn_if_dangling_symref, &data);1684}16851686/*1687 * Call fn for each reference in the specified ref_cache, omitting1688 * references not in the containing_dir of base. fn is called for all1689 * references, including broken ones. If fn ever returns a non-zero1690 * value, stop the iteration and return that value; otherwise, return1691 * 0.1692 */1693static intdo_for_each_entry(struct ref_cache *refs,const char*base,1694 each_ref_entry_fn fn,void*cb_data)1695{1696struct packed_ref_cache *packed_ref_cache;1697struct ref_dir *loose_dir;1698struct ref_dir *packed_dir;1699int retval =0;17001701/*1702 * We must make sure that all loose refs are read before accessing the1703 * packed-refs file; this avoids a race condition in which loose refs1704 * are migrated to the packed-refs file by a simultaneous process, but1705 * our in-memory view is from before the migration. get_packed_ref_cache()1706 * takes care of making sure our view is up to date with what is on1707 * disk.1708 */1709 loose_dir =get_loose_refs(refs);1710if(base && *base) {1711 loose_dir =find_containing_dir(loose_dir, base,0);1712}1713if(loose_dir)1714prime_ref_dir(loose_dir);17151716 packed_ref_cache =get_packed_ref_cache(refs);1717acquire_packed_ref_cache(packed_ref_cache);1718 packed_dir =get_packed_ref_dir(packed_ref_cache);1719if(base && *base) {1720 packed_dir =find_containing_dir(packed_dir, base,0);1721}17221723if(packed_dir && loose_dir) {1724sort_ref_dir(packed_dir);1725sort_ref_dir(loose_dir);1726 retval =do_for_each_entry_in_dirs(1727 packed_dir, loose_dir, fn, cb_data);1728}else if(packed_dir) {1729sort_ref_dir(packed_dir);1730 retval =do_for_each_entry_in_dir(1731 packed_dir,0, fn, cb_data);1732}else if(loose_dir) {1733sort_ref_dir(loose_dir);1734 retval =do_for_each_entry_in_dir(1735 loose_dir,0, fn, cb_data);1736}17371738release_packed_ref_cache(packed_ref_cache);1739return retval;1740}17411742/*1743 * Call fn for each reference in the specified ref_cache for which the1744 * refname begins with base. If trim is non-zero, then trim that many1745 * characters off the beginning of each refname before passing the1746 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1747 * broken references in the iteration. If fn ever returns a non-zero1748 * value, stop the iteration and return that value; otherwise, return1749 * 0.1750 */1751static intdo_for_each_ref(struct ref_cache *refs,const char*base,1752 each_ref_fn fn,int trim,int flags,void*cb_data)1753{1754struct ref_entry_cb data;1755 data.base = base;1756 data.trim = trim;1757 data.flags = flags;1758 data.fn = fn;1759 data.cb_data = cb_data;17601761returndo_for_each_entry(refs, base, do_one_ref, &data);1762}17631764static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1765{1766unsigned char sha1[20];1767int flag;17681769if(submodule) {1770if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1771returnfn("HEAD", sha1,0, cb_data);17721773return0;1774}17751776if(!read_ref_full("HEAD", sha1,1, &flag))1777returnfn("HEAD", sha1, flag, cb_data);17781779return0;1780}17811782inthead_ref(each_ref_fn fn,void*cb_data)1783{1784returndo_head_ref(NULL, fn, cb_data);1785}17861787inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1788{1789returndo_head_ref(submodule, fn, cb_data);1790}17911792intfor_each_ref(each_ref_fn fn,void*cb_data)1793{1794returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1795}17961797intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1798{1799returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1800}18011802intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1803{1804returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1805}18061807intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1808 each_ref_fn fn,void*cb_data)1809{1810returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1811}18121813intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1814{1815returnfor_each_ref_in("refs/tags/", fn, cb_data);1816}18171818intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1819{1820returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1821}18221823intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1824{1825returnfor_each_ref_in("refs/heads/", fn, cb_data);1826}18271828intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1829{1830returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1831}18321833intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1834{1835returnfor_each_ref_in("refs/remotes/", fn, cb_data);1836}18371838intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1839{1840returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);1841}18421843intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1844{1845returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);1846}18471848inthead_ref_namespaced(each_ref_fn fn,void*cb_data)1849{1850struct strbuf buf = STRBUF_INIT;1851int ret =0;1852unsigned char sha1[20];1853int flag;18541855strbuf_addf(&buf,"%sHEAD",get_git_namespace());1856if(!read_ref_full(buf.buf, sha1,1, &flag))1857 ret =fn(buf.buf, sha1, flag, cb_data);1858strbuf_release(&buf);18591860return ret;1861}18621863intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1864{1865struct strbuf buf = STRBUF_INIT;1866int ret;1867strbuf_addf(&buf,"%srefs/",get_git_namespace());1868 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);1869strbuf_release(&buf);1870return ret;1871}18721873intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,1874const char*prefix,void*cb_data)1875{1876struct strbuf real_pattern = STRBUF_INIT;1877struct ref_filter filter;1878int ret;18791880if(!prefix && !starts_with(pattern,"refs/"))1881strbuf_addstr(&real_pattern,"refs/");1882else if(prefix)1883strbuf_addstr(&real_pattern, prefix);1884strbuf_addstr(&real_pattern, pattern);18851886if(!has_glob_specials(pattern)) {1887/* Append implied '/' '*' if not present. */1888if(real_pattern.buf[real_pattern.len -1] !='/')1889strbuf_addch(&real_pattern,'/');1890/* No need to check for '*', there is none. */1891strbuf_addch(&real_pattern,'*');1892}18931894 filter.pattern = real_pattern.buf;1895 filter.fn = fn;1896 filter.cb_data = cb_data;1897 ret =for_each_ref(filter_refs, &filter);18981899strbuf_release(&real_pattern);1900return ret;1901}19021903intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)1904{1905returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);1906}19071908intfor_each_rawref(each_ref_fn fn,void*cb_data)1909{1910returndo_for_each_ref(&ref_cache,"", fn,0,1911 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1912}19131914const char*prettify_refname(const char*name)1915{1916return name + (1917starts_with(name,"refs/heads/") ?11:1918starts_with(name,"refs/tags/") ?10:1919starts_with(name,"refs/remotes/") ?13:19200);1921}19221923static const char*ref_rev_parse_rules[] = {1924"%.*s",1925"refs/%.*s",1926"refs/tags/%.*s",1927"refs/heads/%.*s",1928"refs/remotes/%.*s",1929"refs/remotes/%.*s/HEAD",1930 NULL1931};19321933intrefname_match(const char*abbrev_name,const char*full_name)1934{1935const char**p;1936const int abbrev_name_len =strlen(abbrev_name);19371938for(p = ref_rev_parse_rules; *p; p++) {1939if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {1940return1;1941}1942}19431944return0;1945}19461947/* This function should make sure errno is meaningful on error */1948static struct ref_lock *verify_lock(struct ref_lock *lock,1949const unsigned char*old_sha1,int mustexist)1950{1951if(read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {1952int save_errno = errno;1953error("Can't verify ref%s", lock->ref_name);1954unlock_ref(lock);1955 errno = save_errno;1956return NULL;1957}1958if(hashcmp(lock->old_sha1, old_sha1)) {1959error("Ref%sis at%sbut expected%s", lock->ref_name,1960sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));1961unlock_ref(lock);1962 errno = EBUSY;1963return NULL;1964}1965return lock;1966}19671968static intremove_empty_directories(const char*file)1969{1970/* we want to create a file but there is a directory there;1971 * if that is an empty directory (or a directory that contains1972 * only empty directories), remove them.1973 */1974struct strbuf path;1975int result, save_errno;19761977strbuf_init(&path,20);1978strbuf_addstr(&path, file);19791980 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);1981 save_errno = errno;19821983strbuf_release(&path);1984 errno = save_errno;19851986return result;1987}19881989/*1990 * *string and *len will only be substituted, and *string returned (for1991 * later free()ing) if the string passed in is a magic short-hand form1992 * to name a branch.1993 */1994static char*substitute_branch_name(const char**string,int*len)1995{1996struct strbuf buf = STRBUF_INIT;1997int ret =interpret_branch_name(*string, *len, &buf);19981999if(ret == *len) {2000size_t size;2001*string =strbuf_detach(&buf, &size);2002*len = size;2003return(char*)*string;2004}20052006return NULL;2007}20082009intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2010{2011char*last_branch =substitute_branch_name(&str, &len);2012const char**p, *r;2013int refs_found =0;20142015*ref = NULL;2016for(p = ref_rev_parse_rules; *p; p++) {2017char fullref[PATH_MAX];2018unsigned char sha1_from_ref[20];2019unsigned char*this_result;2020int flag;20212022 this_result = refs_found ? sha1_from_ref : sha1;2023mksnpath(fullref,sizeof(fullref), *p, len, str);2024 r =resolve_ref_unsafe(fullref, this_result,1, &flag);2025if(r) {2026if(!refs_found++)2027*ref =xstrdup(r);2028if(!warn_ambiguous_refs)2029break;2030}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2031warning("ignoring dangling symref%s.", fullref);2032}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2033warning("ignoring broken ref%s.", fullref);2034}2035}2036free(last_branch);2037return refs_found;2038}20392040intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2041{2042char*last_branch =substitute_branch_name(&str, &len);2043const char**p;2044int logs_found =0;20452046*log = NULL;2047for(p = ref_rev_parse_rules; *p; p++) {2048unsigned char hash[20];2049char path[PATH_MAX];2050const char*ref, *it;20512052mksnpath(path,sizeof(path), *p, len, str);2053 ref =resolve_ref_unsafe(path, hash,1, NULL);2054if(!ref)2055continue;2056if(reflog_exists(path))2057 it = path;2058else if(strcmp(ref, path) &&reflog_exists(ref))2059 it = ref;2060else2061continue;2062if(!logs_found++) {2063*log =xstrdup(it);2064hashcpy(sha1, hash);2065}2066if(!warn_ambiguous_refs)2067break;2068}2069free(last_branch);2070return logs_found;2071}20722073/* This function should make sure errno is meaningful on error */2074static struct ref_lock *lock_ref_sha1_basic(const char*refname,2075const unsigned char*old_sha1,2076int flags,int*type_p)2077{2078char*ref_file;2079const char*orig_refname = refname;2080struct ref_lock *lock;2081int last_errno =0;2082int type, lflags;2083int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2084int missing =0;2085int attempts_remaining =3;20862087 lock =xcalloc(1,sizeof(struct ref_lock));2088 lock->lock_fd = -1;20892090 refname =resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);2091if(!refname && errno == EISDIR) {2092/* we are trying to lock foo but we used to2093 * have foo/bar which now does not exist;2094 * it is normal for the empty directory 'foo'2095 * to remain.2096 */2097 ref_file =git_path("%s", orig_refname);2098if(remove_empty_directories(ref_file)) {2099 last_errno = errno;2100error("there are still refs under '%s'", orig_refname);2101goto error_return;2102}2103 refname =resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);2104}2105if(type_p)2106*type_p = type;2107if(!refname) {2108 last_errno = errno;2109error("unable to resolve reference%s:%s",2110 orig_refname,strerror(errno));2111goto error_return;2112}2113 missing =is_null_sha1(lock->old_sha1);2114/* When the ref did not exist and we are creating it,2115 * make sure there is no existing ref that is packed2116 * whose name begins with our refname, nor a ref whose2117 * name is a proper prefix of our refname.2118 */2119if(missing &&2120!is_refname_available(refname, NULL,get_packed_refs(&ref_cache))) {2121 last_errno = ENOTDIR;2122goto error_return;2123}21242125 lock->lk =xcalloc(1,sizeof(struct lock_file));21262127 lflags =0;2128if(flags & REF_NODEREF) {2129 refname = orig_refname;2130 lflags |= LOCK_NODEREF;2131}2132 lock->ref_name =xstrdup(refname);2133 lock->orig_ref_name =xstrdup(orig_refname);2134 ref_file =git_path("%s", refname);2135if(missing)2136 lock->force_write =1;2137if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2138 lock->force_write =1;21392140 retry:2141switch(safe_create_leading_directories(ref_file)) {2142case SCLD_OK:2143break;/* success */2144case SCLD_VANISHED:2145if(--attempts_remaining >0)2146goto retry;2147/* fall through */2148default:2149 last_errno = errno;2150error("unable to create directory for%s", ref_file);2151goto error_return;2152}21532154 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2155if(lock->lock_fd <0) {2156if(errno == ENOENT && --attempts_remaining >0)2157/*2158 * Maybe somebody just deleted one of the2159 * directories leading to ref_file. Try2160 * again:2161 */2162goto retry;2163else2164unable_to_lock_index_die(ref_file, errno);2165}2166return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;21672168 error_return:2169unlock_ref(lock);2170 errno = last_errno;2171return NULL;2172}21732174struct ref_lock *lock_ref_sha1(const char*refname,const unsigned char*old_sha1)2175{2176char refpath[PATH_MAX];2177if(check_refname_format(refname,0))2178return NULL;2179strcpy(refpath,mkpath("refs/%s", refname));2180returnlock_ref_sha1_basic(refpath, old_sha1,0, NULL);2181}21822183struct ref_lock *lock_any_ref_for_update(const char*refname,2184const unsigned char*old_sha1,2185int flags,int*type_p)2186{2187if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))2188return NULL;2189returnlock_ref_sha1_basic(refname, old_sha1, flags, type_p);2190}21912192/*2193 * Write an entry to the packed-refs file for the specified refname.2194 * If peeled is non-NULL, write it as the entry's peeled value.2195 */2196static voidwrite_packed_entry(int fd,char*refname,unsigned char*sha1,2197unsigned char*peeled)2198{2199char line[PATH_MAX +100];2200int len;22012202 len =snprintf(line,sizeof(line),"%s %s\n",2203sha1_to_hex(sha1), refname);2204/* this should not happen but just being defensive */2205if(len >sizeof(line))2206die("too long a refname '%s'", refname);2207write_or_die(fd, line, len);22082209if(peeled) {2210if(snprintf(line,sizeof(line),"^%s\n",2211sha1_to_hex(peeled)) != PEELED_LINE_LENGTH)2212die("internal error");2213write_or_die(fd, line, PEELED_LINE_LENGTH);2214}2215}22162217/*2218 * An each_ref_entry_fn that writes the entry to a packed-refs file.2219 */2220static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2221{2222int*fd = cb_data;2223enum peel_status peel_status =peel_entry(entry,0);22242225if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2226error("internal error:%sis not a valid packed reference!",2227 entry->name);2228write_packed_entry(*fd, entry->name, entry->u.value.sha1,2229 peel_status == PEEL_PEELED ?2230 entry->u.value.peeled : NULL);2231return0;2232}22332234/* This should return a meaningful errno on failure */2235intlock_packed_refs(int flags)2236{2237struct packed_ref_cache *packed_ref_cache;22382239if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2240return-1;2241/*2242 * Get the current packed-refs while holding the lock. If the2243 * packed-refs file has been modified since we last read it,2244 * this will automatically invalidate the cache and re-read2245 * the packed-refs file.2246 */2247 packed_ref_cache =get_packed_ref_cache(&ref_cache);2248 packed_ref_cache->lock = &packlock;2249/* Increment the reference count to prevent it from being freed: */2250acquire_packed_ref_cache(packed_ref_cache);2251return0;2252}22532254/*2255 * Commit the packed refs changes.2256 * On error we must make sure that errno contains a meaningful value.2257 */2258intcommit_packed_refs(void)2259{2260struct packed_ref_cache *packed_ref_cache =2261get_packed_ref_cache(&ref_cache);2262int error =0;2263int save_errno =0;22642265if(!packed_ref_cache->lock)2266die("internal error: packed-refs not locked");2267write_or_die(packed_ref_cache->lock->fd,2268 PACKED_REFS_HEADER,strlen(PACKED_REFS_HEADER));22692270do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),22710, write_packed_entry_fn,2272&packed_ref_cache->lock->fd);2273if(commit_lock_file(packed_ref_cache->lock)) {2274 save_errno = errno;2275 error = -1;2276}2277 packed_ref_cache->lock = NULL;2278release_packed_ref_cache(packed_ref_cache);2279 errno = save_errno;2280return error;2281}22822283voidrollback_packed_refs(void)2284{2285struct packed_ref_cache *packed_ref_cache =2286get_packed_ref_cache(&ref_cache);22872288if(!packed_ref_cache->lock)2289die("internal error: packed-refs not locked");2290rollback_lock_file(packed_ref_cache->lock);2291 packed_ref_cache->lock = NULL;2292release_packed_ref_cache(packed_ref_cache);2293clear_packed_ref_cache(&ref_cache);2294}22952296struct ref_to_prune {2297struct ref_to_prune *next;2298unsigned char sha1[20];2299char name[FLEX_ARRAY];2300};23012302struct pack_refs_cb_data {2303unsigned int flags;2304struct ref_dir *packed_refs;2305struct ref_to_prune *ref_to_prune;2306};23072308/*2309 * An each_ref_entry_fn that is run over loose references only. If2310 * the loose reference can be packed, add an entry in the packed ref2311 * cache. If the reference should be pruned, also add it to2312 * ref_to_prune in the pack_refs_cb_data.2313 */2314static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2315{2316struct pack_refs_cb_data *cb = cb_data;2317enum peel_status peel_status;2318struct ref_entry *packed_entry;2319int is_tag_ref =starts_with(entry->name,"refs/tags/");23202321/* ALWAYS pack tags */2322if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2323return0;23242325/* Do not pack symbolic or broken refs: */2326if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2327return0;23282329/* Add a packed ref cache entry equivalent to the loose entry. */2330 peel_status =peel_entry(entry,1);2331if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2332die("internal error peeling reference%s(%s)",2333 entry->name,sha1_to_hex(entry->u.value.sha1));2334 packed_entry =find_ref(cb->packed_refs, entry->name);2335if(packed_entry) {2336/* Overwrite existing packed entry with info from loose entry */2337 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2338hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2339}else{2340 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2341 REF_ISPACKED | REF_KNOWS_PEELED,0);2342add_ref(cb->packed_refs, packed_entry);2343}2344hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);23452346/* Schedule the loose reference for pruning if requested. */2347if((cb->flags & PACK_REFS_PRUNE)) {2348int namelen =strlen(entry->name) +1;2349struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2350hashcpy(n->sha1, entry->u.value.sha1);2351strcpy(n->name, entry->name);2352 n->next = cb->ref_to_prune;2353 cb->ref_to_prune = n;2354}2355return0;2356}23572358/*2359 * Remove empty parents, but spare refs/ and immediate subdirs.2360 * Note: munges *name.2361 */2362static voidtry_remove_empty_parents(char*name)2363{2364char*p, *q;2365int i;2366 p = name;2367for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2368while(*p && *p !='/')2369 p++;2370/* tolerate duplicate slashes; see check_refname_format() */2371while(*p =='/')2372 p++;2373}2374for(q = p; *q; q++)2375;2376while(1) {2377while(q > p && *q !='/')2378 q--;2379while(q > p && *(q-1) =='/')2380 q--;2381if(q == p)2382break;2383*q ='\0';2384if(rmdir(git_path("%s", name)))2385break;2386}2387}23882389/* make sure nobody touched the ref, and unlink */2390static voidprune_ref(struct ref_to_prune *r)2391{2392struct ref_lock *lock =lock_any_ref_for_update(r->name, r->sha1,23930, NULL);23942395if(lock) {2396unlink_or_warn(git_path("%s", r->name));2397unlock_ref(lock);2398try_remove_empty_parents(r->name);2399}2400}24012402static voidprune_refs(struct ref_to_prune *r)2403{2404while(r) {2405prune_ref(r);2406 r = r->next;2407}2408}24092410intpack_refs(unsigned int flags)2411{2412struct pack_refs_cb_data cbdata;24132414memset(&cbdata,0,sizeof(cbdata));2415 cbdata.flags = flags;24162417lock_packed_refs(LOCK_DIE_ON_ERROR);2418 cbdata.packed_refs =get_packed_refs(&ref_cache);24192420do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2421 pack_if_possible_fn, &cbdata);24222423if(commit_packed_refs())2424die_errno("unable to overwrite old ref-pack file");24252426prune_refs(cbdata.ref_to_prune);2427return0;2428}24292430/*2431 * If entry is no longer needed in packed-refs, add it to the string2432 * list pointed to by cb_data. Reasons for deleting entries:2433 *2434 * - Entry is broken.2435 * - Entry is overridden by a loose ref.2436 * - Entry does not point at a valid object.2437 *2438 * In the first and third cases, also emit an error message because these2439 * are indications of repository corruption.2440 */2441static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2442{2443struct string_list *refs_to_delete = cb_data;24442445if(entry->flag & REF_ISBROKEN) {2446/* This shouldn't happen to packed refs. */2447error("%sis broken!", entry->name);2448string_list_append(refs_to_delete, entry->name);2449return0;2450}2451if(!has_sha1_file(entry->u.value.sha1)) {2452unsigned char sha1[20];2453int flags;24542455if(read_ref_full(entry->name, sha1,0, &flags))2456/* We should at least have found the packed ref. */2457die("Internal error");2458if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2459/*2460 * This packed reference is overridden by a2461 * loose reference, so it is OK that its value2462 * is no longer valid; for example, it might2463 * refer to an object that has been garbage2464 * collected. For this purpose we don't even2465 * care whether the loose reference itself is2466 * invalid, broken, symbolic, etc. Silently2467 * remove the packed reference.2468 */2469string_list_append(refs_to_delete, entry->name);2470return0;2471}2472/*2473 * There is no overriding loose reference, so the fact2474 * that this reference doesn't refer to a valid object2475 * indicates some kind of repository corruption.2476 * Report the problem, then omit the reference from2477 * the output.2478 */2479error("%sdoes not point to a valid object!", entry->name);2480string_list_append(refs_to_delete, entry->name);2481return0;2482}24832484return0;2485}24862487intrepack_without_refs(const char**refnames,int n,struct strbuf *err)2488{2489struct ref_dir *packed;2490struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2491struct string_list_item *ref_to_delete;2492int i, ret, removed =0;24932494/* Look for a packed ref */2495for(i =0; i < n; i++)2496if(get_packed_ref(refnames[i]))2497break;24982499/* Avoid locking if we have nothing to do */2500if(i == n)2501return0;/* no refname exists in packed refs */25022503if(lock_packed_refs(0)) {2504if(err) {2505unable_to_lock_message(git_path("packed-refs"), errno,2506 err);2507return-1;2508}2509unable_to_lock_error(git_path("packed-refs"), errno);2510returnerror("cannot delete '%s' from packed refs", refnames[i]);2511}2512 packed =get_packed_refs(&ref_cache);25132514/* Remove refnames from the cache */2515for(i =0; i < n; i++)2516if(remove_entry(packed, refnames[i]) != -1)2517 removed =1;2518if(!removed) {2519/*2520 * All packed entries disappeared while we were2521 * acquiring the lock.2522 */2523rollback_packed_refs();2524return0;2525}25262527/* Remove any other accumulated cruft */2528do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2529for_each_string_list_item(ref_to_delete, &refs_to_delete) {2530if(remove_entry(packed, ref_to_delete->string) == -1)2531die("internal error");2532}25332534/* Write what remains */2535 ret =commit_packed_refs();2536if(ret && err)2537strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2538strerror(errno));2539return ret;2540}25412542static intrepack_without_ref(const char*refname)2543{2544returnrepack_without_refs(&refname,1, NULL);2545}25462547static intdelete_ref_loose(struct ref_lock *lock,int flag)2548{2549if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2550/* loose */2551int err, i =strlen(lock->lk->filename) -5;/* .lock */25522553 lock->lk->filename[i] =0;2554 err =unlink_or_warn(lock->lk->filename);2555 lock->lk->filename[i] ='.';2556if(err && errno != ENOENT)2557return1;2558}2559return0;2560}25612562intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2563{2564struct ref_lock *lock;2565int ret =0, flag =0;25662567 lock =lock_ref_sha1_basic(refname, sha1, delopt, &flag);2568if(!lock)2569return1;2570 ret |=delete_ref_loose(lock, flag);25712572/* removing the loose one could have resurrected an earlier2573 * packed one. Also, if it was not loose we need to repack2574 * without it.2575 */2576 ret |=repack_without_ref(lock->ref_name);25772578unlink_or_warn(git_path("logs/%s", lock->ref_name));2579clear_loose_ref_cache(&ref_cache);2580unlock_ref(lock);2581return ret;2582}25832584/*2585 * People using contrib's git-new-workdir have .git/logs/refs ->2586 * /some/other/path/.git/logs/refs, and that may live on another device.2587 *2588 * IOW, to avoid cross device rename errors, the temporary renamed log must2589 * live into logs/refs.2590 */2591#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"25922593static intrename_tmp_log(const char*newrefname)2594{2595int attempts_remaining =4;25962597 retry:2598switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2599case SCLD_OK:2600break;/* success */2601case SCLD_VANISHED:2602if(--attempts_remaining >0)2603goto retry;2604/* fall through */2605default:2606error("unable to create directory for%s", newrefname);2607return-1;2608}26092610if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2611if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2612/*2613 * rename(a, b) when b is an existing2614 * directory ought to result in ISDIR, but2615 * Solaris 5.8 gives ENOTDIR. Sheesh.2616 */2617if(remove_empty_directories(git_path("logs/%s", newrefname))) {2618error("Directory not empty: logs/%s", newrefname);2619return-1;2620}2621goto retry;2622}else if(errno == ENOENT && --attempts_remaining >0) {2623/*2624 * Maybe another process just deleted one of2625 * the directories in the path to newrefname.2626 * Try again from the beginning.2627 */2628goto retry;2629}else{2630error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2631 newrefname,strerror(errno));2632return-1;2633}2634}2635return0;2636}26372638intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2639{2640unsigned char sha1[20], orig_sha1[20];2641int flag =0, logmoved =0;2642struct ref_lock *lock;2643struct stat loginfo;2644int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2645const char*symref = NULL;26462647if(log &&S_ISLNK(loginfo.st_mode))2648returnerror("reflog for%sis a symlink", oldrefname);26492650 symref =resolve_ref_unsafe(oldrefname, orig_sha1,1, &flag);2651if(flag & REF_ISSYMREF)2652returnerror("refname%sis a symbolic ref, renaming it is not supported",2653 oldrefname);2654if(!symref)2655returnerror("refname%snot found", oldrefname);26562657if(!is_refname_available(newrefname, oldrefname,get_packed_refs(&ref_cache)))2658return1;26592660if(!is_refname_available(newrefname, oldrefname,get_loose_refs(&ref_cache)))2661return1;26622663if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2664returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2665 oldrefname,strerror(errno));26662667if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2668error("unable to delete old%s", oldrefname);2669goto rollback;2670}26712672if(!read_ref_full(newrefname, sha1,1, &flag) &&2673delete_ref(newrefname, sha1, REF_NODEREF)) {2674if(errno==EISDIR) {2675if(remove_empty_directories(git_path("%s", newrefname))) {2676error("Directory not empty:%s", newrefname);2677goto rollback;2678}2679}else{2680error("unable to delete existing%s", newrefname);2681goto rollback;2682}2683}26842685if(log &&rename_tmp_log(newrefname))2686goto rollback;26872688 logmoved = log;26892690 lock =lock_ref_sha1_basic(newrefname, NULL,0, NULL);2691if(!lock) {2692error("unable to lock%sfor update", newrefname);2693goto rollback;2694}2695 lock->force_write =1;2696hashcpy(lock->old_sha1, orig_sha1);2697if(write_ref_sha1(lock, orig_sha1, logmsg)) {2698error("unable to write current sha1 into%s", newrefname);2699goto rollback;2700}27012702return0;27032704 rollback:2705 lock =lock_ref_sha1_basic(oldrefname, NULL,0, NULL);2706if(!lock) {2707error("unable to lock%sfor rollback", oldrefname);2708goto rollbacklog;2709}27102711 lock->force_write =1;2712 flag = log_all_ref_updates;2713 log_all_ref_updates =0;2714if(write_ref_sha1(lock, orig_sha1, NULL))2715error("unable to write current sha1 into%s", oldrefname);2716 log_all_ref_updates = flag;27172718 rollbacklog:2719if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2720error("unable to restore logfile%sfrom%s:%s",2721 oldrefname, newrefname,strerror(errno));2722if(!logmoved && log &&2723rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2724error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2725 oldrefname,strerror(errno));27262727return1;2728}27292730intclose_ref(struct ref_lock *lock)2731{2732if(close_lock_file(lock->lk))2733return-1;2734 lock->lock_fd = -1;2735return0;2736}27372738intcommit_ref(struct ref_lock *lock)2739{2740if(commit_lock_file(lock->lk))2741return-1;2742 lock->lock_fd = -1;2743return0;2744}27452746voidunlock_ref(struct ref_lock *lock)2747{2748/* Do not free lock->lk -- atexit() still looks at them */2749if(lock->lk)2750rollback_lock_file(lock->lk);2751free(lock->ref_name);2752free(lock->orig_ref_name);2753free(lock);2754}27552756/*2757 * copy the reflog message msg to buf, which has been allocated sufficiently2758 * large, while cleaning up the whitespaces. Especially, convert LF to space,2759 * because reflog file is one line per entry.2760 */2761static intcopy_msg(char*buf,const char*msg)2762{2763char*cp = buf;2764char c;2765int wasspace =1;27662767*cp++ ='\t';2768while((c = *msg++)) {2769if(wasspace &&isspace(c))2770continue;2771 wasspace =isspace(c);2772if(wasspace)2773 c =' ';2774*cp++ = c;2775}2776while(buf < cp &&isspace(cp[-1]))2777 cp--;2778*cp++ ='\n';2779return cp - buf;2780}27812782/* This function must set a meaningful errno on failure */2783intlog_ref_setup(const char*refname,char*logfile,int bufsize)2784{2785int logfd, oflags = O_APPEND | O_WRONLY;27862787git_snpath(logfile, bufsize,"logs/%s", refname);2788if(log_all_ref_updates &&2789(starts_with(refname,"refs/heads/") ||2790starts_with(refname,"refs/remotes/") ||2791starts_with(refname,"refs/notes/") ||2792!strcmp(refname,"HEAD"))) {2793if(safe_create_leading_directories(logfile) <0) {2794int save_errno = errno;2795error("unable to create directory for%s", logfile);2796 errno = save_errno;2797return-1;2798}2799 oflags |= O_CREAT;2800}28012802 logfd =open(logfile, oflags,0666);2803if(logfd <0) {2804if(!(oflags & O_CREAT) && errno == ENOENT)2805return0;28062807if((oflags & O_CREAT) && errno == EISDIR) {2808if(remove_empty_directories(logfile)) {2809int save_errno = errno;2810error("There are still logs under '%s'",2811 logfile);2812 errno = save_errno;2813return-1;2814}2815 logfd =open(logfile, oflags,0666);2816}28172818if(logfd <0) {2819int save_errno = errno;2820error("Unable to append to%s:%s", logfile,2821strerror(errno));2822 errno = save_errno;2823return-1;2824}2825}28262827adjust_shared_perm(logfile);2828close(logfd);2829return0;2830}28312832static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2833const unsigned char*new_sha1,const char*msg)2834{2835int logfd, result, written, oflags = O_APPEND | O_WRONLY;2836unsigned maxlen, len;2837int msglen;2838char log_file[PATH_MAX];2839char*logrec;2840const char*committer;28412842if(log_all_ref_updates <0)2843 log_all_ref_updates = !is_bare_repository();28442845 result =log_ref_setup(refname, log_file,sizeof(log_file));2846if(result)2847return result;28482849 logfd =open(log_file, oflags);2850if(logfd <0)2851return0;2852 msglen = msg ?strlen(msg) :0;2853 committer =git_committer_info(0);2854 maxlen =strlen(committer) + msglen +100;2855 logrec =xmalloc(maxlen);2856 len =sprintf(logrec,"%s %s %s\n",2857sha1_to_hex(old_sha1),2858sha1_to_hex(new_sha1),2859 committer);2860if(msglen)2861 len +=copy_msg(logrec + len -1, msg) -1;2862 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;2863free(logrec);2864if(written != len) {2865int save_errno = errno;2866close(logfd);2867error("Unable to append to%s", log_file);2868 errno = save_errno;2869return-1;2870}2871if(close(logfd)) {2872int save_errno = errno;2873error("Unable to append to%s", log_file);2874 errno = save_errno;2875return-1;2876}2877return0;2878}28792880intis_branch(const char*refname)2881{2882return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");2883}28842885/* This function must return a meaningful errno */2886intwrite_ref_sha1(struct ref_lock *lock,2887const unsigned char*sha1,const char*logmsg)2888{2889static char term ='\n';2890struct object *o;28912892if(!lock) {2893 errno = EINVAL;2894return-1;2895}2896if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {2897unlock_ref(lock);2898return0;2899}2900 o =parse_object(sha1);2901if(!o) {2902error("Trying to write ref%swith nonexistent object%s",2903 lock->ref_name,sha1_to_hex(sha1));2904unlock_ref(lock);2905 errno = EINVAL;2906return-1;2907}2908if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2909error("Trying to write non-commit object%sto branch%s",2910sha1_to_hex(sha1), lock->ref_name);2911unlock_ref(lock);2912 errno = EINVAL;2913return-1;2914}2915if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||2916write_in_full(lock->lock_fd, &term,1) !=1||2917close_ref(lock) <0) {2918int save_errno = errno;2919error("Couldn't write%s", lock->lk->filename);2920unlock_ref(lock);2921 errno = save_errno;2922return-1;2923}2924clear_loose_ref_cache(&ref_cache);2925if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||2926(strcmp(lock->ref_name, lock->orig_ref_name) &&2927log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {2928unlock_ref(lock);2929return-1;2930}2931if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2932/*2933 * Special hack: If a branch is updated directly and HEAD2934 * points to it (may happen on the remote side of a push2935 * for example) then logically the HEAD reflog should be2936 * updated too.2937 * A generic solution implies reverse symref information,2938 * but finding all symrefs pointing to the given branch2939 * would be rather costly for this rare event (the direct2940 * update of a branch) to be worth it. So let's cheat and2941 * check with HEAD only which should cover 99% of all usage2942 * scenarios (even 100% of the default ones).2943 */2944unsigned char head_sha1[20];2945int head_flag;2946const char*head_ref;2947 head_ref =resolve_ref_unsafe("HEAD", head_sha1,1, &head_flag);2948if(head_ref && (head_flag & REF_ISSYMREF) &&2949!strcmp(head_ref, lock->ref_name))2950log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);2951}2952if(commit_ref(lock)) {2953error("Couldn't set%s", lock->ref_name);2954unlock_ref(lock);2955return-1;2956}2957unlock_ref(lock);2958return0;2959}29602961intcreate_symref(const char*ref_target,const char*refs_heads_master,2962const char*logmsg)2963{2964const char*lockpath;2965char ref[1000];2966int fd, len, written;2967char*git_HEAD =git_pathdup("%s", ref_target);2968unsigned char old_sha1[20], new_sha1[20];29692970if(logmsg &&read_ref(ref_target, old_sha1))2971hashclr(old_sha1);29722973if(safe_create_leading_directories(git_HEAD) <0)2974returnerror("unable to create directory for%s", git_HEAD);29752976#ifndef NO_SYMLINK_HEAD2977if(prefer_symlink_refs) {2978unlink(git_HEAD);2979if(!symlink(refs_heads_master, git_HEAD))2980goto done;2981fprintf(stderr,"no symlink - falling back to symbolic ref\n");2982}2983#endif29842985 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);2986if(sizeof(ref) <= len) {2987error("refname too long:%s", refs_heads_master);2988goto error_free_return;2989}2990 lockpath =mkpath("%s.lock", git_HEAD);2991 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);2992if(fd <0) {2993error("Unable to open%sfor writing", lockpath);2994goto error_free_return;2995}2996 written =write_in_full(fd, ref, len);2997if(close(fd) !=0|| written != len) {2998error("Unable to write to%s", lockpath);2999goto error_unlink_return;3000}3001if(rename(lockpath, git_HEAD) <0) {3002error("Unable to create%s", git_HEAD);3003goto error_unlink_return;3004}3005if(adjust_shared_perm(git_HEAD)) {3006error("Unable to fix permissions on%s", lockpath);3007 error_unlink_return:3008unlink_or_warn(lockpath);3009 error_free_return:3010free(git_HEAD);3011return-1;3012}30133014#ifndef NO_SYMLINK_HEAD3015 done:3016#endif3017if(logmsg && !read_ref(refs_heads_master, new_sha1))3018log_ref_write(ref_target, old_sha1, new_sha1, logmsg);30193020free(git_HEAD);3021return0;3022}30233024struct read_ref_at_cb {3025const char*refname;3026unsigned long at_time;3027int cnt;3028int reccnt;3029unsigned char*sha1;3030int found_it;30313032unsigned char osha1[20];3033unsigned char nsha1[20];3034int tz;3035unsigned long date;3036char**msg;3037unsigned long*cutoff_time;3038int*cutoff_tz;3039int*cutoff_cnt;3040};30413042static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3043const char*email,unsigned long timestamp,int tz,3044const char*message,void*cb_data)3045{3046struct read_ref_at_cb *cb = cb_data;30473048 cb->reccnt++;3049 cb->tz = tz;3050 cb->date = timestamp;30513052if(timestamp <= cb->at_time || cb->cnt ==0) {3053if(cb->msg)3054*cb->msg =xstrdup(message);3055if(cb->cutoff_time)3056*cb->cutoff_time = timestamp;3057if(cb->cutoff_tz)3058*cb->cutoff_tz = tz;3059if(cb->cutoff_cnt)3060*cb->cutoff_cnt = cb->reccnt -1;3061/*3062 * we have not yet updated cb->[n|o]sha1 so they still3063 * hold the values for the previous record.3064 */3065if(!is_null_sha1(cb->osha1)) {3066hashcpy(cb->sha1, nsha1);3067if(hashcmp(cb->osha1, nsha1))3068warning("Log for ref%shas gap after%s.",3069 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3070}3071else if(cb->date == cb->at_time)3072hashcpy(cb->sha1, nsha1);3073else if(hashcmp(nsha1, cb->sha1))3074warning("Log for ref%sunexpectedly ended on%s.",3075 cb->refname,show_date(cb->date, cb->tz,3076 DATE_RFC2822));3077hashcpy(cb->osha1, osha1);3078hashcpy(cb->nsha1, nsha1);3079 cb->found_it =1;3080return1;3081}3082hashcpy(cb->osha1, osha1);3083hashcpy(cb->nsha1, nsha1);3084if(cb->cnt >0)3085 cb->cnt--;3086return0;3087}30883089static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3090const char*email,unsigned long timestamp,3091int tz,const char*message,void*cb_data)3092{3093struct read_ref_at_cb *cb = cb_data;30943095if(cb->msg)3096*cb->msg =xstrdup(message);3097if(cb->cutoff_time)3098*cb->cutoff_time = timestamp;3099if(cb->cutoff_tz)3100*cb->cutoff_tz = tz;3101if(cb->cutoff_cnt)3102*cb->cutoff_cnt = cb->reccnt;3103hashcpy(cb->sha1, osha1);3104if(is_null_sha1(cb->sha1))3105hashcpy(cb->sha1, nsha1);3106/* We just want the first entry */3107return1;3108}31093110intread_ref_at(const char*refname,unsigned long at_time,int cnt,3111unsigned char*sha1,char**msg,3112unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3113{3114struct read_ref_at_cb cb;31153116memset(&cb,0,sizeof(cb));3117 cb.refname = refname;3118 cb.at_time = at_time;3119 cb.cnt = cnt;3120 cb.msg = msg;3121 cb.cutoff_time = cutoff_time;3122 cb.cutoff_tz = cutoff_tz;3123 cb.cutoff_cnt = cutoff_cnt;3124 cb.sha1 = sha1;31253126for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);31273128if(!cb.reccnt)3129die("Log for%sis empty.", refname);3130if(cb.found_it)3131return0;31323133for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);31343135return1;3136}31373138intreflog_exists(const char*refname)3139{3140struct stat st;31413142return!lstat(git_path("logs/%s", refname), &st) &&3143S_ISREG(st.st_mode);3144}31453146intdelete_reflog(const char*refname)3147{3148returnremove_path(git_path("logs/%s", refname));3149}31503151static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3152{3153unsigned char osha1[20], nsha1[20];3154char*email_end, *message;3155unsigned long timestamp;3156int tz;31573158/* old SP new SP name <email> SP time TAB msg LF */3159if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3160get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3161get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3162!(email_end =strchr(sb->buf +82,'>')) ||3163 email_end[1] !=' '||3164!(timestamp =strtoul(email_end +2, &message,10)) ||3165!message || message[0] !=' '||3166(message[1] !='+'&& message[1] !='-') ||3167!isdigit(message[2]) || !isdigit(message[3]) ||3168!isdigit(message[4]) || !isdigit(message[5]))3169return0;/* corrupt? */3170 email_end[1] ='\0';3171 tz =strtol(message +1, NULL,10);3172if(message[6] !='\t')3173 message +=6;3174else3175 message +=7;3176returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3177}31783179static char*find_beginning_of_line(char*bob,char*scan)3180{3181while(bob < scan && *(--scan) !='\n')3182;/* keep scanning backwards */3183/*3184 * Return either beginning of the buffer, or LF at the end of3185 * the previous line.3186 */3187return scan;3188}31893190intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3191{3192struct strbuf sb = STRBUF_INIT;3193FILE*logfp;3194long pos;3195int ret =0, at_tail =1;31963197 logfp =fopen(git_path("logs/%s", refname),"r");3198if(!logfp)3199return-1;32003201/* Jump to the end */3202if(fseek(logfp,0, SEEK_END) <0)3203returnerror("cannot seek back reflog for%s:%s",3204 refname,strerror(errno));3205 pos =ftell(logfp);3206while(!ret &&0< pos) {3207int cnt;3208size_t nread;3209char buf[BUFSIZ];3210char*endp, *scanp;32113212/* Fill next block from the end */3213 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3214if(fseek(logfp, pos - cnt, SEEK_SET))3215returnerror("cannot seek back reflog for%s:%s",3216 refname,strerror(errno));3217 nread =fread(buf, cnt,1, logfp);3218if(nread !=1)3219returnerror("cannot read%dbytes from reflog for%s:%s",3220 cnt, refname,strerror(errno));3221 pos -= cnt;32223223 scanp = endp = buf + cnt;3224if(at_tail && scanp[-1] =='\n')3225/* Looking at the final LF at the end of the file */3226 scanp--;3227 at_tail =0;32283229while(buf < scanp) {3230/*3231 * terminating LF of the previous line, or the beginning3232 * of the buffer.3233 */3234char*bp;32353236 bp =find_beginning_of_line(buf, scanp);32373238if(*bp !='\n') {3239strbuf_splice(&sb,0,0, buf, endp - buf);3240if(pos)3241break;/* need to fill another block */3242 scanp = buf -1;/* leave loop */3243}else{3244/*3245 * (bp + 1) thru endp is the beginning of the3246 * current line we have in sb3247 */3248strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3249 scanp = bp;3250 endp = bp +1;3251}3252 ret =show_one_reflog_ent(&sb, fn, cb_data);3253strbuf_reset(&sb);3254if(ret)3255break;3256}32573258}3259if(!ret && sb.len)3260 ret =show_one_reflog_ent(&sb, fn, cb_data);32613262fclose(logfp);3263strbuf_release(&sb);3264return ret;3265}32663267intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3268{3269FILE*logfp;3270struct strbuf sb = STRBUF_INIT;3271int ret =0;32723273 logfp =fopen(git_path("logs/%s", refname),"r");3274if(!logfp)3275return-1;32763277while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3278 ret =show_one_reflog_ent(&sb, fn, cb_data);3279fclose(logfp);3280strbuf_release(&sb);3281return ret;3282}3283/*3284 * Call fn for each reflog in the namespace indicated by name. name3285 * must be empty or end with '/'. Name will be used as a scratch3286 * space, but its contents will be restored before return.3287 */3288static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3289{3290DIR*d =opendir(git_path("logs/%s", name->buf));3291int retval =0;3292struct dirent *de;3293int oldlen = name->len;32943295if(!d)3296return name->len ? errno :0;32973298while((de =readdir(d)) != NULL) {3299struct stat st;33003301if(de->d_name[0] =='.')3302continue;3303if(ends_with(de->d_name,".lock"))3304continue;3305strbuf_addstr(name, de->d_name);3306if(stat(git_path("logs/%s", name->buf), &st) <0) {3307;/* silently ignore */3308}else{3309if(S_ISDIR(st.st_mode)) {3310strbuf_addch(name,'/');3311 retval =do_for_each_reflog(name, fn, cb_data);3312}else{3313unsigned char sha1[20];3314if(read_ref_full(name->buf, sha1,0, NULL))3315 retval =error("bad ref for%s", name->buf);3316else3317 retval =fn(name->buf, sha1,0, cb_data);3318}3319if(retval)3320break;3321}3322strbuf_setlen(name, oldlen);3323}3324closedir(d);3325return retval;3326}33273328intfor_each_reflog(each_ref_fn fn,void*cb_data)3329{3330int retval;3331struct strbuf name;3332strbuf_init(&name, PATH_MAX);3333 retval =do_for_each_reflog(&name, fn, cb_data);3334strbuf_release(&name);3335return retval;3336}33373338static struct ref_lock *update_ref_lock(const char*refname,3339const unsigned char*oldval,3340int flags,int*type_p,3341enum action_on_err onerr)3342{3343struct ref_lock *lock;3344 lock =lock_any_ref_for_update(refname, oldval, flags, type_p);3345if(!lock) {3346const char*str ="Cannot lock the ref '%s'.";3347switch(onerr) {3348case UPDATE_REFS_MSG_ON_ERR:error(str, refname);break;3349case UPDATE_REFS_DIE_ON_ERR:die(str, refname);break;3350case UPDATE_REFS_QUIET_ON_ERR:break;3351}3352}3353return lock;3354}33553356static intupdate_ref_write(const char*action,const char*refname,3357const unsigned char*sha1,struct ref_lock *lock,3358struct strbuf *err,enum action_on_err onerr)3359{3360if(write_ref_sha1(lock, sha1, action) <0) {3361const char*str ="Cannot update the ref '%s'.";3362if(err)3363strbuf_addf(err, str, refname);33643365switch(onerr) {3366case UPDATE_REFS_MSG_ON_ERR:error(str, refname);break;3367case UPDATE_REFS_DIE_ON_ERR:die(str, refname);break;3368case UPDATE_REFS_QUIET_ON_ERR:break;3369}3370return1;3371}3372return0;3373}33743375/**3376 * Information needed for a single ref update. Set new_sha1 to the3377 * new value or to zero to delete the ref. To check the old value3378 * while locking the ref, set have_old to 1 and set old_sha1 to the3379 * value or to zero to ensure the ref does not exist before update.3380 */3381struct ref_update {3382unsigned char new_sha1[20];3383unsigned char old_sha1[20];3384int flags;/* REF_NODEREF? */3385int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3386struct ref_lock *lock;3387int type;3388const char refname[FLEX_ARRAY];3389};33903391/*3392 * Data structure for holding a reference transaction, which can3393 * consist of checks and updates to multiple references, carried out3394 * as atomically as possible. This structure is opaque to callers.3395 */3396struct ref_transaction {3397struct ref_update **updates;3398size_t alloc;3399size_t nr;3400};34013402struct ref_transaction *ref_transaction_begin(void)3403{3404returnxcalloc(1,sizeof(struct ref_transaction));3405}34063407voidref_transaction_free(struct ref_transaction *transaction)3408{3409int i;34103411if(!transaction)3412return;34133414for(i =0; i < transaction->nr; i++)3415free(transaction->updates[i]);34163417free(transaction->updates);3418free(transaction);3419}34203421static struct ref_update *add_update(struct ref_transaction *transaction,3422const char*refname)3423{3424size_t len =strlen(refname);3425struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);34263427strcpy((char*)update->refname, refname);3428ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3429 transaction->updates[transaction->nr++] = update;3430return update;3431}34323433intref_transaction_update(struct ref_transaction *transaction,3434const char*refname,3435const unsigned char*new_sha1,3436const unsigned char*old_sha1,3437int flags,int have_old,3438struct strbuf *err)3439{3440struct ref_update *update;34413442if(have_old && !old_sha1)3443die("BUG: have_old is true but old_sha1 is NULL");34443445 update =add_update(transaction, refname);3446hashcpy(update->new_sha1, new_sha1);3447 update->flags = flags;3448 update->have_old = have_old;3449if(have_old)3450hashcpy(update->old_sha1, old_sha1);3451return0;3452}34533454voidref_transaction_create(struct ref_transaction *transaction,3455const char*refname,3456const unsigned char*new_sha1,3457int flags)3458{3459struct ref_update *update =add_update(transaction, refname);34603461assert(!is_null_sha1(new_sha1));3462hashcpy(update->new_sha1, new_sha1);3463hashclr(update->old_sha1);3464 update->flags = flags;3465 update->have_old =1;3466}34673468voidref_transaction_delete(struct ref_transaction *transaction,3469const char*refname,3470const unsigned char*old_sha1,3471int flags,int have_old)3472{3473struct ref_update *update =add_update(transaction, refname);34743475 update->flags = flags;3476 update->have_old = have_old;3477if(have_old) {3478assert(!is_null_sha1(old_sha1));3479hashcpy(update->old_sha1, old_sha1);3480}3481}34823483intupdate_ref(const char*action,const char*refname,3484const unsigned char*sha1,const unsigned char*oldval,3485int flags,enum action_on_err onerr)3486{3487struct ref_lock *lock;3488 lock =update_ref_lock(refname, oldval, flags, NULL, onerr);3489if(!lock)3490return1;3491returnupdate_ref_write(action, refname, sha1, lock, NULL, onerr);3492}34933494static intref_update_compare(const void*r1,const void*r2)3495{3496const struct ref_update *const*u1 = r1;3497const struct ref_update *const*u2 = r2;3498returnstrcmp((*u1)->refname, (*u2)->refname);3499}35003501static intref_update_reject_duplicates(struct ref_update **updates,int n,3502struct strbuf *err)3503{3504int i;3505for(i =1; i < n; i++)3506if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3507const char*str =3508"Multiple updates for ref '%s' not allowed.";3509if(err)3510strbuf_addf(err, str, updates[i]->refname);35113512return1;3513}3514return0;3515}35163517intref_transaction_commit(struct ref_transaction *transaction,3518const char*msg,struct strbuf *err)3519{3520int ret =0, delnum =0, i;3521const char**delnames;3522int n = transaction->nr;3523struct ref_update **updates = transaction->updates;35243525if(!n)3526return0;35273528/* Allocate work space */3529 delnames =xmalloc(sizeof(*delnames) * n);35303531/* Copy, sort, and reject duplicate refs */3532qsort(updates, n,sizeof(*updates), ref_update_compare);3533 ret =ref_update_reject_duplicates(updates, n, err);3534if(ret)3535goto cleanup;35363537/* Acquire all locks while verifying old values */3538for(i =0; i < n; i++) {3539struct ref_update *update = updates[i];35403541 update->lock =update_ref_lock(update->refname,3542(update->have_old ?3543 update->old_sha1 : NULL),3544 update->flags,3545&update->type,3546 UPDATE_REFS_QUIET_ON_ERR);3547if(!update->lock) {3548if(err)3549strbuf_addf(err,"Cannot lock the ref '%s'.",3550 update->refname);3551 ret =1;3552goto cleanup;3553}3554}35553556/* Perform updates first so live commits remain referenced */3557for(i =0; i < n; i++) {3558struct ref_update *update = updates[i];35593560if(!is_null_sha1(update->new_sha1)) {3561 ret =update_ref_write(msg,3562 update->refname,3563 update->new_sha1,3564 update->lock, err,3565 UPDATE_REFS_QUIET_ON_ERR);3566 update->lock = NULL;/* freed by update_ref_write */3567if(ret)3568goto cleanup;3569}3570}35713572/* Perform deletes now that updates are safely completed */3573for(i =0; i < n; i++) {3574struct ref_update *update = updates[i];35753576if(update->lock) {3577 delnames[delnum++] = update->lock->ref_name;3578 ret |=delete_ref_loose(update->lock, update->type);3579}3580}35813582 ret |=repack_without_refs(delnames, delnum, err);3583for(i =0; i < delnum; i++)3584unlink_or_warn(git_path("logs/%s", delnames[i]));3585clear_loose_ref_cache(&ref_cache);35863587cleanup:3588for(i =0; i < n; i++)3589if(updates[i]->lock)3590unlock_ref(updates[i]->lock);3591free(delnames);3592return ret;3593}35943595char*shorten_unambiguous_ref(const char*refname,int strict)3596{3597int i;3598static char**scanf_fmts;3599static int nr_rules;3600char*short_name;36013602if(!nr_rules) {3603/*3604 * Pre-generate scanf formats from ref_rev_parse_rules[].3605 * Generate a format suitable for scanf from a3606 * ref_rev_parse_rules rule by interpolating "%s" at the3607 * location of the "%.*s".3608 */3609size_t total_len =0;3610size_t offset =0;36113612/* the rule list is NULL terminated, count them first */3613for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3614/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3615 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;36163617 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);36183619 offset =0;3620for(i =0; i < nr_rules; i++) {3621assert(offset < total_len);3622 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3623 offset +=snprintf(scanf_fmts[i], total_len - offset,3624 ref_rev_parse_rules[i],2,"%s") +1;3625}3626}36273628/* bail out if there are no rules */3629if(!nr_rules)3630returnxstrdup(refname);36313632/* buffer for scanf result, at most refname must fit */3633 short_name =xstrdup(refname);36343635/* skip first rule, it will always match */3636for(i = nr_rules -1; i >0; --i) {3637int j;3638int rules_to_fail = i;3639int short_name_len;36403641if(1!=sscanf(refname, scanf_fmts[i], short_name))3642continue;36433644 short_name_len =strlen(short_name);36453646/*3647 * in strict mode, all (except the matched one) rules3648 * must fail to resolve to a valid non-ambiguous ref3649 */3650if(strict)3651 rules_to_fail = nr_rules;36523653/*3654 * check if the short name resolves to a valid ref,3655 * but use only rules prior to the matched one3656 */3657for(j =0; j < rules_to_fail; j++) {3658const char*rule = ref_rev_parse_rules[j];3659char refname[PATH_MAX];36603661/* skip matched rule */3662if(i == j)3663continue;36643665/*3666 * the short name is ambiguous, if it resolves3667 * (with this previous rule) to a valid ref3668 * read_ref() returns 0 on success3669 */3670mksnpath(refname,sizeof(refname),3671 rule, short_name_len, short_name);3672if(ref_exists(refname))3673break;3674}36753676/*3677 * short name is non-ambiguous if all previous rules3678 * haven't resolved to a valid ref3679 */3680if(j == rules_to_fail)3681return short_name;3682}36833684free(short_name);3685returnxstrdup(refname);3686}36873688static struct string_list *hide_refs;36893690intparse_hide_refs_config(const char*var,const char*value,const char*section)3691{3692if(!strcmp("transfer.hiderefs", var) ||3693/* NEEDSWORK: use parse_config_key() once both are merged */3694(starts_with(var, section) && var[strlen(section)] =='.'&&3695!strcmp(var +strlen(section),".hiderefs"))) {3696char*ref;3697int len;36983699if(!value)3700returnconfig_error_nonbool(var);3701 ref =xstrdup(value);3702 len =strlen(ref);3703while(len && ref[len -1] =='/')3704 ref[--len] ='\0';3705if(!hide_refs) {3706 hide_refs =xcalloc(1,sizeof(*hide_refs));3707 hide_refs->strdup_strings =1;3708}3709string_list_append(hide_refs, ref);3710}3711return0;3712}37133714intref_is_hidden(const char*refname)3715{3716struct string_list_item *item;37173718if(!hide_refs)3719return0;3720for_each_string_list_item(item, hide_refs) {3721int len;3722if(!starts_with(refname, item->string))3723continue;3724 len =strlen(item->string);3725if(!refname[len] || refname[len] =='/')3726return1;3727}3728return0;3729}