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}13161317voidadd_packed_ref(const char*refname,const unsigned char*sha1)1318{1319struct packed_ref_cache *packed_ref_cache =1320get_packed_ref_cache(&ref_cache);13211322if(!packed_ref_cache->lock)1323die("internal error: packed refs not locked");1324add_ref(get_packed_ref_dir(packed_ref_cache),1325create_ref_entry(refname, sha1, REF_ISPACKED,1));1326}13271328/*1329 * Read the loose references from the namespace dirname into dir1330 * (without recursing). dirname must end with '/'. dir must be the1331 * directory entry corresponding to dirname.1332 */1333static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1334{1335struct ref_cache *refs = dir->ref_cache;1336DIR*d;1337const char*path;1338struct dirent *de;1339int dirnamelen =strlen(dirname);1340struct strbuf refname;13411342if(*refs->name)1343 path =git_path_submodule(refs->name,"%s", dirname);1344else1345 path =git_path("%s", dirname);13461347 d =opendir(path);1348if(!d)1349return;13501351strbuf_init(&refname, dirnamelen +257);1352strbuf_add(&refname, dirname, dirnamelen);13531354while((de =readdir(d)) != NULL) {1355unsigned char sha1[20];1356struct stat st;1357int flag;1358const char*refdir;13591360if(de->d_name[0] =='.')1361continue;1362if(ends_with(de->d_name,".lock"))1363continue;1364strbuf_addstr(&refname, de->d_name);1365 refdir = *refs->name1366?git_path_submodule(refs->name,"%s", refname.buf)1367:git_path("%s", refname.buf);1368if(stat(refdir, &st) <0) {1369;/* silently ignore */1370}else if(S_ISDIR(st.st_mode)) {1371strbuf_addch(&refname,'/');1372add_entry_to_dir(dir,1373create_dir_entry(refs, refname.buf,1374 refname.len,1));1375}else{1376int read_ok;13771378if(*refs->name) {1379hashclr(sha1);1380 flag =0;1381 read_ok = !resolve_gitlink_ref(refs->name,1382 refname.buf, sha1);1383}else{1384 read_ok = !read_ref_full(refname.buf,1385 RESOLVE_REF_READING,1386 sha1, &flag);1387}13881389if(!read_ok) {1390hashclr(sha1);1391 flag |= REF_ISBROKEN;1392}else if(is_null_sha1(sha1)) {1393/*1394 * It is so astronomically unlikely1395 * that NULL_SHA1 is the SHA-1 of an1396 * actual object that we consider its1397 * appearance in a loose reference1398 * file to be repo corruption1399 * (probably due to a software bug).1400 */1401 flag |= REF_ISBROKEN;1402}14031404if(check_refname_format(refname.buf,1405 REFNAME_ALLOW_ONELEVEL)) {1406if(!refname_is_safe(refname.buf))1407die("loose refname is dangerous:%s", refname.buf);1408hashclr(sha1);1409 flag |= REF_BAD_NAME | REF_ISBROKEN;1410}1411add_entry_to_dir(dir,1412create_ref_entry(refname.buf, sha1, flag,0));1413}1414strbuf_setlen(&refname, dirnamelen);1415}1416strbuf_release(&refname);1417closedir(d);1418}14191420static struct ref_dir *get_loose_refs(struct ref_cache *refs)1421{1422if(!refs->loose) {1423/*1424 * Mark the top-level directory complete because we1425 * are about to read the only subdirectory that can1426 * hold references:1427 */1428 refs->loose =create_dir_entry(refs,"",0,0);1429/*1430 * Create an incomplete entry for "refs/":1431 */1432add_entry_to_dir(get_ref_dir(refs->loose),1433create_dir_entry(refs,"refs/",5,1));1434}1435returnget_ref_dir(refs->loose);1436}14371438/* We allow "recursive" symbolic refs. Only within reason, though */1439#define MAXDEPTH 51440#define MAXREFLEN (1024)14411442/*1443 * Called by resolve_gitlink_ref_recursive() after it failed to read1444 * from the loose refs in ref_cache refs. Find <refname> in the1445 * packed-refs file for the submodule.1446 */1447static intresolve_gitlink_packed_ref(struct ref_cache *refs,1448const char*refname,unsigned char*sha1)1449{1450struct ref_entry *ref;1451struct ref_dir *dir =get_packed_refs(refs);14521453 ref =find_ref(dir, refname);1454if(ref == NULL)1455return-1;14561457hashcpy(sha1, ref->u.value.oid.hash);1458return0;1459}14601461static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1462const char*refname,unsigned char*sha1,1463int recursion)1464{1465int fd, len;1466char buffer[128], *p;1467const char*path;14681469if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1470return-1;1471 path = *refs->name1472?git_path_submodule(refs->name,"%s", refname)1473:git_path("%s", refname);1474 fd =open(path, O_RDONLY);1475if(fd <0)1476returnresolve_gitlink_packed_ref(refs, refname, sha1);14771478 len =read(fd, buffer,sizeof(buffer)-1);1479close(fd);1480if(len <0)1481return-1;1482while(len &&isspace(buffer[len-1]))1483 len--;1484 buffer[len] =0;14851486/* Was it a detached head or an old-fashioned symlink? */1487if(!get_sha1_hex(buffer, sha1))1488return0;14891490/* Symref? */1491if(strncmp(buffer,"ref:",4))1492return-1;1493 p = buffer +4;1494while(isspace(*p))1495 p++;14961497returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1498}14991500intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1501{1502int len =strlen(path), retval;1503char*submodule;1504struct ref_cache *refs;15051506while(len && path[len-1] =='/')1507 len--;1508if(!len)1509return-1;1510 submodule =xstrndup(path, len);1511 refs =get_ref_cache(submodule);1512free(submodule);15131514 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1515return retval;1516}15171518/*1519 * Return the ref_entry for the given refname from the packed1520 * references. If it does not exist, return NULL.1521 */1522static struct ref_entry *get_packed_ref(const char*refname)1523{1524returnfind_ref(get_packed_refs(&ref_cache), refname);1525}15261527/*1528 * A loose ref file doesn't exist; check for a packed ref. The1529 * options are forwarded from resolve_safe_unsafe().1530 */1531static intresolve_missing_loose_ref(const char*refname,1532int resolve_flags,1533unsigned char*sha1,1534int*flags)1535{1536struct ref_entry *entry;15371538/*1539 * The loose reference file does not exist; check for a packed1540 * reference.1541 */1542 entry =get_packed_ref(refname);1543if(entry) {1544hashcpy(sha1, entry->u.value.oid.hash);1545if(flags)1546*flags |= REF_ISPACKED;1547return0;1548}1549/* The reference is not a packed reference, either. */1550if(resolve_flags & RESOLVE_REF_READING) {1551 errno = ENOENT;1552return-1;1553}else{1554hashclr(sha1);1555return0;1556}1557}15581559/* This function needs to return a meaningful errno on failure */1560static const char*resolve_ref_unsafe_1(const char*refname,1561int resolve_flags,1562unsigned char*sha1,1563int*flags,1564struct strbuf *sb_path)1565{1566int depth = MAXDEPTH;1567 ssize_t len;1568char buffer[256];1569static char refname_buffer[256];1570int bad_name =0;15711572if(flags)1573*flags =0;15741575if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1576if(flags)1577*flags |= REF_BAD_NAME;15781579if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1580!refname_is_safe(refname)) {1581 errno = EINVAL;1582return NULL;1583}1584/*1585 * dwim_ref() uses REF_ISBROKEN to distinguish between1586 * missing refs and refs that were present but invalid,1587 * to complain about the latter to stderr.1588 *1589 * We don't know whether the ref exists, so don't set1590 * REF_ISBROKEN yet.1591 */1592 bad_name =1;1593}1594for(;;) {1595const char*path;1596struct stat st;1597char*buf;1598int fd;15991600if(--depth <0) {1601 errno = ELOOP;1602return NULL;1603}16041605strbuf_reset(sb_path);1606strbuf_git_path(sb_path,"%s", refname);1607 path = sb_path->buf;16081609/*1610 * We might have to loop back here to avoid a race1611 * condition: first we lstat() the file, then we try1612 * to read it as a link or as a file. But if somebody1613 * changes the type of the file (file <-> directory1614 * <-> symlink) between the lstat() and reading, then1615 * we don't want to report that as an error but rather1616 * try again starting with the lstat().1617 */1618 stat_ref:1619if(lstat(path, &st) <0) {1620if(errno != ENOENT)1621return NULL;1622if(resolve_missing_loose_ref(refname, resolve_flags,1623 sha1, flags))1624return NULL;1625if(bad_name) {1626hashclr(sha1);1627if(flags)1628*flags |= REF_ISBROKEN;1629}1630return refname;1631}16321633/* Follow "normalized" - ie "refs/.." symlinks by hand */1634if(S_ISLNK(st.st_mode)) {1635 len =readlink(path, buffer,sizeof(buffer)-1);1636if(len <0) {1637if(errno == ENOENT || errno == EINVAL)1638/* inconsistent with lstat; retry */1639goto stat_ref;1640else1641return NULL;1642}1643 buffer[len] =0;1644if(starts_with(buffer,"refs/") &&1645!check_refname_format(buffer,0)) {1646strcpy(refname_buffer, buffer);1647 refname = refname_buffer;1648if(flags)1649*flags |= REF_ISSYMREF;1650if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1651hashclr(sha1);1652return refname;1653}1654continue;1655}1656}16571658/* Is it a directory? */1659if(S_ISDIR(st.st_mode)) {1660 errno = EISDIR;1661return NULL;1662}16631664/*1665 * Anything else, just open it and try to use it as1666 * a ref1667 */1668 fd =open(path, O_RDONLY);1669if(fd <0) {1670if(errno == ENOENT)1671/* inconsistent with lstat; retry */1672goto stat_ref;1673else1674return NULL;1675}1676 len =read_in_full(fd, buffer,sizeof(buffer)-1);1677if(len <0) {1678int save_errno = errno;1679close(fd);1680 errno = save_errno;1681return NULL;1682}1683close(fd);1684while(len &&isspace(buffer[len-1]))1685 len--;1686 buffer[len] ='\0';16871688/*1689 * Is it a symbolic ref?1690 */1691if(!starts_with(buffer,"ref:")) {1692/*1693 * Please note that FETCH_HEAD has a second1694 * line containing other data.1695 */1696if(get_sha1_hex(buffer, sha1) ||1697(buffer[40] !='\0'&& !isspace(buffer[40]))) {1698if(flags)1699*flags |= REF_ISBROKEN;1700 errno = EINVAL;1701return NULL;1702}1703if(bad_name) {1704hashclr(sha1);1705if(flags)1706*flags |= REF_ISBROKEN;1707}1708return refname;1709}1710if(flags)1711*flags |= REF_ISSYMREF;1712 buf = buffer +4;1713while(isspace(*buf))1714 buf++;1715 refname =strcpy(refname_buffer, buf);1716if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1717hashclr(sha1);1718return refname;1719}1720if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1721if(flags)1722*flags |= REF_ISBROKEN;17231724if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1725!refname_is_safe(buf)) {1726 errno = EINVAL;1727return NULL;1728}1729 bad_name =1;1730}1731}1732}17331734const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1735unsigned char*sha1,int*flags)1736{1737struct strbuf sb_path = STRBUF_INIT;1738const char*ret =resolve_ref_unsafe_1(refname, resolve_flags,1739 sha1, flags, &sb_path);1740strbuf_release(&sb_path);1741return ret;1742}17431744char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1745{1746returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1747}17481749/* The argument to filter_refs */1750struct ref_filter {1751const char*pattern;1752 each_ref_fn *fn;1753void*cb_data;1754};17551756intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1757{1758if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1759return0;1760return-1;1761}17621763intread_ref(const char*refname,unsigned char*sha1)1764{1765returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1766}17671768intref_exists(const char*refname)1769{1770unsigned char sha1[20];1771return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1772}17731774static intfilter_refs(const char*refname,const struct object_id *oid,1775int flags,void*data)1776{1777struct ref_filter *filter = (struct ref_filter *)data;17781779if(wildmatch(filter->pattern, refname,0, NULL))1780return0;1781return filter->fn(refname, oid, flags, filter->cb_data);1782}17831784enum peel_status {1785/* object was peeled successfully: */1786 PEEL_PEELED =0,17871788/*1789 * object cannot be peeled because the named object (or an1790 * object referred to by a tag in the peel chain), does not1791 * exist.1792 */1793 PEEL_INVALID = -1,17941795/* object cannot be peeled because it is not a tag: */1796 PEEL_NON_TAG = -2,17971798/* ref_entry contains no peeled value because it is a symref: */1799 PEEL_IS_SYMREF = -3,18001801/*1802 * ref_entry cannot be peeled because it is broken (i.e., the1803 * symbolic reference cannot even be resolved to an object1804 * name):1805 */1806 PEEL_BROKEN = -41807};18081809/*1810 * Peel the named object; i.e., if the object is a tag, resolve the1811 * tag recursively until a non-tag is found. If successful, store the1812 * result to sha1 and return PEEL_PEELED. If the object is not a tag1813 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1814 * and leave sha1 unchanged.1815 */1816static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1817{1818struct object *o =lookup_unknown_object(name);18191820if(o->type == OBJ_NONE) {1821int type =sha1_object_info(name, NULL);1822if(type <0|| !object_as_type(o, type,0))1823return PEEL_INVALID;1824}18251826if(o->type != OBJ_TAG)1827return PEEL_NON_TAG;18281829 o =deref_tag_noverify(o);1830if(!o)1831return PEEL_INVALID;18321833hashcpy(sha1, o->sha1);1834return PEEL_PEELED;1835}18361837/*1838 * Peel the entry (if possible) and return its new peel_status. If1839 * repeel is true, re-peel the entry even if there is an old peeled1840 * value that is already stored in it.1841 *1842 * It is OK to call this function with a packed reference entry that1843 * might be stale and might even refer to an object that has since1844 * been garbage-collected. In such a case, if the entry has1845 * REF_KNOWS_PEELED then leave the status unchanged and return1846 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1847 */1848static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1849{1850enum peel_status status;18511852if(entry->flag & REF_KNOWS_PEELED) {1853if(repeel) {1854 entry->flag &= ~REF_KNOWS_PEELED;1855oidclr(&entry->u.value.peeled);1856}else{1857returnis_null_oid(&entry->u.value.peeled) ?1858 PEEL_NON_TAG : PEEL_PEELED;1859}1860}1861if(entry->flag & REF_ISBROKEN)1862return PEEL_BROKEN;1863if(entry->flag & REF_ISSYMREF)1864return PEEL_IS_SYMREF;18651866 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1867if(status == PEEL_PEELED || status == PEEL_NON_TAG)1868 entry->flag |= REF_KNOWS_PEELED;1869return status;1870}18711872intpeel_ref(const char*refname,unsigned char*sha1)1873{1874int flag;1875unsigned char base[20];18761877if(current_ref && (current_ref->name == refname1878|| !strcmp(current_ref->name, refname))) {1879if(peel_entry(current_ref,0))1880return-1;1881hashcpy(sha1, current_ref->u.value.peeled.hash);1882return0;1883}18841885if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1886return-1;18871888/*1889 * If the reference is packed, read its ref_entry from the1890 * cache in the hope that we already know its peeled value.1891 * We only try this optimization on packed references because1892 * (a) forcing the filling of the loose reference cache could1893 * be expensive and (b) loose references anyway usually do not1894 * have REF_KNOWS_PEELED.1895 */1896if(flag & REF_ISPACKED) {1897struct ref_entry *r =get_packed_ref(refname);1898if(r) {1899if(peel_entry(r,0))1900return-1;1901hashcpy(sha1, r->u.value.peeled.hash);1902return0;1903}1904}19051906returnpeel_object(base, sha1);1907}19081909struct warn_if_dangling_data {1910FILE*fp;1911const char*refname;1912const struct string_list *refnames;1913const char*msg_fmt;1914};19151916static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1917int flags,void*cb_data)1918{1919struct warn_if_dangling_data *d = cb_data;1920const char*resolves_to;1921struct object_id junk;19221923if(!(flags & REF_ISSYMREF))1924return0;19251926 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1927if(!resolves_to1928|| (d->refname1929?strcmp(resolves_to, d->refname)1930: !string_list_has_string(d->refnames, resolves_to))) {1931return0;1932}19331934fprintf(d->fp, d->msg_fmt, refname);1935fputc('\n', d->fp);1936return0;1937}19381939voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1940{1941struct warn_if_dangling_data data;19421943 data.fp = fp;1944 data.refname = refname;1945 data.refnames = NULL;1946 data.msg_fmt = msg_fmt;1947for_each_rawref(warn_if_dangling_symref, &data);1948}19491950voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1951{1952struct warn_if_dangling_data data;19531954 data.fp = fp;1955 data.refname = NULL;1956 data.refnames = refnames;1957 data.msg_fmt = msg_fmt;1958for_each_rawref(warn_if_dangling_symref, &data);1959}19601961/*1962 * Call fn for each reference in the specified ref_cache, omitting1963 * references not in the containing_dir of base. fn is called for all1964 * references, including broken ones. If fn ever returns a non-zero1965 * value, stop the iteration and return that value; otherwise, return1966 * 0.1967 */1968static intdo_for_each_entry(struct ref_cache *refs,const char*base,1969 each_ref_entry_fn fn,void*cb_data)1970{1971struct packed_ref_cache *packed_ref_cache;1972struct ref_dir *loose_dir;1973struct ref_dir *packed_dir;1974int retval =0;19751976/*1977 * We must make sure that all loose refs are read before accessing the1978 * packed-refs file; this avoids a race condition in which loose refs1979 * are migrated to the packed-refs file by a simultaneous process, but1980 * our in-memory view is from before the migration. get_packed_ref_cache()1981 * takes care of making sure our view is up to date with what is on1982 * disk.1983 */1984 loose_dir =get_loose_refs(refs);1985if(base && *base) {1986 loose_dir =find_containing_dir(loose_dir, base,0);1987}1988if(loose_dir)1989prime_ref_dir(loose_dir);19901991 packed_ref_cache =get_packed_ref_cache(refs);1992acquire_packed_ref_cache(packed_ref_cache);1993 packed_dir =get_packed_ref_dir(packed_ref_cache);1994if(base && *base) {1995 packed_dir =find_containing_dir(packed_dir, base,0);1996}19971998if(packed_dir && loose_dir) {1999sort_ref_dir(packed_dir);2000sort_ref_dir(loose_dir);2001 retval =do_for_each_entry_in_dirs(2002 packed_dir, loose_dir, fn, cb_data);2003}else if(packed_dir) {2004sort_ref_dir(packed_dir);2005 retval =do_for_each_entry_in_dir(2006 packed_dir,0, fn, cb_data);2007}else if(loose_dir) {2008sort_ref_dir(loose_dir);2009 retval =do_for_each_entry_in_dir(2010 loose_dir,0, fn, cb_data);2011}20122013release_packed_ref_cache(packed_ref_cache);2014return retval;2015}20162017/*2018 * Call fn for each reference in the specified ref_cache for which the2019 * refname begins with base. If trim is non-zero, then trim that many2020 * characters off the beginning of each refname before passing the2021 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2022 * broken references in the iteration. If fn ever returns a non-zero2023 * value, stop the iteration and return that value; otherwise, return2024 * 0.2025 */2026static intdo_for_each_ref(struct ref_cache *refs,const char*base,2027 each_ref_fn fn,int trim,int flags,void*cb_data)2028{2029struct ref_entry_cb data;2030 data.base = base;2031 data.trim = trim;2032 data.flags = flags;2033 data.fn = fn;2034 data.cb_data = cb_data;20352036if(ref_paranoia <0)2037 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2038if(ref_paranoia)2039 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20402041returndo_for_each_entry(refs, base, do_one_ref, &data);2042}20432044static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2045{2046struct object_id oid;2047int flag;20482049if(submodule) {2050if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2051returnfn("HEAD", &oid,0, cb_data);20522053return0;2054}20552056if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2057returnfn("HEAD", &oid, flag, cb_data);20582059return0;2060}20612062inthead_ref(each_ref_fn fn,void*cb_data)2063{2064returndo_head_ref(NULL, fn, cb_data);2065}20662067inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2068{2069returndo_head_ref(submodule, fn, cb_data);2070}20712072intfor_each_ref(each_ref_fn fn,void*cb_data)2073{2074returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2075}20762077intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2078{2079returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2080}20812082intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2083{2084returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2085}20862087intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2088 each_ref_fn fn,void*cb_data)2089{2090returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2091}20922093intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2094{2095returnfor_each_ref_in("refs/tags/", fn, cb_data);2096}20972098intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2099{2100returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2101}21022103intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2104{2105returnfor_each_ref_in("refs/heads/", fn, cb_data);2106}21072108intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2109{2110returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2111}21122113intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2114{2115returnfor_each_ref_in("refs/remotes/", fn, cb_data);2116}21172118intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2119{2120returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2121}21222123intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2124{2125returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2126}21272128inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2129{2130struct strbuf buf = STRBUF_INIT;2131int ret =0;2132struct object_id oid;2133int flag;21342135strbuf_addf(&buf,"%sHEAD",get_git_namespace());2136if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2137 ret =fn(buf.buf, &oid, flag, cb_data);2138strbuf_release(&buf);21392140return ret;2141}21422143intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2144{2145struct strbuf buf = STRBUF_INIT;2146int ret;2147strbuf_addf(&buf,"%srefs/",get_git_namespace());2148 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2149strbuf_release(&buf);2150return ret;2151}21522153intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2154const char*prefix,void*cb_data)2155{2156struct strbuf real_pattern = STRBUF_INIT;2157struct ref_filter filter;2158int ret;21592160if(!prefix && !starts_with(pattern,"refs/"))2161strbuf_addstr(&real_pattern,"refs/");2162else if(prefix)2163strbuf_addstr(&real_pattern, prefix);2164strbuf_addstr(&real_pattern, pattern);21652166if(!has_glob_specials(pattern)) {2167/* Append implied '/' '*' if not present. */2168if(real_pattern.buf[real_pattern.len -1] !='/')2169strbuf_addch(&real_pattern,'/');2170/* No need to check for '*', there is none. */2171strbuf_addch(&real_pattern,'*');2172}21732174 filter.pattern = real_pattern.buf;2175 filter.fn = fn;2176 filter.cb_data = cb_data;2177 ret =for_each_ref(filter_refs, &filter);21782179strbuf_release(&real_pattern);2180return ret;2181}21822183intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2184{2185returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2186}21872188intfor_each_rawref(each_ref_fn fn,void*cb_data)2189{2190returndo_for_each_ref(&ref_cache,"", fn,0,2191 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2192}21932194const char*prettify_refname(const char*name)2195{2196return name + (2197starts_with(name,"refs/heads/") ?11:2198starts_with(name,"refs/tags/") ?10:2199starts_with(name,"refs/remotes/") ?13:22000);2201}22022203static const char*ref_rev_parse_rules[] = {2204"%.*s",2205"refs/%.*s",2206"refs/tags/%.*s",2207"refs/heads/%.*s",2208"refs/remotes/%.*s",2209"refs/remotes/%.*s/HEAD",2210 NULL2211};22122213intrefname_match(const char*abbrev_name,const char*full_name)2214{2215const char**p;2216const int abbrev_name_len =strlen(abbrev_name);22172218for(p = ref_rev_parse_rules; *p; p++) {2219if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2220return1;2221}2222}22232224return0;2225}22262227static voidunlock_ref(struct ref_lock *lock)2228{2229/* Do not free lock->lk -- atexit() still looks at them */2230if(lock->lk)2231rollback_lock_file(lock->lk);2232free(lock->ref_name);2233free(lock->orig_ref_name);2234free(lock);2235}22362237/*2238 * Verify that the reference locked by lock has the value old_sha1.2239 * Fail if the reference doesn't exist and mustexist is set. Return 02240 * on success. On error, write an error message to err, set errno, and2241 * return a negative value.2242 */2243static intverify_lock(struct ref_lock *lock,2244const unsigned char*old_sha1,int mustexist,2245struct strbuf *err)2246{2247assert(err);22482249if(read_ref_full(lock->ref_name,2250 mustexist ? RESOLVE_REF_READING :0,2251 lock->old_oid.hash, NULL)) {2252int save_errno = errno;2253strbuf_addf(err,"can't verify ref%s", lock->ref_name);2254 errno = save_errno;2255return-1;2256}2257if(hashcmp(lock->old_oid.hash, old_sha1)) {2258strbuf_addf(err,"ref%sis at%sbut expected%s",2259 lock->ref_name,2260sha1_to_hex(lock->old_oid.hash),2261sha1_to_hex(old_sha1));2262 errno = EBUSY;2263return-1;2264}2265return0;2266}22672268static intremove_empty_directories(const char*file)2269{2270/* we want to create a file but there is a directory there;2271 * if that is an empty directory (or a directory that contains2272 * only empty directories), remove them.2273 */2274struct strbuf path;2275int result, save_errno;22762277strbuf_init(&path,20);2278strbuf_addstr(&path, file);22792280 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2281 save_errno = errno;22822283strbuf_release(&path);2284 errno = save_errno;22852286return result;2287}22882289/*2290 * *string and *len will only be substituted, and *string returned (for2291 * later free()ing) if the string passed in is a magic short-hand form2292 * to name a branch.2293 */2294static char*substitute_branch_name(const char**string,int*len)2295{2296struct strbuf buf = STRBUF_INIT;2297int ret =interpret_branch_name(*string, *len, &buf);22982299if(ret == *len) {2300size_t size;2301*string =strbuf_detach(&buf, &size);2302*len = size;2303return(char*)*string;2304}23052306return NULL;2307}23082309intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2310{2311char*last_branch =substitute_branch_name(&str, &len);2312const char**p, *r;2313int refs_found =0;23142315*ref = NULL;2316for(p = ref_rev_parse_rules; *p; p++) {2317char fullref[PATH_MAX];2318unsigned char sha1_from_ref[20];2319unsigned char*this_result;2320int flag;23212322 this_result = refs_found ? sha1_from_ref : sha1;2323mksnpath(fullref,sizeof(fullref), *p, len, str);2324 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2325 this_result, &flag);2326if(r) {2327if(!refs_found++)2328*ref =xstrdup(r);2329if(!warn_ambiguous_refs)2330break;2331}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2332warning("ignoring dangling symref%s.", fullref);2333}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2334warning("ignoring broken ref%s.", fullref);2335}2336}2337free(last_branch);2338return refs_found;2339}23402341intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2342{2343char*last_branch =substitute_branch_name(&str, &len);2344const char**p;2345int logs_found =0;23462347*log = NULL;2348for(p = ref_rev_parse_rules; *p; p++) {2349unsigned char hash[20];2350char path[PATH_MAX];2351const char*ref, *it;23522353mksnpath(path,sizeof(path), *p, len, str);2354 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2355 hash, NULL);2356if(!ref)2357continue;2358if(reflog_exists(path))2359 it = path;2360else if(strcmp(ref, path) &&reflog_exists(ref))2361 it = ref;2362else2363continue;2364if(!logs_found++) {2365*log =xstrdup(it);2366hashcpy(sha1, hash);2367}2368if(!warn_ambiguous_refs)2369break;2370}2371free(last_branch);2372return logs_found;2373}23742375/*2376 * Locks a ref returning the lock on success and NULL on failure.2377 * On failure errno is set to something meaningful.2378 */2379static struct ref_lock *lock_ref_sha1_basic(const char*refname,2380const unsigned char*old_sha1,2381const struct string_list *extras,2382const struct string_list *skip,2383unsigned int flags,int*type_p,2384struct strbuf *err)2385{2386const char*ref_file;2387const char*orig_refname = refname;2388struct ref_lock *lock;2389int last_errno =0;2390int type, lflags;2391int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2392int resolve_flags =0;2393int attempts_remaining =3;23942395assert(err);23962397 lock =xcalloc(1,sizeof(struct ref_lock));23982399if(mustexist)2400 resolve_flags |= RESOLVE_REF_READING;2401if(flags & REF_DELETING) {2402 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2403if(flags & REF_NODEREF)2404 resolve_flags |= RESOLVE_REF_NO_RECURSE;2405}24062407 refname =resolve_ref_unsafe(refname, resolve_flags,2408 lock->old_oid.hash, &type);2409if(!refname && errno == EISDIR) {2410/* we are trying to lock foo but we used to2411 * have foo/bar which now does not exist;2412 * it is normal for the empty directory 'foo'2413 * to remain.2414 */2415 ref_file =git_path("%s", orig_refname);2416if(remove_empty_directories(ref_file)) {2417 last_errno = errno;24182419if(!verify_refname_available(orig_refname, extras, skip,2420get_loose_refs(&ref_cache), err))2421strbuf_addf(err,"there are still refs under '%s'",2422 orig_refname);24232424goto error_return;2425}2426 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2427 lock->old_oid.hash, &type);2428}2429if(type_p)2430*type_p = type;2431if(!refname) {2432 last_errno = errno;2433if(last_errno != ENOTDIR ||2434!verify_refname_available(orig_refname, extras, skip,2435get_loose_refs(&ref_cache), err))2436strbuf_addf(err,"unable to resolve reference%s:%s",2437 orig_refname,strerror(last_errno));24382439goto error_return;2440}2441/*2442 * If the ref did not exist and we are creating it, make sure2443 * there is no existing packed ref whose name begins with our2444 * refname, nor a packed ref whose name is a proper prefix of2445 * our refname.2446 */2447if(is_null_oid(&lock->old_oid) &&2448verify_refname_available(refname, extras, skip,2449get_packed_refs(&ref_cache), err)) {2450 last_errno = ENOTDIR;2451goto error_return;2452}24532454 lock->lk =xcalloc(1,sizeof(struct lock_file));24552456 lflags =0;2457if(flags & REF_NODEREF) {2458 refname = orig_refname;2459 lflags |= LOCK_NO_DEREF;2460}2461 lock->ref_name =xstrdup(refname);2462 lock->orig_ref_name =xstrdup(orig_refname);2463 ref_file =git_path("%s", refname);24642465 retry:2466switch(safe_create_leading_directories_const(ref_file)) {2467case SCLD_OK:2468break;/* success */2469case SCLD_VANISHED:2470if(--attempts_remaining >0)2471goto retry;2472/* fall through */2473default:2474 last_errno = errno;2475strbuf_addf(err,"unable to create directory for%s", ref_file);2476goto error_return;2477}24782479if(hold_lock_file_for_update(lock->lk, ref_file, lflags) <0) {2480 last_errno = errno;2481if(errno == ENOENT && --attempts_remaining >0)2482/*2483 * Maybe somebody just deleted one of the2484 * directories leading to ref_file. Try2485 * again:2486 */2487goto retry;2488else{2489unable_to_lock_message(ref_file, errno, err);2490goto error_return;2491}2492}2493if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2494 last_errno = errno;2495goto error_return;2496}2497return lock;24982499 error_return:2500unlock_ref(lock);2501 errno = last_errno;2502return NULL;2503}25042505/*2506 * Write an entry to the packed-refs file for the specified refname.2507 * If peeled is non-NULL, write it as the entry's peeled value.2508 */2509static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2510unsigned char*peeled)2511{2512fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2513if(peeled)2514fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2515}25162517/*2518 * An each_ref_entry_fn that writes the entry to a packed-refs file.2519 */2520static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2521{2522enum peel_status peel_status =peel_entry(entry,0);25232524if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2525error("internal error:%sis not a valid packed reference!",2526 entry->name);2527write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2528 peel_status == PEEL_PEELED ?2529 entry->u.value.peeled.hash : NULL);2530return0;2531}25322533/* This should return a meaningful errno on failure */2534intlock_packed_refs(int flags)2535{2536static int timeout_configured =0;2537static int timeout_value =1000;25382539struct packed_ref_cache *packed_ref_cache;25402541if(!timeout_configured) {2542git_config_get_int("core.packedrefstimeout", &timeout_value);2543 timeout_configured =1;2544}25452546if(hold_lock_file_for_update_timeout(2547&packlock,git_path("packed-refs"),2548 flags, timeout_value) <0)2549return-1;2550/*2551 * Get the current packed-refs while holding the lock. If the2552 * packed-refs file has been modified since we last read it,2553 * this will automatically invalidate the cache and re-read2554 * the packed-refs file.2555 */2556 packed_ref_cache =get_packed_ref_cache(&ref_cache);2557 packed_ref_cache->lock = &packlock;2558/* Increment the reference count to prevent it from being freed: */2559acquire_packed_ref_cache(packed_ref_cache);2560return0;2561}25622563/*2564 * Commit the packed refs changes.2565 * On error we must make sure that errno contains a meaningful value.2566 */2567intcommit_packed_refs(void)2568{2569struct packed_ref_cache *packed_ref_cache =2570get_packed_ref_cache(&ref_cache);2571int error =0;2572int save_errno =0;2573FILE*out;25742575if(!packed_ref_cache->lock)2576die("internal error: packed-refs not locked");25772578 out =fdopen_lock_file(packed_ref_cache->lock,"w");2579if(!out)2580die_errno("unable to fdopen packed-refs descriptor");25812582fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2583do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),25840, write_packed_entry_fn, out);25852586if(commit_lock_file(packed_ref_cache->lock)) {2587 save_errno = errno;2588 error = -1;2589}2590 packed_ref_cache->lock = NULL;2591release_packed_ref_cache(packed_ref_cache);2592 errno = save_errno;2593return error;2594}25952596voidrollback_packed_refs(void)2597{2598struct packed_ref_cache *packed_ref_cache =2599get_packed_ref_cache(&ref_cache);26002601if(!packed_ref_cache->lock)2602die("internal error: packed-refs not locked");2603rollback_lock_file(packed_ref_cache->lock);2604 packed_ref_cache->lock = NULL;2605release_packed_ref_cache(packed_ref_cache);2606clear_packed_ref_cache(&ref_cache);2607}26082609struct ref_to_prune {2610struct ref_to_prune *next;2611unsigned char sha1[20];2612char name[FLEX_ARRAY];2613};26142615struct pack_refs_cb_data {2616unsigned int flags;2617struct ref_dir *packed_refs;2618struct ref_to_prune *ref_to_prune;2619};26202621/*2622 * An each_ref_entry_fn that is run over loose references only. If2623 * the loose reference can be packed, add an entry in the packed ref2624 * cache. If the reference should be pruned, also add it to2625 * ref_to_prune in the pack_refs_cb_data.2626 */2627static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2628{2629struct pack_refs_cb_data *cb = cb_data;2630enum peel_status peel_status;2631struct ref_entry *packed_entry;2632int is_tag_ref =starts_with(entry->name,"refs/tags/");26332634/* ALWAYS pack tags */2635if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2636return0;26372638/* Do not pack symbolic or broken refs: */2639if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2640return0;26412642/* Add a packed ref cache entry equivalent to the loose entry. */2643 peel_status =peel_entry(entry,1);2644if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2645die("internal error peeling reference%s(%s)",2646 entry->name,oid_to_hex(&entry->u.value.oid));2647 packed_entry =find_ref(cb->packed_refs, entry->name);2648if(packed_entry) {2649/* Overwrite existing packed entry with info from loose entry */2650 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2651oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2652}else{2653 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2654 REF_ISPACKED | REF_KNOWS_PEELED,0);2655add_ref(cb->packed_refs, packed_entry);2656}2657oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);26582659/* Schedule the loose reference for pruning if requested. */2660if((cb->flags & PACK_REFS_PRUNE)) {2661int namelen =strlen(entry->name) +1;2662struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2663hashcpy(n->sha1, entry->u.value.oid.hash);2664strcpy(n->name, entry->name);2665 n->next = cb->ref_to_prune;2666 cb->ref_to_prune = n;2667}2668return0;2669}26702671/*2672 * Remove empty parents, but spare refs/ and immediate subdirs.2673 * Note: munges *name.2674 */2675static voidtry_remove_empty_parents(char*name)2676{2677char*p, *q;2678int i;2679 p = name;2680for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2681while(*p && *p !='/')2682 p++;2683/* tolerate duplicate slashes; see check_refname_format() */2684while(*p =='/')2685 p++;2686}2687for(q = p; *q; q++)2688;2689while(1) {2690while(q > p && *q !='/')2691 q--;2692while(q > p && *(q-1) =='/')2693 q--;2694if(q == p)2695break;2696*q ='\0';2697if(rmdir(git_path("%s", name)))2698break;2699}2700}27012702/* make sure nobody touched the ref, and unlink */2703static voidprune_ref(struct ref_to_prune *r)2704{2705struct ref_transaction *transaction;2706struct strbuf err = STRBUF_INIT;27072708if(check_refname_format(r->name,0))2709return;27102711 transaction =ref_transaction_begin(&err);2712if(!transaction ||2713ref_transaction_delete(transaction, r->name, r->sha1,2714 REF_ISPRUNING, NULL, &err) ||2715ref_transaction_commit(transaction, &err)) {2716ref_transaction_free(transaction);2717error("%s", err.buf);2718strbuf_release(&err);2719return;2720}2721ref_transaction_free(transaction);2722strbuf_release(&err);2723try_remove_empty_parents(r->name);2724}27252726static voidprune_refs(struct ref_to_prune *r)2727{2728while(r) {2729prune_ref(r);2730 r = r->next;2731}2732}27332734intpack_refs(unsigned int flags)2735{2736struct pack_refs_cb_data cbdata;27372738memset(&cbdata,0,sizeof(cbdata));2739 cbdata.flags = flags;27402741lock_packed_refs(LOCK_DIE_ON_ERROR);2742 cbdata.packed_refs =get_packed_refs(&ref_cache);27432744do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2745 pack_if_possible_fn, &cbdata);27462747if(commit_packed_refs())2748die_errno("unable to overwrite old ref-pack file");27492750prune_refs(cbdata.ref_to_prune);2751return0;2752}27532754intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2755{2756struct ref_dir *packed;2757struct string_list_item *refname;2758int ret, needs_repacking =0, removed =0;27592760assert(err);27612762/* Look for a packed ref */2763for_each_string_list_item(refname, refnames) {2764if(get_packed_ref(refname->string)) {2765 needs_repacking =1;2766break;2767}2768}27692770/* Avoid locking if we have nothing to do */2771if(!needs_repacking)2772return0;/* no refname exists in packed refs */27732774if(lock_packed_refs(0)) {2775unable_to_lock_message(git_path("packed-refs"), errno, err);2776return-1;2777}2778 packed =get_packed_refs(&ref_cache);27792780/* Remove refnames from the cache */2781for_each_string_list_item(refname, refnames)2782if(remove_entry(packed, refname->string) != -1)2783 removed =1;2784if(!removed) {2785/*2786 * All packed entries disappeared while we were2787 * acquiring the lock.2788 */2789rollback_packed_refs();2790return0;2791}27922793/* Write what remains */2794 ret =commit_packed_refs();2795if(ret)2796strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2797strerror(errno));2798return ret;2799}28002801static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2802{2803assert(err);28042805if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2806/*2807 * loose. The loose file name is the same as the2808 * lockfile name, minus ".lock":2809 */2810char*loose_filename =get_locked_file_path(lock->lk);2811int res =unlink_or_msg(loose_filename, err);2812free(loose_filename);2813if(res)2814return1;2815}2816return0;2817}28182819intdelete_ref(const char*refname,const unsigned char*sha1,unsigned int flags)2820{2821struct ref_transaction *transaction;2822struct strbuf err = STRBUF_INIT;28232824 transaction =ref_transaction_begin(&err);2825if(!transaction ||2826ref_transaction_delete(transaction, refname,2827(sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,2828 flags, NULL, &err) ||2829ref_transaction_commit(transaction, &err)) {2830error("%s", err.buf);2831ref_transaction_free(transaction);2832strbuf_release(&err);2833return1;2834}2835ref_transaction_free(transaction);2836strbuf_release(&err);2837return0;2838}28392840/*2841 * People using contrib's git-new-workdir have .git/logs/refs ->2842 * /some/other/path/.git/logs/refs, and that may live on another device.2843 *2844 * IOW, to avoid cross device rename errors, the temporary renamed log must2845 * live into logs/refs.2846 */2847#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"28482849static intrename_tmp_log(const char*newrefname)2850{2851int attempts_remaining =4;28522853 retry:2854switch(safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {2855case SCLD_OK:2856break;/* success */2857case SCLD_VANISHED:2858if(--attempts_remaining >0)2859goto retry;2860/* fall through */2861default:2862error("unable to create directory for%s", newrefname);2863return-1;2864}28652866if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2867if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2868/*2869 * rename(a, b) when b is an existing2870 * directory ought to result in ISDIR, but2871 * Solaris 5.8 gives ENOTDIR. Sheesh.2872 */2873if(remove_empty_directories(git_path("logs/%s", newrefname))) {2874error("Directory not empty: logs/%s", newrefname);2875return-1;2876}2877goto retry;2878}else if(errno == ENOENT && --attempts_remaining >0) {2879/*2880 * Maybe another process just deleted one of2881 * the directories in the path to newrefname.2882 * Try again from the beginning.2883 */2884goto retry;2885}else{2886error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2887 newrefname,strerror(errno));2888return-1;2889}2890}2891return0;2892}28932894static intrename_ref_available(const char*oldname,const char*newname)2895{2896struct string_list skip = STRING_LIST_INIT_NODUP;2897struct strbuf err = STRBUF_INIT;2898int ret;28992900string_list_insert(&skip, oldname);2901 ret = !verify_refname_available(newname, NULL, &skip,2902get_packed_refs(&ref_cache), &err)2903&& !verify_refname_available(newname, NULL, &skip,2904get_loose_refs(&ref_cache), &err);2905if(!ret)2906error("%s", err.buf);29072908string_list_clear(&skip,0);2909strbuf_release(&err);2910return ret;2911}29122913static intwrite_ref_to_lockfile(struct ref_lock *lock,const unsigned char*sha1);2914static intcommit_ref_update(struct ref_lock *lock,2915const unsigned char*sha1,const char*logmsg);29162917intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2918{2919unsigned char sha1[20], orig_sha1[20];2920int flag =0, logmoved =0;2921struct ref_lock *lock;2922struct stat loginfo;2923int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2924const char*symref = NULL;2925struct strbuf err = STRBUF_INIT;29262927if(log &&S_ISLNK(loginfo.st_mode))2928returnerror("reflog for%sis a symlink", oldrefname);29292930 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2931 orig_sha1, &flag);2932if(flag & REF_ISSYMREF)2933returnerror("refname%sis a symbolic ref, renaming it is not supported",2934 oldrefname);2935if(!symref)2936returnerror("refname%snot found", oldrefname);29372938if(!rename_ref_available(oldrefname, newrefname))2939return1;29402941if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2942returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2943 oldrefname,strerror(errno));29442945if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2946error("unable to delete old%s", oldrefname);2947goto rollback;2948}29492950if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2951delete_ref(newrefname, sha1, REF_NODEREF)) {2952if(errno==EISDIR) {2953if(remove_empty_directories(git_path("%s", newrefname))) {2954error("Directory not empty:%s", newrefname);2955goto rollback;2956}2957}else{2958error("unable to delete existing%s", newrefname);2959goto rollback;2960}2961}29622963if(log &&rename_tmp_log(newrefname))2964goto rollback;29652966 logmoved = log;29672968 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2969if(!lock) {2970error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2971strbuf_release(&err);2972goto rollback;2973}2974hashcpy(lock->old_oid.hash, orig_sha1);29752976if(write_ref_to_lockfile(lock, orig_sha1) ||2977commit_ref_update(lock, orig_sha1, logmsg)) {2978error("unable to write current sha1 into%s", newrefname);2979goto rollback;2980}29812982return0;29832984 rollback:2985 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2986if(!lock) {2987error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2988strbuf_release(&err);2989goto rollbacklog;2990}29912992 flag = log_all_ref_updates;2993 log_all_ref_updates =0;2994if(write_ref_to_lockfile(lock, orig_sha1) ||2995commit_ref_update(lock, orig_sha1, NULL))2996error("unable to write current sha1 into%s", oldrefname);2997 log_all_ref_updates = flag;29982999 rollbacklog:3000if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3001error("unable to restore logfile%sfrom%s:%s",3002 oldrefname, newrefname,strerror(errno));3003if(!logmoved && log &&3004rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3005error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3006 oldrefname,strerror(errno));30073008return1;3009}30103011static intclose_ref(struct ref_lock *lock)3012{3013if(close_lock_file(lock->lk))3014return-1;3015return0;3016}30173018static intcommit_ref(struct ref_lock *lock)3019{3020if(commit_lock_file(lock->lk))3021return-1;3022return0;3023}30243025/*3026 * copy the reflog message msg to buf, which has been allocated sufficiently3027 * large, while cleaning up the whitespaces. Especially, convert LF to space,3028 * because reflog file is one line per entry.3029 */3030static intcopy_msg(char*buf,const char*msg)3031{3032char*cp = buf;3033char c;3034int wasspace =1;30353036*cp++ ='\t';3037while((c = *msg++)) {3038if(wasspace &&isspace(c))3039continue;3040 wasspace =isspace(c);3041if(wasspace)3042 c =' ';3043*cp++ = c;3044}3045while(buf < cp &&isspace(cp[-1]))3046 cp--;3047*cp++ ='\n';3048return cp - buf;3049}30503051/* This function must set a meaningful errno on failure */3052intlog_ref_setup(const char*refname,struct strbuf *sb_logfile)3053{3054int logfd, oflags = O_APPEND | O_WRONLY;3055char*logfile;30563057strbuf_git_path(sb_logfile,"logs/%s", refname);3058 logfile = sb_logfile->buf;3059/* make sure the rest of the function can't change "logfile" */3060 sb_logfile = NULL;3061if(log_all_ref_updates &&3062(starts_with(refname,"refs/heads/") ||3063starts_with(refname,"refs/remotes/") ||3064starts_with(refname,"refs/notes/") ||3065!strcmp(refname,"HEAD"))) {3066if(safe_create_leading_directories(logfile) <0) {3067int save_errno = errno;3068error("unable to create directory for%s", logfile);3069 errno = save_errno;3070return-1;3071}3072 oflags |= O_CREAT;3073}30743075 logfd =open(logfile, oflags,0666);3076if(logfd <0) {3077if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3078return0;30793080if(errno == EISDIR) {3081if(remove_empty_directories(logfile)) {3082int save_errno = errno;3083error("There are still logs under '%s'",3084 logfile);3085 errno = save_errno;3086return-1;3087}3088 logfd =open(logfile, oflags,0666);3089}30903091if(logfd <0) {3092int save_errno = errno;3093error("Unable to append to%s:%s", logfile,3094strerror(errno));3095 errno = save_errno;3096return-1;3097}3098}30993100adjust_shared_perm(logfile);3101close(logfd);3102return0;3103}31043105static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3106const unsigned char*new_sha1,3107const char*committer,const char*msg)3108{3109int msglen, written;3110unsigned maxlen, len;3111char*logrec;31123113 msglen = msg ?strlen(msg) :0;3114 maxlen =strlen(committer) + msglen +100;3115 logrec =xmalloc(maxlen);3116 len =sprintf(logrec,"%s %s %s\n",3117sha1_to_hex(old_sha1),3118sha1_to_hex(new_sha1),3119 committer);3120if(msglen)3121 len +=copy_msg(logrec + len -1, msg) -1;31223123 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3124free(logrec);3125if(written != len)3126return-1;31273128return0;3129}31303131static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3132const unsigned char*new_sha1,const char*msg,3133struct strbuf *sb_log_file)3134{3135int logfd, result, oflags = O_APPEND | O_WRONLY;3136char*log_file;31373138if(log_all_ref_updates <0)3139 log_all_ref_updates = !is_bare_repository();31403141 result =log_ref_setup(refname, sb_log_file);3142if(result)3143return result;3144 log_file = sb_log_file->buf;3145/* make sure the rest of the function can't change "log_file" */3146 sb_log_file = NULL;31473148 logfd =open(log_file, oflags);3149if(logfd <0)3150return0;3151 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3152git_committer_info(0), msg);3153if(result) {3154int save_errno = errno;3155close(logfd);3156error("Unable to append to%s", log_file);3157 errno = save_errno;3158return-1;3159}3160if(close(logfd)) {3161int save_errno = errno;3162error("Unable to append to%s", log_file);3163 errno = save_errno;3164return-1;3165}3166return0;3167}31683169static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3170const unsigned char*new_sha1,const char*msg)3171{3172struct strbuf sb = STRBUF_INIT;3173int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb);3174strbuf_release(&sb);3175return ret;3176}31773178intis_branch(const char*refname)3179{3180return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3181}31823183/*3184 * Write sha1 into the open lockfile, then close the lockfile. On3185 * errors, rollback the lockfile and set errno to reflect the problem.3186 */3187static intwrite_ref_to_lockfile(struct ref_lock *lock,3188const unsigned char*sha1)3189{3190static char term ='\n';3191struct object *o;31923193 o =parse_object(sha1);3194if(!o) {3195error("Trying to write ref%swith nonexistent object%s",3196 lock->ref_name,sha1_to_hex(sha1));3197unlock_ref(lock);3198 errno = EINVAL;3199return-1;3200}3201if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3202error("Trying to write non-commit object%sto branch%s",3203sha1_to_hex(sha1), lock->ref_name);3204unlock_ref(lock);3205 errno = EINVAL;3206return-1;3207}3208if(write_in_full(lock->lk->fd,sha1_to_hex(sha1),40) !=40||3209write_in_full(lock->lk->fd, &term,1) !=1||3210close_ref(lock) <0) {3211int save_errno = errno;3212error("Couldn't write%s", lock->lk->filename.buf);3213unlock_ref(lock);3214 errno = save_errno;3215return-1;3216}3217return0;3218}32193220/*3221 * Commit a change to a loose reference that has already been written3222 * to the loose reference lockfile. Also update the reflogs if3223 * necessary, using the specified lockmsg (which can be NULL).3224 */3225static intcommit_ref_update(struct ref_lock *lock,3226const unsigned char*sha1,const char*logmsg)3227{3228clear_loose_ref_cache(&ref_cache);3229if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg) <0||3230(strcmp(lock->ref_name, lock->orig_ref_name) &&3231log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg) <0)) {3232unlock_ref(lock);3233return-1;3234}3235if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3236/*3237 * Special hack: If a branch is updated directly and HEAD3238 * points to it (may happen on the remote side of a push3239 * for example) then logically the HEAD reflog should be3240 * updated too.3241 * A generic solution implies reverse symref information,3242 * but finding all symrefs pointing to the given branch3243 * would be rather costly for this rare event (the direct3244 * update of a branch) to be worth it. So let's cheat and3245 * check with HEAD only which should cover 99% of all usage3246 * scenarios (even 100% of the default ones).3247 */3248unsigned char head_sha1[20];3249int head_flag;3250const char*head_ref;3251 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3252 head_sha1, &head_flag);3253if(head_ref && (head_flag & REF_ISSYMREF) &&3254!strcmp(head_ref, lock->ref_name))3255log_ref_write("HEAD", lock->old_oid.hash, sha1, logmsg);3256}3257if(commit_ref(lock)) {3258error("Couldn't set%s", lock->ref_name);3259unlock_ref(lock);3260return-1;3261}3262unlock_ref(lock);3263return0;3264}32653266intcreate_symref(const char*ref_target,const char*refs_heads_master,3267const char*logmsg)3268{3269const char*lockpath;3270char ref[1000];3271int fd, len, written;3272char*git_HEAD =git_pathdup("%s", ref_target);3273unsigned char old_sha1[20], new_sha1[20];32743275if(logmsg &&read_ref(ref_target, old_sha1))3276hashclr(old_sha1);32773278if(safe_create_leading_directories(git_HEAD) <0)3279returnerror("unable to create directory for%s", git_HEAD);32803281#ifndef NO_SYMLINK_HEAD3282if(prefer_symlink_refs) {3283unlink(git_HEAD);3284if(!symlink(refs_heads_master, git_HEAD))3285goto done;3286fprintf(stderr,"no symlink - falling back to symbolic ref\n");3287}3288#endif32893290 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3291if(sizeof(ref) <= len) {3292error("refname too long:%s", refs_heads_master);3293goto error_free_return;3294}3295 lockpath =mkpath("%s.lock", git_HEAD);3296 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3297if(fd <0) {3298error("Unable to open%sfor writing", lockpath);3299goto error_free_return;3300}3301 written =write_in_full(fd, ref, len);3302if(close(fd) !=0|| written != len) {3303error("Unable to write to%s", lockpath);3304goto error_unlink_return;3305}3306if(rename(lockpath, git_HEAD) <0) {3307error("Unable to create%s", git_HEAD);3308goto error_unlink_return;3309}3310if(adjust_shared_perm(git_HEAD)) {3311error("Unable to fix permissions on%s", lockpath);3312 error_unlink_return:3313unlink_or_warn(lockpath);3314 error_free_return:3315free(git_HEAD);3316return-1;3317}33183319#ifndef NO_SYMLINK_HEAD3320 done:3321#endif3322if(logmsg && !read_ref(refs_heads_master, new_sha1))3323log_ref_write(ref_target, old_sha1, new_sha1, logmsg);33243325free(git_HEAD);3326return0;3327}33283329struct read_ref_at_cb {3330const char*refname;3331unsigned long at_time;3332int cnt;3333int reccnt;3334unsigned char*sha1;3335int found_it;33363337unsigned char osha1[20];3338unsigned char nsha1[20];3339int tz;3340unsigned long date;3341char**msg;3342unsigned long*cutoff_time;3343int*cutoff_tz;3344int*cutoff_cnt;3345};33463347static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3348const char*email,unsigned long timestamp,int tz,3349const char*message,void*cb_data)3350{3351struct read_ref_at_cb *cb = cb_data;33523353 cb->reccnt++;3354 cb->tz = tz;3355 cb->date = timestamp;33563357if(timestamp <= cb->at_time || cb->cnt ==0) {3358if(cb->msg)3359*cb->msg =xstrdup(message);3360if(cb->cutoff_time)3361*cb->cutoff_time = timestamp;3362if(cb->cutoff_tz)3363*cb->cutoff_tz = tz;3364if(cb->cutoff_cnt)3365*cb->cutoff_cnt = cb->reccnt -1;3366/*3367 * we have not yet updated cb->[n|o]sha1 so they still3368 * hold the values for the previous record.3369 */3370if(!is_null_sha1(cb->osha1)) {3371hashcpy(cb->sha1, nsha1);3372if(hashcmp(cb->osha1, nsha1))3373warning("Log for ref%shas gap after%s.",3374 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3375}3376else if(cb->date == cb->at_time)3377hashcpy(cb->sha1, nsha1);3378else if(hashcmp(nsha1, cb->sha1))3379warning("Log for ref%sunexpectedly ended on%s.",3380 cb->refname,show_date(cb->date, cb->tz,3381DATE_MODE(RFC2822)));3382hashcpy(cb->osha1, osha1);3383hashcpy(cb->nsha1, nsha1);3384 cb->found_it =1;3385return1;3386}3387hashcpy(cb->osha1, osha1);3388hashcpy(cb->nsha1, nsha1);3389if(cb->cnt >0)3390 cb->cnt--;3391return0;3392}33933394static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3395const char*email,unsigned long timestamp,3396int tz,const char*message,void*cb_data)3397{3398struct read_ref_at_cb *cb = cb_data;33993400if(cb->msg)3401*cb->msg =xstrdup(message);3402if(cb->cutoff_time)3403*cb->cutoff_time = timestamp;3404if(cb->cutoff_tz)3405*cb->cutoff_tz = tz;3406if(cb->cutoff_cnt)3407*cb->cutoff_cnt = cb->reccnt;3408hashcpy(cb->sha1, osha1);3409if(is_null_sha1(cb->sha1))3410hashcpy(cb->sha1, nsha1);3411/* We just want the first entry */3412return1;3413}34143415intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3416unsigned char*sha1,char**msg,3417unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3418{3419struct read_ref_at_cb cb;34203421memset(&cb,0,sizeof(cb));3422 cb.refname = refname;3423 cb.at_time = at_time;3424 cb.cnt = cnt;3425 cb.msg = msg;3426 cb.cutoff_time = cutoff_time;3427 cb.cutoff_tz = cutoff_tz;3428 cb.cutoff_cnt = cutoff_cnt;3429 cb.sha1 = sha1;34303431for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);34323433if(!cb.reccnt) {3434if(flags & GET_SHA1_QUIETLY)3435exit(128);3436else3437die("Log for%sis empty.", refname);3438}3439if(cb.found_it)3440return0;34413442for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);34433444return1;3445}34463447intreflog_exists(const char*refname)3448{3449struct stat st;34503451return!lstat(git_path("logs/%s", refname), &st) &&3452S_ISREG(st.st_mode);3453}34543455intdelete_reflog(const char*refname)3456{3457returnremove_path(git_path("logs/%s", refname));3458}34593460static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3461{3462unsigned char osha1[20], nsha1[20];3463char*email_end, *message;3464unsigned long timestamp;3465int tz;34663467/* old SP new SP name <email> SP time TAB msg LF */3468if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3469get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3470get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3471!(email_end =strchr(sb->buf +82,'>')) ||3472 email_end[1] !=' '||3473!(timestamp =strtoul(email_end +2, &message,10)) ||3474!message || message[0] !=' '||3475(message[1] !='+'&& message[1] !='-') ||3476!isdigit(message[2]) || !isdigit(message[3]) ||3477!isdigit(message[4]) || !isdigit(message[5]))3478return0;/* corrupt? */3479 email_end[1] ='\0';3480 tz =strtol(message +1, NULL,10);3481if(message[6] !='\t')3482 message +=6;3483else3484 message +=7;3485returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3486}34873488static char*find_beginning_of_line(char*bob,char*scan)3489{3490while(bob < scan && *(--scan) !='\n')3491;/* keep scanning backwards */3492/*3493 * Return either beginning of the buffer, or LF at the end of3494 * the previous line.3495 */3496return scan;3497}34983499intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3500{3501struct strbuf sb = STRBUF_INIT;3502FILE*logfp;3503long pos;3504int ret =0, at_tail =1;35053506 logfp =fopen(git_path("logs/%s", refname),"r");3507if(!logfp)3508return-1;35093510/* Jump to the end */3511if(fseek(logfp,0, SEEK_END) <0)3512returnerror("cannot seek back reflog for%s:%s",3513 refname,strerror(errno));3514 pos =ftell(logfp);3515while(!ret &&0< pos) {3516int cnt;3517size_t nread;3518char buf[BUFSIZ];3519char*endp, *scanp;35203521/* Fill next block from the end */3522 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3523if(fseek(logfp, pos - cnt, SEEK_SET))3524returnerror("cannot seek back reflog for%s:%s",3525 refname,strerror(errno));3526 nread =fread(buf, cnt,1, logfp);3527if(nread !=1)3528returnerror("cannot read%dbytes from reflog for%s:%s",3529 cnt, refname,strerror(errno));3530 pos -= cnt;35313532 scanp = endp = buf + cnt;3533if(at_tail && scanp[-1] =='\n')3534/* Looking at the final LF at the end of the file */3535 scanp--;3536 at_tail =0;35373538while(buf < scanp) {3539/*3540 * terminating LF of the previous line, or the beginning3541 * of the buffer.3542 */3543char*bp;35443545 bp =find_beginning_of_line(buf, scanp);35463547if(*bp =='\n') {3548/*3549 * The newline is the end of the previous line,3550 * so we know we have complete line starting3551 * at (bp + 1). Prefix it onto any prior data3552 * we collected for the line and process it.3553 */3554strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3555 scanp = bp;3556 endp = bp +1;3557 ret =show_one_reflog_ent(&sb, fn, cb_data);3558strbuf_reset(&sb);3559if(ret)3560break;3561}else if(!pos) {3562/*3563 * We are at the start of the buffer, and the3564 * start of the file; there is no previous3565 * line, and we have everything for this one.3566 * Process it, and we can end the loop.3567 */3568strbuf_splice(&sb,0,0, buf, endp - buf);3569 ret =show_one_reflog_ent(&sb, fn, cb_data);3570strbuf_reset(&sb);3571break;3572}35733574if(bp == buf) {3575/*3576 * We are at the start of the buffer, and there3577 * is more file to read backwards. Which means3578 * we are in the middle of a line. Note that we3579 * may get here even if *bp was a newline; that3580 * just means we are at the exact end of the3581 * previous line, rather than some spot in the3582 * middle.3583 *3584 * Save away what we have to be combined with3585 * the data from the next read.3586 */3587strbuf_splice(&sb,0,0, buf, endp - buf);3588break;3589}3590}35913592}3593if(!ret && sb.len)3594die("BUG: reverse reflog parser had leftover data");35953596fclose(logfp);3597strbuf_release(&sb);3598return ret;3599}36003601intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3602{3603FILE*logfp;3604struct strbuf sb = STRBUF_INIT;3605int ret =0;36063607 logfp =fopen(git_path("logs/%s", refname),"r");3608if(!logfp)3609return-1;36103611while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3612 ret =show_one_reflog_ent(&sb, fn, cb_data);3613fclose(logfp);3614strbuf_release(&sb);3615return ret;3616}3617/*3618 * Call fn for each reflog in the namespace indicated by name. name3619 * must be empty or end with '/'. Name will be used as a scratch3620 * space, but its contents will be restored before return.3621 */3622static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3623{3624DIR*d =opendir(git_path("logs/%s", name->buf));3625int retval =0;3626struct dirent *de;3627int oldlen = name->len;36283629if(!d)3630return name->len ? errno :0;36313632while((de =readdir(d)) != NULL) {3633struct stat st;36343635if(de->d_name[0] =='.')3636continue;3637if(ends_with(de->d_name,".lock"))3638continue;3639strbuf_addstr(name, de->d_name);3640if(stat(git_path("logs/%s", name->buf), &st) <0) {3641;/* silently ignore */3642}else{3643if(S_ISDIR(st.st_mode)) {3644strbuf_addch(name,'/');3645 retval =do_for_each_reflog(name, fn, cb_data);3646}else{3647struct object_id oid;36483649if(read_ref_full(name->buf,0, oid.hash, NULL))3650 retval =error("bad ref for%s", name->buf);3651else3652 retval =fn(name->buf, &oid,0, cb_data);3653}3654if(retval)3655break;3656}3657strbuf_setlen(name, oldlen);3658}3659closedir(d);3660return retval;3661}36623663intfor_each_reflog(each_ref_fn fn,void*cb_data)3664{3665int retval;3666struct strbuf name;3667strbuf_init(&name, PATH_MAX);3668 retval =do_for_each_reflog(&name, fn, cb_data);3669strbuf_release(&name);3670return retval;3671}36723673/**3674 * Information needed for a single ref update. Set new_sha1 to the new3675 * value or to null_sha1 to delete the ref. To check the old value3676 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3677 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3678 * not exist before update.3679 */3680struct ref_update {3681/*3682 * If (flags & REF_HAVE_NEW), set the reference to this value:3683 */3684unsigned char new_sha1[20];3685/*3686 * If (flags & REF_HAVE_OLD), check that the reference3687 * previously had this value:3688 */3689unsigned char old_sha1[20];3690/*3691 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3692 * REF_DELETING, and REF_ISPRUNING:3693 */3694unsigned int flags;3695struct ref_lock *lock;3696int type;3697char*msg;3698const char refname[FLEX_ARRAY];3699};37003701/*3702 * Transaction states.3703 * OPEN: The transaction is in a valid state and can accept new updates.3704 * An OPEN transaction can be committed.3705 * CLOSED: A closed transaction is no longer active and no other operations3706 * than free can be used on it in this state.3707 * A transaction can either become closed by successfully committing3708 * an active transaction or if there is a failure while building3709 * the transaction thus rendering it failed/inactive.3710 */3711enum ref_transaction_state {3712 REF_TRANSACTION_OPEN =0,3713 REF_TRANSACTION_CLOSED =13714};37153716/*3717 * Data structure for holding a reference transaction, which can3718 * consist of checks and updates to multiple references, carried out3719 * as atomically as possible. This structure is opaque to callers.3720 */3721struct ref_transaction {3722struct ref_update **updates;3723size_t alloc;3724size_t nr;3725enum ref_transaction_state state;3726};37273728struct ref_transaction *ref_transaction_begin(struct strbuf *err)3729{3730assert(err);37313732returnxcalloc(1,sizeof(struct ref_transaction));3733}37343735voidref_transaction_free(struct ref_transaction *transaction)3736{3737int i;37383739if(!transaction)3740return;37413742for(i =0; i < transaction->nr; i++) {3743free(transaction->updates[i]->msg);3744free(transaction->updates[i]);3745}3746free(transaction->updates);3747free(transaction);3748}37493750static struct ref_update *add_update(struct ref_transaction *transaction,3751const char*refname)3752{3753size_t len =strlen(refname);3754struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);37553756strcpy((char*)update->refname, refname);3757ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3758 transaction->updates[transaction->nr++] = update;3759return update;3760}37613762intref_transaction_update(struct ref_transaction *transaction,3763const char*refname,3764const unsigned char*new_sha1,3765const unsigned char*old_sha1,3766unsigned int flags,const char*msg,3767struct strbuf *err)3768{3769struct ref_update *update;37703771assert(err);37723773if(transaction->state != REF_TRANSACTION_OPEN)3774die("BUG: update called for transaction that is not open");37753776if(new_sha1 && !is_null_sha1(new_sha1) &&3777check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3778strbuf_addf(err,"refusing to update ref with bad name%s",3779 refname);3780return-1;3781}37823783 update =add_update(transaction, refname);3784if(new_sha1) {3785hashcpy(update->new_sha1, new_sha1);3786 flags |= REF_HAVE_NEW;3787}3788if(old_sha1) {3789hashcpy(update->old_sha1, old_sha1);3790 flags |= REF_HAVE_OLD;3791}3792 update->flags = flags;3793if(msg)3794 update->msg =xstrdup(msg);3795return0;3796}37973798intref_transaction_create(struct ref_transaction *transaction,3799const char*refname,3800const unsigned char*new_sha1,3801unsigned int flags,const char*msg,3802struct strbuf *err)3803{3804if(!new_sha1 ||is_null_sha1(new_sha1))3805die("BUG: create called without valid new_sha1");3806returnref_transaction_update(transaction, refname, new_sha1,3807 null_sha1, flags, msg, err);3808}38093810intref_transaction_delete(struct ref_transaction *transaction,3811const char*refname,3812const unsigned char*old_sha1,3813unsigned int flags,const char*msg,3814struct strbuf *err)3815{3816if(old_sha1 &&is_null_sha1(old_sha1))3817die("BUG: delete called with old_sha1 set to zeros");3818returnref_transaction_update(transaction, refname,3819 null_sha1, old_sha1,3820 flags, msg, err);3821}38223823intref_transaction_verify(struct ref_transaction *transaction,3824const char*refname,3825const unsigned char*old_sha1,3826unsigned int flags,3827struct strbuf *err)3828{3829if(!old_sha1)3830die("BUG: verify called with old_sha1 set to NULL");3831returnref_transaction_update(transaction, refname,3832 NULL, old_sha1,3833 flags, NULL, err);3834}38353836intupdate_ref(const char*msg,const char*refname,3837const unsigned char*new_sha1,const unsigned char*old_sha1,3838unsigned int flags,enum action_on_err onerr)3839{3840struct ref_transaction *t;3841struct strbuf err = STRBUF_INIT;38423843 t =ref_transaction_begin(&err);3844if(!t ||3845ref_transaction_update(t, refname, new_sha1, old_sha1,3846 flags, msg, &err) ||3847ref_transaction_commit(t, &err)) {3848const char*str ="update_ref failed for ref '%s':%s";38493850ref_transaction_free(t);3851switch(onerr) {3852case UPDATE_REFS_MSG_ON_ERR:3853error(str, refname, err.buf);3854break;3855case UPDATE_REFS_DIE_ON_ERR:3856die(str, refname, err.buf);3857break;3858case UPDATE_REFS_QUIET_ON_ERR:3859break;3860}3861strbuf_release(&err);3862return1;3863}3864strbuf_release(&err);3865ref_transaction_free(t);3866return0;3867}38683869static intref_update_reject_duplicates(struct string_list *refnames,3870struct strbuf *err)3871{3872int i, n = refnames->nr;38733874assert(err);38753876for(i =1; i < n; i++)3877if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3878strbuf_addf(err,3879"Multiple updates for ref '%s' not allowed.",3880 refnames->items[i].string);3881return1;3882}3883return0;3884}38853886intref_transaction_commit(struct ref_transaction *transaction,3887struct strbuf *err)3888{3889int ret =0, i;3890int n = transaction->nr;3891struct ref_update **updates = transaction->updates;3892struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3893struct string_list_item *ref_to_delete;3894struct string_list affected_refnames = STRING_LIST_INIT_NODUP;38953896assert(err);38973898if(transaction->state != REF_TRANSACTION_OPEN)3899die("BUG: commit called for transaction that is not open");39003901if(!n) {3902 transaction->state = REF_TRANSACTION_CLOSED;3903return0;3904}39053906/* Fail if a refname appears more than once in the transaction: */3907for(i =0; i < n; i++)3908string_list_append(&affected_refnames, updates[i]->refname);3909string_list_sort(&affected_refnames);3910if(ref_update_reject_duplicates(&affected_refnames, err)) {3911 ret = TRANSACTION_GENERIC_ERROR;3912goto cleanup;3913}39143915/*3916 * Acquire all locks, verify old values if provided, check3917 * that new values are valid, and write new values to the3918 * lockfiles, ready to be activated. Only keep one lockfile3919 * open at a time to avoid running out of file descriptors.3920 */3921for(i =0; i < n; i++) {3922struct ref_update *update = updates[i];39233924if((update->flags & REF_HAVE_NEW) &&3925is_null_sha1(update->new_sha1))3926 update->flags |= REF_DELETING;3927 update->lock =lock_ref_sha1_basic(3928 update->refname,3929((update->flags & REF_HAVE_OLD) ?3930 update->old_sha1 : NULL),3931&affected_refnames, NULL,3932 update->flags,3933&update->type,3934 err);3935if(!update->lock) {3936char*reason;39373938 ret = (errno == ENOTDIR)3939? TRANSACTION_NAME_CONFLICT3940: TRANSACTION_GENERIC_ERROR;3941 reason =strbuf_detach(err, NULL);3942strbuf_addf(err,"cannot lock ref '%s':%s",3943 update->refname, reason);3944free(reason);3945goto cleanup;3946}3947if((update->flags & REF_HAVE_NEW) &&3948!(update->flags & REF_DELETING)) {3949int overwriting_symref = ((update->type & REF_ISSYMREF) &&3950(update->flags & REF_NODEREF));39513952if(!overwriting_symref &&3953!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3954/*3955 * The reference already has the desired3956 * value, so we don't need to write it.3957 */3958}else if(write_ref_to_lockfile(update->lock,3959 update->new_sha1)) {3960/*3961 * The lock was freed upon failure of3962 * write_ref_to_lockfile():3963 */3964 update->lock = NULL;3965strbuf_addf(err,"cannot update the ref '%s'.",3966 update->refname);3967 ret = TRANSACTION_GENERIC_ERROR;3968goto cleanup;3969}else{3970 update->flags |= REF_NEEDS_COMMIT;3971}3972}3973if(!(update->flags & REF_NEEDS_COMMIT)) {3974/*3975 * We didn't have to write anything to the lockfile.3976 * Close it to free up the file descriptor:3977 */3978if(close_ref(update->lock)) {3979strbuf_addf(err,"Couldn't close%s.lock",3980 update->refname);3981goto cleanup;3982}3983}3984}39853986/* Perform updates first so live commits remain referenced */3987for(i =0; i < n; i++) {3988struct ref_update *update = updates[i];39893990if(update->flags & REF_NEEDS_COMMIT) {3991if(commit_ref_update(update->lock,3992 update->new_sha1, update->msg)) {3993/* freed by commit_ref_update(): */3994 update->lock = NULL;3995strbuf_addf(err,"Cannot update the ref '%s'.",3996 update->refname);3997 ret = TRANSACTION_GENERIC_ERROR;3998goto cleanup;3999}else{4000/* freed by commit_ref_update(): */4001 update->lock = NULL;4002}4003}4004}40054006/* Perform deletes now that updates are safely completed */4007for(i =0; i < n; i++) {4008struct ref_update *update = updates[i];40094010if(update->flags & REF_DELETING) {4011if(delete_ref_loose(update->lock, update->type, err)) {4012 ret = TRANSACTION_GENERIC_ERROR;4013goto cleanup;4014}40154016if(!(update->flags & REF_ISPRUNING))4017string_list_append(&refs_to_delete,4018 update->lock->ref_name);4019}4020}40214022if(repack_without_refs(&refs_to_delete, err)) {4023 ret = TRANSACTION_GENERIC_ERROR;4024goto cleanup;4025}4026for_each_string_list_item(ref_to_delete, &refs_to_delete)4027unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4028clear_loose_ref_cache(&ref_cache);40294030cleanup:4031 transaction->state = REF_TRANSACTION_CLOSED;40324033for(i =0; i < n; i++)4034if(updates[i]->lock)4035unlock_ref(updates[i]->lock);4036string_list_clear(&refs_to_delete,0);4037string_list_clear(&affected_refnames,0);4038return ret;4039}40404041char*shorten_unambiguous_ref(const char*refname,int strict)4042{4043int i;4044static char**scanf_fmts;4045static int nr_rules;4046char*short_name;40474048if(!nr_rules) {4049/*4050 * Pre-generate scanf formats from ref_rev_parse_rules[].4051 * Generate a format suitable for scanf from a4052 * ref_rev_parse_rules rule by interpolating "%s" at the4053 * location of the "%.*s".4054 */4055size_t total_len =0;4056size_t offset =0;40574058/* the rule list is NULL terminated, count them first */4059for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4060/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4061 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;40624063 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);40644065 offset =0;4066for(i =0; i < nr_rules; i++) {4067assert(offset < total_len);4068 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4069 offset +=snprintf(scanf_fmts[i], total_len - offset,4070 ref_rev_parse_rules[i],2,"%s") +1;4071}4072}40734074/* bail out if there are no rules */4075if(!nr_rules)4076returnxstrdup(refname);40774078/* buffer for scanf result, at most refname must fit */4079 short_name =xstrdup(refname);40804081/* skip first rule, it will always match */4082for(i = nr_rules -1; i >0; --i) {4083int j;4084int rules_to_fail = i;4085int short_name_len;40864087if(1!=sscanf(refname, scanf_fmts[i], short_name))4088continue;40894090 short_name_len =strlen(short_name);40914092/*4093 * in strict mode, all (except the matched one) rules4094 * must fail to resolve to a valid non-ambiguous ref4095 */4096if(strict)4097 rules_to_fail = nr_rules;40984099/*4100 * check if the short name resolves to a valid ref,4101 * but use only rules prior to the matched one4102 */4103for(j =0; j < rules_to_fail; j++) {4104const char*rule = ref_rev_parse_rules[j];4105char refname[PATH_MAX];41064107/* skip matched rule */4108if(i == j)4109continue;41104111/*4112 * the short name is ambiguous, if it resolves4113 * (with this previous rule) to a valid ref4114 * read_ref() returns 0 on success4115 */4116mksnpath(refname,sizeof(refname),4117 rule, short_name_len, short_name);4118if(ref_exists(refname))4119break;4120}41214122/*4123 * short name is non-ambiguous if all previous rules4124 * haven't resolved to a valid ref4125 */4126if(j == rules_to_fail)4127return short_name;4128}41294130free(short_name);4131returnxstrdup(refname);4132}41334134static struct string_list *hide_refs;41354136intparse_hide_refs_config(const char*var,const char*value,const char*section)4137{4138if(!strcmp("transfer.hiderefs", var) ||4139/* NEEDSWORK: use parse_config_key() once both are merged */4140(starts_with(var, section) && var[strlen(section)] =='.'&&4141!strcmp(var +strlen(section),".hiderefs"))) {4142char*ref;4143int len;41444145if(!value)4146returnconfig_error_nonbool(var);4147 ref =xstrdup(value);4148 len =strlen(ref);4149while(len && ref[len -1] =='/')4150 ref[--len] ='\0';4151if(!hide_refs) {4152 hide_refs =xcalloc(1,sizeof(*hide_refs));4153 hide_refs->strdup_strings =1;4154}4155string_list_append(hide_refs, ref);4156}4157return0;4158}41594160intref_is_hidden(const char*refname)4161{4162struct string_list_item *item;41634164if(!hide_refs)4165return0;4166for_each_string_list_item(item, hide_refs) {4167int len;4168if(!starts_with(refname, item->string))4169continue;4170 len =strlen(item->string);4171if(!refname[len] || refname[len] =='/')4172return1;4173}4174return0;4175}41764177struct expire_reflog_cb {4178unsigned int flags;4179 reflog_expiry_should_prune_fn *should_prune_fn;4180void*policy_cb;4181FILE*newlog;4182unsigned char last_kept_sha1[20];4183};41844185static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4186const char*email,unsigned long timestamp,int tz,4187const char*message,void*cb_data)4188{4189struct expire_reflog_cb *cb = cb_data;4190struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;41914192if(cb->flags & EXPIRE_REFLOGS_REWRITE)4193 osha1 = cb->last_kept_sha1;41944195if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4196 message, policy_cb)) {4197if(!cb->newlog)4198printf("would prune%s", message);4199else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4200printf("prune%s", message);4201}else{4202if(cb->newlog) {4203fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4204sha1_to_hex(osha1),sha1_to_hex(nsha1),4205 email, timestamp, tz, message);4206hashcpy(cb->last_kept_sha1, nsha1);4207}4208if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4209printf("keep%s", message);4210}4211return0;4212}42134214intreflog_expire(const char*refname,const unsigned char*sha1,4215unsigned int flags,4216 reflog_expiry_prepare_fn prepare_fn,4217 reflog_expiry_should_prune_fn should_prune_fn,4218 reflog_expiry_cleanup_fn cleanup_fn,4219void*policy_cb_data)4220{4221static struct lock_file reflog_lock;4222struct expire_reflog_cb cb;4223struct ref_lock *lock;4224char*log_file;4225int status =0;4226int type;4227struct strbuf err = STRBUF_INIT;42284229memset(&cb,0,sizeof(cb));4230 cb.flags = flags;4231 cb.policy_cb = policy_cb_data;4232 cb.should_prune_fn = should_prune_fn;42334234/*4235 * The reflog file is locked by holding the lock on the4236 * reference itself, plus we might need to update the4237 * reference if --updateref was specified:4238 */4239 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4240if(!lock) {4241error("cannot lock ref '%s':%s", refname, err.buf);4242strbuf_release(&err);4243return-1;4244}4245if(!reflog_exists(refname)) {4246unlock_ref(lock);4247return0;4248}42494250 log_file =git_pathdup("logs/%s", refname);4251if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4252/*4253 * Even though holding $GIT_DIR/logs/$reflog.lock has4254 * no locking implications, we use the lock_file4255 * machinery here anyway because it does a lot of the4256 * work we need, including cleaning up if the program4257 * exits unexpectedly.4258 */4259if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4260struct strbuf err = STRBUF_INIT;4261unable_to_lock_message(log_file, errno, &err);4262error("%s", err.buf);4263strbuf_release(&err);4264goto failure;4265}4266 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4267if(!cb.newlog) {4268error("cannot fdopen%s(%s)",4269 reflog_lock.filename.buf,strerror(errno));4270goto failure;4271}4272}42734274(*prepare_fn)(refname, sha1, cb.policy_cb);4275for_each_reflog_ent(refname, expire_reflog_ent, &cb);4276(*cleanup_fn)(cb.policy_cb);42774278if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4279/*4280 * It doesn't make sense to adjust a reference pointed4281 * to by a symbolic ref based on expiring entries in4282 * the symbolic reference's reflog. Nor can we update4283 * a reference if there are no remaining reflog4284 * entries.4285 */4286int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4287!(type & REF_ISSYMREF) &&4288!is_null_sha1(cb.last_kept_sha1);42894290if(close_lock_file(&reflog_lock)) {4291 status |=error("couldn't write%s:%s", log_file,4292strerror(errno));4293}else if(update &&4294(write_in_full(lock->lk->fd,4295sha1_to_hex(cb.last_kept_sha1),40) !=40||4296write_str_in_full(lock->lk->fd,"\n") !=1||4297close_ref(lock) <0)) {4298 status |=error("couldn't write%s",4299 lock->lk->filename.buf);4300rollback_lock_file(&reflog_lock);4301}else if(commit_lock_file(&reflog_lock)) {4302 status |=error("unable to commit reflog '%s' (%s)",4303 log_file,strerror(errno));4304}else if(update &&commit_ref(lock)) {4305 status |=error("couldn't set%s", lock->ref_name);4306}4307}4308free(log_file);4309unlock_ref(lock);4310return status;43114312 failure:4313rollback_lock_file(&reflog_lock);4314free(log_file);4315unlock_ref(lock);4316return-1;4317}