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 * Used as a flag to ref_transaction_delete when a loose ref is being 29 * pruned. 30 */ 31#define REF_ISPRUNING 0x0100 32/* 33 * Try to read one refname component from the front of refname. 34 * Return the length of the component found, or -1 if the component is 35 * not legal. It is legal if it is something reasonable to have under 36 * ".git/refs/"; We do not like it if: 37 * 38 * - any path component of it begins with ".", or 39 * - it has double dots "..", or 40 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 41 * - it ends with a "/". 42 * - it ends with ".lock" 43 * - it contains a "\" (backslash) 44 */ 45static intcheck_refname_component(const char*refname,int flags) 46{ 47const char*cp; 48char last ='\0'; 49 50for(cp = refname; ; cp++) { 51int ch = *cp &255; 52unsigned char disp = refname_disposition[ch]; 53switch(disp) { 54case1: 55goto out; 56case2: 57if(last =='.') 58return-1;/* Refname contains "..". */ 59break; 60case3: 61if(last =='@') 62return-1;/* Refname contains "@{". */ 63break; 64case4: 65return-1; 66} 67 last = ch; 68} 69out: 70if(cp == refname) 71return0;/* Component has zero length. */ 72if(refname[0] =='.') { 73if(!(flags & REFNAME_DOT_COMPONENT)) 74return-1;/* Component starts with '.'. */ 75/* 76 * Even if leading dots are allowed, don't allow "." 77 * as a component (".." is prevented by a rule above). 78 */ 79if(refname[1] =='\0') 80return-1;/* Component equals ".". */ 81} 82if(cp - refname >= LOCK_SUFFIX_LEN && 83!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 84return-1;/* Refname ends with ".lock". */ 85return cp - refname; 86} 87 88intcheck_refname_format(const char*refname,int flags) 89{ 90int component_len, component_count =0; 91 92if(!strcmp(refname,"@")) 93/* Refname is a single character '@'. */ 94return-1; 95 96while(1) { 97/* We are at the start of a path component. */ 98 component_len =check_refname_component(refname, flags); 99if(component_len <=0) { 100if((flags & REFNAME_REFSPEC_PATTERN) && 101 refname[0] =='*'&& 102(refname[1] =='\0'|| refname[1] =='/')) { 103/* Accept one wildcard as a full refname component. */ 104 flags &= ~REFNAME_REFSPEC_PATTERN; 105 component_len =1; 106}else{ 107return-1; 108} 109} 110 component_count++; 111if(refname[component_len] =='\0') 112break; 113/* Skip to next component. */ 114 refname += component_len +1; 115} 116 117if(refname[component_len -1] =='.') 118return-1;/* Refname ends with '.'. */ 119if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 120return-1;/* Refname has only one component. */ 121return0; 122} 123 124struct ref_entry; 125 126/* 127 * Information used (along with the information in ref_entry) to 128 * describe a single cached reference. This data structure only 129 * occurs embedded in a union in struct ref_entry, and only when 130 * (ref_entry->flag & REF_DIR) is zero. 131 */ 132struct ref_value { 133/* 134 * The name of the object to which this reference resolves 135 * (which may be a tag object). If REF_ISBROKEN, this is 136 * null. If REF_ISSYMREF, then this is the name of the object 137 * referred to by the last reference in the symlink chain. 138 */ 139unsigned char sha1[20]; 140 141/* 142 * If REF_KNOWS_PEELED, then this field holds the peeled value 143 * of this reference, or null if the reference is known not to 144 * be peelable. See the documentation for peel_ref() for an 145 * exact definition of "peelable". 146 */ 147unsigned char peeled[20]; 148}; 149 150struct ref_cache; 151 152/* 153 * Information used (along with the information in ref_entry) to 154 * describe a level in the hierarchy of references. This data 155 * structure only occurs embedded in a union in struct ref_entry, and 156 * only when (ref_entry.flag & REF_DIR) is set. In that case, 157 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 158 * in the directory have already been read: 159 * 160 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 161 * or packed references, already read. 162 * 163 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 164 * references that hasn't been read yet (nor has any of its 165 * subdirectories). 166 * 167 * Entries within a directory are stored within a growable array of 168 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 169 * sorted are sorted by their component name in strcmp() order and the 170 * remaining entries are unsorted. 171 * 172 * Loose references are read lazily, one directory at a time. When a 173 * directory of loose references is read, then all of the references 174 * in that directory are stored, and REF_INCOMPLETE stubs are created 175 * for any subdirectories, but the subdirectories themselves are not 176 * read. The reading is triggered by get_ref_dir(). 177 */ 178struct ref_dir { 179int nr, alloc; 180 181/* 182 * Entries with index 0 <= i < sorted are sorted by name. New 183 * entries are appended to the list unsorted, and are sorted 184 * only when required; thus we avoid the need to sort the list 185 * after the addition of every reference. 186 */ 187int sorted; 188 189/* A pointer to the ref_cache that contains this ref_dir. */ 190struct ref_cache *ref_cache; 191 192struct ref_entry **entries; 193}; 194 195/* 196 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 197 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see 198 * refs.h. 199 */ 200 201/* 202 * The field ref_entry->u.value.peeled of this value entry contains 203 * the correct peeled value for the reference, which might be 204 * null_sha1 if the reference is not a tag or if it is broken. 205 */ 206#define REF_KNOWS_PEELED 0x08 207 208/* ref_entry represents a directory of references */ 209#define REF_DIR 0x10 210 211/* 212 * Entry has not yet been read from disk (used only for REF_DIR 213 * entries representing loose references) 214 */ 215#define REF_INCOMPLETE 0x20 216 217/* 218 * A ref_entry represents either a reference or a "subdirectory" of 219 * references. 220 * 221 * Each directory in the reference namespace is represented by a 222 * ref_entry with (flags & REF_DIR) set and containing a subdir member 223 * that holds the entries in that directory that have been read so 224 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 225 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 226 * used for loose reference directories. 227 * 228 * References are represented by a ref_entry with (flags & REF_DIR) 229 * unset and a value member that describes the reference's value. The 230 * flag member is at the ref_entry level, but it is also needed to 231 * interpret the contents of the value field (in other words, a 232 * ref_value object is not very much use without the enclosing 233 * ref_entry). 234 * 235 * Reference names cannot end with slash and directories' names are 236 * always stored with a trailing slash (except for the top-level 237 * directory, which is always denoted by ""). This has two nice 238 * consequences: (1) when the entries in each subdir are sorted 239 * lexicographically by name (as they usually are), the references in 240 * a whole tree can be generated in lexicographic order by traversing 241 * the tree in left-to-right, depth-first order; (2) the names of 242 * references and subdirectories cannot conflict, and therefore the 243 * presence of an empty subdirectory does not block the creation of a 244 * similarly-named reference. (The fact that reference names with the 245 * same leading components can conflict *with each other* is a 246 * separate issue that is regulated by is_refname_available().) 247 * 248 * Please note that the name field contains the fully-qualified 249 * reference (or subdirectory) name. Space could be saved by only 250 * storing the relative names. But that would require the full names 251 * to be generated on the fly when iterating in do_for_each_ref(), and 252 * would break callback functions, who have always been able to assume 253 * that the name strings that they are passed will not be freed during 254 * the iteration. 255 */ 256struct ref_entry { 257unsigned char flag;/* ISSYMREF? ISPACKED? */ 258union{ 259struct ref_value value;/* if not (flags&REF_DIR) */ 260struct ref_dir subdir;/* if (flags&REF_DIR) */ 261} u; 262/* 263 * The full name of the reference (e.g., "refs/heads/master") 264 * or the full name of the directory with a trailing slash 265 * (e.g., "refs/heads/"): 266 */ 267char name[FLEX_ARRAY]; 268}; 269 270static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 271 272static struct ref_dir *get_ref_dir(struct ref_entry *entry) 273{ 274struct ref_dir *dir; 275assert(entry->flag & REF_DIR); 276 dir = &entry->u.subdir; 277if(entry->flag & REF_INCOMPLETE) { 278read_loose_refs(entry->name, dir); 279 entry->flag &= ~REF_INCOMPLETE; 280} 281return dir; 282} 283 284static struct ref_entry *create_ref_entry(const char*refname, 285const unsigned char*sha1,int flag, 286int check_name) 287{ 288int len; 289struct ref_entry *ref; 290 291if(check_name && 292check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) 293die("Reference has invalid format: '%s'", refname); 294 len =strlen(refname) +1; 295 ref =xmalloc(sizeof(struct ref_entry) + len); 296hashcpy(ref->u.value.sha1, sha1); 297hashclr(ref->u.value.peeled); 298memcpy(ref->name, refname, len); 299 ref->flag = flag; 300return ref; 301} 302 303static voidclear_ref_dir(struct ref_dir *dir); 304 305static voidfree_ref_entry(struct ref_entry *entry) 306{ 307if(entry->flag & REF_DIR) { 308/* 309 * Do not use get_ref_dir() here, as that might 310 * trigger the reading of loose refs. 311 */ 312clear_ref_dir(&entry->u.subdir); 313} 314free(entry); 315} 316 317/* 318 * Add a ref_entry to the end of dir (unsorted). Entry is always 319 * stored directly in dir; no recursion into subdirectories is 320 * done. 321 */ 322static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 323{ 324ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 325 dir->entries[dir->nr++] = entry; 326/* optimize for the case that entries are added in order */ 327if(dir->nr ==1|| 328(dir->nr == dir->sorted +1&& 329strcmp(dir->entries[dir->nr -2]->name, 330 dir->entries[dir->nr -1]->name) <0)) 331 dir->sorted = dir->nr; 332} 333 334/* 335 * Clear and free all entries in dir, recursively. 336 */ 337static voidclear_ref_dir(struct ref_dir *dir) 338{ 339int i; 340for(i =0; i < dir->nr; i++) 341free_ref_entry(dir->entries[i]); 342free(dir->entries); 343 dir->sorted = dir->nr = dir->alloc =0; 344 dir->entries = NULL; 345} 346 347/* 348 * Create a struct ref_entry object for the specified dirname. 349 * dirname is the name of the directory with a trailing slash (e.g., 350 * "refs/heads/") or "" for the top-level directory. 351 */ 352static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 353const char*dirname,size_t len, 354int incomplete) 355{ 356struct ref_entry *direntry; 357 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 358memcpy(direntry->name, dirname, len); 359 direntry->name[len] ='\0'; 360 direntry->u.subdir.ref_cache = ref_cache; 361 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 362return direntry; 363} 364 365static intref_entry_cmp(const void*a,const void*b) 366{ 367struct ref_entry *one = *(struct ref_entry **)a; 368struct ref_entry *two = *(struct ref_entry **)b; 369returnstrcmp(one->name, two->name); 370} 371 372static voidsort_ref_dir(struct ref_dir *dir); 373 374struct string_slice { 375size_t len; 376const char*str; 377}; 378 379static intref_entry_cmp_sslice(const void*key_,const void*ent_) 380{ 381const struct string_slice *key = key_; 382const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 383int cmp =strncmp(key->str, ent->name, key->len); 384if(cmp) 385return cmp; 386return'\0'- (unsigned char)ent->name[key->len]; 387} 388 389/* 390 * Return the index of the entry with the given refname from the 391 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 392 * no such entry is found. dir must already be complete. 393 */ 394static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 395{ 396struct ref_entry **r; 397struct string_slice key; 398 399if(refname == NULL || !dir->nr) 400return-1; 401 402sort_ref_dir(dir); 403 key.len = len; 404 key.str = refname; 405 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 406 ref_entry_cmp_sslice); 407 408if(r == NULL) 409return-1; 410 411return r - dir->entries; 412} 413 414/* 415 * Search for a directory entry directly within dir (without 416 * recursing). Sort dir if necessary. subdirname must be a directory 417 * name (i.e., end in '/'). If mkdir is set, then create the 418 * directory if it is missing; otherwise, return NULL if the desired 419 * directory cannot be found. dir must already be complete. 420 */ 421static struct ref_dir *search_for_subdir(struct ref_dir *dir, 422const char*subdirname,size_t len, 423int mkdir) 424{ 425int entry_index =search_ref_dir(dir, subdirname, len); 426struct ref_entry *entry; 427if(entry_index == -1) { 428if(!mkdir) 429return NULL; 430/* 431 * Since dir is complete, the absence of a subdir 432 * means that the subdir really doesn't exist; 433 * therefore, create an empty record for it but mark 434 * the record complete. 435 */ 436 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 437add_entry_to_dir(dir, entry); 438}else{ 439 entry = dir->entries[entry_index]; 440} 441returnget_ref_dir(entry); 442} 443 444/* 445 * If refname is a reference name, find the ref_dir within the dir 446 * tree that should hold refname. If refname is a directory name 447 * (i.e., ends in '/'), then return that ref_dir itself. dir must 448 * represent the top-level directory and must already be complete. 449 * Sort ref_dirs and recurse into subdirectories as necessary. If 450 * mkdir is set, then create any missing directories; otherwise, 451 * return NULL if the desired directory cannot be found. 452 */ 453static struct ref_dir *find_containing_dir(struct ref_dir *dir, 454const char*refname,int mkdir) 455{ 456const char*slash; 457for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 458size_t dirnamelen = slash - refname +1; 459struct ref_dir *subdir; 460 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 461if(!subdir) { 462 dir = NULL; 463break; 464} 465 dir = subdir; 466} 467 468return dir; 469} 470 471/* 472 * Find the value entry with the given name in dir, sorting ref_dirs 473 * and recursing into subdirectories as necessary. If the name is not 474 * found or it corresponds to a directory entry, return NULL. 475 */ 476static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 477{ 478int entry_index; 479struct ref_entry *entry; 480 dir =find_containing_dir(dir, refname,0); 481if(!dir) 482return NULL; 483 entry_index =search_ref_dir(dir, refname,strlen(refname)); 484if(entry_index == -1) 485return NULL; 486 entry = dir->entries[entry_index]; 487return(entry->flag & REF_DIR) ? NULL : entry; 488} 489 490/* 491 * Remove the entry with the given name from dir, recursing into 492 * subdirectories as necessary. If refname is the name of a directory 493 * (i.e., ends with '/'), then remove the directory and its contents. 494 * If the removal was successful, return the number of entries 495 * remaining in the directory entry that contained the deleted entry. 496 * If the name was not found, return -1. Please note that this 497 * function only deletes the entry from the cache; it does not delete 498 * it from the filesystem or ensure that other cache entries (which 499 * might be symbolic references to the removed entry) are updated. 500 * Nor does it remove any containing dir entries that might be made 501 * empty by the removal. dir must represent the top-level directory 502 * and must already be complete. 503 */ 504static intremove_entry(struct ref_dir *dir,const char*refname) 505{ 506int refname_len =strlen(refname); 507int entry_index; 508struct ref_entry *entry; 509int is_dir = refname[refname_len -1] =='/'; 510if(is_dir) { 511/* 512 * refname represents a reference directory. Remove 513 * the trailing slash; otherwise we will get the 514 * directory *representing* refname rather than the 515 * one *containing* it. 516 */ 517char*dirname =xmemdupz(refname, refname_len -1); 518 dir =find_containing_dir(dir, dirname,0); 519free(dirname); 520}else{ 521 dir =find_containing_dir(dir, refname,0); 522} 523if(!dir) 524return-1; 525 entry_index =search_ref_dir(dir, refname, refname_len); 526if(entry_index == -1) 527return-1; 528 entry = dir->entries[entry_index]; 529 530memmove(&dir->entries[entry_index], 531&dir->entries[entry_index +1], 532(dir->nr - entry_index -1) *sizeof(*dir->entries) 533); 534 dir->nr--; 535if(dir->sorted > entry_index) 536 dir->sorted--; 537free_ref_entry(entry); 538return dir->nr; 539} 540 541/* 542 * Add a ref_entry to the ref_dir (unsorted), recursing into 543 * subdirectories as necessary. dir must represent the top-level 544 * directory. Return 0 on success. 545 */ 546static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 547{ 548 dir =find_containing_dir(dir, ref->name,1); 549if(!dir) 550return-1; 551add_entry_to_dir(dir, ref); 552return0; 553} 554 555/* 556 * Emit a warning and return true iff ref1 and ref2 have the same name 557 * and the same sha1. Die if they have the same name but different 558 * sha1s. 559 */ 560static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 561{ 562if(strcmp(ref1->name, ref2->name)) 563return0; 564 565/* Duplicate name; make sure that they don't conflict: */ 566 567if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 568/* This is impossible by construction */ 569die("Reference directory conflict:%s", ref1->name); 570 571if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 572die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 573 574warning("Duplicated ref:%s", ref1->name); 575return1; 576} 577 578/* 579 * Sort the entries in dir non-recursively (if they are not already 580 * sorted) and remove any duplicate entries. 581 */ 582static voidsort_ref_dir(struct ref_dir *dir) 583{ 584int i, j; 585struct ref_entry *last = NULL; 586 587/* 588 * This check also prevents passing a zero-length array to qsort(), 589 * which is a problem on some platforms. 590 */ 591if(dir->sorted == dir->nr) 592return; 593 594qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 595 596/* Remove any duplicates: */ 597for(i =0, j =0; j < dir->nr; j++) { 598struct ref_entry *entry = dir->entries[j]; 599if(last &&is_dup_ref(last, entry)) 600free_ref_entry(entry); 601else 602 last = dir->entries[i++] = entry; 603} 604 dir->sorted = dir->nr = i; 605} 606 607/* Include broken references in a do_for_each_ref*() iteration: */ 608#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 609 610/* 611 * Return true iff the reference described by entry can be resolved to 612 * an object in the database. Emit a warning if the referred-to 613 * object does not exist. 614 */ 615static intref_resolves_to_object(struct ref_entry *entry) 616{ 617if(entry->flag & REF_ISBROKEN) 618return0; 619if(!has_sha1_file(entry->u.value.sha1)) { 620error("%sdoes not point to a valid object!", entry->name); 621return0; 622} 623return1; 624} 625 626/* 627 * current_ref is a performance hack: when iterating over references 628 * using the for_each_ref*() functions, current_ref is set to the 629 * current reference's entry before calling the callback function. If 630 * the callback function calls peel_ref(), then peel_ref() first 631 * checks whether the reference to be peeled is the current reference 632 * (it usually is) and if so, returns that reference's peeled version 633 * if it is available. This avoids a refname lookup in a common case. 634 */ 635static struct ref_entry *current_ref; 636 637typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 638 639struct ref_entry_cb { 640const char*base; 641int trim; 642int flags; 643 each_ref_fn *fn; 644void*cb_data; 645}; 646 647/* 648 * Handle one reference in a do_for_each_ref*()-style iteration, 649 * calling an each_ref_fn for each entry. 650 */ 651static intdo_one_ref(struct ref_entry *entry,void*cb_data) 652{ 653struct ref_entry_cb *data = cb_data; 654struct ref_entry *old_current_ref; 655int retval; 656 657if(!starts_with(entry->name, data->base)) 658return0; 659 660if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 661!ref_resolves_to_object(entry)) 662return0; 663 664/* Store the old value, in case this is a recursive call: */ 665 old_current_ref = current_ref; 666 current_ref = entry; 667 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 668 entry->flag, data->cb_data); 669 current_ref = old_current_ref; 670return retval; 671} 672 673/* 674 * Call fn for each reference in dir that has index in the range 675 * offset <= index < dir->nr. Recurse into subdirectories that are in 676 * that index range, sorting them before iterating. This function 677 * does not sort dir itself; it should be sorted beforehand. fn is 678 * called for all references, including broken ones. 679 */ 680static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 681 each_ref_entry_fn fn,void*cb_data) 682{ 683int i; 684assert(dir->sorted == dir->nr); 685for(i = offset; i < dir->nr; i++) { 686struct ref_entry *entry = dir->entries[i]; 687int retval; 688if(entry->flag & REF_DIR) { 689struct ref_dir *subdir =get_ref_dir(entry); 690sort_ref_dir(subdir); 691 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 692}else{ 693 retval =fn(entry, cb_data); 694} 695if(retval) 696return retval; 697} 698return0; 699} 700 701/* 702 * Call fn for each reference in the union of dir1 and dir2, in order 703 * by refname. Recurse into subdirectories. If a value entry appears 704 * in both dir1 and dir2, then only process the version that is in 705 * dir2. The input dirs must already be sorted, but subdirs will be 706 * sorted as needed. fn is called for all references, including 707 * broken ones. 708 */ 709static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 710struct ref_dir *dir2, 711 each_ref_entry_fn fn,void*cb_data) 712{ 713int retval; 714int i1 =0, i2 =0; 715 716assert(dir1->sorted == dir1->nr); 717assert(dir2->sorted == dir2->nr); 718while(1) { 719struct ref_entry *e1, *e2; 720int cmp; 721if(i1 == dir1->nr) { 722returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 723} 724if(i2 == dir2->nr) { 725returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 726} 727 e1 = dir1->entries[i1]; 728 e2 = dir2->entries[i2]; 729 cmp =strcmp(e1->name, e2->name); 730if(cmp ==0) { 731if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 732/* Both are directories; descend them in parallel. */ 733struct ref_dir *subdir1 =get_ref_dir(e1); 734struct ref_dir *subdir2 =get_ref_dir(e2); 735sort_ref_dir(subdir1); 736sort_ref_dir(subdir2); 737 retval =do_for_each_entry_in_dirs( 738 subdir1, subdir2, fn, cb_data); 739 i1++; 740 i2++; 741}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 742/* Both are references; ignore the one from dir1. */ 743 retval =fn(e2, cb_data); 744 i1++; 745 i2++; 746}else{ 747die("conflict between reference and directory:%s", 748 e1->name); 749} 750}else{ 751struct ref_entry *e; 752if(cmp <0) { 753 e = e1; 754 i1++; 755}else{ 756 e = e2; 757 i2++; 758} 759if(e->flag & REF_DIR) { 760struct ref_dir *subdir =get_ref_dir(e); 761sort_ref_dir(subdir); 762 retval =do_for_each_entry_in_dir( 763 subdir,0, fn, cb_data); 764}else{ 765 retval =fn(e, cb_data); 766} 767} 768if(retval) 769return retval; 770} 771} 772 773/* 774 * Load all of the refs from the dir into our in-memory cache. The hard work 775 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 776 * through all of the sub-directories. We do not even need to care about 777 * sorting, as traversal order does not matter to us. 778 */ 779static voidprime_ref_dir(struct ref_dir *dir) 780{ 781int i; 782for(i =0; i < dir->nr; i++) { 783struct ref_entry *entry = dir->entries[i]; 784if(entry->flag & REF_DIR) 785prime_ref_dir(get_ref_dir(entry)); 786} 787} 788 789static intentry_matches(struct ref_entry *entry,const char*refname) 790{ 791return refname && !strcmp(entry->name, refname); 792} 793 794struct nonmatching_ref_data { 795const char*skip; 796struct ref_entry *found; 797}; 798 799static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 800{ 801struct nonmatching_ref_data *data = vdata; 802 803if(entry_matches(entry, data->skip)) 804return0; 805 806 data->found = entry; 807return1; 808} 809 810static voidreport_refname_conflict(struct ref_entry *entry, 811const char*refname) 812{ 813error("'%s' exists; cannot create '%s'", entry->name, refname); 814} 815 816/* 817 * Return true iff a reference named refname could be created without 818 * conflicting with the name of an existing reference in dir. If 819 * oldrefname is non-NULL, ignore potential conflicts with oldrefname 820 * (e.g., because oldrefname is scheduled for deletion in the same 821 * operation). 822 * 823 * Two reference names conflict if one of them exactly matches the 824 * leading components of the other; e.g., "foo/bar" conflicts with 825 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 826 * "foo/barbados". 827 */ 828static intis_refname_available(const char*refname,const char*oldrefname, 829struct ref_dir *dir) 830{ 831const char*slash; 832size_t len; 833int pos; 834char*dirname; 835 836for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 837/* 838 * We are still at a leading dir of the refname; we are 839 * looking for a conflict with a leaf entry. 840 * 841 * If we find one, we still must make sure it is 842 * not "oldrefname". 843 */ 844 pos =search_ref_dir(dir, refname, slash - refname); 845if(pos >=0) { 846struct ref_entry *entry = dir->entries[pos]; 847if(entry_matches(entry, oldrefname)) 848return1; 849report_refname_conflict(entry, refname); 850return0; 851} 852 853 854/* 855 * Otherwise, we can try to continue our search with 856 * the next component; if we come up empty, we know 857 * there is nothing under this whole prefix. 858 */ 859 pos =search_ref_dir(dir, refname, slash +1- refname); 860if(pos <0) 861return1; 862 863 dir =get_ref_dir(dir->entries[pos]); 864} 865 866/* 867 * We are at the leaf of our refname; we want to 868 * make sure there are no directories which match it. 869 */ 870 len =strlen(refname); 871 dirname =xmallocz(len +1); 872sprintf(dirname,"%s/", refname); 873 pos =search_ref_dir(dir, dirname, len +1); 874free(dirname); 875 876if(pos >=0) { 877/* 878 * We found a directory named "refname". It is a 879 * problem iff it contains any ref that is not 880 * "oldrefname". 881 */ 882struct ref_entry *entry = dir->entries[pos]; 883struct ref_dir *dir =get_ref_dir(entry); 884struct nonmatching_ref_data data; 885 886 data.skip = oldrefname; 887sort_ref_dir(dir); 888if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 889return1; 890 891report_refname_conflict(data.found, refname); 892return0; 893} 894 895/* 896 * There is no point in searching for another leaf 897 * node which matches it; such an entry would be the 898 * ref we are looking for, not a conflict. 899 */ 900return1; 901} 902 903struct packed_ref_cache { 904struct ref_entry *root; 905 906/* 907 * Count of references to the data structure in this instance, 908 * including the pointer from ref_cache::packed if any. The 909 * data will not be freed as long as the reference count is 910 * nonzero. 911 */ 912unsigned int referrers; 913 914/* 915 * Iff the packed-refs file associated with this instance is 916 * currently locked for writing, this points at the associated 917 * lock (which is owned by somebody else). The referrer count 918 * is also incremented when the file is locked and decremented 919 * when it is unlocked. 920 */ 921struct lock_file *lock; 922 923/* The metadata from when this packed-refs cache was read */ 924struct stat_validity validity; 925}; 926 927/* 928 * Future: need to be in "struct repository" 929 * when doing a full libification. 930 */ 931static struct ref_cache { 932struct ref_cache *next; 933struct ref_entry *loose; 934struct packed_ref_cache *packed; 935/* 936 * The submodule name, or "" for the main repo. We allocate 937 * length 1 rather than FLEX_ARRAY so that the main ref_cache 938 * is initialized correctly. 939 */ 940char name[1]; 941} ref_cache, *submodule_ref_caches; 942 943/* Lock used for the main packed-refs file: */ 944static struct lock_file packlock; 945 946/* 947 * Increment the reference count of *packed_refs. 948 */ 949static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 950{ 951 packed_refs->referrers++; 952} 953 954/* 955 * Decrease the reference count of *packed_refs. If it goes to zero, 956 * free *packed_refs and return true; otherwise return false. 957 */ 958static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 959{ 960if(!--packed_refs->referrers) { 961free_ref_entry(packed_refs->root); 962stat_validity_clear(&packed_refs->validity); 963free(packed_refs); 964return1; 965}else{ 966return0; 967} 968} 969 970static voidclear_packed_ref_cache(struct ref_cache *refs) 971{ 972if(refs->packed) { 973struct packed_ref_cache *packed_refs = refs->packed; 974 975if(packed_refs->lock) 976die("internal error: packed-ref cache cleared while locked"); 977 refs->packed = NULL; 978release_packed_ref_cache(packed_refs); 979} 980} 981 982static voidclear_loose_ref_cache(struct ref_cache *refs) 983{ 984if(refs->loose) { 985free_ref_entry(refs->loose); 986 refs->loose = NULL; 987} 988} 989 990static struct ref_cache *create_ref_cache(const char*submodule) 991{ 992int len; 993struct ref_cache *refs; 994if(!submodule) 995 submodule =""; 996 len =strlen(submodule) +1; 997 refs =xcalloc(1,sizeof(struct ref_cache) + len); 998memcpy(refs->name, submodule, len); 999return refs;1000}10011002/*1003 * Return a pointer to a ref_cache for the specified submodule. For1004 * the main repository, use submodule==NULL. The returned structure1005 * will be allocated and initialized but not necessarily populated; it1006 * should not be freed.1007 */1008static struct ref_cache *get_ref_cache(const char*submodule)1009{1010struct ref_cache *refs;10111012if(!submodule || !*submodule)1013return&ref_cache;10141015for(refs = submodule_ref_caches; refs; refs = refs->next)1016if(!strcmp(submodule, refs->name))1017return refs;10181019 refs =create_ref_cache(submodule);1020 refs->next = submodule_ref_caches;1021 submodule_ref_caches = refs;1022return refs;1023}10241025/* The length of a peeled reference line in packed-refs, including EOL: */1026#define PEELED_LINE_LENGTH 4210271028/*1029 * The packed-refs header line that we write out. Perhaps other1030 * traits will be added later. The trailing space is required.1031 */1032static const char PACKED_REFS_HEADER[] =1033"# pack-refs with: peeled fully-peeled\n";10341035/*1036 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1037 * Return a pointer to the refname within the line (null-terminated),1038 * or NULL if there was a problem.1039 */1040static const char*parse_ref_line(char*line,unsigned char*sha1)1041{1042/*1043 * 42: the answer to everything.1044 *1045 * In this case, it happens to be the answer to1046 * 40 (length of sha1 hex representation)1047 * +1 (space in between hex and name)1048 * +1 (newline at the end of the line)1049 */1050int len =strlen(line) -42;10511052if(len <=0)1053return NULL;1054if(get_sha1_hex(line, sha1) <0)1055return NULL;1056if(!isspace(line[40]))1057return NULL;1058 line +=41;1059if(isspace(*line))1060return NULL;1061if(line[len] !='\n')1062return NULL;1063 line[len] =0;10641065return line;1066}10671068/*1069 * Read f, which is a packed-refs file, into dir.1070 *1071 * A comment line of the form "# pack-refs with: " may contain zero or1072 * more traits. We interpret the traits as follows:1073 *1074 * No traits:1075 *1076 * Probably no references are peeled. But if the file contains a1077 * peeled value for a reference, we will use it.1078 *1079 * peeled:1080 *1081 * References under "refs/tags/", if they *can* be peeled, *are*1082 * peeled in this file. References outside of "refs/tags/" are1083 * probably not peeled even if they could have been, but if we find1084 * a peeled value for such a reference we will use it.1085 *1086 * fully-peeled:1087 *1088 * All references in the file that can be peeled are peeled.1089 * Inversely (and this is more important), any references in the1090 * file for which no peeled value is recorded is not peelable. This1091 * trait should typically be written alongside "peeled" for1092 * compatibility with older clients, but we do not require it1093 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1094 */1095static voidread_packed_refs(FILE*f,struct ref_dir *dir)1096{1097struct ref_entry *last = NULL;1098char refline[PATH_MAX];1099enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11001101while(fgets(refline,sizeof(refline), f)) {1102unsigned char sha1[20];1103const char*refname;1104static const char header[] ="# pack-refs with:";11051106if(!strncmp(refline, header,sizeof(header)-1)) {1107const char*traits = refline +sizeof(header) -1;1108if(strstr(traits," fully-peeled "))1109 peeled = PEELED_FULLY;1110else if(strstr(traits," peeled "))1111 peeled = PEELED_TAGS;1112/* perhaps other traits later as well */1113continue;1114}11151116 refname =parse_ref_line(refline, sha1);1117if(refname) {1118 last =create_ref_entry(refname, sha1, REF_ISPACKED,1);1119if(peeled == PEELED_FULLY ||1120(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1121 last->flag |= REF_KNOWS_PEELED;1122add_ref(dir, last);1123continue;1124}1125if(last &&1126 refline[0] =='^'&&1127strlen(refline) == PEELED_LINE_LENGTH &&1128 refline[PEELED_LINE_LENGTH -1] =='\n'&&1129!get_sha1_hex(refline +1, sha1)) {1130hashcpy(last->u.value.peeled, sha1);1131/*1132 * Regardless of what the file header said,1133 * we definitely know the value of *this*1134 * reference:1135 */1136 last->flag |= REF_KNOWS_PEELED;1137}1138}1139}11401141/*1142 * Get the packed_ref_cache for the specified ref_cache, creating it1143 * if necessary.1144 */1145static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1146{1147const char*packed_refs_file;11481149if(*refs->name)1150 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1151else1152 packed_refs_file =git_path("packed-refs");11531154if(refs->packed &&1155!stat_validity_check(&refs->packed->validity, packed_refs_file))1156clear_packed_ref_cache(refs);11571158if(!refs->packed) {1159FILE*f;11601161 refs->packed =xcalloc(1,sizeof(*refs->packed));1162acquire_packed_ref_cache(refs->packed);1163 refs->packed->root =create_dir_entry(refs,"",0,0);1164 f =fopen(packed_refs_file,"r");1165if(f) {1166stat_validity_update(&refs->packed->validity,fileno(f));1167read_packed_refs(f,get_ref_dir(refs->packed->root));1168fclose(f);1169}1170}1171return refs->packed;1172}11731174static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1175{1176returnget_ref_dir(packed_ref_cache->root);1177}11781179static struct ref_dir *get_packed_refs(struct ref_cache *refs)1180{1181returnget_packed_ref_dir(get_packed_ref_cache(refs));1182}11831184voidadd_packed_ref(const char*refname,const unsigned char*sha1)1185{1186struct packed_ref_cache *packed_ref_cache =1187get_packed_ref_cache(&ref_cache);11881189if(!packed_ref_cache->lock)1190die("internal error: packed refs not locked");1191add_ref(get_packed_ref_dir(packed_ref_cache),1192create_ref_entry(refname, sha1, REF_ISPACKED,1));1193}11941195/*1196 * Read the loose references from the namespace dirname into dir1197 * (without recursing). dirname must end with '/'. dir must be the1198 * directory entry corresponding to dirname.1199 */1200static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1201{1202struct ref_cache *refs = dir->ref_cache;1203DIR*d;1204const char*path;1205struct dirent *de;1206int dirnamelen =strlen(dirname);1207struct strbuf refname;12081209if(*refs->name)1210 path =git_path_submodule(refs->name,"%s", dirname);1211else1212 path =git_path("%s", dirname);12131214 d =opendir(path);1215if(!d)1216return;12171218strbuf_init(&refname, dirnamelen +257);1219strbuf_add(&refname, dirname, dirnamelen);12201221while((de =readdir(d)) != NULL) {1222unsigned char sha1[20];1223struct stat st;1224int flag;1225const char*refdir;12261227if(de->d_name[0] =='.')1228continue;1229if(ends_with(de->d_name,".lock"))1230continue;1231strbuf_addstr(&refname, de->d_name);1232 refdir = *refs->name1233?git_path_submodule(refs->name,"%s", refname.buf)1234:git_path("%s", refname.buf);1235if(stat(refdir, &st) <0) {1236;/* silently ignore */1237}else if(S_ISDIR(st.st_mode)) {1238strbuf_addch(&refname,'/');1239add_entry_to_dir(dir,1240create_dir_entry(refs, refname.buf,1241 refname.len,1));1242}else{1243if(*refs->name) {1244hashclr(sha1);1245 flag =0;1246if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1247hashclr(sha1);1248 flag |= REF_ISBROKEN;1249}1250}else if(read_ref_full(refname.buf, sha1,1, &flag)) {1251hashclr(sha1);1252 flag |= REF_ISBROKEN;1253}1254add_entry_to_dir(dir,1255create_ref_entry(refname.buf, sha1, flag,1));1256}1257strbuf_setlen(&refname, dirnamelen);1258}1259strbuf_release(&refname);1260closedir(d);1261}12621263static struct ref_dir *get_loose_refs(struct ref_cache *refs)1264{1265if(!refs->loose) {1266/*1267 * Mark the top-level directory complete because we1268 * are about to read the only subdirectory that can1269 * hold references:1270 */1271 refs->loose =create_dir_entry(refs,"",0,0);1272/*1273 * Create an incomplete entry for "refs/":1274 */1275add_entry_to_dir(get_ref_dir(refs->loose),1276create_dir_entry(refs,"refs/",5,1));1277}1278returnget_ref_dir(refs->loose);1279}12801281/* We allow "recursive" symbolic refs. Only within reason, though */1282#define MAXDEPTH 51283#define MAXREFLEN (1024)12841285/*1286 * Called by resolve_gitlink_ref_recursive() after it failed to read1287 * from the loose refs in ref_cache refs. Find <refname> in the1288 * packed-refs file for the submodule.1289 */1290static intresolve_gitlink_packed_ref(struct ref_cache *refs,1291const char*refname,unsigned char*sha1)1292{1293struct ref_entry *ref;1294struct ref_dir *dir =get_packed_refs(refs);12951296 ref =find_ref(dir, refname);1297if(ref == NULL)1298return-1;12991300hashcpy(sha1, ref->u.value.sha1);1301return0;1302}13031304static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1305const char*refname,unsigned char*sha1,1306int recursion)1307{1308int fd, len;1309char buffer[128], *p;1310char*path;13111312if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1313return-1;1314 path = *refs->name1315?git_path_submodule(refs->name,"%s", refname)1316:git_path("%s", refname);1317 fd =open(path, O_RDONLY);1318if(fd <0)1319returnresolve_gitlink_packed_ref(refs, refname, sha1);13201321 len =read(fd, buffer,sizeof(buffer)-1);1322close(fd);1323if(len <0)1324return-1;1325while(len &&isspace(buffer[len-1]))1326 len--;1327 buffer[len] =0;13281329/* Was it a detached head or an old-fashioned symlink? */1330if(!get_sha1_hex(buffer, sha1))1331return0;13321333/* Symref? */1334if(strncmp(buffer,"ref:",4))1335return-1;1336 p = buffer +4;1337while(isspace(*p))1338 p++;13391340returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1341}13421343intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1344{1345int len =strlen(path), retval;1346char*submodule;1347struct ref_cache *refs;13481349while(len && path[len-1] =='/')1350 len--;1351if(!len)1352return-1;1353 submodule =xstrndup(path, len);1354 refs =get_ref_cache(submodule);1355free(submodule);13561357 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1358return retval;1359}13601361/*1362 * Return the ref_entry for the given refname from the packed1363 * references. If it does not exist, return NULL.1364 */1365static struct ref_entry *get_packed_ref(const char*refname)1366{1367returnfind_ref(get_packed_refs(&ref_cache), refname);1368}13691370/*1371 * A loose ref file doesn't exist; check for a packed ref. The1372 * options are forwarded from resolve_safe_unsafe().1373 */1374static const char*handle_missing_loose_ref(const char*refname,1375unsigned char*sha1,1376int reading,1377int*flag)1378{1379struct ref_entry *entry;13801381/*1382 * The loose reference file does not exist; check for a packed1383 * reference.1384 */1385 entry =get_packed_ref(refname);1386if(entry) {1387hashcpy(sha1, entry->u.value.sha1);1388if(flag)1389*flag |= REF_ISPACKED;1390return refname;1391}1392/* The reference is not a packed reference, either. */1393if(reading) {1394return NULL;1395}else{1396hashclr(sha1);1397return refname;1398}1399}14001401/* This function needs to return a meaningful errno on failure */1402const char*resolve_ref_unsafe(const char*refname,unsigned char*sha1,int reading,int*flag)1403{1404int depth = MAXDEPTH;1405 ssize_t len;1406char buffer[256];1407static char refname_buffer[256];14081409if(flag)1410*flag =0;14111412if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1413 errno = EINVAL;1414return NULL;1415}14161417for(;;) {1418char path[PATH_MAX];1419struct stat st;1420char*buf;1421int fd;14221423if(--depth <0) {1424 errno = ELOOP;1425return NULL;1426}14271428git_snpath(path,sizeof(path),"%s", refname);14291430/*1431 * We might have to loop back here to avoid a race1432 * condition: first we lstat() the file, then we try1433 * to read it as a link or as a file. But if somebody1434 * changes the type of the file (file <-> directory1435 * <-> symlink) between the lstat() and reading, then1436 * we don't want to report that as an error but rather1437 * try again starting with the lstat().1438 */1439 stat_ref:1440if(lstat(path, &st) <0) {1441if(errno == ENOENT)1442returnhandle_missing_loose_ref(refname, sha1,1443 reading, flag);1444else1445return NULL;1446}14471448/* Follow "normalized" - ie "refs/.." symlinks by hand */1449if(S_ISLNK(st.st_mode)) {1450 len =readlink(path, buffer,sizeof(buffer)-1);1451if(len <0) {1452if(errno == ENOENT || errno == EINVAL)1453/* inconsistent with lstat; retry */1454goto stat_ref;1455else1456return NULL;1457}1458 buffer[len] =0;1459if(starts_with(buffer,"refs/") &&1460!check_refname_format(buffer,0)) {1461strcpy(refname_buffer, buffer);1462 refname = refname_buffer;1463if(flag)1464*flag |= REF_ISSYMREF;1465continue;1466}1467}14681469/* Is it a directory? */1470if(S_ISDIR(st.st_mode)) {1471 errno = EISDIR;1472return NULL;1473}14741475/*1476 * Anything else, just open it and try to use it as1477 * a ref1478 */1479 fd =open(path, O_RDONLY);1480if(fd <0) {1481if(errno == ENOENT)1482/* inconsistent with lstat; retry */1483goto stat_ref;1484else1485return NULL;1486}1487 len =read_in_full(fd, buffer,sizeof(buffer)-1);1488if(len <0) {1489int save_errno = errno;1490close(fd);1491 errno = save_errno;1492return NULL;1493}1494close(fd);1495while(len &&isspace(buffer[len-1]))1496 len--;1497 buffer[len] ='\0';14981499/*1500 * Is it a symbolic ref?1501 */1502if(!starts_with(buffer,"ref:")) {1503/*1504 * Please note that FETCH_HEAD has a second1505 * line containing other data.1506 */1507if(get_sha1_hex(buffer, sha1) ||1508(buffer[40] !='\0'&& !isspace(buffer[40]))) {1509if(flag)1510*flag |= REF_ISBROKEN;1511 errno = EINVAL;1512return NULL;1513}1514return refname;1515}1516if(flag)1517*flag |= REF_ISSYMREF;1518 buf = buffer +4;1519while(isspace(*buf))1520 buf++;1521if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1522if(flag)1523*flag |= REF_ISBROKEN;1524 errno = EINVAL;1525return NULL;1526}1527 refname =strcpy(refname_buffer, buf);1528}1529}15301531char*resolve_refdup(const char*ref,unsigned char*sha1,int reading,int*flag)1532{1533const char*ret =resolve_ref_unsafe(ref, sha1, reading, flag);1534return ret ?xstrdup(ret) : NULL;1535}15361537/* The argument to filter_refs */1538struct ref_filter {1539const char*pattern;1540 each_ref_fn *fn;1541void*cb_data;1542};15431544intread_ref_full(const char*refname,unsigned char*sha1,int reading,int*flags)1545{1546if(resolve_ref_unsafe(refname, sha1, reading, flags))1547return0;1548return-1;1549}15501551intread_ref(const char*refname,unsigned char*sha1)1552{1553returnread_ref_full(refname, sha1,1, NULL);1554}15551556intref_exists(const char*refname)1557{1558unsigned char sha1[20];1559return!!resolve_ref_unsafe(refname, sha1,1, NULL);1560}15611562static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1563void*data)1564{1565struct ref_filter *filter = (struct ref_filter *)data;1566if(wildmatch(filter->pattern, refname,0, NULL))1567return0;1568return filter->fn(refname, sha1, flags, filter->cb_data);1569}15701571enum peel_status {1572/* object was peeled successfully: */1573 PEEL_PEELED =0,15741575/*1576 * object cannot be peeled because the named object (or an1577 * object referred to by a tag in the peel chain), does not1578 * exist.1579 */1580 PEEL_INVALID = -1,15811582/* object cannot be peeled because it is not a tag: */1583 PEEL_NON_TAG = -2,15841585/* ref_entry contains no peeled value because it is a symref: */1586 PEEL_IS_SYMREF = -3,15871588/*1589 * ref_entry cannot be peeled because it is broken (i.e., the1590 * symbolic reference cannot even be resolved to an object1591 * name):1592 */1593 PEEL_BROKEN = -41594};15951596/*1597 * Peel the named object; i.e., if the object is a tag, resolve the1598 * tag recursively until a non-tag is found. If successful, store the1599 * result to sha1 and return PEEL_PEELED. If the object is not a tag1600 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1601 * and leave sha1 unchanged.1602 */1603static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1604{1605struct object *o =lookup_unknown_object(name);16061607if(o->type == OBJ_NONE) {1608int type =sha1_object_info(name, NULL);1609if(type <0|| !object_as_type(o, type,0))1610return PEEL_INVALID;1611}16121613if(o->type != OBJ_TAG)1614return PEEL_NON_TAG;16151616 o =deref_tag_noverify(o);1617if(!o)1618return PEEL_INVALID;16191620hashcpy(sha1, o->sha1);1621return PEEL_PEELED;1622}16231624/*1625 * Peel the entry (if possible) and return its new peel_status. If1626 * repeel is true, re-peel the entry even if there is an old peeled1627 * value that is already stored in it.1628 *1629 * It is OK to call this function with a packed reference entry that1630 * might be stale and might even refer to an object that has since1631 * been garbage-collected. In such a case, if the entry has1632 * REF_KNOWS_PEELED then leave the status unchanged and return1633 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1634 */1635static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1636{1637enum peel_status status;16381639if(entry->flag & REF_KNOWS_PEELED) {1640if(repeel) {1641 entry->flag &= ~REF_KNOWS_PEELED;1642hashclr(entry->u.value.peeled);1643}else{1644returnis_null_sha1(entry->u.value.peeled) ?1645 PEEL_NON_TAG : PEEL_PEELED;1646}1647}1648if(entry->flag & REF_ISBROKEN)1649return PEEL_BROKEN;1650if(entry->flag & REF_ISSYMREF)1651return PEEL_IS_SYMREF;16521653 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1654if(status == PEEL_PEELED || status == PEEL_NON_TAG)1655 entry->flag |= REF_KNOWS_PEELED;1656return status;1657}16581659intpeel_ref(const char*refname,unsigned char*sha1)1660{1661int flag;1662unsigned char base[20];16631664if(current_ref && (current_ref->name == refname1665|| !strcmp(current_ref->name, refname))) {1666if(peel_entry(current_ref,0))1667return-1;1668hashcpy(sha1, current_ref->u.value.peeled);1669return0;1670}16711672if(read_ref_full(refname, base,1, &flag))1673return-1;16741675/*1676 * If the reference is packed, read its ref_entry from the1677 * cache in the hope that we already know its peeled value.1678 * We only try this optimization on packed references because1679 * (a) forcing the filling of the loose reference cache could1680 * be expensive and (b) loose references anyway usually do not1681 * have REF_KNOWS_PEELED.1682 */1683if(flag & REF_ISPACKED) {1684struct ref_entry *r =get_packed_ref(refname);1685if(r) {1686if(peel_entry(r,0))1687return-1;1688hashcpy(sha1, r->u.value.peeled);1689return0;1690}1691}16921693returnpeel_object(base, sha1);1694}16951696struct warn_if_dangling_data {1697FILE*fp;1698const char*refname;1699const struct string_list *refnames;1700const char*msg_fmt;1701};17021703static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1704int flags,void*cb_data)1705{1706struct warn_if_dangling_data *d = cb_data;1707const char*resolves_to;1708unsigned char junk[20];17091710if(!(flags & REF_ISSYMREF))1711return0;17121713 resolves_to =resolve_ref_unsafe(refname, junk,0, NULL);1714if(!resolves_to1715|| (d->refname1716?strcmp(resolves_to, d->refname)1717: !string_list_has_string(d->refnames, resolves_to))) {1718return0;1719}17201721fprintf(d->fp, d->msg_fmt, refname);1722fputc('\n', d->fp);1723return0;1724}17251726voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1727{1728struct warn_if_dangling_data data;17291730 data.fp = fp;1731 data.refname = refname;1732 data.refnames = NULL;1733 data.msg_fmt = msg_fmt;1734for_each_rawref(warn_if_dangling_symref, &data);1735}17361737voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1738{1739struct warn_if_dangling_data data;17401741 data.fp = fp;1742 data.refname = NULL;1743 data.refnames = refnames;1744 data.msg_fmt = msg_fmt;1745for_each_rawref(warn_if_dangling_symref, &data);1746}17471748/*1749 * Call fn for each reference in the specified ref_cache, omitting1750 * references not in the containing_dir of base. fn is called for all1751 * references, including broken ones. If fn ever returns a non-zero1752 * value, stop the iteration and return that value; otherwise, return1753 * 0.1754 */1755static intdo_for_each_entry(struct ref_cache *refs,const char*base,1756 each_ref_entry_fn fn,void*cb_data)1757{1758struct packed_ref_cache *packed_ref_cache;1759struct ref_dir *loose_dir;1760struct ref_dir *packed_dir;1761int retval =0;17621763/*1764 * We must make sure that all loose refs are read before accessing the1765 * packed-refs file; this avoids a race condition in which loose refs1766 * are migrated to the packed-refs file by a simultaneous process, but1767 * our in-memory view is from before the migration. get_packed_ref_cache()1768 * takes care of making sure our view is up to date with what is on1769 * disk.1770 */1771 loose_dir =get_loose_refs(refs);1772if(base && *base) {1773 loose_dir =find_containing_dir(loose_dir, base,0);1774}1775if(loose_dir)1776prime_ref_dir(loose_dir);17771778 packed_ref_cache =get_packed_ref_cache(refs);1779acquire_packed_ref_cache(packed_ref_cache);1780 packed_dir =get_packed_ref_dir(packed_ref_cache);1781if(base && *base) {1782 packed_dir =find_containing_dir(packed_dir, base,0);1783}17841785if(packed_dir && loose_dir) {1786sort_ref_dir(packed_dir);1787sort_ref_dir(loose_dir);1788 retval =do_for_each_entry_in_dirs(1789 packed_dir, loose_dir, fn, cb_data);1790}else if(packed_dir) {1791sort_ref_dir(packed_dir);1792 retval =do_for_each_entry_in_dir(1793 packed_dir,0, fn, cb_data);1794}else if(loose_dir) {1795sort_ref_dir(loose_dir);1796 retval =do_for_each_entry_in_dir(1797 loose_dir,0, fn, cb_data);1798}17991800release_packed_ref_cache(packed_ref_cache);1801return retval;1802}18031804/*1805 * Call fn for each reference in the specified ref_cache for which the1806 * refname begins with base. If trim is non-zero, then trim that many1807 * characters off the beginning of each refname before passing the1808 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1809 * broken references in the iteration. If fn ever returns a non-zero1810 * value, stop the iteration and return that value; otherwise, return1811 * 0.1812 */1813static intdo_for_each_ref(struct ref_cache *refs,const char*base,1814 each_ref_fn fn,int trim,int flags,void*cb_data)1815{1816struct ref_entry_cb data;1817 data.base = base;1818 data.trim = trim;1819 data.flags = flags;1820 data.fn = fn;1821 data.cb_data = cb_data;18221823returndo_for_each_entry(refs, base, do_one_ref, &data);1824}18251826static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1827{1828unsigned char sha1[20];1829int flag;18301831if(submodule) {1832if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1833returnfn("HEAD", sha1,0, cb_data);18341835return0;1836}18371838if(!read_ref_full("HEAD", sha1,1, &flag))1839returnfn("HEAD", sha1, flag, cb_data);18401841return0;1842}18431844inthead_ref(each_ref_fn fn,void*cb_data)1845{1846returndo_head_ref(NULL, fn, cb_data);1847}18481849inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1850{1851returndo_head_ref(submodule, fn, cb_data);1852}18531854intfor_each_ref(each_ref_fn fn,void*cb_data)1855{1856returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1857}18581859intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1860{1861returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1862}18631864intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1865{1866returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1867}18681869intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1870 each_ref_fn fn,void*cb_data)1871{1872returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1873}18741875intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1876{1877returnfor_each_ref_in("refs/tags/", fn, cb_data);1878}18791880intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1881{1882returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1883}18841885intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1886{1887returnfor_each_ref_in("refs/heads/", fn, cb_data);1888}18891890intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1891{1892returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1893}18941895intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1896{1897returnfor_each_ref_in("refs/remotes/", fn, cb_data);1898}18991900intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1901{1902returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);1903}19041905intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1906{1907returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);1908}19091910inthead_ref_namespaced(each_ref_fn fn,void*cb_data)1911{1912struct strbuf buf = STRBUF_INIT;1913int ret =0;1914unsigned char sha1[20];1915int flag;19161917strbuf_addf(&buf,"%sHEAD",get_git_namespace());1918if(!read_ref_full(buf.buf, sha1,1, &flag))1919 ret =fn(buf.buf, sha1, flag, cb_data);1920strbuf_release(&buf);19211922return ret;1923}19241925intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1926{1927struct strbuf buf = STRBUF_INIT;1928int ret;1929strbuf_addf(&buf,"%srefs/",get_git_namespace());1930 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);1931strbuf_release(&buf);1932return ret;1933}19341935intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,1936const char*prefix,void*cb_data)1937{1938struct strbuf real_pattern = STRBUF_INIT;1939struct ref_filter filter;1940int ret;19411942if(!prefix && !starts_with(pattern,"refs/"))1943strbuf_addstr(&real_pattern,"refs/");1944else if(prefix)1945strbuf_addstr(&real_pattern, prefix);1946strbuf_addstr(&real_pattern, pattern);19471948if(!has_glob_specials(pattern)) {1949/* Append implied '/' '*' if not present. */1950if(real_pattern.buf[real_pattern.len -1] !='/')1951strbuf_addch(&real_pattern,'/');1952/* No need to check for '*', there is none. */1953strbuf_addch(&real_pattern,'*');1954}19551956 filter.pattern = real_pattern.buf;1957 filter.fn = fn;1958 filter.cb_data = cb_data;1959 ret =for_each_ref(filter_refs, &filter);19601961strbuf_release(&real_pattern);1962return ret;1963}19641965intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)1966{1967returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);1968}19691970intfor_each_rawref(each_ref_fn fn,void*cb_data)1971{1972returndo_for_each_ref(&ref_cache,"", fn,0,1973 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1974}19751976const char*prettify_refname(const char*name)1977{1978return name + (1979starts_with(name,"refs/heads/") ?11:1980starts_with(name,"refs/tags/") ?10:1981starts_with(name,"refs/remotes/") ?13:19820);1983}19841985static const char*ref_rev_parse_rules[] = {1986"%.*s",1987"refs/%.*s",1988"refs/tags/%.*s",1989"refs/heads/%.*s",1990"refs/remotes/%.*s",1991"refs/remotes/%.*s/HEAD",1992 NULL1993};19941995intrefname_match(const char*abbrev_name,const char*full_name)1996{1997const char**p;1998const int abbrev_name_len =strlen(abbrev_name);19992000for(p = ref_rev_parse_rules; *p; p++) {2001if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2002return1;2003}2004}20052006return0;2007}20082009/* This function should make sure errno is meaningful on error */2010static struct ref_lock *verify_lock(struct ref_lock *lock,2011const unsigned char*old_sha1,int mustexist)2012{2013if(read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {2014int save_errno = errno;2015error("Can't verify ref%s", lock->ref_name);2016unlock_ref(lock);2017 errno = save_errno;2018return NULL;2019}2020if(hashcmp(lock->old_sha1, old_sha1)) {2021error("Ref%sis at%sbut expected%s", lock->ref_name,2022sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2023unlock_ref(lock);2024 errno = EBUSY;2025return NULL;2026}2027return lock;2028}20292030static intremove_empty_directories(const char*file)2031{2032/* we want to create a file but there is a directory there;2033 * if that is an empty directory (or a directory that contains2034 * only empty directories), remove them.2035 */2036struct strbuf path;2037int result, save_errno;20382039strbuf_init(&path,20);2040strbuf_addstr(&path, file);20412042 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2043 save_errno = errno;20442045strbuf_release(&path);2046 errno = save_errno;20472048return result;2049}20502051/*2052 * *string and *len will only be substituted, and *string returned (for2053 * later free()ing) if the string passed in is a magic short-hand form2054 * to name a branch.2055 */2056static char*substitute_branch_name(const char**string,int*len)2057{2058struct strbuf buf = STRBUF_INIT;2059int ret =interpret_branch_name(*string, *len, &buf);20602061if(ret == *len) {2062size_t size;2063*string =strbuf_detach(&buf, &size);2064*len = size;2065return(char*)*string;2066}20672068return NULL;2069}20702071intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2072{2073char*last_branch =substitute_branch_name(&str, &len);2074const char**p, *r;2075int refs_found =0;20762077*ref = NULL;2078for(p = ref_rev_parse_rules; *p; p++) {2079char fullref[PATH_MAX];2080unsigned char sha1_from_ref[20];2081unsigned char*this_result;2082int flag;20832084 this_result = refs_found ? sha1_from_ref : sha1;2085mksnpath(fullref,sizeof(fullref), *p, len, str);2086 r =resolve_ref_unsafe(fullref, this_result,1, &flag);2087if(r) {2088if(!refs_found++)2089*ref =xstrdup(r);2090if(!warn_ambiguous_refs)2091break;2092}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2093warning("ignoring dangling symref%s.", fullref);2094}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2095warning("ignoring broken ref%s.", fullref);2096}2097}2098free(last_branch);2099return refs_found;2100}21012102intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2103{2104char*last_branch =substitute_branch_name(&str, &len);2105const char**p;2106int logs_found =0;21072108*log = NULL;2109for(p = ref_rev_parse_rules; *p; p++) {2110unsigned char hash[20];2111char path[PATH_MAX];2112const char*ref, *it;21132114mksnpath(path,sizeof(path), *p, len, str);2115 ref =resolve_ref_unsafe(path, hash,1, NULL);2116if(!ref)2117continue;2118if(reflog_exists(path))2119 it = path;2120else if(strcmp(ref, path) &&reflog_exists(ref))2121 it = ref;2122else2123continue;2124if(!logs_found++) {2125*log =xstrdup(it);2126hashcpy(sha1, hash);2127}2128if(!warn_ambiguous_refs)2129break;2130}2131free(last_branch);2132return logs_found;2133}21342135/*2136 * Locks a "refs/" ref returning the lock on success and NULL on failure.2137 * On failure errno is set to something meaningful.2138 */2139static struct ref_lock *lock_ref_sha1_basic(const char*refname,2140const unsigned char*old_sha1,2141int flags,int*type_p)2142{2143char*ref_file;2144const char*orig_refname = refname;2145struct ref_lock *lock;2146int last_errno =0;2147int type, lflags;2148int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2149int missing =0;2150int attempts_remaining =3;21512152 lock =xcalloc(1,sizeof(struct ref_lock));2153 lock->lock_fd = -1;21542155 refname =resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);2156if(!refname && errno == EISDIR) {2157/* we are trying to lock foo but we used to2158 * have foo/bar which now does not exist;2159 * it is normal for the empty directory 'foo'2160 * to remain.2161 */2162 ref_file =git_path("%s", orig_refname);2163if(remove_empty_directories(ref_file)) {2164 last_errno = errno;2165error("there are still refs under '%s'", orig_refname);2166goto error_return;2167}2168 refname =resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);2169}2170if(type_p)2171*type_p = type;2172if(!refname) {2173 last_errno = errno;2174error("unable to resolve reference%s:%s",2175 orig_refname,strerror(errno));2176goto error_return;2177}2178 missing =is_null_sha1(lock->old_sha1);2179/* When the ref did not exist and we are creating it,2180 * make sure there is no existing ref that is packed2181 * whose name begins with our refname, nor a ref whose2182 * name is a proper prefix of our refname.2183 */2184if(missing &&2185!is_refname_available(refname, NULL,get_packed_refs(&ref_cache))) {2186 last_errno = ENOTDIR;2187goto error_return;2188}21892190 lock->lk =xcalloc(1,sizeof(struct lock_file));21912192 lflags =0;2193if(flags & REF_NODEREF) {2194 refname = orig_refname;2195 lflags |= LOCK_NODEREF;2196}2197 lock->ref_name =xstrdup(refname);2198 lock->orig_ref_name =xstrdup(orig_refname);2199 ref_file =git_path("%s", refname);2200if(missing)2201 lock->force_write =1;2202if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2203 lock->force_write =1;22042205 retry:2206switch(safe_create_leading_directories(ref_file)) {2207case SCLD_OK:2208break;/* success */2209case SCLD_VANISHED:2210if(--attempts_remaining >0)2211goto retry;2212/* fall through */2213default:2214 last_errno = errno;2215error("unable to create directory for%s", ref_file);2216goto error_return;2217}22182219 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2220if(lock->lock_fd <0) {2221if(errno == ENOENT && --attempts_remaining >0)2222/*2223 * Maybe somebody just deleted one of the2224 * directories leading to ref_file. Try2225 * again:2226 */2227goto retry;2228else2229unable_to_lock_die(ref_file, errno);2230}2231return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;22322233 error_return:2234unlock_ref(lock);2235 errno = last_errno;2236return NULL;2237}22382239struct ref_lock *lock_any_ref_for_update(const char*refname,2240const unsigned char*old_sha1,2241int flags,int*type_p)2242{2243if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))2244return NULL;2245returnlock_ref_sha1_basic(refname, old_sha1, flags, type_p);2246}22472248/*2249 * Write an entry to the packed-refs file for the specified refname.2250 * If peeled is non-NULL, write it as the entry's peeled value.2251 */2252static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2253unsigned char*peeled)2254{2255fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2256if(peeled)2257fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2258}22592260/*2261 * An each_ref_entry_fn that writes the entry to a packed-refs file.2262 */2263static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2264{2265enum peel_status peel_status =peel_entry(entry,0);22662267if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2268error("internal error:%sis not a valid packed reference!",2269 entry->name);2270write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2271 peel_status == PEEL_PEELED ?2272 entry->u.value.peeled : NULL);2273return0;2274}22752276/* This should return a meaningful errno on failure */2277intlock_packed_refs(int flags)2278{2279struct packed_ref_cache *packed_ref_cache;22802281if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2282return-1;2283/*2284 * Get the current packed-refs while holding the lock. If the2285 * packed-refs file has been modified since we last read it,2286 * this will automatically invalidate the cache and re-read2287 * the packed-refs file.2288 */2289 packed_ref_cache =get_packed_ref_cache(&ref_cache);2290 packed_ref_cache->lock = &packlock;2291/* Increment the reference count to prevent it from being freed: */2292acquire_packed_ref_cache(packed_ref_cache);2293return0;2294}22952296/*2297 * Commit the packed refs changes.2298 * On error we must make sure that errno contains a meaningful value.2299 */2300intcommit_packed_refs(void)2301{2302struct packed_ref_cache *packed_ref_cache =2303get_packed_ref_cache(&ref_cache);2304int error =0;2305int save_errno =0;2306FILE*out;23072308if(!packed_ref_cache->lock)2309die("internal error: packed-refs not locked");23102311 out =fdopen(packed_ref_cache->lock->fd,"w");2312if(!out)2313die_errno("unable to fdopen packed-refs descriptor");23142315fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2316do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),23170, write_packed_entry_fn, out);2318if(fclose(out))2319die_errno("write error");2320 packed_ref_cache->lock->fd = -1;23212322if(commit_lock_file(packed_ref_cache->lock)) {2323 save_errno = errno;2324 error = -1;2325}2326 packed_ref_cache->lock = NULL;2327release_packed_ref_cache(packed_ref_cache);2328 errno = save_errno;2329return error;2330}23312332voidrollback_packed_refs(void)2333{2334struct packed_ref_cache *packed_ref_cache =2335get_packed_ref_cache(&ref_cache);23362337if(!packed_ref_cache->lock)2338die("internal error: packed-refs not locked");2339rollback_lock_file(packed_ref_cache->lock);2340 packed_ref_cache->lock = NULL;2341release_packed_ref_cache(packed_ref_cache);2342clear_packed_ref_cache(&ref_cache);2343}23442345struct ref_to_prune {2346struct ref_to_prune *next;2347unsigned char sha1[20];2348char name[FLEX_ARRAY];2349};23502351struct pack_refs_cb_data {2352unsigned int flags;2353struct ref_dir *packed_refs;2354struct ref_to_prune *ref_to_prune;2355};23562357/*2358 * An each_ref_entry_fn that is run over loose references only. If2359 * the loose reference can be packed, add an entry in the packed ref2360 * cache. If the reference should be pruned, also add it to2361 * ref_to_prune in the pack_refs_cb_data.2362 */2363static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2364{2365struct pack_refs_cb_data *cb = cb_data;2366enum peel_status peel_status;2367struct ref_entry *packed_entry;2368int is_tag_ref =starts_with(entry->name,"refs/tags/");23692370/* ALWAYS pack tags */2371if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2372return0;23732374/* Do not pack symbolic or broken refs: */2375if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2376return0;23772378/* Add a packed ref cache entry equivalent to the loose entry. */2379 peel_status =peel_entry(entry,1);2380if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2381die("internal error peeling reference%s(%s)",2382 entry->name,sha1_to_hex(entry->u.value.sha1));2383 packed_entry =find_ref(cb->packed_refs, entry->name);2384if(packed_entry) {2385/* Overwrite existing packed entry with info from loose entry */2386 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2387hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2388}else{2389 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2390 REF_ISPACKED | REF_KNOWS_PEELED,0);2391add_ref(cb->packed_refs, packed_entry);2392}2393hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);23942395/* Schedule the loose reference for pruning if requested. */2396if((cb->flags & PACK_REFS_PRUNE)) {2397int namelen =strlen(entry->name) +1;2398struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2399hashcpy(n->sha1, entry->u.value.sha1);2400strcpy(n->name, entry->name);2401 n->next = cb->ref_to_prune;2402 cb->ref_to_prune = n;2403}2404return0;2405}24062407/*2408 * Remove empty parents, but spare refs/ and immediate subdirs.2409 * Note: munges *name.2410 */2411static voidtry_remove_empty_parents(char*name)2412{2413char*p, *q;2414int i;2415 p = name;2416for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2417while(*p && *p !='/')2418 p++;2419/* tolerate duplicate slashes; see check_refname_format() */2420while(*p =='/')2421 p++;2422}2423for(q = p; *q; q++)2424;2425while(1) {2426while(q > p && *q !='/')2427 q--;2428while(q > p && *(q-1) =='/')2429 q--;2430if(q == p)2431break;2432*q ='\0';2433if(rmdir(git_path("%s", name)))2434break;2435}2436}24372438/* make sure nobody touched the ref, and unlink */2439static voidprune_ref(struct ref_to_prune *r)2440{2441struct ref_transaction *transaction;2442struct strbuf err = STRBUF_INIT;24432444if(check_refname_format(r->name,0))2445return;24462447 transaction =ref_transaction_begin(&err);2448if(!transaction ||2449ref_transaction_delete(transaction, r->name, r->sha1,2450 REF_ISPRUNING,1, &err) ||2451ref_transaction_commit(transaction, NULL, &err)) {2452ref_transaction_free(transaction);2453error("%s", err.buf);2454strbuf_release(&err);2455return;2456}2457ref_transaction_free(transaction);2458strbuf_release(&err);2459try_remove_empty_parents(r->name);2460}24612462static voidprune_refs(struct ref_to_prune *r)2463{2464while(r) {2465prune_ref(r);2466 r = r->next;2467}2468}24692470intpack_refs(unsigned int flags)2471{2472struct pack_refs_cb_data cbdata;24732474memset(&cbdata,0,sizeof(cbdata));2475 cbdata.flags = flags;24762477lock_packed_refs(LOCK_DIE_ON_ERROR);2478 cbdata.packed_refs =get_packed_refs(&ref_cache);24792480do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2481 pack_if_possible_fn, &cbdata);24822483if(commit_packed_refs())2484die_errno("unable to overwrite old ref-pack file");24852486prune_refs(cbdata.ref_to_prune);2487return0;2488}24892490/*2491 * If entry is no longer needed in packed-refs, add it to the string2492 * list pointed to by cb_data. Reasons for deleting entries:2493 *2494 * - Entry is broken.2495 * - Entry is overridden by a loose ref.2496 * - Entry does not point at a valid object.2497 *2498 * In the first and third cases, also emit an error message because these2499 * are indications of repository corruption.2500 */2501static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2502{2503struct string_list *refs_to_delete = cb_data;25042505if(entry->flag & REF_ISBROKEN) {2506/* This shouldn't happen to packed refs. */2507error("%sis broken!", entry->name);2508string_list_append(refs_to_delete, entry->name);2509return0;2510}2511if(!has_sha1_file(entry->u.value.sha1)) {2512unsigned char sha1[20];2513int flags;25142515if(read_ref_full(entry->name, sha1,0, &flags))2516/* We should at least have found the packed ref. */2517die("Internal error");2518if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2519/*2520 * This packed reference is overridden by a2521 * loose reference, so it is OK that its value2522 * is no longer valid; for example, it might2523 * refer to an object that has been garbage2524 * collected. For this purpose we don't even2525 * care whether the loose reference itself is2526 * invalid, broken, symbolic, etc. Silently2527 * remove the packed reference.2528 */2529string_list_append(refs_to_delete, entry->name);2530return0;2531}2532/*2533 * There is no overriding loose reference, so the fact2534 * that this reference doesn't refer to a valid object2535 * indicates some kind of repository corruption.2536 * Report the problem, then omit the reference from2537 * the output.2538 */2539error("%sdoes not point to a valid object!", entry->name);2540string_list_append(refs_to_delete, entry->name);2541return0;2542}25432544return0;2545}25462547intrepack_without_refs(const char**refnames,int n,struct strbuf *err)2548{2549struct ref_dir *packed;2550struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2551struct string_list_item *ref_to_delete;2552int i, ret, removed =0;25532554/* Look for a packed ref */2555for(i =0; i < n; i++)2556if(get_packed_ref(refnames[i]))2557break;25582559/* Avoid locking if we have nothing to do */2560if(i == n)2561return0;/* no refname exists in packed refs */25622563if(lock_packed_refs(0)) {2564if(err) {2565unable_to_lock_message(git_path("packed-refs"), errno,2566 err);2567return-1;2568}2569unable_to_lock_error(git_path("packed-refs"), errno);2570returnerror("cannot delete '%s' from packed refs", refnames[i]);2571}2572 packed =get_packed_refs(&ref_cache);25732574/* Remove refnames from the cache */2575for(i =0; i < n; i++)2576if(remove_entry(packed, refnames[i]) != -1)2577 removed =1;2578if(!removed) {2579/*2580 * All packed entries disappeared while we were2581 * acquiring the lock.2582 */2583rollback_packed_refs();2584return0;2585}25862587/* Remove any other accumulated cruft */2588do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2589for_each_string_list_item(ref_to_delete, &refs_to_delete) {2590if(remove_entry(packed, ref_to_delete->string) == -1)2591die("internal error");2592}25932594/* Write what remains */2595 ret =commit_packed_refs();2596if(ret && err)2597strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2598strerror(errno));2599return ret;2600}26012602static intdelete_ref_loose(struct ref_lock *lock,int flag)2603{2604if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2605/*2606 * loose. The loose file name is the same as the2607 * lockfile name, minus ".lock":2608 */2609char*loose_filename =xmemdupz(2610 lock->lk->filename,2611strlen(lock->lk->filename) - LOCK_SUFFIX_LEN);2612int err =unlink_or_warn(loose_filename);2613free(loose_filename);2614if(err && errno != ENOENT)2615return1;2616}2617return0;2618}26192620intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2621{2622struct ref_transaction *transaction;2623struct strbuf err = STRBUF_INIT;26242625 transaction =ref_transaction_begin(&err);2626if(!transaction ||2627ref_transaction_delete(transaction, refname, sha1, delopt,2628 sha1 && !is_null_sha1(sha1), &err) ||2629ref_transaction_commit(transaction, NULL, &err)) {2630error("%s", err.buf);2631ref_transaction_free(transaction);2632strbuf_release(&err);2633return1;2634}2635ref_transaction_free(transaction);2636strbuf_release(&err);2637return0;2638}26392640/*2641 * People using contrib's git-new-workdir have .git/logs/refs ->2642 * /some/other/path/.git/logs/refs, and that may live on another device.2643 *2644 * IOW, to avoid cross device rename errors, the temporary renamed log must2645 * live into logs/refs.2646 */2647#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"26482649static intrename_tmp_log(const char*newrefname)2650{2651int attempts_remaining =4;26522653 retry:2654switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2655case SCLD_OK:2656break;/* success */2657case SCLD_VANISHED:2658if(--attempts_remaining >0)2659goto retry;2660/* fall through */2661default:2662error("unable to create directory for%s", newrefname);2663return-1;2664}26652666if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2667if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2668/*2669 * rename(a, b) when b is an existing2670 * directory ought to result in ISDIR, but2671 * Solaris 5.8 gives ENOTDIR. Sheesh.2672 */2673if(remove_empty_directories(git_path("logs/%s", newrefname))) {2674error("Directory not empty: logs/%s", newrefname);2675return-1;2676}2677goto retry;2678}else if(errno == ENOENT && --attempts_remaining >0) {2679/*2680 * Maybe another process just deleted one of2681 * the directories in the path to newrefname.2682 * Try again from the beginning.2683 */2684goto retry;2685}else{2686error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2687 newrefname,strerror(errno));2688return-1;2689}2690}2691return0;2692}26932694intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2695{2696unsigned char sha1[20], orig_sha1[20];2697int flag =0, logmoved =0;2698struct ref_lock *lock;2699struct stat loginfo;2700int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2701const char*symref = NULL;27022703if(log &&S_ISLNK(loginfo.st_mode))2704returnerror("reflog for%sis a symlink", oldrefname);27052706 symref =resolve_ref_unsafe(oldrefname, orig_sha1,1, &flag);2707if(flag & REF_ISSYMREF)2708returnerror("refname%sis a symbolic ref, renaming it is not supported",2709 oldrefname);2710if(!symref)2711returnerror("refname%snot found", oldrefname);27122713if(!is_refname_available(newrefname, oldrefname,get_packed_refs(&ref_cache)))2714return1;27152716if(!is_refname_available(newrefname, oldrefname,get_loose_refs(&ref_cache)))2717return1;27182719if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2720returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2721 oldrefname,strerror(errno));27222723if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2724error("unable to delete old%s", oldrefname);2725goto rollback;2726}27272728if(!read_ref_full(newrefname, sha1,1, &flag) &&2729delete_ref(newrefname, sha1, REF_NODEREF)) {2730if(errno==EISDIR) {2731if(remove_empty_directories(git_path("%s", newrefname))) {2732error("Directory not empty:%s", newrefname);2733goto rollback;2734}2735}else{2736error("unable to delete existing%s", newrefname);2737goto rollback;2738}2739}27402741if(log &&rename_tmp_log(newrefname))2742goto rollback;27432744 logmoved = log;27452746 lock =lock_ref_sha1_basic(newrefname, NULL,0, NULL);2747if(!lock) {2748error("unable to lock%sfor update", newrefname);2749goto rollback;2750}2751 lock->force_write =1;2752hashcpy(lock->old_sha1, orig_sha1);2753if(write_ref_sha1(lock, orig_sha1, logmsg)) {2754error("unable to write current sha1 into%s", newrefname);2755goto rollback;2756}27572758return0;27592760 rollback:2761 lock =lock_ref_sha1_basic(oldrefname, NULL,0, NULL);2762if(!lock) {2763error("unable to lock%sfor rollback", oldrefname);2764goto rollbacklog;2765}27662767 lock->force_write =1;2768 flag = log_all_ref_updates;2769 log_all_ref_updates =0;2770if(write_ref_sha1(lock, orig_sha1, NULL))2771error("unable to write current sha1 into%s", oldrefname);2772 log_all_ref_updates = flag;27732774 rollbacklog:2775if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2776error("unable to restore logfile%sfrom%s:%s",2777 oldrefname, newrefname,strerror(errno));2778if(!logmoved && log &&2779rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2780error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2781 oldrefname,strerror(errno));27822783return1;2784}27852786intclose_ref(struct ref_lock *lock)2787{2788if(close_lock_file(lock->lk))2789return-1;2790 lock->lock_fd = -1;2791return0;2792}27932794intcommit_ref(struct ref_lock *lock)2795{2796if(commit_lock_file(lock->lk))2797return-1;2798 lock->lock_fd = -1;2799return0;2800}28012802voidunlock_ref(struct ref_lock *lock)2803{2804/* Do not free lock->lk -- atexit() still looks at them */2805if(lock->lk)2806rollback_lock_file(lock->lk);2807free(lock->ref_name);2808free(lock->orig_ref_name);2809free(lock);2810}28112812/*2813 * copy the reflog message msg to buf, which has been allocated sufficiently2814 * large, while cleaning up the whitespaces. Especially, convert LF to space,2815 * because reflog file is one line per entry.2816 */2817static intcopy_msg(char*buf,const char*msg)2818{2819char*cp = buf;2820char c;2821int wasspace =1;28222823*cp++ ='\t';2824while((c = *msg++)) {2825if(wasspace &&isspace(c))2826continue;2827 wasspace =isspace(c);2828if(wasspace)2829 c =' ';2830*cp++ = c;2831}2832while(buf < cp &&isspace(cp[-1]))2833 cp--;2834*cp++ ='\n';2835return cp - buf;2836}28372838/* This function must set a meaningful errno on failure */2839intlog_ref_setup(const char*refname,char*logfile,int bufsize)2840{2841int logfd, oflags = O_APPEND | O_WRONLY;28422843git_snpath(logfile, bufsize,"logs/%s", refname);2844if(log_all_ref_updates &&2845(starts_with(refname,"refs/heads/") ||2846starts_with(refname,"refs/remotes/") ||2847starts_with(refname,"refs/notes/") ||2848!strcmp(refname,"HEAD"))) {2849if(safe_create_leading_directories(logfile) <0) {2850int save_errno = errno;2851error("unable to create directory for%s", logfile);2852 errno = save_errno;2853return-1;2854}2855 oflags |= O_CREAT;2856}28572858 logfd =open(logfile, oflags,0666);2859if(logfd <0) {2860if(!(oflags & O_CREAT) && errno == ENOENT)2861return0;28622863if((oflags & O_CREAT) && errno == EISDIR) {2864if(remove_empty_directories(logfile)) {2865int save_errno = errno;2866error("There are still logs under '%s'",2867 logfile);2868 errno = save_errno;2869return-1;2870}2871 logfd =open(logfile, oflags,0666);2872}28732874if(logfd <0) {2875int save_errno = errno;2876error("Unable to append to%s:%s", logfile,2877strerror(errno));2878 errno = save_errno;2879return-1;2880}2881}28822883adjust_shared_perm(logfile);2884close(logfd);2885return0;2886}28872888static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2889const unsigned char*new_sha1,const char*msg)2890{2891int logfd, result, written, oflags = O_APPEND | O_WRONLY;2892unsigned maxlen, len;2893int msglen;2894char log_file[PATH_MAX];2895char*logrec;2896const char*committer;28972898if(log_all_ref_updates <0)2899 log_all_ref_updates = !is_bare_repository();29002901 result =log_ref_setup(refname, log_file,sizeof(log_file));2902if(result)2903return result;29042905 logfd =open(log_file, oflags);2906if(logfd <0)2907return0;2908 msglen = msg ?strlen(msg) :0;2909 committer =git_committer_info(0);2910 maxlen =strlen(committer) + msglen +100;2911 logrec =xmalloc(maxlen);2912 len =sprintf(logrec,"%s %s %s\n",2913sha1_to_hex(old_sha1),2914sha1_to_hex(new_sha1),2915 committer);2916if(msglen)2917 len +=copy_msg(logrec + len -1, msg) -1;2918 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;2919free(logrec);2920if(written != len) {2921int save_errno = errno;2922close(logfd);2923error("Unable to append to%s", log_file);2924 errno = save_errno;2925return-1;2926}2927if(close(logfd)) {2928int save_errno = errno;2929error("Unable to append to%s", log_file);2930 errno = save_errno;2931return-1;2932}2933return0;2934}29352936intis_branch(const char*refname)2937{2938return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");2939}29402941/* This function must return a meaningful errno */2942intwrite_ref_sha1(struct ref_lock *lock,2943const unsigned char*sha1,const char*logmsg)2944{2945static char term ='\n';2946struct object *o;29472948if(!lock) {2949 errno = EINVAL;2950return-1;2951}2952if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {2953unlock_ref(lock);2954return0;2955}2956 o =parse_object(sha1);2957if(!o) {2958error("Trying to write ref%swith nonexistent object%s",2959 lock->ref_name,sha1_to_hex(sha1));2960unlock_ref(lock);2961 errno = EINVAL;2962return-1;2963}2964if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2965error("Trying to write non-commit object%sto branch%s",2966sha1_to_hex(sha1), lock->ref_name);2967unlock_ref(lock);2968 errno = EINVAL;2969return-1;2970}2971if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||2972write_in_full(lock->lock_fd, &term,1) !=1||2973close_ref(lock) <0) {2974int save_errno = errno;2975error("Couldn't write%s", lock->lk->filename);2976unlock_ref(lock);2977 errno = save_errno;2978return-1;2979}2980clear_loose_ref_cache(&ref_cache);2981if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||2982(strcmp(lock->ref_name, lock->orig_ref_name) &&2983log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {2984unlock_ref(lock);2985return-1;2986}2987if(strcmp(lock->orig_ref_name,"HEAD") !=0) {2988/*2989 * Special hack: If a branch is updated directly and HEAD2990 * points to it (may happen on the remote side of a push2991 * for example) then logically the HEAD reflog should be2992 * updated too.2993 * A generic solution implies reverse symref information,2994 * but finding all symrefs pointing to the given branch2995 * would be rather costly for this rare event (the direct2996 * update of a branch) to be worth it. So let's cheat and2997 * check with HEAD only which should cover 99% of all usage2998 * scenarios (even 100% of the default ones).2999 */3000unsigned char head_sha1[20];3001int head_flag;3002const char*head_ref;3003 head_ref =resolve_ref_unsafe("HEAD", head_sha1,1, &head_flag);3004if(head_ref && (head_flag & REF_ISSYMREF) &&3005!strcmp(head_ref, lock->ref_name))3006log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3007}3008if(commit_ref(lock)) {3009error("Couldn't set%s", lock->ref_name);3010unlock_ref(lock);3011return-1;3012}3013unlock_ref(lock);3014return0;3015}30163017intcreate_symref(const char*ref_target,const char*refs_heads_master,3018const char*logmsg)3019{3020const char*lockpath;3021char ref[1000];3022int fd, len, written;3023char*git_HEAD =git_pathdup("%s", ref_target);3024unsigned char old_sha1[20], new_sha1[20];30253026if(logmsg &&read_ref(ref_target, old_sha1))3027hashclr(old_sha1);30283029if(safe_create_leading_directories(git_HEAD) <0)3030returnerror("unable to create directory for%s", git_HEAD);30313032#ifndef NO_SYMLINK_HEAD3033if(prefer_symlink_refs) {3034unlink(git_HEAD);3035if(!symlink(refs_heads_master, git_HEAD))3036goto done;3037fprintf(stderr,"no symlink - falling back to symbolic ref\n");3038}3039#endif30403041 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3042if(sizeof(ref) <= len) {3043error("refname too long:%s", refs_heads_master);3044goto error_free_return;3045}3046 lockpath =mkpath("%s.lock", git_HEAD);3047 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3048if(fd <0) {3049error("Unable to open%sfor writing", lockpath);3050goto error_free_return;3051}3052 written =write_in_full(fd, ref, len);3053if(close(fd) !=0|| written != len) {3054error("Unable to write to%s", lockpath);3055goto error_unlink_return;3056}3057if(rename(lockpath, git_HEAD) <0) {3058error("Unable to create%s", git_HEAD);3059goto error_unlink_return;3060}3061if(adjust_shared_perm(git_HEAD)) {3062error("Unable to fix permissions on%s", lockpath);3063 error_unlink_return:3064unlink_or_warn(lockpath);3065 error_free_return:3066free(git_HEAD);3067return-1;3068}30693070#ifndef NO_SYMLINK_HEAD3071 done:3072#endif3073if(logmsg && !read_ref(refs_heads_master, new_sha1))3074log_ref_write(ref_target, old_sha1, new_sha1, logmsg);30753076free(git_HEAD);3077return0;3078}30793080struct read_ref_at_cb {3081const char*refname;3082unsigned long at_time;3083int cnt;3084int reccnt;3085unsigned char*sha1;3086int found_it;30873088unsigned char osha1[20];3089unsigned char nsha1[20];3090int tz;3091unsigned long date;3092char**msg;3093unsigned long*cutoff_time;3094int*cutoff_tz;3095int*cutoff_cnt;3096};30973098static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3099const char*email,unsigned long timestamp,int tz,3100const char*message,void*cb_data)3101{3102struct read_ref_at_cb *cb = cb_data;31033104 cb->reccnt++;3105 cb->tz = tz;3106 cb->date = timestamp;31073108if(timestamp <= cb->at_time || cb->cnt ==0) {3109if(cb->msg)3110*cb->msg =xstrdup(message);3111if(cb->cutoff_time)3112*cb->cutoff_time = timestamp;3113if(cb->cutoff_tz)3114*cb->cutoff_tz = tz;3115if(cb->cutoff_cnt)3116*cb->cutoff_cnt = cb->reccnt -1;3117/*3118 * we have not yet updated cb->[n|o]sha1 so they still3119 * hold the values for the previous record.3120 */3121if(!is_null_sha1(cb->osha1)) {3122hashcpy(cb->sha1, nsha1);3123if(hashcmp(cb->osha1, nsha1))3124warning("Log for ref%shas gap after%s.",3125 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3126}3127else if(cb->date == cb->at_time)3128hashcpy(cb->sha1, nsha1);3129else if(hashcmp(nsha1, cb->sha1))3130warning("Log for ref%sunexpectedly ended on%s.",3131 cb->refname,show_date(cb->date, cb->tz,3132 DATE_RFC2822));3133hashcpy(cb->osha1, osha1);3134hashcpy(cb->nsha1, nsha1);3135 cb->found_it =1;3136return1;3137}3138hashcpy(cb->osha1, osha1);3139hashcpy(cb->nsha1, nsha1);3140if(cb->cnt >0)3141 cb->cnt--;3142return0;3143}31443145static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3146const char*email,unsigned long timestamp,3147int tz,const char*message,void*cb_data)3148{3149struct read_ref_at_cb *cb = cb_data;31503151if(cb->msg)3152*cb->msg =xstrdup(message);3153if(cb->cutoff_time)3154*cb->cutoff_time = timestamp;3155if(cb->cutoff_tz)3156*cb->cutoff_tz = tz;3157if(cb->cutoff_cnt)3158*cb->cutoff_cnt = cb->reccnt;3159hashcpy(cb->sha1, osha1);3160if(is_null_sha1(cb->sha1))3161hashcpy(cb->sha1, nsha1);3162/* We just want the first entry */3163return1;3164}31653166intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3167unsigned char*sha1,char**msg,3168unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3169{3170struct read_ref_at_cb cb;31713172memset(&cb,0,sizeof(cb));3173 cb.refname = refname;3174 cb.at_time = at_time;3175 cb.cnt = cnt;3176 cb.msg = msg;3177 cb.cutoff_time = cutoff_time;3178 cb.cutoff_tz = cutoff_tz;3179 cb.cutoff_cnt = cutoff_cnt;3180 cb.sha1 = sha1;31813182for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);31833184if(!cb.reccnt) {3185if(flags & GET_SHA1_QUIETLY)3186exit(128);3187else3188die("Log for%sis empty.", refname);3189}3190if(cb.found_it)3191return0;31923193for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);31943195return1;3196}31973198intreflog_exists(const char*refname)3199{3200struct stat st;32013202return!lstat(git_path("logs/%s", refname), &st) &&3203S_ISREG(st.st_mode);3204}32053206intdelete_reflog(const char*refname)3207{3208returnremove_path(git_path("logs/%s", refname));3209}32103211static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3212{3213unsigned char osha1[20], nsha1[20];3214char*email_end, *message;3215unsigned long timestamp;3216int tz;32173218/* old SP new SP name <email> SP time TAB msg LF */3219if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3220get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3221get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3222!(email_end =strchr(sb->buf +82,'>')) ||3223 email_end[1] !=' '||3224!(timestamp =strtoul(email_end +2, &message,10)) ||3225!message || message[0] !=' '||3226(message[1] !='+'&& message[1] !='-') ||3227!isdigit(message[2]) || !isdigit(message[3]) ||3228!isdigit(message[4]) || !isdigit(message[5]))3229return0;/* corrupt? */3230 email_end[1] ='\0';3231 tz =strtol(message +1, NULL,10);3232if(message[6] !='\t')3233 message +=6;3234else3235 message +=7;3236returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3237}32383239static char*find_beginning_of_line(char*bob,char*scan)3240{3241while(bob < scan && *(--scan) !='\n')3242;/* keep scanning backwards */3243/*3244 * Return either beginning of the buffer, or LF at the end of3245 * the previous line.3246 */3247return scan;3248}32493250intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3251{3252struct strbuf sb = STRBUF_INIT;3253FILE*logfp;3254long pos;3255int ret =0, at_tail =1;32563257 logfp =fopen(git_path("logs/%s", refname),"r");3258if(!logfp)3259return-1;32603261/* Jump to the end */3262if(fseek(logfp,0, SEEK_END) <0)3263returnerror("cannot seek back reflog for%s:%s",3264 refname,strerror(errno));3265 pos =ftell(logfp);3266while(!ret &&0< pos) {3267int cnt;3268size_t nread;3269char buf[BUFSIZ];3270char*endp, *scanp;32713272/* Fill next block from the end */3273 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3274if(fseek(logfp, pos - cnt, SEEK_SET))3275returnerror("cannot seek back reflog for%s:%s",3276 refname,strerror(errno));3277 nread =fread(buf, cnt,1, logfp);3278if(nread !=1)3279returnerror("cannot read%dbytes from reflog for%s:%s",3280 cnt, refname,strerror(errno));3281 pos -= cnt;32823283 scanp = endp = buf + cnt;3284if(at_tail && scanp[-1] =='\n')3285/* Looking at the final LF at the end of the file */3286 scanp--;3287 at_tail =0;32883289while(buf < scanp) {3290/*3291 * terminating LF of the previous line, or the beginning3292 * of the buffer.3293 */3294char*bp;32953296 bp =find_beginning_of_line(buf, scanp);32973298if(*bp !='\n') {3299strbuf_splice(&sb,0,0, buf, endp - buf);3300if(pos)3301break;/* need to fill another block */3302 scanp = buf -1;/* leave loop */3303}else{3304/*3305 * (bp + 1) thru endp is the beginning of the3306 * current line we have in sb3307 */3308strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3309 scanp = bp;3310 endp = bp +1;3311}3312 ret =show_one_reflog_ent(&sb, fn, cb_data);3313strbuf_reset(&sb);3314if(ret)3315break;3316}33173318}3319if(!ret && sb.len)3320 ret =show_one_reflog_ent(&sb, fn, cb_data);33213322fclose(logfp);3323strbuf_release(&sb);3324return ret;3325}33263327intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3328{3329FILE*logfp;3330struct strbuf sb = STRBUF_INIT;3331int ret =0;33323333 logfp =fopen(git_path("logs/%s", refname),"r");3334if(!logfp)3335return-1;33363337while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3338 ret =show_one_reflog_ent(&sb, fn, cb_data);3339fclose(logfp);3340strbuf_release(&sb);3341return ret;3342}3343/*3344 * Call fn for each reflog in the namespace indicated by name. name3345 * must be empty or end with '/'. Name will be used as a scratch3346 * space, but its contents will be restored before return.3347 */3348static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3349{3350DIR*d =opendir(git_path("logs/%s", name->buf));3351int retval =0;3352struct dirent *de;3353int oldlen = name->len;33543355if(!d)3356return name->len ? errno :0;33573358while((de =readdir(d)) != NULL) {3359struct stat st;33603361if(de->d_name[0] =='.')3362continue;3363if(ends_with(de->d_name,".lock"))3364continue;3365strbuf_addstr(name, de->d_name);3366if(stat(git_path("logs/%s", name->buf), &st) <0) {3367;/* silently ignore */3368}else{3369if(S_ISDIR(st.st_mode)) {3370strbuf_addch(name,'/');3371 retval =do_for_each_reflog(name, fn, cb_data);3372}else{3373unsigned char sha1[20];3374if(read_ref_full(name->buf, sha1,0, NULL))3375 retval =error("bad ref for%s", name->buf);3376else3377 retval =fn(name->buf, sha1,0, cb_data);3378}3379if(retval)3380break;3381}3382strbuf_setlen(name, oldlen);3383}3384closedir(d);3385return retval;3386}33873388intfor_each_reflog(each_ref_fn fn,void*cb_data)3389{3390int retval;3391struct strbuf name;3392strbuf_init(&name, PATH_MAX);3393 retval =do_for_each_reflog(&name, fn, cb_data);3394strbuf_release(&name);3395return retval;3396}33973398/**3399 * Information needed for a single ref update. Set new_sha1 to the3400 * new value or to zero to delete the ref. To check the old value3401 * while locking the ref, set have_old to 1 and set old_sha1 to the3402 * value or to zero to ensure the ref does not exist before update.3403 */3404struct ref_update {3405unsigned char new_sha1[20];3406unsigned char old_sha1[20];3407int flags;/* REF_NODEREF? */3408int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3409struct ref_lock *lock;3410int type;3411const char refname[FLEX_ARRAY];3412};34133414/*3415 * Transaction states.3416 * OPEN: The transaction is in a valid state and can accept new updates.3417 * An OPEN transaction can be committed.3418 * CLOSED: A closed transaction is no longer active and no other operations3419 * than free can be used on it in this state.3420 * A transaction can either become closed by successfully committing3421 * an active transaction or if there is a failure while building3422 * the transaction thus rendering it failed/inactive.3423 */3424enum ref_transaction_state {3425 REF_TRANSACTION_OPEN =0,3426 REF_TRANSACTION_CLOSED =13427};34283429/*3430 * Data structure for holding a reference transaction, which can3431 * consist of checks and updates to multiple references, carried out3432 * as atomically as possible. This structure is opaque to callers.3433 */3434struct ref_transaction {3435struct ref_update **updates;3436size_t alloc;3437size_t nr;3438enum ref_transaction_state state;3439};34403441struct ref_transaction *ref_transaction_begin(struct strbuf *err)3442{3443returnxcalloc(1,sizeof(struct ref_transaction));3444}34453446voidref_transaction_free(struct ref_transaction *transaction)3447{3448int i;34493450if(!transaction)3451return;34523453for(i =0; i < transaction->nr; i++)3454free(transaction->updates[i]);34553456free(transaction->updates);3457free(transaction);3458}34593460static struct ref_update *add_update(struct ref_transaction *transaction,3461const char*refname)3462{3463size_t len =strlen(refname);3464struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);34653466strcpy((char*)update->refname, refname);3467ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3468 transaction->updates[transaction->nr++] = update;3469return update;3470}34713472intref_transaction_update(struct ref_transaction *transaction,3473const char*refname,3474const unsigned char*new_sha1,3475const unsigned char*old_sha1,3476int flags,int have_old,3477struct strbuf *err)3478{3479struct ref_update *update;34803481if(transaction->state != REF_TRANSACTION_OPEN)3482die("BUG: update called for transaction that is not open");34833484if(have_old && !old_sha1)3485die("BUG: have_old is true but old_sha1 is NULL");34863487 update =add_update(transaction, refname);3488hashcpy(update->new_sha1, new_sha1);3489 update->flags = flags;3490 update->have_old = have_old;3491if(have_old)3492hashcpy(update->old_sha1, old_sha1);3493return0;3494}34953496intref_transaction_create(struct ref_transaction *transaction,3497const char*refname,3498const unsigned char*new_sha1,3499int flags,3500struct strbuf *err)3501{3502struct ref_update *update;35033504if(transaction->state != REF_TRANSACTION_OPEN)3505die("BUG: create called for transaction that is not open");35063507if(!new_sha1 ||is_null_sha1(new_sha1))3508die("BUG: create ref with null new_sha1");35093510 update =add_update(transaction, refname);35113512hashcpy(update->new_sha1, new_sha1);3513hashclr(update->old_sha1);3514 update->flags = flags;3515 update->have_old =1;3516return0;3517}35183519intref_transaction_delete(struct ref_transaction *transaction,3520const char*refname,3521const unsigned char*old_sha1,3522int flags,int have_old,3523struct strbuf *err)3524{3525struct ref_update *update;35263527if(transaction->state != REF_TRANSACTION_OPEN)3528die("BUG: delete called for transaction that is not open");35293530if(have_old && !old_sha1)3531die("BUG: have_old is true but old_sha1 is NULL");35323533 update =add_update(transaction, refname);3534 update->flags = flags;3535 update->have_old = have_old;3536if(have_old) {3537assert(!is_null_sha1(old_sha1));3538hashcpy(update->old_sha1, old_sha1);3539}3540return0;3541}35423543intupdate_ref(const char*action,const char*refname,3544const unsigned char*sha1,const unsigned char*oldval,3545int flags,enum action_on_err onerr)3546{3547struct ref_transaction *t;3548struct strbuf err = STRBUF_INIT;35493550 t =ref_transaction_begin(&err);3551if(!t ||3552ref_transaction_update(t, refname, sha1, oldval, flags,3553!!oldval, &err) ||3554ref_transaction_commit(t, action, &err)) {3555const char*str ="update_ref failed for ref '%s':%s";35563557ref_transaction_free(t);3558switch(onerr) {3559case UPDATE_REFS_MSG_ON_ERR:3560error(str, refname, err.buf);3561break;3562case UPDATE_REFS_DIE_ON_ERR:3563die(str, refname, err.buf);3564break;3565case UPDATE_REFS_QUIET_ON_ERR:3566break;3567}3568strbuf_release(&err);3569return1;3570}3571strbuf_release(&err);3572ref_transaction_free(t);3573return0;3574}35753576static intref_update_compare(const void*r1,const void*r2)3577{3578const struct ref_update *const*u1 = r1;3579const struct ref_update *const*u2 = r2;3580returnstrcmp((*u1)->refname, (*u2)->refname);3581}35823583static intref_update_reject_duplicates(struct ref_update **updates,int n,3584struct strbuf *err)3585{3586int i;3587for(i =1; i < n; i++)3588if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3589const char*str =3590"Multiple updates for ref '%s' not allowed.";3591if(err)3592strbuf_addf(err, str, updates[i]->refname);35933594return1;3595}3596return0;3597}35983599intref_transaction_commit(struct ref_transaction *transaction,3600const char*msg,struct strbuf *err)3601{3602int ret =0, delnum =0, i;3603const char**delnames;3604int n = transaction->nr;3605struct ref_update **updates = transaction->updates;36063607if(transaction->state != REF_TRANSACTION_OPEN)3608die("BUG: commit called for transaction that is not open");36093610if(!n) {3611 transaction->state = REF_TRANSACTION_CLOSED;3612return0;3613}36143615/* Allocate work space */3616 delnames =xmalloc(sizeof(*delnames) * n);36173618/* Copy, sort, and reject duplicate refs */3619qsort(updates, n,sizeof(*updates), ref_update_compare);3620 ret =ref_update_reject_duplicates(updates, n, err);3621if(ret)3622goto cleanup;36233624/* Acquire all locks while verifying old values */3625for(i =0; i < n; i++) {3626struct ref_update *update = updates[i];36273628 update->lock =lock_any_ref_for_update(update->refname,3629(update->have_old ?3630 update->old_sha1 :3631 NULL),3632 update->flags,3633&update->type);3634if(!update->lock) {3635if(err)3636strbuf_addf(err,"Cannot lock the ref '%s'.",3637 update->refname);3638 ret =1;3639goto cleanup;3640}3641}36423643/* Perform updates first so live commits remain referenced */3644for(i =0; i < n; i++) {3645struct ref_update *update = updates[i];36463647if(!is_null_sha1(update->new_sha1)) {3648 ret =write_ref_sha1(update->lock, update->new_sha1,3649 msg);3650 update->lock = NULL;/* freed by write_ref_sha1 */3651if(ret) {3652if(err)3653strbuf_addf(err,"Cannot update the ref '%s'.",3654 update->refname);3655goto cleanup;3656}3657}3658}36593660/* Perform deletes now that updates are safely completed */3661for(i =0; i < n; i++) {3662struct ref_update *update = updates[i];36633664if(update->lock) {3665 ret |=delete_ref_loose(update->lock, update->type);3666if(!(update->flags & REF_ISPRUNING))3667 delnames[delnum++] = update->lock->ref_name;3668}3669}36703671 ret |=repack_without_refs(delnames, delnum, err);3672for(i =0; i < delnum; i++)3673unlink_or_warn(git_path("logs/%s", delnames[i]));3674clear_loose_ref_cache(&ref_cache);36753676cleanup:3677 transaction->state = REF_TRANSACTION_CLOSED;36783679for(i =0; i < n; i++)3680if(updates[i]->lock)3681unlock_ref(updates[i]->lock);3682free(delnames);3683return ret;3684}36853686char*shorten_unambiguous_ref(const char*refname,int strict)3687{3688int i;3689static char**scanf_fmts;3690static int nr_rules;3691char*short_name;36923693if(!nr_rules) {3694/*3695 * Pre-generate scanf formats from ref_rev_parse_rules[].3696 * Generate a format suitable for scanf from a3697 * ref_rev_parse_rules rule by interpolating "%s" at the3698 * location of the "%.*s".3699 */3700size_t total_len =0;3701size_t offset =0;37023703/* the rule list is NULL terminated, count them first */3704for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3705/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3706 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;37073708 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);37093710 offset =0;3711for(i =0; i < nr_rules; i++) {3712assert(offset < total_len);3713 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3714 offset +=snprintf(scanf_fmts[i], total_len - offset,3715 ref_rev_parse_rules[i],2,"%s") +1;3716}3717}37183719/* bail out if there are no rules */3720if(!nr_rules)3721returnxstrdup(refname);37223723/* buffer for scanf result, at most refname must fit */3724 short_name =xstrdup(refname);37253726/* skip first rule, it will always match */3727for(i = nr_rules -1; i >0; --i) {3728int j;3729int rules_to_fail = i;3730int short_name_len;37313732if(1!=sscanf(refname, scanf_fmts[i], short_name))3733continue;37343735 short_name_len =strlen(short_name);37363737/*3738 * in strict mode, all (except the matched one) rules3739 * must fail to resolve to a valid non-ambiguous ref3740 */3741if(strict)3742 rules_to_fail = nr_rules;37433744/*3745 * check if the short name resolves to a valid ref,3746 * but use only rules prior to the matched one3747 */3748for(j =0; j < rules_to_fail; j++) {3749const char*rule = ref_rev_parse_rules[j];3750char refname[PATH_MAX];37513752/* skip matched rule */3753if(i == j)3754continue;37553756/*3757 * the short name is ambiguous, if it resolves3758 * (with this previous rule) to a valid ref3759 * read_ref() returns 0 on success3760 */3761mksnpath(refname,sizeof(refname),3762 rule, short_name_len, short_name);3763if(ref_exists(refname))3764break;3765}37663767/*3768 * short name is non-ambiguous if all previous rules3769 * haven't resolved to a valid ref3770 */3771if(j == rules_to_fail)3772return short_name;3773}37743775free(short_name);3776returnxstrdup(refname);3777}37783779static struct string_list *hide_refs;37803781intparse_hide_refs_config(const char*var,const char*value,const char*section)3782{3783if(!strcmp("transfer.hiderefs", var) ||3784/* NEEDSWORK: use parse_config_key() once both are merged */3785(starts_with(var, section) && var[strlen(section)] =='.'&&3786!strcmp(var +strlen(section),".hiderefs"))) {3787char*ref;3788int len;37893790if(!value)3791returnconfig_error_nonbool(var);3792 ref =xstrdup(value);3793 len =strlen(ref);3794while(len && ref[len -1] =='/')3795 ref[--len] ='\0';3796if(!hide_refs) {3797 hide_refs =xcalloc(1,sizeof(*hide_refs));3798 hide_refs->strdup_strings =1;3799}3800string_list_append(hide_refs, ref);3801}3802return0;3803}38043805intref_is_hidden(const char*refname)3806{3807struct string_list_item *item;38083809if(!hide_refs)3810return0;3811for_each_string_list_item(item, hide_refs) {3812int len;3813if(!starts_with(refname, item->string))3814continue;3815 len =strlen(item->string);3816if(!refname[len] || refname[len] =='/')3817return1;3818}3819return0;3820}