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; 13struct object_id old_oid; 14}; 15 16/* 17 * How to handle various characters in refnames: 18 * 0: An acceptable character for refs 19 * 1: End-of-component 20 * 2: ., look for a preceding . to reject .. in refs 21 * 3: {, look for a preceding @ to reject @{ in refs 22 * 4: A bad character: ASCII control characters, "~", "^", ":" or SP 23 */ 24static unsigned char refname_disposition[256] = { 251,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 264,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 274,0,0,0,0,0,0,0,0,0,4,0,0,0,2,1, 280,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 290,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 300,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 310,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 320,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 33}; 34 35/* 36 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 37 * refs (i.e., because the reference is about to be deleted anyway). 38 */ 39#define REF_DELETING 0x02 40 41/* 42 * Used as a flag in ref_update::flags when a loose ref is being 43 * pruned. 44 */ 45#define REF_ISPRUNING 0x04 46 47/* 48 * Used as a flag in ref_update::flags when the reference should be 49 * updated to new_sha1. 50 */ 51#define REF_HAVE_NEW 0x08 52 53/* 54 * Used as a flag in ref_update::flags when old_sha1 should be 55 * checked. 56 */ 57#define REF_HAVE_OLD 0x10 58 59/* 60 * Used as a flag in ref_update::flags when the lockfile needs to be 61 * committed. 62 */ 63#define REF_NEEDS_COMMIT 0x20 64 65/* 66 * Try to read one refname component from the front of refname. 67 * Return the length of the component found, or -1 if the component is 68 * not legal. It is legal if it is something reasonable to have under 69 * ".git/refs/"; We do not like it if: 70 * 71 * - any path component of it begins with ".", or 72 * - it has double dots "..", or 73 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 74 * - it ends with a "/". 75 * - it ends with ".lock" 76 * - it contains a "\" (backslash) 77 */ 78static intcheck_refname_component(const char*refname,int flags) 79{ 80const char*cp; 81char last ='\0'; 82 83for(cp = refname; ; cp++) { 84int ch = *cp &255; 85unsigned char disp = refname_disposition[ch]; 86switch(disp) { 87case1: 88goto out; 89case2: 90if(last =='.') 91return-1;/* Refname contains "..". */ 92break; 93case3: 94if(last =='@') 95return-1;/* Refname contains "@{". */ 96break; 97case4: 98return-1; 99} 100 last = ch; 101} 102out: 103if(cp == refname) 104return0;/* Component has zero length. */ 105if(refname[0] =='.') 106return-1;/* Component starts with '.'. */ 107if(cp - refname >= LOCK_SUFFIX_LEN && 108!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 109return-1;/* Refname ends with ".lock". */ 110return cp - refname; 111} 112 113intcheck_refname_format(const char*refname,int flags) 114{ 115int component_len, component_count =0; 116 117if(!strcmp(refname,"@")) 118/* Refname is a single character '@'. */ 119return-1; 120 121while(1) { 122/* We are at the start of a path component. */ 123 component_len =check_refname_component(refname, flags); 124if(component_len <=0) { 125if((flags & REFNAME_REFSPEC_PATTERN) && 126 refname[0] =='*'&& 127(refname[1] =='\0'|| refname[1] =='/')) { 128/* Accept one wildcard as a full refname component. */ 129 flags &= ~REFNAME_REFSPEC_PATTERN; 130 component_len =1; 131}else{ 132return-1; 133} 134} 135 component_count++; 136if(refname[component_len] =='\0') 137break; 138/* Skip to next component. */ 139 refname += component_len +1; 140} 141 142if(refname[component_len -1] =='.') 143return-1;/* Refname ends with '.'. */ 144if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 145return-1;/* Refname has only one component. */ 146return0; 147} 148 149struct ref_entry; 150 151/* 152 * Information used (along with the information in ref_entry) to 153 * describe a single cached reference. This data structure only 154 * occurs embedded in a union in struct ref_entry, and only when 155 * (ref_entry->flag & REF_DIR) is zero. 156 */ 157struct ref_value { 158/* 159 * The name of the object to which this reference resolves 160 * (which may be a tag object). If REF_ISBROKEN, this is 161 * null. If REF_ISSYMREF, then this is the name of the object 162 * referred to by the last reference in the symlink chain. 163 */ 164struct object_id oid; 165 166/* 167 * If REF_KNOWS_PEELED, then this field holds the peeled value 168 * of this reference, or null if the reference is known not to 169 * be peelable. See the documentation for peel_ref() for an 170 * exact definition of "peelable". 171 */ 172struct object_id peeled; 173}; 174 175struct ref_cache; 176 177/* 178 * Information used (along with the information in ref_entry) to 179 * describe a level in the hierarchy of references. This data 180 * structure only occurs embedded in a union in struct ref_entry, and 181 * only when (ref_entry.flag & REF_DIR) is set. In that case, 182 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 183 * in the directory have already been read: 184 * 185 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 186 * or packed references, already read. 187 * 188 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 189 * references that hasn't been read yet (nor has any of its 190 * subdirectories). 191 * 192 * Entries within a directory are stored within a growable array of 193 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 194 * sorted are sorted by their component name in strcmp() order and the 195 * remaining entries are unsorted. 196 * 197 * Loose references are read lazily, one directory at a time. When a 198 * directory of loose references is read, then all of the references 199 * in that directory are stored, and REF_INCOMPLETE stubs are created 200 * for any subdirectories, but the subdirectories themselves are not 201 * read. The reading is triggered by get_ref_dir(). 202 */ 203struct ref_dir { 204int nr, alloc; 205 206/* 207 * Entries with index 0 <= i < sorted are sorted by name. New 208 * entries are appended to the list unsorted, and are sorted 209 * only when required; thus we avoid the need to sort the list 210 * after the addition of every reference. 211 */ 212int sorted; 213 214/* A pointer to the ref_cache that contains this ref_dir. */ 215struct ref_cache *ref_cache; 216 217struct ref_entry **entries; 218}; 219 220/* 221 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 222 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 223 * public values; see refs.h. 224 */ 225 226/* 227 * The field ref_entry->u.value.peeled of this value entry contains 228 * the correct peeled value for the reference, which might be 229 * null_sha1 if the reference is not a tag or if it is broken. 230 */ 231#define REF_KNOWS_PEELED 0x10 232 233/* ref_entry represents a directory of references */ 234#define REF_DIR 0x20 235 236/* 237 * Entry has not yet been read from disk (used only for REF_DIR 238 * entries representing loose references) 239 */ 240#define REF_INCOMPLETE 0x40 241 242/* 243 * A ref_entry represents either a reference or a "subdirectory" of 244 * references. 245 * 246 * Each directory in the reference namespace is represented by a 247 * ref_entry with (flags & REF_DIR) set and containing a subdir member 248 * that holds the entries in that directory that have been read so 249 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 250 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 251 * used for loose reference directories. 252 * 253 * References are represented by a ref_entry with (flags & REF_DIR) 254 * unset and a value member that describes the reference's value. The 255 * flag member is at the ref_entry level, but it is also needed to 256 * interpret the contents of the value field (in other words, a 257 * ref_value object is not very much use without the enclosing 258 * ref_entry). 259 * 260 * Reference names cannot end with slash and directories' names are 261 * always stored with a trailing slash (except for the top-level 262 * directory, which is always denoted by ""). This has two nice 263 * consequences: (1) when the entries in each subdir are sorted 264 * lexicographically by name (as they usually are), the references in 265 * a whole tree can be generated in lexicographic order by traversing 266 * the tree in left-to-right, depth-first order; (2) the names of 267 * references and subdirectories cannot conflict, and therefore the 268 * presence of an empty subdirectory does not block the creation of a 269 * similarly-named reference. (The fact that reference names with the 270 * same leading components can conflict *with each other* is a 271 * separate issue that is regulated by verify_refname_available().) 272 * 273 * Please note that the name field contains the fully-qualified 274 * reference (or subdirectory) name. Space could be saved by only 275 * storing the relative names. But that would require the full names 276 * to be generated on the fly when iterating in do_for_each_ref(), and 277 * would break callback functions, who have always been able to assume 278 * that the name strings that they are passed will not be freed during 279 * the iteration. 280 */ 281struct ref_entry { 282unsigned char flag;/* ISSYMREF? ISPACKED? */ 283union{ 284struct ref_value value;/* if not (flags&REF_DIR) */ 285struct ref_dir subdir;/* if (flags&REF_DIR) */ 286} u; 287/* 288 * The full name of the reference (e.g., "refs/heads/master") 289 * or the full name of the directory with a trailing slash 290 * (e.g., "refs/heads/"): 291 */ 292char name[FLEX_ARRAY]; 293}; 294 295static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 296 297static struct ref_dir *get_ref_dir(struct ref_entry *entry) 298{ 299struct ref_dir *dir; 300assert(entry->flag & REF_DIR); 301 dir = &entry->u.subdir; 302if(entry->flag & REF_INCOMPLETE) { 303read_loose_refs(entry->name, dir); 304 entry->flag &= ~REF_INCOMPLETE; 305} 306return dir; 307} 308 309/* 310 * Check if a refname is safe. 311 * For refs that start with "refs/" we consider it safe as long they do 312 * not try to resolve to outside of refs/. 313 * 314 * For all other refs we only consider them safe iff they only contain 315 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 316 * "config"). 317 */ 318static intrefname_is_safe(const char*refname) 319{ 320if(starts_with(refname,"refs/")) { 321char*buf; 322int result; 323 324 buf =xmalloc(strlen(refname) +1); 325/* 326 * Does the refname try to escape refs/? 327 * For example: refs/foo/../bar is safe but refs/foo/../../bar 328 * is not. 329 */ 330 result = !normalize_path_copy(buf, refname +strlen("refs/")); 331free(buf); 332return result; 333} 334while(*refname) { 335if(!isupper(*refname) && *refname !='_') 336return0; 337 refname++; 338} 339return1; 340} 341 342static struct ref_entry *create_ref_entry(const char*refname, 343const unsigned char*sha1,int flag, 344int check_name) 345{ 346int len; 347struct ref_entry *ref; 348 349if(check_name && 350check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 351die("Reference has invalid format: '%s'", refname); 352 len =strlen(refname) +1; 353 ref =xmalloc(sizeof(struct ref_entry) + len); 354hashcpy(ref->u.value.oid.hash, sha1); 355oidclr(&ref->u.value.peeled); 356memcpy(ref->name, refname, len); 357 ref->flag = flag; 358return ref; 359} 360 361static voidclear_ref_dir(struct ref_dir *dir); 362 363static voidfree_ref_entry(struct ref_entry *entry) 364{ 365if(entry->flag & REF_DIR) { 366/* 367 * Do not use get_ref_dir() here, as that might 368 * trigger the reading of loose refs. 369 */ 370clear_ref_dir(&entry->u.subdir); 371} 372free(entry); 373} 374 375/* 376 * Add a ref_entry to the end of dir (unsorted). Entry is always 377 * stored directly in dir; no recursion into subdirectories is 378 * done. 379 */ 380static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 381{ 382ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 383 dir->entries[dir->nr++] = entry; 384/* optimize for the case that entries are added in order */ 385if(dir->nr ==1|| 386(dir->nr == dir->sorted +1&& 387strcmp(dir->entries[dir->nr -2]->name, 388 dir->entries[dir->nr -1]->name) <0)) 389 dir->sorted = dir->nr; 390} 391 392/* 393 * Clear and free all entries in dir, recursively. 394 */ 395static voidclear_ref_dir(struct ref_dir *dir) 396{ 397int i; 398for(i =0; i < dir->nr; i++) 399free_ref_entry(dir->entries[i]); 400free(dir->entries); 401 dir->sorted = dir->nr = dir->alloc =0; 402 dir->entries = NULL; 403} 404 405/* 406 * Create a struct ref_entry object for the specified dirname. 407 * dirname is the name of the directory with a trailing slash (e.g., 408 * "refs/heads/") or "" for the top-level directory. 409 */ 410static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 411const char*dirname,size_t len, 412int incomplete) 413{ 414struct ref_entry *direntry; 415 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 416memcpy(direntry->name, dirname, len); 417 direntry->name[len] ='\0'; 418 direntry->u.subdir.ref_cache = ref_cache; 419 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 420return direntry; 421} 422 423static intref_entry_cmp(const void*a,const void*b) 424{ 425struct ref_entry *one = *(struct ref_entry **)a; 426struct ref_entry *two = *(struct ref_entry **)b; 427returnstrcmp(one->name, two->name); 428} 429 430static voidsort_ref_dir(struct ref_dir *dir); 431 432struct string_slice { 433size_t len; 434const char*str; 435}; 436 437static intref_entry_cmp_sslice(const void*key_,const void*ent_) 438{ 439const struct string_slice *key = key_; 440const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 441int cmp =strncmp(key->str, ent->name, key->len); 442if(cmp) 443return cmp; 444return'\0'- (unsigned char)ent->name[key->len]; 445} 446 447/* 448 * Return the index of the entry with the given refname from the 449 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 450 * no such entry is found. dir must already be complete. 451 */ 452static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 453{ 454struct ref_entry **r; 455struct string_slice key; 456 457if(refname == NULL || !dir->nr) 458return-1; 459 460sort_ref_dir(dir); 461 key.len = len; 462 key.str = refname; 463 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 464 ref_entry_cmp_sslice); 465 466if(r == NULL) 467return-1; 468 469return r - dir->entries; 470} 471 472/* 473 * Search for a directory entry directly within dir (without 474 * recursing). Sort dir if necessary. subdirname must be a directory 475 * name (i.e., end in '/'). If mkdir is set, then create the 476 * directory if it is missing; otherwise, return NULL if the desired 477 * directory cannot be found. dir must already be complete. 478 */ 479static struct ref_dir *search_for_subdir(struct ref_dir *dir, 480const char*subdirname,size_t len, 481int mkdir) 482{ 483int entry_index =search_ref_dir(dir, subdirname, len); 484struct ref_entry *entry; 485if(entry_index == -1) { 486if(!mkdir) 487return NULL; 488/* 489 * Since dir is complete, the absence of a subdir 490 * means that the subdir really doesn't exist; 491 * therefore, create an empty record for it but mark 492 * the record complete. 493 */ 494 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 495add_entry_to_dir(dir, entry); 496}else{ 497 entry = dir->entries[entry_index]; 498} 499returnget_ref_dir(entry); 500} 501 502/* 503 * If refname is a reference name, find the ref_dir within the dir 504 * tree that should hold refname. If refname is a directory name 505 * (i.e., ends in '/'), then return that ref_dir itself. dir must 506 * represent the top-level directory and must already be complete. 507 * Sort ref_dirs and recurse into subdirectories as necessary. If 508 * mkdir is set, then create any missing directories; otherwise, 509 * return NULL if the desired directory cannot be found. 510 */ 511static struct ref_dir *find_containing_dir(struct ref_dir *dir, 512const char*refname,int mkdir) 513{ 514const char*slash; 515for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 516size_t dirnamelen = slash - refname +1; 517struct ref_dir *subdir; 518 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 519if(!subdir) { 520 dir = NULL; 521break; 522} 523 dir = subdir; 524} 525 526return dir; 527} 528 529/* 530 * Find the value entry with the given name in dir, sorting ref_dirs 531 * and recursing into subdirectories as necessary. If the name is not 532 * found or it corresponds to a directory entry, return NULL. 533 */ 534static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 535{ 536int entry_index; 537struct ref_entry *entry; 538 dir =find_containing_dir(dir, refname,0); 539if(!dir) 540return NULL; 541 entry_index =search_ref_dir(dir, refname,strlen(refname)); 542if(entry_index == -1) 543return NULL; 544 entry = dir->entries[entry_index]; 545return(entry->flag & REF_DIR) ? NULL : entry; 546} 547 548/* 549 * Remove the entry with the given name from dir, recursing into 550 * subdirectories as necessary. If refname is the name of a directory 551 * (i.e., ends with '/'), then remove the directory and its contents. 552 * If the removal was successful, return the number of entries 553 * remaining in the directory entry that contained the deleted entry. 554 * If the name was not found, return -1. Please note that this 555 * function only deletes the entry from the cache; it does not delete 556 * it from the filesystem or ensure that other cache entries (which 557 * might be symbolic references to the removed entry) are updated. 558 * Nor does it remove any containing dir entries that might be made 559 * empty by the removal. dir must represent the top-level directory 560 * and must already be complete. 561 */ 562static intremove_entry(struct ref_dir *dir,const char*refname) 563{ 564int refname_len =strlen(refname); 565int entry_index; 566struct ref_entry *entry; 567int is_dir = refname[refname_len -1] =='/'; 568if(is_dir) { 569/* 570 * refname represents a reference directory. Remove 571 * the trailing slash; otherwise we will get the 572 * directory *representing* refname rather than the 573 * one *containing* it. 574 */ 575char*dirname =xmemdupz(refname, refname_len -1); 576 dir =find_containing_dir(dir, dirname,0); 577free(dirname); 578}else{ 579 dir =find_containing_dir(dir, refname,0); 580} 581if(!dir) 582return-1; 583 entry_index =search_ref_dir(dir, refname, refname_len); 584if(entry_index == -1) 585return-1; 586 entry = dir->entries[entry_index]; 587 588memmove(&dir->entries[entry_index], 589&dir->entries[entry_index +1], 590(dir->nr - entry_index -1) *sizeof(*dir->entries) 591); 592 dir->nr--; 593if(dir->sorted > entry_index) 594 dir->sorted--; 595free_ref_entry(entry); 596return dir->nr; 597} 598 599/* 600 * Add a ref_entry to the ref_dir (unsorted), recursing into 601 * subdirectories as necessary. dir must represent the top-level 602 * directory. Return 0 on success. 603 */ 604static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 605{ 606 dir =find_containing_dir(dir, ref->name,1); 607if(!dir) 608return-1; 609add_entry_to_dir(dir, ref); 610return0; 611} 612 613/* 614 * Emit a warning and return true iff ref1 and ref2 have the same name 615 * and the same sha1. Die if they have the same name but different 616 * sha1s. 617 */ 618static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 619{ 620if(strcmp(ref1->name, ref2->name)) 621return0; 622 623/* Duplicate name; make sure that they don't conflict: */ 624 625if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 626/* This is impossible by construction */ 627die("Reference directory conflict:%s", ref1->name); 628 629if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 630die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 631 632warning("Duplicated ref:%s", ref1->name); 633return1; 634} 635 636/* 637 * Sort the entries in dir non-recursively (if they are not already 638 * sorted) and remove any duplicate entries. 639 */ 640static voidsort_ref_dir(struct ref_dir *dir) 641{ 642int i, j; 643struct ref_entry *last = NULL; 644 645/* 646 * This check also prevents passing a zero-length array to qsort(), 647 * which is a problem on some platforms. 648 */ 649if(dir->sorted == dir->nr) 650return; 651 652qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 653 654/* Remove any duplicates: */ 655for(i =0, j =0; j < dir->nr; j++) { 656struct ref_entry *entry = dir->entries[j]; 657if(last &&is_dup_ref(last, entry)) 658free_ref_entry(entry); 659else 660 last = dir->entries[i++] = entry; 661} 662 dir->sorted = dir->nr = i; 663} 664 665/* Include broken references in a do_for_each_ref*() iteration: */ 666#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 667 668/* 669 * Return true iff the reference described by entry can be resolved to 670 * an object in the database. Emit a warning if the referred-to 671 * object does not exist. 672 */ 673static intref_resolves_to_object(struct ref_entry *entry) 674{ 675if(entry->flag & REF_ISBROKEN) 676return0; 677if(!has_sha1_file(entry->u.value.oid.hash)) { 678error("%sdoes not point to a valid object!", entry->name); 679return0; 680} 681return1; 682} 683 684/* 685 * current_ref is a performance hack: when iterating over references 686 * using the for_each_ref*() functions, current_ref is set to the 687 * current reference's entry before calling the callback function. If 688 * the callback function calls peel_ref(), then peel_ref() first 689 * checks whether the reference to be peeled is the current reference 690 * (it usually is) and if so, returns that reference's peeled version 691 * if it is available. This avoids a refname lookup in a common case. 692 */ 693static struct ref_entry *current_ref; 694 695typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 696 697struct ref_entry_cb { 698const char*base; 699int trim; 700int flags; 701 each_ref_fn *fn; 702void*cb_data; 703}; 704 705/* 706 * Handle one reference in a do_for_each_ref*()-style iteration, 707 * calling an each_ref_fn for each entry. 708 */ 709static intdo_one_ref(struct ref_entry *entry,void*cb_data) 710{ 711struct ref_entry_cb *data = cb_data; 712struct ref_entry *old_current_ref; 713int retval; 714 715if(!starts_with(entry->name, data->base)) 716return0; 717 718if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 719!ref_resolves_to_object(entry)) 720return0; 721 722/* Store the old value, in case this is a recursive call: */ 723 old_current_ref = current_ref; 724 current_ref = entry; 725 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 726 entry->flag, data->cb_data); 727 current_ref = old_current_ref; 728return retval; 729} 730 731/* 732 * Call fn for each reference in dir that has index in the range 733 * offset <= index < dir->nr. Recurse into subdirectories that are in 734 * that index range, sorting them before iterating. This function 735 * does not sort dir itself; it should be sorted beforehand. fn is 736 * called for all references, including broken ones. 737 */ 738static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 739 each_ref_entry_fn fn,void*cb_data) 740{ 741int i; 742assert(dir->sorted == dir->nr); 743for(i = offset; i < dir->nr; i++) { 744struct ref_entry *entry = dir->entries[i]; 745int retval; 746if(entry->flag & REF_DIR) { 747struct ref_dir *subdir =get_ref_dir(entry); 748sort_ref_dir(subdir); 749 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 750}else{ 751 retval =fn(entry, cb_data); 752} 753if(retval) 754return retval; 755} 756return0; 757} 758 759/* 760 * Call fn for each reference in the union of dir1 and dir2, in order 761 * by refname. Recurse into subdirectories. If a value entry appears 762 * in both dir1 and dir2, then only process the version that is in 763 * dir2. The input dirs must already be sorted, but subdirs will be 764 * sorted as needed. fn is called for all references, including 765 * broken ones. 766 */ 767static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 768struct ref_dir *dir2, 769 each_ref_entry_fn fn,void*cb_data) 770{ 771int retval; 772int i1 =0, i2 =0; 773 774assert(dir1->sorted == dir1->nr); 775assert(dir2->sorted == dir2->nr); 776while(1) { 777struct ref_entry *e1, *e2; 778int cmp; 779if(i1 == dir1->nr) { 780returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 781} 782if(i2 == dir2->nr) { 783returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 784} 785 e1 = dir1->entries[i1]; 786 e2 = dir2->entries[i2]; 787 cmp =strcmp(e1->name, e2->name); 788if(cmp ==0) { 789if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 790/* Both are directories; descend them in parallel. */ 791struct ref_dir *subdir1 =get_ref_dir(e1); 792struct ref_dir *subdir2 =get_ref_dir(e2); 793sort_ref_dir(subdir1); 794sort_ref_dir(subdir2); 795 retval =do_for_each_entry_in_dirs( 796 subdir1, subdir2, fn, cb_data); 797 i1++; 798 i2++; 799}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 800/* Both are references; ignore the one from dir1. */ 801 retval =fn(e2, cb_data); 802 i1++; 803 i2++; 804}else{ 805die("conflict between reference and directory:%s", 806 e1->name); 807} 808}else{ 809struct ref_entry *e; 810if(cmp <0) { 811 e = e1; 812 i1++; 813}else{ 814 e = e2; 815 i2++; 816} 817if(e->flag & REF_DIR) { 818struct ref_dir *subdir =get_ref_dir(e); 819sort_ref_dir(subdir); 820 retval =do_for_each_entry_in_dir( 821 subdir,0, fn, cb_data); 822}else{ 823 retval =fn(e, cb_data); 824} 825} 826if(retval) 827return retval; 828} 829} 830 831/* 832 * Load all of the refs from the dir into our in-memory cache. The hard work 833 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 834 * through all of the sub-directories. We do not even need to care about 835 * sorting, as traversal order does not matter to us. 836 */ 837static voidprime_ref_dir(struct ref_dir *dir) 838{ 839int i; 840for(i =0; i < dir->nr; i++) { 841struct ref_entry *entry = dir->entries[i]; 842if(entry->flag & REF_DIR) 843prime_ref_dir(get_ref_dir(entry)); 844} 845} 846 847struct nonmatching_ref_data { 848const struct string_list *skip; 849const char*conflicting_refname; 850}; 851 852static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 853{ 854struct nonmatching_ref_data *data = vdata; 855 856if(data->skip &&string_list_has_string(data->skip, entry->name)) 857return0; 858 859 data->conflicting_refname = entry->name; 860return1; 861} 862 863/* 864 * Return 0 if a reference named refname could be created without 865 * conflicting with the name of an existing reference in dir. 866 * Otherwise, return a negative value and write an explanation to err. 867 * If extras is non-NULL, it is a list of additional refnames with 868 * which refname is not allowed to conflict. If skip is non-NULL, 869 * ignore potential conflicts with refs in skip (e.g., because they 870 * are scheduled for deletion in the same operation). Behavior is 871 * undefined if the same name is listed in both extras and skip. 872 * 873 * Two reference names conflict if one of them exactly matches the 874 * leading components of the other; e.g., "refs/foo/bar" conflicts 875 * with both "refs/foo" and with "refs/foo/bar/baz" but not with 876 * "refs/foo/bar" or "refs/foo/barbados". 877 * 878 * extras and skip must be sorted. 879 */ 880static intverify_refname_available(const char*refname, 881const struct string_list *extras, 882const struct string_list *skip, 883struct ref_dir *dir, 884struct strbuf *err) 885{ 886const char*slash; 887int pos; 888struct strbuf dirname = STRBUF_INIT; 889int ret = -1; 890 891/* 892 * For the sake of comments in this function, suppose that 893 * refname is "refs/foo/bar". 894 */ 895 896assert(err); 897 898strbuf_grow(&dirname,strlen(refname) +1); 899for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 900/* Expand dirname to the new prefix, not including the trailing slash: */ 901strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 902 903/* 904 * We are still at a leading dir of the refname (e.g., 905 * "refs/foo"; if there is a reference with that name, 906 * it is a conflict, *unless* it is in skip. 907 */ 908if(dir) { 909 pos =search_ref_dir(dir, dirname.buf, dirname.len); 910if(pos >=0&& 911(!skip || !string_list_has_string(skip, dirname.buf))) { 912/* 913 * We found a reference whose name is 914 * a proper prefix of refname; e.g., 915 * "refs/foo", and is not in skip. 916 */ 917strbuf_addf(err,"'%s' exists; cannot create '%s'", 918 dirname.buf, refname); 919goto cleanup; 920} 921} 922 923if(extras &&string_list_has_string(extras, dirname.buf) && 924(!skip || !string_list_has_string(skip, dirname.buf))) { 925strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 926 refname, dirname.buf); 927goto cleanup; 928} 929 930/* 931 * Otherwise, we can try to continue our search with 932 * the next component. So try to look up the 933 * directory, e.g., "refs/foo/". If we come up empty, 934 * we know there is nothing under this whole prefix, 935 * but even in that case we still have to continue the 936 * search for conflicts with extras. 937 */ 938strbuf_addch(&dirname,'/'); 939if(dir) { 940 pos =search_ref_dir(dir, dirname.buf, dirname.len); 941if(pos <0) { 942/* 943 * There was no directory "refs/foo/", 944 * so there is nothing under this 945 * whole prefix. So there is no need 946 * to continue looking for conflicting 947 * references. But we need to continue 948 * looking for conflicting extras. 949 */ 950 dir = NULL; 951}else{ 952 dir =get_ref_dir(dir->entries[pos]); 953} 954} 955} 956 957/* 958 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 959 * There is no point in searching for a reference with that 960 * name, because a refname isn't considered to conflict with 961 * itself. But we still need to check for references whose 962 * names are in the "refs/foo/bar/" namespace, because they 963 * *do* conflict. 964 */ 965strbuf_addstr(&dirname, refname + dirname.len); 966strbuf_addch(&dirname,'/'); 967 968if(dir) { 969 pos =search_ref_dir(dir, dirname.buf, dirname.len); 970 971if(pos >=0) { 972/* 973 * We found a directory named "$refname/" 974 * (e.g., "refs/foo/bar/"). It is a problem 975 * iff it contains any ref that is not in 976 * "skip". 977 */ 978struct nonmatching_ref_data data; 979 980 data.skip = skip; 981 data.conflicting_refname = NULL; 982 dir =get_ref_dir(dir->entries[pos]); 983sort_ref_dir(dir); 984if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 985strbuf_addf(err,"'%s' exists; cannot create '%s'", 986 data.conflicting_refname, refname); 987goto cleanup; 988} 989} 990} 991 992if(extras) { 993/* 994 * Check for entries in extras that start with 995 * "$refname/". We do that by looking for the place 996 * where "$refname/" would be inserted in extras. If 997 * there is an entry at that position that starts with 998 * "$refname/" and is not in skip, then we have a 999 * conflict.1000 */1001for(pos =string_list_find_insert_index(extras, dirname.buf,0);1002 pos < extras->nr; pos++) {1003const char*extra_refname = extras->items[pos].string;10041005if(!starts_with(extra_refname, dirname.buf))1006break;10071008if(!skip || !string_list_has_string(skip, extra_refname)) {1009strbuf_addf(err,"cannot process '%s' and '%s' at the same time",1010 refname, extra_refname);1011goto cleanup;1012}1013}1014}10151016/* No conflicts were found */1017 ret =0;10181019cleanup:1020strbuf_release(&dirname);1021return ret;1022}10231024struct packed_ref_cache {1025struct ref_entry *root;10261027/*1028 * Count of references to the data structure in this instance,1029 * including the pointer from ref_cache::packed if any. The1030 * data will not be freed as long as the reference count is1031 * nonzero.1032 */1033unsigned int referrers;10341035/*1036 * Iff the packed-refs file associated with this instance is1037 * currently locked for writing, this points at the associated1038 * lock (which is owned by somebody else). The referrer count1039 * is also incremented when the file is locked and decremented1040 * when it is unlocked.1041 */1042struct lock_file *lock;10431044/* The metadata from when this packed-refs cache was read */1045struct stat_validity validity;1046};10471048/*1049 * Future: need to be in "struct repository"1050 * when doing a full libification.1051 */1052static struct ref_cache {1053struct ref_cache *next;1054struct ref_entry *loose;1055struct packed_ref_cache *packed;1056/*1057 * The submodule name, or "" for the main repo. We allocate1058 * length 1 rather than FLEX_ARRAY so that the main ref_cache1059 * is initialized correctly.1060 */1061char name[1];1062} ref_cache, *submodule_ref_caches;10631064/* Lock used for the main packed-refs file: */1065static struct lock_file packlock;10661067/*1068 * Increment the reference count of *packed_refs.1069 */1070static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1071{1072 packed_refs->referrers++;1073}10741075/*1076 * Decrease the reference count of *packed_refs. If it goes to zero,1077 * free *packed_refs and return true; otherwise return false.1078 */1079static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1080{1081if(!--packed_refs->referrers) {1082free_ref_entry(packed_refs->root);1083stat_validity_clear(&packed_refs->validity);1084free(packed_refs);1085return1;1086}else{1087return0;1088}1089}10901091static voidclear_packed_ref_cache(struct ref_cache *refs)1092{1093if(refs->packed) {1094struct packed_ref_cache *packed_refs = refs->packed;10951096if(packed_refs->lock)1097die("internal error: packed-ref cache cleared while locked");1098 refs->packed = NULL;1099release_packed_ref_cache(packed_refs);1100}1101}11021103static voidclear_loose_ref_cache(struct ref_cache *refs)1104{1105if(refs->loose) {1106free_ref_entry(refs->loose);1107 refs->loose = NULL;1108}1109}11101111static struct ref_cache *create_ref_cache(const char*submodule)1112{1113int len;1114struct ref_cache *refs;1115if(!submodule)1116 submodule ="";1117 len =strlen(submodule) +1;1118 refs =xcalloc(1,sizeof(struct ref_cache) + len);1119memcpy(refs->name, submodule, len);1120return refs;1121}11221123/*1124 * Return a pointer to a ref_cache for the specified submodule. For1125 * the main repository, use submodule==NULL. The returned structure1126 * will be allocated and initialized but not necessarily populated; it1127 * should not be freed.1128 */1129static struct ref_cache *get_ref_cache(const char*submodule)1130{1131struct ref_cache *refs;11321133if(!submodule || !*submodule)1134return&ref_cache;11351136for(refs = submodule_ref_caches; refs; refs = refs->next)1137if(!strcmp(submodule, refs->name))1138return refs;11391140 refs =create_ref_cache(submodule);1141 refs->next = submodule_ref_caches;1142 submodule_ref_caches = refs;1143return refs;1144}11451146/* The length of a peeled reference line in packed-refs, including EOL: */1147#define PEELED_LINE_LENGTH 4211481149/*1150 * The packed-refs header line that we write out. Perhaps other1151 * traits will be added later. The trailing space is required.1152 */1153static const char PACKED_REFS_HEADER[] =1154"# pack-refs with: peeled fully-peeled\n";11551156/*1157 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1158 * Return a pointer to the refname within the line (null-terminated),1159 * or NULL if there was a problem.1160 */1161static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1162{1163const char*ref;11641165/*1166 * 42: the answer to everything.1167 *1168 * In this case, it happens to be the answer to1169 * 40 (length of sha1 hex representation)1170 * +1 (space in between hex and name)1171 * +1 (newline at the end of the line)1172 */1173if(line->len <=42)1174return NULL;11751176if(get_sha1_hex(line->buf, sha1) <0)1177return NULL;1178if(!isspace(line->buf[40]))1179return NULL;11801181 ref = line->buf +41;1182if(isspace(*ref))1183return NULL;11841185if(line->buf[line->len -1] !='\n')1186return NULL;1187 line->buf[--line->len] =0;11881189return ref;1190}11911192/*1193 * Read f, which is a packed-refs file, into dir.1194 *1195 * A comment line of the form "# pack-refs with: " may contain zero or1196 * more traits. We interpret the traits as follows:1197 *1198 * No traits:1199 *1200 * Probably no references are peeled. But if the file contains a1201 * peeled value for a reference, we will use it.1202 *1203 * peeled:1204 *1205 * References under "refs/tags/", if they *can* be peeled, *are*1206 * peeled in this file. References outside of "refs/tags/" are1207 * probably not peeled even if they could have been, but if we find1208 * a peeled value for such a reference we will use it.1209 *1210 * fully-peeled:1211 *1212 * All references in the file that can be peeled are peeled.1213 * Inversely (and this is more important), any references in the1214 * file for which no peeled value is recorded is not peelable. This1215 * trait should typically be written alongside "peeled" for1216 * compatibility with older clients, but we do not require it1217 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1218 */1219static voidread_packed_refs(FILE*f,struct ref_dir *dir)1220{1221struct ref_entry *last = NULL;1222struct strbuf line = STRBUF_INIT;1223enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12241225while(strbuf_getwholeline(&line, f,'\n') != EOF) {1226unsigned char sha1[20];1227const char*refname;1228const char*traits;12291230if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1231if(strstr(traits," fully-peeled "))1232 peeled = PEELED_FULLY;1233else if(strstr(traits," peeled "))1234 peeled = PEELED_TAGS;1235/* perhaps other traits later as well */1236continue;1237}12381239 refname =parse_ref_line(&line, sha1);1240if(refname) {1241int flag = REF_ISPACKED;12421243if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1244if(!refname_is_safe(refname))1245die("packed refname is dangerous:%s", refname);1246hashclr(sha1);1247 flag |= REF_BAD_NAME | REF_ISBROKEN;1248}1249 last =create_ref_entry(refname, sha1, flag,0);1250if(peeled == PEELED_FULLY ||1251(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1252 last->flag |= REF_KNOWS_PEELED;1253add_ref(dir, last);1254continue;1255}1256if(last &&1257 line.buf[0] =='^'&&1258 line.len == PEELED_LINE_LENGTH &&1259 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1260!get_sha1_hex(line.buf +1, sha1)) {1261hashcpy(last->u.value.peeled.hash, sha1);1262/*1263 * Regardless of what the file header said,1264 * we definitely know the value of *this*1265 * reference:1266 */1267 last->flag |= REF_KNOWS_PEELED;1268}1269}12701271strbuf_release(&line);1272}12731274/*1275 * Get the packed_ref_cache for the specified ref_cache, creating it1276 * if necessary.1277 */1278static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1279{1280const char*packed_refs_file;12811282if(*refs->name)1283 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1284else1285 packed_refs_file =git_path("packed-refs");12861287if(refs->packed &&1288!stat_validity_check(&refs->packed->validity, packed_refs_file))1289clear_packed_ref_cache(refs);12901291if(!refs->packed) {1292FILE*f;12931294 refs->packed =xcalloc(1,sizeof(*refs->packed));1295acquire_packed_ref_cache(refs->packed);1296 refs->packed->root =create_dir_entry(refs,"",0,0);1297 f =fopen(packed_refs_file,"r");1298if(f) {1299stat_validity_update(&refs->packed->validity,fileno(f));1300read_packed_refs(f,get_ref_dir(refs->packed->root));1301fclose(f);1302}1303}1304return refs->packed;1305}13061307static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1308{1309returnget_ref_dir(packed_ref_cache->root);1310}13111312static struct ref_dir *get_packed_refs(struct ref_cache *refs)1313{1314returnget_packed_ref_dir(get_packed_ref_cache(refs));1315}13161317/*1318 * Add a reference to the in-memory packed reference cache. This may1319 * only be called while the packed-refs file is locked (see1320 * lock_packed_refs()). To actually write the packed-refs file, call1321 * commit_packed_refs().1322 */1323static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1324{1325struct packed_ref_cache *packed_ref_cache =1326get_packed_ref_cache(&ref_cache);13271328if(!packed_ref_cache->lock)1329die("internal error: packed refs not locked");1330add_ref(get_packed_ref_dir(packed_ref_cache),1331create_ref_entry(refname, sha1, REF_ISPACKED,1));1332}13331334/*1335 * Read the loose references from the namespace dirname into dir1336 * (without recursing). dirname must end with '/'. dir must be the1337 * directory entry corresponding to dirname.1338 */1339static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1340{1341struct ref_cache *refs = dir->ref_cache;1342DIR*d;1343const char*path;1344struct dirent *de;1345int dirnamelen =strlen(dirname);1346struct strbuf refname;13471348if(*refs->name)1349 path =git_path_submodule(refs->name,"%s", dirname);1350else1351 path =git_path("%s", dirname);13521353 d =opendir(path);1354if(!d)1355return;13561357strbuf_init(&refname, dirnamelen +257);1358strbuf_add(&refname, dirname, dirnamelen);13591360while((de =readdir(d)) != NULL) {1361unsigned char sha1[20];1362struct stat st;1363int flag;1364const char*refdir;13651366if(de->d_name[0] =='.')1367continue;1368if(ends_with(de->d_name,".lock"))1369continue;1370strbuf_addstr(&refname, de->d_name);1371 refdir = *refs->name1372?git_path_submodule(refs->name,"%s", refname.buf)1373:git_path("%s", refname.buf);1374if(stat(refdir, &st) <0) {1375;/* silently ignore */1376}else if(S_ISDIR(st.st_mode)) {1377strbuf_addch(&refname,'/');1378add_entry_to_dir(dir,1379create_dir_entry(refs, refname.buf,1380 refname.len,1));1381}else{1382int read_ok;13831384if(*refs->name) {1385hashclr(sha1);1386 flag =0;1387 read_ok = !resolve_gitlink_ref(refs->name,1388 refname.buf, sha1);1389}else{1390 read_ok = !read_ref_full(refname.buf,1391 RESOLVE_REF_READING,1392 sha1, &flag);1393}13941395if(!read_ok) {1396hashclr(sha1);1397 flag |= REF_ISBROKEN;1398}else if(is_null_sha1(sha1)) {1399/*1400 * It is so astronomically unlikely1401 * that NULL_SHA1 is the SHA-1 of an1402 * actual object that we consider its1403 * appearance in a loose reference1404 * file to be repo corruption1405 * (probably due to a software bug).1406 */1407 flag |= REF_ISBROKEN;1408}14091410if(check_refname_format(refname.buf,1411 REFNAME_ALLOW_ONELEVEL)) {1412if(!refname_is_safe(refname.buf))1413die("loose refname is dangerous:%s", refname.buf);1414hashclr(sha1);1415 flag |= REF_BAD_NAME | REF_ISBROKEN;1416}1417add_entry_to_dir(dir,1418create_ref_entry(refname.buf, sha1, flag,0));1419}1420strbuf_setlen(&refname, dirnamelen);1421}1422strbuf_release(&refname);1423closedir(d);1424}14251426static struct ref_dir *get_loose_refs(struct ref_cache *refs)1427{1428if(!refs->loose) {1429/*1430 * Mark the top-level directory complete because we1431 * are about to read the only subdirectory that can1432 * hold references:1433 */1434 refs->loose =create_dir_entry(refs,"",0,0);1435/*1436 * Create an incomplete entry for "refs/":1437 */1438add_entry_to_dir(get_ref_dir(refs->loose),1439create_dir_entry(refs,"refs/",5,1));1440}1441returnget_ref_dir(refs->loose);1442}14431444/* We allow "recursive" symbolic refs. Only within reason, though */1445#define MAXDEPTH 51446#define MAXREFLEN (1024)14471448/*1449 * Called by resolve_gitlink_ref_recursive() after it failed to read1450 * from the loose refs in ref_cache refs. Find <refname> in the1451 * packed-refs file for the submodule.1452 */1453static intresolve_gitlink_packed_ref(struct ref_cache *refs,1454const char*refname,unsigned char*sha1)1455{1456struct ref_entry *ref;1457struct ref_dir *dir =get_packed_refs(refs);14581459 ref =find_ref(dir, refname);1460if(ref == NULL)1461return-1;14621463hashcpy(sha1, ref->u.value.oid.hash);1464return0;1465}14661467static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1468const char*refname,unsigned char*sha1,1469int recursion)1470{1471int fd, len;1472char buffer[128], *p;1473const char*path;14741475if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1476return-1;1477 path = *refs->name1478?git_path_submodule(refs->name,"%s", refname)1479:git_path("%s", refname);1480 fd =open(path, O_RDONLY);1481if(fd <0)1482returnresolve_gitlink_packed_ref(refs, refname, sha1);14831484 len =read(fd, buffer,sizeof(buffer)-1);1485close(fd);1486if(len <0)1487return-1;1488while(len &&isspace(buffer[len-1]))1489 len--;1490 buffer[len] =0;14911492/* Was it a detached head or an old-fashioned symlink? */1493if(!get_sha1_hex(buffer, sha1))1494return0;14951496/* Symref? */1497if(strncmp(buffer,"ref:",4))1498return-1;1499 p = buffer +4;1500while(isspace(*p))1501 p++;15021503returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1504}15051506intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1507{1508int len =strlen(path), retval;1509char*submodule;1510struct ref_cache *refs;15111512while(len && path[len-1] =='/')1513 len--;1514if(!len)1515return-1;1516 submodule =xstrndup(path, len);1517 refs =get_ref_cache(submodule);1518free(submodule);15191520 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1521return retval;1522}15231524/*1525 * Return the ref_entry for the given refname from the packed1526 * references. If it does not exist, return NULL.1527 */1528static struct ref_entry *get_packed_ref(const char*refname)1529{1530returnfind_ref(get_packed_refs(&ref_cache), refname);1531}15321533/*1534 * A loose ref file doesn't exist; check for a packed ref. The1535 * options are forwarded from resolve_safe_unsafe().1536 */1537static intresolve_missing_loose_ref(const char*refname,1538int resolve_flags,1539unsigned char*sha1,1540int*flags)1541{1542struct ref_entry *entry;15431544/*1545 * The loose reference file does not exist; check for a packed1546 * reference.1547 */1548 entry =get_packed_ref(refname);1549if(entry) {1550hashcpy(sha1, entry->u.value.oid.hash);1551if(flags)1552*flags |= REF_ISPACKED;1553return0;1554}1555/* The reference is not a packed reference, either. */1556if(resolve_flags & RESOLVE_REF_READING) {1557 errno = ENOENT;1558return-1;1559}else{1560hashclr(sha1);1561return0;1562}1563}15641565/* This function needs to return a meaningful errno on failure */1566static const char*resolve_ref_unsafe_1(const char*refname,1567int resolve_flags,1568unsigned char*sha1,1569int*flags,1570struct strbuf *sb_path)1571{1572int depth = MAXDEPTH;1573 ssize_t len;1574char buffer[256];1575static char refname_buffer[256];1576int bad_name =0;15771578if(flags)1579*flags =0;15801581if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1582if(flags)1583*flags |= REF_BAD_NAME;15841585if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1586!refname_is_safe(refname)) {1587 errno = EINVAL;1588return NULL;1589}1590/*1591 * dwim_ref() uses REF_ISBROKEN to distinguish between1592 * missing refs and refs that were present but invalid,1593 * to complain about the latter to stderr.1594 *1595 * We don't know whether the ref exists, so don't set1596 * REF_ISBROKEN yet.1597 */1598 bad_name =1;1599}1600for(;;) {1601const char*path;1602struct stat st;1603char*buf;1604int fd;16051606if(--depth <0) {1607 errno = ELOOP;1608return NULL;1609}16101611strbuf_reset(sb_path);1612strbuf_git_path(sb_path,"%s", refname);1613 path = sb_path->buf;16141615/*1616 * We might have to loop back here to avoid a race1617 * condition: first we lstat() the file, then we try1618 * to read it as a link or as a file. But if somebody1619 * changes the type of the file (file <-> directory1620 * <-> symlink) between the lstat() and reading, then1621 * we don't want to report that as an error but rather1622 * try again starting with the lstat().1623 */1624 stat_ref:1625if(lstat(path, &st) <0) {1626if(errno != ENOENT)1627return NULL;1628if(resolve_missing_loose_ref(refname, resolve_flags,1629 sha1, flags))1630return NULL;1631if(bad_name) {1632hashclr(sha1);1633if(flags)1634*flags |= REF_ISBROKEN;1635}1636return refname;1637}16381639/* Follow "normalized" - ie "refs/.." symlinks by hand */1640if(S_ISLNK(st.st_mode)) {1641 len =readlink(path, buffer,sizeof(buffer)-1);1642if(len <0) {1643if(errno == ENOENT || errno == EINVAL)1644/* inconsistent with lstat; retry */1645goto stat_ref;1646else1647return NULL;1648}1649 buffer[len] =0;1650if(starts_with(buffer,"refs/") &&1651!check_refname_format(buffer,0)) {1652strcpy(refname_buffer, buffer);1653 refname = refname_buffer;1654if(flags)1655*flags |= REF_ISSYMREF;1656if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1657hashclr(sha1);1658return refname;1659}1660continue;1661}1662}16631664/* Is it a directory? */1665if(S_ISDIR(st.st_mode)) {1666 errno = EISDIR;1667return NULL;1668}16691670/*1671 * Anything else, just open it and try to use it as1672 * a ref1673 */1674 fd =open(path, O_RDONLY);1675if(fd <0) {1676if(errno == ENOENT)1677/* inconsistent with lstat; retry */1678goto stat_ref;1679else1680return NULL;1681}1682 len =read_in_full(fd, buffer,sizeof(buffer)-1);1683if(len <0) {1684int save_errno = errno;1685close(fd);1686 errno = save_errno;1687return NULL;1688}1689close(fd);1690while(len &&isspace(buffer[len-1]))1691 len--;1692 buffer[len] ='\0';16931694/*1695 * Is it a symbolic ref?1696 */1697if(!starts_with(buffer,"ref:")) {1698/*1699 * Please note that FETCH_HEAD has a second1700 * line containing other data.1701 */1702if(get_sha1_hex(buffer, sha1) ||1703(buffer[40] !='\0'&& !isspace(buffer[40]))) {1704if(flags)1705*flags |= REF_ISBROKEN;1706 errno = EINVAL;1707return NULL;1708}1709if(bad_name) {1710hashclr(sha1);1711if(flags)1712*flags |= REF_ISBROKEN;1713}1714return refname;1715}1716if(flags)1717*flags |= REF_ISSYMREF;1718 buf = buffer +4;1719while(isspace(*buf))1720 buf++;1721 refname =strcpy(refname_buffer, buf);1722if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1723hashclr(sha1);1724return refname;1725}1726if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1727if(flags)1728*flags |= REF_ISBROKEN;17291730if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1731!refname_is_safe(buf)) {1732 errno = EINVAL;1733return NULL;1734}1735 bad_name =1;1736}1737}1738}17391740const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1741unsigned char*sha1,int*flags)1742{1743struct strbuf sb_path = STRBUF_INIT;1744const char*ret =resolve_ref_unsafe_1(refname, resolve_flags,1745 sha1, flags, &sb_path);1746strbuf_release(&sb_path);1747return ret;1748}17491750char*resolve_refdup(const char*refname,int resolve_flags,1751unsigned char*sha1,int*flags)1752{1753returnxstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1754 sha1, flags));1755}17561757/* The argument to filter_refs */1758struct ref_filter {1759const char*pattern;1760 each_ref_fn *fn;1761void*cb_data;1762};17631764intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1765{1766if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1767return0;1768return-1;1769}17701771intread_ref(const char*refname,unsigned char*sha1)1772{1773returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1774}17751776intref_exists(const char*refname)1777{1778unsigned char sha1[20];1779return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1780}17811782static intfilter_refs(const char*refname,const struct object_id *oid,1783int flags,void*data)1784{1785struct ref_filter *filter = (struct ref_filter *)data;17861787if(wildmatch(filter->pattern, refname,0, NULL))1788return0;1789return filter->fn(refname, oid, flags, filter->cb_data);1790}17911792enum peel_status {1793/* object was peeled successfully: */1794 PEEL_PEELED =0,17951796/*1797 * object cannot be peeled because the named object (or an1798 * object referred to by a tag in the peel chain), does not1799 * exist.1800 */1801 PEEL_INVALID = -1,18021803/* object cannot be peeled because it is not a tag: */1804 PEEL_NON_TAG = -2,18051806/* ref_entry contains no peeled value because it is a symref: */1807 PEEL_IS_SYMREF = -3,18081809/*1810 * ref_entry cannot be peeled because it is broken (i.e., the1811 * symbolic reference cannot even be resolved to an object1812 * name):1813 */1814 PEEL_BROKEN = -41815};18161817/*1818 * Peel the named object; i.e., if the object is a tag, resolve the1819 * tag recursively until a non-tag is found. If successful, store the1820 * result to sha1 and return PEEL_PEELED. If the object is not a tag1821 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1822 * and leave sha1 unchanged.1823 */1824static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1825{1826struct object *o =lookup_unknown_object(name);18271828if(o->type == OBJ_NONE) {1829int type =sha1_object_info(name, NULL);1830if(type <0|| !object_as_type(o, type,0))1831return PEEL_INVALID;1832}18331834if(o->type != OBJ_TAG)1835return PEEL_NON_TAG;18361837 o =deref_tag_noverify(o);1838if(!o)1839return PEEL_INVALID;18401841hashcpy(sha1, o->sha1);1842return PEEL_PEELED;1843}18441845/*1846 * Peel the entry (if possible) and return its new peel_status. If1847 * repeel is true, re-peel the entry even if there is an old peeled1848 * value that is already stored in it.1849 *1850 * It is OK to call this function with a packed reference entry that1851 * might be stale and might even refer to an object that has since1852 * been garbage-collected. In such a case, if the entry has1853 * REF_KNOWS_PEELED then leave the status unchanged and return1854 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1855 */1856static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1857{1858enum peel_status status;18591860if(entry->flag & REF_KNOWS_PEELED) {1861if(repeel) {1862 entry->flag &= ~REF_KNOWS_PEELED;1863oidclr(&entry->u.value.peeled);1864}else{1865returnis_null_oid(&entry->u.value.peeled) ?1866 PEEL_NON_TAG : PEEL_PEELED;1867}1868}1869if(entry->flag & REF_ISBROKEN)1870return PEEL_BROKEN;1871if(entry->flag & REF_ISSYMREF)1872return PEEL_IS_SYMREF;18731874 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1875if(status == PEEL_PEELED || status == PEEL_NON_TAG)1876 entry->flag |= REF_KNOWS_PEELED;1877return status;1878}18791880intpeel_ref(const char*refname,unsigned char*sha1)1881{1882int flag;1883unsigned char base[20];18841885if(current_ref && (current_ref->name == refname1886|| !strcmp(current_ref->name, refname))) {1887if(peel_entry(current_ref,0))1888return-1;1889hashcpy(sha1, current_ref->u.value.peeled.hash);1890return0;1891}18921893if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1894return-1;18951896/*1897 * If the reference is packed, read its ref_entry from the1898 * cache in the hope that we already know its peeled value.1899 * We only try this optimization on packed references because1900 * (a) forcing the filling of the loose reference cache could1901 * be expensive and (b) loose references anyway usually do not1902 * have REF_KNOWS_PEELED.1903 */1904if(flag & REF_ISPACKED) {1905struct ref_entry *r =get_packed_ref(refname);1906if(r) {1907if(peel_entry(r,0))1908return-1;1909hashcpy(sha1, r->u.value.peeled.hash);1910return0;1911}1912}19131914returnpeel_object(base, sha1);1915}19161917struct warn_if_dangling_data {1918FILE*fp;1919const char*refname;1920const struct string_list *refnames;1921const char*msg_fmt;1922};19231924static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1925int flags,void*cb_data)1926{1927struct warn_if_dangling_data *d = cb_data;1928const char*resolves_to;1929struct object_id junk;19301931if(!(flags & REF_ISSYMREF))1932return0;19331934 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1935if(!resolves_to1936|| (d->refname1937?strcmp(resolves_to, d->refname)1938: !string_list_has_string(d->refnames, resolves_to))) {1939return0;1940}19411942fprintf(d->fp, d->msg_fmt, refname);1943fputc('\n', d->fp);1944return0;1945}19461947voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1948{1949struct warn_if_dangling_data data;19501951 data.fp = fp;1952 data.refname = refname;1953 data.refnames = NULL;1954 data.msg_fmt = msg_fmt;1955for_each_rawref(warn_if_dangling_symref, &data);1956}19571958voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1959{1960struct warn_if_dangling_data data;19611962 data.fp = fp;1963 data.refname = NULL;1964 data.refnames = refnames;1965 data.msg_fmt = msg_fmt;1966for_each_rawref(warn_if_dangling_symref, &data);1967}19681969/*1970 * Call fn for each reference in the specified ref_cache, omitting1971 * references not in the containing_dir of base. fn is called for all1972 * references, including broken ones. If fn ever returns a non-zero1973 * value, stop the iteration and return that value; otherwise, return1974 * 0.1975 */1976static intdo_for_each_entry(struct ref_cache *refs,const char*base,1977 each_ref_entry_fn fn,void*cb_data)1978{1979struct packed_ref_cache *packed_ref_cache;1980struct ref_dir *loose_dir;1981struct ref_dir *packed_dir;1982int retval =0;19831984/*1985 * We must make sure that all loose refs are read before accessing the1986 * packed-refs file; this avoids a race condition in which loose refs1987 * are migrated to the packed-refs file by a simultaneous process, but1988 * our in-memory view is from before the migration. get_packed_ref_cache()1989 * takes care of making sure our view is up to date with what is on1990 * disk.1991 */1992 loose_dir =get_loose_refs(refs);1993if(base && *base) {1994 loose_dir =find_containing_dir(loose_dir, base,0);1995}1996if(loose_dir)1997prime_ref_dir(loose_dir);19981999 packed_ref_cache =get_packed_ref_cache(refs);2000acquire_packed_ref_cache(packed_ref_cache);2001 packed_dir =get_packed_ref_dir(packed_ref_cache);2002if(base && *base) {2003 packed_dir =find_containing_dir(packed_dir, base,0);2004}20052006if(packed_dir && loose_dir) {2007sort_ref_dir(packed_dir);2008sort_ref_dir(loose_dir);2009 retval =do_for_each_entry_in_dirs(2010 packed_dir, loose_dir, fn, cb_data);2011}else if(packed_dir) {2012sort_ref_dir(packed_dir);2013 retval =do_for_each_entry_in_dir(2014 packed_dir,0, fn, cb_data);2015}else if(loose_dir) {2016sort_ref_dir(loose_dir);2017 retval =do_for_each_entry_in_dir(2018 loose_dir,0, fn, cb_data);2019}20202021release_packed_ref_cache(packed_ref_cache);2022return retval;2023}20242025/*2026 * Call fn for each reference in the specified ref_cache for which the2027 * refname begins with base. If trim is non-zero, then trim that many2028 * characters off the beginning of each refname before passing the2029 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2030 * broken references in the iteration. If fn ever returns a non-zero2031 * value, stop the iteration and return that value; otherwise, return2032 * 0.2033 */2034static intdo_for_each_ref(struct ref_cache *refs,const char*base,2035 each_ref_fn fn,int trim,int flags,void*cb_data)2036{2037struct ref_entry_cb data;2038 data.base = base;2039 data.trim = trim;2040 data.flags = flags;2041 data.fn = fn;2042 data.cb_data = cb_data;20432044if(ref_paranoia <0)2045 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2046if(ref_paranoia)2047 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20482049returndo_for_each_entry(refs, base, do_one_ref, &data);2050}20512052static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2053{2054struct object_id oid;2055int flag;20562057if(submodule) {2058if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2059returnfn("HEAD", &oid,0, cb_data);20602061return0;2062}20632064if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2065returnfn("HEAD", &oid, flag, cb_data);20662067return0;2068}20692070inthead_ref(each_ref_fn fn,void*cb_data)2071{2072returndo_head_ref(NULL, fn, cb_data);2073}20742075inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2076{2077returndo_head_ref(submodule, fn, cb_data);2078}20792080intfor_each_ref(each_ref_fn fn,void*cb_data)2081{2082returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2083}20842085intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2086{2087returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2088}20892090intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2091{2092returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2093}20942095intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2096 each_ref_fn fn,void*cb_data)2097{2098returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2099}21002101intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2102{2103returnfor_each_ref_in("refs/tags/", fn, cb_data);2104}21052106intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2107{2108returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2109}21102111intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2112{2113returnfor_each_ref_in("refs/heads/", fn, cb_data);2114}21152116intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2117{2118returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2119}21202121intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2122{2123returnfor_each_ref_in("refs/remotes/", fn, cb_data);2124}21252126intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2127{2128returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2129}21302131intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2132{2133returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,2134strlen(git_replace_ref_base),0, cb_data);2135}21362137inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2138{2139struct strbuf buf = STRBUF_INIT;2140int ret =0;2141struct object_id oid;2142int flag;21432144strbuf_addf(&buf,"%sHEAD",get_git_namespace());2145if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2146 ret =fn(buf.buf, &oid, flag, cb_data);2147strbuf_release(&buf);21482149return ret;2150}21512152intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2153{2154struct strbuf buf = STRBUF_INIT;2155int ret;2156strbuf_addf(&buf,"%srefs/",get_git_namespace());2157 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2158strbuf_release(&buf);2159return ret;2160}21612162intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2163const char*prefix,void*cb_data)2164{2165struct strbuf real_pattern = STRBUF_INIT;2166struct ref_filter filter;2167int ret;21682169if(!prefix && !starts_with(pattern,"refs/"))2170strbuf_addstr(&real_pattern,"refs/");2171else if(prefix)2172strbuf_addstr(&real_pattern, prefix);2173strbuf_addstr(&real_pattern, pattern);21742175if(!has_glob_specials(pattern)) {2176/* Append implied '/' '*' if not present. */2177if(real_pattern.buf[real_pattern.len -1] !='/')2178strbuf_addch(&real_pattern,'/');2179/* No need to check for '*', there is none. */2180strbuf_addch(&real_pattern,'*');2181}21822183 filter.pattern = real_pattern.buf;2184 filter.fn = fn;2185 filter.cb_data = cb_data;2186 ret =for_each_ref(filter_refs, &filter);21872188strbuf_release(&real_pattern);2189return ret;2190}21912192intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2193{2194returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2195}21962197intfor_each_rawref(each_ref_fn fn,void*cb_data)2198{2199returndo_for_each_ref(&ref_cache,"", fn,0,2200 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2201}22022203const char*prettify_refname(const char*name)2204{2205return name + (2206starts_with(name,"refs/heads/") ?11:2207starts_with(name,"refs/tags/") ?10:2208starts_with(name,"refs/remotes/") ?13:22090);2210}22112212static const char*ref_rev_parse_rules[] = {2213"%.*s",2214"refs/%.*s",2215"refs/tags/%.*s",2216"refs/heads/%.*s",2217"refs/remotes/%.*s",2218"refs/remotes/%.*s/HEAD",2219 NULL2220};22212222intrefname_match(const char*abbrev_name,const char*full_name)2223{2224const char**p;2225const int abbrev_name_len =strlen(abbrev_name);22262227for(p = ref_rev_parse_rules; *p; p++) {2228if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2229return1;2230}2231}22322233return0;2234}22352236static voidunlock_ref(struct ref_lock *lock)2237{2238/* Do not free lock->lk -- atexit() still looks at them */2239if(lock->lk)2240rollback_lock_file(lock->lk);2241free(lock->ref_name);2242free(lock->orig_ref_name);2243free(lock);2244}22452246/*2247 * Verify that the reference locked by lock has the value old_sha1.2248 * Fail if the reference doesn't exist and mustexist is set. Return 02249 * on success. On error, write an error message to err, set errno, and2250 * return a negative value.2251 */2252static intverify_lock(struct ref_lock *lock,2253const unsigned char*old_sha1,int mustexist,2254struct strbuf *err)2255{2256assert(err);22572258if(read_ref_full(lock->ref_name,2259 mustexist ? RESOLVE_REF_READING :0,2260 lock->old_oid.hash, NULL)) {2261int save_errno = errno;2262strbuf_addf(err,"can't verify ref%s", lock->ref_name);2263 errno = save_errno;2264return-1;2265}2266if(hashcmp(lock->old_oid.hash, old_sha1)) {2267strbuf_addf(err,"ref%sis at%sbut expected%s",2268 lock->ref_name,2269sha1_to_hex(lock->old_oid.hash),2270sha1_to_hex(old_sha1));2271 errno = EBUSY;2272return-1;2273}2274return0;2275}22762277static intremove_empty_directories(const char*file)2278{2279/* we want to create a file but there is a directory there;2280 * if that is an empty directory (or a directory that contains2281 * only empty directories), remove them.2282 */2283struct strbuf path;2284int result, save_errno;22852286strbuf_init(&path,20);2287strbuf_addstr(&path, file);22882289 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2290 save_errno = errno;22912292strbuf_release(&path);2293 errno = save_errno;22942295return result;2296}22972298/*2299 * *string and *len will only be substituted, and *string returned (for2300 * later free()ing) if the string passed in is a magic short-hand form2301 * to name a branch.2302 */2303static char*substitute_branch_name(const char**string,int*len)2304{2305struct strbuf buf = STRBUF_INIT;2306int ret =interpret_branch_name(*string, *len, &buf);23072308if(ret == *len) {2309size_t size;2310*string =strbuf_detach(&buf, &size);2311*len = size;2312return(char*)*string;2313}23142315return NULL;2316}23172318intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2319{2320char*last_branch =substitute_branch_name(&str, &len);2321const char**p, *r;2322int refs_found =0;23232324*ref = NULL;2325for(p = ref_rev_parse_rules; *p; p++) {2326char fullref[PATH_MAX];2327unsigned char sha1_from_ref[20];2328unsigned char*this_result;2329int flag;23302331 this_result = refs_found ? sha1_from_ref : sha1;2332mksnpath(fullref,sizeof(fullref), *p, len, str);2333 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2334 this_result, &flag);2335if(r) {2336if(!refs_found++)2337*ref =xstrdup(r);2338if(!warn_ambiguous_refs)2339break;2340}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2341warning("ignoring dangling symref%s.", fullref);2342}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2343warning("ignoring broken ref%s.", fullref);2344}2345}2346free(last_branch);2347return refs_found;2348}23492350intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2351{2352char*last_branch =substitute_branch_name(&str, &len);2353const char**p;2354int logs_found =0;23552356*log = NULL;2357for(p = ref_rev_parse_rules; *p; p++) {2358unsigned char hash[20];2359char path[PATH_MAX];2360const char*ref, *it;23612362mksnpath(path,sizeof(path), *p, len, str);2363 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2364 hash, NULL);2365if(!ref)2366continue;2367if(reflog_exists(path))2368 it = path;2369else if(strcmp(ref, path) &&reflog_exists(ref))2370 it = ref;2371else2372continue;2373if(!logs_found++) {2374*log =xstrdup(it);2375hashcpy(sha1, hash);2376}2377if(!warn_ambiguous_refs)2378break;2379}2380free(last_branch);2381return logs_found;2382}23832384/*2385 * Locks a ref returning the lock on success and NULL on failure.2386 * On failure errno is set to something meaningful.2387 */2388static struct ref_lock *lock_ref_sha1_basic(const char*refname,2389const unsigned char*old_sha1,2390const struct string_list *extras,2391const struct string_list *skip,2392unsigned int flags,int*type_p,2393struct strbuf *err)2394{2395const char*ref_file;2396const char*orig_refname = refname;2397struct ref_lock *lock;2398int last_errno =0;2399int type, lflags;2400int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2401int resolve_flags =0;2402int attempts_remaining =3;24032404assert(err);24052406 lock =xcalloc(1,sizeof(struct ref_lock));24072408if(mustexist)2409 resolve_flags |= RESOLVE_REF_READING;2410if(flags & REF_DELETING) {2411 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2412if(flags & REF_NODEREF)2413 resolve_flags |= RESOLVE_REF_NO_RECURSE;2414}24152416 refname =resolve_ref_unsafe(refname, resolve_flags,2417 lock->old_oid.hash, &type);2418if(!refname && errno == EISDIR) {2419/* we are trying to lock foo but we used to2420 * have foo/bar which now does not exist;2421 * it is normal for the empty directory 'foo'2422 * to remain.2423 */2424 ref_file =git_path("%s", orig_refname);2425if(remove_empty_directories(ref_file)) {2426 last_errno = errno;24272428if(!verify_refname_available(orig_refname, extras, skip,2429get_loose_refs(&ref_cache), err))2430strbuf_addf(err,"there are still refs under '%s'",2431 orig_refname);24322433goto error_return;2434}2435 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2436 lock->old_oid.hash, &type);2437}2438if(type_p)2439*type_p = type;2440if(!refname) {2441 last_errno = errno;2442if(last_errno != ENOTDIR ||2443!verify_refname_available(orig_refname, extras, skip,2444get_loose_refs(&ref_cache), err))2445strbuf_addf(err,"unable to resolve reference%s:%s",2446 orig_refname,strerror(last_errno));24472448goto error_return;2449}2450/*2451 * If the ref did not exist and we are creating it, make sure2452 * there is no existing packed ref whose name begins with our2453 * refname, nor a packed ref whose name is a proper prefix of2454 * our refname.2455 */2456if(is_null_oid(&lock->old_oid) &&2457verify_refname_available(refname, extras, skip,2458get_packed_refs(&ref_cache), err)) {2459 last_errno = ENOTDIR;2460goto error_return;2461}24622463 lock->lk =xcalloc(1,sizeof(struct lock_file));24642465 lflags =0;2466if(flags & REF_NODEREF) {2467 refname = orig_refname;2468 lflags |= LOCK_NO_DEREF;2469}2470 lock->ref_name =xstrdup(refname);2471 lock->orig_ref_name =xstrdup(orig_refname);2472 ref_file =git_path("%s", refname);24732474 retry:2475switch(safe_create_leading_directories_const(ref_file)) {2476case SCLD_OK:2477break;/* success */2478case SCLD_VANISHED:2479if(--attempts_remaining >0)2480goto retry;2481/* fall through */2482default:2483 last_errno = errno;2484strbuf_addf(err,"unable to create directory for%s", ref_file);2485goto error_return;2486}24872488if(hold_lock_file_for_update(lock->lk, ref_file, lflags) <0) {2489 last_errno = errno;2490if(errno == ENOENT && --attempts_remaining >0)2491/*2492 * Maybe somebody just deleted one of the2493 * directories leading to ref_file. Try2494 * again:2495 */2496goto retry;2497else{2498unable_to_lock_message(ref_file, errno, err);2499goto error_return;2500}2501}2502if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2503 last_errno = errno;2504goto error_return;2505}2506return lock;25072508 error_return:2509unlock_ref(lock);2510 errno = last_errno;2511return NULL;2512}25132514/*2515 * Write an entry to the packed-refs file for the specified refname.2516 * If peeled is non-NULL, write it as the entry's peeled value.2517 */2518static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2519unsigned char*peeled)2520{2521fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2522if(peeled)2523fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2524}25252526/*2527 * An each_ref_entry_fn that writes the entry to a packed-refs file.2528 */2529static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2530{2531enum peel_status peel_status =peel_entry(entry,0);25322533if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2534error("internal error:%sis not a valid packed reference!",2535 entry->name);2536write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2537 peel_status == PEEL_PEELED ?2538 entry->u.value.peeled.hash : NULL);2539return0;2540}25412542/*2543 * Lock the packed-refs file for writing. Flags is passed to2544 * hold_lock_file_for_update(). Return 0 on success. On errors, set2545 * errno appropriately and return a nonzero value.2546 */2547static intlock_packed_refs(int flags)2548{2549static int timeout_configured =0;2550static int timeout_value =1000;25512552struct packed_ref_cache *packed_ref_cache;25532554if(!timeout_configured) {2555git_config_get_int("core.packedrefstimeout", &timeout_value);2556 timeout_configured =1;2557}25582559if(hold_lock_file_for_update_timeout(2560&packlock,git_path("packed-refs"),2561 flags, timeout_value) <0)2562return-1;2563/*2564 * Get the current packed-refs while holding the lock. If the2565 * packed-refs file has been modified since we last read it,2566 * this will automatically invalidate the cache and re-read2567 * the packed-refs file.2568 */2569 packed_ref_cache =get_packed_ref_cache(&ref_cache);2570 packed_ref_cache->lock = &packlock;2571/* Increment the reference count to prevent it from being freed: */2572acquire_packed_ref_cache(packed_ref_cache);2573return0;2574}25752576/*2577 * Write the current version of the packed refs cache from memory to2578 * disk. The packed-refs file must already be locked for writing (see2579 * lock_packed_refs()). Return zero on success. On errors, set errno2580 * and return a nonzero value2581 */2582static intcommit_packed_refs(void)2583{2584struct packed_ref_cache *packed_ref_cache =2585get_packed_ref_cache(&ref_cache);2586int error =0;2587int save_errno =0;2588FILE*out;25892590if(!packed_ref_cache->lock)2591die("internal error: packed-refs not locked");25922593 out =fdopen_lock_file(packed_ref_cache->lock,"w");2594if(!out)2595die_errno("unable to fdopen packed-refs descriptor");25962597fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2598do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),25990, write_packed_entry_fn, out);26002601if(commit_lock_file(packed_ref_cache->lock)) {2602 save_errno = errno;2603 error = -1;2604}2605 packed_ref_cache->lock = NULL;2606release_packed_ref_cache(packed_ref_cache);2607 errno = save_errno;2608return error;2609}26102611/*2612 * Rollback the lockfile for the packed-refs file, and discard the2613 * in-memory packed reference cache. (The packed-refs file will be2614 * read anew if it is needed again after this function is called.)2615 */2616static voidrollback_packed_refs(void)2617{2618struct packed_ref_cache *packed_ref_cache =2619get_packed_ref_cache(&ref_cache);26202621if(!packed_ref_cache->lock)2622die("internal error: packed-refs not locked");2623rollback_lock_file(packed_ref_cache->lock);2624 packed_ref_cache->lock = NULL;2625release_packed_ref_cache(packed_ref_cache);2626clear_packed_ref_cache(&ref_cache);2627}26282629struct ref_to_prune {2630struct ref_to_prune *next;2631unsigned char sha1[20];2632char name[FLEX_ARRAY];2633};26342635struct pack_refs_cb_data {2636unsigned int flags;2637struct ref_dir *packed_refs;2638struct ref_to_prune *ref_to_prune;2639};26402641/*2642 * An each_ref_entry_fn that is run over loose references only. If2643 * the loose reference can be packed, add an entry in the packed ref2644 * cache. If the reference should be pruned, also add it to2645 * ref_to_prune in the pack_refs_cb_data.2646 */2647static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2648{2649struct pack_refs_cb_data *cb = cb_data;2650enum peel_status peel_status;2651struct ref_entry *packed_entry;2652int is_tag_ref =starts_with(entry->name,"refs/tags/");26532654/* ALWAYS pack tags */2655if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2656return0;26572658/* Do not pack symbolic or broken refs: */2659if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2660return0;26612662/* Add a packed ref cache entry equivalent to the loose entry. */2663 peel_status =peel_entry(entry,1);2664if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2665die("internal error peeling reference%s(%s)",2666 entry->name,oid_to_hex(&entry->u.value.oid));2667 packed_entry =find_ref(cb->packed_refs, entry->name);2668if(packed_entry) {2669/* Overwrite existing packed entry with info from loose entry */2670 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2671oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2672}else{2673 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2674 REF_ISPACKED | REF_KNOWS_PEELED,0);2675add_ref(cb->packed_refs, packed_entry);2676}2677oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);26782679/* Schedule the loose reference for pruning if requested. */2680if((cb->flags & PACK_REFS_PRUNE)) {2681int namelen =strlen(entry->name) +1;2682struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2683hashcpy(n->sha1, entry->u.value.oid.hash);2684strcpy(n->name, entry->name);2685 n->next = cb->ref_to_prune;2686 cb->ref_to_prune = n;2687}2688return0;2689}26902691/*2692 * Remove empty parents, but spare refs/ and immediate subdirs.2693 * Note: munges *name.2694 */2695static voidtry_remove_empty_parents(char*name)2696{2697char*p, *q;2698int i;2699 p = name;2700for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2701while(*p && *p !='/')2702 p++;2703/* tolerate duplicate slashes; see check_refname_format() */2704while(*p =='/')2705 p++;2706}2707for(q = p; *q; q++)2708;2709while(1) {2710while(q > p && *q !='/')2711 q--;2712while(q > p && *(q-1) =='/')2713 q--;2714if(q == p)2715break;2716*q ='\0';2717if(rmdir(git_path("%s", name)))2718break;2719}2720}27212722/* make sure nobody touched the ref, and unlink */2723static voidprune_ref(struct ref_to_prune *r)2724{2725struct ref_transaction *transaction;2726struct strbuf err = STRBUF_INIT;27272728if(check_refname_format(r->name,0))2729return;27302731 transaction =ref_transaction_begin(&err);2732if(!transaction ||2733ref_transaction_delete(transaction, r->name, r->sha1,2734 REF_ISPRUNING, NULL, &err) ||2735ref_transaction_commit(transaction, &err)) {2736ref_transaction_free(transaction);2737error("%s", err.buf);2738strbuf_release(&err);2739return;2740}2741ref_transaction_free(transaction);2742strbuf_release(&err);2743try_remove_empty_parents(r->name);2744}27452746static voidprune_refs(struct ref_to_prune *r)2747{2748while(r) {2749prune_ref(r);2750 r = r->next;2751}2752}27532754intpack_refs(unsigned int flags)2755{2756struct pack_refs_cb_data cbdata;27572758memset(&cbdata,0,sizeof(cbdata));2759 cbdata.flags = flags;27602761lock_packed_refs(LOCK_DIE_ON_ERROR);2762 cbdata.packed_refs =get_packed_refs(&ref_cache);27632764do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2765 pack_if_possible_fn, &cbdata);27662767if(commit_packed_refs())2768die_errno("unable to overwrite old ref-pack file");27692770prune_refs(cbdata.ref_to_prune);2771return0;2772}27732774/*2775 * Rewrite the packed-refs file, omitting any refs listed in2776 * 'refnames'. On error, leave packed-refs unchanged, write an error2777 * message to 'err', and return a nonzero value.2778 *2779 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2780 */2781static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2782{2783struct ref_dir *packed;2784struct string_list_item *refname;2785int ret, needs_repacking =0, removed =0;27862787assert(err);27882789/* Look for a packed ref */2790for_each_string_list_item(refname, refnames) {2791if(get_packed_ref(refname->string)) {2792 needs_repacking =1;2793break;2794}2795}27962797/* Avoid locking if we have nothing to do */2798if(!needs_repacking)2799return0;/* no refname exists in packed refs */28002801if(lock_packed_refs(0)) {2802unable_to_lock_message(git_path("packed-refs"), errno, err);2803return-1;2804}2805 packed =get_packed_refs(&ref_cache);28062807/* Remove refnames from the cache */2808for_each_string_list_item(refname, refnames)2809if(remove_entry(packed, refname->string) != -1)2810 removed =1;2811if(!removed) {2812/*2813 * All packed entries disappeared while we were2814 * acquiring the lock.2815 */2816rollback_packed_refs();2817return0;2818}28192820/* Write what remains */2821 ret =commit_packed_refs();2822if(ret)2823strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2824strerror(errno));2825return ret;2826}28272828static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2829{2830assert(err);28312832if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2833/*2834 * loose. The loose file name is the same as the2835 * lockfile name, minus ".lock":2836 */2837char*loose_filename =get_locked_file_path(lock->lk);2838int res =unlink_or_msg(loose_filename, err);2839free(loose_filename);2840if(res)2841return1;2842}2843return0;2844}28452846intdelete_ref(const char*refname,const unsigned char*old_sha1,2847unsigned int flags)2848{2849struct ref_transaction *transaction;2850struct strbuf err = STRBUF_INIT;28512852 transaction =ref_transaction_begin(&err);2853if(!transaction ||2854ref_transaction_delete(transaction, refname, old_sha1,2855 flags, NULL, &err) ||2856ref_transaction_commit(transaction, &err)) {2857error("%s", err.buf);2858ref_transaction_free(transaction);2859strbuf_release(&err);2860return1;2861}2862ref_transaction_free(transaction);2863strbuf_release(&err);2864return0;2865}28662867intdelete_refs(struct string_list *refnames)2868{2869struct strbuf err = STRBUF_INIT;2870int i, result =0;28712872if(!refnames->nr)2873return0;28742875 result =repack_without_refs(refnames, &err);2876if(result) {2877/*2878 * If we failed to rewrite the packed-refs file, then2879 * it is unsafe to try to remove loose refs, because2880 * doing so might expose an obsolete packed value for2881 * a reference that might even point at an object that2882 * has been garbage collected.2883 */2884if(refnames->nr ==1)2885error(_("could not delete reference%s:%s"),2886 refnames->items[0].string, err.buf);2887else2888error(_("could not delete references:%s"), err.buf);28892890goto out;2891}28922893for(i =0; i < refnames->nr; i++) {2894const char*refname = refnames->items[i].string;28952896if(delete_ref(refname, NULL,0))2897 result |=error(_("could not remove reference%s"), refname);2898}28992900out:2901strbuf_release(&err);2902return result;2903}29042905/*2906 * People using contrib's git-new-workdir have .git/logs/refs ->2907 * /some/other/path/.git/logs/refs, and that may live on another device.2908 *2909 * IOW, to avoid cross device rename errors, the temporary renamed log must2910 * live into logs/refs.2911 */2912#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"29132914static intrename_tmp_log(const char*newrefname)2915{2916int attempts_remaining =4;29172918 retry:2919switch(safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {2920case SCLD_OK:2921break;/* success */2922case SCLD_VANISHED:2923if(--attempts_remaining >0)2924goto retry;2925/* fall through */2926default:2927error("unable to create directory for%s", newrefname);2928return-1;2929}29302931if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2932if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2933/*2934 * rename(a, b) when b is an existing2935 * directory ought to result in ISDIR, but2936 * Solaris 5.8 gives ENOTDIR. Sheesh.2937 */2938if(remove_empty_directories(git_path("logs/%s", newrefname))) {2939error("Directory not empty: logs/%s", newrefname);2940return-1;2941}2942goto retry;2943}else if(errno == ENOENT && --attempts_remaining >0) {2944/*2945 * Maybe another process just deleted one of2946 * the directories in the path to newrefname.2947 * Try again from the beginning.2948 */2949goto retry;2950}else{2951error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2952 newrefname,strerror(errno));2953return-1;2954}2955}2956return0;2957}29582959static intrename_ref_available(const char*oldname,const char*newname)2960{2961struct string_list skip = STRING_LIST_INIT_NODUP;2962struct strbuf err = STRBUF_INIT;2963int ret;29642965string_list_insert(&skip, oldname);2966 ret = !verify_refname_available(newname, NULL, &skip,2967get_packed_refs(&ref_cache), &err)2968&& !verify_refname_available(newname, NULL, &skip,2969get_loose_refs(&ref_cache), &err);2970if(!ret)2971error("%s", err.buf);29722973string_list_clear(&skip,0);2974strbuf_release(&err);2975return ret;2976}29772978static intwrite_ref_to_lockfile(struct ref_lock *lock,const unsigned char*sha1);2979static intcommit_ref_update(struct ref_lock *lock,2980const unsigned char*sha1,const char*logmsg);29812982intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2983{2984unsigned char sha1[20], orig_sha1[20];2985int flag =0, logmoved =0;2986struct ref_lock *lock;2987struct stat loginfo;2988int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2989const char*symref = NULL;2990struct strbuf err = STRBUF_INIT;29912992if(log &&S_ISLNK(loginfo.st_mode))2993returnerror("reflog for%sis a symlink", oldrefname);29942995 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2996 orig_sha1, &flag);2997if(flag & REF_ISSYMREF)2998returnerror("refname%sis a symbolic ref, renaming it is not supported",2999 oldrefname);3000if(!symref)3001returnerror("refname%snot found", oldrefname);30023003if(!rename_ref_available(oldrefname, newrefname))3004return1;30053006if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3007returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3008 oldrefname,strerror(errno));30093010if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3011error("unable to delete old%s", oldrefname);3012goto rollback;3013}30143015if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3016delete_ref(newrefname, sha1, REF_NODEREF)) {3017if(errno==EISDIR) {3018if(remove_empty_directories(git_path("%s", newrefname))) {3019error("Directory not empty:%s", newrefname);3020goto rollback;3021}3022}else{3023error("unable to delete existing%s", newrefname);3024goto rollback;3025}3026}30273028if(log &&rename_tmp_log(newrefname))3029goto rollback;30303031 logmoved = log;30323033 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3034if(!lock) {3035error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3036strbuf_release(&err);3037goto rollback;3038}3039hashcpy(lock->old_oid.hash, orig_sha1);30403041if(write_ref_to_lockfile(lock, orig_sha1) ||3042commit_ref_update(lock, orig_sha1, logmsg)) {3043error("unable to write current sha1 into%s", newrefname);3044goto rollback;3045}30463047return0;30483049 rollback:3050 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3051if(!lock) {3052error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3053strbuf_release(&err);3054goto rollbacklog;3055}30563057 flag = log_all_ref_updates;3058 log_all_ref_updates =0;3059if(write_ref_to_lockfile(lock, orig_sha1) ||3060commit_ref_update(lock, orig_sha1, NULL))3061error("unable to write current sha1 into%s", oldrefname);3062 log_all_ref_updates = flag;30633064 rollbacklog:3065if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3066error("unable to restore logfile%sfrom%s:%s",3067 oldrefname, newrefname,strerror(errno));3068if(!logmoved && log &&3069rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3070error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3071 oldrefname,strerror(errno));30723073return1;3074}30753076static intclose_ref(struct ref_lock *lock)3077{3078if(close_lock_file(lock->lk))3079return-1;3080return0;3081}30823083static intcommit_ref(struct ref_lock *lock)3084{3085if(commit_lock_file(lock->lk))3086return-1;3087return0;3088}30893090/*3091 * copy the reflog message msg to buf, which has been allocated sufficiently3092 * large, while cleaning up the whitespaces. Especially, convert LF to space,3093 * because reflog file is one line per entry.3094 */3095static intcopy_msg(char*buf,const char*msg)3096{3097char*cp = buf;3098char c;3099int wasspace =1;31003101*cp++ ='\t';3102while((c = *msg++)) {3103if(wasspace &&isspace(c))3104continue;3105 wasspace =isspace(c);3106if(wasspace)3107 c =' ';3108*cp++ = c;3109}3110while(buf < cp &&isspace(cp[-1]))3111 cp--;3112*cp++ ='\n';3113return cp - buf;3114}31153116/* This function must set a meaningful errno on failure */3117intlog_ref_setup(const char*refname,struct strbuf *sb_logfile)3118{3119int logfd, oflags = O_APPEND | O_WRONLY;3120char*logfile;31213122strbuf_git_path(sb_logfile,"logs/%s", refname);3123 logfile = sb_logfile->buf;3124/* make sure the rest of the function can't change "logfile" */3125 sb_logfile = NULL;3126if(log_all_ref_updates &&3127(starts_with(refname,"refs/heads/") ||3128starts_with(refname,"refs/remotes/") ||3129starts_with(refname,"refs/notes/") ||3130!strcmp(refname,"HEAD"))) {3131if(safe_create_leading_directories(logfile) <0) {3132int save_errno = errno;3133error("unable to create directory for%s", logfile);3134 errno = save_errno;3135return-1;3136}3137 oflags |= O_CREAT;3138}31393140 logfd =open(logfile, oflags,0666);3141if(logfd <0) {3142if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3143return0;31443145if(errno == EISDIR) {3146if(remove_empty_directories(logfile)) {3147int save_errno = errno;3148error("There are still logs under '%s'",3149 logfile);3150 errno = save_errno;3151return-1;3152}3153 logfd =open(logfile, oflags,0666);3154}31553156if(logfd <0) {3157int save_errno = errno;3158error("Unable to append to%s:%s", logfile,3159strerror(errno));3160 errno = save_errno;3161return-1;3162}3163}31643165adjust_shared_perm(logfile);3166close(logfd);3167return0;3168}31693170static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3171const unsigned char*new_sha1,3172const char*committer,const char*msg)3173{3174int msglen, written;3175unsigned maxlen, len;3176char*logrec;31773178 msglen = msg ?strlen(msg) :0;3179 maxlen =strlen(committer) + msglen +100;3180 logrec =xmalloc(maxlen);3181 len =sprintf(logrec,"%s %s %s\n",3182sha1_to_hex(old_sha1),3183sha1_to_hex(new_sha1),3184 committer);3185if(msglen)3186 len +=copy_msg(logrec + len -1, msg) -1;31873188 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3189free(logrec);3190if(written != len)3191return-1;31923193return0;3194}31953196static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3197const unsigned char*new_sha1,const char*msg,3198struct strbuf *sb_log_file)3199{3200int logfd, result, oflags = O_APPEND | O_WRONLY;3201char*log_file;32023203if(log_all_ref_updates <0)3204 log_all_ref_updates = !is_bare_repository();32053206 result =log_ref_setup(refname, sb_log_file);3207if(result)3208return result;3209 log_file = sb_log_file->buf;3210/* make sure the rest of the function can't change "log_file" */3211 sb_log_file = NULL;32123213 logfd =open(log_file, oflags);3214if(logfd <0)3215return0;3216 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3217git_committer_info(0), msg);3218if(result) {3219int save_errno = errno;3220close(logfd);3221error("Unable to append to%s", log_file);3222 errno = save_errno;3223return-1;3224}3225if(close(logfd)) {3226int save_errno = errno;3227error("Unable to append to%s", log_file);3228 errno = save_errno;3229return-1;3230}3231return0;3232}32333234static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3235const unsigned char*new_sha1,const char*msg)3236{3237struct strbuf sb = STRBUF_INIT;3238int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb);3239strbuf_release(&sb);3240return ret;3241}32423243intis_branch(const char*refname)3244{3245return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3246}32473248/*3249 * Write sha1 into the open lockfile, then close the lockfile. On3250 * errors, rollback the lockfile and set errno to reflect the problem.3251 */3252static intwrite_ref_to_lockfile(struct ref_lock *lock,3253const unsigned char*sha1)3254{3255static char term ='\n';3256struct object *o;32573258 o =parse_object(sha1);3259if(!o) {3260error("Trying to write ref%swith nonexistent object%s",3261 lock->ref_name,sha1_to_hex(sha1));3262unlock_ref(lock);3263 errno = EINVAL;3264return-1;3265}3266if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3267error("Trying to write non-commit object%sto branch%s",3268sha1_to_hex(sha1), lock->ref_name);3269unlock_ref(lock);3270 errno = EINVAL;3271return-1;3272}3273if(write_in_full(lock->lk->fd,sha1_to_hex(sha1),40) !=40||3274write_in_full(lock->lk->fd, &term,1) !=1||3275close_ref(lock) <0) {3276int save_errno = errno;3277error("Couldn't write%s", lock->lk->filename.buf);3278unlock_ref(lock);3279 errno = save_errno;3280return-1;3281}3282return0;3283}32843285/*3286 * Commit a change to a loose reference that has already been written3287 * to the loose reference lockfile. Also update the reflogs if3288 * necessary, using the specified lockmsg (which can be NULL).3289 */3290static intcommit_ref_update(struct ref_lock *lock,3291const unsigned char*sha1,const char*logmsg)3292{3293clear_loose_ref_cache(&ref_cache);3294if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg) <0||3295(strcmp(lock->ref_name, lock->orig_ref_name) &&3296log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg) <0)) {3297unlock_ref(lock);3298return-1;3299}3300if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3301/*3302 * Special hack: If a branch is updated directly and HEAD3303 * points to it (may happen on the remote side of a push3304 * for example) then logically the HEAD reflog should be3305 * updated too.3306 * A generic solution implies reverse symref information,3307 * but finding all symrefs pointing to the given branch3308 * would be rather costly for this rare event (the direct3309 * update of a branch) to be worth it. So let's cheat and3310 * check with HEAD only which should cover 99% of all usage3311 * scenarios (even 100% of the default ones).3312 */3313unsigned char head_sha1[20];3314int head_flag;3315const char*head_ref;3316 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3317 head_sha1, &head_flag);3318if(head_ref && (head_flag & REF_ISSYMREF) &&3319!strcmp(head_ref, lock->ref_name))3320log_ref_write("HEAD", lock->old_oid.hash, sha1, logmsg);3321}3322if(commit_ref(lock)) {3323error("Couldn't set%s", lock->ref_name);3324unlock_ref(lock);3325return-1;3326}3327unlock_ref(lock);3328return0;3329}33303331intcreate_symref(const char*ref_target,const char*refs_heads_master,3332const char*logmsg)3333{3334const char*lockpath;3335char ref[1000];3336int fd, len, written;3337char*git_HEAD =git_pathdup("%s", ref_target);3338unsigned char old_sha1[20], new_sha1[20];33393340if(logmsg &&read_ref(ref_target, old_sha1))3341hashclr(old_sha1);33423343if(safe_create_leading_directories(git_HEAD) <0)3344returnerror("unable to create directory for%s", git_HEAD);33453346#ifndef NO_SYMLINK_HEAD3347if(prefer_symlink_refs) {3348unlink(git_HEAD);3349if(!symlink(refs_heads_master, git_HEAD))3350goto done;3351fprintf(stderr,"no symlink - falling back to symbolic ref\n");3352}3353#endif33543355 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3356if(sizeof(ref) <= len) {3357error("refname too long:%s", refs_heads_master);3358goto error_free_return;3359}3360 lockpath =mkpath("%s.lock", git_HEAD);3361 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3362if(fd <0) {3363error("Unable to open%sfor writing", lockpath);3364goto error_free_return;3365}3366 written =write_in_full(fd, ref, len);3367if(close(fd) !=0|| written != len) {3368error("Unable to write to%s", lockpath);3369goto error_unlink_return;3370}3371if(rename(lockpath, git_HEAD) <0) {3372error("Unable to create%s", git_HEAD);3373goto error_unlink_return;3374}3375if(adjust_shared_perm(git_HEAD)) {3376error("Unable to fix permissions on%s", lockpath);3377 error_unlink_return:3378unlink_or_warn(lockpath);3379 error_free_return:3380free(git_HEAD);3381return-1;3382}33833384#ifndef NO_SYMLINK_HEAD3385 done:3386#endif3387if(logmsg && !read_ref(refs_heads_master, new_sha1))3388log_ref_write(ref_target, old_sha1, new_sha1, logmsg);33893390free(git_HEAD);3391return0;3392}33933394struct read_ref_at_cb {3395const char*refname;3396unsigned long at_time;3397int cnt;3398int reccnt;3399unsigned char*sha1;3400int found_it;34013402unsigned char osha1[20];3403unsigned char nsha1[20];3404int tz;3405unsigned long date;3406char**msg;3407unsigned long*cutoff_time;3408int*cutoff_tz;3409int*cutoff_cnt;3410};34113412static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3413const char*email,unsigned long timestamp,int tz,3414const char*message,void*cb_data)3415{3416struct read_ref_at_cb *cb = cb_data;34173418 cb->reccnt++;3419 cb->tz = tz;3420 cb->date = timestamp;34213422if(timestamp <= cb->at_time || cb->cnt ==0) {3423if(cb->msg)3424*cb->msg =xstrdup(message);3425if(cb->cutoff_time)3426*cb->cutoff_time = timestamp;3427if(cb->cutoff_tz)3428*cb->cutoff_tz = tz;3429if(cb->cutoff_cnt)3430*cb->cutoff_cnt = cb->reccnt -1;3431/*3432 * we have not yet updated cb->[n|o]sha1 so they still3433 * hold the values for the previous record.3434 */3435if(!is_null_sha1(cb->osha1)) {3436hashcpy(cb->sha1, nsha1);3437if(hashcmp(cb->osha1, nsha1))3438warning("Log for ref%shas gap after%s.",3439 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3440}3441else if(cb->date == cb->at_time)3442hashcpy(cb->sha1, nsha1);3443else if(hashcmp(nsha1, cb->sha1))3444warning("Log for ref%sunexpectedly ended on%s.",3445 cb->refname,show_date(cb->date, cb->tz,3446DATE_MODE(RFC2822)));3447hashcpy(cb->osha1, osha1);3448hashcpy(cb->nsha1, nsha1);3449 cb->found_it =1;3450return1;3451}3452hashcpy(cb->osha1, osha1);3453hashcpy(cb->nsha1, nsha1);3454if(cb->cnt >0)3455 cb->cnt--;3456return0;3457}34583459static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3460const char*email,unsigned long timestamp,3461int tz,const char*message,void*cb_data)3462{3463struct read_ref_at_cb *cb = cb_data;34643465if(cb->msg)3466*cb->msg =xstrdup(message);3467if(cb->cutoff_time)3468*cb->cutoff_time = timestamp;3469if(cb->cutoff_tz)3470*cb->cutoff_tz = tz;3471if(cb->cutoff_cnt)3472*cb->cutoff_cnt = cb->reccnt;3473hashcpy(cb->sha1, osha1);3474if(is_null_sha1(cb->sha1))3475hashcpy(cb->sha1, nsha1);3476/* We just want the first entry */3477return1;3478}34793480intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3481unsigned char*sha1,char**msg,3482unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3483{3484struct read_ref_at_cb cb;34853486memset(&cb,0,sizeof(cb));3487 cb.refname = refname;3488 cb.at_time = at_time;3489 cb.cnt = cnt;3490 cb.msg = msg;3491 cb.cutoff_time = cutoff_time;3492 cb.cutoff_tz = cutoff_tz;3493 cb.cutoff_cnt = cutoff_cnt;3494 cb.sha1 = sha1;34953496for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);34973498if(!cb.reccnt) {3499if(flags & GET_SHA1_QUIETLY)3500exit(128);3501else3502die("Log for%sis empty.", refname);3503}3504if(cb.found_it)3505return0;35063507for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);35083509return1;3510}35113512intreflog_exists(const char*refname)3513{3514struct stat st;35153516return!lstat(git_path("logs/%s", refname), &st) &&3517S_ISREG(st.st_mode);3518}35193520intdelete_reflog(const char*refname)3521{3522returnremove_path(git_path("logs/%s", refname));3523}35243525static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3526{3527unsigned char osha1[20], nsha1[20];3528char*email_end, *message;3529unsigned long timestamp;3530int tz;35313532/* old SP new SP name <email> SP time TAB msg LF */3533if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3534get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3535get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3536!(email_end =strchr(sb->buf +82,'>')) ||3537 email_end[1] !=' '||3538!(timestamp =strtoul(email_end +2, &message,10)) ||3539!message || message[0] !=' '||3540(message[1] !='+'&& message[1] !='-') ||3541!isdigit(message[2]) || !isdigit(message[3]) ||3542!isdigit(message[4]) || !isdigit(message[5]))3543return0;/* corrupt? */3544 email_end[1] ='\0';3545 tz =strtol(message +1, NULL,10);3546if(message[6] !='\t')3547 message +=6;3548else3549 message +=7;3550returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3551}35523553static char*find_beginning_of_line(char*bob,char*scan)3554{3555while(bob < scan && *(--scan) !='\n')3556;/* keep scanning backwards */3557/*3558 * Return either beginning of the buffer, or LF at the end of3559 * the previous line.3560 */3561return scan;3562}35633564intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3565{3566struct strbuf sb = STRBUF_INIT;3567FILE*logfp;3568long pos;3569int ret =0, at_tail =1;35703571 logfp =fopen(git_path("logs/%s", refname),"r");3572if(!logfp)3573return-1;35743575/* Jump to the end */3576if(fseek(logfp,0, SEEK_END) <0)3577returnerror("cannot seek back reflog for%s:%s",3578 refname,strerror(errno));3579 pos =ftell(logfp);3580while(!ret &&0< pos) {3581int cnt;3582size_t nread;3583char buf[BUFSIZ];3584char*endp, *scanp;35853586/* Fill next block from the end */3587 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3588if(fseek(logfp, pos - cnt, SEEK_SET))3589returnerror("cannot seek back reflog for%s:%s",3590 refname,strerror(errno));3591 nread =fread(buf, cnt,1, logfp);3592if(nread !=1)3593returnerror("cannot read%dbytes from reflog for%s:%s",3594 cnt, refname,strerror(errno));3595 pos -= cnt;35963597 scanp = endp = buf + cnt;3598if(at_tail && scanp[-1] =='\n')3599/* Looking at the final LF at the end of the file */3600 scanp--;3601 at_tail =0;36023603while(buf < scanp) {3604/*3605 * terminating LF of the previous line, or the beginning3606 * of the buffer.3607 */3608char*bp;36093610 bp =find_beginning_of_line(buf, scanp);36113612if(*bp =='\n') {3613/*3614 * The newline is the end of the previous line,3615 * so we know we have complete line starting3616 * at (bp + 1). Prefix it onto any prior data3617 * we collected for the line and process it.3618 */3619strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3620 scanp = bp;3621 endp = bp +1;3622 ret =show_one_reflog_ent(&sb, fn, cb_data);3623strbuf_reset(&sb);3624if(ret)3625break;3626}else if(!pos) {3627/*3628 * We are at the start of the buffer, and the3629 * start of the file; there is no previous3630 * line, and we have everything for this one.3631 * Process it, and we can end the loop.3632 */3633strbuf_splice(&sb,0,0, buf, endp - buf);3634 ret =show_one_reflog_ent(&sb, fn, cb_data);3635strbuf_reset(&sb);3636break;3637}36383639if(bp == buf) {3640/*3641 * We are at the start of the buffer, and there3642 * is more file to read backwards. Which means3643 * we are in the middle of a line. Note that we3644 * may get here even if *bp was a newline; that3645 * just means we are at the exact end of the3646 * previous line, rather than some spot in the3647 * middle.3648 *3649 * Save away what we have to be combined with3650 * the data from the next read.3651 */3652strbuf_splice(&sb,0,0, buf, endp - buf);3653break;3654}3655}36563657}3658if(!ret && sb.len)3659die("BUG: reverse reflog parser had leftover data");36603661fclose(logfp);3662strbuf_release(&sb);3663return ret;3664}36653666intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3667{3668FILE*logfp;3669struct strbuf sb = STRBUF_INIT;3670int ret =0;36713672 logfp =fopen(git_path("logs/%s", refname),"r");3673if(!logfp)3674return-1;36753676while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3677 ret =show_one_reflog_ent(&sb, fn, cb_data);3678fclose(logfp);3679strbuf_release(&sb);3680return ret;3681}3682/*3683 * Call fn for each reflog in the namespace indicated by name. name3684 * must be empty or end with '/'. Name will be used as a scratch3685 * space, but its contents will be restored before return.3686 */3687static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3688{3689DIR*d =opendir(git_path("logs/%s", name->buf));3690int retval =0;3691struct dirent *de;3692int oldlen = name->len;36933694if(!d)3695return name->len ? errno :0;36963697while((de =readdir(d)) != NULL) {3698struct stat st;36993700if(de->d_name[0] =='.')3701continue;3702if(ends_with(de->d_name,".lock"))3703continue;3704strbuf_addstr(name, de->d_name);3705if(stat(git_path("logs/%s", name->buf), &st) <0) {3706;/* silently ignore */3707}else{3708if(S_ISDIR(st.st_mode)) {3709strbuf_addch(name,'/');3710 retval =do_for_each_reflog(name, fn, cb_data);3711}else{3712struct object_id oid;37133714if(read_ref_full(name->buf,0, oid.hash, NULL))3715 retval =error("bad ref for%s", name->buf);3716else3717 retval =fn(name->buf, &oid,0, cb_data);3718}3719if(retval)3720break;3721}3722strbuf_setlen(name, oldlen);3723}3724closedir(d);3725return retval;3726}37273728intfor_each_reflog(each_ref_fn fn,void*cb_data)3729{3730int retval;3731struct strbuf name;3732strbuf_init(&name, PATH_MAX);3733 retval =do_for_each_reflog(&name, fn, cb_data);3734strbuf_release(&name);3735return retval;3736}37373738/**3739 * Information needed for a single ref update. Set new_sha1 to the new3740 * value or to null_sha1 to delete the ref. To check the old value3741 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3742 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3743 * not exist before update.3744 */3745struct ref_update {3746/*3747 * If (flags & REF_HAVE_NEW), set the reference to this value:3748 */3749unsigned char new_sha1[20];3750/*3751 * If (flags & REF_HAVE_OLD), check that the reference3752 * previously had this value:3753 */3754unsigned char old_sha1[20];3755/*3756 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3757 * REF_DELETING, and REF_ISPRUNING:3758 */3759unsigned int flags;3760struct ref_lock *lock;3761int type;3762char*msg;3763const char refname[FLEX_ARRAY];3764};37653766/*3767 * Transaction states.3768 * OPEN: The transaction is in a valid state and can accept new updates.3769 * An OPEN transaction can be committed.3770 * CLOSED: A closed transaction is no longer active and no other operations3771 * than free can be used on it in this state.3772 * A transaction can either become closed by successfully committing3773 * an active transaction or if there is a failure while building3774 * the transaction thus rendering it failed/inactive.3775 */3776enum ref_transaction_state {3777 REF_TRANSACTION_OPEN =0,3778 REF_TRANSACTION_CLOSED =13779};37803781/*3782 * Data structure for holding a reference transaction, which can3783 * consist of checks and updates to multiple references, carried out3784 * as atomically as possible. This structure is opaque to callers.3785 */3786struct ref_transaction {3787struct ref_update **updates;3788size_t alloc;3789size_t nr;3790enum ref_transaction_state state;3791};37923793struct ref_transaction *ref_transaction_begin(struct strbuf *err)3794{3795assert(err);37963797returnxcalloc(1,sizeof(struct ref_transaction));3798}37993800voidref_transaction_free(struct ref_transaction *transaction)3801{3802int i;38033804if(!transaction)3805return;38063807for(i =0; i < transaction->nr; i++) {3808free(transaction->updates[i]->msg);3809free(transaction->updates[i]);3810}3811free(transaction->updates);3812free(transaction);3813}38143815static struct ref_update *add_update(struct ref_transaction *transaction,3816const char*refname)3817{3818size_t len =strlen(refname);3819struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);38203821strcpy((char*)update->refname, refname);3822ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3823 transaction->updates[transaction->nr++] = update;3824return update;3825}38263827intref_transaction_update(struct ref_transaction *transaction,3828const char*refname,3829const unsigned char*new_sha1,3830const unsigned char*old_sha1,3831unsigned int flags,const char*msg,3832struct strbuf *err)3833{3834struct ref_update *update;38353836assert(err);38373838if(transaction->state != REF_TRANSACTION_OPEN)3839die("BUG: update called for transaction that is not open");38403841if(new_sha1 && !is_null_sha1(new_sha1) &&3842check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3843strbuf_addf(err,"refusing to update ref with bad name%s",3844 refname);3845return-1;3846}38473848 update =add_update(transaction, refname);3849if(new_sha1) {3850hashcpy(update->new_sha1, new_sha1);3851 flags |= REF_HAVE_NEW;3852}3853if(old_sha1) {3854hashcpy(update->old_sha1, old_sha1);3855 flags |= REF_HAVE_OLD;3856}3857 update->flags = flags;3858if(msg)3859 update->msg =xstrdup(msg);3860return0;3861}38623863intref_transaction_create(struct ref_transaction *transaction,3864const char*refname,3865const unsigned char*new_sha1,3866unsigned int flags,const char*msg,3867struct strbuf *err)3868{3869if(!new_sha1 ||is_null_sha1(new_sha1))3870die("BUG: create called without valid new_sha1");3871returnref_transaction_update(transaction, refname, new_sha1,3872 null_sha1, flags, msg, err);3873}38743875intref_transaction_delete(struct ref_transaction *transaction,3876const char*refname,3877const unsigned char*old_sha1,3878unsigned int flags,const char*msg,3879struct strbuf *err)3880{3881if(old_sha1 &&is_null_sha1(old_sha1))3882die("BUG: delete called with old_sha1 set to zeros");3883returnref_transaction_update(transaction, refname,3884 null_sha1, old_sha1,3885 flags, msg, err);3886}38873888intref_transaction_verify(struct ref_transaction *transaction,3889const char*refname,3890const unsigned char*old_sha1,3891unsigned int flags,3892struct strbuf *err)3893{3894if(!old_sha1)3895die("BUG: verify called with old_sha1 set to NULL");3896returnref_transaction_update(transaction, refname,3897 NULL, old_sha1,3898 flags, NULL, err);3899}39003901intupdate_ref(const char*msg,const char*refname,3902const unsigned char*new_sha1,const unsigned char*old_sha1,3903unsigned int flags,enum action_on_err onerr)3904{3905struct ref_transaction *t;3906struct strbuf err = STRBUF_INIT;39073908 t =ref_transaction_begin(&err);3909if(!t ||3910ref_transaction_update(t, refname, new_sha1, old_sha1,3911 flags, msg, &err) ||3912ref_transaction_commit(t, &err)) {3913const char*str ="update_ref failed for ref '%s':%s";39143915ref_transaction_free(t);3916switch(onerr) {3917case UPDATE_REFS_MSG_ON_ERR:3918error(str, refname, err.buf);3919break;3920case UPDATE_REFS_DIE_ON_ERR:3921die(str, refname, err.buf);3922break;3923case UPDATE_REFS_QUIET_ON_ERR:3924break;3925}3926strbuf_release(&err);3927return1;3928}3929strbuf_release(&err);3930ref_transaction_free(t);3931return0;3932}39333934static intref_update_reject_duplicates(struct string_list *refnames,3935struct strbuf *err)3936{3937int i, n = refnames->nr;39383939assert(err);39403941for(i =1; i < n; i++)3942if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3943strbuf_addf(err,3944"Multiple updates for ref '%s' not allowed.",3945 refnames->items[i].string);3946return1;3947}3948return0;3949}39503951intref_transaction_commit(struct ref_transaction *transaction,3952struct strbuf *err)3953{3954int ret =0, i;3955int n = transaction->nr;3956struct ref_update **updates = transaction->updates;3957struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3958struct string_list_item *ref_to_delete;3959struct string_list affected_refnames = STRING_LIST_INIT_NODUP;39603961assert(err);39623963if(transaction->state != REF_TRANSACTION_OPEN)3964die("BUG: commit called for transaction that is not open");39653966if(!n) {3967 transaction->state = REF_TRANSACTION_CLOSED;3968return0;3969}39703971/* Fail if a refname appears more than once in the transaction: */3972for(i =0; i < n; i++)3973string_list_append(&affected_refnames, updates[i]->refname);3974string_list_sort(&affected_refnames);3975if(ref_update_reject_duplicates(&affected_refnames, err)) {3976 ret = TRANSACTION_GENERIC_ERROR;3977goto cleanup;3978}39793980/*3981 * Acquire all locks, verify old values if provided, check3982 * that new values are valid, and write new values to the3983 * lockfiles, ready to be activated. Only keep one lockfile3984 * open at a time to avoid running out of file descriptors.3985 */3986for(i =0; i < n; i++) {3987struct ref_update *update = updates[i];39883989if((update->flags & REF_HAVE_NEW) &&3990is_null_sha1(update->new_sha1))3991 update->flags |= REF_DELETING;3992 update->lock =lock_ref_sha1_basic(3993 update->refname,3994((update->flags & REF_HAVE_OLD) ?3995 update->old_sha1 : NULL),3996&affected_refnames, NULL,3997 update->flags,3998&update->type,3999 err);4000if(!update->lock) {4001char*reason;40024003 ret = (errno == ENOTDIR)4004? TRANSACTION_NAME_CONFLICT4005: TRANSACTION_GENERIC_ERROR;4006 reason =strbuf_detach(err, NULL);4007strbuf_addf(err,"cannot lock ref '%s':%s",4008 update->refname, reason);4009free(reason);4010goto cleanup;4011}4012if((update->flags & REF_HAVE_NEW) &&4013!(update->flags & REF_DELETING)) {4014int overwriting_symref = ((update->type & REF_ISSYMREF) &&4015(update->flags & REF_NODEREF));40164017if(!overwriting_symref &&4018!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4019/*4020 * The reference already has the desired4021 * value, so we don't need to write it.4022 */4023}else if(write_ref_to_lockfile(update->lock,4024 update->new_sha1)) {4025/*4026 * The lock was freed upon failure of4027 * write_ref_to_lockfile():4028 */4029 update->lock = NULL;4030strbuf_addf(err,"cannot update the ref '%s'.",4031 update->refname);4032 ret = TRANSACTION_GENERIC_ERROR;4033goto cleanup;4034}else{4035 update->flags |= REF_NEEDS_COMMIT;4036}4037}4038if(!(update->flags & REF_NEEDS_COMMIT)) {4039/*4040 * We didn't have to write anything to the lockfile.4041 * Close it to free up the file descriptor:4042 */4043if(close_ref(update->lock)) {4044strbuf_addf(err,"Couldn't close%s.lock",4045 update->refname);4046goto cleanup;4047}4048}4049}40504051/* Perform updates first so live commits remain referenced */4052for(i =0; i < n; i++) {4053struct ref_update *update = updates[i];40544055if(update->flags & REF_NEEDS_COMMIT) {4056if(commit_ref_update(update->lock,4057 update->new_sha1, update->msg)) {4058/* freed by commit_ref_update(): */4059 update->lock = NULL;4060strbuf_addf(err,"Cannot update the ref '%s'.",4061 update->refname);4062 ret = TRANSACTION_GENERIC_ERROR;4063goto cleanup;4064}else{4065/* freed by commit_ref_update(): */4066 update->lock = NULL;4067}4068}4069}40704071/* Perform deletes now that updates are safely completed */4072for(i =0; i < n; i++) {4073struct ref_update *update = updates[i];40744075if(update->flags & REF_DELETING) {4076if(delete_ref_loose(update->lock, update->type, err)) {4077 ret = TRANSACTION_GENERIC_ERROR;4078goto cleanup;4079}40804081if(!(update->flags & REF_ISPRUNING))4082string_list_append(&refs_to_delete,4083 update->lock->ref_name);4084}4085}40864087if(repack_without_refs(&refs_to_delete, err)) {4088 ret = TRANSACTION_GENERIC_ERROR;4089goto cleanup;4090}4091for_each_string_list_item(ref_to_delete, &refs_to_delete)4092unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4093clear_loose_ref_cache(&ref_cache);40944095cleanup:4096 transaction->state = REF_TRANSACTION_CLOSED;40974098for(i =0; i < n; i++)4099if(updates[i]->lock)4100unlock_ref(updates[i]->lock);4101string_list_clear(&refs_to_delete,0);4102string_list_clear(&affected_refnames,0);4103return ret;4104}41054106static intref_present(const char*refname,4107const struct object_id *oid,int flags,void*cb_data)4108{4109struct string_list *affected_refnames = cb_data;41104111returnstring_list_has_string(affected_refnames, refname);4112}41134114intinitial_ref_transaction_commit(struct ref_transaction *transaction,4115struct strbuf *err)4116{4117struct ref_dir *loose_refs =get_loose_refs(&ref_cache);4118struct ref_dir *packed_refs =get_packed_refs(&ref_cache);4119int ret =0, i;4120int n = transaction->nr;4121struct ref_update **updates = transaction->updates;4122struct string_list affected_refnames = STRING_LIST_INIT_NODUP;41234124assert(err);41254126if(transaction->state != REF_TRANSACTION_OPEN)4127die("BUG: commit called for transaction that is not open");41284129/* Fail if a refname appears more than once in the transaction: */4130for(i =0; i < n; i++)4131string_list_append(&affected_refnames, updates[i]->refname);4132string_list_sort(&affected_refnames);4133if(ref_update_reject_duplicates(&affected_refnames, err)) {4134 ret = TRANSACTION_GENERIC_ERROR;4135goto cleanup;4136}41374138/*4139 * It's really undefined to call this function in an active4140 * repository or when there are existing references: we are4141 * only locking and changing packed-refs, so (1) any4142 * simultaneous processes might try to change a reference at4143 * the same time we do, and (2) any existing loose versions of4144 * the references that we are setting would have precedence4145 * over our values. But some remote helpers create the remote4146 * "HEAD" and "master" branches before calling this function,4147 * so here we really only check that none of the references4148 * that we are creating already exists.4149 */4150if(for_each_rawref(ref_present, &affected_refnames))4151die("BUG: initial ref transaction called with existing refs");41524153for(i =0; i < n; i++) {4154struct ref_update *update = updates[i];41554156if((update->flags & REF_HAVE_OLD) &&4157!is_null_sha1(update->old_sha1))4158die("BUG: initial ref transaction with old_sha1 set");4159if(verify_refname_available(update->refname,4160&affected_refnames, NULL,4161 loose_refs, err) ||4162verify_refname_available(update->refname,4163&affected_refnames, NULL,4164 packed_refs, err)) {4165 ret = TRANSACTION_NAME_CONFLICT;4166goto cleanup;4167}4168}41694170if(lock_packed_refs(0)) {4171strbuf_addf(err,"unable to lock packed-refs file:%s",4172strerror(errno));4173 ret = TRANSACTION_GENERIC_ERROR;4174goto cleanup;4175}41764177for(i =0; i < n; i++) {4178struct ref_update *update = updates[i];41794180if((update->flags & REF_HAVE_NEW) &&4181!is_null_sha1(update->new_sha1))4182add_packed_ref(update->refname, update->new_sha1);4183}41844185if(commit_packed_refs()) {4186strbuf_addf(err,"unable to commit packed-refs file:%s",4187strerror(errno));4188 ret = TRANSACTION_GENERIC_ERROR;4189goto cleanup;4190}41914192cleanup:4193 transaction->state = REF_TRANSACTION_CLOSED;4194string_list_clear(&affected_refnames,0);4195return ret;4196}41974198char*shorten_unambiguous_ref(const char*refname,int strict)4199{4200int i;4201static char**scanf_fmts;4202static int nr_rules;4203char*short_name;42044205if(!nr_rules) {4206/*4207 * Pre-generate scanf formats from ref_rev_parse_rules[].4208 * Generate a format suitable for scanf from a4209 * ref_rev_parse_rules rule by interpolating "%s" at the4210 * location of the "%.*s".4211 */4212size_t total_len =0;4213size_t offset =0;42144215/* the rule list is NULL terminated, count them first */4216for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4217/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4218 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;42194220 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);42214222 offset =0;4223for(i =0; i < nr_rules; i++) {4224assert(offset < total_len);4225 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4226 offset +=snprintf(scanf_fmts[i], total_len - offset,4227 ref_rev_parse_rules[i],2,"%s") +1;4228}4229}42304231/* bail out if there are no rules */4232if(!nr_rules)4233returnxstrdup(refname);42344235/* buffer for scanf result, at most refname must fit */4236 short_name =xstrdup(refname);42374238/* skip first rule, it will always match */4239for(i = nr_rules -1; i >0; --i) {4240int j;4241int rules_to_fail = i;4242int short_name_len;42434244if(1!=sscanf(refname, scanf_fmts[i], short_name))4245continue;42464247 short_name_len =strlen(short_name);42484249/*4250 * in strict mode, all (except the matched one) rules4251 * must fail to resolve to a valid non-ambiguous ref4252 */4253if(strict)4254 rules_to_fail = nr_rules;42554256/*4257 * check if the short name resolves to a valid ref,4258 * but use only rules prior to the matched one4259 */4260for(j =0; j < rules_to_fail; j++) {4261const char*rule = ref_rev_parse_rules[j];4262char refname[PATH_MAX];42634264/* skip matched rule */4265if(i == j)4266continue;42674268/*4269 * the short name is ambiguous, if it resolves4270 * (with this previous rule) to a valid ref4271 * read_ref() returns 0 on success4272 */4273mksnpath(refname,sizeof(refname),4274 rule, short_name_len, short_name);4275if(ref_exists(refname))4276break;4277}42784279/*4280 * short name is non-ambiguous if all previous rules4281 * haven't resolved to a valid ref4282 */4283if(j == rules_to_fail)4284return short_name;4285}42864287free(short_name);4288returnxstrdup(refname);4289}42904291static struct string_list *hide_refs;42924293intparse_hide_refs_config(const char*var,const char*value,const char*section)4294{4295if(!strcmp("transfer.hiderefs", var) ||4296/* NEEDSWORK: use parse_config_key() once both are merged */4297(starts_with(var, section) && var[strlen(section)] =='.'&&4298!strcmp(var +strlen(section),".hiderefs"))) {4299char*ref;4300int len;43014302if(!value)4303returnconfig_error_nonbool(var);4304 ref =xstrdup(value);4305 len =strlen(ref);4306while(len && ref[len -1] =='/')4307 ref[--len] ='\0';4308if(!hide_refs) {4309 hide_refs =xcalloc(1,sizeof(*hide_refs));4310 hide_refs->strdup_strings =1;4311}4312string_list_append(hide_refs, ref);4313}4314return0;4315}43164317intref_is_hidden(const char*refname)4318{4319struct string_list_item *item;43204321if(!hide_refs)4322return0;4323for_each_string_list_item(item, hide_refs) {4324int len;4325if(!starts_with(refname, item->string))4326continue;4327 len =strlen(item->string);4328if(!refname[len] || refname[len] =='/')4329return1;4330}4331return0;4332}43334334struct expire_reflog_cb {4335unsigned int flags;4336 reflog_expiry_should_prune_fn *should_prune_fn;4337void*policy_cb;4338FILE*newlog;4339unsigned char last_kept_sha1[20];4340};43414342static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4343const char*email,unsigned long timestamp,int tz,4344const char*message,void*cb_data)4345{4346struct expire_reflog_cb *cb = cb_data;4347struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;43484349if(cb->flags & EXPIRE_REFLOGS_REWRITE)4350 osha1 = cb->last_kept_sha1;43514352if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4353 message, policy_cb)) {4354if(!cb->newlog)4355printf("would prune%s", message);4356else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4357printf("prune%s", message);4358}else{4359if(cb->newlog) {4360fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4361sha1_to_hex(osha1),sha1_to_hex(nsha1),4362 email, timestamp, tz, message);4363hashcpy(cb->last_kept_sha1, nsha1);4364}4365if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4366printf("keep%s", message);4367}4368return0;4369}43704371intreflog_expire(const char*refname,const unsigned char*sha1,4372unsigned int flags,4373 reflog_expiry_prepare_fn prepare_fn,4374 reflog_expiry_should_prune_fn should_prune_fn,4375 reflog_expiry_cleanup_fn cleanup_fn,4376void*policy_cb_data)4377{4378static struct lock_file reflog_lock;4379struct expire_reflog_cb cb;4380struct ref_lock *lock;4381char*log_file;4382int status =0;4383int type;4384struct strbuf err = STRBUF_INIT;43854386memset(&cb,0,sizeof(cb));4387 cb.flags = flags;4388 cb.policy_cb = policy_cb_data;4389 cb.should_prune_fn = should_prune_fn;43904391/*4392 * The reflog file is locked by holding the lock on the4393 * reference itself, plus we might need to update the4394 * reference if --updateref was specified:4395 */4396 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4397if(!lock) {4398error("cannot lock ref '%s':%s", refname, err.buf);4399strbuf_release(&err);4400return-1;4401}4402if(!reflog_exists(refname)) {4403unlock_ref(lock);4404return0;4405}44064407 log_file =git_pathdup("logs/%s", refname);4408if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4409/*4410 * Even though holding $GIT_DIR/logs/$reflog.lock has4411 * no locking implications, we use the lock_file4412 * machinery here anyway because it does a lot of the4413 * work we need, including cleaning up if the program4414 * exits unexpectedly.4415 */4416if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4417struct strbuf err = STRBUF_INIT;4418unable_to_lock_message(log_file, errno, &err);4419error("%s", err.buf);4420strbuf_release(&err);4421goto failure;4422}4423 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4424if(!cb.newlog) {4425error("cannot fdopen%s(%s)",4426 reflog_lock.filename.buf,strerror(errno));4427goto failure;4428}4429}44304431(*prepare_fn)(refname, sha1, cb.policy_cb);4432for_each_reflog_ent(refname, expire_reflog_ent, &cb);4433(*cleanup_fn)(cb.policy_cb);44344435if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4436/*4437 * It doesn't make sense to adjust a reference pointed4438 * to by a symbolic ref based on expiring entries in4439 * the symbolic reference's reflog. Nor can we update4440 * a reference if there are no remaining reflog4441 * entries.4442 */4443int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4444!(type & REF_ISSYMREF) &&4445!is_null_sha1(cb.last_kept_sha1);44464447if(close_lock_file(&reflog_lock)) {4448 status |=error("couldn't write%s:%s", log_file,4449strerror(errno));4450}else if(update &&4451(write_in_full(lock->lk->fd,4452sha1_to_hex(cb.last_kept_sha1),40) !=40||4453write_str_in_full(lock->lk->fd,"\n") !=1||4454close_ref(lock) <0)) {4455 status |=error("couldn't write%s",4456 lock->lk->filename.buf);4457rollback_lock_file(&reflog_lock);4458}else if(commit_lock_file(&reflog_lock)) {4459 status |=error("unable to commit reflog '%s' (%s)",4460 log_file,strerror(errno));4461}else if(update &&commit_ref(lock)) {4462 status |=error("couldn't set%s", lock->ref_name);4463}4464}4465free(log_file);4466unlock_ref(lock);4467return status;44684469 failure:4470rollback_lock_file(&reflog_lock);4471free(log_file);4472unlock_ref(lock);4473return-1;4474}