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{1377if(*refs->name) {1378hashclr(sha1);1379 flag =0;1380if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1381hashclr(sha1);1382 flag |= REF_ISBROKEN;1383}1384}else if(read_ref_full(refname.buf,1385 RESOLVE_REF_READING,1386 sha1, &flag)) {1387hashclr(sha1);1388 flag |= REF_ISBROKEN;1389}1390if(check_refname_format(refname.buf,1391 REFNAME_ALLOW_ONELEVEL)) {1392hashclr(sha1);1393 flag |= REF_BAD_NAME | REF_ISBROKEN;1394}1395add_entry_to_dir(dir,1396create_ref_entry(refname.buf, sha1, flag,0));1397}1398strbuf_setlen(&refname, dirnamelen);1399}1400strbuf_release(&refname);1401closedir(d);1402}14031404static struct ref_dir *get_loose_refs(struct ref_cache *refs)1405{1406if(!refs->loose) {1407/*1408 * Mark the top-level directory complete because we1409 * are about to read the only subdirectory that can1410 * hold references:1411 */1412 refs->loose =create_dir_entry(refs,"",0,0);1413/*1414 * Create an incomplete entry for "refs/":1415 */1416add_entry_to_dir(get_ref_dir(refs->loose),1417create_dir_entry(refs,"refs/",5,1));1418}1419returnget_ref_dir(refs->loose);1420}14211422/* We allow "recursive" symbolic refs. Only within reason, though */1423#define MAXDEPTH 51424#define MAXREFLEN (1024)14251426/*1427 * Called by resolve_gitlink_ref_recursive() after it failed to read1428 * from the loose refs in ref_cache refs. Find <refname> in the1429 * packed-refs file for the submodule.1430 */1431static intresolve_gitlink_packed_ref(struct ref_cache *refs,1432const char*refname,unsigned char*sha1)1433{1434struct ref_entry *ref;1435struct ref_dir *dir =get_packed_refs(refs);14361437 ref =find_ref(dir, refname);1438if(ref == NULL)1439return-1;14401441hashcpy(sha1, ref->u.value.sha1);1442return0;1443}14441445static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1446const char*refname,unsigned char*sha1,1447int recursion)1448{1449int fd, len;1450char buffer[128], *p;1451char*path;14521453if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1454return-1;1455 path = *refs->name1456?git_path_submodule(refs->name,"%s", refname)1457:git_path("%s", refname);1458 fd =open(path, O_RDONLY);1459if(fd <0)1460returnresolve_gitlink_packed_ref(refs, refname, sha1);14611462 len =read(fd, buffer,sizeof(buffer)-1);1463close(fd);1464if(len <0)1465return-1;1466while(len &&isspace(buffer[len-1]))1467 len--;1468 buffer[len] =0;14691470/* Was it a detached head or an old-fashioned symlink? */1471if(!get_sha1_hex(buffer, sha1))1472return0;14731474/* Symref? */1475if(strncmp(buffer,"ref:",4))1476return-1;1477 p = buffer +4;1478while(isspace(*p))1479 p++;14801481returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1482}14831484intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1485{1486int len =strlen(path), retval;1487char*submodule;1488struct ref_cache *refs;14891490while(len && path[len-1] =='/')1491 len--;1492if(!len)1493return-1;1494 submodule =xstrndup(path, len);1495 refs =get_ref_cache(submodule);1496free(submodule);14971498 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1499return retval;1500}15011502/*1503 * Return the ref_entry for the given refname from the packed1504 * references. If it does not exist, return NULL.1505 */1506static struct ref_entry *get_packed_ref(const char*refname)1507{1508returnfind_ref(get_packed_refs(&ref_cache), refname);1509}15101511/*1512 * A loose ref file doesn't exist; check for a packed ref. The1513 * options are forwarded from resolve_safe_unsafe().1514 */1515static intresolve_missing_loose_ref(const char*refname,1516int resolve_flags,1517unsigned char*sha1,1518int*flags)1519{1520struct ref_entry *entry;15211522/*1523 * The loose reference file does not exist; check for a packed1524 * reference.1525 */1526 entry =get_packed_ref(refname);1527if(entry) {1528hashcpy(sha1, entry->u.value.sha1);1529if(flags)1530*flags |= REF_ISPACKED;1531return0;1532}1533/* The reference is not a packed reference, either. */1534if(resolve_flags & RESOLVE_REF_READING) {1535 errno = ENOENT;1536return-1;1537}else{1538hashclr(sha1);1539return0;1540}1541}15421543/* This function needs to return a meaningful errno on failure */1544const char*resolve_ref_unsafe(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1545{1546int depth = MAXDEPTH;1547 ssize_t len;1548char buffer[256];1549static char refname_buffer[256];1550int bad_name =0;15511552if(flags)1553*flags =0;15541555if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1556if(flags)1557*flags |= REF_BAD_NAME;15581559if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1560!refname_is_safe(refname)) {1561 errno = EINVAL;1562return NULL;1563}1564/*1565 * dwim_ref() uses REF_ISBROKEN to distinguish between1566 * missing refs and refs that were present but invalid,1567 * to complain about the latter to stderr.1568 *1569 * We don't know whether the ref exists, so don't set1570 * REF_ISBROKEN yet.1571 */1572 bad_name =1;1573}1574for(;;) {1575char path[PATH_MAX];1576struct stat st;1577char*buf;1578int fd;15791580if(--depth <0) {1581 errno = ELOOP;1582return NULL;1583}15841585git_snpath(path,sizeof(path),"%s", refname);15861587/*1588 * We might have to loop back here to avoid a race1589 * condition: first we lstat() the file, then we try1590 * to read it as a link or as a file. But if somebody1591 * changes the type of the file (file <-> directory1592 * <-> symlink) between the lstat() and reading, then1593 * we don't want to report that as an error but rather1594 * try again starting with the lstat().1595 */1596 stat_ref:1597if(lstat(path, &st) <0) {1598if(errno != ENOENT)1599return NULL;1600if(resolve_missing_loose_ref(refname, resolve_flags,1601 sha1, flags))1602return NULL;1603if(bad_name) {1604hashclr(sha1);1605if(flags)1606*flags |= REF_ISBROKEN;1607}1608return refname;1609}16101611/* Follow "normalized" - ie "refs/.." symlinks by hand */1612if(S_ISLNK(st.st_mode)) {1613 len =readlink(path, buffer,sizeof(buffer)-1);1614if(len <0) {1615if(errno == ENOENT || errno == EINVAL)1616/* inconsistent with lstat; retry */1617goto stat_ref;1618else1619return NULL;1620}1621 buffer[len] =0;1622if(starts_with(buffer,"refs/") &&1623!check_refname_format(buffer,0)) {1624strcpy(refname_buffer, buffer);1625 refname = refname_buffer;1626if(flags)1627*flags |= REF_ISSYMREF;1628if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1629hashclr(sha1);1630return refname;1631}1632continue;1633}1634}16351636/* Is it a directory? */1637if(S_ISDIR(st.st_mode)) {1638 errno = EISDIR;1639return NULL;1640}16411642/*1643 * Anything else, just open it and try to use it as1644 * a ref1645 */1646 fd =open(path, O_RDONLY);1647if(fd <0) {1648if(errno == ENOENT)1649/* inconsistent with lstat; retry */1650goto stat_ref;1651else1652return NULL;1653}1654 len =read_in_full(fd, buffer,sizeof(buffer)-1);1655if(len <0) {1656int save_errno = errno;1657close(fd);1658 errno = save_errno;1659return NULL;1660}1661close(fd);1662while(len &&isspace(buffer[len-1]))1663 len--;1664 buffer[len] ='\0';16651666/*1667 * Is it a symbolic ref?1668 */1669if(!starts_with(buffer,"ref:")) {1670/*1671 * Please note that FETCH_HEAD has a second1672 * line containing other data.1673 */1674if(get_sha1_hex(buffer, sha1) ||1675(buffer[40] !='\0'&& !isspace(buffer[40]))) {1676if(flags)1677*flags |= REF_ISBROKEN;1678 errno = EINVAL;1679return NULL;1680}1681if(bad_name) {1682hashclr(sha1);1683if(flags)1684*flags |= REF_ISBROKEN;1685}1686return refname;1687}1688if(flags)1689*flags |= REF_ISSYMREF;1690 buf = buffer +4;1691while(isspace(*buf))1692 buf++;1693 refname =strcpy(refname_buffer, buf);1694if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1695hashclr(sha1);1696return refname;1697}1698if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1699if(flags)1700*flags |= REF_ISBROKEN;17011702if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1703!refname_is_safe(buf)) {1704 errno = EINVAL;1705return NULL;1706}1707 bad_name =1;1708}1709}1710}17111712char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1713{1714returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1715}17161717/* The argument to filter_refs */1718struct ref_filter {1719const char*pattern;1720 each_ref_fn *fn;1721void*cb_data;1722};17231724intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1725{1726if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1727return0;1728return-1;1729}17301731intread_ref(const char*refname,unsigned char*sha1)1732{1733returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1734}17351736intref_exists(const char*refname)1737{1738unsigned char sha1[20];1739return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1740}17411742static intfilter_refs(const char*refname,const unsigned char*sha1,int flags,1743void*data)1744{1745struct ref_filter *filter = (struct ref_filter *)data;1746if(wildmatch(filter->pattern, refname,0, NULL))1747return0;1748return filter->fn(refname, sha1, flags, filter->cb_data);1749}17501751enum peel_status {1752/* object was peeled successfully: */1753 PEEL_PEELED =0,17541755/*1756 * object cannot be peeled because the named object (or an1757 * object referred to by a tag in the peel chain), does not1758 * exist.1759 */1760 PEEL_INVALID = -1,17611762/* object cannot be peeled because it is not a tag: */1763 PEEL_NON_TAG = -2,17641765/* ref_entry contains no peeled value because it is a symref: */1766 PEEL_IS_SYMREF = -3,17671768/*1769 * ref_entry cannot be peeled because it is broken (i.e., the1770 * symbolic reference cannot even be resolved to an object1771 * name):1772 */1773 PEEL_BROKEN = -41774};17751776/*1777 * Peel the named object; i.e., if the object is a tag, resolve the1778 * tag recursively until a non-tag is found. If successful, store the1779 * result to sha1 and return PEEL_PEELED. If the object is not a tag1780 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1781 * and leave sha1 unchanged.1782 */1783static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1784{1785struct object *o =lookup_unknown_object(name);17861787if(o->type == OBJ_NONE) {1788int type =sha1_object_info(name, NULL);1789if(type <0|| !object_as_type(o, type,0))1790return PEEL_INVALID;1791}17921793if(o->type != OBJ_TAG)1794return PEEL_NON_TAG;17951796 o =deref_tag_noverify(o);1797if(!o)1798return PEEL_INVALID;17991800hashcpy(sha1, o->sha1);1801return PEEL_PEELED;1802}18031804/*1805 * Peel the entry (if possible) and return its new peel_status. If1806 * repeel is true, re-peel the entry even if there is an old peeled1807 * value that is already stored in it.1808 *1809 * It is OK to call this function with a packed reference entry that1810 * might be stale and might even refer to an object that has since1811 * been garbage-collected. In such a case, if the entry has1812 * REF_KNOWS_PEELED then leave the status unchanged and return1813 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1814 */1815static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1816{1817enum peel_status status;18181819if(entry->flag & REF_KNOWS_PEELED) {1820if(repeel) {1821 entry->flag &= ~REF_KNOWS_PEELED;1822hashclr(entry->u.value.peeled);1823}else{1824returnis_null_sha1(entry->u.value.peeled) ?1825 PEEL_NON_TAG : PEEL_PEELED;1826}1827}1828if(entry->flag & REF_ISBROKEN)1829return PEEL_BROKEN;1830if(entry->flag & REF_ISSYMREF)1831return PEEL_IS_SYMREF;18321833 status =peel_object(entry->u.value.sha1, entry->u.value.peeled);1834if(status == PEEL_PEELED || status == PEEL_NON_TAG)1835 entry->flag |= REF_KNOWS_PEELED;1836return status;1837}18381839intpeel_ref(const char*refname,unsigned char*sha1)1840{1841int flag;1842unsigned char base[20];18431844if(current_ref && (current_ref->name == refname1845|| !strcmp(current_ref->name, refname))) {1846if(peel_entry(current_ref,0))1847return-1;1848hashcpy(sha1, current_ref->u.value.peeled);1849return0;1850}18511852if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1853return-1;18541855/*1856 * If the reference is packed, read its ref_entry from the1857 * cache in the hope that we already know its peeled value.1858 * We only try this optimization on packed references because1859 * (a) forcing the filling of the loose reference cache could1860 * be expensive and (b) loose references anyway usually do not1861 * have REF_KNOWS_PEELED.1862 */1863if(flag & REF_ISPACKED) {1864struct ref_entry *r =get_packed_ref(refname);1865if(r) {1866if(peel_entry(r,0))1867return-1;1868hashcpy(sha1, r->u.value.peeled);1869return0;1870}1871}18721873returnpeel_object(base, sha1);1874}18751876struct warn_if_dangling_data {1877FILE*fp;1878const char*refname;1879const struct string_list *refnames;1880const char*msg_fmt;1881};18821883static intwarn_if_dangling_symref(const char*refname,const unsigned char*sha1,1884int flags,void*cb_data)1885{1886struct warn_if_dangling_data *d = cb_data;1887const char*resolves_to;1888unsigned char junk[20];18891890if(!(flags & REF_ISSYMREF))1891return0;18921893 resolves_to =resolve_ref_unsafe(refname,0, junk, NULL);1894if(!resolves_to1895|| (d->refname1896?strcmp(resolves_to, d->refname)1897: !string_list_has_string(d->refnames, resolves_to))) {1898return0;1899}19001901fprintf(d->fp, d->msg_fmt, refname);1902fputc('\n', d->fp);1903return0;1904}19051906voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1907{1908struct warn_if_dangling_data data;19091910 data.fp = fp;1911 data.refname = refname;1912 data.refnames = NULL;1913 data.msg_fmt = msg_fmt;1914for_each_rawref(warn_if_dangling_symref, &data);1915}19161917voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1918{1919struct warn_if_dangling_data data;19201921 data.fp = fp;1922 data.refname = NULL;1923 data.refnames = refnames;1924 data.msg_fmt = msg_fmt;1925for_each_rawref(warn_if_dangling_symref, &data);1926}19271928/*1929 * Call fn for each reference in the specified ref_cache, omitting1930 * references not in the containing_dir of base. fn is called for all1931 * references, including broken ones. If fn ever returns a non-zero1932 * value, stop the iteration and return that value; otherwise, return1933 * 0.1934 */1935static intdo_for_each_entry(struct ref_cache *refs,const char*base,1936 each_ref_entry_fn fn,void*cb_data)1937{1938struct packed_ref_cache *packed_ref_cache;1939struct ref_dir *loose_dir;1940struct ref_dir *packed_dir;1941int retval =0;19421943/*1944 * We must make sure that all loose refs are read before accessing the1945 * packed-refs file; this avoids a race condition in which loose refs1946 * are migrated to the packed-refs file by a simultaneous process, but1947 * our in-memory view is from before the migration. get_packed_ref_cache()1948 * takes care of making sure our view is up to date with what is on1949 * disk.1950 */1951 loose_dir =get_loose_refs(refs);1952if(base && *base) {1953 loose_dir =find_containing_dir(loose_dir, base,0);1954}1955if(loose_dir)1956prime_ref_dir(loose_dir);19571958 packed_ref_cache =get_packed_ref_cache(refs);1959acquire_packed_ref_cache(packed_ref_cache);1960 packed_dir =get_packed_ref_dir(packed_ref_cache);1961if(base && *base) {1962 packed_dir =find_containing_dir(packed_dir, base,0);1963}19641965if(packed_dir && loose_dir) {1966sort_ref_dir(packed_dir);1967sort_ref_dir(loose_dir);1968 retval =do_for_each_entry_in_dirs(1969 packed_dir, loose_dir, fn, cb_data);1970}else if(packed_dir) {1971sort_ref_dir(packed_dir);1972 retval =do_for_each_entry_in_dir(1973 packed_dir,0, fn, cb_data);1974}else if(loose_dir) {1975sort_ref_dir(loose_dir);1976 retval =do_for_each_entry_in_dir(1977 loose_dir,0, fn, cb_data);1978}19791980release_packed_ref_cache(packed_ref_cache);1981return retval;1982}19831984/*1985 * Call fn for each reference in the specified ref_cache for which the1986 * refname begins with base. If trim is non-zero, then trim that many1987 * characters off the beginning of each refname before passing the1988 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include1989 * broken references in the iteration. If fn ever returns a non-zero1990 * value, stop the iteration and return that value; otherwise, return1991 * 0.1992 */1993static intdo_for_each_ref(struct ref_cache *refs,const char*base,1994 each_ref_fn fn,int trim,int flags,void*cb_data)1995{1996struct ref_entry_cb data;1997 data.base = base;1998 data.trim = trim;1999 data.flags = flags;2000 data.fn = fn;2001 data.cb_data = cb_data;20022003if(ref_paranoia <0)2004 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2005if(ref_paranoia)2006 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20072008returndo_for_each_entry(refs, base, do_one_ref, &data);2009}20102011static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2012{2013unsigned char sha1[20];2014int flag;20152016if(submodule) {2017if(resolve_gitlink_ref(submodule,"HEAD", sha1) ==0)2018returnfn("HEAD", sha1,0, cb_data);20192020return0;2021}20222023if(!read_ref_full("HEAD", RESOLVE_REF_READING, sha1, &flag))2024returnfn("HEAD", sha1, flag, cb_data);20252026return0;2027}20282029inthead_ref(each_ref_fn fn,void*cb_data)2030{2031returndo_head_ref(NULL, fn, cb_data);2032}20332034inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2035{2036returndo_head_ref(submodule, fn, cb_data);2037}20382039intfor_each_ref(each_ref_fn fn,void*cb_data)2040{2041returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2042}20432044intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2045{2046returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2047}20482049intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2050{2051returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2052}20532054intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2055 each_ref_fn fn,void*cb_data)2056{2057returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2058}20592060intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2061{2062returnfor_each_ref_in("refs/tags/", fn, cb_data);2063}20642065intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2066{2067returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2068}20692070intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2071{2072returnfor_each_ref_in("refs/heads/", fn, cb_data);2073}20742075intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2076{2077returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2078}20792080intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2081{2082returnfor_each_ref_in("refs/remotes/", fn, cb_data);2083}20842085intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2086{2087returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2088}20892090intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2091{2092returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2093}20942095inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2096{2097struct strbuf buf = STRBUF_INIT;2098int ret =0;2099unsigned char sha1[20];2100int flag;21012102strbuf_addf(&buf,"%sHEAD",get_git_namespace());2103if(!read_ref_full(buf.buf, RESOLVE_REF_READING, sha1, &flag))2104 ret =fn(buf.buf, sha1, flag, cb_data);2105strbuf_release(&buf);21062107return ret;2108}21092110intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2111{2112struct strbuf buf = STRBUF_INIT;2113int ret;2114strbuf_addf(&buf,"%srefs/",get_git_namespace());2115 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2116strbuf_release(&buf);2117return ret;2118}21192120intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2121const char*prefix,void*cb_data)2122{2123struct strbuf real_pattern = STRBUF_INIT;2124struct ref_filter filter;2125int ret;21262127if(!prefix && !starts_with(pattern,"refs/"))2128strbuf_addstr(&real_pattern,"refs/");2129else if(prefix)2130strbuf_addstr(&real_pattern, prefix);2131strbuf_addstr(&real_pattern, pattern);21322133if(!has_glob_specials(pattern)) {2134/* Append implied '/' '*' if not present. */2135if(real_pattern.buf[real_pattern.len -1] !='/')2136strbuf_addch(&real_pattern,'/');2137/* No need to check for '*', there is none. */2138strbuf_addch(&real_pattern,'*');2139}21402141 filter.pattern = real_pattern.buf;2142 filter.fn = fn;2143 filter.cb_data = cb_data;2144 ret =for_each_ref(filter_refs, &filter);21452146strbuf_release(&real_pattern);2147return ret;2148}21492150intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2151{2152returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2153}21542155intfor_each_rawref(each_ref_fn fn,void*cb_data)2156{2157returndo_for_each_ref(&ref_cache,"", fn,0,2158 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2159}21602161const char*prettify_refname(const char*name)2162{2163return name + (2164starts_with(name,"refs/heads/") ?11:2165starts_with(name,"refs/tags/") ?10:2166starts_with(name,"refs/remotes/") ?13:21670);2168}21692170static const char*ref_rev_parse_rules[] = {2171"%.*s",2172"refs/%.*s",2173"refs/tags/%.*s",2174"refs/heads/%.*s",2175"refs/remotes/%.*s",2176"refs/remotes/%.*s/HEAD",2177 NULL2178};21792180intrefname_match(const char*abbrev_name,const char*full_name)2181{2182const char**p;2183const int abbrev_name_len =strlen(abbrev_name);21842185for(p = ref_rev_parse_rules; *p; p++) {2186if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2187return1;2188}2189}21902191return0;2192}21932194static voidunlock_ref(struct ref_lock *lock)2195{2196/* Do not free lock->lk -- atexit() still looks at them */2197if(lock->lk)2198rollback_lock_file(lock->lk);2199free(lock->ref_name);2200free(lock->orig_ref_name);2201free(lock);2202}22032204/* This function should make sure errno is meaningful on error */2205static struct ref_lock *verify_lock(struct ref_lock *lock,2206const unsigned char*old_sha1,int mustexist)2207{2208if(read_ref_full(lock->ref_name,2209 mustexist ? RESOLVE_REF_READING :0,2210 lock->old_sha1, NULL)) {2211int save_errno = errno;2212error("Can't verify ref%s", lock->ref_name);2213unlock_ref(lock);2214 errno = save_errno;2215return NULL;2216}2217if(hashcmp(lock->old_sha1, old_sha1)) {2218error("Ref%sis at%sbut expected%s", lock->ref_name,2219sha1_to_hex(lock->old_sha1),sha1_to_hex(old_sha1));2220unlock_ref(lock);2221 errno = EBUSY;2222return NULL;2223}2224return lock;2225}22262227static intremove_empty_directories(const char*file)2228{2229/* we want to create a file but there is a directory there;2230 * if that is an empty directory (or a directory that contains2231 * only empty directories), remove them.2232 */2233struct strbuf path;2234int result, save_errno;22352236strbuf_init(&path,20);2237strbuf_addstr(&path, file);22382239 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2240 save_errno = errno;22412242strbuf_release(&path);2243 errno = save_errno;22442245return result;2246}22472248/*2249 * *string and *len will only be substituted, and *string returned (for2250 * later free()ing) if the string passed in is a magic short-hand form2251 * to name a branch.2252 */2253static char*substitute_branch_name(const char**string,int*len)2254{2255struct strbuf buf = STRBUF_INIT;2256int ret =interpret_branch_name(*string, *len, &buf);22572258if(ret == *len) {2259size_t size;2260*string =strbuf_detach(&buf, &size);2261*len = size;2262return(char*)*string;2263}22642265return NULL;2266}22672268intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2269{2270char*last_branch =substitute_branch_name(&str, &len);2271const char**p, *r;2272int refs_found =0;22732274*ref = NULL;2275for(p = ref_rev_parse_rules; *p; p++) {2276char fullref[PATH_MAX];2277unsigned char sha1_from_ref[20];2278unsigned char*this_result;2279int flag;22802281 this_result = refs_found ? sha1_from_ref : sha1;2282mksnpath(fullref,sizeof(fullref), *p, len, str);2283 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2284 this_result, &flag);2285if(r) {2286if(!refs_found++)2287*ref =xstrdup(r);2288if(!warn_ambiguous_refs)2289break;2290}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2291warning("ignoring dangling symref%s.", fullref);2292}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2293warning("ignoring broken ref%s.", fullref);2294}2295}2296free(last_branch);2297return refs_found;2298}22992300intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2301{2302char*last_branch =substitute_branch_name(&str, &len);2303const char**p;2304int logs_found =0;23052306*log = NULL;2307for(p = ref_rev_parse_rules; *p; p++) {2308unsigned char hash[20];2309char path[PATH_MAX];2310const char*ref, *it;23112312mksnpath(path,sizeof(path), *p, len, str);2313 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2314 hash, NULL);2315if(!ref)2316continue;2317if(reflog_exists(path))2318 it = path;2319else if(strcmp(ref, path) &&reflog_exists(ref))2320 it = ref;2321else2322continue;2323if(!logs_found++) {2324*log =xstrdup(it);2325hashcpy(sha1, hash);2326}2327if(!warn_ambiguous_refs)2328break;2329}2330free(last_branch);2331return logs_found;2332}23332334/*2335 * Locks a ref returning the lock on success and NULL on failure.2336 * On failure errno is set to something meaningful.2337 */2338static struct ref_lock *lock_ref_sha1_basic(const char*refname,2339const unsigned char*old_sha1,2340const struct string_list *extras,2341const struct string_list *skip,2342unsigned int flags,int*type_p,2343struct strbuf *err)2344{2345char*ref_file;2346const char*orig_refname = refname;2347struct ref_lock *lock;2348int last_errno =0;2349int type, lflags;2350int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2351int resolve_flags =0;2352int attempts_remaining =3;23532354assert(err);23552356 lock =xcalloc(1,sizeof(struct ref_lock));2357 lock->lock_fd = -1;23582359if(mustexist)2360 resolve_flags |= RESOLVE_REF_READING;2361if(flags & REF_DELETING) {2362 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2363if(flags & REF_NODEREF)2364 resolve_flags |= RESOLVE_REF_NO_RECURSE;2365}23662367 refname =resolve_ref_unsafe(refname, resolve_flags,2368 lock->old_sha1, &type);2369if(!refname && errno == EISDIR) {2370/* we are trying to lock foo but we used to2371 * have foo/bar which now does not exist;2372 * it is normal for the empty directory 'foo'2373 * to remain.2374 */2375 ref_file =git_path("%s", orig_refname);2376if(remove_empty_directories(ref_file)) {2377 last_errno = errno;23782379if(!verify_refname_available(orig_refname, extras, skip,2380get_loose_refs(&ref_cache), err))2381strbuf_addf(err,"there are still refs under '%s'",2382 orig_refname);23832384goto error_return;2385}2386 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2387 lock->old_sha1, &type);2388}2389if(type_p)2390*type_p = type;2391if(!refname) {2392 last_errno = errno;2393if(last_errno != ENOTDIR ||2394!verify_refname_available(orig_refname, extras, skip,2395get_loose_refs(&ref_cache), err))2396strbuf_addf(err,"unable to resolve reference%s:%s",2397 orig_refname,strerror(last_errno));23982399goto error_return;2400}2401/*2402 * If the ref did not exist and we are creating it, make sure2403 * there is no existing packed ref whose name begins with our2404 * refname, nor a packed ref whose name is a proper prefix of2405 * our refname.2406 */2407if(is_null_sha1(lock->old_sha1) &&2408verify_refname_available(refname, extras, skip,2409get_packed_refs(&ref_cache), err)) {2410 last_errno = ENOTDIR;2411goto error_return;2412}24132414 lock->lk =xcalloc(1,sizeof(struct lock_file));24152416 lflags =0;2417if(flags & REF_NODEREF) {2418 refname = orig_refname;2419 lflags |= LOCK_NO_DEREF;2420}2421 lock->ref_name =xstrdup(refname);2422 lock->orig_ref_name =xstrdup(orig_refname);2423 ref_file =git_path("%s", refname);24242425 retry:2426switch(safe_create_leading_directories(ref_file)) {2427case SCLD_OK:2428break;/* success */2429case SCLD_VANISHED:2430if(--attempts_remaining >0)2431goto retry;2432/* fall through */2433default:2434 last_errno = errno;2435strbuf_addf(err,"unable to create directory for%s", ref_file);2436goto error_return;2437}24382439 lock->lock_fd =hold_lock_file_for_update(lock->lk, ref_file, lflags);2440if(lock->lock_fd <0) {2441 last_errno = errno;2442if(errno == ENOENT && --attempts_remaining >0)2443/*2444 * Maybe somebody just deleted one of the2445 * directories leading to ref_file. Try2446 * again:2447 */2448goto retry;2449else{2450unable_to_lock_message(ref_file, errno, err);2451goto error_return;2452}2453}2454return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;24552456 error_return:2457unlock_ref(lock);2458 errno = last_errno;2459return NULL;2460}24612462/*2463 * Write an entry to the packed-refs file for the specified refname.2464 * If peeled is non-NULL, write it as the entry's peeled value.2465 */2466static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2467unsigned char*peeled)2468{2469fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2470if(peeled)2471fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2472}24732474/*2475 * An each_ref_entry_fn that writes the entry to a packed-refs file.2476 */2477static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2478{2479enum peel_status peel_status =peel_entry(entry,0);24802481if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2482error("internal error:%sis not a valid packed reference!",2483 entry->name);2484write_packed_entry(cb_data, entry->name, entry->u.value.sha1,2485 peel_status == PEEL_PEELED ?2486 entry->u.value.peeled : NULL);2487return0;2488}24892490/* This should return a meaningful errno on failure */2491intlock_packed_refs(int flags)2492{2493struct packed_ref_cache *packed_ref_cache;24942495if(hold_lock_file_for_update(&packlock,git_path("packed-refs"), flags) <0)2496return-1;2497/*2498 * Get the current packed-refs while holding the lock. If the2499 * packed-refs file has been modified since we last read it,2500 * this will automatically invalidate the cache and re-read2501 * the packed-refs file.2502 */2503 packed_ref_cache =get_packed_ref_cache(&ref_cache);2504 packed_ref_cache->lock = &packlock;2505/* Increment the reference count to prevent it from being freed: */2506acquire_packed_ref_cache(packed_ref_cache);2507return0;2508}25092510/*2511 * Commit the packed refs changes.2512 * On error we must make sure that errno contains a meaningful value.2513 */2514intcommit_packed_refs(void)2515{2516struct packed_ref_cache *packed_ref_cache =2517get_packed_ref_cache(&ref_cache);2518int error =0;2519int save_errno =0;2520FILE*out;25212522if(!packed_ref_cache->lock)2523die("internal error: packed-refs not locked");25242525 out =fdopen_lock_file(packed_ref_cache->lock,"w");2526if(!out)2527die_errno("unable to fdopen packed-refs descriptor");25282529fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2530do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),25310, write_packed_entry_fn, out);25322533if(commit_lock_file(packed_ref_cache->lock)) {2534 save_errno = errno;2535 error = -1;2536}2537 packed_ref_cache->lock = NULL;2538release_packed_ref_cache(packed_ref_cache);2539 errno = save_errno;2540return error;2541}25422543voidrollback_packed_refs(void)2544{2545struct packed_ref_cache *packed_ref_cache =2546get_packed_ref_cache(&ref_cache);25472548if(!packed_ref_cache->lock)2549die("internal error: packed-refs not locked");2550rollback_lock_file(packed_ref_cache->lock);2551 packed_ref_cache->lock = NULL;2552release_packed_ref_cache(packed_ref_cache);2553clear_packed_ref_cache(&ref_cache);2554}25552556struct ref_to_prune {2557struct ref_to_prune *next;2558unsigned char sha1[20];2559char name[FLEX_ARRAY];2560};25612562struct pack_refs_cb_data {2563unsigned int flags;2564struct ref_dir *packed_refs;2565struct ref_to_prune *ref_to_prune;2566};25672568/*2569 * An each_ref_entry_fn that is run over loose references only. If2570 * the loose reference can be packed, add an entry in the packed ref2571 * cache. If the reference should be pruned, also add it to2572 * ref_to_prune in the pack_refs_cb_data.2573 */2574static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2575{2576struct pack_refs_cb_data *cb = cb_data;2577enum peel_status peel_status;2578struct ref_entry *packed_entry;2579int is_tag_ref =starts_with(entry->name,"refs/tags/");25802581/* ALWAYS pack tags */2582if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2583return0;25842585/* Do not pack symbolic or broken refs: */2586if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2587return0;25882589/* Add a packed ref cache entry equivalent to the loose entry. */2590 peel_status =peel_entry(entry,1);2591if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2592die("internal error peeling reference%s(%s)",2593 entry->name,sha1_to_hex(entry->u.value.sha1));2594 packed_entry =find_ref(cb->packed_refs, entry->name);2595if(packed_entry) {2596/* Overwrite existing packed entry with info from loose entry */2597 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2598hashcpy(packed_entry->u.value.sha1, entry->u.value.sha1);2599}else{2600 packed_entry =create_ref_entry(entry->name, entry->u.value.sha1,2601 REF_ISPACKED | REF_KNOWS_PEELED,0);2602add_ref(cb->packed_refs, packed_entry);2603}2604hashcpy(packed_entry->u.value.peeled, entry->u.value.peeled);26052606/* Schedule the loose reference for pruning if requested. */2607if((cb->flags & PACK_REFS_PRUNE)) {2608int namelen =strlen(entry->name) +1;2609struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2610hashcpy(n->sha1, entry->u.value.sha1);2611strcpy(n->name, entry->name);2612 n->next = cb->ref_to_prune;2613 cb->ref_to_prune = n;2614}2615return0;2616}26172618/*2619 * Remove empty parents, but spare refs/ and immediate subdirs.2620 * Note: munges *name.2621 */2622static voidtry_remove_empty_parents(char*name)2623{2624char*p, *q;2625int i;2626 p = name;2627for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2628while(*p && *p !='/')2629 p++;2630/* tolerate duplicate slashes; see check_refname_format() */2631while(*p =='/')2632 p++;2633}2634for(q = p; *q; q++)2635;2636while(1) {2637while(q > p && *q !='/')2638 q--;2639while(q > p && *(q-1) =='/')2640 q--;2641if(q == p)2642break;2643*q ='\0';2644if(rmdir(git_path("%s", name)))2645break;2646}2647}26482649/* make sure nobody touched the ref, and unlink */2650static voidprune_ref(struct ref_to_prune *r)2651{2652struct ref_transaction *transaction;2653struct strbuf err = STRBUF_INIT;26542655if(check_refname_format(r->name,0))2656return;26572658 transaction =ref_transaction_begin(&err);2659if(!transaction ||2660ref_transaction_delete(transaction, r->name, r->sha1,2661 REF_ISPRUNING, NULL, &err) ||2662ref_transaction_commit(transaction, &err)) {2663ref_transaction_free(transaction);2664error("%s", err.buf);2665strbuf_release(&err);2666return;2667}2668ref_transaction_free(transaction);2669strbuf_release(&err);2670try_remove_empty_parents(r->name);2671}26722673static voidprune_refs(struct ref_to_prune *r)2674{2675while(r) {2676prune_ref(r);2677 r = r->next;2678}2679}26802681intpack_refs(unsigned int flags)2682{2683struct pack_refs_cb_data cbdata;26842685memset(&cbdata,0,sizeof(cbdata));2686 cbdata.flags = flags;26872688lock_packed_refs(LOCK_DIE_ON_ERROR);2689 cbdata.packed_refs =get_packed_refs(&ref_cache);26902691do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2692 pack_if_possible_fn, &cbdata);26932694if(commit_packed_refs())2695die_errno("unable to overwrite old ref-pack file");26962697prune_refs(cbdata.ref_to_prune);2698return0;2699}27002701intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2702{2703struct ref_dir *packed;2704struct string_list_item *refname;2705int ret, needs_repacking =0, removed =0;27062707assert(err);27082709/* Look for a packed ref */2710for_each_string_list_item(refname, refnames) {2711if(get_packed_ref(refname->string)) {2712 needs_repacking =1;2713break;2714}2715}27162717/* Avoid locking if we have nothing to do */2718if(!needs_repacking)2719return0;/* no refname exists in packed refs */27202721if(lock_packed_refs(0)) {2722unable_to_lock_message(git_path("packed-refs"), errno, err);2723return-1;2724}2725 packed =get_packed_refs(&ref_cache);27262727/* Remove refnames from the cache */2728for_each_string_list_item(refname, refnames)2729if(remove_entry(packed, refname->string) != -1)2730 removed =1;2731if(!removed) {2732/*2733 * All packed entries disappeared while we were2734 * acquiring the lock.2735 */2736rollback_packed_refs();2737return0;2738}27392740/* Write what remains */2741 ret =commit_packed_refs();2742if(ret)2743strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2744strerror(errno));2745return ret;2746}27472748static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2749{2750assert(err);27512752if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2753/*2754 * loose. The loose file name is the same as the2755 * lockfile name, minus ".lock":2756 */2757char*loose_filename =get_locked_file_path(lock->lk);2758int res =unlink_or_msg(loose_filename, err);2759free(loose_filename);2760if(res)2761return1;2762}2763return0;2764}27652766intdelete_ref(const char*refname,const unsigned char*sha1,unsigned int flags)2767{2768struct ref_transaction *transaction;2769struct strbuf err = STRBUF_INIT;27702771 transaction =ref_transaction_begin(&err);2772if(!transaction ||2773ref_transaction_delete(transaction, refname,2774(sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,2775 flags, NULL, &err) ||2776ref_transaction_commit(transaction, &err)) {2777error("%s", err.buf);2778ref_transaction_free(transaction);2779strbuf_release(&err);2780return1;2781}2782ref_transaction_free(transaction);2783strbuf_release(&err);2784return0;2785}27862787/*2788 * People using contrib's git-new-workdir have .git/logs/refs ->2789 * /some/other/path/.git/logs/refs, and that may live on another device.2790 *2791 * IOW, to avoid cross device rename errors, the temporary renamed log must2792 * live into logs/refs.2793 */2794#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"27952796static intrename_tmp_log(const char*newrefname)2797{2798int attempts_remaining =4;27992800 retry:2801switch(safe_create_leading_directories(git_path("logs/%s", newrefname))) {2802case SCLD_OK:2803break;/* success */2804case SCLD_VANISHED:2805if(--attempts_remaining >0)2806goto retry;2807/* fall through */2808default:2809error("unable to create directory for%s", newrefname);2810return-1;2811}28122813if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2814if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2815/*2816 * rename(a, b) when b is an existing2817 * directory ought to result in ISDIR, but2818 * Solaris 5.8 gives ENOTDIR. Sheesh.2819 */2820if(remove_empty_directories(git_path("logs/%s", newrefname))) {2821error("Directory not empty: logs/%s", newrefname);2822return-1;2823}2824goto retry;2825}else if(errno == ENOENT && --attempts_remaining >0) {2826/*2827 * Maybe another process just deleted one of2828 * the directories in the path to newrefname.2829 * Try again from the beginning.2830 */2831goto retry;2832}else{2833error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2834 newrefname,strerror(errno));2835return-1;2836}2837}2838return0;2839}28402841static intrename_ref_available(const char*oldname,const char*newname)2842{2843struct string_list skip = STRING_LIST_INIT_NODUP;2844struct strbuf err = STRBUF_INIT;2845int ret;28462847string_list_insert(&skip, oldname);2848 ret = !verify_refname_available(newname, NULL, &skip,2849get_packed_refs(&ref_cache), &err)2850&& !verify_refname_available(newname, NULL, &skip,2851get_loose_refs(&ref_cache), &err);2852if(!ret)2853error("%s", err.buf);28542855string_list_clear(&skip,0);2856strbuf_release(&err);2857return ret;2858}28592860static intwrite_ref_to_lockfile(struct ref_lock *lock,const unsigned char*sha1);2861static intcommit_ref_update(struct ref_lock *lock,2862const unsigned char*sha1,const char*logmsg);28632864intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2865{2866unsigned char sha1[20], orig_sha1[20];2867int flag =0, logmoved =0;2868struct ref_lock *lock;2869struct stat loginfo;2870int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2871const char*symref = NULL;2872struct strbuf err = STRBUF_INIT;28732874if(log &&S_ISLNK(loginfo.st_mode))2875returnerror("reflog for%sis a symlink", oldrefname);28762877 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2878 orig_sha1, &flag);2879if(flag & REF_ISSYMREF)2880returnerror("refname%sis a symbolic ref, renaming it is not supported",2881 oldrefname);2882if(!symref)2883returnerror("refname%snot found", oldrefname);28842885if(!rename_ref_available(oldrefname, newrefname))2886return1;28872888if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2889returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2890 oldrefname,strerror(errno));28912892if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2893error("unable to delete old%s", oldrefname);2894goto rollback;2895}28962897if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2898delete_ref(newrefname, sha1, REF_NODEREF)) {2899if(errno==EISDIR) {2900if(remove_empty_directories(git_path("%s", newrefname))) {2901error("Directory not empty:%s", newrefname);2902goto rollback;2903}2904}else{2905error("unable to delete existing%s", newrefname);2906goto rollback;2907}2908}29092910if(log &&rename_tmp_log(newrefname))2911goto rollback;29122913 logmoved = log;29142915 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2916if(!lock) {2917error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2918strbuf_release(&err);2919goto rollback;2920}2921hashcpy(lock->old_sha1, orig_sha1);29222923if(write_ref_to_lockfile(lock, orig_sha1) ||2924commit_ref_update(lock, orig_sha1, logmsg)) {2925error("unable to write current sha1 into%s", newrefname);2926goto rollback;2927}29282929return0;29302931 rollback:2932 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2933if(!lock) {2934error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2935strbuf_release(&err);2936goto rollbacklog;2937}29382939 flag = log_all_ref_updates;2940 log_all_ref_updates =0;2941if(write_ref_to_lockfile(lock, orig_sha1) ||2942commit_ref_update(lock, orig_sha1, NULL))2943error("unable to write current sha1 into%s", oldrefname);2944 log_all_ref_updates = flag;29452946 rollbacklog:2947if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2948error("unable to restore logfile%sfrom%s:%s",2949 oldrefname, newrefname,strerror(errno));2950if(!logmoved && log &&2951rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2952error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2953 oldrefname,strerror(errno));29542955return1;2956}29572958static intclose_ref(struct ref_lock *lock)2959{2960if(close_lock_file(lock->lk))2961return-1;2962 lock->lock_fd = -1;2963return0;2964}29652966static intcommit_ref(struct ref_lock *lock)2967{2968if(commit_lock_file(lock->lk))2969return-1;2970 lock->lock_fd = -1;2971return0;2972}29732974/*2975 * copy the reflog message msg to buf, which has been allocated sufficiently2976 * large, while cleaning up the whitespaces. Especially, convert LF to space,2977 * because reflog file is one line per entry.2978 */2979static intcopy_msg(char*buf,const char*msg)2980{2981char*cp = buf;2982char c;2983int wasspace =1;29842985*cp++ ='\t';2986while((c = *msg++)) {2987if(wasspace &&isspace(c))2988continue;2989 wasspace =isspace(c);2990if(wasspace)2991 c =' ';2992*cp++ = c;2993}2994while(buf < cp &&isspace(cp[-1]))2995 cp--;2996*cp++ ='\n';2997return cp - buf;2998}29993000/* This function must set a meaningful errno on failure */3001intlog_ref_setup(const char*refname,char*logfile,int bufsize)3002{3003int logfd, oflags = O_APPEND | O_WRONLY;30043005git_snpath(logfile, bufsize,"logs/%s", refname);3006if(log_all_ref_updates &&3007(starts_with(refname,"refs/heads/") ||3008starts_with(refname,"refs/remotes/") ||3009starts_with(refname,"refs/notes/") ||3010!strcmp(refname,"HEAD"))) {3011if(safe_create_leading_directories(logfile) <0) {3012int save_errno = errno;3013error("unable to create directory for%s", logfile);3014 errno = save_errno;3015return-1;3016}3017 oflags |= O_CREAT;3018}30193020 logfd =open(logfile, oflags,0666);3021if(logfd <0) {3022if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3023return0;30243025if(errno == EISDIR) {3026if(remove_empty_directories(logfile)) {3027int save_errno = errno;3028error("There are still logs under '%s'",3029 logfile);3030 errno = save_errno;3031return-1;3032}3033 logfd =open(logfile, oflags,0666);3034}30353036if(logfd <0) {3037int save_errno = errno;3038error("Unable to append to%s:%s", logfile,3039strerror(errno));3040 errno = save_errno;3041return-1;3042}3043}30443045adjust_shared_perm(logfile);3046close(logfd);3047return0;3048}30493050static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3051const unsigned char*new_sha1,3052const char*committer,const char*msg)3053{3054int msglen, written;3055unsigned maxlen, len;3056char*logrec;30573058 msglen = msg ?strlen(msg) :0;3059 maxlen =strlen(committer) + msglen +100;3060 logrec =xmalloc(maxlen);3061 len =sprintf(logrec,"%s %s %s\n",3062sha1_to_hex(old_sha1),3063sha1_to_hex(new_sha1),3064 committer);3065if(msglen)3066 len +=copy_msg(logrec + len -1, msg) -1;30673068 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3069free(logrec);3070if(written != len)3071return-1;30723073return0;3074}30753076static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3077const unsigned char*new_sha1,const char*msg)3078{3079int logfd, result, oflags = O_APPEND | O_WRONLY;3080char log_file[PATH_MAX];30813082if(log_all_ref_updates <0)3083 log_all_ref_updates = !is_bare_repository();30843085 result =log_ref_setup(refname, log_file,sizeof(log_file));3086if(result)3087return result;30883089 logfd =open(log_file, oflags);3090if(logfd <0)3091return0;3092 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3093git_committer_info(0), msg);3094if(result) {3095int save_errno = errno;3096close(logfd);3097error("Unable to append to%s", log_file);3098 errno = save_errno;3099return-1;3100}3101if(close(logfd)) {3102int save_errno = errno;3103error("Unable to append to%s", log_file);3104 errno = save_errno;3105return-1;3106}3107return0;3108}31093110intis_branch(const char*refname)3111{3112return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3113}31143115/*3116 * Write sha1 into the open lockfile, then close the lockfile. On3117 * errors, rollback the lockfile and set errno to reflect the problem.3118 */3119static intwrite_ref_to_lockfile(struct ref_lock *lock,3120const unsigned char*sha1)3121{3122static char term ='\n';3123struct object *o;31243125 o =parse_object(sha1);3126if(!o) {3127error("Trying to write ref%swith nonexistent object%s",3128 lock->ref_name,sha1_to_hex(sha1));3129unlock_ref(lock);3130 errno = EINVAL;3131return-1;3132}3133if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3134error("Trying to write non-commit object%sto branch%s",3135sha1_to_hex(sha1), lock->ref_name);3136unlock_ref(lock);3137 errno = EINVAL;3138return-1;3139}3140if(write_in_full(lock->lock_fd,sha1_to_hex(sha1),40) !=40||3141write_in_full(lock->lock_fd, &term,1) !=1||3142close_ref(lock) <0) {3143int save_errno = errno;3144error("Couldn't write%s", lock->lk->filename.buf);3145unlock_ref(lock);3146 errno = save_errno;3147return-1;3148}3149return0;3150}31513152/*3153 * Commit a change to a loose reference that has already been written3154 * to the loose reference lockfile. Also update the reflogs if3155 * necessary, using the specified lockmsg (which can be NULL).3156 */3157static intcommit_ref_update(struct ref_lock *lock,3158const unsigned char*sha1,const char*logmsg)3159{3160clear_loose_ref_cache(&ref_cache);3161if(log_ref_write(lock->ref_name, lock->old_sha1, sha1, logmsg) <0||3162(strcmp(lock->ref_name, lock->orig_ref_name) &&3163log_ref_write(lock->orig_ref_name, lock->old_sha1, sha1, logmsg) <0)) {3164unlock_ref(lock);3165return-1;3166}3167if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3168/*3169 * Special hack: If a branch is updated directly and HEAD3170 * points to it (may happen on the remote side of a push3171 * for example) then logically the HEAD reflog should be3172 * updated too.3173 * A generic solution implies reverse symref information,3174 * but finding all symrefs pointing to the given branch3175 * would be rather costly for this rare event (the direct3176 * update of a branch) to be worth it. So let's cheat and3177 * check with HEAD only which should cover 99% of all usage3178 * scenarios (even 100% of the default ones).3179 */3180unsigned char head_sha1[20];3181int head_flag;3182const char*head_ref;3183 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3184 head_sha1, &head_flag);3185if(head_ref && (head_flag & REF_ISSYMREF) &&3186!strcmp(head_ref, lock->ref_name))3187log_ref_write("HEAD", lock->old_sha1, sha1, logmsg);3188}3189if(commit_ref(lock)) {3190error("Couldn't set%s", lock->ref_name);3191unlock_ref(lock);3192return-1;3193}3194unlock_ref(lock);3195return0;3196}31973198intcreate_symref(const char*ref_target,const char*refs_heads_master,3199const char*logmsg)3200{3201const char*lockpath;3202char ref[1000];3203int fd, len, written;3204char*git_HEAD =git_pathdup("%s", ref_target);3205unsigned char old_sha1[20], new_sha1[20];32063207if(logmsg &&read_ref(ref_target, old_sha1))3208hashclr(old_sha1);32093210if(safe_create_leading_directories(git_HEAD) <0)3211returnerror("unable to create directory for%s", git_HEAD);32123213#ifndef NO_SYMLINK_HEAD3214if(prefer_symlink_refs) {3215unlink(git_HEAD);3216if(!symlink(refs_heads_master, git_HEAD))3217goto done;3218fprintf(stderr,"no symlink - falling back to symbolic ref\n");3219}3220#endif32213222 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3223if(sizeof(ref) <= len) {3224error("refname too long:%s", refs_heads_master);3225goto error_free_return;3226}3227 lockpath =mkpath("%s.lock", git_HEAD);3228 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3229if(fd <0) {3230error("Unable to open%sfor writing", lockpath);3231goto error_free_return;3232}3233 written =write_in_full(fd, ref, len);3234if(close(fd) !=0|| written != len) {3235error("Unable to write to%s", lockpath);3236goto error_unlink_return;3237}3238if(rename(lockpath, git_HEAD) <0) {3239error("Unable to create%s", git_HEAD);3240goto error_unlink_return;3241}3242if(adjust_shared_perm(git_HEAD)) {3243error("Unable to fix permissions on%s", lockpath);3244 error_unlink_return:3245unlink_or_warn(lockpath);3246 error_free_return:3247free(git_HEAD);3248return-1;3249}32503251#ifndef NO_SYMLINK_HEAD3252 done:3253#endif3254if(logmsg && !read_ref(refs_heads_master, new_sha1))3255log_ref_write(ref_target, old_sha1, new_sha1, logmsg);32563257free(git_HEAD);3258return0;3259}32603261struct read_ref_at_cb {3262const char*refname;3263unsigned long at_time;3264int cnt;3265int reccnt;3266unsigned char*sha1;3267int found_it;32683269unsigned char osha1[20];3270unsigned char nsha1[20];3271int tz;3272unsigned long date;3273char**msg;3274unsigned long*cutoff_time;3275int*cutoff_tz;3276int*cutoff_cnt;3277};32783279static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3280const char*email,unsigned long timestamp,int tz,3281const char*message,void*cb_data)3282{3283struct read_ref_at_cb *cb = cb_data;32843285 cb->reccnt++;3286 cb->tz = tz;3287 cb->date = timestamp;32883289if(timestamp <= cb->at_time || cb->cnt ==0) {3290if(cb->msg)3291*cb->msg =xstrdup(message);3292if(cb->cutoff_time)3293*cb->cutoff_time = timestamp;3294if(cb->cutoff_tz)3295*cb->cutoff_tz = tz;3296if(cb->cutoff_cnt)3297*cb->cutoff_cnt = cb->reccnt -1;3298/*3299 * we have not yet updated cb->[n|o]sha1 so they still3300 * hold the values for the previous record.3301 */3302if(!is_null_sha1(cb->osha1)) {3303hashcpy(cb->sha1, nsha1);3304if(hashcmp(cb->osha1, nsha1))3305warning("Log for ref%shas gap after%s.",3306 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3307}3308else if(cb->date == cb->at_time)3309hashcpy(cb->sha1, nsha1);3310else if(hashcmp(nsha1, cb->sha1))3311warning("Log for ref%sunexpectedly ended on%s.",3312 cb->refname,show_date(cb->date, cb->tz,3313 DATE_RFC2822));3314hashcpy(cb->osha1, osha1);3315hashcpy(cb->nsha1, nsha1);3316 cb->found_it =1;3317return1;3318}3319hashcpy(cb->osha1, osha1);3320hashcpy(cb->nsha1, nsha1);3321if(cb->cnt >0)3322 cb->cnt--;3323return0;3324}33253326static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3327const char*email,unsigned long timestamp,3328int tz,const char*message,void*cb_data)3329{3330struct read_ref_at_cb *cb = cb_data;33313332if(cb->msg)3333*cb->msg =xstrdup(message);3334if(cb->cutoff_time)3335*cb->cutoff_time = timestamp;3336if(cb->cutoff_tz)3337*cb->cutoff_tz = tz;3338if(cb->cutoff_cnt)3339*cb->cutoff_cnt = cb->reccnt;3340hashcpy(cb->sha1, osha1);3341if(is_null_sha1(cb->sha1))3342hashcpy(cb->sha1, nsha1);3343/* We just want the first entry */3344return1;3345}33463347intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3348unsigned char*sha1,char**msg,3349unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3350{3351struct read_ref_at_cb cb;33523353memset(&cb,0,sizeof(cb));3354 cb.refname = refname;3355 cb.at_time = at_time;3356 cb.cnt = cnt;3357 cb.msg = msg;3358 cb.cutoff_time = cutoff_time;3359 cb.cutoff_tz = cutoff_tz;3360 cb.cutoff_cnt = cutoff_cnt;3361 cb.sha1 = sha1;33623363for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);33643365if(!cb.reccnt) {3366if(flags & GET_SHA1_QUIETLY)3367exit(128);3368else3369die("Log for%sis empty.", refname);3370}3371if(cb.found_it)3372return0;33733374for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);33753376return1;3377}33783379intreflog_exists(const char*refname)3380{3381struct stat st;33823383return!lstat(git_path("logs/%s", refname), &st) &&3384S_ISREG(st.st_mode);3385}33863387intdelete_reflog(const char*refname)3388{3389returnremove_path(git_path("logs/%s", refname));3390}33913392static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3393{3394unsigned char osha1[20], nsha1[20];3395char*email_end, *message;3396unsigned long timestamp;3397int tz;33983399/* old SP new SP name <email> SP time TAB msg LF */3400if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3401get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3402get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3403!(email_end =strchr(sb->buf +82,'>')) ||3404 email_end[1] !=' '||3405!(timestamp =strtoul(email_end +2, &message,10)) ||3406!message || message[0] !=' '||3407(message[1] !='+'&& message[1] !='-') ||3408!isdigit(message[2]) || !isdigit(message[3]) ||3409!isdigit(message[4]) || !isdigit(message[5]))3410return0;/* corrupt? */3411 email_end[1] ='\0';3412 tz =strtol(message +1, NULL,10);3413if(message[6] !='\t')3414 message +=6;3415else3416 message +=7;3417returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3418}34193420static char*find_beginning_of_line(char*bob,char*scan)3421{3422while(bob < scan && *(--scan) !='\n')3423;/* keep scanning backwards */3424/*3425 * Return either beginning of the buffer, or LF at the end of3426 * the previous line.3427 */3428return scan;3429}34303431intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3432{3433struct strbuf sb = STRBUF_INIT;3434FILE*logfp;3435long pos;3436int ret =0, at_tail =1;34373438 logfp =fopen(git_path("logs/%s", refname),"r");3439if(!logfp)3440return-1;34413442/* Jump to the end */3443if(fseek(logfp,0, SEEK_END) <0)3444returnerror("cannot seek back reflog for%s:%s",3445 refname,strerror(errno));3446 pos =ftell(logfp);3447while(!ret &&0< pos) {3448int cnt;3449size_t nread;3450char buf[BUFSIZ];3451char*endp, *scanp;34523453/* Fill next block from the end */3454 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3455if(fseek(logfp, pos - cnt, SEEK_SET))3456returnerror("cannot seek back reflog for%s:%s",3457 refname,strerror(errno));3458 nread =fread(buf, cnt,1, logfp);3459if(nread !=1)3460returnerror("cannot read%dbytes from reflog for%s:%s",3461 cnt, refname,strerror(errno));3462 pos -= cnt;34633464 scanp = endp = buf + cnt;3465if(at_tail && scanp[-1] =='\n')3466/* Looking at the final LF at the end of the file */3467 scanp--;3468 at_tail =0;34693470while(buf < scanp) {3471/*3472 * terminating LF of the previous line, or the beginning3473 * of the buffer.3474 */3475char*bp;34763477 bp =find_beginning_of_line(buf, scanp);34783479if(*bp =='\n') {3480/*3481 * The newline is the end of the previous line,3482 * so we know we have complete line starting3483 * at (bp + 1). Prefix it onto any prior data3484 * we collected for the line and process it.3485 */3486strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3487 scanp = bp;3488 endp = bp +1;3489 ret =show_one_reflog_ent(&sb, fn, cb_data);3490strbuf_reset(&sb);3491if(ret)3492break;3493}else if(!pos) {3494/*3495 * We are at the start of the buffer, and the3496 * start of the file; there is no previous3497 * line, and we have everything for this one.3498 * Process it, and we can end the loop.3499 */3500strbuf_splice(&sb,0,0, buf, endp - buf);3501 ret =show_one_reflog_ent(&sb, fn, cb_data);3502strbuf_reset(&sb);3503break;3504}35053506if(bp == buf) {3507/*3508 * We are at the start of the buffer, and there3509 * is more file to read backwards. Which means3510 * we are in the middle of a line. Note that we3511 * may get here even if *bp was a newline; that3512 * just means we are at the exact end of the3513 * previous line, rather than some spot in the3514 * middle.3515 *3516 * Save away what we have to be combined with3517 * the data from the next read.3518 */3519strbuf_splice(&sb,0,0, buf, endp - buf);3520break;3521}3522}35233524}3525if(!ret && sb.len)3526die("BUG: reverse reflog parser had leftover data");35273528fclose(logfp);3529strbuf_release(&sb);3530return ret;3531}35323533intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3534{3535FILE*logfp;3536struct strbuf sb = STRBUF_INIT;3537int ret =0;35383539 logfp =fopen(git_path("logs/%s", refname),"r");3540if(!logfp)3541return-1;35423543while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3544 ret =show_one_reflog_ent(&sb, fn, cb_data);3545fclose(logfp);3546strbuf_release(&sb);3547return ret;3548}3549/*3550 * Call fn for each reflog in the namespace indicated by name. name3551 * must be empty or end with '/'. Name will be used as a scratch3552 * space, but its contents will be restored before return.3553 */3554static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3555{3556DIR*d =opendir(git_path("logs/%s", name->buf));3557int retval =0;3558struct dirent *de;3559int oldlen = name->len;35603561if(!d)3562return name->len ? errno :0;35633564while((de =readdir(d)) != NULL) {3565struct stat st;35663567if(de->d_name[0] =='.')3568continue;3569if(ends_with(de->d_name,".lock"))3570continue;3571strbuf_addstr(name, de->d_name);3572if(stat(git_path("logs/%s", name->buf), &st) <0) {3573;/* silently ignore */3574}else{3575if(S_ISDIR(st.st_mode)) {3576strbuf_addch(name,'/');3577 retval =do_for_each_reflog(name, fn, cb_data);3578}else{3579unsigned char sha1[20];3580if(read_ref_full(name->buf,0, sha1, NULL))3581 retval =error("bad ref for%s", name->buf);3582else3583 retval =fn(name->buf, sha1,0, cb_data);3584}3585if(retval)3586break;3587}3588strbuf_setlen(name, oldlen);3589}3590closedir(d);3591return retval;3592}35933594intfor_each_reflog(each_ref_fn fn,void*cb_data)3595{3596int retval;3597struct strbuf name;3598strbuf_init(&name, PATH_MAX);3599 retval =do_for_each_reflog(&name, fn, cb_data);3600strbuf_release(&name);3601return retval;3602}36033604/**3605 * Information needed for a single ref update. Set new_sha1 to the new3606 * value or to null_sha1 to delete the ref. To check the old value3607 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3608 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3609 * not exist before update.3610 */3611struct ref_update {3612/*3613 * If (flags & REF_HAVE_NEW), set the reference to this value:3614 */3615unsigned char new_sha1[20];3616/*3617 * If (flags & REF_HAVE_OLD), check that the reference3618 * previously had this value:3619 */3620unsigned char old_sha1[20];3621/*3622 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3623 * REF_DELETING, and REF_ISPRUNING:3624 */3625unsigned int flags;3626struct ref_lock *lock;3627int type;3628char*msg;3629const char refname[FLEX_ARRAY];3630};36313632/*3633 * Transaction states.3634 * OPEN: The transaction is in a valid state and can accept new updates.3635 * An OPEN transaction can be committed.3636 * CLOSED: A closed transaction is no longer active and no other operations3637 * than free can be used on it in this state.3638 * A transaction can either become closed by successfully committing3639 * an active transaction or if there is a failure while building3640 * the transaction thus rendering it failed/inactive.3641 */3642enum ref_transaction_state {3643 REF_TRANSACTION_OPEN =0,3644 REF_TRANSACTION_CLOSED =13645};36463647/*3648 * Data structure for holding a reference transaction, which can3649 * consist of checks and updates to multiple references, carried out3650 * as atomically as possible. This structure is opaque to callers.3651 */3652struct ref_transaction {3653struct ref_update **updates;3654size_t alloc;3655size_t nr;3656enum ref_transaction_state state;3657};36583659struct ref_transaction *ref_transaction_begin(struct strbuf *err)3660{3661assert(err);36623663returnxcalloc(1,sizeof(struct ref_transaction));3664}36653666voidref_transaction_free(struct ref_transaction *transaction)3667{3668int i;36693670if(!transaction)3671return;36723673for(i =0; i < transaction->nr; i++) {3674free(transaction->updates[i]->msg);3675free(transaction->updates[i]);3676}3677free(transaction->updates);3678free(transaction);3679}36803681static struct ref_update *add_update(struct ref_transaction *transaction,3682const char*refname)3683{3684size_t len =strlen(refname);3685struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);36863687strcpy((char*)update->refname, refname);3688ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3689 transaction->updates[transaction->nr++] = update;3690return update;3691}36923693intref_transaction_update(struct ref_transaction *transaction,3694const char*refname,3695const unsigned char*new_sha1,3696const unsigned char*old_sha1,3697unsigned int flags,const char*msg,3698struct strbuf *err)3699{3700struct ref_update *update;37013702assert(err);37033704if(transaction->state != REF_TRANSACTION_OPEN)3705die("BUG: update called for transaction that is not open");37063707if(new_sha1 && !is_null_sha1(new_sha1) &&3708check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3709strbuf_addf(err,"refusing to update ref with bad name%s",3710 refname);3711return-1;3712}37133714 update =add_update(transaction, refname);3715if(new_sha1) {3716hashcpy(update->new_sha1, new_sha1);3717 flags |= REF_HAVE_NEW;3718}3719if(old_sha1) {3720hashcpy(update->old_sha1, old_sha1);3721 flags |= REF_HAVE_OLD;3722}3723 update->flags = flags;3724if(msg)3725 update->msg =xstrdup(msg);3726return0;3727}37283729intref_transaction_create(struct ref_transaction *transaction,3730const char*refname,3731const unsigned char*new_sha1,3732unsigned int flags,const char*msg,3733struct strbuf *err)3734{3735if(!new_sha1 ||is_null_sha1(new_sha1))3736die("BUG: create called without valid new_sha1");3737returnref_transaction_update(transaction, refname, new_sha1,3738 null_sha1, flags, msg, err);3739}37403741intref_transaction_delete(struct ref_transaction *transaction,3742const char*refname,3743const unsigned char*old_sha1,3744unsigned int flags,const char*msg,3745struct strbuf *err)3746{3747if(old_sha1 &&is_null_sha1(old_sha1))3748die("BUG: delete called with old_sha1 set to zeros");3749returnref_transaction_update(transaction, refname,3750 null_sha1, old_sha1,3751 flags, msg, err);3752}37533754intref_transaction_verify(struct ref_transaction *transaction,3755const char*refname,3756const unsigned char*old_sha1,3757unsigned int flags,3758struct strbuf *err)3759{3760if(!old_sha1)3761die("BUG: verify called with old_sha1 set to NULL");3762returnref_transaction_update(transaction, refname,3763 NULL, old_sha1,3764 flags, NULL, err);3765}37663767intupdate_ref(const char*msg,const char*refname,3768const unsigned char*new_sha1,const unsigned char*old_sha1,3769unsigned int flags,enum action_on_err onerr)3770{3771struct ref_transaction *t;3772struct strbuf err = STRBUF_INIT;37733774 t =ref_transaction_begin(&err);3775if(!t ||3776ref_transaction_update(t, refname, new_sha1, old_sha1,3777 flags, msg, &err) ||3778ref_transaction_commit(t, &err)) {3779const char*str ="update_ref failed for ref '%s':%s";37803781ref_transaction_free(t);3782switch(onerr) {3783case UPDATE_REFS_MSG_ON_ERR:3784error(str, refname, err.buf);3785break;3786case UPDATE_REFS_DIE_ON_ERR:3787die(str, refname, err.buf);3788break;3789case UPDATE_REFS_QUIET_ON_ERR:3790break;3791}3792strbuf_release(&err);3793return1;3794}3795strbuf_release(&err);3796ref_transaction_free(t);3797return0;3798}37993800static intref_update_reject_duplicates(struct string_list *refnames,3801struct strbuf *err)3802{3803int i, n = refnames->nr;38043805assert(err);38063807for(i =1; i < n; i++)3808if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3809strbuf_addf(err,3810"Multiple updates for ref '%s' not allowed.",3811 refnames->items[i].string);3812return1;3813}3814return0;3815}38163817intref_transaction_commit(struct ref_transaction *transaction,3818struct strbuf *err)3819{3820int ret =0, i;3821int n = transaction->nr;3822struct ref_update **updates = transaction->updates;3823struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3824struct string_list_item *ref_to_delete;3825struct string_list affected_refnames = STRING_LIST_INIT_NODUP;38263827assert(err);38283829if(transaction->state != REF_TRANSACTION_OPEN)3830die("BUG: commit called for transaction that is not open");38313832if(!n) {3833 transaction->state = REF_TRANSACTION_CLOSED;3834return0;3835}38363837/* Fail if a refname appears more than once in the transaction: */3838for(i =0; i < n; i++)3839string_list_append(&affected_refnames, updates[i]->refname);3840string_list_sort(&affected_refnames);3841if(ref_update_reject_duplicates(&affected_refnames, err)) {3842 ret = TRANSACTION_GENERIC_ERROR;3843goto cleanup;3844}38453846/*3847 * Acquire all locks, verify old values if provided, check3848 * that new values are valid, and write new values to the3849 * lockfiles, ready to be activated. Only keep one lockfile3850 * open at a time to avoid running out of file descriptors.3851 */3852for(i =0; i < n; i++) {3853struct ref_update *update = updates[i];38543855if((update->flags & REF_HAVE_NEW) &&3856is_null_sha1(update->new_sha1))3857 update->flags |= REF_DELETING;3858 update->lock =lock_ref_sha1_basic(3859 update->refname,3860((update->flags & REF_HAVE_OLD) ?3861 update->old_sha1 : NULL),3862&affected_refnames, NULL,3863 update->flags,3864&update->type,3865 err);3866if(!update->lock) {3867char*reason;38683869 ret = (errno == ENOTDIR)3870? TRANSACTION_NAME_CONFLICT3871: TRANSACTION_GENERIC_ERROR;3872 reason =strbuf_detach(err, NULL);3873strbuf_addf(err,"Cannot lock ref '%s':%s",3874 update->refname, reason);3875free(reason);3876goto cleanup;3877}3878if((update->flags & REF_HAVE_NEW) &&3879!(update->flags & REF_DELETING)) {3880int overwriting_symref = ((update->type & REF_ISSYMREF) &&3881(update->flags & REF_NODEREF));38823883if(!overwriting_symref &&3884!hashcmp(update->lock->old_sha1, update->new_sha1)) {3885/*3886 * The reference already has the desired3887 * value, so we don't need to write it.3888 */3889}else if(write_ref_to_lockfile(update->lock,3890 update->new_sha1)) {3891/*3892 * The lock was freed upon failure of3893 * write_ref_to_lockfile():3894 */3895 update->lock = NULL;3896strbuf_addf(err,"Cannot update the ref '%s'.",3897 update->refname);3898 ret = TRANSACTION_GENERIC_ERROR;3899goto cleanup;3900}else{3901 update->flags |= REF_NEEDS_COMMIT;3902}3903}3904if(!(update->flags & REF_NEEDS_COMMIT)) {3905/*3906 * We didn't have to write anything to the lockfile.3907 * Close it to free up the file descriptor:3908 */3909if(close_ref(update->lock)) {3910strbuf_addf(err,"Couldn't close%s.lock",3911 update->refname);3912goto cleanup;3913}3914}3915}39163917/* Perform updates first so live commits remain referenced */3918for(i =0; i < n; i++) {3919struct ref_update *update = updates[i];39203921if(update->flags & REF_NEEDS_COMMIT) {3922if(commit_ref_update(update->lock,3923 update->new_sha1, update->msg)) {3924/* freed by commit_ref_update(): */3925 update->lock = NULL;3926strbuf_addf(err,"Cannot update the ref '%s'.",3927 update->refname);3928 ret = TRANSACTION_GENERIC_ERROR;3929goto cleanup;3930}else{3931/* freed by commit_ref_update(): */3932 update->lock = NULL;3933}3934}3935}39363937/* Perform deletes now that updates are safely completed */3938for(i =0; i < n; i++) {3939struct ref_update *update = updates[i];39403941if(update->flags & REF_DELETING) {3942if(delete_ref_loose(update->lock, update->type, err)) {3943 ret = TRANSACTION_GENERIC_ERROR;3944goto cleanup;3945}39463947if(!(update->flags & REF_ISPRUNING))3948string_list_append(&refs_to_delete,3949 update->lock->ref_name);3950}3951}39523953if(repack_without_refs(&refs_to_delete, err)) {3954 ret = TRANSACTION_GENERIC_ERROR;3955goto cleanup;3956}3957for_each_string_list_item(ref_to_delete, &refs_to_delete)3958unlink_or_warn(git_path("logs/%s", ref_to_delete->string));3959clear_loose_ref_cache(&ref_cache);39603961cleanup:3962 transaction->state = REF_TRANSACTION_CLOSED;39633964for(i =0; i < n; i++)3965if(updates[i]->lock)3966unlock_ref(updates[i]->lock);3967string_list_clear(&refs_to_delete,0);3968string_list_clear(&affected_refnames,0);3969return ret;3970}39713972char*shorten_unambiguous_ref(const char*refname,int strict)3973{3974int i;3975static char**scanf_fmts;3976static int nr_rules;3977char*short_name;39783979if(!nr_rules) {3980/*3981 * Pre-generate scanf formats from ref_rev_parse_rules[].3982 * Generate a format suitable for scanf from a3983 * ref_rev_parse_rules rule by interpolating "%s" at the3984 * location of the "%.*s".3985 */3986size_t total_len =0;3987size_t offset =0;39883989/* the rule list is NULL terminated, count them first */3990for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)3991/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */3992 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;39933994 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);39953996 offset =0;3997for(i =0; i < nr_rules; i++) {3998assert(offset < total_len);3999 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4000 offset +=snprintf(scanf_fmts[i], total_len - offset,4001 ref_rev_parse_rules[i],2,"%s") +1;4002}4003}40044005/* bail out if there are no rules */4006if(!nr_rules)4007returnxstrdup(refname);40084009/* buffer for scanf result, at most refname must fit */4010 short_name =xstrdup(refname);40114012/* skip first rule, it will always match */4013for(i = nr_rules -1; i >0; --i) {4014int j;4015int rules_to_fail = i;4016int short_name_len;40174018if(1!=sscanf(refname, scanf_fmts[i], short_name))4019continue;40204021 short_name_len =strlen(short_name);40224023/*4024 * in strict mode, all (except the matched one) rules4025 * must fail to resolve to a valid non-ambiguous ref4026 */4027if(strict)4028 rules_to_fail = nr_rules;40294030/*4031 * check if the short name resolves to a valid ref,4032 * but use only rules prior to the matched one4033 */4034for(j =0; j < rules_to_fail; j++) {4035const char*rule = ref_rev_parse_rules[j];4036char refname[PATH_MAX];40374038/* skip matched rule */4039if(i == j)4040continue;40414042/*4043 * the short name is ambiguous, if it resolves4044 * (with this previous rule) to a valid ref4045 * read_ref() returns 0 on success4046 */4047mksnpath(refname,sizeof(refname),4048 rule, short_name_len, short_name);4049if(ref_exists(refname))4050break;4051}40524053/*4054 * short name is non-ambiguous if all previous rules4055 * haven't resolved to a valid ref4056 */4057if(j == rules_to_fail)4058return short_name;4059}40604061free(short_name);4062returnxstrdup(refname);4063}40644065static struct string_list *hide_refs;40664067intparse_hide_refs_config(const char*var,const char*value,const char*section)4068{4069if(!strcmp("transfer.hiderefs", var) ||4070/* NEEDSWORK: use parse_config_key() once both are merged */4071(starts_with(var, section) && var[strlen(section)] =='.'&&4072!strcmp(var +strlen(section),".hiderefs"))) {4073char*ref;4074int len;40754076if(!value)4077returnconfig_error_nonbool(var);4078 ref =xstrdup(value);4079 len =strlen(ref);4080while(len && ref[len -1] =='/')4081 ref[--len] ='\0';4082if(!hide_refs) {4083 hide_refs =xcalloc(1,sizeof(*hide_refs));4084 hide_refs->strdup_strings =1;4085}4086string_list_append(hide_refs, ref);4087}4088return0;4089}40904091intref_is_hidden(const char*refname)4092{4093struct string_list_item *item;40944095if(!hide_refs)4096return0;4097for_each_string_list_item(item, hide_refs) {4098int len;4099if(!starts_with(refname, item->string))4100continue;4101 len =strlen(item->string);4102if(!refname[len] || refname[len] =='/')4103return1;4104}4105return0;4106}41074108struct expire_reflog_cb {4109unsigned int flags;4110 reflog_expiry_should_prune_fn *should_prune_fn;4111void*policy_cb;4112FILE*newlog;4113unsigned char last_kept_sha1[20];4114};41154116static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4117const char*email,unsigned long timestamp,int tz,4118const char*message,void*cb_data)4119{4120struct expire_reflog_cb *cb = cb_data;4121struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;41224123if(cb->flags & EXPIRE_REFLOGS_REWRITE)4124 osha1 = cb->last_kept_sha1;41254126if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4127 message, policy_cb)) {4128if(!cb->newlog)4129printf("would prune%s", message);4130else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4131printf("prune%s", message);4132}else{4133if(cb->newlog) {4134fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4135sha1_to_hex(osha1),sha1_to_hex(nsha1),4136 email, timestamp, tz, message);4137hashcpy(cb->last_kept_sha1, nsha1);4138}4139if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4140printf("keep%s", message);4141}4142return0;4143}41444145intreflog_expire(const char*refname,const unsigned char*sha1,4146unsigned int flags,4147 reflog_expiry_prepare_fn prepare_fn,4148 reflog_expiry_should_prune_fn should_prune_fn,4149 reflog_expiry_cleanup_fn cleanup_fn,4150void*policy_cb_data)4151{4152static struct lock_file reflog_lock;4153struct expire_reflog_cb cb;4154struct ref_lock *lock;4155char*log_file;4156int status =0;4157int type;4158struct strbuf err = STRBUF_INIT;41594160memset(&cb,0,sizeof(cb));4161 cb.flags = flags;4162 cb.policy_cb = policy_cb_data;4163 cb.should_prune_fn = should_prune_fn;41644165/*4166 * The reflog file is locked by holding the lock on the4167 * reference itself, plus we might need to update the4168 * reference if --updateref was specified:4169 */4170 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4171if(!lock) {4172error("cannot lock ref '%s':%s", refname, err.buf);4173strbuf_release(&err);4174return-1;4175}4176if(!reflog_exists(refname)) {4177unlock_ref(lock);4178return0;4179}41804181 log_file =git_pathdup("logs/%s", refname);4182if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4183/*4184 * Even though holding $GIT_DIR/logs/$reflog.lock has4185 * no locking implications, we use the lock_file4186 * machinery here anyway because it does a lot of the4187 * work we need, including cleaning up if the program4188 * exits unexpectedly.4189 */4190if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4191struct strbuf err = STRBUF_INIT;4192unable_to_lock_message(log_file, errno, &err);4193error("%s", err.buf);4194strbuf_release(&err);4195goto failure;4196}4197 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4198if(!cb.newlog) {4199error("cannot fdopen%s(%s)",4200 reflog_lock.filename.buf,strerror(errno));4201goto failure;4202}4203}42044205(*prepare_fn)(refname, sha1, cb.policy_cb);4206for_each_reflog_ent(refname, expire_reflog_ent, &cb);4207(*cleanup_fn)(cb.policy_cb);42084209if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4210/*4211 * It doesn't make sense to adjust a reference pointed4212 * to by a symbolic ref based on expiring entries in4213 * the symbolic reference's reflog. Nor can we update4214 * a reference if there are no remaining reflog4215 * entries.4216 */4217int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4218!(type & REF_ISSYMREF) &&4219!is_null_sha1(cb.last_kept_sha1);42204221if(close_lock_file(&reflog_lock)) {4222 status |=error("couldn't write%s:%s", log_file,4223strerror(errno));4224}else if(update &&4225(write_in_full(lock->lock_fd,4226sha1_to_hex(cb.last_kept_sha1),40) !=40||4227write_str_in_full(lock->lock_fd,"\n") !=1||4228close_ref(lock) <0)) {4229 status |=error("couldn't write%s",4230 lock->lk->filename.buf);4231rollback_lock_file(&reflog_lock);4232}else if(commit_lock_file(&reflog_lock)) {4233 status |=error("unable to commit reflog '%s' (%s)",4234 log_file,strerror(errno));4235}else if(update &&commit_ref(lock)) {4236 status |=error("couldn't set%s", lock->ref_name);4237}4238}4239free(log_file);4240unlock_ref(lock);4241return status;42424243 failure:4244rollback_lock_file(&reflog_lock);4245free(log_file);4246unlock_ref(lock);4247return-1;4248}