1#include"cache.h" 2#include"lockfile.h" 3#include"refs.h" 4#include"object.h" 5#include"tag.h" 6#include"dir.h" 7#include"string-list.h" 8 9struct ref_lock { 10char*ref_name; 11char*orig_ref_name; 12struct lock_file *lk; 13struct object_id old_oid; 14}; 15 16/* 17 * How to handle various characters in refnames: 18 * 0: An acceptable character for refs 19 * 1: End-of-component 20 * 2: ., look for a preceding . to reject .. in refs 21 * 3: {, look for a preceding @ to reject @{ in refs 22 * 4: A bad character: ASCII control characters, and 23 * ":", "?", "[", "\", "^", "~", SP, or TAB 24 * 5: *, reject unless REFNAME_REFSPEC_PATTERN is set 25 */ 26static unsigned char refname_disposition[256] = { 271,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 284,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 294,0,0,0,0,0,0,0,0,0,5,0,0,0,2,1, 300,0,0,0,0,0,0,0,0,0,4,0,0,0,0,4, 310,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 320,0,0,0,0,0,0,0,0,0,0,4,4,0,4,0, 330,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 340,0,0,0,0,0,0,0,0,0,0,3,0,0,4,4 35}; 36 37/* 38 * Flag passed to lock_ref_sha1_basic() telling it to tolerate broken 39 * refs (i.e., because the reference is about to be deleted anyway). 40 */ 41#define REF_DELETING 0x02 42 43/* 44 * Used as a flag in ref_update::flags when a loose ref is being 45 * pruned. 46 */ 47#define REF_ISPRUNING 0x04 48 49/* 50 * Used as a flag in ref_update::flags when the reference should be 51 * updated to new_sha1. 52 */ 53#define REF_HAVE_NEW 0x08 54 55/* 56 * Used as a flag in ref_update::flags when old_sha1 should be 57 * checked. 58 */ 59#define REF_HAVE_OLD 0x10 60 61/* 62 * Used as a flag in ref_update::flags when the lockfile needs to be 63 * committed. 64 */ 65#define REF_NEEDS_COMMIT 0x20 66 67/* 68 * 0x40 is REF_FORCE_CREATE_REFLOG, so skip it if you're adding a 69 * value to ref_update::flags 70 */ 71 72/* 73 * Try to read one refname component from the front of refname. 74 * Return the length of the component found, or -1 if the component is 75 * not legal. It is legal if it is something reasonable to have under 76 * ".git/refs/"; We do not like it if: 77 * 78 * - any path component of it begins with ".", or 79 * - it has double dots "..", or 80 * - it has ASCII control characters, or 81 * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or 82 * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or 83 * - it ends with a "/", or 84 * - it ends with ".lock", or 85 * - it contains a "@{" portion 86 */ 87static intcheck_refname_component(const char*refname,int*flags) 88{ 89const char*cp; 90char last ='\0'; 91 92for(cp = refname; ; cp++) { 93int ch = *cp &255; 94unsigned char disp = refname_disposition[ch]; 95switch(disp) { 96case1: 97goto out; 98case2: 99if(last =='.') 100return-1;/* Refname contains "..". */ 101break; 102case3: 103if(last =='@') 104return-1;/* Refname contains "@{". */ 105break; 106case4: 107return-1; 108case5: 109if(!(*flags & REFNAME_REFSPEC_PATTERN)) 110return-1;/* refspec can't be a pattern */ 111 112/* 113 * Unset the pattern flag so that we only accept 114 * a single asterisk for one side of refspec. 115 */ 116*flags &= ~ REFNAME_REFSPEC_PATTERN; 117break; 118} 119 last = ch; 120} 121out: 122if(cp == refname) 123return0;/* Component has zero length. */ 124if(refname[0] =='.') 125return-1;/* Component starts with '.'. */ 126if(cp - refname >= LOCK_SUFFIX_LEN && 127!memcmp(cp - LOCK_SUFFIX_LEN, LOCK_SUFFIX, LOCK_SUFFIX_LEN)) 128return-1;/* Refname ends with ".lock". */ 129return cp - refname; 130} 131 132intcheck_refname_format(const char*refname,int flags) 133{ 134int component_len, component_count =0; 135 136if(!strcmp(refname,"@")) 137/* Refname is a single character '@'. */ 138return-1; 139 140while(1) { 141/* We are at the start of a path component. */ 142 component_len =check_refname_component(refname, &flags); 143if(component_len <=0) 144return-1; 145 146 component_count++; 147if(refname[component_len] =='\0') 148break; 149/* Skip to next component. */ 150 refname += component_len +1; 151} 152 153if(refname[component_len -1] =='.') 154return-1;/* Refname ends with '.'. */ 155if(!(flags & REFNAME_ALLOW_ONELEVEL) && component_count <2) 156return-1;/* Refname has only one component. */ 157return0; 158} 159 160struct ref_entry; 161 162/* 163 * Information used (along with the information in ref_entry) to 164 * describe a single cached reference. This data structure only 165 * occurs embedded in a union in struct ref_entry, and only when 166 * (ref_entry->flag & REF_DIR) is zero. 167 */ 168struct ref_value { 169/* 170 * The name of the object to which this reference resolves 171 * (which may be a tag object). If REF_ISBROKEN, this is 172 * null. If REF_ISSYMREF, then this is the name of the object 173 * referred to by the last reference in the symlink chain. 174 */ 175struct object_id oid; 176 177/* 178 * If REF_KNOWS_PEELED, then this field holds the peeled value 179 * of this reference, or null if the reference is known not to 180 * be peelable. See the documentation for peel_ref() for an 181 * exact definition of "peelable". 182 */ 183struct object_id peeled; 184}; 185 186struct ref_cache; 187 188/* 189 * Information used (along with the information in ref_entry) to 190 * describe a level in the hierarchy of references. This data 191 * structure only occurs embedded in a union in struct ref_entry, and 192 * only when (ref_entry.flag & REF_DIR) is set. In that case, 193 * (ref_entry.flag & REF_INCOMPLETE) determines whether the references 194 * in the directory have already been read: 195 * 196 * (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose 197 * or packed references, already read. 198 * 199 * (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose 200 * references that hasn't been read yet (nor has any of its 201 * subdirectories). 202 * 203 * Entries within a directory are stored within a growable array of 204 * pointers to ref_entries (entries, nr, alloc). Entries 0 <= i < 205 * sorted are sorted by their component name in strcmp() order and the 206 * remaining entries are unsorted. 207 * 208 * Loose references are read lazily, one directory at a time. When a 209 * directory of loose references is read, then all of the references 210 * in that directory are stored, and REF_INCOMPLETE stubs are created 211 * for any subdirectories, but the subdirectories themselves are not 212 * read. The reading is triggered by get_ref_dir(). 213 */ 214struct ref_dir { 215int nr, alloc; 216 217/* 218 * Entries with index 0 <= i < sorted are sorted by name. New 219 * entries are appended to the list unsorted, and are sorted 220 * only when required; thus we avoid the need to sort the list 221 * after the addition of every reference. 222 */ 223int sorted; 224 225/* A pointer to the ref_cache that contains this ref_dir. */ 226struct ref_cache *ref_cache; 227 228struct ref_entry **entries; 229}; 230 231/* 232 * Bit values for ref_entry::flag. REF_ISSYMREF=0x01, 233 * REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are 234 * public values; see refs.h. 235 */ 236 237/* 238 * The field ref_entry->u.value.peeled of this value entry contains 239 * the correct peeled value for the reference, which might be 240 * null_sha1 if the reference is not a tag or if it is broken. 241 */ 242#define REF_KNOWS_PEELED 0x10 243 244/* ref_entry represents a directory of references */ 245#define REF_DIR 0x20 246 247/* 248 * Entry has not yet been read from disk (used only for REF_DIR 249 * entries representing loose references) 250 */ 251#define REF_INCOMPLETE 0x40 252 253/* 254 * A ref_entry represents either a reference or a "subdirectory" of 255 * references. 256 * 257 * Each directory in the reference namespace is represented by a 258 * ref_entry with (flags & REF_DIR) set and containing a subdir member 259 * that holds the entries in that directory that have been read so 260 * far. If (flags & REF_INCOMPLETE) is set, then the directory and 261 * its subdirectories haven't been read yet. REF_INCOMPLETE is only 262 * used for loose reference directories. 263 * 264 * References are represented by a ref_entry with (flags & REF_DIR) 265 * unset and a value member that describes the reference's value. The 266 * flag member is at the ref_entry level, but it is also needed to 267 * interpret the contents of the value field (in other words, a 268 * ref_value object is not very much use without the enclosing 269 * ref_entry). 270 * 271 * Reference names cannot end with slash and directories' names are 272 * always stored with a trailing slash (except for the top-level 273 * directory, which is always denoted by ""). This has two nice 274 * consequences: (1) when the entries in each subdir are sorted 275 * lexicographically by name (as they usually are), the references in 276 * a whole tree can be generated in lexicographic order by traversing 277 * the tree in left-to-right, depth-first order; (2) the names of 278 * references and subdirectories cannot conflict, and therefore the 279 * presence of an empty subdirectory does not block the creation of a 280 * similarly-named reference. (The fact that reference names with the 281 * same leading components can conflict *with each other* is a 282 * separate issue that is regulated by verify_refname_available().) 283 * 284 * Please note that the name field contains the fully-qualified 285 * reference (or subdirectory) name. Space could be saved by only 286 * storing the relative names. But that would require the full names 287 * to be generated on the fly when iterating in do_for_each_ref(), and 288 * would break callback functions, who have always been able to assume 289 * that the name strings that they are passed will not be freed during 290 * the iteration. 291 */ 292struct ref_entry { 293unsigned char flag;/* ISSYMREF? ISPACKED? */ 294union{ 295struct ref_value value;/* if not (flags&REF_DIR) */ 296struct ref_dir subdir;/* if (flags&REF_DIR) */ 297} u; 298/* 299 * The full name of the reference (e.g., "refs/heads/master") 300 * or the full name of the directory with a trailing slash 301 * (e.g., "refs/heads/"): 302 */ 303char name[FLEX_ARRAY]; 304}; 305 306static voidread_loose_refs(const char*dirname,struct ref_dir *dir); 307static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len); 308static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 309const char*dirname,size_t len, 310int incomplete); 311static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry); 312 313static struct ref_dir *get_ref_dir(struct ref_entry *entry) 314{ 315struct ref_dir *dir; 316assert(entry->flag & REF_DIR); 317 dir = &entry->u.subdir; 318if(entry->flag & REF_INCOMPLETE) { 319read_loose_refs(entry->name, dir); 320 321/* 322 * Manually add refs/bisect, which, being 323 * per-worktree, might not appear in the directory 324 * listing for refs/ in the main repo. 325 */ 326if(!strcmp(entry->name,"refs/")) { 327int pos =search_ref_dir(dir,"refs/bisect/",12); 328if(pos <0) { 329struct ref_entry *child_entry; 330 child_entry =create_dir_entry(dir->ref_cache, 331"refs/bisect/", 33212,1); 333add_entry_to_dir(dir, child_entry); 334read_loose_refs("refs/bisect", 335&child_entry->u.subdir); 336} 337} 338 entry->flag &= ~REF_INCOMPLETE; 339} 340return dir; 341} 342 343/* 344 * Check if a refname is safe. 345 * For refs that start with "refs/" we consider it safe as long they do 346 * not try to resolve to outside of refs/. 347 * 348 * For all other refs we only consider them safe iff they only contain 349 * upper case characters and '_' (like "HEAD" AND "MERGE_HEAD", and not like 350 * "config"). 351 */ 352static intrefname_is_safe(const char*refname) 353{ 354if(starts_with(refname,"refs/")) { 355char*buf; 356int result; 357 358 buf =xmalloc(strlen(refname) +1); 359/* 360 * Does the refname try to escape refs/? 361 * For example: refs/foo/../bar is safe but refs/foo/../../bar 362 * is not. 363 */ 364 result = !normalize_path_copy(buf, refname +strlen("refs/")); 365free(buf); 366return result; 367} 368while(*refname) { 369if(!isupper(*refname) && *refname !='_') 370return0; 371 refname++; 372} 373return1; 374} 375 376static struct ref_entry *create_ref_entry(const char*refname, 377const unsigned char*sha1,int flag, 378int check_name) 379{ 380int len; 381struct ref_entry *ref; 382 383if(check_name && 384check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 385die("Reference has invalid format: '%s'", refname); 386 len =strlen(refname) +1; 387 ref =xmalloc(sizeof(struct ref_entry) + len); 388hashcpy(ref->u.value.oid.hash, sha1); 389oidclr(&ref->u.value.peeled); 390memcpy(ref->name, refname, len); 391 ref->flag = flag; 392return ref; 393} 394 395static voidclear_ref_dir(struct ref_dir *dir); 396 397static voidfree_ref_entry(struct ref_entry *entry) 398{ 399if(entry->flag & REF_DIR) { 400/* 401 * Do not use get_ref_dir() here, as that might 402 * trigger the reading of loose refs. 403 */ 404clear_ref_dir(&entry->u.subdir); 405} 406free(entry); 407} 408 409/* 410 * Add a ref_entry to the end of dir (unsorted). Entry is always 411 * stored directly in dir; no recursion into subdirectories is 412 * done. 413 */ 414static voidadd_entry_to_dir(struct ref_dir *dir,struct ref_entry *entry) 415{ 416ALLOC_GROW(dir->entries, dir->nr +1, dir->alloc); 417 dir->entries[dir->nr++] = entry; 418/* optimize for the case that entries are added in order */ 419if(dir->nr ==1|| 420(dir->nr == dir->sorted +1&& 421strcmp(dir->entries[dir->nr -2]->name, 422 dir->entries[dir->nr -1]->name) <0)) 423 dir->sorted = dir->nr; 424} 425 426/* 427 * Clear and free all entries in dir, recursively. 428 */ 429static voidclear_ref_dir(struct ref_dir *dir) 430{ 431int i; 432for(i =0; i < dir->nr; i++) 433free_ref_entry(dir->entries[i]); 434free(dir->entries); 435 dir->sorted = dir->nr = dir->alloc =0; 436 dir->entries = NULL; 437} 438 439/* 440 * Create a struct ref_entry object for the specified dirname. 441 * dirname is the name of the directory with a trailing slash (e.g., 442 * "refs/heads/") or "" for the top-level directory. 443 */ 444static struct ref_entry *create_dir_entry(struct ref_cache *ref_cache, 445const char*dirname,size_t len, 446int incomplete) 447{ 448struct ref_entry *direntry; 449 direntry =xcalloc(1,sizeof(struct ref_entry) + len +1); 450memcpy(direntry->name, dirname, len); 451 direntry->name[len] ='\0'; 452 direntry->u.subdir.ref_cache = ref_cache; 453 direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE :0); 454return direntry; 455} 456 457static intref_entry_cmp(const void*a,const void*b) 458{ 459struct ref_entry *one = *(struct ref_entry **)a; 460struct ref_entry *two = *(struct ref_entry **)b; 461returnstrcmp(one->name, two->name); 462} 463 464static voidsort_ref_dir(struct ref_dir *dir); 465 466struct string_slice { 467size_t len; 468const char*str; 469}; 470 471static intref_entry_cmp_sslice(const void*key_,const void*ent_) 472{ 473const struct string_slice *key = key_; 474const struct ref_entry *ent = *(const struct ref_entry *const*)ent_; 475int cmp =strncmp(key->str, ent->name, key->len); 476if(cmp) 477return cmp; 478return'\0'- (unsigned char)ent->name[key->len]; 479} 480 481/* 482 * Return the index of the entry with the given refname from the 483 * ref_dir (non-recursively), sorting dir if necessary. Return -1 if 484 * no such entry is found. dir must already be complete. 485 */ 486static intsearch_ref_dir(struct ref_dir *dir,const char*refname,size_t len) 487{ 488struct ref_entry **r; 489struct string_slice key; 490 491if(refname == NULL || !dir->nr) 492return-1; 493 494sort_ref_dir(dir); 495 key.len = len; 496 key.str = refname; 497 r =bsearch(&key, dir->entries, dir->nr,sizeof(*dir->entries), 498 ref_entry_cmp_sslice); 499 500if(r == NULL) 501return-1; 502 503return r - dir->entries; 504} 505 506/* 507 * Search for a directory entry directly within dir (without 508 * recursing). Sort dir if necessary. subdirname must be a directory 509 * name (i.e., end in '/'). If mkdir is set, then create the 510 * directory if it is missing; otherwise, return NULL if the desired 511 * directory cannot be found. dir must already be complete. 512 */ 513static struct ref_dir *search_for_subdir(struct ref_dir *dir, 514const char*subdirname,size_t len, 515int mkdir) 516{ 517int entry_index =search_ref_dir(dir, subdirname, len); 518struct ref_entry *entry; 519if(entry_index == -1) { 520if(!mkdir) 521return NULL; 522/* 523 * Since dir is complete, the absence of a subdir 524 * means that the subdir really doesn't exist; 525 * therefore, create an empty record for it but mark 526 * the record complete. 527 */ 528 entry =create_dir_entry(dir->ref_cache, subdirname, len,0); 529add_entry_to_dir(dir, entry); 530}else{ 531 entry = dir->entries[entry_index]; 532} 533returnget_ref_dir(entry); 534} 535 536/* 537 * If refname is a reference name, find the ref_dir within the dir 538 * tree that should hold refname. If refname is a directory name 539 * (i.e., ends in '/'), then return that ref_dir itself. dir must 540 * represent the top-level directory and must already be complete. 541 * Sort ref_dirs and recurse into subdirectories as necessary. If 542 * mkdir is set, then create any missing directories; otherwise, 543 * return NULL if the desired directory cannot be found. 544 */ 545static struct ref_dir *find_containing_dir(struct ref_dir *dir, 546const char*refname,int mkdir) 547{ 548const char*slash; 549for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 550size_t dirnamelen = slash - refname +1; 551struct ref_dir *subdir; 552 subdir =search_for_subdir(dir, refname, dirnamelen, mkdir); 553if(!subdir) { 554 dir = NULL; 555break; 556} 557 dir = subdir; 558} 559 560return dir; 561} 562 563/* 564 * Find the value entry with the given name in dir, sorting ref_dirs 565 * and recursing into subdirectories as necessary. If the name is not 566 * found or it corresponds to a directory entry, return NULL. 567 */ 568static struct ref_entry *find_ref(struct ref_dir *dir,const char*refname) 569{ 570int entry_index; 571struct ref_entry *entry; 572 dir =find_containing_dir(dir, refname,0); 573if(!dir) 574return NULL; 575 entry_index =search_ref_dir(dir, refname,strlen(refname)); 576if(entry_index == -1) 577return NULL; 578 entry = dir->entries[entry_index]; 579return(entry->flag & REF_DIR) ? NULL : entry; 580} 581 582/* 583 * Remove the entry with the given name from dir, recursing into 584 * subdirectories as necessary. If refname is the name of a directory 585 * (i.e., ends with '/'), then remove the directory and its contents. 586 * If the removal was successful, return the number of entries 587 * remaining in the directory entry that contained the deleted entry. 588 * If the name was not found, return -1. Please note that this 589 * function only deletes the entry from the cache; it does not delete 590 * it from the filesystem or ensure that other cache entries (which 591 * might be symbolic references to the removed entry) are updated. 592 * Nor does it remove any containing dir entries that might be made 593 * empty by the removal. dir must represent the top-level directory 594 * and must already be complete. 595 */ 596static intremove_entry(struct ref_dir *dir,const char*refname) 597{ 598int refname_len =strlen(refname); 599int entry_index; 600struct ref_entry *entry; 601int is_dir = refname[refname_len -1] =='/'; 602if(is_dir) { 603/* 604 * refname represents a reference directory. Remove 605 * the trailing slash; otherwise we will get the 606 * directory *representing* refname rather than the 607 * one *containing* it. 608 */ 609char*dirname =xmemdupz(refname, refname_len -1); 610 dir =find_containing_dir(dir, dirname,0); 611free(dirname); 612}else{ 613 dir =find_containing_dir(dir, refname,0); 614} 615if(!dir) 616return-1; 617 entry_index =search_ref_dir(dir, refname, refname_len); 618if(entry_index == -1) 619return-1; 620 entry = dir->entries[entry_index]; 621 622memmove(&dir->entries[entry_index], 623&dir->entries[entry_index +1], 624(dir->nr - entry_index -1) *sizeof(*dir->entries) 625); 626 dir->nr--; 627if(dir->sorted > entry_index) 628 dir->sorted--; 629free_ref_entry(entry); 630return dir->nr; 631} 632 633/* 634 * Add a ref_entry to the ref_dir (unsorted), recursing into 635 * subdirectories as necessary. dir must represent the top-level 636 * directory. Return 0 on success. 637 */ 638static intadd_ref(struct ref_dir *dir,struct ref_entry *ref) 639{ 640 dir =find_containing_dir(dir, ref->name,1); 641if(!dir) 642return-1; 643add_entry_to_dir(dir, ref); 644return0; 645} 646 647/* 648 * Emit a warning and return true iff ref1 and ref2 have the same name 649 * and the same sha1. Die if they have the same name but different 650 * sha1s. 651 */ 652static intis_dup_ref(const struct ref_entry *ref1,const struct ref_entry *ref2) 653{ 654if(strcmp(ref1->name, ref2->name)) 655return0; 656 657/* Duplicate name; make sure that they don't conflict: */ 658 659if((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR)) 660/* This is impossible by construction */ 661die("Reference directory conflict:%s", ref1->name); 662 663if(oidcmp(&ref1->u.value.oid, &ref2->u.value.oid)) 664die("Duplicated ref, and SHA1s don't match:%s", ref1->name); 665 666warning("Duplicated ref:%s", ref1->name); 667return1; 668} 669 670/* 671 * Sort the entries in dir non-recursively (if they are not already 672 * sorted) and remove any duplicate entries. 673 */ 674static voidsort_ref_dir(struct ref_dir *dir) 675{ 676int i, j; 677struct ref_entry *last = NULL; 678 679/* 680 * This check also prevents passing a zero-length array to qsort(), 681 * which is a problem on some platforms. 682 */ 683if(dir->sorted == dir->nr) 684return; 685 686qsort(dir->entries, dir->nr,sizeof(*dir->entries), ref_entry_cmp); 687 688/* Remove any duplicates: */ 689for(i =0, j =0; j < dir->nr; j++) { 690struct ref_entry *entry = dir->entries[j]; 691if(last &&is_dup_ref(last, entry)) 692free_ref_entry(entry); 693else 694 last = dir->entries[i++] = entry; 695} 696 dir->sorted = dir->nr = i; 697} 698 699/* Include broken references in a do_for_each_ref*() iteration: */ 700#define DO_FOR_EACH_INCLUDE_BROKEN 0x01 701 702/* 703 * Return true iff the reference described by entry can be resolved to 704 * an object in the database. Emit a warning if the referred-to 705 * object does not exist. 706 */ 707static intref_resolves_to_object(struct ref_entry *entry) 708{ 709if(entry->flag & REF_ISBROKEN) 710return0; 711if(!has_sha1_file(entry->u.value.oid.hash)) { 712error("%sdoes not point to a valid object!", entry->name); 713return0; 714} 715return1; 716} 717 718/* 719 * current_ref is a performance hack: when iterating over references 720 * using the for_each_ref*() functions, current_ref is set to the 721 * current reference's entry before calling the callback function. If 722 * the callback function calls peel_ref(), then peel_ref() first 723 * checks whether the reference to be peeled is the current reference 724 * (it usually is) and if so, returns that reference's peeled version 725 * if it is available. This avoids a refname lookup in a common case. 726 */ 727static struct ref_entry *current_ref; 728 729typedefinteach_ref_entry_fn(struct ref_entry *entry,void*cb_data); 730 731struct ref_entry_cb { 732const char*base; 733int trim; 734int flags; 735 each_ref_fn *fn; 736void*cb_data; 737}; 738 739/* 740 * Handle one reference in a do_for_each_ref*()-style iteration, 741 * calling an each_ref_fn for each entry. 742 */ 743static intdo_one_ref(struct ref_entry *entry,void*cb_data) 744{ 745struct ref_entry_cb *data = cb_data; 746struct ref_entry *old_current_ref; 747int retval; 748 749if(!starts_with(entry->name, data->base)) 750return0; 751 752if(!(data->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 753!ref_resolves_to_object(entry)) 754return0; 755 756/* Store the old value, in case this is a recursive call: */ 757 old_current_ref = current_ref; 758 current_ref = entry; 759 retval = data->fn(entry->name + data->trim, &entry->u.value.oid, 760 entry->flag, data->cb_data); 761 current_ref = old_current_ref; 762return retval; 763} 764 765/* 766 * Call fn for each reference in dir that has index in the range 767 * offset <= index < dir->nr. Recurse into subdirectories that are in 768 * that index range, sorting them before iterating. This function 769 * does not sort dir itself; it should be sorted beforehand. fn is 770 * called for all references, including broken ones. 771 */ 772static intdo_for_each_entry_in_dir(struct ref_dir *dir,int offset, 773 each_ref_entry_fn fn,void*cb_data) 774{ 775int i; 776assert(dir->sorted == dir->nr); 777for(i = offset; i < dir->nr; i++) { 778struct ref_entry *entry = dir->entries[i]; 779int retval; 780if(entry->flag & REF_DIR) { 781struct ref_dir *subdir =get_ref_dir(entry); 782sort_ref_dir(subdir); 783 retval =do_for_each_entry_in_dir(subdir,0, fn, cb_data); 784}else{ 785 retval =fn(entry, cb_data); 786} 787if(retval) 788return retval; 789} 790return0; 791} 792 793/* 794 * Call fn for each reference in the union of dir1 and dir2, in order 795 * by refname. Recurse into subdirectories. If a value entry appears 796 * in both dir1 and dir2, then only process the version that is in 797 * dir2. The input dirs must already be sorted, but subdirs will be 798 * sorted as needed. fn is called for all references, including 799 * broken ones. 800 */ 801static intdo_for_each_entry_in_dirs(struct ref_dir *dir1, 802struct ref_dir *dir2, 803 each_ref_entry_fn fn,void*cb_data) 804{ 805int retval; 806int i1 =0, i2 =0; 807 808assert(dir1->sorted == dir1->nr); 809assert(dir2->sorted == dir2->nr); 810while(1) { 811struct ref_entry *e1, *e2; 812int cmp; 813if(i1 == dir1->nr) { 814returndo_for_each_entry_in_dir(dir2, i2, fn, cb_data); 815} 816if(i2 == dir2->nr) { 817returndo_for_each_entry_in_dir(dir1, i1, fn, cb_data); 818} 819 e1 = dir1->entries[i1]; 820 e2 = dir2->entries[i2]; 821 cmp =strcmp(e1->name, e2->name); 822if(cmp ==0) { 823if((e1->flag & REF_DIR) && (e2->flag & REF_DIR)) { 824/* Both are directories; descend them in parallel. */ 825struct ref_dir *subdir1 =get_ref_dir(e1); 826struct ref_dir *subdir2 =get_ref_dir(e2); 827sort_ref_dir(subdir1); 828sort_ref_dir(subdir2); 829 retval =do_for_each_entry_in_dirs( 830 subdir1, subdir2, fn, cb_data); 831 i1++; 832 i2++; 833}else if(!(e1->flag & REF_DIR) && !(e2->flag & REF_DIR)) { 834/* Both are references; ignore the one from dir1. */ 835 retval =fn(e2, cb_data); 836 i1++; 837 i2++; 838}else{ 839die("conflict between reference and directory:%s", 840 e1->name); 841} 842}else{ 843struct ref_entry *e; 844if(cmp <0) { 845 e = e1; 846 i1++; 847}else{ 848 e = e2; 849 i2++; 850} 851if(e->flag & REF_DIR) { 852struct ref_dir *subdir =get_ref_dir(e); 853sort_ref_dir(subdir); 854 retval =do_for_each_entry_in_dir( 855 subdir,0, fn, cb_data); 856}else{ 857 retval =fn(e, cb_data); 858} 859} 860if(retval) 861return retval; 862} 863} 864 865/* 866 * Load all of the refs from the dir into our in-memory cache. The hard work 867 * of loading loose refs is done by get_ref_dir(), so we just need to recurse 868 * through all of the sub-directories. We do not even need to care about 869 * sorting, as traversal order does not matter to us. 870 */ 871static voidprime_ref_dir(struct ref_dir *dir) 872{ 873int i; 874for(i =0; i < dir->nr; i++) { 875struct ref_entry *entry = dir->entries[i]; 876if(entry->flag & REF_DIR) 877prime_ref_dir(get_ref_dir(entry)); 878} 879} 880 881struct nonmatching_ref_data { 882const struct string_list *skip; 883const char*conflicting_refname; 884}; 885 886static intnonmatching_ref_fn(struct ref_entry *entry,void*vdata) 887{ 888struct nonmatching_ref_data *data = vdata; 889 890if(data->skip &&string_list_has_string(data->skip, entry->name)) 891return0; 892 893 data->conflicting_refname = entry->name; 894return1; 895} 896 897/* 898 * Return 0 if a reference named refname could be created without 899 * conflicting with the name of an existing reference in dir. 900 * Otherwise, return a negative value and write an explanation to err. 901 * If extras is non-NULL, it is a list of additional refnames with 902 * which refname is not allowed to conflict. If skip is non-NULL, 903 * ignore potential conflicts with refs in skip (e.g., because they 904 * are scheduled for deletion in the same operation). Behavior is 905 * undefined if the same name is listed in both extras and skip. 906 * 907 * Two reference names conflict if one of them exactly matches the 908 * leading components of the other; e.g., "refs/foo/bar" conflicts 909 * with both "refs/foo" and with "refs/foo/bar/baz" but not with 910 * "refs/foo/bar" or "refs/foo/barbados". 911 * 912 * extras and skip must be sorted. 913 */ 914static intverify_refname_available(const char*refname, 915const struct string_list *extras, 916const struct string_list *skip, 917struct ref_dir *dir, 918struct strbuf *err) 919{ 920const char*slash; 921int pos; 922struct strbuf dirname = STRBUF_INIT; 923int ret = -1; 924 925/* 926 * For the sake of comments in this function, suppose that 927 * refname is "refs/foo/bar". 928 */ 929 930assert(err); 931 932strbuf_grow(&dirname,strlen(refname) +1); 933for(slash =strchr(refname,'/'); slash; slash =strchr(slash +1,'/')) { 934/* Expand dirname to the new prefix, not including the trailing slash: */ 935strbuf_add(&dirname, refname + dirname.len, slash - refname - dirname.len); 936 937/* 938 * We are still at a leading dir of the refname (e.g., 939 * "refs/foo"; if there is a reference with that name, 940 * it is a conflict, *unless* it is in skip. 941 */ 942if(dir) { 943 pos =search_ref_dir(dir, dirname.buf, dirname.len); 944if(pos >=0&& 945(!skip || !string_list_has_string(skip, dirname.buf))) { 946/* 947 * We found a reference whose name is 948 * a proper prefix of refname; e.g., 949 * "refs/foo", and is not in skip. 950 */ 951strbuf_addf(err,"'%s' exists; cannot create '%s'", 952 dirname.buf, refname); 953goto cleanup; 954} 955} 956 957if(extras &&string_list_has_string(extras, dirname.buf) && 958(!skip || !string_list_has_string(skip, dirname.buf))) { 959strbuf_addf(err,"cannot process '%s' and '%s' at the same time", 960 refname, dirname.buf); 961goto cleanup; 962} 963 964/* 965 * Otherwise, we can try to continue our search with 966 * the next component. So try to look up the 967 * directory, e.g., "refs/foo/". If we come up empty, 968 * we know there is nothing under this whole prefix, 969 * but even in that case we still have to continue the 970 * search for conflicts with extras. 971 */ 972strbuf_addch(&dirname,'/'); 973if(dir) { 974 pos =search_ref_dir(dir, dirname.buf, dirname.len); 975if(pos <0) { 976/* 977 * There was no directory "refs/foo/", 978 * so there is nothing under this 979 * whole prefix. So there is no need 980 * to continue looking for conflicting 981 * references. But we need to continue 982 * looking for conflicting extras. 983 */ 984 dir = NULL; 985}else{ 986 dir =get_ref_dir(dir->entries[pos]); 987} 988} 989} 990 991/* 992 * We are at the leaf of our refname (e.g., "refs/foo/bar"). 993 * There is no point in searching for a reference with that 994 * name, because a refname isn't considered to conflict with 995 * itself. But we still need to check for references whose 996 * names are in the "refs/foo/bar/" namespace, because they 997 * *do* conflict. 998 */ 999strbuf_addstr(&dirname, refname + dirname.len);1000strbuf_addch(&dirname,'/');10011002if(dir) {1003 pos =search_ref_dir(dir, dirname.buf, dirname.len);10041005if(pos >=0) {1006/*1007 * We found a directory named "$refname/"1008 * (e.g., "refs/foo/bar/"). It is a problem1009 * iff it contains any ref that is not in1010 * "skip".1011 */1012struct nonmatching_ref_data data;10131014 data.skip = skip;1015 data.conflicting_refname = NULL;1016 dir =get_ref_dir(dir->entries[pos]);1017sort_ref_dir(dir);1018if(do_for_each_entry_in_dir(dir,0, nonmatching_ref_fn, &data)) {1019strbuf_addf(err,"'%s' exists; cannot create '%s'",1020 data.conflicting_refname, refname);1021goto cleanup;1022}1023}1024}10251026if(extras) {1027/*1028 * Check for entries in extras that start with1029 * "$refname/". We do that by looking for the place1030 * where "$refname/" would be inserted in extras. If1031 * there is an entry at that position that starts with1032 * "$refname/" and is not in skip, then we have a1033 * conflict.1034 */1035for(pos =string_list_find_insert_index(extras, dirname.buf,0);1036 pos < extras->nr; pos++) {1037const char*extra_refname = extras->items[pos].string;10381039if(!starts_with(extra_refname, dirname.buf))1040break;10411042if(!skip || !string_list_has_string(skip, extra_refname)) {1043strbuf_addf(err,"cannot process '%s' and '%s' at the same time",1044 refname, extra_refname);1045goto cleanup;1046}1047}1048}10491050/* No conflicts were found */1051 ret =0;10521053cleanup:1054strbuf_release(&dirname);1055return ret;1056}10571058struct packed_ref_cache {1059struct ref_entry *root;10601061/*1062 * Count of references to the data structure in this instance,1063 * including the pointer from ref_cache::packed if any. The1064 * data will not be freed as long as the reference count is1065 * nonzero.1066 */1067unsigned int referrers;10681069/*1070 * Iff the packed-refs file associated with this instance is1071 * currently locked for writing, this points at the associated1072 * lock (which is owned by somebody else). The referrer count1073 * is also incremented when the file is locked and decremented1074 * when it is unlocked.1075 */1076struct lock_file *lock;10771078/* The metadata from when this packed-refs cache was read */1079struct stat_validity validity;1080};10811082/*1083 * Future: need to be in "struct repository"1084 * when doing a full libification.1085 */1086static struct ref_cache {1087struct ref_cache *next;1088struct ref_entry *loose;1089struct packed_ref_cache *packed;1090/*1091 * The submodule name, or "" for the main repo. We allocate1092 * length 1 rather than FLEX_ARRAY so that the main ref_cache1093 * is initialized correctly.1094 */1095char name[1];1096} ref_cache, *submodule_ref_caches;10971098/* Lock used for the main packed-refs file: */1099static struct lock_file packlock;11001101/*1102 * Increment the reference count of *packed_refs.1103 */1104static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs)1105{1106 packed_refs->referrers++;1107}11081109/*1110 * Decrease the reference count of *packed_refs. If it goes to zero,1111 * free *packed_refs and return true; otherwise return false.1112 */1113static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs)1114{1115if(!--packed_refs->referrers) {1116free_ref_entry(packed_refs->root);1117stat_validity_clear(&packed_refs->validity);1118free(packed_refs);1119return1;1120}else{1121return0;1122}1123}11241125static voidclear_packed_ref_cache(struct ref_cache *refs)1126{1127if(refs->packed) {1128struct packed_ref_cache *packed_refs = refs->packed;11291130if(packed_refs->lock)1131die("internal error: packed-ref cache cleared while locked");1132 refs->packed = NULL;1133release_packed_ref_cache(packed_refs);1134}1135}11361137static voidclear_loose_ref_cache(struct ref_cache *refs)1138{1139if(refs->loose) {1140free_ref_entry(refs->loose);1141 refs->loose = NULL;1142}1143}11441145static struct ref_cache *create_ref_cache(const char*submodule)1146{1147int len;1148struct ref_cache *refs;1149if(!submodule)1150 submodule ="";1151 len =strlen(submodule) +1;1152 refs =xcalloc(1,sizeof(struct ref_cache) + len);1153memcpy(refs->name, submodule, len);1154return refs;1155}11561157/*1158 * Return a pointer to a ref_cache for the specified submodule. For1159 * the main repository, use submodule==NULL. The returned structure1160 * will be allocated and initialized but not necessarily populated; it1161 * should not be freed.1162 */1163static struct ref_cache *get_ref_cache(const char*submodule)1164{1165struct ref_cache *refs;11661167if(!submodule || !*submodule)1168return&ref_cache;11691170for(refs = submodule_ref_caches; refs; refs = refs->next)1171if(!strcmp(submodule, refs->name))1172return refs;11731174 refs =create_ref_cache(submodule);1175 refs->next = submodule_ref_caches;1176 submodule_ref_caches = refs;1177return refs;1178}11791180/* The length of a peeled reference line in packed-refs, including EOL: */1181#define PEELED_LINE_LENGTH 4211821183/*1184 * The packed-refs header line that we write out. Perhaps other1185 * traits will be added later. The trailing space is required.1186 */1187static const char PACKED_REFS_HEADER[] =1188"# pack-refs with: peeled fully-peeled\n";11891190/*1191 * Parse one line from a packed-refs file. Write the SHA1 to sha1.1192 * Return a pointer to the refname within the line (null-terminated),1193 * or NULL if there was a problem.1194 */1195static const char*parse_ref_line(struct strbuf *line,unsigned char*sha1)1196{1197const char*ref;11981199/*1200 * 42: the answer to everything.1201 *1202 * In this case, it happens to be the answer to1203 * 40 (length of sha1 hex representation)1204 * +1 (space in between hex and name)1205 * +1 (newline at the end of the line)1206 */1207if(line->len <=42)1208return NULL;12091210if(get_sha1_hex(line->buf, sha1) <0)1211return NULL;1212if(!isspace(line->buf[40]))1213return NULL;12141215 ref = line->buf +41;1216if(isspace(*ref))1217return NULL;12181219if(line->buf[line->len -1] !='\n')1220return NULL;1221 line->buf[--line->len] =0;12221223return ref;1224}12251226/*1227 * Read f, which is a packed-refs file, into dir.1228 *1229 * A comment line of the form "# pack-refs with: " may contain zero or1230 * more traits. We interpret the traits as follows:1231 *1232 * No traits:1233 *1234 * Probably no references are peeled. But if the file contains a1235 * peeled value for a reference, we will use it.1236 *1237 * peeled:1238 *1239 * References under "refs/tags/", if they *can* be peeled, *are*1240 * peeled in this file. References outside of "refs/tags/" are1241 * probably not peeled even if they could have been, but if we find1242 * a peeled value for such a reference we will use it.1243 *1244 * fully-peeled:1245 *1246 * All references in the file that can be peeled are peeled.1247 * Inversely (and this is more important), any references in the1248 * file for which no peeled value is recorded is not peelable. This1249 * trait should typically be written alongside "peeled" for1250 * compatibility with older clients, but we do not require it1251 * (i.e., "peeled" is a no-op if "fully-peeled" is set).1252 */1253static voidread_packed_refs(FILE*f,struct ref_dir *dir)1254{1255struct ref_entry *last = NULL;1256struct strbuf line = STRBUF_INIT;1257enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE;12581259while(strbuf_getwholeline(&line, f,'\n') != EOF) {1260unsigned char sha1[20];1261const char*refname;1262const char*traits;12631264if(skip_prefix(line.buf,"# pack-refs with:", &traits)) {1265if(strstr(traits," fully-peeled "))1266 peeled = PEELED_FULLY;1267else if(strstr(traits," peeled "))1268 peeled = PEELED_TAGS;1269/* perhaps other traits later as well */1270continue;1271}12721273 refname =parse_ref_line(&line, sha1);1274if(refname) {1275int flag = REF_ISPACKED;12761277if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1278if(!refname_is_safe(refname))1279die("packed refname is dangerous:%s", refname);1280hashclr(sha1);1281 flag |= REF_BAD_NAME | REF_ISBROKEN;1282}1283 last =create_ref_entry(refname, sha1, flag,0);1284if(peeled == PEELED_FULLY ||1285(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/")))1286 last->flag |= REF_KNOWS_PEELED;1287add_ref(dir, last);1288continue;1289}1290if(last &&1291 line.buf[0] =='^'&&1292 line.len == PEELED_LINE_LENGTH &&1293 line.buf[PEELED_LINE_LENGTH -1] =='\n'&&1294!get_sha1_hex(line.buf +1, sha1)) {1295hashcpy(last->u.value.peeled.hash, sha1);1296/*1297 * Regardless of what the file header said,1298 * we definitely know the value of *this*1299 * reference:1300 */1301 last->flag |= REF_KNOWS_PEELED;1302}1303}13041305strbuf_release(&line);1306}13071308/*1309 * Get the packed_ref_cache for the specified ref_cache, creating it1310 * if necessary.1311 */1312static struct packed_ref_cache *get_packed_ref_cache(struct ref_cache *refs)1313{1314char*packed_refs_file;13151316if(*refs->name)1317 packed_refs_file =git_pathdup_submodule(refs->name,"packed-refs");1318else1319 packed_refs_file =git_pathdup("packed-refs");13201321if(refs->packed &&1322!stat_validity_check(&refs->packed->validity, packed_refs_file))1323clear_packed_ref_cache(refs);13241325if(!refs->packed) {1326FILE*f;13271328 refs->packed =xcalloc(1,sizeof(*refs->packed));1329acquire_packed_ref_cache(refs->packed);1330 refs->packed->root =create_dir_entry(refs,"",0,0);1331 f =fopen(packed_refs_file,"r");1332if(f) {1333stat_validity_update(&refs->packed->validity,fileno(f));1334read_packed_refs(f,get_ref_dir(refs->packed->root));1335fclose(f);1336}1337}1338free(packed_refs_file);1339return refs->packed;1340}13411342static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache)1343{1344returnget_ref_dir(packed_ref_cache->root);1345}13461347static struct ref_dir *get_packed_refs(struct ref_cache *refs)1348{1349returnget_packed_ref_dir(get_packed_ref_cache(refs));1350}13511352/*1353 * Add a reference to the in-memory packed reference cache. This may1354 * only be called while the packed-refs file is locked (see1355 * lock_packed_refs()). To actually write the packed-refs file, call1356 * commit_packed_refs().1357 */1358static voidadd_packed_ref(const char*refname,const unsigned char*sha1)1359{1360struct packed_ref_cache *packed_ref_cache =1361get_packed_ref_cache(&ref_cache);13621363if(!packed_ref_cache->lock)1364die("internal error: packed refs not locked");1365add_ref(get_packed_ref_dir(packed_ref_cache),1366create_ref_entry(refname, sha1, REF_ISPACKED,1));1367}13681369/*1370 * Read the loose references from the namespace dirname into dir1371 * (without recursing). dirname must end with '/'. dir must be the1372 * directory entry corresponding to dirname.1373 */1374static voidread_loose_refs(const char*dirname,struct ref_dir *dir)1375{1376struct ref_cache *refs = dir->ref_cache;1377DIR*d;1378struct dirent *de;1379int dirnamelen =strlen(dirname);1380struct strbuf refname;1381struct strbuf path = STRBUF_INIT;1382size_t path_baselen;13831384if(*refs->name)1385strbuf_git_path_submodule(&path, refs->name,"%s", dirname);1386else1387strbuf_git_path(&path,"%s", dirname);1388 path_baselen = path.len;13891390 d =opendir(path.buf);1391if(!d) {1392strbuf_release(&path);1393return;1394}13951396strbuf_init(&refname, dirnamelen +257);1397strbuf_add(&refname, dirname, dirnamelen);13981399while((de =readdir(d)) != NULL) {1400unsigned char sha1[20];1401struct stat st;1402int flag;14031404if(de->d_name[0] =='.')1405continue;1406if(ends_with(de->d_name,".lock"))1407continue;1408strbuf_addstr(&refname, de->d_name);1409strbuf_addstr(&path, de->d_name);1410if(stat(path.buf, &st) <0) {1411;/* silently ignore */1412}else if(S_ISDIR(st.st_mode)) {1413strbuf_addch(&refname,'/');1414add_entry_to_dir(dir,1415create_dir_entry(refs, refname.buf,1416 refname.len,1));1417}else{1418int read_ok;14191420if(*refs->name) {1421hashclr(sha1);1422 flag =0;1423 read_ok = !resolve_gitlink_ref(refs->name,1424 refname.buf, sha1);1425}else{1426 read_ok = !read_ref_full(refname.buf,1427 RESOLVE_REF_READING,1428 sha1, &flag);1429}14301431if(!read_ok) {1432hashclr(sha1);1433 flag |= REF_ISBROKEN;1434}else if(is_null_sha1(sha1)) {1435/*1436 * It is so astronomically unlikely1437 * that NULL_SHA1 is the SHA-1 of an1438 * actual object that we consider its1439 * appearance in a loose reference1440 * file to be repo corruption1441 * (probably due to a software bug).1442 */1443 flag |= REF_ISBROKEN;1444}14451446if(check_refname_format(refname.buf,1447 REFNAME_ALLOW_ONELEVEL)) {1448if(!refname_is_safe(refname.buf))1449die("loose refname is dangerous:%s", refname.buf);1450hashclr(sha1);1451 flag |= REF_BAD_NAME | REF_ISBROKEN;1452}1453add_entry_to_dir(dir,1454create_ref_entry(refname.buf, sha1, flag,0));1455}1456strbuf_setlen(&refname, dirnamelen);1457strbuf_setlen(&path, path_baselen);1458}1459strbuf_release(&refname);1460strbuf_release(&path);1461closedir(d);1462}14631464static struct ref_dir *get_loose_refs(struct ref_cache *refs)1465{1466if(!refs->loose) {1467/*1468 * Mark the top-level directory complete because we1469 * are about to read the only subdirectory that can1470 * hold references:1471 */1472 refs->loose =create_dir_entry(refs,"",0,0);1473/*1474 * Create an incomplete entry for "refs/":1475 */1476add_entry_to_dir(get_ref_dir(refs->loose),1477create_dir_entry(refs,"refs/",5,1));1478}1479returnget_ref_dir(refs->loose);1480}14811482/* We allow "recursive" symbolic refs. Only within reason, though */1483#define MAXDEPTH 51484#define MAXREFLEN (1024)14851486/*1487 * Called by resolve_gitlink_ref_recursive() after it failed to read1488 * from the loose refs in ref_cache refs. Find <refname> in the1489 * packed-refs file for the submodule.1490 */1491static intresolve_gitlink_packed_ref(struct ref_cache *refs,1492const char*refname,unsigned char*sha1)1493{1494struct ref_entry *ref;1495struct ref_dir *dir =get_packed_refs(refs);14961497 ref =find_ref(dir, refname);1498if(ref == NULL)1499return-1;15001501hashcpy(sha1, ref->u.value.oid.hash);1502return0;1503}15041505static intresolve_gitlink_ref_recursive(struct ref_cache *refs,1506const char*refname,unsigned char*sha1,1507int recursion)1508{1509int fd, len;1510char buffer[128], *p;1511char*path;15121513if(recursion > MAXDEPTH ||strlen(refname) > MAXREFLEN)1514return-1;1515 path = *refs->name1516?git_pathdup_submodule(refs->name,"%s", refname)1517:git_pathdup("%s", refname);1518 fd =open(path, O_RDONLY);1519free(path);1520if(fd <0)1521returnresolve_gitlink_packed_ref(refs, refname, sha1);15221523 len =read(fd, buffer,sizeof(buffer)-1);1524close(fd);1525if(len <0)1526return-1;1527while(len &&isspace(buffer[len-1]))1528 len--;1529 buffer[len] =0;15301531/* Was it a detached head or an old-fashioned symlink? */1532if(!get_sha1_hex(buffer, sha1))1533return0;15341535/* Symref? */1536if(strncmp(buffer,"ref:",4))1537return-1;1538 p = buffer +4;1539while(isspace(*p))1540 p++;15411542returnresolve_gitlink_ref_recursive(refs, p, sha1, recursion+1);1543}15441545intresolve_gitlink_ref(const char*path,const char*refname,unsigned char*sha1)1546{1547int len =strlen(path), retval;1548char*submodule;1549struct ref_cache *refs;15501551while(len && path[len-1] =='/')1552 len--;1553if(!len)1554return-1;1555 submodule =xstrndup(path, len);1556 refs =get_ref_cache(submodule);1557free(submodule);15581559 retval =resolve_gitlink_ref_recursive(refs, refname, sha1,0);1560return retval;1561}15621563/*1564 * Return the ref_entry for the given refname from the packed1565 * references. If it does not exist, return NULL.1566 */1567static struct ref_entry *get_packed_ref(const char*refname)1568{1569returnfind_ref(get_packed_refs(&ref_cache), refname);1570}15711572/*1573 * A loose ref file doesn't exist; check for a packed ref. The1574 * options are forwarded from resolve_safe_unsafe().1575 */1576static intresolve_missing_loose_ref(const char*refname,1577int resolve_flags,1578unsigned char*sha1,1579int*flags)1580{1581struct ref_entry *entry;15821583/*1584 * The loose reference file does not exist; check for a packed1585 * reference.1586 */1587 entry =get_packed_ref(refname);1588if(entry) {1589hashcpy(sha1, entry->u.value.oid.hash);1590if(flags)1591*flags |= REF_ISPACKED;1592return0;1593}1594/* The reference is not a packed reference, either. */1595if(resolve_flags & RESOLVE_REF_READING) {1596 errno = ENOENT;1597return-1;1598}else{1599hashclr(sha1);1600return0;1601}1602}16031604/* This function needs to return a meaningful errno on failure */1605static const char*resolve_ref_unsafe_1(const char*refname,1606int resolve_flags,1607unsigned char*sha1,1608int*flags,1609struct strbuf *sb_path)1610{1611int depth = MAXDEPTH;1612 ssize_t len;1613char buffer[256];1614static char refname_buffer[256];1615int bad_name =0;16161617if(flags)1618*flags =0;16191620if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {1621if(flags)1622*flags |= REF_BAD_NAME;16231624if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1625!refname_is_safe(refname)) {1626 errno = EINVAL;1627return NULL;1628}1629/*1630 * dwim_ref() uses REF_ISBROKEN to distinguish between1631 * missing refs and refs that were present but invalid,1632 * to complain about the latter to stderr.1633 *1634 * We don't know whether the ref exists, so don't set1635 * REF_ISBROKEN yet.1636 */1637 bad_name =1;1638}1639for(;;) {1640const char*path;1641struct stat st;1642char*buf;1643int fd;16441645if(--depth <0) {1646 errno = ELOOP;1647return NULL;1648}16491650strbuf_reset(sb_path);1651strbuf_git_path(sb_path,"%s", refname);1652 path = sb_path->buf;16531654/*1655 * We might have to loop back here to avoid a race1656 * condition: first we lstat() the file, then we try1657 * to read it as a link or as a file. But if somebody1658 * changes the type of the file (file <-> directory1659 * <-> symlink) between the lstat() and reading, then1660 * we don't want to report that as an error but rather1661 * try again starting with the lstat().1662 */1663 stat_ref:1664if(lstat(path, &st) <0) {1665if(errno != ENOENT)1666return NULL;1667if(resolve_missing_loose_ref(refname, resolve_flags,1668 sha1, flags))1669return NULL;1670if(bad_name) {1671hashclr(sha1);1672if(flags)1673*flags |= REF_ISBROKEN;1674}1675return refname;1676}16771678/* Follow "normalized" - ie "refs/.." symlinks by hand */1679if(S_ISLNK(st.st_mode)) {1680 len =readlink(path, buffer,sizeof(buffer)-1);1681if(len <0) {1682if(errno == ENOENT || errno == EINVAL)1683/* inconsistent with lstat; retry */1684goto stat_ref;1685else1686return NULL;1687}1688 buffer[len] =0;1689if(starts_with(buffer,"refs/") &&1690!check_refname_format(buffer,0)) {1691strcpy(refname_buffer, buffer);1692 refname = refname_buffer;1693if(flags)1694*flags |= REF_ISSYMREF;1695if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1696hashclr(sha1);1697return refname;1698}1699continue;1700}1701}17021703/* Is it a directory? */1704if(S_ISDIR(st.st_mode)) {1705 errno = EISDIR;1706return NULL;1707}17081709/*1710 * Anything else, just open it and try to use it as1711 * a ref1712 */1713 fd =open(path, O_RDONLY);1714if(fd <0) {1715if(errno == ENOENT)1716/* inconsistent with lstat; retry */1717goto stat_ref;1718else1719return NULL;1720}1721 len =read_in_full(fd, buffer,sizeof(buffer)-1);1722if(len <0) {1723int save_errno = errno;1724close(fd);1725 errno = save_errno;1726return NULL;1727}1728close(fd);1729while(len &&isspace(buffer[len-1]))1730 len--;1731 buffer[len] ='\0';17321733/*1734 * Is it a symbolic ref?1735 */1736if(!starts_with(buffer,"ref:")) {1737/*1738 * Please note that FETCH_HEAD has a second1739 * line containing other data.1740 */1741if(get_sha1_hex(buffer, sha1) ||1742(buffer[40] !='\0'&& !isspace(buffer[40]))) {1743if(flags)1744*flags |= REF_ISBROKEN;1745 errno = EINVAL;1746return NULL;1747}1748if(bad_name) {1749hashclr(sha1);1750if(flags)1751*flags |= REF_ISBROKEN;1752}1753return refname;1754}1755if(flags)1756*flags |= REF_ISSYMREF;1757 buf = buffer +4;1758while(isspace(*buf))1759 buf++;1760 refname =strcpy(refname_buffer, buf);1761if(resolve_flags & RESOLVE_REF_NO_RECURSE) {1762hashclr(sha1);1763return refname;1764}1765if(check_refname_format(buf, REFNAME_ALLOW_ONELEVEL)) {1766if(flags)1767*flags |= REF_ISBROKEN;17681769if(!(resolve_flags & RESOLVE_REF_ALLOW_BAD_NAME) ||1770!refname_is_safe(buf)) {1771 errno = EINVAL;1772return NULL;1773}1774 bad_name =1;1775}1776}1777}17781779const char*resolve_ref_unsafe(const char*refname,int resolve_flags,1780unsigned char*sha1,int*flags)1781{1782struct strbuf sb_path = STRBUF_INIT;1783const char*ret =resolve_ref_unsafe_1(refname, resolve_flags,1784 sha1, flags, &sb_path);1785strbuf_release(&sb_path);1786return ret;1787}17881789char*resolve_refdup(const char*refname,int resolve_flags,1790unsigned char*sha1,int*flags)1791{1792returnxstrdup_or_null(resolve_ref_unsafe(refname, resolve_flags,1793 sha1, flags));1794}17951796/* The argument to filter_refs */1797struct ref_filter {1798const char*pattern;1799 each_ref_fn *fn;1800void*cb_data;1801};18021803intread_ref_full(const char*refname,int resolve_flags,unsigned char*sha1,int*flags)1804{1805if(resolve_ref_unsafe(refname, resolve_flags, sha1, flags))1806return0;1807return-1;1808}18091810intread_ref(const char*refname,unsigned char*sha1)1811{1812returnread_ref_full(refname, RESOLVE_REF_READING, sha1, NULL);1813}18141815intref_exists(const char*refname)1816{1817unsigned char sha1[20];1818return!!resolve_ref_unsafe(refname, RESOLVE_REF_READING, sha1, NULL);1819}18201821static intfilter_refs(const char*refname,const struct object_id *oid,1822int flags,void*data)1823{1824struct ref_filter *filter = (struct ref_filter *)data;18251826if(wildmatch(filter->pattern, refname,0, NULL))1827return0;1828return filter->fn(refname, oid, flags, filter->cb_data);1829}18301831enum peel_status {1832/* object was peeled successfully: */1833 PEEL_PEELED =0,18341835/*1836 * object cannot be peeled because the named object (or an1837 * object referred to by a tag in the peel chain), does not1838 * exist.1839 */1840 PEEL_INVALID = -1,18411842/* object cannot be peeled because it is not a tag: */1843 PEEL_NON_TAG = -2,18441845/* ref_entry contains no peeled value because it is a symref: */1846 PEEL_IS_SYMREF = -3,18471848/*1849 * ref_entry cannot be peeled because it is broken (i.e., the1850 * symbolic reference cannot even be resolved to an object1851 * name):1852 */1853 PEEL_BROKEN = -41854};18551856/*1857 * Peel the named object; i.e., if the object is a tag, resolve the1858 * tag recursively until a non-tag is found. If successful, store the1859 * result to sha1 and return PEEL_PEELED. If the object is not a tag1860 * or is not valid, return PEEL_NON_TAG or PEEL_INVALID, respectively,1861 * and leave sha1 unchanged.1862 */1863static enum peel_status peel_object(const unsigned char*name,unsigned char*sha1)1864{1865struct object *o =lookup_unknown_object(name);18661867if(o->type == OBJ_NONE) {1868int type =sha1_object_info(name, NULL);1869if(type <0|| !object_as_type(o, type,0))1870return PEEL_INVALID;1871}18721873if(o->type != OBJ_TAG)1874return PEEL_NON_TAG;18751876 o =deref_tag_noverify(o);1877if(!o)1878return PEEL_INVALID;18791880hashcpy(sha1, o->sha1);1881return PEEL_PEELED;1882}18831884/*1885 * Peel the entry (if possible) and return its new peel_status. If1886 * repeel is true, re-peel the entry even if there is an old peeled1887 * value that is already stored in it.1888 *1889 * It is OK to call this function with a packed reference entry that1890 * might be stale and might even refer to an object that has since1891 * been garbage-collected. In such a case, if the entry has1892 * REF_KNOWS_PEELED then leave the status unchanged and return1893 * PEEL_PEELED or PEEL_NON_TAG; otherwise, return PEEL_INVALID.1894 */1895static enum peel_status peel_entry(struct ref_entry *entry,int repeel)1896{1897enum peel_status status;18981899if(entry->flag & REF_KNOWS_PEELED) {1900if(repeel) {1901 entry->flag &= ~REF_KNOWS_PEELED;1902oidclr(&entry->u.value.peeled);1903}else{1904returnis_null_oid(&entry->u.value.peeled) ?1905 PEEL_NON_TAG : PEEL_PEELED;1906}1907}1908if(entry->flag & REF_ISBROKEN)1909return PEEL_BROKEN;1910if(entry->flag & REF_ISSYMREF)1911return PEEL_IS_SYMREF;19121913 status =peel_object(entry->u.value.oid.hash, entry->u.value.peeled.hash);1914if(status == PEEL_PEELED || status == PEEL_NON_TAG)1915 entry->flag |= REF_KNOWS_PEELED;1916return status;1917}19181919intpeel_ref(const char*refname,unsigned char*sha1)1920{1921int flag;1922unsigned char base[20];19231924if(current_ref && (current_ref->name == refname1925|| !strcmp(current_ref->name, refname))) {1926if(peel_entry(current_ref,0))1927return-1;1928hashcpy(sha1, current_ref->u.value.peeled.hash);1929return0;1930}19311932if(read_ref_full(refname, RESOLVE_REF_READING, base, &flag))1933return-1;19341935/*1936 * If the reference is packed, read its ref_entry from the1937 * cache in the hope that we already know its peeled value.1938 * We only try this optimization on packed references because1939 * (a) forcing the filling of the loose reference cache could1940 * be expensive and (b) loose references anyway usually do not1941 * have REF_KNOWS_PEELED.1942 */1943if(flag & REF_ISPACKED) {1944struct ref_entry *r =get_packed_ref(refname);1945if(r) {1946if(peel_entry(r,0))1947return-1;1948hashcpy(sha1, r->u.value.peeled.hash);1949return0;1950}1951}19521953returnpeel_object(base, sha1);1954}19551956struct warn_if_dangling_data {1957FILE*fp;1958const char*refname;1959const struct string_list *refnames;1960const char*msg_fmt;1961};19621963static intwarn_if_dangling_symref(const char*refname,const struct object_id *oid,1964int flags,void*cb_data)1965{1966struct warn_if_dangling_data *d = cb_data;1967const char*resolves_to;1968struct object_id junk;19691970if(!(flags & REF_ISSYMREF))1971return0;19721973 resolves_to =resolve_ref_unsafe(refname,0, junk.hash, NULL);1974if(!resolves_to1975|| (d->refname1976?strcmp(resolves_to, d->refname)1977: !string_list_has_string(d->refnames, resolves_to))) {1978return0;1979}19801981fprintf(d->fp, d->msg_fmt, refname);1982fputc('\n', d->fp);1983return0;1984}19851986voidwarn_dangling_symref(FILE*fp,const char*msg_fmt,const char*refname)1987{1988struct warn_if_dangling_data data;19891990 data.fp = fp;1991 data.refname = refname;1992 data.refnames = NULL;1993 data.msg_fmt = msg_fmt;1994for_each_rawref(warn_if_dangling_symref, &data);1995}19961997voidwarn_dangling_symrefs(FILE*fp,const char*msg_fmt,const struct string_list *refnames)1998{1999struct warn_if_dangling_data data;20002001 data.fp = fp;2002 data.refname = NULL;2003 data.refnames = refnames;2004 data.msg_fmt = msg_fmt;2005for_each_rawref(warn_if_dangling_symref, &data);2006}20072008/*2009 * Call fn for each reference in the specified ref_cache, omitting2010 * references not in the containing_dir of base. fn is called for all2011 * references, including broken ones. If fn ever returns a non-zero2012 * value, stop the iteration and return that value; otherwise, return2013 * 0.2014 */2015static intdo_for_each_entry(struct ref_cache *refs,const char*base,2016 each_ref_entry_fn fn,void*cb_data)2017{2018struct packed_ref_cache *packed_ref_cache;2019struct ref_dir *loose_dir;2020struct ref_dir *packed_dir;2021int retval =0;20222023/*2024 * We must make sure that all loose refs are read before accessing the2025 * packed-refs file; this avoids a race condition in which loose refs2026 * are migrated to the packed-refs file by a simultaneous process, but2027 * our in-memory view is from before the migration. get_packed_ref_cache()2028 * takes care of making sure our view is up to date with what is on2029 * disk.2030 */2031 loose_dir =get_loose_refs(refs);2032if(base && *base) {2033 loose_dir =find_containing_dir(loose_dir, base,0);2034}2035if(loose_dir)2036prime_ref_dir(loose_dir);20372038 packed_ref_cache =get_packed_ref_cache(refs);2039acquire_packed_ref_cache(packed_ref_cache);2040 packed_dir =get_packed_ref_dir(packed_ref_cache);2041if(base && *base) {2042 packed_dir =find_containing_dir(packed_dir, base,0);2043}20442045if(packed_dir && loose_dir) {2046sort_ref_dir(packed_dir);2047sort_ref_dir(loose_dir);2048 retval =do_for_each_entry_in_dirs(2049 packed_dir, loose_dir, fn, cb_data);2050}else if(packed_dir) {2051sort_ref_dir(packed_dir);2052 retval =do_for_each_entry_in_dir(2053 packed_dir,0, fn, cb_data);2054}else if(loose_dir) {2055sort_ref_dir(loose_dir);2056 retval =do_for_each_entry_in_dir(2057 loose_dir,0, fn, cb_data);2058}20592060release_packed_ref_cache(packed_ref_cache);2061return retval;2062}20632064/*2065 * Call fn for each reference in the specified ref_cache for which the2066 * refname begins with base. If trim is non-zero, then trim that many2067 * characters off the beginning of each refname before passing the2068 * refname to fn. flags can be DO_FOR_EACH_INCLUDE_BROKEN to include2069 * broken references in the iteration. If fn ever returns a non-zero2070 * value, stop the iteration and return that value; otherwise, return2071 * 0.2072 */2073static intdo_for_each_ref(struct ref_cache *refs,const char*base,2074 each_ref_fn fn,int trim,int flags,void*cb_data)2075{2076struct ref_entry_cb data;2077 data.base = base;2078 data.trim = trim;2079 data.flags = flags;2080 data.fn = fn;2081 data.cb_data = cb_data;20822083if(ref_paranoia <0)2084 ref_paranoia =git_env_bool("GIT_REF_PARANOIA",0);2085if(ref_paranoia)2086 data.flags |= DO_FOR_EACH_INCLUDE_BROKEN;20872088returndo_for_each_entry(refs, base, do_one_ref, &data);2089}20902091static intdo_head_ref(const char*submodule, each_ref_fn fn,void*cb_data)2092{2093struct object_id oid;2094int flag;20952096if(submodule) {2097if(resolve_gitlink_ref(submodule,"HEAD", oid.hash) ==0)2098returnfn("HEAD", &oid,0, cb_data);20992100return0;2101}21022103if(!read_ref_full("HEAD", RESOLVE_REF_READING, oid.hash, &flag))2104returnfn("HEAD", &oid, flag, cb_data);21052106return0;2107}21082109inthead_ref(each_ref_fn fn,void*cb_data)2110{2111returndo_head_ref(NULL, fn, cb_data);2112}21132114inthead_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2115{2116returndo_head_ref(submodule, fn, cb_data);2117}21182119intfor_each_ref(each_ref_fn fn,void*cb_data)2120{2121returndo_for_each_ref(&ref_cache,"", fn,0,0, cb_data);2122}21232124intfor_each_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2125{2126returndo_for_each_ref(get_ref_cache(submodule),"", fn,0,0, cb_data);2127}21282129intfor_each_ref_in(const char*prefix, each_ref_fn fn,void*cb_data)2130{2131returndo_for_each_ref(&ref_cache, prefix, fn,strlen(prefix),0, cb_data);2132}21332134intfor_each_ref_in_submodule(const char*submodule,const char*prefix,2135 each_ref_fn fn,void*cb_data)2136{2137returndo_for_each_ref(get_ref_cache(submodule), prefix, fn,strlen(prefix),0, cb_data);2138}21392140intfor_each_tag_ref(each_ref_fn fn,void*cb_data)2141{2142returnfor_each_ref_in("refs/tags/", fn, cb_data);2143}21442145intfor_each_tag_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2146{2147returnfor_each_ref_in_submodule(submodule,"refs/tags/", fn, cb_data);2148}21492150intfor_each_branch_ref(each_ref_fn fn,void*cb_data)2151{2152returnfor_each_ref_in("refs/heads/", fn, cb_data);2153}21542155intfor_each_branch_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2156{2157returnfor_each_ref_in_submodule(submodule,"refs/heads/", fn, cb_data);2158}21592160intfor_each_remote_ref(each_ref_fn fn,void*cb_data)2161{2162returnfor_each_ref_in("refs/remotes/", fn, cb_data);2163}21642165intfor_each_remote_ref_submodule(const char*submodule, each_ref_fn fn,void*cb_data)2166{2167returnfor_each_ref_in_submodule(submodule,"refs/remotes/", fn, cb_data);2168}21692170intfor_each_replace_ref(each_ref_fn fn,void*cb_data)2171{2172returndo_for_each_ref(&ref_cache, git_replace_ref_base, fn,2173strlen(git_replace_ref_base),0, cb_data);2174}21752176inthead_ref_namespaced(each_ref_fn fn,void*cb_data)2177{2178struct strbuf buf = STRBUF_INIT;2179int ret =0;2180struct object_id oid;2181int flag;21822183strbuf_addf(&buf,"%sHEAD",get_git_namespace());2184if(!read_ref_full(buf.buf, RESOLVE_REF_READING, oid.hash, &flag))2185 ret =fn(buf.buf, &oid, flag, cb_data);2186strbuf_release(&buf);21872188return ret;2189}21902191intfor_each_namespaced_ref(each_ref_fn fn,void*cb_data)2192{2193struct strbuf buf = STRBUF_INIT;2194int ret;2195strbuf_addf(&buf,"%srefs/",get_git_namespace());2196 ret =do_for_each_ref(&ref_cache, buf.buf, fn,0,0, cb_data);2197strbuf_release(&buf);2198return ret;2199}22002201intfor_each_glob_ref_in(each_ref_fn fn,const char*pattern,2202const char*prefix,void*cb_data)2203{2204struct strbuf real_pattern = STRBUF_INIT;2205struct ref_filter filter;2206int ret;22072208if(!prefix && !starts_with(pattern,"refs/"))2209strbuf_addstr(&real_pattern,"refs/");2210else if(prefix)2211strbuf_addstr(&real_pattern, prefix);2212strbuf_addstr(&real_pattern, pattern);22132214if(!has_glob_specials(pattern)) {2215/* Append implied '/' '*' if not present. */2216if(real_pattern.buf[real_pattern.len -1] !='/')2217strbuf_addch(&real_pattern,'/');2218/* No need to check for '*', there is none. */2219strbuf_addch(&real_pattern,'*');2220}22212222 filter.pattern = real_pattern.buf;2223 filter.fn = fn;2224 filter.cb_data = cb_data;2225 ret =for_each_ref(filter_refs, &filter);22262227strbuf_release(&real_pattern);2228return ret;2229}22302231intfor_each_glob_ref(each_ref_fn fn,const char*pattern,void*cb_data)2232{2233returnfor_each_glob_ref_in(fn, pattern, NULL, cb_data);2234}22352236intfor_each_rawref(each_ref_fn fn,void*cb_data)2237{2238returndo_for_each_ref(&ref_cache,"", fn,0,2239 DO_FOR_EACH_INCLUDE_BROKEN, cb_data);2240}22412242const char*prettify_refname(const char*name)2243{2244return name + (2245starts_with(name,"refs/heads/") ?11:2246starts_with(name,"refs/tags/") ?10:2247starts_with(name,"refs/remotes/") ?13:22480);2249}22502251static const char*ref_rev_parse_rules[] = {2252"%.*s",2253"refs/%.*s",2254"refs/tags/%.*s",2255"refs/heads/%.*s",2256"refs/remotes/%.*s",2257"refs/remotes/%.*s/HEAD",2258 NULL2259};22602261intrefname_match(const char*abbrev_name,const char*full_name)2262{2263const char**p;2264const int abbrev_name_len =strlen(abbrev_name);22652266for(p = ref_rev_parse_rules; *p; p++) {2267if(!strcmp(full_name,mkpath(*p, abbrev_name_len, abbrev_name))) {2268return1;2269}2270}22712272return0;2273}22742275static voidunlock_ref(struct ref_lock *lock)2276{2277/* Do not free lock->lk -- atexit() still looks at them */2278if(lock->lk)2279rollback_lock_file(lock->lk);2280free(lock->ref_name);2281free(lock->orig_ref_name);2282free(lock);2283}22842285/*2286 * Verify that the reference locked by lock has the value old_sha1.2287 * Fail if the reference doesn't exist and mustexist is set. Return 02288 * on success. On error, write an error message to err, set errno, and2289 * return a negative value.2290 */2291static intverify_lock(struct ref_lock *lock,2292const unsigned char*old_sha1,int mustexist,2293struct strbuf *err)2294{2295assert(err);22962297if(read_ref_full(lock->ref_name,2298 mustexist ? RESOLVE_REF_READING :0,2299 lock->old_oid.hash, NULL)) {2300int save_errno = errno;2301strbuf_addf(err,"can't verify ref%s", lock->ref_name);2302 errno = save_errno;2303return-1;2304}2305if(hashcmp(lock->old_oid.hash, old_sha1)) {2306strbuf_addf(err,"ref%sis at%sbut expected%s",2307 lock->ref_name,2308sha1_to_hex(lock->old_oid.hash),2309sha1_to_hex(old_sha1));2310 errno = EBUSY;2311return-1;2312}2313return0;2314}23152316static intremove_empty_directories(struct strbuf *path)2317{2318/*2319 * we want to create a file but there is a directory there;2320 * if that is an empty directory (or a directory that contains2321 * only empty directories), remove them.2322 */2323returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);2324}23252326/*2327 * *string and *len will only be substituted, and *string returned (for2328 * later free()ing) if the string passed in is a magic short-hand form2329 * to name a branch.2330 */2331static char*substitute_branch_name(const char**string,int*len)2332{2333struct strbuf buf = STRBUF_INIT;2334int ret =interpret_branch_name(*string, *len, &buf);23352336if(ret == *len) {2337size_t size;2338*string =strbuf_detach(&buf, &size);2339*len = size;2340return(char*)*string;2341}23422343return NULL;2344}23452346intdwim_ref(const char*str,int len,unsigned char*sha1,char**ref)2347{2348char*last_branch =substitute_branch_name(&str, &len);2349const char**p, *r;2350int refs_found =0;23512352*ref = NULL;2353for(p = ref_rev_parse_rules; *p; p++) {2354char fullref[PATH_MAX];2355unsigned char sha1_from_ref[20];2356unsigned char*this_result;2357int flag;23582359 this_result = refs_found ? sha1_from_ref : sha1;2360mksnpath(fullref,sizeof(fullref), *p, len, str);2361 r =resolve_ref_unsafe(fullref, RESOLVE_REF_READING,2362 this_result, &flag);2363if(r) {2364if(!refs_found++)2365*ref =xstrdup(r);2366if(!warn_ambiguous_refs)2367break;2368}else if((flag & REF_ISSYMREF) &&strcmp(fullref,"HEAD")) {2369warning("ignoring dangling symref%s.", fullref);2370}else if((flag & REF_ISBROKEN) &&strchr(fullref,'/')) {2371warning("ignoring broken ref%s.", fullref);2372}2373}2374free(last_branch);2375return refs_found;2376}23772378intdwim_log(const char*str,int len,unsigned char*sha1,char**log)2379{2380char*last_branch =substitute_branch_name(&str, &len);2381const char**p;2382int logs_found =0;23832384*log = NULL;2385for(p = ref_rev_parse_rules; *p; p++) {2386unsigned char hash[20];2387char path[PATH_MAX];2388const char*ref, *it;23892390mksnpath(path,sizeof(path), *p, len, str);2391 ref =resolve_ref_unsafe(path, RESOLVE_REF_READING,2392 hash, NULL);2393if(!ref)2394continue;2395if(reflog_exists(path))2396 it = path;2397else if(strcmp(ref, path) &&reflog_exists(ref))2398 it = ref;2399else2400continue;2401if(!logs_found++) {2402*log =xstrdup(it);2403hashcpy(sha1, hash);2404}2405if(!warn_ambiguous_refs)2406break;2407}2408free(last_branch);2409return logs_found;2410}24112412/*2413 * Locks a ref returning the lock on success and NULL on failure.2414 * On failure errno is set to something meaningful.2415 */2416static struct ref_lock *lock_ref_sha1_basic(const char*refname,2417const unsigned char*old_sha1,2418const struct string_list *extras,2419const struct string_list *skip,2420unsigned int flags,int*type_p,2421struct strbuf *err)2422{2423struct strbuf ref_file = STRBUF_INIT;2424struct strbuf orig_ref_file = STRBUF_INIT;2425const char*orig_refname = refname;2426struct ref_lock *lock;2427int last_errno =0;2428int type, lflags;2429int mustexist = (old_sha1 && !is_null_sha1(old_sha1));2430int resolve_flags =0;2431int attempts_remaining =3;24322433assert(err);24342435 lock =xcalloc(1,sizeof(struct ref_lock));24362437if(mustexist)2438 resolve_flags |= RESOLVE_REF_READING;2439if(flags & REF_DELETING) {2440 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;2441if(flags & REF_NODEREF)2442 resolve_flags |= RESOLVE_REF_NO_RECURSE;2443}24442445 refname =resolve_ref_unsafe(refname, resolve_flags,2446 lock->old_oid.hash, &type);2447if(!refname && errno == EISDIR) {2448/*2449 * we are trying to lock foo but we used to2450 * have foo/bar which now does not exist;2451 * it is normal for the empty directory 'foo'2452 * to remain.2453 */2454strbuf_git_path(&orig_ref_file,"%s", orig_refname);2455if(remove_empty_directories(&orig_ref_file)) {2456 last_errno = errno;2457if(!verify_refname_available(orig_refname, extras, skip,2458get_loose_refs(&ref_cache), err))2459strbuf_addf(err,"there are still refs under '%s'",2460 orig_refname);2461goto error_return;2462}2463 refname =resolve_ref_unsafe(orig_refname, resolve_flags,2464 lock->old_oid.hash, &type);2465}2466if(type_p)2467*type_p = type;2468if(!refname) {2469 last_errno = errno;2470if(last_errno != ENOTDIR ||2471!verify_refname_available(orig_refname, extras, skip,2472get_loose_refs(&ref_cache), err))2473strbuf_addf(err,"unable to resolve reference%s:%s",2474 orig_refname,strerror(last_errno));24752476goto error_return;2477}2478/*2479 * If the ref did not exist and we are creating it, make sure2480 * there is no existing packed ref whose name begins with our2481 * refname, nor a packed ref whose name is a proper prefix of2482 * our refname.2483 */2484if(is_null_oid(&lock->old_oid) &&2485verify_refname_available(refname, extras, skip,2486get_packed_refs(&ref_cache), err)) {2487 last_errno = ENOTDIR;2488goto error_return;2489}24902491 lock->lk =xcalloc(1,sizeof(struct lock_file));24922493 lflags =0;2494if(flags & REF_NODEREF) {2495 refname = orig_refname;2496 lflags |= LOCK_NO_DEREF;2497}2498 lock->ref_name =xstrdup(refname);2499 lock->orig_ref_name =xstrdup(orig_refname);2500strbuf_git_path(&ref_file,"%s", refname);25012502 retry:2503switch(safe_create_leading_directories_const(ref_file.buf)) {2504case SCLD_OK:2505break;/* success */2506case SCLD_VANISHED:2507if(--attempts_remaining >0)2508goto retry;2509/* fall through */2510default:2511 last_errno = errno;2512strbuf_addf(err,"unable to create directory for%s",2513 ref_file.buf);2514goto error_return;2515}25162517if(hold_lock_file_for_update(lock->lk, ref_file.buf, lflags) <0) {2518 last_errno = errno;2519if(errno == ENOENT && --attempts_remaining >0)2520/*2521 * Maybe somebody just deleted one of the2522 * directories leading to ref_file. Try2523 * again:2524 */2525goto retry;2526else{2527unable_to_lock_message(ref_file.buf, errno, err);2528goto error_return;2529}2530}2531if(old_sha1 &&verify_lock(lock, old_sha1, mustexist, err)) {2532 last_errno = errno;2533goto error_return;2534}2535goto out;25362537 error_return:2538unlock_ref(lock);2539 lock = NULL;25402541 out:2542strbuf_release(&ref_file);2543strbuf_release(&orig_ref_file);2544 errno = last_errno;2545return lock;2546}25472548/*2549 * Write an entry to the packed-refs file for the specified refname.2550 * If peeled is non-NULL, write it as the entry's peeled value.2551 */2552static voidwrite_packed_entry(FILE*fh,char*refname,unsigned char*sha1,2553unsigned char*peeled)2554{2555fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);2556if(peeled)2557fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));2558}25592560/*2561 * An each_ref_entry_fn that writes the entry to a packed-refs file.2562 */2563static intwrite_packed_entry_fn(struct ref_entry *entry,void*cb_data)2564{2565enum peel_status peel_status =peel_entry(entry,0);25662567if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2568error("internal error:%sis not a valid packed reference!",2569 entry->name);2570write_packed_entry(cb_data, entry->name, entry->u.value.oid.hash,2571 peel_status == PEEL_PEELED ?2572 entry->u.value.peeled.hash : NULL);2573return0;2574}25752576/*2577 * Lock the packed-refs file for writing. Flags is passed to2578 * hold_lock_file_for_update(). Return 0 on success. On errors, set2579 * errno appropriately and return a nonzero value.2580 */2581static intlock_packed_refs(int flags)2582{2583static int timeout_configured =0;2584static int timeout_value =1000;25852586struct packed_ref_cache *packed_ref_cache;25872588if(!timeout_configured) {2589git_config_get_int("core.packedrefstimeout", &timeout_value);2590 timeout_configured =1;2591}25922593if(hold_lock_file_for_update_timeout(2594&packlock,git_path("packed-refs"),2595 flags, timeout_value) <0)2596return-1;2597/*2598 * Get the current packed-refs while holding the lock. If the2599 * packed-refs file has been modified since we last read it,2600 * this will automatically invalidate the cache and re-read2601 * the packed-refs file.2602 */2603 packed_ref_cache =get_packed_ref_cache(&ref_cache);2604 packed_ref_cache->lock = &packlock;2605/* Increment the reference count to prevent it from being freed: */2606acquire_packed_ref_cache(packed_ref_cache);2607return0;2608}26092610/*2611 * Write the current version of the packed refs cache from memory to2612 * disk. The packed-refs file must already be locked for writing (see2613 * lock_packed_refs()). Return zero on success. On errors, set errno2614 * and return a nonzero value2615 */2616static intcommit_packed_refs(void)2617{2618struct packed_ref_cache *packed_ref_cache =2619get_packed_ref_cache(&ref_cache);2620int error =0;2621int save_errno =0;2622FILE*out;26232624if(!packed_ref_cache->lock)2625die("internal error: packed-refs not locked");26262627 out =fdopen_lock_file(packed_ref_cache->lock,"w");2628if(!out)2629die_errno("unable to fdopen packed-refs descriptor");26302631fprintf_or_die(out,"%s", PACKED_REFS_HEADER);2632do_for_each_entry_in_dir(get_packed_ref_dir(packed_ref_cache),26330, write_packed_entry_fn, out);26342635if(commit_lock_file(packed_ref_cache->lock)) {2636 save_errno = errno;2637 error = -1;2638}2639 packed_ref_cache->lock = NULL;2640release_packed_ref_cache(packed_ref_cache);2641 errno = save_errno;2642return error;2643}26442645/*2646 * Rollback the lockfile for the packed-refs file, and discard the2647 * in-memory packed reference cache. (The packed-refs file will be2648 * read anew if it is needed again after this function is called.)2649 */2650static voidrollback_packed_refs(void)2651{2652struct packed_ref_cache *packed_ref_cache =2653get_packed_ref_cache(&ref_cache);26542655if(!packed_ref_cache->lock)2656die("internal error: packed-refs not locked");2657rollback_lock_file(packed_ref_cache->lock);2658 packed_ref_cache->lock = NULL;2659release_packed_ref_cache(packed_ref_cache);2660clear_packed_ref_cache(&ref_cache);2661}26622663struct ref_to_prune {2664struct ref_to_prune *next;2665unsigned char sha1[20];2666char name[FLEX_ARRAY];2667};26682669struct pack_refs_cb_data {2670unsigned int flags;2671struct ref_dir *packed_refs;2672struct ref_to_prune *ref_to_prune;2673};26742675static intis_per_worktree_ref(const char*refname);26762677/*2678 * An each_ref_entry_fn that is run over loose references only. If2679 * the loose reference can be packed, add an entry in the packed ref2680 * cache. If the reference should be pruned, also add it to2681 * ref_to_prune in the pack_refs_cb_data.2682 */2683static intpack_if_possible_fn(struct ref_entry *entry,void*cb_data)2684{2685struct pack_refs_cb_data *cb = cb_data;2686enum peel_status peel_status;2687struct ref_entry *packed_entry;2688int is_tag_ref =starts_with(entry->name,"refs/tags/");26892690/* Do not pack per-worktree refs: */2691if(is_per_worktree_ref(entry->name))2692return0;26932694/* ALWAYS pack tags */2695if(!(cb->flags & PACK_REFS_ALL) && !is_tag_ref)2696return0;26972698/* Do not pack symbolic or broken refs: */2699if((entry->flag & REF_ISSYMREF) || !ref_resolves_to_object(entry))2700return0;27012702/* Add a packed ref cache entry equivalent to the loose entry. */2703 peel_status =peel_entry(entry,1);2704if(peel_status != PEEL_PEELED && peel_status != PEEL_NON_TAG)2705die("internal error peeling reference%s(%s)",2706 entry->name,oid_to_hex(&entry->u.value.oid));2707 packed_entry =find_ref(cb->packed_refs, entry->name);2708if(packed_entry) {2709/* Overwrite existing packed entry with info from loose entry */2710 packed_entry->flag = REF_ISPACKED | REF_KNOWS_PEELED;2711oidcpy(&packed_entry->u.value.oid, &entry->u.value.oid);2712}else{2713 packed_entry =create_ref_entry(entry->name, entry->u.value.oid.hash,2714 REF_ISPACKED | REF_KNOWS_PEELED,0);2715add_ref(cb->packed_refs, packed_entry);2716}2717oidcpy(&packed_entry->u.value.peeled, &entry->u.value.peeled);27182719/* Schedule the loose reference for pruning if requested. */2720if((cb->flags & PACK_REFS_PRUNE)) {2721int namelen =strlen(entry->name) +1;2722struct ref_to_prune *n =xcalloc(1,sizeof(*n) + namelen);2723hashcpy(n->sha1, entry->u.value.oid.hash);2724strcpy(n->name, entry->name);2725 n->next = cb->ref_to_prune;2726 cb->ref_to_prune = n;2727}2728return0;2729}27302731/*2732 * Remove empty parents, but spare refs/ and immediate subdirs.2733 * Note: munges *name.2734 */2735static voidtry_remove_empty_parents(char*name)2736{2737char*p, *q;2738int i;2739 p = name;2740for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */2741while(*p && *p !='/')2742 p++;2743/* tolerate duplicate slashes; see check_refname_format() */2744while(*p =='/')2745 p++;2746}2747for(q = p; *q; q++)2748;2749while(1) {2750while(q > p && *q !='/')2751 q--;2752while(q > p && *(q-1) =='/')2753 q--;2754if(q == p)2755break;2756*q ='\0';2757if(rmdir(git_path("%s", name)))2758break;2759}2760}27612762/* make sure nobody touched the ref, and unlink */2763static voidprune_ref(struct ref_to_prune *r)2764{2765struct ref_transaction *transaction;2766struct strbuf err = STRBUF_INIT;27672768if(check_refname_format(r->name,0))2769return;27702771 transaction =ref_transaction_begin(&err);2772if(!transaction ||2773ref_transaction_delete(transaction, r->name, r->sha1,2774 REF_ISPRUNING, NULL, &err) ||2775ref_transaction_commit(transaction, &err)) {2776ref_transaction_free(transaction);2777error("%s", err.buf);2778strbuf_release(&err);2779return;2780}2781ref_transaction_free(transaction);2782strbuf_release(&err);2783try_remove_empty_parents(r->name);2784}27852786static voidprune_refs(struct ref_to_prune *r)2787{2788while(r) {2789prune_ref(r);2790 r = r->next;2791}2792}27932794intpack_refs(unsigned int flags)2795{2796struct pack_refs_cb_data cbdata;27972798memset(&cbdata,0,sizeof(cbdata));2799 cbdata.flags = flags;28002801lock_packed_refs(LOCK_DIE_ON_ERROR);2802 cbdata.packed_refs =get_packed_refs(&ref_cache);28032804do_for_each_entry_in_dir(get_loose_refs(&ref_cache),0,2805 pack_if_possible_fn, &cbdata);28062807if(commit_packed_refs())2808die_errno("unable to overwrite old ref-pack file");28092810prune_refs(cbdata.ref_to_prune);2811return0;2812}28132814/*2815 * Rewrite the packed-refs file, omitting any refs listed in2816 * 'refnames'. On error, leave packed-refs unchanged, write an error2817 * message to 'err', and return a nonzero value.2818 *2819 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.2820 */2821static intrepack_without_refs(struct string_list *refnames,struct strbuf *err)2822{2823struct ref_dir *packed;2824struct string_list_item *refname;2825int ret, needs_repacking =0, removed =0;28262827assert(err);28282829/* Look for a packed ref */2830for_each_string_list_item(refname, refnames) {2831if(get_packed_ref(refname->string)) {2832 needs_repacking =1;2833break;2834}2835}28362837/* Avoid locking if we have nothing to do */2838if(!needs_repacking)2839return0;/* no refname exists in packed refs */28402841if(lock_packed_refs(0)) {2842unable_to_lock_message(git_path("packed-refs"), errno, err);2843return-1;2844}2845 packed =get_packed_refs(&ref_cache);28462847/* Remove refnames from the cache */2848for_each_string_list_item(refname, refnames)2849if(remove_entry(packed, refname->string) != -1)2850 removed =1;2851if(!removed) {2852/*2853 * All packed entries disappeared while we were2854 * acquiring the lock.2855 */2856rollback_packed_refs();2857return0;2858}28592860/* Write what remains */2861 ret =commit_packed_refs();2862if(ret)2863strbuf_addf(err,"unable to overwrite old ref-pack file:%s",2864strerror(errno));2865return ret;2866}28672868static intdelete_ref_loose(struct ref_lock *lock,int flag,struct strbuf *err)2869{2870assert(err);28712872if(!(flag & REF_ISPACKED) || flag & REF_ISSYMREF) {2873/*2874 * loose. The loose file name is the same as the2875 * lockfile name, minus ".lock":2876 */2877char*loose_filename =get_locked_file_path(lock->lk);2878int res =unlink_or_msg(loose_filename, err);2879free(loose_filename);2880if(res)2881return1;2882}2883return0;2884}28852886static intis_per_worktree_ref(const char*refname)2887{2888return!strcmp(refname,"HEAD") ||2889starts_with(refname,"refs/bisect/");2890}28912892static intis_pseudoref_syntax(const char*refname)2893{2894const char*c;28952896for(c = refname; *c; c++) {2897if(!isupper(*c) && *c !='-'&& *c !='_')2898return0;2899}29002901return1;2902}29032904enum ref_type ref_type(const char*refname)2905{2906if(is_per_worktree_ref(refname))2907return REF_TYPE_PER_WORKTREE;2908if(is_pseudoref_syntax(refname))2909return REF_TYPE_PSEUDOREF;2910return REF_TYPE_NORMAL;2911}29122913static intwrite_pseudoref(const char*pseudoref,const unsigned char*sha1,2914const unsigned char*old_sha1,struct strbuf *err)2915{2916const char*filename;2917int fd;2918static struct lock_file lock;2919struct strbuf buf = STRBUF_INIT;2920int ret = -1;29212922strbuf_addf(&buf,"%s\n",sha1_to_hex(sha1));29232924 filename =git_path("%s", pseudoref);2925 fd =hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);2926if(fd <0) {2927strbuf_addf(err,"Could not open '%s' for writing:%s",2928 filename,strerror(errno));2929return-1;2930}29312932if(old_sha1) {2933unsigned char actual_old_sha1[20];29342935if(read_ref(pseudoref, actual_old_sha1))2936die("could not read ref '%s'", pseudoref);2937if(hashcmp(actual_old_sha1, old_sha1)) {2938strbuf_addf(err,"Unexpected sha1 when writing%s", pseudoref);2939rollback_lock_file(&lock);2940goto done;2941}2942}29432944if(write_in_full(fd, buf.buf, buf.len) != buf.len) {2945strbuf_addf(err,"Could not write to '%s'", filename);2946rollback_lock_file(&lock);2947goto done;2948}29492950commit_lock_file(&lock);2951 ret =0;2952done:2953strbuf_release(&buf);2954return ret;2955}29562957static intdelete_pseudoref(const char*pseudoref,const unsigned char*old_sha1)2958{2959static struct lock_file lock;2960const char*filename;29612962 filename =git_path("%s", pseudoref);29632964if(old_sha1 && !is_null_sha1(old_sha1)) {2965int fd;2966unsigned char actual_old_sha1[20];29672968 fd =hold_lock_file_for_update(&lock, filename,2969 LOCK_DIE_ON_ERROR);2970if(fd <0)2971die_errno(_("Could not open '%s' for writing"), filename);2972if(read_ref(pseudoref, actual_old_sha1))2973die("could not read ref '%s'", pseudoref);2974if(hashcmp(actual_old_sha1, old_sha1)) {2975warning("Unexpected sha1 when deleting%s", pseudoref);2976rollback_lock_file(&lock);2977return-1;2978}29792980unlink(filename);2981rollback_lock_file(&lock);2982}else{2983unlink(filename);2984}29852986return0;2987}29882989intdelete_ref(const char*refname,const unsigned char*old_sha1,2990unsigned int flags)2991{2992struct ref_transaction *transaction;2993struct strbuf err = STRBUF_INIT;29942995if(ref_type(refname) == REF_TYPE_PSEUDOREF)2996returndelete_pseudoref(refname, old_sha1);29972998 transaction =ref_transaction_begin(&err);2999if(!transaction ||3000ref_transaction_delete(transaction, refname, old_sha1,3001 flags, NULL, &err) ||3002ref_transaction_commit(transaction, &err)) {3003error("%s", err.buf);3004ref_transaction_free(transaction);3005strbuf_release(&err);3006return1;3007}3008ref_transaction_free(transaction);3009strbuf_release(&err);3010return0;3011}30123013intdelete_refs(struct string_list *refnames)3014{3015struct strbuf err = STRBUF_INIT;3016int i, result =0;30173018if(!refnames->nr)3019return0;30203021 result =repack_without_refs(refnames, &err);3022if(result) {3023/*3024 * If we failed to rewrite the packed-refs file, then3025 * it is unsafe to try to remove loose refs, because3026 * doing so might expose an obsolete packed value for3027 * a reference that might even point at an object that3028 * has been garbage collected.3029 */3030if(refnames->nr ==1)3031error(_("could not delete reference%s:%s"),3032 refnames->items[0].string, err.buf);3033else3034error(_("could not delete references:%s"), err.buf);30353036goto out;3037}30383039for(i =0; i < refnames->nr; i++) {3040const char*refname = refnames->items[i].string;30413042if(delete_ref(refname, NULL,0))3043 result |=error(_("could not remove reference%s"), refname);3044}30453046out:3047strbuf_release(&err);3048return result;3049}30503051/*3052 * People using contrib's git-new-workdir have .git/logs/refs ->3053 * /some/other/path/.git/logs/refs, and that may live on another device.3054 *3055 * IOW, to avoid cross device rename errors, the temporary renamed log must3056 * live into logs/refs.3057 */3058#define TMP_RENAMED_LOG"logs/refs/.tmp-renamed-log"30593060static intrename_tmp_log(const char*newrefname)3061{3062int attempts_remaining =4;3063struct strbuf path = STRBUF_INIT;3064int ret = -1;30653066 retry:3067strbuf_reset(&path);3068strbuf_git_path(&path,"logs/%s", newrefname);3069switch(safe_create_leading_directories_const(path.buf)) {3070case SCLD_OK:3071break;/* success */3072case SCLD_VANISHED:3073if(--attempts_remaining >0)3074goto retry;3075/* fall through */3076default:3077error("unable to create directory for%s", newrefname);3078goto out;3079}30803081if(rename(git_path(TMP_RENAMED_LOG), path.buf)) {3082if((errno==EISDIR || errno==ENOTDIR) && --attempts_remaining >0) {3083/*3084 * rename(a, b) when b is an existing3085 * directory ought to result in ISDIR, but3086 * Solaris 5.8 gives ENOTDIR. Sheesh.3087 */3088if(remove_empty_directories(&path)) {3089error("Directory not empty: logs/%s", newrefname);3090goto out;3091}3092goto retry;3093}else if(errno == ENOENT && --attempts_remaining >0) {3094/*3095 * Maybe another process just deleted one of3096 * the directories in the path to newrefname.3097 * Try again from the beginning.3098 */3099goto retry;3100}else{3101error("unable to move logfile "TMP_RENAMED_LOG" to logs/%s:%s",3102 newrefname,strerror(errno));3103goto out;3104}3105}3106 ret =0;3107out:3108strbuf_release(&path);3109return ret;3110}31113112static intrename_ref_available(const char*oldname,const char*newname)3113{3114struct string_list skip = STRING_LIST_INIT_NODUP;3115struct strbuf err = STRBUF_INIT;3116int ret;31173118string_list_insert(&skip, oldname);3119 ret = !verify_refname_available(newname, NULL, &skip,3120get_packed_refs(&ref_cache), &err)3121&& !verify_refname_available(newname, NULL, &skip,3122get_loose_refs(&ref_cache), &err);3123if(!ret)3124error("%s", err.buf);31253126string_list_clear(&skip,0);3127strbuf_release(&err);3128return ret;3129}31303131static intwrite_ref_to_lockfile(struct ref_lock *lock,3132const unsigned char*sha1,struct strbuf *err);3133static intcommit_ref_update(struct ref_lock *lock,3134const unsigned char*sha1,const char*logmsg,3135int flags,struct strbuf *err);31363137intrename_ref(const char*oldrefname,const char*newrefname,const char*logmsg)3138{3139unsigned char sha1[20], orig_sha1[20];3140int flag =0, logmoved =0;3141struct ref_lock *lock;3142struct stat loginfo;3143int log = !lstat(git_path("logs/%s", oldrefname), &loginfo);3144const char*symref = NULL;3145struct strbuf err = STRBUF_INIT;31463147if(log &&S_ISLNK(loginfo.st_mode))3148returnerror("reflog for%sis a symlink", oldrefname);31493150 symref =resolve_ref_unsafe(oldrefname, RESOLVE_REF_READING,3151 orig_sha1, &flag);3152if(flag & REF_ISSYMREF)3153returnerror("refname%sis a symbolic ref, renaming it is not supported",3154 oldrefname);3155if(!symref)3156returnerror("refname%snot found", oldrefname);31573158if(!rename_ref_available(oldrefname, newrefname))3159return1;31603161if(log &&rename(git_path("logs/%s", oldrefname),git_path(TMP_RENAMED_LOG)))3162returnerror("unable to move logfile logs/%sto "TMP_RENAMED_LOG":%s",3163 oldrefname,strerror(errno));31643165if(delete_ref(oldrefname, orig_sha1, REF_NODEREF)) {3166error("unable to delete old%s", oldrefname);3167goto rollback;3168}31693170if(!read_ref_full(newrefname, RESOLVE_REF_READING, sha1, NULL) &&3171delete_ref(newrefname, sha1, REF_NODEREF)) {3172if(errno==EISDIR) {3173struct strbuf path = STRBUF_INIT;3174int result;31753176strbuf_git_path(&path,"%s", newrefname);3177 result =remove_empty_directories(&path);3178strbuf_release(&path);31793180if(result) {3181error("Directory not empty:%s", newrefname);3182goto rollback;3183}3184}else{3185error("unable to delete existing%s", newrefname);3186goto rollback;3187}3188}31893190if(log &&rename_tmp_log(newrefname))3191goto rollback;31923193 logmoved = log;31943195 lock =lock_ref_sha1_basic(newrefname, NULL, NULL, NULL,0, NULL, &err);3196if(!lock) {3197error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);3198strbuf_release(&err);3199goto rollback;3200}3201hashcpy(lock->old_oid.hash, orig_sha1);32023203if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3204commit_ref_update(lock, orig_sha1, logmsg,0, &err)) {3205error("unable to write current sha1 into%s:%s", newrefname, err.buf);3206strbuf_release(&err);3207goto rollback;3208}32093210return0;32113212 rollback:3213 lock =lock_ref_sha1_basic(oldrefname, NULL, NULL, NULL,0, NULL, &err);3214if(!lock) {3215error("unable to lock%sfor rollback:%s", oldrefname, err.buf);3216strbuf_release(&err);3217goto rollbacklog;3218}32193220 flag = log_all_ref_updates;3221 log_all_ref_updates =0;3222if(write_ref_to_lockfile(lock, orig_sha1, &err) ||3223commit_ref_update(lock, orig_sha1, NULL,0, &err)) {3224error("unable to write current sha1 into%s:%s", oldrefname, err.buf);3225strbuf_release(&err);3226}3227 log_all_ref_updates = flag;32283229 rollbacklog:3230if(logmoved &&rename(git_path("logs/%s", newrefname),git_path("logs/%s", oldrefname)))3231error("unable to restore logfile%sfrom%s:%s",3232 oldrefname, newrefname,strerror(errno));3233if(!logmoved && log &&3234rename(git_path(TMP_RENAMED_LOG),git_path("logs/%s", oldrefname)))3235error("unable to restore logfile%sfrom "TMP_RENAMED_LOG":%s",3236 oldrefname,strerror(errno));32373238return1;3239}32403241static intclose_ref(struct ref_lock *lock)3242{3243if(close_lock_file(lock->lk))3244return-1;3245return0;3246}32473248static intcommit_ref(struct ref_lock *lock)3249{3250if(commit_lock_file(lock->lk))3251return-1;3252return0;3253}32543255/*3256 * copy the reflog message msg to buf, which has been allocated sufficiently3257 * large, while cleaning up the whitespaces. Especially, convert LF to space,3258 * because reflog file is one line per entry.3259 */3260static intcopy_msg(char*buf,const char*msg)3261{3262char*cp = buf;3263char c;3264int wasspace =1;32653266*cp++ ='\t';3267while((c = *msg++)) {3268if(wasspace &&isspace(c))3269continue;3270 wasspace =isspace(c);3271if(wasspace)3272 c =' ';3273*cp++ = c;3274}3275while(buf < cp &&isspace(cp[-1]))3276 cp--;3277*cp++ ='\n';3278return cp - buf;3279}32803281static intshould_autocreate_reflog(const char*refname)3282{3283if(!log_all_ref_updates)3284return0;3285returnstarts_with(refname,"refs/heads/") ||3286starts_with(refname,"refs/remotes/") ||3287starts_with(refname,"refs/notes/") ||3288!strcmp(refname,"HEAD");3289}32903291/*3292 * Create a reflog for a ref. If force_create = 0, the reflog will3293 * only be created for certain refs (those for which3294 * should_autocreate_reflog returns non-zero. Otherwise, create it3295 * regardless of the ref name. Fill in *err and return -1 on failure.3296 */3297static intlog_ref_setup(const char*refname,struct strbuf *logfile,struct strbuf *err,int force_create)3298{3299int logfd, oflags = O_APPEND | O_WRONLY;33003301strbuf_git_path(logfile,"logs/%s", refname);3302if(force_create ||should_autocreate_reflog(refname)) {3303if(safe_create_leading_directories(logfile->buf) <0) {3304strbuf_addf(err,"unable to create directory for%s: "3305"%s", logfile->buf,strerror(errno));3306return-1;3307}3308 oflags |= O_CREAT;3309}33103311 logfd =open(logfile->buf, oflags,0666);3312if(logfd <0) {3313if(!(oflags & O_CREAT) && (errno == ENOENT || errno == EISDIR))3314return0;33153316if(errno == EISDIR) {3317if(remove_empty_directories(logfile)) {3318strbuf_addf(err,"There are still logs under "3319"'%s'", logfile->buf);3320return-1;3321}3322 logfd =open(logfile->buf, oflags,0666);3323}33243325if(logfd <0) {3326strbuf_addf(err,"unable to append to%s:%s",3327 logfile->buf,strerror(errno));3328return-1;3329}3330}33313332adjust_shared_perm(logfile->buf);3333close(logfd);3334return0;3335}333633373338intsafe_create_reflog(const char*refname,int force_create,struct strbuf *err)3339{3340int ret;3341struct strbuf sb = STRBUF_INIT;33423343 ret =log_ref_setup(refname, &sb, err, force_create);3344strbuf_release(&sb);3345return ret;3346}33473348static intlog_ref_write_fd(int fd,const unsigned char*old_sha1,3349const unsigned char*new_sha1,3350const char*committer,const char*msg)3351{3352int msglen, written;3353unsigned maxlen, len;3354char*logrec;33553356 msglen = msg ?strlen(msg) :0;3357 maxlen =strlen(committer) + msglen +100;3358 logrec =xmalloc(maxlen);3359 len =sprintf(logrec,"%s %s %s\n",3360sha1_to_hex(old_sha1),3361sha1_to_hex(new_sha1),3362 committer);3363if(msglen)3364 len +=copy_msg(logrec + len -1, msg) -1;33653366 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;3367free(logrec);3368if(written != len)3369return-1;33703371return0;3372}33733374static intlog_ref_write_1(const char*refname,const unsigned char*old_sha1,3375const unsigned char*new_sha1,const char*msg,3376struct strbuf *logfile,int flags,3377struct strbuf *err)3378{3379int logfd, result, oflags = O_APPEND | O_WRONLY;33803381if(log_all_ref_updates <0)3382 log_all_ref_updates = !is_bare_repository();33833384 result =log_ref_setup(refname, logfile, err, flags & REF_FORCE_CREATE_REFLOG);33853386if(result)3387return result;33883389 logfd =open(logfile->buf, oflags);3390if(logfd <0)3391return0;3392 result =log_ref_write_fd(logfd, old_sha1, new_sha1,3393git_committer_info(0), msg);3394if(result) {3395strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3396strerror(errno));3397close(logfd);3398return-1;3399}3400if(close(logfd)) {3401strbuf_addf(err,"unable to append to%s:%s", logfile->buf,3402strerror(errno));3403return-1;3404}3405return0;3406}34073408static intlog_ref_write(const char*refname,const unsigned char*old_sha1,3409const unsigned char*new_sha1,const char*msg,3410int flags,struct strbuf *err)3411{3412struct strbuf sb = STRBUF_INIT;3413int ret =log_ref_write_1(refname, old_sha1, new_sha1, msg, &sb, flags,3414 err);3415strbuf_release(&sb);3416return ret;3417}34183419intis_branch(const char*refname)3420{3421return!strcmp(refname,"HEAD") ||starts_with(refname,"refs/heads/");3422}34233424/*3425 * Write sha1 into the open lockfile, then close the lockfile. On3426 * errors, rollback the lockfile, fill in *err and3427 * return -1.3428 */3429static intwrite_ref_to_lockfile(struct ref_lock *lock,3430const unsigned char*sha1,struct strbuf *err)3431{3432static char term ='\n';3433struct object *o;3434int fd;34353436 o =parse_object(sha1);3437if(!o) {3438strbuf_addf(err,3439"Trying to write ref%swith nonexistent object%s",3440 lock->ref_name,sha1_to_hex(sha1));3441unlock_ref(lock);3442return-1;3443}3444if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {3445strbuf_addf(err,3446"Trying to write non-commit object%sto branch%s",3447sha1_to_hex(sha1), lock->ref_name);3448unlock_ref(lock);3449return-1;3450}3451 fd =get_lock_file_fd(lock->lk);3452if(write_in_full(fd,sha1_to_hex(sha1),40) !=40||3453write_in_full(fd, &term,1) !=1||3454close_ref(lock) <0) {3455strbuf_addf(err,3456"Couldn't write%s",get_lock_file_path(lock->lk));3457unlock_ref(lock);3458return-1;3459}3460return0;3461}34623463/*3464 * Commit a change to a loose reference that has already been written3465 * to the loose reference lockfile. Also update the reflogs if3466 * necessary, using the specified lockmsg (which can be NULL).3467 */3468static intcommit_ref_update(struct ref_lock *lock,3469const unsigned char*sha1,const char*logmsg,3470int flags,struct strbuf *err)3471{3472clear_loose_ref_cache(&ref_cache);3473if(log_ref_write(lock->ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0||3474(strcmp(lock->ref_name, lock->orig_ref_name) &&3475log_ref_write(lock->orig_ref_name, lock->old_oid.hash, sha1, logmsg, flags, err) <0)) {3476char*old_msg =strbuf_detach(err, NULL);3477strbuf_addf(err,"Cannot update the ref '%s':%s",3478 lock->ref_name, old_msg);3479free(old_msg);3480unlock_ref(lock);3481return-1;3482}3483if(strcmp(lock->orig_ref_name,"HEAD") !=0) {3484/*3485 * Special hack: If a branch is updated directly and HEAD3486 * points to it (may happen on the remote side of a push3487 * for example) then logically the HEAD reflog should be3488 * updated too.3489 * A generic solution implies reverse symref information,3490 * but finding all symrefs pointing to the given branch3491 * would be rather costly for this rare event (the direct3492 * update of a branch) to be worth it. So let's cheat and3493 * check with HEAD only which should cover 99% of all usage3494 * scenarios (even 100% of the default ones).3495 */3496unsigned char head_sha1[20];3497int head_flag;3498const char*head_ref;3499 head_ref =resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,3500 head_sha1, &head_flag);3501if(head_ref && (head_flag & REF_ISSYMREF) &&3502!strcmp(head_ref, lock->ref_name)) {3503struct strbuf log_err = STRBUF_INIT;3504if(log_ref_write("HEAD", lock->old_oid.hash, sha1,3505 logmsg,0, &log_err)) {3506error("%s", log_err.buf);3507strbuf_release(&log_err);3508}3509}3510}3511if(commit_ref(lock)) {3512error("Couldn't set%s", lock->ref_name);3513unlock_ref(lock);3514return-1;3515}35163517unlock_ref(lock);3518return0;3519}35203521intcreate_symref(const char*ref_target,const char*refs_heads_master,3522const char*logmsg)3523{3524char*lockpath = NULL;3525char ref[1000];3526int fd, len, written;3527char*git_HEAD =git_pathdup("%s", ref_target);3528unsigned char old_sha1[20], new_sha1[20];3529struct strbuf err = STRBUF_INIT;35303531if(logmsg &&read_ref(ref_target, old_sha1))3532hashclr(old_sha1);35333534if(safe_create_leading_directories(git_HEAD) <0)3535returnerror("unable to create directory for%s", git_HEAD);35363537#ifndef NO_SYMLINK_HEAD3538if(prefer_symlink_refs) {3539unlink(git_HEAD);3540if(!symlink(refs_heads_master, git_HEAD))3541goto done;3542fprintf(stderr,"no symlink - falling back to symbolic ref\n");3543}3544#endif35453546 len =snprintf(ref,sizeof(ref),"ref:%s\n", refs_heads_master);3547if(sizeof(ref) <= len) {3548error("refname too long:%s", refs_heads_master);3549goto error_free_return;3550}3551 lockpath =mkpathdup("%s.lock", git_HEAD);3552 fd =open(lockpath, O_CREAT | O_EXCL | O_WRONLY,0666);3553if(fd <0) {3554error("Unable to open%sfor writing", lockpath);3555goto error_free_return;3556}3557 written =write_in_full(fd, ref, len);3558if(close(fd) !=0|| written != len) {3559error("Unable to write to%s", lockpath);3560goto error_unlink_return;3561}3562if(rename(lockpath, git_HEAD) <0) {3563error("Unable to create%s", git_HEAD);3564goto error_unlink_return;3565}3566if(adjust_shared_perm(git_HEAD)) {3567error("Unable to fix permissions on%s", lockpath);3568 error_unlink_return:3569unlink_or_warn(lockpath);3570 error_free_return:3571free(lockpath);3572free(git_HEAD);3573return-1;3574}3575free(lockpath);35763577#ifndef NO_SYMLINK_HEAD3578 done:3579#endif3580if(logmsg && !read_ref(refs_heads_master, new_sha1) &&3581log_ref_write(ref_target, old_sha1, new_sha1, logmsg,0, &err)) {3582error("%s", err.buf);3583strbuf_release(&err);3584}35853586free(git_HEAD);3587return0;3588}35893590struct read_ref_at_cb {3591const char*refname;3592unsigned long at_time;3593int cnt;3594int reccnt;3595unsigned char*sha1;3596int found_it;35973598unsigned char osha1[20];3599unsigned char nsha1[20];3600int tz;3601unsigned long date;3602char**msg;3603unsigned long*cutoff_time;3604int*cutoff_tz;3605int*cutoff_cnt;3606};36073608static intread_ref_at_ent(unsigned char*osha1,unsigned char*nsha1,3609const char*email,unsigned long timestamp,int tz,3610const char*message,void*cb_data)3611{3612struct read_ref_at_cb *cb = cb_data;36133614 cb->reccnt++;3615 cb->tz = tz;3616 cb->date = timestamp;36173618if(timestamp <= cb->at_time || cb->cnt ==0) {3619if(cb->msg)3620*cb->msg =xstrdup(message);3621if(cb->cutoff_time)3622*cb->cutoff_time = timestamp;3623if(cb->cutoff_tz)3624*cb->cutoff_tz = tz;3625if(cb->cutoff_cnt)3626*cb->cutoff_cnt = cb->reccnt -1;3627/*3628 * we have not yet updated cb->[n|o]sha1 so they still3629 * hold the values for the previous record.3630 */3631if(!is_null_sha1(cb->osha1)) {3632hashcpy(cb->sha1, nsha1);3633if(hashcmp(cb->osha1, nsha1))3634warning("Log for ref%shas gap after%s.",3635 cb->refname,show_date(cb->date, cb->tz,DATE_MODE(RFC2822)));3636}3637else if(cb->date == cb->at_time)3638hashcpy(cb->sha1, nsha1);3639else if(hashcmp(nsha1, cb->sha1))3640warning("Log for ref%sunexpectedly ended on%s.",3641 cb->refname,show_date(cb->date, cb->tz,3642DATE_MODE(RFC2822)));3643hashcpy(cb->osha1, osha1);3644hashcpy(cb->nsha1, nsha1);3645 cb->found_it =1;3646return1;3647}3648hashcpy(cb->osha1, osha1);3649hashcpy(cb->nsha1, nsha1);3650if(cb->cnt >0)3651 cb->cnt--;3652return0;3653}36543655static intread_ref_at_ent_oldest(unsigned char*osha1,unsigned char*nsha1,3656const char*email,unsigned long timestamp,3657int tz,const char*message,void*cb_data)3658{3659struct read_ref_at_cb *cb = cb_data;36603661if(cb->msg)3662*cb->msg =xstrdup(message);3663if(cb->cutoff_time)3664*cb->cutoff_time = timestamp;3665if(cb->cutoff_tz)3666*cb->cutoff_tz = tz;3667if(cb->cutoff_cnt)3668*cb->cutoff_cnt = cb->reccnt;3669hashcpy(cb->sha1, osha1);3670if(is_null_sha1(cb->sha1))3671hashcpy(cb->sha1, nsha1);3672/* We just want the first entry */3673return1;3674}36753676intread_ref_at(const char*refname,unsigned int flags,unsigned long at_time,int cnt,3677unsigned char*sha1,char**msg,3678unsigned long*cutoff_time,int*cutoff_tz,int*cutoff_cnt)3679{3680struct read_ref_at_cb cb;36813682memset(&cb,0,sizeof(cb));3683 cb.refname = refname;3684 cb.at_time = at_time;3685 cb.cnt = cnt;3686 cb.msg = msg;3687 cb.cutoff_time = cutoff_time;3688 cb.cutoff_tz = cutoff_tz;3689 cb.cutoff_cnt = cutoff_cnt;3690 cb.sha1 = sha1;36913692for_each_reflog_ent_reverse(refname, read_ref_at_ent, &cb);36933694if(!cb.reccnt) {3695if(flags & GET_SHA1_QUIETLY)3696exit(128);3697else3698die("Log for%sis empty.", refname);3699}3700if(cb.found_it)3701return0;37023703for_each_reflog_ent(refname, read_ref_at_ent_oldest, &cb);37043705return1;3706}37073708intreflog_exists(const char*refname)3709{3710struct stat st;37113712return!lstat(git_path("logs/%s", refname), &st) &&3713S_ISREG(st.st_mode);3714}37153716intdelete_reflog(const char*refname)3717{3718returnremove_path(git_path("logs/%s", refname));3719}37203721static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)3722{3723unsigned char osha1[20], nsha1[20];3724char*email_end, *message;3725unsigned long timestamp;3726int tz;37273728/* old SP new SP name <email> SP time TAB msg LF */3729if(sb->len <83|| sb->buf[sb->len -1] !='\n'||3730get_sha1_hex(sb->buf, osha1) || sb->buf[40] !=' '||3731get_sha1_hex(sb->buf +41, nsha1) || sb->buf[81] !=' '||3732!(email_end =strchr(sb->buf +82,'>')) ||3733 email_end[1] !=' '||3734!(timestamp =strtoul(email_end +2, &message,10)) ||3735!message || message[0] !=' '||3736(message[1] !='+'&& message[1] !='-') ||3737!isdigit(message[2]) || !isdigit(message[3]) ||3738!isdigit(message[4]) || !isdigit(message[5]))3739return0;/* corrupt? */3740 email_end[1] ='\0';3741 tz =strtol(message +1, NULL,10);3742if(message[6] !='\t')3743 message +=6;3744else3745 message +=7;3746returnfn(osha1, nsha1, sb->buf +82, timestamp, tz, message, cb_data);3747}37483749static char*find_beginning_of_line(char*bob,char*scan)3750{3751while(bob < scan && *(--scan) !='\n')3752;/* keep scanning backwards */3753/*3754 * Return either beginning of the buffer, or LF at the end of3755 * the previous line.3756 */3757return scan;3758}37593760intfor_each_reflog_ent_reverse(const char*refname, each_reflog_ent_fn fn,void*cb_data)3761{3762struct strbuf sb = STRBUF_INIT;3763FILE*logfp;3764long pos;3765int ret =0, at_tail =1;37663767 logfp =fopen(git_path("logs/%s", refname),"r");3768if(!logfp)3769return-1;37703771/* Jump to the end */3772if(fseek(logfp,0, SEEK_END) <0)3773returnerror("cannot seek back reflog for%s:%s",3774 refname,strerror(errno));3775 pos =ftell(logfp);3776while(!ret &&0< pos) {3777int cnt;3778size_t nread;3779char buf[BUFSIZ];3780char*endp, *scanp;37813782/* Fill next block from the end */3783 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;3784if(fseek(logfp, pos - cnt, SEEK_SET))3785returnerror("cannot seek back reflog for%s:%s",3786 refname,strerror(errno));3787 nread =fread(buf, cnt,1, logfp);3788if(nread !=1)3789returnerror("cannot read%dbytes from reflog for%s:%s",3790 cnt, refname,strerror(errno));3791 pos -= cnt;37923793 scanp = endp = buf + cnt;3794if(at_tail && scanp[-1] =='\n')3795/* Looking at the final LF at the end of the file */3796 scanp--;3797 at_tail =0;37983799while(buf < scanp) {3800/*3801 * terminating LF of the previous line, or the beginning3802 * of the buffer.3803 */3804char*bp;38053806 bp =find_beginning_of_line(buf, scanp);38073808if(*bp =='\n') {3809/*3810 * The newline is the end of the previous line,3811 * so we know we have complete line starting3812 * at (bp + 1). Prefix it onto any prior data3813 * we collected for the line and process it.3814 */3815strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));3816 scanp = bp;3817 endp = bp +1;3818 ret =show_one_reflog_ent(&sb, fn, cb_data);3819strbuf_reset(&sb);3820if(ret)3821break;3822}else if(!pos) {3823/*3824 * We are at the start of the buffer, and the3825 * start of the file; there is no previous3826 * line, and we have everything for this one.3827 * Process it, and we can end the loop.3828 */3829strbuf_splice(&sb,0,0, buf, endp - buf);3830 ret =show_one_reflog_ent(&sb, fn, cb_data);3831strbuf_reset(&sb);3832break;3833}38343835if(bp == buf) {3836/*3837 * We are at the start of the buffer, and there3838 * is more file to read backwards. Which means3839 * we are in the middle of a line. Note that we3840 * may get here even if *bp was a newline; that3841 * just means we are at the exact end of the3842 * previous line, rather than some spot in the3843 * middle.3844 *3845 * Save away what we have to be combined with3846 * the data from the next read.3847 */3848strbuf_splice(&sb,0,0, buf, endp - buf);3849break;3850}3851}38523853}3854if(!ret && sb.len)3855die("BUG: reverse reflog parser had leftover data");38563857fclose(logfp);3858strbuf_release(&sb);3859return ret;3860}38613862intfor_each_reflog_ent(const char*refname, each_reflog_ent_fn fn,void*cb_data)3863{3864FILE*logfp;3865struct strbuf sb = STRBUF_INIT;3866int ret =0;38673868 logfp =fopen(git_path("logs/%s", refname),"r");3869if(!logfp)3870return-1;38713872while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))3873 ret =show_one_reflog_ent(&sb, fn, cb_data);3874fclose(logfp);3875strbuf_release(&sb);3876return ret;3877}3878/*3879 * Call fn for each reflog in the namespace indicated by name. name3880 * must be empty or end with '/'. Name will be used as a scratch3881 * space, but its contents will be restored before return.3882 */3883static intdo_for_each_reflog(struct strbuf *name, each_ref_fn fn,void*cb_data)3884{3885DIR*d =opendir(git_path("logs/%s", name->buf));3886int retval =0;3887struct dirent *de;3888int oldlen = name->len;38893890if(!d)3891return name->len ? errno :0;38923893while((de =readdir(d)) != NULL) {3894struct stat st;38953896if(de->d_name[0] =='.')3897continue;3898if(ends_with(de->d_name,".lock"))3899continue;3900strbuf_addstr(name, de->d_name);3901if(stat(git_path("logs/%s", name->buf), &st) <0) {3902;/* silently ignore */3903}else{3904if(S_ISDIR(st.st_mode)) {3905strbuf_addch(name,'/');3906 retval =do_for_each_reflog(name, fn, cb_data);3907}else{3908struct object_id oid;39093910if(read_ref_full(name->buf,0, oid.hash, NULL))3911 retval =error("bad ref for%s", name->buf);3912else3913 retval =fn(name->buf, &oid,0, cb_data);3914}3915if(retval)3916break;3917}3918strbuf_setlen(name, oldlen);3919}3920closedir(d);3921return retval;3922}39233924intfor_each_reflog(each_ref_fn fn,void*cb_data)3925{3926int retval;3927struct strbuf name;3928strbuf_init(&name, PATH_MAX);3929 retval =do_for_each_reflog(&name, fn, cb_data);3930strbuf_release(&name);3931return retval;3932}39333934/**3935 * Information needed for a single ref update. Set new_sha1 to the new3936 * value or to null_sha1 to delete the ref. To check the old value3937 * while the ref is locked, set (flags & REF_HAVE_OLD) and set3938 * old_sha1 to the old value, or to null_sha1 to ensure the ref does3939 * not exist before update.3940 */3941struct ref_update {3942/*3943 * If (flags & REF_HAVE_NEW), set the reference to this value:3944 */3945unsigned char new_sha1[20];3946/*3947 * If (flags & REF_HAVE_OLD), check that the reference3948 * previously had this value:3949 */3950unsigned char old_sha1[20];3951/*3952 * One or more of REF_HAVE_NEW, REF_HAVE_OLD, REF_NODEREF,3953 * REF_DELETING, and REF_ISPRUNING:3954 */3955unsigned int flags;3956struct ref_lock *lock;3957int type;3958char*msg;3959const char refname[FLEX_ARRAY];3960};39613962/*3963 * Transaction states.3964 * OPEN: The transaction is in a valid state and can accept new updates.3965 * An OPEN transaction can be committed.3966 * CLOSED: A closed transaction is no longer active and no other operations3967 * than free can be used on it in this state.3968 * A transaction can either become closed by successfully committing3969 * an active transaction or if there is a failure while building3970 * the transaction thus rendering it failed/inactive.3971 */3972enum ref_transaction_state {3973 REF_TRANSACTION_OPEN =0,3974 REF_TRANSACTION_CLOSED =13975};39763977/*3978 * Data structure for holding a reference transaction, which can3979 * consist of checks and updates to multiple references, carried out3980 * as atomically as possible. This structure is opaque to callers.3981 */3982struct ref_transaction {3983struct ref_update **updates;3984size_t alloc;3985size_t nr;3986enum ref_transaction_state state;3987};39883989struct ref_transaction *ref_transaction_begin(struct strbuf *err)3990{3991assert(err);39923993returnxcalloc(1,sizeof(struct ref_transaction));3994}39953996voidref_transaction_free(struct ref_transaction *transaction)3997{3998int i;39994000if(!transaction)4001return;40024003for(i =0; i < transaction->nr; i++) {4004free(transaction->updates[i]->msg);4005free(transaction->updates[i]);4006}4007free(transaction->updates);4008free(transaction);4009}40104011static struct ref_update *add_update(struct ref_transaction *transaction,4012const char*refname)4013{4014size_t len =strlen(refname);4015struct ref_update *update =xcalloc(1,sizeof(*update) + len +1);40164017strcpy((char*)update->refname, refname);4018ALLOC_GROW(transaction->updates, transaction->nr +1, transaction->alloc);4019 transaction->updates[transaction->nr++] = update;4020return update;4021}40224023intref_transaction_update(struct ref_transaction *transaction,4024const char*refname,4025const unsigned char*new_sha1,4026const unsigned char*old_sha1,4027unsigned int flags,const char*msg,4028struct strbuf *err)4029{4030struct ref_update *update;40314032assert(err);40334034if(transaction->state != REF_TRANSACTION_OPEN)4035die("BUG: update called for transaction that is not open");40364037if(new_sha1 && !is_null_sha1(new_sha1) &&4038check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) {4039strbuf_addf(err,"refusing to update ref with bad name%s",4040 refname);4041return-1;4042}40434044 update =add_update(transaction, refname);4045if(new_sha1) {4046hashcpy(update->new_sha1, new_sha1);4047 flags |= REF_HAVE_NEW;4048}4049if(old_sha1) {4050hashcpy(update->old_sha1, old_sha1);4051 flags |= REF_HAVE_OLD;4052}4053 update->flags = flags;4054if(msg)4055 update->msg =xstrdup(msg);4056return0;4057}40584059intref_transaction_create(struct ref_transaction *transaction,4060const char*refname,4061const unsigned char*new_sha1,4062unsigned int flags,const char*msg,4063struct strbuf *err)4064{4065if(!new_sha1 ||is_null_sha1(new_sha1))4066die("BUG: create called without valid new_sha1");4067returnref_transaction_update(transaction, refname, new_sha1,4068 null_sha1, flags, msg, err);4069}40704071intref_transaction_delete(struct ref_transaction *transaction,4072const char*refname,4073const unsigned char*old_sha1,4074unsigned int flags,const char*msg,4075struct strbuf *err)4076{4077if(old_sha1 &&is_null_sha1(old_sha1))4078die("BUG: delete called with old_sha1 set to zeros");4079returnref_transaction_update(transaction, refname,4080 null_sha1, old_sha1,4081 flags, msg, err);4082}40834084intref_transaction_verify(struct ref_transaction *transaction,4085const char*refname,4086const unsigned char*old_sha1,4087unsigned int flags,4088struct strbuf *err)4089{4090if(!old_sha1)4091die("BUG: verify called with old_sha1 set to NULL");4092returnref_transaction_update(transaction, refname,4093 NULL, old_sha1,4094 flags, NULL, err);4095}40964097intupdate_ref(const char*msg,const char*refname,4098const unsigned char*new_sha1,const unsigned char*old_sha1,4099unsigned int flags,enum action_on_err onerr)4100{4101struct ref_transaction *t = NULL;4102struct strbuf err = STRBUF_INIT;4103int ret =0;41044105if(ref_type(refname) == REF_TYPE_PSEUDOREF) {4106 ret =write_pseudoref(refname, new_sha1, old_sha1, &err);4107}else{4108 t =ref_transaction_begin(&err);4109if(!t ||4110ref_transaction_update(t, refname, new_sha1, old_sha1,4111 flags, msg, &err) ||4112ref_transaction_commit(t, &err)) {4113 ret =1;4114ref_transaction_free(t);4115}4116}4117if(ret) {4118const char*str ="update_ref failed for ref '%s':%s";41194120switch(onerr) {4121case UPDATE_REFS_MSG_ON_ERR:4122error(str, refname, err.buf);4123break;4124case UPDATE_REFS_DIE_ON_ERR:4125die(str, refname, err.buf);4126break;4127case UPDATE_REFS_QUIET_ON_ERR:4128break;4129}4130strbuf_release(&err);4131return1;4132}4133strbuf_release(&err);4134if(t)4135ref_transaction_free(t);4136return0;4137}41384139static intref_update_reject_duplicates(struct string_list *refnames,4140struct strbuf *err)4141{4142int i, n = refnames->nr;41434144assert(err);41454146for(i =1; i < n; i++)4147if(!strcmp(refnames->items[i -1].string, refnames->items[i].string)) {4148strbuf_addf(err,4149"Multiple updates for ref '%s' not allowed.",4150 refnames->items[i].string);4151return1;4152}4153return0;4154}41554156intref_transaction_commit(struct ref_transaction *transaction,4157struct strbuf *err)4158{4159int ret =0, i;4160int n = transaction->nr;4161struct ref_update **updates = transaction->updates;4162struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;4163struct string_list_item *ref_to_delete;4164struct string_list affected_refnames = STRING_LIST_INIT_NODUP;41654166assert(err);41674168if(transaction->state != REF_TRANSACTION_OPEN)4169die("BUG: commit called for transaction that is not open");41704171if(!n) {4172 transaction->state = REF_TRANSACTION_CLOSED;4173return0;4174}41754176/* Fail if a refname appears more than once in the transaction: */4177for(i =0; i < n; i++)4178string_list_append(&affected_refnames, updates[i]->refname);4179string_list_sort(&affected_refnames);4180if(ref_update_reject_duplicates(&affected_refnames, err)) {4181 ret = TRANSACTION_GENERIC_ERROR;4182goto cleanup;4183}41844185/*4186 * Acquire all locks, verify old values if provided, check4187 * that new values are valid, and write new values to the4188 * lockfiles, ready to be activated. Only keep one lockfile4189 * open at a time to avoid running out of file descriptors.4190 */4191for(i =0; i < n; i++) {4192struct ref_update *update = updates[i];41934194if((update->flags & REF_HAVE_NEW) &&4195is_null_sha1(update->new_sha1))4196 update->flags |= REF_DELETING;4197 update->lock =lock_ref_sha1_basic(4198 update->refname,4199((update->flags & REF_HAVE_OLD) ?4200 update->old_sha1 : NULL),4201&affected_refnames, NULL,4202 update->flags,4203&update->type,4204 err);4205if(!update->lock) {4206char*reason;42074208 ret = (errno == ENOTDIR)4209? TRANSACTION_NAME_CONFLICT4210: TRANSACTION_GENERIC_ERROR;4211 reason =strbuf_detach(err, NULL);4212strbuf_addf(err,"cannot lock ref '%s':%s",4213 update->refname, reason);4214free(reason);4215goto cleanup;4216}4217if((update->flags & REF_HAVE_NEW) &&4218!(update->flags & REF_DELETING)) {4219int overwriting_symref = ((update->type & REF_ISSYMREF) &&4220(update->flags & REF_NODEREF));42214222if(!overwriting_symref &&4223!hashcmp(update->lock->old_oid.hash, update->new_sha1)) {4224/*4225 * The reference already has the desired4226 * value, so we don't need to write it.4227 */4228}else if(write_ref_to_lockfile(update->lock,4229 update->new_sha1,4230 err)) {4231char*write_err =strbuf_detach(err, NULL);42324233/*4234 * The lock was freed upon failure of4235 * write_ref_to_lockfile():4236 */4237 update->lock = NULL;4238strbuf_addf(err,4239"cannot update the ref '%s':%s",4240 update->refname, write_err);4241free(write_err);4242 ret = TRANSACTION_GENERIC_ERROR;4243goto cleanup;4244}else{4245 update->flags |= REF_NEEDS_COMMIT;4246}4247}4248if(!(update->flags & REF_NEEDS_COMMIT)) {4249/*4250 * We didn't have to write anything to the lockfile.4251 * Close it to free up the file descriptor:4252 */4253if(close_ref(update->lock)) {4254strbuf_addf(err,"Couldn't close%s.lock",4255 update->refname);4256goto cleanup;4257}4258}4259}42604261/* Perform updates first so live commits remain referenced */4262for(i =0; i < n; i++) {4263struct ref_update *update = updates[i];42644265if(update->flags & REF_NEEDS_COMMIT) {4266if(commit_ref_update(update->lock,4267 update->new_sha1, update->msg,4268 update->flags, err)) {4269/* freed by commit_ref_update(): */4270 update->lock = NULL;4271 ret = TRANSACTION_GENERIC_ERROR;4272goto cleanup;4273}else{4274/* freed by commit_ref_update(): */4275 update->lock = NULL;4276}4277}4278}42794280/* Perform deletes now that updates are safely completed */4281for(i =0; i < n; i++) {4282struct ref_update *update = updates[i];42834284if(update->flags & REF_DELETING) {4285if(delete_ref_loose(update->lock, update->type, err)) {4286 ret = TRANSACTION_GENERIC_ERROR;4287goto cleanup;4288}42894290if(!(update->flags & REF_ISPRUNING))4291string_list_append(&refs_to_delete,4292 update->lock->ref_name);4293}4294}42954296if(repack_without_refs(&refs_to_delete, err)) {4297 ret = TRANSACTION_GENERIC_ERROR;4298goto cleanup;4299}4300for_each_string_list_item(ref_to_delete, &refs_to_delete)4301unlink_or_warn(git_path("logs/%s", ref_to_delete->string));4302clear_loose_ref_cache(&ref_cache);43034304cleanup:4305 transaction->state = REF_TRANSACTION_CLOSED;43064307for(i =0; i < n; i++)4308if(updates[i]->lock)4309unlock_ref(updates[i]->lock);4310string_list_clear(&refs_to_delete,0);4311string_list_clear(&affected_refnames,0);4312return ret;4313}43144315static intref_present(const char*refname,4316const struct object_id *oid,int flags,void*cb_data)4317{4318struct string_list *affected_refnames = cb_data;43194320returnstring_list_has_string(affected_refnames, refname);4321}43224323intinitial_ref_transaction_commit(struct ref_transaction *transaction,4324struct strbuf *err)4325{4326struct ref_dir *loose_refs =get_loose_refs(&ref_cache);4327struct ref_dir *packed_refs =get_packed_refs(&ref_cache);4328int ret =0, i;4329int n = transaction->nr;4330struct ref_update **updates = transaction->updates;4331struct string_list affected_refnames = STRING_LIST_INIT_NODUP;43324333assert(err);43344335if(transaction->state != REF_TRANSACTION_OPEN)4336die("BUG: commit called for transaction that is not open");43374338/* Fail if a refname appears more than once in the transaction: */4339for(i =0; i < n; i++)4340string_list_append(&affected_refnames, updates[i]->refname);4341string_list_sort(&affected_refnames);4342if(ref_update_reject_duplicates(&affected_refnames, err)) {4343 ret = TRANSACTION_GENERIC_ERROR;4344goto cleanup;4345}43464347/*4348 * It's really undefined to call this function in an active4349 * repository or when there are existing references: we are4350 * only locking and changing packed-refs, so (1) any4351 * simultaneous processes might try to change a reference at4352 * the same time we do, and (2) any existing loose versions of4353 * the references that we are setting would have precedence4354 * over our values. But some remote helpers create the remote4355 * "HEAD" and "master" branches before calling this function,4356 * so here we really only check that none of the references4357 * that we are creating already exists.4358 */4359if(for_each_rawref(ref_present, &affected_refnames))4360die("BUG: initial ref transaction called with existing refs");43614362for(i =0; i < n; i++) {4363struct ref_update *update = updates[i];43644365if((update->flags & REF_HAVE_OLD) &&4366!is_null_sha1(update->old_sha1))4367die("BUG: initial ref transaction with old_sha1 set");4368if(verify_refname_available(update->refname,4369&affected_refnames, NULL,4370 loose_refs, err) ||4371verify_refname_available(update->refname,4372&affected_refnames, NULL,4373 packed_refs, err)) {4374 ret = TRANSACTION_NAME_CONFLICT;4375goto cleanup;4376}4377}43784379if(lock_packed_refs(0)) {4380strbuf_addf(err,"unable to lock packed-refs file:%s",4381strerror(errno));4382 ret = TRANSACTION_GENERIC_ERROR;4383goto cleanup;4384}43854386for(i =0; i < n; i++) {4387struct ref_update *update = updates[i];43884389if((update->flags & REF_HAVE_NEW) &&4390!is_null_sha1(update->new_sha1))4391add_packed_ref(update->refname, update->new_sha1);4392}43934394if(commit_packed_refs()) {4395strbuf_addf(err,"unable to commit packed-refs file:%s",4396strerror(errno));4397 ret = TRANSACTION_GENERIC_ERROR;4398goto cleanup;4399}44004401cleanup:4402 transaction->state = REF_TRANSACTION_CLOSED;4403string_list_clear(&affected_refnames,0);4404return ret;4405}44064407char*shorten_unambiguous_ref(const char*refname,int strict)4408{4409int i;4410static char**scanf_fmts;4411static int nr_rules;4412char*short_name;44134414if(!nr_rules) {4415/*4416 * Pre-generate scanf formats from ref_rev_parse_rules[].4417 * Generate a format suitable for scanf from a4418 * ref_rev_parse_rules rule by interpolating "%s" at the4419 * location of the "%.*s".4420 */4421size_t total_len =0;4422size_t offset =0;44234424/* the rule list is NULL terminated, count them first */4425for(nr_rules =0; ref_rev_parse_rules[nr_rules]; nr_rules++)4426/* -2 for strlen("%.*s") - strlen("%s"); +1 for NUL */4427 total_len +=strlen(ref_rev_parse_rules[nr_rules]) -2+1;44284429 scanf_fmts =xmalloc(nr_rules *sizeof(char*) + total_len);44304431 offset =0;4432for(i =0; i < nr_rules; i++) {4433assert(offset < total_len);4434 scanf_fmts[i] = (char*)&scanf_fmts[nr_rules] + offset;4435 offset +=snprintf(scanf_fmts[i], total_len - offset,4436 ref_rev_parse_rules[i],2,"%s") +1;4437}4438}44394440/* bail out if there are no rules */4441if(!nr_rules)4442returnxstrdup(refname);44434444/* buffer for scanf result, at most refname must fit */4445 short_name =xstrdup(refname);44464447/* skip first rule, it will always match */4448for(i = nr_rules -1; i >0; --i) {4449int j;4450int rules_to_fail = i;4451int short_name_len;44524453if(1!=sscanf(refname, scanf_fmts[i], short_name))4454continue;44554456 short_name_len =strlen(short_name);44574458/*4459 * in strict mode, all (except the matched one) rules4460 * must fail to resolve to a valid non-ambiguous ref4461 */4462if(strict)4463 rules_to_fail = nr_rules;44644465/*4466 * check if the short name resolves to a valid ref,4467 * but use only rules prior to the matched one4468 */4469for(j =0; j < rules_to_fail; j++) {4470const char*rule = ref_rev_parse_rules[j];4471char refname[PATH_MAX];44724473/* skip matched rule */4474if(i == j)4475continue;44764477/*4478 * the short name is ambiguous, if it resolves4479 * (with this previous rule) to a valid ref4480 * read_ref() returns 0 on success4481 */4482mksnpath(refname,sizeof(refname),4483 rule, short_name_len, short_name);4484if(ref_exists(refname))4485break;4486}44874488/*4489 * short name is non-ambiguous if all previous rules4490 * haven't resolved to a valid ref4491 */4492if(j == rules_to_fail)4493return short_name;4494}44954496free(short_name);4497returnxstrdup(refname);4498}44994500static struct string_list *hide_refs;45014502intparse_hide_refs_config(const char*var,const char*value,const char*section)4503{4504if(!strcmp("transfer.hiderefs", var) ||4505/* NEEDSWORK: use parse_config_key() once both are merged */4506(starts_with(var, section) && var[strlen(section)] =='.'&&4507!strcmp(var +strlen(section),".hiderefs"))) {4508char*ref;4509int len;45104511if(!value)4512returnconfig_error_nonbool(var);4513 ref =xstrdup(value);4514 len =strlen(ref);4515while(len && ref[len -1] =='/')4516 ref[--len] ='\0';4517if(!hide_refs) {4518 hide_refs =xcalloc(1,sizeof(*hide_refs));4519 hide_refs->strdup_strings =1;4520}4521string_list_append(hide_refs, ref);4522}4523return0;4524}45254526intref_is_hidden(const char*refname)4527{4528int i;45294530if(!hide_refs)4531return0;4532for(i = hide_refs->nr -1; i >=0; i--) {4533const char*match = hide_refs->items[i].string;4534int neg =0;4535int len;45364537if(*match =='!') {4538 neg =1;4539 match++;4540}45414542if(!starts_with(refname, match))4543continue;4544 len =strlen(match);4545if(!refname[len] || refname[len] =='/')4546return!neg;4547}4548return0;4549}45504551struct expire_reflog_cb {4552unsigned int flags;4553 reflog_expiry_should_prune_fn *should_prune_fn;4554void*policy_cb;4555FILE*newlog;4556unsigned char last_kept_sha1[20];4557};45584559static intexpire_reflog_ent(unsigned char*osha1,unsigned char*nsha1,4560const char*email,unsigned long timestamp,int tz,4561const char*message,void*cb_data)4562{4563struct expire_reflog_cb *cb = cb_data;4564struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;45654566if(cb->flags & EXPIRE_REFLOGS_REWRITE)4567 osha1 = cb->last_kept_sha1;45684569if((*cb->should_prune_fn)(osha1, nsha1, email, timestamp, tz,4570 message, policy_cb)) {4571if(!cb->newlog)4572printf("would prune%s", message);4573else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4574printf("prune%s", message);4575}else{4576if(cb->newlog) {4577fprintf(cb->newlog,"%s %s %s %lu %+05d\t%s",4578sha1_to_hex(osha1),sha1_to_hex(nsha1),4579 email, timestamp, tz, message);4580hashcpy(cb->last_kept_sha1, nsha1);4581}4582if(cb->flags & EXPIRE_REFLOGS_VERBOSE)4583printf("keep%s", message);4584}4585return0;4586}45874588intreflog_expire(const char*refname,const unsigned char*sha1,4589unsigned int flags,4590 reflog_expiry_prepare_fn prepare_fn,4591 reflog_expiry_should_prune_fn should_prune_fn,4592 reflog_expiry_cleanup_fn cleanup_fn,4593void*policy_cb_data)4594{4595static struct lock_file reflog_lock;4596struct expire_reflog_cb cb;4597struct ref_lock *lock;4598char*log_file;4599int status =0;4600int type;4601struct strbuf err = STRBUF_INIT;46024603memset(&cb,0,sizeof(cb));4604 cb.flags = flags;4605 cb.policy_cb = policy_cb_data;4606 cb.should_prune_fn = should_prune_fn;46074608/*4609 * The reflog file is locked by holding the lock on the4610 * reference itself, plus we might need to update the4611 * reference if --updateref was specified:4612 */4613 lock =lock_ref_sha1_basic(refname, sha1, NULL, NULL,0, &type, &err);4614if(!lock) {4615error("cannot lock ref '%s':%s", refname, err.buf);4616strbuf_release(&err);4617return-1;4618}4619if(!reflog_exists(refname)) {4620unlock_ref(lock);4621return0;4622}46234624 log_file =git_pathdup("logs/%s", refname);4625if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4626/*4627 * Even though holding $GIT_DIR/logs/$reflog.lock has4628 * no locking implications, we use the lock_file4629 * machinery here anyway because it does a lot of the4630 * work we need, including cleaning up if the program4631 * exits unexpectedly.4632 */4633if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {4634struct strbuf err = STRBUF_INIT;4635unable_to_lock_message(log_file, errno, &err);4636error("%s", err.buf);4637strbuf_release(&err);4638goto failure;4639}4640 cb.newlog =fdopen_lock_file(&reflog_lock,"w");4641if(!cb.newlog) {4642error("cannot fdopen%s(%s)",4643get_lock_file_path(&reflog_lock),strerror(errno));4644goto failure;4645}4646}46474648(*prepare_fn)(refname, sha1, cb.policy_cb);4649for_each_reflog_ent(refname, expire_reflog_ent, &cb);4650(*cleanup_fn)(cb.policy_cb);46514652if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {4653/*4654 * It doesn't make sense to adjust a reference pointed4655 * to by a symbolic ref based on expiring entries in4656 * the symbolic reference's reflog. Nor can we update4657 * a reference if there are no remaining reflog4658 * entries.4659 */4660int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&4661!(type & REF_ISSYMREF) &&4662!is_null_sha1(cb.last_kept_sha1);46634664if(close_lock_file(&reflog_lock)) {4665 status |=error("couldn't write%s:%s", log_file,4666strerror(errno));4667}else if(update &&4668(write_in_full(get_lock_file_fd(lock->lk),4669sha1_to_hex(cb.last_kept_sha1),40) !=40||4670write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||4671close_ref(lock) <0)) {4672 status |=error("couldn't write%s",4673get_lock_file_path(lock->lk));4674rollback_lock_file(&reflog_lock);4675}else if(commit_lock_file(&reflog_lock)) {4676 status |=error("unable to commit reflog '%s' (%s)",4677 log_file,strerror(errno));4678}else if(update &&commit_ref(lock)) {4679 status |=error("couldn't set%s", lock->ref_name);4680}4681}4682free(log_file);4683unlock_ref(lock);4684return status;46854686 failure:4687rollback_lock_file(&reflog_lock);4688free(log_file);4689unlock_ref(lock);4690return-1;4691}