1#include"cache.h" 2#include"refs.h" 3#include"object.h" 4#include"tag.h" 5#include"dir.h" 6#include"string-list.h" 7 8/* 9 * How to handle various characters in refnames: 10 * This table is used by both the SIMD and non-SIMD code. It has 11 * some cases that are only useful for the SIMD; these are handled 12 * equivalently to the listed disposition in the non-SIMD code. 13 * 0: An acceptable character for refs 14 * 1: @, look for a following { to reject @{ in refs (SIMD or = 0) 15 * 2: \0: End-of-component and string 16 * 3: /: End-of-component (SIMD or = 2) 17 * 4: ., look for a preceding . to reject .. in refs 18 * 5: {, look for a preceding @ to reject @{ in refs 19 * 6: *, usually a bad character except, once as a wildcard (SIMD or = 7) 20 * 7: A bad character except * (see check_refname_component below) 21 */ 22static unsigned char refname_disposition[256] = { 232,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 247,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 257,0,0,0,0,0,0,0,0,0,6,0,0,0,4,3, 260,0,0,0,0,0,0,0,0,0,7,0,0,0,0,7, 271,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 280,0,0,0,0,0,0,0,0,0,0,7,7,0,7,0, 290,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 300,0,0,0,0,0,0,0,0,0,0,5,0,0,7,7 31}; 32 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 has pattern-matching notation "*", "?", "[", anywhere, or 43 * - it ends with a "/", or 44 * - it ends with ".lock", or 45 * - it contains a "\" (backslash) 46 */ 47static intcheck_refname_component(const char*refname,int flags) 48{ 49const char*cp; 50char last ='\0'; 51 52for(cp = refname; ; cp++) { 53int ch = *cp &255; 54unsigned char disp = refname_disposition[ch]; 55switch(disp) { 56case2:/* fall-through */ 57case3: 58goto out; 59case4: 60if(last =='.') 61return-1;/* Refname contains "..". */ 62break; 63case5: 64if(last =='@') 65return-1;/* Refname contains "@{". */ 66break; 67case6:/* fall-through */ 68case7: 69return-1; 70} 71 last = ch; 72} 73out: 74if(cp == refname) 75return0;/* Component has zero length. */ 76if(refname[0] =='.') { 77if(!(flags & REFNAME_DOT_COMPONENT)) 78return-1;/* Component starts with '.'. */ 79/* 80 * Even if leading dots are allowed, don't allow "." 81 * as a component (".." is prevented by a rule above). 82 */ 83if(refname[1] =='\0') 84return-1;/* Component equals ".". */ 85} 86if(cp - refname >=5&& !memcmp(cp -5,".lock",5)) 87return-1;/* Refname ends with ".lock". */ 88return cp - refname; 89} 90 91static intcheck_refname_format_bytewise(const char*refname,int flags) 92{ 93int component_len, component_count =0; 94 95if(!strcmp(refname,"@")) 96/* Refname is a single character '@'. */ 97return-1; 98 99while(1) { 100/* We are at the start of a path component. */ 101 component_len =check_refname_component(refname, flags); 102if(component_len <=0) { 103if((flags & REFNAME_REFSPEC_PATTERN) && 104 refname[0] =='*'&& 105(refname[1] =='\0'|| refname[1] =='/')) { 106/* Accept one wildcard as a full refname component. */ 107 flags &= ~REFNAME_REFSPEC_PATTERN; 108 component_len =1; 109}else{ 110return-1; 111} 112} 113 component_count++; 114if(refname[component_len] =='\0') 115break; 116/* Skip to next component. */ 117 refname += component_len +1; 118} 119 120if(refname[component_len -1] =='.') 121return-1;/* Refname ends with '.'. */ 122if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 123return-1;/* Refname has only one component. */ 124return0; 125} 126 127#if defined(__GNUC__) && defined(__x86_64__) 128#define SSE_VECTOR_BYTES 16 129 130/* Vectorized version of check_refname_format. */ 131intcheck_refname_format(const char*refname,int flags) 132{ 133const char*cp = refname; 134 135const __m128i dot =_mm_set1_epi8('.'); 136const __m128i at =_mm_set1_epi8('@'); 137const __m128i curly =_mm_set1_epi8('{'); 138const __m128i slash =_mm_set1_epi8('/'); 139const __m128i zero =_mm_set1_epi8('\000'); 140const __m128i el =_mm_set1_epi8('l'); 141 142/* below '*', all characters are forbidden or rare */ 143const __m128i star_ub =_mm_set1_epi8('*'+1); 144 145const __m128i colon =_mm_set1_epi8(':'); 146const __m128i question =_mm_set1_epi8('?'); 147 148/* '['..'^' contains 4 characters: 3 forbidden and 1 rare */ 149const __m128i bracket_lb =_mm_set1_epi8('['-1); 150const __m128i caret_ub =_mm_set1_epi8('^'+1); 151 152/* '~' and above are forbidden */ 153const __m128i tilde_lb =_mm_set1_epi8('~'-1); 154 155int component_count =0; 156 157if(refname[0] ==0|| refname[0] =='/') { 158/* entirely empty ref or initial ref component */ 159return-1; 160} 161 162/* 163 * Initial ref component of '.'; below we look for /. so we'll 164 * miss this. 165 */ 166if(refname[0] =='.') { 167if(refname[1] =='/'|| refname[1] =='\0') 168return-1; 169if(!(flags & REFNAME_DOT_COMPONENT)) 170return-1; 171} 172while(1) { 173 __m128i tmp, tmp1, result; 174uint64_t mask; 175 176if((uintptr_t) cp % PAGE_SIZE > PAGE_SIZE - SSE_VECTOR_BYTES -1) 177/* 178 * End-of-page; fall back to slow method for 179 * this entire ref. 180 */ 181returncheck_refname_format_bytewise(refname, flags); 182 183 tmp =_mm_loadu_si128((__m128i *)cp); 184 tmp1 =_mm_loadu_si128((__m128i *)(cp +1)); 185 186/* 187 * This range (note the lt) contains some 188 * permissible-but-rare characters (including all 189 * characters >= 128), which we handle later. It also 190 * includes \000. 191 */ 192 result =_mm_cmplt_epi8(tmp, star_ub); 193 194 result =_mm_or_si128(result,_mm_cmpeq_epi8(tmp, question)); 195 result =_mm_or_si128(result,_mm_cmpeq_epi8(tmp, colon)); 196 197/* This range contains the permissible ] as bycatch */ 198 result =_mm_or_si128(result,_mm_and_si128( 199_mm_cmpgt_epi8(tmp, bracket_lb), 200_mm_cmplt_epi8(tmp, caret_ub))); 201 202 result =_mm_or_si128(result,_mm_cmpgt_epi8(tmp, tilde_lb)); 203 204/* .. */ 205 result =_mm_or_si128(result,_mm_and_si128( 206_mm_cmpeq_epi8(tmp, dot), 207_mm_cmpeq_epi8(tmp1, dot))); 208/* @{ */ 209 result =_mm_or_si128(result,_mm_and_si128( 210_mm_cmpeq_epi8(tmp, at), 211_mm_cmpeq_epi8(tmp1, curly))); 212/* // */ 213 result =_mm_or_si128(result,_mm_and_si128( 214_mm_cmpeq_epi8(tmp, slash), 215_mm_cmpeq_epi8(tmp1, slash))); 216/* trailing / */ 217 result =_mm_or_si128(result,_mm_and_si128( 218_mm_cmpeq_epi8(tmp, slash), 219_mm_cmpeq_epi8(tmp1, zero))); 220/* .l, beginning of .lock */ 221 result =_mm_or_si128(result,_mm_and_si128( 222_mm_cmpeq_epi8(tmp, dot), 223_mm_cmpeq_epi8(tmp1, el))); 224/* 225 * Even though /. is not necessarily an error, we flag 226 * it anyway. If we find it, we'll check if it's valid 227 * and if so we'll advance just past it. 228 */ 229 result =_mm_or_si128(result,_mm_and_si128( 230_mm_cmpeq_epi8(tmp, slash), 231_mm_cmpeq_epi8(tmp1, dot))); 232 233 mask =_mm_movemask_epi8(result); 234if(mask) { 235/* 236 * We've found either end-of-string, or some 237 * probably-bad character or substring. 238 */ 239int i =__builtin_ctz(mask); 240switch(refname_disposition[cp[i] &255]) { 241case0:/* fall-through */ 242case5: 243/* 244 * bycatch: a good character that's in 245 * one of the ranges of mostly-forbidden 246 * characters 247 */ 248 cp += i +1; 249break; 250case1: 251if(cp[i +1] =='{') 252return-1; 253 cp += i +1; 254break; 255case2: 256if(!(flags & REFNAME_ALLOW_ONELEVEL) 257&& !component_count && !strchr(refname,'/')) 258/* Refname has only one component. */ 259return-1; 260return0; 261case3: 262 component_count ++; 263/* 264 * Even if leading dots are allowed, don't 265 * allow "." as a component (".." is 266 * prevented by case 4 below). 267 */ 268if(cp[i +1] =='.') { 269if(cp[i +2] =='\0') 270return-1; 271if(flags & REFNAME_DOT_COMPONENT) { 272/* skip to just after the /. */ 273 cp += i +2; 274break; 275} 276return-1; 277}else if(cp[i +1] =='/'|| cp[i +1] =='\0') 278return-1; 279break; 280case4: 281if(cp[i +1] =='.'|| cp[i +1] =='\0') 282return-1; 283/* .lock as end-of-component or end-of-string */ 284if((!strncmp(cp + i,".lock",5)) 285&& (cp[i +5] =='/'|| cp[i +5] ==0)) 286return-1; 287 cp +=1; 288break; 289case6: 290if(((cp == refname + i) || cp[i -1] =='/') 291&& (cp[i +1] =='/'|| cp[i +1] ==0)) 292if(flags & REFNAME_REFSPEC_PATTERN) { 293 flags &= ~REFNAME_REFSPEC_PATTERN; 294/* restart after the * */ 295 cp += i +1; 296continue; 297} 298/* fall-through */ 299case7: 300return-1; 301} 302}else 303 cp += SSE_VECTOR_BYTES; 304} 305} 306 307#else 308 309intcheck_refname_format(const char*refname,int flags) 310{ 311returncheck_refname_format_bytewise(refname, flags); 312} 313 314#endif 315 316struct ref_entry; 317 318/* 319 * Information used (along with the information in ref_entry) to 320 * describe a single cached reference. This data structure only 321 * occurs embedded in a union in struct ref_entry, and only when 322 * (ref_entry->flag & REF_DIR) is zero. 323 */ 324struct ref_value { 325/* 326 * The name of the object to which this reference resolves 327 * (which may be a tag object). If REF_ISBROKEN, this is 328 * null. If REF_ISSYMREF, then this is the name of the object 329 * referred to by the last reference in the symlink chain. 330 */ 331unsigned char sha1[20]; 332 333/* 334 * If REF_KNOWS_PEELED, then this field holds the peeled value 335 * of this reference, or null if the reference is known not to 336 * be peelable. See the documentation for peel_ref() for an 337 * exact definition of "peelable". 338 */ 339unsigned char peeled[20]; 340}; 341 342struct ref_cache; 343 344/* 345 * Information used (along with the information in ref_entry) to 346 * describe a level in the hierarchy of references. This data 347 * structure only occurs embedded in a union in struct ref_entry, and 348 * only when (ref_entry.flag & REF_DIR) is set. In that case, 349 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 350 * in the directory have already been read: 351 * 352 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 353 * or packed references, already read. 354 * 355 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 356 * references that hasn't been read yet (nor has any of its 357 * subdirectories). 358 * 359 * Entries within a directory are stored within a growable array of 360 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 361 * sorted are sorted by their component name in strcmp() order and the 362 * remaining entries are unsorted. 363 * 364 * Loose references are read lazily, one directory at a time. When a 365 * directory of loose references is read, then all of the references 366 * in that directory are stored, and REF_INCOMPLETE stubs are created 367 * for any subdirectories, but the subdirectories themselves are not 368 * read. The reading is triggered by get_ref_dir(). 369 */ 370struct ref_dir { 371int nr, alloc; 372 373/* 374 * Entries with index 0 <= i < sorted are sorted by name. New 375 * entries are appended to the list unsorted, and are sorted 376 * only when required; thus we avoid the need to sort the list 377 * after the addition of every reference. 378 */ 379int sorted; 380 381/* A pointer to the ref_cache that contains this ref_dir. */ 382struct ref_cache *ref_cache; 383 384struct ref_entry **entries; 385}; 386 387/* 388 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 389 * REF_ISPACKED=0x02, and REF_ISBROKEN=0x04 are public values; see 390 * refs.h. 391 */ 392 393/* 394 * The field ref_entry->u.value.peeled of this value entry contains 395 * the correct peeled value for the reference, which might be 396 * null_sha1 if the reference is not a tag or if it is broken. 397 */ 398#define REF_KNOWS_PEELED 0x08 399 400/* ref_entry represents a directory of references */ 401#define REF_DIR 0x10 402 403/* 404 * Entry has not yet been read from disk (used only for REF_DIR 405 * entries representing loose references) 406 */ 407#define REF_INCOMPLETE 0x20 408 409/* 410 * A ref_entry represents either a reference or a "subdirectory" of 411 * references. 412 * 413 * Each directory in the reference namespace is represented by a 414 * ref_entry with (flags & REF_DIR) set and containing a subdir member 415 * that holds the entries in that directory that have been read so 416 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 417 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 418 * used for loose reference directories. 419 * 420 * References are represented by a ref_entry with (flags & REF_DIR) 421 * unset and a value member that describes the reference's value. The 422 * flag member is at the ref_entry level, but it is also needed to 423 * interpret the contents of the value field (in other words, a 424 * ref_value object is not very much use without the enclosing 425 * ref_entry). 426 * 427 * Reference names cannot end with slash and directories' names are 428 * always stored with a trailing slash (except for the top-level 429 * directory, which is always denoted by ""). This has two nice 430 * consequences: (1) when the entries in each subdir are sorted 431 * lexicographically by name (as they usually are), the references in 432 * a whole tree can be generated in lexicographic order by traversing 433 * the tree in left-to-right, depth-first order; (2) the names of 434 * references and subdirectories cannot conflict, and therefore the 435 * presence of an empty subdirectory does not block the creation of a 436 * similarly-named reference. (The fact that reference names with the 437 * same leading components can conflict *with each other* is a 438 * separate issue that is regulated by is_refname_available().) 439 * 440 * Please note that the name field contains the fully-qualified 441 * reference (or subdirectory) name. Space could be saved by only 442 * storing the relative names. But that would require the full names 443 * to be generated on the fly when iterating in do_for_each_ref(), and 444 * would break callback functions, who have always been able to assume 445 * that the name strings that they are passed will not be freed during 446 * the iteration. 447 */ 448struct ref_entry { 449unsigned char flag;/* ISSYMREF? ISPACKED? */ 450union{ 451struct ref_value value;/* if not (flags&REF_DIR) */ 452struct ref_dir subdir;/* if (flags&REF_DIR) */ 453} u; 454/* 455 * The full name of the reference (e.g., "refs/heads/master") 456 * or the full name of the directory with a trailing slash 457 * (e.g., "refs/heads/"): 458 */ 459char name[FLEX_ARRAY]; 460}; 461 462static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 463 464static struct ref_dir *get_ref_dir(struct ref_entry *entry) 465{ 466struct ref_dir *dir; 467assert(entry->flag & REF_DIR); 468 dir = &entry->u.subdir; 469if(entry->flag & REF_INCOMPLETE) { 470read_loose_refs(entry->name, dir); 471 entry->flag &= ~REF_INCOMPLETE; 472} 473return dir; 474} 475 476static struct ref_entry *create_ref_entry(const char*refname, 477const unsigned char*sha1,int flag, 478int check_name) 479{ 480int len; 481struct ref_entry *ref; 482 483if(check_name && 484check_refname_format(refname, REFNAME_ALLOW_ONELEVEL|REFNAME_DOT_COMPONENT)) 485die("Reference has invalid format: '%s'", refname); 486 len =strlen(refname) +1; 487 ref =xmalloc(sizeof(struct ref_entry) + len); 488hashcpy(ref->u.value.sha1, sha1); 489hashclr(ref->u.value.peeled); 490memcpy(ref->name, refname, len); 491 ref->flag = flag; 492return ref; 493} 494 495static voidclear_ref_dir(struct ref_dir *dir); 496 497static voidfree_ref_entry(struct ref_entry *entry) 498{ 499if(entry->flag & REF_DIR) { 500/* 501 * Do not use get_ref_dir() here, as that might 502 * trigger the reading of loose refs. 503 */ 504clear_ref_dir(&entry->u.subdir); 505} 506free(entry); 507} 508 509/* 510 * Add a ref_entry to the end of dir (unsorted). Entry is always 511 * stored directly in dir; no recursion into subdirectories is 512 * done. 513 */ 514static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 515{ 516ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 517 dir->entries[dir->nr++] = entry; 518/* optimize for the case that entries are added in order */ 519if(dir->nr ==1|| 520(dir->nr == dir->sorted +1&& 521strcmp(dir->entries[dir->nr -2]->name, 522 dir->entries[dir->nr -1]->name) <0)) 523 dir->sorted = dir->nr; 524} 525 526/* 527 * Clear and free all entries in dir, recursively. 528 */ 529static voidclear_ref_dir(struct ref_dir *dir) 530{ 531int i; 532for(i =0; i < dir->nr; i++) 533free_ref_entry(dir->entries[i]); 534free(dir->entries); 535 dir->sorted = dir->nr = dir->alloc =0; 536 dir->entries = NULL; 537} 538 539/* 540 * Create a struct ref_entry object for the specified dirname. 541 * dirname is the name of the directory with a trailing slash (e.g., 542 * "refs/heads/") or "" for the top-level directory. 543 */ 544static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 545const char*dirname,size_t len, 546int incomplete) 547{ 548struct ref_entry *direntry; 549 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 550memcpy(direntry->name, dirname, len); 551 direntry->name[len] ='\0'; 552 direntry->u.subdir.ref_cache = ref_cache; 553 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 554return direntry; 555} 556 557static intref_entry_cmp(const void*a,const void*b) 558{ 559struct ref_entry *one = *(struct ref_entry **)a; 560struct ref_entry *two = *(struct ref_entry **)b; 561returnstrcmp(one->name, two->name); 562} 563 564static voidsort_ref_dir(struct ref_dir *dir); 565 566struct string_slice { 567size_t len; 568const char*str; 569}; 570 571static intref_entry_cmp_sslice(const void*key_,const void*ent_) 572{ 573const struct string_slice *key = key_; 574const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 575int cmp =strncmp(key->str, ent->name, key->len); 576if(cmp) 577return cmp; 578return'\0'- (unsigned char)ent->name[key->len]; 579} 580 581/* 582 * Return the index of the entry with the given refname from the 583 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 584 * no such entry is found. dir must already be complete. 585 */ 586static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 587{ 588struct ref_entry **r; 589struct string_slice key; 590 591if(refname == NULL || !dir->nr) 592return-1; 593 594sort_ref_dir(dir); 595 key.len = len; 596 key.str = refname; 597 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 598 ref_entry_cmp_sslice); 599 600if(r == NULL) 601return-1; 602 603return r - dir->entries; 604} 605 606/* 607 * Search for a directory entry directly within dir (without 608 * recursing). Sort dir if necessary. subdirname must be a directory 609 * name (i.e., end in '/'). If mkdir is set, then create the 610 * directory if it is missing; otherwise, return NULL if the desired 611 * directory cannot be found. dir must already be complete. 612 */ 613static struct ref_dir *search_for_subdir(struct ref_dir *dir, 614const char*subdirname,size_t len, 615int mkdir) 616{ 617int entry_index =search_ref_dir(dir, subdirname, len); 618struct ref_entry *entry; 619if(entry_index == -1) { 620if(!mkdir) 621return NULL; 622/* 623 * Since dir is complete, the absence of a subdir 624 * means that the subdir really doesn't exist; 625 * therefore, create an empty record for it but mark 626 * the record complete. 627 */ 628 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 629add_entry_to_dir(dir, entry); 630}else{ 631 entry = dir->entries[entry_index]; 632} 633returnget_ref_dir(entry); 634} 635 636/* 637 * If refname is a reference name, find the ref_dir within the dir 638 * tree that should hold refname. If refname is a directory name 639 * (i.e., ends in '/'), then return that ref_dir itself. dir must 640 * represent the top-level directory and must already be complete. 641 * Sort ref_dirs and recurse into subdirectories as necessary. If 642 * mkdir is set, then create any missing directories; otherwise, 643 * return NULL if the desired directory cannot be found. 644 */ 645static struct ref_dir *find_containing_dir(struct ref_dir *dir, 646const char*refname,int mkdir) 647{ 648const char*slash; 649for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 650size_t dirnamelen = slash - refname +1; 651struct ref_dir *subdir; 652 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 653if(!subdir) { 654 dir = NULL; 655break; 656} 657 dir = subdir; 658} 659 660return dir; 661} 662 663/* 664 * Find the value entry with the given name in dir, sorting ref_dirs 665 * and recursing into subdirectories as necessary. If the name is not 666 * found or it corresponds to a directory entry, return NULL. 667 */ 668static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 669{ 670int entry_index; 671struct ref_entry *entry; 672 dir =find_containing_dir(dir, refname,0); 673if(!dir) 674return NULL; 675 entry_index =search_ref_dir(dir, refname,strlen(refname)); 676if(entry_index == -1) 677return NULL; 678 entry = dir->entries[entry_index]; 679return(entry->flag & REF_DIR) ? NULL : entry; 680} 681 682/* 683 * Remove the entry with the given name from dir, recursing into 684 * subdirectories as necessary. If refname is the name of a directory 685 * (i.e., ends with '/'), then remove the directory and its contents. 686 * If the removal was successful, return the number of entries 687 * remaining in the directory entry that contained the deleted entry. 688 * If the name was not found, return -1. Please note that this 689 * function only deletes the entry from the cache; it does not delete 690 * it from the filesystem or ensure that other cache entries (which 691 * might be symbolic references to the removed entry) are updated. 692 * Nor does it remove any containing dir entries that might be made 693 * empty by the removal. dir must represent the top-level directory 694 * and must already be complete. 695 */ 696static intremove_entry(struct ref_dir *dir,const char*refname) 697{ 698int refname_len =strlen(refname); 699int entry_index; 700struct ref_entry *entry; 701int is_dir = refname[refname_len -1] =='/'; 702if(is_dir) { 703/* 704 * refname represents a reference directory. Remove 705 * the trailing slash; otherwise we will get the 706 * directory *representing* refname rather than the 707 * one *containing* it. 708 */ 709char*dirname =xmemdupz(refname, refname_len -1); 710 dir =find_containing_dir(dir, dirname,0); 711free(dirname); 712}else{ 713 dir =find_containing_dir(dir, refname,0); 714} 715if(!dir) 716return-1; 717 entry_index =search_ref_dir(dir, refname, refname_len); 718if(entry_index == -1) 719return-1; 720 entry = dir->entries[entry_index]; 721 722memmove(&dir->entries[entry_index], 723&dir->entries[entry_index +1], 724(dir->nr - entry_index -1) *sizeof(*dir->entries) 725); 726 dir->nr--; 727if(dir->sorted > entry_index) 728 dir->sorted--; 729free_ref_entry(entry); 730return dir->nr; 731} 732 733/* 734 * Add a ref_entry to the ref_dir (unsorted), recursing into 735 * subdirectories as necessary. dir must represent the top-level 736 * directory. Return 0 on success. 737 */ 738static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 739{ 740 dir =find_containing_dir(dir, ref->name,1); 741if(!dir) 742return-1; 743add_entry_to_dir(dir, ref); 744return0; 745} 746 747/* 748 * Emit a warning and return true iff ref1 and ref2 have the same name 749 * and the same sha1. Die if they have the same name but different 750 * sha1s. 751 */ 752static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 753{ 754if(strcmp(ref1->name, ref2->name)) 755return0; 756 757/* Duplicate name; make sure that they don't conflict: */ 758 759if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 760/* This is impossible by construction */ 761die("Reference directory conflict:%s", ref1->name); 762 763if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 764die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 765 766warning("Duplicated ref:%s", ref1->name); 767return1; 768} 769 770/* 771 * Sort the entries in dir non-recursively (if they are not already 772 * sorted) and remove any duplicate entries. 773 */ 774static voidsort_ref_dir(struct ref_dir *dir) 775{ 776int i, j; 777struct ref_entry *last = NULL; 778 779/* 780 * This check also prevents passing a zero-length array to qsort(), 781 * which is a problem on some platforms. 782 */ 783if(dir->sorted == dir->nr) 784return; 785 786qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 787 788/* Remove any duplicates: */ 789for(i =0, j =0; j < dir->nr; j++) { 790struct ref_entry *entry = dir->entries[j]; 791if(last &&is_dup_ref(last, entry)) 792free_ref_entry(entry); 793else 794 last = dir->entries[i++] = entry; 795} 796 dir->sorted = dir->nr = i; 797} 798 799/* Include broken references in a do_for_each_ref*() iteration: */ 800#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 801 802/* 803 * Return true iff the reference described by entry can be resolved to 804 * an object in the database. Emit a warning if the referred-to 805 * object does not exist. 806 */ 807static intref_resolves_to_object(struct ref_entry *entry) 808{ 809if(entry->flag & REF_ISBROKEN) 810return0; 811if(!has_sha1_file(entry->u.value.sha1)) { 812error("%sdoes not point to a valid object!", entry->name); 813return0; 814} 815return1; 816} 817 818/* 819 * current_ref is a performance hack: when iterating over references 820 * using the for_each_ref*() functions, current_ref is set to the 821 * current reference's entry before calling the callback function. If 822 * the callback function calls peel_ref(), then peel_ref() first 823 * checks whether the reference to be peeled is the current reference 824 * (it usually is) and if so, returns that reference's peeled version 825 * if it is available. This avoids a refname lookup in a common case. 826 */ 827static struct ref_entry *current_ref; 828 829typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 830 831struct ref_entry_cb { 832const char*base; 833int trim; 834int flags; 835 each_ref_fn *fn; 836void*cb_data; 837}; 838 839/* 840 * Handle one reference in a do_for_each_ref*()-style iteration, 841 * calling an each_ref_fn for each entry. 842 */ 843static intdo_one_ref(struct ref_entry *entry,void*cb_data) 844{ 845struct ref_entry_cb *data = cb_data; 846struct ref_entry *old_current_ref; 847int retval; 848 849if(!starts_with(entry->name, data->base)) 850return0; 851 852if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 853!ref_resolves_to_object(entry)) 854return0; 855 856/* Store the old value, in case this is a recursive call: */ 857 old_current_ref = current_ref; 858 current_ref = entry; 859 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 860 entry->flag, data->cb_data); 861 current_ref = old_current_ref; 862return retval; 863} 864 865/* 866 * Call fn for each reference in dir that has index in the range 867 * offset <= index < dir->nr. Recurse into subdirectories that are in 868 * that index range, sorting them before iterating. This function 869 * does not sort dir itself; it should be sorted beforehand. fn is 870 * called for all references, including broken ones. 871 */ 872static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 873 each_ref_entry_fn fn,void*cb_data) 874{ 875int i; 876assert(dir->sorted == dir->nr); 877for(i = offset; i < dir->nr; i++) { 878struct ref_entry *entry = dir->entries[i]; 879int retval; 880if(entry->flag & REF_DIR) { 881struct ref_dir *subdir =get_ref_dir(entry); 882sort_ref_dir(subdir); 883 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 884}else{ 885 retval =fn(entry, cb_data); 886} 887if(retval) 888return retval; 889} 890return0; 891} 892 893/* 894 * Call fn for each reference in the union of dir1 and dir2, in order 895 * by refname. Recurse into subdirectories. If a value entry appears 896 * in both dir1 and dir2, then only process the version that is in 897 * dir2. The input dirs must already be sorted, but subdirs will be 898 * sorted as needed. fn is called for all references, including 899 * broken ones. 900 */ 901static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 902struct ref_dir *dir2, 903 each_ref_entry_fn fn,void*cb_data) 904{ 905int retval; 906int i1 =0, i2 =0; 907 908assert(dir1->sorted == dir1->nr); 909assert(dir2->sorted == dir2->nr); 910while(1) { 911struct ref_entry *e1, *e2; 912int cmp; 913if(i1 == dir1->nr) { 914returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 915} 916if(i2 == dir2->nr) { 917returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 918} 919 e1 = dir1->entries[i1]; 920 e2 = dir2->entries[i2]; 921 cmp =strcmp(e1->name, e2->name); 922if(cmp ==0) { 923if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 924/* Both are directories; descend them in parallel. */ 925struct ref_dir *subdir1 =get_ref_dir(e1); 926struct ref_dir *subdir2 =get_ref_dir(e2); 927sort_ref_dir(subdir1); 928sort_ref_dir(subdir2); 929 retval =do_for_each_entry_in_dirs( 930 subdir1, subdir2, fn, cb_data); 931 i1++; 932 i2++; 933}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 934/* Both are references; ignore the one from dir1. */ 935 retval =fn(e2, cb_data); 936 i1++; 937 i2++; 938}else{ 939die("conflict between reference and directory:%s", 940 e1->name); 941} 942}else{ 943struct ref_entry *e; 944if(cmp <0) { 945 e = e1; 946 i1++; 947}else{ 948 e = e2; 949 i2++; 950} 951if(e->flag & REF_DIR) { 952struct ref_dir *subdir =get_ref_dir(e); 953sort_ref_dir(subdir); 954 retval =do_for_each_entry_in_dir( 955 subdir,0, fn, cb_data); 956}else{ 957 retval =fn(e, cb_data); 958} 959} 960if(retval) 961return retval; 962} 963} 964 965/* 966 * Load all of the refs from the dir into our in-memory cache. The hard work 967 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 968 * through all of the sub-directories. We do not even need to care about 969 * sorting, as traversal order does not matter to us. 970 */ 971static voidprime_ref_dir(struct ref_dir *dir) 972{ 973int i; 974for(i =0; i < dir->nr; i++) { 975struct ref_entry *entry = dir->entries[i]; 976if(entry->flag & REF_DIR) 977prime_ref_dir(get_ref_dir(entry)); 978} 979} 980/* 981 * Return true iff refname1 and refname2 conflict with each other. 982 * Two reference names conflict if one of them exactly matches the 983 * leading components of the other; e.g., "foo/bar" conflicts with 984 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 985 * "foo/barbados". 986 */ 987static intnames_conflict(const char*refname1,const char*refname2) 988{ 989for(; *refname1 && *refname1 == *refname2; refname1++, refname2++) 990; 991return(*refname1 =='\0'&& *refname2 =='/') 992|| (*refname1 =='/'&& *refname2 =='\0'); 993} 994 995struct name_conflict_cb { 996const char*refname; 997const char*oldrefname; 998const char*conflicting_refname; 999};10001001static intname_conflict_fn(struct ref_entry *entry,void*cb_data)1002{1003struct name_conflict_cb *data = (struct name_conflict_cb *)cb_data;1004if(data->oldrefname && !strcmp(data->oldrefname, entry->name))1005return0;1006if(names_conflict(data->refname, entry->name)) {1007 data->conflicting_refname = entry->name;1008return1;1009}1010return0;1011}10121013/*1014 * Return true iff a reference named refname could be created without1015 * conflicting with the name of an existing reference in dir. If1016 * oldrefname is non-NULL, ignore potential conflicts with oldrefname1017 * (e.g., because oldrefname is scheduled for deletion in the same1018 * operation).1019 */1020static intis_refname_available(const char*refname,const char*oldrefname,1021struct ref_dir *dir)1022{1023struct name_conflict_cb data;1024 data.refname = refname;1025 data.oldrefname = oldrefname;1026 data.conflicting_refname = NULL;10271028sort_ref_dir(dir);1029if(do_for_each_entry_in_dir(dir,0, name_conflict_fn, &data)) {1030error("'%s' exists; cannot create '%s'",1031 data.conflicting_refname, refname);1032return0;1033}1034return1;1035}10361037struct packed_ref_cache {1038struct ref_entry *root;10391040/*1041 * Count of references to the data structure in this instance,1042 * including the pointer from ref_cache::packed if any. The1043 * data will not be freed as long as the reference count is1044 * nonzero.1045 */1046unsigned int referrers;10471048/*1049 * Iff the packed-refs file associated with this instance is1050 * currently locked for writing, this points at the associated1051 * lock (which is owned by somebody else). The referrer count1052 * is also incremented when the file is locked and decremented1053 * when it is unlocked.1054 */1055struct lock_file *lock;10561057/* The metadata from when this packed-refs cache was read */1058struct stat_validity validity;1059};10601061/*1062 * Future: need to be in "struct repository"1063 * when doing a full libification.1064 */1065static struct ref_cache {1066struct ref_cache *next;1067struct ref_entry *loose;1068struct packed_ref_cache *packed;1069/*1070 * The submodule name, or "" for the main repo. We allocate1071 * length 1 rather than FLEX_ARRAY so that the main ref_cache1072 * is initialized correctly.1073 */1074char name[1];1075} ref_cache, *submodule_ref_caches;10761077/* Lock used for the main packed-refs file: */1078static struct lock_file packlock;10791080/*1081 * Increment the reference count of *packed_refs.1082 */1083static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1084{1085 packed_refs->referrers++;1086}10871088/*1089 * Decrease the reference count of *packed_refs. If it goes to zero,1090 * free *packed_refs and return true; otherwise return false.1091 */1092static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1093{1094if(!--packed_refs->referrers) {1095free_ref_entry(packed_refs->root);1096stat_validity_clear(&packed_refs->validity);1097free(packed_refs);1098return1;1099}else{1100return0;1101}1102}11031104static voidclear_packed_ref_cache(struct ref_cache *refs)1105{1106if(refs->packed) {1107struct packed_ref_cache *packed_refs = refs->packed;11081109if(packed_refs->lock)1110die("internal error: packed-ref cache cleared while locked");1111 refs->packed = NULL;1112release_packed_ref_cache(packed_refs);1113}1114}11151116static voidclear_loose_ref_cache(struct ref_cache *refs)1117{1118if(refs->loose) {1119free_ref_entry(refs->loose);1120 refs->loose = NULL;1121}1122}11231124static struct ref_cache *create_ref_cache(const char*submodule)1125{1126int len;1127struct ref_cache *refs;1128if(!submodule)1129 submodule ="";1130 len =strlen(submodule) +1;1131 refs =xcalloc(1,sizeof(struct ref_cache) + len);1132memcpy(refs->name, submodule, len);1133return refs;1134}11351136/*1137 * Return a pointer to a ref_cache for the specified submodule. For1138 * the main repository, use submodule==NULL. The returned structure1139 * will be allocated and initialized but not necessarily populated; it1140 * should not be freed.1141 */1142static struct ref_cache *get_ref_cache(const char*submodule)1143{1144struct ref_cache *refs;11451146if(!submodule || !*submodule)1147return&ref_cache;11481149for(refs = submodule_ref_caches; refs; refs = refs->next)1150if(!strcmp(submodule, refs->name))1151return refs;11521153 refs =create_ref_cache(submodule);1154 refs->next = submodule_ref_caches;1155 submodule_ref_caches = refs;1156return refs;1157}11581159/* The length of a peeled reference line in packed-refs, including EOL: */1160#define PEELED_LINE_LENGTH 4211611162/*1163 * The packed-refs header line that we write out. Perhaps other1164 * traits will be added later. The trailing space is required.1165 */1166static const char PACKED_REFS_HEADER[] =1167"# pack-refs with: peeled fully-peeled\n";11681169/*1170 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1171 * Return a pointer to the refname within the line (null-terminated),1172 * or NULL if there was a problem.1173 */1174static const char*parse_ref_line(char*line,unsigned char*sha1)1175{1176/*1177 * 42: the answer to everything.1178 *1179 * In this case, it happens to be the answer to1180 * 40 (length of sha1 hex representation)1181 * +1 (space in between hex and name)1182 * +1 (newline at the end of the line)1183 */1184int len =strlen(line) -42;11851186if(len <=0)1187return NULL;1188if(get_sha1_hex(line, sha1) <0)1189return NULL;1190if(!isspace(line[40]))1191return NULL;1192 line +=41;1193if(isspace(*line))1194return NULL;1195if(line[len] !='\n')1196return NULL;1197 line[len] =0;11981199return line;1200}12011202/*1203 * Read f, which is a packed-refs file, into dir.1204 *1205 * A comment line of the form "# pack-refs with: " may contain zero or1206 * more traits. We interpret the traits as follows:1207 *1208 * No traits:1209 *1210 * Probably no references are peeled. But if the file contains a1211 * peeled value for a reference, we will use it.1212 *1213 * peeled:1214 *1215 * References under "refs/tags/", if they *can* be peeled, *are*1216 * peeled in this file. References outside of "refs/tags/" are1217 * probably not peeled even if they could have been, but if we find1218 * a peeled value for such a reference we will use it.1219 *1220 * fully-peeled:1221 *1222 * All references in the file that can be peeled are peeled.1223 * Inversely (and this is more important), any references in the1224 * file for which no peeled value is recorded is not peelable. This1225 * trait should typically be written alongside "peeled" for1226 * compatibility with older clients, but we do not require it1227 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1228 */1229static voidread_packed_refs(FILE*f,struct ref_dir *dir)1230{1231struct ref_entry *last = NULL;1232char refline[PATH_MAX];1233enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12341235while(fgets(refline,sizeof(refline), f)) {1236unsigned char sha1[20];1237const char*refname;1238static const char header[] ="# pack-refs with:";12391240if(!strncmp(refline, header,sizeof(header)-1)) {1241const char*traits = refline +sizeof(header) -1;1242if(strstr(traits," fully-peeled "))1243 peeled = PEELED_FULLY;1244else if(strstr(traits," peeled "))1245 peeled = PEELED_TAGS;1246/* perhaps other traits later as well */1247continue;1248}12491250 refname =parse_ref_line(refline, sha1);1251if(refname) {1252 last =create_ref_entry(refname, sha1, REF_ISPACKED,1);1253if(peeled == PEELED_FULLY ||1254(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1255 last->flag |= REF_KNOWS_PEELED;1256add_ref(dir, last);1257continue;1258}1259if(last &&1260 refline[0] =='^'&&1261strlen(refline) == PEELED_LINE_LENGTH &&1262 refline[PEELED_LINE_LENGTH -1] =='\n'&&1263!get_sha1_hex(refline +1, sha1)) {1264hashcpy(last->u.value.peeled, sha1);1265/*1266 * Regardless of what the file header said,1267 * we definitely know the value of *this*1268 * reference:1269 */1270 last->flag |= REF_KNOWS_PEELED;1271}1272}1273}12741275/*1276 * Get the packed_ref_cache for the specified ref_cache, creating it1277 * if necessary.1278 */1279static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1280{1281const char*packed_refs_file;12821283if(*refs->name)1284 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1285else1286 packed_refs_file =git_path("packed-refs");12871288if(refs->packed &&1289!stat_validity_check(&refs->packed->validity, packed_refs_file))1290clear_packed_ref_cache(refs);12911292if(!refs->packed) {1293FILE*f;12941295 refs->packed =xcalloc(1,sizeof(*refs->packed));1296acquire_packed_ref_cache(refs->packed);1297 refs->packed->root =create_dir_entry(refs,"",0,0);1298 f =fopen(packed_refs_file,"r");1299if(f) {1300stat_validity_update(&refs->packed->validity,fileno(f));1301read_packed_refs(f,get_ref_dir(refs->packed->root));1302fclose(f);1303}1304}1305return refs->packed;1306}13071308static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1309{1310returnget_ref_dir(packed_ref_cache->root);1311}13121313static struct ref_dir *get_packed_refs(struct ref_cache *refs)1314{1315returnget_packed_ref_dir(get_packed_ref_cache(refs));1316}13171318voidadd_packed_ref(const char*refname,const unsigned char*sha1)1319{1320struct packed_ref_cache *packed_ref_cache =1321get_packed_ref_cache(&ref_cache);13221323if(!packed_ref_cache->lock)1324die("internal error: packed refs not locked");1325add_ref(get_packed_ref_dir(packed_ref_cache),1326create_ref_entry(refname, sha1, REF_ISPACKED,1));1327}13281329/*1330 * Read the loose references from the namespace dirname into dir1331 * (without recursing). dirname must end with '/'. dir must be the1332 * directory entry corresponding to dirname.1333 */1334static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1335{1336struct ref_cache *refs = dir->ref_cache;1337DIR*d;1338const char*path;1339struct dirent *de;1340int dirnamelen =strlen(dirname);1341struct strbuf refname;13421343if(*refs->name)1344 path =git_path_submodule(refs->name,"%s", dirname);1345else1346 path =git_path("%s", dirname);13471348 d =opendir(path);1349if(!d)1350return;13511352strbuf_init(&refname, dirnamelen +257);1353strbuf_add(&refname, dirname, dirnamelen);13541355while((de =readdir(d)) != NULL) {1356unsigned char sha1[20];1357struct stat st;1358int flag;1359const char*refdir;13601361if(de->d_name[0] =='.')1362continue;1363if(ends_with(de->d_name,".lock"))1364continue;1365strbuf_addstr(&refname, de->d_name);1366 refdir = *refs->name1367?git_path_submodule(refs->name,"%s", refname.buf)1368:git_path("%s", refname.buf);1369if(stat(refdir, &st) <0) {1370;/* silently ignore */1371}else if(S_ISDIR(st.st_mode)) {1372strbuf_addch(&refname,'/');1373add_entry_to_dir(dir,1374create_dir_entry(refs, refname.buf,1375 refname.len,1));1376}else{1377if(*refs->name) {1378hashclr(sha1);1379 flag =0;1380if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1381hashclr(sha1);1382 flag |= REF_ISBROKEN;1383}1384}else if(read_ref_full(refname.buf, sha1,1, &flag)) {1385hashclr(sha1);1386 flag |= REF_ISBROKEN;1387}1388add_entry_to_dir(dir,1389create_ref_entry(refname.buf, sha1, flag,1));1390}1391strbuf_setlen(&refname, dirnamelen);1392}1393strbuf_release(&refname);1394closedir(d);1395}13961397static struct ref_dir *get_loose_refs(struct ref_cache *refs)1398{1399if(!refs->loose) {1400/*1401 * Mark the top-level directory complete because we1402 * are about to read the only subdirectory that can1403 * hold references:1404 */1405 refs->loose =create_dir_entry(refs,"",0,0);1406/*1407 * Create an incomplete entry for "refs/":1408 */1409add_entry_to_dir(get_ref_dir(refs->loose),1410create_dir_entry(refs,"refs/",5,1));1411}1412returnget_ref_dir(refs->loose);1413}14141415/* We allow "recursive" symbolic refs. Only within reason, though */1416#define MAXDEPTH 51417#define MAXREFLEN (1024)14181419/*1420 * Called by resolve_gitlink_ref_recursive() after it failed to read1421 * from the loose refs in ref_cache refs. Find <refname> in the1422 * packed-refs file for the submodule.1423 */1424static intresolve_gitlink_packed_ref(struct ref_cache *refs,1425const char*refname,unsigned char*sha1)1426{1427struct ref_entry *ref;1428struct ref_dir *dir =get_packed_refs(refs);14291430 ref =find_ref(dir, refname);1431if(ref == NULL)1432return-1;14331434hashcpy(sha1, ref->u.value.sha1);1435return0;1436}14371438static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1439const char*refname,unsigned char*sha1,1440int recursion)1441{1442int fd, len;1443char buffer[128], *p;1444char*path;14451446if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1447return-1;1448 path = *refs->name1449?git_path_submodule(refs->name,"%s", refname)1450:git_path("%s", refname);1451 fd =open(path, O_RDONLY);1452if(fd <0)1453returnresolve_gitlink_packed_ref(refs, refname, sha1);14541455 len =read(fd, buffer,sizeof(buffer)-1);1456close(fd);1457if(len <0)1458return-1;1459while(len &&isspace(buffer[len-1]))1460 len--;1461 buffer[len] =0;14621463/* Was it a detached head or an old-fashioned symlink? */1464if(!get_sha1_hex(buffer, sha1))1465return0;14661467/* Symref? */1468if(strncmp(buffer,"ref:",4))1469return-1;1470 p = buffer +4;1471while(isspace(*p))1472 p++;14731474returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1475}14761477intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1478{1479int len =strlen(path), retval;1480char*submodule;1481struct ref_cache *refs;14821483while(len && path[len-1] =='/')1484 len--;1485if(!len)1486return-1;1487 submodule =xstrndup(path, len);1488 refs =get_ref_cache(submodule);1489free(submodule);14901491 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1492return retval;1493}14941495/*1496 * Return the ref_entry for the given refname from the packed1497 * references. If it does not exist, return NULL.1498 */1499static struct ref_entry *get_packed_ref(const char*refname)1500{1501returnfind_ref(get_packed_refs(&ref_cache), refname);1502}15031504/*1505 * A loose ref file doesn't exist; check for a packed ref. The1506 * options are forwarded from resolve_safe_unsafe().1507 */1508static const char*handle_missing_loose_ref(const char*refname,1509unsigned char*sha1,1510int reading,1511int*flag)1512{1513struct ref_entry *entry;15141515/*1516 * The loose reference file does not exist; check for a packed1517 * reference.1518 */1519 entry =get_packed_ref(refname);1520if(entry) {1521hashcpy(sha1, entry->u.value.sha1);1522if(flag)1523*flag |= REF_ISPACKED;1524return refname;1525}1526/* The reference is not a packed reference, either. */1527if(reading) {1528return NULL;1529}else{1530hashclr(sha1);1531return refname;1532}1533}15341535/* This function needs to return a meaningful errno on failure */1536const char*resolve_ref_unsafe(const char*refname,unsigned char*sha1,int reading,int*flag)1537{1538int depth = MAXDEPTH;1539 ssize_t len;1540char buffer[256];1541static char refname_buffer[256];15421543if(flag)1544*flag =0;15451546if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1547 errno = EINVAL;1548return NULL;1549}15501551for(;;) {1552char path[PATH_MAX];1553struct stat st;1554char*buf;1555int fd;15561557if(--depth <0) {1558 errno = ELOOP;1559return NULL;1560}15611562git_snpath(path,sizeof(path),"%s", refname);15631564/*1565 * We might have to loop back here to avoid a race1566 * condition: first we lstat() the file, then we try1567 * to read it as a link or as a file. But if somebody1568 * changes the type of the file (file <-> directory1569 * <-> symlink) between the lstat() and reading, then1570 * we don't want to report that as an error but rather1571 * try again starting with the lstat().1572 */1573 stat_ref:1574if(lstat(path, &st) <0) {1575if(errno == ENOENT)1576returnhandle_missing_loose_ref(refname, sha1,1577 reading, flag);1578else1579return NULL;1580}15811582/* Follow "normalized" - ie "refs/.." symlinks by hand */1583if(S_ISLNK(st.st_mode)) {1584 len =readlink(path, buffer,sizeof(buffer)-1);1585if(len <0) {1586if(errno == ENOENT || errno == EINVAL)1587/* inconsistent with lstat; retry */1588goto stat_ref;1589else1590return NULL;1591}1592 buffer[len] =0;1593if(starts_with(buffer,"refs/") &&1594!check_refname_format(buffer,0)) {1595strcpy(refname_buffer, buffer);1596 refname = refname_buffer;1597if(flag)1598*flag |= REF_ISSYMREF;1599continue;1600}1601}16021603/* Is it a directory? */1604if(S_ISDIR(st.st_mode)) {1605 errno = EISDIR;1606return NULL;1607}16081609/*1610 * Anything else, just open it and try to use it as1611 * a ref1612 */1613 fd =open(path, O_RDONLY);1614if(fd <0) {1615if(errno == ENOENT)1616/* inconsistent with lstat; retry */1617goto stat_ref;1618else1619return NULL;1620}1621 len =read_in_full(fd, buffer,sizeof(buffer)-1);1622if(len <0) {1623int save_errno = errno;1624close(fd);1625 errno = save_errno;1626return NULL;1627}1628close(fd);1629while(len &&isspace(buffer[len-1]))1630 len--;1631 buffer[len] ='\0';16321633/*1634 * Is it a symbolic ref?1635 */1636if(!starts_with(buffer,"ref:")) {1637/*1638 * Please note that FETCH_HEAD has a second1639 * line containing other data.1640 */1641if(get_sha1_hex(buffer, sha1) ||1642(buffer[40] !='\0'&& !isspace(buffer[40]))) {1643if(flag)1644*flag |= REF_ISBROKEN;1645 errno = EINVAL;1646return NULL;1647}1648return refname;1649}1650if(flag)1651*flag |= REF_ISSYMREF;1652 buf = buffer +4;1653while(isspace(*buf))1654 buf++;1655if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1656if(flag)1657*flag |= REF_ISBROKEN;1658 errno = EINVAL;1659return NULL;1660}1661 refname =strcpy(refname_buffer, buf);1662}1663}16641665char*resolve_refdup(const char*ref,unsigned char*sha1,int reading,int*flag)1666{1667const char*ret =resolve_ref_unsafe(ref, sha1, reading, flag);1668return ret ?xstrdup(ret) : NULL;1669}16701671/* The argument to filter_refs */1672struct ref_filter {1673const char*pattern;1674 each_ref_fn *fn;1675void*cb_data;1676};16771678intread_ref_full(const char*refname,unsigned char*sha1,int reading,int*flags)1679{1680if(resolve_ref_unsafe(refname, sha1, reading, flags))1681return0;1682return-1;1683}16841685intread_ref(const char*refname,unsigned char*sha1)1686{1687returnread_ref_full(refname, sha1,1, NULL);1688}16891690intref_exists(const char*refname)1691{1692unsigned char sha1[20];1693return!!resolve_ref_unsafe(refname, sha1,1, NULL);1694}16951696static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1697void*data)1698{1699struct ref_filter *filter = (struct ref_filter *)data;1700if(wildmatch(filter->pattern, refname,0, NULL))1701return0;1702return filter->fn(refname, sha1, flags, filter->cb_data);1703}17041705enum peel_status {1706/* object was peeled successfully: */1707 PEEL_PEELED =0,17081709/*1710 * object cannot be peeled because the named object (or an1711 * object referred to by a tag in the peel chain), does not1712 * exist.1713 */1714 PEEL_INVALID = -1,17151716/* object cannot be peeled because it is not a tag: */1717 PEEL_NON_TAG = -2,17181719/* ref_entry contains no peeled value because it is a symref: */1720 PEEL_IS_SYMREF = -3,17211722/*1723 * ref_entry cannot be peeled because it is broken (i.e., the1724 * symbolic reference cannot even be resolved to an object1725 * name):1726 */1727 PEEL_BROKEN = -41728};17291730/*1731 * Peel the named object; i.e., if the object is a tag, resolve the1732 * tag recursively until a non-tag is found. If successful, store the1733 * result to sha1 and return PEEL_PEELED. If the object is not a tag1734 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1735 * and leave sha1 unchanged.1736 */1737static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1738{1739struct object *o =lookup_unknown_object(name);17401741if(o->type == OBJ_NONE) {1742int type =sha1_object_info(name, NULL);1743if(type <0|| !object_as_type(o, type,0))1744return PEEL_INVALID;1745}17461747if(o->type != OBJ_TAG)1748return PEEL_NON_TAG;17491750 o =deref_tag_noverify(o);1751if(!o)1752return PEEL_INVALID;17531754hashcpy(sha1, o->sha1);1755return PEEL_PEELED;1756}17571758/*1759 * Peel the entry (if possible) and return its new peel_status. If1760 * repeel is true, re-peel the entry even if there is an old peeled1761 * value that is already stored in it.1762 *1763 * It is OK to call this function with a packed reference entry that1764 * might be stale and might even refer to an object that has since1765 * been garbage-collected. In such a case, if the entry has1766 * REF_KNOWS_PEELED then leave the status unchanged and return1767 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1768 */1769static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1770{1771enum peel_status status;17721773if(entry->flag & REF_KNOWS_PEELED) {1774if(repeel) {1775 entry->flag &= ~REF_KNOWS_PEELED;1776hashclr(entry->u.value.peeled);1777}else{1778returnis_null_sha1(entry->u.value.peeled) ?1779 PEEL_NON_TAG : PEEL_PEELED;1780}1781}1782if(entry->flag & REF_ISBROKEN)1783return PEEL_BROKEN;1784if(entry->flag & REF_ISSYMREF)1785return PEEL_IS_SYMREF;17861787 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1788if(status == PEEL_PEELED || status == PEEL_NON_TAG)1789 entry->flag |= REF_KNOWS_PEELED;1790return status;1791}17921793intpeel_ref(const char*refname,unsigned char*sha1)1794{1795int flag;1796unsigned char base[20];17971798if(current_ref && (current_ref->name == refname1799|| !strcmp(current_ref->name, refname))) {1800if(peel_entry(current_ref,0))1801return-1;1802hashcpy(sha1, current_ref->u.value.peeled);1803return0;1804}18051806if(read_ref_full(refname, base,1, &flag))1807return-1;18081809/*1810 * If the reference is packed, read its ref_entry from the1811 * cache in the hope that we already know its peeled value.1812 * We only try this optimization on packed references because1813 * (a) forcing the filling of the loose reference cache could1814 * be expensive and (b) loose references anyway usually do not1815 * have REF_KNOWS_PEELED.1816 */1817if(flag & REF_ISPACKED) {1818struct ref_entry *r =get_packed_ref(refname);1819if(r) {1820if(peel_entry(r,0))1821return-1;1822hashcpy(sha1, r->u.value.peeled);1823return0;1824}1825}18261827returnpeel_object(base, sha1);1828}18291830struct warn_if_dangling_data {1831FILE*fp;1832const char*refname;1833const struct string_list *refnames;1834const char*msg_fmt;1835};18361837static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1838int flags,void*cb_data)1839{1840struct warn_if_dangling_data *d = cb_data;1841const char*resolves_to;1842unsigned char junk[20];18431844if(!(flags & REF_ISSYMREF))1845return0;18461847 resolves_to =resolve_ref_unsafe(refname, junk,0, NULL);1848if(!resolves_to1849|| (d->refname1850?strcmp(resolves_to, d->refname)1851: !string_list_has_string(d->refnames, resolves_to))) {1852return0;1853}18541855fprintf(d->fp, d->msg_fmt, refname);1856fputc('\n', d->fp);1857return0;1858}18591860voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1861{1862struct warn_if_dangling_data data;18631864 data.fp = fp;1865 data.refname = refname;1866 data.refnames = NULL;1867 data.msg_fmt = msg_fmt;1868for_each_rawref(warn_if_dangling_symref, &data);1869}18701871voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1872{1873struct warn_if_dangling_data data;18741875 data.fp = fp;1876 data.refname = NULL;1877 data.refnames = refnames;1878 data.msg_fmt = msg_fmt;1879for_each_rawref(warn_if_dangling_symref, &data);1880}18811882/*1883 * Call fn for each reference in the specified ref_cache, omitting1884 * references not in the containing_dir of base. fn is called for all1885 * references, including broken ones. If fn ever returns a non-zero1886 * value, stop the iteration and return that value; otherwise, return1887 * 0.1888 */1889static intdo_for_each_entry(struct ref_cache *refs,const char*base,1890 each_ref_entry_fn fn,void*cb_data)1891{1892struct packed_ref_cache *packed_ref_cache;1893struct ref_dir *loose_dir;1894struct ref_dir *packed_dir;1895int retval =0;18961897/*1898 * We must make sure that all loose refs are read before accessing the1899 * packed-refs file; this avoids a race condition in which loose refs1900 * are migrated to the packed-refs file by a simultaneous process, but1901 * our in-memory view is from before the migration. get_packed_ref_cache()1902 * takes care of making sure our view is up to date with what is on1903 * disk.1904 */1905 loose_dir =get_loose_refs(refs);1906if(base && *base) {1907 loose_dir =find_containing_dir(loose_dir, base,0);1908}1909if(loose_dir)1910prime_ref_dir(loose_dir);19111912 packed_ref_cache =get_packed_ref_cache(refs);1913acquire_packed_ref_cache(packed_ref_cache);1914 packed_dir =get_packed_ref_dir(packed_ref_cache);1915if(base && *base) {1916 packed_dir =find_containing_dir(packed_dir, base,0);1917}19181919if(packed_dir && loose_dir) {1920sort_ref_dir(packed_dir);1921sort_ref_dir(loose_dir);1922 retval =do_for_each_entry_in_dirs(1923 packed_dir, loose_dir, fn, cb_data);1924}else if(packed_dir) {1925sort_ref_dir(packed_dir);1926 retval =do_for_each_entry_in_dir(1927 packed_dir,0, fn, cb_data);1928}else if(loose_dir) {1929sort_ref_dir(loose_dir);1930 retval =do_for_each_entry_in_dir(1931 loose_dir,0, fn, cb_data);1932}19331934release_packed_ref_cache(packed_ref_cache);1935return retval;1936}19371938/*1939 * Call fn for each reference in the specified ref_cache for which the1940 * refname begins with base. If trim is non-zero, then trim that many1941 * characters off the beginning of each refname before passing the1942 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1943 * broken references in the iteration. If fn ever returns a non-zero1944 * value, stop the iteration and return that value; otherwise, return1945 * 0.1946 */1947static intdo_for_each_ref(struct ref_cache *refs,const char*base,1948 each_ref_fn fn,int trim,int flags,void*cb_data)1949{1950struct ref_entry_cb data;1951 data.base = base;1952 data.trim = trim;1953 data.flags = flags;1954 data.fn = fn;1955 data.cb_data = cb_data;19561957returndo_for_each_entry(refs, base, do_one_ref, &data);1958}19591960static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1961{1962unsigned char sha1[20];1963int flag;19641965if(submodule) {1966if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1967returnfn("HEAD", sha1,0, cb_data);19681969return0;1970}19711972if(!read_ref_full("HEAD", sha1,1, &flag))1973returnfn("HEAD", sha1, flag, cb_data);19741975return0;1976}19771978inthead_ref(each_ref_fn fn,void*cb_data)1979{1980returndo_head_ref(NULL, fn, cb_data);1981}19821983inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1984{1985returndo_head_ref(submodule, fn, cb_data);1986}19871988intfor_each_ref(each_ref_fn fn,void*cb_data)1989{1990returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1991}19921993intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1994{1995returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1996}19971998intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1999{2000returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2001}20022003intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2004 each_ref_fn fn,void*cb_data)2005{2006returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2007}20082009intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2010{2011returnfor_each_ref_in("refs/tags/", fn, cb_data);2012}20132014intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2015{2016returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2017}20182019intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2020{2021returnfor_each_ref_in("refs/heads/", fn, cb_data);2022}20232024intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2025{2026returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2027}20282029intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2030{2031returnfor_each_ref_in("refs/remotes/", fn, cb_data);2032}20332034intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2035{2036returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2037}20382039intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2040{2041returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2042}20432044inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2045{2046struct strbuf buf = STRBUF_INIT;2047int ret =0;2048unsigned char sha1[20];2049int flag;20502051strbuf_addf(&buf,"%sHEAD",get_git_namespace());2052if(!read_ref_full(buf.buf, sha1,1, &flag))2053 ret =fn(buf.buf, sha1, flag, cb_data);2054strbuf_release(&buf);20552056return ret;2057}20582059intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2060{2061struct strbuf buf = STRBUF_INIT;2062int ret;2063strbuf_addf(&buf,"%srefs/",get_git_namespace());2064 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2065strbuf_release(&buf);2066return ret;2067}20682069intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2070const char*prefix,void*cb_data)2071{2072struct strbuf real_pattern = STRBUF_INIT;2073struct ref_filter filter;2074int ret;20752076if(!prefix && !starts_with(pattern,"refs/"))2077strbuf_addstr(&real_pattern,"refs/");2078else if(prefix)2079strbuf_addstr(&real_pattern, prefix);2080strbuf_addstr(&real_pattern, pattern);20812082if(!has_glob_specials(pattern)) {2083/* Append implied '/' '*' if not present. */2084if(real_pattern.buf[real_pattern.len -1] !='/')2085strbuf_addch(&real_pattern,'/');2086/* No need to check for '*', there is none. */2087strbuf_addch(&real_pattern,'*');2088}20892090 filter.pattern = real_pattern.buf;2091 filter.fn = fn;2092 filter.cb_data = cb_data;2093 ret =for_each_ref(filter_refs, &filter);20942095strbuf_release(&real_pattern);2096return ret;2097}20982099intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2100{2101returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2102}21032104intfor_each_rawref(each_ref_fn fn,void*cb_data)2105{2106returndo_for_each_ref(&ref_cache,"", fn,0,2107 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2108}21092110const char*prettify_refname(const char*name)2111{2112return name + (2113starts_with(name,"refs/heads/") ?11:2114starts_with(name,"refs/tags/") ?10:2115starts_with(name,"refs/remotes/") ?13:21160);2117}21182119static const char*ref_rev_parse_rules[] = {2120"%.*s",2121"refs/%.*s",2122"refs/tags/%.*s",2123"refs/heads/%.*s",2124"refs/remotes/%.*s",2125"refs/remotes/%.*s/HEAD",2126 NULL2127};21282129intrefname_match(const char*abbrev_name,const char*full_name)2130{2131const char**p;2132const int abbrev_name_len =strlen(abbrev_name);21332134for(p = ref_rev_parse_rules; *p; p++) {2135if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2136return1;2137}2138}21392140return0;2141}21422143/* This function should make sure errno is meaningful on error */2144static struct ref_lock *verify_lock(struct ref_lock *lock,2145const unsigned char*old_sha1,int mustexist)2146{2147if(read_ref_full(lock->ref_name, lock->old_sha1, mustexist, NULL)) {2148int save_errno = errno;2149error("Can't verify ref%s", lock->ref_name);2150unlock_ref(lock);2151 errno = save_errno;2152return NULL;2153}2154if(hashcmp(lock->old_sha1, old_sha1)) {2155error("Ref%sis at%sbut expected%s", lock->ref_name,2156sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2157unlock_ref(lock);2158 errno = EBUSY;2159return NULL;2160}2161return lock;2162}21632164static intremove_empty_directories(const char*file)2165{2166/* we want to create a file but there is a directory there;2167 * if that is an empty directory (or a directory that contains2168 * only empty directories), remove them.2169 */2170struct strbuf path;2171int result, save_errno;21722173strbuf_init(&path,20);2174strbuf_addstr(&path, file);21752176 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2177 save_errno = errno;21782179strbuf_release(&path);2180 errno = save_errno;21812182return result;2183}21842185/*2186 * *string and *len will only be substituted, and *string returned (for2187 * later free()ing) if the string passed in is a magic short-hand form2188 * to name a branch.2189 */2190static char*substitute_branch_name(const char**string,int*len)2191{2192struct strbuf buf = STRBUF_INIT;2193int ret =interpret_branch_name(*string, *len, &buf);21942195if(ret == *len) {2196size_t size;2197*string =strbuf_detach(&buf, &size);2198*len = size;2199return(char*)*string;2200}22012202return NULL;2203}22042205intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2206{2207char*last_branch =substitute_branch_name(&str, &len);2208const char**p, *r;2209int refs_found =0;22102211*ref = NULL;2212for(p = ref_rev_parse_rules; *p; p++) {2213char fullref[PATH_MAX];2214unsigned char sha1_from_ref[20];2215unsigned char*this_result;2216int flag;22172218 this_result = refs_found ? sha1_from_ref : sha1;2219mksnpath(fullref,sizeof(fullref), *p, len, str);2220 r =resolve_ref_unsafe(fullref, this_result,1, &flag);2221if(r) {2222if(!refs_found++)2223*ref =xstrdup(r);2224if(!warn_ambiguous_refs)2225break;2226}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2227warning("ignoring dangling symref%s.", fullref);2228}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2229warning("ignoring broken ref%s.", fullref);2230}2231}2232free(last_branch);2233return refs_found;2234}22352236intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2237{2238char*last_branch =substitute_branch_name(&str, &len);2239const char**p;2240int logs_found =0;22412242*log = NULL;2243for(p = ref_rev_parse_rules; *p; p++) {2244unsigned char hash[20];2245char path[PATH_MAX];2246const char*ref, *it;22472248mksnpath(path,sizeof(path), *p, len, str);2249 ref =resolve_ref_unsafe(path, hash,1, NULL);2250if(!ref)2251continue;2252if(reflog_exists(path))2253 it = path;2254else if(strcmp(ref, path) &&reflog_exists(ref))2255 it = ref;2256else2257continue;2258if(!logs_found++) {2259*log =xstrdup(it);2260hashcpy(sha1, hash);2261}2262if(!warn_ambiguous_refs)2263break;2264}2265free(last_branch);2266return logs_found;2267}22682269/* This function should make sure errno is meaningful on error */2270static struct ref_lock *lock_ref_sha1_basic(const char*refname,2271const unsigned char*old_sha1,2272int flags,int*type_p)2273{2274char*ref_file;2275const char*orig_refname = refname;2276struct ref_lock *lock;2277int last_errno =0;2278int type, lflags;2279int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2280int missing =0;2281int attempts_remaining =3;22822283 lock =xcalloc(1,sizeof(struct ref_lock));2284 lock->lock_fd = -1;22852286 refname =resolve_ref_unsafe(refname, lock->old_sha1, mustexist, &type);2287if(!refname && errno == EISDIR) {2288/* we are trying to lock foo but we used to2289 * have foo/bar which now does not exist;2290 * it is normal for the empty directory 'foo'2291 * to remain.2292 */2293 ref_file =git_path("%s", orig_refname);2294if(remove_empty_directories(ref_file)) {2295 last_errno = errno;2296error("there are still refs under '%s'", orig_refname);2297goto error_return;2298}2299 refname =resolve_ref_unsafe(orig_refname, lock->old_sha1, mustexist, &type);2300}2301if(type_p)2302*type_p = type;2303if(!refname) {2304 last_errno = errno;2305error("unable to resolve reference%s:%s",2306 orig_refname,strerror(errno));2307goto error_return;2308}2309 missing =is_null_sha1(lock->old_sha1);2310/* When the ref did not exist and we are creating it,2311 * make sure there is no existing ref that is packed2312 * whose name begins with our refname, nor a ref whose2313 * name is a proper prefix of our refname.2314 */2315if(missing &&2316!is_refname_available(refname, NULL,get_packed_refs(&ref_cache))) {2317 last_errno = ENOTDIR;2318goto error_return;2319}23202321 lock->lk =xcalloc(1,sizeof(struct lock_file));23222323 lflags =0;2324if(flags & REF_NODEREF) {2325 refname = orig_refname;2326 lflags |= LOCK_NODEREF;2327}2328 lock->ref_name =xstrdup(refname);2329 lock->orig_ref_name =xstrdup(orig_refname);2330 ref_file =git_path("%s", refname);2331if(missing)2332 lock->force_write =1;2333if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2334 lock->force_write =1;23352336 retry:2337switch(safe_create_leading_directories(ref_file)) {2338case SCLD_OK:2339break;/* success */2340case SCLD_VANISHED:2341if(--attempts_remaining >0)2342goto retry;2343/* fall through */2344default:2345 last_errno = errno;2346error("unable to create directory for%s", ref_file);2347goto error_return;2348}23492350 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2351if(lock->lock_fd <0) {2352if(errno == ENOENT && --attempts_remaining >0)2353/*2354 * Maybe somebody just deleted one of the2355 * directories leading to ref_file. Try2356 * again:2357 */2358goto retry;2359else2360unable_to_lock_index_die(ref_file, errno);2361}2362return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;23632364 error_return:2365unlock_ref(lock);2366 errno = last_errno;2367return NULL;2368}23692370struct ref_lock *lock_ref_sha1(const char*refname,const unsigned char*old_sha1)2371{2372char refpath[PATH_MAX];2373if(check_refname_format(refname,0))2374return NULL;2375strcpy(refpath,mkpath("refs/%s", refname));2376returnlock_ref_sha1_basic(refpath, old_sha1,0, NULL);2377}23782379struct ref_lock *lock_any_ref_for_update(const char*refname,2380const unsigned char*old_sha1,2381int flags,int*type_p)2382{2383if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))2384return NULL;2385returnlock_ref_sha1_basic(refname, old_sha1, flags, type_p);2386}23872388/*2389 * Write an entry to the packed-refs file for the specified refname.2390 * If peeled is non-NULL, write it as the entry's peeled value.2391 */2392static voidwrite_packed_entry(int fd,char*refname,unsigned char*sha1,2393unsigned char*peeled)2394{2395char line[PATH_MAX +100];2396int len;23972398 len =snprintf(line,sizeof(line),"%s %s\n",2399sha1_to_hex(sha1), refname);2400/* this should not happen but just being defensive */2401if(len >sizeof(line))2402die("too long a refname '%s'", refname);2403write_or_die(fd, line, len);24042405if(peeled) {2406if(snprintf(line,sizeof(line),"^%s\n",2407sha1_to_hex(peeled)) != PEELED_LINE_LENGTH)2408die("internal error");2409write_or_die(fd, line, PEELED_LINE_LENGTH);2410}2411}24122413/*2414 * An each_ref_entry_fn that writes the entry to a packed-refs file.2415 */2416static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2417{2418int*fd = cb_data;2419enum peel_status peel_status =peel_entry(entry,0);24202421if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2422error("internal error:%sis not a valid packed reference!",2423 entry->name);2424write_packed_entry(*fd, entry->name, entry->u.value.sha1,2425 peel_status == PEEL_PEELED ?2426 entry->u.value.peeled : NULL);2427return0;2428}24292430/* This should return a meaningful errno on failure */2431intlock_packed_refs(int flags)2432{2433struct packed_ref_cache *packed_ref_cache;24342435if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2436return-1;2437/*2438 * Get the current packed-refs while holding the lock. If the2439 * packed-refs file has been modified since we last read it,2440 * this will automatically invalidate the cache and re-read2441 * the packed-refs file.2442 */2443 packed_ref_cache =get_packed_ref_cache(&ref_cache);2444 packed_ref_cache->lock = &packlock;2445/* Increment the reference count to prevent it from being freed: */2446acquire_packed_ref_cache(packed_ref_cache);2447return0;2448}24492450/*2451 * Commit the packed refs changes.2452 * On error we must make sure that errno contains a meaningful value.2453 */2454intcommit_packed_refs(void)2455{2456struct packed_ref_cache *packed_ref_cache =2457get_packed_ref_cache(&ref_cache);2458int error =0;2459int save_errno =0;24602461if(!packed_ref_cache->lock)2462die("internal error: packed-refs not locked");2463write_or_die(packed_ref_cache->lock->fd,2464 PACKED_REFS_HEADER,strlen(PACKED_REFS_HEADER));24652466do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),24670, write_packed_entry_fn,2468&packed_ref_cache->lock->fd);2469if(commit_lock_file(packed_ref_cache->lock)) {2470 save_errno = errno;2471 error = -1;2472}2473 packed_ref_cache->lock = NULL;2474release_packed_ref_cache(packed_ref_cache);2475 errno = save_errno;2476return error;2477}24782479voidrollback_packed_refs(void)2480{2481struct packed_ref_cache *packed_ref_cache =2482get_packed_ref_cache(&ref_cache);24832484if(!packed_ref_cache->lock)2485die("internal error: packed-refs not locked");2486rollback_lock_file(packed_ref_cache->lock);2487 packed_ref_cache->lock = NULL;2488release_packed_ref_cache(packed_ref_cache);2489clear_packed_ref_cache(&ref_cache);2490}24912492struct ref_to_prune {2493struct ref_to_prune *next;2494unsigned char sha1[20];2495char name[FLEX_ARRAY];2496};24972498struct pack_refs_cb_data {2499unsigned int flags;2500struct ref_dir *packed_refs;2501struct ref_to_prune *ref_to_prune;2502};25032504/*2505 * An each_ref_entry_fn that is run over loose references only. If2506 * the loose reference can be packed, add an entry in the packed ref2507 * cache. If the reference should be pruned, also add it to2508 * ref_to_prune in the pack_refs_cb_data.2509 */2510static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2511{2512struct pack_refs_cb_data *cb = cb_data;2513enum peel_status peel_status;2514struct ref_entry *packed_entry;2515int is_tag_ref =starts_with(entry->name,"refs/tags/");25162517/* ALWAYS pack tags */2518if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2519return0;25202521/* Do not pack symbolic or broken refs: */2522if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2523return0;25242525/* Add a packed ref cache entry equivalent to the loose entry. */2526 peel_status =peel_entry(entry,1);2527if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2528die("internal error peeling reference%s(%s)",2529 entry->name,sha1_to_hex(entry->u.value.sha1));2530 packed_entry =find_ref(cb->packed_refs, entry->name);2531if(packed_entry) {2532/* Overwrite existing packed entry with info from loose entry */2533 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2534hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2535}else{2536 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2537 REF_ISPACKED | REF_KNOWS_PEELED,0);2538add_ref(cb->packed_refs, packed_entry);2539}2540hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);25412542/* Schedule the loose reference for pruning if requested. */2543if((cb->flags & PACK_REFS_PRUNE)) {2544int namelen =strlen(entry->name) +1;2545struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2546hashcpy(n->sha1, entry->u.value.sha1);2547strcpy(n->name, entry->name);2548 n->next = cb->ref_to_prune;2549 cb->ref_to_prune = n;2550}2551return0;2552}25532554/*2555 * Remove empty parents, but spare refs/ and immediate subdirs.2556 * Note: munges *name.2557 */2558static voidtry_remove_empty_parents(char*name)2559{2560char*p, *q;2561int i;2562 p = name;2563for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2564while(*p && *p !='/')2565 p++;2566/* tolerate duplicate slashes; see check_refname_format() */2567while(*p =='/')2568 p++;2569}2570for(q = p; *q; q++)2571;2572while(1) {2573while(q > p && *q !='/')2574 q--;2575while(q > p && *(q-1) =='/')2576 q--;2577if(q == p)2578break;2579*q ='\0';2580if(rmdir(git_path("%s", name)))2581break;2582}2583}25842585/* make sure nobody touched the ref, and unlink */2586static voidprune_ref(struct ref_to_prune *r)2587{2588struct ref_lock *lock =lock_ref_sha1(r->name +5, r->sha1);25892590if(lock) {2591unlink_or_warn(git_path("%s", r->name));2592unlock_ref(lock);2593try_remove_empty_parents(r->name);2594}2595}25962597static voidprune_refs(struct ref_to_prune *r)2598{2599while(r) {2600prune_ref(r);2601 r = r->next;2602}2603}26042605intpack_refs(unsigned int flags)2606{2607struct pack_refs_cb_data cbdata;26082609memset(&cbdata,0,sizeof(cbdata));2610 cbdata.flags = flags;26112612lock_packed_refs(LOCK_DIE_ON_ERROR);2613 cbdata.packed_refs =get_packed_refs(&ref_cache);26142615do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2616 pack_if_possible_fn, &cbdata);26172618if(commit_packed_refs())2619die_errno("unable to overwrite old ref-pack file");26202621prune_refs(cbdata.ref_to_prune);2622return0;2623}26242625/*2626 * If entry is no longer needed in packed-refs, add it to the string2627 * list pointed to by cb_data. Reasons for deleting entries:2628 *2629 * - Entry is broken.2630 * - Entry is overridden by a loose ref.2631 * - Entry does not point at a valid object.2632 *2633 * In the first and third cases, also emit an error message because these2634 * are indications of repository corruption.2635 */2636static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2637{2638struct string_list *refs_to_delete = cb_data;26392640if(entry->flag & REF_ISBROKEN) {2641/* This shouldn't happen to packed refs. */2642error("%sis broken!", entry->name);2643string_list_append(refs_to_delete, entry->name);2644return0;2645}2646if(!has_sha1_file(entry->u.value.sha1)) {2647unsigned char sha1[20];2648int flags;26492650if(read_ref_full(entry->name, sha1,0, &flags))2651/* We should at least have found the packed ref. */2652die("Internal error");2653if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2654/*2655 * This packed reference is overridden by a2656 * loose reference, so it is OK that its value2657 * is no longer valid; for example, it might2658 * refer to an object that has been garbage2659 * collected. For this purpose we don't even2660 * care whether the loose reference itself is2661 * invalid, broken, symbolic, etc. Silently2662 * remove the packed reference.2663 */2664string_list_append(refs_to_delete, entry->name);2665return0;2666}2667/*2668 * There is no overriding loose reference, so the fact2669 * that this reference doesn't refer to a valid object2670 * indicates some kind of repository corruption.2671 * Report the problem, then omit the reference from2672 * the output.2673 */2674error("%sdoes not point to a valid object!", entry->name);2675string_list_append(refs_to_delete, entry->name);2676return0;2677}26782679return0;2680}26812682intrepack_without_refs(const char**refnames,int n,struct strbuf *err)2683{2684struct ref_dir *packed;2685struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2686struct string_list_item *ref_to_delete;2687int i, ret, removed =0;26882689/* Look for a packed ref */2690for(i =0; i < n; i++)2691if(get_packed_ref(refnames[i]))2692break;26932694/* Avoid locking if we have nothing to do */2695if(i == n)2696return0;/* no refname exists in packed refs */26972698if(lock_packed_refs(0)) {2699if(err) {2700unable_to_lock_message(git_path("packed-refs"), errno,2701 err);2702return-1;2703}2704unable_to_lock_error(git_path("packed-refs"), errno);2705returnerror("cannot delete '%s' from packed refs", refnames[i]);2706}2707 packed =get_packed_refs(&ref_cache);27082709/* Remove refnames from the cache */2710for(i =0; i < n; i++)2711if(remove_entry(packed, refnames[i]) != -1)2712 removed =1;2713if(!removed) {2714/*2715 * All packed entries disappeared while we were2716 * acquiring the lock.2717 */2718rollback_packed_refs();2719return0;2720}27212722/* Remove any other accumulated cruft */2723do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2724for_each_string_list_item(ref_to_delete, &refs_to_delete) {2725if(remove_entry(packed, ref_to_delete->string) == -1)2726die("internal error");2727}27282729/* Write what remains */2730 ret =commit_packed_refs();2731if(ret && err)2732strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2733strerror(errno));2734return ret;2735}27362737static intrepack_without_ref(const char*refname)2738{2739returnrepack_without_refs(&refname,1, NULL);2740}27412742static intdelete_ref_loose(struct ref_lock *lock,int flag)2743{2744if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2745/* loose */2746int err, i =strlen(lock->lk->filename) -5;/* .lock */27472748 lock->lk->filename[i] =0;2749 err =unlink_or_warn(lock->lk->filename);2750 lock->lk->filename[i] ='.';2751if(err && errno != ENOENT)2752return1;2753}2754return0;2755}27562757intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2758{2759struct ref_lock *lock;2760int ret =0, flag =0;27612762 lock =lock_ref_sha1_basic(refname, sha1, delopt, &flag);2763if(!lock)2764return1;2765 ret |=delete_ref_loose(lock, flag);27662767/* removing the loose one could have resurrected an earlier2768 * packed one. Also, if it was not loose we need to repack2769 * without it.2770 */2771 ret |=repack_without_ref(lock->ref_name);27722773unlink_or_warn(git_path("logs/%s", lock->ref_name));2774clear_loose_ref_cache(&ref_cache);2775unlock_ref(lock);2776return ret;2777}27782779/*2780 * People using contrib's git-new-workdir have .git/logs/refs ->2781 * /some/other/path/.git/logs/refs, and that may live on another device.2782 *2783 * IOW, to avoid cross device rename errors, the temporary renamed log must2784 * live into logs/refs.2785 */2786#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"27872788static intrename_tmp_log(const char*newrefname)2789{2790int attempts_remaining =4;27912792 retry:2793switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2794case SCLD_OK:2795break;/* success */2796case SCLD_VANISHED:2797if(--attempts_remaining >0)2798goto retry;2799/* fall through */2800default:2801error("unable to create directory for%s", newrefname);2802return-1;2803}28042805if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2806if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2807/*2808 * rename(a, b) when b is an existing2809 * directory ought to result in ISDIR, but2810 * Solaris 5.8 gives ENOTDIR. Sheesh.2811 */2812if(remove_empty_directories(git_path("logs/%s", newrefname))) {2813error("Directory not empty: logs/%s", newrefname);2814return-1;2815}2816goto retry;2817}else if(errno == ENOENT && --attempts_remaining >0) {2818/*2819 * Maybe another process just deleted one of2820 * the directories in the path to newrefname.2821 * Try again from the beginning.2822 */2823goto retry;2824}else{2825error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2826 newrefname,strerror(errno));2827return-1;2828}2829}2830return0;2831}28322833intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2834{2835unsigned char sha1[20], orig_sha1[20];2836int flag =0, logmoved =0;2837struct ref_lock *lock;2838struct stat loginfo;2839int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2840const char*symref = NULL;28412842if(log &&S_ISLNK(loginfo.st_mode))2843returnerror("reflog for%sis a symlink", oldrefname);28442845 symref =resolve_ref_unsafe(oldrefname, orig_sha1,1, &flag);2846if(flag & REF_ISSYMREF)2847returnerror("refname%sis a symbolic ref, renaming it is not supported",2848 oldrefname);2849if(!symref)2850returnerror("refname%snot found", oldrefname);28512852if(!is_refname_available(newrefname, oldrefname,get_packed_refs(&ref_cache)))2853return1;28542855if(!is_refname_available(newrefname, oldrefname,get_loose_refs(&ref_cache)))2856return1;28572858if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2859returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2860 oldrefname,strerror(errno));28612862if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2863error("unable to delete old%s", oldrefname);2864goto rollback;2865}28662867if(!read_ref_full(newrefname, sha1,1, &flag) &&2868delete_ref(newrefname, sha1, REF_NODEREF)) {2869if(errno==EISDIR) {2870if(remove_empty_directories(git_path("%s", newrefname))) {2871error("Directory not empty:%s", newrefname);2872goto rollback;2873}2874}else{2875error("unable to delete existing%s", newrefname);2876goto rollback;2877}2878}28792880if(log &&rename_tmp_log(newrefname))2881goto rollback;28822883 logmoved = log;28842885 lock =lock_ref_sha1_basic(newrefname, NULL,0, NULL);2886if(!lock) {2887error("unable to lock%sfor update", newrefname);2888goto rollback;2889}2890 lock->force_write =1;2891hashcpy(lock->old_sha1, orig_sha1);2892if(write_ref_sha1(lock, orig_sha1, logmsg)) {2893error("unable to write current sha1 into%s", newrefname);2894goto rollback;2895}28962897return0;28982899 rollback:2900 lock =lock_ref_sha1_basic(oldrefname, NULL,0, NULL);2901if(!lock) {2902error("unable to lock%sfor rollback", oldrefname);2903goto rollbacklog;2904}29052906 lock->force_write =1;2907 flag = log_all_ref_updates;2908 log_all_ref_updates =0;2909if(write_ref_sha1(lock, orig_sha1, NULL))2910error("unable to write current sha1 into%s", oldrefname);2911 log_all_ref_updates = flag;29122913 rollbacklog:2914if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2915error("unable to restore logfile%sfrom%s:%s",2916 oldrefname, newrefname,strerror(errno));2917if(!logmoved && log &&2918rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2919error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2920 oldrefname,strerror(errno));29212922return1;2923}29242925intclose_ref(struct ref_lock *lock)2926{2927if(close_lock_file(lock->lk))2928return-1;2929 lock->lock_fd = -1;2930return0;2931}29322933intcommit_ref(struct ref_lock *lock)2934{2935if(commit_lock_file(lock->lk))2936return-1;2937 lock->lock_fd = -1;2938return0;2939}29402941voidunlock_ref(struct ref_lock *lock)2942{2943/* Do not free lock->lk -- atexit() still looks at them */2944if(lock->lk)2945rollback_lock_file(lock->lk);2946free(lock->ref_name);2947free(lock->orig_ref_name);2948free(lock);2949}29502951/*2952 * copy the reflog message msg to buf, which has been allocated sufficiently2953 * large, while cleaning up the whitespaces. Especially, convert LF to space,2954 * because reflog file is one line per entry.2955 */2956static intcopy_msg(char*buf,const char*msg)2957{2958char*cp = buf;2959char c;2960int wasspace =1;29612962*cp++ ='\t';2963while((c = *msg++)) {2964if(wasspace &&isspace(c))2965continue;2966 wasspace =isspace(c);2967if(wasspace)2968 c =' ';2969*cp++ = c;2970}2971while(buf < cp &&isspace(cp[-1]))2972 cp--;2973*cp++ ='\n';2974return cp - buf;2975}29762977/* This function must set a meaningful errno on failure */2978intlog_ref_setup(const char*refname,char*logfile,int bufsize)2979{2980int logfd, oflags = O_APPEND | O_WRONLY;29812982git_snpath(logfile, bufsize,"logs/%s", refname);2983if(log_all_ref_updates &&2984(starts_with(refname,"refs/heads/") ||2985starts_with(refname,"refs/remotes/") ||2986starts_with(refname,"refs/notes/") ||2987!strcmp(refname,"HEAD"))) {2988if(safe_create_leading_directories(logfile) <0) {2989int save_errno = errno;2990error("unable to create directory for%s", logfile);2991 errno = save_errno;2992return-1;2993}2994 oflags |= O_CREAT;2995}29962997 logfd =open(logfile, oflags,0666);2998if(logfd <0) {2999if(!(oflags & O_CREAT) && errno == ENOENT)3000return0;30013002if((oflags & O_CREAT) && errno == EISDIR) {3003if(remove_empty_directories(logfile)) {3004int save_errno = errno;3005error("There are still logs under '%s'",3006 logfile);3007 errno = save_errno;3008return-1;3009}3010 logfd =open(logfile, oflags,0666);3011}30123013if(logfd <0) {3014int save_errno = errno;3015error("Unable to append to%s:%s", logfile,3016strerror(errno));3017 errno = save_errno;3018return-1;3019}3020}30213022adjust_shared_perm(logfile);3023close(logfd);3024return0;3025}30263027static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3028const unsigned char*new_sha1,const char*msg)3029{3030int logfd, result, written, oflags = O_APPEND | O_WRONLY;3031unsigned maxlen, len;3032int msglen;3033char log_file[PATH_MAX];3034char*logrec;3035const char*committer;30363037if(log_all_ref_updates <0)3038 log_all_ref_updates = !is_bare_repository();30393040 result =log_ref_setup(refname, log_file,sizeof(log_file));3041if(result)3042return result;30433044 logfd =open(log_file, oflags);3045if(logfd <0)3046return0;3047 msglen = msg ?strlen(msg) :0;3048 committer =git_committer_info(0);3049 maxlen =strlen(committer) + msglen +100;3050 logrec =xmalloc(maxlen);3051 len =sprintf(logrec,"%s %s %s\n",3052sha1_to_hex(old_sha1),3053sha1_to_hex(new_sha1),3054 committer);3055if(msglen)3056 len +=copy_msg(logrec + len -1, msg) -1;3057 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;3058free(logrec);3059if(written != len) {3060int save_errno = errno;3061close(logfd);3062error("Unable to append to%s", log_file);3063 errno = save_errno;3064return-1;3065}3066if(close(logfd)) {3067int save_errno = errno;3068error("Unable to append to%s", log_file);3069 errno = save_errno;3070return-1;3071}3072return0;3073}30743075intis_branch(const char*refname)3076{3077return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3078}30793080/* This function must return a meaningful errno */3081intwrite_ref_sha1(struct ref_lock *lock,3082const unsigned char*sha1,const char*logmsg)3083{3084static char term ='\n';3085struct object *o;30863087if(!lock) {3088 errno = EINVAL;3089return-1;3090}3091if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {3092unlock_ref(lock);3093return0;3094}3095 o =parse_object(sha1);3096if(!o) {3097error("Trying to write ref%swith nonexistent object%s",3098 lock->ref_name,sha1_to_hex(sha1));3099unlock_ref(lock);3100 errno = EINVAL;3101return-1;3102}3103if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3104error("Trying to write non-commit object%sto branch%s",3105sha1_to_hex(sha1), lock->ref_name);3106unlock_ref(lock);3107 errno = EINVAL;3108return-1;3109}3110if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3111write_in_full(lock->lock_fd, &term,1) !=1||3112close_ref(lock) <0) {3113int save_errno = errno;3114error("Couldn't write%s", lock->lk->filename);3115unlock_ref(lock);3116 errno = save_errno;3117return-1;3118}3119clear_loose_ref_cache(&ref_cache);3120if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3121(strcmp(lock->ref_name, lock->orig_ref_name) &&3122log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3123unlock_ref(lock);3124return-1;3125}3126if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3127/*3128 * Special hack: If a branch is updated directly and HEAD3129 * points to it (may happen on the remote side of a push3130 * for example) then logically the HEAD reflog should be3131 * updated too.3132 * A generic solution implies reverse symref information,3133 * but finding all symrefs pointing to the given branch3134 * would be rather costly for this rare event (the direct3135 * update of a branch) to be worth it. So let's cheat and3136 * check with HEAD only which should cover 99% of all usage3137 * scenarios (even 100% of the default ones).3138 */3139unsigned char head_sha1[20];3140int head_flag;3141const char*head_ref;3142 head_ref =resolve_ref_unsafe("HEAD", head_sha1,1, &head_flag);3143if(head_ref && (head_flag & REF_ISSYMREF) &&3144!strcmp(head_ref, lock->ref_name))3145log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3146}3147if(commit_ref(lock)) {3148error("Couldn't set%s", lock->ref_name);3149unlock_ref(lock);3150return-1;3151}3152unlock_ref(lock);3153return0;3154}31553156intcreate_symref(const char*ref_target,const char*refs_heads_master,3157const char*logmsg)3158{3159const char*lockpath;3160char ref[1000];3161int fd, len, written;3162char*git_HEAD =git_pathdup("%s", ref_target);3163unsigned char old_sha1[20], new_sha1[20];31643165if(logmsg &&read_ref(ref_target, old_sha1))3166hashclr(old_sha1);31673168if(safe_create_leading_directories(git_HEAD) <0)3169returnerror("unable to create directory for%s", git_HEAD);31703171#ifndef NO_SYMLINK_HEAD3172if(prefer_symlink_refs) {3173unlink(git_HEAD);3174if(!symlink(refs_heads_master, git_HEAD))3175goto done;3176fprintf(stderr,"no symlink - falling back to symbolic ref\n");3177}3178#endif31793180 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3181if(sizeof(ref) <= len) {3182error("refname too long:%s", refs_heads_master);3183goto error_free_return;3184}3185 lockpath =mkpath("%s.lock", git_HEAD);3186 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3187if(fd <0) {3188error("Unable to open%sfor writing", lockpath);3189goto error_free_return;3190}3191 written =write_in_full(fd, ref, len);3192if(close(fd) !=0|| written != len) {3193error("Unable to write to%s", lockpath);3194goto error_unlink_return;3195}3196if(rename(lockpath, git_HEAD) <0) {3197error("Unable to create%s", git_HEAD);3198goto error_unlink_return;3199}3200if(adjust_shared_perm(git_HEAD)) {3201error("Unable to fix permissions on%s", lockpath);3202 error_unlink_return:3203unlink_or_warn(lockpath);3204 error_free_return:3205free(git_HEAD);3206return-1;3207}32083209#ifndef NO_SYMLINK_HEAD3210 done:3211#endif3212if(logmsg && !read_ref(refs_heads_master, new_sha1))3213log_ref_write(ref_target, old_sha1, new_sha1, logmsg);32143215free(git_HEAD);3216return0;3217}32183219struct read_ref_at_cb {3220const char*refname;3221unsigned long at_time;3222int cnt;3223int reccnt;3224unsigned char*sha1;3225int found_it;32263227unsigned char osha1[20];3228unsigned char nsha1[20];3229int tz;3230unsigned long date;3231char**msg;3232unsigned long*cutoff_time;3233int*cutoff_tz;3234int*cutoff_cnt;3235};32363237static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3238const char*email,unsigned long timestamp,int tz,3239const char*message,void*cb_data)3240{3241struct read_ref_at_cb *cb = cb_data;32423243 cb->reccnt++;3244 cb->tz = tz;3245 cb->date = timestamp;32463247if(timestamp <= cb->at_time || cb->cnt ==0) {3248if(cb->msg)3249*cb->msg =xstrdup(message);3250if(cb->cutoff_time)3251*cb->cutoff_time = timestamp;3252if(cb->cutoff_tz)3253*cb->cutoff_tz = tz;3254if(cb->cutoff_cnt)3255*cb->cutoff_cnt = cb->reccnt -1;3256/*3257 * we have not yet updated cb->[n|o]sha1 so they still3258 * hold the values for the previous record.3259 */3260if(!is_null_sha1(cb->osha1)) {3261hashcpy(cb->sha1, nsha1);3262if(hashcmp(cb->osha1, nsha1))3263warning("Log for ref%shas gap after%s.",3264 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3265}3266else if(cb->date == cb->at_time)3267hashcpy(cb->sha1, nsha1);3268else if(hashcmp(nsha1, cb->sha1))3269warning("Log for ref%sunexpectedly ended on%s.",3270 cb->refname,show_date(cb->date, cb->tz,3271 DATE_RFC2822));3272hashcpy(cb->osha1, osha1);3273hashcpy(cb->nsha1, nsha1);3274 cb->found_it =1;3275return1;3276}3277hashcpy(cb->osha1, osha1);3278hashcpy(cb->nsha1, nsha1);3279if(cb->cnt >0)3280 cb->cnt--;3281return0;3282}32833284static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3285const char*email,unsigned long timestamp,3286int tz,const char*message,void*cb_data)3287{3288struct read_ref_at_cb *cb = cb_data;32893290if(cb->msg)3291*cb->msg =xstrdup(message);3292if(cb->cutoff_time)3293*cb->cutoff_time = timestamp;3294if(cb->cutoff_tz)3295*cb->cutoff_tz = tz;3296if(cb->cutoff_cnt)3297*cb->cutoff_cnt = cb->reccnt;3298hashcpy(cb->sha1, osha1);3299if(is_null_sha1(cb->sha1))3300hashcpy(cb->sha1, nsha1);3301/* We just want the first entry */3302return1;3303}33043305intread_ref_at(const char*refname,unsigned long at_time,int cnt,3306unsigned char*sha1,char**msg,3307unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3308{3309struct read_ref_at_cb cb;33103311memset(&cb,0,sizeof(cb));3312 cb.refname = refname;3313 cb.at_time = at_time;3314 cb.cnt = cnt;3315 cb.msg = msg;3316 cb.cutoff_time = cutoff_time;3317 cb.cutoff_tz = cutoff_tz;3318 cb.cutoff_cnt = cutoff_cnt;3319 cb.sha1 = sha1;33203321for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);33223323if(!cb.reccnt)3324die("Log for%sis empty.", refname);3325if(cb.found_it)3326return0;33273328for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);33293330return1;3331}33323333intreflog_exists(const char*refname)3334{3335struct stat st;33363337return!lstat(git_path("logs/%s", refname), &st) &&3338S_ISREG(st.st_mode);3339}33403341intdelete_reflog(const char*refname)3342{3343returnremove_path(git_path("logs/%s", refname));3344}33453346static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3347{3348unsigned char osha1[20], nsha1[20];3349char*email_end, *message;3350unsigned long timestamp;3351int tz;33523353/* old SP new SP name <email> SP time TAB msg LF */3354if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3355get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3356get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3357!(email_end =strchr(sb->buf +82,'>')) ||3358 email_end[1] !=' '||3359!(timestamp =strtoul(email_end +2, &message,10)) ||3360!message || message[0] !=' '||3361(message[1] !='+'&& message[1] !='-') ||3362!isdigit(message[2]) || !isdigit(message[3]) ||3363!isdigit(message[4]) || !isdigit(message[5]))3364return0;/* corrupt? */3365 email_end[1] ='\0';3366 tz =strtol(message +1, NULL,10);3367if(message[6] !='\t')3368 message +=6;3369else3370 message +=7;3371returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3372}33733374static char*find_beginning_of_line(char*bob,char*scan)3375{3376while(bob < scan && *(--scan) !='\n')3377;/* keep scanning backwards */3378/*3379 * Return either beginning of the buffer, or LF at the end of3380 * the previous line.3381 */3382return scan;3383}33843385intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3386{3387struct strbuf sb = STRBUF_INIT;3388FILE*logfp;3389long pos;3390int ret =0, at_tail =1;33913392 logfp =fopen(git_path("logs/%s", refname),"r");3393if(!logfp)3394return-1;33953396/* Jump to the end */3397if(fseek(logfp,0, SEEK_END) <0)3398returnerror("cannot seek back reflog for%s:%s",3399 refname,strerror(errno));3400 pos =ftell(logfp);3401while(!ret &&0< pos) {3402int cnt;3403size_t nread;3404char buf[BUFSIZ];3405char*endp, *scanp;34063407/* Fill next block from the end */3408 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3409if(fseek(logfp, pos - cnt, SEEK_SET))3410returnerror("cannot seek back reflog for%s:%s",3411 refname,strerror(errno));3412 nread =fread(buf, cnt,1, logfp);3413if(nread !=1)3414returnerror("cannot read%dbytes from reflog for%s:%s",3415 cnt, refname,strerror(errno));3416 pos -= cnt;34173418 scanp = endp = buf + cnt;3419if(at_tail && scanp[-1] =='\n')3420/* Looking at the final LF at the end of the file */3421 scanp--;3422 at_tail =0;34233424while(buf < scanp) {3425/*3426 * terminating LF of the previous line, or the beginning3427 * of the buffer.3428 */3429char*bp;34303431 bp =find_beginning_of_line(buf, scanp);34323433if(*bp !='\n') {3434strbuf_splice(&sb,0,0, buf, endp - buf);3435if(pos)3436break;/* need to fill another block */3437 scanp = buf -1;/* leave loop */3438}else{3439/*3440 * (bp + 1) thru endp is the beginning of the3441 * current line we have in sb3442 */3443strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3444 scanp = bp;3445 endp = bp +1;3446}3447 ret =show_one_reflog_ent(&sb, fn, cb_data);3448strbuf_reset(&sb);3449if(ret)3450break;3451}34523453}3454if(!ret && sb.len)3455 ret =show_one_reflog_ent(&sb, fn, cb_data);34563457fclose(logfp);3458strbuf_release(&sb);3459return ret;3460}34613462intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3463{3464FILE*logfp;3465struct strbuf sb = STRBUF_INIT;3466int ret =0;34673468 logfp =fopen(git_path("logs/%s", refname),"r");3469if(!logfp)3470return-1;34713472while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3473 ret =show_one_reflog_ent(&sb, fn, cb_data);3474fclose(logfp);3475strbuf_release(&sb);3476return ret;3477}3478/*3479 * Call fn for each reflog in the namespace indicated by name. name3480 * must be empty or end with '/'. Name will be used as a scratch3481 * space, but its contents will be restored before return.3482 */3483static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3484{3485DIR*d =opendir(git_path("logs/%s", name->buf));3486int retval =0;3487struct dirent *de;3488int oldlen = name->len;34893490if(!d)3491return name->len ? errno :0;34923493while((de =readdir(d)) != NULL) {3494struct stat st;34953496if(de->d_name[0] =='.')3497continue;3498if(ends_with(de->d_name,".lock"))3499continue;3500strbuf_addstr(name, de->d_name);3501if(stat(git_path("logs/%s", name->buf), &st) <0) {3502;/* silently ignore */3503}else{3504if(S_ISDIR(st.st_mode)) {3505strbuf_addch(name,'/');3506 retval =do_for_each_reflog(name, fn, cb_data);3507}else{3508unsigned char sha1[20];3509if(read_ref_full(name->buf, sha1,0, NULL))3510 retval =error("bad ref for%s", name->buf);3511else3512 retval =fn(name->buf, sha1,0, cb_data);3513}3514if(retval)3515break;3516}3517strbuf_setlen(name, oldlen);3518}3519closedir(d);3520return retval;3521}35223523intfor_each_reflog(each_ref_fn fn,void*cb_data)3524{3525int retval;3526struct strbuf name;3527strbuf_init(&name, PATH_MAX);3528 retval =do_for_each_reflog(&name, fn, cb_data);3529strbuf_release(&name);3530return retval;3531}35323533static struct ref_lock *update_ref_lock(const char*refname,3534const unsigned char*oldval,3535int flags,int*type_p,3536enum action_on_err onerr)3537{3538struct ref_lock *lock;3539 lock =lock_any_ref_for_update(refname, oldval, flags, type_p);3540if(!lock) {3541const char*str ="Cannot lock the ref '%s'.";3542switch(onerr) {3543case UPDATE_REFS_MSG_ON_ERR:error(str, refname);break;3544case UPDATE_REFS_DIE_ON_ERR:die(str, refname);break;3545case UPDATE_REFS_QUIET_ON_ERR:break;3546}3547}3548return lock;3549}35503551static intupdate_ref_write(const char*action,const char*refname,3552const unsigned char*sha1,struct ref_lock *lock,3553struct strbuf *err,enum action_on_err onerr)3554{3555if(write_ref_sha1(lock, sha1, action) <0) {3556const char*str ="Cannot update the ref '%s'.";3557if(err)3558strbuf_addf(err, str, refname);35593560switch(onerr) {3561case UPDATE_REFS_MSG_ON_ERR:error(str, refname);break;3562case UPDATE_REFS_DIE_ON_ERR:die(str, refname);break;3563case UPDATE_REFS_QUIET_ON_ERR:break;3564}3565return1;3566}3567return0;3568}35693570/**3571 * Information needed for a single ref update. Set new_sha1 to the3572 * new value or to zero to delete the ref. To check the old value3573 * while locking the ref, set have_old to 1 and set old_sha1 to the3574 * value or to zero to ensure the ref does not exist before update.3575 */3576struct ref_update {3577unsigned char new_sha1[20];3578unsigned char old_sha1[20];3579int flags;/* REF_NODEREF? */3580int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3581struct ref_lock *lock;3582int type;3583const char refname[FLEX_ARRAY];3584};35853586/*3587 * Data structure for holding a reference transaction, which can3588 * consist of checks and updates to multiple references, carried out3589 * as atomically as possible. This structure is opaque to callers.3590 */3591struct ref_transaction {3592struct ref_update **updates;3593size_t alloc;3594size_t nr;3595};35963597struct ref_transaction *ref_transaction_begin(void)3598{3599returnxcalloc(1,sizeof(struct ref_transaction));3600}36013602voidref_transaction_free(struct ref_transaction *transaction)3603{3604int i;36053606if(!transaction)3607return;36083609for(i =0; i < transaction->nr; i++)3610free(transaction->updates[i]);36113612free(transaction->updates);3613free(transaction);3614}36153616static struct ref_update *add_update(struct ref_transaction *transaction,3617const char*refname)3618{3619size_t len =strlen(refname);3620struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);36213622strcpy((char*)update->refname, refname);3623ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3624 transaction->updates[transaction->nr++] = update;3625return update;3626}36273628intref_transaction_update(struct ref_transaction *transaction,3629const char*refname,3630const unsigned char*new_sha1,3631const unsigned char*old_sha1,3632int flags,int have_old,3633struct strbuf *err)3634{3635struct ref_update *update;36363637if(have_old && !old_sha1)3638die("BUG: have_old is true but old_sha1 is NULL");36393640 update =add_update(transaction, refname);3641hashcpy(update->new_sha1, new_sha1);3642 update->flags = flags;3643 update->have_old = have_old;3644if(have_old)3645hashcpy(update->old_sha1, old_sha1);3646return0;3647}36483649voidref_transaction_create(struct ref_transaction *transaction,3650const char*refname,3651const unsigned char*new_sha1,3652int flags)3653{3654struct ref_update *update =add_update(transaction, refname);36553656assert(!is_null_sha1(new_sha1));3657hashcpy(update->new_sha1, new_sha1);3658hashclr(update->old_sha1);3659 update->flags = flags;3660 update->have_old =1;3661}36623663voidref_transaction_delete(struct ref_transaction *transaction,3664const char*refname,3665const unsigned char*old_sha1,3666int flags,int have_old)3667{3668struct ref_update *update =add_update(transaction, refname);36693670 update->flags = flags;3671 update->have_old = have_old;3672if(have_old) {3673assert(!is_null_sha1(old_sha1));3674hashcpy(update->old_sha1, old_sha1);3675}3676}36773678intupdate_ref(const char*action,const char*refname,3679const unsigned char*sha1,const unsigned char*oldval,3680int flags,enum action_on_err onerr)3681{3682struct ref_lock *lock;3683 lock =update_ref_lock(refname, oldval, flags, NULL, onerr);3684if(!lock)3685return1;3686returnupdate_ref_write(action, refname, sha1, lock, NULL, onerr);3687}36883689static intref_update_compare(const void*r1,const void*r2)3690{3691const struct ref_update *const*u1 = r1;3692const struct ref_update *const*u2 = r2;3693returnstrcmp((*u1)->refname, (*u2)->refname);3694}36953696static intref_update_reject_duplicates(struct ref_update **updates,int n,3697struct strbuf *err)3698{3699int i;3700for(i =1; i < n; i++)3701if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3702const char*str =3703"Multiple updates for ref '%s' not allowed.";3704if(err)3705strbuf_addf(err, str, updates[i]->refname);37063707return1;3708}3709return0;3710}37113712intref_transaction_commit(struct ref_transaction *transaction,3713const char*msg,struct strbuf *err)3714{3715int ret =0, delnum =0, i;3716const char**delnames;3717int n = transaction->nr;3718struct ref_update **updates = transaction->updates;37193720if(!n)3721return0;37223723/* Allocate work space */3724 delnames =xmalloc(sizeof(*delnames) * n);37253726/* Copy, sort, and reject duplicate refs */3727qsort(updates, n,sizeof(*updates), ref_update_compare);3728 ret =ref_update_reject_duplicates(updates, n, err);3729if(ret)3730goto cleanup;37313732/* Acquire all locks while verifying old values */3733for(i =0; i < n; i++) {3734struct ref_update *update = updates[i];37353736 update->lock =update_ref_lock(update->refname,3737(update->have_old ?3738 update->old_sha1 : NULL),3739 update->flags,3740&update->type,3741 UPDATE_REFS_QUIET_ON_ERR);3742if(!update->lock) {3743if(err)3744strbuf_addf(err,"Cannot lock the ref '%s'.",3745 update->refname);3746 ret =1;3747goto cleanup;3748}3749}37503751/* Perform updates first so live commits remain referenced */3752for(i =0; i < n; i++) {3753struct ref_update *update = updates[i];37543755if(!is_null_sha1(update->new_sha1)) {3756 ret =update_ref_write(msg,3757 update->refname,3758 update->new_sha1,3759 update->lock, err,3760 UPDATE_REFS_QUIET_ON_ERR);3761 update->lock = NULL;/* freed by update_ref_write */3762if(ret)3763goto cleanup;3764}3765}37663767/* Perform deletes now that updates are safely completed */3768for(i =0; i < n; i++) {3769struct ref_update *update = updates[i];37703771if(update->lock) {3772 delnames[delnum++] = update->lock->ref_name;3773 ret |=delete_ref_loose(update->lock, update->type);3774}3775}37763777 ret |=repack_without_refs(delnames, delnum, err);3778for(i =0; i < delnum; i++)3779unlink_or_warn(git_path("logs/%s", delnames[i]));3780clear_loose_ref_cache(&ref_cache);37813782cleanup:3783for(i =0; i < n; i++)3784if(updates[i]->lock)3785unlock_ref(updates[i]->lock);3786free(delnames);3787return ret;3788}37893790char*shorten_unambiguous_ref(const char*refname,int strict)3791{3792int i;3793static char**scanf_fmts;3794static int nr_rules;3795char*short_name;37963797if(!nr_rules) {3798/*3799 * Pre-generate scanf formats from ref_rev_parse_rules[].3800 * Generate a format suitable for scanf from a3801 * ref_rev_parse_rules rule by interpolating "%s" at the3802 * location of the "%.*s".3803 */3804size_t total_len =0;3805size_t offset =0;38063807/* the rule list is NULL terminated, count them first */3808for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3809/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3810 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;38113812 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);38133814 offset =0;3815for(i =0; i < nr_rules; i++) {3816assert(offset < total_len);3817 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3818 offset +=snprintf(scanf_fmts[i], total_len - offset,3819 ref_rev_parse_rules[i],2,"%s") +1;3820}3821}38223823/* bail out if there are no rules */3824if(!nr_rules)3825returnxstrdup(refname);38263827/* buffer for scanf result, at most refname must fit */3828 short_name =xstrdup(refname);38293830/* skip first rule, it will always match */3831for(i = nr_rules -1; i >0; --i) {3832int j;3833int rules_to_fail = i;3834int short_name_len;38353836if(1!=sscanf(refname, scanf_fmts[i], short_name))3837continue;38383839 short_name_len =strlen(short_name);38403841/*3842 * in strict mode, all (except the matched one) rules3843 * must fail to resolve to a valid non-ambiguous ref3844 */3845if(strict)3846 rules_to_fail = nr_rules;38473848/*3849 * check if the short name resolves to a valid ref,3850 * but use only rules prior to the matched one3851 */3852for(j =0; j < rules_to_fail; j++) {3853const char*rule = ref_rev_parse_rules[j];3854char refname[PATH_MAX];38553856/* skip matched rule */3857if(i == j)3858continue;38593860/*3861 * the short name is ambiguous, if it resolves3862 * (with this previous rule) to a valid ref3863 * read_ref() returns 0 on success3864 */3865mksnpath(refname,sizeof(refname),3866 rule, short_name_len, short_name);3867if(ref_exists(refname))3868break;3869}38703871/*3872 * short name is non-ambiguous if all previous rules3873 * haven't resolved to a valid ref3874 */3875if(j == rules_to_fail)3876return short_name;3877}38783879free(short_name);3880returnxstrdup(refname);3881}38823883static struct string_list *hide_refs;38843885intparse_hide_refs_config(const char*var,const char*value,const char*section)3886{3887if(!strcmp("transfer.hiderefs", var) ||3888/* NEEDSWORK: use parse_config_key() once both are merged */3889(starts_with(var, section) && var[strlen(section)] =='.'&&3890!strcmp(var +strlen(section),".hiderefs"))) {3891char*ref;3892int len;38933894if(!value)3895returnconfig_error_nonbool(var);3896 ref =xstrdup(value);3897 len =strlen(ref);3898while(len && ref[len -1] =='/')3899 ref[--len] ='\0';3900if(!hide_refs) {3901 hide_refs =xcalloc(1,sizeof(*hide_refs));3902 hide_refs->strdup_strings =1;3903}3904string_list_append(hide_refs, ref);3905}3906return0;3907}39083909intref_is_hidden(const char*refname)3910{3911struct string_list_item *item;39123913if(!hide_refs)3914return0;3915for_each_string_list_item(item, hide_refs) {3916int len;3917if(!starts_with(refname, item->string))3918continue;3919 len =strlen(item->string);3920if(!refname[len] || refname[len] =='/')3921return1;3922}3923return0;3924}