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}13211322/*1323 * Add a reference to the in-memory packed reference cache. This may1324 * only be called while the packed-refs file is locked (see1325 * lock_packed_refs()). To actually write the packed-refs file, call1326 * commit_packed_refs().1327 */1328static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1329{1330struct packed_ref_cache *packed_ref_cache =1331get_packed_ref_cache(&ref_cache);13321333if(!packed_ref_cache->lock)1334die("internal error: packed refs not locked");1335add_ref(get_packed_ref_dir(packed_ref_cache),1336create_ref_entry(refname, sha1, REF_ISPACKED,1));1337}13381339/*1340 * Read the loose references from the namespace dirname into dir1341 * (without recursing). dirname must end with '/'. dir must be the1342 * directory entry corresponding to dirname.1343 */1344static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1345{1346struct ref_cache *refs = dir->ref_cache;1347DIR*d;1348const char*path;1349struct dirent *de;1350int dirnamelen =strlen(dirname);1351struct strbuf refname;13521353if(*refs->name)1354 path =git_path_submodule(refs->name,"%s", dirname);1355else1356 path =git_path("%s", dirname);13571358 d =opendir(path);1359if(!d)1360return;13611362strbuf_init(&refname, dirnamelen +257);1363strbuf_add(&refname, dirname, dirnamelen);13641365while((de =readdir(d)) != NULL) {1366unsigned char sha1[20];1367struct stat st;1368int flag;1369const char*refdir;13701371if(de->d_name[0] =='.')1372continue;1373if(ends_with(de->d_name,".lock"))1374continue;1375strbuf_addstr(&refname, de->d_name);1376 refdir = *refs->name1377?git_path_submodule(refs->name,"%s", refname.buf)1378:git_path("%s", refname.buf);1379if(stat(refdir, &st) <0) {1380;/* silently ignore */1381}else if(S_ISDIR(st.st_mode)) {1382strbuf_addch(&refname,'/');1383add_entry_to_dir(dir,1384create_dir_entry(refs, refname.buf,1385 refname.len,1));1386}else{1387int read_ok;13881389if(*refs->name) {1390hashclr(sha1);1391 flag =0;1392 read_ok = !resolve_gitlink_ref(refs->name,1393 refname.buf, sha1);1394}else{1395 read_ok = !read_ref_full(refname.buf,1396 RESOLVE_REF_READING,1397 sha1, &flag);1398}13991400if(!read_ok) {1401hashclr(sha1);1402 flag |= REF_ISBROKEN;1403}else if(is_null_sha1(sha1)) {1404/*1405 * It is so astronomically unlikely1406 * that NULL_SHA1 is the SHA-1 of an1407 * actual object that we consider its1408 * appearance in a loose reference1409 * file to be repo corruption1410 * (probably due to a software bug).1411 */1412 flag |= REF_ISBROKEN;1413}14141415if(check_refname_format(refname.buf,1416 REFNAME_ALLOW_ONELEVEL)) {1417if(!refname_is_safe(refname.buf))1418die("loose refname is dangerous:%s", refname.buf);1419hashclr(sha1);1420 flag |= REF_BAD_NAME | REF_ISBROKEN;1421}1422add_entry_to_dir(dir,1423create_ref_entry(refname.buf, sha1, flag,0));1424}1425strbuf_setlen(&refname, dirnamelen);1426}1427strbuf_release(&refname);1428closedir(d);1429}14301431static struct ref_dir *get_loose_refs(struct ref_cache *refs)1432{1433if(!refs->loose) {1434/*1435 * Mark the top-level directory complete because we1436 * are about to read the only subdirectory that can1437 * hold references:1438 */1439 refs->loose =create_dir_entry(refs,"",0,0);1440/*1441 * Create an incomplete entry for "refs/":1442 */1443add_entry_to_dir(get_ref_dir(refs->loose),1444create_dir_entry(refs,"refs/",5,1));1445}1446returnget_ref_dir(refs->loose);1447}14481449/* We allow "recursive" symbolic refs. Only within reason, though */1450#define MAXDEPTH 51451#define MAXREFLEN (1024)14521453/*1454 * Called by resolve_gitlink_ref_recursive() after it failed to read1455 * from the loose refs in ref_cache refs. Find <refname> in the1456 * packed-refs file for the submodule.1457 */1458static intresolve_gitlink_packed_ref(struct ref_cache *refs,1459const char*refname,unsigned char*sha1)1460{1461struct ref_entry *ref;1462struct ref_dir *dir =get_packed_refs(refs);14631464 ref =find_ref(dir, refname);1465if(ref == NULL)1466return-1;14671468hashcpy(sha1, ref->u.value.oid.hash);1469return0;1470}14711472static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1473const char*refname,unsigned char*sha1,1474int recursion)1475{1476int fd, len;1477char buffer[128], *p;1478const char*path;14791480if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1481return-1;1482 path = *refs->name1483?git_path_submodule(refs->name,"%s", refname)1484:git_path("%s", refname);1485 fd =open(path, O_RDONLY);1486if(fd <0)1487returnresolve_gitlink_packed_ref(refs, refname, sha1);14881489 len =read(fd, buffer,sizeof(buffer)-1);1490close(fd);1491if(len <0)1492return-1;1493while(len &&isspace(buffer[len-1]))1494 len--;1495 buffer[len] =0;14961497/* Was it a detached head or an old-fashioned symlink? */1498if(!get_sha1_hex(buffer, sha1))1499return0;15001501/* Symref? */1502if(strncmp(buffer,"ref:",4))1503return-1;1504 p = buffer +4;1505while(isspace(*p))1506 p++;15071508returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1509}15101511intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1512{1513int len =strlen(path), retval;1514char*submodule;1515struct ref_cache *refs;15161517while(len && path[len-1] =='/')1518 len--;1519if(!len)1520return-1;1521 submodule =xstrndup(path, len);1522 refs =get_ref_cache(submodule);1523free(submodule);15241525 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1526return retval;1527}15281529/*1530 * Return the ref_entry for the given refname from the packed1531 * references. If it does not exist, return NULL.1532 */1533static struct ref_entry *get_packed_ref(const char*refname)1534{1535returnfind_ref(get_packed_refs(&ref_cache), refname);1536}15371538/*1539 * A loose ref file doesn't exist; check for a packed ref. The1540 * options are forwarded from resolve_safe_unsafe().1541 */1542static intresolve_missing_loose_ref(const char*refname,1543int resolve_flags,1544unsigned char*sha1,1545int*flags)1546{1547struct ref_entry *entry;15481549/*1550 * The loose reference file does not exist; check for a packed1551 * reference.1552 */1553 entry =get_packed_ref(refname);1554if(entry) {1555hashcpy(sha1, entry->u.value.oid.hash);1556if(flags)1557*flags |= REF_ISPACKED;1558return0;1559}1560/* The reference is not a packed reference, either. */1561if(resolve_flags & RESOLVE_REF_READING) {1562 errno = ENOENT;1563return-1;1564}else{1565hashclr(sha1);1566return0;1567}1568}15691570/* This function needs to return a meaningful errno on failure */1571static const char*resolve_ref_unsafe_1(const char*refname,1572int resolve_flags,1573unsigned char*sha1,1574int*flags,1575struct strbuf *sb_path)1576{1577int depth = MAXDEPTH;1578 ssize_t len;1579char buffer[256];1580static char refname_buffer[256];1581int bad_name =0;15821583if(flags)1584*flags =0;15851586if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1587if(flags)1588*flags |= REF_BAD_NAME;15891590if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1591!refname_is_safe(refname)) {1592 errno = EINVAL;1593return NULL;1594}1595/*1596 * dwim_ref() uses REF_ISBROKEN to distinguish between1597 * missing refs and refs that were present but invalid,1598 * to complain about the latter to stderr.1599 *1600 * We don't know whether the ref exists, so don't set1601 * REF_ISBROKEN yet.1602 */1603 bad_name =1;1604}1605for(;;) {1606const char*path;1607struct stat st;1608char*buf;1609int fd;16101611if(--depth <0) {1612 errno = ELOOP;1613return NULL;1614}16151616strbuf_reset(sb_path);1617strbuf_git_path(sb_path,"%s", refname);1618 path = sb_path->buf;16191620/*1621 * We might have to loop back here to avoid a race1622 * condition: first we lstat() the file, then we try1623 * to read it as a link or as a file. But if somebody1624 * changes the type of the file (file <-> directory1625 * <-> symlink) between the lstat() and reading, then1626 * we don't want to report that as an error but rather1627 * try again starting with the lstat().1628 */1629 stat_ref:1630if(lstat(path, &st) <0) {1631if(errno != ENOENT)1632return NULL;1633if(resolve_missing_loose_ref(refname, resolve_flags,1634 sha1, flags))1635return NULL;1636if(bad_name) {1637hashclr(sha1);1638if(flags)1639*flags |= REF_ISBROKEN;1640}1641return refname;1642}16431644/* Follow "normalized" - ie "refs/.." symlinks by hand */1645if(S_ISLNK(st.st_mode)) {1646 len =readlink(path, buffer,sizeof(buffer)-1);1647if(len <0) {1648if(errno == ENOENT || errno == EINVAL)1649/* inconsistent with lstat; retry */1650goto stat_ref;1651else1652return NULL;1653}1654 buffer[len] =0;1655if(starts_with(buffer,"refs/") &&1656!check_refname_format(buffer,0)) {1657strcpy(refname_buffer, buffer);1658 refname = refname_buffer;1659if(flags)1660*flags |= REF_ISSYMREF;1661if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1662hashclr(sha1);1663return refname;1664}1665continue;1666}1667}16681669/* Is it a directory? */1670if(S_ISDIR(st.st_mode)) {1671 errno = EISDIR;1672return NULL;1673}16741675/*1676 * Anything else, just open it and try to use it as1677 * a ref1678 */1679 fd =open(path, O_RDONLY);1680if(fd <0) {1681if(errno == ENOENT)1682/* inconsistent with lstat; retry */1683goto stat_ref;1684else1685return NULL;1686}1687 len =read_in_full(fd, buffer,sizeof(buffer)-1);1688if(len <0) {1689int save_errno = errno;1690close(fd);1691 errno = save_errno;1692return NULL;1693}1694close(fd);1695while(len &&isspace(buffer[len-1]))1696 len--;1697 buffer[len] ='\0';16981699/*1700 * Is it a symbolic ref?1701 */1702if(!starts_with(buffer,"ref:")) {1703/*1704 * Please note that FETCH_HEAD has a second1705 * line containing other data.1706 */1707if(get_sha1_hex(buffer, sha1) ||1708(buffer[40] !='\0'&& !isspace(buffer[40]))) {1709if(flags)1710*flags |= REF_ISBROKEN;1711 errno = EINVAL;1712return NULL;1713}1714if(bad_name) {1715hashclr(sha1);1716if(flags)1717*flags |= REF_ISBROKEN;1718}1719return refname;1720}1721if(flags)1722*flags |= REF_ISSYMREF;1723 buf = buffer +4;1724while(isspace(*buf))1725 buf++;1726 refname =strcpy(refname_buffer, buf);1727if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1728hashclr(sha1);1729return refname;1730}1731if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1732if(flags)1733*flags |= REF_ISBROKEN;17341735if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1736!refname_is_safe(buf)) {1737 errno = EINVAL;1738return NULL;1739}1740 bad_name =1;1741}1742}1743}17441745const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1746unsigned char*sha1,int*flags)1747{1748struct strbuf sb_path = STRBUF_INIT;1749const char*ret =resolve_ref_unsafe_1(refname, resolve_flags,1750 sha1, flags, &sb_path);1751strbuf_release(&sb_path);1752return ret;1753}17541755char*resolve_refdup(const char*refname,int resolve_flags,1756unsigned char*sha1,int*flags)1757{1758returnxstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1759 sha1, flags));1760}17611762/* The argument to filter_refs */1763struct ref_filter {1764const char*pattern;1765 each_ref_fn *fn;1766void*cb_data;1767};17681769intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1770{1771if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1772return0;1773return-1;1774}17751776intread_ref(const char*refname,unsigned char*sha1)1777{1778returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1779}17801781intref_exists(const char*refname)1782{1783unsigned char sha1[20];1784return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1785}17861787static intfilter_refs(const char*refname,const struct object_id *oid,1788int flags,void*data)1789{1790struct ref_filter *filter = (struct ref_filter *)data;17911792if(wildmatch(filter->pattern, refname,0, NULL))1793return0;1794return filter->fn(refname, oid, flags, filter->cb_data);1795}17961797enum peel_status {1798/* object was peeled successfully: */1799 PEEL_PEELED =0,18001801/*1802 * object cannot be peeled because the named object (or an1803 * object referred to by a tag in the peel chain), does not1804 * exist.1805 */1806 PEEL_INVALID = -1,18071808/* object cannot be peeled because it is not a tag: */1809 PEEL_NON_TAG = -2,18101811/* ref_entry contains no peeled value because it is a symref: */1812 PEEL_IS_SYMREF = -3,18131814/*1815 * ref_entry cannot be peeled because it is broken (i.e., the1816 * symbolic reference cannot even be resolved to an object1817 * name):1818 */1819 PEEL_BROKEN = -41820};18211822/*1823 * Peel the named object; i.e., if the object is a tag, resolve the1824 * tag recursively until a non-tag is found. If successful, store the1825 * result to sha1 and return PEEL_PEELED. If the object is not a tag1826 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1827 * and leave sha1 unchanged.1828 */1829static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1830{1831struct object *o =lookup_unknown_object(name);18321833if(o->type == OBJ_NONE) {1834int type =sha1_object_info(name, NULL);1835if(type <0|| !object_as_type(o, type,0))1836return PEEL_INVALID;1837}18381839if(o->type != OBJ_TAG)1840return PEEL_NON_TAG;18411842 o =deref_tag_noverify(o);1843if(!o)1844return PEEL_INVALID;18451846hashcpy(sha1, o->sha1);1847return PEEL_PEELED;1848}18491850/*1851 * Peel the entry (if possible) and return its new peel_status. If1852 * repeel is true, re-peel the entry even if there is an old peeled1853 * value that is already stored in it.1854 *1855 * It is OK to call this function with a packed reference entry that1856 * might be stale and might even refer to an object that has since1857 * been garbage-collected. In such a case, if the entry has1858 * REF_KNOWS_PEELED then leave the status unchanged and return1859 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1860 */1861static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1862{1863enum peel_status status;18641865if(entry->flag & REF_KNOWS_PEELED) {1866if(repeel) {1867 entry->flag &= ~REF_KNOWS_PEELED;1868oidclr(&entry->u.value.peeled);1869}else{1870returnis_null_oid(&entry->u.value.peeled) ?1871 PEEL_NON_TAG : PEEL_PEELED;1872}1873}1874if(entry->flag & REF_ISBROKEN)1875return PEEL_BROKEN;1876if(entry->flag & REF_ISSYMREF)1877return PEEL_IS_SYMREF;18781879 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1880if(status == PEEL_PEELED || status == PEEL_NON_TAG)1881 entry->flag |= REF_KNOWS_PEELED;1882return status;1883}18841885intpeel_ref(const char*refname,unsigned char*sha1)1886{1887int flag;1888unsigned char base[20];18891890if(current_ref && (current_ref->name == refname1891|| !strcmp(current_ref->name, refname))) {1892if(peel_entry(current_ref,0))1893return-1;1894hashcpy(sha1, current_ref->u.value.peeled.hash);1895return0;1896}18971898if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1899return-1;19001901/*1902 * If the reference is packed, read its ref_entry from the1903 * cache in the hope that we already know its peeled value.1904 * We only try this optimization on packed references because1905 * (a) forcing the filling of the loose reference cache could1906 * be expensive and (b) loose references anyway usually do not1907 * have REF_KNOWS_PEELED.1908 */1909if(flag & REF_ISPACKED) {1910struct ref_entry *r =get_packed_ref(refname);1911if(r) {1912if(peel_entry(r,0))1913return-1;1914hashcpy(sha1, r->u.value.peeled.hash);1915return0;1916}1917}19181919returnpeel_object(base, sha1);1920}19211922struct warn_if_dangling_data {1923FILE*fp;1924const char*refname;1925const struct string_list *refnames;1926const char*msg_fmt;1927};19281929static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1930int flags,void*cb_data)1931{1932struct warn_if_dangling_data *d = cb_data;1933const char*resolves_to;1934struct object_id junk;19351936if(!(flags & REF_ISSYMREF))1937return0;19381939 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1940if(!resolves_to1941|| (d->refname1942?strcmp(resolves_to, d->refname)1943: !string_list_has_string(d->refnames, resolves_to))) {1944return0;1945}19461947fprintf(d->fp, d->msg_fmt, refname);1948fputc('\n', d->fp);1949return0;1950}19511952voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1953{1954struct warn_if_dangling_data data;19551956 data.fp = fp;1957 data.refname = refname;1958 data.refnames = NULL;1959 data.msg_fmt = msg_fmt;1960for_each_rawref(warn_if_dangling_symref, &data);1961}19621963voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1964{1965struct warn_if_dangling_data data;19661967 data.fp = fp;1968 data.refname = NULL;1969 data.refnames = refnames;1970 data.msg_fmt = msg_fmt;1971for_each_rawref(warn_if_dangling_symref, &data);1972}19731974/*1975 * Call fn for each reference in the specified ref_cache, omitting1976 * references not in the containing_dir of base. fn is called for all1977 * references, including broken ones. If fn ever returns a non-zero1978 * value, stop the iteration and return that value; otherwise, return1979 * 0.1980 */1981static intdo_for_each_entry(struct ref_cache *refs,const char*base,1982 each_ref_entry_fn fn,void*cb_data)1983{1984struct packed_ref_cache *packed_ref_cache;1985struct ref_dir *loose_dir;1986struct ref_dir *packed_dir;1987int retval =0;19881989/*1990 * We must make sure that all loose refs are read before accessing the1991 * packed-refs file; this avoids a race condition in which loose refs1992 * are migrated to the packed-refs file by a simultaneous process, but1993 * our in-memory view is from before the migration. get_packed_ref_cache()1994 * takes care of making sure our view is up to date with what is on1995 * disk.1996 */1997 loose_dir =get_loose_refs(refs);1998if(base && *base) {1999 loose_dir =find_containing_dir(loose_dir, base,0);2000}2001if(loose_dir)2002prime_ref_dir(loose_dir);20032004 packed_ref_cache =get_packed_ref_cache(refs);2005acquire_packed_ref_cache(packed_ref_cache);2006 packed_dir =get_packed_ref_dir(packed_ref_cache);2007if(base && *base) {2008 packed_dir =find_containing_dir(packed_dir, base,0);2009}20102011if(packed_dir && loose_dir) {2012sort_ref_dir(packed_dir);2013sort_ref_dir(loose_dir);2014 retval =do_for_each_entry_in_dirs(2015 packed_dir, loose_dir, fn, cb_data);2016}else if(packed_dir) {2017sort_ref_dir(packed_dir);2018 retval =do_for_each_entry_in_dir(2019 packed_dir,0, fn, cb_data);2020}else if(loose_dir) {2021sort_ref_dir(loose_dir);2022 retval =do_for_each_entry_in_dir(2023 loose_dir,0, fn, cb_data);2024}20252026release_packed_ref_cache(packed_ref_cache);2027return retval;2028}20292030/*2031 * Call fn for each reference in the specified ref_cache for which the2032 * refname begins with base. If trim is non-zero, then trim that many2033 * characters off the beginning of each refname before passing the2034 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2035 * broken references in the iteration. If fn ever returns a non-zero2036 * value, stop the iteration and return that value; otherwise, return2037 * 0.2038 */2039static intdo_for_each_ref(struct ref_cache *refs,const char*base,2040 each_ref_fn fn,int trim,int flags,void*cb_data)2041{2042struct ref_entry_cb data;2043 data.base = base;2044 data.trim = trim;2045 data.flags = flags;2046 data.fn = fn;2047 data.cb_data = cb_data;20482049if(ref_paranoia <0)2050 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2051if(ref_paranoia)2052 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20532054returndo_for_each_entry(refs, base, do_one_ref, &data);2055}20562057static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2058{2059struct object_id oid;2060int flag;20612062if(submodule) {2063if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2064returnfn("HEAD", &oid,0, cb_data);20652066return0;2067}20682069if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2070returnfn("HEAD", &oid, flag, cb_data);20712072return0;2073}20742075inthead_ref(each_ref_fn fn,void*cb_data)2076{2077returndo_head_ref(NULL, fn, cb_data);2078}20792080inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2081{2082returndo_head_ref(submodule, fn, cb_data);2083}20842085intfor_each_ref(each_ref_fn fn,void*cb_data)2086{2087returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2088}20892090intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2091{2092returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2093}20942095intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2096{2097returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2098}20992100intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2101 each_ref_fn fn,void*cb_data)2102{2103returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2104}21052106intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2107{2108returnfor_each_ref_in("refs/tags/", fn, cb_data);2109}21102111intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2112{2113returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2114}21152116intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2117{2118returnfor_each_ref_in("refs/heads/", fn, cb_data);2119}21202121intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2122{2123returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2124}21252126intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2127{2128returnfor_each_ref_in("refs/remotes/", fn, cb_data);2129}21302131intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2132{2133returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2134}21352136intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2137{2138returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,2139strlen(git_replace_ref_base),0, cb_data);2140}21412142inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2143{2144struct strbuf buf = STRBUF_INIT;2145int ret =0;2146struct object_id oid;2147int flag;21482149strbuf_addf(&buf,"%sHEAD",get_git_namespace());2150if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2151 ret =fn(buf.buf, &oid, flag, cb_data);2152strbuf_release(&buf);21532154return ret;2155}21562157intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2158{2159struct strbuf buf = STRBUF_INIT;2160int ret;2161strbuf_addf(&buf,"%srefs/",get_git_namespace());2162 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2163strbuf_release(&buf);2164return ret;2165}21662167intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2168const char*prefix,void*cb_data)2169{2170struct strbuf real_pattern = STRBUF_INIT;2171struct ref_filter filter;2172int ret;21732174if(!prefix && !starts_with(pattern,"refs/"))2175strbuf_addstr(&real_pattern,"refs/");2176else if(prefix)2177strbuf_addstr(&real_pattern, prefix);2178strbuf_addstr(&real_pattern, pattern);21792180if(!has_glob_specials(pattern)) {2181/* Append implied '/' '*' if not present. */2182if(real_pattern.buf[real_pattern.len -1] !='/')2183strbuf_addch(&real_pattern,'/');2184/* No need to check for '*', there is none. */2185strbuf_addch(&real_pattern,'*');2186}21872188 filter.pattern = real_pattern.buf;2189 filter.fn = fn;2190 filter.cb_data = cb_data;2191 ret =for_each_ref(filter_refs, &filter);21922193strbuf_release(&real_pattern);2194return ret;2195}21962197intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2198{2199returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2200}22012202intfor_each_rawref(each_ref_fn fn,void*cb_data)2203{2204returndo_for_each_ref(&ref_cache,"", fn,0,2205 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2206}22072208const char*prettify_refname(const char*name)2209{2210return name + (2211starts_with(name,"refs/heads/") ?11:2212starts_with(name,"refs/tags/") ?10:2213starts_with(name,"refs/remotes/") ?13:22140);2215}22162217static const char*ref_rev_parse_rules[] = {2218"%.*s",2219"refs/%.*s",2220"refs/tags/%.*s",2221"refs/heads/%.*s",2222"refs/remotes/%.*s",2223"refs/remotes/%.*s/HEAD",2224 NULL2225};22262227intrefname_match(const char*abbrev_name,const char*full_name)2228{2229const char**p;2230const int abbrev_name_len =strlen(abbrev_name);22312232for(p = ref_rev_parse_rules; *p; p++) {2233if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2234return1;2235}2236}22372238return0;2239}22402241static voidunlock_ref(struct ref_lock *lock)2242{2243/* Do not free lock->lk -- atexit() still looks at them */2244if(lock->lk)2245rollback_lock_file(lock->lk);2246free(lock->ref_name);2247free(lock->orig_ref_name);2248free(lock);2249}22502251/*2252 * Verify that the reference locked by lock has the value old_sha1.2253 * Fail if the reference doesn't exist and mustexist is set. Return 02254 * on success. On error, write an error message to err, set errno, and2255 * return a negative value.2256 */2257static intverify_lock(struct ref_lock *lock,2258const unsigned char*old_sha1,int mustexist,2259struct strbuf *err)2260{2261assert(err);22622263if(read_ref_full(lock->ref_name,2264 mustexist ? RESOLVE_REF_READING :0,2265 lock->old_oid.hash, NULL)) {2266int save_errno = errno;2267strbuf_addf(err,"can't verify ref%s", lock->ref_name);2268 errno = save_errno;2269return-1;2270}2271if(hashcmp(lock->old_oid.hash, old_sha1)) {2272strbuf_addf(err,"ref%sis at%sbut expected%s",2273 lock->ref_name,2274sha1_to_hex(lock->old_oid.hash),2275sha1_to_hex(old_sha1));2276 errno = EBUSY;2277return-1;2278}2279return0;2280}22812282static intremove_empty_directories(const char*file)2283{2284/* we want to create a file but there is a directory there;2285 * if that is an empty directory (or a directory that contains2286 * only empty directories), remove them.2287 */2288struct strbuf path;2289int result, save_errno;22902291strbuf_init(&path,20);2292strbuf_addstr(&path, file);22932294 result =remove_dir_recursively(&path, REMOVE_DIR_EMPTY_ONLY);2295 save_errno = errno;22962297strbuf_release(&path);2298 errno = save_errno;22992300return result;2301}23022303/*2304 * *string and *len will only be substituted, and *string returned (for2305 * later free()ing) if the string passed in is a magic short-hand form2306 * to name a branch.2307 */2308static char*substitute_branch_name(const char**string,int*len)2309{2310struct strbuf buf = STRBUF_INIT;2311int ret =interpret_branch_name(*string, *len, &buf);23122313if(ret == *len) {2314size_t size;2315*string =strbuf_detach(&buf, &size);2316*len = size;2317return(char*)*string;2318}23192320return NULL;2321}23222323intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2324{2325char*last_branch =substitute_branch_name(&str, &len);2326const char**p, *r;2327int refs_found =0;23282329*ref = NULL;2330for(p = ref_rev_parse_rules; *p; p++) {2331char fullref[PATH_MAX];2332unsigned char sha1_from_ref[20];2333unsigned char*this_result;2334int flag;23352336 this_result = refs_found ? sha1_from_ref : sha1;2337mksnpath(fullref,sizeof(fullref), *p, len, str);2338 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2339 this_result, &flag);2340if(r) {2341if(!refs_found++)2342*ref =xstrdup(r);2343if(!warn_ambiguous_refs)2344break;2345}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2346warning("ignoring dangling symref%s.", fullref);2347}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2348warning("ignoring broken ref%s.", fullref);2349}2350}2351free(last_branch);2352return refs_found;2353}23542355intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2356{2357char*last_branch =substitute_branch_name(&str, &len);2358const char**p;2359int logs_found =0;23602361*log = NULL;2362for(p = ref_rev_parse_rules; *p; p++) {2363unsigned char hash[20];2364char path[PATH_MAX];2365const char*ref, *it;23662367mksnpath(path,sizeof(path), *p, len, str);2368 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2369 hash, NULL);2370if(!ref)2371continue;2372if(reflog_exists(path))2373 it = path;2374else if(strcmp(ref, path) &&reflog_exists(ref))2375 it = ref;2376else2377continue;2378if(!logs_found++) {2379*log =xstrdup(it);2380hashcpy(sha1, hash);2381}2382if(!warn_ambiguous_refs)2383break;2384}2385free(last_branch);2386return logs_found;2387}23882389/*2390 * Locks a ref returning the lock on success and NULL on failure.2391 * On failure errno is set to something meaningful.2392 */2393static struct ref_lock *lock_ref_sha1_basic(const char*refname,2394const unsigned char*old_sha1,2395const struct string_list *extras,2396const struct string_list *skip,2397unsigned int flags,int*type_p,2398struct strbuf *err)2399{2400const char*ref_file;2401const char*orig_refname = refname;2402struct ref_lock *lock;2403int last_errno =0;2404int type, lflags;2405int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2406int resolve_flags =0;2407int attempts_remaining =3;24082409assert(err);24102411 lock =xcalloc(1,sizeof(struct ref_lock));24122413if(mustexist)2414 resolve_flags |= RESOLVE_REF_READING;2415if(flags & REF_DELETING) {2416 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2417if(flags & REF_NODEREF)2418 resolve_flags |= RESOLVE_REF_NO_RECURSE;2419}24202421 refname =resolve_ref_unsafe(refname, resolve_flags,2422 lock->old_oid.hash, &type);2423if(!refname && errno == EISDIR) {2424/* we are trying to lock foo but we used to2425 * have foo/bar which now does not exist;2426 * it is normal for the empty directory 'foo'2427 * to remain.2428 */2429 ref_file =git_path("%s", orig_refname);2430if(remove_empty_directories(ref_file)) {2431 last_errno = errno;24322433if(!verify_refname_available(orig_refname, extras, skip,2434get_loose_refs(&ref_cache), err))2435strbuf_addf(err,"there are still refs under '%s'",2436 orig_refname);24372438goto error_return;2439}2440 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2441 lock->old_oid.hash, &type);2442}2443if(type_p)2444*type_p = type;2445if(!refname) {2446 last_errno = errno;2447if(last_errno != ENOTDIR ||2448!verify_refname_available(orig_refname, extras, skip,2449get_loose_refs(&ref_cache), err))2450strbuf_addf(err,"unable to resolve reference%s:%s",2451 orig_refname,strerror(last_errno));24522453goto error_return;2454}2455/*2456 * If the ref did not exist and we are creating it, make sure2457 * there is no existing packed ref whose name begins with our2458 * refname, nor a packed ref whose name is a proper prefix of2459 * our refname.2460 */2461if(is_null_oid(&lock->old_oid) &&2462verify_refname_available(refname, extras, skip,2463get_packed_refs(&ref_cache), err)) {2464 last_errno = ENOTDIR;2465goto error_return;2466}24672468 lock->lk =xcalloc(1,sizeof(struct lock_file));24692470 lflags =0;2471if(flags & REF_NODEREF) {2472 refname = orig_refname;2473 lflags |= LOCK_NO_DEREF;2474}2475 lock->ref_name =xstrdup(refname);2476 lock->orig_ref_name =xstrdup(orig_refname);2477 ref_file =git_path("%s", refname);24782479 retry:2480switch(safe_create_leading_directories_const(ref_file)) {2481case SCLD_OK:2482break;/* success */2483case SCLD_VANISHED:2484if(--attempts_remaining >0)2485goto retry;2486/* fall through */2487default:2488 last_errno = errno;2489strbuf_addf(err,"unable to create directory for%s", ref_file);2490goto error_return;2491}24922493if(hold_lock_file_for_update(lock->lk, ref_file, lflags) <0) {2494 last_errno = errno;2495if(errno == ENOENT && --attempts_remaining >0)2496/*2497 * Maybe somebody just deleted one of the2498 * directories leading to ref_file. Try2499 * again:2500 */2501goto retry;2502else{2503unable_to_lock_message(ref_file, errno, err);2504goto error_return;2505}2506}2507if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2508 last_errno = errno;2509goto error_return;2510}2511return lock;25122513 error_return:2514unlock_ref(lock);2515 errno = last_errno;2516return NULL;2517}25182519/*2520 * Write an entry to the packed-refs file for the specified refname.2521 * If peeled is non-NULL, write it as the entry's peeled value.2522 */2523static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2524unsigned char*peeled)2525{2526fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2527if(peeled)2528fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2529}25302531/*2532 * An each_ref_entry_fn that writes the entry to a packed-refs file.2533 */2534static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2535{2536enum peel_status peel_status =peel_entry(entry,0);25372538if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2539error("internal error:%sis not a valid packed reference!",2540 entry->name);2541write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2542 peel_status == PEEL_PEELED ?2543 entry->u.value.peeled.hash : NULL);2544return0;2545}25462547/*2548 * Lock the packed-refs file for writing. Flags is passed to2549 * hold_lock_file_for_update(). Return 0 on success. On errors, set2550 * errno appropriately and return a nonzero value.2551 */2552static intlock_packed_refs(int flags)2553{2554static int timeout_configured =0;2555static int timeout_value =1000;25562557struct packed_ref_cache *packed_ref_cache;25582559if(!timeout_configured) {2560git_config_get_int("core.packedrefstimeout", &timeout_value);2561 timeout_configured =1;2562}25632564if(hold_lock_file_for_update_timeout(2565&packlock,git_path("packed-refs"),2566 flags, timeout_value) <0)2567return-1;2568/*2569 * Get the current packed-refs while holding the lock. If the2570 * packed-refs file has been modified since we last read it,2571 * this will automatically invalidate the cache and re-read2572 * the packed-refs file.2573 */2574 packed_ref_cache =get_packed_ref_cache(&ref_cache);2575 packed_ref_cache->lock = &packlock;2576/* Increment the reference count to prevent it from being freed: */2577acquire_packed_ref_cache(packed_ref_cache);2578return0;2579}25802581/*2582 * Write the current version of the packed refs cache from memory to2583 * disk. The packed-refs file must already be locked for writing (see2584 * lock_packed_refs()). Return zero on success. On errors, set errno2585 * and return a nonzero value2586 */2587static intcommit_packed_refs(void)2588{2589struct packed_ref_cache *packed_ref_cache =2590get_packed_ref_cache(&ref_cache);2591int error =0;2592int save_errno =0;2593FILE*out;25942595if(!packed_ref_cache->lock)2596die("internal error: packed-refs not locked");25972598 out =fdopen_lock_file(packed_ref_cache->lock,"w");2599if(!out)2600die_errno("unable to fdopen packed-refs descriptor");26012602fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2603do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),26040, write_packed_entry_fn, out);26052606if(commit_lock_file(packed_ref_cache->lock)) {2607 save_errno = errno;2608 error = -1;2609}2610 packed_ref_cache->lock = NULL;2611release_packed_ref_cache(packed_ref_cache);2612 errno = save_errno;2613return error;2614}26152616/*2617 * Rollback the lockfile for the packed-refs file, and discard the2618 * in-memory packed reference cache. (The packed-refs file will be2619 * read anew if it is needed again after this function is called.)2620 */2621static voidrollback_packed_refs(void)2622{2623struct packed_ref_cache *packed_ref_cache =2624get_packed_ref_cache(&ref_cache);26252626if(!packed_ref_cache->lock)2627die("internal error: packed-refs not locked");2628rollback_lock_file(packed_ref_cache->lock);2629 packed_ref_cache->lock = NULL;2630release_packed_ref_cache(packed_ref_cache);2631clear_packed_ref_cache(&ref_cache);2632}26332634struct ref_to_prune {2635struct ref_to_prune *next;2636unsigned char sha1[20];2637char name[FLEX_ARRAY];2638};26392640struct pack_refs_cb_data {2641unsigned int flags;2642struct ref_dir *packed_refs;2643struct ref_to_prune *ref_to_prune;2644};26452646/*2647 * An each_ref_entry_fn that is run over loose references only. If2648 * the loose reference can be packed, add an entry in the packed ref2649 * cache. If the reference should be pruned, also add it to2650 * ref_to_prune in the pack_refs_cb_data.2651 */2652static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2653{2654struct pack_refs_cb_data *cb = cb_data;2655enum peel_status peel_status;2656struct ref_entry *packed_entry;2657int is_tag_ref =starts_with(entry->name,"refs/tags/");26582659/* ALWAYS pack tags */2660if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2661return0;26622663/* Do not pack symbolic or broken refs: */2664if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2665return0;26662667/* Add a packed ref cache entry equivalent to the loose entry. */2668 peel_status =peel_entry(entry,1);2669if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2670die("internal error peeling reference%s(%s)",2671 entry->name,oid_to_hex(&entry->u.value.oid));2672 packed_entry =find_ref(cb->packed_refs, entry->name);2673if(packed_entry) {2674/* Overwrite existing packed entry with info from loose entry */2675 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2676oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2677}else{2678 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2679 REF_ISPACKED | REF_KNOWS_PEELED,0);2680add_ref(cb->packed_refs, packed_entry);2681}2682oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);26832684/* Schedule the loose reference for pruning if requested. */2685if((cb->flags & PACK_REFS_PRUNE)) {2686int namelen =strlen(entry->name) +1;2687struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2688hashcpy(n->sha1, entry->u.value.oid.hash);2689strcpy(n->name, entry->name);2690 n->next = cb->ref_to_prune;2691 cb->ref_to_prune = n;2692}2693return0;2694}26952696/*2697 * Remove empty parents, but spare refs/ and immediate subdirs.2698 * Note: munges *name.2699 */2700static voidtry_remove_empty_parents(char*name)2701{2702char*p, *q;2703int i;2704 p = name;2705for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2706while(*p && *p !='/')2707 p++;2708/* tolerate duplicate slashes; see check_refname_format() */2709while(*p =='/')2710 p++;2711}2712for(q = p; *q; q++)2713;2714while(1) {2715while(q > p && *q !='/')2716 q--;2717while(q > p && *(q-1) =='/')2718 q--;2719if(q == p)2720break;2721*q ='\0';2722if(rmdir(git_path("%s", name)))2723break;2724}2725}27262727/* make sure nobody touched the ref, and unlink */2728static voidprune_ref(struct ref_to_prune *r)2729{2730struct ref_transaction *transaction;2731struct strbuf err = STRBUF_INIT;27322733if(check_refname_format(r->name,0))2734return;27352736 transaction =ref_transaction_begin(&err);2737if(!transaction ||2738ref_transaction_delete(transaction, r->name, r->sha1,2739 REF_ISPRUNING, NULL, &err) ||2740ref_transaction_commit(transaction, &err)) {2741ref_transaction_free(transaction);2742error("%s", err.buf);2743strbuf_release(&err);2744return;2745}2746ref_transaction_free(transaction);2747strbuf_release(&err);2748try_remove_empty_parents(r->name);2749}27502751static voidprune_refs(struct ref_to_prune *r)2752{2753while(r) {2754prune_ref(r);2755 r = r->next;2756}2757}27582759intpack_refs(unsigned int flags)2760{2761struct pack_refs_cb_data cbdata;27622763memset(&cbdata,0,sizeof(cbdata));2764 cbdata.flags = flags;27652766lock_packed_refs(LOCK_DIE_ON_ERROR);2767 cbdata.packed_refs =get_packed_refs(&ref_cache);27682769do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2770 pack_if_possible_fn, &cbdata);27712772if(commit_packed_refs())2773die_errno("unable to overwrite old ref-pack file");27742775prune_refs(cbdata.ref_to_prune);2776return0;2777}27782779/*2780 * Rewrite the packed-refs file, omitting any refs listed in2781 * 'refnames'. On error, leave packed-refs unchanged, write an error2782 * message to 'err', and return a nonzero value.2783 *2784 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2785 */2786static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2787{2788struct ref_dir *packed;2789struct string_list_item *refname;2790int ret, needs_repacking =0, removed =0;27912792assert(err);27932794/* Look for a packed ref */2795for_each_string_list_item(refname, refnames) {2796if(get_packed_ref(refname->string)) {2797 needs_repacking =1;2798break;2799}2800}28012802/* Avoid locking if we have nothing to do */2803if(!needs_repacking)2804return0;/* no refname exists in packed refs */28052806if(lock_packed_refs(0)) {2807unable_to_lock_message(git_path("packed-refs"), errno, err);2808return-1;2809}2810 packed =get_packed_refs(&ref_cache);28112812/* Remove refnames from the cache */2813for_each_string_list_item(refname, refnames)2814if(remove_entry(packed, refname->string) != -1)2815 removed =1;2816if(!removed) {2817/*2818 * All packed entries disappeared while we were2819 * acquiring the lock.2820 */2821rollback_packed_refs();2822return0;2823}28242825/* Write what remains */2826 ret =commit_packed_refs();2827if(ret)2828strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2829strerror(errno));2830return ret;2831}28322833static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2834{2835assert(err);28362837if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2838/*2839 * loose. The loose file name is the same as the2840 * lockfile name, minus ".lock":2841 */2842char*loose_filename =get_locked_file_path(lock->lk);2843int res =unlink_or_msg(loose_filename, err);2844free(loose_filename);2845if(res)2846return1;2847}2848return0;2849}28502851intdelete_ref(const char*refname,const unsigned char*old_sha1,2852unsigned int flags)2853{2854struct ref_transaction *transaction;2855struct strbuf err = STRBUF_INIT;28562857 transaction =ref_transaction_begin(&err);2858if(!transaction ||2859ref_transaction_delete(transaction, refname, old_sha1,2860 flags, NULL, &err) ||2861ref_transaction_commit(transaction, &err)) {2862error("%s", err.buf);2863ref_transaction_free(transaction);2864strbuf_release(&err);2865return1;2866}2867ref_transaction_free(transaction);2868strbuf_release(&err);2869return0;2870}28712872intdelete_refs(struct string_list *refnames)2873{2874struct strbuf err = STRBUF_INIT;2875int i, result =0;28762877if(!refnames->nr)2878return0;28792880 result =repack_without_refs(refnames, &err);2881if(result) {2882/*2883 * If we failed to rewrite the packed-refs file, then2884 * it is unsafe to try to remove loose refs, because2885 * doing so might expose an obsolete packed value for2886 * a reference that might even point at an object that2887 * has been garbage collected.2888 */2889if(refnames->nr ==1)2890error(_("could not delete reference%s:%s"),2891 refnames->items[0].string, err.buf);2892else2893error(_("could not delete references:%s"), err.buf);28942895goto out;2896}28972898for(i =0; i < refnames->nr; i++) {2899const char*refname = refnames->items[i].string;29002901if(delete_ref(refname, NULL,0))2902 result |=error(_("could not remove reference%s"), refname);2903}29042905out:2906strbuf_release(&err);2907return result;2908}29092910/*2911 * People using contrib's git-new-workdir have .git/logs/refs ->2912 * /some/other/path/.git/logs/refs, and that may live on another device.2913 *2914 * IOW, to avoid cross device rename errors, the temporary renamed log must2915 * live into logs/refs.2916 */2917#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"29182919static intrename_tmp_log(const char*newrefname)2920{2921int attempts_remaining =4;29222923 retry:2924switch(safe_create_leading_directories_const(git_path("logs/%s", newrefname))) {2925case SCLD_OK:2926break;/* success */2927case SCLD_VANISHED:2928if(--attempts_remaining >0)2929goto retry;2930/* fall through */2931default:2932error("unable to create directory for%s", newrefname);2933return-1;2934}29352936if(rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", newrefname))) {2937if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {2938/*2939 * rename(a, b) when b is an existing2940 * directory ought to result in ISDIR, but2941 * Solaris 5.8 gives ENOTDIR. Sheesh.2942 */2943if(remove_empty_directories(git_path("logs/%s", newrefname))) {2944error("Directory not empty: logs/%s", newrefname);2945return-1;2946}2947goto retry;2948}else if(errno == ENOENT && --attempts_remaining >0) {2949/*2950 * Maybe another process just deleted one of2951 * the directories in the path to newrefname.2952 * Try again from the beginning.2953 */2954goto retry;2955}else{2956error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",2957 newrefname,strerror(errno));2958return-1;2959}2960}2961return0;2962}29632964static intrename_ref_available(const char*oldname,const char*newname)2965{2966struct string_list skip = STRING_LIST_INIT_NODUP;2967struct strbuf err = STRBUF_INIT;2968int ret;29692970string_list_insert(&skip, oldname);2971 ret = !verify_refname_available(newname, NULL, &skip,2972get_packed_refs(&ref_cache), &err)2973&& !verify_refname_available(newname, NULL, &skip,2974get_loose_refs(&ref_cache), &err);2975if(!ret)2976error("%s", err.buf);29772978string_list_clear(&skip,0);2979strbuf_release(&err);2980return ret;2981}29822983static intwrite_ref_to_lockfile(struct ref_lock *lock,2984const unsigned char*sha1,struct strbuf *err);2985static intcommit_ref_update(struct ref_lock *lock,2986const unsigned char*sha1,const char*logmsg,2987int flags,struct strbuf *err);29882989intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)2990{2991unsigned char sha1[20], orig_sha1[20];2992int flag =0, logmoved =0;2993struct ref_lock *lock;2994struct stat loginfo;2995int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);2996const char*symref = NULL;2997struct strbuf err = STRBUF_INIT;29982999if(log &&S_ISLNK(loginfo.st_mode))3000returnerror("reflog for%sis a symlink", oldrefname);30013002 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3003 orig_sha1, &flag);3004if(flag & REF_ISSYMREF)3005returnerror("refname%sis a symbolic ref, renaming it is not supported",3006 oldrefname);3007if(!symref)3008returnerror("refname%snot found", oldrefname);30093010if(!rename_ref_available(oldrefname, newrefname))3011return1;30123013if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3014returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3015 oldrefname,strerror(errno));30163017if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3018error("unable to delete old%s", oldrefname);3019goto rollback;3020}30213022if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3023delete_ref(newrefname, sha1, REF_NODEREF)) {3024if(errno==EISDIR) {3025if(remove_empty_directories(git_path("%s", newrefname))) {3026error("Directory not empty:%s", newrefname);3027goto rollback;3028}3029}else{3030error("unable to delete existing%s", newrefname);3031goto rollback;3032}3033}30343035if(log &&rename_tmp_log(newrefname))3036goto rollback;30373038 logmoved = log;30393040 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3041if(!lock) {3042error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3043strbuf_release(&err);3044goto rollback;3045}3046hashcpy(lock->old_oid.hash, orig_sha1);30473048if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3049commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {3050error("unable to write current sha1 into%s:%s", newrefname, err.buf);3051strbuf_release(&err);3052goto rollback;3053}30543055return0;30563057 rollback:3058 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3059if(!lock) {3060error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3061strbuf_release(&err);3062goto rollbacklog;3063}30643065 flag = log_all_ref_updates;3066 log_all_ref_updates =0;3067if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3068commit_ref_update(lock, orig_sha1, NULL,0, &err)) {3069error("unable to write current sha1 into%s:%s", oldrefname, err.buf);3070strbuf_release(&err);3071}3072 log_all_ref_updates = flag;30733074 rollbacklog:3075if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3076error("unable to restore logfile%sfrom%s:%s",3077 oldrefname, newrefname,strerror(errno));3078if(!logmoved && log &&3079rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3080error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3081 oldrefname,strerror(errno));30823083return1;3084}30853086static intclose_ref(struct ref_lock *lock)3087{3088if(close_lock_file(lock->lk))3089return-1;3090return0;3091}30923093static intcommit_ref(struct ref_lock *lock)3094{3095if(commit_lock_file(lock->lk))3096return-1;3097return0;3098}30993100/*3101 * copy the reflog message msg to buf, which has been allocated sufficiently3102 * large, while cleaning up the whitespaces. Especially, convert LF to space,3103 * because reflog file is one line per entry.3104 */3105static intcopy_msg(char*buf,const char*msg)3106{3107char*cp = buf;3108char c;3109int wasspace =1;31103111*cp++ ='\t';3112while((c = *msg++)) {3113if(wasspace &&isspace(c))3114continue;3115 wasspace =isspace(c);3116if(wasspace)3117 c =' ';3118*cp++ = c;3119}3120while(buf < cp &&isspace(cp[-1]))3121 cp--;3122*cp++ ='\n';3123return cp - buf;3124}31253126static intshould_autocreate_reflog(const char*refname)3127{3128if(!log_all_ref_updates)3129return0;3130returnstarts_with(refname,"refs/heads/") ||3131starts_with(refname,"refs/remotes/") ||3132starts_with(refname,"refs/notes/") ||3133!strcmp(refname,"HEAD");3134}31353136/*3137 * Create a reflog for a ref. If force_create = 0, the reflog will3138 * only be created for certain refs (those for which3139 * should_autocreate_reflog returns non-zero. Otherwise, create it3140 * regardless of the ref name. Fill in *err and return -1 on failure.3141 */3142static intlog_ref_setup(const char*refname,struct strbuf *sb_logfile,struct strbuf *err,int force_create)3143{3144int logfd, oflags = O_APPEND | O_WRONLY;3145char*logfile;31463147strbuf_git_path(sb_logfile,"logs/%s", refname);3148 logfile = sb_logfile->buf;3149/* make sure the rest of the function can't change "logfile" */3150 sb_logfile = NULL;3151if(force_create ||should_autocreate_reflog(refname)) {3152if(safe_create_leading_directories(logfile) <0) {3153strbuf_addf(err,"unable to create directory for%s: "3154"%s", logfile,strerror(errno));3155return-1;3156}3157 oflags |= O_CREAT;3158}31593160 logfd =open(logfile, oflags,0666);3161if(logfd <0) {3162if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3163return0;31643165if(errno == EISDIR) {3166if(remove_empty_directories(logfile)) {3167strbuf_addf(err,"There are still logs under "3168"'%s'", logfile);3169return-1;3170}3171 logfd =open(logfile, oflags,0666);3172}31733174if(logfd <0) {3175strbuf_addf(err,"unable to append to%s:%s",3176 logfile,strerror(errno));3177return-1;3178}3179}31803181adjust_shared_perm(logfile);3182close(logfd);3183return0;3184}318531863187intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3188{3189int ret;3190struct strbuf sb = STRBUF_INIT;31913192 ret =log_ref_setup(refname, &sb, err, force_create);3193strbuf_release(&sb);3194return ret;3195}31963197static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3198const unsigned char*new_sha1,3199const char*committer,const char*msg)3200{3201int msglen, written;3202unsigned maxlen, len;3203char*logrec;32043205 msglen = msg ?strlen(msg) :0;3206 maxlen =strlen(committer) + msglen +100;3207 logrec =xmalloc(maxlen);3208 len =sprintf(logrec,"%s %s %s\n",3209sha1_to_hex(old_sha1),3210sha1_to_hex(new_sha1),3211 committer);3212if(msglen)3213 len +=copy_msg(logrec + len -1, msg) -1;32143215 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3216free(logrec);3217if(written != len)3218return-1;32193220return0;3221}32223223static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3224const unsigned char*new_sha1,const char*msg,3225struct strbuf *sb_log_file,int flags,3226struct strbuf *err)3227{3228int logfd, result, oflags = O_APPEND | O_WRONLY;3229char*log_file;32303231if(log_all_ref_updates <0)3232 log_all_ref_updates = !is_bare_repository();32333234 result =log_ref_setup(refname, sb_log_file, err, flags & REF_FORCE_CREATE_REFLOG);32353236if(result)3237return result;3238 log_file = sb_log_file->buf;3239/* make sure the rest of the function can't change "log_file" */3240 sb_log_file = NULL;32413242 logfd =open(log_file, oflags);3243if(logfd <0)3244return0;3245 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3246git_committer_info(0), msg);3247if(result) {3248strbuf_addf(err,"unable to append to%s:%s", log_file,3249strerror(errno));3250close(logfd);3251return-1;3252}3253if(close(logfd)) {3254strbuf_addf(err,"unable to append to%s:%s", log_file,3255strerror(errno));3256return-1;3257}3258return0;3259}32603261static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3262const unsigned char*new_sha1,const char*msg,3263int flags,struct strbuf *err)3264{3265struct strbuf sb = STRBUF_INIT;3266int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3267 err);3268strbuf_release(&sb);3269return ret;3270}32713272intis_branch(const char*refname)3273{3274return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3275}32763277/*3278 * Write sha1 into the open lockfile, then close the lockfile. On3279 * errors, rollback the lockfile, fill in *err and3280 * return -1.3281 */3282static intwrite_ref_to_lockfile(struct ref_lock *lock,3283const unsigned char*sha1,struct strbuf *err)3284{3285static char term ='\n';3286struct object *o;32873288 o =parse_object(sha1);3289if(!o) {3290strbuf_addf(err,3291"Trying to write ref%swith nonexistent object%s",3292 lock->ref_name,sha1_to_hex(sha1));3293unlock_ref(lock);3294return-1;3295}3296if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3297strbuf_addf(err,3298"Trying to write non-commit object%sto branch%s",3299sha1_to_hex(sha1), lock->ref_name);3300unlock_ref(lock);3301return-1;3302}3303if(write_in_full(lock->lk->fd,sha1_to_hex(sha1),40) !=40||3304write_in_full(lock->lk->fd, &term,1) !=1||3305close_ref(lock) <0) {3306strbuf_addf(err,3307"Couldn't write%s", lock->lk->filename.buf);3308unlock_ref(lock);3309return-1;3310}3311return0;3312}33133314/*3315 * Commit a change to a loose reference that has already been written3316 * to the loose reference lockfile. Also update the reflogs if3317 * necessary, using the specified lockmsg (which can be NULL).3318 */3319static intcommit_ref_update(struct ref_lock *lock,3320const unsigned char*sha1,const char*logmsg,3321int flags,struct strbuf *err)3322{3323clear_loose_ref_cache(&ref_cache);3324if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||3325(strcmp(lock->ref_name, lock->orig_ref_name) &&3326log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {3327char*old_msg =strbuf_detach(err, NULL);3328strbuf_addf(err,"Cannot update the ref '%s':%s",3329 lock->ref_name, old_msg);3330free(old_msg);3331unlock_ref(lock);3332return-1;3333}3334if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3335/*3336 * Special hack: If a branch is updated directly and HEAD3337 * points to it (may happen on the remote side of a push3338 * for example) then logically the HEAD reflog should be3339 * updated too.3340 * A generic solution implies reverse symref information,3341 * but finding all symrefs pointing to the given branch3342 * would be rather costly for this rare event (the direct3343 * update of a branch) to be worth it. So let's cheat and3344 * check with HEAD only which should cover 99% of all usage3345 * scenarios (even 100% of the default ones).3346 */3347unsigned char head_sha1[20];3348int head_flag;3349const char*head_ref;3350 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3351 head_sha1, &head_flag);3352if(head_ref && (head_flag & REF_ISSYMREF) &&3353!strcmp(head_ref, lock->ref_name)) {3354struct strbuf log_err = STRBUF_INIT;3355if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3356 logmsg,0, &log_err)) {3357error("%s", log_err.buf);3358strbuf_release(&log_err);3359}3360}3361}3362if(commit_ref(lock)) {3363error("Couldn't set%s", lock->ref_name);3364unlock_ref(lock);3365return-1;3366}33673368unlock_ref(lock);3369return0;3370}33713372intcreate_symref(const char*ref_target,const char*refs_heads_master,3373const char*logmsg)3374{3375const char*lockpath;3376char ref[1000];3377int fd, len, written;3378char*git_HEAD =git_pathdup("%s", ref_target);3379unsigned char old_sha1[20], new_sha1[20];3380struct strbuf err = STRBUF_INIT;33813382if(logmsg &&read_ref(ref_target, old_sha1))3383hashclr(old_sha1);33843385if(safe_create_leading_directories(git_HEAD) <0)3386returnerror("unable to create directory for%s", git_HEAD);33873388#ifndef NO_SYMLINK_HEAD3389if(prefer_symlink_refs) {3390unlink(git_HEAD);3391if(!symlink(refs_heads_master, git_HEAD))3392goto done;3393fprintf(stderr,"no symlink - falling back to symbolic ref\n");3394}3395#endif33963397 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3398if(sizeof(ref) <= len) {3399error("refname too long:%s", refs_heads_master);3400goto error_free_return;3401}3402 lockpath =mkpath("%s.lock", git_HEAD);3403 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3404if(fd <0) {3405error("Unable to open%sfor writing", lockpath);3406goto error_free_return;3407}3408 written =write_in_full(fd, ref, len);3409if(close(fd) !=0|| written != len) {3410error("Unable to write to%s", lockpath);3411goto error_unlink_return;3412}3413if(rename(lockpath, git_HEAD) <0) {3414error("Unable to create%s", git_HEAD);3415goto error_unlink_return;3416}3417if(adjust_shared_perm(git_HEAD)) {3418error("Unable to fix permissions on%s", lockpath);3419 error_unlink_return:3420unlink_or_warn(lockpath);3421 error_free_return:3422free(git_HEAD);3423return-1;3424}34253426#ifndef NO_SYMLINK_HEAD3427 done:3428#endif3429if(logmsg && !read_ref(refs_heads_master, new_sha1) &&3430log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {3431error("%s", err.buf);3432strbuf_release(&err);3433}34343435free(git_HEAD);3436return0;3437}34383439struct read_ref_at_cb {3440const char*refname;3441unsigned long at_time;3442int cnt;3443int reccnt;3444unsigned char*sha1;3445int found_it;34463447unsigned char osha1[20];3448unsigned char nsha1[20];3449int tz;3450unsigned long date;3451char**msg;3452unsigned long*cutoff_time;3453int*cutoff_tz;3454int*cutoff_cnt;3455};34563457static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3458const char*email,unsigned long timestamp,int tz,3459const char*message,void*cb_data)3460{3461struct read_ref_at_cb *cb = cb_data;34623463 cb->reccnt++;3464 cb->tz = tz;3465 cb->date = timestamp;34663467if(timestamp <= cb->at_time || cb->cnt ==0) {3468if(cb->msg)3469*cb->msg =xstrdup(message);3470if(cb->cutoff_time)3471*cb->cutoff_time = timestamp;3472if(cb->cutoff_tz)3473*cb->cutoff_tz = tz;3474if(cb->cutoff_cnt)3475*cb->cutoff_cnt = cb->reccnt -1;3476/*3477 * we have not yet updated cb->[n|o]sha1 so they still3478 * hold the values for the previous record.3479 */3480if(!is_null_sha1(cb->osha1)) {3481hashcpy(cb->sha1, nsha1);3482if(hashcmp(cb->osha1, nsha1))3483warning("Log for ref%shas gap after%s.",3484 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3485}3486else if(cb->date == cb->at_time)3487hashcpy(cb->sha1, nsha1);3488else if(hashcmp(nsha1, cb->sha1))3489warning("Log for ref%sunexpectedly ended on%s.",3490 cb->refname,show_date(cb->date, cb->tz,3491DATE_MODE(RFC2822)));3492hashcpy(cb->osha1, osha1);3493hashcpy(cb->nsha1, nsha1);3494 cb->found_it =1;3495return1;3496}3497hashcpy(cb->osha1, osha1);3498hashcpy(cb->nsha1, nsha1);3499if(cb->cnt >0)3500 cb->cnt--;3501return0;3502}35033504static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3505const char*email,unsigned long timestamp,3506int tz,const char*message,void*cb_data)3507{3508struct read_ref_at_cb *cb = cb_data;35093510if(cb->msg)3511*cb->msg =xstrdup(message);3512if(cb->cutoff_time)3513*cb->cutoff_time = timestamp;3514if(cb->cutoff_tz)3515*cb->cutoff_tz = tz;3516if(cb->cutoff_cnt)3517*cb->cutoff_cnt = cb->reccnt;3518hashcpy(cb->sha1, osha1);3519if(is_null_sha1(cb->sha1))3520hashcpy(cb->sha1, nsha1);3521/* We just want the first entry */3522return1;3523}35243525intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3526unsigned char*sha1,char**msg,3527unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3528{3529struct read_ref_at_cb cb;35303531memset(&cb,0,sizeof(cb));3532 cb.refname = refname;3533 cb.at_time = at_time;3534 cb.cnt = cnt;3535 cb.msg = msg;3536 cb.cutoff_time = cutoff_time;3537 cb.cutoff_tz = cutoff_tz;3538 cb.cutoff_cnt = cutoff_cnt;3539 cb.sha1 = sha1;35403541for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);35423543if(!cb.reccnt) {3544if(flags & GET_SHA1_QUIETLY)3545exit(128);3546else3547die("Log for%sis empty.", refname);3548}3549if(cb.found_it)3550return0;35513552for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);35533554return1;3555}35563557intreflog_exists(const char*refname)3558{3559struct stat st;35603561return!lstat(git_path("logs/%s", refname), &st) &&3562S_ISREG(st.st_mode);3563}35643565intdelete_reflog(const char*refname)3566{3567returnremove_path(git_path("logs/%s", refname));3568}35693570static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3571{3572unsigned char osha1[20], nsha1[20];3573char*email_end, *message;3574unsigned long timestamp;3575int tz;35763577/* old SP new SP name <email> SP time TAB msg LF */3578if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3579get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3580get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3581!(email_end =strchr(sb->buf +82,'>')) ||3582 email_end[1] !=' '||3583!(timestamp =strtoul(email_end +2, &message,10)) ||3584!message || message[0] !=' '||3585(message[1] !='+'&& message[1] !='-') ||3586!isdigit(message[2]) || !isdigit(message[3]) ||3587!isdigit(message[4]) || !isdigit(message[5]))3588return0;/* corrupt? */3589 email_end[1] ='\0';3590 tz =strtol(message +1, NULL,10);3591if(message[6] !='\t')3592 message +=6;3593else3594 message +=7;3595returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3596}35973598static char*find_beginning_of_line(char*bob,char*scan)3599{3600while(bob < scan && *(--scan) !='\n')3601;/* keep scanning backwards */3602/*3603 * Return either beginning of the buffer, or LF at the end of3604 * the previous line.3605 */3606return scan;3607}36083609intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3610{3611struct strbuf sb = STRBUF_INIT;3612FILE*logfp;3613long pos;3614int ret =0, at_tail =1;36153616 logfp =fopen(git_path("logs/%s", refname),"r");3617if(!logfp)3618return-1;36193620/* Jump to the end */3621if(fseek(logfp,0, SEEK_END) <0)3622returnerror("cannot seek back reflog for%s:%s",3623 refname,strerror(errno));3624 pos =ftell(logfp);3625while(!ret &&0< pos) {3626int cnt;3627size_t nread;3628char buf[BUFSIZ];3629char*endp, *scanp;36303631/* Fill next block from the end */3632 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3633if(fseek(logfp, pos - cnt, SEEK_SET))3634returnerror("cannot seek back reflog for%s:%s",3635 refname,strerror(errno));3636 nread =fread(buf, cnt,1, logfp);3637if(nread !=1)3638returnerror("cannot read%dbytes from reflog for%s:%s",3639 cnt, refname,strerror(errno));3640 pos -= cnt;36413642 scanp = endp = buf + cnt;3643if(at_tail && scanp[-1] =='\n')3644/* Looking at the final LF at the end of the file */3645 scanp--;3646 at_tail =0;36473648while(buf < scanp) {3649/*3650 * terminating LF of the previous line, or the beginning3651 * of the buffer.3652 */3653char*bp;36543655 bp =find_beginning_of_line(buf, scanp);36563657if(*bp =='\n') {3658/*3659 * The newline is the end of the previous line,3660 * so we know we have complete line starting3661 * at (bp + 1). Prefix it onto any prior data3662 * we collected for the line and process it.3663 */3664strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3665 scanp = bp;3666 endp = bp +1;3667 ret =show_one_reflog_ent(&sb, fn, cb_data);3668strbuf_reset(&sb);3669if(ret)3670break;3671}else if(!pos) {3672/*3673 * We are at the start of the buffer, and the3674 * start of the file; there is no previous3675 * line, and we have everything for this one.3676 * Process it, and we can end the loop.3677 */3678strbuf_splice(&sb,0,0, buf, endp - buf);3679 ret =show_one_reflog_ent(&sb, fn, cb_data);3680strbuf_reset(&sb);3681break;3682}36833684if(bp == buf) {3685/*3686 * We are at the start of the buffer, and there3687 * is more file to read backwards. Which means3688 * we are in the middle of a line. Note that we3689 * may get here even if *bp was a newline; that3690 * just means we are at the exact end of the3691 * previous line, rather than some spot in the3692 * middle.3693 *3694 * Save away what we have to be combined with3695 * the data from the next read.3696 */3697strbuf_splice(&sb,0,0, buf, endp - buf);3698break;3699}3700}37013702}3703if(!ret && sb.len)3704die("BUG: reverse reflog parser had leftover data");37053706fclose(logfp);3707strbuf_release(&sb);3708return ret;3709}37103711intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3712{3713FILE*logfp;3714struct strbuf sb = STRBUF_INIT;3715int ret =0;37163717 logfp =fopen(git_path("logs/%s", refname),"r");3718if(!logfp)3719return-1;37203721while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3722 ret =show_one_reflog_ent(&sb, fn, cb_data);3723fclose(logfp);3724strbuf_release(&sb);3725return ret;3726}3727/*3728 * Call fn for each reflog in the namespace indicated by name. name3729 * must be empty or end with '/'. Name will be used as a scratch3730 * space, but its contents will be restored before return.3731 */3732static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3733{3734DIR*d =opendir(git_path("logs/%s", name->buf));3735int retval =0;3736struct dirent *de;3737int oldlen = name->len;37383739if(!d)3740return name->len ? errno :0;37413742while((de =readdir(d)) != NULL) {3743struct stat st;37443745if(de->d_name[0] =='.')3746continue;3747if(ends_with(de->d_name,".lock"))3748continue;3749strbuf_addstr(name, de->d_name);3750if(stat(git_path("logs/%s", name->buf), &st) <0) {3751;/* silently ignore */3752}else{3753if(S_ISDIR(st.st_mode)) {3754strbuf_addch(name,'/');3755 retval =do_for_each_reflog(name, fn, cb_data);3756}else{3757struct object_id oid;37583759if(read_ref_full(name->buf,0, oid.hash, NULL))3760 retval =error("bad ref for%s", name->buf);3761else3762 retval =fn(name->buf, &oid,0, cb_data);3763}3764if(retval)3765break;3766}3767strbuf_setlen(name, oldlen);3768}3769closedir(d);3770return retval;3771}37723773intfor_each_reflog(each_ref_fn fn,void*cb_data)3774{3775int retval;3776struct strbuf name;3777strbuf_init(&name, PATH_MAX);3778 retval =do_for_each_reflog(&name, fn, cb_data);3779strbuf_release(&name);3780return retval;3781}37823783/**3784 * Information needed for a single ref update. Set new_sha1 to the new3785 * value or to null_sha1 to delete the ref. To check the old value3786 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3787 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3788 * not exist before update.3789 */3790struct ref_update {3791/*3792 * If (flags & REF_HAVE_NEW), set the reference to this value:3793 */3794unsigned char new_sha1[20];3795/*3796 * If (flags & REF_HAVE_OLD), check that the reference3797 * previously had this value:3798 */3799unsigned char old_sha1[20];3800/*3801 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3802 * REF_DELETING, and REF_ISPRUNING:3803 */3804unsigned int flags;3805struct ref_lock *lock;3806int type;3807char*msg;3808const char refname[FLEX_ARRAY];3809};38103811/*3812 * Transaction states.3813 * OPEN: The transaction is in a valid state and can accept new updates.3814 * An OPEN transaction can be committed.3815 * CLOSED: A closed transaction is no longer active and no other operations3816 * than free can be used on it in this state.3817 * A transaction can either become closed by successfully committing3818 * an active transaction or if there is a failure while building3819 * the transaction thus rendering it failed/inactive.3820 */3821enum ref_transaction_state {3822 REF_TRANSACTION_OPEN =0,3823 REF_TRANSACTION_CLOSED =13824};38253826/*3827 * Data structure for holding a reference transaction, which can3828 * consist of checks and updates to multiple references, carried out3829 * as atomically as possible. This structure is opaque to callers.3830 */3831struct ref_transaction {3832struct ref_update **updates;3833size_t alloc;3834size_t nr;3835enum ref_transaction_state state;3836};38373838struct ref_transaction *ref_transaction_begin(struct strbuf *err)3839{3840assert(err);38413842returnxcalloc(1,sizeof(struct ref_transaction));3843}38443845voidref_transaction_free(struct ref_transaction *transaction)3846{3847int i;38483849if(!transaction)3850return;38513852for(i =0; i < transaction->nr; i++) {3853free(transaction->updates[i]->msg);3854free(transaction->updates[i]);3855}3856free(transaction->updates);3857free(transaction);3858}38593860static struct ref_update *add_update(struct ref_transaction *transaction,3861const char*refname)3862{3863size_t len =strlen(refname);3864struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);38653866strcpy((char*)update->refname, refname);3867ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);3868 transaction->updates[transaction->nr++] = update;3869return update;3870}38713872intref_transaction_update(struct ref_transaction *transaction,3873const char*refname,3874const unsigned char*new_sha1,3875const unsigned char*old_sha1,3876unsigned int flags,const char*msg,3877struct strbuf *err)3878{3879struct ref_update *update;38803881assert(err);38823883if(transaction->state != REF_TRANSACTION_OPEN)3884die("BUG: update called for transaction that is not open");38853886if(new_sha1 && !is_null_sha1(new_sha1) &&3887check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {3888strbuf_addf(err,"refusing to update ref with bad name%s",3889 refname);3890return-1;3891}38923893 update =add_update(transaction, refname);3894if(new_sha1) {3895hashcpy(update->new_sha1, new_sha1);3896 flags |= REF_HAVE_NEW;3897}3898if(old_sha1) {3899hashcpy(update->old_sha1, old_sha1);3900 flags |= REF_HAVE_OLD;3901}3902 update->flags = flags;3903if(msg)3904 update->msg =xstrdup(msg);3905return0;3906}39073908intref_transaction_create(struct ref_transaction *transaction,3909const char*refname,3910const unsigned char*new_sha1,3911unsigned int flags,const char*msg,3912struct strbuf *err)3913{3914if(!new_sha1 ||is_null_sha1(new_sha1))3915die("BUG: create called without valid new_sha1");3916returnref_transaction_update(transaction, refname, new_sha1,3917 null_sha1, flags, msg, err);3918}39193920intref_transaction_delete(struct ref_transaction *transaction,3921const char*refname,3922const unsigned char*old_sha1,3923unsigned int flags,const char*msg,3924struct strbuf *err)3925{3926if(old_sha1 &&is_null_sha1(old_sha1))3927die("BUG: delete called with old_sha1 set to zeros");3928returnref_transaction_update(transaction, refname,3929 null_sha1, old_sha1,3930 flags, msg, err);3931}39323933intref_transaction_verify(struct ref_transaction *transaction,3934const char*refname,3935const unsigned char*old_sha1,3936unsigned int flags,3937struct strbuf *err)3938{3939if(!old_sha1)3940die("BUG: verify called with old_sha1 set to NULL");3941returnref_transaction_update(transaction, refname,3942 NULL, old_sha1,3943 flags, NULL, err);3944}39453946intupdate_ref(const char*msg,const char*refname,3947const unsigned char*new_sha1,const unsigned char*old_sha1,3948unsigned int flags,enum action_on_err onerr)3949{3950struct ref_transaction *t;3951struct strbuf err = STRBUF_INIT;39523953 t =ref_transaction_begin(&err);3954if(!t ||3955ref_transaction_update(t, refname, new_sha1, old_sha1,3956 flags, msg, &err) ||3957ref_transaction_commit(t, &err)) {3958const char*str ="update_ref failed for ref '%s':%s";39593960ref_transaction_free(t);3961switch(onerr) {3962case UPDATE_REFS_MSG_ON_ERR:3963error(str, refname, err.buf);3964break;3965case UPDATE_REFS_DIE_ON_ERR:3966die(str, refname, err.buf);3967break;3968case UPDATE_REFS_QUIET_ON_ERR:3969break;3970}3971strbuf_release(&err);3972return1;3973}3974strbuf_release(&err);3975ref_transaction_free(t);3976return0;3977}39783979static intref_update_reject_duplicates(struct string_list *refnames,3980struct strbuf *err)3981{3982int i, n = refnames->nr;39833984assert(err);39853986for(i =1; i < n; i++)3987if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {3988strbuf_addf(err,3989"Multiple updates for ref '%s' not allowed.",3990 refnames->items[i].string);3991return1;3992}3993return0;3994}39953996intref_transaction_commit(struct ref_transaction *transaction,3997struct strbuf *err)3998{3999int ret =0, i;4000int n = transaction->nr;4001struct ref_update **updates = transaction->updates;4002struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4003struct string_list_item *ref_to_delete;4004struct string_list affected_refnames = STRING_LIST_INIT_NODUP;40054006assert(err);40074008if(transaction->state != REF_TRANSACTION_OPEN)4009die("BUG: commit called for transaction that is not open");40104011if(!n) {4012 transaction->state = REF_TRANSACTION_CLOSED;4013return0;4014}40154016/* Fail if a refname appears more than once in the transaction: */4017for(i =0; i < n; i++)4018string_list_append(&affected_refnames, updates[i]->refname);4019string_list_sort(&affected_refnames);4020if(ref_update_reject_duplicates(&affected_refnames, err)) {4021 ret = TRANSACTION_GENERIC_ERROR;4022goto cleanup;4023}40244025/*4026 * Acquire all locks, verify old values if provided, check4027 * that new values are valid, and write new values to the4028 * lockfiles, ready to be activated. Only keep one lockfile4029 * open at a time to avoid running out of file descriptors.4030 */4031for(i =0; i < n; i++) {4032struct ref_update *update = updates[i];40334034if((update->flags & REF_HAVE_NEW) &&4035is_null_sha1(update->new_sha1))4036 update->flags |= REF_DELETING;4037 update->lock =lock_ref_sha1_basic(4038 update->refname,4039((update->flags & REF_HAVE_OLD) ?4040 update->old_sha1 : NULL),4041&affected_refnames, NULL,4042 update->flags,4043&update->type,4044 err);4045if(!update->lock) {4046char*reason;40474048 ret = (errno == ENOTDIR)4049? TRANSACTION_NAME_CONFLICT4050: TRANSACTION_GENERIC_ERROR;4051 reason =strbuf_detach(err, NULL);4052strbuf_addf(err,"cannot lock ref '%s':%s",4053 update->refname, reason);4054free(reason);4055goto cleanup;4056}4057if((update->flags & REF_HAVE_NEW) &&4058!(update->flags & REF_DELETING)) {4059int overwriting_symref = ((update->type & REF_ISSYMREF) &&4060(update->flags & REF_NODEREF));40614062if(!overwriting_symref &&4063!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4064/*4065 * The reference already has the desired4066 * value, so we don't need to write it.4067 */4068}else if(write_ref_to_lockfile(update->lock,4069 update->new_sha1,4070 err)) {4071char*write_err =strbuf_detach(err, NULL);40724073/*4074 * The lock was freed upon failure of4075 * write_ref_to_lockfile():4076 */4077 update->lock = NULL;4078strbuf_addf(err,4079"cannot update the ref '%s':%s",4080 update->refname, write_err);4081free(write_err);4082 ret = TRANSACTION_GENERIC_ERROR;4083goto cleanup;4084}else{4085 update->flags |= REF_NEEDS_COMMIT;4086}4087}4088if(!(update->flags & REF_NEEDS_COMMIT)) {4089/*4090 * We didn't have to write anything to the lockfile.4091 * Close it to free up the file descriptor:4092 */4093if(close_ref(update->lock)) {4094strbuf_addf(err,"Couldn't close%s.lock",4095 update->refname);4096goto cleanup;4097}4098}4099}41004101/* Perform updates first so live commits remain referenced */4102for(i =0; i < n; i++) {4103struct ref_update *update = updates[i];41044105if(update->flags & REF_NEEDS_COMMIT) {4106if(commit_ref_update(update->lock,4107 update->new_sha1, update->msg,4108 update->flags, err)) {4109/* freed by commit_ref_update(): */4110 update->lock = NULL;4111 ret = TRANSACTION_GENERIC_ERROR;4112goto cleanup;4113}else{4114/* freed by commit_ref_update(): */4115 update->lock = NULL;4116}4117}4118}41194120/* Perform deletes now that updates are safely completed */4121for(i =0; i < n; i++) {4122struct ref_update *update = updates[i];41234124if(update->flags & REF_DELETING) {4125if(delete_ref_loose(update->lock, update->type, err)) {4126 ret = TRANSACTION_GENERIC_ERROR;4127goto cleanup;4128}41294130if(!(update->flags & REF_ISPRUNING))4131string_list_append(&refs_to_delete,4132 update->lock->ref_name);4133}4134}41354136if(repack_without_refs(&refs_to_delete, err)) {4137 ret = TRANSACTION_GENERIC_ERROR;4138goto cleanup;4139}4140for_each_string_list_item(ref_to_delete, &refs_to_delete)4141unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4142clear_loose_ref_cache(&ref_cache);41434144cleanup:4145 transaction->state = REF_TRANSACTION_CLOSED;41464147for(i =0; i < n; i++)4148if(updates[i]->lock)4149unlock_ref(updates[i]->lock);4150string_list_clear(&refs_to_delete,0);4151string_list_clear(&affected_refnames,0);4152return ret;4153}41544155static intref_present(const char*refname,4156const struct object_id *oid,int flags,void*cb_data)4157{4158struct string_list *affected_refnames = cb_data;41594160returnstring_list_has_string(affected_refnames, refname);4161}41624163intinitial_ref_transaction_commit(struct ref_transaction *transaction,4164struct strbuf *err)4165{4166struct ref_dir *loose_refs =get_loose_refs(&ref_cache);4167struct ref_dir *packed_refs =get_packed_refs(&ref_cache);4168int ret =0, i;4169int n = transaction->nr;4170struct ref_update **updates = transaction->updates;4171struct string_list affected_refnames = STRING_LIST_INIT_NODUP;41724173assert(err);41744175if(transaction->state != REF_TRANSACTION_OPEN)4176die("BUG: commit called for transaction that is not open");41774178/* Fail if a refname appears more than once in the transaction: */4179for(i =0; i < n; i++)4180string_list_append(&affected_refnames, updates[i]->refname);4181string_list_sort(&affected_refnames);4182if(ref_update_reject_duplicates(&affected_refnames, err)) {4183 ret = TRANSACTION_GENERIC_ERROR;4184goto cleanup;4185}41864187/*4188 * It's really undefined to call this function in an active4189 * repository or when there are existing references: we are4190 * only locking and changing packed-refs, so (1) any4191 * simultaneous processes might try to change a reference at4192 * the same time we do, and (2) any existing loose versions of4193 * the references that we are setting would have precedence4194 * over our values. But some remote helpers create the remote4195 * "HEAD" and "master" branches before calling this function,4196 * so here we really only check that none of the references4197 * that we are creating already exists.4198 */4199if(for_each_rawref(ref_present, &affected_refnames))4200die("BUG: initial ref transaction called with existing refs");42014202for(i =0; i < n; i++) {4203struct ref_update *update = updates[i];42044205if((update->flags & REF_HAVE_OLD) &&4206!is_null_sha1(update->old_sha1))4207die("BUG: initial ref transaction with old_sha1 set");4208if(verify_refname_available(update->refname,4209&affected_refnames, NULL,4210 loose_refs, err) ||4211verify_refname_available(update->refname,4212&affected_refnames, NULL,4213 packed_refs, err)) {4214 ret = TRANSACTION_NAME_CONFLICT;4215goto cleanup;4216}4217}42184219if(lock_packed_refs(0)) {4220strbuf_addf(err,"unable to lock packed-refs file:%s",4221strerror(errno));4222 ret = TRANSACTION_GENERIC_ERROR;4223goto cleanup;4224}42254226for(i =0; i < n; i++) {4227struct ref_update *update = updates[i];42284229if((update->flags & REF_HAVE_NEW) &&4230!is_null_sha1(update->new_sha1))4231add_packed_ref(update->refname, update->new_sha1);4232}42334234if(commit_packed_refs()) {4235strbuf_addf(err,"unable to commit packed-refs file:%s",4236strerror(errno));4237 ret = TRANSACTION_GENERIC_ERROR;4238goto cleanup;4239}42404241cleanup:4242 transaction->state = REF_TRANSACTION_CLOSED;4243string_list_clear(&affected_refnames,0);4244return ret;4245}42464247char*shorten_unambiguous_ref(const char*refname,int strict)4248{4249int i;4250static char**scanf_fmts;4251static int nr_rules;4252char*short_name;42534254if(!nr_rules) {4255/*4256 * Pre-generate scanf formats from ref_rev_parse_rules[].4257 * Generate a format suitable for scanf from a4258 * ref_rev_parse_rules rule by interpolating "%s" at the4259 * location of the "%.*s".4260 */4261size_t total_len =0;4262size_t offset =0;42634264/* the rule list is NULL terminated, count them first */4265for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4266/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4267 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;42684269 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);42704271 offset =0;4272for(i =0; i < nr_rules; i++) {4273assert(offset < total_len);4274 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4275 offset +=snprintf(scanf_fmts[i], total_len - offset,4276 ref_rev_parse_rules[i],2,"%s") +1;4277}4278}42794280/* bail out if there are no rules */4281if(!nr_rules)4282returnxstrdup(refname);42834284/* buffer for scanf result, at most refname must fit */4285 short_name =xstrdup(refname);42864287/* skip first rule, it will always match */4288for(i = nr_rules -1; i >0; --i) {4289int j;4290int rules_to_fail = i;4291int short_name_len;42924293if(1!=sscanf(refname, scanf_fmts[i], short_name))4294continue;42954296 short_name_len =strlen(short_name);42974298/*4299 * in strict mode, all (except the matched one) rules4300 * must fail to resolve to a valid non-ambiguous ref4301 */4302if(strict)4303 rules_to_fail = nr_rules;43044305/*4306 * check if the short name resolves to a valid ref,4307 * but use only rules prior to the matched one4308 */4309for(j =0; j < rules_to_fail; j++) {4310const char*rule = ref_rev_parse_rules[j];4311char refname[PATH_MAX];43124313/* skip matched rule */4314if(i == j)4315continue;43164317/*4318 * the short name is ambiguous, if it resolves4319 * (with this previous rule) to a valid ref4320 * read_ref() returns 0 on success4321 */4322mksnpath(refname,sizeof(refname),4323 rule, short_name_len, short_name);4324if(ref_exists(refname))4325break;4326}43274328/*4329 * short name is non-ambiguous if all previous rules4330 * haven't resolved to a valid ref4331 */4332if(j == rules_to_fail)4333return short_name;4334}43354336free(short_name);4337returnxstrdup(refname);4338}43394340static struct string_list *hide_refs;43414342intparse_hide_refs_config(const char*var,const char*value,const char*section)4343{4344if(!strcmp("transfer.hiderefs", var) ||4345/* NEEDSWORK: use parse_config_key() once both are merged */4346(starts_with(var, section) && var[strlen(section)] =='.'&&4347!strcmp(var +strlen(section),".hiderefs"))) {4348char*ref;4349int len;43504351if(!value)4352returnconfig_error_nonbool(var);4353 ref =xstrdup(value);4354 len =strlen(ref);4355while(len && ref[len -1] =='/')4356 ref[--len] ='\0';4357if(!hide_refs) {4358 hide_refs =xcalloc(1,sizeof(*hide_refs));4359 hide_refs->strdup_strings =1;4360}4361string_list_append(hide_refs, ref);4362}4363return0;4364}43654366intref_is_hidden(const char*refname)4367{4368struct string_list_item *item;43694370if(!hide_refs)4371return0;4372for_each_string_list_item(item, hide_refs) {4373int len;4374if(!starts_with(refname, item->string))4375continue;4376 len =strlen(item->string);4377if(!refname[len] || refname[len] =='/')4378return1;4379}4380return0;4381}43824383struct expire_reflog_cb {4384unsigned int flags;4385 reflog_expiry_should_prune_fn *should_prune_fn;4386void*policy_cb;4387FILE*newlog;4388unsigned char last_kept_sha1[20];4389};43904391static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4392const char*email,unsigned long timestamp,int tz,4393const char*message,void*cb_data)4394{4395struct expire_reflog_cb *cb = cb_data;4396struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;43974398if(cb->flags & EXPIRE_REFLOGS_REWRITE)4399 osha1 = cb->last_kept_sha1;44004401if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4402 message, policy_cb)) {4403if(!cb->newlog)4404printf("would prune%s", message);4405else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4406printf("prune%s", message);4407}else{4408if(cb->newlog) {4409fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4410sha1_to_hex(osha1),sha1_to_hex(nsha1),4411 email, timestamp, tz, message);4412hashcpy(cb->last_kept_sha1, nsha1);4413}4414if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4415printf("keep%s", message);4416}4417return0;4418}44194420intreflog_expire(const char*refname,const unsigned char*sha1,4421unsigned int flags,4422 reflog_expiry_prepare_fn prepare_fn,4423 reflog_expiry_should_prune_fn should_prune_fn,4424 reflog_expiry_cleanup_fn cleanup_fn,4425void*policy_cb_data)4426{4427static struct lock_file reflog_lock;4428struct expire_reflog_cb cb;4429struct ref_lock *lock;4430char*log_file;4431int status =0;4432int type;4433struct strbuf err = STRBUF_INIT;44344435memset(&cb,0,sizeof(cb));4436 cb.flags = flags;4437 cb.policy_cb = policy_cb_data;4438 cb.should_prune_fn = should_prune_fn;44394440/*4441 * The reflog file is locked by holding the lock on the4442 * reference itself, plus we might need to update the4443 * reference if --updateref was specified:4444 */4445 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4446if(!lock) {4447error("cannot lock ref '%s':%s", refname, err.buf);4448strbuf_release(&err);4449return-1;4450}4451if(!reflog_exists(refname)) {4452unlock_ref(lock);4453return0;4454}44554456 log_file =git_pathdup("logs/%s", refname);4457if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4458/*4459 * Even though holding $GIT_DIR/logs/$reflog.lock has4460 * no locking implications, we use the lock_file4461 * machinery here anyway because it does a lot of the4462 * work we need, including cleaning up if the program4463 * exits unexpectedly.4464 */4465if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4466struct strbuf err = STRBUF_INIT;4467unable_to_lock_message(log_file, errno, &err);4468error("%s", err.buf);4469strbuf_release(&err);4470goto failure;4471}4472 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4473if(!cb.newlog) {4474error("cannot fdopen%s(%s)",4475 reflog_lock.filename.buf,strerror(errno));4476goto failure;4477}4478}44794480(*prepare_fn)(refname, sha1, cb.policy_cb);4481for_each_reflog_ent(refname, expire_reflog_ent, &cb);4482(*cleanup_fn)(cb.policy_cb);44834484if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4485/*4486 * It doesn't make sense to adjust a reference pointed4487 * to by a symbolic ref based on expiring entries in4488 * the symbolic reference's reflog. Nor can we update4489 * a reference if there are no remaining reflog4490 * entries.4491 */4492int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4493!(type & REF_ISSYMREF) &&4494!is_null_sha1(cb.last_kept_sha1);44954496if(close_lock_file(&reflog_lock)) {4497 status |=error("couldn't write%s:%s", log_file,4498strerror(errno));4499}else if(update &&4500(write_in_full(lock->lk->fd,4501sha1_to_hex(cb.last_kept_sha1),40) !=40||4502write_str_in_full(lock->lk->fd,"\n") !=1||4503close_ref(lock) <0)) {4504 status |=error("couldn't write%s",4505 lock->lk->filename.buf);4506rollback_lock_file(&reflog_lock);4507}else if(commit_lock_file(&reflog_lock)) {4508 status |=error("unable to commit reflog '%s' (%s)",4509 log_file,strerror(errno));4510}else if(update &&commit_ref(lock)) {4511 status |=error("couldn't set%s", lock->ref_name);4512}4513}4514free(log_file);4515unlock_ref(lock);4516return status;45174518 failure:4519rollback_lock_file(&reflog_lock);4520free(log_file);4521unlock_ref(lock);4522return-1;4523}