1#include"cache.h" 2#include"lockfile.h" 3#include"refs.h" 4#include"object.h" 5#include"tag.h" 6#include"dir.h" 7#include"string-list.h" 8 9/* 10 * How to handle various characters in refnames: 11 * 0: An acceptable character for refs 12 * 1: End-of-component 13 * 2: ., look for a preceding . to reject .. in refs 14 * 3: {, look for a preceding @ to reject @{ in refs 15 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 16 */ 17static unsigned char refname_disposition[256] = { 181,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 194,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 204,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 210,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 220,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 230,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 250,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 26}; 27 28/* 29 * Used as a flag to ref_transaction_delete when a loose ref is being 30 * pruned. 31 */ 32#define REF_ISPRUNING 0x0100 33/* 34 * Try to read one refname component from the front of refname. 35 * Return the length of the component found, or -1 if the component is 36 * not legal. It is legal if it is something reasonable to have under 37 * ".git/refs/"; We do not like it if: 38 * 39 * - any path component of it begins with ".", or 40 * - it has double dots "..", or 41 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 42 * - it ends with a "/". 43 * - it ends with ".lock" 44 * - it contains a "\" (backslash) 45 */ 46static intcheck_refname_component(const char*refname,int flags) 47{ 48const char*cp; 49char last ='\0'; 50 51for(cp = refname; ; cp++) { 52int ch = *cp &255; 53unsigned char disp = refname_disposition[ch]; 54switch(disp) { 55case1: 56goto out; 57case2: 58if(last =='.') 59return-1;/* Refname contains "..". */ 60break; 61case3: 62if(last =='@') 63return-1;/* Refname contains "@{". */ 64break; 65case4: 66return-1; 67} 68 last = ch; 69} 70out: 71if(cp == refname) 72return0;/* Component has zero length. */ 73if(refname[0] =='.') 74return-1;/* Component starts with '.'. */ 75if(cp - refname >= LOCK_SUFFIX_LEN && 76!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 77return-1;/* Refname ends with ".lock". */ 78return cp - refname; 79} 80 81intcheck_refname_format(const char*refname,int flags) 82{ 83int component_len, component_count =0; 84 85if(!strcmp(refname,"@")) 86/* Refname is a single character '@'. */ 87return-1; 88 89while(1) { 90/* We are at the start of a path component. */ 91 component_len =check_refname_component(refname, flags); 92if(component_len <=0) { 93if((flags & REFNAME_REFSPEC_PATTERN) && 94 refname[0] =='*'&& 95(refname[1] =='\0'|| refname[1] =='/')) { 96/* Accept one wildcard as a full refname component. */ 97 flags &= ~REFNAME_REFSPEC_PATTERN; 98 component_len =1; 99}else{ 100return-1; 101} 102} 103 component_count++; 104if(refname[component_len] =='\0') 105break; 106/* Skip to next component. */ 107 refname += component_len +1; 108} 109 110if(refname[component_len -1] =='.') 111return-1;/* Refname ends with '.'. */ 112if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 113return-1;/* Refname has only one component. */ 114return0; 115} 116 117struct ref_entry; 118 119/* 120 * Information used (along with the information in ref_entry) to 121 * describe a single cached reference. This data structure only 122 * occurs embedded in a union in struct ref_entry, and only when 123 * (ref_entry->flag & REF_DIR) is zero. 124 */ 125struct ref_value { 126/* 127 * The name of the object to which this reference resolves 128 * (which may be a tag object). If REF_ISBROKEN, this is 129 * null. If REF_ISSYMREF, then this is the name of the object 130 * referred to by the last reference in the symlink chain. 131 */ 132unsigned char sha1[20]; 133 134/* 135 * If REF_KNOWS_PEELED, then this field holds the peeled value 136 * of this reference, or null if the reference is known not to 137 * be peelable. See the documentation for peel_ref() for an 138 * exact definition of "peelable". 139 */ 140unsigned char peeled[20]; 141}; 142 143struct ref_cache; 144 145/* 146 * Information used (along with the information in ref_entry) to 147 * describe a level in the hierarchy of references. This data 148 * structure only occurs embedded in a union in struct ref_entry, and 149 * only when (ref_entry.flag & REF_DIR) is set. In that case, 150 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 151 * in the directory have already been read: 152 * 153 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 154 * or packed references, already read. 155 * 156 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 157 * references that hasn't been read yet (nor has any of its 158 * subdirectories). 159 * 160 * Entries within a directory are stored within a growable array of 161 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 162 * sorted are sorted by their component name in strcmp() order and the 163 * remaining entries are unsorted. 164 * 165 * Loose references are read lazily, one directory at a time. When a 166 * directory of loose references is read, then all of the references 167 * in that directory are stored, and REF_INCOMPLETE stubs are created 168 * for any subdirectories, but the subdirectories themselves are not 169 * read. The reading is triggered by get_ref_dir(). 170 */ 171struct ref_dir { 172int nr, alloc; 173 174/* 175 * Entries with index 0 <= i < sorted are sorted by name. New 176 * entries are appended to the list unsorted, and are sorted 177 * only when required; thus we avoid the need to sort the list 178 * after the addition of every reference. 179 */ 180int sorted; 181 182/* A pointer to the ref_cache that contains this ref_dir. */ 183struct ref_cache *ref_cache; 184 185struct ref_entry **entries; 186}; 187 188/* 189 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 190 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see 191 * refs.h. 192 */ 193 194/* 195 * The field ref_entry->u.value.peeled of this value entry contains 196 * the correct peeled value for the reference, which might be 197 * null_sha1 if the reference is not a tag or if it is broken. 198 */ 199#define REF_KNOWS_PEELED 0x08 200 201/* ref_entry represents a directory of references */ 202#define REF_DIR 0x10 203 204/* 205 * Entry has not yet been read from disk (used only for REF_DIR 206 * entries representing loose references) 207 */ 208#define REF_INCOMPLETE 0x20 209 210/* 211 * A ref_entry represents either a reference or a "subdirectory" of 212 * references. 213 * 214 * Each directory in the reference namespace is represented by a 215 * ref_entry with (flags & REF_DIR) set and containing a subdir member 216 * that holds the entries in that directory that have been read so 217 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 218 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 219 * used for loose reference directories. 220 * 221 * References are represented by a ref_entry with (flags & REF_DIR) 222 * unset and a value member that describes the reference's value. The 223 * flag member is at the ref_entry level, but it is also needed to 224 * interpret the contents of the value field (in other words, a 225 * ref_value object is not very much use without the enclosing 226 * ref_entry). 227 * 228 * Reference names cannot end with slash and directories' names are 229 * always stored with a trailing slash (except for the top-level 230 * directory, which is always denoted by ""). This has two nice 231 * consequences: (1) when the entries in each subdir are sorted 232 * lexicographically by name (as they usually are), the references in 233 * a whole tree can be generated in lexicographic order by traversing 234 * the tree in left-to-right, depth-first order; (2) the names of 235 * references and subdirectories cannot conflict, and therefore the 236 * presence of an empty subdirectory does not block the creation of a 237 * similarly-named reference. (The fact that reference names with the 238 * same leading components can conflict *with each other* is a 239 * separate issue that is regulated by is_refname_available().) 240 * 241 * Please note that the name field contains the fully-qualified 242 * reference (or subdirectory) name. Space could be saved by only 243 * storing the relative names. But that would require the full names 244 * to be generated on the fly when iterating in do_for_each_ref(), and 245 * would break callback functions, who have always been able to assume 246 * that the name strings that they are passed will not be freed during 247 * the iteration. 248 */ 249struct ref_entry { 250unsigned char flag;/* ISSYMREF? ISPACKED? */ 251union{ 252struct ref_value value;/* if not (flags&REF_DIR) */ 253struct ref_dir subdir;/* if (flags&REF_DIR) */ 254} u; 255/* 256 * The full name of the reference (e.g., "refs/heads/master") 257 * or the full name of the directory with a trailing slash 258 * (e.g., "refs/heads/"): 259 */ 260char name[FLEX_ARRAY]; 261}; 262 263static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 264 265static struct ref_dir *get_ref_dir(struct ref_entry *entry) 266{ 267struct ref_dir *dir; 268assert(entry->flag & REF_DIR); 269 dir = &entry->u.subdir; 270if(entry->flag & REF_INCOMPLETE) { 271read_loose_refs(entry->name, dir); 272 entry->flag &= ~REF_INCOMPLETE; 273} 274return dir; 275} 276 277static struct ref_entry *create_ref_entry(const char*refname, 278const unsigned char*sha1,int flag, 279int check_name) 280{ 281int len; 282struct ref_entry *ref; 283 284if(check_name && 285check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 286die("Reference has invalid format: '%s'", refname); 287 len =strlen(refname) +1; 288 ref =xmalloc(sizeof(struct ref_entry) + len); 289hashcpy(ref->u.value.sha1, sha1); 290hashclr(ref->u.value.peeled); 291memcpy(ref->name, refname, len); 292 ref->flag = flag; 293return ref; 294} 295 296static voidclear_ref_dir(struct ref_dir *dir); 297 298static voidfree_ref_entry(struct ref_entry *entry) 299{ 300if(entry->flag & REF_DIR) { 301/* 302 * Do not use get_ref_dir() here, as that might 303 * trigger the reading of loose refs. 304 */ 305clear_ref_dir(&entry->u.subdir); 306} 307free(entry); 308} 309 310/* 311 * Add a ref_entry to the end of dir (unsorted). Entry is always 312 * stored directly in dir; no recursion into subdirectories is 313 * done. 314 */ 315static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 316{ 317ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 318 dir->entries[dir->nr++] = entry; 319/* optimize for the case that entries are added in order */ 320if(dir->nr ==1|| 321(dir->nr == dir->sorted +1&& 322strcmp(dir->entries[dir->nr -2]->name, 323 dir->entries[dir->nr -1]->name) <0)) 324 dir->sorted = dir->nr; 325} 326 327/* 328 * Clear and free all entries in dir, recursively. 329 */ 330static voidclear_ref_dir(struct ref_dir *dir) 331{ 332int i; 333for(i =0; i < dir->nr; i++) 334free_ref_entry(dir->entries[i]); 335free(dir->entries); 336 dir->sorted = dir->nr = dir->alloc =0; 337 dir->entries = NULL; 338} 339 340/* 341 * Create a struct ref_entry object for the specified dirname. 342 * dirname is the name of the directory with a trailing slash (e.g., 343 * "refs/heads/") or "" for the top-level directory. 344 */ 345static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 346const char*dirname,size_t len, 347int incomplete) 348{ 349struct ref_entry *direntry; 350 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 351memcpy(direntry->name, dirname, len); 352 direntry->name[len] ='\0'; 353 direntry->u.subdir.ref_cache = ref_cache; 354 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 355return direntry; 356} 357 358static intref_entry_cmp(const void*a,const void*b) 359{ 360struct ref_entry *one = *(struct ref_entry **)a; 361struct ref_entry *two = *(struct ref_entry **)b; 362returnstrcmp(one->name, two->name); 363} 364 365static voidsort_ref_dir(struct ref_dir *dir); 366 367struct string_slice { 368size_t len; 369const char*str; 370}; 371 372static intref_entry_cmp_sslice(const void*key_,const void*ent_) 373{ 374const struct string_slice *key = key_; 375const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 376int cmp =strncmp(key->str, ent->name, key->len); 377if(cmp) 378return cmp; 379return'\0'- (unsigned char)ent->name[key->len]; 380} 381 382/* 383 * Return the index of the entry with the given refname from the 384 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 385 * no such entry is found. dir must already be complete. 386 */ 387static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 388{ 389struct ref_entry **r; 390struct string_slice key; 391 392if(refname == NULL || !dir->nr) 393return-1; 394 395sort_ref_dir(dir); 396 key.len = len; 397 key.str = refname; 398 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 399 ref_entry_cmp_sslice); 400 401if(r == NULL) 402return-1; 403 404return r - dir->entries; 405} 406 407/* 408 * Search for a directory entry directly within dir (without 409 * recursing). Sort dir if necessary. subdirname must be a directory 410 * name (i.e., end in '/'). If mkdir is set, then create the 411 * directory if it is missing; otherwise, return NULL if the desired 412 * directory cannot be found. dir must already be complete. 413 */ 414static struct ref_dir *search_for_subdir(struct ref_dir *dir, 415const char*subdirname,size_t len, 416int mkdir) 417{ 418int entry_index =search_ref_dir(dir, subdirname, len); 419struct ref_entry *entry; 420if(entry_index == -1) { 421if(!mkdir) 422return NULL; 423/* 424 * Since dir is complete, the absence of a subdir 425 * means that the subdir really doesn't exist; 426 * therefore, create an empty record for it but mark 427 * the record complete. 428 */ 429 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 430add_entry_to_dir(dir, entry); 431}else{ 432 entry = dir->entries[entry_index]; 433} 434returnget_ref_dir(entry); 435} 436 437/* 438 * If refname is a reference name, find the ref_dir within the dir 439 * tree that should hold refname. If refname is a directory name 440 * (i.e., ends in '/'), then return that ref_dir itself. dir must 441 * represent the top-level directory and must already be complete. 442 * Sort ref_dirs and recurse into subdirectories as necessary. If 443 * mkdir is set, then create any missing directories; otherwise, 444 * return NULL if the desired directory cannot be found. 445 */ 446static struct ref_dir *find_containing_dir(struct ref_dir *dir, 447const char*refname,int mkdir) 448{ 449const char*slash; 450for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 451size_t dirnamelen = slash - refname +1; 452struct ref_dir *subdir; 453 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 454if(!subdir) { 455 dir = NULL; 456break; 457} 458 dir = subdir; 459} 460 461return dir; 462} 463 464/* 465 * Find the value entry with the given name in dir, sorting ref_dirs 466 * and recursing into subdirectories as necessary. If the name is not 467 * found or it corresponds to a directory entry, return NULL. 468 */ 469static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 470{ 471int entry_index; 472struct ref_entry *entry; 473 dir =find_containing_dir(dir, refname,0); 474if(!dir) 475return NULL; 476 entry_index =search_ref_dir(dir, refname,strlen(refname)); 477if(entry_index == -1) 478return NULL; 479 entry = dir->entries[entry_index]; 480return(entry->flag & REF_DIR) ? NULL : entry; 481} 482 483/* 484 * Remove the entry with the given name from dir, recursing into 485 * subdirectories as necessary. If refname is the name of a directory 486 * (i.e., ends with '/'), then remove the directory and its contents. 487 * If the removal was successful, return the number of entries 488 * remaining in the directory entry that contained the deleted entry. 489 * If the name was not found, return -1. Please note that this 490 * function only deletes the entry from the cache; it does not delete 491 * it from the filesystem or ensure that other cache entries (which 492 * might be symbolic references to the removed entry) are updated. 493 * Nor does it remove any containing dir entries that might be made 494 * empty by the removal. dir must represent the top-level directory 495 * and must already be complete. 496 */ 497static intremove_entry(struct ref_dir *dir,const char*refname) 498{ 499int refname_len =strlen(refname); 500int entry_index; 501struct ref_entry *entry; 502int is_dir = refname[refname_len -1] =='/'; 503if(is_dir) { 504/* 505 * refname represents a reference directory. Remove 506 * the trailing slash; otherwise we will get the 507 * directory *representing* refname rather than the 508 * one *containing* it. 509 */ 510char*dirname =xmemdupz(refname, refname_len -1); 511 dir =find_containing_dir(dir, dirname,0); 512free(dirname); 513}else{ 514 dir =find_containing_dir(dir, refname,0); 515} 516if(!dir) 517return-1; 518 entry_index =search_ref_dir(dir, refname, refname_len); 519if(entry_index == -1) 520return-1; 521 entry = dir->entries[entry_index]; 522 523memmove(&dir->entries[entry_index], 524&dir->entries[entry_index +1], 525(dir->nr - entry_index -1) *sizeof(*dir->entries) 526); 527 dir->nr--; 528if(dir->sorted > entry_index) 529 dir->sorted--; 530free_ref_entry(entry); 531return dir->nr; 532} 533 534/* 535 * Add a ref_entry to the ref_dir (unsorted), recursing into 536 * subdirectories as necessary. dir must represent the top-level 537 * directory. Return 0 on success. 538 */ 539static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 540{ 541 dir =find_containing_dir(dir, ref->name,1); 542if(!dir) 543return-1; 544add_entry_to_dir(dir, ref); 545return0; 546} 547 548/* 549 * Emit a warning and return true iff ref1 and ref2 have the same name 550 * and the same sha1. Die if they have the same name but different 551 * sha1s. 552 */ 553static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 554{ 555if(strcmp(ref1->name, ref2->name)) 556return0; 557 558/* Duplicate name; make sure that they don't conflict: */ 559 560if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 561/* This is impossible by construction */ 562die("Reference directory conflict:%s", ref1->name); 563 564if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 565die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 566 567warning("Duplicated ref:%s", ref1->name); 568return1; 569} 570 571/* 572 * Sort the entries in dir non-recursively (if they are not already 573 * sorted) and remove any duplicate entries. 574 */ 575static voidsort_ref_dir(struct ref_dir *dir) 576{ 577int i, j; 578struct ref_entry *last = NULL; 579 580/* 581 * This check also prevents passing a zero-length array to qsort(), 582 * which is a problem on some platforms. 583 */ 584if(dir->sorted == dir->nr) 585return; 586 587qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 588 589/* Remove any duplicates: */ 590for(i =0, j =0; j < dir->nr; j++) { 591struct ref_entry *entry = dir->entries[j]; 592if(last &&is_dup_ref(last, entry)) 593free_ref_entry(entry); 594else 595 last = dir->entries[i++] = entry; 596} 597 dir->sorted = dir->nr = i; 598} 599 600/* Include broken references in a do_for_each_ref*() iteration: */ 601#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 602 603/* 604 * Return true iff the reference described by entry can be resolved to 605 * an object in the database. Emit a warning if the referred-to 606 * object does not exist. 607 */ 608static intref_resolves_to_object(struct ref_entry *entry) 609{ 610if(entry->flag & REF_ISBROKEN) 611return0; 612if(!has_sha1_file(entry->u.value.sha1)) { 613error("%sdoes not point to a valid object!", entry->name); 614return0; 615} 616return1; 617} 618 619/* 620 * current_ref is a performance hack: when iterating over references 621 * using the for_each_ref*() functions, current_ref is set to the 622 * current reference's entry before calling the callback function. If 623 * the callback function calls peel_ref(), then peel_ref() first 624 * checks whether the reference to be peeled is the current reference 625 * (it usually is) and if so, returns that reference's peeled version 626 * if it is available. This avoids a refname lookup in a common case. 627 */ 628static struct ref_entry *current_ref; 629 630typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 631 632struct ref_entry_cb { 633const char*base; 634int trim; 635int flags; 636 each_ref_fn *fn; 637void*cb_data; 638}; 639 640/* 641 * Handle one reference in a do_for_each_ref*()-style iteration, 642 * calling an each_ref_fn for each entry. 643 */ 644static intdo_one_ref(struct ref_entry *entry,void*cb_data) 645{ 646struct ref_entry_cb *data = cb_data; 647struct ref_entry *old_current_ref; 648int retval; 649 650if(!starts_with(entry->name, data->base)) 651return0; 652 653if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 654!ref_resolves_to_object(entry)) 655return0; 656 657/* Store the old value, in case this is a recursive call: */ 658 old_current_ref = current_ref; 659 current_ref = entry; 660 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 661 entry->flag, data->cb_data); 662 current_ref = old_current_ref; 663return retval; 664} 665 666/* 667 * Call fn for each reference in dir that has index in the range 668 * offset <= index < dir->nr. Recurse into subdirectories that are in 669 * that index range, sorting them before iterating. This function 670 * does not sort dir itself; it should be sorted beforehand. fn is 671 * called for all references, including broken ones. 672 */ 673static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 674 each_ref_entry_fn fn,void*cb_data) 675{ 676int i; 677assert(dir->sorted == dir->nr); 678for(i = offset; i < dir->nr; i++) { 679struct ref_entry *entry = dir->entries[i]; 680int retval; 681if(entry->flag & REF_DIR) { 682struct ref_dir *subdir =get_ref_dir(entry); 683sort_ref_dir(subdir); 684 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 685}else{ 686 retval =fn(entry, cb_data); 687} 688if(retval) 689return retval; 690} 691return0; 692} 693 694/* 695 * Call fn for each reference in the union of dir1 and dir2, in order 696 * by refname. Recurse into subdirectories. If a value entry appears 697 * in both dir1 and dir2, then only process the version that is in 698 * dir2. The input dirs must already be sorted, but subdirs will be 699 * sorted as needed. fn is called for all references, including 700 * broken ones. 701 */ 702static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 703struct ref_dir *dir2, 704 each_ref_entry_fn fn,void*cb_data) 705{ 706int retval; 707int i1 =0, i2 =0; 708 709assert(dir1->sorted == dir1->nr); 710assert(dir2->sorted == dir2->nr); 711while(1) { 712struct ref_entry *e1, *e2; 713int cmp; 714if(i1 == dir1->nr) { 715returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 716} 717if(i2 == dir2->nr) { 718returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 719} 720 e1 = dir1->entries[i1]; 721 e2 = dir2->entries[i2]; 722 cmp =strcmp(e1->name, e2->name); 723if(cmp ==0) { 724if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 725/* Both are directories; descend them in parallel. */ 726struct ref_dir *subdir1 =get_ref_dir(e1); 727struct ref_dir *subdir2 =get_ref_dir(e2); 728sort_ref_dir(subdir1); 729sort_ref_dir(subdir2); 730 retval =do_for_each_entry_in_dirs( 731 subdir1, subdir2, fn, cb_data); 732 i1++; 733 i2++; 734}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 735/* Both are references; ignore the one from dir1. */ 736 retval =fn(e2, cb_data); 737 i1++; 738 i2++; 739}else{ 740die("conflict between reference and directory:%s", 741 e1->name); 742} 743}else{ 744struct ref_entry *e; 745if(cmp <0) { 746 e = e1; 747 i1++; 748}else{ 749 e = e2; 750 i2++; 751} 752if(e->flag & REF_DIR) { 753struct ref_dir *subdir =get_ref_dir(e); 754sort_ref_dir(subdir); 755 retval =do_for_each_entry_in_dir( 756 subdir,0, fn, cb_data); 757}else{ 758 retval =fn(e, cb_data); 759} 760} 761if(retval) 762return retval; 763} 764} 765 766/* 767 * Load all of the refs from the dir into our in-memory cache. The hard work 768 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 769 * through all of the sub-directories. We do not even need to care about 770 * sorting, as traversal order does not matter to us. 771 */ 772static voidprime_ref_dir(struct ref_dir *dir) 773{ 774int i; 775for(i =0; i < dir->nr; i++) { 776struct ref_entry *entry = dir->entries[i]; 777if(entry->flag & REF_DIR) 778prime_ref_dir(get_ref_dir(entry)); 779} 780} 781 782static intentry_matches(struct ref_entry *entry,const struct string_list *list) 783{ 784return list &&string_list_has_string(list, entry->name); 785} 786 787struct nonmatching_ref_data { 788const struct string_list *skip; 789struct ref_entry *found; 790}; 791 792static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 793{ 794struct nonmatching_ref_data *data = vdata; 795 796if(entry_matches(entry, data->skip)) 797return0; 798 799 data->found = entry; 800return1; 801} 802 803static voidreport_refname_conflict(struct ref_entry *entry, 804const char*refname) 805{ 806error("'%s' exists; cannot create '%s'", entry->name, refname); 807} 808 809/* 810 * Return true iff a reference named refname could be created without 811 * conflicting with the name of an existing reference in dir. If 812 * skip is non-NULL, ignore potential conflicts with refs in skip 813 * (e.g., because they are scheduled for deletion in the same 814 * operation). 815 * 816 * Two reference names conflict if one of them exactly matches the 817 * leading components of the other; e.g., "foo/bar" conflicts with 818 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 819 * "foo/barbados". 820 * 821 * skip must be sorted. 822 */ 823static intis_refname_available(const char*refname, 824const struct string_list *skip, 825struct ref_dir *dir) 826{ 827const char*slash; 828size_t len; 829int pos; 830char*dirname; 831 832for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 833/* 834 * We are still at a leading dir of the refname; we are 835 * looking for a conflict with a leaf entry. 836 * 837 * If we find one, we still must make sure it is 838 * not in "skip". 839 */ 840 pos =search_ref_dir(dir, refname, slash - refname); 841if(pos >=0) { 842struct ref_entry *entry = dir->entries[pos]; 843if(entry_matches(entry, skip)) 844return1; 845report_refname_conflict(entry, refname); 846return0; 847} 848 849 850/* 851 * Otherwise, we can try to continue our search with 852 * the next component; if we come up empty, we know 853 * there is nothing under this whole prefix. 854 */ 855 pos =search_ref_dir(dir, refname, slash +1- refname); 856if(pos <0) 857return1; 858 859 dir =get_ref_dir(dir->entries[pos]); 860} 861 862/* 863 * We are at the leaf of our refname; we want to 864 * make sure there are no directories which match it. 865 */ 866 len =strlen(refname); 867 dirname =xmallocz(len +1); 868sprintf(dirname,"%s/", refname); 869 pos =search_ref_dir(dir, dirname, len +1); 870free(dirname); 871 872if(pos >=0) { 873/* 874 * We found a directory named "refname". It is a 875 * problem iff it contains any ref that is not 876 * in "skip". 877 */ 878struct ref_entry *entry = dir->entries[pos]; 879struct ref_dir *dir =get_ref_dir(entry); 880struct nonmatching_ref_data data; 881 882 data.skip = skip; 883sort_ref_dir(dir); 884if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 885return1; 886 887report_refname_conflict(data.found, refname); 888return0; 889} 890 891/* 892 * There is no point in searching for another leaf 893 * node which matches it; such an entry would be the 894 * ref we are looking for, not a conflict. 895 */ 896return1; 897} 898 899struct packed_ref_cache { 900struct ref_entry *root; 901 902/* 903 * Count of references to the data structure in this instance, 904 * including the pointer from ref_cache::packed if any. The 905 * data will not be freed as long as the reference count is 906 * nonzero. 907 */ 908unsigned int referrers; 909 910/* 911 * Iff the packed-refs file associated with this instance is 912 * currently locked for writing, this points at the associated 913 * lock (which is owned by somebody else). The referrer count 914 * is also incremented when the file is locked and decremented 915 * when it is unlocked. 916 */ 917struct lock_file *lock; 918 919/* The metadata from when this packed-refs cache was read */ 920struct stat_validity validity; 921}; 922 923/* 924 * Future: need to be in "struct repository" 925 * when doing a full libification. 926 */ 927static struct ref_cache { 928struct ref_cache *next; 929struct ref_entry *loose; 930struct packed_ref_cache *packed; 931/* 932 * The submodule name, or "" for the main repo. We allocate 933 * length 1 rather than FLEX_ARRAY so that the main ref_cache 934 * is initialized correctly. 935 */ 936char name[1]; 937} ref_cache, *submodule_ref_caches; 938 939/* Lock used for the main packed-refs file: */ 940static struct lock_file packlock; 941 942/* 943 * Increment the reference count of *packed_refs. 944 */ 945static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 946{ 947 packed_refs->referrers++; 948} 949 950/* 951 * Decrease the reference count of *packed_refs. If it goes to zero, 952 * free *packed_refs and return true; otherwise return false. 953 */ 954static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 955{ 956if(!--packed_refs->referrers) { 957free_ref_entry(packed_refs->root); 958stat_validity_clear(&packed_refs->validity); 959free(packed_refs); 960return1; 961}else{ 962return0; 963} 964} 965 966static voidclear_packed_ref_cache(struct ref_cache *refs) 967{ 968if(refs->packed) { 969struct packed_ref_cache *packed_refs = refs->packed; 970 971if(packed_refs->lock) 972die("internal error: packed-ref cache cleared while locked"); 973 refs->packed = NULL; 974release_packed_ref_cache(packed_refs); 975} 976} 977 978static voidclear_loose_ref_cache(struct ref_cache *refs) 979{ 980if(refs->loose) { 981free_ref_entry(refs->loose); 982 refs->loose = NULL; 983} 984} 985 986static struct ref_cache *create_ref_cache(const char*submodule) 987{ 988int len; 989struct ref_cache *refs; 990if(!submodule) 991 submodule =""; 992 len =strlen(submodule) +1; 993 refs =xcalloc(1,sizeof(struct ref_cache) + len); 994memcpy(refs->name, submodule, len); 995return refs; 996} 997 998/* 999 * Return a pointer to a ref_cache for the specified submodule. For1000 * the main repository, use submodule==NULL. The returned structure1001 * will be allocated and initialized but not necessarily populated; it1002 * should not be freed.1003 */1004static struct ref_cache *get_ref_cache(const char*submodule)1005{1006struct ref_cache *refs;10071008if(!submodule || !*submodule)1009return&ref_cache;10101011for(refs = submodule_ref_caches; refs; refs = refs->next)1012if(!strcmp(submodule, refs->name))1013return refs;10141015 refs =create_ref_cache(submodule);1016 refs->next = submodule_ref_caches;1017 submodule_ref_caches = refs;1018return refs;1019}10201021/* The length of a peeled reference line in packed-refs, including EOL: */1022#define PEELED_LINE_LENGTH 4210231024/*1025 * The packed-refs header line that we write out. Perhaps other1026 * traits will be added later. The trailing space is required.1027 */1028static const char PACKED_REFS_HEADER[] =1029"# pack-refs with: peeled fully-peeled\n";10301031/*1032 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1033 * Return a pointer to the refname within the line (null-terminated),1034 * or NULL if there was a problem.1035 */1036static const char*parse_ref_line(char*line,unsigned char*sha1)1037{1038/*1039 * 42: the answer to everything.1040 *1041 * In this case, it happens to be the answer to1042 * 40 (length of sha1 hex representation)1043 * +1 (space in between hex and name)1044 * +1 (newline at the end of the line)1045 */1046int len =strlen(line) -42;10471048if(len <=0)1049return NULL;1050if(get_sha1_hex(line, sha1) <0)1051return NULL;1052if(!isspace(line[40]))1053return NULL;1054 line +=41;1055if(isspace(*line))1056return NULL;1057if(line[len] !='\n')1058return NULL;1059 line[len] =0;10601061return line;1062}10631064/*1065 * Read f, which is a packed-refs file, into dir.1066 *1067 * A comment line of the form "# pack-refs with: " may contain zero or1068 * more traits. We interpret the traits as follows:1069 *1070 * No traits:1071 *1072 * Probably no references are peeled. But if the file contains a1073 * peeled value for a reference, we will use it.1074 *1075 * peeled:1076 *1077 * References under "refs/tags/", if they *can* be peeled, *are*1078 * peeled in this file. References outside of "refs/tags/" are1079 * probably not peeled even if they could have been, but if we find1080 * a peeled value for such a reference we will use it.1081 *1082 * fully-peeled:1083 *1084 * All references in the file that can be peeled are peeled.1085 * Inversely (and this is more important), any references in the1086 * file for which no peeled value is recorded is not peelable. This1087 * trait should typically be written alongside "peeled" for1088 * compatibility with older clients, but we do not require it1089 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1090 */1091static voidread_packed_refs(FILE*f,struct ref_dir *dir)1092{1093struct ref_entry *last = NULL;1094char refline[PATH_MAX];1095enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;10961097while(fgets(refline,sizeof(refline), f)) {1098unsigned char sha1[20];1099const char*refname;1100static const char header[] ="# pack-refs with:";11011102if(!strncmp(refline, header,sizeof(header)-1)) {1103const char*traits = refline +sizeof(header) -1;1104if(strstr(traits," fully-peeled "))1105 peeled = PEELED_FULLY;1106else if(strstr(traits," peeled "))1107 peeled = PEELED_TAGS;1108/* perhaps other traits later as well */1109continue;1110}11111112 refname =parse_ref_line(refline, sha1);1113if(refname) {1114 last =create_ref_entry(refname, sha1, REF_ISPACKED,1);1115if(peeled == PEELED_FULLY ||1116(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1117 last->flag |= REF_KNOWS_PEELED;1118add_ref(dir, last);1119continue;1120}1121if(last &&1122 refline[0] =='^'&&1123strlen(refline) == PEELED_LINE_LENGTH &&1124 refline[PEELED_LINE_LENGTH -1] =='\n'&&1125!get_sha1_hex(refline +1, sha1)) {1126hashcpy(last->u.value.peeled, sha1);1127/*1128 * Regardless of what the file header said,1129 * we definitely know the value of *this*1130 * reference:1131 */1132 last->flag |= REF_KNOWS_PEELED;1133}1134}1135}11361137/*1138 * Get the packed_ref_cache for the specified ref_cache, creating it1139 * if necessary.1140 */1141static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1142{1143const char*packed_refs_file;11441145if(*refs->name)1146 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1147else1148 packed_refs_file =git_path("packed-refs");11491150if(refs->packed &&1151!stat_validity_check(&refs->packed->validity, packed_refs_file))1152clear_packed_ref_cache(refs);11531154if(!refs->packed) {1155FILE*f;11561157 refs->packed =xcalloc(1,sizeof(*refs->packed));1158acquire_packed_ref_cache(refs->packed);1159 refs->packed->root =create_dir_entry(refs,"",0,0);1160 f =fopen(packed_refs_file,"r");1161if(f) {1162stat_validity_update(&refs->packed->validity,fileno(f));1163read_packed_refs(f,get_ref_dir(refs->packed->root));1164fclose(f);1165}1166}1167return refs->packed;1168}11691170static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1171{1172returnget_ref_dir(packed_ref_cache->root);1173}11741175static struct ref_dir *get_packed_refs(struct ref_cache *refs)1176{1177returnget_packed_ref_dir(get_packed_ref_cache(refs));1178}11791180voidadd_packed_ref(const char*refname,const unsigned char*sha1)1181{1182struct packed_ref_cache *packed_ref_cache =1183get_packed_ref_cache(&ref_cache);11841185if(!packed_ref_cache->lock)1186die("internal error: packed refs not locked");1187add_ref(get_packed_ref_dir(packed_ref_cache),1188create_ref_entry(refname, sha1, REF_ISPACKED,1));1189}11901191/*1192 * Read the loose references from the namespace dirname into dir1193 * (without recursing). dirname must end with '/'. dir must be the1194 * directory entry corresponding to dirname.1195 */1196static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1197{1198struct ref_cache *refs = dir->ref_cache;1199DIR*d;1200const char*path;1201struct dirent *de;1202int dirnamelen =strlen(dirname);1203struct strbuf refname;12041205if(*refs->name)1206 path =git_path_submodule(refs->name,"%s", dirname);1207else1208 path =git_path("%s", dirname);12091210 d =opendir(path);1211if(!d)1212return;12131214strbuf_init(&refname, dirnamelen +257);1215strbuf_add(&refname, dirname, dirnamelen);12161217while((de =readdir(d)) != NULL) {1218unsigned char sha1[20];1219struct stat st;1220int flag;1221const char*refdir;12221223if(de->d_name[0] =='.')1224continue;1225if(ends_with(de->d_name,".lock"))1226continue;1227strbuf_addstr(&refname, de->d_name);1228 refdir = *refs->name1229?git_path_submodule(refs->name,"%s", refname.buf)1230:git_path("%s", refname.buf);1231if(stat(refdir, &st) <0) {1232;/* silently ignore */1233}else if(S_ISDIR(st.st_mode)) {1234strbuf_addch(&refname,'/');1235add_entry_to_dir(dir,1236create_dir_entry(refs, refname.buf,1237 refname.len,1));1238}else{1239if(*refs->name) {1240hashclr(sha1);1241 flag =0;1242if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1243hashclr(sha1);1244 flag |= REF_ISBROKEN;1245}1246}else if(read_ref_full(refname.buf,1247 RESOLVE_REF_READING,1248 sha1, &flag)) {1249hashclr(sha1);1250 flag |= REF_ISBROKEN;1251}1252add_entry_to_dir(dir,1253create_ref_entry(refname.buf, sha1, flag,1));1254}1255strbuf_setlen(&refname, dirnamelen);1256}1257strbuf_release(&refname);1258closedir(d);1259}12601261static struct ref_dir *get_loose_refs(struct ref_cache *refs)1262{1263if(!refs->loose) {1264/*1265 * Mark the top-level directory complete because we1266 * are about to read the only subdirectory that can1267 * hold references:1268 */1269 refs->loose =create_dir_entry(refs,"",0,0);1270/*1271 * Create an incomplete entry for "refs/":1272 */1273add_entry_to_dir(get_ref_dir(refs->loose),1274create_dir_entry(refs,"refs/",5,1));1275}1276returnget_ref_dir(refs->loose);1277}12781279/* We allow "recursive" symbolic refs. Only within reason, though */1280#define MAXDEPTH 51281#define MAXREFLEN (1024)12821283/*1284 * Called by resolve_gitlink_ref_recursive() after it failed to read1285 * from the loose refs in ref_cache refs. Find <refname> in the1286 * packed-refs file for the submodule.1287 */1288static intresolve_gitlink_packed_ref(struct ref_cache *refs,1289const char*refname,unsigned char*sha1)1290{1291struct ref_entry *ref;1292struct ref_dir *dir =get_packed_refs(refs);12931294 ref =find_ref(dir, refname);1295if(ref == NULL)1296return-1;12971298hashcpy(sha1, ref->u.value.sha1);1299return0;1300}13011302static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1303const char*refname,unsigned char*sha1,1304int recursion)1305{1306int fd, len;1307char buffer[128], *p;1308char*path;13091310if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1311return-1;1312 path = *refs->name1313?git_path_submodule(refs->name,"%s", refname)1314:git_path("%s", refname);1315 fd =open(path, O_RDONLY);1316if(fd <0)1317returnresolve_gitlink_packed_ref(refs, refname, sha1);13181319 len =read(fd, buffer,sizeof(buffer)-1);1320close(fd);1321if(len <0)1322return-1;1323while(len &&isspace(buffer[len-1]))1324 len--;1325 buffer[len] =0;13261327/* Was it a detached head or an old-fashioned symlink? */1328if(!get_sha1_hex(buffer, sha1))1329return0;13301331/* Symref? */1332if(strncmp(buffer,"ref:",4))1333return-1;1334 p = buffer +4;1335while(isspace(*p))1336 p++;13371338returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1339}13401341intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1342{1343int len =strlen(path), retval;1344char*submodule;1345struct ref_cache *refs;13461347while(len && path[len-1] =='/')1348 len--;1349if(!len)1350return-1;1351 submodule =xstrndup(path, len);1352 refs =get_ref_cache(submodule);1353free(submodule);13541355 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1356return retval;1357}13581359/*1360 * Return the ref_entry for the given refname from the packed1361 * references. If it does not exist, return NULL.1362 */1363static struct ref_entry *get_packed_ref(const char*refname)1364{1365returnfind_ref(get_packed_refs(&ref_cache), refname);1366}13671368/*1369 * A loose ref file doesn't exist; check for a packed ref. The1370 * options are forwarded from resolve_safe_unsafe().1371 */1372static const char*handle_missing_loose_ref(const char*refname,1373int resolve_flags,1374unsigned char*sha1,1375int*flags)1376{1377struct ref_entry *entry;13781379/*1380 * The loose reference file does not exist; check for a packed1381 * reference.1382 */1383 entry =get_packed_ref(refname);1384if(entry) {1385hashcpy(sha1, entry->u.value.sha1);1386if(flags)1387*flags |= REF_ISPACKED;1388return refname;1389}1390/* The reference is not a packed reference, either. */1391if(resolve_flags & RESOLVE_REF_READING) {1392return NULL;1393}else{1394hashclr(sha1);1395return refname;1396}1397}13981399/* This function needs to return a meaningful errno on failure */1400const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1401{1402int depth = MAXDEPTH;1403 ssize_t len;1404char buffer[256];1405static char refname_buffer[256];14061407if(flags)1408*flags =0;14091410if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1411 errno = EINVAL;1412return NULL;1413}1414for(;;) {1415char path[PATH_MAX];1416struct stat st;1417char*buf;1418int fd;14191420if(--depth <0) {1421 errno = ELOOP;1422return NULL;1423}14241425git_snpath(path,sizeof(path),"%s", refname);14261427/*1428 * We might have to loop back here to avoid a race1429 * condition: first we lstat() the file, then we try1430 * to read it as a link or as a file. But if somebody1431 * changes the type of the file (file <-> directory1432 * <-> symlink) between the lstat() and reading, then1433 * we don't want to report that as an error but rather1434 * try again starting with the lstat().1435 */1436 stat_ref:1437if(lstat(path, &st) <0) {1438if(errno == ENOENT)1439returnhandle_missing_loose_ref(refname,1440 resolve_flags, sha1, flags);1441else1442return NULL;1443}14441445/* Follow "normalized" - ie "refs/.." symlinks by hand */1446if(S_ISLNK(st.st_mode)) {1447 len =readlink(path, buffer,sizeof(buffer)-1);1448if(len <0) {1449if(errno == ENOENT || errno == EINVAL)1450/* inconsistent with lstat; retry */1451goto stat_ref;1452else1453return NULL;1454}1455 buffer[len] =0;1456if(starts_with(buffer,"refs/") &&1457!check_refname_format(buffer,0)) {1458strcpy(refname_buffer, buffer);1459 refname = refname_buffer;1460if(flags)1461*flags |= REF_ISSYMREF;1462if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1463hashclr(sha1);1464return refname;1465}1466continue;1467}1468}14691470/* Is it a directory? */1471if(S_ISDIR(st.st_mode)) {1472 errno = EISDIR;1473return NULL;1474}14751476/*1477 * Anything else, just open it and try to use it as1478 * a ref1479 */1480 fd =open(path, O_RDONLY);1481if(fd <0) {1482if(errno == ENOENT)1483/* inconsistent with lstat; retry */1484goto stat_ref;1485else1486return NULL;1487}1488 len =read_in_full(fd, buffer,sizeof(buffer)-1);1489if(len <0) {1490int save_errno = errno;1491close(fd);1492 errno = save_errno;1493return NULL;1494}1495close(fd);1496while(len &&isspace(buffer[len-1]))1497 len--;1498 buffer[len] ='\0';14991500/*1501 * Is it a symbolic ref?1502 */1503if(!starts_with(buffer,"ref:")) {1504/*1505 * Please note that FETCH_HEAD has a second1506 * line containing other data.1507 */1508if(get_sha1_hex(buffer, sha1) ||1509(buffer[40] !='\0'&& !isspace(buffer[40]))) {1510if(flags)1511*flags |= REF_ISBROKEN;1512 errno = EINVAL;1513return NULL;1514}1515return refname;1516}1517if(flags)1518*flags |= REF_ISSYMREF;1519 buf = buffer +4;1520while(isspace(*buf))1521 buf++;1522 refname =strcpy(refname_buffer, buf);1523if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1524hashclr(sha1);1525return refname;1526}1527if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1528if(flags)1529*flags |= REF_ISBROKEN;1530 errno = EINVAL;1531return NULL;1532}1533}1534}15351536char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1537{1538const char*ret =resolve_ref_unsafe(ref, resolve_flags, sha1, flags);1539return ret ?xstrdup(ret) : NULL;1540}15411542/* The argument to filter_refs */1543struct ref_filter {1544const char*pattern;1545 each_ref_fn *fn;1546void*cb_data;1547};15481549intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1550{1551if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1552return0;1553return-1;1554}15551556intread_ref(const char*refname,unsigned char*sha1)1557{1558returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1559}15601561intref_exists(const char*refname)1562{1563unsigned char sha1[20];1564return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1565}15661567static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1568void*data)1569{1570struct ref_filter *filter = (struct ref_filter *)data;1571if(wildmatch(filter->pattern, refname,0, NULL))1572return0;1573return filter->fn(refname, sha1, flags, filter->cb_data);1574}15751576enum peel_status {1577/* object was peeled successfully: */1578 PEEL_PEELED =0,15791580/*1581 * object cannot be peeled because the named object (or an1582 * object referred to by a tag in the peel chain), does not1583 * exist.1584 */1585 PEEL_INVALID = -1,15861587/* object cannot be peeled because it is not a tag: */1588 PEEL_NON_TAG = -2,15891590/* ref_entry contains no peeled value because it is a symref: */1591 PEEL_IS_SYMREF = -3,15921593/*1594 * ref_entry cannot be peeled because it is broken (i.e., the1595 * symbolic reference cannot even be resolved to an object1596 * name):1597 */1598 PEEL_BROKEN = -41599};16001601/*1602 * Peel the named object; i.e., if the object is a tag, resolve the1603 * tag recursively until a non-tag is found. If successful, store the1604 * result to sha1 and return PEEL_PEELED. If the object is not a tag1605 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1606 * and leave sha1 unchanged.1607 */1608static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1609{1610struct object *o =lookup_unknown_object(name);16111612if(o->type == OBJ_NONE) {1613int type =sha1_object_info(name, NULL);1614if(type <0|| !object_as_type(o, type,0))1615return PEEL_INVALID;1616}16171618if(o->type != OBJ_TAG)1619return PEEL_NON_TAG;16201621 o =deref_tag_noverify(o);1622if(!o)1623return PEEL_INVALID;16241625hashcpy(sha1, o->sha1);1626return PEEL_PEELED;1627}16281629/*1630 * Peel the entry (if possible) and return its new peel_status. If1631 * repeel is true, re-peel the entry even if there is an old peeled1632 * value that is already stored in it.1633 *1634 * It is OK to call this function with a packed reference entry that1635 * might be stale and might even refer to an object that has since1636 * been garbage-collected. In such a case, if the entry has1637 * REF_KNOWS_PEELED then leave the status unchanged and return1638 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1639 */1640static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1641{1642enum peel_status status;16431644if(entry->flag & REF_KNOWS_PEELED) {1645if(repeel) {1646 entry->flag &= ~REF_KNOWS_PEELED;1647hashclr(entry->u.value.peeled);1648}else{1649returnis_null_sha1(entry->u.value.peeled) ?1650 PEEL_NON_TAG : PEEL_PEELED;1651}1652}1653if(entry->flag & REF_ISBROKEN)1654return PEEL_BROKEN;1655if(entry->flag & REF_ISSYMREF)1656return PEEL_IS_SYMREF;16571658 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1659if(status == PEEL_PEELED || status == PEEL_NON_TAG)1660 entry->flag |= REF_KNOWS_PEELED;1661return status;1662}16631664intpeel_ref(const char*refname,unsigned char*sha1)1665{1666int flag;1667unsigned char base[20];16681669if(current_ref && (current_ref->name == refname1670|| !strcmp(current_ref->name, refname))) {1671if(peel_entry(current_ref,0))1672return-1;1673hashcpy(sha1, current_ref->u.value.peeled);1674return0;1675}16761677if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1678return-1;16791680/*1681 * If the reference is packed, read its ref_entry from the1682 * cache in the hope that we already know its peeled value.1683 * We only try this optimization on packed references because1684 * (a) forcing the filling of the loose reference cache could1685 * be expensive and (b) loose references anyway usually do not1686 * have REF_KNOWS_PEELED.1687 */1688if(flag & REF_ISPACKED) {1689struct ref_entry *r =get_packed_ref(refname);1690if(r) {1691if(peel_entry(r,0))1692return-1;1693hashcpy(sha1, r->u.value.peeled);1694return0;1695}1696}16971698returnpeel_object(base, sha1);1699}17001701struct warn_if_dangling_data {1702FILE*fp;1703const char*refname;1704const struct string_list *refnames;1705const char*msg_fmt;1706};17071708static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1709int flags,void*cb_data)1710{1711struct warn_if_dangling_data *d = cb_data;1712const char*resolves_to;1713unsigned char junk[20];17141715if(!(flags & REF_ISSYMREF))1716return0;17171718 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1719if(!resolves_to1720|| (d->refname1721?strcmp(resolves_to, d->refname)1722: !string_list_has_string(d->refnames, resolves_to))) {1723return0;1724}17251726fprintf(d->fp, d->msg_fmt, refname);1727fputc('\n', d->fp);1728return0;1729}17301731voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1732{1733struct warn_if_dangling_data data;17341735 data.fp = fp;1736 data.refname = refname;1737 data.refnames = NULL;1738 data.msg_fmt = msg_fmt;1739for_each_rawref(warn_if_dangling_symref, &data);1740}17411742voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1743{1744struct warn_if_dangling_data data;17451746 data.fp = fp;1747 data.refname = NULL;1748 data.refnames = refnames;1749 data.msg_fmt = msg_fmt;1750for_each_rawref(warn_if_dangling_symref, &data);1751}17521753/*1754 * Call fn for each reference in the specified ref_cache, omitting1755 * references not in the containing_dir of base. fn is called for all1756 * references, including broken ones. If fn ever returns a non-zero1757 * value, stop the iteration and return that value; otherwise, return1758 * 0.1759 */1760static intdo_for_each_entry(struct ref_cache *refs,const char*base,1761 each_ref_entry_fn fn,void*cb_data)1762{1763struct packed_ref_cache *packed_ref_cache;1764struct ref_dir *loose_dir;1765struct ref_dir *packed_dir;1766int retval =0;17671768/*1769 * We must make sure that all loose refs are read before accessing the1770 * packed-refs file; this avoids a race condition in which loose refs1771 * are migrated to the packed-refs file by a simultaneous process, but1772 * our in-memory view is from before the migration. get_packed_ref_cache()1773 * takes care of making sure our view is up to date with what is on1774 * disk.1775 */1776 loose_dir =get_loose_refs(refs);1777if(base && *base) {1778 loose_dir =find_containing_dir(loose_dir, base,0);1779}1780if(loose_dir)1781prime_ref_dir(loose_dir);17821783 packed_ref_cache =get_packed_ref_cache(refs);1784acquire_packed_ref_cache(packed_ref_cache);1785 packed_dir =get_packed_ref_dir(packed_ref_cache);1786if(base && *base) {1787 packed_dir =find_containing_dir(packed_dir, base,0);1788}17891790if(packed_dir && loose_dir) {1791sort_ref_dir(packed_dir);1792sort_ref_dir(loose_dir);1793 retval =do_for_each_entry_in_dirs(1794 packed_dir, loose_dir, fn, cb_data);1795}else if(packed_dir) {1796sort_ref_dir(packed_dir);1797 retval =do_for_each_entry_in_dir(1798 packed_dir,0, fn, cb_data);1799}else if(loose_dir) {1800sort_ref_dir(loose_dir);1801 retval =do_for_each_entry_in_dir(1802 loose_dir,0, fn, cb_data);1803}18041805release_packed_ref_cache(packed_ref_cache);1806return retval;1807}18081809/*1810 * Call fn for each reference in the specified ref_cache for which the1811 * refname begins with base. If trim is non-zero, then trim that many1812 * characters off the beginning of each refname before passing the1813 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1814 * broken references in the iteration. If fn ever returns a non-zero1815 * value, stop the iteration and return that value; otherwise, return1816 * 0.1817 */1818static intdo_for_each_ref(struct ref_cache *refs,const char*base,1819 each_ref_fn fn,int trim,int flags,void*cb_data)1820{1821struct ref_entry_cb data;1822 data.base = base;1823 data.trim = trim;1824 data.flags = flags;1825 data.fn = fn;1826 data.cb_data = cb_data;18271828returndo_for_each_entry(refs, base, do_one_ref, &data);1829}18301831static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1832{1833unsigned char sha1[20];1834int flag;18351836if(submodule) {1837if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1838returnfn("HEAD", sha1,0, cb_data);18391840return0;1841}18421843if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))1844returnfn("HEAD", sha1, flag, cb_data);18451846return0;1847}18481849inthead_ref(each_ref_fn fn,void*cb_data)1850{1851returndo_head_ref(NULL, fn, cb_data);1852}18531854inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1855{1856returndo_head_ref(submodule, fn, cb_data);1857}18581859intfor_each_ref(each_ref_fn fn,void*cb_data)1860{1861returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1862}18631864intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1865{1866returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1867}18681869intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1870{1871returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1872}18731874intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1875 each_ref_fn fn,void*cb_data)1876{1877returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1878}18791880intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1881{1882returnfor_each_ref_in("refs/tags/", fn, cb_data);1883}18841885intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1886{1887returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1888}18891890intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1891{1892returnfor_each_ref_in("refs/heads/", fn, cb_data);1893}18941895intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1896{1897returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1898}18991900intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1901{1902returnfor_each_ref_in("refs/remotes/", fn, cb_data);1903}19041905intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1906{1907returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);1908}19091910intfor_each_replace_ref(each_ref_fn fn,void*cb_data)1911{1912returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);1913}19141915inthead_ref_namespaced(each_ref_fn fn,void*cb_data)1916{1917struct strbuf buf = STRBUF_INIT;1918int ret =0;1919unsigned char sha1[20];1920int flag;19211922strbuf_addf(&buf,"%sHEAD",get_git_namespace());1923if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))1924 ret =fn(buf.buf, sha1, flag, cb_data);1925strbuf_release(&buf);19261927return ret;1928}19291930intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)1931{1932struct strbuf buf = STRBUF_INIT;1933int ret;1934strbuf_addf(&buf,"%srefs/",get_git_namespace());1935 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);1936strbuf_release(&buf);1937return ret;1938}19391940intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,1941const char*prefix,void*cb_data)1942{1943struct strbuf real_pattern = STRBUF_INIT;1944struct ref_filter filter;1945int ret;19461947if(!prefix && !starts_with(pattern,"refs/"))1948strbuf_addstr(&real_pattern,"refs/");1949else if(prefix)1950strbuf_addstr(&real_pattern, prefix);1951strbuf_addstr(&real_pattern, pattern);19521953if(!has_glob_specials(pattern)) {1954/* Append implied '/' '*' if not present. */1955if(real_pattern.buf[real_pattern.len -1] !='/')1956strbuf_addch(&real_pattern,'/');1957/* No need to check for '*', there is none. */1958strbuf_addch(&real_pattern,'*');1959}19601961 filter.pattern = real_pattern.buf;1962 filter.fn = fn;1963 filter.cb_data = cb_data;1964 ret =for_each_ref(filter_refs, &filter);19651966strbuf_release(&real_pattern);1967return ret;1968}19691970intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)1971{1972returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);1973}19741975intfor_each_rawref(each_ref_fn fn,void*cb_data)1976{1977returndo_for_each_ref(&ref_cache,"", fn,0,1978 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);1979}19801981const char*prettify_refname(const char*name)1982{1983return name + (1984starts_with(name,"refs/heads/") ?11:1985starts_with(name,"refs/tags/") ?10:1986starts_with(name,"refs/remotes/") ?13:19870);1988}19891990static const char*ref_rev_parse_rules[] = {1991"%.*s",1992"refs/%.*s",1993"refs/tags/%.*s",1994"refs/heads/%.*s",1995"refs/remotes/%.*s",1996"refs/remotes/%.*s/HEAD",1997 NULL1998};19992000intrefname_match(const char*abbrev_name,const char*full_name)2001{2002const char**p;2003const int abbrev_name_len =strlen(abbrev_name);20042005for(p = ref_rev_parse_rules; *p; p++) {2006if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2007return1;2008}2009}20102011return0;2012}20132014/* This function should make sure errno is meaningful on error */2015static struct ref_lock *verify_lock(struct ref_lock *lock,2016const unsigned char*old_sha1,int mustexist)2017{2018if(read_ref_full(lock->ref_name,2019 mustexist ? RESOLVE_REF_READING :0,2020 lock->old_sha1, NULL)) {2021int save_errno = errno;2022error("Can't verify ref%s", lock->ref_name);2023unlock_ref(lock);2024 errno = save_errno;2025return NULL;2026}2027if(hashcmp(lock->old_sha1, old_sha1)) {2028error("Ref%sis at%sbut expected%s", lock->ref_name,2029sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2030unlock_ref(lock);2031 errno = EBUSY;2032return NULL;2033}2034return lock;2035}20362037static intremove_empty_directories(const char*file)2038{2039/* we want to create a file but there is a directory there;2040 * if that is an empty directory (or a directory that contains2041 * only empty directories), remove them.2042 */2043struct strbuf path;2044int result, save_errno;20452046strbuf_init(&path,20);2047strbuf_addstr(&path, file);20482049 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2050 save_errno = errno;20512052strbuf_release(&path);2053 errno = save_errno;20542055return result;2056}20572058/*2059 * *string and *len will only be substituted, and *string returned (for2060 * later free()ing) if the string passed in is a magic short-hand form2061 * to name a branch.2062 */2063static char*substitute_branch_name(const char**string,int*len)2064{2065struct strbuf buf = STRBUF_INIT;2066int ret =interpret_branch_name(*string, *len, &buf);20672068if(ret == *len) {2069size_t size;2070*string =strbuf_detach(&buf, &size);2071*len = size;2072return(char*)*string;2073}20742075return NULL;2076}20772078intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2079{2080char*last_branch =substitute_branch_name(&str, &len);2081const char**p, *r;2082int refs_found =0;20832084*ref = NULL;2085for(p = ref_rev_parse_rules; *p; p++) {2086char fullref[PATH_MAX];2087unsigned char sha1_from_ref[20];2088unsigned char*this_result;2089int flag;20902091 this_result = refs_found ? sha1_from_ref : sha1;2092mksnpath(fullref,sizeof(fullref), *p, len, str);2093 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2094 this_result, &flag);2095if(r) {2096if(!refs_found++)2097*ref =xstrdup(r);2098if(!warn_ambiguous_refs)2099break;2100}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2101warning("ignoring dangling symref%s.", fullref);2102}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2103warning("ignoring broken ref%s.", fullref);2104}2105}2106free(last_branch);2107return refs_found;2108}21092110intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2111{2112char*last_branch =substitute_branch_name(&str, &len);2113const char**p;2114int logs_found =0;21152116*log = NULL;2117for(p = ref_rev_parse_rules; *p; p++) {2118unsigned char hash[20];2119char path[PATH_MAX];2120const char*ref, *it;21212122mksnpath(path,sizeof(path), *p, len, str);2123 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2124 hash, NULL);2125if(!ref)2126continue;2127if(reflog_exists(path))2128 it = path;2129else if(strcmp(ref, path) &&reflog_exists(ref))2130 it = ref;2131else2132continue;2133if(!logs_found++) {2134*log =xstrdup(it);2135hashcpy(sha1, hash);2136}2137if(!warn_ambiguous_refs)2138break;2139}2140free(last_branch);2141return logs_found;2142}21432144/*2145 * Locks a ref returning the lock on success and NULL on failure.2146 * On failure errno is set to something meaningful.2147 */2148static struct ref_lock *lock_ref_sha1_basic(const char*refname,2149const unsigned char*old_sha1,2150const struct string_list *skip,2151int flags,int*type_p)2152{2153char*ref_file;2154const char*orig_refname = refname;2155struct ref_lock *lock;2156int last_errno =0;2157int type, lflags;2158int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2159int resolve_flags =0;2160int missing =0;2161int attempts_remaining =3;21622163if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {2164 errno = EINVAL;2165return NULL;2166}21672168 lock =xcalloc(1,sizeof(struct ref_lock));2169 lock->lock_fd = -1;21702171if(mustexist)2172 resolve_flags |= RESOLVE_REF_READING;2173if(flags & REF_NODEREF && flags & REF_DELETING)2174 resolve_flags |= RESOLVE_REF_NO_RECURSE;21752176 refname =resolve_ref_unsafe(refname, resolve_flags,2177 lock->old_sha1, &type);2178if(!refname && errno == EISDIR) {2179/* we are trying to lock foo but we used to2180 * have foo/bar which now does not exist;2181 * it is normal for the empty directory 'foo'2182 * to remain.2183 */2184 ref_file =git_path("%s", orig_refname);2185if(remove_empty_directories(ref_file)) {2186 last_errno = errno;2187error("there are still refs under '%s'", orig_refname);2188goto error_return;2189}2190 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2191 lock->old_sha1, &type);2192}2193if(type_p)2194*type_p = type;2195if(!refname) {2196 last_errno = errno;2197error("unable to resolve reference%s:%s",2198 orig_refname,strerror(errno));2199goto error_return;2200}2201 missing =is_null_sha1(lock->old_sha1);2202/* When the ref did not exist and we are creating it,2203 * make sure there is no existing ref that is packed2204 * whose name begins with our refname, nor a ref whose2205 * name is a proper prefix of our refname.2206 */2207if(missing &&2208!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2209 last_errno = ENOTDIR;2210goto error_return;2211}22122213 lock->lk =xcalloc(1,sizeof(struct lock_file));22142215 lflags =0;2216if(flags & REF_NODEREF) {2217 refname = orig_refname;2218 lflags |= LOCK_NO_DEREF;2219}2220 lock->ref_name =xstrdup(refname);2221 lock->orig_ref_name =xstrdup(orig_refname);2222 ref_file =git_path("%s", refname);2223if(missing)2224 lock->force_write =1;2225if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2226 lock->force_write =1;22272228 retry:2229switch(safe_create_leading_directories(ref_file)) {2230case SCLD_OK:2231break;/* success */2232case SCLD_VANISHED:2233if(--attempts_remaining >0)2234goto retry;2235/* fall through */2236default:2237 last_errno = errno;2238error("unable to create directory for%s", ref_file);2239goto error_return;2240}22412242 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2243if(lock->lock_fd <0) {2244if(errno == ENOENT && --attempts_remaining >0)2245/*2246 * Maybe somebody just deleted one of the2247 * directories leading to ref_file. Try2248 * again:2249 */2250goto retry;2251else2252unable_to_lock_die(ref_file, errno);2253}2254return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;22552256 error_return:2257unlock_ref(lock);2258 errno = last_errno;2259return NULL;2260}22612262struct ref_lock *lock_any_ref_for_update(const char*refname,2263const unsigned char*old_sha1,2264int flags,int*type_p)2265{2266returnlock_ref_sha1_basic(refname, old_sha1, NULL, flags, type_p);2267}22682269/*2270 * Write an entry to the packed-refs file for the specified refname.2271 * If peeled is non-NULL, write it as the entry's peeled value.2272 */2273static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2274unsigned char*peeled)2275{2276fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2277if(peeled)2278fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2279}22802281/*2282 * An each_ref_entry_fn that writes the entry to a packed-refs file.2283 */2284static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2285{2286enum peel_status peel_status =peel_entry(entry,0);22872288if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2289error("internal error:%sis not a valid packed reference!",2290 entry->name);2291write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2292 peel_status == PEEL_PEELED ?2293 entry->u.value.peeled : NULL);2294return0;2295}22962297/* This should return a meaningful errno on failure */2298intlock_packed_refs(int flags)2299{2300struct packed_ref_cache *packed_ref_cache;23012302if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2303return-1;2304/*2305 * Get the current packed-refs while holding the lock. If the2306 * packed-refs file has been modified since we last read it,2307 * this will automatically invalidate the cache and re-read2308 * the packed-refs file.2309 */2310 packed_ref_cache =get_packed_ref_cache(&ref_cache);2311 packed_ref_cache->lock = &packlock;2312/* Increment the reference count to prevent it from being freed: */2313acquire_packed_ref_cache(packed_ref_cache);2314return0;2315}23162317/*2318 * Commit the packed refs changes.2319 * On error we must make sure that errno contains a meaningful value.2320 */2321intcommit_packed_refs(void)2322{2323struct packed_ref_cache *packed_ref_cache =2324get_packed_ref_cache(&ref_cache);2325int error =0;2326int save_errno =0;2327FILE*out;23282329if(!packed_ref_cache->lock)2330die("internal error: packed-refs not locked");23312332 out =fdopen_lock_file(packed_ref_cache->lock,"w");2333if(!out)2334die_errno("unable to fdopen packed-refs descriptor");23352336fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2337do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),23380, write_packed_entry_fn, out);23392340if(commit_lock_file(packed_ref_cache->lock)) {2341 save_errno = errno;2342 error = -1;2343}2344 packed_ref_cache->lock = NULL;2345release_packed_ref_cache(packed_ref_cache);2346 errno = save_errno;2347return error;2348}23492350voidrollback_packed_refs(void)2351{2352struct packed_ref_cache *packed_ref_cache =2353get_packed_ref_cache(&ref_cache);23542355if(!packed_ref_cache->lock)2356die("internal error: packed-refs not locked");2357rollback_lock_file(packed_ref_cache->lock);2358 packed_ref_cache->lock = NULL;2359release_packed_ref_cache(packed_ref_cache);2360clear_packed_ref_cache(&ref_cache);2361}23622363struct ref_to_prune {2364struct ref_to_prune *next;2365unsigned char sha1[20];2366char name[FLEX_ARRAY];2367};23682369struct pack_refs_cb_data {2370unsigned int flags;2371struct ref_dir *packed_refs;2372struct ref_to_prune *ref_to_prune;2373};23742375/*2376 * An each_ref_entry_fn that is run over loose references only. If2377 * the loose reference can be packed, add an entry in the packed ref2378 * cache. If the reference should be pruned, also add it to2379 * ref_to_prune in the pack_refs_cb_data.2380 */2381static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2382{2383struct pack_refs_cb_data *cb = cb_data;2384enum peel_status peel_status;2385struct ref_entry *packed_entry;2386int is_tag_ref =starts_with(entry->name,"refs/tags/");23872388/* ALWAYS pack tags */2389if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2390return0;23912392/* Do not pack symbolic or broken refs: */2393if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2394return0;23952396/* Add a packed ref cache entry equivalent to the loose entry. */2397 peel_status =peel_entry(entry,1);2398if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2399die("internal error peeling reference%s(%s)",2400 entry->name,sha1_to_hex(entry->u.value.sha1));2401 packed_entry =find_ref(cb->packed_refs, entry->name);2402if(packed_entry) {2403/* Overwrite existing packed entry with info from loose entry */2404 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2405hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2406}else{2407 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2408 REF_ISPACKED | REF_KNOWS_PEELED,0);2409add_ref(cb->packed_refs, packed_entry);2410}2411hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);24122413/* Schedule the loose reference for pruning if requested. */2414if((cb->flags & PACK_REFS_PRUNE)) {2415int namelen =strlen(entry->name) +1;2416struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2417hashcpy(n->sha1, entry->u.value.sha1);2418strcpy(n->name, entry->name);2419 n->next = cb->ref_to_prune;2420 cb->ref_to_prune = n;2421}2422return0;2423}24242425/*2426 * Remove empty parents, but spare refs/ and immediate subdirs.2427 * Note: munges *name.2428 */2429static voidtry_remove_empty_parents(char*name)2430{2431char*p, *q;2432int i;2433 p = name;2434for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2435while(*p && *p !='/')2436 p++;2437/* tolerate duplicate slashes; see check_refname_format() */2438while(*p =='/')2439 p++;2440}2441for(q = p; *q; q++)2442;2443while(1) {2444while(q > p && *q !='/')2445 q--;2446while(q > p && *(q-1) =='/')2447 q--;2448if(q == p)2449break;2450*q ='\0';2451if(rmdir(git_path("%s", name)))2452break;2453}2454}24552456/* make sure nobody touched the ref, and unlink */2457static voidprune_ref(struct ref_to_prune *r)2458{2459struct ref_transaction *transaction;2460struct strbuf err = STRBUF_INIT;24612462if(check_refname_format(r->name,0))2463return;24642465 transaction =ref_transaction_begin(&err);2466if(!transaction ||2467ref_transaction_delete(transaction, r->name, r->sha1,2468 REF_ISPRUNING,1, NULL, &err) ||2469ref_transaction_commit(transaction, &err)) {2470ref_transaction_free(transaction);2471error("%s", err.buf);2472strbuf_release(&err);2473return;2474}2475ref_transaction_free(transaction);2476strbuf_release(&err);2477try_remove_empty_parents(r->name);2478}24792480static voidprune_refs(struct ref_to_prune *r)2481{2482while(r) {2483prune_ref(r);2484 r = r->next;2485}2486}24872488intpack_refs(unsigned int flags)2489{2490struct pack_refs_cb_data cbdata;24912492memset(&cbdata,0,sizeof(cbdata));2493 cbdata.flags = flags;24942495lock_packed_refs(LOCK_DIE_ON_ERROR);2496 cbdata.packed_refs =get_packed_refs(&ref_cache);24972498do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2499 pack_if_possible_fn, &cbdata);25002501if(commit_packed_refs())2502die_errno("unable to overwrite old ref-pack file");25032504prune_refs(cbdata.ref_to_prune);2505return0;2506}25072508/*2509 * If entry is no longer needed in packed-refs, add it to the string2510 * list pointed to by cb_data. Reasons for deleting entries:2511 *2512 * - Entry is broken.2513 * - Entry is overridden by a loose ref.2514 * - Entry does not point at a valid object.2515 *2516 * In the first and third cases, also emit an error message because these2517 * are indications of repository corruption.2518 */2519static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2520{2521struct string_list *refs_to_delete = cb_data;25222523if(entry->flag & REF_ISBROKEN) {2524/* This shouldn't happen to packed refs. */2525error("%sis broken!", entry->name);2526string_list_append(refs_to_delete, entry->name);2527return0;2528}2529if(!has_sha1_file(entry->u.value.sha1)) {2530unsigned char sha1[20];2531int flags;25322533if(read_ref_full(entry->name,0, sha1, &flags))2534/* We should at least have found the packed ref. */2535die("Internal error");2536if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2537/*2538 * This packed reference is overridden by a2539 * loose reference, so it is OK that its value2540 * is no longer valid; for example, it might2541 * refer to an object that has been garbage2542 * collected. For this purpose we don't even2543 * care whether the loose reference itself is2544 * invalid, broken, symbolic, etc. Silently2545 * remove the packed reference.2546 */2547string_list_append(refs_to_delete, entry->name);2548return0;2549}2550/*2551 * There is no overriding loose reference, so the fact2552 * that this reference doesn't refer to a valid object2553 * indicates some kind of repository corruption.2554 * Report the problem, then omit the reference from2555 * the output.2556 */2557error("%sdoes not point to a valid object!", entry->name);2558string_list_append(refs_to_delete, entry->name);2559return0;2560}25612562return0;2563}25642565intrepack_without_refs(const char**refnames,int n,struct strbuf *err)2566{2567struct ref_dir *packed;2568struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2569struct string_list_item *ref_to_delete;2570int i, ret, removed =0;25712572/* Look for a packed ref */2573for(i =0; i < n; i++)2574if(get_packed_ref(refnames[i]))2575break;25762577/* Avoid locking if we have nothing to do */2578if(i == n)2579return0;/* no refname exists in packed refs */25802581if(lock_packed_refs(0)) {2582if(err) {2583unable_to_lock_message(git_path("packed-refs"), errno,2584 err);2585return-1;2586}2587unable_to_lock_error(git_path("packed-refs"), errno);2588returnerror("cannot delete '%s' from packed refs", refnames[i]);2589}2590 packed =get_packed_refs(&ref_cache);25912592/* Remove refnames from the cache */2593for(i =0; i < n; i++)2594if(remove_entry(packed, refnames[i]) != -1)2595 removed =1;2596if(!removed) {2597/*2598 * All packed entries disappeared while we were2599 * acquiring the lock.2600 */2601rollback_packed_refs();2602return0;2603}26042605/* Remove any other accumulated cruft */2606do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2607for_each_string_list_item(ref_to_delete, &refs_to_delete) {2608if(remove_entry(packed, ref_to_delete->string) == -1)2609die("internal error");2610}26112612/* Write what remains */2613 ret =commit_packed_refs();2614if(ret && err)2615strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2616strerror(errno));2617return ret;2618}26192620static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2621{2622if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2623/*2624 * loose. The loose file name is the same as the2625 * lockfile name, minus ".lock":2626 */2627char*loose_filename =get_locked_file_path(lock->lk);2628int res =unlink_or_msg(loose_filename, err);2629free(loose_filename);2630if(res)2631return1;2632}2633return0;2634}26352636intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2637{2638struct ref_transaction *transaction;2639struct strbuf err = STRBUF_INIT;26402641 transaction =ref_transaction_begin(&err);2642if(!transaction ||2643ref_transaction_delete(transaction, refname, sha1, delopt,2644 sha1 && !is_null_sha1(sha1), NULL, &err) ||2645ref_transaction_commit(transaction, &err)) {2646error("%s", err.buf);2647ref_transaction_free(transaction);2648strbuf_release(&err);2649return1;2650}2651ref_transaction_free(transaction);2652strbuf_release(&err);2653return0;2654}26552656/*2657 * People using contrib's git-new-workdir have .git/logs/refs ->2658 * /some/other/path/.git/logs/refs, and that may live on another device.2659 *2660 * IOW, to avoid cross device rename errors, the temporary renamed log must2661 * live into logs/refs.2662 */2663#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"26642665static intrename_tmp_log(const char*newrefname)2666{2667int attempts_remaining =4;26682669 retry:2670switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2671case SCLD_OK:2672break;/* success */2673case SCLD_VANISHED:2674if(--attempts_remaining >0)2675goto retry;2676/* fall through */2677default:2678error("unable to create directory for%s", newrefname);2679return-1;2680}26812682if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2683if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2684/*2685 * rename(a, b) when b is an existing2686 * directory ought to result in ISDIR, but2687 * Solaris 5.8 gives ENOTDIR. Sheesh.2688 */2689if(remove_empty_directories(git_path("logs/%s", newrefname))) {2690error("Directory not empty: logs/%s", newrefname);2691return-1;2692}2693goto retry;2694}else if(errno == ENOENT && --attempts_remaining >0) {2695/*2696 * Maybe another process just deleted one of2697 * the directories in the path to newrefname.2698 * Try again from the beginning.2699 */2700goto retry;2701}else{2702error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2703 newrefname,strerror(errno));2704return-1;2705}2706}2707return0;2708}27092710static intrename_ref_available(const char*oldname,const char*newname)2711{2712struct string_list skip = STRING_LIST_INIT_NODUP;2713int ret;27142715string_list_insert(&skip, oldname);2716 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2717&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2718string_list_clear(&skip,0);2719return ret;2720}27212722static intwrite_ref_sha1(struct ref_lock *lock,const unsigned char*sha1,2723const char*logmsg);27242725intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2726{2727unsigned char sha1[20], orig_sha1[20];2728int flag =0, logmoved =0;2729struct ref_lock *lock;2730struct stat loginfo;2731int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2732const char*symref = NULL;27332734if(log &&S_ISLNK(loginfo.st_mode))2735returnerror("reflog for%sis a symlink", oldrefname);27362737 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2738 orig_sha1, &flag);2739if(flag & REF_ISSYMREF)2740returnerror("refname%sis a symbolic ref, renaming it is not supported",2741 oldrefname);2742if(!symref)2743returnerror("refname%snot found", oldrefname);27442745if(!rename_ref_available(oldrefname, newrefname))2746return1;27472748if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2749returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2750 oldrefname,strerror(errno));27512752if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2753error("unable to delete old%s", oldrefname);2754goto rollback;2755}27562757if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2758delete_ref(newrefname, sha1, REF_NODEREF)) {2759if(errno==EISDIR) {2760if(remove_empty_directories(git_path("%s", newrefname))) {2761error("Directory not empty:%s", newrefname);2762goto rollback;2763}2764}else{2765error("unable to delete existing%s", newrefname);2766goto rollback;2767}2768}27692770if(log &&rename_tmp_log(newrefname))2771goto rollback;27722773 logmoved = log;27742775 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2776if(!lock) {2777error("unable to lock%sfor update", newrefname);2778goto rollback;2779}2780 lock->force_write =1;2781hashcpy(lock->old_sha1, orig_sha1);2782if(write_ref_sha1(lock, orig_sha1, logmsg)) {2783error("unable to write current sha1 into%s", newrefname);2784goto rollback;2785}27862787return0;27882789 rollback:2790 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2791if(!lock) {2792error("unable to lock%sfor rollback", oldrefname);2793goto rollbacklog;2794}27952796 lock->force_write =1;2797 flag = log_all_ref_updates;2798 log_all_ref_updates =0;2799if(write_ref_sha1(lock, orig_sha1, NULL))2800error("unable to write current sha1 into%s", oldrefname);2801 log_all_ref_updates = flag;28022803 rollbacklog:2804if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2805error("unable to restore logfile%sfrom%s:%s",2806 oldrefname, newrefname,strerror(errno));2807if(!logmoved && log &&2808rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2809error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2810 oldrefname,strerror(errno));28112812return1;2813}28142815intclose_ref(struct ref_lock *lock)2816{2817if(close_lock_file(lock->lk))2818return-1;2819 lock->lock_fd = -1;2820return0;2821}28222823intcommit_ref(struct ref_lock *lock)2824{2825if(commit_lock_file(lock->lk))2826return-1;2827 lock->lock_fd = -1;2828return0;2829}28302831voidunlock_ref(struct ref_lock *lock)2832{2833/* Do not free lock->lk -- atexit() still looks at them */2834if(lock->lk)2835rollback_lock_file(lock->lk);2836free(lock->ref_name);2837free(lock->orig_ref_name);2838free(lock);2839}28402841/*2842 * copy the reflog message msg to buf, which has been allocated sufficiently2843 * large, while cleaning up the whitespaces. Especially, convert LF to space,2844 * because reflog file is one line per entry.2845 */2846static intcopy_msg(char*buf,const char*msg)2847{2848char*cp = buf;2849char c;2850int wasspace =1;28512852*cp++ ='\t';2853while((c = *msg++)) {2854if(wasspace &&isspace(c))2855continue;2856 wasspace =isspace(c);2857if(wasspace)2858 c =' ';2859*cp++ = c;2860}2861while(buf < cp &&isspace(cp[-1]))2862 cp--;2863*cp++ ='\n';2864return cp - buf;2865}28662867/* This function must set a meaningful errno on failure */2868intlog_ref_setup(const char*refname,char*logfile,int bufsize)2869{2870int logfd, oflags = O_APPEND | O_WRONLY;28712872git_snpath(logfile, bufsize,"logs/%s", refname);2873if(log_all_ref_updates &&2874(starts_with(refname,"refs/heads/") ||2875starts_with(refname,"refs/remotes/") ||2876starts_with(refname,"refs/notes/") ||2877!strcmp(refname,"HEAD"))) {2878if(safe_create_leading_directories(logfile) <0) {2879int save_errno = errno;2880error("unable to create directory for%s", logfile);2881 errno = save_errno;2882return-1;2883}2884 oflags |= O_CREAT;2885}28862887 logfd =open(logfile, oflags,0666);2888if(logfd <0) {2889if(!(oflags & O_CREAT) && errno == ENOENT)2890return0;28912892if((oflags & O_CREAT) && errno == EISDIR) {2893if(remove_empty_directories(logfile)) {2894int save_errno = errno;2895error("There are still logs under '%s'",2896 logfile);2897 errno = save_errno;2898return-1;2899}2900 logfd =open(logfile, oflags,0666);2901}29022903if(logfd <0) {2904int save_errno = errno;2905error("Unable to append to%s:%s", logfile,2906strerror(errno));2907 errno = save_errno;2908return-1;2909}2910}29112912adjust_shared_perm(logfile);2913close(logfd);2914return0;2915}29162917static intlog_ref_write(const char*refname,const unsigned char*old_sha1,2918const unsigned char*new_sha1,const char*msg)2919{2920int logfd, result, written, oflags = O_APPEND | O_WRONLY;2921unsigned maxlen, len;2922int msglen;2923char log_file[PATH_MAX];2924char*logrec;2925const char*committer;29262927if(log_all_ref_updates <0)2928 log_all_ref_updates = !is_bare_repository();29292930 result =log_ref_setup(refname, log_file,sizeof(log_file));2931if(result)2932return result;29332934 logfd =open(log_file, oflags);2935if(logfd <0)2936return0;2937 msglen = msg ?strlen(msg) :0;2938 committer =git_committer_info(0);2939 maxlen =strlen(committer) + msglen +100;2940 logrec =xmalloc(maxlen);2941 len =sprintf(logrec,"%s %s %s\n",2942sha1_to_hex(old_sha1),2943sha1_to_hex(new_sha1),2944 committer);2945if(msglen)2946 len +=copy_msg(logrec + len -1, msg) -1;2947 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;2948free(logrec);2949if(written != len) {2950int save_errno = errno;2951close(logfd);2952error("Unable to append to%s", log_file);2953 errno = save_errno;2954return-1;2955}2956if(close(logfd)) {2957int save_errno = errno;2958error("Unable to append to%s", log_file);2959 errno = save_errno;2960return-1;2961}2962return0;2963}29642965intis_branch(const char*refname)2966{2967return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");2968}29692970/*2971 * Write sha1 into the ref specified by the lock. Make sure that errno2972 * is sane on error.2973 */2974static intwrite_ref_sha1(struct ref_lock *lock,2975const unsigned char*sha1,const char*logmsg)2976{2977static char term ='\n';2978struct object *o;29792980if(!lock) {2981 errno = EINVAL;2982return-1;2983}2984if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {2985unlock_ref(lock);2986return0;2987}2988 o =parse_object(sha1);2989if(!o) {2990error("Trying to write ref%swith nonexistent object%s",2991 lock->ref_name,sha1_to_hex(sha1));2992unlock_ref(lock);2993 errno = EINVAL;2994return-1;2995}2996if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2997error("Trying to write non-commit object%sto branch%s",2998sha1_to_hex(sha1), lock->ref_name);2999unlock_ref(lock);3000 errno = EINVAL;3001return-1;3002}3003if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3004write_in_full(lock->lock_fd, &term,1) !=1||3005close_ref(lock) <0) {3006int save_errno = errno;3007error("Couldn't write%s", lock->lk->filename.buf);3008unlock_ref(lock);3009 errno = save_errno;3010return-1;3011}3012clear_loose_ref_cache(&ref_cache);3013if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3014(strcmp(lock->ref_name, lock->orig_ref_name) &&3015log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3016unlock_ref(lock);3017return-1;3018}3019if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3020/*3021 * Special hack: If a branch is updated directly and HEAD3022 * points to it (may happen on the remote side of a push3023 * for example) then logically the HEAD reflog should be3024 * updated too.3025 * A generic solution implies reverse symref information,3026 * but finding all symrefs pointing to the given branch3027 * would be rather costly for this rare event (the direct3028 * update of a branch) to be worth it. So let's cheat and3029 * check with HEAD only which should cover 99% of all usage3030 * scenarios (even 100% of the default ones).3031 */3032unsigned char head_sha1[20];3033int head_flag;3034const char*head_ref;3035 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3036 head_sha1, &head_flag);3037if(head_ref && (head_flag & REF_ISSYMREF) &&3038!strcmp(head_ref, lock->ref_name))3039log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3040}3041if(commit_ref(lock)) {3042error("Couldn't set%s", lock->ref_name);3043unlock_ref(lock);3044return-1;3045}3046unlock_ref(lock);3047return0;3048}30493050intcreate_symref(const char*ref_target,const char*refs_heads_master,3051const char*logmsg)3052{3053const char*lockpath;3054char ref[1000];3055int fd, len, written;3056char*git_HEAD =git_pathdup("%s", ref_target);3057unsigned char old_sha1[20], new_sha1[20];30583059if(logmsg &&read_ref(ref_target, old_sha1))3060hashclr(old_sha1);30613062if(safe_create_leading_directories(git_HEAD) <0)3063returnerror("unable to create directory for%s", git_HEAD);30643065#ifndef NO_SYMLINK_HEAD3066if(prefer_symlink_refs) {3067unlink(git_HEAD);3068if(!symlink(refs_heads_master, git_HEAD))3069goto done;3070fprintf(stderr,"no symlink - falling back to symbolic ref\n");3071}3072#endif30733074 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3075if(sizeof(ref) <= len) {3076error("refname too long:%s", refs_heads_master);3077goto error_free_return;3078}3079 lockpath =mkpath("%s.lock", git_HEAD);3080 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3081if(fd <0) {3082error("Unable to open%sfor writing", lockpath);3083goto error_free_return;3084}3085 written =write_in_full(fd, ref, len);3086if(close(fd) !=0|| written != len) {3087error("Unable to write to%s", lockpath);3088goto error_unlink_return;3089}3090if(rename(lockpath, git_HEAD) <0) {3091error("Unable to create%s", git_HEAD);3092goto error_unlink_return;3093}3094if(adjust_shared_perm(git_HEAD)) {3095error("Unable to fix permissions on%s", lockpath);3096 error_unlink_return:3097unlink_or_warn(lockpath);3098 error_free_return:3099free(git_HEAD);3100return-1;3101}31023103#ifndef NO_SYMLINK_HEAD3104 done:3105#endif3106if(logmsg && !read_ref(refs_heads_master, new_sha1))3107log_ref_write(ref_target, old_sha1, new_sha1, logmsg);31083109free(git_HEAD);3110return0;3111}31123113struct read_ref_at_cb {3114const char*refname;3115unsigned long at_time;3116int cnt;3117int reccnt;3118unsigned char*sha1;3119int found_it;31203121unsigned char osha1[20];3122unsigned char nsha1[20];3123int tz;3124unsigned long date;3125char**msg;3126unsigned long*cutoff_time;3127int*cutoff_tz;3128int*cutoff_cnt;3129};31303131static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3132const char*email,unsigned long timestamp,int tz,3133const char*message,void*cb_data)3134{3135struct read_ref_at_cb *cb = cb_data;31363137 cb->reccnt++;3138 cb->tz = tz;3139 cb->date = timestamp;31403141if(timestamp <= cb->at_time || cb->cnt ==0) {3142if(cb->msg)3143*cb->msg =xstrdup(message);3144if(cb->cutoff_time)3145*cb->cutoff_time = timestamp;3146if(cb->cutoff_tz)3147*cb->cutoff_tz = tz;3148if(cb->cutoff_cnt)3149*cb->cutoff_cnt = cb->reccnt -1;3150/*3151 * we have not yet updated cb->[n|o]sha1 so they still3152 * hold the values for the previous record.3153 */3154if(!is_null_sha1(cb->osha1)) {3155hashcpy(cb->sha1, nsha1);3156if(hashcmp(cb->osha1, nsha1))3157warning("Log for ref%shas gap after%s.",3158 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3159}3160else if(cb->date == cb->at_time)3161hashcpy(cb->sha1, nsha1);3162else if(hashcmp(nsha1, cb->sha1))3163warning("Log for ref%sunexpectedly ended on%s.",3164 cb->refname,show_date(cb->date, cb->tz,3165 DATE_RFC2822));3166hashcpy(cb->osha1, osha1);3167hashcpy(cb->nsha1, nsha1);3168 cb->found_it =1;3169return1;3170}3171hashcpy(cb->osha1, osha1);3172hashcpy(cb->nsha1, nsha1);3173if(cb->cnt >0)3174 cb->cnt--;3175return0;3176}31773178static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3179const char*email,unsigned long timestamp,3180int tz,const char*message,void*cb_data)3181{3182struct read_ref_at_cb *cb = cb_data;31833184if(cb->msg)3185*cb->msg =xstrdup(message);3186if(cb->cutoff_time)3187*cb->cutoff_time = timestamp;3188if(cb->cutoff_tz)3189*cb->cutoff_tz = tz;3190if(cb->cutoff_cnt)3191*cb->cutoff_cnt = cb->reccnt;3192hashcpy(cb->sha1, osha1);3193if(is_null_sha1(cb->sha1))3194hashcpy(cb->sha1, nsha1);3195/* We just want the first entry */3196return1;3197}31983199intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3200unsigned char*sha1,char**msg,3201unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3202{3203struct read_ref_at_cb cb;32043205memset(&cb,0,sizeof(cb));3206 cb.refname = refname;3207 cb.at_time = at_time;3208 cb.cnt = cnt;3209 cb.msg = msg;3210 cb.cutoff_time = cutoff_time;3211 cb.cutoff_tz = cutoff_tz;3212 cb.cutoff_cnt = cutoff_cnt;3213 cb.sha1 = sha1;32143215for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);32163217if(!cb.reccnt) {3218if(flags & GET_SHA1_QUIETLY)3219exit(128);3220else3221die("Log for%sis empty.", refname);3222}3223if(cb.found_it)3224return0;32253226for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);32273228return1;3229}32303231intreflog_exists(const char*refname)3232{3233struct stat st;32343235return!lstat(git_path("logs/%s", refname), &st) &&3236S_ISREG(st.st_mode);3237}32383239intdelete_reflog(const char*refname)3240{3241returnremove_path(git_path("logs/%s", refname));3242}32433244static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3245{3246unsigned char osha1[20], nsha1[20];3247char*email_end, *message;3248unsigned long timestamp;3249int tz;32503251/* old SP new SP name <email> SP time TAB msg LF */3252if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3253get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3254get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3255!(email_end =strchr(sb->buf +82,'>')) ||3256 email_end[1] !=' '||3257!(timestamp =strtoul(email_end +2, &message,10)) ||3258!message || message[0] !=' '||3259(message[1] !='+'&& message[1] !='-') ||3260!isdigit(message[2]) || !isdigit(message[3]) ||3261!isdigit(message[4]) || !isdigit(message[5]))3262return0;/* corrupt? */3263 email_end[1] ='\0';3264 tz =strtol(message +1, NULL,10);3265if(message[6] !='\t')3266 message +=6;3267else3268 message +=7;3269returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3270}32713272static char*find_beginning_of_line(char*bob,char*scan)3273{3274while(bob < scan && *(--scan) !='\n')3275;/* keep scanning backwards */3276/*3277 * Return either beginning of the buffer, or LF at the end of3278 * the previous line.3279 */3280return scan;3281}32823283intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3284{3285struct strbuf sb = STRBUF_INIT;3286FILE*logfp;3287long pos;3288int ret =0, at_tail =1;32893290 logfp =fopen(git_path("logs/%s", refname),"r");3291if(!logfp)3292return-1;32933294/* Jump to the end */3295if(fseek(logfp,0, SEEK_END) <0)3296returnerror("cannot seek back reflog for%s:%s",3297 refname,strerror(errno));3298 pos =ftell(logfp);3299while(!ret &&0< pos) {3300int cnt;3301size_t nread;3302char buf[BUFSIZ];3303char*endp, *scanp;33043305/* Fill next block from the end */3306 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3307if(fseek(logfp, pos - cnt, SEEK_SET))3308returnerror("cannot seek back reflog for%s:%s",3309 refname,strerror(errno));3310 nread =fread(buf, cnt,1, logfp);3311if(nread !=1)3312returnerror("cannot read%dbytes from reflog for%s:%s",3313 cnt, refname,strerror(errno));3314 pos -= cnt;33153316 scanp = endp = buf + cnt;3317if(at_tail && scanp[-1] =='\n')3318/* Looking at the final LF at the end of the file */3319 scanp--;3320 at_tail =0;33213322while(buf < scanp) {3323/*3324 * terminating LF of the previous line, or the beginning3325 * of the buffer.3326 */3327char*bp;33283329 bp =find_beginning_of_line(buf, scanp);33303331if(*bp !='\n') {3332strbuf_splice(&sb,0,0, buf, endp - buf);3333if(pos)3334break;/* need to fill another block */3335 scanp = buf -1;/* leave loop */3336}else{3337/*3338 * (bp + 1) thru endp is the beginning of the3339 * current line we have in sb3340 */3341strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3342 scanp = bp;3343 endp = bp +1;3344}3345 ret =show_one_reflog_ent(&sb, fn, cb_data);3346strbuf_reset(&sb);3347if(ret)3348break;3349}33503351}3352if(!ret && sb.len)3353 ret =show_one_reflog_ent(&sb, fn, cb_data);33543355fclose(logfp);3356strbuf_release(&sb);3357return ret;3358}33593360intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3361{3362FILE*logfp;3363struct strbuf sb = STRBUF_INIT;3364int ret =0;33653366 logfp =fopen(git_path("logs/%s", refname),"r");3367if(!logfp)3368return-1;33693370while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3371 ret =show_one_reflog_ent(&sb, fn, cb_data);3372fclose(logfp);3373strbuf_release(&sb);3374return ret;3375}3376/*3377 * Call fn for each reflog in the namespace indicated by name. name3378 * must be empty or end with '/'. Name will be used as a scratch3379 * space, but its contents will be restored before return.3380 */3381static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3382{3383DIR*d =opendir(git_path("logs/%s", name->buf));3384int retval =0;3385struct dirent *de;3386int oldlen = name->len;33873388if(!d)3389return name->len ? errno :0;33903391while((de =readdir(d)) != NULL) {3392struct stat st;33933394if(de->d_name[0] =='.')3395continue;3396if(ends_with(de->d_name,".lock"))3397continue;3398strbuf_addstr(name, de->d_name);3399if(stat(git_path("logs/%s", name->buf), &st) <0) {3400;/* silently ignore */3401}else{3402if(S_ISDIR(st.st_mode)) {3403strbuf_addch(name,'/');3404 retval =do_for_each_reflog(name, fn, cb_data);3405}else{3406unsigned char sha1[20];3407if(read_ref_full(name->buf,0, sha1, NULL))3408 retval =error("bad ref for%s", name->buf);3409else3410 retval =fn(name->buf, sha1,0, cb_data);3411}3412if(retval)3413break;3414}3415strbuf_setlen(name, oldlen);3416}3417closedir(d);3418return retval;3419}34203421intfor_each_reflog(each_ref_fn fn,void*cb_data)3422{3423int retval;3424struct strbuf name;3425strbuf_init(&name, PATH_MAX);3426 retval =do_for_each_reflog(&name, fn, cb_data);3427strbuf_release(&name);3428return retval;3429}34303431/**3432 * Information needed for a single ref update. Set new_sha1 to the3433 * new value or to zero to delete the ref. To check the old value3434 * while locking the ref, set have_old to 1 and set old_sha1 to the3435 * value or to zero to ensure the ref does not exist before update.3436 */3437struct ref_update {3438unsigned char new_sha1[20];3439unsigned char old_sha1[20];3440int flags;/* REF_NODEREF? */3441int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3442struct ref_lock *lock;3443int type;3444char*msg;3445const char refname[FLEX_ARRAY];3446};34473448/*3449 * Transaction states.3450 * OPEN: The transaction is in a valid state and can accept new updates.3451 * An OPEN transaction can be committed.3452 * CLOSED: A closed transaction is no longer active and no other operations3453 * than free can be used on it in this state.3454 * A transaction can either become closed by successfully committing3455 * an active transaction or if there is a failure while building3456 * the transaction thus rendering it failed/inactive.3457 */3458enum ref_transaction_state {3459 REF_TRANSACTION_OPEN =0,3460 REF_TRANSACTION_CLOSED =13461};34623463/*3464 * Data structure for holding a reference transaction, which can3465 * consist of checks and updates to multiple references, carried out3466 * as atomically as possible. This structure is opaque to callers.3467 */3468struct ref_transaction {3469struct ref_update **updates;3470size_t alloc;3471size_t nr;3472enum ref_transaction_state state;3473};34743475struct ref_transaction *ref_transaction_begin(struct strbuf *err)3476{3477returnxcalloc(1,sizeof(struct ref_transaction));3478}34793480voidref_transaction_free(struct ref_transaction *transaction)3481{3482int i;34833484if(!transaction)3485return;34863487for(i =0; i < transaction->nr; i++) {3488free(transaction->updates[i]->msg);3489free(transaction->updates[i]);3490}3491free(transaction->updates);3492free(transaction);3493}34943495static struct ref_update *add_update(struct ref_transaction *transaction,3496const char*refname)3497{3498size_t len =strlen(refname);3499struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);35003501strcpy((char*)update->refname, refname);3502ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3503 transaction->updates[transaction->nr++] = update;3504return update;3505}35063507intref_transaction_update(struct ref_transaction *transaction,3508const char*refname,3509const unsigned char*new_sha1,3510const unsigned char*old_sha1,3511int flags,int have_old,const char*msg,3512struct strbuf *err)3513{3514struct ref_update *update;35153516if(transaction->state != REF_TRANSACTION_OPEN)3517die("BUG: update called for transaction that is not open");35183519if(have_old && !old_sha1)3520die("BUG: have_old is true but old_sha1 is NULL");35213522 update =add_update(transaction, refname);3523hashcpy(update->new_sha1, new_sha1);3524 update->flags = flags;3525 update->have_old = have_old;3526if(have_old)3527hashcpy(update->old_sha1, old_sha1);3528if(msg)3529 update->msg =xstrdup(msg);3530return0;3531}35323533intref_transaction_create(struct ref_transaction *transaction,3534const char*refname,3535const unsigned char*new_sha1,3536int flags,const char*msg,3537struct strbuf *err)3538{3539struct ref_update *update;35403541if(transaction->state != REF_TRANSACTION_OPEN)3542die("BUG: create called for transaction that is not open");35433544if(!new_sha1 ||is_null_sha1(new_sha1))3545die("BUG: create ref with null new_sha1");35463547 update =add_update(transaction, refname);35483549hashcpy(update->new_sha1, new_sha1);3550hashclr(update->old_sha1);3551 update->flags = flags;3552 update->have_old =1;3553if(msg)3554 update->msg =xstrdup(msg);3555return0;3556}35573558intref_transaction_delete(struct ref_transaction *transaction,3559const char*refname,3560const unsigned char*old_sha1,3561int flags,int have_old,const char*msg,3562struct strbuf *err)3563{3564struct ref_update *update;35653566if(transaction->state != REF_TRANSACTION_OPEN)3567die("BUG: delete called for transaction that is not open");35683569if(have_old && !old_sha1)3570die("BUG: have_old is true but old_sha1 is NULL");35713572 update =add_update(transaction, refname);3573 update->flags = flags;3574 update->have_old = have_old;3575if(have_old) {3576assert(!is_null_sha1(old_sha1));3577hashcpy(update->old_sha1, old_sha1);3578}3579if(msg)3580 update->msg =xstrdup(msg);3581return0;3582}35833584intupdate_ref(const char*action,const char*refname,3585const unsigned char*sha1,const unsigned char*oldval,3586int flags,enum action_on_err onerr)3587{3588struct ref_transaction *t;3589struct strbuf err = STRBUF_INIT;35903591 t =ref_transaction_begin(&err);3592if(!t ||3593ref_transaction_update(t, refname, sha1, oldval, flags,3594!!oldval, action, &err) ||3595ref_transaction_commit(t, &err)) {3596const char*str ="update_ref failed for ref '%s':%s";35973598ref_transaction_free(t);3599switch(onerr) {3600case UPDATE_REFS_MSG_ON_ERR:3601error(str, refname, err.buf);3602break;3603case UPDATE_REFS_DIE_ON_ERR:3604die(str, refname, err.buf);3605break;3606case UPDATE_REFS_QUIET_ON_ERR:3607break;3608}3609strbuf_release(&err);3610return1;3611}3612strbuf_release(&err);3613ref_transaction_free(t);3614return0;3615}36163617static intref_update_compare(const void*r1,const void*r2)3618{3619const struct ref_update *const*u1 = r1;3620const struct ref_update *const*u2 = r2;3621returnstrcmp((*u1)->refname, (*u2)->refname);3622}36233624static intref_update_reject_duplicates(struct ref_update **updates,int n,3625struct strbuf *err)3626{3627int i;3628for(i =1; i < n; i++)3629if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3630const char*str =3631"Multiple updates for ref '%s' not allowed.";3632if(err)3633strbuf_addf(err, str, updates[i]->refname);36343635return1;3636}3637return0;3638}36393640intref_transaction_commit(struct ref_transaction *transaction,3641struct strbuf *err)3642{3643int ret =0, delnum =0, i;3644const char**delnames;3645int n = transaction->nr;3646struct ref_update **updates = transaction->updates;36473648if(transaction->state != REF_TRANSACTION_OPEN)3649die("BUG: commit called for transaction that is not open");36503651if(!n) {3652 transaction->state = REF_TRANSACTION_CLOSED;3653return0;3654}36553656/* Allocate work space */3657 delnames =xmalloc(sizeof(*delnames) * n);36583659/* Copy, sort, and reject duplicate refs */3660qsort(updates, n,sizeof(*updates), ref_update_compare);3661if(ref_update_reject_duplicates(updates, n, err)) {3662 ret = TRANSACTION_GENERIC_ERROR;3663goto cleanup;3664}36653666/* Acquire all locks while verifying old values */3667for(i =0; i < n; i++) {3668struct ref_update *update = updates[i];3669int flags = update->flags;36703671if(is_null_sha1(update->new_sha1))3672 flags |= REF_DELETING;3673 update->lock =lock_ref_sha1_basic(update->refname,3674(update->have_old ?3675 update->old_sha1 :3676 NULL),3677 NULL,3678 flags,3679&update->type);3680if(!update->lock) {3681 ret = (errno == ENOTDIR)3682? TRANSACTION_NAME_CONFLICT3683: TRANSACTION_GENERIC_ERROR;3684if(err)3685strbuf_addf(err,"Cannot lock the ref '%s'.",3686 update->refname);3687goto cleanup;3688}3689}36903691/* Perform updates first so live commits remain referenced */3692for(i =0; i < n; i++) {3693struct ref_update *update = updates[i];36943695if(!is_null_sha1(update->new_sha1)) {3696if(write_ref_sha1(update->lock, update->new_sha1,3697 update->msg)) {3698 update->lock = NULL;/* freed by write_ref_sha1 */3699if(err)3700strbuf_addf(err,"Cannot update the ref '%s'.",3701 update->refname);3702 ret = TRANSACTION_GENERIC_ERROR;3703goto cleanup;3704}3705 update->lock = NULL;/* freed by write_ref_sha1 */3706}3707}37083709/* Perform deletes now that updates are safely completed */3710for(i =0; i < n; i++) {3711struct ref_update *update = updates[i];37123713if(update->lock) {3714if(delete_ref_loose(update->lock, update->type, err))3715 ret = TRANSACTION_GENERIC_ERROR;37163717if(!(update->flags & REF_ISPRUNING))3718 delnames[delnum++] = update->lock->ref_name;3719}3720}37213722if(repack_without_refs(delnames, delnum, err))3723 ret = TRANSACTION_GENERIC_ERROR;3724for(i =0; i < delnum; i++)3725unlink_or_warn(git_path("logs/%s", delnames[i]));3726clear_loose_ref_cache(&ref_cache);37273728cleanup:3729 transaction->state = REF_TRANSACTION_CLOSED;37303731for(i =0; i < n; i++)3732if(updates[i]->lock)3733unlock_ref(updates[i]->lock);3734free(delnames);3735return ret;3736}37373738char*shorten_unambiguous_ref(const char*refname,int strict)3739{3740int i;3741static char**scanf_fmts;3742static int nr_rules;3743char*short_name;37443745if(!nr_rules) {3746/*3747 * Pre-generate scanf formats from ref_rev_parse_rules[].3748 * Generate a format suitable for scanf from a3749 * ref_rev_parse_rules rule by interpolating "%s" at the3750 * location of the "%.*s".3751 */3752size_t total_len =0;3753size_t offset =0;37543755/* the rule list is NULL terminated, count them first */3756for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3757/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3758 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;37593760 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);37613762 offset =0;3763for(i =0; i < nr_rules; i++) {3764assert(offset < total_len);3765 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3766 offset +=snprintf(scanf_fmts[i], total_len - offset,3767 ref_rev_parse_rules[i],2,"%s") +1;3768}3769}37703771/* bail out if there are no rules */3772if(!nr_rules)3773returnxstrdup(refname);37743775/* buffer for scanf result, at most refname must fit */3776 short_name =xstrdup(refname);37773778/* skip first rule, it will always match */3779for(i = nr_rules -1; i >0; --i) {3780int j;3781int rules_to_fail = i;3782int short_name_len;37833784if(1!=sscanf(refname, scanf_fmts[i], short_name))3785continue;37863787 short_name_len =strlen(short_name);37883789/*3790 * in strict mode, all (except the matched one) rules3791 * must fail to resolve to a valid non-ambiguous ref3792 */3793if(strict)3794 rules_to_fail = nr_rules;37953796/*3797 * check if the short name resolves to a valid ref,3798 * but use only rules prior to the matched one3799 */3800for(j =0; j < rules_to_fail; j++) {3801const char*rule = ref_rev_parse_rules[j];3802char refname[PATH_MAX];38033804/* skip matched rule */3805if(i == j)3806continue;38073808/*3809 * the short name is ambiguous, if it resolves3810 * (with this previous rule) to a valid ref3811 * read_ref() returns 0 on success3812 */3813mksnpath(refname,sizeof(refname),3814 rule, short_name_len, short_name);3815if(ref_exists(refname))3816break;3817}38183819/*3820 * short name is non-ambiguous if all previous rules3821 * haven't resolved to a valid ref3822 */3823if(j == rules_to_fail)3824return short_name;3825}38263827free(short_name);3828returnxstrdup(refname);3829}38303831static struct string_list *hide_refs;38323833intparse_hide_refs_config(const char*var,const char*value,const char*section)3834{3835if(!strcmp("transfer.hiderefs", var) ||3836/* NEEDSWORK: use parse_config_key() once both are merged */3837(starts_with(var, section) && var[strlen(section)] =='.'&&3838!strcmp(var +strlen(section),".hiderefs"))) {3839char*ref;3840int len;38413842if(!value)3843returnconfig_error_nonbool(var);3844 ref =xstrdup(value);3845 len =strlen(ref);3846while(len && ref[len -1] =='/')3847 ref[--len] ='\0';3848if(!hide_refs) {3849 hide_refs =xcalloc(1,sizeof(*hide_refs));3850 hide_refs->strdup_strings =1;3851}3852string_list_append(hide_refs, ref);3853}3854return0;3855}38563857intref_is_hidden(const char*refname)3858{3859struct string_list_item *item;38603861if(!hide_refs)3862return0;3863for_each_string_list_item(item, hide_refs) {3864int len;3865if(!starts_with(refname, item->string))3866continue;3867 len =strlen(item->string);3868if(!refname[len] || refname[len] =='/')3869return1;3870}3871return0;3872}