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{1376if(*refs->name) {1377hashclr(sha1);1378 flag =0;1379if(resolve_gitlink_ref(refs->name, refname.buf, sha1) <0) {1380hashclr(sha1);1381 flag |= REF_ISBROKEN;1382}1383}else if(read_ref_full(refname.buf,1384 RESOLVE_REF_READING,1385 sha1, &flag)) {1386hashclr(sha1);1387 flag |= REF_ISBROKEN;1388}1389if(check_refname_format(refname.buf,1390 REFNAME_ALLOW_ONELEVEL)) {1391if(!refname_is_safe(refname.buf))1392die("loose refname is dangerous:%s", refname.buf);1393hashclr(sha1);1394 flag |= REF_BAD_NAME | REF_ISBROKEN;1395}1396add_entry_to_dir(dir,1397create_ref_entry(refname.buf, sha1, flag,0));1398}1399strbuf_setlen(&refname, dirnamelen);1400}1401strbuf_release(&refname);1402closedir(d);1403}14041405static struct ref_dir *get_loose_refs(struct ref_cache *refs)1406{1407if(!refs->loose) {1408/*1409 * Mark the top-level directory complete because we1410 * are about to read the only subdirectory that can1411 * hold references:1412 */1413 refs->loose =create_dir_entry(refs,"",0,0);1414/*1415 * Create an incomplete entry for "refs/":1416 */1417add_entry_to_dir(get_ref_dir(refs->loose),1418create_dir_entry(refs,"refs/",5,1));1419}1420returnget_ref_dir(refs->loose);1421}14221423/* We allow "recursive" symbolic refs. Only within reason, though */1424#define MAXDEPTH 51425#define MAXREFLEN (1024)14261427/*1428 * Called by resolve_gitlink_ref_recursive() after it failed to read1429 * from the loose refs in ref_cache refs. Find <refname> in the1430 * packed-refs file for the submodule.1431 */1432static intresolve_gitlink_packed_ref(struct ref_cache *refs,1433const char*refname,unsigned char*sha1)1434{1435struct ref_entry *ref;1436struct ref_dir *dir =get_packed_refs(refs);14371438 ref =find_ref(dir, refname);1439if(ref == NULL)1440return-1;14411442hashcpy(sha1, ref->u.value.oid.hash);1443return0;1444}14451446static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1447const char*refname,unsigned char*sha1,1448int recursion)1449{1450int fd, len;1451char buffer[128], *p;1452const char*path;14531454if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1455return-1;1456 path = *refs->name1457?git_path_submodule(refs->name,"%s", refname)1458:git_path("%s", refname);1459 fd =open(path, O_RDONLY);1460if(fd <0)1461returnresolve_gitlink_packed_ref(refs, refname, sha1);14621463 len =read(fd, buffer,sizeof(buffer)-1);1464close(fd);1465if(len <0)1466return-1;1467while(len &&isspace(buffer[len-1]))1468 len--;1469 buffer[len] =0;14701471/* Was it a detached head or an old-fashioned symlink? */1472if(!get_sha1_hex(buffer, sha1))1473return0;14741475/* Symref? */1476if(strncmp(buffer,"ref:",4))1477return-1;1478 p = buffer +4;1479while(isspace(*p))1480 p++;14811482returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1483}14841485intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1486{1487int len =strlen(path), retval;1488char*submodule;1489struct ref_cache *refs;14901491while(len && path[len-1] =='/')1492 len--;1493if(!len)1494return-1;1495 submodule =xstrndup(path, len);1496 refs =get_ref_cache(submodule);1497free(submodule);14981499 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1500return retval;1501}15021503/*1504 * Return the ref_entry for the given refname from the packed1505 * references. If it does not exist, return NULL.1506 */1507static struct ref_entry *get_packed_ref(const char*refname)1508{1509returnfind_ref(get_packed_refs(&ref_cache), refname);1510}15111512/*1513 * A loose ref file doesn't exist; check for a packed ref. The1514 * options are forwarded from resolve_safe_unsafe().1515 */1516static intresolve_missing_loose_ref(const char*refname,1517int resolve_flags,1518unsigned char*sha1,1519int*flags)1520{1521struct ref_entry *entry;15221523/*1524 * The loose reference file does not exist; check for a packed1525 * reference.1526 */1527 entry =get_packed_ref(refname);1528if(entry) {1529hashcpy(sha1, entry->u.value.oid.hash);1530if(flags)1531*flags |= REF_ISPACKED;1532return0;1533}1534/* The reference is not a packed reference, either. */1535if(resolve_flags & RESOLVE_REF_READING) {1536 errno = ENOENT;1537return-1;1538}else{1539hashclr(sha1);1540return0;1541}1542}15431544/* This function needs to return a meaningful errno on failure */1545static const char*resolve_ref_unsafe_1(const char*refname,1546int resolve_flags,1547unsigned char*sha1,1548int*flags,1549struct strbuf *sb_path)1550{1551int depth = MAXDEPTH;1552 ssize_t len;1553char buffer[256];1554static char refname_buffer[256];1555int bad_name =0;15561557if(flags)1558*flags =0;15591560if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1561if(flags)1562*flags |= REF_BAD_NAME;15631564if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1565!refname_is_safe(refname)) {1566 errno = EINVAL;1567return NULL;1568}1569/*1570 * dwim_ref() uses REF_ISBROKEN to distinguish between1571 * missing refs and refs that were present but invalid,1572 * to complain about the latter to stderr.1573 *1574 * We don't know whether the ref exists, so don't set1575 * REF_ISBROKEN yet.1576 */1577 bad_name =1;1578}1579for(;;) {1580const char*path;1581struct stat st;1582char*buf;1583int fd;15841585if(--depth <0) {1586 errno = ELOOP;1587return NULL;1588}15891590strbuf_reset(sb_path);1591strbuf_git_path(sb_path,"%s", refname);1592 path = sb_path->buf;15931594/*1595 * We might have to loop back here to avoid a race1596 * condition: first we lstat() the file, then we try1597 * to read it as a link or as a file. But if somebody1598 * changes the type of the file (file <-> directory1599 * <-> symlink) between the lstat() and reading, then1600 * we don't want to report that as an error but rather1601 * try again starting with the lstat().1602 */1603 stat_ref:1604if(lstat(path, &st) <0) {1605if(errno != ENOENT)1606return NULL;1607if(resolve_missing_loose_ref(refname, resolve_flags,1608 sha1, flags))1609return NULL;1610if(bad_name) {1611hashclr(sha1);1612if(flags)1613*flags |= REF_ISBROKEN;1614}1615return refname;1616}16171618/* Follow "normalized" - ie "refs/.." symlinks by hand */1619if(S_ISLNK(st.st_mode)) {1620 len =readlink(path, buffer,sizeof(buffer)-1);1621if(len <0) {1622if(errno == ENOENT || errno == EINVAL)1623/* inconsistent with lstat; retry */1624goto stat_ref;1625else1626return NULL;1627}1628 buffer[len] =0;1629if(starts_with(buffer,"refs/") &&1630!check_refname_format(buffer,0)) {1631strcpy(refname_buffer, buffer);1632 refname = refname_buffer;1633if(flags)1634*flags |= REF_ISSYMREF;1635if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1636hashclr(sha1);1637return refname;1638}1639continue;1640}1641}16421643/* Is it a directory? */1644if(S_ISDIR(st.st_mode)) {1645 errno = EISDIR;1646return NULL;1647}16481649/*1650 * Anything else, just open it and try to use it as1651 * a ref1652 */1653 fd =open(path, O_RDONLY);1654if(fd <0) {1655if(errno == ENOENT)1656/* inconsistent with lstat; retry */1657goto stat_ref;1658else1659return NULL;1660}1661 len =read_in_full(fd, buffer,sizeof(buffer)-1);1662if(len <0) {1663int save_errno = errno;1664close(fd);1665 errno = save_errno;1666return NULL;1667}1668close(fd);1669while(len &&isspace(buffer[len-1]))1670 len--;1671 buffer[len] ='\0';16721673/*1674 * Is it a symbolic ref?1675 */1676if(!starts_with(buffer,"ref:")) {1677/*1678 * Please note that FETCH_HEAD has a second1679 * line containing other data.1680 */1681if(get_sha1_hex(buffer, sha1) ||1682(buffer[40] !='\0'&& !isspace(buffer[40]))) {1683if(flags)1684*flags |= REF_ISBROKEN;1685 errno = EINVAL;1686return NULL;1687}1688if(bad_name) {1689hashclr(sha1);1690if(flags)1691*flags |= REF_ISBROKEN;1692}1693return refname;1694}1695if(flags)1696*flags |= REF_ISSYMREF;1697 buf = buffer +4;1698while(isspace(*buf))1699 buf++;1700 refname =strcpy(refname_buffer, buf);1701if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1702hashclr(sha1);1703return refname;1704}1705if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1706if(flags)1707*flags |= REF_ISBROKEN;17081709if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1710!refname_is_safe(buf)) {1711 errno = EINVAL;1712return NULL;1713}1714 bad_name =1;1715}1716}1717}17181719const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1720unsigned char*sha1,int*flags)1721{1722struct strbuf sb_path = STRBUF_INIT;1723const char*ret =resolve_ref_unsafe_1(refname, resolve_flags,1724 sha1, flags, &sb_path);1725strbuf_release(&sb_path);1726return ret;1727}17281729char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1730{1731returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1732}17331734/* The argument to filter_refs */1735struct ref_filter {1736const char*pattern;1737 each_ref_fn *fn;1738void*cb_data;1739};17401741intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1742{1743if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1744return0;1745return-1;1746}17471748intread_ref(const char*refname,unsigned char*sha1)1749{1750returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1751}17521753intref_exists(const char*refname)1754{1755unsigned char sha1[20];1756return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1757}17581759static intfilter_refs(const char*refname,const struct object_id *oid,1760int flags,void*data)1761{1762struct ref_filter *filter = (struct ref_filter *)data;17631764if(wildmatch(filter->pattern, refname,0, NULL))1765return0;1766return filter->fn(refname, oid, flags, filter->cb_data);1767}17681769enum peel_status {1770/* object was peeled successfully: */1771 PEEL_PEELED =0,17721773/*1774 * object cannot be peeled because the named object (or an1775 * object referred to by a tag in the peel chain), does not1776 * exist.1777 */1778 PEEL_INVALID = -1,17791780/* object cannot be peeled because it is not a tag: */1781 PEEL_NON_TAG = -2,17821783/* ref_entry contains no peeled value because it is a symref: */1784 PEEL_IS_SYMREF = -3,17851786/*1787 * ref_entry cannot be peeled because it is broken (i.e., the1788 * symbolic reference cannot even be resolved to an object1789 * name):1790 */1791 PEEL_BROKEN = -41792};17931794/*1795 * Peel the named object; i.e., if the object is a tag, resolve the1796 * tag recursively until a non-tag is found. If successful, store the1797 * result to sha1 and return PEEL_PEELED. If the object is not a tag1798 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1799 * and leave sha1 unchanged.1800 */1801static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1802{1803struct object *o =lookup_unknown_object(name);18041805if(o->type == OBJ_NONE) {1806int type =sha1_object_info(name, NULL);1807if(type <0|| !object_as_type(o, type,0))1808return PEEL_INVALID;1809}18101811if(o->type != OBJ_TAG)1812return PEEL_NON_TAG;18131814 o =deref_tag_noverify(o);1815if(!o)1816return PEEL_INVALID;18171818hashcpy(sha1, o->sha1);1819return PEEL_PEELED;1820}18211822/*1823 * Peel the entry (if possible) and return its new peel_status. If1824 * repeel is true, re-peel the entry even if there is an old peeled1825 * value that is already stored in it.1826 *1827 * It is OK to call this function with a packed reference entry that1828 * might be stale and might even refer to an object that has since1829 * been garbage-collected. In such a case, if the entry has1830 * REF_KNOWS_PEELED then leave the status unchanged and return1831 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1832 */1833static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1834{1835enum peel_status status;18361837if(entry->flag & REF_KNOWS_PEELED) {1838if(repeel) {1839 entry->flag &= ~REF_KNOWS_PEELED;1840oidclr(&entry->u.value.peeled);1841}else{1842returnis_null_oid(&entry->u.value.peeled) ?1843 PEEL_NON_TAG : PEEL_PEELED;1844}1845}1846if(entry->flag & REF_ISBROKEN)1847return PEEL_BROKEN;1848if(entry->flag & REF_ISSYMREF)1849return PEEL_IS_SYMREF;18501851 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1852if(status == PEEL_PEELED || status == PEEL_NON_TAG)1853 entry->flag |= REF_KNOWS_PEELED;1854return status;1855}18561857intpeel_ref(const char*refname,unsigned char*sha1)1858{1859int flag;1860unsigned char base[20];18611862if(current_ref && (current_ref->name == refname1863|| !strcmp(current_ref->name, refname))) {1864if(peel_entry(current_ref,0))1865return-1;1866hashcpy(sha1, current_ref->u.value.peeled.hash);1867return0;1868}18691870if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1871return-1;18721873/*1874 * If the reference is packed, read its ref_entry from the1875 * cache in the hope that we already know its peeled value.1876 * We only try this optimization on packed references because1877 * (a) forcing the filling of the loose reference cache could1878 * be expensive and (b) loose references anyway usually do not1879 * have REF_KNOWS_PEELED.1880 */1881if(flag & REF_ISPACKED) {1882struct ref_entry *r =get_packed_ref(refname);1883if(r) {1884if(peel_entry(r,0))1885return-1;1886hashcpy(sha1, r->u.value.peeled.hash);1887return0;1888}1889}18901891returnpeel_object(base, sha1);1892}18931894struct warn_if_dangling_data {1895FILE*fp;1896const char*refname;1897const struct string_list *refnames;1898const char*msg_fmt;1899};19001901static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1902int flags,void*cb_data)1903{1904struct warn_if_dangling_data *d = cb_data;1905const char*resolves_to;1906struct object_id junk;19071908if(!(flags & REF_ISSYMREF))1909return0;19101911 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1912if(!resolves_to1913|| (d->refname1914?strcmp(resolves_to, d->refname)1915: !string_list_has_string(d->refnames, resolves_to))) {1916return0;1917}19181919fprintf(d->fp, d->msg_fmt, refname);1920fputc('\n', d->fp);1921return0;1922}19231924voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1925{1926struct warn_if_dangling_data data;19271928 data.fp = fp;1929 data.refname = refname;1930 data.refnames = NULL;1931 data.msg_fmt = msg_fmt;1932for_each_rawref(warn_if_dangling_symref, &data);1933}19341935voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1936{1937struct warn_if_dangling_data data;19381939 data.fp = fp;1940 data.refname = NULL;1941 data.refnames = refnames;1942 data.msg_fmt = msg_fmt;1943for_each_rawref(warn_if_dangling_symref, &data);1944}19451946/*1947 * Call fn for each reference in the specified ref_cache, omitting1948 * references not in the containing_dir of base. fn is called for all1949 * references, including broken ones. If fn ever returns a non-zero1950 * value, stop the iteration and return that value; otherwise, return1951 * 0.1952 */1953static intdo_for_each_entry(struct ref_cache *refs,const char*base,1954 each_ref_entry_fn fn,void*cb_data)1955{1956struct packed_ref_cache *packed_ref_cache;1957struct ref_dir *loose_dir;1958struct ref_dir *packed_dir;1959int retval =0;19601961/*1962 * We must make sure that all loose refs are read before accessing the1963 * packed-refs file; this avoids a race condition in which loose refs1964 * are migrated to the packed-refs file by a simultaneous process, but1965 * our in-memory view is from before the migration. get_packed_ref_cache()1966 * takes care of making sure our view is up to date with what is on1967 * disk.1968 */1969 loose_dir =get_loose_refs(refs);1970if(base && *base) {1971 loose_dir =find_containing_dir(loose_dir, base,0);1972}1973if(loose_dir)1974prime_ref_dir(loose_dir);19751976 packed_ref_cache =get_packed_ref_cache(refs);1977acquire_packed_ref_cache(packed_ref_cache);1978 packed_dir =get_packed_ref_dir(packed_ref_cache);1979if(base && *base) {1980 packed_dir =find_containing_dir(packed_dir, base,0);1981}19821983if(packed_dir && loose_dir) {1984sort_ref_dir(packed_dir);1985sort_ref_dir(loose_dir);1986 retval =do_for_each_entry_in_dirs(1987 packed_dir, loose_dir, fn, cb_data);1988}else if(packed_dir) {1989sort_ref_dir(packed_dir);1990 retval =do_for_each_entry_in_dir(1991 packed_dir,0, fn, cb_data);1992}else if(loose_dir) {1993sort_ref_dir(loose_dir);1994 retval =do_for_each_entry_in_dir(1995 loose_dir,0, fn, cb_data);1996}19971998release_packed_ref_cache(packed_ref_cache);1999return retval;2000}20012002/*2003 * Call fn for each reference in the specified ref_cache for which the2004 * refname begins with base. If trim is non-zero, then trim that many2005 * characters off the beginning of each refname before passing the2006 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2007 * broken references in the iteration. If fn ever returns a non-zero2008 * value, stop the iteration and return that value; otherwise, return2009 * 0.2010 */2011static intdo_for_each_ref(struct ref_cache *refs,const char*base,2012 each_ref_fn fn,int trim,int flags,void*cb_data)2013{2014struct ref_entry_cb data;2015 data.base = base;2016 data.trim = trim;2017 data.flags = flags;2018 data.fn = fn;2019 data.cb_data = cb_data;20202021if(ref_paranoia <0)2022 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2023if(ref_paranoia)2024 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20252026returndo_for_each_entry(refs, base, do_one_ref, &data);2027}20282029static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2030{2031struct object_id oid;2032int flag;20332034if(submodule) {2035if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2036returnfn("HEAD", &oid,0, cb_data);20372038return0;2039}20402041if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2042returnfn("HEAD", &oid, flag, cb_data);20432044return0;2045}20462047inthead_ref(each_ref_fn fn,void*cb_data)2048{2049returndo_head_ref(NULL, fn, cb_data);2050}20512052inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2053{2054returndo_head_ref(submodule, fn, cb_data);2055}20562057intfor_each_ref(each_ref_fn fn,void*cb_data)2058{2059returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2060}20612062intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2063{2064returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2065}20662067intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2068{2069returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2070}20712072intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2073 each_ref_fn fn,void*cb_data)2074{2075returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2076}20772078intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2079{2080returnfor_each_ref_in("refs/tags/", fn, cb_data);2081}20822083intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2084{2085returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2086}20872088intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2089{2090returnfor_each_ref_in("refs/heads/", fn, cb_data);2091}20922093intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2094{2095returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2096}20972098intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2099{2100returnfor_each_ref_in("refs/remotes/", fn, cb_data);2101}21022103intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2104{2105returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2106}21072108intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2109{2110returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2111}21122113inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2114{2115struct strbuf buf = STRBUF_INIT;2116int ret =0;2117struct object_id oid;2118int flag;21192120strbuf_addf(&buf,"%sHEAD",get_git_namespace());2121if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2122 ret =fn(buf.buf, &oid, flag, cb_data);2123strbuf_release(&buf);21242125return ret;2126}21272128intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2129{2130struct strbuf buf = STRBUF_INIT;2131int ret;2132strbuf_addf(&buf,"%srefs/",get_git_namespace());2133 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2134strbuf_release(&buf);2135return ret;2136}21372138intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2139const char*prefix,void*cb_data)2140{2141struct strbuf real_pattern = STRBUF_INIT;2142struct ref_filter filter;2143int ret;21442145if(!prefix && !starts_with(pattern,"refs/"))2146strbuf_addstr(&real_pattern,"refs/");2147else if(prefix)2148strbuf_addstr(&real_pattern, prefix);2149strbuf_addstr(&real_pattern, pattern);21502151if(!has_glob_specials(pattern)) {2152/* Append implied '/' '*' if not present. */2153if(real_pattern.buf[real_pattern.len -1] !='/')2154strbuf_addch(&real_pattern,'/');2155/* No need to check for '*', there is none. */2156strbuf_addch(&real_pattern,'*');2157}21582159 filter.pattern = real_pattern.buf;2160 filter.fn = fn;2161 filter.cb_data = cb_data;2162 ret =for_each_ref(filter_refs, &filter);21632164strbuf_release(&real_pattern);2165return ret;2166}21672168intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2169{2170returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2171}21722173intfor_each_rawref(each_ref_fn fn,void*cb_data)2174{2175returndo_for_each_ref(&ref_cache,"", fn,0,2176 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2177}21782179const char*prettify_refname(const char*name)2180{2181return name + (2182starts_with(name,"refs/heads/") ?11:2183starts_with(name,"refs/tags/") ?10:2184starts_with(name,"refs/remotes/") ?13:21850);2186}21872188static const char*ref_rev_parse_rules[] = {2189"%.*s",2190"refs/%.*s",2191"refs/tags/%.*s",2192"refs/heads/%.*s",2193"refs/remotes/%.*s",2194"refs/remotes/%.*s/HEAD",2195 NULL2196};21972198intrefname_match(const char*abbrev_name,const char*full_name)2199{2200const char**p;2201const int abbrev_name_len =strlen(abbrev_name);22022203for(p = ref_rev_parse_rules; *p; p++) {2204if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2205return1;2206}2207}22082209return0;2210}22112212static voidunlock_ref(struct ref_lock *lock)2213{2214/* Do not free lock->lk -- atexit() still looks at them */2215if(lock->lk)2216rollback_lock_file(lock->lk);2217free(lock->ref_name);2218free(lock->orig_ref_name);2219free(lock);2220}22212222/* This function should make sure errno is meaningful on error */2223static struct ref_lock *verify_lock(struct ref_lock *lock,2224const unsigned char*old_sha1,int mustexist)2225{2226if(read_ref_full(lock->ref_name,2227 mustexist ? RESOLVE_REF_READING :0,2228 lock->old_oid.hash, NULL)) {2229int save_errno = errno;2230error("Can't verify ref%s", lock->ref_name);2231unlock_ref(lock);2232 errno = save_errno;2233return NULL;2234}2235if(hashcmp(lock->old_oid.hash, old_sha1)) {2236error("Ref%sis at%sbut expected%s", lock->ref_name,2237oid_to_hex(&lock->old_oid),sha1_to_hex(old_sha1));2238unlock_ref(lock);2239 errno = EBUSY;2240return NULL;2241}2242return lock;2243}22442245static intremove_empty_directories(const char*file)2246{2247/* we want to create a file but there is a directory there;2248 * if that is an empty directory (or a directory that contains2249 * only empty directories), remove them.2250 */2251struct strbuf path;2252int result, save_errno;22532254strbuf_init(&path,20);2255strbuf_addstr(&path, file);22562257 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2258 save_errno = errno;22592260strbuf_release(&path);2261 errno = save_errno;22622263return result;2264}22652266/*2267 * *string and *len will only be substituted, and *string returned (for2268 * later free()ing) if the string passed in is a magic short-hand form2269 * to name a branch.2270 */2271static char*substitute_branch_name(const char**string,int*len)2272{2273struct strbuf buf = STRBUF_INIT;2274int ret =interpret_branch_name(*string, *len, &buf);22752276if(ret == *len) {2277size_t size;2278*string =strbuf_detach(&buf, &size);2279*len = size;2280return(char*)*string;2281}22822283return NULL;2284}22852286intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2287{2288char*last_branch =substitute_branch_name(&str, &len);2289const char**p, *r;2290int refs_found =0;22912292*ref = NULL;2293for(p = ref_rev_parse_rules; *p; p++) {2294char fullref[PATH_MAX];2295unsigned char sha1_from_ref[20];2296unsigned char*this_result;2297int flag;22982299 this_result = refs_found ? sha1_from_ref : sha1;2300mksnpath(fullref,sizeof(fullref), *p, len, str);2301 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2302 this_result, &flag);2303if(r) {2304if(!refs_found++)2305*ref =xstrdup(r);2306if(!warn_ambiguous_refs)2307break;2308}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2309warning("ignoring dangling symref%s.", fullref);2310}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2311warning("ignoring broken ref%s.", fullref);2312}2313}2314free(last_branch);2315return refs_found;2316}23172318intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2319{2320char*last_branch =substitute_branch_name(&str, &len);2321const char**p;2322int logs_found =0;23232324*log = NULL;2325for(p = ref_rev_parse_rules; *p; p++) {2326unsigned char hash[20];2327char path[PATH_MAX];2328const char*ref, *it;23292330mksnpath(path,sizeof(path), *p, len, str);2331 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2332 hash, NULL);2333if(!ref)2334continue;2335if(reflog_exists(path))2336 it = path;2337else if(strcmp(ref, path) &&reflog_exists(ref))2338 it = ref;2339else2340continue;2341if(!logs_found++) {2342*log =xstrdup(it);2343hashcpy(sha1, hash);2344}2345if(!warn_ambiguous_refs)2346break;2347}2348free(last_branch);2349return logs_found;2350}23512352/*2353 * Locks a ref returning the lock on success and NULL on failure.2354 * On failure errno is set to something meaningful.2355 */2356static struct ref_lock *lock_ref_sha1_basic(const char*refname,2357const unsigned char*old_sha1,2358const struct string_list *extras,2359const struct string_list *skip,2360unsigned int flags,int*type_p,2361struct strbuf *err)2362{2363const char*ref_file;2364const char*orig_refname = refname;2365struct ref_lock *lock;2366int last_errno =0;2367int type, lflags;2368int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2369int resolve_flags =0;2370int attempts_remaining =3;23712372assert(err);23732374 lock =xcalloc(1,sizeof(struct ref_lock));23752376if(mustexist)2377 resolve_flags |= RESOLVE_REF_READING;2378if(flags & REF_DELETING) {2379 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2380if(flags & REF_NODEREF)2381 resolve_flags |= RESOLVE_REF_NO_RECURSE;2382}23832384 refname =resolve_ref_unsafe(refname, resolve_flags,2385 lock->old_oid.hash, &type);2386if(!refname && errno == EISDIR) {2387/* we are trying to lock foo but we used to2388 * have foo/bar which now does not exist;2389 * it is normal for the empty directory 'foo'2390 * to remain.2391 */2392 ref_file =git_path("%s", orig_refname);2393if(remove_empty_directories(ref_file)) {2394 last_errno = errno;23952396if(!verify_refname_available(orig_refname, extras, skip,2397get_loose_refs(&ref_cache), err))2398strbuf_addf(err,"there are still refs under '%s'",2399 orig_refname);24002401goto error_return;2402}2403 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2404 lock->old_oid.hash, &type);2405}2406if(type_p)2407*type_p = type;2408if(!refname) {2409 last_errno = errno;2410if(last_errno != ENOTDIR ||2411!verify_refname_available(orig_refname, extras, skip,2412get_loose_refs(&ref_cache), err))2413strbuf_addf(err,"unable to resolve reference%s:%s",2414 orig_refname,strerror(last_errno));24152416goto error_return;2417}2418/*2419 * If the ref did not exist and we are creating it, make sure2420 * there is no existing packed ref whose name begins with our2421 * refname, nor a packed ref whose name is a proper prefix of2422 * our refname.2423 */2424if(is_null_oid(&lock->old_oid) &&2425verify_refname_available(refname, extras, skip,2426get_packed_refs(&ref_cache), err)) {2427 last_errno = ENOTDIR;2428goto error_return;2429}24302431 lock->lk =xcalloc(1,sizeof(struct lock_file));24322433 lflags =0;2434if(flags & REF_NODEREF) {2435 refname = orig_refname;2436 lflags |= LOCK_NO_DEREF;2437}2438 lock->ref_name =xstrdup(refname);2439 lock->orig_ref_name =xstrdup(orig_refname);2440 ref_file =git_path("%s", refname);24412442 retry:2443switch(safe_create_leading_directories_const(ref_file)) {2444case SCLD_OK:2445break;/* success */2446case SCLD_VANISHED:2447if(--attempts_remaining >0)2448goto retry;2449/* fall through */2450default:2451 last_errno = errno;2452strbuf_addf(err,"unable to create directory for%s", ref_file);2453goto error_return;2454}24552456if(hold_lock_file_for_update(lock->lk, ref_file, lflags) <0) {2457 last_errno = errno;2458if(errno == ENOENT && --attempts_remaining >0)2459/*2460 * Maybe somebody just deleted one of the2461 * directories leading to ref_file. Try2462 * again:2463 */2464goto retry;2465else{2466unable_to_lock_message(ref_file, errno, err);2467goto error_return;2468}2469}2470return old_sha1 ?verify_lock(lock, old_sha1, mustexist) : lock;24712472 error_return:2473unlock_ref(lock);2474 errno = last_errno;2475return NULL;2476}24772478/*2479 * Write an entry to the packed-refs file for the specified refname.2480 * If peeled is non-NULL, write it as the entry's peeled value.2481 */2482static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2483unsigned char*peeled)2484{2485fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2486if(peeled)2487fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2488}24892490/*2491 * An each_ref_entry_fn that writes the entry to a packed-refs file.2492 */2493static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2494{2495enum peel_status peel_status =peel_entry(entry,0);24962497if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2498error("internal error:%sis not a valid packed reference!",2499 entry->name);2500write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2501 peel_status == PEEL_PEELED ?2502 entry->u.value.peeled.hash : NULL);2503return0;2504}25052506/* This should return a meaningful errno on failure */2507intlock_packed_refs(int flags)2508{2509static int timeout_configured =0;2510static int timeout_value =1000;25112512struct packed_ref_cache *packed_ref_cache;25132514if(!timeout_configured) {2515git_config_get_int("core.packedrefstimeout", &timeout_value);2516 timeout_configured =1;2517}25182519if(hold_lock_file_for_update_timeout(2520&packlock,git_path("packed-refs"),2521 flags, timeout_value) <0)2522return-1;2523/*2524 * Get the current packed-refs while holding the lock. If the2525 * packed-refs file has been modified since we last read it,2526 * this will automatically invalidate the cache and re-read2527 * the packed-refs file.2528 */2529 packed_ref_cache =get_packed_ref_cache(&ref_cache);2530 packed_ref_cache->lock = &packlock;2531/* Increment the reference count to prevent it from being freed: */2532acquire_packed_ref_cache(packed_ref_cache);2533return0;2534}25352536/*2537 * Commit the packed refs changes.2538 * On error we must make sure that errno contains a meaningful value.2539 */2540intcommit_packed_refs(void)2541{2542struct packed_ref_cache *packed_ref_cache =2543get_packed_ref_cache(&ref_cache);2544int error =0;2545int save_errno =0;2546FILE*out;25472548if(!packed_ref_cache->lock)2549die("internal error: packed-refs not locked");25502551 out =fdopen_lock_file(packed_ref_cache->lock,"w");2552if(!out)2553die_errno("unable to fdopen packed-refs descriptor");25542555fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2556do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),25570, write_packed_entry_fn, out);25582559if(commit_lock_file(packed_ref_cache->lock)) {2560 save_errno = errno;2561 error = -1;2562}2563 packed_ref_cache->lock = NULL;2564release_packed_ref_cache(packed_ref_cache);2565 errno = save_errno;2566return error;2567}25682569voidrollback_packed_refs(void)2570{2571struct packed_ref_cache *packed_ref_cache =2572get_packed_ref_cache(&ref_cache);25732574if(!packed_ref_cache->lock)2575die("internal error: packed-refs not locked");2576rollback_lock_file(packed_ref_cache->lock);2577 packed_ref_cache->lock = NULL;2578release_packed_ref_cache(packed_ref_cache);2579clear_packed_ref_cache(&ref_cache);2580}25812582struct ref_to_prune {2583struct ref_to_prune *next;2584unsigned char sha1[20];2585char name[FLEX_ARRAY];2586};25872588struct pack_refs_cb_data {2589unsigned int flags;2590struct ref_dir *packed_refs;2591struct ref_to_prune *ref_to_prune;2592};25932594/*2595 * An each_ref_entry_fn that is run over loose references only. If2596 * the loose reference can be packed, add an entry in the packed ref2597 * cache. If the reference should be pruned, also add it to2598 * ref_to_prune in the pack_refs_cb_data.2599 */2600static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2601{2602struct pack_refs_cb_data *cb = cb_data;2603enum peel_status peel_status;2604struct ref_entry *packed_entry;2605int is_tag_ref =starts_with(entry->name,"refs/tags/");26062607/* ALWAYS pack tags */2608if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2609return0;26102611/* Do not pack symbolic or broken refs: */2612if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2613return0;26142615/* Add a packed ref cache entry equivalent to the loose entry. */2616 peel_status =peel_entry(entry,1);2617if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2618die("internal error peeling reference%s(%s)",2619 entry->name,oid_to_hex(&entry->u.value.oid));2620 packed_entry =find_ref(cb->packed_refs, entry->name);2621if(packed_entry) {2622/* Overwrite existing packed entry with info from loose entry */2623 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2624oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2625}else{2626 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2627 REF_ISPACKED | REF_KNOWS_PEELED,0);2628add_ref(cb->packed_refs, packed_entry);2629}2630oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);26312632/* Schedule the loose reference for pruning if requested. */2633if((cb->flags & PACK_REFS_PRUNE)) {2634int namelen =strlen(entry->name) +1;2635struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2636hashcpy(n->sha1, entry->u.value.oid.hash);2637strcpy(n->name, entry->name);2638 n->next = cb->ref_to_prune;2639 cb->ref_to_prune = n;2640}2641return0;2642}26432644/*2645 * Remove empty parents, but spare refs/ and immediate subdirs.2646 * Note: munges *name.2647 */2648static voidtry_remove_empty_parents(char*name)2649{2650char*p, *q;2651int i;2652 p = name;2653for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2654while(*p && *p !='/')2655 p++;2656/* tolerate duplicate slashes; see check_refname_format() */2657while(*p =='/')2658 p++;2659}2660for(q = p; *q; q++)2661;2662while(1) {2663while(q > p && *q !='/')2664 q--;2665while(q > p && *(q-1) =='/')2666 q--;2667if(q == p)2668break;2669*q ='\0';2670if(rmdir(git_path("%s", name)))2671break;2672}2673}26742675/* make sure nobody touched the ref, and unlink */2676static voidprune_ref(struct ref_to_prune *r)2677{2678struct ref_transaction *transaction;2679struct strbuf err = STRBUF_INIT;26802681if(check_refname_format(r->name,0))2682return;26832684 transaction =ref_transaction_begin(&err);2685if(!transaction ||2686ref_transaction_delete(transaction, r->name, r->sha1,2687 REF_ISPRUNING, NULL, &err) ||2688ref_transaction_commit(transaction, &err)) {2689ref_transaction_free(transaction);2690error("%s", err.buf);2691strbuf_release(&err);2692return;2693}2694ref_transaction_free(transaction);2695strbuf_release(&err);2696try_remove_empty_parents(r->name);2697}26982699static voidprune_refs(struct ref_to_prune *r)2700{2701while(r) {2702prune_ref(r);2703 r = r->next;2704}2705}27062707intpack_refs(unsigned int flags)2708{2709struct pack_refs_cb_data cbdata;27102711memset(&cbdata,0,sizeof(cbdata));2712 cbdata.flags = flags;27132714lock_packed_refs(LOCK_DIE_ON_ERROR);2715 cbdata.packed_refs =get_packed_refs(&ref_cache);27162717do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2718 pack_if_possible_fn, &cbdata);27192720if(commit_packed_refs())2721die_errno("unable to overwrite old ref-pack file");27222723prune_refs(cbdata.ref_to_prune);2724return0;2725}27262727intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2728{2729struct ref_dir *packed;2730struct string_list_item *refname;2731int ret, needs_repacking =0, removed =0;27322733assert(err);27342735/* Look for a packed ref */2736for_each_string_list_item(refname, refnames) {2737if(get_packed_ref(refname->string)) {2738 needs_repacking =1;2739break;2740}2741}27422743/* Avoid locking if we have nothing to do */2744if(!needs_repacking)2745return0;/* no refname exists in packed refs */27462747if(lock_packed_refs(0)) {2748unable_to_lock_message(git_path("packed-refs"), errno, err);2749return-1;2750}2751 packed =get_packed_refs(&ref_cache);27522753/* Remove refnames from the cache */2754for_each_string_list_item(refname, refnames)2755if(remove_entry(packed, refname->string) != -1)2756 removed =1;2757if(!removed) {2758/*2759 * All packed entries disappeared while we were2760 * acquiring the lock.2761 */2762rollback_packed_refs();2763return0;2764}27652766/* Write what remains */2767 ret =commit_packed_refs();2768if(ret)2769strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2770strerror(errno));2771return ret;2772}27732774static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2775{2776assert(err);27772778if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2779/*2780 * loose. The loose file name is the same as the2781 * lockfile name, minus ".lock":2782 */2783char*loose_filename =get_locked_file_path(lock->lk);2784int res =unlink_or_msg(loose_filename, err);2785free(loose_filename);2786if(res)2787return1;2788}2789return0;2790}27912792intdelete_ref(const char*refname,const unsigned char*sha1,unsigned int flags)2793{2794struct ref_transaction *transaction;2795struct strbuf err = STRBUF_INIT;27962797 transaction =ref_transaction_begin(&err);2798if(!transaction ||2799ref_transaction_delete(transaction, refname,2800(sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,2801 flags, NULL, &err) ||2802ref_transaction_commit(transaction, &err)) {2803error("%s", err.buf);2804ref_transaction_free(transaction);2805strbuf_release(&err);2806return1;2807}2808ref_transaction_free(transaction);2809strbuf_release(&err);2810return0;2811}28122813/*2814 * People using contrib's git-new-workdir have .git/logs/refs ->2815 * /some/other/path/.git/logs/refs, and that may live on another device.2816 *2817 * IOW, to avoid cross device rename errors, the temporary renamed log must2818 * live into logs/refs.2819 */2820#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"28212822static intrename_tmp_log(const char*newrefname)2823{2824int attempts_remaining =4;28252826 retry:2827switch(safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {2828case SCLD_OK:2829break;/* success */2830case SCLD_VANISHED:2831if(--attempts_remaining >0)2832goto retry;2833/* fall through */2834default:2835error("unable to create directory for%s", newrefname);2836return-1;2837}28382839if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2840if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2841/*2842 * rename(a, b) when b is an existing2843 * directory ought to result in ISDIR, but2844 * Solaris 5.8 gives ENOTDIR. Sheesh.2845 */2846if(remove_empty_directories(git_path("logs/%s", newrefname))) {2847error("Directory not empty: logs/%s", newrefname);2848return-1;2849}2850goto retry;2851}else if(errno == ENOENT && --attempts_remaining >0) {2852/*2853 * Maybe another process just deleted one of2854 * the directories in the path to newrefname.2855 * Try again from the beginning.2856 */2857goto retry;2858}else{2859error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2860 newrefname,strerror(errno));2861return-1;2862}2863}2864return0;2865}28662867static intrename_ref_available(const char*oldname,const char*newname)2868{2869struct string_list skip = STRING_LIST_INIT_NODUP;2870struct strbuf err = STRBUF_INIT;2871int ret;28722873string_list_insert(&skip, oldname);2874 ret = !verify_refname_available(newname, NULL, &skip,2875get_packed_refs(&ref_cache), &err)2876&& !verify_refname_available(newname, NULL, &skip,2877get_loose_refs(&ref_cache), &err);2878if(!ret)2879error("%s", err.buf);28802881string_list_clear(&skip,0);2882strbuf_release(&err);2883return ret;2884}28852886static intwrite_ref_to_lockfile(struct ref_lock *lock,const unsigned char*sha1);2887static intcommit_ref_update(struct ref_lock *lock,2888const unsigned char*sha1,const char*logmsg);28892890intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2891{2892unsigned char sha1[20], orig_sha1[20];2893int flag =0, logmoved =0;2894struct ref_lock *lock;2895struct stat loginfo;2896int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2897const char*symref = NULL;2898struct strbuf err = STRBUF_INIT;28992900if(log &&S_ISLNK(loginfo.st_mode))2901returnerror("reflog for%sis a symlink", oldrefname);29022903 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,2904 orig_sha1, &flag);2905if(flag & REF_ISSYMREF)2906returnerror("refname%sis a symbolic ref, renaming it is not supported",2907 oldrefname);2908if(!symref)2909returnerror("refname%snot found", oldrefname);29102911if(!rename_ref_available(oldrefname, newrefname))2912return1;29132914if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))2915returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",2916 oldrefname,strerror(errno));29172918if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {2919error("unable to delete old%s", oldrefname);2920goto rollback;2921}29222923if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&2924delete_ref(newrefname, sha1, REF_NODEREF)) {2925if(errno==EISDIR) {2926if(remove_empty_directories(git_path("%s", newrefname))) {2927error("Directory not empty:%s", newrefname);2928goto rollback;2929}2930}else{2931error("unable to delete existing%s", newrefname);2932goto rollback;2933}2934}29352936if(log &&rename_tmp_log(newrefname))2937goto rollback;29382939 logmoved = log;29402941 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);2942if(!lock) {2943error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);2944strbuf_release(&err);2945goto rollback;2946}2947hashcpy(lock->old_oid.hash, orig_sha1);29482949if(write_ref_to_lockfile(lock, orig_sha1) ||2950commit_ref_update(lock, orig_sha1, logmsg)) {2951error("unable to write current sha1 into%s", newrefname);2952goto rollback;2953}29542955return0;29562957 rollback:2958 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);2959if(!lock) {2960error("unable to lock%sfor rollback:%s", oldrefname, err.buf);2961strbuf_release(&err);2962goto rollbacklog;2963}29642965 flag = log_all_ref_updates;2966 log_all_ref_updates =0;2967if(write_ref_to_lockfile(lock, orig_sha1) ||2968commit_ref_update(lock, orig_sha1, NULL))2969error("unable to write current sha1 into%s", oldrefname);2970 log_all_ref_updates = flag;29712972 rollbacklog:2973if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))2974error("unable to restore logfile%sfrom%s:%s",2975 oldrefname, newrefname,strerror(errno));2976if(!logmoved && log &&2977rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))2978error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",2979 oldrefname,strerror(errno));29802981return1;2982}29832984static intclose_ref(struct ref_lock *lock)2985{2986if(close_lock_file(lock->lk))2987return-1;2988return0;2989}29902991static intcommit_ref(struct ref_lock *lock)2992{2993if(commit_lock_file(lock->lk))2994return-1;2995return0;2996}29972998/*2999 * copy the reflog message msg to buf, which has been allocated sufficiently3000 * large, while cleaning up the whitespaces. Especially, convert LF to space,3001 * because reflog file is one line per entry.3002 */3003static intcopy_msg(char*buf,const char*msg)3004{3005char*cp = buf;3006char c;3007int wasspace =1;30083009*cp++ ='\t';3010while((c = *msg++)) {3011if(wasspace &&isspace(c))3012continue;3013 wasspace =isspace(c);3014if(wasspace)3015 c =' ';3016*cp++ = c;3017}3018while(buf < cp &&isspace(cp[-1]))3019 cp--;3020*cp++ ='\n';3021return cp - buf;3022}30233024/* This function must set a meaningful errno on failure */3025intlog_ref_setup(const char*refname,struct strbuf *sb_logfile)3026{3027int logfd, oflags = O_APPEND | O_WRONLY;3028char*logfile;30293030strbuf_git_path(sb_logfile,"logs/%s", refname);3031 logfile = sb_logfile->buf;3032/* make sure the rest of the function can't change "logfile" */3033 sb_logfile = NULL;3034if(log_all_ref_updates &&3035(starts_with(refname,"refs/heads/") ||3036starts_with(refname,"refs/remotes/") ||3037starts_with(refname,"refs/notes/") ||3038!strcmp(refname,"HEAD"))) {3039if(safe_create_leading_directories(logfile) <0) {3040int save_errno = errno;3041error("unable to create directory for%s", logfile);3042 errno = save_errno;3043return-1;3044}3045 oflags |= O_CREAT;3046}30473048 logfd =open(logfile, oflags,0666);3049if(logfd <0) {3050if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3051return0;30523053if(errno == EISDIR) {3054if(remove_empty_directories(logfile)) {3055int save_errno = errno;3056error("There are still logs under '%s'",3057 logfile);3058 errno = save_errno;3059return-1;3060}3061 logfd =open(logfile, oflags,0666);3062}30633064if(logfd <0) {3065int save_errno = errno;3066error("Unable to append to%s:%s", logfile,3067strerror(errno));3068 errno = save_errno;3069return-1;3070}3071}30723073adjust_shared_perm(logfile);3074close(logfd);3075return0;3076}30773078static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3079const unsigned char*new_sha1,3080const char*committer,const char*msg)3081{3082int msglen, written;3083unsigned maxlen, len;3084char*logrec;30853086 msglen = msg ?strlen(msg) :0;3087 maxlen =strlen(committer) + msglen +100;3088 logrec =xmalloc(maxlen);3089 len =sprintf(logrec,"%s %s %s\n",3090sha1_to_hex(old_sha1),3091sha1_to_hex(new_sha1),3092 committer);3093if(msglen)3094 len +=copy_msg(logrec + len -1, msg) -1;30953096 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3097free(logrec);3098if(written != len)3099return-1;31003101return0;3102}31033104static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3105const unsigned char*new_sha1,const char*msg,3106struct strbuf *sb_log_file)3107{3108int logfd, result, oflags = O_APPEND | O_WRONLY;3109char*log_file;31103111if(log_all_ref_updates <0)3112 log_all_ref_updates = !is_bare_repository();31133114 result =log_ref_setup(refname, sb_log_file);3115if(result)3116return result;3117 log_file = sb_log_file->buf;3118/* make sure the rest of the function can't change "log_file" */3119 sb_log_file = NULL;31203121 logfd =open(log_file, oflags);3122if(logfd <0)3123return0;3124 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3125git_committer_info(0), msg);3126if(result) {3127int save_errno = errno;3128close(logfd);3129error("Unable to append to%s", log_file);3130 errno = save_errno;3131return-1;3132}3133if(close(logfd)) {3134int save_errno = errno;3135error("Unable to append to%s", log_file);3136 errno = save_errno;3137return-1;3138}3139return0;3140}31413142static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3143const unsigned char*new_sha1,const char*msg)3144{3145struct strbuf sb = STRBUF_INIT;3146int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb);3147strbuf_release(&sb);3148return ret;3149}31503151intis_branch(const char*refname)3152{3153return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3154}31553156/*3157 * Write sha1 into the open lockfile, then close the lockfile. On3158 * errors, rollback the lockfile and set errno to reflect the problem.3159 */3160static intwrite_ref_to_lockfile(struct ref_lock *lock,3161const unsigned char*sha1)3162{3163static char term ='\n';3164struct object *o;31653166 o =parse_object(sha1);3167if(!o) {3168error("Trying to write ref%swith nonexistent object%s",3169 lock->ref_name,sha1_to_hex(sha1));3170unlock_ref(lock);3171 errno = EINVAL;3172return-1;3173}3174if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3175error("Trying to write non-commit object%sto branch%s",3176sha1_to_hex(sha1), lock->ref_name);3177unlock_ref(lock);3178 errno = EINVAL;3179return-1;3180}3181if(write_in_full(lock->lk->fd,sha1_to_hex(sha1),40) !=40||3182write_in_full(lock->lk->fd, &term,1) !=1||3183close_ref(lock) <0) {3184int save_errno = errno;3185error("Couldn't write%s", lock->lk->filename.buf);3186unlock_ref(lock);3187 errno = save_errno;3188return-1;3189}3190return0;3191}31923193/*3194 * Commit a change to a loose reference that has already been written3195 * to the loose reference lockfile. Also update the reflogs if3196 * necessary, using the specified lockmsg (which can be NULL).3197 */3198static intcommit_ref_update(struct ref_lock *lock,3199const unsigned char*sha1,const char*logmsg)3200{3201clear_loose_ref_cache(&ref_cache);3202if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg) <0||3203(strcmp(lock->ref_name, lock->orig_ref_name) &&3204log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg) <0)) {3205unlock_ref(lock);3206return-1;3207}3208if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3209/*3210 * Special hack: If a branch is updated directly and HEAD3211 * points to it (may happen on the remote side of a push3212 * for example) then logically the HEAD reflog should be3213 * updated too.3214 * A generic solution implies reverse symref information,3215 * but finding all symrefs pointing to the given branch3216 * would be rather costly for this rare event (the direct3217 * update of a branch) to be worth it. So let's cheat and3218 * check with HEAD only which should cover 99% of all usage3219 * scenarios (even 100% of the default ones).3220 */3221unsigned char head_sha1[20];3222int head_flag;3223const char*head_ref;3224 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3225 head_sha1, &head_flag);3226if(head_ref && (head_flag & REF_ISSYMREF) &&3227!strcmp(head_ref, lock->ref_name))3228log_ref_write("HEAD", lock->old_oid.hash, sha1, logmsg);3229}3230if(commit_ref(lock)) {3231error("Couldn't set%s", lock->ref_name);3232unlock_ref(lock);3233return-1;3234}3235unlock_ref(lock);3236return0;3237}32383239intcreate_symref(const char*ref_target,const char*refs_heads_master,3240const char*logmsg)3241{3242const char*lockpath;3243char ref[1000];3244int fd, len, written;3245char*git_HEAD =git_pathdup("%s", ref_target);3246unsigned char old_sha1[20], new_sha1[20];32473248if(logmsg &&read_ref(ref_target, old_sha1))3249hashclr(old_sha1);32503251if(safe_create_leading_directories(git_HEAD) <0)3252returnerror("unable to create directory for%s", git_HEAD);32533254#ifndef NO_SYMLINK_HEAD3255if(prefer_symlink_refs) {3256unlink(git_HEAD);3257if(!symlink(refs_heads_master, git_HEAD))3258goto done;3259fprintf(stderr,"no symlink - falling back to symbolic ref\n");3260}3261#endif32623263 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3264if(sizeof(ref) <= len) {3265error("refname too long:%s", refs_heads_master);3266goto error_free_return;3267}3268 lockpath =mkpath("%s.lock", git_HEAD);3269 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3270if(fd <0) {3271error("Unable to open%sfor writing", lockpath);3272goto error_free_return;3273}3274 written =write_in_full(fd, ref, len);3275if(close(fd) !=0|| written != len) {3276error("Unable to write to%s", lockpath);3277goto error_unlink_return;3278}3279if(rename(lockpath, git_HEAD) <0) {3280error("Unable to create%s", git_HEAD);3281goto error_unlink_return;3282}3283if(adjust_shared_perm(git_HEAD)) {3284error("Unable to fix permissions on%s", lockpath);3285 error_unlink_return:3286unlink_or_warn(lockpath);3287 error_free_return:3288free(git_HEAD);3289return-1;3290}32913292#ifndef NO_SYMLINK_HEAD3293 done:3294#endif3295if(logmsg && !read_ref(refs_heads_master, new_sha1))3296log_ref_write(ref_target, old_sha1, new_sha1, logmsg);32973298free(git_HEAD);3299return0;3300}33013302struct read_ref_at_cb {3303const char*refname;3304unsigned long at_time;3305int cnt;3306int reccnt;3307unsigned char*sha1;3308int found_it;33093310unsigned char osha1[20];3311unsigned char nsha1[20];3312int tz;3313unsigned long date;3314char**msg;3315unsigned long*cutoff_time;3316int*cutoff_tz;3317int*cutoff_cnt;3318};33193320static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3321const char*email,unsigned long timestamp,int tz,3322const char*message,void*cb_data)3323{3324struct read_ref_at_cb *cb = cb_data;33253326 cb->reccnt++;3327 cb->tz = tz;3328 cb->date = timestamp;33293330if(timestamp <= cb->at_time || cb->cnt ==0) {3331if(cb->msg)3332*cb->msg =xstrdup(message);3333if(cb->cutoff_time)3334*cb->cutoff_time = timestamp;3335if(cb->cutoff_tz)3336*cb->cutoff_tz = tz;3337if(cb->cutoff_cnt)3338*cb->cutoff_cnt = cb->reccnt -1;3339/*3340 * we have not yet updated cb->[n|o]sha1 so they still3341 * hold the values for the previous record.3342 */3343if(!is_null_sha1(cb->osha1)) {3344hashcpy(cb->sha1, nsha1);3345if(hashcmp(cb->osha1, nsha1))3346warning("Log for ref%shas gap after%s.",3347 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3348}3349else if(cb->date == cb->at_time)3350hashcpy(cb->sha1, nsha1);3351else if(hashcmp(nsha1, cb->sha1))3352warning("Log for ref%sunexpectedly ended on%s.",3353 cb->refname,show_date(cb->date, cb->tz,3354 DATE_RFC2822));3355hashcpy(cb->osha1, osha1);3356hashcpy(cb->nsha1, nsha1);3357 cb->found_it =1;3358return1;3359}3360hashcpy(cb->osha1, osha1);3361hashcpy(cb->nsha1, nsha1);3362if(cb->cnt >0)3363 cb->cnt--;3364return0;3365}33663367static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3368const char*email,unsigned long timestamp,3369int tz,const char*message,void*cb_data)3370{3371struct read_ref_at_cb *cb = cb_data;33723373if(cb->msg)3374*cb->msg =xstrdup(message);3375if(cb->cutoff_time)3376*cb->cutoff_time = timestamp;3377if(cb->cutoff_tz)3378*cb->cutoff_tz = tz;3379if(cb->cutoff_cnt)3380*cb->cutoff_cnt = cb->reccnt;3381hashcpy(cb->sha1, osha1);3382if(is_null_sha1(cb->sha1))3383hashcpy(cb->sha1, nsha1);3384/* We just want the first entry */3385return1;3386}33873388intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3389unsigned char*sha1,char**msg,3390unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3391{3392struct read_ref_at_cb cb;33933394memset(&cb,0,sizeof(cb));3395 cb.refname = refname;3396 cb.at_time = at_time;3397 cb.cnt = cnt;3398 cb.msg = msg;3399 cb.cutoff_time = cutoff_time;3400 cb.cutoff_tz = cutoff_tz;3401 cb.cutoff_cnt = cutoff_cnt;3402 cb.sha1 = sha1;34033404for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);34053406if(!cb.reccnt) {3407if(flags & GET_SHA1_QUIETLY)3408exit(128);3409else3410die("Log for%sis empty.", refname);3411}3412if(cb.found_it)3413return0;34143415for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);34163417return1;3418}34193420intreflog_exists(const char*refname)3421{3422struct stat st;34233424return!lstat(git_path("logs/%s", refname), &st) &&3425S_ISREG(st.st_mode);3426}34273428intdelete_reflog(const char*refname)3429{3430returnremove_path(git_path("logs/%s", refname));3431}34323433static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3434{3435unsigned char osha1[20], nsha1[20];3436char*email_end, *message;3437unsigned long timestamp;3438int tz;34393440/* old SP new SP name <email> SP time TAB msg LF */3441if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3442get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3443get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3444!(email_end =strchr(sb->buf +82,'>')) ||3445 email_end[1] !=' '||3446!(timestamp =strtoul(email_end +2, &message,10)) ||3447!message || message[0] !=' '||3448(message[1] !='+'&& message[1] !='-') ||3449!isdigit(message[2]) || !isdigit(message[3]) ||3450!isdigit(message[4]) || !isdigit(message[5]))3451return0;/* corrupt? */3452 email_end[1] ='\0';3453 tz =strtol(message +1, NULL,10);3454if(message[6] !='\t')3455 message +=6;3456else3457 message +=7;3458returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3459}34603461static char*find_beginning_of_line(char*bob,char*scan)3462{3463while(bob < scan && *(--scan) !='\n')3464;/* keep scanning backwards */3465/*3466 * Return either beginning of the buffer, or LF at the end of3467 * the previous line.3468 */3469return scan;3470}34713472intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3473{3474struct strbuf sb = STRBUF_INIT;3475FILE*logfp;3476long pos;3477int ret =0, at_tail =1;34783479 logfp =fopen(git_path("logs/%s", refname),"r");3480if(!logfp)3481return-1;34823483/* Jump to the end */3484if(fseek(logfp,0, SEEK_END) <0)3485returnerror("cannot seek back reflog for%s:%s",3486 refname,strerror(errno));3487 pos =ftell(logfp);3488while(!ret &&0< pos) {3489int cnt;3490size_t nread;3491char buf[BUFSIZ];3492char*endp, *scanp;34933494/* Fill next block from the end */3495 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3496if(fseek(logfp, pos - cnt, SEEK_SET))3497returnerror("cannot seek back reflog for%s:%s",3498 refname,strerror(errno));3499 nread =fread(buf, cnt,1, logfp);3500if(nread !=1)3501returnerror("cannot read%dbytes from reflog for%s:%s",3502 cnt, refname,strerror(errno));3503 pos -= cnt;35043505 scanp = endp = buf + cnt;3506if(at_tail && scanp[-1] =='\n')3507/* Looking at the final LF at the end of the file */3508 scanp--;3509 at_tail =0;35103511while(buf < scanp) {3512/*3513 * terminating LF of the previous line, or the beginning3514 * of the buffer.3515 */3516char*bp;35173518 bp =find_beginning_of_line(buf, scanp);35193520if(*bp =='\n') {3521/*3522 * The newline is the end of the previous line,3523 * so we know we have complete line starting3524 * at (bp + 1). Prefix it onto any prior data3525 * we collected for the line and process it.3526 */3527strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3528 scanp = bp;3529 endp = bp +1;3530 ret =show_one_reflog_ent(&sb, fn, cb_data);3531strbuf_reset(&sb);3532if(ret)3533break;3534}else if(!pos) {3535/*3536 * We are at the start of the buffer, and the3537 * start of the file; there is no previous3538 * line, and we have everything for this one.3539 * Process it, and we can end the loop.3540 */3541strbuf_splice(&sb,0,0, buf, endp - buf);3542 ret =show_one_reflog_ent(&sb, fn, cb_data);3543strbuf_reset(&sb);3544break;3545}35463547if(bp == buf) {3548/*3549 * We are at the start of the buffer, and there3550 * is more file to read backwards. Which means3551 * we are in the middle of a line. Note that we3552 * may get here even if *bp was a newline; that3553 * just means we are at the exact end of the3554 * previous line, rather than some spot in the3555 * middle.3556 *3557 * Save away what we have to be combined with3558 * the data from the next read.3559 */3560strbuf_splice(&sb,0,0, buf, endp - buf);3561break;3562}3563}35643565}3566if(!ret && sb.len)3567die("BUG: reverse reflog parser had leftover data");35683569fclose(logfp);3570strbuf_release(&sb);3571return ret;3572}35733574intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3575{3576FILE*logfp;3577struct strbuf sb = STRBUF_INIT;3578int ret =0;35793580 logfp =fopen(git_path("logs/%s", refname),"r");3581if(!logfp)3582return-1;35833584while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3585 ret =show_one_reflog_ent(&sb, fn, cb_data);3586fclose(logfp);3587strbuf_release(&sb);3588return ret;3589}3590/*3591 * Call fn for each reflog in the namespace indicated by name. name3592 * must be empty or end with '/'. Name will be used as a scratch3593 * space, but its contents will be restored before return.3594 */3595static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3596{3597DIR*d =opendir(git_path("logs/%s", name->buf));3598int retval =0;3599struct dirent *de;3600int oldlen = name->len;36013602if(!d)3603return name->len ? errno :0;36043605while((de =readdir(d)) != NULL) {3606struct stat st;36073608if(de->d_name[0] =='.')3609continue;3610if(ends_with(de->d_name,".lock"))3611continue;3612strbuf_addstr(name, de->d_name);3613if(stat(git_path("logs/%s", name->buf), &st) <0) {3614;/* silently ignore */3615}else{3616if(S_ISDIR(st.st_mode)) {3617strbuf_addch(name,'/');3618 retval =do_for_each_reflog(name, fn, cb_data);3619}else{3620struct object_id oid;36213622if(read_ref_full(name->buf,0, oid.hash, NULL))3623 retval =error("bad ref for%s", name->buf);3624else3625 retval =fn(name->buf, &oid,0, cb_data);3626}3627if(retval)3628break;3629}3630strbuf_setlen(name, oldlen);3631}3632closedir(d);3633return retval;3634}36353636intfor_each_reflog(each_ref_fn fn,void*cb_data)3637{3638int retval;3639struct strbuf name;3640strbuf_init(&name, PATH_MAX);3641 retval =do_for_each_reflog(&name, fn, cb_data);3642strbuf_release(&name);3643return retval;3644}36453646/**3647 * Information needed for a single ref update. Set new_sha1 to the new3648 * value or to null_sha1 to delete the ref. To check the old value3649 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3650 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3651 * not exist before update.3652 */3653struct ref_update {3654/*3655 * If (flags & REF_HAVE_NEW), set the reference to this value:3656 */3657unsigned char new_sha1[20];3658/*3659 * If (flags & REF_HAVE_OLD), check that the reference3660 * previously had this value:3661 */3662unsigned char old_sha1[20];3663/*3664 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3665 * REF_DELETING, and REF_ISPRUNING:3666 */3667unsigned int flags;3668struct ref_lock *lock;3669int type;3670char*msg;3671const char refname[FLEX_ARRAY];3672};36733674/*3675 * Transaction states.3676 * OPEN: The transaction is in a valid state and can accept new updates.3677 * An OPEN transaction can be committed.3678 * CLOSED: A closed transaction is no longer active and no other operations3679 * than free can be used on it in this state.3680 * A transaction can either become closed by successfully committing3681 * an active transaction or if there is a failure while building3682 * the transaction thus rendering it failed/inactive.3683 */3684enum ref_transaction_state {3685 REF_TRANSACTION_OPEN =0,3686 REF_TRANSACTION_CLOSED =13687};36883689/*3690 * Data structure for holding a reference transaction, which can3691 * consist of checks and updates to multiple references, carried out3692 * as atomically as possible. This structure is opaque to callers.3693 */3694struct ref_transaction {3695struct ref_update **updates;3696size_t alloc;3697size_t nr;3698enum ref_transaction_state state;3699};37003701struct ref_transaction *ref_transaction_begin(struct strbuf *err)3702{3703assert(err);37043705returnxcalloc(1,sizeof(struct ref_transaction));3706}37073708voidref_transaction_free(struct ref_transaction *transaction)3709{3710int i;37113712if(!transaction)3713return;37143715for(i =0; i < transaction->nr; i++) {3716free(transaction->updates[i]->msg);3717free(transaction->updates[i]);3718}3719free(transaction->updates);3720free(transaction);3721}37223723static struct ref_update *add_update(struct ref_transaction *transaction,3724const char*refname)3725{3726size_t len =strlen(refname);3727struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);37283729strcpy((char*)update->refname, refname);3730ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3731 transaction->updates[transaction->nr++] = update;3732return update;3733}37343735intref_transaction_update(struct ref_transaction *transaction,3736const char*refname,3737const unsigned char*new_sha1,3738const unsigned char*old_sha1,3739unsigned int flags,const char*msg,3740struct strbuf *err)3741{3742struct ref_update *update;37433744assert(err);37453746if(transaction->state != REF_TRANSACTION_OPEN)3747die("BUG: update called for transaction that is not open");37483749if(new_sha1 && !is_null_sha1(new_sha1) &&3750check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3751strbuf_addf(err,"refusing to update ref with bad name%s",3752 refname);3753return-1;3754}37553756 update =add_update(transaction, refname);3757if(new_sha1) {3758hashcpy(update->new_sha1, new_sha1);3759 flags |= REF_HAVE_NEW;3760}3761if(old_sha1) {3762hashcpy(update->old_sha1, old_sha1);3763 flags |= REF_HAVE_OLD;3764}3765 update->flags = flags;3766if(msg)3767 update->msg =xstrdup(msg);3768return0;3769}37703771intref_transaction_create(struct ref_transaction *transaction,3772const char*refname,3773const unsigned char*new_sha1,3774unsigned int flags,const char*msg,3775struct strbuf *err)3776{3777if(!new_sha1 ||is_null_sha1(new_sha1))3778die("BUG: create called without valid new_sha1");3779returnref_transaction_update(transaction, refname, new_sha1,3780 null_sha1, flags, msg, err);3781}37823783intref_transaction_delete(struct ref_transaction *transaction,3784const char*refname,3785const unsigned char*old_sha1,3786unsigned int flags,const char*msg,3787struct strbuf *err)3788{3789if(old_sha1 &&is_null_sha1(old_sha1))3790die("BUG: delete called with old_sha1 set to zeros");3791returnref_transaction_update(transaction, refname,3792 null_sha1, old_sha1,3793 flags, msg, err);3794}37953796intref_transaction_verify(struct ref_transaction *transaction,3797const char*refname,3798const unsigned char*old_sha1,3799unsigned int flags,3800struct strbuf *err)3801{3802if(!old_sha1)3803die("BUG: verify called with old_sha1 set to NULL");3804returnref_transaction_update(transaction, refname,3805 NULL, old_sha1,3806 flags, NULL, err);3807}38083809intupdate_ref(const char*msg,const char*refname,3810const unsigned char*new_sha1,const unsigned char*old_sha1,3811unsigned int flags,enum action_on_err onerr)3812{3813struct ref_transaction *t;3814struct strbuf err = STRBUF_INIT;38153816 t =ref_transaction_begin(&err);3817if(!t ||3818ref_transaction_update(t, refname, new_sha1, old_sha1,3819 flags, msg, &err) ||3820ref_transaction_commit(t, &err)) {3821const char*str ="update_ref failed for ref '%s':%s";38223823ref_transaction_free(t);3824switch(onerr) {3825case UPDATE_REFS_MSG_ON_ERR:3826error(str, refname, err.buf);3827break;3828case UPDATE_REFS_DIE_ON_ERR:3829die(str, refname, err.buf);3830break;3831case UPDATE_REFS_QUIET_ON_ERR:3832break;3833}3834strbuf_release(&err);3835return1;3836}3837strbuf_release(&err);3838ref_transaction_free(t);3839return0;3840}38413842static intref_update_reject_duplicates(struct string_list *refnames,3843struct strbuf *err)3844{3845int i, n = refnames->nr;38463847assert(err);38483849for(i =1; i < n; i++)3850if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3851strbuf_addf(err,3852"Multiple updates for ref '%s' not allowed.",3853 refnames->items[i].string);3854return1;3855}3856return0;3857}38583859intref_transaction_commit(struct ref_transaction *transaction,3860struct strbuf *err)3861{3862int ret =0, i;3863int n = transaction->nr;3864struct ref_update **updates = transaction->updates;3865struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3866struct string_list_item *ref_to_delete;3867struct string_list affected_refnames = STRING_LIST_INIT_NODUP;38683869assert(err);38703871if(transaction->state != REF_TRANSACTION_OPEN)3872die("BUG: commit called for transaction that is not open");38733874if(!n) {3875 transaction->state = REF_TRANSACTION_CLOSED;3876return0;3877}38783879/* Fail if a refname appears more than once in the transaction: */3880for(i =0; i < n; i++)3881string_list_append(&affected_refnames, updates[i]->refname);3882string_list_sort(&affected_refnames);3883if(ref_update_reject_duplicates(&affected_refnames, err)) {3884 ret = TRANSACTION_GENERIC_ERROR;3885goto cleanup;3886}38873888/*3889 * Acquire all locks, verify old values if provided, check3890 * that new values are valid, and write new values to the3891 * lockfiles, ready to be activated. Only keep one lockfile3892 * open at a time to avoid running out of file descriptors.3893 */3894for(i =0; i < n; i++) {3895struct ref_update *update = updates[i];38963897if((update->flags & REF_HAVE_NEW) &&3898is_null_sha1(update->new_sha1))3899 update->flags |= REF_DELETING;3900 update->lock =lock_ref_sha1_basic(3901 update->refname,3902((update->flags & REF_HAVE_OLD) ?3903 update->old_sha1 : NULL),3904&affected_refnames, NULL,3905 update->flags,3906&update->type,3907 err);3908if(!update->lock) {3909char*reason;39103911 ret = (errno == ENOTDIR)3912? TRANSACTION_NAME_CONFLICT3913: TRANSACTION_GENERIC_ERROR;3914 reason =strbuf_detach(err, NULL);3915strbuf_addf(err,"Cannot lock ref '%s':%s",3916 update->refname, reason);3917free(reason);3918goto cleanup;3919}3920if((update->flags & REF_HAVE_NEW) &&3921!(update->flags & REF_DELETING)) {3922int overwriting_symref = ((update->type & REF_ISSYMREF) &&3923(update->flags & REF_NODEREF));39243925if(!overwriting_symref &&3926!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {3927/*3928 * The reference already has the desired3929 * value, so we don't need to write it.3930 */3931}else if(write_ref_to_lockfile(update->lock,3932 update->new_sha1)) {3933/*3934 * The lock was freed upon failure of3935 * write_ref_to_lockfile():3936 */3937 update->lock = NULL;3938strbuf_addf(err,"Cannot update the ref '%s'.",3939 update->refname);3940 ret = TRANSACTION_GENERIC_ERROR;3941goto cleanup;3942}else{3943 update->flags |= REF_NEEDS_COMMIT;3944}3945}3946if(!(update->flags & REF_NEEDS_COMMIT)) {3947/*3948 * We didn't have to write anything to the lockfile.3949 * Close it to free up the file descriptor:3950 */3951if(close_ref(update->lock)) {3952strbuf_addf(err,"Couldn't close%s.lock",3953 update->refname);3954goto cleanup;3955}3956}3957}39583959/* Perform updates first so live commits remain referenced */3960for(i =0; i < n; i++) {3961struct ref_update *update = updates[i];39623963if(update->flags & REF_NEEDS_COMMIT) {3964if(commit_ref_update(update->lock,3965 update->new_sha1, update->msg)) {3966/* freed by commit_ref_update(): */3967 update->lock = NULL;3968strbuf_addf(err,"Cannot update the ref '%s'.",3969 update->refname);3970 ret = TRANSACTION_GENERIC_ERROR;3971goto cleanup;3972}else{3973/* freed by commit_ref_update(): */3974 update->lock = NULL;3975}3976}3977}39783979/* Perform deletes now that updates are safely completed */3980for(i =0; i < n; i++) {3981struct ref_update *update = updates[i];39823983if(update->flags & REF_DELETING) {3984if(delete_ref_loose(update->lock, update->type, err)) {3985 ret = TRANSACTION_GENERIC_ERROR;3986goto cleanup;3987}39883989if(!(update->flags & REF_ISPRUNING))3990string_list_append(&refs_to_delete,3991 update->lock->ref_name);3992}3993}39943995if(repack_without_refs(&refs_to_delete, err)) {3996 ret = TRANSACTION_GENERIC_ERROR;3997goto cleanup;3998}3999for_each_string_list_item(ref_to_delete, &refs_to_delete)4000unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4001clear_loose_ref_cache(&ref_cache);40024003cleanup:4004 transaction->state = REF_TRANSACTION_CLOSED;40054006for(i =0; i < n; i++)4007if(updates[i]->lock)4008unlock_ref(updates[i]->lock);4009string_list_clear(&refs_to_delete,0);4010string_list_clear(&affected_refnames,0);4011return ret;4012}40134014char*shorten_unambiguous_ref(const char*refname,int strict)4015{4016int i;4017static char**scanf_fmts;4018static int nr_rules;4019char*short_name;40204021if(!nr_rules) {4022/*4023 * Pre-generate scanf formats from ref_rev_parse_rules[].4024 * Generate a format suitable for scanf from a4025 * ref_rev_parse_rules rule by interpolating "%s" at the4026 * location of the "%.*s".4027 */4028size_t total_len =0;4029size_t offset =0;40304031/* the rule list is NULL terminated, count them first */4032for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4033/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4034 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;40354036 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);40374038 offset =0;4039for(i =0; i < nr_rules; i++) {4040assert(offset < total_len);4041 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4042 offset +=snprintf(scanf_fmts[i], total_len - offset,4043 ref_rev_parse_rules[i],2,"%s") +1;4044}4045}40464047/* bail out if there are no rules */4048if(!nr_rules)4049returnxstrdup(refname);40504051/* buffer for scanf result, at most refname must fit */4052 short_name =xstrdup(refname);40534054/* skip first rule, it will always match */4055for(i = nr_rules -1; i >0; --i) {4056int j;4057int rules_to_fail = i;4058int short_name_len;40594060if(1!=sscanf(refname, scanf_fmts[i], short_name))4061continue;40624063 short_name_len =strlen(short_name);40644065/*4066 * in strict mode, all (except the matched one) rules4067 * must fail to resolve to a valid non-ambiguous ref4068 */4069if(strict)4070 rules_to_fail = nr_rules;40714072/*4073 * check if the short name resolves to a valid ref,4074 * but use only rules prior to the matched one4075 */4076for(j =0; j < rules_to_fail; j++) {4077const char*rule = ref_rev_parse_rules[j];4078char refname[PATH_MAX];40794080/* skip matched rule */4081if(i == j)4082continue;40834084/*4085 * the short name is ambiguous, if it resolves4086 * (with this previous rule) to a valid ref4087 * read_ref() returns 0 on success4088 */4089mksnpath(refname,sizeof(refname),4090 rule, short_name_len, short_name);4091if(ref_exists(refname))4092break;4093}40944095/*4096 * short name is non-ambiguous if all previous rules4097 * haven't resolved to a valid ref4098 */4099if(j == rules_to_fail)4100return short_name;4101}41024103free(short_name);4104returnxstrdup(refname);4105}41064107static struct string_list *hide_refs;41084109intparse_hide_refs_config(const char*var,const char*value,const char*section)4110{4111if(!strcmp("transfer.hiderefs", var) ||4112/* NEEDSWORK: use parse_config_key() once both are merged */4113(starts_with(var, section) && var[strlen(section)] =='.'&&4114!strcmp(var +strlen(section),".hiderefs"))) {4115char*ref;4116int len;41174118if(!value)4119returnconfig_error_nonbool(var);4120 ref =xstrdup(value);4121 len =strlen(ref);4122while(len && ref[len -1] =='/')4123 ref[--len] ='\0';4124if(!hide_refs) {4125 hide_refs =xcalloc(1,sizeof(*hide_refs));4126 hide_refs->strdup_strings =1;4127}4128string_list_append(hide_refs, ref);4129}4130return0;4131}41324133intref_is_hidden(const char*refname)4134{4135struct string_list_item *item;41364137if(!hide_refs)4138return0;4139for_each_string_list_item(item, hide_refs) {4140int len;4141if(!starts_with(refname, item->string))4142continue;4143 len =strlen(item->string);4144if(!refname[len] || refname[len] =='/')4145return1;4146}4147return0;4148}41494150struct expire_reflog_cb {4151unsigned int flags;4152 reflog_expiry_should_prune_fn *should_prune_fn;4153void*policy_cb;4154FILE*newlog;4155unsigned char last_kept_sha1[20];4156};41574158static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4159const char*email,unsigned long timestamp,int tz,4160const char*message,void*cb_data)4161{4162struct expire_reflog_cb *cb = cb_data;4163struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;41644165if(cb->flags & EXPIRE_REFLOGS_REWRITE)4166 osha1 = cb->last_kept_sha1;41674168if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4169 message, policy_cb)) {4170if(!cb->newlog)4171printf("would prune%s", message);4172else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4173printf("prune%s", message);4174}else{4175if(cb->newlog) {4176fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4177sha1_to_hex(osha1),sha1_to_hex(nsha1),4178 email, timestamp, tz, message);4179hashcpy(cb->last_kept_sha1, nsha1);4180}4181if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4182printf("keep%s", message);4183}4184return0;4185}41864187intreflog_expire(const char*refname,const unsigned char*sha1,4188unsigned int flags,4189 reflog_expiry_prepare_fn prepare_fn,4190 reflog_expiry_should_prune_fn should_prune_fn,4191 reflog_expiry_cleanup_fn cleanup_fn,4192void*policy_cb_data)4193{4194static struct lock_file reflog_lock;4195struct expire_reflog_cb cb;4196struct ref_lock *lock;4197char*log_file;4198int status =0;4199int type;4200struct strbuf err = STRBUF_INIT;42014202memset(&cb,0,sizeof(cb));4203 cb.flags = flags;4204 cb.policy_cb = policy_cb_data;4205 cb.should_prune_fn = should_prune_fn;42064207/*4208 * The reflog file is locked by holding the lock on the4209 * reference itself, plus we might need to update the4210 * reference if --updateref was specified:4211 */4212 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4213if(!lock) {4214error("cannot lock ref '%s':%s", refname, err.buf);4215strbuf_release(&err);4216return-1;4217}4218if(!reflog_exists(refname)) {4219unlock_ref(lock);4220return0;4221}42224223 log_file =git_pathdup("logs/%s", refname);4224if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4225/*4226 * Even though holding $GIT_DIR/logs/$reflog.lock has4227 * no locking implications, we use the lock_file4228 * machinery here anyway because it does a lot of the4229 * work we need, including cleaning up if the program4230 * exits unexpectedly.4231 */4232if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4233struct strbuf err = STRBUF_INIT;4234unable_to_lock_message(log_file, errno, &err);4235error("%s", err.buf);4236strbuf_release(&err);4237goto failure;4238}4239 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4240if(!cb.newlog) {4241error("cannot fdopen%s(%s)",4242 reflog_lock.filename.buf,strerror(errno));4243goto failure;4244}4245}42464247(*prepare_fn)(refname, sha1, cb.policy_cb);4248for_each_reflog_ent(refname, expire_reflog_ent, &cb);4249(*cleanup_fn)(cb.policy_cb);42504251if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4252/*4253 * It doesn't make sense to adjust a reference pointed4254 * to by a symbolic ref based on expiring entries in4255 * the symbolic reference's reflog. Nor can we update4256 * a reference if there are no remaining reflog4257 * entries.4258 */4259int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4260!(type & REF_ISSYMREF) &&4261!is_null_sha1(cb.last_kept_sha1);42624263if(close_lock_file(&reflog_lock)) {4264 status |=error("couldn't write%s:%s", log_file,4265strerror(errno));4266}else if(update &&4267(write_in_full(lock->lk->fd,4268sha1_to_hex(cb.last_kept_sha1),40) !=40||4269write_str_in_full(lock->lk->fd,"\n") !=1||4270close_ref(lock) <0)) {4271 status |=error("couldn't write%s",4272 lock->lk->filename.buf);4273rollback_lock_file(&reflog_lock);4274}else if(commit_lock_file(&reflog_lock)) {4275 status |=error("unable to commit reflog '%s' (%s)",4276 log_file,strerror(errno));4277}else if(update &&commit_ref(lock)) {4278 status |=error("couldn't set%s", lock->ref_name);4279}4280}4281free(log_file);4282unlock_ref(lock);4283return status;42844285 failure:4286rollback_lock_file(&reflog_lock);4287free(log_file);4288unlock_ref(lock);4289return-1;4290}