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 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a 67 * value to ref_update::flags 68 */ 69 70/* 71 * Try to read one refname component from the front of refname. 72 * Return the length of the component found, or -1 if the component is 73 * not legal. It is legal if it is something reasonable to have under 74 * ".git/refs/"; We do not like it if: 75 * 76 * - any path component of it begins with ".", or 77 * - it has double dots "..", or 78 * - it has ASCII control character, "~", "^", ":" or SP, anywhere, or 79 * - it ends with a "/". 80 * - it ends with ".lock" 81 * - it contains a "\" (backslash) 82 */ 83static intcheck_refname_component(const char*refname,int flags) 84{ 85const char*cp; 86char last ='\0'; 87 88for(cp = refname; ; cp++) { 89int ch = *cp &255; 90unsigned char disp = refname_disposition[ch]; 91switch(disp) { 92case1: 93goto out; 94case2: 95if(last =='.') 96return-1;/* Refname contains "..". */ 97break; 98case3: 99if(last =='@') 100return-1;/* Refname contains "@{". */ 101break; 102case4: 103return-1; 104} 105 last = ch; 106} 107out: 108if(cp == refname) 109return0;/* Component has zero length. */ 110if(refname[0] =='.') 111return-1;/* Component starts with '.'. */ 112if(cp - refname >= LOCK_SUFFIX_LEN && 113!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 114return-1;/* Refname ends with ".lock". */ 115return cp - refname; 116} 117 118intcheck_refname_format(const char*refname,int flags) 119{ 120int component_len, component_count =0; 121 122if(!strcmp(refname,"@")) 123/* Refname is a single character '@'. */ 124return-1; 125 126while(1) { 127/* We are at the start of a path component. */ 128 component_len =check_refname_component(refname, flags); 129if(component_len <=0) { 130if((flags & REFNAME_REFSPEC_PATTERN) && 131 refname[0] =='*'&& 132(refname[1] =='\0'|| refname[1] =='/')) { 133/* Accept one wildcard as a full refname component. */ 134 flags &= ~REFNAME_REFSPEC_PATTERN; 135 component_len =1; 136}else{ 137return-1; 138} 139} 140 component_count++; 141if(refname[component_len] =='\0') 142break; 143/* Skip to next component. */ 144 refname += component_len +1; 145} 146 147if(refname[component_len -1] =='.') 148return-1;/* Refname ends with '.'. */ 149if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 150return-1;/* Refname has only one component. */ 151return0; 152} 153 154struct ref_entry; 155 156/* 157 * Information used (along with the information in ref_entry) to 158 * describe a single cached reference. This data structure only 159 * occurs embedded in a union in struct ref_entry, and only when 160 * (ref_entry->flag & REF_DIR) is zero. 161 */ 162struct ref_value { 163/* 164 * The name of the object to which this reference resolves 165 * (which may be a tag object). If REF_ISBROKEN, this is 166 * null. If REF_ISSYMREF, then this is the name of the object 167 * referred to by the last reference in the symlink chain. 168 */ 169struct object_id oid; 170 171/* 172 * If REF_KNOWS_PEELED, then this field holds the peeled value 173 * of this reference, or null if the reference is known not to 174 * be peelable. See the documentation for peel_ref() for an 175 * exact definition of "peelable". 176 */ 177struct object_id peeled; 178}; 179 180struct ref_cache; 181 182/* 183 * Information used (along with the information in ref_entry) to 184 * describe a level in the hierarchy of references. This data 185 * structure only occurs embedded in a union in struct ref_entry, and 186 * only when (ref_entry.flag & REF_DIR) is set. In that case, 187 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 188 * in the directory have already been read: 189 * 190 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 191 * or packed references, already read. 192 * 193 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 194 * references that hasn't been read yet (nor has any of its 195 * subdirectories). 196 * 197 * Entries within a directory are stored within a growable array of 198 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 199 * sorted are sorted by their component name in strcmp() order and the 200 * remaining entries are unsorted. 201 * 202 * Loose references are read lazily, one directory at a time. When a 203 * directory of loose references is read, then all of the references 204 * in that directory are stored, and REF_INCOMPLETE stubs are created 205 * for any subdirectories, but the subdirectories themselves are not 206 * read. The reading is triggered by get_ref_dir(). 207 */ 208struct ref_dir { 209int nr, alloc; 210 211/* 212 * Entries with index 0 <= i < sorted are sorted by name. New 213 * entries are appended to the list unsorted, and are sorted 214 * only when required; thus we avoid the need to sort the list 215 * after the addition of every reference. 216 */ 217int sorted; 218 219/* A pointer to the ref_cache that contains this ref_dir. */ 220struct ref_cache *ref_cache; 221 222struct ref_entry **entries; 223}; 224 225/* 226 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 227 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 228 * public values; see refs.h. 229 */ 230 231/* 232 * The field ref_entry->u.value.peeled of this value entry contains 233 * the correct peeled value for the reference, which might be 234 * null_sha1 if the reference is not a tag or if it is broken. 235 */ 236#define REF_KNOWS_PEELED 0x10 237 238/* ref_entry represents a directory of references */ 239#define REF_DIR 0x20 240 241/* 242 * Entry has not yet been read from disk (used only for REF_DIR 243 * entries representing loose references) 244 */ 245#define REF_INCOMPLETE 0x40 246 247/* 248 * A ref_entry represents either a reference or a "subdirectory" of 249 * references. 250 * 251 * Each directory in the reference namespace is represented by a 252 * ref_entry with (flags & REF_DIR) set and containing a subdir member 253 * that holds the entries in that directory that have been read so 254 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 255 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 256 * used for loose reference directories. 257 * 258 * References are represented by a ref_entry with (flags & REF_DIR) 259 * unset and a value member that describes the reference's value. The 260 * flag member is at the ref_entry level, but it is also needed to 261 * interpret the contents of the value field (in other words, a 262 * ref_value object is not very much use without the enclosing 263 * ref_entry). 264 * 265 * Reference names cannot end with slash and directories' names are 266 * always stored with a trailing slash (except for the top-level 267 * directory, which is always denoted by ""). This has two nice 268 * consequences: (1) when the entries in each subdir are sorted 269 * lexicographically by name (as they usually are), the references in 270 * a whole tree can be generated in lexicographic order by traversing 271 * the tree in left-to-right, depth-first order; (2) the names of 272 * references and subdirectories cannot conflict, and therefore the 273 * presence of an empty subdirectory does not block the creation of a 274 * similarly-named reference. (The fact that reference names with the 275 * same leading components can conflict *with each other* is a 276 * separate issue that is regulated by verify_refname_available().) 277 * 278 * Please note that the name field contains the fully-qualified 279 * reference (or subdirectory) name. Space could be saved by only 280 * storing the relative names. But that would require the full names 281 * to be generated on the fly when iterating in do_for_each_ref(), and 282 * would break callback functions, who have always been able to assume 283 * that the name strings that they are passed will not be freed during 284 * the iteration. 285 */ 286struct ref_entry { 287unsigned char flag;/* ISSYMREF? ISPACKED? */ 288union{ 289struct ref_value value;/* if not (flags&REF_DIR) */ 290struct ref_dir subdir;/* if (flags&REF_DIR) */ 291} u; 292/* 293 * The full name of the reference (e.g., "refs/heads/master") 294 * or the full name of the directory with a trailing slash 295 * (e.g., "refs/heads/"): 296 */ 297char name[FLEX_ARRAY]; 298}; 299 300static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 301 302static struct ref_dir *get_ref_dir(struct ref_entry *entry) 303{ 304struct ref_dir *dir; 305assert(entry->flag & REF_DIR); 306 dir = &entry->u.subdir; 307if(entry->flag & REF_INCOMPLETE) { 308read_loose_refs(entry->name, dir); 309 entry->flag &= ~REF_INCOMPLETE; 310} 311return dir; 312} 313 314/* 315 * Check if a refname is safe. 316 * For refs that start with "refs/" we consider it safe as long they do 317 * not try to resolve to outside of refs/. 318 * 319 * For all other refs we only consider them safe iff they only contain 320 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 321 * "config"). 322 */ 323static intrefname_is_safe(const char*refname) 324{ 325if(starts_with(refname,"refs/")) { 326char*buf; 327int result; 328 329 buf =xmalloc(strlen(refname) +1); 330/* 331 * Does the refname try to escape refs/? 332 * For example: refs/foo/../bar is safe but refs/foo/../../bar 333 * is not. 334 */ 335 result = !normalize_path_copy(buf, refname +strlen("refs/")); 336free(buf); 337return result; 338} 339while(*refname) { 340if(!isupper(*refname) && *refname !='_') 341return0; 342 refname++; 343} 344return1; 345} 346 347static struct ref_entry *create_ref_entry(const char*refname, 348const unsigned char*sha1,int flag, 349int check_name) 350{ 351int len; 352struct ref_entry *ref; 353 354if(check_name && 355check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 356die("Reference has invalid format: '%s'", refname); 357 len =strlen(refname) +1; 358 ref =xmalloc(sizeof(struct ref_entry) + len); 359hashcpy(ref->u.value.oid.hash, sha1); 360oidclr(&ref->u.value.peeled); 361memcpy(ref->name, refname, len); 362 ref->flag = flag; 363return ref; 364} 365 366static voidclear_ref_dir(struct ref_dir *dir); 367 368static voidfree_ref_entry(struct ref_entry *entry) 369{ 370if(entry->flag & REF_DIR) { 371/* 372 * Do not use get_ref_dir() here, as that might 373 * trigger the reading of loose refs. 374 */ 375clear_ref_dir(&entry->u.subdir); 376} 377free(entry); 378} 379 380/* 381 * Add a ref_entry to the end of dir (unsorted). Entry is always 382 * stored directly in dir; no recursion into subdirectories is 383 * done. 384 */ 385static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 386{ 387ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 388 dir->entries[dir->nr++] = entry; 389/* optimize for the case that entries are added in order */ 390if(dir->nr ==1|| 391(dir->nr == dir->sorted +1&& 392strcmp(dir->entries[dir->nr -2]->name, 393 dir->entries[dir->nr -1]->name) <0)) 394 dir->sorted = dir->nr; 395} 396 397/* 398 * Clear and free all entries in dir, recursively. 399 */ 400static voidclear_ref_dir(struct ref_dir *dir) 401{ 402int i; 403for(i =0; i < dir->nr; i++) 404free_ref_entry(dir->entries[i]); 405free(dir->entries); 406 dir->sorted = dir->nr = dir->alloc =0; 407 dir->entries = NULL; 408} 409 410/* 411 * Create a struct ref_entry object for the specified dirname. 412 * dirname is the name of the directory with a trailing slash (e.g., 413 * "refs/heads/") or "" for the top-level directory. 414 */ 415static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 416const char*dirname,size_t len, 417int incomplete) 418{ 419struct ref_entry *direntry; 420 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 421memcpy(direntry->name, dirname, len); 422 direntry->name[len] ='\0'; 423 direntry->u.subdir.ref_cache = ref_cache; 424 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 425return direntry; 426} 427 428static intref_entry_cmp(const void*a,const void*b) 429{ 430struct ref_entry *one = *(struct ref_entry **)a; 431struct ref_entry *two = *(struct ref_entry **)b; 432returnstrcmp(one->name, two->name); 433} 434 435static voidsort_ref_dir(struct ref_dir *dir); 436 437struct string_slice { 438size_t len; 439const char*str; 440}; 441 442static intref_entry_cmp_sslice(const void*key_,const void*ent_) 443{ 444const struct string_slice *key = key_; 445const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 446int cmp =strncmp(key->str, ent->name, key->len); 447if(cmp) 448return cmp; 449return'\0'- (unsigned char)ent->name[key->len]; 450} 451 452/* 453 * Return the index of the entry with the given refname from the 454 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 455 * no such entry is found. dir must already be complete. 456 */ 457static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 458{ 459struct ref_entry **r; 460struct string_slice key; 461 462if(refname == NULL || !dir->nr) 463return-1; 464 465sort_ref_dir(dir); 466 key.len = len; 467 key.str = refname; 468 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 469 ref_entry_cmp_sslice); 470 471if(r == NULL) 472return-1; 473 474return r - dir->entries; 475} 476 477/* 478 * Search for a directory entry directly within dir (without 479 * recursing). Sort dir if necessary. subdirname must be a directory 480 * name (i.e., end in '/'). If mkdir is set, then create the 481 * directory if it is missing; otherwise, return NULL if the desired 482 * directory cannot be found. dir must already be complete. 483 */ 484static struct ref_dir *search_for_subdir(struct ref_dir *dir, 485const char*subdirname,size_t len, 486int mkdir) 487{ 488int entry_index =search_ref_dir(dir, subdirname, len); 489struct ref_entry *entry; 490if(entry_index == -1) { 491if(!mkdir) 492return NULL; 493/* 494 * Since dir is complete, the absence of a subdir 495 * means that the subdir really doesn't exist; 496 * therefore, create an empty record for it but mark 497 * the record complete. 498 */ 499 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 500add_entry_to_dir(dir, entry); 501}else{ 502 entry = dir->entries[entry_index]; 503} 504returnget_ref_dir(entry); 505} 506 507/* 508 * If refname is a reference name, find the ref_dir within the dir 509 * tree that should hold refname. If refname is a directory name 510 * (i.e., ends in '/'), then return that ref_dir itself. dir must 511 * represent the top-level directory and must already be complete. 512 * Sort ref_dirs and recurse into subdirectories as necessary. If 513 * mkdir is set, then create any missing directories; otherwise, 514 * return NULL if the desired directory cannot be found. 515 */ 516static struct ref_dir *find_containing_dir(struct ref_dir *dir, 517const char*refname,int mkdir) 518{ 519const char*slash; 520for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 521size_t dirnamelen = slash - refname +1; 522struct ref_dir *subdir; 523 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 524if(!subdir) { 525 dir = NULL; 526break; 527} 528 dir = subdir; 529} 530 531return dir; 532} 533 534/* 535 * Find the value entry with the given name in dir, sorting ref_dirs 536 * and recursing into subdirectories as necessary. If the name is not 537 * found or it corresponds to a directory entry, return NULL. 538 */ 539static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 540{ 541int entry_index; 542struct ref_entry *entry; 543 dir =find_containing_dir(dir, refname,0); 544if(!dir) 545return NULL; 546 entry_index =search_ref_dir(dir, refname,strlen(refname)); 547if(entry_index == -1) 548return NULL; 549 entry = dir->entries[entry_index]; 550return(entry->flag & REF_DIR) ? NULL : entry; 551} 552 553/* 554 * Remove the entry with the given name from dir, recursing into 555 * subdirectories as necessary. If refname is the name of a directory 556 * (i.e., ends with '/'), then remove the directory and its contents. 557 * If the removal was successful, return the number of entries 558 * remaining in the directory entry that contained the deleted entry. 559 * If the name was not found, return -1. Please note that this 560 * function only deletes the entry from the cache; it does not delete 561 * it from the filesystem or ensure that other cache entries (which 562 * might be symbolic references to the removed entry) are updated. 563 * Nor does it remove any containing dir entries that might be made 564 * empty by the removal. dir must represent the top-level directory 565 * and must already be complete. 566 */ 567static intremove_entry(struct ref_dir *dir,const char*refname) 568{ 569int refname_len =strlen(refname); 570int entry_index; 571struct ref_entry *entry; 572int is_dir = refname[refname_len -1] =='/'; 573if(is_dir) { 574/* 575 * refname represents a reference directory. Remove 576 * the trailing slash; otherwise we will get the 577 * directory *representing* refname rather than the 578 * one *containing* it. 579 */ 580char*dirname =xmemdupz(refname, refname_len -1); 581 dir =find_containing_dir(dir, dirname,0); 582free(dirname); 583}else{ 584 dir =find_containing_dir(dir, refname,0); 585} 586if(!dir) 587return-1; 588 entry_index =search_ref_dir(dir, refname, refname_len); 589if(entry_index == -1) 590return-1; 591 entry = dir->entries[entry_index]; 592 593memmove(&dir->entries[entry_index], 594&dir->entries[entry_index +1], 595(dir->nr - entry_index -1) *sizeof(*dir->entries) 596); 597 dir->nr--; 598if(dir->sorted > entry_index) 599 dir->sorted--; 600free_ref_entry(entry); 601return dir->nr; 602} 603 604/* 605 * Add a ref_entry to the ref_dir (unsorted), recursing into 606 * subdirectories as necessary. dir must represent the top-level 607 * directory. Return 0 on success. 608 */ 609static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 610{ 611 dir =find_containing_dir(dir, ref->name,1); 612if(!dir) 613return-1; 614add_entry_to_dir(dir, ref); 615return0; 616} 617 618/* 619 * Emit a warning and return true iff ref1 and ref2 have the same name 620 * and the same sha1. Die if they have the same name but different 621 * sha1s. 622 */ 623static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 624{ 625if(strcmp(ref1->name, ref2->name)) 626return0; 627 628/* Duplicate name; make sure that they don't conflict: */ 629 630if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 631/* This is impossible by construction */ 632die("Reference directory conflict:%s", ref1->name); 633 634if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 635die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 636 637warning("Duplicated ref:%s", ref1->name); 638return1; 639} 640 641/* 642 * Sort the entries in dir non-recursively (if they are not already 643 * sorted) and remove any duplicate entries. 644 */ 645static voidsort_ref_dir(struct ref_dir *dir) 646{ 647int i, j; 648struct ref_entry *last = NULL; 649 650/* 651 * This check also prevents passing a zero-length array to qsort(), 652 * which is a problem on some platforms. 653 */ 654if(dir->sorted == dir->nr) 655return; 656 657qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 658 659/* Remove any duplicates: */ 660for(i =0, j =0; j < dir->nr; j++) { 661struct ref_entry *entry = dir->entries[j]; 662if(last &&is_dup_ref(last, entry)) 663free_ref_entry(entry); 664else 665 last = dir->entries[i++] = entry; 666} 667 dir->sorted = dir->nr = i; 668} 669 670/* Include broken references in a do_for_each_ref*() iteration: */ 671#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 672 673/* 674 * Return true iff the reference described by entry can be resolved to 675 * an object in the database. Emit a warning if the referred-to 676 * object does not exist. 677 */ 678static intref_resolves_to_object(struct ref_entry *entry) 679{ 680if(entry->flag & REF_ISBROKEN) 681return0; 682if(!has_sha1_file(entry->u.value.oid.hash)) { 683error("%sdoes not point to a valid object!", entry->name); 684return0; 685} 686return1; 687} 688 689/* 690 * current_ref is a performance hack: when iterating over references 691 * using the for_each_ref*() functions, current_ref is set to the 692 * current reference's entry before calling the callback function. If 693 * the callback function calls peel_ref(), then peel_ref() first 694 * checks whether the reference to be peeled is the current reference 695 * (it usually is) and if so, returns that reference's peeled version 696 * if it is available. This avoids a refname lookup in a common case. 697 */ 698static struct ref_entry *current_ref; 699 700typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 701 702struct ref_entry_cb { 703const char*base; 704int trim; 705int flags; 706 each_ref_fn *fn; 707void*cb_data; 708}; 709 710/* 711 * Handle one reference in a do_for_each_ref*()-style iteration, 712 * calling an each_ref_fn for each entry. 713 */ 714static intdo_one_ref(struct ref_entry *entry,void*cb_data) 715{ 716struct ref_entry_cb *data = cb_data; 717struct ref_entry *old_current_ref; 718int retval; 719 720if(!starts_with(entry->name, data->base)) 721return0; 722 723if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 724!ref_resolves_to_object(entry)) 725return0; 726 727/* Store the old value, in case this is a recursive call: */ 728 old_current_ref = current_ref; 729 current_ref = entry; 730 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 731 entry->flag, data->cb_data); 732 current_ref = old_current_ref; 733return retval; 734} 735 736/* 737 * Call fn for each reference in dir that has index in the range 738 * offset <= index < dir->nr. Recurse into subdirectories that are in 739 * that index range, sorting them before iterating. This function 740 * does not sort dir itself; it should be sorted beforehand. fn is 741 * called for all references, including broken ones. 742 */ 743static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 744 each_ref_entry_fn fn,void*cb_data) 745{ 746int i; 747assert(dir->sorted == dir->nr); 748for(i = offset; i < dir->nr; i++) { 749struct ref_entry *entry = dir->entries[i]; 750int retval; 751if(entry->flag & REF_DIR) { 752struct ref_dir *subdir =get_ref_dir(entry); 753sort_ref_dir(subdir); 754 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 755}else{ 756 retval =fn(entry, cb_data); 757} 758if(retval) 759return retval; 760} 761return0; 762} 763 764/* 765 * Call fn for each reference in the union of dir1 and dir2, in order 766 * by refname. Recurse into subdirectories. If a value entry appears 767 * in both dir1 and dir2, then only process the version that is in 768 * dir2. The input dirs must already be sorted, but subdirs will be 769 * sorted as needed. fn is called for all references, including 770 * broken ones. 771 */ 772static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 773struct ref_dir *dir2, 774 each_ref_entry_fn fn,void*cb_data) 775{ 776int retval; 777int i1 =0, i2 =0; 778 779assert(dir1->sorted == dir1->nr); 780assert(dir2->sorted == dir2->nr); 781while(1) { 782struct ref_entry *e1, *e2; 783int cmp; 784if(i1 == dir1->nr) { 785returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 786} 787if(i2 == dir2->nr) { 788returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 789} 790 e1 = dir1->entries[i1]; 791 e2 = dir2->entries[i2]; 792 cmp =strcmp(e1->name, e2->name); 793if(cmp ==0) { 794if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 795/* Both are directories; descend them in parallel. */ 796struct ref_dir *subdir1 =get_ref_dir(e1); 797struct ref_dir *subdir2 =get_ref_dir(e2); 798sort_ref_dir(subdir1); 799sort_ref_dir(subdir2); 800 retval =do_for_each_entry_in_dirs( 801 subdir1, subdir2, fn, cb_data); 802 i1++; 803 i2++; 804}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 805/* Both are references; ignore the one from dir1. */ 806 retval =fn(e2, cb_data); 807 i1++; 808 i2++; 809}else{ 810die("conflict between reference and directory:%s", 811 e1->name); 812} 813}else{ 814struct ref_entry *e; 815if(cmp <0) { 816 e = e1; 817 i1++; 818}else{ 819 e = e2; 820 i2++; 821} 822if(e->flag & REF_DIR) { 823struct ref_dir *subdir =get_ref_dir(e); 824sort_ref_dir(subdir); 825 retval =do_for_each_entry_in_dir( 826 subdir,0, fn, cb_data); 827}else{ 828 retval =fn(e, cb_data); 829} 830} 831if(retval) 832return retval; 833} 834} 835 836/* 837 * Load all of the refs from the dir into our in-memory cache. The hard work 838 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 839 * through all of the sub-directories. We do not even need to care about 840 * sorting, as traversal order does not matter to us. 841 */ 842static voidprime_ref_dir(struct ref_dir *dir) 843{ 844int i; 845for(i =0; i < dir->nr; i++) { 846struct ref_entry *entry = dir->entries[i]; 847if(entry->flag & REF_DIR) 848prime_ref_dir(get_ref_dir(entry)); 849} 850} 851 852struct nonmatching_ref_data { 853const struct string_list *skip; 854const char*conflicting_refname; 855}; 856 857static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 858{ 859struct nonmatching_ref_data *data = vdata; 860 861if(data->skip &&string_list_has_string(data->skip, entry->name)) 862return0; 863 864 data->conflicting_refname = entry->name; 865return1; 866} 867 868/* 869 * Return 0 if a reference named refname could be created without 870 * conflicting with the name of an existing reference in dir. 871 * Otherwise, return a negative value and write an explanation to err. 872 * If extras is non-NULL, it is a list of additional refnames with 873 * which refname is not allowed to conflict. If skip is non-NULL, 874 * ignore potential conflicts with refs in skip (e.g., because they 875 * are scheduled for deletion in the same operation). Behavior is 876 * undefined if the same name is listed in both extras and skip. 877 * 878 * Two reference names conflict if one of them exactly matches the 879 * leading components of the other; e.g., "refs/foo/bar" conflicts 880 * with both "refs/foo" and with "refs/foo/bar/baz" but not with 881 * "refs/foo/bar" or "refs/foo/barbados". 882 * 883 * extras and skip must be sorted. 884 */ 885static intverify_refname_available(const char*refname, 886const struct string_list *extras, 887const struct string_list *skip, 888struct ref_dir *dir, 889struct strbuf *err) 890{ 891const char*slash; 892int pos; 893struct strbuf dirname = STRBUF_INIT; 894int ret = -1; 895 896/* 897 * For the sake of comments in this function, suppose that 898 * refname is "refs/foo/bar". 899 */ 900 901assert(err); 902 903strbuf_grow(&dirname,strlen(refname) +1); 904for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 905/* Expand dirname to the new prefix, not including the trailing slash: */ 906strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 907 908/* 909 * We are still at a leading dir of the refname (e.g., 910 * "refs/foo"; if there is a reference with that name, 911 * it is a conflict, *unless* it is in skip. 912 */ 913if(dir) { 914 pos =search_ref_dir(dir, dirname.buf, dirname.len); 915if(pos >=0&& 916(!skip || !string_list_has_string(skip, dirname.buf))) { 917/* 918 * We found a reference whose name is 919 * a proper prefix of refname; e.g., 920 * "refs/foo", and is not in skip. 921 */ 922strbuf_addf(err,"'%s' exists; cannot create '%s'", 923 dirname.buf, refname); 924goto cleanup; 925} 926} 927 928if(extras &&string_list_has_string(extras, dirname.buf) && 929(!skip || !string_list_has_string(skip, dirname.buf))) { 930strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 931 refname, dirname.buf); 932goto cleanup; 933} 934 935/* 936 * Otherwise, we can try to continue our search with 937 * the next component. So try to look up the 938 * directory, e.g., "refs/foo/". If we come up empty, 939 * we know there is nothing under this whole prefix, 940 * but even in that case we still have to continue the 941 * search for conflicts with extras. 942 */ 943strbuf_addch(&dirname,'/'); 944if(dir) { 945 pos =search_ref_dir(dir, dirname.buf, dirname.len); 946if(pos <0) { 947/* 948 * There was no directory "refs/foo/", 949 * so there is nothing under this 950 * whole prefix. So there is no need 951 * to continue looking for conflicting 952 * references. But we need to continue 953 * looking for conflicting extras. 954 */ 955 dir = NULL; 956}else{ 957 dir =get_ref_dir(dir->entries[pos]); 958} 959} 960} 961 962/* 963 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 964 * There is no point in searching for a reference with that 965 * name, because a refname isn't considered to conflict with 966 * itself. But we still need to check for references whose 967 * names are in the "refs/foo/bar/" namespace, because they 968 * *do* conflict. 969 */ 970strbuf_addstr(&dirname, refname + dirname.len); 971strbuf_addch(&dirname,'/'); 972 973if(dir) { 974 pos =search_ref_dir(dir, dirname.buf, dirname.len); 975 976if(pos >=0) { 977/* 978 * We found a directory named "$refname/" 979 * (e.g., "refs/foo/bar/"). It is a problem 980 * iff it contains any ref that is not in 981 * "skip". 982 */ 983struct nonmatching_ref_data data; 984 985 data.skip = skip; 986 data.conflicting_refname = NULL; 987 dir =get_ref_dir(dir->entries[pos]); 988sort_ref_dir(dir); 989if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) { 990strbuf_addf(err,"'%s' exists; cannot create '%s'", 991 data.conflicting_refname, refname); 992goto cleanup; 993} 994} 995} 996 997if(extras) { 998/* 999 * Check for entries in extras that start with1000 * "$refname/". We do that by looking for the place1001 * where "$refname/" would be inserted in extras. If1002 * there is an entry at that position that starts with1003 * "$refname/" and is not in skip, then we have a1004 * conflict.1005 */1006for(pos =string_list_find_insert_index(extras, dirname.buf,0);1007 pos < extras->nr; pos++) {1008const char*extra_refname = extras->items[pos].string;10091010if(!starts_with(extra_refname, dirname.buf))1011break;10121013if(!skip || !string_list_has_string(skip, extra_refname)) {1014strbuf_addf(err,"cannot process '%s' and '%s' at the same time",1015 refname, extra_refname);1016goto cleanup;1017}1018}1019}10201021/* No conflicts were found */1022 ret =0;10231024cleanup:1025strbuf_release(&dirname);1026return ret;1027}10281029struct packed_ref_cache {1030struct ref_entry *root;10311032/*1033 * Count of references to the data structure in this instance,1034 * including the pointer from ref_cache::packed if any. The1035 * data will not be freed as long as the reference count is1036 * nonzero.1037 */1038unsigned int referrers;10391040/*1041 * Iff the packed-refs file associated with this instance is1042 * currently locked for writing, this points at the associated1043 * lock (which is owned by somebody else). The referrer count1044 * is also incremented when the file is locked and decremented1045 * when it is unlocked.1046 */1047struct lock_file *lock;10481049/* The metadata from when this packed-refs cache was read */1050struct stat_validity validity;1051};10521053/*1054 * Future: need to be in "struct repository"1055 * when doing a full libification.1056 */1057static struct ref_cache {1058struct ref_cache *next;1059struct ref_entry *loose;1060struct packed_ref_cache *packed;1061/*1062 * The submodule name, or "" for the main repo. We allocate1063 * length 1 rather than FLEX_ARRAY so that the main ref_cache1064 * is initialized correctly.1065 */1066char name[1];1067} ref_cache, *submodule_ref_caches;10681069/* Lock used for the main packed-refs file: */1070static struct lock_file packlock;10711072/*1073 * Increment the reference count of *packed_refs.1074 */1075static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1076{1077 packed_refs->referrers++;1078}10791080/*1081 * Decrease the reference count of *packed_refs. If it goes to zero,1082 * free *packed_refs and return true; otherwise return false.1083 */1084static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1085{1086if(!--packed_refs->referrers) {1087free_ref_entry(packed_refs->root);1088stat_validity_clear(&packed_refs->validity);1089free(packed_refs);1090return1;1091}else{1092return0;1093}1094}10951096static voidclear_packed_ref_cache(struct ref_cache *refs)1097{1098if(refs->packed) {1099struct packed_ref_cache *packed_refs = refs->packed;11001101if(packed_refs->lock)1102die("internal error: packed-ref cache cleared while locked");1103 refs->packed = NULL;1104release_packed_ref_cache(packed_refs);1105}1106}11071108static voidclear_loose_ref_cache(struct ref_cache *refs)1109{1110if(refs->loose) {1111free_ref_entry(refs->loose);1112 refs->loose = NULL;1113}1114}11151116static struct ref_cache *create_ref_cache(const char*submodule)1117{1118int len;1119struct ref_cache *refs;1120if(!submodule)1121 submodule ="";1122 len =strlen(submodule) +1;1123 refs =xcalloc(1,sizeof(struct ref_cache) + len);1124memcpy(refs->name, submodule, len);1125return refs;1126}11271128/*1129 * Return a pointer to a ref_cache for the specified submodule. For1130 * the main repository, use submodule==NULL. The returned structure1131 * will be allocated and initialized but not necessarily populated; it1132 * should not be freed.1133 */1134static struct ref_cache *get_ref_cache(const char*submodule)1135{1136struct ref_cache *refs;11371138if(!submodule || !*submodule)1139return&ref_cache;11401141for(refs = submodule_ref_caches; refs; refs = refs->next)1142if(!strcmp(submodule, refs->name))1143return refs;11441145 refs =create_ref_cache(submodule);1146 refs->next = submodule_ref_caches;1147 submodule_ref_caches = refs;1148return refs;1149}11501151/* The length of a peeled reference line in packed-refs, including EOL: */1152#define PEELED_LINE_LENGTH 4211531154/*1155 * The packed-refs header line that we write out. Perhaps other1156 * traits will be added later. The trailing space is required.1157 */1158static const char PACKED_REFS_HEADER[] =1159"# pack-refs with: peeled fully-peeled\n";11601161/*1162 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1163 * Return a pointer to the refname within the line (null-terminated),1164 * or NULL if there was a problem.1165 */1166static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1167{1168const char*ref;11691170/*1171 * 42: the answer to everything.1172 *1173 * In this case, it happens to be the answer to1174 * 40 (length of sha1 hex representation)1175 * +1 (space in between hex and name)1176 * +1 (newline at the end of the line)1177 */1178if(line->len <=42)1179return NULL;11801181if(get_sha1_hex(line->buf, sha1) <0)1182return NULL;1183if(!isspace(line->buf[40]))1184return NULL;11851186 ref = line->buf +41;1187if(isspace(*ref))1188return NULL;11891190if(line->buf[line->len -1] !='\n')1191return NULL;1192 line->buf[--line->len] =0;11931194return ref;1195}11961197/*1198 * Read f, which is a packed-refs file, into dir.1199 *1200 * A comment line of the form "# pack-refs with: " may contain zero or1201 * more traits. We interpret the traits as follows:1202 *1203 * No traits:1204 *1205 * Probably no references are peeled. But if the file contains a1206 * peeled value for a reference, we will use it.1207 *1208 * peeled:1209 *1210 * References under "refs/tags/", if they *can* be peeled, *are*1211 * peeled in this file. References outside of "refs/tags/" are1212 * probably not peeled even if they could have been, but if we find1213 * a peeled value for such a reference we will use it.1214 *1215 * fully-peeled:1216 *1217 * All references in the file that can be peeled are peeled.1218 * Inversely (and this is more important), any references in the1219 * file for which no peeled value is recorded is not peelable. This1220 * trait should typically be written alongside "peeled" for1221 * compatibility with older clients, but we do not require it1222 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1223 */1224static voidread_packed_refs(FILE*f,struct ref_dir *dir)1225{1226struct ref_entry *last = NULL;1227struct strbuf line = STRBUF_INIT;1228enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12291230while(strbuf_getwholeline(&line, f,'\n') != EOF) {1231unsigned char sha1[20];1232const char*refname;1233const char*traits;12341235if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1236if(strstr(traits," fully-peeled "))1237 peeled = PEELED_FULLY;1238else if(strstr(traits," peeled "))1239 peeled = PEELED_TAGS;1240/* perhaps other traits later as well */1241continue;1242}12431244 refname =parse_ref_line(&line, sha1);1245if(refname) {1246int flag = REF_ISPACKED;12471248if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1249if(!refname_is_safe(refname))1250die("packed refname is dangerous:%s", refname);1251hashclr(sha1);1252 flag |= REF_BAD_NAME | REF_ISBROKEN;1253}1254 last =create_ref_entry(refname, sha1, flag,0);1255if(peeled == PEELED_FULLY ||1256(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1257 last->flag |= REF_KNOWS_PEELED;1258add_ref(dir, last);1259continue;1260}1261if(last &&1262 line.buf[0] =='^'&&1263 line.len == PEELED_LINE_LENGTH &&1264 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1265!get_sha1_hex(line.buf +1, sha1)) {1266hashcpy(last->u.value.peeled.hash, sha1);1267/*1268 * Regardless of what the file header said,1269 * we definitely know the value of *this*1270 * reference:1271 */1272 last->flag |= REF_KNOWS_PEELED;1273}1274}12751276strbuf_release(&line);1277}12781279/*1280 * Get the packed_ref_cache for the specified ref_cache, creating it1281 * if necessary.1282 */1283static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1284{1285const char*packed_refs_file;12861287if(*refs->name)1288 packed_refs_file =git_path_submodule(refs->name,"packed-refs");1289else1290 packed_refs_file =git_path("packed-refs");12911292if(refs->packed &&1293!stat_validity_check(&refs->packed->validity, packed_refs_file))1294clear_packed_ref_cache(refs);12951296if(!refs->packed) {1297FILE*f;12981299 refs->packed =xcalloc(1,sizeof(*refs->packed));1300acquire_packed_ref_cache(refs->packed);1301 refs->packed->root =create_dir_entry(refs,"",0,0);1302 f =fopen(packed_refs_file,"r");1303if(f) {1304stat_validity_update(&refs->packed->validity,fileno(f));1305read_packed_refs(f,get_ref_dir(refs->packed->root));1306fclose(f);1307}1308}1309return refs->packed;1310}13111312static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1313{1314returnget_ref_dir(packed_ref_cache->root);1315}13161317static struct ref_dir *get_packed_refs(struct ref_cache *refs)1318{1319returnget_packed_ref_dir(get_packed_ref_cache(refs));1320}13211322voidadd_packed_ref(const char*refname,const unsigned char*sha1)1323{1324struct packed_ref_cache *packed_ref_cache =1325get_packed_ref_cache(&ref_cache);13261327if(!packed_ref_cache->lock)1328die("internal error: packed refs not locked");1329add_ref(get_packed_ref_dir(packed_ref_cache),1330create_ref_entry(refname, sha1, REF_ISPACKED,1));1331}13321333/*1334 * Read the loose references from the namespace dirname into dir1335 * (without recursing). dirname must end with '/'. dir must be the1336 * directory entry corresponding to dirname.1337 */1338static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1339{1340struct ref_cache *refs = dir->ref_cache;1341DIR*d;1342const char*path;1343struct dirent *de;1344int dirnamelen =strlen(dirname);1345struct strbuf refname;13461347if(*refs->name)1348 path =git_path_submodule(refs->name,"%s", dirname);1349else1350 path =git_path("%s", dirname);13511352 d =opendir(path);1353if(!d)1354return;13551356strbuf_init(&refname, dirnamelen +257);1357strbuf_add(&refname, dirname, dirnamelen);13581359while((de =readdir(d)) != NULL) {1360unsigned char sha1[20];1361struct stat st;1362int flag;1363const char*refdir;13641365if(de->d_name[0] =='.')1366continue;1367if(ends_with(de->d_name,".lock"))1368continue;1369strbuf_addstr(&refname, de->d_name);1370 refdir = *refs->name1371?git_path_submodule(refs->name,"%s", refname.buf)1372:git_path("%s", refname.buf);1373if(stat(refdir, &st) <0) {1374;/* silently ignore */1375}else if(S_ISDIR(st.st_mode)) {1376strbuf_addch(&refname,'/');1377add_entry_to_dir(dir,1378create_dir_entry(refs, refname.buf,1379 refname.len,1));1380}else{1381int read_ok;13821383if(*refs->name) {1384hashclr(sha1);1385 flag =0;1386 read_ok = !resolve_gitlink_ref(refs->name,1387 refname.buf, sha1);1388}else{1389 read_ok = !read_ref_full(refname.buf,1390 RESOLVE_REF_READING,1391 sha1, &flag);1392}13931394if(!read_ok) {1395hashclr(sha1);1396 flag |= REF_ISBROKEN;1397}else if(is_null_sha1(sha1)) {1398/*1399 * It is so astronomically unlikely1400 * that NULL_SHA1 is the SHA-1 of an1401 * actual object that we consider its1402 * appearance in a loose reference1403 * file to be repo corruption1404 * (probably due to a software bug).1405 */1406 flag |= REF_ISBROKEN;1407}14081409if(check_refname_format(refname.buf,1410 REFNAME_ALLOW_ONELEVEL)) {1411if(!refname_is_safe(refname.buf))1412die("loose refname is dangerous:%s", refname.buf);1413hashclr(sha1);1414 flag |= REF_BAD_NAME | REF_ISBROKEN;1415}1416add_entry_to_dir(dir,1417create_ref_entry(refname.buf, sha1, flag,0));1418}1419strbuf_setlen(&refname, dirnamelen);1420}1421strbuf_release(&refname);1422closedir(d);1423}14241425static struct ref_dir *get_loose_refs(struct ref_cache *refs)1426{1427if(!refs->loose) {1428/*1429 * Mark the top-level directory complete because we1430 * are about to read the only subdirectory that can1431 * hold references:1432 */1433 refs->loose =create_dir_entry(refs,"",0,0);1434/*1435 * Create an incomplete entry for "refs/":1436 */1437add_entry_to_dir(get_ref_dir(refs->loose),1438create_dir_entry(refs,"refs/",5,1));1439}1440returnget_ref_dir(refs->loose);1441}14421443/* We allow "recursive" symbolic refs. Only within reason, though */1444#define MAXDEPTH 51445#define MAXREFLEN (1024)14461447/*1448 * Called by resolve_gitlink_ref_recursive() after it failed to read1449 * from the loose refs in ref_cache refs. Find <refname> in the1450 * packed-refs file for the submodule.1451 */1452static intresolve_gitlink_packed_ref(struct ref_cache *refs,1453const char*refname,unsigned char*sha1)1454{1455struct ref_entry *ref;1456struct ref_dir *dir =get_packed_refs(refs);14571458 ref =find_ref(dir, refname);1459if(ref == NULL)1460return-1;14611462hashcpy(sha1, ref->u.value.oid.hash);1463return0;1464}14651466static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1467const char*refname,unsigned char*sha1,1468int recursion)1469{1470int fd, len;1471char buffer[128], *p;1472const char*path;14731474if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1475return-1;1476 path = *refs->name1477?git_path_submodule(refs->name,"%s", refname)1478:git_path("%s", refname);1479 fd =open(path, O_RDONLY);1480if(fd <0)1481returnresolve_gitlink_packed_ref(refs, refname, sha1);14821483 len =read(fd, buffer,sizeof(buffer)-1);1484close(fd);1485if(len <0)1486return-1;1487while(len &&isspace(buffer[len-1]))1488 len--;1489 buffer[len] =0;14901491/* Was it a detached head or an old-fashioned symlink? */1492if(!get_sha1_hex(buffer, sha1))1493return0;14941495/* Symref? */1496if(strncmp(buffer,"ref:",4))1497return-1;1498 p = buffer +4;1499while(isspace(*p))1500 p++;15011502returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1503}15041505intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1506{1507int len =strlen(path), retval;1508char*submodule;1509struct ref_cache *refs;15101511while(len && path[len-1] =='/')1512 len--;1513if(!len)1514return-1;1515 submodule =xstrndup(path, len);1516 refs =get_ref_cache(submodule);1517free(submodule);15181519 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1520return retval;1521}15221523/*1524 * Return the ref_entry for the given refname from the packed1525 * references. If it does not exist, return NULL.1526 */1527static struct ref_entry *get_packed_ref(const char*refname)1528{1529returnfind_ref(get_packed_refs(&ref_cache), refname);1530}15311532/*1533 * A loose ref file doesn't exist; check for a packed ref. The1534 * options are forwarded from resolve_safe_unsafe().1535 */1536static intresolve_missing_loose_ref(const char*refname,1537int resolve_flags,1538unsigned char*sha1,1539int*flags)1540{1541struct ref_entry *entry;15421543/*1544 * The loose reference file does not exist; check for a packed1545 * reference.1546 */1547 entry =get_packed_ref(refname);1548if(entry) {1549hashcpy(sha1, entry->u.value.oid.hash);1550if(flags)1551*flags |= REF_ISPACKED;1552return0;1553}1554/* The reference is not a packed reference, either. */1555if(resolve_flags & RESOLVE_REF_READING) {1556 errno = ENOENT;1557return-1;1558}else{1559hashclr(sha1);1560return0;1561}1562}15631564/* This function needs to return a meaningful errno on failure */1565static const char*resolve_ref_unsafe_1(const char*refname,1566int resolve_flags,1567unsigned char*sha1,1568int*flags,1569struct strbuf *sb_path)1570{1571int depth = MAXDEPTH;1572 ssize_t len;1573char buffer[256];1574static char refname_buffer[256];1575int bad_name =0;15761577if(flags)1578*flags =0;15791580if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1581if(flags)1582*flags |= REF_BAD_NAME;15831584if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1585!refname_is_safe(refname)) {1586 errno = EINVAL;1587return NULL;1588}1589/*1590 * dwim_ref() uses REF_ISBROKEN to distinguish between1591 * missing refs and refs that were present but invalid,1592 * to complain about the latter to stderr.1593 *1594 * We don't know whether the ref exists, so don't set1595 * REF_ISBROKEN yet.1596 */1597 bad_name =1;1598}1599for(;;) {1600const char*path;1601struct stat st;1602char*buf;1603int fd;16041605if(--depth <0) {1606 errno = ELOOP;1607return NULL;1608}16091610strbuf_reset(sb_path);1611strbuf_git_path(sb_path,"%s", refname);1612 path = sb_path->buf;16131614/*1615 * We might have to loop back here to avoid a race1616 * condition: first we lstat() the file, then we try1617 * to read it as a link or as a file. But if somebody1618 * changes the type of the file (file <-> directory1619 * <-> symlink) between the lstat() and reading, then1620 * we don't want to report that as an error but rather1621 * try again starting with the lstat().1622 */1623 stat_ref:1624if(lstat(path, &st) <0) {1625if(errno != ENOENT)1626return NULL;1627if(resolve_missing_loose_ref(refname, resolve_flags,1628 sha1, flags))1629return NULL;1630if(bad_name) {1631hashclr(sha1);1632if(flags)1633*flags |= REF_ISBROKEN;1634}1635return refname;1636}16371638/* Follow "normalized" - ie "refs/.." symlinks by hand */1639if(S_ISLNK(st.st_mode)) {1640 len =readlink(path, buffer,sizeof(buffer)-1);1641if(len <0) {1642if(errno == ENOENT || errno == EINVAL)1643/* inconsistent with lstat; retry */1644goto stat_ref;1645else1646return NULL;1647}1648 buffer[len] =0;1649if(starts_with(buffer,"refs/") &&1650!check_refname_format(buffer,0)) {1651strcpy(refname_buffer, buffer);1652 refname = refname_buffer;1653if(flags)1654*flags |= REF_ISSYMREF;1655if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1656hashclr(sha1);1657return refname;1658}1659continue;1660}1661}16621663/* Is it a directory? */1664if(S_ISDIR(st.st_mode)) {1665 errno = EISDIR;1666return NULL;1667}16681669/*1670 * Anything else, just open it and try to use it as1671 * a ref1672 */1673 fd =open(path, O_RDONLY);1674if(fd <0) {1675if(errno == ENOENT)1676/* inconsistent with lstat; retry */1677goto stat_ref;1678else1679return NULL;1680}1681 len =read_in_full(fd, buffer,sizeof(buffer)-1);1682if(len <0) {1683int save_errno = errno;1684close(fd);1685 errno = save_errno;1686return NULL;1687}1688close(fd);1689while(len &&isspace(buffer[len-1]))1690 len--;1691 buffer[len] ='\0';16921693/*1694 * Is it a symbolic ref?1695 */1696if(!starts_with(buffer,"ref:")) {1697/*1698 * Please note that FETCH_HEAD has a second1699 * line containing other data.1700 */1701if(get_sha1_hex(buffer, sha1) ||1702(buffer[40] !='\0'&& !isspace(buffer[40]))) {1703if(flags)1704*flags |= REF_ISBROKEN;1705 errno = EINVAL;1706return NULL;1707}1708if(bad_name) {1709hashclr(sha1);1710if(flags)1711*flags |= REF_ISBROKEN;1712}1713return refname;1714}1715if(flags)1716*flags |= REF_ISSYMREF;1717 buf = buffer +4;1718while(isspace(*buf))1719 buf++;1720 refname =strcpy(refname_buffer, buf);1721if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1722hashclr(sha1);1723return refname;1724}1725if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1726if(flags)1727*flags |= REF_ISBROKEN;17281729if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1730!refname_is_safe(buf)) {1731 errno = EINVAL;1732return NULL;1733}1734 bad_name =1;1735}1736}1737}17381739const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1740unsigned char*sha1,int*flags)1741{1742struct strbuf sb_path = STRBUF_INIT;1743const char*ret =resolve_ref_unsafe_1(refname, resolve_flags,1744 sha1, flags, &sb_path);1745strbuf_release(&sb_path);1746return ret;1747}17481749char*resolve_refdup(const char*ref,int resolve_flags,unsigned char*sha1,int*flags)1750{1751returnxstrdup_or_null(resolve_ref_unsafe(ref, resolve_flags, sha1, flags));1752}17531754/* The argument to filter_refs */1755struct ref_filter {1756const char*pattern;1757 each_ref_fn *fn;1758void*cb_data;1759};17601761intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1762{1763if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1764return0;1765return-1;1766}17671768intread_ref(const char*refname,unsigned char*sha1)1769{1770returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1771}17721773intref_exists(const char*refname)1774{1775unsigned char sha1[20];1776return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1777}17781779static intfilter_refs(const char*refname,const struct object_id *oid,1780int flags,void*data)1781{1782struct ref_filter *filter = (struct ref_filter *)data;17831784if(wildmatch(filter->pattern, refname,0, NULL))1785return0;1786return filter->fn(refname, oid, flags, filter->cb_data);1787}17881789enum peel_status {1790/* object was peeled successfully: */1791 PEEL_PEELED =0,17921793/*1794 * object cannot be peeled because the named object (or an1795 * object referred to by a tag in the peel chain), does not1796 * exist.1797 */1798 PEEL_INVALID = -1,17991800/* object cannot be peeled because it is not a tag: */1801 PEEL_NON_TAG = -2,18021803/* ref_entry contains no peeled value because it is a symref: */1804 PEEL_IS_SYMREF = -3,18051806/*1807 * ref_entry cannot be peeled because it is broken (i.e., the1808 * symbolic reference cannot even be resolved to an object1809 * name):1810 */1811 PEEL_BROKEN = -41812};18131814/*1815 * Peel the named object; i.e., if the object is a tag, resolve the1816 * tag recursively until a non-tag is found. If successful, store the1817 * result to sha1 and return PEEL_PEELED. If the object is not a tag1818 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1819 * and leave sha1 unchanged.1820 */1821static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1822{1823struct object *o =lookup_unknown_object(name);18241825if(o->type == OBJ_NONE) {1826int type =sha1_object_info(name, NULL);1827if(type <0|| !object_as_type(o, type,0))1828return PEEL_INVALID;1829}18301831if(o->type != OBJ_TAG)1832return PEEL_NON_TAG;18331834 o =deref_tag_noverify(o);1835if(!o)1836return PEEL_INVALID;18371838hashcpy(sha1, o->sha1);1839return PEEL_PEELED;1840}18411842/*1843 * Peel the entry (if possible) and return its new peel_status. If1844 * repeel is true, re-peel the entry even if there is an old peeled1845 * value that is already stored in it.1846 *1847 * It is OK to call this function with a packed reference entry that1848 * might be stale and might even refer to an object that has since1849 * been garbage-collected. In such a case, if the entry has1850 * REF_KNOWS_PEELED then leave the status unchanged and return1851 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1852 */1853static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1854{1855enum peel_status status;18561857if(entry->flag & REF_KNOWS_PEELED) {1858if(repeel) {1859 entry->flag &= ~REF_KNOWS_PEELED;1860oidclr(&entry->u.value.peeled);1861}else{1862returnis_null_oid(&entry->u.value.peeled) ?1863 PEEL_NON_TAG : PEEL_PEELED;1864}1865}1866if(entry->flag & REF_ISBROKEN)1867return PEEL_BROKEN;1868if(entry->flag & REF_ISSYMREF)1869return PEEL_IS_SYMREF;18701871 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1872if(status == PEEL_PEELED || status == PEEL_NON_TAG)1873 entry->flag |= REF_KNOWS_PEELED;1874return status;1875}18761877intpeel_ref(const char*refname,unsigned char*sha1)1878{1879int flag;1880unsigned char base[20];18811882if(current_ref && (current_ref->name == refname1883|| !strcmp(current_ref->name, refname))) {1884if(peel_entry(current_ref,0))1885return-1;1886hashcpy(sha1, current_ref->u.value.peeled.hash);1887return0;1888}18891890if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1891return-1;18921893/*1894 * If the reference is packed, read its ref_entry from the1895 * cache in the hope that we already know its peeled value.1896 * We only try this optimization on packed references because1897 * (a) forcing the filling of the loose reference cache could1898 * be expensive and (b) loose references anyway usually do not1899 * have REF_KNOWS_PEELED.1900 */1901if(flag & REF_ISPACKED) {1902struct ref_entry *r =get_packed_ref(refname);1903if(r) {1904if(peel_entry(r,0))1905return-1;1906hashcpy(sha1, r->u.value.peeled.hash);1907return0;1908}1909}19101911returnpeel_object(base, sha1);1912}19131914struct warn_if_dangling_data {1915FILE*fp;1916const char*refname;1917const struct string_list *refnames;1918const char*msg_fmt;1919};19201921static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1922int flags,void*cb_data)1923{1924struct warn_if_dangling_data *d = cb_data;1925const char*resolves_to;1926struct object_id junk;19271928if(!(flags & REF_ISSYMREF))1929return0;19301931 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1932if(!resolves_to1933|| (d->refname1934?strcmp(resolves_to, d->refname)1935: !string_list_has_string(d->refnames, resolves_to))) {1936return0;1937}19381939fprintf(d->fp, d->msg_fmt, refname);1940fputc('\n', d->fp);1941return0;1942}19431944voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1945{1946struct warn_if_dangling_data data;19471948 data.fp = fp;1949 data.refname = refname;1950 data.refnames = NULL;1951 data.msg_fmt = msg_fmt;1952for_each_rawref(warn_if_dangling_symref, &data);1953}19541955voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1956{1957struct warn_if_dangling_data data;19581959 data.fp = fp;1960 data.refname = NULL;1961 data.refnames = refnames;1962 data.msg_fmt = msg_fmt;1963for_each_rawref(warn_if_dangling_symref, &data);1964}19651966/*1967 * Call fn for each reference in the specified ref_cache, omitting1968 * references not in the containing_dir of base. fn is called for all1969 * references, including broken ones. If fn ever returns a non-zero1970 * value, stop the iteration and return that value; otherwise, return1971 * 0.1972 */1973static intdo_for_each_entry(struct ref_cache *refs,const char*base,1974 each_ref_entry_fn fn,void*cb_data)1975{1976struct packed_ref_cache *packed_ref_cache;1977struct ref_dir *loose_dir;1978struct ref_dir *packed_dir;1979int retval =0;19801981/*1982 * We must make sure that all loose refs are read before accessing the1983 * packed-refs file; this avoids a race condition in which loose refs1984 * are migrated to the packed-refs file by a simultaneous process, but1985 * our in-memory view is from before the migration. get_packed_ref_cache()1986 * takes care of making sure our view is up to date with what is on1987 * disk.1988 */1989 loose_dir =get_loose_refs(refs);1990if(base && *base) {1991 loose_dir =find_containing_dir(loose_dir, base,0);1992}1993if(loose_dir)1994prime_ref_dir(loose_dir);19951996 packed_ref_cache =get_packed_ref_cache(refs);1997acquire_packed_ref_cache(packed_ref_cache);1998 packed_dir =get_packed_ref_dir(packed_ref_cache);1999if(base && *base) {2000 packed_dir =find_containing_dir(packed_dir, base,0);2001}20022003if(packed_dir && loose_dir) {2004sort_ref_dir(packed_dir);2005sort_ref_dir(loose_dir);2006 retval =do_for_each_entry_in_dirs(2007 packed_dir, loose_dir, fn, cb_data);2008}else if(packed_dir) {2009sort_ref_dir(packed_dir);2010 retval =do_for_each_entry_in_dir(2011 packed_dir,0, fn, cb_data);2012}else if(loose_dir) {2013sort_ref_dir(loose_dir);2014 retval =do_for_each_entry_in_dir(2015 loose_dir,0, fn, cb_data);2016}20172018release_packed_ref_cache(packed_ref_cache);2019return retval;2020}20212022/*2023 * Call fn for each reference in the specified ref_cache for which the2024 * refname begins with base. If trim is non-zero, then trim that many2025 * characters off the beginning of each refname before passing the2026 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2027 * broken references in the iteration. If fn ever returns a non-zero2028 * value, stop the iteration and return that value; otherwise, return2029 * 0.2030 */2031static intdo_for_each_ref(struct ref_cache *refs,const char*base,2032 each_ref_fn fn,int trim,int flags,void*cb_data)2033{2034struct ref_entry_cb data;2035 data.base = base;2036 data.trim = trim;2037 data.flags = flags;2038 data.fn = fn;2039 data.cb_data = cb_data;20402041if(ref_paranoia <0)2042 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2043if(ref_paranoia)2044 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20452046returndo_for_each_entry(refs, base, do_one_ref, &data);2047}20482049static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2050{2051struct object_id oid;2052int flag;20532054if(submodule) {2055if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2056returnfn("HEAD", &oid,0, cb_data);20572058return0;2059}20602061if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2062returnfn("HEAD", &oid, flag, cb_data);20632064return0;2065}20662067inthead_ref(each_ref_fn fn,void*cb_data)2068{2069returndo_head_ref(NULL, fn, cb_data);2070}20712072inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2073{2074returndo_head_ref(submodule, fn, cb_data);2075}20762077intfor_each_ref(each_ref_fn fn,void*cb_data)2078{2079returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2080}20812082intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2083{2084returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2085}20862087intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2088{2089returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2090}20912092intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2093 each_ref_fn fn,void*cb_data)2094{2095returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2096}20972098intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2099{2100returnfor_each_ref_in("refs/tags/", fn, cb_data);2101}21022103intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2104{2105returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2106}21072108intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2109{2110returnfor_each_ref_in("refs/heads/", fn, cb_data);2111}21122113intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2114{2115returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2116}21172118intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2119{2120returnfor_each_ref_in("refs/remotes/", fn, cb_data);2121}21222123intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2124{2125returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2126}21272128intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2129{2130returndo_for_each_ref(&ref_cache,"refs/replace/", fn,13,0, cb_data);2131}21322133inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2134{2135struct strbuf buf = STRBUF_INIT;2136int ret =0;2137struct object_id oid;2138int flag;21392140strbuf_addf(&buf,"%sHEAD",get_git_namespace());2141if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2142 ret =fn(buf.buf, &oid, flag, cb_data);2143strbuf_release(&buf);21442145return ret;2146}21472148intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2149{2150struct strbuf buf = STRBUF_INIT;2151int ret;2152strbuf_addf(&buf,"%srefs/",get_git_namespace());2153 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2154strbuf_release(&buf);2155return ret;2156}21572158intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2159const char*prefix,void*cb_data)2160{2161struct strbuf real_pattern = STRBUF_INIT;2162struct ref_filter filter;2163int ret;21642165if(!prefix && !starts_with(pattern,"refs/"))2166strbuf_addstr(&real_pattern,"refs/");2167else if(prefix)2168strbuf_addstr(&real_pattern, prefix);2169strbuf_addstr(&real_pattern, pattern);21702171if(!has_glob_specials(pattern)) {2172/* Append implied '/' '*' if not present. */2173if(real_pattern.buf[real_pattern.len -1] !='/')2174strbuf_addch(&real_pattern,'/');2175/* No need to check for '*', there is none. */2176strbuf_addch(&real_pattern,'*');2177}21782179 filter.pattern = real_pattern.buf;2180 filter.fn = fn;2181 filter.cb_data = cb_data;2182 ret =for_each_ref(filter_refs, &filter);21832184strbuf_release(&real_pattern);2185return ret;2186}21872188intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2189{2190returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2191}21922193intfor_each_rawref(each_ref_fn fn,void*cb_data)2194{2195returndo_for_each_ref(&ref_cache,"", fn,0,2196 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2197}21982199const char*prettify_refname(const char*name)2200{2201return name + (2202starts_with(name,"refs/heads/") ?11:2203starts_with(name,"refs/tags/") ?10:2204starts_with(name,"refs/remotes/") ?13:22050);2206}22072208static const char*ref_rev_parse_rules[] = {2209"%.*s",2210"refs/%.*s",2211"refs/tags/%.*s",2212"refs/heads/%.*s",2213"refs/remotes/%.*s",2214"refs/remotes/%.*s/HEAD",2215 NULL2216};22172218intrefname_match(const char*abbrev_name,const char*full_name)2219{2220const char**p;2221const int abbrev_name_len =strlen(abbrev_name);22222223for(p = ref_rev_parse_rules; *p; p++) {2224if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2225return1;2226}2227}22282229return0;2230}22312232static voidunlock_ref(struct ref_lock *lock)2233{2234/* Do not free lock->lk -- atexit() still looks at them */2235if(lock->lk)2236rollback_lock_file(lock->lk);2237free(lock->ref_name);2238free(lock->orig_ref_name);2239free(lock);2240}22412242/*2243 * Verify that the reference locked by lock has the value old_sha1.2244 * Fail if the reference doesn't exist and mustexist is set. Return 02245 * on success. On error, write an error message to err, set errno, and2246 * return a negative value.2247 */2248static intverify_lock(struct ref_lock *lock,2249const unsigned char*old_sha1,int mustexist,2250struct strbuf *err)2251{2252assert(err);22532254if(read_ref_full(lock->ref_name,2255 mustexist ? RESOLVE_REF_READING :0,2256 lock->old_oid.hash, NULL)) {2257int save_errno = errno;2258strbuf_addf(err,"can't verify ref%s", lock->ref_name);2259 errno = save_errno;2260return-1;2261}2262if(hashcmp(lock->old_oid.hash, old_sha1)) {2263strbuf_addf(err,"ref%sis at%sbut expected%s",2264 lock->ref_name,2265sha1_to_hex(lock->old_oid.hash),2266sha1_to_hex(old_sha1));2267 errno = EBUSY;2268return-1;2269}2270return0;2271}22722273static intremove_empty_directories(const char*file)2274{2275/* we want to create a file but there is a directory there;2276 * if that is an empty directory (or a directory that contains2277 * only empty directories), remove them.2278 */2279struct strbuf path;2280int result, save_errno;22812282strbuf_init(&path,20);2283strbuf_addstr(&path, file);22842285 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2286 save_errno = errno;22872288strbuf_release(&path);2289 errno = save_errno;22902291return result;2292}22932294/*2295 * *string and *len will only be substituted, and *string returned (for2296 * later free()ing) if the string passed in is a magic short-hand form2297 * to name a branch.2298 */2299static char*substitute_branch_name(const char**string,int*len)2300{2301struct strbuf buf = STRBUF_INIT;2302int ret =interpret_branch_name(*string, *len, &buf);23032304if(ret == *len) {2305size_t size;2306*string =strbuf_detach(&buf, &size);2307*len = size;2308return(char*)*string;2309}23102311return NULL;2312}23132314intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2315{2316char*last_branch =substitute_branch_name(&str, &len);2317const char**p, *r;2318int refs_found =0;23192320*ref = NULL;2321for(p = ref_rev_parse_rules; *p; p++) {2322char fullref[PATH_MAX];2323unsigned char sha1_from_ref[20];2324unsigned char*this_result;2325int flag;23262327 this_result = refs_found ? sha1_from_ref : sha1;2328mksnpath(fullref,sizeof(fullref), *p, len, str);2329 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2330 this_result, &flag);2331if(r) {2332if(!refs_found++)2333*ref =xstrdup(r);2334if(!warn_ambiguous_refs)2335break;2336}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2337warning("ignoring dangling symref%s.", fullref);2338}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2339warning("ignoring broken ref%s.", fullref);2340}2341}2342free(last_branch);2343return refs_found;2344}23452346intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2347{2348char*last_branch =substitute_branch_name(&str, &len);2349const char**p;2350int logs_found =0;23512352*log = NULL;2353for(p = ref_rev_parse_rules; *p; p++) {2354unsigned char hash[20];2355char path[PATH_MAX];2356const char*ref, *it;23572358mksnpath(path,sizeof(path), *p, len, str);2359 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2360 hash, NULL);2361if(!ref)2362continue;2363if(reflog_exists(path))2364 it = path;2365else if(strcmp(ref, path) &&reflog_exists(ref))2366 it = ref;2367else2368continue;2369if(!logs_found++) {2370*log =xstrdup(it);2371hashcpy(sha1, hash);2372}2373if(!warn_ambiguous_refs)2374break;2375}2376free(last_branch);2377return logs_found;2378}23792380/*2381 * Locks a ref returning the lock on success and NULL on failure.2382 * On failure errno is set to something meaningful.2383 */2384static struct ref_lock *lock_ref_sha1_basic(const char*refname,2385const unsigned char*old_sha1,2386const struct string_list *extras,2387const struct string_list *skip,2388unsigned int flags,int*type_p,2389struct strbuf *err)2390{2391const char*ref_file;2392const char*orig_refname = refname;2393struct ref_lock *lock;2394int last_errno =0;2395int type, lflags;2396int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2397int resolve_flags =0;2398int attempts_remaining =3;23992400assert(err);24012402 lock =xcalloc(1,sizeof(struct ref_lock));24032404if(mustexist)2405 resolve_flags |= RESOLVE_REF_READING;2406if(flags & REF_DELETING) {2407 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2408if(flags & REF_NODEREF)2409 resolve_flags |= RESOLVE_REF_NO_RECURSE;2410}24112412 refname =resolve_ref_unsafe(refname, resolve_flags,2413 lock->old_oid.hash, &type);2414if(!refname && errno == EISDIR) {2415/* we are trying to lock foo but we used to2416 * have foo/bar which now does not exist;2417 * it is normal for the empty directory 'foo'2418 * to remain.2419 */2420 ref_file =git_path("%s", orig_refname);2421if(remove_empty_directories(ref_file)) {2422 last_errno = errno;24232424if(!verify_refname_available(orig_refname, extras, skip,2425get_loose_refs(&ref_cache), err))2426strbuf_addf(err,"there are still refs under '%s'",2427 orig_refname);24282429goto error_return;2430}2431 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2432 lock->old_oid.hash, &type);2433}2434if(type_p)2435*type_p = type;2436if(!refname) {2437 last_errno = errno;2438if(last_errno != ENOTDIR ||2439!verify_refname_available(orig_refname, extras, skip,2440get_loose_refs(&ref_cache), err))2441strbuf_addf(err,"unable to resolve reference%s:%s",2442 orig_refname,strerror(last_errno));24432444goto error_return;2445}2446/*2447 * If the ref did not exist and we are creating it, make sure2448 * there is no existing packed ref whose name begins with our2449 * refname, nor a packed ref whose name is a proper prefix of2450 * our refname.2451 */2452if(is_null_oid(&lock->old_oid) &&2453verify_refname_available(refname, extras, skip,2454get_packed_refs(&ref_cache), err)) {2455 last_errno = ENOTDIR;2456goto error_return;2457}24582459 lock->lk =xcalloc(1,sizeof(struct lock_file));24602461 lflags =0;2462if(flags & REF_NODEREF) {2463 refname = orig_refname;2464 lflags |= LOCK_NO_DEREF;2465}2466 lock->ref_name =xstrdup(refname);2467 lock->orig_ref_name =xstrdup(orig_refname);2468 ref_file =git_path("%s", refname);24692470 retry:2471switch(safe_create_leading_directories_const(ref_file)) {2472case SCLD_OK:2473break;/* success */2474case SCLD_VANISHED:2475if(--attempts_remaining >0)2476goto retry;2477/* fall through */2478default:2479 last_errno = errno;2480strbuf_addf(err,"unable to create directory for%s", ref_file);2481goto error_return;2482}24832484if(hold_lock_file_for_update(lock->lk, ref_file, lflags) <0) {2485 last_errno = errno;2486if(errno == ENOENT && --attempts_remaining >0)2487/*2488 * Maybe somebody just deleted one of the2489 * directories leading to ref_file. Try2490 * again:2491 */2492goto retry;2493else{2494unable_to_lock_message(ref_file, errno, err);2495goto error_return;2496}2497}2498if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2499 last_errno = errno;2500goto error_return;2501}2502return lock;25032504 error_return:2505unlock_ref(lock);2506 errno = last_errno;2507return NULL;2508}25092510/*2511 * Write an entry to the packed-refs file for the specified refname.2512 * If peeled is non-NULL, write it as the entry's peeled value.2513 */2514static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2515unsigned char*peeled)2516{2517fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2518if(peeled)2519fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2520}25212522/*2523 * An each_ref_entry_fn that writes the entry to a packed-refs file.2524 */2525static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2526{2527enum peel_status peel_status =peel_entry(entry,0);25282529if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2530error("internal error:%sis not a valid packed reference!",2531 entry->name);2532write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2533 peel_status == PEEL_PEELED ?2534 entry->u.value.peeled.hash : NULL);2535return0;2536}25372538/* This should return a meaningful errno on failure */2539intlock_packed_refs(int flags)2540{2541static int timeout_configured =0;2542static int timeout_value =1000;25432544struct packed_ref_cache *packed_ref_cache;25452546if(!timeout_configured) {2547git_config_get_int("core.packedrefstimeout", &timeout_value);2548 timeout_configured =1;2549}25502551if(hold_lock_file_for_update_timeout(2552&packlock,git_path("packed-refs"),2553 flags, timeout_value) <0)2554return-1;2555/*2556 * Get the current packed-refs while holding the lock. If the2557 * packed-refs file has been modified since we last read it,2558 * this will automatically invalidate the cache and re-read2559 * the packed-refs file.2560 */2561 packed_ref_cache =get_packed_ref_cache(&ref_cache);2562 packed_ref_cache->lock = &packlock;2563/* Increment the reference count to prevent it from being freed: */2564acquire_packed_ref_cache(packed_ref_cache);2565return0;2566}25672568/*2569 * Commit the packed refs changes.2570 * On error we must make sure that errno contains a meaningful value.2571 */2572intcommit_packed_refs(void)2573{2574struct packed_ref_cache *packed_ref_cache =2575get_packed_ref_cache(&ref_cache);2576int error =0;2577int save_errno =0;2578FILE*out;25792580if(!packed_ref_cache->lock)2581die("internal error: packed-refs not locked");25822583 out =fdopen_lock_file(packed_ref_cache->lock,"w");2584if(!out)2585die_errno("unable to fdopen packed-refs descriptor");25862587fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2588do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),25890, write_packed_entry_fn, out);25902591if(commit_lock_file(packed_ref_cache->lock)) {2592 save_errno = errno;2593 error = -1;2594}2595 packed_ref_cache->lock = NULL;2596release_packed_ref_cache(packed_ref_cache);2597 errno = save_errno;2598return error;2599}26002601voidrollback_packed_refs(void)2602{2603struct packed_ref_cache *packed_ref_cache =2604get_packed_ref_cache(&ref_cache);26052606if(!packed_ref_cache->lock)2607die("internal error: packed-refs not locked");2608rollback_lock_file(packed_ref_cache->lock);2609 packed_ref_cache->lock = NULL;2610release_packed_ref_cache(packed_ref_cache);2611clear_packed_ref_cache(&ref_cache);2612}26132614struct ref_to_prune {2615struct ref_to_prune *next;2616unsigned char sha1[20];2617char name[FLEX_ARRAY];2618};26192620struct pack_refs_cb_data {2621unsigned int flags;2622struct ref_dir *packed_refs;2623struct ref_to_prune *ref_to_prune;2624};26252626/*2627 * An each_ref_entry_fn that is run over loose references only. If2628 * the loose reference can be packed, add an entry in the packed ref2629 * cache. If the reference should be pruned, also add it to2630 * ref_to_prune in the pack_refs_cb_data.2631 */2632static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2633{2634struct pack_refs_cb_data *cb = cb_data;2635enum peel_status peel_status;2636struct ref_entry *packed_entry;2637int is_tag_ref =starts_with(entry->name,"refs/tags/");26382639/* ALWAYS pack tags */2640if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2641return0;26422643/* Do not pack symbolic or broken refs: */2644if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2645return0;26462647/* Add a packed ref cache entry equivalent to the loose entry. */2648 peel_status =peel_entry(entry,1);2649if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2650die("internal error peeling reference%s(%s)",2651 entry->name,oid_to_hex(&entry->u.value.oid));2652 packed_entry =find_ref(cb->packed_refs, entry->name);2653if(packed_entry) {2654/* Overwrite existing packed entry with info from loose entry */2655 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2656oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2657}else{2658 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2659 REF_ISPACKED | REF_KNOWS_PEELED,0);2660add_ref(cb->packed_refs, packed_entry);2661}2662oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);26632664/* Schedule the loose reference for pruning if requested. */2665if((cb->flags & PACK_REFS_PRUNE)) {2666int namelen =strlen(entry->name) +1;2667struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2668hashcpy(n->sha1, entry->u.value.oid.hash);2669strcpy(n->name, entry->name);2670 n->next = cb->ref_to_prune;2671 cb->ref_to_prune = n;2672}2673return0;2674}26752676/*2677 * Remove empty parents, but spare refs/ and immediate subdirs.2678 * Note: munges *name.2679 */2680static voidtry_remove_empty_parents(char*name)2681{2682char*p, *q;2683int i;2684 p = name;2685for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2686while(*p && *p !='/')2687 p++;2688/* tolerate duplicate slashes; see check_refname_format() */2689while(*p =='/')2690 p++;2691}2692for(q = p; *q; q++)2693;2694while(1) {2695while(q > p && *q !='/')2696 q--;2697while(q > p && *(q-1) =='/')2698 q--;2699if(q == p)2700break;2701*q ='\0';2702if(rmdir(git_path("%s", name)))2703break;2704}2705}27062707/* make sure nobody touched the ref, and unlink */2708static voidprune_ref(struct ref_to_prune *r)2709{2710struct ref_transaction *transaction;2711struct strbuf err = STRBUF_INIT;27122713if(check_refname_format(r->name,0))2714return;27152716 transaction =ref_transaction_begin(&err);2717if(!transaction ||2718ref_transaction_delete(transaction, r->name, r->sha1,2719 REF_ISPRUNING, NULL, &err) ||2720ref_transaction_commit(transaction, &err)) {2721ref_transaction_free(transaction);2722error("%s", err.buf);2723strbuf_release(&err);2724return;2725}2726ref_transaction_free(transaction);2727strbuf_release(&err);2728try_remove_empty_parents(r->name);2729}27302731static voidprune_refs(struct ref_to_prune *r)2732{2733while(r) {2734prune_ref(r);2735 r = r->next;2736}2737}27382739intpack_refs(unsigned int flags)2740{2741struct pack_refs_cb_data cbdata;27422743memset(&cbdata,0,sizeof(cbdata));2744 cbdata.flags = flags;27452746lock_packed_refs(LOCK_DIE_ON_ERROR);2747 cbdata.packed_refs =get_packed_refs(&ref_cache);27482749do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2750 pack_if_possible_fn, &cbdata);27512752if(commit_packed_refs())2753die_errno("unable to overwrite old ref-pack file");27542755prune_refs(cbdata.ref_to_prune);2756return0;2757}27582759intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2760{2761struct ref_dir *packed;2762struct string_list_item *refname;2763int ret, needs_repacking =0, removed =0;27642765assert(err);27662767/* Look for a packed ref */2768for_each_string_list_item(refname, refnames) {2769if(get_packed_ref(refname->string)) {2770 needs_repacking =1;2771break;2772}2773}27742775/* Avoid locking if we have nothing to do */2776if(!needs_repacking)2777return0;/* no refname exists in packed refs */27782779if(lock_packed_refs(0)) {2780unable_to_lock_message(git_path("packed-refs"), errno, err);2781return-1;2782}2783 packed =get_packed_refs(&ref_cache);27842785/* Remove refnames from the cache */2786for_each_string_list_item(refname, refnames)2787if(remove_entry(packed, refname->string) != -1)2788 removed =1;2789if(!removed) {2790/*2791 * All packed entries disappeared while we were2792 * acquiring the lock.2793 */2794rollback_packed_refs();2795return0;2796}27972798/* Write what remains */2799 ret =commit_packed_refs();2800if(ret)2801strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2802strerror(errno));2803return ret;2804}28052806static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2807{2808assert(err);28092810if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2811/*2812 * loose. The loose file name is the same as the2813 * lockfile name, minus ".lock":2814 */2815char*loose_filename =get_locked_file_path(lock->lk);2816int res =unlink_or_msg(loose_filename, err);2817free(loose_filename);2818if(res)2819return1;2820}2821return0;2822}28232824static intis_per_worktree_ref(const char*refname)2825{2826return!strcmp(refname,"HEAD");2827}28282829static intis_pseudoref_syntax(const char*refname)2830{2831const char*c;28322833for(c = refname; *c; c++) {2834if(!isupper(*c) && *c !='-'&& *c !='_')2835return0;2836}28372838return1;2839}28402841enum ref_type ref_type(const char*refname)2842{2843if(is_per_worktree_ref(refname))2844return REF_TYPE_PER_WORKTREE;2845if(is_pseudoref_syntax(refname))2846return REF_TYPE_PSEUDOREF;2847return REF_TYPE_NORMAL;2848}28492850static intwrite_pseudoref(const char*pseudoref,const unsigned char*sha1,2851const unsigned char*old_sha1,struct strbuf *err)2852{2853const char*filename;2854int fd;2855static struct lock_file lock;2856struct strbuf buf = STRBUF_INIT;2857int ret = -1;28582859strbuf_addf(&buf,"%s\n",sha1_to_hex(sha1));28602861 filename =git_path("%s", pseudoref);2862 fd =hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);2863if(fd <0) {2864strbuf_addf(err,"Could not open '%s' for writing:%s",2865 filename,strerror(errno));2866return-1;2867}28682869if(old_sha1) {2870unsigned char actual_old_sha1[20];28712872if(read_ref(pseudoref, actual_old_sha1))2873die("could not read ref '%s'", pseudoref);2874if(hashcmp(actual_old_sha1, old_sha1)) {2875strbuf_addf(err,"Unexpected sha1 when writing%s", pseudoref);2876rollback_lock_file(&lock);2877goto done;2878}2879}28802881if(write_in_full(fd, buf.buf, buf.len) != buf.len) {2882strbuf_addf(err,"Could not write to '%s'", filename);2883rollback_lock_file(&lock);2884goto done;2885}28862887commit_lock_file(&lock);2888 ret =0;2889done:2890strbuf_release(&buf);2891return ret;2892}28932894static intdelete_pseudoref(const char*pseudoref,const unsigned char*old_sha1)2895{2896static struct lock_file lock;2897const char*filename;28982899 filename =git_path("%s", pseudoref);29002901if(old_sha1 && !is_null_sha1(old_sha1)) {2902int fd;2903unsigned char actual_old_sha1[20];29042905 fd =hold_lock_file_for_update(&lock, filename,2906 LOCK_DIE_ON_ERROR);2907if(fd <0)2908die_errno(_("Could not open '%s' for writing"), filename);2909if(read_ref(pseudoref, actual_old_sha1))2910die("could not read ref '%s'", pseudoref);2911if(hashcmp(actual_old_sha1, old_sha1)) {2912warning("Unexpected sha1 when deleting%s", pseudoref);2913rollback_lock_file(&lock);2914return-1;2915}29162917unlink(filename);2918rollback_lock_file(&lock);2919}else{2920unlink(filename);2921}29222923return0;2924}29252926intdelete_ref(const char*refname,const unsigned char*sha1,unsigned int flags)2927{2928struct ref_transaction *transaction;2929struct strbuf err = STRBUF_INIT;29302931if(ref_type(refname) == REF_TYPE_PSEUDOREF)2932returndelete_pseudoref(refname, sha1);29332934 transaction =ref_transaction_begin(&err);2935if(!transaction ||2936ref_transaction_delete(transaction, refname,2937(sha1 && !is_null_sha1(sha1)) ? sha1 : NULL,2938 flags, NULL, &err) ||2939ref_transaction_commit(transaction, &err)) {2940error("%s", err.buf);2941ref_transaction_free(transaction);2942strbuf_release(&err);2943return1;2944}2945ref_transaction_free(transaction);2946strbuf_release(&err);2947return0;2948}29492950/*2951 * People using contrib's git-new-workdir have .git/logs/refs ->2952 * /some/other/path/.git/logs/refs, and that may live on another device.2953 *2954 * IOW, to avoid cross device rename errors, the temporary renamed log must2955 * live into logs/refs.2956 */2957#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"29582959static intrename_tmp_log(const char*newrefname)2960{2961int attempts_remaining =4;29622963 retry:2964switch(safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {2965case SCLD_OK:2966break;/* success */2967case SCLD_VANISHED:2968if(--attempts_remaining >0)2969goto retry;2970/* fall through */2971default:2972error("unable to create directory for%s", newrefname);2973return-1;2974}29752976if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2977if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2978/*2979 * rename(a, b) when b is an existing2980 * directory ought to result in ISDIR, but2981 * Solaris 5.8 gives ENOTDIR. Sheesh.2982 */2983if(remove_empty_directories(git_path("logs/%s", newrefname))) {2984error("Directory not empty: logs/%s", newrefname);2985return-1;2986}2987goto retry;2988}else if(errno == ENOENT && --attempts_remaining >0) {2989/*2990 * Maybe another process just deleted one of2991 * the directories in the path to newrefname.2992 * Try again from the beginning.2993 */2994goto retry;2995}else{2996error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2997 newrefname,strerror(errno));2998return-1;2999}3000}3001return0;3002}30033004static intrename_ref_available(const char*oldname,const char*newname)3005{3006struct string_list skip = STRING_LIST_INIT_NODUP;3007struct strbuf err = STRBUF_INIT;3008int ret;30093010string_list_insert(&skip, oldname);3011 ret = !verify_refname_available(newname, NULL, &skip,3012get_packed_refs(&ref_cache), &err)3013&& !verify_refname_available(newname, NULL, &skip,3014get_loose_refs(&ref_cache), &err);3015if(!ret)3016error("%s", err.buf);30173018string_list_clear(&skip,0);3019strbuf_release(&err);3020return ret;3021}30223023static intwrite_ref_to_lockfile(struct ref_lock *lock,3024const unsigned char*sha1,struct strbuf *err);3025static intcommit_ref_update(struct ref_lock *lock,3026const unsigned char*sha1,const char*logmsg,3027int flags,struct strbuf *err);30283029intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)3030{3031unsigned char sha1[20], orig_sha1[20];3032int flag =0, logmoved =0;3033struct ref_lock *lock;3034struct stat loginfo;3035int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);3036const char*symref = NULL;3037struct strbuf err = STRBUF_INIT;30383039if(log &&S_ISLNK(loginfo.st_mode))3040returnerror("reflog for%sis a symlink", oldrefname);30413042 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3043 orig_sha1, &flag);3044if(flag & REF_ISSYMREF)3045returnerror("refname%sis a symbolic ref, renaming it is not supported",3046 oldrefname);3047if(!symref)3048returnerror("refname%snot found", oldrefname);30493050if(!rename_ref_available(oldrefname, newrefname))3051return1;30523053if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3054returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3055 oldrefname,strerror(errno));30563057if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3058error("unable to delete old%s", oldrefname);3059goto rollback;3060}30613062if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3063delete_ref(newrefname, sha1, REF_NODEREF)) {3064if(errno==EISDIR) {3065if(remove_empty_directories(git_path("%s", newrefname))) {3066error("Directory not empty:%s", newrefname);3067goto rollback;3068}3069}else{3070error("unable to delete existing%s", newrefname);3071goto rollback;3072}3073}30743075if(log &&rename_tmp_log(newrefname))3076goto rollback;30773078 logmoved = log;30793080 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3081if(!lock) {3082error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3083strbuf_release(&err);3084goto rollback;3085}3086hashcpy(lock->old_oid.hash, orig_sha1);30873088if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3089commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {3090error("unable to write current sha1 into%s:%s", newrefname, err.buf);3091strbuf_release(&err);3092goto rollback;3093}30943095return0;30963097 rollback:3098 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3099if(!lock) {3100error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3101strbuf_release(&err);3102goto rollbacklog;3103}31043105 flag = log_all_ref_updates;3106 log_all_ref_updates =0;3107if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3108commit_ref_update(lock, orig_sha1, NULL,0, &err)) {3109error("unable to write current sha1 into%s:%s", oldrefname, err.buf);3110strbuf_release(&err);3111}3112 log_all_ref_updates = flag;31133114 rollbacklog:3115if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3116error("unable to restore logfile%sfrom%s:%s",3117 oldrefname, newrefname,strerror(errno));3118if(!logmoved && log &&3119rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3120error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3121 oldrefname,strerror(errno));31223123return1;3124}31253126static intclose_ref(struct ref_lock *lock)3127{3128if(close_lock_file(lock->lk))3129return-1;3130return0;3131}31323133static intcommit_ref(struct ref_lock *lock)3134{3135if(commit_lock_file(lock->lk))3136return-1;3137return0;3138}31393140/*3141 * copy the reflog message msg to buf, which has been allocated sufficiently3142 * large, while cleaning up the whitespaces. Especially, convert LF to space,3143 * because reflog file is one line per entry.3144 */3145static intcopy_msg(char*buf,const char*msg)3146{3147char*cp = buf;3148char c;3149int wasspace =1;31503151*cp++ ='\t';3152while((c = *msg++)) {3153if(wasspace &&isspace(c))3154continue;3155 wasspace =isspace(c);3156if(wasspace)3157 c =' ';3158*cp++ = c;3159}3160while(buf < cp &&isspace(cp[-1]))3161 cp--;3162*cp++ ='\n';3163return cp - buf;3164}31653166static intshould_autocreate_reflog(const char*refname)3167{3168if(!log_all_ref_updates)3169return0;3170returnstarts_with(refname,"refs/heads/") ||3171starts_with(refname,"refs/remotes/") ||3172starts_with(refname,"refs/notes/") ||3173!strcmp(refname,"HEAD");3174}31753176/*3177 * Create a reflog for a ref. If force_create = 0, the reflog will3178 * only be created for certain refs (those for which3179 * should_autocreate_reflog returns non-zero. Otherwise, create it3180 * regardless of the ref name. Fill in *err and return -1 on failure.3181 */3182static intlog_ref_setup(const char*refname,struct strbuf *sb_logfile,struct strbuf *err,int force_create)3183{3184int logfd, oflags = O_APPEND | O_WRONLY;3185char*logfile;31863187strbuf_git_path(sb_logfile,"logs/%s", refname);3188 logfile = sb_logfile->buf;3189/* make sure the rest of the function can't change "logfile" */3190 sb_logfile = NULL;3191if(force_create ||should_autocreate_reflog(refname)) {3192if(safe_create_leading_directories(logfile) <0) {3193strbuf_addf(err,"unable to create directory for%s: "3194"%s", logfile,strerror(errno));3195return-1;3196}3197 oflags |= O_CREAT;3198}31993200 logfd =open(logfile, oflags,0666);3201if(logfd <0) {3202if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3203return0;32043205if(errno == EISDIR) {3206if(remove_empty_directories(logfile)) {3207strbuf_addf(err,"There are still logs under "3208"'%s'", logfile);3209return-1;3210}3211 logfd =open(logfile, oflags,0666);3212}32133214if(logfd <0) {3215strbuf_addf(err,"unable to append to%s:%s",3216 logfile,strerror(errno));3217return-1;3218}3219}32203221adjust_shared_perm(logfile);3222close(logfd);3223return0;3224}322532263227intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3228{3229int ret;3230struct strbuf sb = STRBUF_INIT;32313232 ret =log_ref_setup(refname, &sb, err, force_create);3233strbuf_release(&sb);3234return ret;3235}32363237static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3238const unsigned char*new_sha1,3239const char*committer,const char*msg)3240{3241int msglen, written;3242unsigned maxlen, len;3243char*logrec;32443245 msglen = msg ?strlen(msg) :0;3246 maxlen =strlen(committer) + msglen +100;3247 logrec =xmalloc(maxlen);3248 len =sprintf(logrec,"%s %s %s\n",3249sha1_to_hex(old_sha1),3250sha1_to_hex(new_sha1),3251 committer);3252if(msglen)3253 len +=copy_msg(logrec + len -1, msg) -1;32543255 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3256free(logrec);3257if(written != len)3258return-1;32593260return0;3261}32623263static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3264const unsigned char*new_sha1,const char*msg,3265struct strbuf *sb_log_file,int flags,3266struct strbuf *err)3267{3268int logfd, result, oflags = O_APPEND | O_WRONLY;3269char*log_file;32703271if(log_all_ref_updates <0)3272 log_all_ref_updates = !is_bare_repository();32733274 result =log_ref_setup(refname, sb_log_file, err, flags & REF_FORCE_CREATE_REFLOG);32753276if(result)3277return result;3278 log_file = sb_log_file->buf;3279/* make sure the rest of the function can't change "log_file" */3280 sb_log_file = NULL;32813282 logfd =open(log_file, oflags);3283if(logfd <0)3284return0;3285 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3286git_committer_info(0), msg);3287if(result) {3288strbuf_addf(err,"unable to append to%s:%s", log_file,3289strerror(errno));3290close(logfd);3291return-1;3292}3293if(close(logfd)) {3294strbuf_addf(err,"unable to append to%s:%s", log_file,3295strerror(errno));3296return-1;3297}3298return0;3299}33003301static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3302const unsigned char*new_sha1,const char*msg,3303int flags,struct strbuf *err)3304{3305struct strbuf sb = STRBUF_INIT;3306int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3307 err);3308strbuf_release(&sb);3309return ret;3310}33113312intis_branch(const char*refname)3313{3314return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3315}33163317/*3318 * Write sha1 into the open lockfile, then close the lockfile. On3319 * errors, rollback the lockfile, fill in *err and3320 * return -1.3321 */3322static intwrite_ref_to_lockfile(struct ref_lock *lock,3323const unsigned char*sha1,struct strbuf *err)3324{3325static char term ='\n';3326struct object *o;33273328 o =parse_object(sha1);3329if(!o) {3330strbuf_addf(err,3331"Trying to write ref%swith nonexistent object%s",3332 lock->ref_name,sha1_to_hex(sha1));3333unlock_ref(lock);3334return-1;3335}3336if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3337strbuf_addf(err,3338"Trying to write non-commit object%sto branch%s",3339sha1_to_hex(sha1), lock->ref_name);3340unlock_ref(lock);3341return-1;3342}3343if(write_in_full(lock->lk->fd,sha1_to_hex(sha1),40) !=40||3344write_in_full(lock->lk->fd, &term,1) !=1||3345close_ref(lock) <0) {3346strbuf_addf(err,3347"Couldn't write%s", lock->lk->filename.buf);3348unlock_ref(lock);3349return-1;3350}3351return0;3352}33533354/*3355 * Commit a change to a loose reference that has already been written3356 * to the loose reference lockfile. Also update the reflogs if3357 * necessary, using the specified lockmsg (which can be NULL).3358 */3359static intcommit_ref_update(struct ref_lock *lock,3360const unsigned char*sha1,const char*logmsg,3361int flags,struct strbuf *err)3362{3363clear_loose_ref_cache(&ref_cache);3364if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||3365(strcmp(lock->ref_name, lock->orig_ref_name) &&3366log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {3367char*old_msg =strbuf_detach(err, NULL);3368strbuf_addf(err,"Cannot update the ref '%s':%s",3369 lock->ref_name, old_msg);3370free(old_msg);3371unlock_ref(lock);3372return-1;3373}3374if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3375/*3376 * Special hack: If a branch is updated directly and HEAD3377 * points to it (may happen on the remote side of a push3378 * for example) then logically the HEAD reflog should be3379 * updated too.3380 * A generic solution implies reverse symref information,3381 * but finding all symrefs pointing to the given branch3382 * would be rather costly for this rare event (the direct3383 * update of a branch) to be worth it. So let's cheat and3384 * check with HEAD only which should cover 99% of all usage3385 * scenarios (even 100% of the default ones).3386 */3387unsigned char head_sha1[20];3388int head_flag;3389const char*head_ref;3390 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3391 head_sha1, &head_flag);3392if(head_ref && (head_flag & REF_ISSYMREF) &&3393!strcmp(head_ref, lock->ref_name)) {3394struct strbuf log_err = STRBUF_INIT;3395if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3396 logmsg,0, &log_err)) {3397error("%s", log_err.buf);3398strbuf_release(&log_err);3399}3400}3401}3402if(commit_ref(lock)) {3403error("Couldn't set%s", lock->ref_name);3404unlock_ref(lock);3405return-1;3406}34073408unlock_ref(lock);3409return0;3410}34113412intcreate_symref(const char*ref_target,const char*refs_heads_master,3413const char*logmsg)3414{3415const char*lockpath;3416char ref[1000];3417int fd, len, written;3418char*git_HEAD =git_pathdup("%s", ref_target);3419unsigned char old_sha1[20], new_sha1[20];3420struct strbuf err = STRBUF_INIT;34213422if(logmsg &&read_ref(ref_target, old_sha1))3423hashclr(old_sha1);34243425if(safe_create_leading_directories(git_HEAD) <0)3426returnerror("unable to create directory for%s", git_HEAD);34273428#ifndef NO_SYMLINK_HEAD3429if(prefer_symlink_refs) {3430unlink(git_HEAD);3431if(!symlink(refs_heads_master, git_HEAD))3432goto done;3433fprintf(stderr,"no symlink - falling back to symbolic ref\n");3434}3435#endif34363437 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3438if(sizeof(ref) <= len) {3439error("refname too long:%s", refs_heads_master);3440goto error_free_return;3441}3442 lockpath =mkpath("%s.lock", git_HEAD);3443 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3444if(fd <0) {3445error("Unable to open%sfor writing", lockpath);3446goto error_free_return;3447}3448 written =write_in_full(fd, ref, len);3449if(close(fd) !=0|| written != len) {3450error("Unable to write to%s", lockpath);3451goto error_unlink_return;3452}3453if(rename(lockpath, git_HEAD) <0) {3454error("Unable to create%s", git_HEAD);3455goto error_unlink_return;3456}3457if(adjust_shared_perm(git_HEAD)) {3458error("Unable to fix permissions on%s", lockpath);3459 error_unlink_return:3460unlink_or_warn(lockpath);3461 error_free_return:3462free(git_HEAD);3463return-1;3464}34653466#ifndef NO_SYMLINK_HEAD3467 done:3468#endif3469if(logmsg && !read_ref(refs_heads_master, new_sha1) &&3470log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {3471error("%s", err.buf);3472strbuf_release(&err);3473}34743475free(git_HEAD);3476return0;3477}34783479struct read_ref_at_cb {3480const char*refname;3481unsigned long at_time;3482int cnt;3483int reccnt;3484unsigned char*sha1;3485int found_it;34863487unsigned char osha1[20];3488unsigned char nsha1[20];3489int tz;3490unsigned long date;3491char**msg;3492unsigned long*cutoff_time;3493int*cutoff_tz;3494int*cutoff_cnt;3495};34963497static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3498const char*email,unsigned long timestamp,int tz,3499const char*message,void*cb_data)3500{3501struct read_ref_at_cb *cb = cb_data;35023503 cb->reccnt++;3504 cb->tz = tz;3505 cb->date = timestamp;35063507if(timestamp <= cb->at_time || cb->cnt ==0) {3508if(cb->msg)3509*cb->msg =xstrdup(message);3510if(cb->cutoff_time)3511*cb->cutoff_time = timestamp;3512if(cb->cutoff_tz)3513*cb->cutoff_tz = tz;3514if(cb->cutoff_cnt)3515*cb->cutoff_cnt = cb->reccnt -1;3516/*3517 * we have not yet updated cb->[n|o]sha1 so they still3518 * hold the values for the previous record.3519 */3520if(!is_null_sha1(cb->osha1)) {3521hashcpy(cb->sha1, nsha1);3522if(hashcmp(cb->osha1, nsha1))3523warning("Log for ref%shas gap after%s.",3524 cb->refname,show_date(cb->date, cb->tz, DATE_RFC2822));3525}3526else if(cb->date == cb->at_time)3527hashcpy(cb->sha1, nsha1);3528else if(hashcmp(nsha1, cb->sha1))3529warning("Log for ref%sunexpectedly ended on%s.",3530 cb->refname,show_date(cb->date, cb->tz,3531 DATE_RFC2822));3532hashcpy(cb->osha1, osha1);3533hashcpy(cb->nsha1, nsha1);3534 cb->found_it =1;3535return1;3536}3537hashcpy(cb->osha1, osha1);3538hashcpy(cb->nsha1, nsha1);3539if(cb->cnt >0)3540 cb->cnt--;3541return0;3542}35433544static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3545const char*email,unsigned long timestamp,3546int tz,const char*message,void*cb_data)3547{3548struct read_ref_at_cb *cb = cb_data;35493550if(cb->msg)3551*cb->msg =xstrdup(message);3552if(cb->cutoff_time)3553*cb->cutoff_time = timestamp;3554if(cb->cutoff_tz)3555*cb->cutoff_tz = tz;3556if(cb->cutoff_cnt)3557*cb->cutoff_cnt = cb->reccnt;3558hashcpy(cb->sha1, osha1);3559if(is_null_sha1(cb->sha1))3560hashcpy(cb->sha1, nsha1);3561/* We just want the first entry */3562return1;3563}35643565intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3566unsigned char*sha1,char**msg,3567unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3568{3569struct read_ref_at_cb cb;35703571memset(&cb,0,sizeof(cb));3572 cb.refname = refname;3573 cb.at_time = at_time;3574 cb.cnt = cnt;3575 cb.msg = msg;3576 cb.cutoff_time = cutoff_time;3577 cb.cutoff_tz = cutoff_tz;3578 cb.cutoff_cnt = cutoff_cnt;3579 cb.sha1 = sha1;35803581for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);35823583if(!cb.reccnt) {3584if(flags & GET_SHA1_QUIETLY)3585exit(128);3586else3587die("Log for%sis empty.", refname);3588}3589if(cb.found_it)3590return0;35913592for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);35933594return1;3595}35963597intreflog_exists(const char*refname)3598{3599struct stat st;36003601return!lstat(git_path("logs/%s", refname), &st) &&3602S_ISREG(st.st_mode);3603}36043605intdelete_reflog(const char*refname)3606{3607returnremove_path(git_path("logs/%s", refname));3608}36093610static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3611{3612unsigned char osha1[20], nsha1[20];3613char*email_end, *message;3614unsigned long timestamp;3615int tz;36163617/* old SP new SP name <email> SP time TAB msg LF */3618if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3619get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3620get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3621!(email_end =strchr(sb->buf +82,'>')) ||3622 email_end[1] !=' '||3623!(timestamp =strtoul(email_end +2, &message,10)) ||3624!message || message[0] !=' '||3625(message[1] !='+'&& message[1] !='-') ||3626!isdigit(message[2]) || !isdigit(message[3]) ||3627!isdigit(message[4]) || !isdigit(message[5]))3628return0;/* corrupt? */3629 email_end[1] ='\0';3630 tz =strtol(message +1, NULL,10);3631if(message[6] !='\t')3632 message +=6;3633else3634 message +=7;3635returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3636}36373638static char*find_beginning_of_line(char*bob,char*scan)3639{3640while(bob < scan && *(--scan) !='\n')3641;/* keep scanning backwards */3642/*3643 * Return either beginning of the buffer, or LF at the end of3644 * the previous line.3645 */3646return scan;3647}36483649intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3650{3651struct strbuf sb = STRBUF_INIT;3652FILE*logfp;3653long pos;3654int ret =0, at_tail =1;36553656 logfp =fopen(git_path("logs/%s", refname),"r");3657if(!logfp)3658return-1;36593660/* Jump to the end */3661if(fseek(logfp,0, SEEK_END) <0)3662returnerror("cannot seek back reflog for%s:%s",3663 refname,strerror(errno));3664 pos =ftell(logfp);3665while(!ret &&0< pos) {3666int cnt;3667size_t nread;3668char buf[BUFSIZ];3669char*endp, *scanp;36703671/* Fill next block from the end */3672 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3673if(fseek(logfp, pos - cnt, SEEK_SET))3674returnerror("cannot seek back reflog for%s:%s",3675 refname,strerror(errno));3676 nread =fread(buf, cnt,1, logfp);3677if(nread !=1)3678returnerror("cannot read%dbytes from reflog for%s:%s",3679 cnt, refname,strerror(errno));3680 pos -= cnt;36813682 scanp = endp = buf + cnt;3683if(at_tail && scanp[-1] =='\n')3684/* Looking at the final LF at the end of the file */3685 scanp--;3686 at_tail =0;36873688while(buf < scanp) {3689/*3690 * terminating LF of the previous line, or the beginning3691 * of the buffer.3692 */3693char*bp;36943695 bp =find_beginning_of_line(buf, scanp);36963697if(*bp =='\n') {3698/*3699 * The newline is the end of the previous line,3700 * so we know we have complete line starting3701 * at (bp + 1). Prefix it onto any prior data3702 * we collected for the line and process it.3703 */3704strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3705 scanp = bp;3706 endp = bp +1;3707 ret =show_one_reflog_ent(&sb, fn, cb_data);3708strbuf_reset(&sb);3709if(ret)3710break;3711}else if(!pos) {3712/*3713 * We are at the start of the buffer, and the3714 * start of the file; there is no previous3715 * line, and we have everything for this one.3716 * Process it, and we can end the loop.3717 */3718strbuf_splice(&sb,0,0, buf, endp - buf);3719 ret =show_one_reflog_ent(&sb, fn, cb_data);3720strbuf_reset(&sb);3721break;3722}37233724if(bp == buf) {3725/*3726 * We are at the start of the buffer, and there3727 * is more file to read backwards. Which means3728 * we are in the middle of a line. Note that we3729 * may get here even if *bp was a newline; that3730 * just means we are at the exact end of the3731 * previous line, rather than some spot in the3732 * middle.3733 *3734 * Save away what we have to be combined with3735 * the data from the next read.3736 */3737strbuf_splice(&sb,0,0, buf, endp - buf);3738break;3739}3740}37413742}3743if(!ret && sb.len)3744die("BUG: reverse reflog parser had leftover data");37453746fclose(logfp);3747strbuf_release(&sb);3748return ret;3749}37503751intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3752{3753FILE*logfp;3754struct strbuf sb = STRBUF_INIT;3755int ret =0;37563757 logfp =fopen(git_path("logs/%s", refname),"r");3758if(!logfp)3759return-1;37603761while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3762 ret =show_one_reflog_ent(&sb, fn, cb_data);3763fclose(logfp);3764strbuf_release(&sb);3765return ret;3766}3767/*3768 * Call fn for each reflog in the namespace indicated by name. name3769 * must be empty or end with '/'. Name will be used as a scratch3770 * space, but its contents will be restored before return.3771 */3772static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3773{3774DIR*d =opendir(git_path("logs/%s", name->buf));3775int retval =0;3776struct dirent *de;3777int oldlen = name->len;37783779if(!d)3780return name->len ? errno :0;37813782while((de =readdir(d)) != NULL) {3783struct stat st;37843785if(de->d_name[0] =='.')3786continue;3787if(ends_with(de->d_name,".lock"))3788continue;3789strbuf_addstr(name, de->d_name);3790if(stat(git_path("logs/%s", name->buf), &st) <0) {3791;/* silently ignore */3792}else{3793if(S_ISDIR(st.st_mode)) {3794strbuf_addch(name,'/');3795 retval =do_for_each_reflog(name, fn, cb_data);3796}else{3797struct object_id oid;37983799if(read_ref_full(name->buf,0, oid.hash, NULL))3800 retval =error("bad ref for%s", name->buf);3801else3802 retval =fn(name->buf, &oid,0, cb_data);3803}3804if(retval)3805break;3806}3807strbuf_setlen(name, oldlen);3808}3809closedir(d);3810return retval;3811}38123813intfor_each_reflog(each_ref_fn fn,void*cb_data)3814{3815int retval;3816struct strbuf name;3817strbuf_init(&name, PATH_MAX);3818 retval =do_for_each_reflog(&name, fn, cb_data);3819strbuf_release(&name);3820return retval;3821}38223823/**3824 * Information needed for a single ref update. Set new_sha1 to the new3825 * value or to null_sha1 to delete the ref. To check the old value3826 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3827 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3828 * not exist before update.3829 */3830struct ref_update {3831/*3832 * If (flags & REF_HAVE_NEW), set the reference to this value:3833 */3834unsigned char new_sha1[20];3835/*3836 * If (flags & REF_HAVE_OLD), check that the reference3837 * previously had this value:3838 */3839unsigned char old_sha1[20];3840/*3841 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3842 * REF_DELETING, and REF_ISPRUNING:3843 */3844unsigned int flags;3845struct ref_lock *lock;3846int type;3847char*msg;3848const char refname[FLEX_ARRAY];3849};38503851/*3852 * Transaction states.3853 * OPEN: The transaction is in a valid state and can accept new updates.3854 * An OPEN transaction can be committed.3855 * CLOSED: A closed transaction is no longer active and no other operations3856 * than free can be used on it in this state.3857 * A transaction can either become closed by successfully committing3858 * an active transaction or if there is a failure while building3859 * the transaction thus rendering it failed/inactive.3860 */3861enum ref_transaction_state {3862 REF_TRANSACTION_OPEN =0,3863 REF_TRANSACTION_CLOSED =13864};38653866/*3867 * Data structure for holding a reference transaction, which can3868 * consist of checks and updates to multiple references, carried out3869 * as atomically as possible. This structure is opaque to callers.3870 */3871struct ref_transaction {3872struct ref_update **updates;3873size_t alloc;3874size_t nr;3875enum ref_transaction_state state;3876};38773878struct ref_transaction *ref_transaction_begin(struct strbuf *err)3879{3880assert(err);38813882returnxcalloc(1,sizeof(struct ref_transaction));3883}38843885voidref_transaction_free(struct ref_transaction *transaction)3886{3887int i;38883889if(!transaction)3890return;38913892for(i =0; i < transaction->nr; i++) {3893free(transaction->updates[i]->msg);3894free(transaction->updates[i]);3895}3896free(transaction->updates);3897free(transaction);3898}38993900static struct ref_update *add_update(struct ref_transaction *transaction,3901const char*refname)3902{3903size_t len =strlen(refname);3904struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);39053906strcpy((char*)update->refname, refname);3907ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3908 transaction->updates[transaction->nr++] = update;3909return update;3910}39113912intref_transaction_update(struct ref_transaction *transaction,3913const char*refname,3914const unsigned char*new_sha1,3915const unsigned char*old_sha1,3916unsigned int flags,const char*msg,3917struct strbuf *err)3918{3919struct ref_update *update;39203921assert(err);39223923if(transaction->state != REF_TRANSACTION_OPEN)3924die("BUG: update called for transaction that is not open");39253926if(new_sha1 && !is_null_sha1(new_sha1) &&3927check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3928strbuf_addf(err,"refusing to update ref with bad name%s",3929 refname);3930return-1;3931}39323933 update =add_update(transaction, refname);3934if(new_sha1) {3935hashcpy(update->new_sha1, new_sha1);3936 flags |= REF_HAVE_NEW;3937}3938if(old_sha1) {3939hashcpy(update->old_sha1, old_sha1);3940 flags |= REF_HAVE_OLD;3941}3942 update->flags = flags;3943if(msg)3944 update->msg =xstrdup(msg);3945return0;3946}39473948intref_transaction_create(struct ref_transaction *transaction,3949const char*refname,3950const unsigned char*new_sha1,3951unsigned int flags,const char*msg,3952struct strbuf *err)3953{3954if(!new_sha1 ||is_null_sha1(new_sha1))3955die("BUG: create called without valid new_sha1");3956returnref_transaction_update(transaction, refname, new_sha1,3957 null_sha1, flags, msg, err);3958}39593960intref_transaction_delete(struct ref_transaction *transaction,3961const char*refname,3962const unsigned char*old_sha1,3963unsigned int flags,const char*msg,3964struct strbuf *err)3965{3966if(old_sha1 &&is_null_sha1(old_sha1))3967die("BUG: delete called with old_sha1 set to zeros");3968returnref_transaction_update(transaction, refname,3969 null_sha1, old_sha1,3970 flags, msg, err);3971}39723973intref_transaction_verify(struct ref_transaction *transaction,3974const char*refname,3975const unsigned char*old_sha1,3976unsigned int flags,3977struct strbuf *err)3978{3979if(!old_sha1)3980die("BUG: verify called with old_sha1 set to NULL");3981returnref_transaction_update(transaction, refname,3982 NULL, old_sha1,3983 flags, NULL, err);3984}39853986intupdate_ref(const char*msg,const char*refname,3987const unsigned char*new_sha1,const unsigned char*old_sha1,3988unsigned int flags,enum action_on_err onerr)3989{3990struct ref_transaction *t = NULL;3991struct strbuf err = STRBUF_INIT;3992int ret =0;39933994if(ref_type(refname) == REF_TYPE_PSEUDOREF) {3995 ret =write_pseudoref(refname, new_sha1, old_sha1, &err);3996}else{3997 t =ref_transaction_begin(&err);3998if(!t ||3999ref_transaction_update(t, refname, new_sha1, old_sha1,4000 flags, msg, &err) ||4001ref_transaction_commit(t, &err)) {4002 ret =1;4003ref_transaction_free(t);4004}4005}4006if(ret) {4007const char*str ="update_ref failed for ref '%s':%s";40084009switch(onerr) {4010case UPDATE_REFS_MSG_ON_ERR:4011error(str, refname, err.buf);4012break;4013case UPDATE_REFS_DIE_ON_ERR:4014die(str, refname, err.buf);4015break;4016case UPDATE_REFS_QUIET_ON_ERR:4017break;4018}4019strbuf_release(&err);4020return1;4021}4022strbuf_release(&err);4023if(t)4024ref_transaction_free(t);4025return0;4026}40274028static intref_update_reject_duplicates(struct string_list *refnames,4029struct strbuf *err)4030{4031int i, n = refnames->nr;40324033assert(err);40344035for(i =1; i < n; i++)4036if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {4037strbuf_addf(err,4038"Multiple updates for ref '%s' not allowed.",4039 refnames->items[i].string);4040return1;4041}4042return0;4043}40444045intref_transaction_commit(struct ref_transaction *transaction,4046struct strbuf *err)4047{4048int ret =0, i;4049int n = transaction->nr;4050struct ref_update **updates = transaction->updates;4051struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4052struct string_list_item *ref_to_delete;4053struct string_list affected_refnames = STRING_LIST_INIT_NODUP;40544055assert(err);40564057if(transaction->state != REF_TRANSACTION_OPEN)4058die("BUG: commit called for transaction that is not open");40594060if(!n) {4061 transaction->state = REF_TRANSACTION_CLOSED;4062return0;4063}40644065/* Fail if a refname appears more than once in the transaction: */4066for(i =0; i < n; i++)4067string_list_append(&affected_refnames, updates[i]->refname);4068string_list_sort(&affected_refnames);4069if(ref_update_reject_duplicates(&affected_refnames, err)) {4070 ret = TRANSACTION_GENERIC_ERROR;4071goto cleanup;4072}40734074/*4075 * Acquire all locks, verify old values if provided, check4076 * that new values are valid, and write new values to the4077 * lockfiles, ready to be activated. Only keep one lockfile4078 * open at a time to avoid running out of file descriptors.4079 */4080for(i =0; i < n; i++) {4081struct ref_update *update = updates[i];40824083if((update->flags & REF_HAVE_NEW) &&4084is_null_sha1(update->new_sha1))4085 update->flags |= REF_DELETING;4086 update->lock =lock_ref_sha1_basic(4087 update->refname,4088((update->flags & REF_HAVE_OLD) ?4089 update->old_sha1 : NULL),4090&affected_refnames, NULL,4091 update->flags,4092&update->type,4093 err);4094if(!update->lock) {4095char*reason;40964097 ret = (errno == ENOTDIR)4098? TRANSACTION_NAME_CONFLICT4099: TRANSACTION_GENERIC_ERROR;4100 reason =strbuf_detach(err, NULL);4101strbuf_addf(err,"cannot lock ref '%s':%s",4102 update->refname, reason);4103free(reason);4104goto cleanup;4105}4106if((update->flags & REF_HAVE_NEW) &&4107!(update->flags & REF_DELETING)) {4108int overwriting_symref = ((update->type & REF_ISSYMREF) &&4109(update->flags & REF_NODEREF));41104111if(!overwriting_symref &&4112!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4113/*4114 * The reference already has the desired4115 * value, so we don't need to write it.4116 */4117}else if(write_ref_to_lockfile(update->lock,4118 update->new_sha1,4119 err)) {4120char*write_err =strbuf_detach(err, NULL);41214122/*4123 * The lock was freed upon failure of4124 * write_ref_to_lockfile():4125 */4126 update->lock = NULL;4127strbuf_addf(err,4128"cannot update the ref '%s':%s",4129 update->refname, write_err);4130free(write_err);4131 ret = TRANSACTION_GENERIC_ERROR;4132goto cleanup;4133}else{4134 update->flags |= REF_NEEDS_COMMIT;4135}4136}4137if(!(update->flags & REF_NEEDS_COMMIT)) {4138/*4139 * We didn't have to write anything to the lockfile.4140 * Close it to free up the file descriptor:4141 */4142if(close_ref(update->lock)) {4143strbuf_addf(err,"Couldn't close%s.lock",4144 update->refname);4145goto cleanup;4146}4147}4148}41494150/* Perform updates first so live commits remain referenced */4151for(i =0; i < n; i++) {4152struct ref_update *update = updates[i];41534154if(update->flags & REF_NEEDS_COMMIT) {4155if(commit_ref_update(update->lock,4156 update->new_sha1, update->msg,4157 update->flags, err)) {4158/* freed by commit_ref_update(): */4159 update->lock = NULL;4160 ret = TRANSACTION_GENERIC_ERROR;4161goto cleanup;4162}else{4163/* freed by commit_ref_update(): */4164 update->lock = NULL;4165}4166}4167}41684169/* Perform deletes now that updates are safely completed */4170for(i =0; i < n; i++) {4171struct ref_update *update = updates[i];41724173if(update->flags & REF_DELETING) {4174if(delete_ref_loose(update->lock, update->type, err)) {4175 ret = TRANSACTION_GENERIC_ERROR;4176goto cleanup;4177}41784179if(!(update->flags & REF_ISPRUNING))4180string_list_append(&refs_to_delete,4181 update->lock->ref_name);4182}4183}41844185if(repack_without_refs(&refs_to_delete, err)) {4186 ret = TRANSACTION_GENERIC_ERROR;4187goto cleanup;4188}4189for_each_string_list_item(ref_to_delete, &refs_to_delete)4190unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4191clear_loose_ref_cache(&ref_cache);41924193cleanup:4194 transaction->state = REF_TRANSACTION_CLOSED;41954196for(i =0; i < n; i++)4197if(updates[i]->lock)4198unlock_ref(updates[i]->lock);4199string_list_clear(&refs_to_delete,0);4200string_list_clear(&affected_refnames,0);4201return ret;4202}42034204char*shorten_unambiguous_ref(const char*refname,int strict)4205{4206int i;4207static char**scanf_fmts;4208static int nr_rules;4209char*short_name;42104211if(!nr_rules) {4212/*4213 * Pre-generate scanf formats from ref_rev_parse_rules[].4214 * Generate a format suitable for scanf from a4215 * ref_rev_parse_rules rule by interpolating "%s" at the4216 * location of the "%.*s".4217 */4218size_t total_len =0;4219size_t offset =0;42204221/* the rule list is NULL terminated, count them first */4222for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4223/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4224 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;42254226 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);42274228 offset =0;4229for(i =0; i < nr_rules; i++) {4230assert(offset < total_len);4231 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4232 offset +=snprintf(scanf_fmts[i], total_len - offset,4233 ref_rev_parse_rules[i],2,"%s") +1;4234}4235}42364237/* bail out if there are no rules */4238if(!nr_rules)4239returnxstrdup(refname);42404241/* buffer for scanf result, at most refname must fit */4242 short_name =xstrdup(refname);42434244/* skip first rule, it will always match */4245for(i = nr_rules -1; i >0; --i) {4246int j;4247int rules_to_fail = i;4248int short_name_len;42494250if(1!=sscanf(refname, scanf_fmts[i], short_name))4251continue;42524253 short_name_len =strlen(short_name);42544255/*4256 * in strict mode, all (except the matched one) rules4257 * must fail to resolve to a valid non-ambiguous ref4258 */4259if(strict)4260 rules_to_fail = nr_rules;42614262/*4263 * check if the short name resolves to a valid ref,4264 * but use only rules prior to the matched one4265 */4266for(j =0; j < rules_to_fail; j++) {4267const char*rule = ref_rev_parse_rules[j];4268char refname[PATH_MAX];42694270/* skip matched rule */4271if(i == j)4272continue;42734274/*4275 * the short name is ambiguous, if it resolves4276 * (with this previous rule) to a valid ref4277 * read_ref() returns 0 on success4278 */4279mksnpath(refname,sizeof(refname),4280 rule, short_name_len, short_name);4281if(ref_exists(refname))4282break;4283}42844285/*4286 * short name is non-ambiguous if all previous rules4287 * haven't resolved to a valid ref4288 */4289if(j == rules_to_fail)4290return short_name;4291}42924293free(short_name);4294returnxstrdup(refname);4295}42964297static struct string_list *hide_refs;42984299intparse_hide_refs_config(const char*var,const char*value,const char*section)4300{4301if(!strcmp("transfer.hiderefs", var) ||4302/* NEEDSWORK: use parse_config_key() once both are merged */4303(starts_with(var, section) && var[strlen(section)] =='.'&&4304!strcmp(var +strlen(section),".hiderefs"))) {4305char*ref;4306int len;43074308if(!value)4309returnconfig_error_nonbool(var);4310 ref =xstrdup(value);4311 len =strlen(ref);4312while(len && ref[len -1] =='/')4313 ref[--len] ='\0';4314if(!hide_refs) {4315 hide_refs =xcalloc(1,sizeof(*hide_refs));4316 hide_refs->strdup_strings =1;4317}4318string_list_append(hide_refs, ref);4319}4320return0;4321}43224323intref_is_hidden(const char*refname)4324{4325struct string_list_item *item;43264327if(!hide_refs)4328return0;4329for_each_string_list_item(item, hide_refs) {4330int len;4331if(!starts_with(refname, item->string))4332continue;4333 len =strlen(item->string);4334if(!refname[len] || refname[len] =='/')4335return1;4336}4337return0;4338}43394340struct expire_reflog_cb {4341unsigned int flags;4342 reflog_expiry_should_prune_fn *should_prune_fn;4343void*policy_cb;4344FILE*newlog;4345unsigned char last_kept_sha1[20];4346};43474348static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4349const char*email,unsigned long timestamp,int tz,4350const char*message,void*cb_data)4351{4352struct expire_reflog_cb *cb = cb_data;4353struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;43544355if(cb->flags & EXPIRE_REFLOGS_REWRITE)4356 osha1 = cb->last_kept_sha1;43574358if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4359 message, policy_cb)) {4360if(!cb->newlog)4361printf("would prune%s", message);4362else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4363printf("prune%s", message);4364}else{4365if(cb->newlog) {4366fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4367sha1_to_hex(osha1),sha1_to_hex(nsha1),4368 email, timestamp, tz, message);4369hashcpy(cb->last_kept_sha1, nsha1);4370}4371if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4372printf("keep%s", message);4373}4374return0;4375}43764377intreflog_expire(const char*refname,const unsigned char*sha1,4378unsigned int flags,4379 reflog_expiry_prepare_fn prepare_fn,4380 reflog_expiry_should_prune_fn should_prune_fn,4381 reflog_expiry_cleanup_fn cleanup_fn,4382void*policy_cb_data)4383{4384static struct lock_file reflog_lock;4385struct expire_reflog_cb cb;4386struct ref_lock *lock;4387char*log_file;4388int status =0;4389int type;4390struct strbuf err = STRBUF_INIT;43914392memset(&cb,0,sizeof(cb));4393 cb.flags = flags;4394 cb.policy_cb = policy_cb_data;4395 cb.should_prune_fn = should_prune_fn;43964397/*4398 * The reflog file is locked by holding the lock on the4399 * reference itself, plus we might need to update the4400 * reference if --updateref was specified:4401 */4402 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4403if(!lock) {4404error("cannot lock ref '%s':%s", refname, err.buf);4405strbuf_release(&err);4406return-1;4407}4408if(!reflog_exists(refname)) {4409unlock_ref(lock);4410return0;4411}44124413 log_file =git_pathdup("logs/%s", refname);4414if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4415/*4416 * Even though holding $GIT_DIR/logs/$reflog.lock has4417 * no locking implications, we use the lock_file4418 * machinery here anyway because it does a lot of the4419 * work we need, including cleaning up if the program4420 * exits unexpectedly.4421 */4422if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4423struct strbuf err = STRBUF_INIT;4424unable_to_lock_message(log_file, errno, &err);4425error("%s", err.buf);4426strbuf_release(&err);4427goto failure;4428}4429 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4430if(!cb.newlog) {4431error("cannot fdopen%s(%s)",4432 reflog_lock.filename.buf,strerror(errno));4433goto failure;4434}4435}44364437(*prepare_fn)(refname, sha1, cb.policy_cb);4438for_each_reflog_ent(refname, expire_reflog_ent, &cb);4439(*cleanup_fn)(cb.policy_cb);44404441if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4442/*4443 * It doesn't make sense to adjust a reference pointed4444 * to by a symbolic ref based on expiring entries in4445 * the symbolic reference's reflog. Nor can we update4446 * a reference if there are no remaining reflog4447 * entries.4448 */4449int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4450!(type & REF_ISSYMREF) &&4451!is_null_sha1(cb.last_kept_sha1);44524453if(close_lock_file(&reflog_lock)) {4454 status |=error("couldn't write%s:%s", log_file,4455strerror(errno));4456}else if(update &&4457(write_in_full(lock->lk->fd,4458sha1_to_hex(cb.last_kept_sha1),40) !=40||4459write_str_in_full(lock->lk->fd,"\n") !=1||4460close_ref(lock) <0)) {4461 status |=error("couldn't write%s",4462 lock->lk->filename.buf);4463rollback_lock_file(&reflog_lock);4464}else if(commit_lock_file(&reflog_lock)) {4465 status |=error("unable to commit reflog '%s' (%s)",4466 log_file,strerror(errno));4467}else if(update &&commit_ref(lock)) {4468 status |=error("couldn't set%s", lock->ref_name);4469}4470}4471free(log_file);4472unlock_ref(lock);4473return status;44744475 failure:4476rollback_lock_file(&reflog_lock);4477free(log_file);4478unlock_ref(lock);4479return-1;4480}