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 9struct ref_lock { 10char*ref_name; 11char*orig_ref_name; 12struct lock_file *lk; 13unsigned char old_sha1[20]; 14int lock_fd; 15}; 16 17/* 18 * How to handle various characters in refnames: 19 * 0: An acceptable character for refs 20 * 1: End-of-component 21 * 2: ., look for a preceding . to reject .. in refs 22 * 3: {, look for a preceding @ to reject @{ in refs 23 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 24 */ 25static unsigned char refname_disposition[256] = { 261,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 274,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 284,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 290,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 300,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 310,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 320,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 330,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 34}; 35 36/* 37 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 38 * refs (i.e., because the reference is about to be deleted anyway). 39 */ 40#define REF_DELETING 0x02 41 42/* 43 * Used as a flag in ref_update::flags when a loose ref is being 44 * pruned. 45 */ 46#define REF_ISPRUNING 0x04 47 48/* 49 * Used as a flag in ref_update::flags when the reference should be 50 * updated to new_sha1. 51 */ 52#define REF_HAVE_NEW 0x08 53 54/* 55 * Used as a flag in ref_update::flags when old_sha1 should be 56 * checked. 57 */ 58#define REF_HAVE_OLD 0x10 59 60/* 61 * Used as a flag in ref_update::flags when the lockfile needs to be 62 * committed. 63 */ 64#define REF_NEEDS_COMMIT 0x20 65 66/* 67 * Try to read one refname component from the front of refname. 68 * Return the length of the component found, or -1 if the component is 69 * not legal. It is legal if it is something reasonable to have under 70 * ".git/refs/"; We do not like it if: 71 * 72 * - any path component of it begins with ".", or 73 * - it has double dots "..", or 74 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 75 * - it ends with a "/". 76 * - it ends with ".lock" 77 * - it contains a "\" (backslash) 78 */ 79static intcheck_refname_component(const char*refname,int flags) 80{ 81const char*cp; 82char last ='\0'; 83 84for(cp = refname; ; cp++) { 85int ch = *cp &255; 86unsigned char disp = refname_disposition[ch]; 87switch(disp) { 88case1: 89goto out; 90case2: 91if(last =='.') 92return-1;/* Refname contains "..". */ 93break; 94case3: 95if(last =='@') 96return-1;/* Refname contains "@{". */ 97break; 98case4: 99return-1; 100} 101 last = ch; 102} 103out: 104if(cp == refname) 105return0;/* Component has zero length. */ 106if(refname[0] =='.') 107return-1;/* Component starts with '.'. */ 108if(cp - refname >= LOCK_SUFFIX_LEN && 109!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 110return-1;/* Refname ends with ".lock". */ 111return cp - refname; 112} 113 114intcheck_refname_format(const char*refname,int flags) 115{ 116int component_len, component_count =0; 117 118if(!strcmp(refname,"@")) 119/* Refname is a single character '@'. */ 120return-1; 121 122while(1) { 123/* We are at the start of a path component. */ 124 component_len =check_refname_component(refname, flags); 125if(component_len <=0) { 126if((flags & REFNAME_REFSPEC_PATTERN) && 127 refname[0] =='*'&& 128(refname[1] =='\0'|| refname[1] =='/')) { 129/* Accept one wildcard as a full refname component. */ 130 flags &= ~REFNAME_REFSPEC_PATTERN; 131 component_len =1; 132}else{ 133return-1; 134} 135} 136 component_count++; 137if(refname[component_len] =='\0') 138break; 139/* Skip to next component. */ 140 refname += component_len +1; 141} 142 143if(refname[component_len -1] =='.') 144return-1;/* Refname ends with '.'. */ 145if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 146return-1;/* Refname has only one component. */ 147return0; 148} 149 150struct ref_entry; 151 152/* 153 * Information used (along with the information in ref_entry) to 154 * describe a single cached reference. This data structure only 155 * occurs embedded in a union in struct ref_entry, and only when 156 * (ref_entry->flag & REF_DIR) is zero. 157 */ 158struct ref_value { 159/* 160 * The name of the object to which this reference resolves 161 * (which may be a tag object). If REF_ISBROKEN, this is 162 * null. If REF_ISSYMREF, then this is the name of the object 163 * referred to by the last reference in the symlink chain. 164 */ 165unsigned char sha1[20]; 166 167/* 168 * If REF_KNOWS_PEELED, then this field holds the peeled value 169 * of this reference, or null if the reference is known not to 170 * be peelable. See the documentation for peel_ref() for an 171 * exact definition of "peelable". 172 */ 173unsigned char peeled[20]; 174}; 175 176struct ref_cache; 177 178/* 179 * Information used (along with the information in ref_entry) to 180 * describe a level in the hierarchy of references. This data 181 * structure only occurs embedded in a union in struct ref_entry, and 182 * only when (ref_entry.flag & REF_DIR) is set. In that case, 183 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 184 * in the directory have already been read: 185 * 186 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 187 * or packed references, already read. 188 * 189 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 190 * references that hasn't been read yet (nor has any of its 191 * subdirectories). 192 * 193 * Entries within a directory are stored within a growable array of 194 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 195 * sorted are sorted by their component name in strcmp() order and the 196 * remaining entries are unsorted. 197 * 198 * Loose references are read lazily, one directory at a time. When a 199 * directory of loose references is read, then all of the references 200 * in that directory are stored, and REF_INCOMPLETE stubs are created 201 * for any subdirectories, but the subdirectories themselves are not 202 * read. The reading is triggered by get_ref_dir(). 203 */ 204struct ref_dir { 205int nr, alloc; 206 207/* 208 * Entries with index 0 <= i < sorted are sorted by name. New 209 * entries are appended to the list unsorted, and are sorted 210 * only when required; thus we avoid the need to sort the list 211 * after the addition of every reference. 212 */ 213int sorted; 214 215/* A pointer to the ref_cache that contains this ref_dir. */ 216struct ref_cache *ref_cache; 217 218struct ref_entry **entries; 219}; 220 221/* 222 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 223 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 224 * public values; see refs.h. 225 */ 226 227/* 228 * The field ref_entry->u.value.peeled of this value entry contains 229 * the correct peeled value for the reference, which might be 230 * null_sha1 if the reference is not a tag or if it is broken. 231 */ 232#define REF_KNOWS_PEELED 0x10 233 234/* ref_entry represents a directory of references */ 235#define REF_DIR 0x20 236 237/* 238 * Entry has not yet been read from disk (used only for REF_DIR 239 * entries representing loose references) 240 */ 241#define REF_INCOMPLETE 0x40 242 243/* 244 * A ref_entry represents either a reference or a "subdirectory" of 245 * references. 246 * 247 * Each directory in the reference namespace is represented by a 248 * ref_entry with (flags & REF_DIR) set and containing a subdir member 249 * that holds the entries in that directory that have been read so 250 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 251 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 252 * used for loose reference directories. 253 * 254 * References are represented by a ref_entry with (flags & REF_DIR) 255 * unset and a value member that describes the reference's value. The 256 * flag member is at the ref_entry level, but it is also needed to 257 * interpret the contents of the value field (in other words, a 258 * ref_value object is not very much use without the enclosing 259 * ref_entry). 260 * 261 * Reference names cannot end with slash and directories' names are 262 * always stored with a trailing slash (except for the top-level 263 * directory, which is always denoted by ""). This has two nice 264 * consequences: (1) when the entries in each subdir are sorted 265 * lexicographically by name (as they usually are), the references in 266 * a whole tree can be generated in lexicographic order by traversing 267 * the tree in left-to-right, depth-first order; (2) the names of 268 * references and subdirectories cannot conflict, and therefore the 269 * presence of an empty subdirectory does not block the creation of a 270 * similarly-named reference. (The fact that reference names with the 271 * same leading components can conflict *with each other* is a 272 * separate issue that is regulated by verify_refname_available().) 273 * 274 * Please note that the name field contains the fully-qualified 275 * reference (or subdirectory) name. Space could be saved by only 276 * storing the relative names. But that would require the full names 277 * to be generated on the fly when iterating in do_for_each_ref(), and 278 * would break callback functions, who have always been able to assume 279 * that the name strings that they are passed will not be freed during 280 * the iteration. 281 */ 282struct ref_entry { 283unsigned char flag;/* ISSYMREF? ISPACKED? */ 284union{ 285struct ref_value value;/* if not (flags&REF_DIR) */ 286struct ref_dir subdir;/* if (flags&REF_DIR) */ 287} u; 288/* 289 * The full name of the reference (e.g., "refs/heads/master") 290 * or the full name of the directory with a trailing slash 291 * (e.g., "refs/heads/"): 292 */ 293char name[FLEX_ARRAY]; 294}; 295 296static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 297 298static struct ref_dir *get_ref_dir(struct ref_entry *entry) 299{ 300struct ref_dir *dir; 301assert(entry->flag & REF_DIR); 302 dir = &entry->u.subdir; 303if(entry->flag & REF_INCOMPLETE) { 304read_loose_refs(entry->name, dir); 305 entry->flag &= ~REF_INCOMPLETE; 306} 307return dir; 308} 309 310/* 311 * Check if a refname is safe. 312 * For refs that start with "refs/" we consider it safe as long they do 313 * not try to resolve to outside of refs/. 314 * 315 * For all other refs we only consider them safe iff they only contain 316 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 317 * "config"). 318 */ 319static intrefname_is_safe(const char*refname) 320{ 321if(starts_with(refname,"refs/")) { 322char*buf; 323int result; 324 325 buf =xmalloc(strlen(refname) +1); 326/* 327 * Does the refname try to escape refs/? 328 * For example: refs/foo/../bar is safe but refs/foo/../../bar 329 * is not. 330 */ 331 result = !normalize_path_copy(buf, refname +strlen("refs/")); 332free(buf); 333return result; 334} 335while(*refname) { 336if(!isupper(*refname) && *refname !='_') 337return0; 338 refname++; 339} 340return1; 341} 342 343static struct ref_entry *create_ref_entry(const char*refname, 344const unsigned char*sha1,int flag, 345int check_name) 346{ 347int len; 348struct ref_entry *ref; 349 350if(check_name && 351check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 352die("Reference has invalid format: '%s'", refname); 353if(!check_name && !refname_is_safe(refname)) 354die("Reference has invalid name: '%s'", refname); 355 len =strlen(refname) +1; 356 ref =xmalloc(sizeof(struct ref_entry) + len); 357hashcpy(ref->u.value.sha1, sha1); 358hashclr(ref->u.value.peeled); 359memcpy(ref->name, refname, len); 360 ref->flag = flag; 361return ref; 362} 363 364static voidclear_ref_dir(struct ref_dir *dir); 365 366static voidfree_ref_entry(struct ref_entry *entry) 367{ 368if(entry->flag & REF_DIR) { 369/* 370 * Do not use get_ref_dir() here, as that might 371 * trigger the reading of loose refs. 372 */ 373clear_ref_dir(&entry->u.subdir); 374} 375free(entry); 376} 377 378/* 379 * Add a ref_entry to the end of dir (unsorted). Entry is always 380 * stored directly in dir; no recursion into subdirectories is 381 * done. 382 */ 383static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 384{ 385ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 386 dir->entries[dir->nr++] = entry; 387/* optimize for the case that entries are added in order */ 388if(dir->nr ==1|| 389(dir->nr == dir->sorted +1&& 390strcmp(dir->entries[dir->nr -2]->name, 391 dir->entries[dir->nr -1]->name) <0)) 392 dir->sorted = dir->nr; 393} 394 395/* 396 * Clear and free all entries in dir, recursively. 397 */ 398static voidclear_ref_dir(struct ref_dir *dir) 399{ 400int i; 401for(i =0; i < dir->nr; i++) 402free_ref_entry(dir->entries[i]); 403free(dir->entries); 404 dir->sorted = dir->nr = dir->alloc =0; 405 dir->entries = NULL; 406} 407 408/* 409 * Create a struct ref_entry object for the specified dirname. 410 * dirname is the name of the directory with a trailing slash (e.g., 411 * "refs/heads/") or "" for the top-level directory. 412 */ 413static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 414const char*dirname,size_t len, 415int incomplete) 416{ 417struct ref_entry *direntry; 418 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 419memcpy(direntry->name, dirname, len); 420 direntry->name[len] ='\0'; 421 direntry->u.subdir.ref_cache = ref_cache; 422 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 423return direntry; 424} 425 426static intref_entry_cmp(const void*a,const void*b) 427{ 428struct ref_entry *one = *(struct ref_entry **)a; 429struct ref_entry *two = *(struct ref_entry **)b; 430returnstrcmp(one->name, two->name); 431} 432 433static voidsort_ref_dir(struct ref_dir *dir); 434 435struct string_slice { 436size_t len; 437const char*str; 438}; 439 440static intref_entry_cmp_sslice(const void*key_,const void*ent_) 441{ 442const struct string_slice *key = key_; 443const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 444int cmp =strncmp(key->str, ent->name, key->len); 445if(cmp) 446return cmp; 447return'\0'- (unsigned char)ent->name[key->len]; 448} 449 450/* 451 * Return the index of the entry with the given refname from the 452 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 453 * no such entry is found. dir must already be complete. 454 */ 455static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 456{ 457struct ref_entry **r; 458struct string_slice key; 459 460if(refname == NULL || !dir->nr) 461return-1; 462 463sort_ref_dir(dir); 464 key.len = len; 465 key.str = refname; 466 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 467 ref_entry_cmp_sslice); 468 469if(r == NULL) 470return-1; 471 472return r - dir->entries; 473} 474 475/* 476 * Search for a directory entry directly within dir (without 477 * recursing). Sort dir if necessary. subdirname must be a directory 478 * name (i.e., end in '/'). If mkdir is set, then create the 479 * directory if it is missing; otherwise, return NULL if the desired 480 * directory cannot be found. dir must already be complete. 481 */ 482static struct ref_dir *search_for_subdir(struct ref_dir *dir, 483const char*subdirname,size_t len, 484int mkdir) 485{ 486int entry_index =search_ref_dir(dir, subdirname, len); 487struct ref_entry *entry; 488if(entry_index == -1) { 489if(!mkdir) 490return NULL; 491/* 492 * Since dir is complete, the absence of a subdir 493 * means that the subdir really doesn't exist; 494 * therefore, create an empty record for it but mark 495 * the record complete. 496 */ 497 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 498add_entry_to_dir(dir, entry); 499}else{ 500 entry = dir->entries[entry_index]; 501} 502returnget_ref_dir(entry); 503} 504 505/* 506 * If refname is a reference name, find the ref_dir within the dir 507 * tree that should hold refname. If refname is a directory name 508 * (i.e., ends in '/'), then return that ref_dir itself. dir must 509 * represent the top-level directory and must already be complete. 510 * Sort ref_dirs and recurse into subdirectories as necessary. If 511 * mkdir is set, then create any missing directories; otherwise, 512 * return NULL if the desired directory cannot be found. 513 */ 514static struct ref_dir *find_containing_dir(struct ref_dir *dir, 515const char*refname,int mkdir) 516{ 517const char*slash; 518for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 519size_t dirnamelen = slash - refname +1; 520struct ref_dir *subdir; 521 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 522if(!subdir) { 523 dir = NULL; 524break; 525} 526 dir = subdir; 527} 528 529return dir; 530} 531 532/* 533 * Find the value entry with the given name in dir, sorting ref_dirs 534 * and recursing into subdirectories as necessary. If the name is not 535 * found or it corresponds to a directory entry, return NULL. 536 */ 537static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 538{ 539int entry_index; 540struct ref_entry *entry; 541 dir =find_containing_dir(dir, refname,0); 542if(!dir) 543return NULL; 544 entry_index =search_ref_dir(dir, refname,strlen(refname)); 545if(entry_index == -1) 546return NULL; 547 entry = dir->entries[entry_index]; 548return(entry->flag & REF_DIR) ? NULL : entry; 549} 550 551/* 552 * Remove the entry with the given name from dir, recursing into 553 * subdirectories as necessary. If refname is the name of a directory 554 * (i.e., ends with '/'), then remove the directory and its contents. 555 * If the removal was successful, return the number of entries 556 * remaining in the directory entry that contained the deleted entry. 557 * If the name was not found, return -1. Please note that this 558 * function only deletes the entry from the cache; it does not delete 559 * it from the filesystem or ensure that other cache entries (which 560 * might be symbolic references to the removed entry) are updated. 561 * Nor does it remove any containing dir entries that might be made 562 * empty by the removal. dir must represent the top-level directory 563 * and must already be complete. 564 */ 565static intremove_entry(struct ref_dir *dir,const char*refname) 566{ 567int refname_len =strlen(refname); 568int entry_index; 569struct ref_entry *entry; 570int is_dir = refname[refname_len -1] =='/'; 571if(is_dir) { 572/* 573 * refname represents a reference directory. Remove 574 * the trailing slash; otherwise we will get the 575 * directory *representing* refname rather than the 576 * one *containing* it. 577 */ 578char*dirname =xmemdupz(refname, refname_len -1); 579 dir =find_containing_dir(dir, dirname,0); 580free(dirname); 581}else{ 582 dir =find_containing_dir(dir, refname,0); 583} 584if(!dir) 585return-1; 586 entry_index =search_ref_dir(dir, refname, refname_len); 587if(entry_index == -1) 588return-1; 589 entry = dir->entries[entry_index]; 590 591memmove(&dir->entries[entry_index], 592&dir->entries[entry_index +1], 593(dir->nr - entry_index -1) *sizeof(*dir->entries) 594); 595 dir->nr--; 596if(dir->sorted > entry_index) 597 dir->sorted--; 598free_ref_entry(entry); 599return dir->nr; 600} 601 602/* 603 * Add a ref_entry to the ref_dir (unsorted), recursing into 604 * subdirectories as necessary. dir must represent the top-level 605 * directory. Return 0 on success. 606 */ 607static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 608{ 609 dir =find_containing_dir(dir, ref->name,1); 610if(!dir) 611return-1; 612add_entry_to_dir(dir, ref); 613return0; 614} 615 616/* 617 * Emit a warning and return true iff ref1 and ref2 have the same name 618 * and the same sha1. Die if they have the same name but different 619 * sha1s. 620 */ 621static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 622{ 623if(strcmp(ref1->name, ref2->name)) 624return0; 625 626/* Duplicate name; make sure that they don't conflict: */ 627 628if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 629/* This is impossible by construction */ 630die("Reference directory conflict:%s", ref1->name); 631 632if(hashcmp(ref1->u.value.sha1, ref2->u.value.sha1)) 633die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 634 635warning("Duplicated ref:%s", ref1->name); 636return1; 637} 638 639/* 640 * Sort the entries in dir non-recursively (if they are not already 641 * sorted) and remove any duplicate entries. 642 */ 643static voidsort_ref_dir(struct ref_dir *dir) 644{ 645int i, j; 646struct ref_entry *last = NULL; 647 648/* 649 * This check also prevents passing a zero-length array to qsort(), 650 * which is a problem on some platforms. 651 */ 652if(dir->sorted == dir->nr) 653return; 654 655qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 656 657/* Remove any duplicates: */ 658for(i =0, j =0; j < dir->nr; j++) { 659struct ref_entry *entry = dir->entries[j]; 660if(last &&is_dup_ref(last, entry)) 661free_ref_entry(entry); 662else 663 last = dir->entries[i++] = entry; 664} 665 dir->sorted = dir->nr = i; 666} 667 668/* Include broken references in a do_for_each_ref*() iteration: */ 669#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 670 671/* 672 * Return true iff the reference described by entry can be resolved to 673 * an object in the database. Emit a warning if the referred-to 674 * object does not exist. 675 */ 676static intref_resolves_to_object(struct ref_entry *entry) 677{ 678if(entry->flag & REF_ISBROKEN) 679return0; 680if(!has_sha1_file(entry->u.value.sha1)) { 681error("%sdoes not point to a valid object!", entry->name); 682return0; 683} 684return1; 685} 686 687/* 688 * current_ref is a performance hack: when iterating over references 689 * using the for_each_ref*() functions, current_ref is set to the 690 * current reference's entry before calling the callback function. If 691 * the callback function calls peel_ref(), then peel_ref() first 692 * checks whether the reference to be peeled is the current reference 693 * (it usually is) and if so, returns that reference's peeled version 694 * if it is available. This avoids a refname lookup in a common case. 695 */ 696static struct ref_entry *current_ref; 697 698typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 699 700struct ref_entry_cb { 701const char*base; 702int trim; 703int flags; 704 each_ref_fn *fn; 705void*cb_data; 706}; 707 708/* 709 * Handle one reference in a do_for_each_ref*()-style iteration, 710 * calling an each_ref_fn for each entry. 711 */ 712static intdo_one_ref(struct ref_entry *entry,void*cb_data) 713{ 714struct ref_entry_cb *data = cb_data; 715struct ref_entry *old_current_ref; 716int retval; 717 718if(!starts_with(entry->name, data->base)) 719return0; 720 721if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 722!ref_resolves_to_object(entry)) 723return0; 724 725/* Store the old value, in case this is a recursive call: */ 726 old_current_ref = current_ref; 727 current_ref = entry; 728 retval = data->fn(entry->name + data->trim, entry->u.value.sha1, 729 entry->flag, data->cb_data); 730 current_ref = old_current_ref; 731return retval; 732} 733 734/* 735 * Call fn for each reference in dir that has index in the range 736 * offset <= index < dir->nr. Recurse into subdirectories that are in 737 * that index range, sorting them before iterating. This function 738 * does not sort dir itself; it should be sorted beforehand. fn is 739 * called for all references, including broken ones. 740 */ 741static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 742 each_ref_entry_fn fn,void*cb_data) 743{ 744int i; 745assert(dir->sorted == dir->nr); 746for(i = offset; i < dir->nr; i++) { 747struct ref_entry *entry = dir->entries[i]; 748int retval; 749if(entry->flag & REF_DIR) { 750struct ref_dir *subdir =get_ref_dir(entry); 751sort_ref_dir(subdir); 752 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 753}else{ 754 retval =fn(entry, cb_data); 755} 756if(retval) 757return retval; 758} 759return0; 760} 761 762/* 763 * Call fn for each reference in the union of dir1 and dir2, in order 764 * by refname. Recurse into subdirectories. If a value entry appears 765 * in both dir1 and dir2, then only process the version that is in 766 * dir2. The input dirs must already be sorted, but subdirs will be 767 * sorted as needed. fn is called for all references, including 768 * broken ones. 769 */ 770static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 771struct ref_dir *dir2, 772 each_ref_entry_fn fn,void*cb_data) 773{ 774int retval; 775int i1 =0, i2 =0; 776 777assert(dir1->sorted == dir1->nr); 778assert(dir2->sorted == dir2->nr); 779while(1) { 780struct ref_entry *e1, *e2; 781int cmp; 782if(i1 == dir1->nr) { 783returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 784} 785if(i2 == dir2->nr) { 786returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 787} 788 e1 = dir1->entries[i1]; 789 e2 = dir2->entries[i2]; 790 cmp =strcmp(e1->name, e2->name); 791if(cmp ==0) { 792if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 793/* Both are directories; descend them in parallel. */ 794struct ref_dir *subdir1 =get_ref_dir(e1); 795struct ref_dir *subdir2 =get_ref_dir(e2); 796sort_ref_dir(subdir1); 797sort_ref_dir(subdir2); 798 retval =do_for_each_entry_in_dirs( 799 subdir1, subdir2, fn, cb_data); 800 i1++; 801 i2++; 802}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 803/* Both are references; ignore the one from dir1. */ 804 retval =fn(e2, cb_data); 805 i1++; 806 i2++; 807}else{ 808die("conflict between reference and directory:%s", 809 e1->name); 810} 811}else{ 812struct ref_entry *e; 813if(cmp <0) { 814 e = e1; 815 i1++; 816}else{ 817 e = e2; 818 i2++; 819} 820if(e->flag & REF_DIR) { 821struct ref_dir *subdir =get_ref_dir(e); 822sort_ref_dir(subdir); 823 retval =do_for_each_entry_in_dir( 824 subdir,0, fn, cb_data); 825}else{ 826 retval =fn(e, cb_data); 827} 828} 829if(retval) 830return retval; 831} 832} 833 834/* 835 * Load all of the refs from the dir into our in-memory cache. The hard work 836 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 837 * through all of the sub-directories. We do not even need to care about 838 * sorting, as traversal order does not matter to us. 839 */ 840static voidprime_ref_dir(struct ref_dir *dir) 841{ 842int i; 843for(i =0; i < dir->nr; i++) { 844struct ref_entry *entry = dir->entries[i]; 845if(entry->flag & REF_DIR) 846prime_ref_dir(get_ref_dir(entry)); 847} 848} 849 850struct nonmatching_ref_data { 851const struct string_list *skip; 852const char*conflicting_refname; 853}; 854 855static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 856{ 857struct nonmatching_ref_data *data = vdata; 858 859if(data->skip &&string_list_has_string(data->skip, entry->name)) 860return0; 861 862 data->conflicting_refname = entry->name; 863return1; 864} 865 866/* 867 * Return 0 if a reference named refname could be created without 868 * conflicting with the name of an existing reference in dir. 869 * Otherwise, return a negative value and write an explanation to err. 870 * If extras is non-NULL, it is a list of additional refnames with 871 * which refname is not allowed to conflict. If skip is non-NULL, 872 * ignore potential conflicts with refs in skip (e.g., because they 873 * are scheduled for deletion in the same operation). Behavior is 874 * undefined if the same name is listed in both extras and skip. 875 * 876 * Two reference names conflict if one of them exactly matches the 877 * leading components of the other; e.g., "refs/foo/bar" conflicts 878 * with both "refs/foo" and with "refs/foo/bar/baz" but not with 879 * "refs/foo/bar" or "refs/foo/barbados". 880 * 881 * extras and skip must be sorted. 882 */ 883static intverify_refname_available(const char*refname, 884const struct string_list *extras, 885const struct string_list *skip, 886struct ref_dir *dir, 887struct strbuf *err) 888{ 889const char*slash; 890int pos; 891struct strbuf dirname = STRBUF_INIT; 892int ret = -1; 893 894/* 895 * For the sake of comments in this function, suppose that 896 * refname is "refs/foo/bar". 897 */ 898 899assert(err); 900 901strbuf_grow(&dirname,strlen(refname) +1); 902for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 903/* Expand dirname to the new prefix, not including the trailing slash: */ 904strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 905 906/* 907 * We are still at a leading dir of the refname (e.g., 908 * "refs/foo"; if there is a reference with that name, 909 * it is a conflict, *unless* it is in skip. 910 */ 911if(dir) { 912 pos =search_ref_dir(dir, dirname.buf, dirname.len); 913if(pos >=0&& 914(!skip || !string_list_has_string(skip, dirname.buf))) { 915/* 916 * We found a reference whose name is 917 * a proper prefix of refname; e.g., 918 * "refs/foo", and is not in skip. 919 */ 920strbuf_addf(err,"'%s' exists; cannot create '%s'", 921 dirname.buf, refname); 922goto cleanup; 923} 924} 925 926if(extras &&string_list_has_string(extras, dirname.buf) && 927(!skip || !string_list_has_string(skip, dirname.buf))) { 928strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 929 refname, dirname.buf); 930goto cleanup; 931} 932 933/* 934 * Otherwise, we can try to continue our search with 935 * the next component. So try to look up the 936 * directory, e.g., "refs/foo/". If we come up empty, 937 * we know there is nothing under this whole prefix, 938 * but even in that case we still have to continue the 939 * search for conflicts with extras. 940 */ 941strbuf_addch(&dirname,'/'); 942if(dir) { 943 pos =search_ref_dir(dir, dirname.buf, dirname.len); 944if(pos <0) { 945/* 946 * There was no directory "refs/foo/", 947 * so there is nothing under this 948 * whole prefix. So there is no need 949 * to continue looking for conflicting 950 * references. But we need to continue 951 * looking for conflicting extras. 952 */ 953 dir = NULL; 954}else{ 955 dir =get_ref_dir(dir->entries[pos]); 956} 957} 958} 959 960/* 961 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 962 * There is no point in searching for a reference with that 963 * name, because a refname isn't considered to conflict with 964 * itself. But we still need to check for references whose 965 * names are in the "refs/foo/bar/" namespace, because they 966 * *do* conflict. 967 */ 968strbuf_addstr(&dirname, refname + dirname.len); 969strbuf_addch(&dirname,'/'); 970 971if(dir) { 972 pos =search_ref_dir(dir, dirname.buf, dirname.len); 973 974if(pos >=0) { 975/* 976 * We found a directory named "$refname/" 977 * (e.g., "refs/foo/bar/"). It is a problem 978 * iff it contains any ref that is not in 979 * "skip". 980 */ 981struct nonmatching_ref_data data; 982 983 data.skip = skip; 984 data.conflicting_refname = NULL; 985 dir =get_ref_dir(dir->entries[pos]); 986sort_ref_dir(dir); 987if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 988strbuf_addf(err,"'%s' exists; cannot create '%s'", 989 data.conflicting_refname, refname); 990goto cleanup; 991} 992} 993} 994 995if(extras) { 996/* 997 * Check for entries in extras that start with 998 * "$refname/". We do that by looking for the place 999 * where "$refname/" would be inserted in extras. If1000 * there is an entry at that position that starts with1001 * "$refname/" and is not in skip, then we have a1002 * conflict.1003 */1004for(pos =string_list_find_insert_index(extras, dirname.buf,0);1005 pos < extras->nr; pos++) {1006const char*extra_refname = extras->items[pos].string;10071008if(!starts_with(extra_refname, dirname.buf))1009break;10101011if(!skip || !string_list_has_string(skip, extra_refname)) {1012strbuf_addf(err,"cannot process '%s' and '%s' at the same time",1013 refname, extra_refname);1014goto cleanup;1015}1016}1017}10181019/* No conflicts were found */1020 ret =0;10211022cleanup:1023strbuf_release(&dirname);1024return ret;1025}10261027struct packed_ref_cache {1028struct ref_entry *root;10291030/*1031 * Count of references to the data structure in this instance,1032 * including the pointer from ref_cache::packed if any. The1033 * data will not be freed as long as the reference count is1034 * nonzero.1035 */1036unsigned int referrers;10371038/*1039 * Iff the packed-refs file associated with this instance is1040 * currently locked for writing, this points at the associated1041 * lock (which is owned by somebody else). The referrer count1042 * is also incremented when the file is locked and decremented1043 * when it is unlocked.1044 */1045struct lock_file *lock;10461047/* The metadata from when this packed-refs cache was read */1048struct stat_validity validity;1049};10501051/*1052 * Future: need to be in "struct repository"1053 * when doing a full libification.1054 */1055static struct ref_cache {1056struct ref_cache *next;1057struct ref_entry *loose;1058struct packed_ref_cache *packed;1059/*1060 * The submodule name, or "" for the main repo. We allocate1061 * length 1 rather than FLEX_ARRAY so that the main ref_cache1062 * is initialized correctly.1063 */1064char name[1];1065} ref_cache, *submodule_ref_caches;10661067/* Lock used for the main packed-refs file: */1068static struct lock_file packlock;10691070/*1071 * Increment the reference count of *packed_refs.1072 */1073static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1074{1075 packed_refs->referrers++;1076}10771078/*1079 * Decrease the reference count of *packed_refs. If it goes to zero,1080 * free *packed_refs and return true; otherwise return false.1081 */1082static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1083{1084if(!--packed_refs->referrers) {1085free_ref_entry(packed_refs->root);1086stat_validity_clear(&packed_refs->validity);1087free(packed_refs);1088return1;1089}else{1090return0;1091}1092}10931094static voidclear_packed_ref_cache(struct ref_cache *refs)1095{1096if(refs->packed) {1097struct packed_ref_cache *packed_refs = refs->packed;10981099if(packed_refs->lock)1100die("internal error: packed-ref cache cleared while locked");1101 refs->packed = NULL;1102release_packed_ref_cache(packed_refs);1103}1104}11051106static voidclear_loose_ref_cache(struct ref_cache *refs)1107{1108if(refs->loose) {1109free_ref_entry(refs->loose);1110 refs->loose = NULL;1111}1112}11131114static struct ref_cache *create_ref_cache(const char*submodule)1115{1116int len;1117struct ref_cache *refs;1118if(!submodule)1119 submodule ="";1120 len =strlen(submodule) +1;1121 refs =xcalloc(1,sizeof(struct ref_cache) + len);1122memcpy(refs->name, submodule, len);1123return refs;1124}11251126/*1127 * Return a pointer to a ref_cache for the specified submodule. For1128 * the main repository, use submodule==NULL. The returned structure1129 * will be allocated and initialized but not necessarily populated; it1130 * should not be freed.1131 */1132static struct ref_cache *get_ref_cache(const char*submodule)1133{1134struct ref_cache *refs;11351136if(!submodule || !*submodule)1137return&ref_cache;11381139for(refs = submodule_ref_caches; refs; refs = refs->next)1140if(!strcmp(submodule, refs->name))1141return refs;11421143 refs =create_ref_cache(submodule);1144 refs->next = submodule_ref_caches;1145 submodule_ref_caches = refs;1146return refs;1147}11481149/* The length of a peeled reference line in packed-refs, including EOL: */1150#define PEELED_LINE_LENGTH 4211511152/*1153 * The packed-refs header line that we write out. Perhaps other1154 * traits will be added later. The trailing space is required.1155 */1156static const char PACKED_REFS_HEADER[] =1157"# pack-refs with: peeled fully-peeled\n";11581159/*1160 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1161 * Return a pointer to the refname within the line (null-terminated),1162 * or NULL if there was a problem.1163 */1164static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1165{1166const char*ref;11671168/*1169 * 42: the answer to everything.1170 *1171 * In this case, it happens to be the answer to1172 * 40 (length of sha1 hex representation)1173 * +1 (space in between hex and name)1174 * +1 (newline at the end of the line)1175 */1176if(line->len <=42)1177return NULL;11781179if(get_sha1_hex(line->buf, sha1) <0)1180return NULL;1181if(!isspace(line->buf[40]))1182return NULL;11831184 ref = line->buf +41;1185if(isspace(*ref))1186return NULL;11871188if(line->buf[line->len -1] !='\n')1189return NULL;1190 line->buf[--line->len] =0;11911192return ref;1193}11941195/*1196 * Read f, which is a packed-refs file, into dir.1197 *1198 * A comment line of the form "# pack-refs with: " may contain zero or1199 * more traits. We interpret the traits as follows:1200 *1201 * No traits:1202 *1203 * Probably no references are peeled. But if the file contains a1204 * peeled value for a reference, we will use it.1205 *1206 * peeled:1207 *1208 * References under "refs/tags/", if they *can* be peeled, *are*1209 * peeled in this file. References outside of "refs/tags/" are1210 * probably not peeled even if they could have been, but if we find1211 * a peeled value for such a reference we will use it.1212 *1213 * fully-peeled:1214 *1215 * All references in the file that can be peeled are peeled.1216 * Inversely (and this is more important), any references in the1217 * file for which no peeled value is recorded is not peelable. This1218 * trait should typically be written alongside "peeled" for1219 * compatibility with older clients, but we do not require it1220 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1221 */1222static voidread_packed_refs(FILE*f,struct ref_dir *dir)1223{1224struct ref_entry *last = NULL;1225struct strbuf line = STRBUF_INIT;1226enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12271228while(strbuf_getwholeline(&line, f,'\n') != EOF) {1229unsigned char sha1[20];1230const char*refname;1231const char*traits;12321233if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1234if(strstr(traits," fully-peeled "))1235 peeled = PEELED_FULLY;1236else if(strstr(traits," peeled "))1237 peeled = PEELED_TAGS;1238/* perhaps other traits later as well */1239continue;1240}12411242 refname =parse_ref_line(&line, sha1);1243if(refname) {1244int flag = REF_ISPACKED;12451246if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1247hashclr(sha1);1248 flag |= REF_BAD_NAME | REF_ISBROKEN;1249}1250 last =create_ref_entry(refname, sha1, flag,0);1251if(peeled == PEELED_FULLY ||1252(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1253 last->flag |= REF_KNOWS_PEELED;1254add_ref(dir, last);1255continue;1256}1257if(last &&1258 line.buf[0] =='^'&&1259 line.len == PEELED_LINE_LENGTH &&1260 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1261!get_sha1_hex(line.buf +1, sha1)) {1262hashcpy(last->u.value.peeled, sha1);1263/*1264 * Regardless of what the file header said,1265 * we definitely know the value of *this*1266 * reference:1267 */1268 last->flag |= REF_KNOWS_PEELED;1269}1270}12711272strbuf_release(&line);1273}12741275/*1276 * Get the packed_ref_cache for the specified ref_cache, creating it1277 * if necessary.1278 */1279static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1280{1281const char*packed_refs_file;12821283if(*refs->name)1284 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1285else1286 packed_refs_file =git_path("packed-refs");12871288if(refs->packed &&1289!stat_validity_check(&refs->packed->validity, packed_refs_file))1290clear_packed_ref_cache(refs);12911292if(!refs->packed) {1293FILE*f;12941295 refs->packed =xcalloc(1,sizeof(*refs->packed));1296acquire_packed_ref_cache(refs->packed);1297 refs->packed->root =create_dir_entry(refs,"",0,0);1298 f =fopen(packed_refs_file,"r");1299if(f) {1300stat_validity_update(&refs->packed->validity,fileno(f));1301read_packed_refs(f,get_ref_dir(refs->packed->root));1302fclose(f);1303}1304}1305return refs->packed;1306}13071308static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1309{1310returnget_ref_dir(packed_ref_cache->root);1311}13121313static struct ref_dir *get_packed_refs(struct ref_cache *refs)1314{1315returnget_packed_ref_dir(get_packed_ref_cache(refs));1316}13171318voidadd_packed_ref(const char*refname,const unsigned char*sha1)1319{1320struct packed_ref_cache *packed_ref_cache =1321get_packed_ref_cache(&ref_cache);13221323if(!packed_ref_cache->lock)1324die("internal error: packed refs not locked");1325add_ref(get_packed_ref_dir(packed_ref_cache),1326create_ref_entry(refname, sha1, REF_ISPACKED,1));1327}13281329/*1330 * Read the loose references from the namespace dirname into dir1331 * (without recursing). dirname must end with '/'. dir must be the1332 * directory entry corresponding to dirname.1333 */1334static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1335{1336struct ref_cache *refs = dir->ref_cache;1337DIR*d;1338const char*path;1339struct dirent *de;1340int dirnamelen =strlen(dirname);1341struct strbuf refname;13421343if(*refs->name)1344 path =git_path_submodule(refs->name,"%s", dirname);1345else1346 path =git_path("%s", dirname);13471348 d =opendir(path);1349if(!d)1350return;13511352strbuf_init(&refname, dirnamelen +257);1353strbuf_add(&refname, dirname, dirnamelen);13541355while((de =readdir(d)) != NULL) {1356unsigned char sha1[20];1357struct stat st;1358int flag;1359const char*refdir;13601361if(de->d_name[0] =='.')1362continue;1363if(ends_with(de->d_name,".lock"))1364continue;1365strbuf_addstr(&refname, de->d_name);1366 refdir = *refs->name1367?git_path_submodule(refs->name,"%s", refname.buf)1368:git_path("%s", refname.buf);1369if(stat(refdir, &st) <0) {1370;/* silently ignore */1371}else if(S_ISDIR(st.st_mode)) {1372strbuf_addch(&refname,'/');1373add_entry_to_dir(dir,1374create_dir_entry(refs, refname.buf,1375 refname.len,1));1376}else{1377int read_ok;13781379if(*refs->name) {1380hashclr(sha1);1381 flag =0;1382 read_ok = !resolve_gitlink_ref(refs->name,1383 refname.buf, sha1);1384}else{1385 read_ok = !read_ref_full(refname.buf,1386 RESOLVE_REF_READING,1387 sha1, &flag);1388}13891390if(!read_ok) {1391hashclr(sha1);1392 flag |= REF_ISBROKEN;1393}else if(is_null_sha1(sha1)) {1394/*1395 * It is so astronomically unlikely1396 * that NULL_SHA1 is the SHA-1 of an1397 * actual object that we consider its1398 * appearance in a loose reference1399 * file to be repo corruption1400 * (probably due to a software bug).1401 */1402 flag |= REF_ISBROKEN;1403}14041405if(check_refname_format(refname.buf,1406 REFNAME_ALLOW_ONELEVEL)) {1407hashclr(sha1);1408 flag |= REF_BAD_NAME | REF_ISBROKEN;1409}1410add_entry_to_dir(dir,1411create_ref_entry(refname.buf, sha1, flag,0));1412}1413strbuf_setlen(&refname, dirnamelen);1414}1415strbuf_release(&refname);1416closedir(d);1417}14181419static struct ref_dir *get_loose_refs(struct ref_cache *refs)1420{1421if(!refs->loose) {1422/*1423 * Mark the top-level directory complete because we1424 * are about to read the only subdirectory that can1425 * hold references:1426 */1427 refs->loose =create_dir_entry(refs,"",0,0);1428/*1429 * Create an incomplete entry for "refs/":1430 */1431add_entry_to_dir(get_ref_dir(refs->loose),1432create_dir_entry(refs,"refs/",5,1));1433}1434returnget_ref_dir(refs->loose);1435}14361437/* We allow "recursive" symbolic refs. Only within reason, though */1438#define MAXDEPTH 51439#define MAXREFLEN (1024)14401441/*1442 * Called by resolve_gitlink_ref_recursive() after it failed to read1443 * from the loose refs in ref_cache refs. Find <refname> in the1444 * packed-refs file for the submodule.1445 */1446static intresolve_gitlink_packed_ref(struct ref_cache *refs,1447const char*refname,unsigned char*sha1)1448{1449struct ref_entry *ref;1450struct ref_dir *dir =get_packed_refs(refs);14511452 ref =find_ref(dir, refname);1453if(ref == NULL)1454return-1;14551456hashcpy(sha1, ref->u.value.sha1);1457return0;1458}14591460static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1461const char*refname,unsigned char*sha1,1462int recursion)1463{1464int fd, len;1465char buffer[128], *p;1466char*path;14671468if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1469return-1;1470 path = *refs->name1471?git_path_submodule(refs->name,"%s", refname)1472:git_path("%s", refname);1473 fd =open(path, O_RDONLY);1474if(fd <0)1475returnresolve_gitlink_packed_ref(refs, refname, sha1);14761477 len =read(fd, buffer,sizeof(buffer)-1);1478close(fd);1479if(len <0)1480return-1;1481while(len &&isspace(buffer[len-1]))1482 len--;1483 buffer[len] =0;14841485/* Was it a detached head or an old-fashioned symlink? */1486if(!get_sha1_hex(buffer, sha1))1487return0;14881489/* Symref? */1490if(strncmp(buffer,"ref:",4))1491return-1;1492 p = buffer +4;1493while(isspace(*p))1494 p++;14951496returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1497}14981499intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1500{1501int len =strlen(path), retval;1502char*submodule;1503struct ref_cache *refs;15041505while(len && path[len-1] =='/')1506 len--;1507if(!len)1508return-1;1509 submodule =xstrndup(path, len);1510 refs =get_ref_cache(submodule);1511free(submodule);15121513 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1514return retval;1515}15161517/*1518 * Return the ref_entry for the given refname from the packed1519 * references. If it does not exist, return NULL.1520 */1521static struct ref_entry *get_packed_ref(const char*refname)1522{1523returnfind_ref(get_packed_refs(&ref_cache), refname);1524}15251526/*1527 * A loose ref file doesn't exist; check for a packed ref. The1528 * options are forwarded from resolve_safe_unsafe().1529 */1530static intresolve_missing_loose_ref(const char*refname,1531int resolve_flags,1532unsigned char*sha1,1533int*flags)1534{1535struct ref_entry *entry;15361537/*1538 * The loose reference file does not exist; check for a packed1539 * reference.1540 */1541 entry =get_packed_ref(refname);1542if(entry) {1543hashcpy(sha1, entry->u.value.sha1);1544if(flags)1545*flags |= REF_ISPACKED;1546return0;1547}1548/* The reference is not a packed reference, either. */1549if(resolve_flags & RESOLVE_REF_READING) {1550 errno = ENOENT;1551return-1;1552}else{1553hashclr(sha1);1554return0;1555}1556}15571558/* This function needs to return a meaningful errno on failure */1559const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1560{1561int depth = MAXDEPTH;1562 ssize_t len;1563char buffer[256];1564static char refname_buffer[256];1565int bad_name =0;15661567if(flags)1568*flags =0;15691570if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1571if(flags)1572*flags |= REF_BAD_NAME;15731574if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1575!refname_is_safe(refname)) {1576 errno = EINVAL;1577return NULL;1578}1579/*1580 * dwim_ref() uses REF_ISBROKEN to distinguish between1581 * missing refs and refs that were present but invalid,1582 * to complain about the latter to stderr.1583 *1584 * We don't know whether the ref exists, so don't set1585 * REF_ISBROKEN yet.1586 */1587 bad_name =1;1588}1589for(;;) {1590char path[PATH_MAX];1591struct stat st;1592char*buf;1593int fd;15941595if(--depth <0) {1596 errno = ELOOP;1597return NULL;1598}15991600git_snpath(path,sizeof(path),"%s", refname);16011602/*1603 * We might have to loop back here to avoid a race1604 * condition: first we lstat() the file, then we try1605 * to read it as a link or as a file. But if somebody1606 * changes the type of the file (file <-> directory1607 * <-> symlink) between the lstat() and reading, then1608 * we don't want to report that as an error but rather1609 * try again starting with the lstat().1610 */1611 stat_ref:1612if(lstat(path, &st) <0) {1613if(errno != ENOENT)1614return NULL;1615if(resolve_missing_loose_ref(refname, resolve_flags,1616 sha1, flags))1617return NULL;1618if(bad_name) {1619hashclr(sha1);1620if(flags)1621*flags |= REF_ISBROKEN;1622}1623return refname;1624}16251626/* Follow "normalized" - ie "refs/.." symlinks by hand */1627if(S_ISLNK(st.st_mode)) {1628 len =readlink(path, buffer,sizeof(buffer)-1);1629if(len <0) {1630if(errno == ENOENT || errno == EINVAL)1631/* inconsistent with lstat; retry */1632goto stat_ref;1633else1634return NULL;1635}1636 buffer[len] =0;1637if(starts_with(buffer,"refs/") &&1638!check_refname_format(buffer,0)) {1639strcpy(refname_buffer, buffer);1640 refname = refname_buffer;1641if(flags)1642*flags |= REF_ISSYMREF;1643if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1644hashclr(sha1);1645return refname;1646}1647continue;1648}1649}16501651/* Is it a directory? */1652if(S_ISDIR(st.st_mode)) {1653 errno = EISDIR;1654return NULL;1655}16561657/*1658 * Anything else, just open it and try to use it as1659 * a ref1660 */1661 fd =open(path, O_RDONLY);1662if(fd <0) {1663if(errno == ENOENT)1664/* inconsistent with lstat; retry */1665goto stat_ref;1666else1667return NULL;1668}1669 len =read_in_full(fd, buffer,sizeof(buffer)-1);1670if(len <0) {1671int save_errno = errno;1672close(fd);1673 errno = save_errno;1674return NULL;1675}1676close(fd);1677while(len &&isspace(buffer[len-1]))1678 len--;1679 buffer[len] ='\0';16801681/*1682 * Is it a symbolic ref?1683 */1684if(!starts_with(buffer,"ref:")) {1685/*1686 * Please note that FETCH_HEAD has a second1687 * line containing other data.1688 */1689if(get_sha1_hex(buffer, sha1) ||1690(buffer[40] !='\0'&& !isspace(buffer[40]))) {1691if(flags)1692*flags |= REF_ISBROKEN;1693 errno = EINVAL;1694return NULL;1695}1696if(bad_name) {1697hashclr(sha1);1698if(flags)1699*flags |= REF_ISBROKEN;1700}1701return refname;1702}1703if(flags)1704*flags |= REF_ISSYMREF;1705 buf = buffer +4;1706while(isspace(*buf))1707 buf++;1708 refname =strcpy(refname_buffer, buf);1709if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1710hashclr(sha1);1711return refname;1712}1713if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1714if(flags)1715*flags |= REF_ISBROKEN;17161717if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1718!refname_is_safe(buf)) {1719 errno = EINVAL;1720return NULL;1721}1722 bad_name =1;1723}1724}1725}17261727char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1728{1729returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1730}17311732/* The argument to filter_refs */1733struct ref_filter {1734const char*pattern;1735 each_ref_fn *fn;1736void*cb_data;1737};17381739intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1740{1741if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1742return0;1743return-1;1744}17451746intread_ref(const char*refname,unsigned char*sha1)1747{1748returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1749}17501751intref_exists(const char*refname)1752{1753unsigned char sha1[20];1754return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1755}17561757static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1758void*data)1759{1760struct ref_filter *filter = (struct ref_filter *)data;1761if(wildmatch(filter->pattern, refname,0, NULL))1762return0;1763return filter->fn(refname, sha1, flags, filter->cb_data);1764}17651766enum peel_status {1767/* object was peeled successfully: */1768 PEEL_PEELED =0,17691770/*1771 * object cannot be peeled because the named object (or an1772 * object referred to by a tag in the peel chain), does not1773 * exist.1774 */1775 PEEL_INVALID = -1,17761777/* object cannot be peeled because it is not a tag: */1778 PEEL_NON_TAG = -2,17791780/* ref_entry contains no peeled value because it is a symref: */1781 PEEL_IS_SYMREF = -3,17821783/*1784 * ref_entry cannot be peeled because it is broken (i.e., the1785 * symbolic reference cannot even be resolved to an object1786 * name):1787 */1788 PEEL_BROKEN = -41789};17901791/*1792 * Peel the named object; i.e., if the object is a tag, resolve the1793 * tag recursively until a non-tag is found. If successful, store the1794 * result to sha1 and return PEEL_PEELED. If the object is not a tag1795 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1796 * and leave sha1 unchanged.1797 */1798static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1799{1800struct object *o =lookup_unknown_object(name);18011802if(o->type == OBJ_NONE) {1803int type =sha1_object_info(name, NULL);1804if(type <0|| !object_as_type(o, type,0))1805return PEEL_INVALID;1806}18071808if(o->type != OBJ_TAG)1809return PEEL_NON_TAG;18101811 o =deref_tag_noverify(o);1812if(!o)1813return PEEL_INVALID;18141815hashcpy(sha1, o->sha1);1816return PEEL_PEELED;1817}18181819/*1820 * Peel the entry (if possible) and return its new peel_status. If1821 * repeel is true, re-peel the entry even if there is an old peeled1822 * value that is already stored in it.1823 *1824 * It is OK to call this function with a packed reference entry that1825 * might be stale and might even refer to an object that has since1826 * been garbage-collected. In such a case, if the entry has1827 * REF_KNOWS_PEELED then leave the status unchanged and return1828 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1829 */1830static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1831{1832enum peel_status status;18331834if(entry->flag & REF_KNOWS_PEELED) {1835if(repeel) {1836 entry->flag &= ~REF_KNOWS_PEELED;1837hashclr(entry->u.value.peeled);1838}else{1839returnis_null_sha1(entry->u.value.peeled) ?1840 PEEL_NON_TAG : PEEL_PEELED;1841}1842}1843if(entry->flag & REF_ISBROKEN)1844return PEEL_BROKEN;1845if(entry->flag & REF_ISSYMREF)1846return PEEL_IS_SYMREF;18471848 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1849if(status == PEEL_PEELED || status == PEEL_NON_TAG)1850 entry->flag |= REF_KNOWS_PEELED;1851return status;1852}18531854intpeel_ref(const char*refname,unsigned char*sha1)1855{1856int flag;1857unsigned char base[20];18581859if(current_ref && (current_ref->name == refname1860|| !strcmp(current_ref->name, refname))) {1861if(peel_entry(current_ref,0))1862return-1;1863hashcpy(sha1, current_ref->u.value.peeled);1864return0;1865}18661867if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1868return-1;18691870/*1871 * If the reference is packed, read its ref_entry from the1872 * cache in the hope that we already know its peeled value.1873 * We only try this optimization on packed references because1874 * (a) forcing the filling of the loose reference cache could1875 * be expensive and (b) loose references anyway usually do not1876 * have REF_KNOWS_PEELED.1877 */1878if(flag & REF_ISPACKED) {1879struct ref_entry *r =get_packed_ref(refname);1880if(r) {1881if(peel_entry(r,0))1882return-1;1883hashcpy(sha1, r->u.value.peeled);1884return0;1885}1886}18871888returnpeel_object(base, sha1);1889}18901891struct warn_if_dangling_data {1892FILE*fp;1893const char*refname;1894const struct string_list *refnames;1895const char*msg_fmt;1896};18971898static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1899int flags,void*cb_data)1900{1901struct warn_if_dangling_data *d = cb_data;1902const char*resolves_to;1903unsigned char junk[20];19041905if(!(flags & REF_ISSYMREF))1906return0;19071908 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1909if(!resolves_to1910|| (d->refname1911?strcmp(resolves_to, d->refname)1912: !string_list_has_string(d->refnames, resolves_to))) {1913return0;1914}19151916fprintf(d->fp, d->msg_fmt, refname);1917fputc('\n', d->fp);1918return0;1919}19201921voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1922{1923struct warn_if_dangling_data data;19241925 data.fp = fp;1926 data.refname = refname;1927 data.refnames = NULL;1928 data.msg_fmt = msg_fmt;1929for_each_rawref(warn_if_dangling_symref, &data);1930}19311932voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1933{1934struct warn_if_dangling_data data;19351936 data.fp = fp;1937 data.refname = NULL;1938 data.refnames = refnames;1939 data.msg_fmt = msg_fmt;1940for_each_rawref(warn_if_dangling_symref, &data);1941}19421943/*1944 * Call fn for each reference in the specified ref_cache, omitting1945 * references not in the containing_dir of base. fn is called for all1946 * references, including broken ones. If fn ever returns a non-zero1947 * value, stop the iteration and return that value; otherwise, return1948 * 0.1949 */1950static intdo_for_each_entry(struct ref_cache *refs,const char*base,1951 each_ref_entry_fn fn,void*cb_data)1952{1953struct packed_ref_cache *packed_ref_cache;1954struct ref_dir *loose_dir;1955struct ref_dir *packed_dir;1956int retval =0;19571958/*1959 * We must make sure that all loose refs are read before accessing the1960 * packed-refs file; this avoids a race condition in which loose refs1961 * are migrated to the packed-refs file by a simultaneous process, but1962 * our in-memory view is from before the migration. get_packed_ref_cache()1963 * takes care of making sure our view is up to date with what is on1964 * disk.1965 */1966 loose_dir =get_loose_refs(refs);1967if(base && *base) {1968 loose_dir =find_containing_dir(loose_dir, base,0);1969}1970if(loose_dir)1971prime_ref_dir(loose_dir);19721973 packed_ref_cache =get_packed_ref_cache(refs);1974acquire_packed_ref_cache(packed_ref_cache);1975 packed_dir =get_packed_ref_dir(packed_ref_cache);1976if(base && *base) {1977 packed_dir =find_containing_dir(packed_dir, base,0);1978}19791980if(packed_dir && loose_dir) {1981sort_ref_dir(packed_dir);1982sort_ref_dir(loose_dir);1983 retval =do_for_each_entry_in_dirs(1984 packed_dir, loose_dir, fn, cb_data);1985}else if(packed_dir) {1986sort_ref_dir(packed_dir);1987 retval =do_for_each_entry_in_dir(1988 packed_dir,0, fn, cb_data);1989}else if(loose_dir) {1990sort_ref_dir(loose_dir);1991 retval =do_for_each_entry_in_dir(1992 loose_dir,0, fn, cb_data);1993}19941995release_packed_ref_cache(packed_ref_cache);1996return retval;1997}19981999/*2000 * Call fn for each reference in the specified ref_cache for which the2001 * refname begins with base. If trim is non-zero, then trim that many2002 * characters off the beginning of each refname before passing the2003 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2004 * broken references in the iteration. If fn ever returns a non-zero2005 * value, stop the iteration and return that value; otherwise, return2006 * 0.2007 */2008static intdo_for_each_ref(struct ref_cache *refs,const char*base,2009 each_ref_fn fn,int trim,int flags,void*cb_data)2010{2011struct ref_entry_cb data;2012 data.base = base;2013 data.trim = trim;2014 data.flags = flags;2015 data.fn = fn;2016 data.cb_data = cb_data;20172018if(ref_paranoia <0)2019 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2020if(ref_paranoia)2021 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20222023returndo_for_each_entry(refs, base, do_one_ref, &data);2024}20252026static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2027{2028unsigned char sha1[20];2029int flag;20302031if(submodule) {2032if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)2033returnfn("HEAD", sha1,0, cb_data);20342035return0;2036}20372038if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))2039returnfn("HEAD", sha1, flag, cb_data);20402041return0;2042}20432044inthead_ref(each_ref_fn fn,void*cb_data)2045{2046returndo_head_ref(NULL, fn, cb_data);2047}20482049inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2050{2051returndo_head_ref(submodule, fn, cb_data);2052}20532054intfor_each_ref(each_ref_fn fn,void*cb_data)2055{2056returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2057}20582059intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2060{2061returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2062}20632064intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2065{2066returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2067}20682069intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2070 each_ref_fn fn,void*cb_data)2071{2072returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2073}20742075intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2076{2077returnfor_each_ref_in("refs/tags/", fn, cb_data);2078}20792080intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2081{2082returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2083}20842085intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2086{2087returnfor_each_ref_in("refs/heads/", fn, cb_data);2088}20892090intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2091{2092returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2093}20942095intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2096{2097returnfor_each_ref_in("refs/remotes/", fn, cb_data);2098}20992100intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2101{2102returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2103}21042105intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2106{2107returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2108}21092110inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2111{2112struct strbuf buf = STRBUF_INIT;2113int ret =0;2114unsigned char sha1[20];2115int flag;21162117strbuf_addf(&buf,"%sHEAD",get_git_namespace());2118if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2119 ret =fn(buf.buf, sha1, flag, cb_data);2120strbuf_release(&buf);21212122return ret;2123}21242125intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2126{2127struct strbuf buf = STRBUF_INIT;2128int ret;2129strbuf_addf(&buf,"%srefs/",get_git_namespace());2130 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2131strbuf_release(&buf);2132return ret;2133}21342135intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2136const char*prefix,void*cb_data)2137{2138struct strbuf real_pattern = STRBUF_INIT;2139struct ref_filter filter;2140int ret;21412142if(!prefix && !starts_with(pattern,"refs/"))2143strbuf_addstr(&real_pattern,"refs/");2144else if(prefix)2145strbuf_addstr(&real_pattern, prefix);2146strbuf_addstr(&real_pattern, pattern);21472148if(!has_glob_specials(pattern)) {2149/* Append implied '/' '*' if not present. */2150if(real_pattern.buf[real_pattern.len -1] !='/')2151strbuf_addch(&real_pattern,'/');2152/* No need to check for '*', there is none. */2153strbuf_addch(&real_pattern,'*');2154}21552156 filter.pattern = real_pattern.buf;2157 filter.fn = fn;2158 filter.cb_data = cb_data;2159 ret =for_each_ref(filter_refs, &filter);21602161strbuf_release(&real_pattern);2162return ret;2163}21642165intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2166{2167returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2168}21692170intfor_each_rawref(each_ref_fn fn,void*cb_data)2171{2172returndo_for_each_ref(&ref_cache,"", fn,0,2173 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2174}21752176const char*prettify_refname(const char*name)2177{2178return name + (2179starts_with(name,"refs/heads/") ?11:2180starts_with(name,"refs/tags/") ?10:2181starts_with(name,"refs/remotes/") ?13:21820);2183}21842185static const char*ref_rev_parse_rules[] = {2186"%.*s",2187"refs/%.*s",2188"refs/tags/%.*s",2189"refs/heads/%.*s",2190"refs/remotes/%.*s",2191"refs/remotes/%.*s/HEAD",2192 NULL2193};21942195intrefname_match(const char*abbrev_name,const char*full_name)2196{2197const char**p;2198const int abbrev_name_len =strlen(abbrev_name);21992200for(p = ref_rev_parse_rules; *p; p++) {2201if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2202return1;2203}2204}22052206return0;2207}22082209static voidunlock_ref(struct ref_lock *lock)2210{2211/* Do not free lock->lk -- atexit() still looks at them */2212if(lock->lk)2213rollback_lock_file(lock->lk);2214free(lock->ref_name);2215free(lock->orig_ref_name);2216free(lock);2217}22182219/* This function should make sure errno is meaningful on error */2220static struct ref_lock *verify_lock(struct ref_lock *lock,2221const unsigned char*old_sha1,int mustexist)2222{2223if(read_ref_full(lock->ref_name,2224 mustexist ? RESOLVE_REF_READING :0,2225 lock->old_sha1, NULL)) {2226int save_errno = errno;2227error("Can't verify ref%s", lock->ref_name);2228unlock_ref(lock);2229 errno = save_errno;2230return NULL;2231}2232if(hashcmp(lock->old_sha1, old_sha1)) {2233error("Ref%sis at%sbut expected%s", lock->ref_name,2234sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2235unlock_ref(lock);2236 errno = EBUSY;2237return NULL;2238}2239return lock;2240}22412242static intremove_empty_directories(const char*file)2243{2244/* we want to create a file but there is a directory there;2245 * if that is an empty directory (or a directory that contains2246 * only empty directories), remove them.2247 */2248struct strbuf path;2249int result, save_errno;22502251strbuf_init(&path,20);2252strbuf_addstr(&path, file);22532254 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2255 save_errno = errno;22562257strbuf_release(&path);2258 errno = save_errno;22592260return result;2261}22622263/*2264 * *string and *len will only be substituted, and *string returned (for2265 * later free()ing) if the string passed in is a magic short-hand form2266 * to name a branch.2267 */2268static char*substitute_branch_name(const char**string,int*len)2269{2270struct strbuf buf = STRBUF_INIT;2271int ret =interpret_branch_name(*string, *len, &buf);22722273if(ret == *len) {2274size_t size;2275*string =strbuf_detach(&buf, &size);2276*len = size;2277return(char*)*string;2278}22792280return NULL;2281}22822283intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2284{2285char*last_branch =substitute_branch_name(&str, &len);2286const char**p, *r;2287int refs_found =0;22882289*ref = NULL;2290for(p = ref_rev_parse_rules; *p; p++) {2291char fullref[PATH_MAX];2292unsigned char sha1_from_ref[20];2293unsigned char*this_result;2294int flag;22952296 this_result = refs_found ? sha1_from_ref : sha1;2297mksnpath(fullref,sizeof(fullref), *p, len, str);2298 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2299 this_result, &flag);2300if(r) {2301if(!refs_found++)2302*ref =xstrdup(r);2303if(!warn_ambiguous_refs)2304break;2305}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2306warning("ignoring dangling symref%s.", fullref);2307}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2308warning("ignoring broken ref%s.", fullref);2309}2310}2311free(last_branch);2312return refs_found;2313}23142315intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2316{2317char*last_branch =substitute_branch_name(&str, &len);2318const char**p;2319int logs_found =0;23202321*log = NULL;2322for(p = ref_rev_parse_rules; *p; p++) {2323unsigned char hash[20];2324char path[PATH_MAX];2325const char*ref, *it;23262327mksnpath(path,sizeof(path), *p, len, str);2328 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2329 hash, NULL);2330if(!ref)2331continue;2332if(reflog_exists(path))2333 it = path;2334else if(strcmp(ref, path) &&reflog_exists(ref))2335 it = ref;2336else2337continue;2338if(!logs_found++) {2339*log =xstrdup(it);2340hashcpy(sha1, hash);2341}2342if(!warn_ambiguous_refs)2343break;2344}2345free(last_branch);2346return logs_found;2347}23482349/*2350 * Locks a ref returning the lock on success and NULL on failure.2351 * On failure errno is set to something meaningful.2352 */2353static struct ref_lock *lock_ref_sha1_basic(const char*refname,2354const unsigned char*old_sha1,2355const struct string_list *extras,2356const struct string_list *skip,2357unsigned int flags,int*type_p,2358struct strbuf *err)2359{2360char*ref_file;2361const char*orig_refname = refname;2362struct ref_lock *lock;2363int last_errno =0;2364int type, lflags;2365int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2366int resolve_flags =0;2367int attempts_remaining =3;23682369assert(err);23702371 lock =xcalloc(1,sizeof(struct ref_lock));2372 lock->lock_fd = -1;23732374if(mustexist)2375 resolve_flags |= RESOLVE_REF_READING;2376if(flags & REF_DELETING) {2377 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2378if(flags & REF_NODEREF)2379 resolve_flags |= RESOLVE_REF_NO_RECURSE;2380}23812382 refname =resolve_ref_unsafe(refname, resolve_flags,2383 lock->old_sha1, &type);2384if(!refname && errno == EISDIR) {2385/* we are trying to lock foo but we used to2386 * have foo/bar which now does not exist;2387 * it is normal for the empty directory 'foo'2388 * to remain.2389 */2390 ref_file =git_path("%s", orig_refname);2391if(remove_empty_directories(ref_file)) {2392 last_errno = errno;23932394if(!verify_refname_available(orig_refname, extras, skip,2395get_loose_refs(&ref_cache), err))2396strbuf_addf(err,"there are still refs under '%s'",2397 orig_refname);23982399goto error_return;2400}2401 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2402 lock->old_sha1, &type);2403}2404if(type_p)2405*type_p = type;2406if(!refname) {2407 last_errno = errno;2408if(last_errno != ENOTDIR ||2409!verify_refname_available(orig_refname, extras, skip,2410get_loose_refs(&ref_cache), err))2411strbuf_addf(err,"unable to resolve reference%s:%s",2412 orig_refname,strerror(last_errno));24132414goto error_return;2415}2416/*2417 * If the ref did not exist and we are creating it, make sure2418 * there is no existing packed ref whose name begins with our2419 * refname, nor a packed ref whose name is a proper prefix of2420 * our refname.2421 */2422if(is_null_sha1(lock->old_sha1) &&2423verify_refname_available(refname, extras, skip,2424get_packed_refs(&ref_cache), err)) {2425 last_errno = ENOTDIR;2426goto error_return;2427}24282429 lock->lk =xcalloc(1,sizeof(struct lock_file));24302431 lflags =0;2432if(flags & REF_NODEREF) {2433 refname = orig_refname;2434 lflags |= LOCK_NO_DEREF;2435}2436 lock->ref_name =xstrdup(refname);2437 lock->orig_ref_name =xstrdup(orig_refname);2438 ref_file =git_path("%s", refname);24392440 retry:2441switch(safe_create_leading_directories(ref_file)) {2442case SCLD_OK:2443break;/* success */2444case SCLD_VANISHED:2445if(--attempts_remaining >0)2446goto retry;2447/* fall through */2448default:2449 last_errno = errno;2450strbuf_addf(err,"unable to create directory for%s", ref_file);2451goto error_return;2452}24532454 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2455if(lock->lock_fd <0) {2456 last_errno = errno;2457if(errno == ENOENT && --attempts_remaining >0)2458/*2459 * Maybe somebody just deleted one of the2460 * directories leading to ref_file. Try2461 * again:2462 */2463goto retry;2464else{2465unable_to_lock_message(ref_file, errno, err);2466goto error_return;2467}2468}2469return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;24702471 error_return:2472unlock_ref(lock);2473 errno = last_errno;2474return NULL;2475}24762477/*2478 * Write an entry to the packed-refs file for the specified refname.2479 * If peeled is non-NULL, write it as the entry's peeled value.2480 */2481static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2482unsigned char*peeled)2483{2484fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2485if(peeled)2486fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2487}24882489/*2490 * An each_ref_entry_fn that writes the entry to a packed-refs file.2491 */2492static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2493{2494enum peel_status peel_status =peel_entry(entry,0);24952496if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2497error("internal error:%sis not a valid packed reference!",2498 entry->name);2499write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2500 peel_status == PEEL_PEELED ?2501 entry->u.value.peeled : NULL);2502return0;2503}25042505/* This should return a meaningful errno on failure */2506intlock_packed_refs(int flags)2507{2508struct packed_ref_cache *packed_ref_cache;25092510if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2511return-1;2512/*2513 * Get the current packed-refs while holding the lock. If the2514 * packed-refs file has been modified since we last read it,2515 * this will automatically invalidate the cache and re-read2516 * the packed-refs file.2517 */2518 packed_ref_cache =get_packed_ref_cache(&ref_cache);2519 packed_ref_cache->lock = &packlock;2520/* Increment the reference count to prevent it from being freed: */2521acquire_packed_ref_cache(packed_ref_cache);2522return0;2523}25242525/*2526 * Commit the packed refs changes.2527 * On error we must make sure that errno contains a meaningful value.2528 */2529intcommit_packed_refs(void)2530{2531struct packed_ref_cache *packed_ref_cache =2532get_packed_ref_cache(&ref_cache);2533int error =0;2534int save_errno =0;2535FILE*out;25362537if(!packed_ref_cache->lock)2538die("internal error: packed-refs not locked");25392540 out =fdopen_lock_file(packed_ref_cache->lock,"w");2541if(!out)2542die_errno("unable to fdopen packed-refs descriptor");25432544fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2545do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),25460, write_packed_entry_fn, out);25472548if(commit_lock_file(packed_ref_cache->lock)) {2549 save_errno = errno;2550 error = -1;2551}2552 packed_ref_cache->lock = NULL;2553release_packed_ref_cache(packed_ref_cache);2554 errno = save_errno;2555return error;2556}25572558voidrollback_packed_refs(void)2559{2560struct packed_ref_cache *packed_ref_cache =2561get_packed_ref_cache(&ref_cache);25622563if(!packed_ref_cache->lock)2564die("internal error: packed-refs not locked");2565rollback_lock_file(packed_ref_cache->lock);2566 packed_ref_cache->lock = NULL;2567release_packed_ref_cache(packed_ref_cache);2568clear_packed_ref_cache(&ref_cache);2569}25702571struct ref_to_prune {2572struct ref_to_prune *next;2573unsigned char sha1[20];2574char name[FLEX_ARRAY];2575};25762577struct pack_refs_cb_data {2578unsigned int flags;2579struct ref_dir *packed_refs;2580struct ref_to_prune *ref_to_prune;2581};25822583/*2584 * An each_ref_entry_fn that is run over loose references only. If2585 * the loose reference can be packed, add an entry in the packed ref2586 * cache. If the reference should be pruned, also add it to2587 * ref_to_prune in the pack_refs_cb_data.2588 */2589static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2590{2591struct pack_refs_cb_data *cb = cb_data;2592enum peel_status peel_status;2593struct ref_entry *packed_entry;2594int is_tag_ref =starts_with(entry->name,"refs/tags/");25952596/* ALWAYS pack tags */2597if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2598return0;25992600/* Do not pack symbolic or broken refs: */2601if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2602return0;26032604/* Add a packed ref cache entry equivalent to the loose entry. */2605 peel_status =peel_entry(entry,1);2606if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2607die("internal error peeling reference%s(%s)",2608 entry->name,sha1_to_hex(entry->u.value.sha1));2609 packed_entry =find_ref(cb->packed_refs, entry->name);2610if(packed_entry) {2611/* Overwrite existing packed entry with info from loose entry */2612 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2613hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2614}else{2615 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2616 REF_ISPACKED | REF_KNOWS_PEELED,0);2617add_ref(cb->packed_refs, packed_entry);2618}2619hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);26202621/* Schedule the loose reference for pruning if requested. */2622if((cb->flags & PACK_REFS_PRUNE)) {2623int namelen =strlen(entry->name) +1;2624struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2625hashcpy(n->sha1, entry->u.value.sha1);2626strcpy(n->name, entry->name);2627 n->next = cb->ref_to_prune;2628 cb->ref_to_prune = n;2629}2630return0;2631}26322633/*2634 * Remove empty parents, but spare refs/ and immediate subdirs.2635 * Note: munges *name.2636 */2637static voidtry_remove_empty_parents(char*name)2638{2639char*p, *q;2640int i;2641 p = name;2642for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2643while(*p && *p !='/')2644 p++;2645/* tolerate duplicate slashes; see check_refname_format() */2646while(*p =='/')2647 p++;2648}2649for(q = p; *q; q++)2650;2651while(1) {2652while(q > p && *q !='/')2653 q--;2654while(q > p && *(q-1) =='/')2655 q--;2656if(q == p)2657break;2658*q ='\0';2659if(rmdir(git_path("%s", name)))2660break;2661}2662}26632664/* make sure nobody touched the ref, and unlink */2665static voidprune_ref(struct ref_to_prune *r)2666{2667struct ref_transaction *transaction;2668struct strbuf err = STRBUF_INIT;26692670if(check_refname_format(r->name,0))2671return;26722673 transaction =ref_transaction_begin(&err);2674if(!transaction ||2675ref_transaction_delete(transaction, r->name, r->sha1,2676 REF_ISPRUNING, NULL, &err) ||2677ref_transaction_commit(transaction, &err)) {2678ref_transaction_free(transaction);2679error("%s", err.buf);2680strbuf_release(&err);2681return;2682}2683ref_transaction_free(transaction);2684strbuf_release(&err);2685try_remove_empty_parents(r->name);2686}26872688static voidprune_refs(struct ref_to_prune *r)2689{2690while(r) {2691prune_ref(r);2692 r = r->next;2693}2694}26952696intpack_refs(unsigned int flags)2697{2698struct pack_refs_cb_data cbdata;26992700memset(&cbdata,0,sizeof(cbdata));2701 cbdata.flags = flags;27022703lock_packed_refs(LOCK_DIE_ON_ERROR);2704 cbdata.packed_refs =get_packed_refs(&ref_cache);27052706do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2707 pack_if_possible_fn, &cbdata);27082709if(commit_packed_refs())2710die_errno("unable to overwrite old ref-pack file");27112712prune_refs(cbdata.ref_to_prune);2713return0;2714}27152716intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2717{2718struct ref_dir *packed;2719struct string_list_item *refname;2720int ret, needs_repacking =0, removed =0;27212722assert(err);27232724/* Look for a packed ref */2725for_each_string_list_item(refname, refnames) {2726if(get_packed_ref(refname->string)) {2727 needs_repacking =1;2728break;2729}2730}27312732/* Avoid locking if we have nothing to do */2733if(!needs_repacking)2734return0;/* no refname exists in packed refs */27352736if(lock_packed_refs(0)) {2737unable_to_lock_message(git_path("packed-refs"), errno, err);2738return-1;2739}2740 packed =get_packed_refs(&ref_cache);27412742/* Remove refnames from the cache */2743for_each_string_list_item(refname, refnames)2744if(remove_entry(packed, refname->string) != -1)2745 removed =1;2746if(!removed) {2747/*2748 * All packed entries disappeared while we were2749 * acquiring the lock.2750 */2751rollback_packed_refs();2752return0;2753}27542755/* Write what remains */2756 ret =commit_packed_refs();2757if(ret)2758strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2759strerror(errno));2760return ret;2761}27622763static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2764{2765assert(err);27662767if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2768/*2769 * loose. The loose file name is the same as the2770 * lockfile name, minus ".lock":2771 */2772char*loose_filename =get_locked_file_path(lock->lk);2773int res =unlink_or_msg(loose_filename, err);2774free(loose_filename);2775if(res)2776return1;2777}2778return0;2779}27802781intdelete_ref(const char*refname,const unsigned char*sha1,unsigned int flags)2782{2783struct ref_transaction *transaction;2784struct strbuf err = STRBUF_INIT;27852786 transaction =ref_transaction_begin(&err);2787if(!transaction ||2788ref_transaction_delete(transaction, refname,2789(sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,2790 flags, NULL, &err) ||2791ref_transaction_commit(transaction, &err)) {2792error("%s", err.buf);2793ref_transaction_free(transaction);2794strbuf_release(&err);2795return1;2796}2797ref_transaction_free(transaction);2798strbuf_release(&err);2799return0;2800}28012802/*2803 * People using contrib's git-new-workdir have .git/logs/refs ->2804 * /some/other/path/.git/logs/refs, and that may live on another device.2805 *2806 * IOW, to avoid cross device rename errors, the temporary renamed log must2807 * live into logs/refs.2808 */2809#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"28102811static intrename_tmp_log(const char*newrefname)2812{2813int attempts_remaining =4;28142815 retry:2816switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2817case SCLD_OK:2818break;/* success */2819case SCLD_VANISHED:2820if(--attempts_remaining >0)2821goto retry;2822/* fall through */2823default:2824error("unable to create directory for%s", newrefname);2825return-1;2826}28272828if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2829if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2830/*2831 * rename(a, b) when b is an existing2832 * directory ought to result in ISDIR, but2833 * Solaris 5.8 gives ENOTDIR. Sheesh.2834 */2835if(remove_empty_directories(git_path("logs/%s", newrefname))) {2836error("Directory not empty: logs/%s", newrefname);2837return-1;2838}2839goto retry;2840}else if(errno == ENOENT && --attempts_remaining >0) {2841/*2842 * Maybe another process just deleted one of2843 * the directories in the path to newrefname.2844 * Try again from the beginning.2845 */2846goto retry;2847}else{2848error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2849 newrefname,strerror(errno));2850return-1;2851}2852}2853return0;2854}28552856static intrename_ref_available(const char*oldname,const char*newname)2857{2858struct string_list skip = STRING_LIST_INIT_NODUP;2859struct strbuf err = STRBUF_INIT;2860int ret;28612862string_list_insert(&skip, oldname);2863 ret = !verify_refname_available(newname, NULL, &skip,2864get_packed_refs(&ref_cache), &err)2865&& !verify_refname_available(newname, NULL, &skip,2866get_loose_refs(&ref_cache), &err);2867if(!ret)2868error("%s", err.buf);28692870string_list_clear(&skip,0);2871strbuf_release(&err);2872return ret;2873}28742875static intwrite_ref_to_lockfile(struct ref_lock *lock,const unsigned char*sha1);2876static intcommit_ref_update(struct ref_lock *lock,2877const unsigned char*sha1,const char*logmsg);28782879intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2880{2881unsigned char sha1[20], orig_sha1[20];2882int flag =0, logmoved =0;2883struct ref_lock *lock;2884struct stat loginfo;2885int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2886const char*symref = NULL;2887struct strbuf err = STRBUF_INIT;28882889if(log &&S_ISLNK(loginfo.st_mode))2890returnerror("reflog for%sis a symlink", oldrefname);28912892 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2893 orig_sha1, &flag);2894if(flag & REF_ISSYMREF)2895returnerror("refname%sis a symbolic ref, renaming it is not supported",2896 oldrefname);2897if(!symref)2898returnerror("refname%snot found", oldrefname);28992900if(!rename_ref_available(oldrefname, newrefname))2901return1;29022903if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2904returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2905 oldrefname,strerror(errno));29062907if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2908error("unable to delete old%s", oldrefname);2909goto rollback;2910}29112912if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2913delete_ref(newrefname, sha1, REF_NODEREF)) {2914if(errno==EISDIR) {2915if(remove_empty_directories(git_path("%s", newrefname))) {2916error("Directory not empty:%s", newrefname);2917goto rollback;2918}2919}else{2920error("unable to delete existing%s", newrefname);2921goto rollback;2922}2923}29242925if(log &&rename_tmp_log(newrefname))2926goto rollback;29272928 logmoved = log;29292930 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2931if(!lock) {2932error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2933strbuf_release(&err);2934goto rollback;2935}2936hashcpy(lock->old_sha1, orig_sha1);29372938if(write_ref_to_lockfile(lock, orig_sha1) ||2939commit_ref_update(lock, orig_sha1, logmsg)) {2940error("unable to write current sha1 into%s", newrefname);2941goto rollback;2942}29432944return0;29452946 rollback:2947 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2948if(!lock) {2949error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2950strbuf_release(&err);2951goto rollbacklog;2952}29532954 flag = log_all_ref_updates;2955 log_all_ref_updates =0;2956if(write_ref_to_lockfile(lock, orig_sha1) ||2957commit_ref_update(lock, orig_sha1, NULL))2958error("unable to write current sha1 into%s", oldrefname);2959 log_all_ref_updates = flag;29602961 rollbacklog:2962if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2963error("unable to restore logfile%sfrom%s:%s",2964 oldrefname, newrefname,strerror(errno));2965if(!logmoved && log &&2966rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2967error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2968 oldrefname,strerror(errno));29692970return1;2971}29722973static intclose_ref(struct ref_lock *lock)2974{2975if(close_lock_file(lock->lk))2976return-1;2977 lock->lock_fd = -1;2978return0;2979}29802981static intcommit_ref(struct ref_lock *lock)2982{2983if(commit_lock_file(lock->lk))2984return-1;2985 lock->lock_fd = -1;2986return0;2987}29882989/*2990 * copy the reflog message msg to buf, which has been allocated sufficiently2991 * large, while cleaning up the whitespaces. Especially, convert LF to space,2992 * because reflog file is one line per entry.2993 */2994static intcopy_msg(char*buf,const char*msg)2995{2996char*cp = buf;2997char c;2998int wasspace =1;29993000*cp++ ='\t';3001while((c = *msg++)) {3002if(wasspace &&isspace(c))3003continue;3004 wasspace =isspace(c);3005if(wasspace)3006 c =' ';3007*cp++ = c;3008}3009while(buf < cp &&isspace(cp[-1]))3010 cp--;3011*cp++ ='\n';3012return cp - buf;3013}30143015/* This function must set a meaningful errno on failure */3016intlog_ref_setup(const char*refname,char*logfile,int bufsize)3017{3018int logfd, oflags = O_APPEND | O_WRONLY;30193020git_snpath(logfile, bufsize,"logs/%s", refname);3021if(log_all_ref_updates &&3022(starts_with(refname,"refs/heads/") ||3023starts_with(refname,"refs/remotes/") ||3024starts_with(refname,"refs/notes/") ||3025!strcmp(refname,"HEAD"))) {3026if(safe_create_leading_directories(logfile) <0) {3027int save_errno = errno;3028error("unable to create directory for%s", logfile);3029 errno = save_errno;3030return-1;3031}3032 oflags |= O_CREAT;3033}30343035 logfd =open(logfile, oflags,0666);3036if(logfd <0) {3037if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3038return0;30393040if(errno == EISDIR) {3041if(remove_empty_directories(logfile)) {3042int save_errno = errno;3043error("There are still logs under '%s'",3044 logfile);3045 errno = save_errno;3046return-1;3047}3048 logfd =open(logfile, oflags,0666);3049}30503051if(logfd <0) {3052int save_errno = errno;3053error("Unable to append to%s:%s", logfile,3054strerror(errno));3055 errno = save_errno;3056return-1;3057}3058}30593060adjust_shared_perm(logfile);3061close(logfd);3062return0;3063}30643065static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3066const unsigned char*new_sha1,3067const char*committer,const char*msg)3068{3069int msglen, written;3070unsigned maxlen, len;3071char*logrec;30723073 msglen = msg ?strlen(msg) :0;3074 maxlen =strlen(committer) + msglen +100;3075 logrec =xmalloc(maxlen);3076 len =sprintf(logrec,"%s %s %s\n",3077sha1_to_hex(old_sha1),3078sha1_to_hex(new_sha1),3079 committer);3080if(msglen)3081 len +=copy_msg(logrec + len -1, msg) -1;30823083 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3084free(logrec);3085if(written != len)3086return-1;30873088return0;3089}30903091static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3092const unsigned char*new_sha1,const char*msg)3093{3094int logfd, result, oflags = O_APPEND | O_WRONLY;3095char log_file[PATH_MAX];30963097if(log_all_ref_updates <0)3098 log_all_ref_updates = !is_bare_repository();30993100 result =log_ref_setup(refname, log_file,sizeof(log_file));3101if(result)3102return result;31033104 logfd =open(log_file, oflags);3105if(logfd <0)3106return0;3107 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3108git_committer_info(0), msg);3109if(result) {3110int save_errno = errno;3111close(logfd);3112error("Unable to append to%s", log_file);3113 errno = save_errno;3114return-1;3115}3116if(close(logfd)) {3117int save_errno = errno;3118error("Unable to append to%s", log_file);3119 errno = save_errno;3120return-1;3121}3122return0;3123}31243125intis_branch(const char*refname)3126{3127return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3128}31293130/*3131 * Write sha1 into the open lockfile, then close the lockfile. On3132 * errors, rollback the lockfile and set errno to reflect the problem.3133 */3134static intwrite_ref_to_lockfile(struct ref_lock *lock,3135const unsigned char*sha1)3136{3137static char term ='\n';3138struct object *o;31393140 o =parse_object(sha1);3141if(!o) {3142error("Trying to write ref%swith nonexistent object%s",3143 lock->ref_name,sha1_to_hex(sha1));3144unlock_ref(lock);3145 errno = EINVAL;3146return-1;3147}3148if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3149error("Trying to write non-commit object%sto branch%s",3150sha1_to_hex(sha1), lock->ref_name);3151unlock_ref(lock);3152 errno = EINVAL;3153return-1;3154}3155if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3156write_in_full(lock->lock_fd, &term,1) !=1||3157close_ref(lock) <0) {3158int save_errno = errno;3159error("Couldn't write%s", lock->lk->filename.buf);3160unlock_ref(lock);3161 errno = save_errno;3162return-1;3163}3164return0;3165}31663167/*3168 * Commit a change to a loose reference that has already been written3169 * to the loose reference lockfile. Also update the reflogs if3170 * necessary, using the specified lockmsg (which can be NULL).3171 */3172static intcommit_ref_update(struct ref_lock *lock,3173const unsigned char*sha1,const char*logmsg)3174{3175clear_loose_ref_cache(&ref_cache);3176if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3177(strcmp(lock->ref_name, lock->orig_ref_name) &&3178log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3179unlock_ref(lock);3180return-1;3181}3182if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3183/*3184 * Special hack: If a branch is updated directly and HEAD3185 * points to it (may happen on the remote side of a push3186 * for example) then logically the HEAD reflog should be3187 * updated too.3188 * A generic solution implies reverse symref information,3189 * but finding all symrefs pointing to the given branch3190 * would be rather costly for this rare event (the direct3191 * update of a branch) to be worth it. So let's cheat and3192 * check with HEAD only which should cover 99% of all usage3193 * scenarios (even 100% of the default ones).3194 */3195unsigned char head_sha1[20];3196int head_flag;3197const char*head_ref;3198 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3199 head_sha1, &head_flag);3200if(head_ref && (head_flag & REF_ISSYMREF) &&3201!strcmp(head_ref, lock->ref_name))3202log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3203}3204if(commit_ref(lock)) {3205error("Couldn't set%s", lock->ref_name);3206unlock_ref(lock);3207return-1;3208}3209unlock_ref(lock);3210return0;3211}32123213intcreate_symref(const char*ref_target,const char*refs_heads_master,3214const char*logmsg)3215{3216const char*lockpath;3217char ref[1000];3218int fd, len, written;3219char*git_HEAD =git_pathdup("%s", ref_target);3220unsigned char old_sha1[20], new_sha1[20];32213222if(logmsg &&read_ref(ref_target, old_sha1))3223hashclr(old_sha1);32243225if(safe_create_leading_directories(git_HEAD) <0)3226returnerror("unable to create directory for%s", git_HEAD);32273228#ifndef NO_SYMLINK_HEAD3229if(prefer_symlink_refs) {3230unlink(git_HEAD);3231if(!symlink(refs_heads_master, git_HEAD))3232goto done;3233fprintf(stderr,"no symlink - falling back to symbolic ref\n");3234}3235#endif32363237 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3238if(sizeof(ref) <= len) {3239error("refname too long:%s", refs_heads_master);3240goto error_free_return;3241}3242 lockpath =mkpath("%s.lock", git_HEAD);3243 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3244if(fd <0) {3245error("Unable to open%sfor writing", lockpath);3246goto error_free_return;3247}3248 written =write_in_full(fd, ref, len);3249if(close(fd) !=0|| written != len) {3250error("Unable to write to%s", lockpath);3251goto error_unlink_return;3252}3253if(rename(lockpath, git_HEAD) <0) {3254error("Unable to create%s", git_HEAD);3255goto error_unlink_return;3256}3257if(adjust_shared_perm(git_HEAD)) {3258error("Unable to fix permissions on%s", lockpath);3259 error_unlink_return:3260unlink_or_warn(lockpath);3261 error_free_return:3262free(git_HEAD);3263return-1;3264}32653266#ifndef NO_SYMLINK_HEAD3267 done:3268#endif3269if(logmsg && !read_ref(refs_heads_master, new_sha1))3270log_ref_write(ref_target, old_sha1, new_sha1, logmsg);32713272free(git_HEAD);3273return0;3274}32753276struct read_ref_at_cb {3277const char*refname;3278unsigned long at_time;3279int cnt;3280int reccnt;3281unsigned char*sha1;3282int found_it;32833284unsigned char osha1[20];3285unsigned char nsha1[20];3286int tz;3287unsigned long date;3288char**msg;3289unsigned long*cutoff_time;3290int*cutoff_tz;3291int*cutoff_cnt;3292};32933294static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3295const char*email,unsigned long timestamp,int tz,3296const char*message,void*cb_data)3297{3298struct read_ref_at_cb *cb = cb_data;32993300 cb->reccnt++;3301 cb->tz = tz;3302 cb->date = timestamp;33033304if(timestamp <= cb->at_time || cb->cnt ==0) {3305if(cb->msg)3306*cb->msg =xstrdup(message);3307if(cb->cutoff_time)3308*cb->cutoff_time = timestamp;3309if(cb->cutoff_tz)3310*cb->cutoff_tz = tz;3311if(cb->cutoff_cnt)3312*cb->cutoff_cnt = cb->reccnt -1;3313/*3314 * we have not yet updated cb->[n|o]sha1 so they still3315 * hold the values for the previous record.3316 */3317if(!is_null_sha1(cb->osha1)) {3318hashcpy(cb->sha1, nsha1);3319if(hashcmp(cb->osha1, nsha1))3320warning("Log for ref%shas gap after%s.",3321 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3322}3323else if(cb->date == cb->at_time)3324hashcpy(cb->sha1, nsha1);3325else if(hashcmp(nsha1, cb->sha1))3326warning("Log for ref%sunexpectedly ended on%s.",3327 cb->refname,show_date(cb->date, cb->tz,3328 DATE_RFC2822));3329hashcpy(cb->osha1, osha1);3330hashcpy(cb->nsha1, nsha1);3331 cb->found_it =1;3332return1;3333}3334hashcpy(cb->osha1, osha1);3335hashcpy(cb->nsha1, nsha1);3336if(cb->cnt >0)3337 cb->cnt--;3338return0;3339}33403341static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3342const char*email,unsigned long timestamp,3343int tz,const char*message,void*cb_data)3344{3345struct read_ref_at_cb *cb = cb_data;33463347if(cb->msg)3348*cb->msg =xstrdup(message);3349if(cb->cutoff_time)3350*cb->cutoff_time = timestamp;3351if(cb->cutoff_tz)3352*cb->cutoff_tz = tz;3353if(cb->cutoff_cnt)3354*cb->cutoff_cnt = cb->reccnt;3355hashcpy(cb->sha1, osha1);3356if(is_null_sha1(cb->sha1))3357hashcpy(cb->sha1, nsha1);3358/* We just want the first entry */3359return1;3360}33613362intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3363unsigned char*sha1,char**msg,3364unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3365{3366struct read_ref_at_cb cb;33673368memset(&cb,0,sizeof(cb));3369 cb.refname = refname;3370 cb.at_time = at_time;3371 cb.cnt = cnt;3372 cb.msg = msg;3373 cb.cutoff_time = cutoff_time;3374 cb.cutoff_tz = cutoff_tz;3375 cb.cutoff_cnt = cutoff_cnt;3376 cb.sha1 = sha1;33773378for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);33793380if(!cb.reccnt) {3381if(flags & GET_SHA1_QUIETLY)3382exit(128);3383else3384die("Log for%sis empty.", refname);3385}3386if(cb.found_it)3387return0;33883389for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);33903391return1;3392}33933394intreflog_exists(const char*refname)3395{3396struct stat st;33973398return!lstat(git_path("logs/%s", refname), &st) &&3399S_ISREG(st.st_mode);3400}34013402intdelete_reflog(const char*refname)3403{3404returnremove_path(git_path("logs/%s", refname));3405}34063407static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3408{3409unsigned char osha1[20], nsha1[20];3410char*email_end, *message;3411unsigned long timestamp;3412int tz;34133414/* old SP new SP name <email> SP time TAB msg LF */3415if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3416get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3417get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3418!(email_end =strchr(sb->buf +82,'>')) ||3419 email_end[1] !=' '||3420!(timestamp =strtoul(email_end +2, &message,10)) ||3421!message || message[0] !=' '||3422(message[1] !='+'&& message[1] !='-') ||3423!isdigit(message[2]) || !isdigit(message[3]) ||3424!isdigit(message[4]) || !isdigit(message[5]))3425return0;/* corrupt? */3426 email_end[1] ='\0';3427 tz =strtol(message +1, NULL,10);3428if(message[6] !='\t')3429 message +=6;3430else3431 message +=7;3432returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3433}34343435static char*find_beginning_of_line(char*bob,char*scan)3436{3437while(bob < scan && *(--scan) !='\n')3438;/* keep scanning backwards */3439/*3440 * Return either beginning of the buffer, or LF at the end of3441 * the previous line.3442 */3443return scan;3444}34453446intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3447{3448struct strbuf sb = STRBUF_INIT;3449FILE*logfp;3450long pos;3451int ret =0, at_tail =1;34523453 logfp =fopen(git_path("logs/%s", refname),"r");3454if(!logfp)3455return-1;34563457/* Jump to the end */3458if(fseek(logfp,0, SEEK_END) <0)3459returnerror("cannot seek back reflog for%s:%s",3460 refname,strerror(errno));3461 pos =ftell(logfp);3462while(!ret &&0< pos) {3463int cnt;3464size_t nread;3465char buf[BUFSIZ];3466char*endp, *scanp;34673468/* Fill next block from the end */3469 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3470if(fseek(logfp, pos - cnt, SEEK_SET))3471returnerror("cannot seek back reflog for%s:%s",3472 refname,strerror(errno));3473 nread =fread(buf, cnt,1, logfp);3474if(nread !=1)3475returnerror("cannot read%dbytes from reflog for%s:%s",3476 cnt, refname,strerror(errno));3477 pos -= cnt;34783479 scanp = endp = buf + cnt;3480if(at_tail && scanp[-1] =='\n')3481/* Looking at the final LF at the end of the file */3482 scanp--;3483 at_tail =0;34843485while(buf < scanp) {3486/*3487 * terminating LF of the previous line, or the beginning3488 * of the buffer.3489 */3490char*bp;34913492 bp =find_beginning_of_line(buf, scanp);34933494if(*bp =='\n') {3495/*3496 * The newline is the end of the previous line,3497 * so we know we have complete line starting3498 * at (bp + 1). Prefix it onto any prior data3499 * we collected for the line and process it.3500 */3501strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3502 scanp = bp;3503 endp = bp +1;3504 ret =show_one_reflog_ent(&sb, fn, cb_data);3505strbuf_reset(&sb);3506if(ret)3507break;3508}else if(!pos) {3509/*3510 * We are at the start of the buffer, and the3511 * start of the file; there is no previous3512 * line, and we have everything for this one.3513 * Process it, and we can end the loop.3514 */3515strbuf_splice(&sb,0,0, buf, endp - buf);3516 ret =show_one_reflog_ent(&sb, fn, cb_data);3517strbuf_reset(&sb);3518break;3519}35203521if(bp == buf) {3522/*3523 * We are at the start of the buffer, and there3524 * is more file to read backwards. Which means3525 * we are in the middle of a line. Note that we3526 * may get here even if *bp was a newline; that3527 * just means we are at the exact end of the3528 * previous line, rather than some spot in the3529 * middle.3530 *3531 * Save away what we have to be combined with3532 * the data from the next read.3533 */3534strbuf_splice(&sb,0,0, buf, endp - buf);3535break;3536}3537}35383539}3540if(!ret && sb.len)3541die("BUG: reverse reflog parser had leftover data");35423543fclose(logfp);3544strbuf_release(&sb);3545return ret;3546}35473548intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3549{3550FILE*logfp;3551struct strbuf sb = STRBUF_INIT;3552int ret =0;35533554 logfp =fopen(git_path("logs/%s", refname),"r");3555if(!logfp)3556return-1;35573558while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3559 ret =show_one_reflog_ent(&sb, fn, cb_data);3560fclose(logfp);3561strbuf_release(&sb);3562return ret;3563}3564/*3565 * Call fn for each reflog in the namespace indicated by name. name3566 * must be empty or end with '/'. Name will be used as a scratch3567 * space, but its contents will be restored before return.3568 */3569static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3570{3571DIR*d =opendir(git_path("logs/%s", name->buf));3572int retval =0;3573struct dirent *de;3574int oldlen = name->len;35753576if(!d)3577return name->len ? errno :0;35783579while((de =readdir(d)) != NULL) {3580struct stat st;35813582if(de->d_name[0] =='.')3583continue;3584if(ends_with(de->d_name,".lock"))3585continue;3586strbuf_addstr(name, de->d_name);3587if(stat(git_path("logs/%s", name->buf), &st) <0) {3588;/* silently ignore */3589}else{3590if(S_ISDIR(st.st_mode)) {3591strbuf_addch(name,'/');3592 retval =do_for_each_reflog(name, fn, cb_data);3593}else{3594unsigned char sha1[20];3595if(read_ref_full(name->buf,0, sha1, NULL))3596 retval =error("bad ref for%s", name->buf);3597else3598 retval =fn(name->buf, sha1,0, cb_data);3599}3600if(retval)3601break;3602}3603strbuf_setlen(name, oldlen);3604}3605closedir(d);3606return retval;3607}36083609intfor_each_reflog(each_ref_fn fn,void*cb_data)3610{3611int retval;3612struct strbuf name;3613strbuf_init(&name, PATH_MAX);3614 retval =do_for_each_reflog(&name, fn, cb_data);3615strbuf_release(&name);3616return retval;3617}36183619/**3620 * Information needed for a single ref update. Set new_sha1 to the new3621 * value or to null_sha1 to delete the ref. To check the old value3622 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3623 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3624 * not exist before update.3625 */3626struct ref_update {3627/*3628 * If (flags & REF_HAVE_NEW), set the reference to this value:3629 */3630unsigned char new_sha1[20];3631/*3632 * If (flags & REF_HAVE_OLD), check that the reference3633 * previously had this value:3634 */3635unsigned char old_sha1[20];3636/*3637 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3638 * REF_DELETING, and REF_ISPRUNING:3639 */3640unsigned int flags;3641struct ref_lock *lock;3642int type;3643char*msg;3644const char refname[FLEX_ARRAY];3645};36463647/*3648 * Transaction states.3649 * OPEN: The transaction is in a valid state and can accept new updates.3650 * An OPEN transaction can be committed.3651 * CLOSED: A closed transaction is no longer active and no other operations3652 * than free can be used on it in this state.3653 * A transaction can either become closed by successfully committing3654 * an active transaction or if there is a failure while building3655 * the transaction thus rendering it failed/inactive.3656 */3657enum ref_transaction_state {3658 REF_TRANSACTION_OPEN =0,3659 REF_TRANSACTION_CLOSED =13660};36613662/*3663 * Data structure for holding a reference transaction, which can3664 * consist of checks and updates to multiple references, carried out3665 * as atomically as possible. This structure is opaque to callers.3666 */3667struct ref_transaction {3668struct ref_update **updates;3669size_t alloc;3670size_t nr;3671enum ref_transaction_state state;3672};36733674struct ref_transaction *ref_transaction_begin(struct strbuf *err)3675{3676assert(err);36773678returnxcalloc(1,sizeof(struct ref_transaction));3679}36803681voidref_transaction_free(struct ref_transaction *transaction)3682{3683int i;36843685if(!transaction)3686return;36873688for(i =0; i < transaction->nr; i++) {3689free(transaction->updates[i]->msg);3690free(transaction->updates[i]);3691}3692free(transaction->updates);3693free(transaction);3694}36953696static struct ref_update *add_update(struct ref_transaction *transaction,3697const char*refname)3698{3699size_t len =strlen(refname);3700struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);37013702strcpy((char*)update->refname, refname);3703ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3704 transaction->updates[transaction->nr++] = update;3705return update;3706}37073708intref_transaction_update(struct ref_transaction *transaction,3709const char*refname,3710const unsigned char*new_sha1,3711const unsigned char*old_sha1,3712unsigned int flags,const char*msg,3713struct strbuf *err)3714{3715struct ref_update *update;37163717assert(err);37183719if(transaction->state != REF_TRANSACTION_OPEN)3720die("BUG: update called for transaction that is not open");37213722if(new_sha1 && !is_null_sha1(new_sha1) &&3723check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3724strbuf_addf(err,"refusing to update ref with bad name%s",3725 refname);3726return-1;3727}37283729 update =add_update(transaction, refname);3730if(new_sha1) {3731hashcpy(update->new_sha1, new_sha1);3732 flags |= REF_HAVE_NEW;3733}3734if(old_sha1) {3735hashcpy(update->old_sha1, old_sha1);3736 flags |= REF_HAVE_OLD;3737}3738 update->flags = flags;3739if(msg)3740 update->msg =xstrdup(msg);3741return0;3742}37433744intref_transaction_create(struct ref_transaction *transaction,3745const char*refname,3746const unsigned char*new_sha1,3747unsigned int flags,const char*msg,3748struct strbuf *err)3749{3750if(!new_sha1 ||is_null_sha1(new_sha1))3751die("BUG: create called without valid new_sha1");3752returnref_transaction_update(transaction, refname, new_sha1,3753 null_sha1, flags, msg, err);3754}37553756intref_transaction_delete(struct ref_transaction *transaction,3757const char*refname,3758const unsigned char*old_sha1,3759unsigned int flags,const char*msg,3760struct strbuf *err)3761{3762if(old_sha1 &&is_null_sha1(old_sha1))3763die("BUG: delete called with old_sha1 set to zeros");3764returnref_transaction_update(transaction, refname,3765 null_sha1, old_sha1,3766 flags, msg, err);3767}37683769intref_transaction_verify(struct ref_transaction *transaction,3770const char*refname,3771const unsigned char*old_sha1,3772unsigned int flags,3773struct strbuf *err)3774{3775if(!old_sha1)3776die("BUG: verify called with old_sha1 set to NULL");3777returnref_transaction_update(transaction, refname,3778 NULL, old_sha1,3779 flags, NULL, err);3780}37813782intupdate_ref(const char*msg,const char*refname,3783const unsigned char*new_sha1,const unsigned char*old_sha1,3784unsigned int flags,enum action_on_err onerr)3785{3786struct ref_transaction *t;3787struct strbuf err = STRBUF_INIT;37883789 t =ref_transaction_begin(&err);3790if(!t ||3791ref_transaction_update(t, refname, new_sha1, old_sha1,3792 flags, msg, &err) ||3793ref_transaction_commit(t, &err)) {3794const char*str ="update_ref failed for ref '%s':%s";37953796ref_transaction_free(t);3797switch(onerr) {3798case UPDATE_REFS_MSG_ON_ERR:3799error(str, refname, err.buf);3800break;3801case UPDATE_REFS_DIE_ON_ERR:3802die(str, refname, err.buf);3803break;3804case UPDATE_REFS_QUIET_ON_ERR:3805break;3806}3807strbuf_release(&err);3808return1;3809}3810strbuf_release(&err);3811ref_transaction_free(t);3812return0;3813}38143815static intref_update_reject_duplicates(struct string_list *refnames,3816struct strbuf *err)3817{3818int i, n = refnames->nr;38193820assert(err);38213822for(i =1; i < n; i++)3823if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3824strbuf_addf(err,3825"Multiple updates for ref '%s' not allowed.",3826 refnames->items[i].string);3827return1;3828}3829return0;3830}38313832intref_transaction_commit(struct ref_transaction *transaction,3833struct strbuf *err)3834{3835int ret =0, i;3836int n = transaction->nr;3837struct ref_update **updates = transaction->updates;3838struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3839struct string_list_item *ref_to_delete;3840struct string_list affected_refnames = STRING_LIST_INIT_NODUP;38413842assert(err);38433844if(transaction->state != REF_TRANSACTION_OPEN)3845die("BUG: commit called for transaction that is not open");38463847if(!n) {3848 transaction->state = REF_TRANSACTION_CLOSED;3849return0;3850}38513852/* Fail if a refname appears more than once in the transaction: */3853for(i =0; i < n; i++)3854string_list_append(&affected_refnames, updates[i]->refname);3855string_list_sort(&affected_refnames);3856if(ref_update_reject_duplicates(&affected_refnames, err)) {3857 ret = TRANSACTION_GENERIC_ERROR;3858goto cleanup;3859}38603861/*3862 * Acquire all locks, verify old values if provided, check3863 * that new values are valid, and write new values to the3864 * lockfiles, ready to be activated. Only keep one lockfile3865 * open at a time to avoid running out of file descriptors.3866 */3867for(i =0; i < n; i++) {3868struct ref_update *update = updates[i];38693870if((update->flags & REF_HAVE_NEW) &&3871is_null_sha1(update->new_sha1))3872 update->flags |= REF_DELETING;3873 update->lock =lock_ref_sha1_basic(3874 update->refname,3875((update->flags & REF_HAVE_OLD) ?3876 update->old_sha1 : NULL),3877&affected_refnames, NULL,3878 update->flags,3879&update->type,3880 err);3881if(!update->lock) {3882char*reason;38833884 ret = (errno == ENOTDIR)3885? TRANSACTION_NAME_CONFLICT3886: TRANSACTION_GENERIC_ERROR;3887 reason =strbuf_detach(err, NULL);3888strbuf_addf(err,"Cannot lock ref '%s':%s",3889 update->refname, reason);3890free(reason);3891goto cleanup;3892}3893if((update->flags & REF_HAVE_NEW) &&3894!(update->flags & REF_DELETING)) {3895int overwriting_symref = ((update->type & REF_ISSYMREF) &&3896(update->flags & REF_NODEREF));38973898if(!overwriting_symref &&3899!hashcmp(update->lock->old_sha1, update->new_sha1)) {3900/*3901 * The reference already has the desired3902 * value, so we don't need to write it.3903 */3904}else if(write_ref_to_lockfile(update->lock,3905 update->new_sha1)) {3906/*3907 * The lock was freed upon failure of3908 * write_ref_to_lockfile():3909 */3910 update->lock = NULL;3911strbuf_addf(err,"Cannot update the ref '%s'.",3912 update->refname);3913 ret = TRANSACTION_GENERIC_ERROR;3914goto cleanup;3915}else{3916 update->flags |= REF_NEEDS_COMMIT;3917}3918}3919if(!(update->flags & REF_NEEDS_COMMIT)) {3920/*3921 * We didn't have to write anything to the lockfile.3922 * Close it to free up the file descriptor:3923 */3924if(close_ref(update->lock)) {3925strbuf_addf(err,"Couldn't close%s.lock",3926 update->refname);3927goto cleanup;3928}3929}3930}39313932/* Perform updates first so live commits remain referenced */3933for(i =0; i < n; i++) {3934struct ref_update *update = updates[i];39353936if(update->flags & REF_NEEDS_COMMIT) {3937if(commit_ref_update(update->lock,3938 update->new_sha1, update->msg)) {3939/* freed by commit_ref_update(): */3940 update->lock = NULL;3941strbuf_addf(err,"Cannot update the ref '%s'.",3942 update->refname);3943 ret = TRANSACTION_GENERIC_ERROR;3944goto cleanup;3945}else{3946/* freed by commit_ref_update(): */3947 update->lock = NULL;3948}3949}3950}39513952/* Perform deletes now that updates are safely completed */3953for(i =0; i < n; i++) {3954struct ref_update *update = updates[i];39553956if(update->flags & REF_DELETING) {3957if(delete_ref_loose(update->lock, update->type, err)) {3958 ret = TRANSACTION_GENERIC_ERROR;3959goto cleanup;3960}39613962if(!(update->flags & REF_ISPRUNING))3963string_list_append(&refs_to_delete,3964 update->lock->ref_name);3965}3966}39673968if(repack_without_refs(&refs_to_delete, err)) {3969 ret = TRANSACTION_GENERIC_ERROR;3970goto cleanup;3971}3972for_each_string_list_item(ref_to_delete, &refs_to_delete)3973unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3974clear_loose_ref_cache(&ref_cache);39753976cleanup:3977 transaction->state = REF_TRANSACTION_CLOSED;39783979for(i =0; i < n; i++)3980if(updates[i]->lock)3981unlock_ref(updates[i]->lock);3982string_list_clear(&refs_to_delete,0);3983string_list_clear(&affected_refnames,0);3984return ret;3985}39863987char*shorten_unambiguous_ref(const char*refname,int strict)3988{3989int i;3990static char**scanf_fmts;3991static int nr_rules;3992char*short_name;39933994if(!nr_rules) {3995/*3996 * Pre-generate scanf formats from ref_rev_parse_rules[].3997 * Generate a format suitable for scanf from a3998 * ref_rev_parse_rules rule by interpolating "%s" at the3999 * location of the "%.*s".4000 */4001size_t total_len =0;4002size_t offset =0;40034004/* the rule list is NULL terminated, count them first */4005for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4006/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4007 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;40084009 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);40104011 offset =0;4012for(i =0; i < nr_rules; i++) {4013assert(offset < total_len);4014 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4015 offset +=snprintf(scanf_fmts[i], total_len - offset,4016 ref_rev_parse_rules[i],2,"%s") +1;4017}4018}40194020/* bail out if there are no rules */4021if(!nr_rules)4022returnxstrdup(refname);40234024/* buffer for scanf result, at most refname must fit */4025 short_name =xstrdup(refname);40264027/* skip first rule, it will always match */4028for(i = nr_rules -1; i >0; --i) {4029int j;4030int rules_to_fail = i;4031int short_name_len;40324033if(1!=sscanf(refname, scanf_fmts[i], short_name))4034continue;40354036 short_name_len =strlen(short_name);40374038/*4039 * in strict mode, all (except the matched one) rules4040 * must fail to resolve to a valid non-ambiguous ref4041 */4042if(strict)4043 rules_to_fail = nr_rules;40444045/*4046 * check if the short name resolves to a valid ref,4047 * but use only rules prior to the matched one4048 */4049for(j =0; j < rules_to_fail; j++) {4050const char*rule = ref_rev_parse_rules[j];4051char refname[PATH_MAX];40524053/* skip matched rule */4054if(i == j)4055continue;40564057/*4058 * the short name is ambiguous, if it resolves4059 * (with this previous rule) to a valid ref4060 * read_ref() returns 0 on success4061 */4062mksnpath(refname,sizeof(refname),4063 rule, short_name_len, short_name);4064if(ref_exists(refname))4065break;4066}40674068/*4069 * short name is non-ambiguous if all previous rules4070 * haven't resolved to a valid ref4071 */4072if(j == rules_to_fail)4073return short_name;4074}40754076free(short_name);4077returnxstrdup(refname);4078}40794080static struct string_list *hide_refs;40814082intparse_hide_refs_config(const char*var,const char*value,const char*section)4083{4084if(!strcmp("transfer.hiderefs", var) ||4085/* NEEDSWORK: use parse_config_key() once both are merged */4086(starts_with(var, section) && var[strlen(section)] =='.'&&4087!strcmp(var +strlen(section),".hiderefs"))) {4088char*ref;4089int len;40904091if(!value)4092returnconfig_error_nonbool(var);4093 ref =xstrdup(value);4094 len =strlen(ref);4095while(len && ref[len -1] =='/')4096 ref[--len] ='\0';4097if(!hide_refs) {4098 hide_refs =xcalloc(1,sizeof(*hide_refs));4099 hide_refs->strdup_strings =1;4100}4101string_list_append(hide_refs, ref);4102}4103return0;4104}41054106intref_is_hidden(const char*refname)4107{4108struct string_list_item *item;41094110if(!hide_refs)4111return0;4112for_each_string_list_item(item, hide_refs) {4113int len;4114if(!starts_with(refname, item->string))4115continue;4116 len =strlen(item->string);4117if(!refname[len] || refname[len] =='/')4118return1;4119}4120return0;4121}41224123struct expire_reflog_cb {4124unsigned int flags;4125 reflog_expiry_should_prune_fn *should_prune_fn;4126void*policy_cb;4127FILE*newlog;4128unsigned char last_kept_sha1[20];4129};41304131static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4132const char*email,unsigned long timestamp,int tz,4133const char*message,void*cb_data)4134{4135struct expire_reflog_cb *cb = cb_data;4136struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;41374138if(cb->flags & EXPIRE_REFLOGS_REWRITE)4139 osha1 = cb->last_kept_sha1;41404141if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4142 message, policy_cb)) {4143if(!cb->newlog)4144printf("would prune%s", message);4145else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4146printf("prune%s", message);4147}else{4148if(cb->newlog) {4149fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4150sha1_to_hex(osha1),sha1_to_hex(nsha1),4151 email, timestamp, tz, message);4152hashcpy(cb->last_kept_sha1, nsha1);4153}4154if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4155printf("keep%s", message);4156}4157return0;4158}41594160intreflog_expire(const char*refname,const unsigned char*sha1,4161unsigned int flags,4162 reflog_expiry_prepare_fn prepare_fn,4163 reflog_expiry_should_prune_fn should_prune_fn,4164 reflog_expiry_cleanup_fn cleanup_fn,4165void*policy_cb_data)4166{4167static struct lock_file reflog_lock;4168struct expire_reflog_cb cb;4169struct ref_lock *lock;4170char*log_file;4171int status =0;4172int type;4173struct strbuf err = STRBUF_INIT;41744175memset(&cb,0,sizeof(cb));4176 cb.flags = flags;4177 cb.policy_cb = policy_cb_data;4178 cb.should_prune_fn = should_prune_fn;41794180/*4181 * The reflog file is locked by holding the lock on the4182 * reference itself, plus we might need to update the4183 * reference if --updateref was specified:4184 */4185 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4186if(!lock) {4187error("cannot lock ref '%s':%s", refname, err.buf);4188strbuf_release(&err);4189return-1;4190}4191if(!reflog_exists(refname)) {4192unlock_ref(lock);4193return0;4194}41954196 log_file =git_pathdup("logs/%s", refname);4197if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4198/*4199 * Even though holding $GIT_DIR/logs/$reflog.lock has4200 * no locking implications, we use the lock_file4201 * machinery here anyway because it does a lot of the4202 * work we need, including cleaning up if the program4203 * exits unexpectedly.4204 */4205if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4206struct strbuf err = STRBUF_INIT;4207unable_to_lock_message(log_file, errno, &err);4208error("%s", err.buf);4209strbuf_release(&err);4210goto failure;4211}4212 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4213if(!cb.newlog) {4214error("cannot fdopen%s(%s)",4215 reflog_lock.filename.buf,strerror(errno));4216goto failure;4217}4218}42194220(*prepare_fn)(refname, sha1, cb.policy_cb);4221for_each_reflog_ent(refname, expire_reflog_ent, &cb);4222(*cleanup_fn)(cb.policy_cb);42234224if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4225/*4226 * It doesn't make sense to adjust a reference pointed4227 * to by a symbolic ref based on expiring entries in4228 * the symbolic reference's reflog. Nor can we update4229 * a reference if there are no remaining reflog4230 * entries.4231 */4232int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4233!(type & REF_ISSYMREF) &&4234!is_null_sha1(cb.last_kept_sha1);42354236if(close_lock_file(&reflog_lock)) {4237 status |=error("couldn't write%s:%s", log_file,4238strerror(errno));4239}else if(update &&4240(write_in_full(lock->lock_fd,4241sha1_to_hex(cb.last_kept_sha1),40) !=40||4242write_str_in_full(lock->lock_fd,"\n") !=1||4243close_ref(lock) <0)) {4244 status |=error("couldn't write%s",4245 lock->lk->filename.buf);4246rollback_lock_file(&reflog_lock);4247}else if(commit_lock_file(&reflog_lock)) {4248 status |=error("unable to commit reflog '%s' (%s)",4249 log_file,strerror(errno));4250}else if(update &&commit_ref(lock)) {4251 status |=error("couldn't set%s", lock->ref_name);4252}4253}4254free(log_file);4255unlock_ref(lock);4256return status;42574258 failure:4259rollback_lock_file(&reflog_lock);4260free(log_file);4261unlock_ref(lock);4262return-1;4263}