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 * Return true iff refname is minimally safe. "Safe" here means that 345 * deleting a loose reference by this name will not do any damage, for 346 * example by causing a file that is not a reference to be deleted. 347 * This function does not check that the reference name is legal; for 348 * that, use check_refname_format(). 349 * 350 * We consider a refname that starts with "refs/" to be safe as long 351 * as any ".." components that it might contain do not escape "refs/". 352 * Names that do not start with "refs/" are considered safe iff they 353 * consist entirely of upper case characters and '_' (like "HEAD" and 354 * "MERGE_HEAD" but not "config" or "FOO/BAR"). 355 */ 356static intrefname_is_safe(const char*refname) 357{ 358if(starts_with(refname,"refs/")) { 359char*buf; 360int result; 361 362 buf =xmalloc(strlen(refname) +1); 363/* 364 * Does the refname try to escape refs/? 365 * For example: refs/foo/../bar is safe but refs/foo/../../bar 366 * is not. 367 */ 368 result = !normalize_path_copy(buf, refname +strlen("refs/")); 369free(buf); 370return result; 371} 372while(*refname) { 373if(!isupper(*refname) && *refname !='_') 374return0; 375 refname++; 376} 377return1; 378} 379 380static struct ref_entry *create_ref_entry(const char*refname, 381const unsigned char*sha1,int flag, 382int check_name) 383{ 384int len; 385struct ref_entry *ref; 386 387if(check_name && 388check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 389die("Reference has invalid format: '%s'", refname); 390 len =strlen(refname) +1; 391 ref =xmalloc(sizeof(struct ref_entry) + len); 392hashcpy(ref->u.value.oid.hash, sha1); 393oidclr(&ref->u.value.peeled); 394memcpy(ref->name, refname, len); 395 ref->flag = flag; 396return ref; 397} 398 399static voidclear_ref_dir(struct ref_dir *dir); 400 401static voidfree_ref_entry(struct ref_entry *entry) 402{ 403if(entry->flag & REF_DIR) { 404/* 405 * Do not use get_ref_dir() here, as that might 406 * trigger the reading of loose refs. 407 */ 408clear_ref_dir(&entry->u.subdir); 409} 410free(entry); 411} 412 413/* 414 * Add a ref_entry to the end of dir (unsorted). Entry is always 415 * stored directly in dir; no recursion into subdirectories is 416 * done. 417 */ 418static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 419{ 420ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 421 dir->entries[dir->nr++] = entry; 422/* optimize for the case that entries are added in order */ 423if(dir->nr ==1|| 424(dir->nr == dir->sorted +1&& 425strcmp(dir->entries[dir->nr -2]->name, 426 dir->entries[dir->nr -1]->name) <0)) 427 dir->sorted = dir->nr; 428} 429 430/* 431 * Clear and free all entries in dir, recursively. 432 */ 433static voidclear_ref_dir(struct ref_dir *dir) 434{ 435int i; 436for(i =0; i < dir->nr; i++) 437free_ref_entry(dir->entries[i]); 438free(dir->entries); 439 dir->sorted = dir->nr = dir->alloc =0; 440 dir->entries = NULL; 441} 442 443/* 444 * Create a struct ref_entry object for the specified dirname. 445 * dirname is the name of the directory with a trailing slash (e.g., 446 * "refs/heads/") or "" for the top-level directory. 447 */ 448static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 449const char*dirname,size_t len, 450int incomplete) 451{ 452struct ref_entry *direntry; 453 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 454memcpy(direntry->name, dirname, len); 455 direntry->name[len] ='\0'; 456 direntry->u.subdir.ref_cache = ref_cache; 457 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 458return direntry; 459} 460 461static intref_entry_cmp(const void*a,const void*b) 462{ 463struct ref_entry *one = *(struct ref_entry **)a; 464struct ref_entry *two = *(struct ref_entry **)b; 465returnstrcmp(one->name, two->name); 466} 467 468static voidsort_ref_dir(struct ref_dir *dir); 469 470struct string_slice { 471size_t len; 472const char*str; 473}; 474 475static intref_entry_cmp_sslice(const void*key_,const void*ent_) 476{ 477const struct string_slice *key = key_; 478const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 479int cmp =strncmp(key->str, ent->name, key->len); 480if(cmp) 481return cmp; 482return'\0'- (unsigned char)ent->name[key->len]; 483} 484 485/* 486 * Return the index of the entry with the given refname from the 487 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 488 * no such entry is found. dir must already be complete. 489 */ 490static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 491{ 492struct ref_entry **r; 493struct string_slice key; 494 495if(refname == NULL || !dir->nr) 496return-1; 497 498sort_ref_dir(dir); 499 key.len = len; 500 key.str = refname; 501 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 502 ref_entry_cmp_sslice); 503 504if(r == NULL) 505return-1; 506 507return r - dir->entries; 508} 509 510/* 511 * Search for a directory entry directly within dir (without 512 * recursing). Sort dir if necessary. subdirname must be a directory 513 * name (i.e., end in '/'). If mkdir is set, then create the 514 * directory if it is missing; otherwise, return NULL if the desired 515 * directory cannot be found. dir must already be complete. 516 */ 517static struct ref_dir *search_for_subdir(struct ref_dir *dir, 518const char*subdirname,size_t len, 519int mkdir) 520{ 521int entry_index =search_ref_dir(dir, subdirname, len); 522struct ref_entry *entry; 523if(entry_index == -1) { 524if(!mkdir) 525return NULL; 526/* 527 * Since dir is complete, the absence of a subdir 528 * means that the subdir really doesn't exist; 529 * therefore, create an empty record for it but mark 530 * the record complete. 531 */ 532 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 533add_entry_to_dir(dir, entry); 534}else{ 535 entry = dir->entries[entry_index]; 536} 537returnget_ref_dir(entry); 538} 539 540/* 541 * If refname is a reference name, find the ref_dir within the dir 542 * tree that should hold refname. If refname is a directory name 543 * (i.e., ends in '/'), then return that ref_dir itself. dir must 544 * represent the top-level directory and must already be complete. 545 * Sort ref_dirs and recurse into subdirectories as necessary. If 546 * mkdir is set, then create any missing directories; otherwise, 547 * return NULL if the desired directory cannot be found. 548 */ 549static struct ref_dir *find_containing_dir(struct ref_dir *dir, 550const char*refname,int mkdir) 551{ 552const char*slash; 553for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 554size_t dirnamelen = slash - refname +1; 555struct ref_dir *subdir; 556 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 557if(!subdir) { 558 dir = NULL; 559break; 560} 561 dir = subdir; 562} 563 564return dir; 565} 566 567/* 568 * Find the value entry with the given name in dir, sorting ref_dirs 569 * and recursing into subdirectories as necessary. If the name is not 570 * found or it corresponds to a directory entry, return NULL. 571 */ 572static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 573{ 574int entry_index; 575struct ref_entry *entry; 576 dir =find_containing_dir(dir, refname,0); 577if(!dir) 578return NULL; 579 entry_index =search_ref_dir(dir, refname,strlen(refname)); 580if(entry_index == -1) 581return NULL; 582 entry = dir->entries[entry_index]; 583return(entry->flag & REF_DIR) ? NULL : entry; 584} 585 586/* 587 * Remove the entry with the given name from dir, recursing into 588 * subdirectories as necessary. If refname is the name of a directory 589 * (i.e., ends with '/'), then remove the directory and its contents. 590 * If the removal was successful, return the number of entries 591 * remaining in the directory entry that contained the deleted entry. 592 * If the name was not found, return -1. Please note that this 593 * function only deletes the entry from the cache; it does not delete 594 * it from the filesystem or ensure that other cache entries (which 595 * might be symbolic references to the removed entry) are updated. 596 * Nor does it remove any containing dir entries that might be made 597 * empty by the removal. dir must represent the top-level directory 598 * and must already be complete. 599 */ 600static intremove_entry(struct ref_dir *dir,const char*refname) 601{ 602int refname_len =strlen(refname); 603int entry_index; 604struct ref_entry *entry; 605int is_dir = refname[refname_len -1] =='/'; 606if(is_dir) { 607/* 608 * refname represents a reference directory. Remove 609 * the trailing slash; otherwise we will get the 610 * directory *representing* refname rather than the 611 * one *containing* it. 612 */ 613char*dirname =xmemdupz(refname, refname_len -1); 614 dir =find_containing_dir(dir, dirname,0); 615free(dirname); 616}else{ 617 dir =find_containing_dir(dir, refname,0); 618} 619if(!dir) 620return-1; 621 entry_index =search_ref_dir(dir, refname, refname_len); 622if(entry_index == -1) 623return-1; 624 entry = dir->entries[entry_index]; 625 626memmove(&dir->entries[entry_index], 627&dir->entries[entry_index +1], 628(dir->nr - entry_index -1) *sizeof(*dir->entries) 629); 630 dir->nr--; 631if(dir->sorted > entry_index) 632 dir->sorted--; 633free_ref_entry(entry); 634return dir->nr; 635} 636 637/* 638 * Add a ref_entry to the ref_dir (unsorted), recursing into 639 * subdirectories as necessary. dir must represent the top-level 640 * directory. Return 0 on success. 641 */ 642static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 643{ 644 dir =find_containing_dir(dir, ref->name,1); 645if(!dir) 646return-1; 647add_entry_to_dir(dir, ref); 648return0; 649} 650 651/* 652 * Emit a warning and return true iff ref1 and ref2 have the same name 653 * and the same sha1. Die if they have the same name but different 654 * sha1s. 655 */ 656static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 657{ 658if(strcmp(ref1->name, ref2->name)) 659return0; 660 661/* Duplicate name; make sure that they don't conflict: */ 662 663if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 664/* This is impossible by construction */ 665die("Reference directory conflict:%s", ref1->name); 666 667if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 668die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 669 670warning("Duplicated ref:%s", ref1->name); 671return1; 672} 673 674/* 675 * Sort the entries in dir non-recursively (if they are not already 676 * sorted) and remove any duplicate entries. 677 */ 678static voidsort_ref_dir(struct ref_dir *dir) 679{ 680int i, j; 681struct ref_entry *last = NULL; 682 683/* 684 * This check also prevents passing a zero-length array to qsort(), 685 * which is a problem on some platforms. 686 */ 687if(dir->sorted == dir->nr) 688return; 689 690qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 691 692/* Remove any duplicates: */ 693for(i =0, j =0; j < dir->nr; j++) { 694struct ref_entry *entry = dir->entries[j]; 695if(last &&is_dup_ref(last, entry)) 696free_ref_entry(entry); 697else 698 last = dir->entries[i++] = entry; 699} 700 dir->sorted = dir->nr = i; 701} 702 703/* Include broken references in a do_for_each_ref*() iteration: */ 704#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 705 706/* 707 * Return true iff the reference described by entry can be resolved to 708 * an object in the database. Emit a warning if the referred-to 709 * object does not exist. 710 */ 711static intref_resolves_to_object(struct ref_entry *entry) 712{ 713if(entry->flag & REF_ISBROKEN) 714return0; 715if(!has_sha1_file(entry->u.value.oid.hash)) { 716error("%sdoes not point to a valid object!", entry->name); 717return0; 718} 719return1; 720} 721 722/* 723 * current_ref is a performance hack: when iterating over references 724 * using the for_each_ref*() functions, current_ref is set to the 725 * current reference's entry before calling the callback function. If 726 * the callback function calls peel_ref(), then peel_ref() first 727 * checks whether the reference to be peeled is the current reference 728 * (it usually is) and if so, returns that reference's peeled version 729 * if it is available. This avoids a refname lookup in a common case. 730 */ 731static struct ref_entry *current_ref; 732 733typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 734 735struct ref_entry_cb { 736const char*base; 737int trim; 738int flags; 739 each_ref_fn *fn; 740void*cb_data; 741}; 742 743/* 744 * Handle one reference in a do_for_each_ref*()-style iteration, 745 * calling an each_ref_fn for each entry. 746 */ 747static intdo_one_ref(struct ref_entry *entry,void*cb_data) 748{ 749struct ref_entry_cb *data = cb_data; 750struct ref_entry *old_current_ref; 751int retval; 752 753if(!starts_with(entry->name, data->base)) 754return0; 755 756if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 757!ref_resolves_to_object(entry)) 758return0; 759 760/* Store the old value, in case this is a recursive call: */ 761 old_current_ref = current_ref; 762 current_ref = entry; 763 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 764 entry->flag, data->cb_data); 765 current_ref = old_current_ref; 766return retval; 767} 768 769/* 770 * Call fn for each reference in dir that has index in the range 771 * offset <= index < dir->nr. Recurse into subdirectories that are in 772 * that index range, sorting them before iterating. This function 773 * does not sort dir itself; it should be sorted beforehand. fn is 774 * called for all references, including broken ones. 775 */ 776static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 777 each_ref_entry_fn fn,void*cb_data) 778{ 779int i; 780assert(dir->sorted == dir->nr); 781for(i = offset; i < dir->nr; i++) { 782struct ref_entry *entry = dir->entries[i]; 783int retval; 784if(entry->flag & REF_DIR) { 785struct ref_dir *subdir =get_ref_dir(entry); 786sort_ref_dir(subdir); 787 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 788}else{ 789 retval =fn(entry, cb_data); 790} 791if(retval) 792return retval; 793} 794return0; 795} 796 797/* 798 * Call fn for each reference in the union of dir1 and dir2, in order 799 * by refname. Recurse into subdirectories. If a value entry appears 800 * in both dir1 and dir2, then only process the version that is in 801 * dir2. The input dirs must already be sorted, but subdirs will be 802 * sorted as needed. fn is called for all references, including 803 * broken ones. 804 */ 805static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 806struct ref_dir *dir2, 807 each_ref_entry_fn fn,void*cb_data) 808{ 809int retval; 810int i1 =0, i2 =0; 811 812assert(dir1->sorted == dir1->nr); 813assert(dir2->sorted == dir2->nr); 814while(1) { 815struct ref_entry *e1, *e2; 816int cmp; 817if(i1 == dir1->nr) { 818returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 819} 820if(i2 == dir2->nr) { 821returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 822} 823 e1 = dir1->entries[i1]; 824 e2 = dir2->entries[i2]; 825 cmp =strcmp(e1->name, e2->name); 826if(cmp ==0) { 827if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 828/* Both are directories; descend them in parallel. */ 829struct ref_dir *subdir1 =get_ref_dir(e1); 830struct ref_dir *subdir2 =get_ref_dir(e2); 831sort_ref_dir(subdir1); 832sort_ref_dir(subdir2); 833 retval =do_for_each_entry_in_dirs( 834 subdir1, subdir2, fn, cb_data); 835 i1++; 836 i2++; 837}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 838/* Both are references; ignore the one from dir1. */ 839 retval =fn(e2, cb_data); 840 i1++; 841 i2++; 842}else{ 843die("conflict between reference and directory:%s", 844 e1->name); 845} 846}else{ 847struct ref_entry *e; 848if(cmp <0) { 849 e = e1; 850 i1++; 851}else{ 852 e = e2; 853 i2++; 854} 855if(e->flag & REF_DIR) { 856struct ref_dir *subdir =get_ref_dir(e); 857sort_ref_dir(subdir); 858 retval =do_for_each_entry_in_dir( 859 subdir,0, fn, cb_data); 860}else{ 861 retval =fn(e, cb_data); 862} 863} 864if(retval) 865return retval; 866} 867} 868 869/* 870 * Load all of the refs from the dir into our in-memory cache. The hard work 871 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 872 * through all of the sub-directories. We do not even need to care about 873 * sorting, as traversal order does not matter to us. 874 */ 875static voidprime_ref_dir(struct ref_dir *dir) 876{ 877int i; 878for(i =0; i < dir->nr; i++) { 879struct ref_entry *entry = dir->entries[i]; 880if(entry->flag & REF_DIR) 881prime_ref_dir(get_ref_dir(entry)); 882} 883} 884 885struct nonmatching_ref_data { 886const struct string_list *skip; 887const char*conflicting_refname; 888}; 889 890static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 891{ 892struct nonmatching_ref_data *data = vdata; 893 894if(data->skip &&string_list_has_string(data->skip, entry->name)) 895return0; 896 897 data->conflicting_refname = entry->name; 898return1; 899} 900 901/* 902 * Return 0 if a reference named refname could be created without 903 * conflicting with the name of an existing reference in dir. 904 * See verify_refname_available for more information. 905 */ 906static intverify_refname_available_dir(const char*refname, 907const struct string_list *extras, 908const struct string_list *skip, 909struct ref_dir *dir, 910struct strbuf *err) 911{ 912const char*slash; 913int pos; 914struct strbuf dirname = STRBUF_INIT; 915int ret = -1; 916 917/* 918 * For the sake of comments in this function, suppose that 919 * refname is "refs/foo/bar". 920 */ 921 922assert(err); 923 924strbuf_grow(&dirname,strlen(refname) +1); 925for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 926/* Expand dirname to the new prefix, not including the trailing slash: */ 927strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 928 929/* 930 * We are still at a leading dir of the refname (e.g., 931 * "refs/foo"; if there is a reference with that name, 932 * it is a conflict, *unless* it is in skip. 933 */ 934if(dir) { 935 pos =search_ref_dir(dir, dirname.buf, dirname.len); 936if(pos >=0&& 937(!skip || !string_list_has_string(skip, dirname.buf))) { 938/* 939 * We found a reference whose name is 940 * a proper prefix of refname; e.g., 941 * "refs/foo", and is not in skip. 942 */ 943strbuf_addf(err,"'%s' exists; cannot create '%s'", 944 dirname.buf, refname); 945goto cleanup; 946} 947} 948 949if(extras &&string_list_has_string(extras, dirname.buf) && 950(!skip || !string_list_has_string(skip, dirname.buf))) { 951strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 952 refname, dirname.buf); 953goto cleanup; 954} 955 956/* 957 * Otherwise, we can try to continue our search with 958 * the next component. So try to look up the 959 * directory, e.g., "refs/foo/". If we come up empty, 960 * we know there is nothing under this whole prefix, 961 * but even in that case we still have to continue the 962 * search for conflicts with extras. 963 */ 964strbuf_addch(&dirname,'/'); 965if(dir) { 966 pos =search_ref_dir(dir, dirname.buf, dirname.len); 967if(pos <0) { 968/* 969 * There was no directory "refs/foo/", 970 * so there is nothing under this 971 * whole prefix. So there is no need 972 * to continue looking for conflicting 973 * references. But we need to continue 974 * looking for conflicting extras. 975 */ 976 dir = NULL; 977}else{ 978 dir =get_ref_dir(dir->entries[pos]); 979} 980} 981} 982 983/* 984 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 985 * There is no point in searching for a reference with that 986 * name, because a refname isn't considered to conflict with 987 * itself. But we still need to check for references whose 988 * names are in the "refs/foo/bar/" namespace, because they 989 * *do* conflict. 990 */ 991strbuf_addstr(&dirname, refname + dirname.len); 992strbuf_addch(&dirname,'/'); 993 994if(dir) { 995 pos =search_ref_dir(dir, dirname.buf, dirname.len); 996 997if(pos >=0) { 998/* 999 * We found a directory named "$refname/"1000 * (e.g., "refs/foo/bar/"). It is a problem1001 * iff it contains any ref that is not in1002 * "skip".1003 */1004struct nonmatching_ref_data data;10051006 data.skip = skip;1007 data.conflicting_refname = NULL;1008 dir =get_ref_dir(dir->entries[pos]);1009sort_ref_dir(dir);1010if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) {1011strbuf_addf(err,"'%s' exists; cannot create '%s'",1012 data.conflicting_refname, refname);1013goto cleanup;1014}1015}1016}10171018if(extras) {1019/*1020 * Check for entries in extras that start with1021 * "$refname/". We do that by looking for the place1022 * where "$refname/" would be inserted in extras. If1023 * there is an entry at that position that starts with1024 * "$refname/" and is not in skip, then we have a1025 * conflict.1026 */1027for(pos =string_list_find_insert_index(extras, dirname.buf,0);1028 pos < extras->nr; pos++) {1029const char*extra_refname = extras->items[pos].string;10301031if(!starts_with(extra_refname, dirname.buf))1032break;10331034if(!skip || !string_list_has_string(skip, extra_refname)) {1035strbuf_addf(err,"cannot process '%s' and '%s' at the same time",1036 refname, extra_refname);1037goto cleanup;1038}1039}1040}10411042/* No conflicts were found */1043 ret =0;10441045cleanup:1046strbuf_release(&dirname);1047return ret;1048}10491050struct packed_ref_cache {1051struct ref_entry *root;10521053/*1054 * Count of references to the data structure in this instance,1055 * including the pointer from ref_cache::packed if any. The1056 * data will not be freed as long as the reference count is1057 * nonzero.1058 */1059unsigned int referrers;10601061/*1062 * Iff the packed-refs file associated with this instance is1063 * currently locked for writing, this points at the associated1064 * lock (which is owned by somebody else). The referrer count1065 * is also incremented when the file is locked and decremented1066 * when it is unlocked.1067 */1068struct lock_file *lock;10691070/* The metadata from when this packed-refs cache was read */1071struct stat_validity validity;1072};10731074/*1075 * Future: need to be in "struct repository"1076 * when doing a full libification.1077 */1078static struct ref_cache {1079struct ref_cache *next;1080struct ref_entry *loose;1081struct packed_ref_cache *packed;1082/*1083 * The submodule name, or "" for the main repo. We allocate1084 * length 1 rather than FLEX_ARRAY so that the main ref_cache1085 * is initialized correctly.1086 */1087char name[1];1088} ref_cache, *submodule_ref_caches;10891090/* Lock used for the main packed-refs file: */1091static struct lock_file packlock;10921093/*1094 * Increment the reference count of *packed_refs.1095 */1096static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1097{1098 packed_refs->referrers++;1099}11001101/*1102 * Decrease the reference count of *packed_refs. If it goes to zero,1103 * free *packed_refs and return true; otherwise return false.1104 */1105static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1106{1107if(!--packed_refs->referrers) {1108free_ref_entry(packed_refs->root);1109stat_validity_clear(&packed_refs->validity);1110free(packed_refs);1111return1;1112}else{1113return0;1114}1115}11161117static voidclear_packed_ref_cache(struct ref_cache *refs)1118{1119if(refs->packed) {1120struct packed_ref_cache *packed_refs = refs->packed;11211122if(packed_refs->lock)1123die("internal error: packed-ref cache cleared while locked");1124 refs->packed = NULL;1125release_packed_ref_cache(packed_refs);1126}1127}11281129static voidclear_loose_ref_cache(struct ref_cache *refs)1130{1131if(refs->loose) {1132free_ref_entry(refs->loose);1133 refs->loose = NULL;1134}1135}11361137static struct ref_cache *create_ref_cache(const char*submodule)1138{1139int len;1140struct ref_cache *refs;1141if(!submodule)1142 submodule ="";1143 len =strlen(submodule) +1;1144 refs =xcalloc(1,sizeof(struct ref_cache) + len);1145memcpy(refs->name, submodule, len);1146return refs;1147}11481149/*1150 * Return a pointer to a ref_cache for the specified submodule. For1151 * the main repository, use submodule==NULL. The returned structure1152 * will be allocated and initialized but not necessarily populated; it1153 * should not be freed.1154 */1155static struct ref_cache *get_ref_cache(const char*submodule)1156{1157struct ref_cache *refs;11581159if(!submodule || !*submodule)1160return&ref_cache;11611162for(refs = submodule_ref_caches; refs; refs = refs->next)1163if(!strcmp(submodule, refs->name))1164return refs;11651166 refs =create_ref_cache(submodule);1167 refs->next = submodule_ref_caches;1168 submodule_ref_caches = refs;1169return refs;1170}11711172/* The length of a peeled reference line in packed-refs, including EOL: */1173#define PEELED_LINE_LENGTH 4211741175/*1176 * The packed-refs header line that we write out. Perhaps other1177 * traits will be added later. The trailing space is required.1178 */1179static const char PACKED_REFS_HEADER[] =1180"# pack-refs with: peeled fully-peeled\n";11811182/*1183 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1184 * Return a pointer to the refname within the line (null-terminated),1185 * or NULL if there was a problem.1186 */1187static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1188{1189const char*ref;11901191/*1192 * 42: the answer to everything.1193 *1194 * In this case, it happens to be the answer to1195 * 40 (length of sha1 hex representation)1196 * +1 (space in between hex and name)1197 * +1 (newline at the end of the line)1198 */1199if(line->len <=42)1200return NULL;12011202if(get_sha1_hex(line->buf, sha1) <0)1203return NULL;1204if(!isspace(line->buf[40]))1205return NULL;12061207 ref = line->buf +41;1208if(isspace(*ref))1209return NULL;12101211if(line->buf[line->len -1] !='\n')1212return NULL;1213 line->buf[--line->len] =0;12141215return ref;1216}12171218/*1219 * Read f, which is a packed-refs file, into dir.1220 *1221 * A comment line of the form "# pack-refs with: " may contain zero or1222 * more traits. We interpret the traits as follows:1223 *1224 * No traits:1225 *1226 * Probably no references are peeled. But if the file contains a1227 * peeled value for a reference, we will use it.1228 *1229 * peeled:1230 *1231 * References under "refs/tags/", if they *can* be peeled, *are*1232 * peeled in this file. References outside of "refs/tags/" are1233 * probably not peeled even if they could have been, but if we find1234 * a peeled value for such a reference we will use it.1235 *1236 * fully-peeled:1237 *1238 * All references in the file that can be peeled are peeled.1239 * Inversely (and this is more important), any references in the1240 * file for which no peeled value is recorded is not peelable. This1241 * trait should typically be written alongside "peeled" for1242 * compatibility with older clients, but we do not require it1243 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1244 */1245static voidread_packed_refs(FILE*f,struct ref_dir *dir)1246{1247struct ref_entry *last = NULL;1248struct strbuf line = STRBUF_INIT;1249enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12501251while(strbuf_getwholeline(&line, f,'\n') != EOF) {1252unsigned char sha1[20];1253const char*refname;1254const char*traits;12551256if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1257if(strstr(traits," fully-peeled "))1258 peeled = PEELED_FULLY;1259else if(strstr(traits," peeled "))1260 peeled = PEELED_TAGS;1261/* perhaps other traits later as well */1262continue;1263}12641265 refname =parse_ref_line(&line, sha1);1266if(refname) {1267int flag = REF_ISPACKED;12681269if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1270if(!refname_is_safe(refname))1271die("packed refname is dangerous:%s", refname);1272hashclr(sha1);1273 flag |= REF_BAD_NAME | REF_ISBROKEN;1274}1275 last =create_ref_entry(refname, sha1, flag,0);1276if(peeled == PEELED_FULLY ||1277(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1278 last->flag |= REF_KNOWS_PEELED;1279add_ref(dir, last);1280continue;1281}1282if(last &&1283 line.buf[0] =='^'&&1284 line.len == PEELED_LINE_LENGTH &&1285 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1286!get_sha1_hex(line.buf +1, sha1)) {1287hashcpy(last->u.value.peeled.hash, sha1);1288/*1289 * Regardless of what the file header said,1290 * we definitely know the value of *this*1291 * reference:1292 */1293 last->flag |= REF_KNOWS_PEELED;1294}1295}12961297strbuf_release(&line);1298}12991300/*1301 * Get the packed_ref_cache for the specified ref_cache, creating it1302 * if necessary.1303 */1304static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1305{1306char*packed_refs_file;13071308if(*refs->name)1309 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1310else1311 packed_refs_file =git_pathdup("packed-refs");13121313if(refs->packed &&1314!stat_validity_check(&refs->packed->validity, packed_refs_file))1315clear_packed_ref_cache(refs);13161317if(!refs->packed) {1318FILE*f;13191320 refs->packed =xcalloc(1,sizeof(*refs->packed));1321acquire_packed_ref_cache(refs->packed);1322 refs->packed->root =create_dir_entry(refs,"",0,0);1323 f =fopen(packed_refs_file,"r");1324if(f) {1325stat_validity_update(&refs->packed->validity,fileno(f));1326read_packed_refs(f,get_ref_dir(refs->packed->root));1327fclose(f);1328}1329}1330free(packed_refs_file);1331return refs->packed;1332}13331334static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1335{1336returnget_ref_dir(packed_ref_cache->root);1337}13381339static struct ref_dir *get_packed_refs(struct ref_cache *refs)1340{1341returnget_packed_ref_dir(get_packed_ref_cache(refs));1342}13431344/*1345 * Add a reference to the in-memory packed reference cache. This may1346 * only be called while the packed-refs file is locked (see1347 * lock_packed_refs()). To actually write the packed-refs file, call1348 * commit_packed_refs().1349 */1350static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1351{1352struct packed_ref_cache *packed_ref_cache =1353get_packed_ref_cache(&ref_cache);13541355if(!packed_ref_cache->lock)1356die("internal error: packed refs not locked");1357add_ref(get_packed_ref_dir(packed_ref_cache),1358create_ref_entry(refname, sha1, REF_ISPACKED,1));1359}13601361/*1362 * Read the loose references from the namespace dirname into dir1363 * (without recursing). dirname must end with '/'. dir must be the1364 * directory entry corresponding to dirname.1365 */1366static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1367{1368struct ref_cache *refs = dir->ref_cache;1369DIR*d;1370struct dirent *de;1371int dirnamelen =strlen(dirname);1372struct strbuf refname;1373struct strbuf path = STRBUF_INIT;1374size_t path_baselen;13751376if(*refs->name)1377strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1378else1379strbuf_git_path(&path,"%s", dirname);1380 path_baselen = path.len;13811382 d =opendir(path.buf);1383if(!d) {1384strbuf_release(&path);1385return;1386}13871388strbuf_init(&refname, dirnamelen +257);1389strbuf_add(&refname, dirname, dirnamelen);13901391while((de =readdir(d)) != NULL) {1392unsigned char sha1[20];1393struct stat st;1394int flag;13951396if(de->d_name[0] =='.')1397continue;1398if(ends_with(de->d_name,".lock"))1399continue;1400strbuf_addstr(&refname, de->d_name);1401strbuf_addstr(&path, de->d_name);1402if(stat(path.buf, &st) <0) {1403;/* silently ignore */1404}else if(S_ISDIR(st.st_mode)) {1405strbuf_addch(&refname,'/');1406add_entry_to_dir(dir,1407create_dir_entry(refs, refname.buf,1408 refname.len,1));1409}else{1410int read_ok;14111412if(*refs->name) {1413hashclr(sha1);1414 flag =0;1415 read_ok = !resolve_gitlink_ref(refs->name,1416 refname.buf, sha1);1417}else{1418 read_ok = !read_ref_full(refname.buf,1419 RESOLVE_REF_READING,1420 sha1, &flag);1421}14221423if(!read_ok) {1424hashclr(sha1);1425 flag |= REF_ISBROKEN;1426}else if(is_null_sha1(sha1)) {1427/*1428 * It is so astronomically unlikely1429 * that NULL_SHA1 is the SHA-1 of an1430 * actual object that we consider its1431 * appearance in a loose reference1432 * file to be repo corruption1433 * (probably due to a software bug).1434 */1435 flag |= REF_ISBROKEN;1436}14371438if(check_refname_format(refname.buf,1439 REFNAME_ALLOW_ONELEVEL)) {1440if(!refname_is_safe(refname.buf))1441die("loose refname is dangerous:%s", refname.buf);1442hashclr(sha1);1443 flag |= REF_BAD_NAME | REF_ISBROKEN;1444}1445add_entry_to_dir(dir,1446create_ref_entry(refname.buf, sha1, flag,0));1447}1448strbuf_setlen(&refname, dirnamelen);1449strbuf_setlen(&path, path_baselen);1450}1451strbuf_release(&refname);1452strbuf_release(&path);1453closedir(d);1454}14551456static struct ref_dir *get_loose_refs(struct ref_cache *refs)1457{1458if(!refs->loose) {1459/*1460 * Mark the top-level directory complete because we1461 * are about to read the only subdirectory that can1462 * hold references:1463 */1464 refs->loose =create_dir_entry(refs,"",0,0);1465/*1466 * Create an incomplete entry for "refs/":1467 */1468add_entry_to_dir(get_ref_dir(refs->loose),1469create_dir_entry(refs,"refs/",5,1));1470}1471returnget_ref_dir(refs->loose);1472}14731474/* We allow "recursive" symbolic refs. Only within reason, though */1475#define MAXDEPTH 51476#define MAXREFLEN (1024)14771478/*1479 * Called by resolve_gitlink_ref_recursive() after it failed to read1480 * from the loose refs in ref_cache refs. Find <refname> in the1481 * packed-refs file for the submodule.1482 */1483static intresolve_gitlink_packed_ref(struct ref_cache *refs,1484const char*refname,unsigned char*sha1)1485{1486struct ref_entry *ref;1487struct ref_dir *dir =get_packed_refs(refs);14881489 ref =find_ref(dir, refname);1490if(ref == NULL)1491return-1;14921493hashcpy(sha1, ref->u.value.oid.hash);1494return0;1495}14961497static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1498const char*refname,unsigned char*sha1,1499int recursion)1500{1501int fd, len;1502char buffer[128], *p;1503char*path;15041505if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1506return-1;1507 path = *refs->name1508?git_pathdup_submodule(refs->name,"%s", refname)1509:git_pathdup("%s", refname);1510 fd =open(path, O_RDONLY);1511free(path);1512if(fd <0)1513returnresolve_gitlink_packed_ref(refs, refname, sha1);15141515 len =read(fd, buffer,sizeof(buffer)-1);1516close(fd);1517if(len <0)1518return-1;1519while(len &&isspace(buffer[len-1]))1520 len--;1521 buffer[len] =0;15221523/* Was it a detached head or an old-fashioned symlink? */1524if(!get_sha1_hex(buffer, sha1))1525return0;15261527/* Symref? */1528if(strncmp(buffer,"ref:",4))1529return-1;1530 p = buffer +4;1531while(isspace(*p))1532 p++;15331534returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1535}15361537intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1538{1539int len =strlen(path), retval;1540char*submodule;1541struct ref_cache *refs;15421543while(len && path[len-1] =='/')1544 len--;1545if(!len)1546return-1;1547 submodule =xstrndup(path, len);1548 refs =get_ref_cache(submodule);1549free(submodule);15501551 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1552return retval;1553}15541555/*1556 * Return the ref_entry for the given refname from the packed1557 * references. If it does not exist, return NULL.1558 */1559static struct ref_entry *get_packed_ref(const char*refname)1560{1561returnfind_ref(get_packed_refs(&ref_cache), refname);1562}15631564/*1565 * A loose ref file doesn't exist; check for a packed ref. The1566 * options are forwarded from resolve_safe_unsafe().1567 */1568static intresolve_missing_loose_ref(const char*refname,1569int resolve_flags,1570unsigned char*sha1,1571int*flags)1572{1573struct ref_entry *entry;15741575/*1576 * The loose reference file does not exist; check for a packed1577 * reference.1578 */1579 entry =get_packed_ref(refname);1580if(entry) {1581hashcpy(sha1, entry->u.value.oid.hash);1582if(flags)1583*flags |= REF_ISPACKED;1584return0;1585}1586/* The reference is not a packed reference, either. */1587if(resolve_flags & RESOLVE_REF_READING) {1588 errno = ENOENT;1589return-1;1590}else{1591hashclr(sha1);1592return0;1593}1594}15951596/* This function needs to return a meaningful errno on failure */1597static const char*resolve_ref_1(const char*refname,1598int resolve_flags,1599unsigned char*sha1,1600int*flags,1601struct strbuf *sb_refname,1602struct strbuf *sb_path,1603struct strbuf *sb_contents)1604{1605int depth = MAXDEPTH;1606int bad_name =0;16071608if(flags)1609*flags =0;16101611if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1612if(flags)1613*flags |= REF_BAD_NAME;16141615if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1616!refname_is_safe(refname)) {1617 errno = EINVAL;1618return NULL;1619}1620/*1621 * dwim_ref() uses REF_ISBROKEN to distinguish between1622 * missing refs and refs that were present but invalid,1623 * to complain about the latter to stderr.1624 *1625 * We don't know whether the ref exists, so don't set1626 * REF_ISBROKEN yet.1627 */1628 bad_name =1;1629}1630for(;;) {1631const char*path;1632struct stat st;1633char*buf;1634int fd;16351636if(--depth <0) {1637 errno = ELOOP;1638return NULL;1639}16401641strbuf_reset(sb_path);1642strbuf_git_path(sb_path,"%s", refname);1643 path = sb_path->buf;16441645/*1646 * We might have to loop back here to avoid a race1647 * condition: first we lstat() the file, then we try1648 * to read it as a link or as a file. But if somebody1649 * changes the type of the file (file <-> directory1650 * <-> symlink) between the lstat() and reading, then1651 * we don't want to report that as an error but rather1652 * try again starting with the lstat().1653 */1654 stat_ref:1655if(lstat(path, &st) <0) {1656if(errno != ENOENT)1657return NULL;1658if(resolve_missing_loose_ref(refname, resolve_flags,1659 sha1, flags))1660return NULL;1661if(bad_name) {1662hashclr(sha1);1663if(flags)1664*flags |= REF_ISBROKEN;1665}1666return refname;1667}16681669/* Follow "normalized" - ie "refs/.." symlinks by hand */1670if(S_ISLNK(st.st_mode)) {1671strbuf_reset(sb_contents);1672if(strbuf_readlink(sb_contents, path,0) <0) {1673if(errno == ENOENT || errno == EINVAL)1674/* inconsistent with lstat; retry */1675goto stat_ref;1676else1677return NULL;1678}1679if(starts_with(sb_contents->buf,"refs/") &&1680!check_refname_format(sb_contents->buf,0)) {1681strbuf_swap(sb_refname, sb_contents);1682 refname = sb_refname->buf;1683if(flags)1684*flags |= REF_ISSYMREF;1685if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1686hashclr(sha1);1687return refname;1688}1689continue;1690}1691}16921693/* Is it a directory? */1694if(S_ISDIR(st.st_mode)) {1695 errno = EISDIR;1696return NULL;1697}16981699/*1700 * Anything else, just open it and try to use it as1701 * a ref1702 */1703 fd =open(path, O_RDONLY);1704if(fd <0) {1705if(errno == ENOENT)1706/* inconsistent with lstat; retry */1707goto stat_ref;1708else1709return NULL;1710}1711strbuf_reset(sb_contents);1712if(strbuf_read(sb_contents, fd,256) <0) {1713int save_errno = errno;1714close(fd);1715 errno = save_errno;1716return NULL;1717}1718close(fd);1719strbuf_rtrim(sb_contents);17201721/*1722 * Is it a symbolic ref?1723 */1724if(!starts_with(sb_contents->buf,"ref:")) {1725/*1726 * Please note that FETCH_HEAD has a second1727 * line containing other data.1728 */1729if(get_sha1_hex(sb_contents->buf, sha1) ||1730(sb_contents->buf[40] !='\0'&& !isspace(sb_contents->buf[40]))) {1731if(flags)1732*flags |= REF_ISBROKEN;1733 errno = EINVAL;1734return NULL;1735}1736if(bad_name) {1737hashclr(sha1);1738if(flags)1739*flags |= REF_ISBROKEN;1740}1741return refname;1742}1743if(flags)1744*flags |= REF_ISSYMREF;1745 buf = sb_contents->buf +4;1746while(isspace(*buf))1747 buf++;1748strbuf_reset(sb_refname);1749strbuf_addstr(sb_refname, buf);1750 refname = sb_refname->buf;1751if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1752hashclr(sha1);1753return refname;1754}1755if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1756if(flags)1757*flags |= REF_ISBROKEN;17581759if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1760!refname_is_safe(buf)) {1761 errno = EINVAL;1762return NULL;1763}1764 bad_name =1;1765}1766}1767}17681769const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1770unsigned char*sha1,int*flags)1771{1772static struct strbuf sb_refname = STRBUF_INIT;1773struct strbuf sb_contents = STRBUF_INIT;1774struct strbuf sb_path = STRBUF_INIT;1775const char*ret;17761777 ret =resolve_ref_1(refname, resolve_flags, sha1, flags,1778&sb_refname, &sb_path, &sb_contents);1779strbuf_release(&sb_path);1780strbuf_release(&sb_contents);1781return ret;1782}17831784char*resolve_refdup(const char*refname,int resolve_flags,1785unsigned char*sha1,int*flags)1786{1787returnxstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1788 sha1, flags));1789}17901791/* The argument to filter_refs */1792struct ref_filter {1793const char*pattern;1794 each_ref_fn *fn;1795void*cb_data;1796};17971798intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1799{1800if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1801return0;1802return-1;1803}18041805intread_ref(const char*refname,unsigned char*sha1)1806{1807returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1808}18091810intref_exists(const char*refname)1811{1812unsigned char sha1[20];1813return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1814}18151816static intfilter_refs(const char*refname,const struct object_id *oid,1817int flags,void*data)1818{1819struct ref_filter *filter = (struct ref_filter *)data;18201821if(wildmatch(filter->pattern, refname,0, NULL))1822return0;1823return filter->fn(refname, oid, flags, filter->cb_data);1824}18251826enum peel_status {1827/* object was peeled successfully: */1828 PEEL_PEELED =0,18291830/*1831 * object cannot be peeled because the named object (or an1832 * object referred to by a tag in the peel chain), does not1833 * exist.1834 */1835 PEEL_INVALID = -1,18361837/* object cannot be peeled because it is not a tag: */1838 PEEL_NON_TAG = -2,18391840/* ref_entry contains no peeled value because it is a symref: */1841 PEEL_IS_SYMREF = -3,18421843/*1844 * ref_entry cannot be peeled because it is broken (i.e., the1845 * symbolic reference cannot even be resolved to an object1846 * name):1847 */1848 PEEL_BROKEN = -41849};18501851/*1852 * Peel the named object; i.e., if the object is a tag, resolve the1853 * tag recursively until a non-tag is found. If successful, store the1854 * result to sha1 and return PEEL_PEELED. If the object is not a tag1855 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1856 * and leave sha1 unchanged.1857 */1858static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1859{1860struct object *o =lookup_unknown_object(name);18611862if(o->type == OBJ_NONE) {1863int type =sha1_object_info(name, NULL);1864if(type <0|| !object_as_type(o, type,0))1865return PEEL_INVALID;1866}18671868if(o->type != OBJ_TAG)1869return PEEL_NON_TAG;18701871 o =deref_tag_noverify(o);1872if(!o)1873return PEEL_INVALID;18741875hashcpy(sha1, o->sha1);1876return PEEL_PEELED;1877}18781879/*1880 * Peel the entry (if possible) and return its new peel_status. If1881 * repeel is true, re-peel the entry even if there is an old peeled1882 * value that is already stored in it.1883 *1884 * It is OK to call this function with a packed reference entry that1885 * might be stale and might even refer to an object that has since1886 * been garbage-collected. In such a case, if the entry has1887 * REF_KNOWS_PEELED then leave the status unchanged and return1888 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1889 */1890static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1891{1892enum peel_status status;18931894if(entry->flag & REF_KNOWS_PEELED) {1895if(repeel) {1896 entry->flag &= ~REF_KNOWS_PEELED;1897oidclr(&entry->u.value.peeled);1898}else{1899returnis_null_oid(&entry->u.value.peeled) ?1900 PEEL_NON_TAG : PEEL_PEELED;1901}1902}1903if(entry->flag & REF_ISBROKEN)1904return PEEL_BROKEN;1905if(entry->flag & REF_ISSYMREF)1906return PEEL_IS_SYMREF;19071908 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1909if(status == PEEL_PEELED || status == PEEL_NON_TAG)1910 entry->flag |= REF_KNOWS_PEELED;1911return status;1912}19131914intpeel_ref(const char*refname,unsigned char*sha1)1915{1916int flag;1917unsigned char base[20];19181919if(current_ref && (current_ref->name == refname1920|| !strcmp(current_ref->name, refname))) {1921if(peel_entry(current_ref,0))1922return-1;1923hashcpy(sha1, current_ref->u.value.peeled.hash);1924return0;1925}19261927if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1928return-1;19291930/*1931 * If the reference is packed, read its ref_entry from the1932 * cache in the hope that we already know its peeled value.1933 * We only try this optimization on packed references because1934 * (a) forcing the filling of the loose reference cache could1935 * be expensive and (b) loose references anyway usually do not1936 * have REF_KNOWS_PEELED.1937 */1938if(flag & REF_ISPACKED) {1939struct ref_entry *r =get_packed_ref(refname);1940if(r) {1941if(peel_entry(r,0))1942return-1;1943hashcpy(sha1, r->u.value.peeled.hash);1944return0;1945}1946}19471948returnpeel_object(base, sha1);1949}19501951struct warn_if_dangling_data {1952FILE*fp;1953const char*refname;1954const struct string_list *refnames;1955const char*msg_fmt;1956};19571958static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1959int flags,void*cb_data)1960{1961struct warn_if_dangling_data *d = cb_data;1962const char*resolves_to;1963struct object_id junk;19641965if(!(flags & REF_ISSYMREF))1966return0;19671968 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1969if(!resolves_to1970|| (d->refname1971?strcmp(resolves_to, d->refname)1972: !string_list_has_string(d->refnames, resolves_to))) {1973return0;1974}19751976fprintf(d->fp, d->msg_fmt, refname);1977fputc('\n', d->fp);1978return0;1979}19801981voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1982{1983struct warn_if_dangling_data data;19841985 data.fp = fp;1986 data.refname = refname;1987 data.refnames = NULL;1988 data.msg_fmt = msg_fmt;1989for_each_rawref(warn_if_dangling_symref, &data);1990}19911992voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1993{1994struct warn_if_dangling_data data;19951996 data.fp = fp;1997 data.refname = NULL;1998 data.refnames = refnames;1999 data.msg_fmt = msg_fmt;2000for_each_rawref(warn_if_dangling_symref, &data);2001}20022003/*2004 * Call fn for each reference in the specified ref_cache, omitting2005 * references not in the containing_dir of base. fn is called for all2006 * references, including broken ones. If fn ever returns a non-zero2007 * value, stop the iteration and return that value; otherwise, return2008 * 0.2009 */2010static intdo_for_each_entry(struct ref_cache *refs,const char*base,2011 each_ref_entry_fn fn,void*cb_data)2012{2013struct packed_ref_cache *packed_ref_cache;2014struct ref_dir *loose_dir;2015struct ref_dir *packed_dir;2016int retval =0;20172018/*2019 * We must make sure that all loose refs are read before accessing the2020 * packed-refs file; this avoids a race condition in which loose refs2021 * are migrated to the packed-refs file by a simultaneous process, but2022 * our in-memory view is from before the migration. get_packed_ref_cache()2023 * takes care of making sure our view is up to date with what is on2024 * disk.2025 */2026 loose_dir =get_loose_refs(refs);2027if(base && *base) {2028 loose_dir =find_containing_dir(loose_dir, base,0);2029}2030if(loose_dir)2031prime_ref_dir(loose_dir);20322033 packed_ref_cache =get_packed_ref_cache(refs);2034acquire_packed_ref_cache(packed_ref_cache);2035 packed_dir =get_packed_ref_dir(packed_ref_cache);2036if(base && *base) {2037 packed_dir =find_containing_dir(packed_dir, base,0);2038}20392040if(packed_dir && loose_dir) {2041sort_ref_dir(packed_dir);2042sort_ref_dir(loose_dir);2043 retval =do_for_each_entry_in_dirs(2044 packed_dir, loose_dir, fn, cb_data);2045}else if(packed_dir) {2046sort_ref_dir(packed_dir);2047 retval =do_for_each_entry_in_dir(2048 packed_dir,0, fn, cb_data);2049}else if(loose_dir) {2050sort_ref_dir(loose_dir);2051 retval =do_for_each_entry_in_dir(2052 loose_dir,0, fn, cb_data);2053}20542055release_packed_ref_cache(packed_ref_cache);2056return retval;2057}20582059/*2060 * Call fn for each reference in the specified ref_cache for which the2061 * refname begins with base. If trim is non-zero, then trim that many2062 * characters off the beginning of each refname before passing the2063 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2064 * broken references in the iteration. If fn ever returns a non-zero2065 * value, stop the iteration and return that value; otherwise, return2066 * 0.2067 */2068static intdo_for_each_ref(struct ref_cache *refs,const char*base,2069 each_ref_fn fn,int trim,int flags,void*cb_data)2070{2071struct ref_entry_cb data;2072 data.base = base;2073 data.trim = trim;2074 data.flags = flags;2075 data.fn = fn;2076 data.cb_data = cb_data;20772078if(ref_paranoia <0)2079 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2080if(ref_paranoia)2081 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20822083returndo_for_each_entry(refs, base, do_one_ref, &data);2084}20852086static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2087{2088struct object_id oid;2089int flag;20902091if(submodule) {2092if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2093returnfn("HEAD", &oid,0, cb_data);20942095return0;2096}20972098if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2099returnfn("HEAD", &oid, flag, cb_data);21002101return0;2102}21032104inthead_ref(each_ref_fn fn,void*cb_data)2105{2106returndo_head_ref(NULL, fn, cb_data);2107}21082109inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2110{2111returndo_head_ref(submodule, fn, cb_data);2112}21132114intfor_each_ref(each_ref_fn fn,void*cb_data)2115{2116returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2117}21182119intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2120{2121returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2122}21232124intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2125{2126returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2127}21282129intfor_each_fullref_in(const char*prefix, each_ref_fn fn,void*cb_data,unsigned int broken)2130{2131unsigned int flag =0;21322133if(broken)2134 flag = DO_FOR_EACH_INCLUDE_BROKEN;2135returndo_for_each_ref(&ref_cache, prefix, fn,0, flag, cb_data);2136}21372138intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2139 each_ref_fn fn,void*cb_data)2140{2141returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2142}21432144intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2145{2146returnfor_each_ref_in("refs/tags/", fn, cb_data);2147}21482149intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2150{2151returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2152}21532154intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2155{2156returnfor_each_ref_in("refs/heads/", fn, cb_data);2157}21582159intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2160{2161returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2162}21632164intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2165{2166returnfor_each_ref_in("refs/remotes/", fn, cb_data);2167}21682169intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2170{2171returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2172}21732174intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2175{2176returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,2177strlen(git_replace_ref_base),0, cb_data);2178}21792180inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2181{2182struct strbuf buf = STRBUF_INIT;2183int ret =0;2184struct object_id oid;2185int flag;21862187strbuf_addf(&buf,"%sHEAD",get_git_namespace());2188if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2189 ret =fn(buf.buf, &oid, flag, cb_data);2190strbuf_release(&buf);21912192return ret;2193}21942195intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2196{2197struct strbuf buf = STRBUF_INIT;2198int ret;2199strbuf_addf(&buf,"%srefs/",get_git_namespace());2200 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2201strbuf_release(&buf);2202return ret;2203}22042205intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2206const char*prefix,void*cb_data)2207{2208struct strbuf real_pattern = STRBUF_INIT;2209struct ref_filter filter;2210int ret;22112212if(!prefix && !starts_with(pattern,"refs/"))2213strbuf_addstr(&real_pattern,"refs/");2214else if(prefix)2215strbuf_addstr(&real_pattern, prefix);2216strbuf_addstr(&real_pattern, pattern);22172218if(!has_glob_specials(pattern)) {2219/* Append implied '/' '*' if not present. */2220strbuf_complete(&real_pattern,'/');2221/* No need to check for '*', there is none. */2222strbuf_addch(&real_pattern,'*');2223}22242225 filter.pattern = real_pattern.buf;2226 filter.fn = fn;2227 filter.cb_data = cb_data;2228 ret =for_each_ref(filter_refs, &filter);22292230strbuf_release(&real_pattern);2231return ret;2232}22332234intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2235{2236returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2237}22382239intfor_each_rawref(each_ref_fn fn,void*cb_data)2240{2241returndo_for_each_ref(&ref_cache,"", fn,0,2242 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2243}22442245const char*prettify_refname(const char*name)2246{2247return name + (2248starts_with(name,"refs/heads/") ?11:2249starts_with(name,"refs/tags/") ?10:2250starts_with(name,"refs/remotes/") ?13:22510);2252}22532254static const char*ref_rev_parse_rules[] = {2255"%.*s",2256"refs/%.*s",2257"refs/tags/%.*s",2258"refs/heads/%.*s",2259"refs/remotes/%.*s",2260"refs/remotes/%.*s/HEAD",2261 NULL2262};22632264intrefname_match(const char*abbrev_name,const char*full_name)2265{2266const char**p;2267const int abbrev_name_len =strlen(abbrev_name);22682269for(p = ref_rev_parse_rules; *p; p++) {2270if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2271return1;2272}2273}22742275return0;2276}22772278static voidunlock_ref(struct ref_lock *lock)2279{2280/* Do not free lock->lk -- atexit() still looks at them */2281if(lock->lk)2282rollback_lock_file(lock->lk);2283free(lock->ref_name);2284free(lock->orig_ref_name);2285free(lock);2286}22872288/*2289 * Verify that the reference locked by lock has the value old_sha1.2290 * Fail if the reference doesn't exist and mustexist is set. Return 02291 * on success. On error, write an error message to err, set errno, and2292 * return a negative value.2293 */2294static intverify_lock(struct ref_lock *lock,2295const unsigned char*old_sha1,int mustexist,2296struct strbuf *err)2297{2298assert(err);22992300if(read_ref_full(lock->ref_name,2301 mustexist ? RESOLVE_REF_READING :0,2302 lock->old_oid.hash, NULL)) {2303int save_errno = errno;2304strbuf_addf(err,"can't verify ref%s", lock->ref_name);2305 errno = save_errno;2306return-1;2307}2308if(hashcmp(lock->old_oid.hash, old_sha1)) {2309strbuf_addf(err,"ref%sis at%sbut expected%s",2310 lock->ref_name,2311sha1_to_hex(lock->old_oid.hash),2312sha1_to_hex(old_sha1));2313 errno = EBUSY;2314return-1;2315}2316return0;2317}23182319static intremove_empty_directories(struct strbuf *path)2320{2321/*2322 * we want to create a file but there is a directory there;2323 * if that is an empty directory (or a directory that contains2324 * only empty directories), remove them.2325 */2326returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);2327}23282329/*2330 * *string and *len will only be substituted, and *string returned (for2331 * later free()ing) if the string passed in is a magic short-hand form2332 * to name a branch.2333 */2334static char*substitute_branch_name(const char**string,int*len)2335{2336struct strbuf buf = STRBUF_INIT;2337int ret =interpret_branch_name(*string, *len, &buf);23382339if(ret == *len) {2340size_t size;2341*string =strbuf_detach(&buf, &size);2342*len = size;2343return(char*)*string;2344}23452346return NULL;2347}23482349intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2350{2351char*last_branch =substitute_branch_name(&str, &len);2352const char**p, *r;2353int refs_found =0;23542355*ref = NULL;2356for(p = ref_rev_parse_rules; *p; p++) {2357char fullref[PATH_MAX];2358unsigned char sha1_from_ref[20];2359unsigned char*this_result;2360int flag;23612362 this_result = refs_found ? sha1_from_ref : sha1;2363mksnpath(fullref,sizeof(fullref), *p, len, str);2364 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2365 this_result, &flag);2366if(r) {2367if(!refs_found++)2368*ref =xstrdup(r);2369if(!warn_ambiguous_refs)2370break;2371}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2372warning("ignoring dangling symref%s.", fullref);2373}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2374warning("ignoring broken ref%s.", fullref);2375}2376}2377free(last_branch);2378return refs_found;2379}23802381intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2382{2383char*last_branch =substitute_branch_name(&str, &len);2384const char**p;2385int logs_found =0;23862387*log = NULL;2388for(p = ref_rev_parse_rules; *p; p++) {2389unsigned char hash[20];2390char path[PATH_MAX];2391const char*ref, *it;23922393mksnpath(path,sizeof(path), *p, len, str);2394 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2395 hash, NULL);2396if(!ref)2397continue;2398if(reflog_exists(path))2399 it = path;2400else if(strcmp(ref, path) &&reflog_exists(ref))2401 it = ref;2402else2403continue;2404if(!logs_found++) {2405*log =xstrdup(it);2406hashcpy(sha1, hash);2407}2408if(!warn_ambiguous_refs)2409break;2410}2411free(last_branch);2412return logs_found;2413}24142415/*2416 * Locks a ref returning the lock on success and NULL on failure.2417 * On failure errno is set to something meaningful.2418 */2419static struct ref_lock *lock_ref_sha1_basic(const char*refname,2420const unsigned char*old_sha1,2421const struct string_list *extras,2422const struct string_list *skip,2423unsigned int flags,int*type_p,2424struct strbuf *err)2425{2426struct strbuf ref_file = STRBUF_INIT;2427struct strbuf orig_ref_file = STRBUF_INIT;2428const char*orig_refname = refname;2429struct ref_lock *lock;2430int last_errno =0;2431int type, lflags;2432int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2433int resolve_flags =0;2434int attempts_remaining =3;24352436assert(err);24372438 lock =xcalloc(1,sizeof(struct ref_lock));24392440if(mustexist)2441 resolve_flags |= RESOLVE_REF_READING;2442if(flags & REF_DELETING) {2443 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2444if(flags & REF_NODEREF)2445 resolve_flags |= RESOLVE_REF_NO_RECURSE;2446}24472448 refname =resolve_ref_unsafe(refname, resolve_flags,2449 lock->old_oid.hash, &type);2450if(!refname && errno == EISDIR) {2451/*2452 * we are trying to lock foo but we used to2453 * have foo/bar which now does not exist;2454 * it is normal for the empty directory 'foo'2455 * to remain.2456 */2457strbuf_git_path(&orig_ref_file,"%s", orig_refname);2458if(remove_empty_directories(&orig_ref_file)) {2459 last_errno = errno;2460if(!verify_refname_available_dir(orig_refname, extras, skip,2461get_loose_refs(&ref_cache), err))2462strbuf_addf(err,"there are still refs under '%s'",2463 orig_refname);2464goto error_return;2465}2466 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2467 lock->old_oid.hash, &type);2468}2469if(type_p)2470*type_p = type;2471if(!refname) {2472 last_errno = errno;2473if(last_errno != ENOTDIR ||2474!verify_refname_available_dir(orig_refname, extras, skip,2475get_loose_refs(&ref_cache), err))2476strbuf_addf(err,"unable to resolve reference%s:%s",2477 orig_refname,strerror(last_errno));24782479goto error_return;2480}2481/*2482 * If the ref did not exist and we are creating it, make sure2483 * there is no existing packed ref whose name begins with our2484 * refname, nor a packed ref whose name is a proper prefix of2485 * our refname.2486 */2487if(is_null_oid(&lock->old_oid) &&2488verify_refname_available_dir(refname, extras, skip,2489get_packed_refs(&ref_cache), err)) {2490 last_errno = ENOTDIR;2491goto error_return;2492}24932494 lock->lk =xcalloc(1,sizeof(struct lock_file));24952496 lflags =0;2497if(flags & REF_NODEREF) {2498 refname = orig_refname;2499 lflags |= LOCK_NO_DEREF;2500}2501 lock->ref_name =xstrdup(refname);2502 lock->orig_ref_name =xstrdup(orig_refname);2503strbuf_git_path(&ref_file,"%s", refname);25042505 retry:2506switch(safe_create_leading_directories_const(ref_file.buf)) {2507case SCLD_OK:2508break;/* success */2509case SCLD_VANISHED:2510if(--attempts_remaining >0)2511goto retry;2512/* fall through */2513default:2514 last_errno = errno;2515strbuf_addf(err,"unable to create directory for%s",2516 ref_file.buf);2517goto error_return;2518}25192520if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2521 last_errno = errno;2522if(errno == ENOENT && --attempts_remaining >0)2523/*2524 * Maybe somebody just deleted one of the2525 * directories leading to ref_file. Try2526 * again:2527 */2528goto retry;2529else{2530unable_to_lock_message(ref_file.buf, errno, err);2531goto error_return;2532}2533}2534if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2535 last_errno = errno;2536goto error_return;2537}2538goto out;25392540 error_return:2541unlock_ref(lock);2542 lock = NULL;25432544 out:2545strbuf_release(&ref_file);2546strbuf_release(&orig_ref_file);2547 errno = last_errno;2548return lock;2549}25502551/*2552 * Write an entry to the packed-refs file for the specified refname.2553 * If peeled is non-NULL, write it as the entry's peeled value.2554 */2555static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2556unsigned char*peeled)2557{2558fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2559if(peeled)2560fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2561}25622563/*2564 * An each_ref_entry_fn that writes the entry to a packed-refs file.2565 */2566static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2567{2568enum peel_status peel_status =peel_entry(entry,0);25692570if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2571error("internal error:%sis not a valid packed reference!",2572 entry->name);2573write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2574 peel_status == PEEL_PEELED ?2575 entry->u.value.peeled.hash : NULL);2576return0;2577}25782579/*2580 * Lock the packed-refs file for writing. Flags is passed to2581 * hold_lock_file_for_update(). Return 0 on success. On errors, set2582 * errno appropriately and return a nonzero value.2583 */2584static intlock_packed_refs(int flags)2585{2586static int timeout_configured =0;2587static int timeout_value =1000;25882589struct packed_ref_cache *packed_ref_cache;25902591if(!timeout_configured) {2592git_config_get_int("core.packedrefstimeout", &timeout_value);2593 timeout_configured =1;2594}25952596if(hold_lock_file_for_update_timeout(2597&packlock,git_path("packed-refs"),2598 flags, timeout_value) <0)2599return-1;2600/*2601 * Get the current packed-refs while holding the lock. If the2602 * packed-refs file has been modified since we last read it,2603 * this will automatically invalidate the cache and re-read2604 * the packed-refs file.2605 */2606 packed_ref_cache =get_packed_ref_cache(&ref_cache);2607 packed_ref_cache->lock = &packlock;2608/* Increment the reference count to prevent it from being freed: */2609acquire_packed_ref_cache(packed_ref_cache);2610return0;2611}26122613/*2614 * Write the current version of the packed refs cache from memory to2615 * disk. The packed-refs file must already be locked for writing (see2616 * lock_packed_refs()). Return zero on success. On errors, set errno2617 * and return a nonzero value2618 */2619static intcommit_packed_refs(void)2620{2621struct packed_ref_cache *packed_ref_cache =2622get_packed_ref_cache(&ref_cache);2623int error =0;2624int save_errno =0;2625FILE*out;26262627if(!packed_ref_cache->lock)2628die("internal error: packed-refs not locked");26292630 out =fdopen_lock_file(packed_ref_cache->lock,"w");2631if(!out)2632die_errno("unable to fdopen packed-refs descriptor");26332634fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2635do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),26360, write_packed_entry_fn, out);26372638if(commit_lock_file(packed_ref_cache->lock)) {2639 save_errno = errno;2640 error = -1;2641}2642 packed_ref_cache->lock = NULL;2643release_packed_ref_cache(packed_ref_cache);2644 errno = save_errno;2645return error;2646}26472648/*2649 * Rollback the lockfile for the packed-refs file, and discard the2650 * in-memory packed reference cache. (The packed-refs file will be2651 * read anew if it is needed again after this function is called.)2652 */2653static voidrollback_packed_refs(void)2654{2655struct packed_ref_cache *packed_ref_cache =2656get_packed_ref_cache(&ref_cache);26572658if(!packed_ref_cache->lock)2659die("internal error: packed-refs not locked");2660rollback_lock_file(packed_ref_cache->lock);2661 packed_ref_cache->lock = NULL;2662release_packed_ref_cache(packed_ref_cache);2663clear_packed_ref_cache(&ref_cache);2664}26652666struct ref_to_prune {2667struct ref_to_prune *next;2668unsigned char sha1[20];2669char name[FLEX_ARRAY];2670};26712672struct pack_refs_cb_data {2673unsigned int flags;2674struct ref_dir *packed_refs;2675struct ref_to_prune *ref_to_prune;2676};26772678/*2679 * An each_ref_entry_fn that is run over loose references only. If2680 * the loose reference can be packed, add an entry in the packed ref2681 * cache. If the reference should be pruned, also add it to2682 * ref_to_prune in the pack_refs_cb_data.2683 */2684static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2685{2686struct pack_refs_cb_data *cb = cb_data;2687enum peel_status peel_status;2688struct ref_entry *packed_entry;2689int is_tag_ref =starts_with(entry->name,"refs/tags/");26902691/* Do not pack per-worktree refs: */2692if(ref_type(entry->name) != REF_TYPE_NORMAL)2693return0;26942695/* ALWAYS pack tags */2696if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2697return0;26982699/* Do not pack symbolic or broken refs: */2700if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2701return0;27022703/* Add a packed ref cache entry equivalent to the loose entry. */2704 peel_status =peel_entry(entry,1);2705if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2706die("internal error peeling reference%s(%s)",2707 entry->name,oid_to_hex(&entry->u.value.oid));2708 packed_entry =find_ref(cb->packed_refs, entry->name);2709if(packed_entry) {2710/* Overwrite existing packed entry with info from loose entry */2711 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2712oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2713}else{2714 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2715 REF_ISPACKED | REF_KNOWS_PEELED,0);2716add_ref(cb->packed_refs, packed_entry);2717}2718oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);27192720/* Schedule the loose reference for pruning if requested. */2721if((cb->flags & PACK_REFS_PRUNE)) {2722int namelen =strlen(entry->name) +1;2723struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2724hashcpy(n->sha1, entry->u.value.oid.hash);2725memcpy(n->name, entry->name, namelen);/* includes NUL */2726 n->next = cb->ref_to_prune;2727 cb->ref_to_prune = n;2728}2729return0;2730}27312732/*2733 * Remove empty parents, but spare refs/ and immediate subdirs.2734 * Note: munges *name.2735 */2736static voidtry_remove_empty_parents(char*name)2737{2738char*p, *q;2739int i;2740 p = name;2741for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2742while(*p && *p !='/')2743 p++;2744/* tolerate duplicate slashes; see check_refname_format() */2745while(*p =='/')2746 p++;2747}2748for(q = p; *q; q++)2749;2750while(1) {2751while(q > p && *q !='/')2752 q--;2753while(q > p && *(q-1) =='/')2754 q--;2755if(q == p)2756break;2757*q ='\0';2758if(rmdir(git_path("%s", name)))2759break;2760}2761}27622763/* make sure nobody touched the ref, and unlink */2764static voidprune_ref(struct ref_to_prune *r)2765{2766struct ref_transaction *transaction;2767struct strbuf err = STRBUF_INIT;27682769if(check_refname_format(r->name,0))2770return;27712772 transaction =ref_transaction_begin(&err);2773if(!transaction ||2774ref_transaction_delete(transaction, r->name, r->sha1,2775 REF_ISPRUNING, NULL, &err) ||2776ref_transaction_commit(transaction, &err)) {2777ref_transaction_free(transaction);2778error("%s", err.buf);2779strbuf_release(&err);2780return;2781}2782ref_transaction_free(transaction);2783strbuf_release(&err);2784try_remove_empty_parents(r->name);2785}27862787static voidprune_refs(struct ref_to_prune *r)2788{2789while(r) {2790prune_ref(r);2791 r = r->next;2792}2793}27942795intpack_refs(unsigned int flags)2796{2797struct pack_refs_cb_data cbdata;27982799memset(&cbdata,0,sizeof(cbdata));2800 cbdata.flags = flags;28012802lock_packed_refs(LOCK_DIE_ON_ERROR);2803 cbdata.packed_refs =get_packed_refs(&ref_cache);28042805do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2806 pack_if_possible_fn, &cbdata);28072808if(commit_packed_refs())2809die_errno("unable to overwrite old ref-pack file");28102811prune_refs(cbdata.ref_to_prune);2812return0;2813}28142815/*2816 * Rewrite the packed-refs file, omitting any refs listed in2817 * 'refnames'. On error, leave packed-refs unchanged, write an error2818 * message to 'err', and return a nonzero value.2819 *2820 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2821 */2822static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2823{2824struct ref_dir *packed;2825struct string_list_item *refname;2826int ret, needs_repacking =0, removed =0;28272828assert(err);28292830/* Look for a packed ref */2831for_each_string_list_item(refname, refnames) {2832if(get_packed_ref(refname->string)) {2833 needs_repacking =1;2834break;2835}2836}28372838/* Avoid locking if we have nothing to do */2839if(!needs_repacking)2840return0;/* no refname exists in packed refs */28412842if(lock_packed_refs(0)) {2843unable_to_lock_message(git_path("packed-refs"), errno, err);2844return-1;2845}2846 packed =get_packed_refs(&ref_cache);28472848/* Remove refnames from the cache */2849for_each_string_list_item(refname, refnames)2850if(remove_entry(packed, refname->string) != -1)2851 removed =1;2852if(!removed) {2853/*2854 * All packed entries disappeared while we were2855 * acquiring the lock.2856 */2857rollback_packed_refs();2858return0;2859}28602861/* Write what remains */2862 ret =commit_packed_refs();2863if(ret)2864strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2865strerror(errno));2866return ret;2867}28682869static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2870{2871assert(err);28722873if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2874/*2875 * loose. The loose file name is the same as the2876 * lockfile name, minus ".lock":2877 */2878char*loose_filename =get_locked_file_path(lock->lk);2879int res =unlink_or_msg(loose_filename, err);2880free(loose_filename);2881if(res)2882return1;2883}2884return0;2885}28862887static intis_per_worktree_ref(const char*refname)2888{2889return!strcmp(refname,"HEAD") ||2890starts_with(refname,"refs/bisect/");2891}28922893static intis_pseudoref_syntax(const char*refname)2894{2895const char*c;28962897for(c = refname; *c; c++) {2898if(!isupper(*c) && *c !='-'&& *c !='_')2899return0;2900}29012902return1;2903}29042905enum ref_type ref_type(const char*refname)2906{2907if(is_per_worktree_ref(refname))2908return REF_TYPE_PER_WORKTREE;2909if(is_pseudoref_syntax(refname))2910return REF_TYPE_PSEUDOREF;2911return REF_TYPE_NORMAL;2912}29132914static intwrite_pseudoref(const char*pseudoref,const unsigned char*sha1,2915const unsigned char*old_sha1,struct strbuf *err)2916{2917const char*filename;2918int fd;2919static struct lock_file lock;2920struct strbuf buf = STRBUF_INIT;2921int ret = -1;29222923strbuf_addf(&buf,"%s\n",sha1_to_hex(sha1));29242925 filename =git_path("%s", pseudoref);2926 fd =hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);2927if(fd <0) {2928strbuf_addf(err,"Could not open '%s' for writing:%s",2929 filename,strerror(errno));2930return-1;2931}29322933if(old_sha1) {2934unsigned char actual_old_sha1[20];29352936if(read_ref(pseudoref, actual_old_sha1))2937die("could not read ref '%s'", pseudoref);2938if(hashcmp(actual_old_sha1, old_sha1)) {2939strbuf_addf(err,"Unexpected sha1 when writing%s", pseudoref);2940rollback_lock_file(&lock);2941goto done;2942}2943}29442945if(write_in_full(fd, buf.buf, buf.len) != buf.len) {2946strbuf_addf(err,"Could not write to '%s'", filename);2947rollback_lock_file(&lock);2948goto done;2949}29502951commit_lock_file(&lock);2952 ret =0;2953done:2954strbuf_release(&buf);2955return ret;2956}29572958static intdelete_pseudoref(const char*pseudoref,const unsigned char*old_sha1)2959{2960static struct lock_file lock;2961const char*filename;29622963 filename =git_path("%s", pseudoref);29642965if(old_sha1 && !is_null_sha1(old_sha1)) {2966int fd;2967unsigned char actual_old_sha1[20];29682969 fd =hold_lock_file_for_update(&lock, filename,2970 LOCK_DIE_ON_ERROR);2971if(fd <0)2972die_errno(_("Could not open '%s' for writing"), filename);2973if(read_ref(pseudoref, actual_old_sha1))2974die("could not read ref '%s'", pseudoref);2975if(hashcmp(actual_old_sha1, old_sha1)) {2976warning("Unexpected sha1 when deleting%s", pseudoref);2977rollback_lock_file(&lock);2978return-1;2979}29802981unlink(filename);2982rollback_lock_file(&lock);2983}else{2984unlink(filename);2985}29862987return0;2988}29892990intdelete_ref(const char*refname,const unsigned char*old_sha1,2991unsigned int flags)2992{2993struct ref_transaction *transaction;2994struct strbuf err = STRBUF_INIT;29952996if(ref_type(refname) == REF_TYPE_PSEUDOREF)2997returndelete_pseudoref(refname, old_sha1);29982999 transaction =ref_transaction_begin(&err);3000if(!transaction ||3001ref_transaction_delete(transaction, refname, old_sha1,3002 flags, NULL, &err) ||3003ref_transaction_commit(transaction, &err)) {3004error("%s", err.buf);3005ref_transaction_free(transaction);3006strbuf_release(&err);3007return1;3008}3009ref_transaction_free(transaction);3010strbuf_release(&err);3011return0;3012}30133014intdelete_refs(struct string_list *refnames)3015{3016struct strbuf err = STRBUF_INIT;3017int i, result =0;30183019if(!refnames->nr)3020return0;30213022 result =repack_without_refs(refnames, &err);3023if(result) {3024/*3025 * If we failed to rewrite the packed-refs file, then3026 * it is unsafe to try to remove loose refs, because3027 * doing so might expose an obsolete packed value for3028 * a reference that might even point at an object that3029 * has been garbage collected.3030 */3031if(refnames->nr ==1)3032error(_("could not delete reference%s:%s"),3033 refnames->items[0].string, err.buf);3034else3035error(_("could not delete references:%s"), err.buf);30363037goto out;3038}30393040for(i =0; i < refnames->nr; i++) {3041const char*refname = refnames->items[i].string;30423043if(delete_ref(refname, NULL,0))3044 result |=error(_("could not remove reference%s"), refname);3045}30463047out:3048strbuf_release(&err);3049return result;3050}30513052/*3053 * People using contrib's git-new-workdir have .git/logs/refs ->3054 * /some/other/path/.git/logs/refs, and that may live on another device.3055 *3056 * IOW, to avoid cross device rename errors, the temporary renamed log must3057 * live into logs/refs.3058 */3059#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"30603061static intrename_tmp_log(const char*newrefname)3062{3063int attempts_remaining =4;3064struct strbuf path = STRBUF_INIT;3065int ret = -1;30663067 retry:3068strbuf_reset(&path);3069strbuf_git_path(&path,"logs/%s", newrefname);3070switch(safe_create_leading_directories_const(path.buf)) {3071case SCLD_OK:3072break;/* success */3073case SCLD_VANISHED:3074if(--attempts_remaining >0)3075goto retry;3076/* fall through */3077default:3078error("unable to create directory for%s", newrefname);3079goto out;3080}30813082if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {3083if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {3084/*3085 * rename(a, b) when b is an existing3086 * directory ought to result in ISDIR, but3087 * Solaris 5.8 gives ENOTDIR. Sheesh.3088 */3089if(remove_empty_directories(&path)) {3090error("Directory not empty: logs/%s", newrefname);3091goto out;3092}3093goto retry;3094}else if(errno == ENOENT && --attempts_remaining >0) {3095/*3096 * Maybe another process just deleted one of3097 * the directories in the path to newrefname.3098 * Try again from the beginning.3099 */3100goto retry;3101}else{3102error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",3103 newrefname,strerror(errno));3104goto out;3105}3106}3107 ret =0;3108out:3109strbuf_release(&path);3110return ret;3111}31123113/*3114 * Return 0 if a reference named refname could be created without3115 * conflicting with the name of an existing reference. Otherwise,3116 * return a negative value and write an explanation to err. If extras3117 * is non-NULL, it is a list of additional refnames with which refname3118 * is not allowed to conflict. If skip is non-NULL, ignore potential3119 * conflicts with refs in skip (e.g., because they are scheduled for3120 * deletion in the same operation). Behavior is undefined if the same3121 * name is listed in both extras and skip.3122 *3123 * Two reference names conflict if one of them exactly matches the3124 * leading components of the other; e.g., "foo/bar" conflicts with3125 * both "foo" and with "foo/bar/baz" but not with "foo/bar" or3126 * "foo/barbados".3127 *3128 * extras and skip must be sorted.3129 */3130static intverify_refname_available(const char*newname,3131struct string_list *extras,3132struct string_list *skip,3133struct strbuf *err)3134{3135struct ref_dir *packed_refs =get_packed_refs(&ref_cache);3136struct ref_dir *loose_refs =get_loose_refs(&ref_cache);31373138if(verify_refname_available_dir(newname, extras, skip,3139 packed_refs, err) ||3140verify_refname_available_dir(newname, extras, skip,3141 loose_refs, err))3142return-1;31433144return0;3145}31463147static intrename_ref_available(const char*oldname,const char*newname)3148{3149struct string_list skip = STRING_LIST_INIT_NODUP;3150struct strbuf err = STRBUF_INIT;3151int ret;31523153string_list_insert(&skip, oldname);3154 ret = !verify_refname_available(newname, NULL, &skip, &err);3155if(!ret)3156error("%s", err.buf);31573158string_list_clear(&skip,0);3159strbuf_release(&err);3160return ret;3161}31623163static intwrite_ref_to_lockfile(struct ref_lock *lock,3164const unsigned char*sha1,struct strbuf *err);3165static intcommit_ref_update(struct ref_lock *lock,3166const unsigned char*sha1,const char*logmsg,3167int flags,struct strbuf *err);31683169intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)3170{3171unsigned char sha1[20], orig_sha1[20];3172int flag =0, logmoved =0;3173struct ref_lock *lock;3174struct stat loginfo;3175int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);3176const char*symref = NULL;3177struct strbuf err = STRBUF_INIT;31783179if(log &&S_ISLNK(loginfo.st_mode))3180returnerror("reflog for%sis a symlink", oldrefname);31813182 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3183 orig_sha1, &flag);3184if(flag & REF_ISSYMREF)3185returnerror("refname%sis a symbolic ref, renaming it is not supported",3186 oldrefname);3187if(!symref)3188returnerror("refname%snot found", oldrefname);31893190if(!rename_ref_available(oldrefname, newrefname))3191return1;31923193if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3194returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3195 oldrefname,strerror(errno));31963197if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3198error("unable to delete old%s", oldrefname);3199goto rollback;3200}32013202if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3203delete_ref(newrefname, sha1, REF_NODEREF)) {3204if(errno==EISDIR) {3205struct strbuf path = STRBUF_INIT;3206int result;32073208strbuf_git_path(&path,"%s", newrefname);3209 result =remove_empty_directories(&path);3210strbuf_release(&path);32113212if(result) {3213error("Directory not empty:%s", newrefname);3214goto rollback;3215}3216}else{3217error("unable to delete existing%s", newrefname);3218goto rollback;3219}3220}32213222if(log &&rename_tmp_log(newrefname))3223goto rollback;32243225 logmoved = log;32263227 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3228if(!lock) {3229error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3230strbuf_release(&err);3231goto rollback;3232}3233hashcpy(lock->old_oid.hash, orig_sha1);32343235if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3236commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {3237error("unable to write current sha1 into%s:%s", newrefname, err.buf);3238strbuf_release(&err);3239goto rollback;3240}32413242return0;32433244 rollback:3245 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3246if(!lock) {3247error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3248strbuf_release(&err);3249goto rollbacklog;3250}32513252 flag = log_all_ref_updates;3253 log_all_ref_updates =0;3254if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3255commit_ref_update(lock, orig_sha1, NULL,0, &err)) {3256error("unable to write current sha1 into%s:%s", oldrefname, err.buf);3257strbuf_release(&err);3258}3259 log_all_ref_updates = flag;32603261 rollbacklog:3262if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3263error("unable to restore logfile%sfrom%s:%s",3264 oldrefname, newrefname,strerror(errno));3265if(!logmoved && log &&3266rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3267error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3268 oldrefname,strerror(errno));32693270return1;3271}32723273static intclose_ref(struct ref_lock *lock)3274{3275if(close_lock_file(lock->lk))3276return-1;3277return0;3278}32793280static intcommit_ref(struct ref_lock *lock)3281{3282if(commit_lock_file(lock->lk))3283return-1;3284return0;3285}32863287/*3288 * copy the reflog message msg to buf, which has been allocated sufficiently3289 * large, while cleaning up the whitespaces. Especially, convert LF to space,3290 * because reflog file is one line per entry.3291 */3292static intcopy_reflog_msg(char*buf,const char*msg)3293{3294char*cp = buf;3295char c;3296int wasspace =1;32973298*cp++ ='\t';3299while((c = *msg++)) {3300if(wasspace &&isspace(c))3301continue;3302 wasspace =isspace(c);3303if(wasspace)3304 c =' ';3305*cp++ = c;3306}3307while(buf < cp &&isspace(cp[-1]))3308 cp--;3309*cp++ ='\n';3310return cp - buf;3311}33123313static intshould_autocreate_reflog(const char*refname)3314{3315if(!log_all_ref_updates)3316return0;3317returnstarts_with(refname,"refs/heads/") ||3318starts_with(refname,"refs/remotes/") ||3319starts_with(refname,"refs/notes/") ||3320!strcmp(refname,"HEAD");3321}33223323/*3324 * Create a reflog for a ref. If force_create = 0, the reflog will3325 * only be created for certain refs (those for which3326 * should_autocreate_reflog returns non-zero. Otherwise, create it3327 * regardless of the ref name. Fill in *err and return -1 on failure.3328 */3329static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)3330{3331int logfd, oflags = O_APPEND | O_WRONLY;33323333strbuf_git_path(logfile,"logs/%s", refname);3334if(force_create ||should_autocreate_reflog(refname)) {3335if(safe_create_leading_directories(logfile->buf) <0) {3336strbuf_addf(err,"unable to create directory for%s: "3337"%s", logfile->buf,strerror(errno));3338return-1;3339}3340 oflags |= O_CREAT;3341}33423343 logfd =open(logfile->buf, oflags,0666);3344if(logfd <0) {3345if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3346return0;33473348if(errno == EISDIR) {3349if(remove_empty_directories(logfile)) {3350strbuf_addf(err,"There are still logs under "3351"'%s'", logfile->buf);3352return-1;3353}3354 logfd =open(logfile->buf, oflags,0666);3355}33563357if(logfd <0) {3358strbuf_addf(err,"unable to append to%s:%s",3359 logfile->buf,strerror(errno));3360return-1;3361}3362}33633364adjust_shared_perm(logfile->buf);3365close(logfd);3366return0;3367}336833693370intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3371{3372int ret;3373struct strbuf sb = STRBUF_INIT;33743375 ret =log_ref_setup(refname, &sb, err, force_create);3376strbuf_release(&sb);3377return ret;3378}33793380static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3381const unsigned char*new_sha1,3382const char*committer,const char*msg)3383{3384int msglen, written;3385unsigned maxlen, len;3386char*logrec;33873388 msglen = msg ?strlen(msg) :0;3389 maxlen =strlen(committer) + msglen +100;3390 logrec =xmalloc(maxlen);3391 len =xsnprintf(logrec, maxlen,"%s %s %s\n",3392sha1_to_hex(old_sha1),3393sha1_to_hex(new_sha1),3394 committer);3395if(msglen)3396 len +=copy_reflog_msg(logrec + len -1, msg) -1;33973398 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3399free(logrec);3400if(written != len)3401return-1;34023403return0;3404}34053406static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3407const unsigned char*new_sha1,const char*msg,3408struct strbuf *logfile,int flags,3409struct strbuf *err)3410{3411int logfd, result, oflags = O_APPEND | O_WRONLY;34123413if(log_all_ref_updates <0)3414 log_all_ref_updates = !is_bare_repository();34153416 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);34173418if(result)3419return result;34203421 logfd =open(logfile->buf, oflags);3422if(logfd <0)3423return0;3424 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3425git_committer_info(0), msg);3426if(result) {3427strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3428strerror(errno));3429close(logfd);3430return-1;3431}3432if(close(logfd)) {3433strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3434strerror(errno));3435return-1;3436}3437return0;3438}34393440static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3441const unsigned char*new_sha1,const char*msg,3442int flags,struct strbuf *err)3443{3444struct strbuf sb = STRBUF_INIT;3445int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3446 err);3447strbuf_release(&sb);3448return ret;3449}34503451intis_branch(const char*refname)3452{3453return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3454}34553456/*3457 * Write sha1 into the open lockfile, then close the lockfile. On3458 * errors, rollback the lockfile, fill in *err and3459 * return -1.3460 */3461static intwrite_ref_to_lockfile(struct ref_lock *lock,3462const unsigned char*sha1,struct strbuf *err)3463{3464static char term ='\n';3465struct object *o;3466int fd;34673468 o =parse_object(sha1);3469if(!o) {3470strbuf_addf(err,3471"Trying to write ref%swith nonexistent object%s",3472 lock->ref_name,sha1_to_hex(sha1));3473unlock_ref(lock);3474return-1;3475}3476if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3477strbuf_addf(err,3478"Trying to write non-commit object%sto branch%s",3479sha1_to_hex(sha1), lock->ref_name);3480unlock_ref(lock);3481return-1;3482}3483 fd =get_lock_file_fd(lock->lk);3484if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||3485write_in_full(fd, &term,1) !=1||3486close_ref(lock) <0) {3487strbuf_addf(err,3488"Couldn't write%s",get_lock_file_path(lock->lk));3489unlock_ref(lock);3490return-1;3491}3492return0;3493}34943495/*3496 * Commit a change to a loose reference that has already been written3497 * to the loose reference lockfile. Also update the reflogs if3498 * necessary, using the specified lockmsg (which can be NULL).3499 */3500static intcommit_ref_update(struct ref_lock *lock,3501const unsigned char*sha1,const char*logmsg,3502int flags,struct strbuf *err)3503{3504clear_loose_ref_cache(&ref_cache);3505if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||3506(strcmp(lock->ref_name, lock->orig_ref_name) &&3507log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {3508char*old_msg =strbuf_detach(err, NULL);3509strbuf_addf(err,"Cannot update the ref '%s':%s",3510 lock->ref_name, old_msg);3511free(old_msg);3512unlock_ref(lock);3513return-1;3514}3515if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3516/*3517 * Special hack: If a branch is updated directly and HEAD3518 * points to it (may happen on the remote side of a push3519 * for example) then logically the HEAD reflog should be3520 * updated too.3521 * A generic solution implies reverse symref information,3522 * but finding all symrefs pointing to the given branch3523 * would be rather costly for this rare event (the direct3524 * update of a branch) to be worth it. So let's cheat and3525 * check with HEAD only which should cover 99% of all usage3526 * scenarios (even 100% of the default ones).3527 */3528unsigned char head_sha1[20];3529int head_flag;3530const char*head_ref;3531 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3532 head_sha1, &head_flag);3533if(head_ref && (head_flag & REF_ISSYMREF) &&3534!strcmp(head_ref, lock->ref_name)) {3535struct strbuf log_err = STRBUF_INIT;3536if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3537 logmsg,0, &log_err)) {3538error("%s", log_err.buf);3539strbuf_release(&log_err);3540}3541}3542}3543if(commit_ref(lock)) {3544error("Couldn't set%s", lock->ref_name);3545unlock_ref(lock);3546return-1;3547}35483549unlock_ref(lock);3550return0;3551}35523553intcreate_symref(const char*ref_target,const char*refs_heads_master,3554const char*logmsg)3555{3556char*lockpath = NULL;3557char ref[1000];3558int fd, len, written;3559char*git_HEAD =git_pathdup("%s", ref_target);3560unsigned char old_sha1[20], new_sha1[20];3561struct strbuf err = STRBUF_INIT;35623563if(logmsg &&read_ref(ref_target, old_sha1))3564hashclr(old_sha1);35653566if(safe_create_leading_directories(git_HEAD) <0)3567returnerror("unable to create directory for%s", git_HEAD);35683569#ifndef NO_SYMLINK_HEAD3570if(prefer_symlink_refs) {3571unlink(git_HEAD);3572if(!symlink(refs_heads_master, git_HEAD))3573goto done;3574fprintf(stderr,"no symlink - falling back to symbolic ref\n");3575}3576#endif35773578 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3579if(sizeof(ref) <= len) {3580error("refname too long:%s", refs_heads_master);3581goto error_free_return;3582}3583 lockpath =mkpathdup("%s.lock", git_HEAD);3584 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3585if(fd <0) {3586error("Unable to open%sfor writing", lockpath);3587goto error_free_return;3588}3589 written =write_in_full(fd, ref, len);3590if(close(fd) !=0|| written != len) {3591error("Unable to write to%s", lockpath);3592goto error_unlink_return;3593}3594if(rename(lockpath, git_HEAD) <0) {3595error("Unable to create%s", git_HEAD);3596goto error_unlink_return;3597}3598if(adjust_shared_perm(git_HEAD)) {3599error("Unable to fix permissions on%s", lockpath);3600 error_unlink_return:3601unlink_or_warn(lockpath);3602 error_free_return:3603free(lockpath);3604free(git_HEAD);3605return-1;3606}3607free(lockpath);36083609#ifndef NO_SYMLINK_HEAD3610 done:3611#endif3612if(logmsg && !read_ref(refs_heads_master, new_sha1) &&3613log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {3614error("%s", err.buf);3615strbuf_release(&err);3616}36173618free(git_HEAD);3619return0;3620}36213622struct read_ref_at_cb {3623const char*refname;3624unsigned long at_time;3625int cnt;3626int reccnt;3627unsigned char*sha1;3628int found_it;36293630unsigned char osha1[20];3631unsigned char nsha1[20];3632int tz;3633unsigned long date;3634char**msg;3635unsigned long*cutoff_time;3636int*cutoff_tz;3637int*cutoff_cnt;3638};36393640static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3641const char*email,unsigned long timestamp,int tz,3642const char*message,void*cb_data)3643{3644struct read_ref_at_cb *cb = cb_data;36453646 cb->reccnt++;3647 cb->tz = tz;3648 cb->date = timestamp;36493650if(timestamp <= cb->at_time || cb->cnt ==0) {3651if(cb->msg)3652*cb->msg =xstrdup(message);3653if(cb->cutoff_time)3654*cb->cutoff_time = timestamp;3655if(cb->cutoff_tz)3656*cb->cutoff_tz = tz;3657if(cb->cutoff_cnt)3658*cb->cutoff_cnt = cb->reccnt -1;3659/*3660 * we have not yet updated cb->[n|o]sha1 so they still3661 * hold the values for the previous record.3662 */3663if(!is_null_sha1(cb->osha1)) {3664hashcpy(cb->sha1, nsha1);3665if(hashcmp(cb->osha1, nsha1))3666warning("Log for ref%shas gap after%s.",3667 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3668}3669else if(cb->date == cb->at_time)3670hashcpy(cb->sha1, nsha1);3671else if(hashcmp(nsha1, cb->sha1))3672warning("Log for ref%sunexpectedly ended on%s.",3673 cb->refname,show_date(cb->date, cb->tz,3674DATE_MODE(RFC2822)));3675hashcpy(cb->osha1, osha1);3676hashcpy(cb->nsha1, nsha1);3677 cb->found_it =1;3678return1;3679}3680hashcpy(cb->osha1, osha1);3681hashcpy(cb->nsha1, nsha1);3682if(cb->cnt >0)3683 cb->cnt--;3684return0;3685}36863687static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3688const char*email,unsigned long timestamp,3689int tz,const char*message,void*cb_data)3690{3691struct read_ref_at_cb *cb = cb_data;36923693if(cb->msg)3694*cb->msg =xstrdup(message);3695if(cb->cutoff_time)3696*cb->cutoff_time = timestamp;3697if(cb->cutoff_tz)3698*cb->cutoff_tz = tz;3699if(cb->cutoff_cnt)3700*cb->cutoff_cnt = cb->reccnt;3701hashcpy(cb->sha1, osha1);3702if(is_null_sha1(cb->sha1))3703hashcpy(cb->sha1, nsha1);3704/* We just want the first entry */3705return1;3706}37073708intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3709unsigned char*sha1,char**msg,3710unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3711{3712struct read_ref_at_cb cb;37133714memset(&cb,0,sizeof(cb));3715 cb.refname = refname;3716 cb.at_time = at_time;3717 cb.cnt = cnt;3718 cb.msg = msg;3719 cb.cutoff_time = cutoff_time;3720 cb.cutoff_tz = cutoff_tz;3721 cb.cutoff_cnt = cutoff_cnt;3722 cb.sha1 = sha1;37233724for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);37253726if(!cb.reccnt) {3727if(flags & GET_SHA1_QUIETLY)3728exit(128);3729else3730die("Log for%sis empty.", refname);3731}3732if(cb.found_it)3733return0;37343735for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);37363737return1;3738}37393740intreflog_exists(const char*refname)3741{3742struct stat st;37433744return!lstat(git_path("logs/%s", refname), &st) &&3745S_ISREG(st.st_mode);3746}37473748intdelete_reflog(const char*refname)3749{3750returnremove_path(git_path("logs/%s", refname));3751}37523753static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3754{3755unsigned char osha1[20], nsha1[20];3756char*email_end, *message;3757unsigned long timestamp;3758int tz;37593760/* old SP new SP name <email> SP time TAB msg LF */3761if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3762get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3763get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3764!(email_end =strchr(sb->buf +82,'>')) ||3765 email_end[1] !=' '||3766!(timestamp =strtoul(email_end +2, &message,10)) ||3767!message || message[0] !=' '||3768(message[1] !='+'&& message[1] !='-') ||3769!isdigit(message[2]) || !isdigit(message[3]) ||3770!isdigit(message[4]) || !isdigit(message[5]))3771return0;/* corrupt? */3772 email_end[1] ='\0';3773 tz =strtol(message +1, NULL,10);3774if(message[6] !='\t')3775 message +=6;3776else3777 message +=7;3778returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3779}37803781static char*find_beginning_of_line(char*bob,char*scan)3782{3783while(bob < scan && *(--scan) !='\n')3784;/* keep scanning backwards */3785/*3786 * Return either beginning of the buffer, or LF at the end of3787 * the previous line.3788 */3789return scan;3790}37913792intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3793{3794struct strbuf sb = STRBUF_INIT;3795FILE*logfp;3796long pos;3797int ret =0, at_tail =1;37983799 logfp =fopen(git_path("logs/%s", refname),"r");3800if(!logfp)3801return-1;38023803/* Jump to the end */3804if(fseek(logfp,0, SEEK_END) <0)3805returnerror("cannot seek back reflog for%s:%s",3806 refname,strerror(errno));3807 pos =ftell(logfp);3808while(!ret &&0< pos) {3809int cnt;3810size_t nread;3811char buf[BUFSIZ];3812char*endp, *scanp;38133814/* Fill next block from the end */3815 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3816if(fseek(logfp, pos - cnt, SEEK_SET))3817returnerror("cannot seek back reflog for%s:%s",3818 refname,strerror(errno));3819 nread =fread(buf, cnt,1, logfp);3820if(nread !=1)3821returnerror("cannot read%dbytes from reflog for%s:%s",3822 cnt, refname,strerror(errno));3823 pos -= cnt;38243825 scanp = endp = buf + cnt;3826if(at_tail && scanp[-1] =='\n')3827/* Looking at the final LF at the end of the file */3828 scanp--;3829 at_tail =0;38303831while(buf < scanp) {3832/*3833 * terminating LF of the previous line, or the beginning3834 * of the buffer.3835 */3836char*bp;38373838 bp =find_beginning_of_line(buf, scanp);38393840if(*bp =='\n') {3841/*3842 * The newline is the end of the previous line,3843 * so we know we have complete line starting3844 * at (bp + 1). Prefix it onto any prior data3845 * we collected for the line and process it.3846 */3847strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3848 scanp = bp;3849 endp = bp +1;3850 ret =show_one_reflog_ent(&sb, fn, cb_data);3851strbuf_reset(&sb);3852if(ret)3853break;3854}else if(!pos) {3855/*3856 * We are at the start of the buffer, and the3857 * start of the file; there is no previous3858 * line, and we have everything for this one.3859 * Process it, and we can end the loop.3860 */3861strbuf_splice(&sb,0,0, buf, endp - buf);3862 ret =show_one_reflog_ent(&sb, fn, cb_data);3863strbuf_reset(&sb);3864break;3865}38663867if(bp == buf) {3868/*3869 * We are at the start of the buffer, and there3870 * is more file to read backwards. Which means3871 * we are in the middle of a line. Note that we3872 * may get here even if *bp was a newline; that3873 * just means we are at the exact end of the3874 * previous line, rather than some spot in the3875 * middle.3876 *3877 * Save away what we have to be combined with3878 * the data from the next read.3879 */3880strbuf_splice(&sb,0,0, buf, endp - buf);3881break;3882}3883}38843885}3886if(!ret && sb.len)3887die("BUG: reverse reflog parser had leftover data");38883889fclose(logfp);3890strbuf_release(&sb);3891return ret;3892}38933894intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3895{3896FILE*logfp;3897struct strbuf sb = STRBUF_INIT;3898int ret =0;38993900 logfp =fopen(git_path("logs/%s", refname),"r");3901if(!logfp)3902return-1;39033904while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3905 ret =show_one_reflog_ent(&sb, fn, cb_data);3906fclose(logfp);3907strbuf_release(&sb);3908return ret;3909}3910/*3911 * Call fn for each reflog in the namespace indicated by name. name3912 * must be empty or end with '/'. Name will be used as a scratch3913 * space, but its contents will be restored before return.3914 */3915static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3916{3917DIR*d =opendir(git_path("logs/%s", name->buf));3918int retval =0;3919struct dirent *de;3920int oldlen = name->len;39213922if(!d)3923return name->len ? errno :0;39243925while((de =readdir(d)) != NULL) {3926struct stat st;39273928if(de->d_name[0] =='.')3929continue;3930if(ends_with(de->d_name,".lock"))3931continue;3932strbuf_addstr(name, de->d_name);3933if(stat(git_path("logs/%s", name->buf), &st) <0) {3934;/* silently ignore */3935}else{3936if(S_ISDIR(st.st_mode)) {3937strbuf_addch(name,'/');3938 retval =do_for_each_reflog(name, fn, cb_data);3939}else{3940struct object_id oid;39413942if(read_ref_full(name->buf,0, oid.hash, NULL))3943 retval =error("bad ref for%s", name->buf);3944else3945 retval =fn(name->buf, &oid,0, cb_data);3946}3947if(retval)3948break;3949}3950strbuf_setlen(name, oldlen);3951}3952closedir(d);3953return retval;3954}39553956intfor_each_reflog(each_ref_fn fn,void*cb_data)3957{3958int retval;3959struct strbuf name;3960strbuf_init(&name, PATH_MAX);3961 retval =do_for_each_reflog(&name, fn, cb_data);3962strbuf_release(&name);3963return retval;3964}39653966/**3967 * Information needed for a single ref update. Set new_sha1 to the new3968 * value or to null_sha1 to delete the ref. To check the old value3969 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3970 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3971 * not exist before update.3972 */3973struct ref_update {3974/*3975 * If (flags & REF_HAVE_NEW), set the reference to this value:3976 */3977unsigned char new_sha1[20];3978/*3979 * If (flags & REF_HAVE_OLD), check that the reference3980 * previously had this value:3981 */3982unsigned char old_sha1[20];3983/*3984 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3985 * REF_DELETING, and REF_ISPRUNING:3986 */3987unsigned int flags;3988struct ref_lock *lock;3989int type;3990char*msg;3991const char refname[FLEX_ARRAY];3992};39933994/*3995 * Transaction states.3996 * OPEN: The transaction is in a valid state and can accept new updates.3997 * An OPEN transaction can be committed.3998 * CLOSED: A closed transaction is no longer active and no other operations3999 * than free can be used on it in this state.4000 * A transaction can either become closed by successfully committing4001 * an active transaction or if there is a failure while building4002 * the transaction thus rendering it failed/inactive.4003 */4004enum ref_transaction_state {4005 REF_TRANSACTION_OPEN =0,4006 REF_TRANSACTION_CLOSED =14007};40084009/*4010 * Data structure for holding a reference transaction, which can4011 * consist of checks and updates to multiple references, carried out4012 * as atomically as possible. This structure is opaque to callers.4013 */4014struct ref_transaction {4015struct ref_update **updates;4016size_t alloc;4017size_t nr;4018enum ref_transaction_state state;4019};40204021struct ref_transaction *ref_transaction_begin(struct strbuf *err)4022{4023assert(err);40244025returnxcalloc(1,sizeof(struct ref_transaction));4026}40274028voidref_transaction_free(struct ref_transaction *transaction)4029{4030int i;40314032if(!transaction)4033return;40344035for(i =0; i < transaction->nr; i++) {4036free(transaction->updates[i]->msg);4037free(transaction->updates[i]);4038}4039free(transaction->updates);4040free(transaction);4041}40424043static struct ref_update *add_update(struct ref_transaction *transaction,4044const char*refname)4045{4046size_t len =strlen(refname) +1;4047struct ref_update *update =xcalloc(1,sizeof(*update) + len);40484049memcpy((char*)update->refname, refname, len);/* includes NUL */4050ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);4051 transaction->updates[transaction->nr++] = update;4052return update;4053}40544055intref_transaction_update(struct ref_transaction *transaction,4056const char*refname,4057const unsigned char*new_sha1,4058const unsigned char*old_sha1,4059unsigned int flags,const char*msg,4060struct strbuf *err)4061{4062struct ref_update *update;40634064assert(err);40654066if(transaction->state != REF_TRANSACTION_OPEN)4067die("BUG: update called for transaction that is not open");40684069if(new_sha1 && !is_null_sha1(new_sha1) &&4070check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {4071strbuf_addf(err,"refusing to update ref with bad name%s",4072 refname);4073return-1;4074}40754076 update =add_update(transaction, refname);4077if(new_sha1) {4078hashcpy(update->new_sha1, new_sha1);4079 flags |= REF_HAVE_NEW;4080}4081if(old_sha1) {4082hashcpy(update->old_sha1, old_sha1);4083 flags |= REF_HAVE_OLD;4084}4085 update->flags = flags;4086if(msg)4087 update->msg =xstrdup(msg);4088return0;4089}40904091intref_transaction_create(struct ref_transaction *transaction,4092const char*refname,4093const unsigned char*new_sha1,4094unsigned int flags,const char*msg,4095struct strbuf *err)4096{4097if(!new_sha1 ||is_null_sha1(new_sha1))4098die("BUG: create called without valid new_sha1");4099returnref_transaction_update(transaction, refname, new_sha1,4100 null_sha1, flags, msg, err);4101}41024103intref_transaction_delete(struct ref_transaction *transaction,4104const char*refname,4105const unsigned char*old_sha1,4106unsigned int flags,const char*msg,4107struct strbuf *err)4108{4109if(old_sha1 &&is_null_sha1(old_sha1))4110die("BUG: delete called with old_sha1 set to zeros");4111returnref_transaction_update(transaction, refname,4112 null_sha1, old_sha1,4113 flags, msg, err);4114}41154116intref_transaction_verify(struct ref_transaction *transaction,4117const char*refname,4118const unsigned char*old_sha1,4119unsigned int flags,4120struct strbuf *err)4121{4122if(!old_sha1)4123die("BUG: verify called with old_sha1 set to NULL");4124returnref_transaction_update(transaction, refname,4125 NULL, old_sha1,4126 flags, NULL, err);4127}41284129intupdate_ref(const char*msg,const char*refname,4130const unsigned char*new_sha1,const unsigned char*old_sha1,4131unsigned int flags,enum action_on_err onerr)4132{4133struct ref_transaction *t = NULL;4134struct strbuf err = STRBUF_INIT;4135int ret =0;41364137if(ref_type(refname) == REF_TYPE_PSEUDOREF) {4138 ret =write_pseudoref(refname, new_sha1, old_sha1, &err);4139}else{4140 t =ref_transaction_begin(&err);4141if(!t ||4142ref_transaction_update(t, refname, new_sha1, old_sha1,4143 flags, msg, &err) ||4144ref_transaction_commit(t, &err)) {4145 ret =1;4146ref_transaction_free(t);4147}4148}4149if(ret) {4150const char*str ="update_ref failed for ref '%s':%s";41514152switch(onerr) {4153case UPDATE_REFS_MSG_ON_ERR:4154error(str, refname, err.buf);4155break;4156case UPDATE_REFS_DIE_ON_ERR:4157die(str, refname, err.buf);4158break;4159case UPDATE_REFS_QUIET_ON_ERR:4160break;4161}4162strbuf_release(&err);4163return1;4164}4165strbuf_release(&err);4166if(t)4167ref_transaction_free(t);4168return0;4169}41704171static intref_update_reject_duplicates(struct string_list *refnames,4172struct strbuf *err)4173{4174int i, n = refnames->nr;41754176assert(err);41774178for(i =1; i < n; i++)4179if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {4180strbuf_addf(err,4181"Multiple updates for ref '%s' not allowed.",4182 refnames->items[i].string);4183return1;4184}4185return0;4186}41874188intref_transaction_commit(struct ref_transaction *transaction,4189struct strbuf *err)4190{4191int ret =0, i;4192int n = transaction->nr;4193struct ref_update **updates = transaction->updates;4194struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4195struct string_list_item *ref_to_delete;4196struct string_list affected_refnames = STRING_LIST_INIT_NODUP;41974198assert(err);41994200if(transaction->state != REF_TRANSACTION_OPEN)4201die("BUG: commit called for transaction that is not open");42024203if(!n) {4204 transaction->state = REF_TRANSACTION_CLOSED;4205return0;4206}42074208/* Fail if a refname appears more than once in the transaction: */4209for(i =0; i < n; i++)4210string_list_append(&affected_refnames, updates[i]->refname);4211string_list_sort(&affected_refnames);4212if(ref_update_reject_duplicates(&affected_refnames, err)) {4213 ret = TRANSACTION_GENERIC_ERROR;4214goto cleanup;4215}42164217/*4218 * Acquire all locks, verify old values if provided, check4219 * that new values are valid, and write new values to the4220 * lockfiles, ready to be activated. Only keep one lockfile4221 * open at a time to avoid running out of file descriptors.4222 */4223for(i =0; i < n; i++) {4224struct ref_update *update = updates[i];42254226if((update->flags & REF_HAVE_NEW) &&4227is_null_sha1(update->new_sha1))4228 update->flags |= REF_DELETING;4229 update->lock =lock_ref_sha1_basic(4230 update->refname,4231((update->flags & REF_HAVE_OLD) ?4232 update->old_sha1 : NULL),4233&affected_refnames, NULL,4234 update->flags,4235&update->type,4236 err);4237if(!update->lock) {4238char*reason;42394240 ret = (errno == ENOTDIR)4241? TRANSACTION_NAME_CONFLICT4242: TRANSACTION_GENERIC_ERROR;4243 reason =strbuf_detach(err, NULL);4244strbuf_addf(err,"cannot lock ref '%s':%s",4245 update->refname, reason);4246free(reason);4247goto cleanup;4248}4249if((update->flags & REF_HAVE_NEW) &&4250!(update->flags & REF_DELETING)) {4251int overwriting_symref = ((update->type & REF_ISSYMREF) &&4252(update->flags & REF_NODEREF));42534254if(!overwriting_symref &&4255!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4256/*4257 * The reference already has the desired4258 * value, so we don't need to write it.4259 */4260}else if(write_ref_to_lockfile(update->lock,4261 update->new_sha1,4262 err)) {4263char*write_err =strbuf_detach(err, NULL);42644265/*4266 * The lock was freed upon failure of4267 * write_ref_to_lockfile():4268 */4269 update->lock = NULL;4270strbuf_addf(err,4271"cannot update the ref '%s':%s",4272 update->refname, write_err);4273free(write_err);4274 ret = TRANSACTION_GENERIC_ERROR;4275goto cleanup;4276}else{4277 update->flags |= REF_NEEDS_COMMIT;4278}4279}4280if(!(update->flags & REF_NEEDS_COMMIT)) {4281/*4282 * We didn't have to write anything to the lockfile.4283 * Close it to free up the file descriptor:4284 */4285if(close_ref(update->lock)) {4286strbuf_addf(err,"Couldn't close%s.lock",4287 update->refname);4288goto cleanup;4289}4290}4291}42924293/* Perform updates first so live commits remain referenced */4294for(i =0; i < n; i++) {4295struct ref_update *update = updates[i];42964297if(update->flags & REF_NEEDS_COMMIT) {4298if(commit_ref_update(update->lock,4299 update->new_sha1, update->msg,4300 update->flags, err)) {4301/* freed by commit_ref_update(): */4302 update->lock = NULL;4303 ret = TRANSACTION_GENERIC_ERROR;4304goto cleanup;4305}else{4306/* freed by commit_ref_update(): */4307 update->lock = NULL;4308}4309}4310}43114312/* Perform deletes now that updates are safely completed */4313for(i =0; i < n; i++) {4314struct ref_update *update = updates[i];43154316if(update->flags & REF_DELETING) {4317if(delete_ref_loose(update->lock, update->type, err)) {4318 ret = TRANSACTION_GENERIC_ERROR;4319goto cleanup;4320}43214322if(!(update->flags & REF_ISPRUNING))4323string_list_append(&refs_to_delete,4324 update->lock->ref_name);4325}4326}43274328if(repack_without_refs(&refs_to_delete, err)) {4329 ret = TRANSACTION_GENERIC_ERROR;4330goto cleanup;4331}4332for_each_string_list_item(ref_to_delete, &refs_to_delete)4333unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4334clear_loose_ref_cache(&ref_cache);43354336cleanup:4337 transaction->state = REF_TRANSACTION_CLOSED;43384339for(i =0; i < n; i++)4340if(updates[i]->lock)4341unlock_ref(updates[i]->lock);4342string_list_clear(&refs_to_delete,0);4343string_list_clear(&affected_refnames,0);4344return ret;4345}43464347static intref_present(const char*refname,4348const struct object_id *oid,int flags,void*cb_data)4349{4350struct string_list *affected_refnames = cb_data;43514352returnstring_list_has_string(affected_refnames, refname);4353}43544355intinitial_ref_transaction_commit(struct ref_transaction *transaction,4356struct strbuf *err)4357{4358int ret =0, i;4359int n = transaction->nr;4360struct ref_update **updates = transaction->updates;4361struct string_list affected_refnames = STRING_LIST_INIT_NODUP;43624363assert(err);43644365if(transaction->state != REF_TRANSACTION_OPEN)4366die("BUG: commit called for transaction that is not open");43674368/* Fail if a refname appears more than once in the transaction: */4369for(i =0; i < n; i++)4370string_list_append(&affected_refnames, updates[i]->refname);4371string_list_sort(&affected_refnames);4372if(ref_update_reject_duplicates(&affected_refnames, err)) {4373 ret = TRANSACTION_GENERIC_ERROR;4374goto cleanup;4375}43764377/*4378 * It's really undefined to call this function in an active4379 * repository or when there are existing references: we are4380 * only locking and changing packed-refs, so (1) any4381 * simultaneous processes might try to change a reference at4382 * the same time we do, and (2) any existing loose versions of4383 * the references that we are setting would have precedence4384 * over our values. But some remote helpers create the remote4385 * "HEAD" and "master" branches before calling this function,4386 * so here we really only check that none of the references4387 * that we are creating already exists.4388 */4389if(for_each_rawref(ref_present, &affected_refnames))4390die("BUG: initial ref transaction called with existing refs");43914392for(i =0; i < n; i++) {4393struct ref_update *update = updates[i];43944395if((update->flags & REF_HAVE_OLD) &&4396!is_null_sha1(update->old_sha1))4397die("BUG: initial ref transaction with old_sha1 set");4398if(verify_refname_available(update->refname,4399&affected_refnames, NULL,4400 err)) {4401 ret = TRANSACTION_NAME_CONFLICT;4402goto cleanup;4403}4404}44054406if(lock_packed_refs(0)) {4407strbuf_addf(err,"unable to lock packed-refs file:%s",4408strerror(errno));4409 ret = TRANSACTION_GENERIC_ERROR;4410goto cleanup;4411}44124413for(i =0; i < n; i++) {4414struct ref_update *update = updates[i];44154416if((update->flags & REF_HAVE_NEW) &&4417!is_null_sha1(update->new_sha1))4418add_packed_ref(update->refname, update->new_sha1);4419}44204421if(commit_packed_refs()) {4422strbuf_addf(err,"unable to commit packed-refs file:%s",4423strerror(errno));4424 ret = TRANSACTION_GENERIC_ERROR;4425goto cleanup;4426}44274428cleanup:4429 transaction->state = REF_TRANSACTION_CLOSED;4430string_list_clear(&affected_refnames,0);4431return ret;4432}44334434char*shorten_unambiguous_ref(const char*refname,int strict)4435{4436int i;4437static char**scanf_fmts;4438static int nr_rules;4439char*short_name;44404441if(!nr_rules) {4442/*4443 * Pre-generate scanf formats from ref_rev_parse_rules[].4444 * Generate a format suitable for scanf from a4445 * ref_rev_parse_rules rule by interpolating "%s" at the4446 * location of the "%.*s".4447 */4448size_t total_len =0;4449size_t offset =0;44504451/* the rule list is NULL terminated, count them first */4452for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4453/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4454 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;44554456 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);44574458 offset =0;4459for(i =0; i < nr_rules; i++) {4460assert(offset < total_len);4461 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4462 offset +=snprintf(scanf_fmts[i], total_len - offset,4463 ref_rev_parse_rules[i],2,"%s") +1;4464}4465}44664467/* bail out if there are no rules */4468if(!nr_rules)4469returnxstrdup(refname);44704471/* buffer for scanf result, at most refname must fit */4472 short_name =xstrdup(refname);44734474/* skip first rule, it will always match */4475for(i = nr_rules -1; i >0; --i) {4476int j;4477int rules_to_fail = i;4478int short_name_len;44794480if(1!=sscanf(refname, scanf_fmts[i], short_name))4481continue;44824483 short_name_len =strlen(short_name);44844485/*4486 * in strict mode, all (except the matched one) rules4487 * must fail to resolve to a valid non-ambiguous ref4488 */4489if(strict)4490 rules_to_fail = nr_rules;44914492/*4493 * check if the short name resolves to a valid ref,4494 * but use only rules prior to the matched one4495 */4496for(j =0; j < rules_to_fail; j++) {4497const char*rule = ref_rev_parse_rules[j];4498char refname[PATH_MAX];44994500/* skip matched rule */4501if(i == j)4502continue;45034504/*4505 * the short name is ambiguous, if it resolves4506 * (with this previous rule) to a valid ref4507 * read_ref() returns 0 on success4508 */4509mksnpath(refname,sizeof(refname),4510 rule, short_name_len, short_name);4511if(ref_exists(refname))4512break;4513}45144515/*4516 * short name is non-ambiguous if all previous rules4517 * haven't resolved to a valid ref4518 */4519if(j == rules_to_fail)4520return short_name;4521}45224523free(short_name);4524returnxstrdup(refname);4525}45264527static struct string_list *hide_refs;45284529intparse_hide_refs_config(const char*var,const char*value,const char*section)4530{4531if(!strcmp("transfer.hiderefs", var) ||4532/* NEEDSWORK: use parse_config_key() once both are merged */4533(starts_with(var, section) && var[strlen(section)] =='.'&&4534!strcmp(var +strlen(section),".hiderefs"))) {4535char*ref;4536int len;45374538if(!value)4539returnconfig_error_nonbool(var);4540 ref =xstrdup(value);4541 len =strlen(ref);4542while(len && ref[len -1] =='/')4543 ref[--len] ='\0';4544if(!hide_refs) {4545 hide_refs =xcalloc(1,sizeof(*hide_refs));4546 hide_refs->strdup_strings =1;4547}4548string_list_append(hide_refs, ref);4549}4550return0;4551}45524553intref_is_hidden(const char*refname)4554{4555int i;45564557if(!hide_refs)4558return0;4559for(i = hide_refs->nr -1; i >=0; i--) {4560const char*match = hide_refs->items[i].string;4561int neg =0;4562int len;45634564if(*match =='!') {4565 neg =1;4566 match++;4567}45684569if(!starts_with(refname, match))4570continue;4571 len =strlen(match);4572if(!refname[len] || refname[len] =='/')4573return!neg;4574}4575return0;4576}45774578struct expire_reflog_cb {4579unsigned int flags;4580 reflog_expiry_should_prune_fn *should_prune_fn;4581void*policy_cb;4582FILE*newlog;4583unsigned char last_kept_sha1[20];4584};45854586static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4587const char*email,unsigned long timestamp,int tz,4588const char*message,void*cb_data)4589{4590struct expire_reflog_cb *cb = cb_data;4591struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;45924593if(cb->flags & EXPIRE_REFLOGS_REWRITE)4594 osha1 = cb->last_kept_sha1;45954596if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4597 message, policy_cb)) {4598if(!cb->newlog)4599printf("would prune%s", message);4600else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4601printf("prune%s", message);4602}else{4603if(cb->newlog) {4604fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4605sha1_to_hex(osha1),sha1_to_hex(nsha1),4606 email, timestamp, tz, message);4607hashcpy(cb->last_kept_sha1, nsha1);4608}4609if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4610printf("keep%s", message);4611}4612return0;4613}46144615intreflog_expire(const char*refname,const unsigned char*sha1,4616unsigned int flags,4617 reflog_expiry_prepare_fn prepare_fn,4618 reflog_expiry_should_prune_fn should_prune_fn,4619 reflog_expiry_cleanup_fn cleanup_fn,4620void*policy_cb_data)4621{4622static struct lock_file reflog_lock;4623struct expire_reflog_cb cb;4624struct ref_lock *lock;4625char*log_file;4626int status =0;4627int type;4628struct strbuf err = STRBUF_INIT;46294630memset(&cb,0,sizeof(cb));4631 cb.flags = flags;4632 cb.policy_cb = policy_cb_data;4633 cb.should_prune_fn = should_prune_fn;46344635/*4636 * The reflog file is locked by holding the lock on the4637 * reference itself, plus we might need to update the4638 * reference if --updateref was specified:4639 */4640 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4641if(!lock) {4642error("cannot lock ref '%s':%s", refname, err.buf);4643strbuf_release(&err);4644return-1;4645}4646if(!reflog_exists(refname)) {4647unlock_ref(lock);4648return0;4649}46504651 log_file =git_pathdup("logs/%s", refname);4652if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4653/*4654 * Even though holding $GIT_DIR/logs/$reflog.lock has4655 * no locking implications, we use the lock_file4656 * machinery here anyway because it does a lot of the4657 * work we need, including cleaning up if the program4658 * exits unexpectedly.4659 */4660if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4661struct strbuf err = STRBUF_INIT;4662unable_to_lock_message(log_file, errno, &err);4663error("%s", err.buf);4664strbuf_release(&err);4665goto failure;4666}4667 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4668if(!cb.newlog) {4669error("cannot fdopen%s(%s)",4670get_lock_file_path(&reflog_lock),strerror(errno));4671goto failure;4672}4673}46744675(*prepare_fn)(refname, sha1, cb.policy_cb);4676for_each_reflog_ent(refname, expire_reflog_ent, &cb);4677(*cleanup_fn)(cb.policy_cb);46784679if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4680/*4681 * It doesn't make sense to adjust a reference pointed4682 * to by a symbolic ref based on expiring entries in4683 * the symbolic reference's reflog. Nor can we update4684 * a reference if there are no remaining reflog4685 * entries.4686 */4687int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4688!(type & REF_ISSYMREF) &&4689!is_null_sha1(cb.last_kept_sha1);46904691if(close_lock_file(&reflog_lock)) {4692 status |=error("couldn't write%s:%s", log_file,4693strerror(errno));4694}else if(update &&4695(write_in_full(get_lock_file_fd(lock->lk),4696sha1_to_hex(cb.last_kept_sha1),40) !=40||4697write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||4698close_ref(lock) <0)) {4699 status |=error("couldn't write%s",4700get_lock_file_path(lock->lk));4701rollback_lock_file(&reflog_lock);4702}else if(commit_lock_file(&reflog_lock)) {4703 status |=error("unable to commit reflog '%s' (%s)",4704 log_file,strerror(errno));4705}else if(update &&commit_ref(lock)) {4706 status |=error("couldn't set%s", lock->ref_name);4707}4708}4709free(log_file);4710unlock_ref(lock);4711return status;47124713 failure:4714rollback_lock_file(&reflog_lock);4715free(log_file);4716unlock_ref(lock);4717return-1;4718}