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, and 23 * ":", "?", "[", "\", "^", "~", SP, or TAB 24 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set 25 */ 26static unsigned char refname_disposition[256] = { 271,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 284,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 294,0,0,0,0,0,0,0,0,0,5,0,0,0,2,1, 300,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 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,4,4,0,4,0, 330,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 340,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 35}; 36 37/* 38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 39 * refs (i.e., because the reference is about to be deleted anyway). 40 */ 41#define REF_DELETING 0x02 42 43/* 44 * Used as a flag in ref_update::flags when a loose ref is being 45 * pruned. 46 */ 47#define REF_ISPRUNING 0x04 48 49/* 50 * Used as a flag in ref_update::flags when the reference should be 51 * updated to new_sha1. 52 */ 53#define REF_HAVE_NEW 0x08 54 55/* 56 * Used as a flag in ref_update::flags when old_sha1 should be 57 * checked. 58 */ 59#define REF_HAVE_OLD 0x10 60 61/* 62 * Used as a flag in ref_update::flags when the lockfile needs to be 63 * committed. 64 */ 65#define REF_NEEDS_COMMIT 0x20 66 67/* 68 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a 69 * value to ref_update::flags 70 */ 71 72/* 73 * Try to read one refname component from the front of refname. 74 * Return the length of the component found, or -1 if the component is 75 * not legal. It is legal if it is something reasonable to have under 76 * ".git/refs/"; We do not like it if: 77 * 78 * - any path component of it begins with ".", or 79 * - it has double dots "..", or 80 * - it has ASCII control characters, or 81 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or 82 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or 83 * - it ends with a "/", or 84 * - it ends with ".lock", or 85 * - it contains a "@{" portion 86 */ 87static intcheck_refname_component(const char*refname,int*flags) 88{ 89const char*cp; 90char last ='\0'; 91 92for(cp = refname; ; cp++) { 93int ch = *cp &255; 94unsigned char disp = refname_disposition[ch]; 95switch(disp) { 96case1: 97goto out; 98case2: 99if(last =='.') 100return-1;/* Refname contains "..". */ 101break; 102case3: 103if(last =='@') 104return-1;/* Refname contains "@{". */ 105break; 106case4: 107return-1; 108case5: 109if(!(*flags & REFNAME_REFSPEC_PATTERN)) 110return-1;/* refspec can't be a pattern */ 111 112/* 113 * Unset the pattern flag so that we only accept 114 * a single asterisk for one side of refspec. 115 */ 116*flags &= ~ REFNAME_REFSPEC_PATTERN; 117break; 118} 119 last = ch; 120} 121out: 122if(cp == refname) 123return0;/* Component has zero length. */ 124if(refname[0] =='.') 125return-1;/* Component starts with '.'. */ 126if(cp - refname >= LOCK_SUFFIX_LEN && 127!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 128return-1;/* Refname ends with ".lock". */ 129return cp - refname; 130} 131 132intcheck_refname_format(const char*refname,int flags) 133{ 134int component_len, component_count =0; 135 136if(!strcmp(refname,"@")) 137/* Refname is a single character '@'. */ 138return-1; 139 140while(1) { 141/* We are at the start of a path component. */ 142 component_len =check_refname_component(refname, &flags); 143if(component_len <=0) 144return-1; 145 146 component_count++; 147if(refname[component_len] =='\0') 148break; 149/* Skip to next component. */ 150 refname += component_len +1; 151} 152 153if(refname[component_len -1] =='.') 154return-1;/* Refname ends with '.'. */ 155if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 156return-1;/* Refname has only one component. */ 157return0; 158} 159 160struct ref_entry; 161 162/* 163 * Information used (along with the information in ref_entry) to 164 * describe a single cached reference. This data structure only 165 * occurs embedded in a union in struct ref_entry, and only when 166 * (ref_entry->flag & REF_DIR) is zero. 167 */ 168struct ref_value { 169/* 170 * The name of the object to which this reference resolves 171 * (which may be a tag object). If REF_ISBROKEN, this is 172 * null. If REF_ISSYMREF, then this is the name of the object 173 * referred to by the last reference in the symlink chain. 174 */ 175struct object_id oid; 176 177/* 178 * If REF_KNOWS_PEELED, then this field holds the peeled value 179 * of this reference, or null if the reference is known not to 180 * be peelable. See the documentation for peel_ref() for an 181 * exact definition of "peelable". 182 */ 183struct object_id peeled; 184}; 185 186struct ref_cache; 187 188/* 189 * Information used (along with the information in ref_entry) to 190 * describe a level in the hierarchy of references. This data 191 * structure only occurs embedded in a union in struct ref_entry, and 192 * only when (ref_entry.flag & REF_DIR) is set. In that case, 193 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 194 * in the directory have already been read: 195 * 196 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 197 * or packed references, already read. 198 * 199 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 200 * references that hasn't been read yet (nor has any of its 201 * subdirectories). 202 * 203 * Entries within a directory are stored within a growable array of 204 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 205 * sorted are sorted by their component name in strcmp() order and the 206 * remaining entries are unsorted. 207 * 208 * Loose references are read lazily, one directory at a time. When a 209 * directory of loose references is read, then all of the references 210 * in that directory are stored, and REF_INCOMPLETE stubs are created 211 * for any subdirectories, but the subdirectories themselves are not 212 * read. The reading is triggered by get_ref_dir(). 213 */ 214struct ref_dir { 215int nr, alloc; 216 217/* 218 * Entries with index 0 <= i < sorted are sorted by name. New 219 * entries are appended to the list unsorted, and are sorted 220 * only when required; thus we avoid the need to sort the list 221 * after the addition of every reference. 222 */ 223int sorted; 224 225/* A pointer to the ref_cache that contains this ref_dir. */ 226struct ref_cache *ref_cache; 227 228struct ref_entry **entries; 229}; 230 231/* 232 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 233 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 234 * public values; see refs.h. 235 */ 236 237/* 238 * The field ref_entry->u.value.peeled of this value entry contains 239 * the correct peeled value for the reference, which might be 240 * null_sha1 if the reference is not a tag or if it is broken. 241 */ 242#define REF_KNOWS_PEELED 0x10 243 244/* ref_entry represents a directory of references */ 245#define REF_DIR 0x20 246 247/* 248 * Entry has not yet been read from disk (used only for REF_DIR 249 * entries representing loose references) 250 */ 251#define REF_INCOMPLETE 0x40 252 253/* 254 * A ref_entry represents either a reference or a "subdirectory" of 255 * references. 256 * 257 * Each directory in the reference namespace is represented by a 258 * ref_entry with (flags & REF_DIR) set and containing a subdir member 259 * that holds the entries in that directory that have been read so 260 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 261 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 262 * used for loose reference directories. 263 * 264 * References are represented by a ref_entry with (flags & REF_DIR) 265 * unset and a value member that describes the reference's value. The 266 * flag member is at the ref_entry level, but it is also needed to 267 * interpret the contents of the value field (in other words, a 268 * ref_value object is not very much use without the enclosing 269 * ref_entry). 270 * 271 * Reference names cannot end with slash and directories' names are 272 * always stored with a trailing slash (except for the top-level 273 * directory, which is always denoted by ""). This has two nice 274 * consequences: (1) when the entries in each subdir are sorted 275 * lexicographically by name (as they usually are), the references in 276 * a whole tree can be generated in lexicographic order by traversing 277 * the tree in left-to-right, depth-first order; (2) the names of 278 * references and subdirectories cannot conflict, and therefore the 279 * presence of an empty subdirectory does not block the creation of a 280 * similarly-named reference. (The fact that reference names with the 281 * same leading components can conflict *with each other* is a 282 * separate issue that is regulated by verify_refname_available().) 283 * 284 * Please note that the name field contains the fully-qualified 285 * reference (or subdirectory) name. Space could be saved by only 286 * storing the relative names. But that would require the full names 287 * to be generated on the fly when iterating in do_for_each_ref(), and 288 * would break callback functions, who have always been able to assume 289 * that the name strings that they are passed will not be freed during 290 * the iteration. 291 */ 292struct ref_entry { 293unsigned char flag;/* ISSYMREF? ISPACKED? */ 294union{ 295struct ref_value value;/* if not (flags&REF_DIR) */ 296struct ref_dir subdir;/* if (flags&REF_DIR) */ 297} u; 298/* 299 * The full name of the reference (e.g., "refs/heads/master") 300 * or the full name of the directory with a trailing slash 301 * (e.g., "refs/heads/"): 302 */ 303char name[FLEX_ARRAY]; 304}; 305 306static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 307static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len); 308static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 309const char*dirname,size_t len, 310int incomplete); 311static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry); 312 313static struct ref_dir *get_ref_dir(struct ref_entry *entry) 314{ 315struct ref_dir *dir; 316assert(entry->flag & REF_DIR); 317 dir = &entry->u.subdir; 318if(entry->flag & REF_INCOMPLETE) { 319read_loose_refs(entry->name, dir); 320 321/* 322 * Manually add refs/bisect, which, being 323 * per-worktree, might not appear in the directory 324 * listing for refs/ in the main repo. 325 */ 326if(!strcmp(entry->name,"refs/")) { 327int pos =search_ref_dir(dir,"refs/bisect/",12); 328if(pos <0) { 329struct ref_entry *child_entry; 330 child_entry =create_dir_entry(dir->ref_cache, 331"refs/bisect/", 33212,1); 333add_entry_to_dir(dir, child_entry); 334read_loose_refs("refs/bisect", 335&child_entry->u.subdir); 336} 337} 338 entry->flag &= ~REF_INCOMPLETE; 339} 340return dir; 341} 342 343/* 344 * Check if a refname is safe. 345 * For refs that start with "refs/" we consider it safe as long they do 346 * not try to resolve to outside of refs/. 347 * 348 * For all other refs we only consider them safe iff they only contain 349 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 350 * "config"). 351 */ 352static intrefname_is_safe(const char*refname) 353{ 354if(starts_with(refname,"refs/")) { 355char*buf; 356int result; 357 358 buf =xmalloc(strlen(refname) +1); 359/* 360 * Does the refname try to escape refs/? 361 * For example: refs/foo/../bar is safe but refs/foo/../../bar 362 * is not. 363 */ 364 result = !normalize_path_copy(buf, refname +strlen("refs/")); 365free(buf); 366return result; 367} 368while(*refname) { 369if(!isupper(*refname) && *refname !='_') 370return0; 371 refname++; 372} 373return1; 374} 375 376static struct ref_entry *create_ref_entry(const char*refname, 377const unsigned char*sha1,int flag, 378int check_name) 379{ 380int len; 381struct ref_entry *ref; 382 383if(check_name && 384check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 385die("Reference has invalid format: '%s'", refname); 386 len =strlen(refname) +1; 387 ref =xmalloc(sizeof(struct ref_entry) + len); 388hashcpy(ref->u.value.oid.hash, sha1); 389oidclr(&ref->u.value.peeled); 390memcpy(ref->name, refname, len); 391 ref->flag = flag; 392return ref; 393} 394 395static voidclear_ref_dir(struct ref_dir *dir); 396 397static voidfree_ref_entry(struct ref_entry *entry) 398{ 399if(entry->flag & REF_DIR) { 400/* 401 * Do not use get_ref_dir() here, as that might 402 * trigger the reading of loose refs. 403 */ 404clear_ref_dir(&entry->u.subdir); 405} 406free(entry); 407} 408 409/* 410 * Add a ref_entry to the end of dir (unsorted). Entry is always 411 * stored directly in dir; no recursion into subdirectories is 412 * done. 413 */ 414static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 415{ 416ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 417 dir->entries[dir->nr++] = entry; 418/* optimize for the case that entries are added in order */ 419if(dir->nr ==1|| 420(dir->nr == dir->sorted +1&& 421strcmp(dir->entries[dir->nr -2]->name, 422 dir->entries[dir->nr -1]->name) <0)) 423 dir->sorted = dir->nr; 424} 425 426/* 427 * Clear and free all entries in dir, recursively. 428 */ 429static voidclear_ref_dir(struct ref_dir *dir) 430{ 431int i; 432for(i =0; i < dir->nr; i++) 433free_ref_entry(dir->entries[i]); 434free(dir->entries); 435 dir->sorted = dir->nr = dir->alloc =0; 436 dir->entries = NULL; 437} 438 439/* 440 * Create a struct ref_entry object for the specified dirname. 441 * dirname is the name of the directory with a trailing slash (e.g., 442 * "refs/heads/") or "" for the top-level directory. 443 */ 444static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 445const char*dirname,size_t len, 446int incomplete) 447{ 448struct ref_entry *direntry; 449 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 450memcpy(direntry->name, dirname, len); 451 direntry->name[len] ='\0'; 452 direntry->u.subdir.ref_cache = ref_cache; 453 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 454return direntry; 455} 456 457static intref_entry_cmp(const void*a,const void*b) 458{ 459struct ref_entry *one = *(struct ref_entry **)a; 460struct ref_entry *two = *(struct ref_entry **)b; 461returnstrcmp(one->name, two->name); 462} 463 464static voidsort_ref_dir(struct ref_dir *dir); 465 466struct string_slice { 467size_t len; 468const char*str; 469}; 470 471static intref_entry_cmp_sslice(const void*key_,const void*ent_) 472{ 473const struct string_slice *key = key_; 474const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 475int cmp =strncmp(key->str, ent->name, key->len); 476if(cmp) 477return cmp; 478return'\0'- (unsigned char)ent->name[key->len]; 479} 480 481/* 482 * Return the index of the entry with the given refname from the 483 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 484 * no such entry is found. dir must already be complete. 485 */ 486static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 487{ 488struct ref_entry **r; 489struct string_slice key; 490 491if(refname == NULL || !dir->nr) 492return-1; 493 494sort_ref_dir(dir); 495 key.len = len; 496 key.str = refname; 497 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 498 ref_entry_cmp_sslice); 499 500if(r == NULL) 501return-1; 502 503return r - dir->entries; 504} 505 506/* 507 * Search for a directory entry directly within dir (without 508 * recursing). Sort dir if necessary. subdirname must be a directory 509 * name (i.e., end in '/'). If mkdir is set, then create the 510 * directory if it is missing; otherwise, return NULL if the desired 511 * directory cannot be found. dir must already be complete. 512 */ 513static struct ref_dir *search_for_subdir(struct ref_dir *dir, 514const char*subdirname,size_t len, 515int mkdir) 516{ 517int entry_index =search_ref_dir(dir, subdirname, len); 518struct ref_entry *entry; 519if(entry_index == -1) { 520if(!mkdir) 521return NULL; 522/* 523 * Since dir is complete, the absence of a subdir 524 * means that the subdir really doesn't exist; 525 * therefore, create an empty record for it but mark 526 * the record complete. 527 */ 528 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 529add_entry_to_dir(dir, entry); 530}else{ 531 entry = dir->entries[entry_index]; 532} 533returnget_ref_dir(entry); 534} 535 536/* 537 * If refname is a reference name, find the ref_dir within the dir 538 * tree that should hold refname. If refname is a directory name 539 * (i.e., ends in '/'), then return that ref_dir itself. dir must 540 * represent the top-level directory and must already be complete. 541 * Sort ref_dirs and recurse into subdirectories as necessary. If 542 * mkdir is set, then create any missing directories; otherwise, 543 * return NULL if the desired directory cannot be found. 544 */ 545static struct ref_dir *find_containing_dir(struct ref_dir *dir, 546const char*refname,int mkdir) 547{ 548const char*slash; 549for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 550size_t dirnamelen = slash - refname +1; 551struct ref_dir *subdir; 552 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 553if(!subdir) { 554 dir = NULL; 555break; 556} 557 dir = subdir; 558} 559 560return dir; 561} 562 563/* 564 * Find the value entry with the given name in dir, sorting ref_dirs 565 * and recursing into subdirectories as necessary. If the name is not 566 * found or it corresponds to a directory entry, return NULL. 567 */ 568static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 569{ 570int entry_index; 571struct ref_entry *entry; 572 dir =find_containing_dir(dir, refname,0); 573if(!dir) 574return NULL; 575 entry_index =search_ref_dir(dir, refname,strlen(refname)); 576if(entry_index == -1) 577return NULL; 578 entry = dir->entries[entry_index]; 579return(entry->flag & REF_DIR) ? NULL : entry; 580} 581 582/* 583 * Remove the entry with the given name from dir, recursing into 584 * subdirectories as necessary. If refname is the name of a directory 585 * (i.e., ends with '/'), then remove the directory and its contents. 586 * If the removal was successful, return the number of entries 587 * remaining in the directory entry that contained the deleted entry. 588 * If the name was not found, return -1. Please note that this 589 * function only deletes the entry from the cache; it does not delete 590 * it from the filesystem or ensure that other cache entries (which 591 * might be symbolic references to the removed entry) are updated. 592 * Nor does it remove any containing dir entries that might be made 593 * empty by the removal. dir must represent the top-level directory 594 * and must already be complete. 595 */ 596static intremove_entry(struct ref_dir *dir,const char*refname) 597{ 598int refname_len =strlen(refname); 599int entry_index; 600struct ref_entry *entry; 601int is_dir = refname[refname_len -1] =='/'; 602if(is_dir) { 603/* 604 * refname represents a reference directory. Remove 605 * the trailing slash; otherwise we will get the 606 * directory *representing* refname rather than the 607 * one *containing* it. 608 */ 609char*dirname =xmemdupz(refname, refname_len -1); 610 dir =find_containing_dir(dir, dirname,0); 611free(dirname); 612}else{ 613 dir =find_containing_dir(dir, refname,0); 614} 615if(!dir) 616return-1; 617 entry_index =search_ref_dir(dir, refname, refname_len); 618if(entry_index == -1) 619return-1; 620 entry = dir->entries[entry_index]; 621 622memmove(&dir->entries[entry_index], 623&dir->entries[entry_index +1], 624(dir->nr - entry_index -1) *sizeof(*dir->entries) 625); 626 dir->nr--; 627if(dir->sorted > entry_index) 628 dir->sorted--; 629free_ref_entry(entry); 630return dir->nr; 631} 632 633/* 634 * Add a ref_entry to the ref_dir (unsorted), recursing into 635 * subdirectories as necessary. dir must represent the top-level 636 * directory. Return 0 on success. 637 */ 638static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 639{ 640 dir =find_containing_dir(dir, ref->name,1); 641if(!dir) 642return-1; 643add_entry_to_dir(dir, ref); 644return0; 645} 646 647/* 648 * Emit a warning and return true iff ref1 and ref2 have the same name 649 * and the same sha1. Die if they have the same name but different 650 * sha1s. 651 */ 652static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 653{ 654if(strcmp(ref1->name, ref2->name)) 655return0; 656 657/* Duplicate name; make sure that they don't conflict: */ 658 659if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 660/* This is impossible by construction */ 661die("Reference directory conflict:%s", ref1->name); 662 663if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 664die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 665 666warning("Duplicated ref:%s", ref1->name); 667return1; 668} 669 670/* 671 * Sort the entries in dir non-recursively (if they are not already 672 * sorted) and remove any duplicate entries. 673 */ 674static voidsort_ref_dir(struct ref_dir *dir) 675{ 676int i, j; 677struct ref_entry *last = NULL; 678 679/* 680 * This check also prevents passing a zero-length array to qsort(), 681 * which is a problem on some platforms. 682 */ 683if(dir->sorted == dir->nr) 684return; 685 686qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 687 688/* Remove any duplicates: */ 689for(i =0, j =0; j < dir->nr; j++) { 690struct ref_entry *entry = dir->entries[j]; 691if(last &&is_dup_ref(last, entry)) 692free_ref_entry(entry); 693else 694 last = dir->entries[i++] = entry; 695} 696 dir->sorted = dir->nr = i; 697} 698 699/* Include broken references in a do_for_each_ref*() iteration: */ 700#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 701 702/* 703 * Return true iff the reference described by entry can be resolved to 704 * an object in the database. Emit a warning if the referred-to 705 * object does not exist. 706 */ 707static intref_resolves_to_object(struct ref_entry *entry) 708{ 709if(entry->flag & REF_ISBROKEN) 710return0; 711if(!has_sha1_file(entry->u.value.oid.hash)) { 712error("%sdoes not point to a valid object!", entry->name); 713return0; 714} 715return1; 716} 717 718/* 719 * current_ref is a performance hack: when iterating over references 720 * using the for_each_ref*() functions, current_ref is set to the 721 * current reference's entry before calling the callback function. If 722 * the callback function calls peel_ref(), then peel_ref() first 723 * checks whether the reference to be peeled is the current reference 724 * (it usually is) and if so, returns that reference's peeled version 725 * if it is available. This avoids a refname lookup in a common case. 726 */ 727static struct ref_entry *current_ref; 728 729typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 730 731struct ref_entry_cb { 732const char*base; 733int trim; 734int flags; 735 each_ref_fn *fn; 736void*cb_data; 737}; 738 739/* 740 * Handle one reference in a do_for_each_ref*()-style iteration, 741 * calling an each_ref_fn for each entry. 742 */ 743static intdo_one_ref(struct ref_entry *entry,void*cb_data) 744{ 745struct ref_entry_cb *data = cb_data; 746struct ref_entry *old_current_ref; 747int retval; 748 749if(!starts_with(entry->name, data->base)) 750return0; 751 752if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 753!ref_resolves_to_object(entry)) 754return0; 755 756/* Store the old value, in case this is a recursive call: */ 757 old_current_ref = current_ref; 758 current_ref = entry; 759 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 760 entry->flag, data->cb_data); 761 current_ref = old_current_ref; 762return retval; 763} 764 765/* 766 * Call fn for each reference in dir that has index in the range 767 * offset <= index < dir->nr. Recurse into subdirectories that are in 768 * that index range, sorting them before iterating. This function 769 * does not sort dir itself; it should be sorted beforehand. fn is 770 * called for all references, including broken ones. 771 */ 772static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 773 each_ref_entry_fn fn,void*cb_data) 774{ 775int i; 776assert(dir->sorted == dir->nr); 777for(i = offset; i < dir->nr; i++) { 778struct ref_entry *entry = dir->entries[i]; 779int retval; 780if(entry->flag & REF_DIR) { 781struct ref_dir *subdir =get_ref_dir(entry); 782sort_ref_dir(subdir); 783 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 784}else{ 785 retval =fn(entry, cb_data); 786} 787if(retval) 788return retval; 789} 790return0; 791} 792 793/* 794 * Call fn for each reference in the union of dir1 and dir2, in order 795 * by refname. Recurse into subdirectories. If a value entry appears 796 * in both dir1 and dir2, then only process the version that is in 797 * dir2. The input dirs must already be sorted, but subdirs will be 798 * sorted as needed. fn is called for all references, including 799 * broken ones. 800 */ 801static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 802struct ref_dir *dir2, 803 each_ref_entry_fn fn,void*cb_data) 804{ 805int retval; 806int i1 =0, i2 =0; 807 808assert(dir1->sorted == dir1->nr); 809assert(dir2->sorted == dir2->nr); 810while(1) { 811struct ref_entry *e1, *e2; 812int cmp; 813if(i1 == dir1->nr) { 814returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 815} 816if(i2 == dir2->nr) { 817returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 818} 819 e1 = dir1->entries[i1]; 820 e2 = dir2->entries[i2]; 821 cmp =strcmp(e1->name, e2->name); 822if(cmp ==0) { 823if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 824/* Both are directories; descend them in parallel. */ 825struct ref_dir *subdir1 =get_ref_dir(e1); 826struct ref_dir *subdir2 =get_ref_dir(e2); 827sort_ref_dir(subdir1); 828sort_ref_dir(subdir2); 829 retval =do_for_each_entry_in_dirs( 830 subdir1, subdir2, fn, cb_data); 831 i1++; 832 i2++; 833}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 834/* Both are references; ignore the one from dir1. */ 835 retval =fn(e2, cb_data); 836 i1++; 837 i2++; 838}else{ 839die("conflict between reference and directory:%s", 840 e1->name); 841} 842}else{ 843struct ref_entry *e; 844if(cmp <0) { 845 e = e1; 846 i1++; 847}else{ 848 e = e2; 849 i2++; 850} 851if(e->flag & REF_DIR) { 852struct ref_dir *subdir =get_ref_dir(e); 853sort_ref_dir(subdir); 854 retval =do_for_each_entry_in_dir( 855 subdir,0, fn, cb_data); 856}else{ 857 retval =fn(e, cb_data); 858} 859} 860if(retval) 861return retval; 862} 863} 864 865/* 866 * Load all of the refs from the dir into our in-memory cache. The hard work 867 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 868 * through all of the sub-directories. We do not even need to care about 869 * sorting, as traversal order does not matter to us. 870 */ 871static voidprime_ref_dir(struct ref_dir *dir) 872{ 873int i; 874for(i =0; i < dir->nr; i++) { 875struct ref_entry *entry = dir->entries[i]; 876if(entry->flag & REF_DIR) 877prime_ref_dir(get_ref_dir(entry)); 878} 879} 880 881struct nonmatching_ref_data { 882const struct string_list *skip; 883const char*conflicting_refname; 884}; 885 886static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 887{ 888struct nonmatching_ref_data *data = vdata; 889 890if(data->skip &&string_list_has_string(data->skip, entry->name)) 891return0; 892 893 data->conflicting_refname = entry->name; 894return1; 895} 896 897/* 898 * Return 0 if a reference named refname could be created without 899 * conflicting with the name of an existing reference in dir. 900 * Otherwise, return a negative value and write an explanation to err. 901 * If extras is non-NULL, it is a list of additional refnames with 902 * which refname is not allowed to conflict. If skip is non-NULL, 903 * ignore potential conflicts with refs in skip (e.g., because they 904 * are scheduled for deletion in the same operation). Behavior is 905 * undefined if the same name is listed in both extras and skip. 906 * 907 * Two reference names conflict if one of them exactly matches the 908 * leading components of the other; e.g., "refs/foo/bar" conflicts 909 * with both "refs/foo" and with "refs/foo/bar/baz" but not with 910 * "refs/foo/bar" or "refs/foo/barbados". 911 * 912 * extras and skip must be sorted. 913 */ 914static intverify_refname_available(const char*refname, 915const struct string_list *extras, 916const struct string_list *skip, 917struct ref_dir *dir, 918struct strbuf *err) 919{ 920const char*slash; 921int pos; 922struct strbuf dirname = STRBUF_INIT; 923int ret = -1; 924 925/* 926 * For the sake of comments in this function, suppose that 927 * refname is "refs/foo/bar". 928 */ 929 930assert(err); 931 932strbuf_grow(&dirname,strlen(refname) +1); 933for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 934/* Expand dirname to the new prefix, not including the trailing slash: */ 935strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 936 937/* 938 * We are still at a leading dir of the refname (e.g., 939 * "refs/foo"; if there is a reference with that name, 940 * it is a conflict, *unless* it is in skip. 941 */ 942if(dir) { 943 pos =search_ref_dir(dir, dirname.buf, dirname.len); 944if(pos >=0&& 945(!skip || !string_list_has_string(skip, dirname.buf))) { 946/* 947 * We found a reference whose name is 948 * a proper prefix of refname; e.g., 949 * "refs/foo", and is not in skip. 950 */ 951strbuf_addf(err,"'%s' exists; cannot create '%s'", 952 dirname.buf, refname); 953goto cleanup; 954} 955} 956 957if(extras &&string_list_has_string(extras, dirname.buf) && 958(!skip || !string_list_has_string(skip, dirname.buf))) { 959strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 960 refname, dirname.buf); 961goto cleanup; 962} 963 964/* 965 * Otherwise, we can try to continue our search with 966 * the next component. So try to look up the 967 * directory, e.g., "refs/foo/". If we come up empty, 968 * we know there is nothing under this whole prefix, 969 * but even in that case we still have to continue the 970 * search for conflicts with extras. 971 */ 972strbuf_addch(&dirname,'/'); 973if(dir) { 974 pos =search_ref_dir(dir, dirname.buf, dirname.len); 975if(pos <0) { 976/* 977 * There was no directory "refs/foo/", 978 * so there is nothing under this 979 * whole prefix. So there is no need 980 * to continue looking for conflicting 981 * references. But we need to continue 982 * looking for conflicting extras. 983 */ 984 dir = NULL; 985}else{ 986 dir =get_ref_dir(dir->entries[pos]); 987} 988} 989} 990 991/* 992 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 993 * There is no point in searching for a reference with that 994 * name, because a refname isn't considered to conflict with 995 * itself. But we still need to check for references whose 996 * names are in the "refs/foo/bar/" namespace, because they 997 * *do* conflict. 998 */ 999strbuf_addstr(&dirname, refname + dirname.len);1000strbuf_addch(&dirname,'/');10011002if(dir) {1003 pos =search_ref_dir(dir, dirname.buf, dirname.len);10041005if(pos >=0) {1006/*1007 * We found a directory named "$refname/"1008 * (e.g., "refs/foo/bar/"). It is a problem1009 * iff it contains any ref that is not in1010 * "skip".1011 */1012struct nonmatching_ref_data data;10131014 data.skip = skip;1015 data.conflicting_refname = NULL;1016 dir =get_ref_dir(dir->entries[pos]);1017sort_ref_dir(dir);1018if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) {1019strbuf_addf(err,"'%s' exists; cannot create '%s'",1020 data.conflicting_refname, refname);1021goto cleanup;1022}1023}1024}10251026if(extras) {1027/*1028 * Check for entries in extras that start with1029 * "$refname/". We do that by looking for the place1030 * where "$refname/" would be inserted in extras. If1031 * there is an entry at that position that starts with1032 * "$refname/" and is not in skip, then we have a1033 * conflict.1034 */1035for(pos =string_list_find_insert_index(extras, dirname.buf,0);1036 pos < extras->nr; pos++) {1037const char*extra_refname = extras->items[pos].string;10381039if(!starts_with(extra_refname, dirname.buf))1040break;10411042if(!skip || !string_list_has_string(skip, extra_refname)) {1043strbuf_addf(err,"cannot process '%s' and '%s' at the same time",1044 refname, extra_refname);1045goto cleanup;1046}1047}1048}10491050/* No conflicts were found */1051 ret =0;10521053cleanup:1054strbuf_release(&dirname);1055return ret;1056}10571058struct packed_ref_cache {1059struct ref_entry *root;10601061/*1062 * Count of references to the data structure in this instance,1063 * including the pointer from ref_cache::packed if any. The1064 * data will not be freed as long as the reference count is1065 * nonzero.1066 */1067unsigned int referrers;10681069/*1070 * Iff the packed-refs file associated with this instance is1071 * currently locked for writing, this points at the associated1072 * lock (which is owned by somebody else). The referrer count1073 * is also incremented when the file is locked and decremented1074 * when it is unlocked.1075 */1076struct lock_file *lock;10771078/* The metadata from when this packed-refs cache was read */1079struct stat_validity validity;1080};10811082/*1083 * Future: need to be in "struct repository"1084 * when doing a full libification.1085 */1086static struct ref_cache {1087struct ref_cache *next;1088struct ref_entry *loose;1089struct packed_ref_cache *packed;1090/*1091 * The submodule name, or "" for the main repo. We allocate1092 * length 1 rather than FLEX_ARRAY so that the main ref_cache1093 * is initialized correctly.1094 */1095char name[1];1096} ref_cache, *submodule_ref_caches;10971098/* Lock used for the main packed-refs file: */1099static struct lock_file packlock;11001101/*1102 * Increment the reference count of *packed_refs.1103 */1104static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1105{1106 packed_refs->referrers++;1107}11081109/*1110 * Decrease the reference count of *packed_refs. If it goes to zero,1111 * free *packed_refs and return true; otherwise return false.1112 */1113static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1114{1115if(!--packed_refs->referrers) {1116free_ref_entry(packed_refs->root);1117stat_validity_clear(&packed_refs->validity);1118free(packed_refs);1119return1;1120}else{1121return0;1122}1123}11241125static voidclear_packed_ref_cache(struct ref_cache *refs)1126{1127if(refs->packed) {1128struct packed_ref_cache *packed_refs = refs->packed;11291130if(packed_refs->lock)1131die("internal error: packed-ref cache cleared while locked");1132 refs->packed = NULL;1133release_packed_ref_cache(packed_refs);1134}1135}11361137static voidclear_loose_ref_cache(struct ref_cache *refs)1138{1139if(refs->loose) {1140free_ref_entry(refs->loose);1141 refs->loose = NULL;1142}1143}11441145static struct ref_cache *create_ref_cache(const char*submodule)1146{1147int len;1148struct ref_cache *refs;1149if(!submodule)1150 submodule ="";1151 len =strlen(submodule) +1;1152 refs =xcalloc(1,sizeof(struct ref_cache) + len);1153memcpy(refs->name, submodule, len);1154return refs;1155}11561157/*1158 * Return a pointer to a ref_cache for the specified submodule. For1159 * the main repository, use submodule==NULL. The returned structure1160 * will be allocated and initialized but not necessarily populated; it1161 * should not be freed.1162 */1163static struct ref_cache *get_ref_cache(const char*submodule)1164{1165struct ref_cache *refs;11661167if(!submodule || !*submodule)1168return&ref_cache;11691170for(refs = submodule_ref_caches; refs; refs = refs->next)1171if(!strcmp(submodule, refs->name))1172return refs;11731174 refs =create_ref_cache(submodule);1175 refs->next = submodule_ref_caches;1176 submodule_ref_caches = refs;1177return refs;1178}11791180/* The length of a peeled reference line in packed-refs, including EOL: */1181#define PEELED_LINE_LENGTH 4211821183/*1184 * The packed-refs header line that we write out. Perhaps other1185 * traits will be added later. The trailing space is required.1186 */1187static const char PACKED_REFS_HEADER[] =1188"# pack-refs with: peeled fully-peeled\n";11891190/*1191 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1192 * Return a pointer to the refname within the line (null-terminated),1193 * or NULL if there was a problem.1194 */1195static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1196{1197const char*ref;11981199/*1200 * 42: the answer to everything.1201 *1202 * In this case, it happens to be the answer to1203 * 40 (length of sha1 hex representation)1204 * +1 (space in between hex and name)1205 * +1 (newline at the end of the line)1206 */1207if(line->len <=42)1208return NULL;12091210if(get_sha1_hex(line->buf, sha1) <0)1211return NULL;1212if(!isspace(line->buf[40]))1213return NULL;12141215 ref = line->buf +41;1216if(isspace(*ref))1217return NULL;12181219if(line->buf[line->len -1] !='\n')1220return NULL;1221 line->buf[--line->len] =0;12221223return ref;1224}12251226/*1227 * Read f, which is a packed-refs file, into dir.1228 *1229 * A comment line of the form "# pack-refs with: " may contain zero or1230 * more traits. We interpret the traits as follows:1231 *1232 * No traits:1233 *1234 * Probably no references are peeled. But if the file contains a1235 * peeled value for a reference, we will use it.1236 *1237 * peeled:1238 *1239 * References under "refs/tags/", if they *can* be peeled, *are*1240 * peeled in this file. References outside of "refs/tags/" are1241 * probably not peeled even if they could have been, but if we find1242 * a peeled value for such a reference we will use it.1243 *1244 * fully-peeled:1245 *1246 * All references in the file that can be peeled are peeled.1247 * Inversely (and this is more important), any references in the1248 * file for which no peeled value is recorded is not peelable. This1249 * trait should typically be written alongside "peeled" for1250 * compatibility with older clients, but we do not require it1251 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1252 */1253static voidread_packed_refs(FILE*f,struct ref_dir *dir)1254{1255struct ref_entry *last = NULL;1256struct strbuf line = STRBUF_INIT;1257enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12581259while(strbuf_getwholeline(&line, f,'\n') != EOF) {1260unsigned char sha1[20];1261const char*refname;1262const char*traits;12631264if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1265if(strstr(traits," fully-peeled "))1266 peeled = PEELED_FULLY;1267else if(strstr(traits," peeled "))1268 peeled = PEELED_TAGS;1269/* perhaps other traits later as well */1270continue;1271}12721273 refname =parse_ref_line(&line, sha1);1274if(refname) {1275int flag = REF_ISPACKED;12761277if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1278if(!refname_is_safe(refname))1279die("packed refname is dangerous:%s", refname);1280hashclr(sha1);1281 flag |= REF_BAD_NAME | REF_ISBROKEN;1282}1283 last =create_ref_entry(refname, sha1, flag,0);1284if(peeled == PEELED_FULLY ||1285(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1286 last->flag |= REF_KNOWS_PEELED;1287add_ref(dir, last);1288continue;1289}1290if(last &&1291 line.buf[0] =='^'&&1292 line.len == PEELED_LINE_LENGTH &&1293 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1294!get_sha1_hex(line.buf +1, sha1)) {1295hashcpy(last->u.value.peeled.hash, sha1);1296/*1297 * Regardless of what the file header said,1298 * we definitely know the value of *this*1299 * reference:1300 */1301 last->flag |= REF_KNOWS_PEELED;1302}1303}13041305strbuf_release(&line);1306}13071308/*1309 * Get the packed_ref_cache for the specified ref_cache, creating it1310 * if necessary.1311 */1312static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1313{1314char*packed_refs_file;13151316if(*refs->name)1317 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1318else1319 packed_refs_file =git_pathdup("packed-refs");13201321if(refs->packed &&1322!stat_validity_check(&refs->packed->validity, packed_refs_file))1323clear_packed_ref_cache(refs);13241325if(!refs->packed) {1326FILE*f;13271328 refs->packed =xcalloc(1,sizeof(*refs->packed));1329acquire_packed_ref_cache(refs->packed);1330 refs->packed->root =create_dir_entry(refs,"",0,0);1331 f =fopen(packed_refs_file,"r");1332if(f) {1333stat_validity_update(&refs->packed->validity,fileno(f));1334read_packed_refs(f,get_ref_dir(refs->packed->root));1335fclose(f);1336}1337}1338free(packed_refs_file);1339return refs->packed;1340}13411342static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1343{1344returnget_ref_dir(packed_ref_cache->root);1345}13461347static struct ref_dir *get_packed_refs(struct ref_cache *refs)1348{1349returnget_packed_ref_dir(get_packed_ref_cache(refs));1350}13511352/*1353 * Add a reference to the in-memory packed reference cache. This may1354 * only be called while the packed-refs file is locked (see1355 * lock_packed_refs()). To actually write the packed-refs file, call1356 * commit_packed_refs().1357 */1358static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1359{1360struct packed_ref_cache *packed_ref_cache =1361get_packed_ref_cache(&ref_cache);13621363if(!packed_ref_cache->lock)1364die("internal error: packed refs not locked");1365add_ref(get_packed_ref_dir(packed_ref_cache),1366create_ref_entry(refname, sha1, REF_ISPACKED,1));1367}13681369/*1370 * Read the loose references from the namespace dirname into dir1371 * (without recursing). dirname must end with '/'. dir must be the1372 * directory entry corresponding to dirname.1373 */1374static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1375{1376struct ref_cache *refs = dir->ref_cache;1377DIR*d;1378struct dirent *de;1379int dirnamelen =strlen(dirname);1380struct strbuf refname;1381struct strbuf path = STRBUF_INIT;1382size_t path_baselen;13831384if(*refs->name)1385strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1386else1387strbuf_git_path(&path,"%s", dirname);1388 path_baselen = path.len;13891390 d =opendir(path.buf);1391if(!d) {1392strbuf_release(&path);1393return;1394}13951396strbuf_init(&refname, dirnamelen +257);1397strbuf_add(&refname, dirname, dirnamelen);13981399while((de =readdir(d)) != NULL) {1400unsigned char sha1[20];1401struct stat st;1402int flag;14031404if(de->d_name[0] =='.')1405continue;1406if(ends_with(de->d_name,".lock"))1407continue;1408strbuf_addstr(&refname, de->d_name);1409strbuf_addstr(&path, de->d_name);1410if(stat(path.buf, &st) <0) {1411;/* silently ignore */1412}else if(S_ISDIR(st.st_mode)) {1413strbuf_addch(&refname,'/');1414add_entry_to_dir(dir,1415create_dir_entry(refs, refname.buf,1416 refname.len,1));1417}else{1418int read_ok;14191420if(*refs->name) {1421hashclr(sha1);1422 flag =0;1423 read_ok = !resolve_gitlink_ref(refs->name,1424 refname.buf, sha1);1425}else{1426 read_ok = !read_ref_full(refname.buf,1427 RESOLVE_REF_READING,1428 sha1, &flag);1429}14301431if(!read_ok) {1432hashclr(sha1);1433 flag |= REF_ISBROKEN;1434}else if(is_null_sha1(sha1)) {1435/*1436 * It is so astronomically unlikely1437 * that NULL_SHA1 is the SHA-1 of an1438 * actual object that we consider its1439 * appearance in a loose reference1440 * file to be repo corruption1441 * (probably due to a software bug).1442 */1443 flag |= REF_ISBROKEN;1444}14451446if(check_refname_format(refname.buf,1447 REFNAME_ALLOW_ONELEVEL)) {1448if(!refname_is_safe(refname.buf))1449die("loose refname is dangerous:%s", refname.buf);1450hashclr(sha1);1451 flag |= REF_BAD_NAME | REF_ISBROKEN;1452}1453add_entry_to_dir(dir,1454create_ref_entry(refname.buf, sha1, flag,0));1455}1456strbuf_setlen(&refname, dirnamelen);1457strbuf_setlen(&path, path_baselen);1458}1459strbuf_release(&refname);1460strbuf_release(&path);1461closedir(d);1462}14631464static struct ref_dir *get_loose_refs(struct ref_cache *refs)1465{1466if(!refs->loose) {1467/*1468 * Mark the top-level directory complete because we1469 * are about to read the only subdirectory that can1470 * hold references:1471 */1472 refs->loose =create_dir_entry(refs,"",0,0);1473/*1474 * Create an incomplete entry for "refs/":1475 */1476add_entry_to_dir(get_ref_dir(refs->loose),1477create_dir_entry(refs,"refs/",5,1));1478}1479returnget_ref_dir(refs->loose);1480}14811482/* We allow "recursive" symbolic refs. Only within reason, though */1483#define MAXDEPTH 51484#define MAXREFLEN (1024)14851486/*1487 * Called by resolve_gitlink_ref_recursive() after it failed to read1488 * from the loose refs in ref_cache refs. Find <refname> in the1489 * packed-refs file for the submodule.1490 */1491static intresolve_gitlink_packed_ref(struct ref_cache *refs,1492const char*refname,unsigned char*sha1)1493{1494struct ref_entry *ref;1495struct ref_dir *dir =get_packed_refs(refs);14961497 ref =find_ref(dir, refname);1498if(ref == NULL)1499return-1;15001501hashcpy(sha1, ref->u.value.oid.hash);1502return0;1503}15041505static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1506const char*refname,unsigned char*sha1,1507int recursion)1508{1509int fd, len;1510char buffer[128], *p;1511char*path;15121513if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1514return-1;1515 path = *refs->name1516?git_pathdup_submodule(refs->name,"%s", refname)1517:git_pathdup("%s", refname);1518 fd =open(path, O_RDONLY);1519free(path);1520if(fd <0)1521returnresolve_gitlink_packed_ref(refs, refname, sha1);15221523 len =read(fd, buffer,sizeof(buffer)-1);1524close(fd);1525if(len <0)1526return-1;1527while(len &&isspace(buffer[len-1]))1528 len--;1529 buffer[len] =0;15301531/* Was it a detached head or an old-fashioned symlink? */1532if(!get_sha1_hex(buffer, sha1))1533return0;15341535/* Symref? */1536if(strncmp(buffer,"ref:",4))1537return-1;1538 p = buffer +4;1539while(isspace(*p))1540 p++;15411542returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1543}15441545intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1546{1547int len =strlen(path), retval;1548char*submodule;1549struct ref_cache *refs;15501551while(len && path[len-1] =='/')1552 len--;1553if(!len)1554return-1;1555 submodule =xstrndup(path, len);1556 refs =get_ref_cache(submodule);1557free(submodule);15581559 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1560return retval;1561}15621563/*1564 * Return the ref_entry for the given refname from the packed1565 * references. If it does not exist, return NULL.1566 */1567static struct ref_entry *get_packed_ref(const char*refname)1568{1569returnfind_ref(get_packed_refs(&ref_cache), refname);1570}15711572/*1573 * A loose ref file doesn't exist; check for a packed ref. The1574 * options are forwarded from resolve_safe_unsafe().1575 */1576static intresolve_missing_loose_ref(const char*refname,1577int resolve_flags,1578unsigned char*sha1,1579int*flags)1580{1581struct ref_entry *entry;15821583/*1584 * The loose reference file does not exist; check for a packed1585 * reference.1586 */1587 entry =get_packed_ref(refname);1588if(entry) {1589hashcpy(sha1, entry->u.value.oid.hash);1590if(flags)1591*flags |= REF_ISPACKED;1592return0;1593}1594/* The reference is not a packed reference, either. */1595if(resolve_flags & RESOLVE_REF_READING) {1596 errno = ENOENT;1597return-1;1598}else{1599hashclr(sha1);1600return0;1601}1602}16031604/* This function needs to return a meaningful errno on failure */1605static const char*resolve_ref_1(const char*refname,1606int resolve_flags,1607unsigned char*sha1,1608int*flags,1609struct strbuf *sb_refname,1610struct strbuf *sb_path,1611struct strbuf *sb_contents)1612{1613int depth = MAXDEPTH;1614int bad_name =0;16151616if(flags)1617*flags =0;16181619if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1620if(flags)1621*flags |= REF_BAD_NAME;16221623if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1624!refname_is_safe(refname)) {1625 errno = EINVAL;1626return NULL;1627}1628/*1629 * dwim_ref() uses REF_ISBROKEN to distinguish between1630 * missing refs and refs that were present but invalid,1631 * to complain about the latter to stderr.1632 *1633 * We don't know whether the ref exists, so don't set1634 * REF_ISBROKEN yet.1635 */1636 bad_name =1;1637}1638for(;;) {1639const char*path;1640struct stat st;1641char*buf;1642int fd;16431644if(--depth <0) {1645 errno = ELOOP;1646return NULL;1647}16481649strbuf_reset(sb_path);1650strbuf_git_path(sb_path,"%s", refname);1651 path = sb_path->buf;16521653/*1654 * We might have to loop back here to avoid a race1655 * condition: first we lstat() the file, then we try1656 * to read it as a link or as a file. But if somebody1657 * changes the type of the file (file <-> directory1658 * <-> symlink) between the lstat() and reading, then1659 * we don't want to report that as an error but rather1660 * try again starting with the lstat().1661 */1662 stat_ref:1663if(lstat(path, &st) <0) {1664if(errno != ENOENT)1665return NULL;1666if(resolve_missing_loose_ref(refname, resolve_flags,1667 sha1, flags))1668return NULL;1669if(bad_name) {1670hashclr(sha1);1671if(flags)1672*flags |= REF_ISBROKEN;1673}1674return refname;1675}16761677/* Follow "normalized" - ie "refs/.." symlinks by hand */1678if(S_ISLNK(st.st_mode)) {1679strbuf_reset(sb_contents);1680if(strbuf_readlink(sb_contents, path,0) <0) {1681if(errno == ENOENT || errno == EINVAL)1682/* inconsistent with lstat; retry */1683goto stat_ref;1684else1685return NULL;1686}1687if(starts_with(sb_contents->buf,"refs/") &&1688!check_refname_format(sb_contents->buf,0)) {1689strbuf_swap(sb_refname, sb_contents);1690 refname = sb_refname->buf;1691if(flags)1692*flags |= REF_ISSYMREF;1693if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1694hashclr(sha1);1695return refname;1696}1697continue;1698}1699}17001701/* Is it a directory? */1702if(S_ISDIR(st.st_mode)) {1703 errno = EISDIR;1704return NULL;1705}17061707/*1708 * Anything else, just open it and try to use it as1709 * a ref1710 */1711 fd =open(path, O_RDONLY);1712if(fd <0) {1713if(errno == ENOENT)1714/* inconsistent with lstat; retry */1715goto stat_ref;1716else1717return NULL;1718}1719strbuf_reset(sb_contents);1720if(strbuf_read(sb_contents, fd,256) <0) {1721int save_errno = errno;1722close(fd);1723 errno = save_errno;1724return NULL;1725}1726close(fd);1727strbuf_rtrim(sb_contents);17281729/*1730 * Is it a symbolic ref?1731 */1732if(!starts_with(sb_contents->buf,"ref:")) {1733/*1734 * Please note that FETCH_HEAD has a second1735 * line containing other data.1736 */1737if(get_sha1_hex(sb_contents->buf, sha1) ||1738(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1739if(flags)1740*flags |= REF_ISBROKEN;1741 errno = EINVAL;1742return NULL;1743}1744if(bad_name) {1745hashclr(sha1);1746if(flags)1747*flags |= REF_ISBROKEN;1748}1749return refname;1750}1751if(flags)1752*flags |= REF_ISSYMREF;1753 buf = sb_contents->buf +4;1754while(isspace(*buf))1755 buf++;1756strbuf_reset(sb_refname);1757strbuf_addstr(sb_refname, buf);1758 refname = sb_refname->buf;1759if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1760hashclr(sha1);1761return refname;1762}1763if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1764if(flags)1765*flags |= REF_ISBROKEN;17661767if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1768!refname_is_safe(buf)) {1769 errno = EINVAL;1770return NULL;1771}1772 bad_name =1;1773}1774}1775}17761777const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1778unsigned char*sha1,int*flags)1779{1780static struct strbuf sb_refname = STRBUF_INIT;1781struct strbuf sb_contents = STRBUF_INIT;1782struct strbuf sb_path = STRBUF_INIT;1783const char*ret;17841785 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1786&sb_refname, &sb_path, &sb_contents);1787strbuf_release(&sb_path);1788strbuf_release(&sb_contents);1789return ret;1790}17911792char*resolve_refdup(const char*refname,int resolve_flags,1793unsigned char*sha1,int*flags)1794{1795returnxstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1796 sha1, flags));1797}17981799/* The argument to filter_refs */1800struct ref_filter {1801const char*pattern;1802 each_ref_fn *fn;1803void*cb_data;1804};18051806intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1807{1808if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1809return0;1810return-1;1811}18121813intread_ref(const char*refname,unsigned char*sha1)1814{1815returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1816}18171818intref_exists(const char*refname)1819{1820unsigned char sha1[20];1821return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1822}18231824static intfilter_refs(const char*refname,const struct object_id *oid,1825int flags,void*data)1826{1827struct ref_filter *filter = (struct ref_filter *)data;18281829if(wildmatch(filter->pattern, refname,0, NULL))1830return0;1831return filter->fn(refname, oid, flags, filter->cb_data);1832}18331834enum peel_status {1835/* object was peeled successfully: */1836 PEEL_PEELED =0,18371838/*1839 * object cannot be peeled because the named object (or an1840 * object referred to by a tag in the peel chain), does not1841 * exist.1842 */1843 PEEL_INVALID = -1,18441845/* object cannot be peeled because it is not a tag: */1846 PEEL_NON_TAG = -2,18471848/* ref_entry contains no peeled value because it is a symref: */1849 PEEL_IS_SYMREF = -3,18501851/*1852 * ref_entry cannot be peeled because it is broken (i.e., the1853 * symbolic reference cannot even be resolved to an object1854 * name):1855 */1856 PEEL_BROKEN = -41857};18581859/*1860 * Peel the named object; i.e., if the object is a tag, resolve the1861 * tag recursively until a non-tag is found. If successful, store the1862 * result to sha1 and return PEEL_PEELED. If the object is not a tag1863 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1864 * and leave sha1 unchanged.1865 */1866static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1867{1868struct object *o =lookup_unknown_object(name);18691870if(o->type == OBJ_NONE) {1871int type =sha1_object_info(name, NULL);1872if(type <0|| !object_as_type(o, type,0))1873return PEEL_INVALID;1874}18751876if(o->type != OBJ_TAG)1877return PEEL_NON_TAG;18781879 o =deref_tag_noverify(o);1880if(!o)1881return PEEL_INVALID;18821883hashcpy(sha1, o->sha1);1884return PEEL_PEELED;1885}18861887/*1888 * Peel the entry (if possible) and return its new peel_status. If1889 * repeel is true, re-peel the entry even if there is an old peeled1890 * value that is already stored in it.1891 *1892 * It is OK to call this function with a packed reference entry that1893 * might be stale and might even refer to an object that has since1894 * been garbage-collected. In such a case, if the entry has1895 * REF_KNOWS_PEELED then leave the status unchanged and return1896 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1897 */1898static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1899{1900enum peel_status status;19011902if(entry->flag & REF_KNOWS_PEELED) {1903if(repeel) {1904 entry->flag &= ~REF_KNOWS_PEELED;1905oidclr(&entry->u.value.peeled);1906}else{1907returnis_null_oid(&entry->u.value.peeled) ?1908 PEEL_NON_TAG : PEEL_PEELED;1909}1910}1911if(entry->flag & REF_ISBROKEN)1912return PEEL_BROKEN;1913if(entry->flag & REF_ISSYMREF)1914return PEEL_IS_SYMREF;19151916 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1917if(status == PEEL_PEELED || status == PEEL_NON_TAG)1918 entry->flag |= REF_KNOWS_PEELED;1919return status;1920}19211922intpeel_ref(const char*refname,unsigned char*sha1)1923{1924int flag;1925unsigned char base[20];19261927if(current_ref && (current_ref->name == refname1928|| !strcmp(current_ref->name, refname))) {1929if(peel_entry(current_ref,0))1930return-1;1931hashcpy(sha1, current_ref->u.value.peeled.hash);1932return0;1933}19341935if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1936return-1;19371938/*1939 * If the reference is packed, read its ref_entry from the1940 * cache in the hope that we already know its peeled value.1941 * We only try this optimization on packed references because1942 * (a) forcing the filling of the loose reference cache could1943 * be expensive and (b) loose references anyway usually do not1944 * have REF_KNOWS_PEELED.1945 */1946if(flag & REF_ISPACKED) {1947struct ref_entry *r =get_packed_ref(refname);1948if(r) {1949if(peel_entry(r,0))1950return-1;1951hashcpy(sha1, r->u.value.peeled.hash);1952return0;1953}1954}19551956returnpeel_object(base, sha1);1957}19581959struct warn_if_dangling_data {1960FILE*fp;1961const char*refname;1962const struct string_list *refnames;1963const char*msg_fmt;1964};19651966static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1967int flags,void*cb_data)1968{1969struct warn_if_dangling_data *d = cb_data;1970const char*resolves_to;1971struct object_id junk;19721973if(!(flags & REF_ISSYMREF))1974return0;19751976 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1977if(!resolves_to1978|| (d->refname1979?strcmp(resolves_to, d->refname)1980: !string_list_has_string(d->refnames, resolves_to))) {1981return0;1982}19831984fprintf(d->fp, d->msg_fmt, refname);1985fputc('\n', d->fp);1986return0;1987}19881989voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1990{1991struct warn_if_dangling_data data;19921993 data.fp = fp;1994 data.refname = refname;1995 data.refnames = NULL;1996 data.msg_fmt = msg_fmt;1997for_each_rawref(warn_if_dangling_symref, &data);1998}19992000voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)2001{2002struct warn_if_dangling_data data;20032004 data.fp = fp;2005 data.refname = NULL;2006 data.refnames = refnames;2007 data.msg_fmt = msg_fmt;2008for_each_rawref(warn_if_dangling_symref, &data);2009}20102011/*2012 * Call fn for each reference in the specified ref_cache, omitting2013 * references not in the containing_dir of base. fn is called for all2014 * references, including broken ones. If fn ever returns a non-zero2015 * value, stop the iteration and return that value; otherwise, return2016 * 0.2017 */2018static intdo_for_each_entry(struct ref_cache *refs,const char*base,2019 each_ref_entry_fn fn,void*cb_data)2020{2021struct packed_ref_cache *packed_ref_cache;2022struct ref_dir *loose_dir;2023struct ref_dir *packed_dir;2024int retval =0;20252026/*2027 * We must make sure that all loose refs are read before accessing the2028 * packed-refs file; this avoids a race condition in which loose refs2029 * are migrated to the packed-refs file by a simultaneous process, but2030 * our in-memory view is from before the migration. get_packed_ref_cache()2031 * takes care of making sure our view is up to date with what is on2032 * disk.2033 */2034 loose_dir =get_loose_refs(refs);2035if(base && *base) {2036 loose_dir =find_containing_dir(loose_dir, base,0);2037}2038if(loose_dir)2039prime_ref_dir(loose_dir);20402041 packed_ref_cache =get_packed_ref_cache(refs);2042acquire_packed_ref_cache(packed_ref_cache);2043 packed_dir =get_packed_ref_dir(packed_ref_cache);2044if(base && *base) {2045 packed_dir =find_containing_dir(packed_dir, base,0);2046}20472048if(packed_dir && loose_dir) {2049sort_ref_dir(packed_dir);2050sort_ref_dir(loose_dir);2051 retval =do_for_each_entry_in_dirs(2052 packed_dir, loose_dir, fn, cb_data);2053}else if(packed_dir) {2054sort_ref_dir(packed_dir);2055 retval =do_for_each_entry_in_dir(2056 packed_dir,0, fn, cb_data);2057}else if(loose_dir) {2058sort_ref_dir(loose_dir);2059 retval =do_for_each_entry_in_dir(2060 loose_dir,0, fn, cb_data);2061}20622063release_packed_ref_cache(packed_ref_cache);2064return retval;2065}20662067/*2068 * Call fn for each reference in the specified ref_cache for which the2069 * refname begins with base. If trim is non-zero, then trim that many2070 * characters off the beginning of each refname before passing the2071 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2072 * broken references in the iteration. If fn ever returns a non-zero2073 * value, stop the iteration and return that value; otherwise, return2074 * 0.2075 */2076static intdo_for_each_ref(struct ref_cache *refs,const char*base,2077 each_ref_fn fn,int trim,int flags,void*cb_data)2078{2079struct ref_entry_cb data;2080 data.base = base;2081 data.trim = trim;2082 data.flags = flags;2083 data.fn = fn;2084 data.cb_data = cb_data;20852086if(ref_paranoia <0)2087 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2088if(ref_paranoia)2089 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20902091returndo_for_each_entry(refs, base, do_one_ref, &data);2092}20932094static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2095{2096struct object_id oid;2097int flag;20982099if(submodule) {2100if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2101returnfn("HEAD", &oid,0, cb_data);21022103return0;2104}21052106if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2107returnfn("HEAD", &oid, flag, cb_data);21082109return0;2110}21112112inthead_ref(each_ref_fn fn,void*cb_data)2113{2114returndo_head_ref(NULL, fn, cb_data);2115}21162117inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2118{2119returndo_head_ref(submodule, fn, cb_data);2120}21212122intfor_each_ref(each_ref_fn fn,void*cb_data)2123{2124returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2125}21262127intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2128{2129returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2130}21312132intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2133{2134returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2135}21362137intfor_each_fullref_in(const char*prefix, each_ref_fn fn,void*cb_data,unsigned int broken)2138{2139unsigned int flag =0;21402141if(broken)2142 flag = DO_FOR_EACH_INCLUDE_BROKEN;2143returndo_for_each_ref(&ref_cache, prefix, fn,0, flag, cb_data);2144}21452146intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2147 each_ref_fn fn,void*cb_data)2148{2149returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2150}21512152intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2153{2154returnfor_each_ref_in("refs/tags/", fn, cb_data);2155}21562157intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2158{2159returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2160}21612162intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2163{2164returnfor_each_ref_in("refs/heads/", fn, cb_data);2165}21662167intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2168{2169returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2170}21712172intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2173{2174returnfor_each_ref_in("refs/remotes/", fn, cb_data);2175}21762177intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2178{2179returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2180}21812182intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2183{2184returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,2185strlen(git_replace_ref_base),0, cb_data);2186}21872188inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2189{2190struct strbuf buf = STRBUF_INIT;2191int ret =0;2192struct object_id oid;2193int flag;21942195strbuf_addf(&buf,"%sHEAD",get_git_namespace());2196if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2197 ret =fn(buf.buf, &oid, flag, cb_data);2198strbuf_release(&buf);21992200return ret;2201}22022203intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2204{2205struct strbuf buf = STRBUF_INIT;2206int ret;2207strbuf_addf(&buf,"%srefs/",get_git_namespace());2208 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2209strbuf_release(&buf);2210return ret;2211}22122213intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2214const char*prefix,void*cb_data)2215{2216struct strbuf real_pattern = STRBUF_INIT;2217struct ref_filter filter;2218int ret;22192220if(!prefix && !starts_with(pattern,"refs/"))2221strbuf_addstr(&real_pattern,"refs/");2222else if(prefix)2223strbuf_addstr(&real_pattern, prefix);2224strbuf_addstr(&real_pattern, pattern);22252226if(!has_glob_specials(pattern)) {2227/* Append implied '/' '*' if not present. */2228strbuf_complete(&real_pattern,'/');2229/* No need to check for '*', there is none. */2230strbuf_addch(&real_pattern,'*');2231}22322233 filter.pattern = real_pattern.buf;2234 filter.fn = fn;2235 filter.cb_data = cb_data;2236 ret =for_each_ref(filter_refs, &filter);22372238strbuf_release(&real_pattern);2239return ret;2240}22412242intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2243{2244returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2245}22462247intfor_each_rawref(each_ref_fn fn,void*cb_data)2248{2249returndo_for_each_ref(&ref_cache,"", fn,0,2250 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2251}22522253const char*prettify_refname(const char*name)2254{2255return name + (2256starts_with(name,"refs/heads/") ?11:2257starts_with(name,"refs/tags/") ?10:2258starts_with(name,"refs/remotes/") ?13:22590);2260}22612262static const char*ref_rev_parse_rules[] = {2263"%.*s",2264"refs/%.*s",2265"refs/tags/%.*s",2266"refs/heads/%.*s",2267"refs/remotes/%.*s",2268"refs/remotes/%.*s/HEAD",2269 NULL2270};22712272intrefname_match(const char*abbrev_name,const char*full_name)2273{2274const char**p;2275const int abbrev_name_len =strlen(abbrev_name);22762277for(p = ref_rev_parse_rules; *p; p++) {2278if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2279return1;2280}2281}22822283return0;2284}22852286static voidunlock_ref(struct ref_lock *lock)2287{2288/* Do not free lock->lk -- atexit() still looks at them */2289if(lock->lk)2290rollback_lock_file(lock->lk);2291free(lock->ref_name);2292free(lock->orig_ref_name);2293free(lock);2294}22952296/*2297 * Verify that the reference locked by lock has the value old_sha1.2298 * Fail if the reference doesn't exist and mustexist is set. Return 02299 * on success. On error, write an error message to err, set errno, and2300 * return a negative value.2301 */2302static intverify_lock(struct ref_lock *lock,2303const unsigned char*old_sha1,int mustexist,2304struct strbuf *err)2305{2306assert(err);23072308if(read_ref_full(lock->ref_name,2309 mustexist ? RESOLVE_REF_READING :0,2310 lock->old_oid.hash, NULL)) {2311int save_errno = errno;2312strbuf_addf(err,"can't verify ref%s", lock->ref_name);2313 errno = save_errno;2314return-1;2315}2316if(hashcmp(lock->old_oid.hash, old_sha1)) {2317strbuf_addf(err,"ref%sis at%sbut expected%s",2318 lock->ref_name,2319sha1_to_hex(lock->old_oid.hash),2320sha1_to_hex(old_sha1));2321 errno = EBUSY;2322return-1;2323}2324return0;2325}23262327static intremove_empty_directories(struct strbuf *path)2328{2329/*2330 * we want to create a file but there is a directory there;2331 * if that is an empty directory (or a directory that contains2332 * only empty directories), remove them.2333 */2334returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);2335}23362337/*2338 * *string and *len will only be substituted, and *string returned (for2339 * later free()ing) if the string passed in is a magic short-hand form2340 * to name a branch.2341 */2342static char*substitute_branch_name(const char**string,int*len)2343{2344struct strbuf buf = STRBUF_INIT;2345int ret =interpret_branch_name(*string, *len, &buf);23462347if(ret == *len) {2348size_t size;2349*string =strbuf_detach(&buf, &size);2350*len = size;2351return(char*)*string;2352}23532354return NULL;2355}23562357intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2358{2359char*last_branch =substitute_branch_name(&str, &len);2360const char**p, *r;2361int refs_found =0;23622363*ref = NULL;2364for(p = ref_rev_parse_rules; *p; p++) {2365char fullref[PATH_MAX];2366unsigned char sha1_from_ref[20];2367unsigned char*this_result;2368int flag;23692370 this_result = refs_found ? sha1_from_ref : sha1;2371mksnpath(fullref,sizeof(fullref), *p, len, str);2372 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2373 this_result, &flag);2374if(r) {2375if(!refs_found++)2376*ref =xstrdup(r);2377if(!warn_ambiguous_refs)2378break;2379}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2380warning("ignoring dangling symref%s.", fullref);2381}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2382warning("ignoring broken ref%s.", fullref);2383}2384}2385free(last_branch);2386return refs_found;2387}23882389intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2390{2391char*last_branch =substitute_branch_name(&str, &len);2392const char**p;2393int logs_found =0;23942395*log = NULL;2396for(p = ref_rev_parse_rules; *p; p++) {2397unsigned char hash[20];2398char path[PATH_MAX];2399const char*ref, *it;24002401mksnpath(path,sizeof(path), *p, len, str);2402 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2403 hash, NULL);2404if(!ref)2405continue;2406if(reflog_exists(path))2407 it = path;2408else if(strcmp(ref, path) &&reflog_exists(ref))2409 it = ref;2410else2411continue;2412if(!logs_found++) {2413*log =xstrdup(it);2414hashcpy(sha1, hash);2415}2416if(!warn_ambiguous_refs)2417break;2418}2419free(last_branch);2420return logs_found;2421}24222423/*2424 * Locks a ref returning the lock on success and NULL on failure.2425 * On failure errno is set to something meaningful.2426 */2427static struct ref_lock *lock_ref_sha1_basic(const char*refname,2428const unsigned char*old_sha1,2429const struct string_list *extras,2430const struct string_list *skip,2431unsigned int flags,int*type_p,2432struct strbuf *err)2433{2434struct strbuf ref_file = STRBUF_INIT;2435struct strbuf orig_ref_file = STRBUF_INIT;2436const char*orig_refname = refname;2437struct ref_lock *lock;2438int last_errno =0;2439int type, lflags;2440int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2441int resolve_flags =0;2442int attempts_remaining =3;24432444assert(err);24452446 lock =xcalloc(1,sizeof(struct ref_lock));24472448if(mustexist)2449 resolve_flags |= RESOLVE_REF_READING;2450if(flags & REF_DELETING) {2451 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2452if(flags & REF_NODEREF)2453 resolve_flags |= RESOLVE_REF_NO_RECURSE;2454}24552456 refname =resolve_ref_unsafe(refname, resolve_flags,2457 lock->old_oid.hash, &type);2458if(!refname && errno == EISDIR) {2459/*2460 * we are trying to lock foo but we used to2461 * have foo/bar which now does not exist;2462 * it is normal for the empty directory 'foo'2463 * to remain.2464 */2465strbuf_git_path(&orig_ref_file,"%s", orig_refname);2466if(remove_empty_directories(&orig_ref_file)) {2467 last_errno = errno;2468if(!verify_refname_available(orig_refname, extras, skip,2469get_loose_refs(&ref_cache), err))2470strbuf_addf(err,"there are still refs under '%s'",2471 orig_refname);2472goto error_return;2473}2474 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2475 lock->old_oid.hash, &type);2476}2477if(type_p)2478*type_p = type;2479if(!refname) {2480 last_errno = errno;2481if(last_errno != ENOTDIR ||2482!verify_refname_available(orig_refname, extras, skip,2483get_loose_refs(&ref_cache), err))2484strbuf_addf(err,"unable to resolve reference%s:%s",2485 orig_refname,strerror(last_errno));24862487goto error_return;2488}2489/*2490 * If the ref did not exist and we are creating it, make sure2491 * there is no existing packed ref whose name begins with our2492 * refname, nor a packed ref whose name is a proper prefix of2493 * our refname.2494 */2495if(is_null_oid(&lock->old_oid) &&2496verify_refname_available(refname, extras, skip,2497get_packed_refs(&ref_cache), err)) {2498 last_errno = ENOTDIR;2499goto error_return;2500}25012502 lock->lk =xcalloc(1,sizeof(struct lock_file));25032504 lflags =0;2505if(flags & REF_NODEREF) {2506 refname = orig_refname;2507 lflags |= LOCK_NO_DEREF;2508}2509 lock->ref_name =xstrdup(refname);2510 lock->orig_ref_name =xstrdup(orig_refname);2511strbuf_git_path(&ref_file,"%s", refname);25122513 retry:2514switch(safe_create_leading_directories_const(ref_file.buf)) {2515case SCLD_OK:2516break;/* success */2517case SCLD_VANISHED:2518if(--attempts_remaining >0)2519goto retry;2520/* fall through */2521default:2522 last_errno = errno;2523strbuf_addf(err,"unable to create directory for%s",2524 ref_file.buf);2525goto error_return;2526}25272528if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2529 last_errno = errno;2530if(errno == ENOENT && --attempts_remaining >0)2531/*2532 * Maybe somebody just deleted one of the2533 * directories leading to ref_file. Try2534 * again:2535 */2536goto retry;2537else{2538unable_to_lock_message(ref_file.buf, errno, err);2539goto error_return;2540}2541}2542if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2543 last_errno = errno;2544goto error_return;2545}2546goto out;25472548 error_return:2549unlock_ref(lock);2550 lock = NULL;25512552 out:2553strbuf_release(&ref_file);2554strbuf_release(&orig_ref_file);2555 errno = last_errno;2556return lock;2557}25582559/*2560 * Write an entry to the packed-refs file for the specified refname.2561 * If peeled is non-NULL, write it as the entry's peeled value.2562 */2563static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2564unsigned char*peeled)2565{2566fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2567if(peeled)2568fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2569}25702571/*2572 * An each_ref_entry_fn that writes the entry to a packed-refs file.2573 */2574static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2575{2576enum peel_status peel_status =peel_entry(entry,0);25772578if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2579error("internal error:%sis not a valid packed reference!",2580 entry->name);2581write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2582 peel_status == PEEL_PEELED ?2583 entry->u.value.peeled.hash : NULL);2584return0;2585}25862587/*2588 * Lock the packed-refs file for writing. Flags is passed to2589 * hold_lock_file_for_update(). Return 0 on success. On errors, set2590 * errno appropriately and return a nonzero value.2591 */2592static intlock_packed_refs(int flags)2593{2594static int timeout_configured =0;2595static int timeout_value =1000;25962597struct packed_ref_cache *packed_ref_cache;25982599if(!timeout_configured) {2600git_config_get_int("core.packedrefstimeout", &timeout_value);2601 timeout_configured =1;2602}26032604if(hold_lock_file_for_update_timeout(2605&packlock,git_path("packed-refs"),2606 flags, timeout_value) <0)2607return-1;2608/*2609 * Get the current packed-refs while holding the lock. If the2610 * packed-refs file has been modified since we last read it,2611 * this will automatically invalidate the cache and re-read2612 * the packed-refs file.2613 */2614 packed_ref_cache =get_packed_ref_cache(&ref_cache);2615 packed_ref_cache->lock = &packlock;2616/* Increment the reference count to prevent it from being freed: */2617acquire_packed_ref_cache(packed_ref_cache);2618return0;2619}26202621/*2622 * Write the current version of the packed refs cache from memory to2623 * disk. The packed-refs file must already be locked for writing (see2624 * lock_packed_refs()). Return zero on success. On errors, set errno2625 * and return a nonzero value2626 */2627static intcommit_packed_refs(void)2628{2629struct packed_ref_cache *packed_ref_cache =2630get_packed_ref_cache(&ref_cache);2631int error =0;2632int save_errno =0;2633FILE*out;26342635if(!packed_ref_cache->lock)2636die("internal error: packed-refs not locked");26372638 out =fdopen_lock_file(packed_ref_cache->lock,"w");2639if(!out)2640die_errno("unable to fdopen packed-refs descriptor");26412642fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2643do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),26440, write_packed_entry_fn, out);26452646if(commit_lock_file(packed_ref_cache->lock)) {2647 save_errno = errno;2648 error = -1;2649}2650 packed_ref_cache->lock = NULL;2651release_packed_ref_cache(packed_ref_cache);2652 errno = save_errno;2653return error;2654}26552656/*2657 * Rollback the lockfile for the packed-refs file, and discard the2658 * in-memory packed reference cache. (The packed-refs file will be2659 * read anew if it is needed again after this function is called.)2660 */2661static voidrollback_packed_refs(void)2662{2663struct packed_ref_cache *packed_ref_cache =2664get_packed_ref_cache(&ref_cache);26652666if(!packed_ref_cache->lock)2667die("internal error: packed-refs not locked");2668rollback_lock_file(packed_ref_cache->lock);2669 packed_ref_cache->lock = NULL;2670release_packed_ref_cache(packed_ref_cache);2671clear_packed_ref_cache(&ref_cache);2672}26732674struct ref_to_prune {2675struct ref_to_prune *next;2676unsigned char sha1[20];2677char name[FLEX_ARRAY];2678};26792680struct pack_refs_cb_data {2681unsigned int flags;2682struct ref_dir *packed_refs;2683struct ref_to_prune *ref_to_prune;2684};26852686static intis_per_worktree_ref(const char*refname);26872688/*2689 * An each_ref_entry_fn that is run over loose references only. If2690 * the loose reference can be packed, add an entry in the packed ref2691 * cache. If the reference should be pruned, also add it to2692 * ref_to_prune in the pack_refs_cb_data.2693 */2694static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2695{2696struct pack_refs_cb_data *cb = cb_data;2697enum peel_status peel_status;2698struct ref_entry *packed_entry;2699int is_tag_ref =starts_with(entry->name,"refs/tags/");27002701/* Do not pack per-worktree refs: */2702if(is_per_worktree_ref(entry->name))2703return0;27042705/* ALWAYS pack tags */2706if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2707return0;27082709/* Do not pack symbolic or broken refs: */2710if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2711return0;27122713/* Add a packed ref cache entry equivalent to the loose entry. */2714 peel_status =peel_entry(entry,1);2715if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2716die("internal error peeling reference%s(%s)",2717 entry->name,oid_to_hex(&entry->u.value.oid));2718 packed_entry =find_ref(cb->packed_refs, entry->name);2719if(packed_entry) {2720/* Overwrite existing packed entry with info from loose entry */2721 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2722oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2723}else{2724 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2725 REF_ISPACKED | REF_KNOWS_PEELED,0);2726add_ref(cb->packed_refs, packed_entry);2727}2728oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);27292730/* Schedule the loose reference for pruning if requested. */2731if((cb->flags & PACK_REFS_PRUNE)) {2732int namelen =strlen(entry->name) +1;2733struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2734hashcpy(n->sha1, entry->u.value.oid.hash);2735memcpy(n->name, entry->name, namelen);/* includes NUL */2736 n->next = cb->ref_to_prune;2737 cb->ref_to_prune = n;2738}2739return0;2740}27412742/*2743 * Remove empty parents, but spare refs/ and immediate subdirs.2744 * Note: munges *name.2745 */2746static voidtry_remove_empty_parents(char*name)2747{2748char*p, *q;2749int i;2750 p = name;2751for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2752while(*p && *p !='/')2753 p++;2754/* tolerate duplicate slashes; see check_refname_format() */2755while(*p =='/')2756 p++;2757}2758for(q = p; *q; q++)2759;2760while(1) {2761while(q > p && *q !='/')2762 q--;2763while(q > p && *(q-1) =='/')2764 q--;2765if(q == p)2766break;2767*q ='\0';2768if(rmdir(git_path("%s", name)))2769break;2770}2771}27722773/* make sure nobody touched the ref, and unlink */2774static voidprune_ref(struct ref_to_prune *r)2775{2776struct ref_transaction *transaction;2777struct strbuf err = STRBUF_INIT;27782779if(check_refname_format(r->name,0))2780return;27812782 transaction =ref_transaction_begin(&err);2783if(!transaction ||2784ref_transaction_delete(transaction, r->name, r->sha1,2785 REF_ISPRUNING, NULL, &err) ||2786ref_transaction_commit(transaction, &err)) {2787ref_transaction_free(transaction);2788error("%s", err.buf);2789strbuf_release(&err);2790return;2791}2792ref_transaction_free(transaction);2793strbuf_release(&err);2794try_remove_empty_parents(r->name);2795}27962797static voidprune_refs(struct ref_to_prune *r)2798{2799while(r) {2800prune_ref(r);2801 r = r->next;2802}2803}28042805intpack_refs(unsigned int flags)2806{2807struct pack_refs_cb_data cbdata;28082809memset(&cbdata,0,sizeof(cbdata));2810 cbdata.flags = flags;28112812lock_packed_refs(LOCK_DIE_ON_ERROR);2813 cbdata.packed_refs =get_packed_refs(&ref_cache);28142815do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2816 pack_if_possible_fn, &cbdata);28172818if(commit_packed_refs())2819die_errno("unable to overwrite old ref-pack file");28202821prune_refs(cbdata.ref_to_prune);2822return0;2823}28242825/*2826 * Rewrite the packed-refs file, omitting any refs listed in2827 * 'refnames'. On error, leave packed-refs unchanged, write an error2828 * message to 'err', and return a nonzero value.2829 *2830 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2831 */2832static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2833{2834struct ref_dir *packed;2835struct string_list_item *refname;2836int ret, needs_repacking =0, removed =0;28372838assert(err);28392840/* Look for a packed ref */2841for_each_string_list_item(refname, refnames) {2842if(get_packed_ref(refname->string)) {2843 needs_repacking =1;2844break;2845}2846}28472848/* Avoid locking if we have nothing to do */2849if(!needs_repacking)2850return0;/* no refname exists in packed refs */28512852if(lock_packed_refs(0)) {2853unable_to_lock_message(git_path("packed-refs"), errno, err);2854return-1;2855}2856 packed =get_packed_refs(&ref_cache);28572858/* Remove refnames from the cache */2859for_each_string_list_item(refname, refnames)2860if(remove_entry(packed, refname->string) != -1)2861 removed =1;2862if(!removed) {2863/*2864 * All packed entries disappeared while we were2865 * acquiring the lock.2866 */2867rollback_packed_refs();2868return0;2869}28702871/* Write what remains */2872 ret =commit_packed_refs();2873if(ret)2874strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2875strerror(errno));2876return ret;2877}28782879static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2880{2881assert(err);28822883if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2884/*2885 * loose. The loose file name is the same as the2886 * lockfile name, minus ".lock":2887 */2888char*loose_filename =get_locked_file_path(lock->lk);2889int res =unlink_or_msg(loose_filename, err);2890free(loose_filename);2891if(res)2892return1;2893}2894return0;2895}28962897static intis_per_worktree_ref(const char*refname)2898{2899return!strcmp(refname,"HEAD") ||2900starts_with(refname,"refs/bisect/");2901}29022903static intis_pseudoref_syntax(const char*refname)2904{2905const char*c;29062907for(c = refname; *c; c++) {2908if(!isupper(*c) && *c !='-'&& *c !='_')2909return0;2910}29112912return1;2913}29142915enum ref_type ref_type(const char*refname)2916{2917if(is_per_worktree_ref(refname))2918return REF_TYPE_PER_WORKTREE;2919if(is_pseudoref_syntax(refname))2920return REF_TYPE_PSEUDOREF;2921return REF_TYPE_NORMAL;2922}29232924static intwrite_pseudoref(const char*pseudoref,const unsigned char*sha1,2925const unsigned char*old_sha1,struct strbuf *err)2926{2927const char*filename;2928int fd;2929static struct lock_file lock;2930struct strbuf buf = STRBUF_INIT;2931int ret = -1;29322933strbuf_addf(&buf,"%s\n",sha1_to_hex(sha1));29342935 filename =git_path("%s", pseudoref);2936 fd =hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);2937if(fd <0) {2938strbuf_addf(err,"Could not open '%s' for writing:%s",2939 filename,strerror(errno));2940return-1;2941}29422943if(old_sha1) {2944unsigned char actual_old_sha1[20];29452946if(read_ref(pseudoref, actual_old_sha1))2947die("could not read ref '%s'", pseudoref);2948if(hashcmp(actual_old_sha1, old_sha1)) {2949strbuf_addf(err,"Unexpected sha1 when writing%s", pseudoref);2950rollback_lock_file(&lock);2951goto done;2952}2953}29542955if(write_in_full(fd, buf.buf, buf.len) != buf.len) {2956strbuf_addf(err,"Could not write to '%s'", filename);2957rollback_lock_file(&lock);2958goto done;2959}29602961commit_lock_file(&lock);2962 ret =0;2963done:2964strbuf_release(&buf);2965return ret;2966}29672968static intdelete_pseudoref(const char*pseudoref,const unsigned char*old_sha1)2969{2970static struct lock_file lock;2971const char*filename;29722973 filename =git_path("%s", pseudoref);29742975if(old_sha1 && !is_null_sha1(old_sha1)) {2976int fd;2977unsigned char actual_old_sha1[20];29782979 fd =hold_lock_file_for_update(&lock, filename,2980 LOCK_DIE_ON_ERROR);2981if(fd <0)2982die_errno(_("Could not open '%s' for writing"), filename);2983if(read_ref(pseudoref, actual_old_sha1))2984die("could not read ref '%s'", pseudoref);2985if(hashcmp(actual_old_sha1, old_sha1)) {2986warning("Unexpected sha1 when deleting%s", pseudoref);2987rollback_lock_file(&lock);2988return-1;2989}29902991unlink(filename);2992rollback_lock_file(&lock);2993}else{2994unlink(filename);2995}29962997return0;2998}29993000intdelete_ref(const char*refname,const unsigned char*old_sha1,3001unsigned int flags)3002{3003struct ref_transaction *transaction;3004struct strbuf err = STRBUF_INIT;30053006if(ref_type(refname) == REF_TYPE_PSEUDOREF)3007returndelete_pseudoref(refname, old_sha1);30083009 transaction =ref_transaction_begin(&err);3010if(!transaction ||3011ref_transaction_delete(transaction, refname, old_sha1,3012 flags, NULL, &err) ||3013ref_transaction_commit(transaction, &err)) {3014error("%s", err.buf);3015ref_transaction_free(transaction);3016strbuf_release(&err);3017return1;3018}3019ref_transaction_free(transaction);3020strbuf_release(&err);3021return0;3022}30233024intdelete_refs(struct string_list *refnames)3025{3026struct strbuf err = STRBUF_INIT;3027int i, result =0;30283029if(!refnames->nr)3030return0;30313032 result =repack_without_refs(refnames, &err);3033if(result) {3034/*3035 * If we failed to rewrite the packed-refs file, then3036 * it is unsafe to try to remove loose refs, because3037 * doing so might expose an obsolete packed value for3038 * a reference that might even point at an object that3039 * has been garbage collected.3040 */3041if(refnames->nr ==1)3042error(_("could not delete reference%s:%s"),3043 refnames->items[0].string, err.buf);3044else3045error(_("could not delete references:%s"), err.buf);30463047goto out;3048}30493050for(i =0; i < refnames->nr; i++) {3051const char*refname = refnames->items[i].string;30523053if(delete_ref(refname, NULL,0))3054 result |=error(_("could not remove reference%s"), refname);3055}30563057out:3058strbuf_release(&err);3059return result;3060}30613062/*3063 * People using contrib's git-new-workdir have .git/logs/refs ->3064 * /some/other/path/.git/logs/refs, and that may live on another device.3065 *3066 * IOW, to avoid cross device rename errors, the temporary renamed log must3067 * live into logs/refs.3068 */3069#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"30703071static intrename_tmp_log(const char*newrefname)3072{3073int attempts_remaining =4;3074struct strbuf path = STRBUF_INIT;3075int ret = -1;30763077 retry:3078strbuf_reset(&path);3079strbuf_git_path(&path,"logs/%s", newrefname);3080switch(safe_create_leading_directories_const(path.buf)) {3081case SCLD_OK:3082break;/* success */3083case SCLD_VANISHED:3084if(--attempts_remaining >0)3085goto retry;3086/* fall through */3087default:3088error("unable to create directory for%s", newrefname);3089goto out;3090}30913092if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {3093if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {3094/*3095 * rename(a, b) when b is an existing3096 * directory ought to result in ISDIR, but3097 * Solaris 5.8 gives ENOTDIR. Sheesh.3098 */3099if(remove_empty_directories(&path)) {3100error("Directory not empty: logs/%s", newrefname);3101goto out;3102}3103goto retry;3104}else if(errno == ENOENT && --attempts_remaining >0) {3105/*3106 * Maybe another process just deleted one of3107 * the directories in the path to newrefname.3108 * Try again from the beginning.3109 */3110goto retry;3111}else{3112error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",3113 newrefname,strerror(errno));3114goto out;3115}3116}3117 ret =0;3118out:3119strbuf_release(&path);3120return ret;3121}31223123static intrename_ref_available(const char*oldname,const char*newname)3124{3125struct string_list skip = STRING_LIST_INIT_NODUP;3126struct strbuf err = STRBUF_INIT;3127int ret;31283129string_list_insert(&skip, oldname);3130 ret = !verify_refname_available(newname, NULL, &skip,3131get_packed_refs(&ref_cache), &err)3132&& !verify_refname_available(newname, NULL, &skip,3133get_loose_refs(&ref_cache), &err);3134if(!ret)3135error("%s", err.buf);31363137string_list_clear(&skip,0);3138strbuf_release(&err);3139return ret;3140}31413142static intwrite_ref_to_lockfile(struct ref_lock *lock,3143const unsigned char*sha1,struct strbuf *err);3144static intcommit_ref_update(struct ref_lock *lock,3145const unsigned char*sha1,const char*logmsg,3146int flags,struct strbuf *err);31473148intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)3149{3150unsigned char sha1[20], orig_sha1[20];3151int flag =0, logmoved =0;3152struct ref_lock *lock;3153struct stat loginfo;3154int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);3155const char*symref = NULL;3156struct strbuf err = STRBUF_INIT;31573158if(log &&S_ISLNK(loginfo.st_mode))3159returnerror("reflog for%sis a symlink", oldrefname);31603161 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3162 orig_sha1, &flag);3163if(flag & REF_ISSYMREF)3164returnerror("refname%sis a symbolic ref, renaming it is not supported",3165 oldrefname);3166if(!symref)3167returnerror("refname%snot found", oldrefname);31683169if(!rename_ref_available(oldrefname, newrefname))3170return1;31713172if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3173returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3174 oldrefname,strerror(errno));31753176if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3177error("unable to delete old%s", oldrefname);3178goto rollback;3179}31803181if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3182delete_ref(newrefname, sha1, REF_NODEREF)) {3183if(errno==EISDIR) {3184struct strbuf path = STRBUF_INIT;3185int result;31863187strbuf_git_path(&path,"%s", newrefname);3188 result =remove_empty_directories(&path);3189strbuf_release(&path);31903191if(result) {3192error("Directory not empty:%s", newrefname);3193goto rollback;3194}3195}else{3196error("unable to delete existing%s", newrefname);3197goto rollback;3198}3199}32003201if(log &&rename_tmp_log(newrefname))3202goto rollback;32033204 logmoved = log;32053206 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3207if(!lock) {3208error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3209strbuf_release(&err);3210goto rollback;3211}3212hashcpy(lock->old_oid.hash, orig_sha1);32133214if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3215commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {3216error("unable to write current sha1 into%s:%s", newrefname, err.buf);3217strbuf_release(&err);3218goto rollback;3219}32203221return0;32223223 rollback:3224 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3225if(!lock) {3226error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3227strbuf_release(&err);3228goto rollbacklog;3229}32303231 flag = log_all_ref_updates;3232 log_all_ref_updates =0;3233if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3234commit_ref_update(lock, orig_sha1, NULL,0, &err)) {3235error("unable to write current sha1 into%s:%s", oldrefname, err.buf);3236strbuf_release(&err);3237}3238 log_all_ref_updates = flag;32393240 rollbacklog:3241if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3242error("unable to restore logfile%sfrom%s:%s",3243 oldrefname, newrefname,strerror(errno));3244if(!logmoved && log &&3245rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3246error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3247 oldrefname,strerror(errno));32483249return1;3250}32513252static intclose_ref(struct ref_lock *lock)3253{3254if(close_lock_file(lock->lk))3255return-1;3256return0;3257}32583259static intcommit_ref(struct ref_lock *lock)3260{3261if(commit_lock_file(lock->lk))3262return-1;3263return0;3264}32653266/*3267 * copy the reflog message msg to buf, which has been allocated sufficiently3268 * large, while cleaning up the whitespaces. Especially, convert LF to space,3269 * because reflog file is one line per entry.3270 */3271static intcopy_msg(char*buf,const char*msg)3272{3273char*cp = buf;3274char c;3275int wasspace =1;32763277*cp++ ='\t';3278while((c = *msg++)) {3279if(wasspace &&isspace(c))3280continue;3281 wasspace =isspace(c);3282if(wasspace)3283 c =' ';3284*cp++ = c;3285}3286while(buf < cp &&isspace(cp[-1]))3287 cp--;3288*cp++ ='\n';3289return cp - buf;3290}32913292static intshould_autocreate_reflog(const char*refname)3293{3294if(!log_all_ref_updates)3295return0;3296returnstarts_with(refname,"refs/heads/") ||3297starts_with(refname,"refs/remotes/") ||3298starts_with(refname,"refs/notes/") ||3299!strcmp(refname,"HEAD");3300}33013302/*3303 * Create a reflog for a ref. If force_create = 0, the reflog will3304 * only be created for certain refs (those for which3305 * should_autocreate_reflog returns non-zero. Otherwise, create it3306 * regardless of the ref name. Fill in *err and return -1 on failure.3307 */3308static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)3309{3310int logfd, oflags = O_APPEND | O_WRONLY;33113312strbuf_git_path(logfile,"logs/%s", refname);3313if(force_create ||should_autocreate_reflog(refname)) {3314if(safe_create_leading_directories(logfile->buf) <0) {3315strbuf_addf(err,"unable to create directory for%s: "3316"%s", logfile->buf,strerror(errno));3317return-1;3318}3319 oflags |= O_CREAT;3320}33213322 logfd =open(logfile->buf, oflags,0666);3323if(logfd <0) {3324if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3325return0;33263327if(errno == EISDIR) {3328if(remove_empty_directories(logfile)) {3329strbuf_addf(err,"There are still logs under "3330"'%s'", logfile->buf);3331return-1;3332}3333 logfd =open(logfile->buf, oflags,0666);3334}33353336if(logfd <0) {3337strbuf_addf(err,"unable to append to%s:%s",3338 logfile->buf,strerror(errno));3339return-1;3340}3341}33423343adjust_shared_perm(logfile->buf);3344close(logfd);3345return0;3346}334733483349intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3350{3351int ret;3352struct strbuf sb = STRBUF_INIT;33533354 ret =log_ref_setup(refname, &sb, err, force_create);3355strbuf_release(&sb);3356return ret;3357}33583359static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3360const unsigned char*new_sha1,3361const char*committer,const char*msg)3362{3363int msglen, written;3364unsigned maxlen, len;3365char*logrec;33663367 msglen = msg ?strlen(msg) :0;3368 maxlen =strlen(committer) + msglen +100;3369 logrec =xmalloc(maxlen);3370 len =xsnprintf(logrec, maxlen,"%s %s %s\n",3371sha1_to_hex(old_sha1),3372sha1_to_hex(new_sha1),3373 committer);3374if(msglen)3375 len +=copy_msg(logrec + len -1, msg) -1;33763377 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3378free(logrec);3379if(written != len)3380return-1;33813382return0;3383}33843385static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3386const unsigned char*new_sha1,const char*msg,3387struct strbuf *logfile,int flags,3388struct strbuf *err)3389{3390int logfd, result, oflags = O_APPEND | O_WRONLY;33913392if(log_all_ref_updates <0)3393 log_all_ref_updates = !is_bare_repository();33943395 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);33963397if(result)3398return result;33993400 logfd =open(logfile->buf, oflags);3401if(logfd <0)3402return0;3403 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3404git_committer_info(0), msg);3405if(result) {3406strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3407strerror(errno));3408close(logfd);3409return-1;3410}3411if(close(logfd)) {3412strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3413strerror(errno));3414return-1;3415}3416return0;3417}34183419static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3420const unsigned char*new_sha1,const char*msg,3421int flags,struct strbuf *err)3422{3423struct strbuf sb = STRBUF_INIT;3424int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3425 err);3426strbuf_release(&sb);3427return ret;3428}34293430intis_branch(const char*refname)3431{3432return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3433}34343435/*3436 * Write sha1 into the open lockfile, then close the lockfile. On3437 * errors, rollback the lockfile, fill in *err and3438 * return -1.3439 */3440static intwrite_ref_to_lockfile(struct ref_lock *lock,3441const unsigned char*sha1,struct strbuf *err)3442{3443static char term ='\n';3444struct object *o;3445int fd;34463447 o =parse_object(sha1);3448if(!o) {3449strbuf_addf(err,3450"Trying to write ref%swith nonexistent object%s",3451 lock->ref_name,sha1_to_hex(sha1));3452unlock_ref(lock);3453return-1;3454}3455if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3456strbuf_addf(err,3457"Trying to write non-commit object%sto branch%s",3458sha1_to_hex(sha1), lock->ref_name);3459unlock_ref(lock);3460return-1;3461}3462 fd =get_lock_file_fd(lock->lk);3463if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||3464write_in_full(fd, &term,1) !=1||3465close_ref(lock) <0) {3466strbuf_addf(err,3467"Couldn't write%s",get_lock_file_path(lock->lk));3468unlock_ref(lock);3469return-1;3470}3471return0;3472}34733474/*3475 * Commit a change to a loose reference that has already been written3476 * to the loose reference lockfile. Also update the reflogs if3477 * necessary, using the specified lockmsg (which can be NULL).3478 */3479static intcommit_ref_update(struct ref_lock *lock,3480const unsigned char*sha1,const char*logmsg,3481int flags,struct strbuf *err)3482{3483clear_loose_ref_cache(&ref_cache);3484if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||3485(strcmp(lock->ref_name, lock->orig_ref_name) &&3486log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {3487char*old_msg =strbuf_detach(err, NULL);3488strbuf_addf(err,"Cannot update the ref '%s':%s",3489 lock->ref_name, old_msg);3490free(old_msg);3491unlock_ref(lock);3492return-1;3493}3494if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3495/*3496 * Special hack: If a branch is updated directly and HEAD3497 * points to it (may happen on the remote side of a push3498 * for example) then logically the HEAD reflog should be3499 * updated too.3500 * A generic solution implies reverse symref information,3501 * but finding all symrefs pointing to the given branch3502 * would be rather costly for this rare event (the direct3503 * update of a branch) to be worth it. So let's cheat and3504 * check with HEAD only which should cover 99% of all usage3505 * scenarios (even 100% of the default ones).3506 */3507unsigned char head_sha1[20];3508int head_flag;3509const char*head_ref;3510 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3511 head_sha1, &head_flag);3512if(head_ref && (head_flag & REF_ISSYMREF) &&3513!strcmp(head_ref, lock->ref_name)) {3514struct strbuf log_err = STRBUF_INIT;3515if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3516 logmsg,0, &log_err)) {3517error("%s", log_err.buf);3518strbuf_release(&log_err);3519}3520}3521}3522if(commit_ref(lock)) {3523error("Couldn't set%s", lock->ref_name);3524unlock_ref(lock);3525return-1;3526}35273528unlock_ref(lock);3529return0;3530}35313532intcreate_symref(const char*ref_target,const char*refs_heads_master,3533const char*logmsg)3534{3535char*lockpath = NULL;3536char ref[1000];3537int fd, len, written;3538char*git_HEAD =git_pathdup("%s", ref_target);3539unsigned char old_sha1[20], new_sha1[20];3540struct strbuf err = STRBUF_INIT;35413542if(logmsg &&read_ref(ref_target, old_sha1))3543hashclr(old_sha1);35443545if(safe_create_leading_directories(git_HEAD) <0)3546returnerror("unable to create directory for%s", git_HEAD);35473548#ifndef NO_SYMLINK_HEAD3549if(prefer_symlink_refs) {3550unlink(git_HEAD);3551if(!symlink(refs_heads_master, git_HEAD))3552goto done;3553fprintf(stderr,"no symlink - falling back to symbolic ref\n");3554}3555#endif35563557 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3558if(sizeof(ref) <= len) {3559error("refname too long:%s", refs_heads_master);3560goto error_free_return;3561}3562 lockpath =mkpathdup("%s.lock", git_HEAD);3563 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3564if(fd <0) {3565error("Unable to open%sfor writing", lockpath);3566goto error_free_return;3567}3568 written =write_in_full(fd, ref, len);3569if(close(fd) !=0|| written != len) {3570error("Unable to write to%s", lockpath);3571goto error_unlink_return;3572}3573if(rename(lockpath, git_HEAD) <0) {3574error("Unable to create%s", git_HEAD);3575goto error_unlink_return;3576}3577if(adjust_shared_perm(git_HEAD)) {3578error("Unable to fix permissions on%s", lockpath);3579 error_unlink_return:3580unlink_or_warn(lockpath);3581 error_free_return:3582free(lockpath);3583free(git_HEAD);3584return-1;3585}3586free(lockpath);35873588#ifndef NO_SYMLINK_HEAD3589 done:3590#endif3591if(logmsg && !read_ref(refs_heads_master, new_sha1) &&3592log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {3593error("%s", err.buf);3594strbuf_release(&err);3595}35963597free(git_HEAD);3598return0;3599}36003601struct read_ref_at_cb {3602const char*refname;3603unsigned long at_time;3604int cnt;3605int reccnt;3606unsigned char*sha1;3607int found_it;36083609unsigned char osha1[20];3610unsigned char nsha1[20];3611int tz;3612unsigned long date;3613char**msg;3614unsigned long*cutoff_time;3615int*cutoff_tz;3616int*cutoff_cnt;3617};36183619static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3620const char*email,unsigned long timestamp,int tz,3621const char*message,void*cb_data)3622{3623struct read_ref_at_cb *cb = cb_data;36243625 cb->reccnt++;3626 cb->tz = tz;3627 cb->date = timestamp;36283629if(timestamp <= cb->at_time || cb->cnt ==0) {3630if(cb->msg)3631*cb->msg =xstrdup(message);3632if(cb->cutoff_time)3633*cb->cutoff_time = timestamp;3634if(cb->cutoff_tz)3635*cb->cutoff_tz = tz;3636if(cb->cutoff_cnt)3637*cb->cutoff_cnt = cb->reccnt -1;3638/*3639 * we have not yet updated cb->[n|o]sha1 so they still3640 * hold the values for the previous record.3641 */3642if(!is_null_sha1(cb->osha1)) {3643hashcpy(cb->sha1, nsha1);3644if(hashcmp(cb->osha1, nsha1))3645warning("Log for ref%shas gap after%s.",3646 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3647}3648else if(cb->date == cb->at_time)3649hashcpy(cb->sha1, nsha1);3650else if(hashcmp(nsha1, cb->sha1))3651warning("Log for ref%sunexpectedly ended on%s.",3652 cb->refname,show_date(cb->date, cb->tz,3653DATE_MODE(RFC2822)));3654hashcpy(cb->osha1, osha1);3655hashcpy(cb->nsha1, nsha1);3656 cb->found_it =1;3657return1;3658}3659hashcpy(cb->osha1, osha1);3660hashcpy(cb->nsha1, nsha1);3661if(cb->cnt >0)3662 cb->cnt--;3663return0;3664}36653666static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3667const char*email,unsigned long timestamp,3668int tz,const char*message,void*cb_data)3669{3670struct read_ref_at_cb *cb = cb_data;36713672if(cb->msg)3673*cb->msg =xstrdup(message);3674if(cb->cutoff_time)3675*cb->cutoff_time = timestamp;3676if(cb->cutoff_tz)3677*cb->cutoff_tz = tz;3678if(cb->cutoff_cnt)3679*cb->cutoff_cnt = cb->reccnt;3680hashcpy(cb->sha1, osha1);3681if(is_null_sha1(cb->sha1))3682hashcpy(cb->sha1, nsha1);3683/* We just want the first entry */3684return1;3685}36863687intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3688unsigned char*sha1,char**msg,3689unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3690{3691struct read_ref_at_cb cb;36923693memset(&cb,0,sizeof(cb));3694 cb.refname = refname;3695 cb.at_time = at_time;3696 cb.cnt = cnt;3697 cb.msg = msg;3698 cb.cutoff_time = cutoff_time;3699 cb.cutoff_tz = cutoff_tz;3700 cb.cutoff_cnt = cutoff_cnt;3701 cb.sha1 = sha1;37023703for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);37043705if(!cb.reccnt) {3706if(flags & GET_SHA1_QUIETLY)3707exit(128);3708else3709die("Log for%sis empty.", refname);3710}3711if(cb.found_it)3712return0;37133714for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);37153716return1;3717}37183719intreflog_exists(const char*refname)3720{3721struct stat st;37223723return!lstat(git_path("logs/%s", refname), &st) &&3724S_ISREG(st.st_mode);3725}37263727intdelete_reflog(const char*refname)3728{3729returnremove_path(git_path("logs/%s", refname));3730}37313732static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3733{3734unsigned char osha1[20], nsha1[20];3735char*email_end, *message;3736unsigned long timestamp;3737int tz;37383739/* old SP new SP name <email> SP time TAB msg LF */3740if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3741get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3742get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3743!(email_end =strchr(sb->buf +82,'>')) ||3744 email_end[1] !=' '||3745!(timestamp =strtoul(email_end +2, &message,10)) ||3746!message || message[0] !=' '||3747(message[1] !='+'&& message[1] !='-') ||3748!isdigit(message[2]) || !isdigit(message[3]) ||3749!isdigit(message[4]) || !isdigit(message[5]))3750return0;/* corrupt? */3751 email_end[1] ='\0';3752 tz =strtol(message +1, NULL,10);3753if(message[6] !='\t')3754 message +=6;3755else3756 message +=7;3757returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3758}37593760static char*find_beginning_of_line(char*bob,char*scan)3761{3762while(bob < scan && *(--scan) !='\n')3763;/* keep scanning backwards */3764/*3765 * Return either beginning of the buffer, or LF at the end of3766 * the previous line.3767 */3768return scan;3769}37703771intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3772{3773struct strbuf sb = STRBUF_INIT;3774FILE*logfp;3775long pos;3776int ret =0, at_tail =1;37773778 logfp =fopen(git_path("logs/%s", refname),"r");3779if(!logfp)3780return-1;37813782/* Jump to the end */3783if(fseek(logfp,0, SEEK_END) <0)3784returnerror("cannot seek back reflog for%s:%s",3785 refname,strerror(errno));3786 pos =ftell(logfp);3787while(!ret &&0< pos) {3788int cnt;3789size_t nread;3790char buf[BUFSIZ];3791char*endp, *scanp;37923793/* Fill next block from the end */3794 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3795if(fseek(logfp, pos - cnt, SEEK_SET))3796returnerror("cannot seek back reflog for%s:%s",3797 refname,strerror(errno));3798 nread =fread(buf, cnt,1, logfp);3799if(nread !=1)3800returnerror("cannot read%dbytes from reflog for%s:%s",3801 cnt, refname,strerror(errno));3802 pos -= cnt;38033804 scanp = endp = buf + cnt;3805if(at_tail && scanp[-1] =='\n')3806/* Looking at the final LF at the end of the file */3807 scanp--;3808 at_tail =0;38093810while(buf < scanp) {3811/*3812 * terminating LF of the previous line, or the beginning3813 * of the buffer.3814 */3815char*bp;38163817 bp =find_beginning_of_line(buf, scanp);38183819if(*bp =='\n') {3820/*3821 * The newline is the end of the previous line,3822 * so we know we have complete line starting3823 * at (bp + 1). Prefix it onto any prior data3824 * we collected for the line and process it.3825 */3826strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3827 scanp = bp;3828 endp = bp +1;3829 ret =show_one_reflog_ent(&sb, fn, cb_data);3830strbuf_reset(&sb);3831if(ret)3832break;3833}else if(!pos) {3834/*3835 * We are at the start of the buffer, and the3836 * start of the file; there is no previous3837 * line, and we have everything for this one.3838 * Process it, and we can end the loop.3839 */3840strbuf_splice(&sb,0,0, buf, endp - buf);3841 ret =show_one_reflog_ent(&sb, fn, cb_data);3842strbuf_reset(&sb);3843break;3844}38453846if(bp == buf) {3847/*3848 * We are at the start of the buffer, and there3849 * is more file to read backwards. Which means3850 * we are in the middle of a line. Note that we3851 * may get here even if *bp was a newline; that3852 * just means we are at the exact end of the3853 * previous line, rather than some spot in the3854 * middle.3855 *3856 * Save away what we have to be combined with3857 * the data from the next read.3858 */3859strbuf_splice(&sb,0,0, buf, endp - buf);3860break;3861}3862}38633864}3865if(!ret && sb.len)3866die("BUG: reverse reflog parser had leftover data");38673868fclose(logfp);3869strbuf_release(&sb);3870return ret;3871}38723873intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3874{3875FILE*logfp;3876struct strbuf sb = STRBUF_INIT;3877int ret =0;38783879 logfp =fopen(git_path("logs/%s", refname),"r");3880if(!logfp)3881return-1;38823883while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3884 ret =show_one_reflog_ent(&sb, fn, cb_data);3885fclose(logfp);3886strbuf_release(&sb);3887return ret;3888}3889/*3890 * Call fn for each reflog in the namespace indicated by name. name3891 * must be empty or end with '/'. Name will be used as a scratch3892 * space, but its contents will be restored before return.3893 */3894static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3895{3896DIR*d =opendir(git_path("logs/%s", name->buf));3897int retval =0;3898struct dirent *de;3899int oldlen = name->len;39003901if(!d)3902return name->len ? errno :0;39033904while((de =readdir(d)) != NULL) {3905struct stat st;39063907if(de->d_name[0] =='.')3908continue;3909if(ends_with(de->d_name,".lock"))3910continue;3911strbuf_addstr(name, de->d_name);3912if(stat(git_path("logs/%s", name->buf), &st) <0) {3913;/* silently ignore */3914}else{3915if(S_ISDIR(st.st_mode)) {3916strbuf_addch(name,'/');3917 retval =do_for_each_reflog(name, fn, cb_data);3918}else{3919struct object_id oid;39203921if(read_ref_full(name->buf,0, oid.hash, NULL))3922 retval =error("bad ref for%s", name->buf);3923else3924 retval =fn(name->buf, &oid,0, cb_data);3925}3926if(retval)3927break;3928}3929strbuf_setlen(name, oldlen);3930}3931closedir(d);3932return retval;3933}39343935intfor_each_reflog(each_ref_fn fn,void*cb_data)3936{3937int retval;3938struct strbuf name;3939strbuf_init(&name, PATH_MAX);3940 retval =do_for_each_reflog(&name, fn, cb_data);3941strbuf_release(&name);3942return retval;3943}39443945/**3946 * Information needed for a single ref update. Set new_sha1 to the new3947 * value or to null_sha1 to delete the ref. To check the old value3948 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3949 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3950 * not exist before update.3951 */3952struct ref_update {3953/*3954 * If (flags & REF_HAVE_NEW), set the reference to this value:3955 */3956unsigned char new_sha1[20];3957/*3958 * If (flags & REF_HAVE_OLD), check that the reference3959 * previously had this value:3960 */3961unsigned char old_sha1[20];3962/*3963 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3964 * REF_DELETING, and REF_ISPRUNING:3965 */3966unsigned int flags;3967struct ref_lock *lock;3968int type;3969char*msg;3970const char refname[FLEX_ARRAY];3971};39723973/*3974 * Transaction states.3975 * OPEN: The transaction is in a valid state and can accept new updates.3976 * An OPEN transaction can be committed.3977 * CLOSED: A closed transaction is no longer active and no other operations3978 * than free can be used on it in this state.3979 * A transaction can either become closed by successfully committing3980 * an active transaction or if there is a failure while building3981 * the transaction thus rendering it failed/inactive.3982 */3983enum ref_transaction_state {3984 REF_TRANSACTION_OPEN =0,3985 REF_TRANSACTION_CLOSED =13986};39873988/*3989 * Data structure for holding a reference transaction, which can3990 * consist of checks and updates to multiple references, carried out3991 * as atomically as possible. This structure is opaque to callers.3992 */3993struct ref_transaction {3994struct ref_update **updates;3995size_t alloc;3996size_t nr;3997enum ref_transaction_state state;3998};39994000struct ref_transaction *ref_transaction_begin(struct strbuf *err)4001{4002assert(err);40034004returnxcalloc(1,sizeof(struct ref_transaction));4005}40064007voidref_transaction_free(struct ref_transaction *transaction)4008{4009int i;40104011if(!transaction)4012return;40134014for(i =0; i < transaction->nr; i++) {4015free(transaction->updates[i]->msg);4016free(transaction->updates[i]);4017}4018free(transaction->updates);4019free(transaction);4020}40214022static struct ref_update *add_update(struct ref_transaction *transaction,4023const char*refname)4024{4025size_t len =strlen(refname) +1;4026struct ref_update *update =xcalloc(1,sizeof(*update) + len);40274028memcpy((char*)update->refname, refname, len);/* includes NUL */4029ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);4030 transaction->updates[transaction->nr++] = update;4031return update;4032}40334034intref_transaction_update(struct ref_transaction *transaction,4035const char*refname,4036const unsigned char*new_sha1,4037const unsigned char*old_sha1,4038unsigned int flags,const char*msg,4039struct strbuf *err)4040{4041struct ref_update *update;40424043assert(err);40444045if(transaction->state != REF_TRANSACTION_OPEN)4046die("BUG: update called for transaction that is not open");40474048if(new_sha1 && !is_null_sha1(new_sha1) &&4049check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {4050strbuf_addf(err,"refusing to update ref with bad name%s",4051 refname);4052return-1;4053}40544055 update =add_update(transaction, refname);4056if(new_sha1) {4057hashcpy(update->new_sha1, new_sha1);4058 flags |= REF_HAVE_NEW;4059}4060if(old_sha1) {4061hashcpy(update->old_sha1, old_sha1);4062 flags |= REF_HAVE_OLD;4063}4064 update->flags = flags;4065if(msg)4066 update->msg =xstrdup(msg);4067return0;4068}40694070intref_transaction_create(struct ref_transaction *transaction,4071const char*refname,4072const unsigned char*new_sha1,4073unsigned int flags,const char*msg,4074struct strbuf *err)4075{4076if(!new_sha1 ||is_null_sha1(new_sha1))4077die("BUG: create called without valid new_sha1");4078returnref_transaction_update(transaction, refname, new_sha1,4079 null_sha1, flags, msg, err);4080}40814082intref_transaction_delete(struct ref_transaction *transaction,4083const char*refname,4084const unsigned char*old_sha1,4085unsigned int flags,const char*msg,4086struct strbuf *err)4087{4088if(old_sha1 &&is_null_sha1(old_sha1))4089die("BUG: delete called with old_sha1 set to zeros");4090returnref_transaction_update(transaction, refname,4091 null_sha1, old_sha1,4092 flags, msg, err);4093}40944095intref_transaction_verify(struct ref_transaction *transaction,4096const char*refname,4097const unsigned char*old_sha1,4098unsigned int flags,4099struct strbuf *err)4100{4101if(!old_sha1)4102die("BUG: verify called with old_sha1 set to NULL");4103returnref_transaction_update(transaction, refname,4104 NULL, old_sha1,4105 flags, NULL, err);4106}41074108intupdate_ref(const char*msg,const char*refname,4109const unsigned char*new_sha1,const unsigned char*old_sha1,4110unsigned int flags,enum action_on_err onerr)4111{4112struct ref_transaction *t = NULL;4113struct strbuf err = STRBUF_INIT;4114int ret =0;41154116if(ref_type(refname) == REF_TYPE_PSEUDOREF) {4117 ret =write_pseudoref(refname, new_sha1, old_sha1, &err);4118}else{4119 t =ref_transaction_begin(&err);4120if(!t ||4121ref_transaction_update(t, refname, new_sha1, old_sha1,4122 flags, msg, &err) ||4123ref_transaction_commit(t, &err)) {4124 ret =1;4125ref_transaction_free(t);4126}4127}4128if(ret) {4129const char*str ="update_ref failed for ref '%s':%s";41304131switch(onerr) {4132case UPDATE_REFS_MSG_ON_ERR:4133error(str, refname, err.buf);4134break;4135case UPDATE_REFS_DIE_ON_ERR:4136die(str, refname, err.buf);4137break;4138case UPDATE_REFS_QUIET_ON_ERR:4139break;4140}4141strbuf_release(&err);4142return1;4143}4144strbuf_release(&err);4145if(t)4146ref_transaction_free(t);4147return0;4148}41494150static intref_update_reject_duplicates(struct string_list *refnames,4151struct strbuf *err)4152{4153int i, n = refnames->nr;41544155assert(err);41564157for(i =1; i < n; i++)4158if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {4159strbuf_addf(err,4160"Multiple updates for ref '%s' not allowed.",4161 refnames->items[i].string);4162return1;4163}4164return0;4165}41664167intref_transaction_commit(struct ref_transaction *transaction,4168struct strbuf *err)4169{4170int ret =0, i;4171int n = transaction->nr;4172struct ref_update **updates = transaction->updates;4173struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4174struct string_list_item *ref_to_delete;4175struct string_list affected_refnames = STRING_LIST_INIT_NODUP;41764177assert(err);41784179if(transaction->state != REF_TRANSACTION_OPEN)4180die("BUG: commit called for transaction that is not open");41814182if(!n) {4183 transaction->state = REF_TRANSACTION_CLOSED;4184return0;4185}41864187/* Fail if a refname appears more than once in the transaction: */4188for(i =0; i < n; i++)4189string_list_append(&affected_refnames, updates[i]->refname);4190string_list_sort(&affected_refnames);4191if(ref_update_reject_duplicates(&affected_refnames, err)) {4192 ret = TRANSACTION_GENERIC_ERROR;4193goto cleanup;4194}41954196/*4197 * Acquire all locks, verify old values if provided, check4198 * that new values are valid, and write new values to the4199 * lockfiles, ready to be activated. Only keep one lockfile4200 * open at a time to avoid running out of file descriptors.4201 */4202for(i =0; i < n; i++) {4203struct ref_update *update = updates[i];42044205if((update->flags & REF_HAVE_NEW) &&4206is_null_sha1(update->new_sha1))4207 update->flags |= REF_DELETING;4208 update->lock =lock_ref_sha1_basic(4209 update->refname,4210((update->flags & REF_HAVE_OLD) ?4211 update->old_sha1 : NULL),4212&affected_refnames, NULL,4213 update->flags,4214&update->type,4215 err);4216if(!update->lock) {4217char*reason;42184219 ret = (errno == ENOTDIR)4220? TRANSACTION_NAME_CONFLICT4221: TRANSACTION_GENERIC_ERROR;4222 reason =strbuf_detach(err, NULL);4223strbuf_addf(err,"cannot lock ref '%s':%s",4224 update->refname, reason);4225free(reason);4226goto cleanup;4227}4228if((update->flags & REF_HAVE_NEW) &&4229!(update->flags & REF_DELETING)) {4230int overwriting_symref = ((update->type & REF_ISSYMREF) &&4231(update->flags & REF_NODEREF));42324233if(!overwriting_symref &&4234!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4235/*4236 * The reference already has the desired4237 * value, so we don't need to write it.4238 */4239}else if(write_ref_to_lockfile(update->lock,4240 update->new_sha1,4241 err)) {4242char*write_err =strbuf_detach(err, NULL);42434244/*4245 * The lock was freed upon failure of4246 * write_ref_to_lockfile():4247 */4248 update->lock = NULL;4249strbuf_addf(err,4250"cannot update the ref '%s':%s",4251 update->refname, write_err);4252free(write_err);4253 ret = TRANSACTION_GENERIC_ERROR;4254goto cleanup;4255}else{4256 update->flags |= REF_NEEDS_COMMIT;4257}4258}4259if(!(update->flags & REF_NEEDS_COMMIT)) {4260/*4261 * We didn't have to write anything to the lockfile.4262 * Close it to free up the file descriptor:4263 */4264if(close_ref(update->lock)) {4265strbuf_addf(err,"Couldn't close%s.lock",4266 update->refname);4267goto cleanup;4268}4269}4270}42714272/* Perform updates first so live commits remain referenced */4273for(i =0; i < n; i++) {4274struct ref_update *update = updates[i];42754276if(update->flags & REF_NEEDS_COMMIT) {4277if(commit_ref_update(update->lock,4278 update->new_sha1, update->msg,4279 update->flags, err)) {4280/* freed by commit_ref_update(): */4281 update->lock = NULL;4282 ret = TRANSACTION_GENERIC_ERROR;4283goto cleanup;4284}else{4285/* freed by commit_ref_update(): */4286 update->lock = NULL;4287}4288}4289}42904291/* Perform deletes now that updates are safely completed */4292for(i =0; i < n; i++) {4293struct ref_update *update = updates[i];42944295if(update->flags & REF_DELETING) {4296if(delete_ref_loose(update->lock, update->type, err)) {4297 ret = TRANSACTION_GENERIC_ERROR;4298goto cleanup;4299}43004301if(!(update->flags & REF_ISPRUNING))4302string_list_append(&refs_to_delete,4303 update->lock->ref_name);4304}4305}43064307if(repack_without_refs(&refs_to_delete, err)) {4308 ret = TRANSACTION_GENERIC_ERROR;4309goto cleanup;4310}4311for_each_string_list_item(ref_to_delete, &refs_to_delete)4312unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4313clear_loose_ref_cache(&ref_cache);43144315cleanup:4316 transaction->state = REF_TRANSACTION_CLOSED;43174318for(i =0; i < n; i++)4319if(updates[i]->lock)4320unlock_ref(updates[i]->lock);4321string_list_clear(&refs_to_delete,0);4322string_list_clear(&affected_refnames,0);4323return ret;4324}43254326static intref_present(const char*refname,4327const struct object_id *oid,int flags,void*cb_data)4328{4329struct string_list *affected_refnames = cb_data;43304331returnstring_list_has_string(affected_refnames, refname);4332}43334334intinitial_ref_transaction_commit(struct ref_transaction *transaction,4335struct strbuf *err)4336{4337struct ref_dir *loose_refs =get_loose_refs(&ref_cache);4338struct ref_dir *packed_refs =get_packed_refs(&ref_cache);4339int ret =0, i;4340int n = transaction->nr;4341struct ref_update **updates = transaction->updates;4342struct string_list affected_refnames = STRING_LIST_INIT_NODUP;43434344assert(err);43454346if(transaction->state != REF_TRANSACTION_OPEN)4347die("BUG: commit called for transaction that is not open");43484349/* Fail if a refname appears more than once in the transaction: */4350for(i =0; i < n; i++)4351string_list_append(&affected_refnames, updates[i]->refname);4352string_list_sort(&affected_refnames);4353if(ref_update_reject_duplicates(&affected_refnames, err)) {4354 ret = TRANSACTION_GENERIC_ERROR;4355goto cleanup;4356}43574358/*4359 * It's really undefined to call this function in an active4360 * repository or when there are existing references: we are4361 * only locking and changing packed-refs, so (1) any4362 * simultaneous processes might try to change a reference at4363 * the same time we do, and (2) any existing loose versions of4364 * the references that we are setting would have precedence4365 * over our values. But some remote helpers create the remote4366 * "HEAD" and "master" branches before calling this function,4367 * so here we really only check that none of the references4368 * that we are creating already exists.4369 */4370if(for_each_rawref(ref_present, &affected_refnames))4371die("BUG: initial ref transaction called with existing refs");43724373for(i =0; i < n; i++) {4374struct ref_update *update = updates[i];43754376if((update->flags & REF_HAVE_OLD) &&4377!is_null_sha1(update->old_sha1))4378die("BUG: initial ref transaction with old_sha1 set");4379if(verify_refname_available(update->refname,4380&affected_refnames, NULL,4381 loose_refs, err) ||4382verify_refname_available(update->refname,4383&affected_refnames, NULL,4384 packed_refs, err)) {4385 ret = TRANSACTION_NAME_CONFLICT;4386goto cleanup;4387}4388}43894390if(lock_packed_refs(0)) {4391strbuf_addf(err,"unable to lock packed-refs file:%s",4392strerror(errno));4393 ret = TRANSACTION_GENERIC_ERROR;4394goto cleanup;4395}43964397for(i =0; i < n; i++) {4398struct ref_update *update = updates[i];43994400if((update->flags & REF_HAVE_NEW) &&4401!is_null_sha1(update->new_sha1))4402add_packed_ref(update->refname, update->new_sha1);4403}44044405if(commit_packed_refs()) {4406strbuf_addf(err,"unable to commit packed-refs file:%s",4407strerror(errno));4408 ret = TRANSACTION_GENERIC_ERROR;4409goto cleanup;4410}44114412cleanup:4413 transaction->state = REF_TRANSACTION_CLOSED;4414string_list_clear(&affected_refnames,0);4415return ret;4416}44174418char*shorten_unambiguous_ref(const char*refname,int strict)4419{4420int i;4421static char**scanf_fmts;4422static int nr_rules;4423char*short_name;44244425if(!nr_rules) {4426/*4427 * Pre-generate scanf formats from ref_rev_parse_rules[].4428 * Generate a format suitable for scanf from a4429 * ref_rev_parse_rules rule by interpolating "%s" at the4430 * location of the "%.*s".4431 */4432size_t total_len =0;4433size_t offset =0;44344435/* the rule list is NULL terminated, count them first */4436for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4437/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4438 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;44394440 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);44414442 offset =0;4443for(i =0; i < nr_rules; i++) {4444assert(offset < total_len);4445 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4446 offset +=snprintf(scanf_fmts[i], total_len - offset,4447 ref_rev_parse_rules[i],2,"%s") +1;4448}4449}44504451/* bail out if there are no rules */4452if(!nr_rules)4453returnxstrdup(refname);44544455/* buffer for scanf result, at most refname must fit */4456 short_name =xstrdup(refname);44574458/* skip first rule, it will always match */4459for(i = nr_rules -1; i >0; --i) {4460int j;4461int rules_to_fail = i;4462int short_name_len;44634464if(1!=sscanf(refname, scanf_fmts[i], short_name))4465continue;44664467 short_name_len =strlen(short_name);44684469/*4470 * in strict mode, all (except the matched one) rules4471 * must fail to resolve to a valid non-ambiguous ref4472 */4473if(strict)4474 rules_to_fail = nr_rules;44754476/*4477 * check if the short name resolves to a valid ref,4478 * but use only rules prior to the matched one4479 */4480for(j =0; j < rules_to_fail; j++) {4481const char*rule = ref_rev_parse_rules[j];4482char refname[PATH_MAX];44834484/* skip matched rule */4485if(i == j)4486continue;44874488/*4489 * the short name is ambiguous, if it resolves4490 * (with this previous rule) to a valid ref4491 * read_ref() returns 0 on success4492 */4493mksnpath(refname,sizeof(refname),4494 rule, short_name_len, short_name);4495if(ref_exists(refname))4496break;4497}44984499/*4500 * short name is non-ambiguous if all previous rules4501 * haven't resolved to a valid ref4502 */4503if(j == rules_to_fail)4504return short_name;4505}45064507free(short_name);4508returnxstrdup(refname);4509}45104511static struct string_list *hide_refs;45124513intparse_hide_refs_config(const char*var,const char*value,const char*section)4514{4515if(!strcmp("transfer.hiderefs", var) ||4516/* NEEDSWORK: use parse_config_key() once both are merged */4517(starts_with(var, section) && var[strlen(section)] =='.'&&4518!strcmp(var +strlen(section),".hiderefs"))) {4519char*ref;4520int len;45214522if(!value)4523returnconfig_error_nonbool(var);4524 ref =xstrdup(value);4525 len =strlen(ref);4526while(len && ref[len -1] =='/')4527 ref[--len] ='\0';4528if(!hide_refs) {4529 hide_refs =xcalloc(1,sizeof(*hide_refs));4530 hide_refs->strdup_strings =1;4531}4532string_list_append(hide_refs, ref);4533}4534return0;4535}45364537intref_is_hidden(const char*refname)4538{4539int i;45404541if(!hide_refs)4542return0;4543for(i = hide_refs->nr -1; i >=0; i--) {4544const char*match = hide_refs->items[i].string;4545int neg =0;4546int len;45474548if(*match =='!') {4549 neg =1;4550 match++;4551}45524553if(!starts_with(refname, match))4554continue;4555 len =strlen(match);4556if(!refname[len] || refname[len] =='/')4557return!neg;4558}4559return0;4560}45614562struct expire_reflog_cb {4563unsigned int flags;4564 reflog_expiry_should_prune_fn *should_prune_fn;4565void*policy_cb;4566FILE*newlog;4567unsigned char last_kept_sha1[20];4568};45694570static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4571const char*email,unsigned long timestamp,int tz,4572const char*message,void*cb_data)4573{4574struct expire_reflog_cb *cb = cb_data;4575struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;45764577if(cb->flags & EXPIRE_REFLOGS_REWRITE)4578 osha1 = cb->last_kept_sha1;45794580if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4581 message, policy_cb)) {4582if(!cb->newlog)4583printf("would prune%s", message);4584else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4585printf("prune%s", message);4586}else{4587if(cb->newlog) {4588fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4589sha1_to_hex(osha1),sha1_to_hex(nsha1),4590 email, timestamp, tz, message);4591hashcpy(cb->last_kept_sha1, nsha1);4592}4593if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4594printf("keep%s", message);4595}4596return0;4597}45984599intreflog_expire(const char*refname,const unsigned char*sha1,4600unsigned int flags,4601 reflog_expiry_prepare_fn prepare_fn,4602 reflog_expiry_should_prune_fn should_prune_fn,4603 reflog_expiry_cleanup_fn cleanup_fn,4604void*policy_cb_data)4605{4606static struct lock_file reflog_lock;4607struct expire_reflog_cb cb;4608struct ref_lock *lock;4609char*log_file;4610int status =0;4611int type;4612struct strbuf err = STRBUF_INIT;46134614memset(&cb,0,sizeof(cb));4615 cb.flags = flags;4616 cb.policy_cb = policy_cb_data;4617 cb.should_prune_fn = should_prune_fn;46184619/*4620 * The reflog file is locked by holding the lock on the4621 * reference itself, plus we might need to update the4622 * reference if --updateref was specified:4623 */4624 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4625if(!lock) {4626error("cannot lock ref '%s':%s", refname, err.buf);4627strbuf_release(&err);4628return-1;4629}4630if(!reflog_exists(refname)) {4631unlock_ref(lock);4632return0;4633}46344635 log_file =git_pathdup("logs/%s", refname);4636if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4637/*4638 * Even though holding $GIT_DIR/logs/$reflog.lock has4639 * no locking implications, we use the lock_file4640 * machinery here anyway because it does a lot of the4641 * work we need, including cleaning up if the program4642 * exits unexpectedly.4643 */4644if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4645struct strbuf err = STRBUF_INIT;4646unable_to_lock_message(log_file, errno, &err);4647error("%s", err.buf);4648strbuf_release(&err);4649goto failure;4650}4651 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4652if(!cb.newlog) {4653error("cannot fdopen%s(%s)",4654get_lock_file_path(&reflog_lock),strerror(errno));4655goto failure;4656}4657}46584659(*prepare_fn)(refname, sha1, cb.policy_cb);4660for_each_reflog_ent(refname, expire_reflog_ent, &cb);4661(*cleanup_fn)(cb.policy_cb);46624663if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4664/*4665 * It doesn't make sense to adjust a reference pointed4666 * to by a symbolic ref based on expiring entries in4667 * the symbolic reference's reflog. Nor can we update4668 * a reference if there are no remaining reflog4669 * entries.4670 */4671int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4672!(type & REF_ISSYMREF) &&4673!is_null_sha1(cb.last_kept_sha1);46744675if(close_lock_file(&reflog_lock)) {4676 status |=error("couldn't write%s:%s", log_file,4677strerror(errno));4678}else if(update &&4679(write_in_full(get_lock_file_fd(lock->lk),4680sha1_to_hex(cb.last_kept_sha1),40) !=40||4681write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||4682close_ref(lock) <0)) {4683 status |=error("couldn't write%s",4684get_lock_file_path(lock->lk));4685rollback_lock_file(&reflog_lock);4686}else if(commit_lock_file(&reflog_lock)) {4687 status |=error("unable to commit reflog '%s' (%s)",4688 log_file,strerror(errno));4689}else if(update &&commit_ref(lock)) {4690 status |=error("couldn't set%s", lock->ref_name);4691}4692}4693free(log_file);4694unlock_ref(lock);4695return status;46964697 failure:4698rollback_lock_file(&reflog_lock);4699free(log_file);4700unlock_ref(lock);4701return-1;4702}