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 * See verify_refname_available for more information. 901 */ 902static intverify_refname_available_dir(const char*refname, 903const struct string_list *extras, 904const struct string_list *skip, 905struct ref_dir *dir, 906struct strbuf *err) 907{ 908const char*slash; 909int pos; 910struct strbuf dirname = STRBUF_INIT; 911int ret = -1; 912 913/* 914 * For the sake of comments in this function, suppose that 915 * refname is "refs/foo/bar". 916 */ 917 918assert(err); 919 920strbuf_grow(&dirname,strlen(refname) +1); 921for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 922/* Expand dirname to the new prefix, not including the trailing slash: */ 923strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 924 925/* 926 * We are still at a leading dir of the refname (e.g., 927 * "refs/foo"; if there is a reference with that name, 928 * it is a conflict, *unless* it is in skip. 929 */ 930if(dir) { 931 pos =search_ref_dir(dir, dirname.buf, dirname.len); 932if(pos >=0&& 933(!skip || !string_list_has_string(skip, dirname.buf))) { 934/* 935 * We found a reference whose name is 936 * a proper prefix of refname; e.g., 937 * "refs/foo", and is not in skip. 938 */ 939strbuf_addf(err,"'%s' exists; cannot create '%s'", 940 dirname.buf, refname); 941goto cleanup; 942} 943} 944 945if(extras &&string_list_has_string(extras, dirname.buf) && 946(!skip || !string_list_has_string(skip, dirname.buf))) { 947strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 948 refname, dirname.buf); 949goto cleanup; 950} 951 952/* 953 * Otherwise, we can try to continue our search with 954 * the next component. So try to look up the 955 * directory, e.g., "refs/foo/". If we come up empty, 956 * we know there is nothing under this whole prefix, 957 * but even in that case we still have to continue the 958 * search for conflicts with extras. 959 */ 960strbuf_addch(&dirname,'/'); 961if(dir) { 962 pos =search_ref_dir(dir, dirname.buf, dirname.len); 963if(pos <0) { 964/* 965 * There was no directory "refs/foo/", 966 * so there is nothing under this 967 * whole prefix. So there is no need 968 * to continue looking for conflicting 969 * references. But we need to continue 970 * looking for conflicting extras. 971 */ 972 dir = NULL; 973}else{ 974 dir =get_ref_dir(dir->entries[pos]); 975} 976} 977} 978 979/* 980 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 981 * There is no point in searching for a reference with that 982 * name, because a refname isn't considered to conflict with 983 * itself. But we still need to check for references whose 984 * names are in the "refs/foo/bar/" namespace, because they 985 * *do* conflict. 986 */ 987strbuf_addstr(&dirname, refname + dirname.len); 988strbuf_addch(&dirname,'/'); 989 990if(dir) { 991 pos =search_ref_dir(dir, dirname.buf, dirname.len); 992 993if(pos >=0) { 994/* 995 * We found a directory named "$refname/" 996 * (e.g., "refs/foo/bar/"). It is a problem 997 * iff it contains any ref that is not in 998 * "skip". 999 */1000struct nonmatching_ref_data data;10011002 data.skip = skip;1003 data.conflicting_refname = NULL;1004 dir =get_ref_dir(dir->entries[pos]);1005sort_ref_dir(dir);1006if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) {1007strbuf_addf(err,"'%s' exists; cannot create '%s'",1008 data.conflicting_refname, refname);1009goto cleanup;1010}1011}1012}10131014if(extras) {1015/*1016 * Check for entries in extras that start with1017 * "$refname/". We do that by looking for the place1018 * where "$refname/" would be inserted in extras. If1019 * there is an entry at that position that starts with1020 * "$refname/" and is not in skip, then we have a1021 * conflict.1022 */1023for(pos =string_list_find_insert_index(extras, dirname.buf,0);1024 pos < extras->nr; pos++) {1025const char*extra_refname = extras->items[pos].string;10261027if(!starts_with(extra_refname, dirname.buf))1028break;10291030if(!skip || !string_list_has_string(skip, extra_refname)) {1031strbuf_addf(err,"cannot process '%s' and '%s' at the same time",1032 refname, extra_refname);1033goto cleanup;1034}1035}1036}10371038/* No conflicts were found */1039 ret =0;10401041cleanup:1042strbuf_release(&dirname);1043return ret;1044}10451046struct packed_ref_cache {1047struct ref_entry *root;10481049/*1050 * Count of references to the data structure in this instance,1051 * including the pointer from ref_cache::packed if any. The1052 * data will not be freed as long as the reference count is1053 * nonzero.1054 */1055unsigned int referrers;10561057/*1058 * Iff the packed-refs file associated with this instance is1059 * currently locked for writing, this points at the associated1060 * lock (which is owned by somebody else). The referrer count1061 * is also incremented when the file is locked and decremented1062 * when it is unlocked.1063 */1064struct lock_file *lock;10651066/* The metadata from when this packed-refs cache was read */1067struct stat_validity validity;1068};10691070/*1071 * Future: need to be in "struct repository"1072 * when doing a full libification.1073 */1074static struct ref_cache {1075struct ref_cache *next;1076struct ref_entry *loose;1077struct packed_ref_cache *packed;1078/*1079 * The submodule name, or "" for the main repo. We allocate1080 * length 1 rather than FLEX_ARRAY so that the main ref_cache1081 * is initialized correctly.1082 */1083char name[1];1084} ref_cache, *submodule_ref_caches;10851086/* Lock used for the main packed-refs file: */1087static struct lock_file packlock;10881089/*1090 * Increment the reference count of *packed_refs.1091 */1092static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1093{1094 packed_refs->referrers++;1095}10961097/*1098 * Decrease the reference count of *packed_refs. If it goes to zero,1099 * free *packed_refs and return true; otherwise return false.1100 */1101static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1102{1103if(!--packed_refs->referrers) {1104free_ref_entry(packed_refs->root);1105stat_validity_clear(&packed_refs->validity);1106free(packed_refs);1107return1;1108}else{1109return0;1110}1111}11121113static voidclear_packed_ref_cache(struct ref_cache *refs)1114{1115if(refs->packed) {1116struct packed_ref_cache *packed_refs = refs->packed;11171118if(packed_refs->lock)1119die("internal error: packed-ref cache cleared while locked");1120 refs->packed = NULL;1121release_packed_ref_cache(packed_refs);1122}1123}11241125static voidclear_loose_ref_cache(struct ref_cache *refs)1126{1127if(refs->loose) {1128free_ref_entry(refs->loose);1129 refs->loose = NULL;1130}1131}11321133static struct ref_cache *create_ref_cache(const char*submodule)1134{1135int len;1136struct ref_cache *refs;1137if(!submodule)1138 submodule ="";1139 len =strlen(submodule) +1;1140 refs =xcalloc(1,sizeof(struct ref_cache) + len);1141memcpy(refs->name, submodule, len);1142return refs;1143}11441145/*1146 * Return a pointer to a ref_cache for the specified submodule. For1147 * the main repository, use submodule==NULL. The returned structure1148 * will be allocated and initialized but not necessarily populated; it1149 * should not be freed.1150 */1151static struct ref_cache *get_ref_cache(const char*submodule)1152{1153struct ref_cache *refs;11541155if(!submodule || !*submodule)1156return&ref_cache;11571158for(refs = submodule_ref_caches; refs; refs = refs->next)1159if(!strcmp(submodule, refs->name))1160return refs;11611162 refs =create_ref_cache(submodule);1163 refs->next = submodule_ref_caches;1164 submodule_ref_caches = refs;1165return refs;1166}11671168/* The length of a peeled reference line in packed-refs, including EOL: */1169#define PEELED_LINE_LENGTH 4211701171/*1172 * The packed-refs header line that we write out. Perhaps other1173 * traits will be added later. The trailing space is required.1174 */1175static const char PACKED_REFS_HEADER[] =1176"# pack-refs with: peeled fully-peeled\n";11771178/*1179 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1180 * Return a pointer to the refname within the line (null-terminated),1181 * or NULL if there was a problem.1182 */1183static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1184{1185const char*ref;11861187/*1188 * 42: the answer to everything.1189 *1190 * In this case, it happens to be the answer to1191 * 40 (length of sha1 hex representation)1192 * +1 (space in between hex and name)1193 * +1 (newline at the end of the line)1194 */1195if(line->len <=42)1196return NULL;11971198if(get_sha1_hex(line->buf, sha1) <0)1199return NULL;1200if(!isspace(line->buf[40]))1201return NULL;12021203 ref = line->buf +41;1204if(isspace(*ref))1205return NULL;12061207if(line->buf[line->len -1] !='\n')1208return NULL;1209 line->buf[--line->len] =0;12101211return ref;1212}12131214/*1215 * Read f, which is a packed-refs file, into dir.1216 *1217 * A comment line of the form "# pack-refs with: " may contain zero or1218 * more traits. We interpret the traits as follows:1219 *1220 * No traits:1221 *1222 * Probably no references are peeled. But if the file contains a1223 * peeled value for a reference, we will use it.1224 *1225 * peeled:1226 *1227 * References under "refs/tags/", if they *can* be peeled, *are*1228 * peeled in this file. References outside of "refs/tags/" are1229 * probably not peeled even if they could have been, but if we find1230 * a peeled value for such a reference we will use it.1231 *1232 * fully-peeled:1233 *1234 * All references in the file that can be peeled are peeled.1235 * Inversely (and this is more important), any references in the1236 * file for which no peeled value is recorded is not peelable. This1237 * trait should typically be written alongside "peeled" for1238 * compatibility with older clients, but we do not require it1239 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1240 */1241static voidread_packed_refs(FILE*f,struct ref_dir *dir)1242{1243struct ref_entry *last = NULL;1244struct strbuf line = STRBUF_INIT;1245enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12461247while(strbuf_getwholeline(&line, f,'\n') != EOF) {1248unsigned char sha1[20];1249const char*refname;1250const char*traits;12511252if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1253if(strstr(traits," fully-peeled "))1254 peeled = PEELED_FULLY;1255else if(strstr(traits," peeled "))1256 peeled = PEELED_TAGS;1257/* perhaps other traits later as well */1258continue;1259}12601261 refname =parse_ref_line(&line, sha1);1262if(refname) {1263int flag = REF_ISPACKED;12641265if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1266if(!refname_is_safe(refname))1267die("packed refname is dangerous:%s", refname);1268hashclr(sha1);1269 flag |= REF_BAD_NAME | REF_ISBROKEN;1270}1271 last =create_ref_entry(refname, sha1, flag,0);1272if(peeled == PEELED_FULLY ||1273(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1274 last->flag |= REF_KNOWS_PEELED;1275add_ref(dir, last);1276continue;1277}1278if(last &&1279 line.buf[0] =='^'&&1280 line.len == PEELED_LINE_LENGTH &&1281 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1282!get_sha1_hex(line.buf +1, sha1)) {1283hashcpy(last->u.value.peeled.hash, sha1);1284/*1285 * Regardless of what the file header said,1286 * we definitely know the value of *this*1287 * reference:1288 */1289 last->flag |= REF_KNOWS_PEELED;1290}1291}12921293strbuf_release(&line);1294}12951296/*1297 * Get the packed_ref_cache for the specified ref_cache, creating it1298 * if necessary.1299 */1300static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1301{1302char*packed_refs_file;13031304if(*refs->name)1305 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1306else1307 packed_refs_file =git_pathdup("packed-refs");13081309if(refs->packed &&1310!stat_validity_check(&refs->packed->validity, packed_refs_file))1311clear_packed_ref_cache(refs);13121313if(!refs->packed) {1314FILE*f;13151316 refs->packed =xcalloc(1,sizeof(*refs->packed));1317acquire_packed_ref_cache(refs->packed);1318 refs->packed->root =create_dir_entry(refs,"",0,0);1319 f =fopen(packed_refs_file,"r");1320if(f) {1321stat_validity_update(&refs->packed->validity,fileno(f));1322read_packed_refs(f,get_ref_dir(refs->packed->root));1323fclose(f);1324}1325}1326free(packed_refs_file);1327return refs->packed;1328}13291330static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1331{1332returnget_ref_dir(packed_ref_cache->root);1333}13341335static struct ref_dir *get_packed_refs(struct ref_cache *refs)1336{1337returnget_packed_ref_dir(get_packed_ref_cache(refs));1338}13391340/*1341 * Add a reference to the in-memory packed reference cache. This may1342 * only be called while the packed-refs file is locked (see1343 * lock_packed_refs()). To actually write the packed-refs file, call1344 * commit_packed_refs().1345 */1346static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1347{1348struct packed_ref_cache *packed_ref_cache =1349get_packed_ref_cache(&ref_cache);13501351if(!packed_ref_cache->lock)1352die("internal error: packed refs not locked");1353add_ref(get_packed_ref_dir(packed_ref_cache),1354create_ref_entry(refname, sha1, REF_ISPACKED,1));1355}13561357/*1358 * Read the loose references from the namespace dirname into dir1359 * (without recursing). dirname must end with '/'. dir must be the1360 * directory entry corresponding to dirname.1361 */1362static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1363{1364struct ref_cache *refs = dir->ref_cache;1365DIR*d;1366struct dirent *de;1367int dirnamelen =strlen(dirname);1368struct strbuf refname;1369struct strbuf path = STRBUF_INIT;1370size_t path_baselen;13711372if(*refs->name)1373strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1374else1375strbuf_git_path(&path,"%s", dirname);1376 path_baselen = path.len;13771378 d =opendir(path.buf);1379if(!d) {1380strbuf_release(&path);1381return;1382}13831384strbuf_init(&refname, dirnamelen +257);1385strbuf_add(&refname, dirname, dirnamelen);13861387while((de =readdir(d)) != NULL) {1388unsigned char sha1[20];1389struct stat st;1390int flag;13911392if(de->d_name[0] =='.')1393continue;1394if(ends_with(de->d_name,".lock"))1395continue;1396strbuf_addstr(&refname, de->d_name);1397strbuf_addstr(&path, de->d_name);1398if(stat(path.buf, &st) <0) {1399;/* silently ignore */1400}else if(S_ISDIR(st.st_mode)) {1401strbuf_addch(&refname,'/');1402add_entry_to_dir(dir,1403create_dir_entry(refs, refname.buf,1404 refname.len,1));1405}else{1406int read_ok;14071408if(*refs->name) {1409hashclr(sha1);1410 flag =0;1411 read_ok = !resolve_gitlink_ref(refs->name,1412 refname.buf, sha1);1413}else{1414 read_ok = !read_ref_full(refname.buf,1415 RESOLVE_REF_READING,1416 sha1, &flag);1417}14181419if(!read_ok) {1420hashclr(sha1);1421 flag |= REF_ISBROKEN;1422}else if(is_null_sha1(sha1)) {1423/*1424 * It is so astronomically unlikely1425 * that NULL_SHA1 is the SHA-1 of an1426 * actual object that we consider its1427 * appearance in a loose reference1428 * file to be repo corruption1429 * (probably due to a software bug).1430 */1431 flag |= REF_ISBROKEN;1432}14331434if(check_refname_format(refname.buf,1435 REFNAME_ALLOW_ONELEVEL)) {1436if(!refname_is_safe(refname.buf))1437die("loose refname is dangerous:%s", refname.buf);1438hashclr(sha1);1439 flag |= REF_BAD_NAME | REF_ISBROKEN;1440}1441add_entry_to_dir(dir,1442create_ref_entry(refname.buf, sha1, flag,0));1443}1444strbuf_setlen(&refname, dirnamelen);1445strbuf_setlen(&path, path_baselen);1446}1447strbuf_release(&refname);1448strbuf_release(&path);1449closedir(d);1450}14511452static struct ref_dir *get_loose_refs(struct ref_cache *refs)1453{1454if(!refs->loose) {1455/*1456 * Mark the top-level directory complete because we1457 * are about to read the only subdirectory that can1458 * hold references:1459 */1460 refs->loose =create_dir_entry(refs,"",0,0);1461/*1462 * Create an incomplete entry for "refs/":1463 */1464add_entry_to_dir(get_ref_dir(refs->loose),1465create_dir_entry(refs,"refs/",5,1));1466}1467returnget_ref_dir(refs->loose);1468}14691470/* We allow "recursive" symbolic refs. Only within reason, though */1471#define MAXDEPTH 51472#define MAXREFLEN (1024)14731474/*1475 * Called by resolve_gitlink_ref_recursive() after it failed to read1476 * from the loose refs in ref_cache refs. Find <refname> in the1477 * packed-refs file for the submodule.1478 */1479static intresolve_gitlink_packed_ref(struct ref_cache *refs,1480const char*refname,unsigned char*sha1)1481{1482struct ref_entry *ref;1483struct ref_dir *dir =get_packed_refs(refs);14841485 ref =find_ref(dir, refname);1486if(ref == NULL)1487return-1;14881489hashcpy(sha1, ref->u.value.oid.hash);1490return0;1491}14921493static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1494const char*refname,unsigned char*sha1,1495int recursion)1496{1497int fd, len;1498char buffer[128], *p;1499char*path;15001501if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1502return-1;1503 path = *refs->name1504?git_pathdup_submodule(refs->name,"%s", refname)1505:git_pathdup("%s", refname);1506 fd =open(path, O_RDONLY);1507free(path);1508if(fd <0)1509returnresolve_gitlink_packed_ref(refs, refname, sha1);15101511 len =read(fd, buffer,sizeof(buffer)-1);1512close(fd);1513if(len <0)1514return-1;1515while(len &&isspace(buffer[len-1]))1516 len--;1517 buffer[len] =0;15181519/* Was it a detached head or an old-fashioned symlink? */1520if(!get_sha1_hex(buffer, sha1))1521return0;15221523/* Symref? */1524if(strncmp(buffer,"ref:",4))1525return-1;1526 p = buffer +4;1527while(isspace(*p))1528 p++;15291530returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1531}15321533intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1534{1535int len =strlen(path), retval;1536char*submodule;1537struct ref_cache *refs;15381539while(len && path[len-1] =='/')1540 len--;1541if(!len)1542return-1;1543 submodule =xstrndup(path, len);1544 refs =get_ref_cache(submodule);1545free(submodule);15461547 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1548return retval;1549}15501551/*1552 * Return the ref_entry for the given refname from the packed1553 * references. If it does not exist, return NULL.1554 */1555static struct ref_entry *get_packed_ref(const char*refname)1556{1557returnfind_ref(get_packed_refs(&ref_cache), refname);1558}15591560/*1561 * A loose ref file doesn't exist; check for a packed ref. The1562 * options are forwarded from resolve_safe_unsafe().1563 */1564static intresolve_missing_loose_ref(const char*refname,1565int resolve_flags,1566unsigned char*sha1,1567int*flags)1568{1569struct ref_entry *entry;15701571/*1572 * The loose reference file does not exist; check for a packed1573 * reference.1574 */1575 entry =get_packed_ref(refname);1576if(entry) {1577hashcpy(sha1, entry->u.value.oid.hash);1578if(flags)1579*flags |= REF_ISPACKED;1580return0;1581}1582/* The reference is not a packed reference, either. */1583if(resolve_flags & RESOLVE_REF_READING) {1584 errno = ENOENT;1585return-1;1586}else{1587hashclr(sha1);1588return0;1589}1590}15911592/* This function needs to return a meaningful errno on failure */1593static const char*resolve_ref_1(const char*refname,1594int resolve_flags,1595unsigned char*sha1,1596int*flags,1597struct strbuf *sb_refname,1598struct strbuf *sb_path,1599struct strbuf *sb_contents)1600{1601int depth = MAXDEPTH;1602int bad_name =0;16031604if(flags)1605*flags =0;16061607if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1608if(flags)1609*flags |= REF_BAD_NAME;16101611if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1612!refname_is_safe(refname)) {1613 errno = EINVAL;1614return NULL;1615}1616/*1617 * dwim_ref() uses REF_ISBROKEN to distinguish between1618 * missing refs and refs that were present but invalid,1619 * to complain about the latter to stderr.1620 *1621 * We don't know whether the ref exists, so don't set1622 * REF_ISBROKEN yet.1623 */1624 bad_name =1;1625}1626for(;;) {1627const char*path;1628struct stat st;1629char*buf;1630int fd;16311632if(--depth <0) {1633 errno = ELOOP;1634return NULL;1635}16361637strbuf_reset(sb_path);1638strbuf_git_path(sb_path,"%s", refname);1639 path = sb_path->buf;16401641/*1642 * We might have to loop back here to avoid a race1643 * condition: first we lstat() the file, then we try1644 * to read it as a link or as a file. But if somebody1645 * changes the type of the file (file <-> directory1646 * <-> symlink) between the lstat() and reading, then1647 * we don't want to report that as an error but rather1648 * try again starting with the lstat().1649 */1650 stat_ref:1651if(lstat(path, &st) <0) {1652if(errno != ENOENT)1653return NULL;1654if(resolve_missing_loose_ref(refname, resolve_flags,1655 sha1, flags))1656return NULL;1657if(bad_name) {1658hashclr(sha1);1659if(flags)1660*flags |= REF_ISBROKEN;1661}1662return refname;1663}16641665/* Follow "normalized" - ie "refs/.." symlinks by hand */1666if(S_ISLNK(st.st_mode)) {1667strbuf_reset(sb_contents);1668if(strbuf_readlink(sb_contents, path,0) <0) {1669if(errno == ENOENT || errno == EINVAL)1670/* inconsistent with lstat; retry */1671goto stat_ref;1672else1673return NULL;1674}1675if(starts_with(sb_contents->buf,"refs/") &&1676!check_refname_format(sb_contents->buf,0)) {1677strbuf_swap(sb_refname, sb_contents);1678 refname = sb_refname->buf;1679if(flags)1680*flags |= REF_ISSYMREF;1681if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1682hashclr(sha1);1683return refname;1684}1685continue;1686}1687}16881689/* Is it a directory? */1690if(S_ISDIR(st.st_mode)) {1691 errno = EISDIR;1692return NULL;1693}16941695/*1696 * Anything else, just open it and try to use it as1697 * a ref1698 */1699 fd =open(path, O_RDONLY);1700if(fd <0) {1701if(errno == ENOENT)1702/* inconsistent with lstat; retry */1703goto stat_ref;1704else1705return NULL;1706}1707strbuf_reset(sb_contents);1708if(strbuf_read(sb_contents, fd,256) <0) {1709int save_errno = errno;1710close(fd);1711 errno = save_errno;1712return NULL;1713}1714close(fd);1715strbuf_rtrim(sb_contents);17161717/*1718 * Is it a symbolic ref?1719 */1720if(!starts_with(sb_contents->buf,"ref:")) {1721/*1722 * Please note that FETCH_HEAD has a second1723 * line containing other data.1724 */1725if(get_sha1_hex(sb_contents->buf, sha1) ||1726(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1727if(flags)1728*flags |= REF_ISBROKEN;1729 errno = EINVAL;1730return NULL;1731}1732if(bad_name) {1733hashclr(sha1);1734if(flags)1735*flags |= REF_ISBROKEN;1736}1737return refname;1738}1739if(flags)1740*flags |= REF_ISSYMREF;1741 buf = sb_contents->buf +4;1742while(isspace(*buf))1743 buf++;1744strbuf_reset(sb_refname);1745strbuf_addstr(sb_refname, buf);1746 refname = sb_refname->buf;1747if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1748hashclr(sha1);1749return refname;1750}1751if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1752if(flags)1753*flags |= REF_ISBROKEN;17541755if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1756!refname_is_safe(buf)) {1757 errno = EINVAL;1758return NULL;1759}1760 bad_name =1;1761}1762}1763}17641765const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1766unsigned char*sha1,int*flags)1767{1768static struct strbuf sb_refname = STRBUF_INIT;1769struct strbuf sb_contents = STRBUF_INIT;1770struct strbuf sb_path = STRBUF_INIT;1771const char*ret;17721773 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1774&sb_refname, &sb_path, &sb_contents);1775strbuf_release(&sb_path);1776strbuf_release(&sb_contents);1777return ret;1778}17791780char*resolve_refdup(const char*refname,int resolve_flags,1781unsigned char*sha1,int*flags)1782{1783returnxstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1784 sha1, flags));1785}17861787/* The argument to filter_refs */1788struct ref_filter {1789const char*pattern;1790 each_ref_fn *fn;1791void*cb_data;1792};17931794intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1795{1796if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1797return0;1798return-1;1799}18001801intread_ref(const char*refname,unsigned char*sha1)1802{1803returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1804}18051806intref_exists(const char*refname)1807{1808unsigned char sha1[20];1809return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1810}18111812static intfilter_refs(const char*refname,const struct object_id *oid,1813int flags,void*data)1814{1815struct ref_filter *filter = (struct ref_filter *)data;18161817if(wildmatch(filter->pattern, refname,0, NULL))1818return0;1819return filter->fn(refname, oid, flags, filter->cb_data);1820}18211822enum peel_status {1823/* object was peeled successfully: */1824 PEEL_PEELED =0,18251826/*1827 * object cannot be peeled because the named object (or an1828 * object referred to by a tag in the peel chain), does not1829 * exist.1830 */1831 PEEL_INVALID = -1,18321833/* object cannot be peeled because it is not a tag: */1834 PEEL_NON_TAG = -2,18351836/* ref_entry contains no peeled value because it is a symref: */1837 PEEL_IS_SYMREF = -3,18381839/*1840 * ref_entry cannot be peeled because it is broken (i.e., the1841 * symbolic reference cannot even be resolved to an object1842 * name):1843 */1844 PEEL_BROKEN = -41845};18461847/*1848 * Peel the named object; i.e., if the object is a tag, resolve the1849 * tag recursively until a non-tag is found. If successful, store the1850 * result to sha1 and return PEEL_PEELED. If the object is not a tag1851 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1852 * and leave sha1 unchanged.1853 */1854static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1855{1856struct object *o =lookup_unknown_object(name);18571858if(o->type == OBJ_NONE) {1859int type =sha1_object_info(name, NULL);1860if(type <0|| !object_as_type(o, type,0))1861return PEEL_INVALID;1862}18631864if(o->type != OBJ_TAG)1865return PEEL_NON_TAG;18661867 o =deref_tag_noverify(o);1868if(!o)1869return PEEL_INVALID;18701871hashcpy(sha1, o->sha1);1872return PEEL_PEELED;1873}18741875/*1876 * Peel the entry (if possible) and return its new peel_status. If1877 * repeel is true, re-peel the entry even if there is an old peeled1878 * value that is already stored in it.1879 *1880 * It is OK to call this function with a packed reference entry that1881 * might be stale and might even refer to an object that has since1882 * been garbage-collected. In such a case, if the entry has1883 * REF_KNOWS_PEELED then leave the status unchanged and return1884 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1885 */1886static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1887{1888enum peel_status status;18891890if(entry->flag & REF_KNOWS_PEELED) {1891if(repeel) {1892 entry->flag &= ~REF_KNOWS_PEELED;1893oidclr(&entry->u.value.peeled);1894}else{1895returnis_null_oid(&entry->u.value.peeled) ?1896 PEEL_NON_TAG : PEEL_PEELED;1897}1898}1899if(entry->flag & REF_ISBROKEN)1900return PEEL_BROKEN;1901if(entry->flag & REF_ISSYMREF)1902return PEEL_IS_SYMREF;19031904 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1905if(status == PEEL_PEELED || status == PEEL_NON_TAG)1906 entry->flag |= REF_KNOWS_PEELED;1907return status;1908}19091910intpeel_ref(const char*refname,unsigned char*sha1)1911{1912int flag;1913unsigned char base[20];19141915if(current_ref && (current_ref->name == refname1916|| !strcmp(current_ref->name, refname))) {1917if(peel_entry(current_ref,0))1918return-1;1919hashcpy(sha1, current_ref->u.value.peeled.hash);1920return0;1921}19221923if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1924return-1;19251926/*1927 * If the reference is packed, read its ref_entry from the1928 * cache in the hope that we already know its peeled value.1929 * We only try this optimization on packed references because1930 * (a) forcing the filling of the loose reference cache could1931 * be expensive and (b) loose references anyway usually do not1932 * have REF_KNOWS_PEELED.1933 */1934if(flag & REF_ISPACKED) {1935struct ref_entry *r =get_packed_ref(refname);1936if(r) {1937if(peel_entry(r,0))1938return-1;1939hashcpy(sha1, r->u.value.peeled.hash);1940return0;1941}1942}19431944returnpeel_object(base, sha1);1945}19461947struct warn_if_dangling_data {1948FILE*fp;1949const char*refname;1950const struct string_list *refnames;1951const char*msg_fmt;1952};19531954static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1955int flags,void*cb_data)1956{1957struct warn_if_dangling_data *d = cb_data;1958const char*resolves_to;1959struct object_id junk;19601961if(!(flags & REF_ISSYMREF))1962return0;19631964 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1965if(!resolves_to1966|| (d->refname1967?strcmp(resolves_to, d->refname)1968: !string_list_has_string(d->refnames, resolves_to))) {1969return0;1970}19711972fprintf(d->fp, d->msg_fmt, refname);1973fputc('\n', d->fp);1974return0;1975}19761977voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1978{1979struct warn_if_dangling_data data;19801981 data.fp = fp;1982 data.refname = refname;1983 data.refnames = NULL;1984 data.msg_fmt = msg_fmt;1985for_each_rawref(warn_if_dangling_symref, &data);1986}19871988voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1989{1990struct warn_if_dangling_data data;19911992 data.fp = fp;1993 data.refname = NULL;1994 data.refnames = refnames;1995 data.msg_fmt = msg_fmt;1996for_each_rawref(warn_if_dangling_symref, &data);1997}19981999/*2000 * Call fn for each reference in the specified ref_cache, omitting2001 * references not in the containing_dir of base. fn is called for all2002 * references, including broken ones. If fn ever returns a non-zero2003 * value, stop the iteration and return that value; otherwise, return2004 * 0.2005 */2006static intdo_for_each_entry(struct ref_cache *refs,const char*base,2007 each_ref_entry_fn fn,void*cb_data)2008{2009struct packed_ref_cache *packed_ref_cache;2010struct ref_dir *loose_dir;2011struct ref_dir *packed_dir;2012int retval =0;20132014/*2015 * We must make sure that all loose refs are read before accessing the2016 * packed-refs file; this avoids a race condition in which loose refs2017 * are migrated to the packed-refs file by a simultaneous process, but2018 * our in-memory view is from before the migration. get_packed_ref_cache()2019 * takes care of making sure our view is up to date with what is on2020 * disk.2021 */2022 loose_dir =get_loose_refs(refs);2023if(base && *base) {2024 loose_dir =find_containing_dir(loose_dir, base,0);2025}2026if(loose_dir)2027prime_ref_dir(loose_dir);20282029 packed_ref_cache =get_packed_ref_cache(refs);2030acquire_packed_ref_cache(packed_ref_cache);2031 packed_dir =get_packed_ref_dir(packed_ref_cache);2032if(base && *base) {2033 packed_dir =find_containing_dir(packed_dir, base,0);2034}20352036if(packed_dir && loose_dir) {2037sort_ref_dir(packed_dir);2038sort_ref_dir(loose_dir);2039 retval =do_for_each_entry_in_dirs(2040 packed_dir, loose_dir, fn, cb_data);2041}else if(packed_dir) {2042sort_ref_dir(packed_dir);2043 retval =do_for_each_entry_in_dir(2044 packed_dir,0, fn, cb_data);2045}else if(loose_dir) {2046sort_ref_dir(loose_dir);2047 retval =do_for_each_entry_in_dir(2048 loose_dir,0, fn, cb_data);2049}20502051release_packed_ref_cache(packed_ref_cache);2052return retval;2053}20542055/*2056 * Call fn for each reference in the specified ref_cache for which the2057 * refname begins with base. If trim is non-zero, then trim that many2058 * characters off the beginning of each refname before passing the2059 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2060 * broken references in the iteration. If fn ever returns a non-zero2061 * value, stop the iteration and return that value; otherwise, return2062 * 0.2063 */2064static intdo_for_each_ref(struct ref_cache *refs,const char*base,2065 each_ref_fn fn,int trim,int flags,void*cb_data)2066{2067struct ref_entry_cb data;2068 data.base = base;2069 data.trim = trim;2070 data.flags = flags;2071 data.fn = fn;2072 data.cb_data = cb_data;20732074if(ref_paranoia <0)2075 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2076if(ref_paranoia)2077 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20782079returndo_for_each_entry(refs, base, do_one_ref, &data);2080}20812082static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2083{2084struct object_id oid;2085int flag;20862087if(submodule) {2088if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2089returnfn("HEAD", &oid,0, cb_data);20902091return0;2092}20932094if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2095returnfn("HEAD", &oid, flag, cb_data);20962097return0;2098}20992100inthead_ref(each_ref_fn fn,void*cb_data)2101{2102returndo_head_ref(NULL, fn, cb_data);2103}21042105inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2106{2107returndo_head_ref(submodule, fn, cb_data);2108}21092110intfor_each_ref(each_ref_fn fn,void*cb_data)2111{2112returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2113}21142115intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2116{2117returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2118}21192120intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2121{2122returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2123}21242125intfor_each_fullref_in(const char*prefix, each_ref_fn fn,void*cb_data,unsigned int broken)2126{2127unsigned int flag =0;21282129if(broken)2130 flag = DO_FOR_EACH_INCLUDE_BROKEN;2131returndo_for_each_ref(&ref_cache, prefix, fn,0, flag, cb_data);2132}21332134intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2135 each_ref_fn fn,void*cb_data)2136{2137returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2138}21392140intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2141{2142returnfor_each_ref_in("refs/tags/", fn, cb_data);2143}21442145intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2146{2147returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2148}21492150intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2151{2152returnfor_each_ref_in("refs/heads/", fn, cb_data);2153}21542155intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2156{2157returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2158}21592160intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2161{2162returnfor_each_ref_in("refs/remotes/", fn, cb_data);2163}21642165intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2166{2167returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2168}21692170intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2171{2172returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,2173strlen(git_replace_ref_base),0, cb_data);2174}21752176inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2177{2178struct strbuf buf = STRBUF_INIT;2179int ret =0;2180struct object_id oid;2181int flag;21822183strbuf_addf(&buf,"%sHEAD",get_git_namespace());2184if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2185 ret =fn(buf.buf, &oid, flag, cb_data);2186strbuf_release(&buf);21872188return ret;2189}21902191intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2192{2193struct strbuf buf = STRBUF_INIT;2194int ret;2195strbuf_addf(&buf,"%srefs/",get_git_namespace());2196 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2197strbuf_release(&buf);2198return ret;2199}22002201intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2202const char*prefix,void*cb_data)2203{2204struct strbuf real_pattern = STRBUF_INIT;2205struct ref_filter filter;2206int ret;22072208if(!prefix && !starts_with(pattern,"refs/"))2209strbuf_addstr(&real_pattern,"refs/");2210else if(prefix)2211strbuf_addstr(&real_pattern, prefix);2212strbuf_addstr(&real_pattern, pattern);22132214if(!has_glob_specials(pattern)) {2215/* Append implied '/' '*' if not present. */2216strbuf_complete(&real_pattern,'/');2217/* No need to check for '*', there is none. */2218strbuf_addch(&real_pattern,'*');2219}22202221 filter.pattern = real_pattern.buf;2222 filter.fn = fn;2223 filter.cb_data = cb_data;2224 ret =for_each_ref(filter_refs, &filter);22252226strbuf_release(&real_pattern);2227return ret;2228}22292230intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2231{2232returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2233}22342235intfor_each_rawref(each_ref_fn fn,void*cb_data)2236{2237returndo_for_each_ref(&ref_cache,"", fn,0,2238 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2239}22402241const char*prettify_refname(const char*name)2242{2243return name + (2244starts_with(name,"refs/heads/") ?11:2245starts_with(name,"refs/tags/") ?10:2246starts_with(name,"refs/remotes/") ?13:22470);2248}22492250static const char*ref_rev_parse_rules[] = {2251"%.*s",2252"refs/%.*s",2253"refs/tags/%.*s",2254"refs/heads/%.*s",2255"refs/remotes/%.*s",2256"refs/remotes/%.*s/HEAD",2257 NULL2258};22592260intrefname_match(const char*abbrev_name,const char*full_name)2261{2262const char**p;2263const int abbrev_name_len =strlen(abbrev_name);22642265for(p = ref_rev_parse_rules; *p; p++) {2266if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2267return1;2268}2269}22702271return0;2272}22732274static voidunlock_ref(struct ref_lock *lock)2275{2276/* Do not free lock->lk -- atexit() still looks at them */2277if(lock->lk)2278rollback_lock_file(lock->lk);2279free(lock->ref_name);2280free(lock->orig_ref_name);2281free(lock);2282}22832284/*2285 * Verify that the reference locked by lock has the value old_sha1.2286 * Fail if the reference doesn't exist and mustexist is set. Return 02287 * on success. On error, write an error message to err, set errno, and2288 * return a negative value.2289 */2290static intverify_lock(struct ref_lock *lock,2291const unsigned char*old_sha1,int mustexist,2292struct strbuf *err)2293{2294assert(err);22952296if(read_ref_full(lock->ref_name,2297 mustexist ? RESOLVE_REF_READING :0,2298 lock->old_oid.hash, NULL)) {2299int save_errno = errno;2300strbuf_addf(err,"can't verify ref%s", lock->ref_name);2301 errno = save_errno;2302return-1;2303}2304if(hashcmp(lock->old_oid.hash, old_sha1)) {2305strbuf_addf(err,"ref%sis at%sbut expected%s",2306 lock->ref_name,2307sha1_to_hex(lock->old_oid.hash),2308sha1_to_hex(old_sha1));2309 errno = EBUSY;2310return-1;2311}2312return0;2313}23142315static intremove_empty_directories(struct strbuf *path)2316{2317/*2318 * we want to create a file but there is a directory there;2319 * if that is an empty directory (or a directory that contains2320 * only empty directories), remove them.2321 */2322returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);2323}23242325/*2326 * *string and *len will only be substituted, and *string returned (for2327 * later free()ing) if the string passed in is a magic short-hand form2328 * to name a branch.2329 */2330static char*substitute_branch_name(const char**string,int*len)2331{2332struct strbuf buf = STRBUF_INIT;2333int ret =interpret_branch_name(*string, *len, &buf);23342335if(ret == *len) {2336size_t size;2337*string =strbuf_detach(&buf, &size);2338*len = size;2339return(char*)*string;2340}23412342return NULL;2343}23442345intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2346{2347char*last_branch =substitute_branch_name(&str, &len);2348const char**p, *r;2349int refs_found =0;23502351*ref = NULL;2352for(p = ref_rev_parse_rules; *p; p++) {2353char fullref[PATH_MAX];2354unsigned char sha1_from_ref[20];2355unsigned char*this_result;2356int flag;23572358 this_result = refs_found ? sha1_from_ref : sha1;2359mksnpath(fullref,sizeof(fullref), *p, len, str);2360 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2361 this_result, &flag);2362if(r) {2363if(!refs_found++)2364*ref =xstrdup(r);2365if(!warn_ambiguous_refs)2366break;2367}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2368warning("ignoring dangling symref%s.", fullref);2369}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2370warning("ignoring broken ref%s.", fullref);2371}2372}2373free(last_branch);2374return refs_found;2375}23762377intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2378{2379char*last_branch =substitute_branch_name(&str, &len);2380const char**p;2381int logs_found =0;23822383*log = NULL;2384for(p = ref_rev_parse_rules; *p; p++) {2385unsigned char hash[20];2386char path[PATH_MAX];2387const char*ref, *it;23882389mksnpath(path,sizeof(path), *p, len, str);2390 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2391 hash, NULL);2392if(!ref)2393continue;2394if(reflog_exists(path))2395 it = path;2396else if(strcmp(ref, path) &&reflog_exists(ref))2397 it = ref;2398else2399continue;2400if(!logs_found++) {2401*log =xstrdup(it);2402hashcpy(sha1, hash);2403}2404if(!warn_ambiguous_refs)2405break;2406}2407free(last_branch);2408return logs_found;2409}24102411/*2412 * Locks a ref returning the lock on success and NULL on failure.2413 * On failure errno is set to something meaningful.2414 */2415static struct ref_lock *lock_ref_sha1_basic(const char*refname,2416const unsigned char*old_sha1,2417const struct string_list *extras,2418const struct string_list *skip,2419unsigned int flags,int*type_p,2420struct strbuf *err)2421{2422struct strbuf ref_file = STRBUF_INIT;2423struct strbuf orig_ref_file = STRBUF_INIT;2424const char*orig_refname = refname;2425struct ref_lock *lock;2426int last_errno =0;2427int type, lflags;2428int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2429int resolve_flags =0;2430int attempts_remaining =3;24312432assert(err);24332434 lock =xcalloc(1,sizeof(struct ref_lock));24352436if(mustexist)2437 resolve_flags |= RESOLVE_REF_READING;2438if(flags & REF_DELETING) {2439 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2440if(flags & REF_NODEREF)2441 resolve_flags |= RESOLVE_REF_NO_RECURSE;2442}24432444 refname =resolve_ref_unsafe(refname, resolve_flags,2445 lock->old_oid.hash, &type);2446if(!refname && errno == EISDIR) {2447/*2448 * we are trying to lock foo but we used to2449 * have foo/bar which now does not exist;2450 * it is normal for the empty directory 'foo'2451 * to remain.2452 */2453strbuf_git_path(&orig_ref_file,"%s", orig_refname);2454if(remove_empty_directories(&orig_ref_file)) {2455 last_errno = errno;2456if(!verify_refname_available_dir(orig_refname, extras, skip,2457get_loose_refs(&ref_cache), err))2458strbuf_addf(err,"there are still refs under '%s'",2459 orig_refname);2460goto error_return;2461}2462 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2463 lock->old_oid.hash, &type);2464}2465if(type_p)2466*type_p = type;2467if(!refname) {2468 last_errno = errno;2469if(last_errno != ENOTDIR ||2470!verify_refname_available_dir(orig_refname, extras, skip,2471get_loose_refs(&ref_cache), err))2472strbuf_addf(err,"unable to resolve reference%s:%s",2473 orig_refname,strerror(last_errno));24742475goto error_return;2476}2477/*2478 * If the ref did not exist and we are creating it, make sure2479 * there is no existing packed ref whose name begins with our2480 * refname, nor a packed ref whose name is a proper prefix of2481 * our refname.2482 */2483if(is_null_oid(&lock->old_oid) &&2484verify_refname_available_dir(refname, extras, skip,2485get_packed_refs(&ref_cache), err)) {2486 last_errno = ENOTDIR;2487goto error_return;2488}24892490 lock->lk =xcalloc(1,sizeof(struct lock_file));24912492 lflags =0;2493if(flags & REF_NODEREF) {2494 refname = orig_refname;2495 lflags |= LOCK_NO_DEREF;2496}2497 lock->ref_name =xstrdup(refname);2498 lock->orig_ref_name =xstrdup(orig_refname);2499strbuf_git_path(&ref_file,"%s", refname);25002501 retry:2502switch(safe_create_leading_directories_const(ref_file.buf)) {2503case SCLD_OK:2504break;/* success */2505case SCLD_VANISHED:2506if(--attempts_remaining >0)2507goto retry;2508/* fall through */2509default:2510 last_errno = errno;2511strbuf_addf(err,"unable to create directory for%s",2512 ref_file.buf);2513goto error_return;2514}25152516if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2517 last_errno = errno;2518if(errno == ENOENT && --attempts_remaining >0)2519/*2520 * Maybe somebody just deleted one of the2521 * directories leading to ref_file. Try2522 * again:2523 */2524goto retry;2525else{2526unable_to_lock_message(ref_file.buf, errno, err);2527goto error_return;2528}2529}2530if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2531 last_errno = errno;2532goto error_return;2533}2534goto out;25352536 error_return:2537unlock_ref(lock);2538 lock = NULL;25392540 out:2541strbuf_release(&ref_file);2542strbuf_release(&orig_ref_file);2543 errno = last_errno;2544return lock;2545}25462547/*2548 * Write an entry to the packed-refs file for the specified refname.2549 * If peeled is non-NULL, write it as the entry's peeled value.2550 */2551static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2552unsigned char*peeled)2553{2554fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2555if(peeled)2556fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2557}25582559/*2560 * An each_ref_entry_fn that writes the entry to a packed-refs file.2561 */2562static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2563{2564enum peel_status peel_status =peel_entry(entry,0);25652566if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2567error("internal error:%sis not a valid packed reference!",2568 entry->name);2569write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2570 peel_status == PEEL_PEELED ?2571 entry->u.value.peeled.hash : NULL);2572return0;2573}25742575/*2576 * Lock the packed-refs file for writing. Flags is passed to2577 * hold_lock_file_for_update(). Return 0 on success. On errors, set2578 * errno appropriately and return a nonzero value.2579 */2580static intlock_packed_refs(int flags)2581{2582static int timeout_configured =0;2583static int timeout_value =1000;25842585struct packed_ref_cache *packed_ref_cache;25862587if(!timeout_configured) {2588git_config_get_int("core.packedrefstimeout", &timeout_value);2589 timeout_configured =1;2590}25912592if(hold_lock_file_for_update_timeout(2593&packlock,git_path("packed-refs"),2594 flags, timeout_value) <0)2595return-1;2596/*2597 * Get the current packed-refs while holding the lock. If the2598 * packed-refs file has been modified since we last read it,2599 * this will automatically invalidate the cache and re-read2600 * the packed-refs file.2601 */2602 packed_ref_cache =get_packed_ref_cache(&ref_cache);2603 packed_ref_cache->lock = &packlock;2604/* Increment the reference count to prevent it from being freed: */2605acquire_packed_ref_cache(packed_ref_cache);2606return0;2607}26082609/*2610 * Write the current version of the packed refs cache from memory to2611 * disk. The packed-refs file must already be locked for writing (see2612 * lock_packed_refs()). Return zero on success. On errors, set errno2613 * and return a nonzero value2614 */2615static intcommit_packed_refs(void)2616{2617struct packed_ref_cache *packed_ref_cache =2618get_packed_ref_cache(&ref_cache);2619int error =0;2620int save_errno =0;2621FILE*out;26222623if(!packed_ref_cache->lock)2624die("internal error: packed-refs not locked");26252626 out =fdopen_lock_file(packed_ref_cache->lock,"w");2627if(!out)2628die_errno("unable to fdopen packed-refs descriptor");26292630fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2631do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),26320, write_packed_entry_fn, out);26332634if(commit_lock_file(packed_ref_cache->lock)) {2635 save_errno = errno;2636 error = -1;2637}2638 packed_ref_cache->lock = NULL;2639release_packed_ref_cache(packed_ref_cache);2640 errno = save_errno;2641return error;2642}26432644/*2645 * Rollback the lockfile for the packed-refs file, and discard the2646 * in-memory packed reference cache. (The packed-refs file will be2647 * read anew if it is needed again after this function is called.)2648 */2649static voidrollback_packed_refs(void)2650{2651struct packed_ref_cache *packed_ref_cache =2652get_packed_ref_cache(&ref_cache);26532654if(!packed_ref_cache->lock)2655die("internal error: packed-refs not locked");2656rollback_lock_file(packed_ref_cache->lock);2657 packed_ref_cache->lock = NULL;2658release_packed_ref_cache(packed_ref_cache);2659clear_packed_ref_cache(&ref_cache);2660}26612662struct ref_to_prune {2663struct ref_to_prune *next;2664unsigned char sha1[20];2665char name[FLEX_ARRAY];2666};26672668struct pack_refs_cb_data {2669unsigned int flags;2670struct ref_dir *packed_refs;2671struct ref_to_prune *ref_to_prune;2672};26732674static intis_per_worktree_ref(const char*refname);26752676/*2677 * An each_ref_entry_fn that is run over loose references only. If2678 * the loose reference can be packed, add an entry in the packed ref2679 * cache. If the reference should be pruned, also add it to2680 * ref_to_prune in the pack_refs_cb_data.2681 */2682static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2683{2684struct pack_refs_cb_data *cb = cb_data;2685enum peel_status peel_status;2686struct ref_entry *packed_entry;2687int is_tag_ref =starts_with(entry->name,"refs/tags/");26882689/* Do not pack per-worktree refs: */2690if(is_per_worktree_ref(entry->name))2691return0;26922693/* ALWAYS pack tags */2694if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2695return0;26962697/* Do not pack symbolic or broken refs: */2698if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2699return0;27002701/* Add a packed ref cache entry equivalent to the loose entry. */2702 peel_status =peel_entry(entry,1);2703if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2704die("internal error peeling reference%s(%s)",2705 entry->name,oid_to_hex(&entry->u.value.oid));2706 packed_entry =find_ref(cb->packed_refs, entry->name);2707if(packed_entry) {2708/* Overwrite existing packed entry with info from loose entry */2709 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2710oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2711}else{2712 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2713 REF_ISPACKED | REF_KNOWS_PEELED,0);2714add_ref(cb->packed_refs, packed_entry);2715}2716oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);27172718/* Schedule the loose reference for pruning if requested. */2719if((cb->flags & PACK_REFS_PRUNE)) {2720int namelen =strlen(entry->name) +1;2721struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2722hashcpy(n->sha1, entry->u.value.oid.hash);2723memcpy(n->name, entry->name, namelen);/* includes NUL */2724 n->next = cb->ref_to_prune;2725 cb->ref_to_prune = n;2726}2727return0;2728}27292730/*2731 * Remove empty parents, but spare refs/ and immediate subdirs.2732 * Note: munges *name.2733 */2734static voidtry_remove_empty_parents(char*name)2735{2736char*p, *q;2737int i;2738 p = name;2739for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2740while(*p && *p !='/')2741 p++;2742/* tolerate duplicate slashes; see check_refname_format() */2743while(*p =='/')2744 p++;2745}2746for(q = p; *q; q++)2747;2748while(1) {2749while(q > p && *q !='/')2750 q--;2751while(q > p && *(q-1) =='/')2752 q--;2753if(q == p)2754break;2755*q ='\0';2756if(rmdir(git_path("%s", name)))2757break;2758}2759}27602761/* make sure nobody touched the ref, and unlink */2762static voidprune_ref(struct ref_to_prune *r)2763{2764struct ref_transaction *transaction;2765struct strbuf err = STRBUF_INIT;27662767if(check_refname_format(r->name,0))2768return;27692770 transaction =ref_transaction_begin(&err);2771if(!transaction ||2772ref_transaction_delete(transaction, r->name, r->sha1,2773 REF_ISPRUNING, NULL, &err) ||2774ref_transaction_commit(transaction, &err)) {2775ref_transaction_free(transaction);2776error("%s", err.buf);2777strbuf_release(&err);2778return;2779}2780ref_transaction_free(transaction);2781strbuf_release(&err);2782try_remove_empty_parents(r->name);2783}27842785static voidprune_refs(struct ref_to_prune *r)2786{2787while(r) {2788prune_ref(r);2789 r = r->next;2790}2791}27922793intpack_refs(unsigned int flags)2794{2795struct pack_refs_cb_data cbdata;27962797memset(&cbdata,0,sizeof(cbdata));2798 cbdata.flags = flags;27992800lock_packed_refs(LOCK_DIE_ON_ERROR);2801 cbdata.packed_refs =get_packed_refs(&ref_cache);28022803do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2804 pack_if_possible_fn, &cbdata);28052806if(commit_packed_refs())2807die_errno("unable to overwrite old ref-pack file");28082809prune_refs(cbdata.ref_to_prune);2810return0;2811}28122813/*2814 * Rewrite the packed-refs file, omitting any refs listed in2815 * 'refnames'. On error, leave packed-refs unchanged, write an error2816 * message to 'err', and return a nonzero value.2817 *2818 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2819 */2820static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2821{2822struct ref_dir *packed;2823struct string_list_item *refname;2824int ret, needs_repacking =0, removed =0;28252826assert(err);28272828/* Look for a packed ref */2829for_each_string_list_item(refname, refnames) {2830if(get_packed_ref(refname->string)) {2831 needs_repacking =1;2832break;2833}2834}28352836/* Avoid locking if we have nothing to do */2837if(!needs_repacking)2838return0;/* no refname exists in packed refs */28392840if(lock_packed_refs(0)) {2841unable_to_lock_message(git_path("packed-refs"), errno, err);2842return-1;2843}2844 packed =get_packed_refs(&ref_cache);28452846/* Remove refnames from the cache */2847for_each_string_list_item(refname, refnames)2848if(remove_entry(packed, refname->string) != -1)2849 removed =1;2850if(!removed) {2851/*2852 * All packed entries disappeared while we were2853 * acquiring the lock.2854 */2855rollback_packed_refs();2856return0;2857}28582859/* Write what remains */2860 ret =commit_packed_refs();2861if(ret)2862strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2863strerror(errno));2864return ret;2865}28662867static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2868{2869assert(err);28702871if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2872/*2873 * loose. The loose file name is the same as the2874 * lockfile name, minus ".lock":2875 */2876char*loose_filename =get_locked_file_path(lock->lk);2877int res =unlink_or_msg(loose_filename, err);2878free(loose_filename);2879if(res)2880return1;2881}2882return0;2883}28842885static intis_per_worktree_ref(const char*refname)2886{2887return!strcmp(refname,"HEAD") ||2888starts_with(refname,"refs/bisect/");2889}28902891static intis_pseudoref_syntax(const char*refname)2892{2893const char*c;28942895for(c = refname; *c; c++) {2896if(!isupper(*c) && *c !='-'&& *c !='_')2897return0;2898}28992900return1;2901}29022903enum ref_type ref_type(const char*refname)2904{2905if(is_per_worktree_ref(refname))2906return REF_TYPE_PER_WORKTREE;2907if(is_pseudoref_syntax(refname))2908return REF_TYPE_PSEUDOREF;2909return REF_TYPE_NORMAL;2910}29112912static intwrite_pseudoref(const char*pseudoref,const unsigned char*sha1,2913const unsigned char*old_sha1,struct strbuf *err)2914{2915const char*filename;2916int fd;2917static struct lock_file lock;2918struct strbuf buf = STRBUF_INIT;2919int ret = -1;29202921strbuf_addf(&buf,"%s\n",sha1_to_hex(sha1));29222923 filename =git_path("%s", pseudoref);2924 fd =hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);2925if(fd <0) {2926strbuf_addf(err,"Could not open '%s' for writing:%s",2927 filename,strerror(errno));2928return-1;2929}29302931if(old_sha1) {2932unsigned char actual_old_sha1[20];29332934if(read_ref(pseudoref, actual_old_sha1))2935die("could not read ref '%s'", pseudoref);2936if(hashcmp(actual_old_sha1, old_sha1)) {2937strbuf_addf(err,"Unexpected sha1 when writing%s", pseudoref);2938rollback_lock_file(&lock);2939goto done;2940}2941}29422943if(write_in_full(fd, buf.buf, buf.len) != buf.len) {2944strbuf_addf(err,"Could not write to '%s'", filename);2945rollback_lock_file(&lock);2946goto done;2947}29482949commit_lock_file(&lock);2950 ret =0;2951done:2952strbuf_release(&buf);2953return ret;2954}29552956static intdelete_pseudoref(const char*pseudoref,const unsigned char*old_sha1)2957{2958static struct lock_file lock;2959const char*filename;29602961 filename =git_path("%s", pseudoref);29622963if(old_sha1 && !is_null_sha1(old_sha1)) {2964int fd;2965unsigned char actual_old_sha1[20];29662967 fd =hold_lock_file_for_update(&lock, filename,2968 LOCK_DIE_ON_ERROR);2969if(fd <0)2970die_errno(_("Could not open '%s' for writing"), filename);2971if(read_ref(pseudoref, actual_old_sha1))2972die("could not read ref '%s'", pseudoref);2973if(hashcmp(actual_old_sha1, old_sha1)) {2974warning("Unexpected sha1 when deleting%s", pseudoref);2975rollback_lock_file(&lock);2976return-1;2977}29782979unlink(filename);2980rollback_lock_file(&lock);2981}else{2982unlink(filename);2983}29842985return0;2986}29872988intdelete_ref(const char*refname,const unsigned char*old_sha1,2989unsigned int flags)2990{2991struct ref_transaction *transaction;2992struct strbuf err = STRBUF_INIT;29932994if(ref_type(refname) == REF_TYPE_PSEUDOREF)2995returndelete_pseudoref(refname, old_sha1);29962997 transaction =ref_transaction_begin(&err);2998if(!transaction ||2999ref_transaction_delete(transaction, refname, old_sha1,3000 flags, NULL, &err) ||3001ref_transaction_commit(transaction, &err)) {3002error("%s", err.buf);3003ref_transaction_free(transaction);3004strbuf_release(&err);3005return1;3006}3007ref_transaction_free(transaction);3008strbuf_release(&err);3009return0;3010}30113012intdelete_refs(struct string_list *refnames)3013{3014struct strbuf err = STRBUF_INIT;3015int i, result =0;30163017if(!refnames->nr)3018return0;30193020 result =repack_without_refs(refnames, &err);3021if(result) {3022/*3023 * If we failed to rewrite the packed-refs file, then3024 * it is unsafe to try to remove loose refs, because3025 * doing so might expose an obsolete packed value for3026 * a reference that might even point at an object that3027 * has been garbage collected.3028 */3029if(refnames->nr ==1)3030error(_("could not delete reference%s:%s"),3031 refnames->items[0].string, err.buf);3032else3033error(_("could not delete references:%s"), err.buf);30343035goto out;3036}30373038for(i =0; i < refnames->nr; i++) {3039const char*refname = refnames->items[i].string;30403041if(delete_ref(refname, NULL,0))3042 result |=error(_("could not remove reference%s"), refname);3043}30443045out:3046strbuf_release(&err);3047return result;3048}30493050/*3051 * People using contrib's git-new-workdir have .git/logs/refs ->3052 * /some/other/path/.git/logs/refs, and that may live on another device.3053 *3054 * IOW, to avoid cross device rename errors, the temporary renamed log must3055 * live into logs/refs.3056 */3057#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"30583059static intrename_tmp_log(const char*newrefname)3060{3061int attempts_remaining =4;3062struct strbuf path = STRBUF_INIT;3063int ret = -1;30643065 retry:3066strbuf_reset(&path);3067strbuf_git_path(&path,"logs/%s", newrefname);3068switch(safe_create_leading_directories_const(path.buf)) {3069case SCLD_OK:3070break;/* success */3071case SCLD_VANISHED:3072if(--attempts_remaining >0)3073goto retry;3074/* fall through */3075default:3076error("unable to create directory for%s", newrefname);3077goto out;3078}30793080if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {3081if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {3082/*3083 * rename(a, b) when b is an existing3084 * directory ought to result in ISDIR, but3085 * Solaris 5.8 gives ENOTDIR. Sheesh.3086 */3087if(remove_empty_directories(&path)) {3088error("Directory not empty: logs/%s", newrefname);3089goto out;3090}3091goto retry;3092}else if(errno == ENOENT && --attempts_remaining >0) {3093/*3094 * Maybe another process just deleted one of3095 * the directories in the path to newrefname.3096 * Try again from the beginning.3097 */3098goto retry;3099}else{3100error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",3101 newrefname,strerror(errno));3102goto out;3103}3104}3105 ret =0;3106out:3107strbuf_release(&path);3108return ret;3109}31103111/*3112 * Return 0 if a reference named refname could be created without3113 * conflicting with the name of an existing reference. Otherwise,3114 * return a negative value and write an explanation to err. If extras3115 * is non-NULL, it is a list of additional refnames with which refname3116 * is not allowed to conflict. If skip is non-NULL, ignore potential3117 * conflicts with refs in skip (e.g., because they are scheduled for3118 * deletion in the same operation). Behavior is undefined if the same3119 * name is listed in both extras and skip.3120 *3121 * Two reference names conflict if one of them exactly matches the3122 * leading components of the other; e.g., "foo/bar" conflicts with3123 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or3124 * "foo/barbados".3125 *3126 * extras and skip must be sorted.3127 */3128static intverify_refname_available(const char*newname,3129struct string_list *extras,3130struct string_list *skip,3131struct strbuf *err)3132{3133struct ref_dir *packed_refs =get_packed_refs(&ref_cache);3134struct ref_dir *loose_refs =get_loose_refs(&ref_cache);31353136if(verify_refname_available_dir(newname, extras, skip,3137 packed_refs, err) ||3138verify_refname_available_dir(newname, extras, skip,3139 loose_refs, err))3140return-1;31413142return0;3143}31443145static intrename_ref_available(const char*oldname,const char*newname)3146{3147struct string_list skip = STRING_LIST_INIT_NODUP;3148struct strbuf err = STRBUF_INIT;3149int ret;31503151string_list_insert(&skip, oldname);3152 ret = !verify_refname_available(newname, NULL, &skip, &err);3153if(!ret)3154error("%s", err.buf);31553156string_list_clear(&skip,0);3157strbuf_release(&err);3158return ret;3159}31603161static intwrite_ref_to_lockfile(struct ref_lock *lock,3162const unsigned char*sha1,struct strbuf *err);3163static intcommit_ref_update(struct ref_lock *lock,3164const unsigned char*sha1,const char*logmsg,3165int flags,struct strbuf *err);31663167intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)3168{3169unsigned char sha1[20], orig_sha1[20];3170int flag =0, logmoved =0;3171struct ref_lock *lock;3172struct stat loginfo;3173int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);3174const char*symref = NULL;3175struct strbuf err = STRBUF_INIT;31763177if(log &&S_ISLNK(loginfo.st_mode))3178returnerror("reflog for%sis a symlink", oldrefname);31793180 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3181 orig_sha1, &flag);3182if(flag & REF_ISSYMREF)3183returnerror("refname%sis a symbolic ref, renaming it is not supported",3184 oldrefname);3185if(!symref)3186returnerror("refname%snot found", oldrefname);31873188if(!rename_ref_available(oldrefname, newrefname))3189return1;31903191if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3192returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3193 oldrefname,strerror(errno));31943195if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3196error("unable to delete old%s", oldrefname);3197goto rollback;3198}31993200if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3201delete_ref(newrefname, sha1, REF_NODEREF)) {3202if(errno==EISDIR) {3203struct strbuf path = STRBUF_INIT;3204int result;32053206strbuf_git_path(&path,"%s", newrefname);3207 result =remove_empty_directories(&path);3208strbuf_release(&path);32093210if(result) {3211error("Directory not empty:%s", newrefname);3212goto rollback;3213}3214}else{3215error("unable to delete existing%s", newrefname);3216goto rollback;3217}3218}32193220if(log &&rename_tmp_log(newrefname))3221goto rollback;32223223 logmoved = log;32243225 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3226if(!lock) {3227error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3228strbuf_release(&err);3229goto rollback;3230}3231hashcpy(lock->old_oid.hash, orig_sha1);32323233if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3234commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {3235error("unable to write current sha1 into%s:%s", newrefname, err.buf);3236strbuf_release(&err);3237goto rollback;3238}32393240return0;32413242 rollback:3243 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3244if(!lock) {3245error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3246strbuf_release(&err);3247goto rollbacklog;3248}32493250 flag = log_all_ref_updates;3251 log_all_ref_updates =0;3252if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3253commit_ref_update(lock, orig_sha1, NULL,0, &err)) {3254error("unable to write current sha1 into%s:%s", oldrefname, err.buf);3255strbuf_release(&err);3256}3257 log_all_ref_updates = flag;32583259 rollbacklog:3260if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3261error("unable to restore logfile%sfrom%s:%s",3262 oldrefname, newrefname,strerror(errno));3263if(!logmoved && log &&3264rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3265error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3266 oldrefname,strerror(errno));32673268return1;3269}32703271static intclose_ref(struct ref_lock *lock)3272{3273if(close_lock_file(lock->lk))3274return-1;3275return0;3276}32773278static intcommit_ref(struct ref_lock *lock)3279{3280if(commit_lock_file(lock->lk))3281return-1;3282return0;3283}32843285/*3286 * copy the reflog message msg to buf, which has been allocated sufficiently3287 * large, while cleaning up the whitespaces. Especially, convert LF to space,3288 * because reflog file is one line per entry.3289 */3290static intcopy_reflog_msg(char*buf,const char*msg)3291{3292char*cp = buf;3293char c;3294int wasspace =1;32953296*cp++ ='\t';3297while((c = *msg++)) {3298if(wasspace &&isspace(c))3299continue;3300 wasspace =isspace(c);3301if(wasspace)3302 c =' ';3303*cp++ = c;3304}3305while(buf < cp &&isspace(cp[-1]))3306 cp--;3307*cp++ ='\n';3308return cp - buf;3309}33103311static intshould_autocreate_reflog(const char*refname)3312{3313if(!log_all_ref_updates)3314return0;3315returnstarts_with(refname,"refs/heads/") ||3316starts_with(refname,"refs/remotes/") ||3317starts_with(refname,"refs/notes/") ||3318!strcmp(refname,"HEAD");3319}33203321/*3322 * Create a reflog for a ref. If force_create = 0, the reflog will3323 * only be created for certain refs (those for which3324 * should_autocreate_reflog returns non-zero. Otherwise, create it3325 * regardless of the ref name. Fill in *err and return -1 on failure.3326 */3327static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)3328{3329int logfd, oflags = O_APPEND | O_WRONLY;33303331strbuf_git_path(logfile,"logs/%s", refname);3332if(force_create ||should_autocreate_reflog(refname)) {3333if(safe_create_leading_directories(logfile->buf) <0) {3334strbuf_addf(err,"unable to create directory for%s: "3335"%s", logfile->buf,strerror(errno));3336return-1;3337}3338 oflags |= O_CREAT;3339}33403341 logfd =open(logfile->buf, oflags,0666);3342if(logfd <0) {3343if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3344return0;33453346if(errno == EISDIR) {3347if(remove_empty_directories(logfile)) {3348strbuf_addf(err,"There are still logs under "3349"'%s'", logfile->buf);3350return-1;3351}3352 logfd =open(logfile->buf, oflags,0666);3353}33543355if(logfd <0) {3356strbuf_addf(err,"unable to append to%s:%s",3357 logfile->buf,strerror(errno));3358return-1;3359}3360}33613362adjust_shared_perm(logfile->buf);3363close(logfd);3364return0;3365}336633673368intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3369{3370int ret;3371struct strbuf sb = STRBUF_INIT;33723373 ret =log_ref_setup(refname, &sb, err, force_create);3374strbuf_release(&sb);3375return ret;3376}33773378static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3379const unsigned char*new_sha1,3380const char*committer,const char*msg)3381{3382int msglen, written;3383unsigned maxlen, len;3384char*logrec;33853386 msglen = msg ?strlen(msg) :0;3387 maxlen =strlen(committer) + msglen +100;3388 logrec =xmalloc(maxlen);3389 len =xsnprintf(logrec, maxlen,"%s %s %s\n",3390sha1_to_hex(old_sha1),3391sha1_to_hex(new_sha1),3392 committer);3393if(msglen)3394 len +=copy_reflog_msg(logrec + len -1, msg) -1;33953396 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3397free(logrec);3398if(written != len)3399return-1;34003401return0;3402}34033404static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3405const unsigned char*new_sha1,const char*msg,3406struct strbuf *logfile,int flags,3407struct strbuf *err)3408{3409int logfd, result, oflags = O_APPEND | O_WRONLY;34103411if(log_all_ref_updates <0)3412 log_all_ref_updates = !is_bare_repository();34133414 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);34153416if(result)3417return result;34183419 logfd =open(logfile->buf, oflags);3420if(logfd <0)3421return0;3422 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3423git_committer_info(0), msg);3424if(result) {3425strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3426strerror(errno));3427close(logfd);3428return-1;3429}3430if(close(logfd)) {3431strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3432strerror(errno));3433return-1;3434}3435return0;3436}34373438static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3439const unsigned char*new_sha1,const char*msg,3440int flags,struct strbuf *err)3441{3442struct strbuf sb = STRBUF_INIT;3443int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3444 err);3445strbuf_release(&sb);3446return ret;3447}34483449intis_branch(const char*refname)3450{3451return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3452}34533454/*3455 * Write sha1 into the open lockfile, then close the lockfile. On3456 * errors, rollback the lockfile, fill in *err and3457 * return -1.3458 */3459static intwrite_ref_to_lockfile(struct ref_lock *lock,3460const unsigned char*sha1,struct strbuf *err)3461{3462static char term ='\n';3463struct object *o;3464int fd;34653466 o =parse_object(sha1);3467if(!o) {3468strbuf_addf(err,3469"Trying to write ref%swith nonexistent object%s",3470 lock->ref_name,sha1_to_hex(sha1));3471unlock_ref(lock);3472return-1;3473}3474if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3475strbuf_addf(err,3476"Trying to write non-commit object%sto branch%s",3477sha1_to_hex(sha1), lock->ref_name);3478unlock_ref(lock);3479return-1;3480}3481 fd =get_lock_file_fd(lock->lk);3482if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||3483write_in_full(fd, &term,1) !=1||3484close_ref(lock) <0) {3485strbuf_addf(err,3486"Couldn't write%s",get_lock_file_path(lock->lk));3487unlock_ref(lock);3488return-1;3489}3490return0;3491}34923493/*3494 * Commit a change to a loose reference that has already been written3495 * to the loose reference lockfile. Also update the reflogs if3496 * necessary, using the specified lockmsg (which can be NULL).3497 */3498static intcommit_ref_update(struct ref_lock *lock,3499const unsigned char*sha1,const char*logmsg,3500int flags,struct strbuf *err)3501{3502clear_loose_ref_cache(&ref_cache);3503if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||3504(strcmp(lock->ref_name, lock->orig_ref_name) &&3505log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {3506char*old_msg =strbuf_detach(err, NULL);3507strbuf_addf(err,"Cannot update the ref '%s':%s",3508 lock->ref_name, old_msg);3509free(old_msg);3510unlock_ref(lock);3511return-1;3512}3513if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3514/*3515 * Special hack: If a branch is updated directly and HEAD3516 * points to it (may happen on the remote side of a push3517 * for example) then logically the HEAD reflog should be3518 * updated too.3519 * A generic solution implies reverse symref information,3520 * but finding all symrefs pointing to the given branch3521 * would be rather costly for this rare event (the direct3522 * update of a branch) to be worth it. So let's cheat and3523 * check with HEAD only which should cover 99% of all usage3524 * scenarios (even 100% of the default ones).3525 */3526unsigned char head_sha1[20];3527int head_flag;3528const char*head_ref;3529 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3530 head_sha1, &head_flag);3531if(head_ref && (head_flag & REF_ISSYMREF) &&3532!strcmp(head_ref, lock->ref_name)) {3533struct strbuf log_err = STRBUF_INIT;3534if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3535 logmsg,0, &log_err)) {3536error("%s", log_err.buf);3537strbuf_release(&log_err);3538}3539}3540}3541if(commit_ref(lock)) {3542error("Couldn't set%s", lock->ref_name);3543unlock_ref(lock);3544return-1;3545}35463547unlock_ref(lock);3548return0;3549}35503551intcreate_symref(const char*ref_target,const char*refs_heads_master,3552const char*logmsg)3553{3554char*lockpath = NULL;3555char ref[1000];3556int fd, len, written;3557char*git_HEAD =git_pathdup("%s", ref_target);3558unsigned char old_sha1[20], new_sha1[20];3559struct strbuf err = STRBUF_INIT;35603561if(logmsg &&read_ref(ref_target, old_sha1))3562hashclr(old_sha1);35633564if(safe_create_leading_directories(git_HEAD) <0)3565returnerror("unable to create directory for%s", git_HEAD);35663567#ifndef NO_SYMLINK_HEAD3568if(prefer_symlink_refs) {3569unlink(git_HEAD);3570if(!symlink(refs_heads_master, git_HEAD))3571goto done;3572fprintf(stderr,"no symlink - falling back to symbolic ref\n");3573}3574#endif35753576 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3577if(sizeof(ref) <= len) {3578error("refname too long:%s", refs_heads_master);3579goto error_free_return;3580}3581 lockpath =mkpathdup("%s.lock", git_HEAD);3582 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3583if(fd <0) {3584error("Unable to open%sfor writing", lockpath);3585goto error_free_return;3586}3587 written =write_in_full(fd, ref, len);3588if(close(fd) !=0|| written != len) {3589error("Unable to write to%s", lockpath);3590goto error_unlink_return;3591}3592if(rename(lockpath, git_HEAD) <0) {3593error("Unable to create%s", git_HEAD);3594goto error_unlink_return;3595}3596if(adjust_shared_perm(git_HEAD)) {3597error("Unable to fix permissions on%s", lockpath);3598 error_unlink_return:3599unlink_or_warn(lockpath);3600 error_free_return:3601free(lockpath);3602free(git_HEAD);3603return-1;3604}3605free(lockpath);36063607#ifndef NO_SYMLINK_HEAD3608 done:3609#endif3610if(logmsg && !read_ref(refs_heads_master, new_sha1) &&3611log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {3612error("%s", err.buf);3613strbuf_release(&err);3614}36153616free(git_HEAD);3617return0;3618}36193620struct read_ref_at_cb {3621const char*refname;3622unsigned long at_time;3623int cnt;3624int reccnt;3625unsigned char*sha1;3626int found_it;36273628unsigned char osha1[20];3629unsigned char nsha1[20];3630int tz;3631unsigned long date;3632char**msg;3633unsigned long*cutoff_time;3634int*cutoff_tz;3635int*cutoff_cnt;3636};36373638static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3639const char*email,unsigned long timestamp,int tz,3640const char*message,void*cb_data)3641{3642struct read_ref_at_cb *cb = cb_data;36433644 cb->reccnt++;3645 cb->tz = tz;3646 cb->date = timestamp;36473648if(timestamp <= cb->at_time || cb->cnt ==0) {3649if(cb->msg)3650*cb->msg =xstrdup(message);3651if(cb->cutoff_time)3652*cb->cutoff_time = timestamp;3653if(cb->cutoff_tz)3654*cb->cutoff_tz = tz;3655if(cb->cutoff_cnt)3656*cb->cutoff_cnt = cb->reccnt -1;3657/*3658 * we have not yet updated cb->[n|o]sha1 so they still3659 * hold the values for the previous record.3660 */3661if(!is_null_sha1(cb->osha1)) {3662hashcpy(cb->sha1, nsha1);3663if(hashcmp(cb->osha1, nsha1))3664warning("Log for ref%shas gap after%s.",3665 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3666}3667else if(cb->date == cb->at_time)3668hashcpy(cb->sha1, nsha1);3669else if(hashcmp(nsha1, cb->sha1))3670warning("Log for ref%sunexpectedly ended on%s.",3671 cb->refname,show_date(cb->date, cb->tz,3672DATE_MODE(RFC2822)));3673hashcpy(cb->osha1, osha1);3674hashcpy(cb->nsha1, nsha1);3675 cb->found_it =1;3676return1;3677}3678hashcpy(cb->osha1, osha1);3679hashcpy(cb->nsha1, nsha1);3680if(cb->cnt >0)3681 cb->cnt--;3682return0;3683}36843685static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3686const char*email,unsigned long timestamp,3687int tz,const char*message,void*cb_data)3688{3689struct read_ref_at_cb *cb = cb_data;36903691if(cb->msg)3692*cb->msg =xstrdup(message);3693if(cb->cutoff_time)3694*cb->cutoff_time = timestamp;3695if(cb->cutoff_tz)3696*cb->cutoff_tz = tz;3697if(cb->cutoff_cnt)3698*cb->cutoff_cnt = cb->reccnt;3699hashcpy(cb->sha1, osha1);3700if(is_null_sha1(cb->sha1))3701hashcpy(cb->sha1, nsha1);3702/* We just want the first entry */3703return1;3704}37053706intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3707unsigned char*sha1,char**msg,3708unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3709{3710struct read_ref_at_cb cb;37113712memset(&cb,0,sizeof(cb));3713 cb.refname = refname;3714 cb.at_time = at_time;3715 cb.cnt = cnt;3716 cb.msg = msg;3717 cb.cutoff_time = cutoff_time;3718 cb.cutoff_tz = cutoff_tz;3719 cb.cutoff_cnt = cutoff_cnt;3720 cb.sha1 = sha1;37213722for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);37233724if(!cb.reccnt) {3725if(flags & GET_SHA1_QUIETLY)3726exit(128);3727else3728die("Log for%sis empty.", refname);3729}3730if(cb.found_it)3731return0;37323733for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);37343735return1;3736}37373738intreflog_exists(const char*refname)3739{3740struct stat st;37413742return!lstat(git_path("logs/%s", refname), &st) &&3743S_ISREG(st.st_mode);3744}37453746intdelete_reflog(const char*refname)3747{3748returnremove_path(git_path("logs/%s", refname));3749}37503751static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3752{3753unsigned char osha1[20], nsha1[20];3754char*email_end, *message;3755unsigned long timestamp;3756int tz;37573758/* old SP new SP name <email> SP time TAB msg LF */3759if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3760get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3761get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3762!(email_end =strchr(sb->buf +82,'>')) ||3763 email_end[1] !=' '||3764!(timestamp =strtoul(email_end +2, &message,10)) ||3765!message || message[0] !=' '||3766(message[1] !='+'&& message[1] !='-') ||3767!isdigit(message[2]) || !isdigit(message[3]) ||3768!isdigit(message[4]) || !isdigit(message[5]))3769return0;/* corrupt? */3770 email_end[1] ='\0';3771 tz =strtol(message +1, NULL,10);3772if(message[6] !='\t')3773 message +=6;3774else3775 message +=7;3776returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3777}37783779static char*find_beginning_of_line(char*bob,char*scan)3780{3781while(bob < scan && *(--scan) !='\n')3782;/* keep scanning backwards */3783/*3784 * Return either beginning of the buffer, or LF at the end of3785 * the previous line.3786 */3787return scan;3788}37893790intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3791{3792struct strbuf sb = STRBUF_INIT;3793FILE*logfp;3794long pos;3795int ret =0, at_tail =1;37963797 logfp =fopen(git_path("logs/%s", refname),"r");3798if(!logfp)3799return-1;38003801/* Jump to the end */3802if(fseek(logfp,0, SEEK_END) <0)3803returnerror("cannot seek back reflog for%s:%s",3804 refname,strerror(errno));3805 pos =ftell(logfp);3806while(!ret &&0< pos) {3807int cnt;3808size_t nread;3809char buf[BUFSIZ];3810char*endp, *scanp;38113812/* Fill next block from the end */3813 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3814if(fseek(logfp, pos - cnt, SEEK_SET))3815returnerror("cannot seek back reflog for%s:%s",3816 refname,strerror(errno));3817 nread =fread(buf, cnt,1, logfp);3818if(nread !=1)3819returnerror("cannot read%dbytes from reflog for%s:%s",3820 cnt, refname,strerror(errno));3821 pos -= cnt;38223823 scanp = endp = buf + cnt;3824if(at_tail && scanp[-1] =='\n')3825/* Looking at the final LF at the end of the file */3826 scanp--;3827 at_tail =0;38283829while(buf < scanp) {3830/*3831 * terminating LF of the previous line, or the beginning3832 * of the buffer.3833 */3834char*bp;38353836 bp =find_beginning_of_line(buf, scanp);38373838if(*bp =='\n') {3839/*3840 * The newline is the end of the previous line,3841 * so we know we have complete line starting3842 * at (bp + 1). Prefix it onto any prior data3843 * we collected for the line and process it.3844 */3845strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3846 scanp = bp;3847 endp = bp +1;3848 ret =show_one_reflog_ent(&sb, fn, cb_data);3849strbuf_reset(&sb);3850if(ret)3851break;3852}else if(!pos) {3853/*3854 * We are at the start of the buffer, and the3855 * start of the file; there is no previous3856 * line, and we have everything for this one.3857 * Process it, and we can end the loop.3858 */3859strbuf_splice(&sb,0,0, buf, endp - buf);3860 ret =show_one_reflog_ent(&sb, fn, cb_data);3861strbuf_reset(&sb);3862break;3863}38643865if(bp == buf) {3866/*3867 * We are at the start of the buffer, and there3868 * is more file to read backwards. Which means3869 * we are in the middle of a line. Note that we3870 * may get here even if *bp was a newline; that3871 * just means we are at the exact end of the3872 * previous line, rather than some spot in the3873 * middle.3874 *3875 * Save away what we have to be combined with3876 * the data from the next read.3877 */3878strbuf_splice(&sb,0,0, buf, endp - buf);3879break;3880}3881}38823883}3884if(!ret && sb.len)3885die("BUG: reverse reflog parser had leftover data");38863887fclose(logfp);3888strbuf_release(&sb);3889return ret;3890}38913892intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3893{3894FILE*logfp;3895struct strbuf sb = STRBUF_INIT;3896int ret =0;38973898 logfp =fopen(git_path("logs/%s", refname),"r");3899if(!logfp)3900return-1;39013902while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3903 ret =show_one_reflog_ent(&sb, fn, cb_data);3904fclose(logfp);3905strbuf_release(&sb);3906return ret;3907}3908/*3909 * Call fn for each reflog in the namespace indicated by name. name3910 * must be empty or end with '/'. Name will be used as a scratch3911 * space, but its contents will be restored before return.3912 */3913static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3914{3915DIR*d =opendir(git_path("logs/%s", name->buf));3916int retval =0;3917struct dirent *de;3918int oldlen = name->len;39193920if(!d)3921return name->len ? errno :0;39223923while((de =readdir(d)) != NULL) {3924struct stat st;39253926if(de->d_name[0] =='.')3927continue;3928if(ends_with(de->d_name,".lock"))3929continue;3930strbuf_addstr(name, de->d_name);3931if(stat(git_path("logs/%s", name->buf), &st) <0) {3932;/* silently ignore */3933}else{3934if(S_ISDIR(st.st_mode)) {3935strbuf_addch(name,'/');3936 retval =do_for_each_reflog(name, fn, cb_data);3937}else{3938struct object_id oid;39393940if(read_ref_full(name->buf,0, oid.hash, NULL))3941 retval =error("bad ref for%s", name->buf);3942else3943 retval =fn(name->buf, &oid,0, cb_data);3944}3945if(retval)3946break;3947}3948strbuf_setlen(name, oldlen);3949}3950closedir(d);3951return retval;3952}39533954intfor_each_reflog(each_ref_fn fn,void*cb_data)3955{3956int retval;3957struct strbuf name;3958strbuf_init(&name, PATH_MAX);3959 retval =do_for_each_reflog(&name, fn, cb_data);3960strbuf_release(&name);3961return retval;3962}39633964/**3965 * Information needed for a single ref update. Set new_sha1 to the new3966 * value or to null_sha1 to delete the ref. To check the old value3967 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3968 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3969 * not exist before update.3970 */3971struct ref_update {3972/*3973 * If (flags & REF_HAVE_NEW), set the reference to this value:3974 */3975unsigned char new_sha1[20];3976/*3977 * If (flags & REF_HAVE_OLD), check that the reference3978 * previously had this value:3979 */3980unsigned char old_sha1[20];3981/*3982 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3983 * REF_DELETING, and REF_ISPRUNING:3984 */3985unsigned int flags;3986struct ref_lock *lock;3987int type;3988char*msg;3989const char refname[FLEX_ARRAY];3990};39913992/*3993 * Transaction states.3994 * OPEN: The transaction is in a valid state and can accept new updates.3995 * An OPEN transaction can be committed.3996 * CLOSED: A closed transaction is no longer active and no other operations3997 * than free can be used on it in this state.3998 * A transaction can either become closed by successfully committing3999 * an active transaction or if there is a failure while building4000 * the transaction thus rendering it failed/inactive.4001 */4002enum ref_transaction_state {4003 REF_TRANSACTION_OPEN =0,4004 REF_TRANSACTION_CLOSED =14005};40064007/*4008 * Data structure for holding a reference transaction, which can4009 * consist of checks and updates to multiple references, carried out4010 * as atomically as possible. This structure is opaque to callers.4011 */4012struct ref_transaction {4013struct ref_update **updates;4014size_t alloc;4015size_t nr;4016enum ref_transaction_state state;4017};40184019struct ref_transaction *ref_transaction_begin(struct strbuf *err)4020{4021assert(err);40224023returnxcalloc(1,sizeof(struct ref_transaction));4024}40254026voidref_transaction_free(struct ref_transaction *transaction)4027{4028int i;40294030if(!transaction)4031return;40324033for(i =0; i < transaction->nr; i++) {4034free(transaction->updates[i]->msg);4035free(transaction->updates[i]);4036}4037free(transaction->updates);4038free(transaction);4039}40404041static struct ref_update *add_update(struct ref_transaction *transaction,4042const char*refname)4043{4044size_t len =strlen(refname) +1;4045struct ref_update *update =xcalloc(1,sizeof(*update) + len);40464047memcpy((char*)update->refname, refname, len);/* includes NUL */4048ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);4049 transaction->updates[transaction->nr++] = update;4050return update;4051}40524053intref_transaction_update(struct ref_transaction *transaction,4054const char*refname,4055const unsigned char*new_sha1,4056const unsigned char*old_sha1,4057unsigned int flags,const char*msg,4058struct strbuf *err)4059{4060struct ref_update *update;40614062assert(err);40634064if(transaction->state != REF_TRANSACTION_OPEN)4065die("BUG: update called for transaction that is not open");40664067if(new_sha1 && !is_null_sha1(new_sha1) &&4068check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {4069strbuf_addf(err,"refusing to update ref with bad name%s",4070 refname);4071return-1;4072}40734074 update =add_update(transaction, refname);4075if(new_sha1) {4076hashcpy(update->new_sha1, new_sha1);4077 flags |= REF_HAVE_NEW;4078}4079if(old_sha1) {4080hashcpy(update->old_sha1, old_sha1);4081 flags |= REF_HAVE_OLD;4082}4083 update->flags = flags;4084if(msg)4085 update->msg =xstrdup(msg);4086return0;4087}40884089intref_transaction_create(struct ref_transaction *transaction,4090const char*refname,4091const unsigned char*new_sha1,4092unsigned int flags,const char*msg,4093struct strbuf *err)4094{4095if(!new_sha1 ||is_null_sha1(new_sha1))4096die("BUG: create called without valid new_sha1");4097returnref_transaction_update(transaction, refname, new_sha1,4098 null_sha1, flags, msg, err);4099}41004101intref_transaction_delete(struct ref_transaction *transaction,4102const char*refname,4103const unsigned char*old_sha1,4104unsigned int flags,const char*msg,4105struct strbuf *err)4106{4107if(old_sha1 &&is_null_sha1(old_sha1))4108die("BUG: delete called with old_sha1 set to zeros");4109returnref_transaction_update(transaction, refname,4110 null_sha1, old_sha1,4111 flags, msg, err);4112}41134114intref_transaction_verify(struct ref_transaction *transaction,4115const char*refname,4116const unsigned char*old_sha1,4117unsigned int flags,4118struct strbuf *err)4119{4120if(!old_sha1)4121die("BUG: verify called with old_sha1 set to NULL");4122returnref_transaction_update(transaction, refname,4123 NULL, old_sha1,4124 flags, NULL, err);4125}41264127intupdate_ref(const char*msg,const char*refname,4128const unsigned char*new_sha1,const unsigned char*old_sha1,4129unsigned int flags,enum action_on_err onerr)4130{4131struct ref_transaction *t = NULL;4132struct strbuf err = STRBUF_INIT;4133int ret =0;41344135if(ref_type(refname) == REF_TYPE_PSEUDOREF) {4136 ret =write_pseudoref(refname, new_sha1, old_sha1, &err);4137}else{4138 t =ref_transaction_begin(&err);4139if(!t ||4140ref_transaction_update(t, refname, new_sha1, old_sha1,4141 flags, msg, &err) ||4142ref_transaction_commit(t, &err)) {4143 ret =1;4144ref_transaction_free(t);4145}4146}4147if(ret) {4148const char*str ="update_ref failed for ref '%s':%s";41494150switch(onerr) {4151case UPDATE_REFS_MSG_ON_ERR:4152error(str, refname, err.buf);4153break;4154case UPDATE_REFS_DIE_ON_ERR:4155die(str, refname, err.buf);4156break;4157case UPDATE_REFS_QUIET_ON_ERR:4158break;4159}4160strbuf_release(&err);4161return1;4162}4163strbuf_release(&err);4164if(t)4165ref_transaction_free(t);4166return0;4167}41684169static intref_update_reject_duplicates(struct string_list *refnames,4170struct strbuf *err)4171{4172int i, n = refnames->nr;41734174assert(err);41754176for(i =1; i < n; i++)4177if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {4178strbuf_addf(err,4179"Multiple updates for ref '%s' not allowed.",4180 refnames->items[i].string);4181return1;4182}4183return0;4184}41854186intref_transaction_commit(struct ref_transaction *transaction,4187struct strbuf *err)4188{4189int ret =0, i;4190int n = transaction->nr;4191struct ref_update **updates = transaction->updates;4192struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4193struct string_list_item *ref_to_delete;4194struct string_list affected_refnames = STRING_LIST_INIT_NODUP;41954196assert(err);41974198if(transaction->state != REF_TRANSACTION_OPEN)4199die("BUG: commit called for transaction that is not open");42004201if(!n) {4202 transaction->state = REF_TRANSACTION_CLOSED;4203return0;4204}42054206/* Fail if a refname appears more than once in the transaction: */4207for(i =0; i < n; i++)4208string_list_append(&affected_refnames, updates[i]->refname);4209string_list_sort(&affected_refnames);4210if(ref_update_reject_duplicates(&affected_refnames, err)) {4211 ret = TRANSACTION_GENERIC_ERROR;4212goto cleanup;4213}42144215/*4216 * Acquire all locks, verify old values if provided, check4217 * that new values are valid, and write new values to the4218 * lockfiles, ready to be activated. Only keep one lockfile4219 * open at a time to avoid running out of file descriptors.4220 */4221for(i =0; i < n; i++) {4222struct ref_update *update = updates[i];42234224if((update->flags & REF_HAVE_NEW) &&4225is_null_sha1(update->new_sha1))4226 update->flags |= REF_DELETING;4227 update->lock =lock_ref_sha1_basic(4228 update->refname,4229((update->flags & REF_HAVE_OLD) ?4230 update->old_sha1 : NULL),4231&affected_refnames, NULL,4232 update->flags,4233&update->type,4234 err);4235if(!update->lock) {4236char*reason;42374238 ret = (errno == ENOTDIR)4239? TRANSACTION_NAME_CONFLICT4240: TRANSACTION_GENERIC_ERROR;4241 reason =strbuf_detach(err, NULL);4242strbuf_addf(err,"cannot lock ref '%s':%s",4243 update->refname, reason);4244free(reason);4245goto cleanup;4246}4247if((update->flags & REF_HAVE_NEW) &&4248!(update->flags & REF_DELETING)) {4249int overwriting_symref = ((update->type & REF_ISSYMREF) &&4250(update->flags & REF_NODEREF));42514252if(!overwriting_symref &&4253!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4254/*4255 * The reference already has the desired4256 * value, so we don't need to write it.4257 */4258}else if(write_ref_to_lockfile(update->lock,4259 update->new_sha1,4260 err)) {4261char*write_err =strbuf_detach(err, NULL);42624263/*4264 * The lock was freed upon failure of4265 * write_ref_to_lockfile():4266 */4267 update->lock = NULL;4268strbuf_addf(err,4269"cannot update the ref '%s':%s",4270 update->refname, write_err);4271free(write_err);4272 ret = TRANSACTION_GENERIC_ERROR;4273goto cleanup;4274}else{4275 update->flags |= REF_NEEDS_COMMIT;4276}4277}4278if(!(update->flags & REF_NEEDS_COMMIT)) {4279/*4280 * We didn't have to write anything to the lockfile.4281 * Close it to free up the file descriptor:4282 */4283if(close_ref(update->lock)) {4284strbuf_addf(err,"Couldn't close%s.lock",4285 update->refname);4286goto cleanup;4287}4288}4289}42904291/* Perform updates first so live commits remain referenced */4292for(i =0; i < n; i++) {4293struct ref_update *update = updates[i];42944295if(update->flags & REF_NEEDS_COMMIT) {4296if(commit_ref_update(update->lock,4297 update->new_sha1, update->msg,4298 update->flags, err)) {4299/* freed by commit_ref_update(): */4300 update->lock = NULL;4301 ret = TRANSACTION_GENERIC_ERROR;4302goto cleanup;4303}else{4304/* freed by commit_ref_update(): */4305 update->lock = NULL;4306}4307}4308}43094310/* Perform deletes now that updates are safely completed */4311for(i =0; i < n; i++) {4312struct ref_update *update = updates[i];43134314if(update->flags & REF_DELETING) {4315if(delete_ref_loose(update->lock, update->type, err)) {4316 ret = TRANSACTION_GENERIC_ERROR;4317goto cleanup;4318}43194320if(!(update->flags & REF_ISPRUNING))4321string_list_append(&refs_to_delete,4322 update->lock->ref_name);4323}4324}43254326if(repack_without_refs(&refs_to_delete, err)) {4327 ret = TRANSACTION_GENERIC_ERROR;4328goto cleanup;4329}4330for_each_string_list_item(ref_to_delete, &refs_to_delete)4331unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4332clear_loose_ref_cache(&ref_cache);43334334cleanup:4335 transaction->state = REF_TRANSACTION_CLOSED;43364337for(i =0; i < n; i++)4338if(updates[i]->lock)4339unlock_ref(updates[i]->lock);4340string_list_clear(&refs_to_delete,0);4341string_list_clear(&affected_refnames,0);4342return ret;4343}43444345static intref_present(const char*refname,4346const struct object_id *oid,int flags,void*cb_data)4347{4348struct string_list *affected_refnames = cb_data;43494350returnstring_list_has_string(affected_refnames, refname);4351}43524353intinitial_ref_transaction_commit(struct ref_transaction *transaction,4354struct strbuf *err)4355{4356int ret =0, i;4357int n = transaction->nr;4358struct ref_update **updates = transaction->updates;4359struct string_list affected_refnames = STRING_LIST_INIT_NODUP;43604361assert(err);43624363if(transaction->state != REF_TRANSACTION_OPEN)4364die("BUG: commit called for transaction that is not open");43654366/* Fail if a refname appears more than once in the transaction: */4367for(i =0; i < n; i++)4368string_list_append(&affected_refnames, updates[i]->refname);4369string_list_sort(&affected_refnames);4370if(ref_update_reject_duplicates(&affected_refnames, err)) {4371 ret = TRANSACTION_GENERIC_ERROR;4372goto cleanup;4373}43744375/*4376 * It's really undefined to call this function in an active4377 * repository or when there are existing references: we are4378 * only locking and changing packed-refs, so (1) any4379 * simultaneous processes might try to change a reference at4380 * the same time we do, and (2) any existing loose versions of4381 * the references that we are setting would have precedence4382 * over our values. But some remote helpers create the remote4383 * "HEAD" and "master" branches before calling this function,4384 * so here we really only check that none of the references4385 * that we are creating already exists.4386 */4387if(for_each_rawref(ref_present, &affected_refnames))4388die("BUG: initial ref transaction called with existing refs");43894390for(i =0; i < n; i++) {4391struct ref_update *update = updates[i];43924393if((update->flags & REF_HAVE_OLD) &&4394!is_null_sha1(update->old_sha1))4395die("BUG: initial ref transaction with old_sha1 set");4396if(verify_refname_available(update->refname,4397&affected_refnames, NULL,4398 err)) {4399 ret = TRANSACTION_NAME_CONFLICT;4400goto cleanup;4401}4402}44034404if(lock_packed_refs(0)) {4405strbuf_addf(err,"unable to lock packed-refs file:%s",4406strerror(errno));4407 ret = TRANSACTION_GENERIC_ERROR;4408goto cleanup;4409}44104411for(i =0; i < n; i++) {4412struct ref_update *update = updates[i];44134414if((update->flags & REF_HAVE_NEW) &&4415!is_null_sha1(update->new_sha1))4416add_packed_ref(update->refname, update->new_sha1);4417}44184419if(commit_packed_refs()) {4420strbuf_addf(err,"unable to commit packed-refs file:%s",4421strerror(errno));4422 ret = TRANSACTION_GENERIC_ERROR;4423goto cleanup;4424}44254426cleanup:4427 transaction->state = REF_TRANSACTION_CLOSED;4428string_list_clear(&affected_refnames,0);4429return ret;4430}44314432char*shorten_unambiguous_ref(const char*refname,int strict)4433{4434int i;4435static char**scanf_fmts;4436static int nr_rules;4437char*short_name;44384439if(!nr_rules) {4440/*4441 * Pre-generate scanf formats from ref_rev_parse_rules[].4442 * Generate a format suitable for scanf from a4443 * ref_rev_parse_rules rule by interpolating "%s" at the4444 * location of the "%.*s".4445 */4446size_t total_len =0;4447size_t offset =0;44484449/* the rule list is NULL terminated, count them first */4450for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4451/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4452 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;44534454 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);44554456 offset =0;4457for(i =0; i < nr_rules; i++) {4458assert(offset < total_len);4459 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4460 offset +=snprintf(scanf_fmts[i], total_len - offset,4461 ref_rev_parse_rules[i],2,"%s") +1;4462}4463}44644465/* bail out if there are no rules */4466if(!nr_rules)4467returnxstrdup(refname);44684469/* buffer for scanf result, at most refname must fit */4470 short_name =xstrdup(refname);44714472/* skip first rule, it will always match */4473for(i = nr_rules -1; i >0; --i) {4474int j;4475int rules_to_fail = i;4476int short_name_len;44774478if(1!=sscanf(refname, scanf_fmts[i], short_name))4479continue;44804481 short_name_len =strlen(short_name);44824483/*4484 * in strict mode, all (except the matched one) rules4485 * must fail to resolve to a valid non-ambiguous ref4486 */4487if(strict)4488 rules_to_fail = nr_rules;44894490/*4491 * check if the short name resolves to a valid ref,4492 * but use only rules prior to the matched one4493 */4494for(j =0; j < rules_to_fail; j++) {4495const char*rule = ref_rev_parse_rules[j];4496char refname[PATH_MAX];44974498/* skip matched rule */4499if(i == j)4500continue;45014502/*4503 * the short name is ambiguous, if it resolves4504 * (with this previous rule) to a valid ref4505 * read_ref() returns 0 on success4506 */4507mksnpath(refname,sizeof(refname),4508 rule, short_name_len, short_name);4509if(ref_exists(refname))4510break;4511}45124513/*4514 * short name is non-ambiguous if all previous rules4515 * haven't resolved to a valid ref4516 */4517if(j == rules_to_fail)4518return short_name;4519}45204521free(short_name);4522returnxstrdup(refname);4523}45244525static struct string_list *hide_refs;45264527intparse_hide_refs_config(const char*var,const char*value,const char*section)4528{4529if(!strcmp("transfer.hiderefs", var) ||4530/* NEEDSWORK: use parse_config_key() once both are merged */4531(starts_with(var, section) && var[strlen(section)] =='.'&&4532!strcmp(var +strlen(section),".hiderefs"))) {4533char*ref;4534int len;45354536if(!value)4537returnconfig_error_nonbool(var);4538 ref =xstrdup(value);4539 len =strlen(ref);4540while(len && ref[len -1] =='/')4541 ref[--len] ='\0';4542if(!hide_refs) {4543 hide_refs =xcalloc(1,sizeof(*hide_refs));4544 hide_refs->strdup_strings =1;4545}4546string_list_append(hide_refs, ref);4547}4548return0;4549}45504551intref_is_hidden(const char*refname)4552{4553int i;45544555if(!hide_refs)4556return0;4557for(i = hide_refs->nr -1; i >=0; i--) {4558const char*match = hide_refs->items[i].string;4559int neg =0;4560int len;45614562if(*match =='!') {4563 neg =1;4564 match++;4565}45664567if(!starts_with(refname, match))4568continue;4569 len =strlen(match);4570if(!refname[len] || refname[len] =='/')4571return!neg;4572}4573return0;4574}45754576struct expire_reflog_cb {4577unsigned int flags;4578 reflog_expiry_should_prune_fn *should_prune_fn;4579void*policy_cb;4580FILE*newlog;4581unsigned char last_kept_sha1[20];4582};45834584static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4585const char*email,unsigned long timestamp,int tz,4586const char*message,void*cb_data)4587{4588struct expire_reflog_cb *cb = cb_data;4589struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;45904591if(cb->flags & EXPIRE_REFLOGS_REWRITE)4592 osha1 = cb->last_kept_sha1;45934594if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4595 message, policy_cb)) {4596if(!cb->newlog)4597printf("would prune%s", message);4598else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4599printf("prune%s", message);4600}else{4601if(cb->newlog) {4602fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4603sha1_to_hex(osha1),sha1_to_hex(nsha1),4604 email, timestamp, tz, message);4605hashcpy(cb->last_kept_sha1, nsha1);4606}4607if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4608printf("keep%s", message);4609}4610return0;4611}46124613intreflog_expire(const char*refname,const unsigned char*sha1,4614unsigned int flags,4615 reflog_expiry_prepare_fn prepare_fn,4616 reflog_expiry_should_prune_fn should_prune_fn,4617 reflog_expiry_cleanup_fn cleanup_fn,4618void*policy_cb_data)4619{4620static struct lock_file reflog_lock;4621struct expire_reflog_cb cb;4622struct ref_lock *lock;4623char*log_file;4624int status =0;4625int type;4626struct strbuf err = STRBUF_INIT;46274628memset(&cb,0,sizeof(cb));4629 cb.flags = flags;4630 cb.policy_cb = policy_cb_data;4631 cb.should_prune_fn = should_prune_fn;46324633/*4634 * The reflog file is locked by holding the lock on the4635 * reference itself, plus we might need to update the4636 * reference if --updateref was specified:4637 */4638 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4639if(!lock) {4640error("cannot lock ref '%s':%s", refname, err.buf);4641strbuf_release(&err);4642return-1;4643}4644if(!reflog_exists(refname)) {4645unlock_ref(lock);4646return0;4647}46484649 log_file =git_pathdup("logs/%s", refname);4650if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4651/*4652 * Even though holding $GIT_DIR/logs/$reflog.lock has4653 * no locking implications, we use the lock_file4654 * machinery here anyway because it does a lot of the4655 * work we need, including cleaning up if the program4656 * exits unexpectedly.4657 */4658if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4659struct strbuf err = STRBUF_INIT;4660unable_to_lock_message(log_file, errno, &err);4661error("%s", err.buf);4662strbuf_release(&err);4663goto failure;4664}4665 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4666if(!cb.newlog) {4667error("cannot fdopen%s(%s)",4668get_lock_file_path(&reflog_lock),strerror(errno));4669goto failure;4670}4671}46724673(*prepare_fn)(refname, sha1, cb.policy_cb);4674for_each_reflog_ent(refname, expire_reflog_ent, &cb);4675(*cleanup_fn)(cb.policy_cb);46764677if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4678/*4679 * It doesn't make sense to adjust a reference pointed4680 * to by a symbolic ref based on expiring entries in4681 * the symbolic reference's reflog. Nor can we update4682 * a reference if there are no remaining reflog4683 * entries.4684 */4685int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4686!(type & REF_ISSYMREF) &&4687!is_null_sha1(cb.last_kept_sha1);46884689if(close_lock_file(&reflog_lock)) {4690 status |=error("couldn't write%s:%s", log_file,4691strerror(errno));4692}else if(update &&4693(write_in_full(get_lock_file_fd(lock->lk),4694sha1_to_hex(cb.last_kept_sha1),40) !=40||4695write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||4696close_ref(lock) <0)) {4697 status |=error("couldn't write%s",4698get_lock_file_path(lock->lk));4699rollback_lock_file(&reflog_lock);4700}else if(commit_lock_file(&reflog_lock)) {4701 status |=error("unable to commit reflog '%s' (%s)",4702 log_file,strerror(errno));4703}else if(update &&commit_ref(lock)) {4704 status |=error("couldn't set%s", lock->ref_name);4705}4706}4707free(log_file);4708unlock_ref(lock);4709return status;47104711 failure:4712rollback_lock_file(&reflog_lock);4713free(log_file);4714unlock_ref(lock);4715return-1;4716}