1#include"cache.h" 2#include"lockfile.h" 3#include"refs.h" 4#include"object.h" 5#include"tag.h" 6#include"dir.h" 7#include"string-list.h" 8 9/* 10 * How to handle various characters in refnames: 11 * 0: An acceptable character for refs 12 * 1: End-of-component 13 * 2: ., look for a preceding . to reject .. in refs 14 * 3: {, look for a preceding @ to reject @{ in refs 15 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 16 */ 17static unsigned char refname_disposition[256] = { 181,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 194,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 204,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 210,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 220,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 230,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 240,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 250,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 26}; 27 28/* 29 * Used as a flag to ref_transaction_delete when a loose ref is being 30 * pruned. 31 */ 32#define REF_ISPRUNING 0x0100 33/* 34 * Try to read one refname component from the front of refname. 35 * Return the length of the component found, or -1 if the component is 36 * not legal. It is legal if it is something reasonable to have under 37 * ".git/refs/"; We do not like it if: 38 * 39 * - any path component of it begins with ".", or 40 * - it has double dots "..", or 41 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 42 * - it ends with a "/". 43 * - it ends with ".lock" 44 * - it contains a "\" (backslash) 45 */ 46static intcheck_refname_component(const char*refname,int flags) 47{ 48const char*cp; 49char last ='\0'; 50 51for(cp = refname; ; cp++) { 52int ch = *cp &255; 53unsigned char disp = refname_disposition[ch]; 54switch(disp) { 55case1: 56goto out; 57case2: 58if(last =='.') 59return-1;/* Refname contains "..". */ 60break; 61case3: 62if(last =='@') 63return-1;/* Refname contains "@{". */ 64break; 65case4: 66return-1; 67} 68 last = ch; 69} 70out: 71if(cp == refname) 72return0;/* Component has zero length. */ 73if(refname[0] =='.') 74return-1;/* Component starts with '.'. */ 75if(cp - refname >= LOCK_SUFFIX_LEN && 76!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 77return-1;/* Refname ends with ".lock". */ 78return cp - refname; 79} 80 81intcheck_refname_format(const char*refname,int flags) 82{ 83int component_len, component_count =0; 84 85if(!strcmp(refname,"@")) 86/* Refname is a single character '@'. */ 87return-1; 88 89while(1) { 90/* We are at the start of a path component. */ 91 component_len =check_refname_component(refname, flags); 92if(component_len <=0) { 93if((flags & REFNAME_REFSPEC_PATTERN) && 94 refname[0] =='*'&& 95(refname[1] =='\0'|| refname[1] =='/')) { 96/* Accept one wildcard as a full refname component. */ 97 flags &= ~REFNAME_REFSPEC_PATTERN; 98 component_len =1; 99}else{ 100return-1; 101} 102} 103 component_count++; 104if(refname[component_len] =='\0') 105break; 106/* Skip to next component. */ 107 refname += component_len +1; 108} 109 110if(refname[component_len -1] =='.') 111return-1;/* Refname ends with '.'. */ 112if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 113return-1;/* Refname has only one component. */ 114return0; 115} 116 117struct ref_entry; 118 119/* 120 * Information used (along with the information in ref_entry) to 121 * describe a single cached reference. This data structure only 122 * occurs embedded in a union in struct ref_entry, and only when 123 * (ref_entry->flag & REF_DIR) is zero. 124 */ 125struct ref_value { 126/* 127 * The name of the object to which this reference resolves 128 * (which may be a tag object). If REF_ISBROKEN, this is 129 * null. If REF_ISSYMREF, then this is the name of the object 130 * referred to by the last reference in the symlink chain. 131 */ 132unsigned char sha1[20]; 133 134/* 135 * If REF_KNOWS_PEELED, then this field holds the peeled value 136 * of this reference, or null if the reference is known not to 137 * be peelable. See the documentation for peel_ref() for an 138 * exact definition of "peelable". 139 */ 140unsigned char peeled[20]; 141}; 142 143struct ref_cache; 144 145/* 146 * Information used (along with the information in ref_entry) to 147 * describe a level in the hierarchy of references. This data 148 * structure only occurs embedded in a union in struct ref_entry, and 149 * only when (ref_entry.flag & REF_DIR) is set. In that case, 150 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 151 * in the directory have already been read: 152 * 153 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 154 * or packed references, already read. 155 * 156 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 157 * references that hasn't been read yet (nor has any of its 158 * subdirectories). 159 * 160 * Entries within a directory are stored within a growable array of 161 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 162 * sorted are sorted by their component name in strcmp() order and the 163 * remaining entries are unsorted. 164 * 165 * Loose references are read lazily, one directory at a time. When a 166 * directory of loose references is read, then all of the references 167 * in that directory are stored, and REF_INCOMPLETE stubs are created 168 * for any subdirectories, but the subdirectories themselves are not 169 * read. The reading is triggered by get_ref_dir(). 170 */ 171struct ref_dir { 172int nr, alloc; 173 174/* 175 * Entries with index 0 <= i < sorted are sorted by name. New 176 * entries are appended to the list unsorted, and are sorted 177 * only when required; thus we avoid the need to sort the list 178 * after the addition of every reference. 179 */ 180int sorted; 181 182/* A pointer to the ref_cache that contains this ref_dir. */ 183struct ref_cache *ref_cache; 184 185struct ref_entry **entries; 186}; 187 188/* 189 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 190 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 191 * public values; see refs.h. 192 */ 193 194/* 195 * The field ref_entry->u.value.peeled of this value entry contains 196 * the correct peeled value for the reference, which might be 197 * null_sha1 if the reference is not a tag or if it is broken. 198 */ 199#define REF_KNOWS_PEELED 0x10 200 201/* ref_entry represents a directory of references */ 202#define REF_DIR 0x20 203 204/* 205 * Entry has not yet been read from disk (used only for REF_DIR 206 * entries representing loose references) 207 */ 208#define REF_INCOMPLETE 0x40 209 210/* 211 * A ref_entry represents either a reference or a "subdirectory" of 212 * references. 213 * 214 * Each directory in the reference namespace is represented by a 215 * ref_entry with (flags & REF_DIR) set and containing a subdir member 216 * that holds the entries in that directory that have been read so 217 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 218 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 219 * used for loose reference directories. 220 * 221 * References are represented by a ref_entry with (flags & REF_DIR) 222 * unset and a value member that describes the reference's value. The 223 * flag member is at the ref_entry level, but it is also needed to 224 * interpret the contents of the value field (in other words, a 225 * ref_value object is not very much use without the enclosing 226 * ref_entry). 227 * 228 * Reference names cannot end with slash and directories' names are 229 * always stored with a trailing slash (except for the top-level 230 * directory, which is always denoted by ""). This has two nice 231 * consequences: (1) when the entries in each subdir are sorted 232 * lexicographically by name (as they usually are), the references in 233 * a whole tree can be generated in lexicographic order by traversing 234 * the tree in left-to-right, depth-first order; (2) the names of 235 * references and subdirectories cannot conflict, and therefore the 236 * presence of an empty subdirectory does not block the creation of a 237 * similarly-named reference. (The fact that reference names with the 238 * same leading components can conflict *with each other* is a 239 * separate issue that is regulated by is_refname_available().) 240 * 241 * Please note that the name field contains the fully-qualified 242 * reference (or subdirectory) name. Space could be saved by only 243 * storing the relative names. But that would require the full names 244 * to be generated on the fly when iterating in do_for_each_ref(), and 245 * would break callback functions, who have always been able to assume 246 * that the name strings that they are passed will not be freed during 247 * the iteration. 248 */ 249struct ref_entry { 250unsigned char flag;/* ISSYMREF? ISPACKED? */ 251union{ 252struct ref_value value;/* if not (flags&REF_DIR) */ 253struct ref_dir subdir;/* if (flags&REF_DIR) */ 254} u; 255/* 256 * The full name of the reference (e.g., "refs/heads/master") 257 * or the full name of the directory with a trailing slash 258 * (e.g., "refs/heads/"): 259 */ 260char name[FLEX_ARRAY]; 261}; 262 263static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 264 265static struct ref_dir *get_ref_dir(struct ref_entry *entry) 266{ 267struct ref_dir *dir; 268assert(entry->flag & REF_DIR); 269 dir = &entry->u.subdir; 270if(entry->flag & REF_INCOMPLETE) { 271read_loose_refs(entry->name, dir); 272 entry->flag &= ~REF_INCOMPLETE; 273} 274return dir; 275} 276 277/* 278 * Check if a refname is safe. 279 * For refs that start with "refs/" we consider it safe as long they do 280 * not try to resolve to outside of refs/. 281 * 282 * For all other refs we only consider them safe iff they only contain 283 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 284 * "config"). 285 */ 286static intrefname_is_safe(const char*refname) 287{ 288if(starts_with(refname,"refs/")) { 289char*buf; 290int result; 291 292 buf =xmalloc(strlen(refname) +1); 293/* 294 * Does the refname try to escape refs/? 295 * For example: refs/foo/../bar is safe but refs/foo/../../bar 296 * is not. 297 */ 298 result = !normalize_path_copy(buf, refname +strlen("refs/")); 299free(buf); 300return result; 301} 302while(*refname) { 303if(!isupper(*refname) && *refname !='_') 304return0; 305 refname++; 306} 307return1; 308} 309 310static struct ref_entry *create_ref_entry(const char*refname, 311const unsigned char*sha1,int flag, 312int check_name) 313{ 314int len; 315struct ref_entry *ref; 316 317if(check_name && 318check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 319die("Reference has invalid format: '%s'", refname); 320if(!check_name && !refname_is_safe(refname)) 321die("Reference has invalid name: '%s'", refname); 322 len =strlen(refname) +1; 323 ref =xmalloc(sizeof(struct ref_entry) + len); 324hashcpy(ref->u.value.sha1, sha1); 325hashclr(ref->u.value.peeled); 326memcpy(ref->name, refname, len); 327 ref->flag = flag; 328return ref; 329} 330 331static voidclear_ref_dir(struct ref_dir *dir); 332 333static voidfree_ref_entry(struct ref_entry *entry) 334{ 335if(entry->flag & REF_DIR) { 336/* 337 * Do not use get_ref_dir() here, as that might 338 * trigger the reading of loose refs. 339 */ 340clear_ref_dir(&entry->u.subdir); 341} 342free(entry); 343} 344 345/* 346 * Add a ref_entry to the end of dir (unsorted). Entry is always 347 * stored directly in dir; no recursion into subdirectories is 348 * done. 349 */ 350static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 351{ 352ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 353 dir->entries[dir->nr++] = entry; 354/* optimize for the case that entries are added in order */ 355if(dir->nr ==1|| 356(dir->nr == dir->sorted +1&& 357strcmp(dir->entries[dir->nr -2]->name, 358 dir->entries[dir->nr -1]->name) <0)) 359 dir->sorted = dir->nr; 360} 361 362/* 363 * Clear and free all entries in dir, recursively. 364 */ 365static voidclear_ref_dir(struct ref_dir *dir) 366{ 367int i; 368for(i =0; i < dir->nr; i++) 369free_ref_entry(dir->entries[i]); 370free(dir->entries); 371 dir->sorted = dir->nr = dir->alloc =0; 372 dir->entries = NULL; 373} 374 375/* 376 * Create a struct ref_entry object for the specified dirname. 377 * dirname is the name of the directory with a trailing slash (e.g., 378 * "refs/heads/") or "" for the top-level directory. 379 */ 380static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 381const char*dirname,size_t len, 382int incomplete) 383{ 384struct ref_entry *direntry; 385 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 386memcpy(direntry->name, dirname, len); 387 direntry->name[len] ='\0'; 388 direntry->u.subdir.ref_cache = ref_cache; 389 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 390return direntry; 391} 392 393static intref_entry_cmp(const void*a,const void*b) 394{ 395struct ref_entry *one = *(struct ref_entry **)a; 396struct ref_entry *two = *(struct ref_entry **)b; 397returnstrcmp(one->name, two->name); 398} 399 400static voidsort_ref_dir(struct ref_dir *dir); 401 402struct string_slice { 403size_t len; 404const char*str; 405}; 406 407static intref_entry_cmp_sslice(const void*key_,const void*ent_) 408{ 409const struct string_slice *key = key_; 410const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 411int cmp =strncmp(key->str, ent->name, key->len); 412if(cmp) 413return cmp; 414return'\0'- (unsigned char)ent->name[key->len]; 415} 416 417/* 418 * Return the index of the entry with the given refname from the 419 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 420 * no such entry is found. dir must already be complete. 421 */ 422static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 423{ 424struct ref_entry **r; 425struct string_slice key; 426 427if(refname == NULL || !dir->nr) 428return-1; 429 430sort_ref_dir(dir); 431 key.len = len; 432 key.str = refname; 433 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 434 ref_entry_cmp_sslice); 435 436if(r == NULL) 437return-1; 438 439return r - dir->entries; 440} 441 442/* 443 * Search for a directory entry directly within dir (without 444 * recursing). Sort dir if necessary. subdirname must be a directory 445 * name (i.e., end in '/'). If mkdir is set, then create the 446 * directory if it is missing; otherwise, return NULL if the desired 447 * directory cannot be found. dir must already be complete. 448 */ 449static struct ref_dir *search_for_subdir(struct ref_dir *dir, 450const char*subdirname,size_t len, 451int mkdir) 452{ 453int entry_index =search_ref_dir(dir, subdirname, len); 454struct ref_entry *entry; 455if(entry_index == -1) { 456if(!mkdir) 457return NULL; 458/* 459 * Since dir is complete, the absence of a subdir 460 * means that the subdir really doesn't exist; 461 * therefore, create an empty record for it but mark 462 * the record complete. 463 */ 464 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 465add_entry_to_dir(dir, entry); 466}else{ 467 entry = dir->entries[entry_index]; 468} 469returnget_ref_dir(entry); 470} 471 472/* 473 * If refname is a reference name, find the ref_dir within the dir 474 * tree that should hold refname. If refname is a directory name 475 * (i.e., ends in '/'), then return that ref_dir itself. dir must 476 * represent the top-level directory and must already be complete. 477 * Sort ref_dirs and recurse into subdirectories as necessary. If 478 * mkdir is set, then create any missing directories; otherwise, 479 * return NULL if the desired directory cannot be found. 480 */ 481static struct ref_dir *find_containing_dir(struct ref_dir *dir, 482const char*refname,int mkdir) 483{ 484const char*slash; 485for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 486size_t dirnamelen = slash - refname +1; 487struct ref_dir *subdir; 488 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 489if(!subdir) { 490 dir = NULL; 491break; 492} 493 dir = subdir; 494} 495 496return dir; 497} 498 499/* 500 * Find the value entry with the given name in dir, sorting ref_dirs 501 * and recursing into subdirectories as necessary. If the name is not 502 * found or it corresponds to a directory entry, return NULL. 503 */ 504static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 505{ 506int entry_index; 507struct ref_entry *entry; 508 dir =find_containing_dir(dir, refname,0); 509if(!dir) 510return NULL; 511 entry_index =search_ref_dir(dir, refname,strlen(refname)); 512if(entry_index == -1) 513return NULL; 514 entry = dir->entries[entry_index]; 515return(entry->flag & REF_DIR) ? NULL : entry; 516} 517 518/* 519 * Remove the entry with the given name from dir, recursing into 520 * subdirectories as necessary. If refname is the name of a directory 521 * (i.e., ends with '/'), then remove the directory and its contents. 522 * If the removal was successful, return the number of entries 523 * remaining in the directory entry that contained the deleted entry. 524 * If the name was not found, return -1. Please note that this 525 * function only deletes the entry from the cache; it does not delete 526 * it from the filesystem or ensure that other cache entries (which 527 * might be symbolic references to the removed entry) are updated. 528 * Nor does it remove any containing dir entries that might be made 529 * empty by the removal. dir must represent the top-level directory 530 * and must already be complete. 531 */ 532static intremove_entry(struct ref_dir *dir,const char*refname) 533{ 534int refname_len =strlen(refname); 535int entry_index; 536struct ref_entry *entry; 537int is_dir = refname[refname_len -1] =='/'; 538if(is_dir) { 539/* 540 * refname represents a reference directory. Remove 541 * the trailing slash; otherwise we will get the 542 * directory *representing* refname rather than the 543 * one *containing* it. 544 */ 545char*dirname =xmemdupz(refname, refname_len -1); 546 dir =find_containing_dir(dir, dirname,0); 547free(dirname); 548}else{ 549 dir =find_containing_dir(dir, refname,0); 550} 551if(!dir) 552return-1; 553 entry_index =search_ref_dir(dir, refname, refname_len); 554if(entry_index == -1) 555return-1; 556 entry = dir->entries[entry_index]; 557 558memmove(&dir->entries[entry_index], 559&dir->entries[entry_index +1], 560(dir->nr - entry_index -1) *sizeof(*dir->entries) 561); 562 dir->nr--; 563if(dir->sorted > entry_index) 564 dir->sorted--; 565free_ref_entry(entry); 566return dir->nr; 567} 568 569/* 570 * Add a ref_entry to the ref_dir (unsorted), recursing into 571 * subdirectories as necessary. dir must represent the top-level 572 * directory. Return 0 on success. 573 */ 574static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 575{ 576 dir =find_containing_dir(dir, ref->name,1); 577if(!dir) 578return-1; 579add_entry_to_dir(dir, ref); 580return0; 581} 582 583/* 584 * Emit a warning and return true iff ref1 and ref2 have the same name 585 * and the same sha1. Die if they have the same name but different 586 * sha1s. 587 */ 588static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 589{ 590if(strcmp(ref1->name, ref2->name)) 591return0; 592 593/* Duplicate name; make sure that they don't conflict: */ 594 595if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 596/* This is impossible by construction */ 597die("Reference directory conflict:%s", ref1->name); 598 599if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 600die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 601 602warning("Duplicated ref:%s", ref1->name); 603return1; 604} 605 606/* 607 * Sort the entries in dir non-recursively (if they are not already 608 * sorted) and remove any duplicate entries. 609 */ 610static voidsort_ref_dir(struct ref_dir *dir) 611{ 612int i, j; 613struct ref_entry *last = NULL; 614 615/* 616 * This check also prevents passing a zero-length array to qsort(), 617 * which is a problem on some platforms. 618 */ 619if(dir->sorted == dir->nr) 620return; 621 622qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 623 624/* Remove any duplicates: */ 625for(i =0, j =0; j < dir->nr; j++) { 626struct ref_entry *entry = dir->entries[j]; 627if(last &&is_dup_ref(last, entry)) 628free_ref_entry(entry); 629else 630 last = dir->entries[i++] = entry; 631} 632 dir->sorted = dir->nr = i; 633} 634 635/* Include broken references in a do_for_each_ref*() iteration: */ 636#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 637 638/* 639 * Return true iff the reference described by entry can be resolved to 640 * an object in the database. Emit a warning if the referred-to 641 * object does not exist. 642 */ 643static intref_resolves_to_object(struct ref_entry *entry) 644{ 645if(entry->flag & REF_ISBROKEN) 646return0; 647if(!has_sha1_file(entry->u.value.sha1)) { 648error("%sdoes not point to a valid object!", entry->name); 649return0; 650} 651return1; 652} 653 654/* 655 * current_ref is a performance hack: when iterating over references 656 * using the for_each_ref*() functions, current_ref is set to the 657 * current reference's entry before calling the callback function. If 658 * the callback function calls peel_ref(), then peel_ref() first 659 * checks whether the reference to be peeled is the current reference 660 * (it usually is) and if so, returns that reference's peeled version 661 * if it is available. This avoids a refname lookup in a common case. 662 */ 663static struct ref_entry *current_ref; 664 665typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 666 667struct ref_entry_cb { 668const char*base; 669int trim; 670int flags; 671 each_ref_fn *fn; 672void*cb_data; 673}; 674 675/* 676 * Handle one reference in a do_for_each_ref*()-style iteration, 677 * calling an each_ref_fn for each entry. 678 */ 679static intdo_one_ref(struct ref_entry *entry,void*cb_data) 680{ 681struct ref_entry_cb *data = cb_data; 682struct ref_entry *old_current_ref; 683int retval; 684 685if(!starts_with(entry->name, data->base)) 686return0; 687 688if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 689!ref_resolves_to_object(entry)) 690return0; 691 692/* Store the old value, in case this is a recursive call: */ 693 old_current_ref = current_ref; 694 current_ref = entry; 695 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 696 entry->flag, data->cb_data); 697 current_ref = old_current_ref; 698return retval; 699} 700 701/* 702 * Call fn for each reference in dir that has index in the range 703 * offset <= index < dir->nr. Recurse into subdirectories that are in 704 * that index range, sorting them before iterating. This function 705 * does not sort dir itself; it should be sorted beforehand. fn is 706 * called for all references, including broken ones. 707 */ 708static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 709 each_ref_entry_fn fn,void*cb_data) 710{ 711int i; 712assert(dir->sorted == dir->nr); 713for(i = offset; i < dir->nr; i++) { 714struct ref_entry *entry = dir->entries[i]; 715int retval; 716if(entry->flag & REF_DIR) { 717struct ref_dir *subdir =get_ref_dir(entry); 718sort_ref_dir(subdir); 719 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 720}else{ 721 retval =fn(entry, cb_data); 722} 723if(retval) 724return retval; 725} 726return0; 727} 728 729/* 730 * Call fn for each reference in the union of dir1 and dir2, in order 731 * by refname. Recurse into subdirectories. If a value entry appears 732 * in both dir1 and dir2, then only process the version that is in 733 * dir2. The input dirs must already be sorted, but subdirs will be 734 * sorted as needed. fn is called for all references, including 735 * broken ones. 736 */ 737static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 738struct ref_dir *dir2, 739 each_ref_entry_fn fn,void*cb_data) 740{ 741int retval; 742int i1 =0, i2 =0; 743 744assert(dir1->sorted == dir1->nr); 745assert(dir2->sorted == dir2->nr); 746while(1) { 747struct ref_entry *e1, *e2; 748int cmp; 749if(i1 == dir1->nr) { 750returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 751} 752if(i2 == dir2->nr) { 753returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 754} 755 e1 = dir1->entries[i1]; 756 e2 = dir2->entries[i2]; 757 cmp =strcmp(e1->name, e2->name); 758if(cmp ==0) { 759if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 760/* Both are directories; descend them in parallel. */ 761struct ref_dir *subdir1 =get_ref_dir(e1); 762struct ref_dir *subdir2 =get_ref_dir(e2); 763sort_ref_dir(subdir1); 764sort_ref_dir(subdir2); 765 retval =do_for_each_entry_in_dirs( 766 subdir1, subdir2, fn, cb_data); 767 i1++; 768 i2++; 769}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 770/* Both are references; ignore the one from dir1. */ 771 retval =fn(e2, cb_data); 772 i1++; 773 i2++; 774}else{ 775die("conflict between reference and directory:%s", 776 e1->name); 777} 778}else{ 779struct ref_entry *e; 780if(cmp <0) { 781 e = e1; 782 i1++; 783}else{ 784 e = e2; 785 i2++; 786} 787if(e->flag & REF_DIR) { 788struct ref_dir *subdir =get_ref_dir(e); 789sort_ref_dir(subdir); 790 retval =do_for_each_entry_in_dir( 791 subdir,0, fn, cb_data); 792}else{ 793 retval =fn(e, cb_data); 794} 795} 796if(retval) 797return retval; 798} 799} 800 801/* 802 * Load all of the refs from the dir into our in-memory cache. The hard work 803 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 804 * through all of the sub-directories. We do not even need to care about 805 * sorting, as traversal order does not matter to us. 806 */ 807static voidprime_ref_dir(struct ref_dir *dir) 808{ 809int i; 810for(i =0; i < dir->nr; i++) { 811struct ref_entry *entry = dir->entries[i]; 812if(entry->flag & REF_DIR) 813prime_ref_dir(get_ref_dir(entry)); 814} 815} 816 817static intentry_matches(struct ref_entry *entry,const struct string_list *list) 818{ 819return list &&string_list_has_string(list, entry->name); 820} 821 822struct nonmatching_ref_data { 823const struct string_list *skip; 824struct ref_entry *found; 825}; 826 827static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 828{ 829struct nonmatching_ref_data *data = vdata; 830 831if(entry_matches(entry, data->skip)) 832return0; 833 834 data->found = entry; 835return1; 836} 837 838static voidreport_refname_conflict(struct ref_entry *entry, 839const char*refname) 840{ 841error("'%s' exists; cannot create '%s'", entry->name, refname); 842} 843 844/* 845 * Return true iff a reference named refname could be created without 846 * conflicting with the name of an existing reference in dir. If 847 * skip is non-NULL, ignore potential conflicts with refs in skip 848 * (e.g., because they are scheduled for deletion in the same 849 * operation). 850 * 851 * Two reference names conflict if one of them exactly matches the 852 * leading components of the other; e.g., "foo/bar" conflicts with 853 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or 854 * "foo/barbados". 855 * 856 * skip must be sorted. 857 */ 858static intis_refname_available(const char*refname, 859const struct string_list *skip, 860struct ref_dir *dir) 861{ 862const char*slash; 863size_t len; 864int pos; 865char*dirname; 866 867for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 868/* 869 * We are still at a leading dir of the refname; we are 870 * looking for a conflict with a leaf entry. 871 * 872 * If we find one, we still must make sure it is 873 * not in "skip". 874 */ 875 pos =search_ref_dir(dir, refname, slash - refname); 876if(pos >=0) { 877struct ref_entry *entry = dir->entries[pos]; 878if(entry_matches(entry, skip)) 879return1; 880report_refname_conflict(entry, refname); 881return0; 882} 883 884 885/* 886 * Otherwise, we can try to continue our search with 887 * the next component; if we come up empty, we know 888 * there is nothing under this whole prefix. 889 */ 890 pos =search_ref_dir(dir, refname, slash +1- refname); 891if(pos <0) 892return1; 893 894 dir =get_ref_dir(dir->entries[pos]); 895} 896 897/* 898 * We are at the leaf of our refname; we want to 899 * make sure there are no directories which match it. 900 */ 901 len =strlen(refname); 902 dirname =xmallocz(len +1); 903sprintf(dirname,"%s/", refname); 904 pos =search_ref_dir(dir, dirname, len +1); 905free(dirname); 906 907if(pos >=0) { 908/* 909 * We found a directory named "refname". It is a 910 * problem iff it contains any ref that is not 911 * in "skip". 912 */ 913struct ref_entry *entry = dir->entries[pos]; 914struct ref_dir *dir =get_ref_dir(entry); 915struct nonmatching_ref_data data; 916 917 data.skip = skip; 918sort_ref_dir(dir); 919if(!do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) 920return1; 921 922report_refname_conflict(data.found, refname); 923return0; 924} 925 926/* 927 * There is no point in searching for another leaf 928 * node which matches it; such an entry would be the 929 * ref we are looking for, not a conflict. 930 */ 931return1; 932} 933 934struct packed_ref_cache { 935struct ref_entry *root; 936 937/* 938 * Count of references to the data structure in this instance, 939 * including the pointer from ref_cache::packed if any. The 940 * data will not be freed as long as the reference count is 941 * nonzero. 942 */ 943unsigned int referrers; 944 945/* 946 * Iff the packed-refs file associated with this instance is 947 * currently locked for writing, this points at the associated 948 * lock (which is owned by somebody else). The referrer count 949 * is also incremented when the file is locked and decremented 950 * when it is unlocked. 951 */ 952struct lock_file *lock; 953 954/* The metadata from when this packed-refs cache was read */ 955struct stat_validity validity; 956}; 957 958/* 959 * Future: need to be in "struct repository" 960 * when doing a full libification. 961 */ 962static struct ref_cache { 963struct ref_cache *next; 964struct ref_entry *loose; 965struct packed_ref_cache *packed; 966/* 967 * The submodule name, or "" for the main repo. We allocate 968 * length 1 rather than FLEX_ARRAY so that the main ref_cache 969 * is initialized correctly. 970 */ 971char name[1]; 972} ref_cache, *submodule_ref_caches; 973 974/* Lock used for the main packed-refs file: */ 975static struct lock_file packlock; 976 977/* 978 * Increment the reference count of *packed_refs. 979 */ 980static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 981{ 982 packed_refs->referrers++; 983} 984 985/* 986 * Decrease the reference count of *packed_refs. If it goes to zero, 987 * free *packed_refs and return true; otherwise return false. 988 */ 989static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 990{ 991if(!--packed_refs->referrers) { 992free_ref_entry(packed_refs->root); 993stat_validity_clear(&packed_refs->validity); 994free(packed_refs); 995return1; 996}else{ 997return0; 998} 999}10001001static voidclear_packed_ref_cache(struct ref_cache *refs)1002{1003if(refs->packed) {1004struct packed_ref_cache *packed_refs = refs->packed;10051006if(packed_refs->lock)1007die("internal error: packed-ref cache cleared while locked");1008 refs->packed = NULL;1009release_packed_ref_cache(packed_refs);1010}1011}10121013static voidclear_loose_ref_cache(struct ref_cache *refs)1014{1015if(refs->loose) {1016free_ref_entry(refs->loose);1017 refs->loose = NULL;1018}1019}10201021static struct ref_cache *create_ref_cache(const char*submodule)1022{1023int len;1024struct ref_cache *refs;1025if(!submodule)1026 submodule ="";1027 len =strlen(submodule) +1;1028 refs =xcalloc(1,sizeof(struct ref_cache) + len);1029memcpy(refs->name, submodule, len);1030return refs;1031}10321033/*1034 * Return a pointer to a ref_cache for the specified submodule. For1035 * the main repository, use submodule==NULL. The returned structure1036 * will be allocated and initialized but not necessarily populated; it1037 * should not be freed.1038 */1039static struct ref_cache *get_ref_cache(const char*submodule)1040{1041struct ref_cache *refs;10421043if(!submodule || !*submodule)1044return&ref_cache;10451046for(refs = submodule_ref_caches; refs; refs = refs->next)1047if(!strcmp(submodule, refs->name))1048return refs;10491050 refs =create_ref_cache(submodule);1051 refs->next = submodule_ref_caches;1052 submodule_ref_caches = refs;1053return refs;1054}10551056/* The length of a peeled reference line in packed-refs, including EOL: */1057#define PEELED_LINE_LENGTH 4210581059/*1060 * The packed-refs header line that we write out. Perhaps other1061 * traits will be added later. The trailing space is required.1062 */1063static const char PACKED_REFS_HEADER[] =1064"# pack-refs with: peeled fully-peeled\n";10651066/*1067 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1068 * Return a pointer to the refname within the line (null-terminated),1069 * or NULL if there was a problem.1070 */1071static const char*parse_ref_line(char*line,unsigned char*sha1)1072{1073/*1074 * 42: the answer to everything.1075 *1076 * In this case, it happens to be the answer to1077 * 40 (length of sha1 hex representation)1078 * +1 (space in between hex and name)1079 * +1 (newline at the end of the line)1080 */1081int len =strlen(line) -42;10821083if(len <=0)1084return NULL;1085if(get_sha1_hex(line, sha1) <0)1086return NULL;1087if(!isspace(line[40]))1088return NULL;1089 line +=41;1090if(isspace(*line))1091return NULL;1092if(line[len] !='\n')1093return NULL;1094 line[len] =0;10951096return line;1097}10981099/*1100 * Read f, which is a packed-refs file, into dir.1101 *1102 * A comment line of the form "# pack-refs with: " may contain zero or1103 * more traits. We interpret the traits as follows:1104 *1105 * No traits:1106 *1107 * Probably no references are peeled. But if the file contains a1108 * peeled value for a reference, we will use it.1109 *1110 * peeled:1111 *1112 * References under "refs/tags/", if they *can* be peeled, *are*1113 * peeled in this file. References outside of "refs/tags/" are1114 * probably not peeled even if they could have been, but if we find1115 * a peeled value for such a reference we will use it.1116 *1117 * fully-peeled:1118 *1119 * All references in the file that can be peeled are peeled.1120 * Inversely (and this is more important), any references in the1121 * file for which no peeled value is recorded is not peelable. This1122 * trait should typically be written alongside "peeled" for1123 * compatibility with older clients, but we do not require it1124 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1125 */1126static voidread_packed_refs(FILE*f,struct ref_dir *dir)1127{1128struct ref_entry *last = NULL;1129char refline[PATH_MAX];1130enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;11311132while(fgets(refline,sizeof(refline), f)) {1133unsigned char sha1[20];1134const char*refname;1135static const char header[] ="# pack-refs with:";11361137if(!strncmp(refline, header,sizeof(header)-1)) {1138const char*traits = refline +sizeof(header) -1;1139if(strstr(traits," fully-peeled "))1140 peeled = PEELED_FULLY;1141else if(strstr(traits," peeled "))1142 peeled = PEELED_TAGS;1143/* perhaps other traits later as well */1144continue;1145}11461147 refname =parse_ref_line(refline, sha1);1148if(refname) {1149int flag = REF_ISPACKED;11501151if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1152hashclr(sha1);1153 flag |= REF_BAD_NAME | REF_ISBROKEN;1154}1155 last =create_ref_entry(refname, sha1, flag,0);1156if(peeled == PEELED_FULLY ||1157(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1158 last->flag |= REF_KNOWS_PEELED;1159add_ref(dir, last);1160continue;1161}1162if(last &&1163 refline[0] =='^'&&1164strlen(refline) == PEELED_LINE_LENGTH &&1165 refline[PEELED_LINE_LENGTH -1] =='\n'&&1166!get_sha1_hex(refline +1, sha1)) {1167hashcpy(last->u.value.peeled, sha1);1168/*1169 * Regardless of what the file header said,1170 * we definitely know the value of *this*1171 * reference:1172 */1173 last->flag |= REF_KNOWS_PEELED;1174}1175}1176}11771178/*1179 * Get the packed_ref_cache for the specified ref_cache, creating it1180 * if necessary.1181 */1182static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1183{1184const char*packed_refs_file;11851186if(*refs->name)1187 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1188else1189 packed_refs_file =git_path("packed-refs");11901191if(refs->packed &&1192!stat_validity_check(&refs->packed->validity, packed_refs_file))1193clear_packed_ref_cache(refs);11941195if(!refs->packed) {1196FILE*f;11971198 refs->packed =xcalloc(1,sizeof(*refs->packed));1199acquire_packed_ref_cache(refs->packed);1200 refs->packed->root =create_dir_entry(refs,"",0,0);1201 f =fopen(packed_refs_file,"r");1202if(f) {1203stat_validity_update(&refs->packed->validity,fileno(f));1204read_packed_refs(f,get_ref_dir(refs->packed->root));1205fclose(f);1206}1207}1208return refs->packed;1209}12101211static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1212{1213returnget_ref_dir(packed_ref_cache->root);1214}12151216static struct ref_dir *get_packed_refs(struct ref_cache *refs)1217{1218returnget_packed_ref_dir(get_packed_ref_cache(refs));1219}12201221voidadd_packed_ref(const char*refname,const unsigned char*sha1)1222{1223struct packed_ref_cache *packed_ref_cache =1224get_packed_ref_cache(&ref_cache);12251226if(!packed_ref_cache->lock)1227die("internal error: packed refs not locked");1228add_ref(get_packed_ref_dir(packed_ref_cache),1229create_ref_entry(refname, sha1, REF_ISPACKED,1));1230}12311232/*1233 * Read the loose references from the namespace dirname into dir1234 * (without recursing). dirname must end with '/'. dir must be the1235 * directory entry corresponding to dirname.1236 */1237static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1238{1239struct ref_cache *refs = dir->ref_cache;1240DIR*d;1241const char*path;1242struct dirent *de;1243int dirnamelen =strlen(dirname);1244struct strbuf refname;12451246if(*refs->name)1247 path =git_path_submodule(refs->name,"%s", dirname);1248else1249 path =git_path("%s", dirname);12501251 d =opendir(path);1252if(!d)1253return;12541255strbuf_init(&refname, dirnamelen +257);1256strbuf_add(&refname, dirname, dirnamelen);12571258while((de =readdir(d)) != NULL) {1259unsigned char sha1[20];1260struct stat st;1261int flag;1262const char*refdir;12631264if(de->d_name[0] =='.')1265continue;1266if(ends_with(de->d_name,".lock"))1267continue;1268strbuf_addstr(&refname, de->d_name);1269 refdir = *refs->name1270?git_path_submodule(refs->name,"%s", refname.buf)1271:git_path("%s", refname.buf);1272if(stat(refdir, &st) <0) {1273;/* silently ignore */1274}else if(S_ISDIR(st.st_mode)) {1275strbuf_addch(&refname,'/');1276add_entry_to_dir(dir,1277create_dir_entry(refs, refname.buf,1278 refname.len,1));1279}else{1280if(*refs->name) {1281hashclr(sha1);1282 flag =0;1283if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1284hashclr(sha1);1285 flag |= REF_ISBROKEN;1286}1287}else if(read_ref_full(refname.buf,1288 RESOLVE_REF_READING,1289 sha1, &flag)) {1290hashclr(sha1);1291 flag |= REF_ISBROKEN;1292}1293if(check_refname_format(refname.buf,1294 REFNAME_ALLOW_ONELEVEL)) {1295hashclr(sha1);1296 flag |= REF_BAD_NAME | REF_ISBROKEN;1297}1298add_entry_to_dir(dir,1299create_ref_entry(refname.buf, sha1, flag,0));1300}1301strbuf_setlen(&refname, dirnamelen);1302}1303strbuf_release(&refname);1304closedir(d);1305}13061307static struct ref_dir *get_loose_refs(struct ref_cache *refs)1308{1309if(!refs->loose) {1310/*1311 * Mark the top-level directory complete because we1312 * are about to read the only subdirectory that can1313 * hold references:1314 */1315 refs->loose =create_dir_entry(refs,"",0,0);1316/*1317 * Create an incomplete entry for "refs/":1318 */1319add_entry_to_dir(get_ref_dir(refs->loose),1320create_dir_entry(refs,"refs/",5,1));1321}1322returnget_ref_dir(refs->loose);1323}13241325/* We allow "recursive" symbolic refs. Only within reason, though */1326#define MAXDEPTH 51327#define MAXREFLEN (1024)13281329/*1330 * Called by resolve_gitlink_ref_recursive() after it failed to read1331 * from the loose refs in ref_cache refs. Find <refname> in the1332 * packed-refs file for the submodule.1333 */1334static intresolve_gitlink_packed_ref(struct ref_cache *refs,1335const char*refname,unsigned char*sha1)1336{1337struct ref_entry *ref;1338struct ref_dir *dir =get_packed_refs(refs);13391340 ref =find_ref(dir, refname);1341if(ref == NULL)1342return-1;13431344hashcpy(sha1, ref->u.value.sha1);1345return0;1346}13471348static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1349const char*refname,unsigned char*sha1,1350int recursion)1351{1352int fd, len;1353char buffer[128], *p;1354const char*path;13551356if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1357return-1;1358 path = *refs->name1359?git_path_submodule(refs->name,"%s", refname)1360:git_path("%s", refname);1361 fd =open(path, O_RDONLY);1362if(fd <0)1363returnresolve_gitlink_packed_ref(refs, refname, sha1);13641365 len =read(fd, buffer,sizeof(buffer)-1);1366close(fd);1367if(len <0)1368return-1;1369while(len &&isspace(buffer[len-1]))1370 len--;1371 buffer[len] =0;13721373/* Was it a detached head or an old-fashioned symlink? */1374if(!get_sha1_hex(buffer, sha1))1375return0;13761377/* Symref? */1378if(strncmp(buffer,"ref:",4))1379return-1;1380 p = buffer +4;1381while(isspace(*p))1382 p++;13831384returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1385}13861387intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1388{1389int len =strlen(path), retval;1390char*submodule;1391struct ref_cache *refs;13921393while(len && path[len-1] =='/')1394 len--;1395if(!len)1396return-1;1397 submodule =xstrndup(path, len);1398 refs =get_ref_cache(submodule);1399free(submodule);14001401 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1402return retval;1403}14041405/*1406 * Return the ref_entry for the given refname from the packed1407 * references. If it does not exist, return NULL.1408 */1409static struct ref_entry *get_packed_ref(const char*refname)1410{1411returnfind_ref(get_packed_refs(&ref_cache), refname);1412}14131414/*1415 * A loose ref file doesn't exist; check for a packed ref. The1416 * options are forwarded from resolve_safe_unsafe().1417 */1418static intresolve_missing_loose_ref(const char*refname,1419int resolve_flags,1420unsigned char*sha1,1421int*flags)1422{1423struct ref_entry *entry;14241425/*1426 * The loose reference file does not exist; check for a packed1427 * reference.1428 */1429 entry =get_packed_ref(refname);1430if(entry) {1431hashcpy(sha1, entry->u.value.sha1);1432if(flags)1433*flags |= REF_ISPACKED;1434return0;1435}1436/* The reference is not a packed reference, either. */1437if(resolve_flags & RESOLVE_REF_READING) {1438 errno = ENOENT;1439return-1;1440}else{1441hashclr(sha1);1442return0;1443}1444}14451446/* This function needs to return a meaningful errno on failure */1447static const char*resolve_ref_unsafe_1(const char*refname,1448int resolve_flags,1449unsigned char*sha1,1450int*flags,1451struct strbuf *sb_path)1452{1453int depth = MAXDEPTH;1454 ssize_t len;1455char buffer[256];1456static char refname_buffer[256];1457int bad_name =0;14581459if(flags)1460*flags =0;14611462if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1463if(flags)1464*flags |= REF_BAD_NAME;14651466if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1467!refname_is_safe(refname)) {1468 errno = EINVAL;1469return NULL;1470}1471/*1472 * dwim_ref() uses REF_ISBROKEN to distinguish between1473 * missing refs and refs that were present but invalid,1474 * to complain about the latter to stderr.1475 *1476 * We don't know whether the ref exists, so don't set1477 * REF_ISBROKEN yet.1478 */1479 bad_name =1;1480}1481for(;;) {1482const char*path;1483struct stat st;1484char*buf;1485int fd;14861487if(--depth <0) {1488 errno = ELOOP;1489return NULL;1490}14911492strbuf_reset(sb_path);1493strbuf_git_path(sb_path,"%s", refname);1494 path = sb_path->buf;14951496/*1497 * We might have to loop back here to avoid a race1498 * condition: first we lstat() the file, then we try1499 * to read it as a link or as a file. But if somebody1500 * changes the type of the file (file <-> directory1501 * <-> symlink) between the lstat() and reading, then1502 * we don't want to report that as an error but rather1503 * try again starting with the lstat().1504 */1505 stat_ref:1506if(lstat(path, &st) <0) {1507if(errno != ENOENT)1508return NULL;1509if(resolve_missing_loose_ref(refname, resolve_flags,1510 sha1, flags))1511return NULL;1512if(bad_name) {1513hashclr(sha1);1514if(flags)1515*flags |= REF_ISBROKEN;1516}1517return refname;1518}15191520/* Follow "normalized" - ie "refs/.." symlinks by hand */1521if(S_ISLNK(st.st_mode)) {1522 len =readlink(path, buffer,sizeof(buffer)-1);1523if(len <0) {1524if(errno == ENOENT || errno == EINVAL)1525/* inconsistent with lstat; retry */1526goto stat_ref;1527else1528return NULL;1529}1530 buffer[len] =0;1531if(starts_with(buffer,"refs/") &&1532!check_refname_format(buffer,0)) {1533strcpy(refname_buffer, buffer);1534 refname = refname_buffer;1535if(flags)1536*flags |= REF_ISSYMREF;1537if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1538hashclr(sha1);1539return refname;1540}1541continue;1542}1543}15441545/* Is it a directory? */1546if(S_ISDIR(st.st_mode)) {1547 errno = EISDIR;1548return NULL;1549}15501551/*1552 * Anything else, just open it and try to use it as1553 * a ref1554 */1555 fd =open(path, O_RDONLY);1556if(fd <0) {1557if(errno == ENOENT)1558/* inconsistent with lstat; retry */1559goto stat_ref;1560else1561return NULL;1562}1563 len =read_in_full(fd, buffer,sizeof(buffer)-1);1564if(len <0) {1565int save_errno = errno;1566close(fd);1567 errno = save_errno;1568return NULL;1569}1570close(fd);1571while(len &&isspace(buffer[len-1]))1572 len--;1573 buffer[len] ='\0';15741575/*1576 * Is it a symbolic ref?1577 */1578if(!starts_with(buffer,"ref:")) {1579/*1580 * Please note that FETCH_HEAD has a second1581 * line containing other data.1582 */1583if(get_sha1_hex(buffer, sha1) ||1584(buffer[40] !='\0'&& !isspace(buffer[40]))) {1585if(flags)1586*flags |= REF_ISBROKEN;1587 errno = EINVAL;1588return NULL;1589}1590if(bad_name) {1591hashclr(sha1);1592if(flags)1593*flags |= REF_ISBROKEN;1594}1595return refname;1596}1597if(flags)1598*flags |= REF_ISSYMREF;1599 buf = buffer +4;1600while(isspace(*buf))1601 buf++;1602 refname =strcpy(refname_buffer, buf);1603if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1604hashclr(sha1);1605return refname;1606}1607if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1608if(flags)1609*flags |= REF_ISBROKEN;16101611if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1612!refname_is_safe(buf)) {1613 errno = EINVAL;1614return NULL;1615}1616 bad_name =1;1617}1618}1619}16201621const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1622unsigned char*sha1,int*flags)1623{1624struct strbuf sb_path = STRBUF_INIT;1625const char*ret =resolve_ref_unsafe_1(refname, resolve_flags,1626 sha1, flags, &sb_path);1627strbuf_release(&sb_path);1628return ret;1629}16301631char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1632{1633const char*ret =resolve_ref_unsafe(ref, resolve_flags, sha1, flags);1634return ret ?xstrdup(ret) : NULL;1635}16361637/* The argument to filter_refs */1638struct ref_filter {1639const char*pattern;1640 each_ref_fn *fn;1641void*cb_data;1642};16431644intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1645{1646if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1647return0;1648return-1;1649}16501651intread_ref(const char*refname,unsigned char*sha1)1652{1653returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1654}16551656intref_exists(const char*refname)1657{1658unsigned char sha1[20];1659return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1660}16611662static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1663void*data)1664{1665struct ref_filter *filter = (struct ref_filter *)data;1666if(wildmatch(filter->pattern, refname,0, NULL))1667return0;1668return filter->fn(refname, sha1, flags, filter->cb_data);1669}16701671enum peel_status {1672/* object was peeled successfully: */1673 PEEL_PEELED =0,16741675/*1676 * object cannot be peeled because the named object (or an1677 * object referred to by a tag in the peel chain), does not1678 * exist.1679 */1680 PEEL_INVALID = -1,16811682/* object cannot be peeled because it is not a tag: */1683 PEEL_NON_TAG = -2,16841685/* ref_entry contains no peeled value because it is a symref: */1686 PEEL_IS_SYMREF = -3,16871688/*1689 * ref_entry cannot be peeled because it is broken (i.e., the1690 * symbolic reference cannot even be resolved to an object1691 * name):1692 */1693 PEEL_BROKEN = -41694};16951696/*1697 * Peel the named object; i.e., if the object is a tag, resolve the1698 * tag recursively until a non-tag is found. If successful, store the1699 * result to sha1 and return PEEL_PEELED. If the object is not a tag1700 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1701 * and leave sha1 unchanged.1702 */1703static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1704{1705struct object *o =lookup_unknown_object(name);17061707if(o->type == OBJ_NONE) {1708int type =sha1_object_info(name, NULL);1709if(type <0|| !object_as_type(o, type,0))1710return PEEL_INVALID;1711}17121713if(o->type != OBJ_TAG)1714return PEEL_NON_TAG;17151716 o =deref_tag_noverify(o);1717if(!o)1718return PEEL_INVALID;17191720hashcpy(sha1, o->sha1);1721return PEEL_PEELED;1722}17231724/*1725 * Peel the entry (if possible) and return its new peel_status. If1726 * repeel is true, re-peel the entry even if there is an old peeled1727 * value that is already stored in it.1728 *1729 * It is OK to call this function with a packed reference entry that1730 * might be stale and might even refer to an object that has since1731 * been garbage-collected. In such a case, if the entry has1732 * REF_KNOWS_PEELED then leave the status unchanged and return1733 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1734 */1735static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1736{1737enum peel_status status;17381739if(entry->flag & REF_KNOWS_PEELED) {1740if(repeel) {1741 entry->flag &= ~REF_KNOWS_PEELED;1742hashclr(entry->u.value.peeled);1743}else{1744returnis_null_sha1(entry->u.value.peeled) ?1745 PEEL_NON_TAG : PEEL_PEELED;1746}1747}1748if(entry->flag & REF_ISBROKEN)1749return PEEL_BROKEN;1750if(entry->flag & REF_ISSYMREF)1751return PEEL_IS_SYMREF;17521753 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1754if(status == PEEL_PEELED || status == PEEL_NON_TAG)1755 entry->flag |= REF_KNOWS_PEELED;1756return status;1757}17581759intpeel_ref(const char*refname,unsigned char*sha1)1760{1761int flag;1762unsigned char base[20];17631764if(current_ref && (current_ref->name == refname1765|| !strcmp(current_ref->name, refname))) {1766if(peel_entry(current_ref,0))1767return-1;1768hashcpy(sha1, current_ref->u.value.peeled);1769return0;1770}17711772if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1773return-1;17741775/*1776 * If the reference is packed, read its ref_entry from the1777 * cache in the hope that we already know its peeled value.1778 * We only try this optimization on packed references because1779 * (a) forcing the filling of the loose reference cache could1780 * be expensive and (b) loose references anyway usually do not1781 * have REF_KNOWS_PEELED.1782 */1783if(flag & REF_ISPACKED) {1784struct ref_entry *r =get_packed_ref(refname);1785if(r) {1786if(peel_entry(r,0))1787return-1;1788hashcpy(sha1, r->u.value.peeled);1789return0;1790}1791}17921793returnpeel_object(base, sha1);1794}17951796struct warn_if_dangling_data {1797FILE*fp;1798const char*refname;1799const struct string_list *refnames;1800const char*msg_fmt;1801};18021803static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1804int flags,void*cb_data)1805{1806struct warn_if_dangling_data *d = cb_data;1807const char*resolves_to;1808unsigned char junk[20];18091810if(!(flags & REF_ISSYMREF))1811return0;18121813 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1814if(!resolves_to1815|| (d->refname1816?strcmp(resolves_to, d->refname)1817: !string_list_has_string(d->refnames, resolves_to))) {1818return0;1819}18201821fprintf(d->fp, d->msg_fmt, refname);1822fputc('\n', d->fp);1823return0;1824}18251826voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1827{1828struct warn_if_dangling_data data;18291830 data.fp = fp;1831 data.refname = refname;1832 data.refnames = NULL;1833 data.msg_fmt = msg_fmt;1834for_each_rawref(warn_if_dangling_symref, &data);1835}18361837voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1838{1839struct warn_if_dangling_data data;18401841 data.fp = fp;1842 data.refname = NULL;1843 data.refnames = refnames;1844 data.msg_fmt = msg_fmt;1845for_each_rawref(warn_if_dangling_symref, &data);1846}18471848/*1849 * Call fn for each reference in the specified ref_cache, omitting1850 * references not in the containing_dir of base. fn is called for all1851 * references, including broken ones. If fn ever returns a non-zero1852 * value, stop the iteration and return that value; otherwise, return1853 * 0.1854 */1855static intdo_for_each_entry(struct ref_cache *refs,const char*base,1856 each_ref_entry_fn fn,void*cb_data)1857{1858struct packed_ref_cache *packed_ref_cache;1859struct ref_dir *loose_dir;1860struct ref_dir *packed_dir;1861int retval =0;18621863/*1864 * We must make sure that all loose refs are read before accessing the1865 * packed-refs file; this avoids a race condition in which loose refs1866 * are migrated to the packed-refs file by a simultaneous process, but1867 * our in-memory view is from before the migration. get_packed_ref_cache()1868 * takes care of making sure our view is up to date with what is on1869 * disk.1870 */1871 loose_dir =get_loose_refs(refs);1872if(base && *base) {1873 loose_dir =find_containing_dir(loose_dir, base,0);1874}1875if(loose_dir)1876prime_ref_dir(loose_dir);18771878 packed_ref_cache =get_packed_ref_cache(refs);1879acquire_packed_ref_cache(packed_ref_cache);1880 packed_dir =get_packed_ref_dir(packed_ref_cache);1881if(base && *base) {1882 packed_dir =find_containing_dir(packed_dir, base,0);1883}18841885if(packed_dir && loose_dir) {1886sort_ref_dir(packed_dir);1887sort_ref_dir(loose_dir);1888 retval =do_for_each_entry_in_dirs(1889 packed_dir, loose_dir, fn, cb_data);1890}else if(packed_dir) {1891sort_ref_dir(packed_dir);1892 retval =do_for_each_entry_in_dir(1893 packed_dir,0, fn, cb_data);1894}else if(loose_dir) {1895sort_ref_dir(loose_dir);1896 retval =do_for_each_entry_in_dir(1897 loose_dir,0, fn, cb_data);1898}18991900release_packed_ref_cache(packed_ref_cache);1901return retval;1902}19031904/*1905 * Call fn for each reference in the specified ref_cache for which the1906 * refname begins with base. If trim is non-zero, then trim that many1907 * characters off the beginning of each refname before passing the1908 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1909 * broken references in the iteration. If fn ever returns a non-zero1910 * value, stop the iteration and return that value; otherwise, return1911 * 0.1912 */1913static intdo_for_each_ref(struct ref_cache *refs,const char*base,1914 each_ref_fn fn,int trim,int flags,void*cb_data)1915{1916struct ref_entry_cb data;1917 data.base = base;1918 data.trim = trim;1919 data.flags = flags;1920 data.fn = fn;1921 data.cb_data = cb_data;19221923returndo_for_each_entry(refs, base, do_one_ref, &data);1924}19251926static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)1927{1928unsigned char sha1[20];1929int flag;19301931if(submodule) {1932if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)1933returnfn("HEAD", sha1,0, cb_data);19341935return0;1936}19371938if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))1939returnfn("HEAD", sha1, flag, cb_data);19401941return0;1942}19431944inthead_ref(each_ref_fn fn,void*cb_data)1945{1946returndo_head_ref(NULL, fn, cb_data);1947}19481949inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1950{1951returndo_head_ref(submodule, fn, cb_data);1952}19531954intfor_each_ref(each_ref_fn fn,void*cb_data)1955{1956returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);1957}19581959intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1960{1961returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);1962}19631964intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)1965{1966returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);1967}19681969intfor_each_ref_in_submodule(const char*submodule,const char*prefix,1970 each_ref_fn fn,void*cb_data)1971{1972returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);1973}19741975intfor_each_tag_ref(each_ref_fn fn,void*cb_data)1976{1977returnfor_each_ref_in("refs/tags/", fn, cb_data);1978}19791980intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1981{1982returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);1983}19841985intfor_each_branch_ref(each_ref_fn fn,void*cb_data)1986{1987returnfor_each_ref_in("refs/heads/", fn, cb_data);1988}19891990intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)1991{1992returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);1993}19941995intfor_each_remote_ref(each_ref_fn fn,void*cb_data)1996{1997returnfor_each_ref_in("refs/remotes/", fn, cb_data);1998}19992000intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2001{2002returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2003}20042005intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2006{2007returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2008}20092010inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2011{2012struct strbuf buf = STRBUF_INIT;2013int ret =0;2014unsigned char sha1[20];2015int flag;20162017strbuf_addf(&buf,"%sHEAD",get_git_namespace());2018if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2019 ret =fn(buf.buf, sha1, flag, cb_data);2020strbuf_release(&buf);20212022return ret;2023}20242025intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2026{2027struct strbuf buf = STRBUF_INIT;2028int ret;2029strbuf_addf(&buf,"%srefs/",get_git_namespace());2030 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2031strbuf_release(&buf);2032return ret;2033}20342035intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2036const char*prefix,void*cb_data)2037{2038struct strbuf real_pattern = STRBUF_INIT;2039struct ref_filter filter;2040int ret;20412042if(!prefix && !starts_with(pattern,"refs/"))2043strbuf_addstr(&real_pattern,"refs/");2044else if(prefix)2045strbuf_addstr(&real_pattern, prefix);2046strbuf_addstr(&real_pattern, pattern);20472048if(!has_glob_specials(pattern)) {2049/* Append implied '/' '*' if not present. */2050if(real_pattern.buf[real_pattern.len -1] !='/')2051strbuf_addch(&real_pattern,'/');2052/* No need to check for '*', there is none. */2053strbuf_addch(&real_pattern,'*');2054}20552056 filter.pattern = real_pattern.buf;2057 filter.fn = fn;2058 filter.cb_data = cb_data;2059 ret =for_each_ref(filter_refs, &filter);20602061strbuf_release(&real_pattern);2062return ret;2063}20642065intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2066{2067returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2068}20692070intfor_each_rawref(each_ref_fn fn,void*cb_data)2071{2072returndo_for_each_ref(&ref_cache,"", fn,0,2073 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2074}20752076const char*prettify_refname(const char*name)2077{2078return name + (2079starts_with(name,"refs/heads/") ?11:2080starts_with(name,"refs/tags/") ?10:2081starts_with(name,"refs/remotes/") ?13:20820);2083}20842085static const char*ref_rev_parse_rules[] = {2086"%.*s",2087"refs/%.*s",2088"refs/tags/%.*s",2089"refs/heads/%.*s",2090"refs/remotes/%.*s",2091"refs/remotes/%.*s/HEAD",2092 NULL2093};20942095intrefname_match(const char*abbrev_name,const char*full_name)2096{2097const char**p;2098const int abbrev_name_len =strlen(abbrev_name);20992100for(p = ref_rev_parse_rules; *p; p++) {2101if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2102return1;2103}2104}21052106return0;2107}21082109/* This function should make sure errno is meaningful on error */2110static struct ref_lock *verify_lock(struct ref_lock *lock,2111const unsigned char*old_sha1,int mustexist)2112{2113if(read_ref_full(lock->ref_name,2114 mustexist ? RESOLVE_REF_READING :0,2115 lock->old_sha1, NULL)) {2116int save_errno = errno;2117error("Can't verify ref%s", lock->ref_name);2118unlock_ref(lock);2119 errno = save_errno;2120return NULL;2121}2122if(hashcmp(lock->old_sha1, old_sha1)) {2123error("Ref%sis at%sbut expected%s", lock->ref_name,2124sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2125unlock_ref(lock);2126 errno = EBUSY;2127return NULL;2128}2129return lock;2130}21312132static intremove_empty_directories(const char*file)2133{2134/* we want to create a file but there is a directory there;2135 * if that is an empty directory (or a directory that contains2136 * only empty directories), remove them.2137 */2138struct strbuf path;2139int result, save_errno;21402141strbuf_init(&path,20);2142strbuf_addstr(&path, file);21432144 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2145 save_errno = errno;21462147strbuf_release(&path);2148 errno = save_errno;21492150return result;2151}21522153/*2154 * *string and *len will only be substituted, and *string returned (for2155 * later free()ing) if the string passed in is a magic short-hand form2156 * to name a branch.2157 */2158static char*substitute_branch_name(const char**string,int*len)2159{2160struct strbuf buf = STRBUF_INIT;2161int ret =interpret_branch_name(*string, *len, &buf);21622163if(ret == *len) {2164size_t size;2165*string =strbuf_detach(&buf, &size);2166*len = size;2167return(char*)*string;2168}21692170return NULL;2171}21722173intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2174{2175char*last_branch =substitute_branch_name(&str, &len);2176const char**p, *r;2177int refs_found =0;21782179*ref = NULL;2180for(p = ref_rev_parse_rules; *p; p++) {2181char fullref[PATH_MAX];2182unsigned char sha1_from_ref[20];2183unsigned char*this_result;2184int flag;21852186 this_result = refs_found ? sha1_from_ref : sha1;2187mksnpath(fullref,sizeof(fullref), *p, len, str);2188 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2189 this_result, &flag);2190if(r) {2191if(!refs_found++)2192*ref =xstrdup(r);2193if(!warn_ambiguous_refs)2194break;2195}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2196warning("ignoring dangling symref%s.", fullref);2197}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2198warning("ignoring broken ref%s.", fullref);2199}2200}2201free(last_branch);2202return refs_found;2203}22042205intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2206{2207char*last_branch =substitute_branch_name(&str, &len);2208const char**p;2209int logs_found =0;22102211*log = NULL;2212for(p = ref_rev_parse_rules; *p; p++) {2213unsigned char hash[20];2214char path[PATH_MAX];2215const char*ref, *it;22162217mksnpath(path,sizeof(path), *p, len, str);2218 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2219 hash, NULL);2220if(!ref)2221continue;2222if(reflog_exists(path))2223 it = path;2224else if(strcmp(ref, path) &&reflog_exists(ref))2225 it = ref;2226else2227continue;2228if(!logs_found++) {2229*log =xstrdup(it);2230hashcpy(sha1, hash);2231}2232if(!warn_ambiguous_refs)2233break;2234}2235free(last_branch);2236return logs_found;2237}22382239/*2240 * Locks a ref returning the lock on success and NULL on failure.2241 * On failure errno is set to something meaningful.2242 */2243static struct ref_lock *lock_ref_sha1_basic(const char*refname,2244const unsigned char*old_sha1,2245const struct string_list *skip,2246int flags,int*type_p)2247{2248const char*ref_file;2249const char*orig_refname = refname;2250struct ref_lock *lock;2251int last_errno =0;2252int type, lflags;2253int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2254int resolve_flags =0;2255int missing =0;2256int attempts_remaining =3;22572258 lock =xcalloc(1,sizeof(struct ref_lock));2259 lock->lock_fd = -1;22602261if(mustexist)2262 resolve_flags |= RESOLVE_REF_READING;2263if(flags & REF_DELETING) {2264 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2265if(flags & REF_NODEREF)2266 resolve_flags |= RESOLVE_REF_NO_RECURSE;2267}22682269 refname =resolve_ref_unsafe(refname, resolve_flags,2270 lock->old_sha1, &type);2271if(!refname && errno == EISDIR) {2272/* we are trying to lock foo but we used to2273 * have foo/bar which now does not exist;2274 * it is normal for the empty directory 'foo'2275 * to remain.2276 */2277 ref_file =git_path("%s", orig_refname);2278if(remove_empty_directories(ref_file)) {2279 last_errno = errno;2280error("there are still refs under '%s'", orig_refname);2281goto error_return;2282}2283 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2284 lock->old_sha1, &type);2285}2286if(type_p)2287*type_p = type;2288if(!refname) {2289 last_errno = errno;2290error("unable to resolve reference%s:%s",2291 orig_refname,strerror(errno));2292goto error_return;2293}2294 missing =is_null_sha1(lock->old_sha1);2295/* When the ref did not exist and we are creating it,2296 * make sure there is no existing ref that is packed2297 * whose name begins with our refname, nor a ref whose2298 * name is a proper prefix of our refname.2299 */2300if(missing &&2301!is_refname_available(refname, skip,get_packed_refs(&ref_cache))) {2302 last_errno = ENOTDIR;2303goto error_return;2304}23052306 lock->lk =xcalloc(1,sizeof(struct lock_file));23072308 lflags =0;2309if(flags & REF_NODEREF) {2310 refname = orig_refname;2311 lflags |= LOCK_NO_DEREF;2312}2313 lock->ref_name =xstrdup(refname);2314 lock->orig_ref_name =xstrdup(orig_refname);2315 ref_file =git_path("%s", refname);2316if(missing)2317 lock->force_write =1;2318if((flags & REF_NODEREF) && (type & REF_ISSYMREF))2319 lock->force_write =1;23202321 retry:2322switch(safe_create_leading_directories_const(ref_file)) {2323case SCLD_OK:2324break;/* success */2325case SCLD_VANISHED:2326if(--attempts_remaining >0)2327goto retry;2328/* fall through */2329default:2330 last_errno = errno;2331error("unable to create directory for%s", ref_file);2332goto error_return;2333}23342335 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2336if(lock->lock_fd <0) {2337if(errno == ENOENT && --attempts_remaining >0)2338/*2339 * Maybe somebody just deleted one of the2340 * directories leading to ref_file. Try2341 * again:2342 */2343goto retry;2344else2345unable_to_lock_die(ref_file, errno);2346}2347return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;23482349 error_return:2350unlock_ref(lock);2351 errno = last_errno;2352return NULL;2353}23542355struct ref_lock *lock_any_ref_for_update(const char*refname,2356const unsigned char*old_sha1,2357int flags,int*type_p)2358{2359returnlock_ref_sha1_basic(refname, old_sha1, NULL, flags, type_p);2360}23612362/*2363 * Write an entry to the packed-refs file for the specified refname.2364 * If peeled is non-NULL, write it as the entry's peeled value.2365 */2366static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2367unsigned char*peeled)2368{2369fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2370if(peeled)2371fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2372}23732374/*2375 * An each_ref_entry_fn that writes the entry to a packed-refs file.2376 */2377static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2378{2379enum peel_status peel_status =peel_entry(entry,0);23802381if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2382error("internal error:%sis not a valid packed reference!",2383 entry->name);2384write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2385 peel_status == PEEL_PEELED ?2386 entry->u.value.peeled : NULL);2387return0;2388}23892390/* This should return a meaningful errno on failure */2391intlock_packed_refs(int flags)2392{2393struct packed_ref_cache *packed_ref_cache;23942395if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2396return-1;2397/*2398 * Get the current packed-refs while holding the lock. If the2399 * packed-refs file has been modified since we last read it,2400 * this will automatically invalidate the cache and re-read2401 * the packed-refs file.2402 */2403 packed_ref_cache =get_packed_ref_cache(&ref_cache);2404 packed_ref_cache->lock = &packlock;2405/* Increment the reference count to prevent it from being freed: */2406acquire_packed_ref_cache(packed_ref_cache);2407return0;2408}24092410/*2411 * Commit the packed refs changes.2412 * On error we must make sure that errno contains a meaningful value.2413 */2414intcommit_packed_refs(void)2415{2416struct packed_ref_cache *packed_ref_cache =2417get_packed_ref_cache(&ref_cache);2418int error =0;2419int save_errno =0;2420FILE*out;24212422if(!packed_ref_cache->lock)2423die("internal error: packed-refs not locked");24242425 out =fdopen_lock_file(packed_ref_cache->lock,"w");2426if(!out)2427die_errno("unable to fdopen packed-refs descriptor");24282429fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2430do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),24310, write_packed_entry_fn, out);24322433if(commit_lock_file(packed_ref_cache->lock)) {2434 save_errno = errno;2435 error = -1;2436}2437 packed_ref_cache->lock = NULL;2438release_packed_ref_cache(packed_ref_cache);2439 errno = save_errno;2440return error;2441}24422443voidrollback_packed_refs(void)2444{2445struct packed_ref_cache *packed_ref_cache =2446get_packed_ref_cache(&ref_cache);24472448if(!packed_ref_cache->lock)2449die("internal error: packed-refs not locked");2450rollback_lock_file(packed_ref_cache->lock);2451 packed_ref_cache->lock = NULL;2452release_packed_ref_cache(packed_ref_cache);2453clear_packed_ref_cache(&ref_cache);2454}24552456struct ref_to_prune {2457struct ref_to_prune *next;2458unsigned char sha1[20];2459char name[FLEX_ARRAY];2460};24612462struct pack_refs_cb_data {2463unsigned int flags;2464struct ref_dir *packed_refs;2465struct ref_to_prune *ref_to_prune;2466};24672468/*2469 * An each_ref_entry_fn that is run over loose references only. If2470 * the loose reference can be packed, add an entry in the packed ref2471 * cache. If the reference should be pruned, also add it to2472 * ref_to_prune in the pack_refs_cb_data.2473 */2474static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2475{2476struct pack_refs_cb_data *cb = cb_data;2477enum peel_status peel_status;2478struct ref_entry *packed_entry;2479int is_tag_ref =starts_with(entry->name,"refs/tags/");24802481/* ALWAYS pack tags */2482if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2483return0;24842485/* Do not pack symbolic or broken refs: */2486if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2487return0;24882489/* Add a packed ref cache entry equivalent to the loose entry. */2490 peel_status =peel_entry(entry,1);2491if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2492die("internal error peeling reference%s(%s)",2493 entry->name,sha1_to_hex(entry->u.value.sha1));2494 packed_entry =find_ref(cb->packed_refs, entry->name);2495if(packed_entry) {2496/* Overwrite existing packed entry with info from loose entry */2497 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2498hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2499}else{2500 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2501 REF_ISPACKED | REF_KNOWS_PEELED,0);2502add_ref(cb->packed_refs, packed_entry);2503}2504hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);25052506/* Schedule the loose reference for pruning if requested. */2507if((cb->flags & PACK_REFS_PRUNE)) {2508int namelen =strlen(entry->name) +1;2509struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2510hashcpy(n->sha1, entry->u.value.sha1);2511strcpy(n->name, entry->name);2512 n->next = cb->ref_to_prune;2513 cb->ref_to_prune = n;2514}2515return0;2516}25172518/*2519 * Remove empty parents, but spare refs/ and immediate subdirs.2520 * Note: munges *name.2521 */2522static voidtry_remove_empty_parents(char*name)2523{2524char*p, *q;2525int i;2526 p = name;2527for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2528while(*p && *p !='/')2529 p++;2530/* tolerate duplicate slashes; see check_refname_format() */2531while(*p =='/')2532 p++;2533}2534for(q = p; *q; q++)2535;2536while(1) {2537while(q > p && *q !='/')2538 q--;2539while(q > p && *(q-1) =='/')2540 q--;2541if(q == p)2542break;2543*q ='\0';2544if(rmdir(git_path("%s", name)))2545break;2546}2547}25482549/* make sure nobody touched the ref, and unlink */2550static voidprune_ref(struct ref_to_prune *r)2551{2552struct ref_transaction *transaction;2553struct strbuf err = STRBUF_INIT;25542555if(check_refname_format(r->name,0))2556return;25572558 transaction =ref_transaction_begin(&err);2559if(!transaction ||2560ref_transaction_delete(transaction, r->name, r->sha1,2561 REF_ISPRUNING,1, NULL, &err) ||2562ref_transaction_commit(transaction, &err)) {2563ref_transaction_free(transaction);2564error("%s", err.buf);2565strbuf_release(&err);2566return;2567}2568ref_transaction_free(transaction);2569strbuf_release(&err);2570try_remove_empty_parents(r->name);2571}25722573static voidprune_refs(struct ref_to_prune *r)2574{2575while(r) {2576prune_ref(r);2577 r = r->next;2578}2579}25802581intpack_refs(unsigned int flags)2582{2583struct pack_refs_cb_data cbdata;25842585memset(&cbdata,0,sizeof(cbdata));2586 cbdata.flags = flags;25872588lock_packed_refs(LOCK_DIE_ON_ERROR);2589 cbdata.packed_refs =get_packed_refs(&ref_cache);25902591do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2592 pack_if_possible_fn, &cbdata);25932594if(commit_packed_refs())2595die_errno("unable to overwrite old ref-pack file");25962597prune_refs(cbdata.ref_to_prune);2598return0;2599}26002601/*2602 * If entry is no longer needed in packed-refs, add it to the string2603 * list pointed to by cb_data. Reasons for deleting entries:2604 *2605 * - Entry is broken.2606 * - Entry is overridden by a loose ref.2607 * - Entry does not point at a valid object.2608 *2609 * In the first and third cases, also emit an error message because these2610 * are indications of repository corruption.2611 */2612static intcurate_packed_ref_fn(struct ref_entry *entry,void*cb_data)2613{2614struct string_list *refs_to_delete = cb_data;26152616if(entry->flag & REF_ISBROKEN) {2617/* This shouldn't happen to packed refs. */2618error("%sis broken!", entry->name);2619string_list_append(refs_to_delete, entry->name);2620return0;2621}2622if(!has_sha1_file(entry->u.value.sha1)) {2623unsigned char sha1[20];2624int flags;26252626if(read_ref_full(entry->name,0, sha1, &flags))2627/* We should at least have found the packed ref. */2628die("Internal error");2629if((flags & REF_ISSYMREF) || !(flags & REF_ISPACKED)) {2630/*2631 * This packed reference is overridden by a2632 * loose reference, so it is OK that its value2633 * is no longer valid; for example, it might2634 * refer to an object that has been garbage2635 * collected. For this purpose we don't even2636 * care whether the loose reference itself is2637 * invalid, broken, symbolic, etc. Silently2638 * remove the packed reference.2639 */2640string_list_append(refs_to_delete, entry->name);2641return0;2642}2643/*2644 * There is no overriding loose reference, so the fact2645 * that this reference doesn't refer to a valid object2646 * indicates some kind of repository corruption.2647 * Report the problem, then omit the reference from2648 * the output.2649 */2650error("%sdoes not point to a valid object!", entry->name);2651string_list_append(refs_to_delete, entry->name);2652return0;2653}26542655return0;2656}26572658intrepack_without_refs(const char**refnames,int n,struct strbuf *err)2659{2660struct ref_dir *packed;2661struct string_list refs_to_delete = STRING_LIST_INIT_DUP;2662struct string_list_item *ref_to_delete;2663int i, ret, removed =0;26642665assert(err);26662667/* Look for a packed ref */2668for(i =0; i < n; i++)2669if(get_packed_ref(refnames[i]))2670break;26712672/* Avoid locking if we have nothing to do */2673if(i == n)2674return0;/* no refname exists in packed refs */26752676if(lock_packed_refs(0)) {2677unable_to_lock_message(git_path("packed-refs"), errno, err);2678return-1;2679}2680 packed =get_packed_refs(&ref_cache);26812682/* Remove refnames from the cache */2683for(i =0; i < n; i++)2684if(remove_entry(packed, refnames[i]) != -1)2685 removed =1;2686if(!removed) {2687/*2688 * All packed entries disappeared while we were2689 * acquiring the lock.2690 */2691rollback_packed_refs();2692return0;2693}26942695/* Remove any other accumulated cruft */2696do_for_each_entry_in_dir(packed,0, curate_packed_ref_fn, &refs_to_delete);2697for_each_string_list_item(ref_to_delete, &refs_to_delete) {2698if(remove_entry(packed, ref_to_delete->string) == -1)2699die("internal error");2700}27012702/* Write what remains */2703 ret =commit_packed_refs();2704if(ret)2705strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2706strerror(errno));2707return ret;2708}27092710static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2711{2712assert(err);27132714if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2715/*2716 * loose. The loose file name is the same as the2717 * lockfile name, minus ".lock":2718 */2719char*loose_filename =get_locked_file_path(lock->lk);2720int res =unlink_or_msg(loose_filename, err);2721free(loose_filename);2722if(res)2723return1;2724}2725return0;2726}27272728intdelete_ref(const char*refname,const unsigned char*sha1,int delopt)2729{2730struct ref_transaction *transaction;2731struct strbuf err = STRBUF_INIT;27322733 transaction =ref_transaction_begin(&err);2734if(!transaction ||2735ref_transaction_delete(transaction, refname, sha1, delopt,2736 sha1 && !is_null_sha1(sha1), NULL, &err) ||2737ref_transaction_commit(transaction, &err)) {2738error("%s", err.buf);2739ref_transaction_free(transaction);2740strbuf_release(&err);2741return1;2742}2743ref_transaction_free(transaction);2744strbuf_release(&err);2745return0;2746}27472748/*2749 * People using contrib's git-new-workdir have .git/logs/refs ->2750 * /some/other/path/.git/logs/refs, and that may live on another device.2751 *2752 * IOW, to avoid cross device rename errors, the temporary renamed log must2753 * live into logs/refs.2754 */2755#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"27562757static intrename_tmp_log(const char*newrefname)2758{2759int attempts_remaining =4;27602761 retry:2762switch(safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {2763case SCLD_OK:2764break;/* success */2765case SCLD_VANISHED:2766if(--attempts_remaining >0)2767goto retry;2768/* fall through */2769default:2770error("unable to create directory for%s", newrefname);2771return-1;2772}27732774if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2775if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2776/*2777 * rename(a, b) when b is an existing2778 * directory ought to result in ISDIR, but2779 * Solaris 5.8 gives ENOTDIR. Sheesh.2780 */2781if(remove_empty_directories(git_path("logs/%s", newrefname))) {2782error("Directory not empty: logs/%s", newrefname);2783return-1;2784}2785goto retry;2786}else if(errno == ENOENT && --attempts_remaining >0) {2787/*2788 * Maybe another process just deleted one of2789 * the directories in the path to newrefname.2790 * Try again from the beginning.2791 */2792goto retry;2793}else{2794error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2795 newrefname,strerror(errno));2796return-1;2797}2798}2799return0;2800}28012802static intrename_ref_available(const char*oldname,const char*newname)2803{2804struct string_list skip = STRING_LIST_INIT_NODUP;2805int ret;28062807string_list_insert(&skip, oldname);2808 ret =is_refname_available(newname, &skip,get_packed_refs(&ref_cache))2809&&is_refname_available(newname, &skip,get_loose_refs(&ref_cache));2810string_list_clear(&skip,0);2811return ret;2812}28132814static intwrite_ref_sha1(struct ref_lock *lock,const unsigned char*sha1,2815const char*logmsg);28162817intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2818{2819unsigned char sha1[20], orig_sha1[20];2820int flag =0, logmoved =0;2821struct ref_lock *lock;2822struct stat loginfo;2823int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2824const char*symref = NULL;28252826if(log &&S_ISLNK(loginfo.st_mode))2827returnerror("reflog for%sis a symlink", oldrefname);28282829 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2830 orig_sha1, &flag);2831if(flag & REF_ISSYMREF)2832returnerror("refname%sis a symbolic ref, renaming it is not supported",2833 oldrefname);2834if(!symref)2835returnerror("refname%snot found", oldrefname);28362837if(!rename_ref_available(oldrefname, newrefname))2838return1;28392840if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2841returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2842 oldrefname,strerror(errno));28432844if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2845error("unable to delete old%s", oldrefname);2846goto rollback;2847}28482849if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2850delete_ref(newrefname, sha1, REF_NODEREF)) {2851if(errno==EISDIR) {2852if(remove_empty_directories(git_path("%s", newrefname))) {2853error("Directory not empty:%s", newrefname);2854goto rollback;2855}2856}else{2857error("unable to delete existing%s", newrefname);2858goto rollback;2859}2860}28612862if(log &&rename_tmp_log(newrefname))2863goto rollback;28642865 logmoved = log;28662867 lock =lock_ref_sha1_basic(newrefname, NULL, NULL,0, NULL);2868if(!lock) {2869error("unable to lock%sfor update", newrefname);2870goto rollback;2871}2872 lock->force_write =1;2873hashcpy(lock->old_sha1, orig_sha1);2874if(write_ref_sha1(lock, orig_sha1, logmsg)) {2875error("unable to write current sha1 into%s", newrefname);2876goto rollback;2877}28782879return0;28802881 rollback:2882 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL,0, NULL);2883if(!lock) {2884error("unable to lock%sfor rollback", oldrefname);2885goto rollbacklog;2886}28872888 lock->force_write =1;2889 flag = log_all_ref_updates;2890 log_all_ref_updates =0;2891if(write_ref_sha1(lock, orig_sha1, NULL))2892error("unable to write current sha1 into%s", oldrefname);2893 log_all_ref_updates = flag;28942895 rollbacklog:2896if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2897error("unable to restore logfile%sfrom%s:%s",2898 oldrefname, newrefname,strerror(errno));2899if(!logmoved && log &&2900rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2901error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2902 oldrefname,strerror(errno));29032904return1;2905}29062907intclose_ref(struct ref_lock *lock)2908{2909if(close_lock_file(lock->lk))2910return-1;2911 lock->lock_fd = -1;2912return0;2913}29142915intcommit_ref(struct ref_lock *lock)2916{2917if(commit_lock_file(lock->lk))2918return-1;2919 lock->lock_fd = -1;2920return0;2921}29222923voidunlock_ref(struct ref_lock *lock)2924{2925/* Do not free lock->lk -- atexit() still looks at them */2926if(lock->lk)2927rollback_lock_file(lock->lk);2928free(lock->ref_name);2929free(lock->orig_ref_name);2930free(lock);2931}29322933/*2934 * copy the reflog message msg to buf, which has been allocated sufficiently2935 * large, while cleaning up the whitespaces. Especially, convert LF to space,2936 * because reflog file is one line per entry.2937 */2938static intcopy_msg(char*buf,const char*msg)2939{2940char*cp = buf;2941char c;2942int wasspace =1;29432944*cp++ ='\t';2945while((c = *msg++)) {2946if(wasspace &&isspace(c))2947continue;2948 wasspace =isspace(c);2949if(wasspace)2950 c =' ';2951*cp++ = c;2952}2953while(buf < cp &&isspace(cp[-1]))2954 cp--;2955*cp++ ='\n';2956return cp - buf;2957}29582959/* This function must set a meaningful errno on failure */2960intlog_ref_setup(const char*refname,struct strbuf *sb_logfile)2961{2962int logfd, oflags = O_APPEND | O_WRONLY;2963char*logfile;29642965strbuf_git_path(sb_logfile,"logs/%s", refname);2966 logfile = sb_logfile->buf;2967/* make sure the rest of the function can't change "logfile" */2968 sb_logfile = NULL;2969if(log_all_ref_updates &&2970(starts_with(refname,"refs/heads/") ||2971starts_with(refname,"refs/remotes/") ||2972starts_with(refname,"refs/notes/") ||2973!strcmp(refname,"HEAD"))) {2974if(safe_create_leading_directories(logfile) <0) {2975int save_errno = errno;2976error("unable to create directory for%s", logfile);2977 errno = save_errno;2978return-1;2979}2980 oflags |= O_CREAT;2981}29822983 logfd =open(logfile, oflags,0666);2984if(logfd <0) {2985if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))2986return0;29872988if(errno == EISDIR) {2989if(remove_empty_directories(logfile)) {2990int save_errno = errno;2991error("There are still logs under '%s'",2992 logfile);2993 errno = save_errno;2994return-1;2995}2996 logfd =open(logfile, oflags,0666);2997}29982999if(logfd <0) {3000int save_errno = errno;3001error("Unable to append to%s:%s", logfile,3002strerror(errno));3003 errno = save_errno;3004return-1;3005}3006}30073008adjust_shared_perm(logfile);3009close(logfd);3010return0;3011}30123013static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3014const unsigned char*new_sha1,const char*msg,3015struct strbuf *sb_log_file)3016{3017int logfd, result, written, oflags = O_APPEND | O_WRONLY;3018unsigned maxlen, len;3019int msglen;3020const char*log_file;3021char*logrec;3022const char*committer;30233024if(log_all_ref_updates <0)3025 log_all_ref_updates = !is_bare_repository();30263027 result =log_ref_setup(refname, sb_log_file);3028if(result)3029return result;3030 log_file = sb_log_file->buf;3031/* make sure the rest of the function can't change "log_file" */3032 sb_log_file = NULL;30333034 logfd =open(log_file, oflags);3035if(logfd <0)3036return0;3037 msglen = msg ?strlen(msg) :0;3038 committer =git_committer_info(0);3039 maxlen =strlen(committer) + msglen +100;3040 logrec =xmalloc(maxlen);3041 len =sprintf(logrec,"%s %s %s\n",3042sha1_to_hex(old_sha1),3043sha1_to_hex(new_sha1),3044 committer);3045if(msglen)3046 len +=copy_msg(logrec + len -1, msg) -1;3047 written = len <= maxlen ?write_in_full(logfd, logrec, len) : -1;3048free(logrec);3049if(written != len) {3050int save_errno = errno;3051close(logfd);3052error("Unable to append to%s", log_file);3053 errno = save_errno;3054return-1;3055}3056if(close(logfd)) {3057int save_errno = errno;3058error("Unable to append to%s", log_file);3059 errno = save_errno;3060return-1;3061}3062return0;3063}30643065static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3066const unsigned char*new_sha1,const char*msg)3067{3068struct strbuf sb = STRBUF_INIT;3069int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb);3070strbuf_release(&sb);3071return ret;3072}30733074intis_branch(const char*refname)3075{3076return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3077}30783079/*3080 * Write sha1 into the ref specified by the lock. Make sure that errno3081 * is sane on error.3082 */3083static intwrite_ref_sha1(struct ref_lock *lock,3084const unsigned char*sha1,const char*logmsg)3085{3086static char term ='\n';3087struct object *o;30883089if(!lock) {3090 errno = EINVAL;3091return-1;3092}3093if(!lock->force_write && !hashcmp(lock->old_sha1, sha1)) {3094unlock_ref(lock);3095return0;3096}3097 o =parse_object(sha1);3098if(!o) {3099error("Trying to write ref%swith nonexistent object%s",3100 lock->ref_name,sha1_to_hex(sha1));3101unlock_ref(lock);3102 errno = EINVAL;3103return-1;3104}3105if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3106error("Trying to write non-commit object%sto branch%s",3107sha1_to_hex(sha1), lock->ref_name);3108unlock_ref(lock);3109 errno = EINVAL;3110return-1;3111}3112if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3113write_in_full(lock->lock_fd, &term,1) !=1||3114close_ref(lock) <0) {3115int save_errno = errno;3116error("Couldn't write%s", lock->lk->filename.buf);3117unlock_ref(lock);3118 errno = save_errno;3119return-1;3120}3121clear_loose_ref_cache(&ref_cache);3122if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3123(strcmp(lock->ref_name, lock->orig_ref_name) &&3124log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3125unlock_ref(lock);3126return-1;3127}3128if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3129/*3130 * Special hack: If a branch is updated directly and HEAD3131 * points to it (may happen on the remote side of a push3132 * for example) then logically the HEAD reflog should be3133 * updated too.3134 * A generic solution implies reverse symref information,3135 * but finding all symrefs pointing to the given branch3136 * would be rather costly for this rare event (the direct3137 * update of a branch) to be worth it. So let's cheat and3138 * check with HEAD only which should cover 99% of all usage3139 * scenarios (even 100% of the default ones).3140 */3141unsigned char head_sha1[20];3142int head_flag;3143const char*head_ref;3144 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3145 head_sha1, &head_flag);3146if(head_ref && (head_flag & REF_ISSYMREF) &&3147!strcmp(head_ref, lock->ref_name))3148log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3149}3150if(commit_ref(lock)) {3151error("Couldn't set%s", lock->ref_name);3152unlock_ref(lock);3153return-1;3154}3155unlock_ref(lock);3156return0;3157}31583159intcreate_symref(const char*ref_target,const char*refs_heads_master,3160const char*logmsg)3161{3162const char*lockpath;3163char ref[1000];3164int fd, len, written;3165char*git_HEAD =git_pathdup("%s", ref_target);3166unsigned char old_sha1[20], new_sha1[20];31673168if(logmsg &&read_ref(ref_target, old_sha1))3169hashclr(old_sha1);31703171if(safe_create_leading_directories(git_HEAD) <0)3172returnerror("unable to create directory for%s", git_HEAD);31733174#ifndef NO_SYMLINK_HEAD3175if(prefer_symlink_refs) {3176unlink(git_HEAD);3177if(!symlink(refs_heads_master, git_HEAD))3178goto done;3179fprintf(stderr,"no symlink - falling back to symbolic ref\n");3180}3181#endif31823183 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3184if(sizeof(ref) <= len) {3185error("refname too long:%s", refs_heads_master);3186goto error_free_return;3187}3188 lockpath =mkpath("%s.lock", git_HEAD);3189 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3190if(fd <0) {3191error("Unable to open%sfor writing", lockpath);3192goto error_free_return;3193}3194 written =write_in_full(fd, ref, len);3195if(close(fd) !=0|| written != len) {3196error("Unable to write to%s", lockpath);3197goto error_unlink_return;3198}3199if(rename(lockpath, git_HEAD) <0) {3200error("Unable to create%s", git_HEAD);3201goto error_unlink_return;3202}3203if(adjust_shared_perm(git_HEAD)) {3204error("Unable to fix permissions on%s", lockpath);3205 error_unlink_return:3206unlink_or_warn(lockpath);3207 error_free_return:3208free(git_HEAD);3209return-1;3210}32113212#ifndef NO_SYMLINK_HEAD3213 done:3214#endif3215if(logmsg && !read_ref(refs_heads_master, new_sha1))3216log_ref_write(ref_target, old_sha1, new_sha1, logmsg);32173218free(git_HEAD);3219return0;3220}32213222struct read_ref_at_cb {3223const char*refname;3224unsigned long at_time;3225int cnt;3226int reccnt;3227unsigned char*sha1;3228int found_it;32293230unsigned char osha1[20];3231unsigned char nsha1[20];3232int tz;3233unsigned long date;3234char**msg;3235unsigned long*cutoff_time;3236int*cutoff_tz;3237int*cutoff_cnt;3238};32393240static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3241const char*email,unsigned long timestamp,int tz,3242const char*message,void*cb_data)3243{3244struct read_ref_at_cb *cb = cb_data;32453246 cb->reccnt++;3247 cb->tz = tz;3248 cb->date = timestamp;32493250if(timestamp <= cb->at_time || cb->cnt ==0) {3251if(cb->msg)3252*cb->msg =xstrdup(message);3253if(cb->cutoff_time)3254*cb->cutoff_time = timestamp;3255if(cb->cutoff_tz)3256*cb->cutoff_tz = tz;3257if(cb->cutoff_cnt)3258*cb->cutoff_cnt = cb->reccnt -1;3259/*3260 * we have not yet updated cb->[n|o]sha1 so they still3261 * hold the values for the previous record.3262 */3263if(!is_null_sha1(cb->osha1)) {3264hashcpy(cb->sha1, nsha1);3265if(hashcmp(cb->osha1, nsha1))3266warning("Log for ref%shas gap after%s.",3267 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3268}3269else if(cb->date == cb->at_time)3270hashcpy(cb->sha1, nsha1);3271else if(hashcmp(nsha1, cb->sha1))3272warning("Log for ref%sunexpectedly ended on%s.",3273 cb->refname,show_date(cb->date, cb->tz,3274 DATE_RFC2822));3275hashcpy(cb->osha1, osha1);3276hashcpy(cb->nsha1, nsha1);3277 cb->found_it =1;3278return1;3279}3280hashcpy(cb->osha1, osha1);3281hashcpy(cb->nsha1, nsha1);3282if(cb->cnt >0)3283 cb->cnt--;3284return0;3285}32863287static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3288const char*email,unsigned long timestamp,3289int tz,const char*message,void*cb_data)3290{3291struct read_ref_at_cb *cb = cb_data;32923293if(cb->msg)3294*cb->msg =xstrdup(message);3295if(cb->cutoff_time)3296*cb->cutoff_time = timestamp;3297if(cb->cutoff_tz)3298*cb->cutoff_tz = tz;3299if(cb->cutoff_cnt)3300*cb->cutoff_cnt = cb->reccnt;3301hashcpy(cb->sha1, osha1);3302if(is_null_sha1(cb->sha1))3303hashcpy(cb->sha1, nsha1);3304/* We just want the first entry */3305return1;3306}33073308intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3309unsigned char*sha1,char**msg,3310unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3311{3312struct read_ref_at_cb cb;33133314memset(&cb,0,sizeof(cb));3315 cb.refname = refname;3316 cb.at_time = at_time;3317 cb.cnt = cnt;3318 cb.msg = msg;3319 cb.cutoff_time = cutoff_time;3320 cb.cutoff_tz = cutoff_tz;3321 cb.cutoff_cnt = cutoff_cnt;3322 cb.sha1 = sha1;33233324for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);33253326if(!cb.reccnt) {3327if(flags & GET_SHA1_QUIETLY)3328exit(128);3329else3330die("Log for%sis empty.", refname);3331}3332if(cb.found_it)3333return0;33343335for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);33363337return1;3338}33393340intreflog_exists(const char*refname)3341{3342struct stat st;33433344return!lstat(git_path("logs/%s", refname), &st) &&3345S_ISREG(st.st_mode);3346}33473348intdelete_reflog(const char*refname)3349{3350returnremove_path(git_path("logs/%s", refname));3351}33523353static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3354{3355unsigned char osha1[20], nsha1[20];3356char*email_end, *message;3357unsigned long timestamp;3358int tz;33593360/* old SP new SP name <email> SP time TAB msg LF */3361if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3362get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3363get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3364!(email_end =strchr(sb->buf +82,'>')) ||3365 email_end[1] !=' '||3366!(timestamp =strtoul(email_end +2, &message,10)) ||3367!message || message[0] !=' '||3368(message[1] !='+'&& message[1] !='-') ||3369!isdigit(message[2]) || !isdigit(message[3]) ||3370!isdigit(message[4]) || !isdigit(message[5]))3371return0;/* corrupt? */3372 email_end[1] ='\0';3373 tz =strtol(message +1, NULL,10);3374if(message[6] !='\t')3375 message +=6;3376else3377 message +=7;3378returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3379}33803381static char*find_beginning_of_line(char*bob,char*scan)3382{3383while(bob < scan && *(--scan) !='\n')3384;/* keep scanning backwards */3385/*3386 * Return either beginning of the buffer, or LF at the end of3387 * the previous line.3388 */3389return scan;3390}33913392intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3393{3394struct strbuf sb = STRBUF_INIT;3395FILE*logfp;3396long pos;3397int ret =0, at_tail =1;33983399 logfp =fopen(git_path("logs/%s", refname),"r");3400if(!logfp)3401return-1;34023403/* Jump to the end */3404if(fseek(logfp,0, SEEK_END) <0)3405returnerror("cannot seek back reflog for%s:%s",3406 refname,strerror(errno));3407 pos =ftell(logfp);3408while(!ret &&0< pos) {3409int cnt;3410size_t nread;3411char buf[BUFSIZ];3412char*endp, *scanp;34133414/* Fill next block from the end */3415 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3416if(fseek(logfp, pos - cnt, SEEK_SET))3417returnerror("cannot seek back reflog for%s:%s",3418 refname,strerror(errno));3419 nread =fread(buf, cnt,1, logfp);3420if(nread !=1)3421returnerror("cannot read%dbytes from reflog for%s:%s",3422 cnt, refname,strerror(errno));3423 pos -= cnt;34243425 scanp = endp = buf + cnt;3426if(at_tail && scanp[-1] =='\n')3427/* Looking at the final LF at the end of the file */3428 scanp--;3429 at_tail =0;34303431while(buf < scanp) {3432/*3433 * terminating LF of the previous line, or the beginning3434 * of the buffer.3435 */3436char*bp;34373438 bp =find_beginning_of_line(buf, scanp);34393440if(*bp !='\n') {3441strbuf_splice(&sb,0,0, buf, endp - buf);3442if(pos)3443break;/* need to fill another block */3444 scanp = buf -1;/* leave loop */3445}else{3446/*3447 * (bp + 1) thru endp is the beginning of the3448 * current line we have in sb3449 */3450strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3451 scanp = bp;3452 endp = bp +1;3453}3454 ret =show_one_reflog_ent(&sb, fn, cb_data);3455strbuf_reset(&sb);3456if(ret)3457break;3458}34593460}3461if(!ret && sb.len)3462 ret =show_one_reflog_ent(&sb, fn, cb_data);34633464fclose(logfp);3465strbuf_release(&sb);3466return ret;3467}34683469intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3470{3471FILE*logfp;3472struct strbuf sb = STRBUF_INIT;3473int ret =0;34743475 logfp =fopen(git_path("logs/%s", refname),"r");3476if(!logfp)3477return-1;34783479while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3480 ret =show_one_reflog_ent(&sb, fn, cb_data);3481fclose(logfp);3482strbuf_release(&sb);3483return ret;3484}3485/*3486 * Call fn for each reflog in the namespace indicated by name. name3487 * must be empty or end with '/'. Name will be used as a scratch3488 * space, but its contents will be restored before return.3489 */3490static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3491{3492DIR*d =opendir(git_path("logs/%s", name->buf));3493int retval =0;3494struct dirent *de;3495int oldlen = name->len;34963497if(!d)3498return name->len ? errno :0;34993500while((de =readdir(d)) != NULL) {3501struct stat st;35023503if(de->d_name[0] =='.')3504continue;3505if(ends_with(de->d_name,".lock"))3506continue;3507strbuf_addstr(name, de->d_name);3508if(stat(git_path("logs/%s", name->buf), &st) <0) {3509;/* silently ignore */3510}else{3511if(S_ISDIR(st.st_mode)) {3512strbuf_addch(name,'/');3513 retval =do_for_each_reflog(name, fn, cb_data);3514}else{3515unsigned char sha1[20];3516if(read_ref_full(name->buf,0, sha1, NULL))3517 retval =error("bad ref for%s", name->buf);3518else3519 retval =fn(name->buf, sha1,0, cb_data);3520}3521if(retval)3522break;3523}3524strbuf_setlen(name, oldlen);3525}3526closedir(d);3527return retval;3528}35293530intfor_each_reflog(each_ref_fn fn,void*cb_data)3531{3532int retval;3533struct strbuf name;3534strbuf_init(&name, PATH_MAX);3535 retval =do_for_each_reflog(&name, fn, cb_data);3536strbuf_release(&name);3537return retval;3538}35393540/**3541 * Information needed for a single ref update. Set new_sha1 to the3542 * new value or to zero to delete the ref. To check the old value3543 * while locking the ref, set have_old to 1 and set old_sha1 to the3544 * value or to zero to ensure the ref does not exist before update.3545 */3546struct ref_update {3547unsigned char new_sha1[20];3548unsigned char old_sha1[20];3549int flags;/* REF_NODEREF? */3550int have_old;/* 1 if old_sha1 is valid, 0 otherwise */3551struct ref_lock *lock;3552int type;3553char*msg;3554const char refname[FLEX_ARRAY];3555};35563557/*3558 * Transaction states.3559 * OPEN: The transaction is in a valid state and can accept new updates.3560 * An OPEN transaction can be committed.3561 * CLOSED: A closed transaction is no longer active and no other operations3562 * than free can be used on it in this state.3563 * A transaction can either become closed by successfully committing3564 * an active transaction or if there is a failure while building3565 * the transaction thus rendering it failed/inactive.3566 */3567enum ref_transaction_state {3568 REF_TRANSACTION_OPEN =0,3569 REF_TRANSACTION_CLOSED =13570};35713572/*3573 * Data structure for holding a reference transaction, which can3574 * consist of checks and updates to multiple references, carried out3575 * as atomically as possible. This structure is opaque to callers.3576 */3577struct ref_transaction {3578struct ref_update **updates;3579size_t alloc;3580size_t nr;3581enum ref_transaction_state state;3582};35833584struct ref_transaction *ref_transaction_begin(struct strbuf *err)3585{3586assert(err);35873588returnxcalloc(1,sizeof(struct ref_transaction));3589}35903591voidref_transaction_free(struct ref_transaction *transaction)3592{3593int i;35943595if(!transaction)3596return;35973598for(i =0; i < transaction->nr; i++) {3599free(transaction->updates[i]->msg);3600free(transaction->updates[i]);3601}3602free(transaction->updates);3603free(transaction);3604}36053606static struct ref_update *add_update(struct ref_transaction *transaction,3607const char*refname)3608{3609size_t len =strlen(refname);3610struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);36113612strcpy((char*)update->refname, refname);3613ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3614 transaction->updates[transaction->nr++] = update;3615return update;3616}36173618intref_transaction_update(struct ref_transaction *transaction,3619const char*refname,3620const unsigned char*new_sha1,3621const unsigned char*old_sha1,3622int flags,int have_old,const char*msg,3623struct strbuf *err)3624{3625struct ref_update *update;36263627assert(err);36283629if(transaction->state != REF_TRANSACTION_OPEN)3630die("BUG: update called for transaction that is not open");36313632if(have_old && !old_sha1)3633die("BUG: have_old is true but old_sha1 is NULL");36343635if(!is_null_sha1(new_sha1) &&3636check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3637strbuf_addf(err,"refusing to update ref with bad name%s",3638 refname);3639return-1;3640}36413642 update =add_update(transaction, refname);3643hashcpy(update->new_sha1, new_sha1);3644 update->flags = flags;3645 update->have_old = have_old;3646if(have_old)3647hashcpy(update->old_sha1, old_sha1);3648if(msg)3649 update->msg =xstrdup(msg);3650return0;3651}36523653intref_transaction_create(struct ref_transaction *transaction,3654const char*refname,3655const unsigned char*new_sha1,3656int flags,const char*msg,3657struct strbuf *err)3658{3659struct ref_update *update;36603661assert(err);36623663if(transaction->state != REF_TRANSACTION_OPEN)3664die("BUG: create called for transaction that is not open");36653666if(!new_sha1 ||is_null_sha1(new_sha1))3667die("BUG: create ref with null new_sha1");36683669if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3670strbuf_addf(err,"refusing to create ref with bad name%s",3671 refname);3672return-1;3673}36743675 update =add_update(transaction, refname);36763677hashcpy(update->new_sha1, new_sha1);3678hashclr(update->old_sha1);3679 update->flags = flags;3680 update->have_old =1;3681if(msg)3682 update->msg =xstrdup(msg);3683return0;3684}36853686intref_transaction_delete(struct ref_transaction *transaction,3687const char*refname,3688const unsigned char*old_sha1,3689int flags,int have_old,const char*msg,3690struct strbuf *err)3691{3692struct ref_update *update;36933694assert(err);36953696if(transaction->state != REF_TRANSACTION_OPEN)3697die("BUG: delete called for transaction that is not open");36983699if(have_old && !old_sha1)3700die("BUG: have_old is true but old_sha1 is NULL");37013702 update =add_update(transaction, refname);3703 update->flags = flags;3704 update->have_old = have_old;3705if(have_old) {3706assert(!is_null_sha1(old_sha1));3707hashcpy(update->old_sha1, old_sha1);3708}3709if(msg)3710 update->msg =xstrdup(msg);3711return0;3712}37133714intupdate_ref(const char*action,const char*refname,3715const unsigned char*sha1,const unsigned char*oldval,3716int flags,enum action_on_err onerr)3717{3718struct ref_transaction *t;3719struct strbuf err = STRBUF_INIT;37203721 t =ref_transaction_begin(&err);3722if(!t ||3723ref_transaction_update(t, refname, sha1, oldval, flags,3724!!oldval, action, &err) ||3725ref_transaction_commit(t, &err)) {3726const char*str ="update_ref failed for ref '%s':%s";37273728ref_transaction_free(t);3729switch(onerr) {3730case UPDATE_REFS_MSG_ON_ERR:3731error(str, refname, err.buf);3732break;3733case UPDATE_REFS_DIE_ON_ERR:3734die(str, refname, err.buf);3735break;3736case UPDATE_REFS_QUIET_ON_ERR:3737break;3738}3739strbuf_release(&err);3740return1;3741}3742strbuf_release(&err);3743ref_transaction_free(t);3744return0;3745}37463747static intref_update_compare(const void*r1,const void*r2)3748{3749const struct ref_update *const*u1 = r1;3750const struct ref_update *const*u2 = r2;3751returnstrcmp((*u1)->refname, (*u2)->refname);3752}37533754static intref_update_reject_duplicates(struct ref_update **updates,int n,3755struct strbuf *err)3756{3757int i;37583759assert(err);37603761for(i =1; i < n; i++)3762if(!strcmp(updates[i -1]->refname, updates[i]->refname)) {3763strbuf_addf(err,3764"Multiple updates for ref '%s' not allowed.",3765 updates[i]->refname);3766return1;3767}3768return0;3769}37703771intref_transaction_commit(struct ref_transaction *transaction,3772struct strbuf *err)3773{3774int ret =0, delnum =0, i;3775const char**delnames;3776int n = transaction->nr;3777struct ref_update **updates = transaction->updates;37783779assert(err);37803781if(transaction->state != REF_TRANSACTION_OPEN)3782die("BUG: commit called for transaction that is not open");37833784if(!n) {3785 transaction->state = REF_TRANSACTION_CLOSED;3786return0;3787}37883789/* Allocate work space */3790 delnames =xmalloc(sizeof(*delnames) * n);37913792/* Copy, sort, and reject duplicate refs */3793qsort(updates, n,sizeof(*updates), ref_update_compare);3794if(ref_update_reject_duplicates(updates, n, err)) {3795 ret = TRANSACTION_GENERIC_ERROR;3796goto cleanup;3797}37983799/* Acquire all locks while verifying old values */3800for(i =0; i < n; i++) {3801struct ref_update *update = updates[i];3802int flags = update->flags;38033804if(is_null_sha1(update->new_sha1))3805 flags |= REF_DELETING;3806 update->lock =lock_ref_sha1_basic(update->refname,3807(update->have_old ?3808 update->old_sha1 :3809 NULL),3810 NULL,3811 flags,3812&update->type);3813if(!update->lock) {3814 ret = (errno == ENOTDIR)3815? TRANSACTION_NAME_CONFLICT3816: TRANSACTION_GENERIC_ERROR;3817strbuf_addf(err,"Cannot lock the ref '%s'.",3818 update->refname);3819goto cleanup;3820}3821}38223823/* Perform updates first so live commits remain referenced */3824for(i =0; i < n; i++) {3825struct ref_update *update = updates[i];38263827if(!is_null_sha1(update->new_sha1)) {3828if(write_ref_sha1(update->lock, update->new_sha1,3829 update->msg)) {3830 update->lock = NULL;/* freed by write_ref_sha1 */3831strbuf_addf(err,"Cannot update the ref '%s'.",3832 update->refname);3833 ret = TRANSACTION_GENERIC_ERROR;3834goto cleanup;3835}3836 update->lock = NULL;/* freed by write_ref_sha1 */3837}3838}38393840/* Perform deletes now that updates are safely completed */3841for(i =0; i < n; i++) {3842struct ref_update *update = updates[i];38433844if(update->lock) {3845if(delete_ref_loose(update->lock, update->type, err)) {3846 ret = TRANSACTION_GENERIC_ERROR;3847goto cleanup;3848}38493850if(!(update->flags & REF_ISPRUNING))3851 delnames[delnum++] = update->lock->ref_name;3852}3853}38543855if(repack_without_refs(delnames, delnum, err)) {3856 ret = TRANSACTION_GENERIC_ERROR;3857goto cleanup;3858}3859for(i =0; i < delnum; i++)3860unlink_or_warn(git_path("logs/%s", delnames[i]));3861clear_loose_ref_cache(&ref_cache);38623863cleanup:3864 transaction->state = REF_TRANSACTION_CLOSED;38653866for(i =0; i < n; i++)3867if(updates[i]->lock)3868unlock_ref(updates[i]->lock);3869free(delnames);3870return ret;3871}38723873char*shorten_unambiguous_ref(const char*refname,int strict)3874{3875int i;3876static char**scanf_fmts;3877static int nr_rules;3878char*short_name;38793880if(!nr_rules) {3881/*3882 * Pre-generate scanf formats from ref_rev_parse_rules[].3883 * Generate a format suitable for scanf from a3884 * ref_rev_parse_rules rule by interpolating "%s" at the3885 * location of the "%.*s".3886 */3887size_t total_len =0;3888size_t offset =0;38893890/* the rule list is NULL terminated, count them first */3891for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3892/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3893 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;38943895 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);38963897 offset =0;3898for(i =0; i < nr_rules; i++) {3899assert(offset < total_len);3900 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;3901 offset +=snprintf(scanf_fmts[i], total_len - offset,3902 ref_rev_parse_rules[i],2,"%s") +1;3903}3904}39053906/* bail out if there are no rules */3907if(!nr_rules)3908returnxstrdup(refname);39093910/* buffer for scanf result, at most refname must fit */3911 short_name =xstrdup(refname);39123913/* skip first rule, it will always match */3914for(i = nr_rules -1; i >0; --i) {3915int j;3916int rules_to_fail = i;3917int short_name_len;39183919if(1!=sscanf(refname, scanf_fmts[i], short_name))3920continue;39213922 short_name_len =strlen(short_name);39233924/*3925 * in strict mode, all (except the matched one) rules3926 * must fail to resolve to a valid non-ambiguous ref3927 */3928if(strict)3929 rules_to_fail = nr_rules;39303931/*3932 * check if the short name resolves to a valid ref,3933 * but use only rules prior to the matched one3934 */3935for(j =0; j < rules_to_fail; j++) {3936const char*rule = ref_rev_parse_rules[j];3937char refname[PATH_MAX];39383939/* skip matched rule */3940if(i == j)3941continue;39423943/*3944 * the short name is ambiguous, if it resolves3945 * (with this previous rule) to a valid ref3946 * read_ref() returns 0 on success3947 */3948mksnpath(refname,sizeof(refname),3949 rule, short_name_len, short_name);3950if(ref_exists(refname))3951break;3952}39533954/*3955 * short name is non-ambiguous if all previous rules3956 * haven't resolved to a valid ref3957 */3958if(j == rules_to_fail)3959return short_name;3960}39613962free(short_name);3963returnxstrdup(refname);3964}39653966static struct string_list *hide_refs;39673968intparse_hide_refs_config(const char*var,const char*value,const char*section)3969{3970if(!strcmp("transfer.hiderefs", var) ||3971/* NEEDSWORK: use parse_config_key() once both are merged */3972(starts_with(var, section) && var[strlen(section)] =='.'&&3973!strcmp(var +strlen(section),".hiderefs"))) {3974char*ref;3975int len;39763977if(!value)3978returnconfig_error_nonbool(var);3979 ref =xstrdup(value);3980 len =strlen(ref);3981while(len && ref[len -1] =='/')3982 ref[--len] ='\0';3983if(!hide_refs) {3984 hide_refs =xcalloc(1,sizeof(*hide_refs));3985 hide_refs->strdup_strings =1;3986}3987string_list_append(hide_refs, ref);3988}3989return0;3990}39913992intref_is_hidden(const char*refname)3993{3994struct string_list_item *item;39953996if(!hide_refs)3997return0;3998for_each_string_list_item(item, hide_refs) {3999int len;4000if(!starts_with(refname, item->string))4001continue;4002 len =strlen(item->string);4003if(!refname[len] || refname[len] =='/')4004return1;4005}4006return0;4007}