1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"ref-cache.h" 5#include"../iterator.h" 6#include"../dir-iterator.h" 7#include"../lockfile.h" 8#include"../object.h" 9#include"../dir.h" 10 11struct ref_lock { 12char*ref_name; 13struct lock_file *lk; 14struct object_id old_oid; 15}; 16 17/* 18 * Return true if refname, which has the specified oid and flags, can 19 * be resolved to an object in the database. If the referred-to object 20 * does not exist, emit a warning and return false. 21 */ 22static intref_resolves_to_object(const char*refname, 23const struct object_id *oid, 24unsigned int flags) 25{ 26if(flags & REF_ISBROKEN) 27return0; 28if(!has_sha1_file(oid->hash)) { 29error("%sdoes not point to a valid object!", refname); 30return0; 31} 32return1; 33} 34 35struct packed_ref_cache { 36struct ref_cache *cache; 37 38/* 39 * Count of references to the data structure in this instance, 40 * including the pointer from files_ref_store::packed if any. 41 * The data will not be freed as long as the reference count 42 * is nonzero. 43 */ 44unsigned int referrers; 45 46/* The metadata from when this packed-refs cache was read */ 47struct stat_validity validity; 48}; 49 50/* 51 * A container for `packed-refs`-related data. It is not (yet) a 52 * `ref_store`. 53 */ 54struct packed_ref_store { 55unsigned int store_flags; 56 57/* The path of the "packed-refs" file: */ 58char*path; 59 60/* 61 * A cache of the values read from the `packed-refs` file, if 62 * it might still be current; otherwise, NULL. 63 */ 64struct packed_ref_cache *cache; 65 66/* 67 * Lock used for the "packed-refs" file. Note that this (and 68 * thus the enclosing `packed_ref_store`) must not be freed. 69 */ 70struct lock_file lock; 71}; 72 73static struct packed_ref_store *packed_ref_store_create( 74const char*path,unsigned int store_flags) 75{ 76struct packed_ref_store *refs =xcalloc(1,sizeof(*refs)); 77 78 refs->store_flags = store_flags; 79 refs->path =xstrdup(path); 80return refs; 81} 82 83/* 84 * Future: need to be in "struct repository" 85 * when doing a full libification. 86 */ 87struct files_ref_store { 88struct ref_store base; 89unsigned int store_flags; 90 91char*gitdir; 92char*gitcommondir; 93 94struct ref_cache *loose; 95 96struct packed_ref_store *packed_ref_store; 97}; 98 99/* 100 * Increment the reference count of *packed_refs. 101 */ 102static voidacquire_packed_ref_cache(struct packed_ref_cache *packed_refs) 103{ 104 packed_refs->referrers++; 105} 106 107/* 108 * Decrease the reference count of *packed_refs. If it goes to zero, 109 * free *packed_refs and return true; otherwise return false. 110 */ 111static intrelease_packed_ref_cache(struct packed_ref_cache *packed_refs) 112{ 113if(!--packed_refs->referrers) { 114free_ref_cache(packed_refs->cache); 115stat_validity_clear(&packed_refs->validity); 116free(packed_refs); 117return1; 118}else{ 119return0; 120} 121} 122 123static voidclear_packed_ref_cache(struct files_ref_store *refs) 124{ 125if(refs->packed_ref_store->cache) { 126struct packed_ref_cache *packed_refs = refs->packed_ref_store->cache; 127 128if(is_lock_file_locked(&refs->packed_ref_store->lock)) 129die("BUG: packed-ref cache cleared while locked"); 130 refs->packed_ref_store->cache = NULL; 131release_packed_ref_cache(packed_refs); 132} 133} 134 135static voidclear_loose_ref_cache(struct files_ref_store *refs) 136{ 137if(refs->loose) { 138free_ref_cache(refs->loose); 139 refs->loose = NULL; 140} 141} 142 143/* 144 * Create a new submodule ref cache and add it to the internal 145 * set of caches. 146 */ 147static struct ref_store *files_ref_store_create(const char*gitdir, 148unsigned int flags) 149{ 150struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 151struct ref_store *ref_store = (struct ref_store *)refs; 152struct strbuf sb = STRBUF_INIT; 153 154base_ref_store_init(ref_store, &refs_be_files); 155 refs->store_flags = flags; 156 157 refs->gitdir =xstrdup(gitdir); 158get_common_dir_noenv(&sb, gitdir); 159 refs->gitcommondir =strbuf_detach(&sb, NULL); 160strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 161 refs->packed_ref_store =packed_ref_store_create(sb.buf, flags); 162strbuf_release(&sb); 163 164return ref_store; 165} 166 167/* 168 * Die if refs is not the main ref store. caller is used in any 169 * necessary error messages. 170 */ 171static voidfiles_assert_main_repository(struct files_ref_store *refs, 172const char*caller) 173{ 174if(refs->store_flags & REF_STORE_MAIN) 175return; 176 177die("BUG: operation%sonly allowed for main ref store", caller); 178} 179 180/* 181 * Downcast ref_store to files_ref_store. Die if ref_store is not a 182 * files_ref_store. required_flags is compared with ref_store's 183 * store_flags to ensure the ref_store has all required capabilities. 184 * "caller" is used in any necessary error messages. 185 */ 186static struct files_ref_store *files_downcast(struct ref_store *ref_store, 187unsigned int required_flags, 188const char*caller) 189{ 190struct files_ref_store *refs; 191 192if(ref_store->be != &refs_be_files) 193die("BUG: ref_store is type\"%s\"not\"files\"in%s", 194 ref_store->be->name, caller); 195 196 refs = (struct files_ref_store *)ref_store; 197 198if((refs->store_flags & required_flags) != required_flags) 199die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 200 caller, required_flags, refs->store_flags); 201 202return refs; 203} 204 205/* The length of a peeled reference line in packed-refs, including EOL: */ 206#define PEELED_LINE_LENGTH 42 207 208/* 209 * The packed-refs header line that we write out. Perhaps other 210 * traits will be added later. The trailing space is required. 211 */ 212static const char PACKED_REFS_HEADER[] = 213"# pack-refs with: peeled fully-peeled\n"; 214 215/* 216 * Parse one line from a packed-refs file. Write the SHA1 to sha1. 217 * Return a pointer to the refname within the line (null-terminated), 218 * or NULL if there was a problem. 219 */ 220static const char*parse_ref_line(struct strbuf *line,struct object_id *oid) 221{ 222const char*ref; 223 224if(parse_oid_hex(line->buf, oid, &ref) <0) 225return NULL; 226if(!isspace(*ref++)) 227return NULL; 228 229if(isspace(*ref)) 230return NULL; 231 232if(line->buf[line->len -1] !='\n') 233return NULL; 234 line->buf[--line->len] =0; 235 236return ref; 237} 238 239/* 240 * Read from `packed_refs_file` into a newly-allocated 241 * `packed_ref_cache` and return it. The return value will already 242 * have its reference count incremented. 243 * 244 * A comment line of the form "# pack-refs with: " may contain zero or 245 * more traits. We interpret the traits as follows: 246 * 247 * No traits: 248 * 249 * Probably no references are peeled. But if the file contains a 250 * peeled value for a reference, we will use it. 251 * 252 * peeled: 253 * 254 * References under "refs/tags/", if they *can* be peeled, *are* 255 * peeled in this file. References outside of "refs/tags/" are 256 * probably not peeled even if they could have been, but if we find 257 * a peeled value for such a reference we will use it. 258 * 259 * fully-peeled: 260 * 261 * All references in the file that can be peeled are peeled. 262 * Inversely (and this is more important), any references in the 263 * file for which no peeled value is recorded is not peelable. This 264 * trait should typically be written alongside "peeled" for 265 * compatibility with older clients, but we do not require it 266 * (i.e., "peeled" is a no-op if "fully-peeled" is set). 267 */ 268static struct packed_ref_cache *read_packed_refs(const char*packed_refs_file) 269{ 270FILE*f; 271struct packed_ref_cache *packed_refs =xcalloc(1,sizeof(*packed_refs)); 272struct ref_entry *last = NULL; 273struct strbuf line = STRBUF_INIT; 274enum{ PEELED_NONE, PEELED_TAGS, PEELED_FULLY } peeled = PEELED_NONE; 275struct ref_dir *dir; 276 277acquire_packed_ref_cache(packed_refs); 278 packed_refs->cache =create_ref_cache(NULL, NULL); 279 packed_refs->cache->root->flag &= ~REF_INCOMPLETE; 280 281 f =fopen(packed_refs_file,"r"); 282if(!f) { 283if(errno == ENOENT) { 284/* 285 * This is OK; it just means that no 286 * "packed-refs" file has been written yet, 287 * which is equivalent to it being empty. 288 */ 289return packed_refs; 290}else{ 291die_errno("couldn't read%s", packed_refs_file); 292} 293} 294 295stat_validity_update(&packed_refs->validity,fileno(f)); 296 297 dir =get_ref_dir(packed_refs->cache->root); 298while(strbuf_getwholeline(&line, f,'\n') != EOF) { 299struct object_id oid; 300const char*refname; 301const char*traits; 302 303if(skip_prefix(line.buf,"# pack-refs with:", &traits)) { 304if(strstr(traits," fully-peeled ")) 305 peeled = PEELED_FULLY; 306else if(strstr(traits," peeled ")) 307 peeled = PEELED_TAGS; 308/* perhaps other traits later as well */ 309continue; 310} 311 312 refname =parse_ref_line(&line, &oid); 313if(refname) { 314int flag = REF_ISPACKED; 315 316if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) { 317if(!refname_is_safe(refname)) 318die("packed refname is dangerous:%s", refname); 319oidclr(&oid); 320 flag |= REF_BAD_NAME | REF_ISBROKEN; 321} 322 last =create_ref_entry(refname, &oid, flag); 323if(peeled == PEELED_FULLY || 324(peeled == PEELED_TAGS &&starts_with(refname,"refs/tags/"))) 325 last->flag |= REF_KNOWS_PEELED; 326add_ref_entry(dir, last); 327continue; 328} 329if(last && 330 line.buf[0] =='^'&& 331 line.len == PEELED_LINE_LENGTH && 332 line.buf[PEELED_LINE_LENGTH -1] =='\n'&& 333!get_oid_hex(line.buf +1, &oid)) { 334oidcpy(&last->u.value.peeled, &oid); 335/* 336 * Regardless of what the file header said, 337 * we definitely know the value of *this* 338 * reference: 339 */ 340 last->flag |= REF_KNOWS_PEELED; 341} 342} 343 344fclose(f); 345strbuf_release(&line); 346 347return packed_refs; 348} 349 350static voidfiles_reflog_path(struct files_ref_store *refs, 351struct strbuf *sb, 352const char*refname) 353{ 354if(!refname) { 355/* 356 * FIXME: of course this is wrong in multi worktree 357 * setting. To be fixed real soon. 358 */ 359strbuf_addf(sb,"%s/logs", refs->gitcommondir); 360return; 361} 362 363switch(ref_type(refname)) { 364case REF_TYPE_PER_WORKTREE: 365case REF_TYPE_PSEUDOREF: 366strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 367break; 368case REF_TYPE_NORMAL: 369strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 370break; 371default: 372die("BUG: unknown ref type%dof ref%s", 373ref_type(refname), refname); 374} 375} 376 377static voidfiles_ref_path(struct files_ref_store *refs, 378struct strbuf *sb, 379const char*refname) 380{ 381switch(ref_type(refname)) { 382case REF_TYPE_PER_WORKTREE: 383case REF_TYPE_PSEUDOREF: 384strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 385break; 386case REF_TYPE_NORMAL: 387strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 388break; 389default: 390die("BUG: unknown ref type%dof ref%s", 391ref_type(refname), refname); 392} 393} 394 395/* 396 * Check that the packed refs cache (if any) still reflects the 397 * contents of the file. If not, clear the cache. 398 */ 399static voidvalidate_packed_ref_cache(struct files_ref_store *refs) 400{ 401if(refs->packed_ref_store->cache && 402!stat_validity_check(&refs->packed_ref_store->cache->validity, 403 refs->packed_ref_store->path)) 404clear_packed_ref_cache(refs); 405} 406 407/* 408 * Get the packed_ref_cache for the specified files_ref_store, 409 * creating and populating it if it hasn't been read before or if the 410 * file has been changed (according to its `validity` field) since it 411 * was last read. On the other hand, if we hold the lock, then assume 412 * that the file hasn't been changed out from under us, so skip the 413 * extra `stat()` call in `stat_validity_check()`. 414 */ 415static struct packed_ref_cache *get_packed_ref_cache(struct files_ref_store *refs) 416{ 417const char*packed_refs_file = refs->packed_ref_store->path; 418 419if(!is_lock_file_locked(&refs->packed_ref_store->lock)) 420validate_packed_ref_cache(refs); 421 422if(!refs->packed_ref_store->cache) 423 refs->packed_ref_store->cache =read_packed_refs(packed_refs_file); 424 425return refs->packed_ref_store->cache; 426} 427 428static struct ref_dir *get_packed_ref_dir(struct packed_ref_cache *packed_ref_cache) 429{ 430returnget_ref_dir(packed_ref_cache->cache->root); 431} 432 433static struct ref_dir *get_packed_refs(struct files_ref_store *refs) 434{ 435returnget_packed_ref_dir(get_packed_ref_cache(refs)); 436} 437 438/* 439 * Add or overwrite a reference in the in-memory packed reference 440 * cache. This may only be called while the packed-refs file is locked 441 * (see lock_packed_refs()). To actually write the packed-refs file, 442 * call commit_packed_refs(). 443 */ 444static voidadd_packed_ref(struct files_ref_store *refs, 445const char*refname,const struct object_id *oid) 446{ 447struct ref_dir *packed_refs; 448struct ref_entry *packed_entry; 449 450if(!is_lock_file_locked(&refs->packed_ref_store->lock)) 451die("BUG: packed refs not locked"); 452 453if(check_refname_format(refname, REFNAME_ALLOW_ONELEVEL)) 454die("Reference has invalid format: '%s'", refname); 455 456 packed_refs =get_packed_refs(refs); 457 packed_entry =find_ref_entry(packed_refs, refname); 458if(packed_entry) { 459/* Overwrite the existing entry: */ 460oidcpy(&packed_entry->u.value.oid, oid); 461 packed_entry->flag = REF_ISPACKED; 462oidclr(&packed_entry->u.value.peeled); 463}else{ 464 packed_entry =create_ref_entry(refname, oid, REF_ISPACKED); 465add_ref_entry(packed_refs, packed_entry); 466} 467} 468 469/* 470 * Read the loose references from the namespace dirname into dir 471 * (without recursing). dirname must end with '/'. dir must be the 472 * directory entry corresponding to dirname. 473 */ 474static voidloose_fill_ref_dir(struct ref_store *ref_store, 475struct ref_dir *dir,const char*dirname) 476{ 477struct files_ref_store *refs = 478files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 479DIR*d; 480struct dirent *de; 481int dirnamelen =strlen(dirname); 482struct strbuf refname; 483struct strbuf path = STRBUF_INIT; 484size_t path_baselen; 485 486files_ref_path(refs, &path, dirname); 487 path_baselen = path.len; 488 489 d =opendir(path.buf); 490if(!d) { 491strbuf_release(&path); 492return; 493} 494 495strbuf_init(&refname, dirnamelen +257); 496strbuf_add(&refname, dirname, dirnamelen); 497 498while((de =readdir(d)) != NULL) { 499struct object_id oid; 500struct stat st; 501int flag; 502 503if(de->d_name[0] =='.') 504continue; 505if(ends_with(de->d_name,".lock")) 506continue; 507strbuf_addstr(&refname, de->d_name); 508strbuf_addstr(&path, de->d_name); 509if(stat(path.buf, &st) <0) { 510;/* silently ignore */ 511}else if(S_ISDIR(st.st_mode)) { 512strbuf_addch(&refname,'/'); 513add_entry_to_dir(dir, 514create_dir_entry(dir->cache, refname.buf, 515 refname.len,1)); 516}else{ 517if(!refs_resolve_ref_unsafe(&refs->base, 518 refname.buf, 519 RESOLVE_REF_READING, 520 oid.hash, &flag)) { 521oidclr(&oid); 522 flag |= REF_ISBROKEN; 523}else if(is_null_oid(&oid)) { 524/* 525 * It is so astronomically unlikely 526 * that NULL_SHA1 is the SHA-1 of an 527 * actual object that we consider its 528 * appearance in a loose reference 529 * file to be repo corruption 530 * (probably due to a software bug). 531 */ 532 flag |= REF_ISBROKEN; 533} 534 535if(check_refname_format(refname.buf, 536 REFNAME_ALLOW_ONELEVEL)) { 537if(!refname_is_safe(refname.buf)) 538die("loose refname is dangerous:%s", refname.buf); 539oidclr(&oid); 540 flag |= REF_BAD_NAME | REF_ISBROKEN; 541} 542add_entry_to_dir(dir, 543create_ref_entry(refname.buf, &oid, flag)); 544} 545strbuf_setlen(&refname, dirnamelen); 546strbuf_setlen(&path, path_baselen); 547} 548strbuf_release(&refname); 549strbuf_release(&path); 550closedir(d); 551 552/* 553 * Manually add refs/bisect, which, being per-worktree, might 554 * not appear in the directory listing for refs/ in the main 555 * repo. 556 */ 557if(!strcmp(dirname,"refs/")) { 558int pos =search_ref_dir(dir,"refs/bisect/",12); 559 560if(pos <0) { 561struct ref_entry *child_entry =create_dir_entry( 562 dir->cache,"refs/bisect/",12,1); 563add_entry_to_dir(dir, child_entry); 564} 565} 566} 567 568static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 569{ 570if(!refs->loose) { 571/* 572 * Mark the top-level directory complete because we 573 * are about to read the only subdirectory that can 574 * hold references: 575 */ 576 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 577 578/* We're going to fill the top level ourselves: */ 579 refs->loose->root->flag &= ~REF_INCOMPLETE; 580 581/* 582 * Add an incomplete entry for "refs/" (to be filled 583 * lazily): 584 */ 585add_entry_to_dir(get_ref_dir(refs->loose->root), 586create_dir_entry(refs->loose,"refs/",5,1)); 587} 588return refs->loose; 589} 590 591/* 592 * Return the ref_entry for the given refname from the packed 593 * references. If it does not exist, return NULL. 594 */ 595static struct ref_entry *get_packed_ref(struct files_ref_store *refs, 596const char*refname) 597{ 598returnfind_ref_entry(get_packed_refs(refs), refname); 599} 600 601/* 602 * A loose ref file doesn't exist; check for a packed ref. 603 */ 604static intresolve_packed_ref(struct files_ref_store *refs, 605const char*refname, 606unsigned char*sha1,unsigned int*flags) 607{ 608struct ref_entry *entry; 609 610/* 611 * The loose reference file does not exist; check for a packed 612 * reference. 613 */ 614 entry =get_packed_ref(refs, refname); 615if(entry) { 616hashcpy(sha1, entry->u.value.oid.hash); 617*flags |= REF_ISPACKED; 618return0; 619} 620/* refname is not a packed reference. */ 621return-1; 622} 623 624static intfiles_read_raw_ref(struct ref_store *ref_store, 625const char*refname,unsigned char*sha1, 626struct strbuf *referent,unsigned int*type) 627{ 628struct files_ref_store *refs = 629files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 630struct strbuf sb_contents = STRBUF_INIT; 631struct strbuf sb_path = STRBUF_INIT; 632const char*path; 633const char*buf; 634struct stat st; 635int fd; 636int ret = -1; 637int save_errno; 638int remaining_retries =3; 639 640*type =0; 641strbuf_reset(&sb_path); 642 643files_ref_path(refs, &sb_path, refname); 644 645 path = sb_path.buf; 646 647stat_ref: 648/* 649 * We might have to loop back here to avoid a race 650 * condition: first we lstat() the file, then we try 651 * to read it as a link or as a file. But if somebody 652 * changes the type of the file (file <-> directory 653 * <-> symlink) between the lstat() and reading, then 654 * we don't want to report that as an error but rather 655 * try again starting with the lstat(). 656 * 657 * We'll keep a count of the retries, though, just to avoid 658 * any confusing situation sending us into an infinite loop. 659 */ 660 661if(remaining_retries-- <=0) 662goto out; 663 664if(lstat(path, &st) <0) { 665if(errno != ENOENT) 666goto out; 667if(resolve_packed_ref(refs, refname, sha1, type)) { 668 errno = ENOENT; 669goto out; 670} 671 ret =0; 672goto out; 673} 674 675/* Follow "normalized" - ie "refs/.." symlinks by hand */ 676if(S_ISLNK(st.st_mode)) { 677strbuf_reset(&sb_contents); 678if(strbuf_readlink(&sb_contents, path,0) <0) { 679if(errno == ENOENT || errno == EINVAL) 680/* inconsistent with lstat; retry */ 681goto stat_ref; 682else 683goto out; 684} 685if(starts_with(sb_contents.buf,"refs/") && 686!check_refname_format(sb_contents.buf,0)) { 687strbuf_swap(&sb_contents, referent); 688*type |= REF_ISSYMREF; 689 ret =0; 690goto out; 691} 692/* 693 * It doesn't look like a refname; fall through to just 694 * treating it like a non-symlink, and reading whatever it 695 * points to. 696 */ 697} 698 699/* Is it a directory? */ 700if(S_ISDIR(st.st_mode)) { 701/* 702 * Even though there is a directory where the loose 703 * ref is supposed to be, there could still be a 704 * packed ref: 705 */ 706if(resolve_packed_ref(refs, refname, sha1, type)) { 707 errno = EISDIR; 708goto out; 709} 710 ret =0; 711goto out; 712} 713 714/* 715 * Anything else, just open it and try to use it as 716 * a ref 717 */ 718 fd =open(path, O_RDONLY); 719if(fd <0) { 720if(errno == ENOENT && !S_ISLNK(st.st_mode)) 721/* inconsistent with lstat; retry */ 722goto stat_ref; 723else 724goto out; 725} 726strbuf_reset(&sb_contents); 727if(strbuf_read(&sb_contents, fd,256) <0) { 728int save_errno = errno; 729close(fd); 730 errno = save_errno; 731goto out; 732} 733close(fd); 734strbuf_rtrim(&sb_contents); 735 buf = sb_contents.buf; 736if(starts_with(buf,"ref:")) { 737 buf +=4; 738while(isspace(*buf)) 739 buf++; 740 741strbuf_reset(referent); 742strbuf_addstr(referent, buf); 743*type |= REF_ISSYMREF; 744 ret =0; 745goto out; 746} 747 748/* 749 * Please note that FETCH_HEAD has additional 750 * data after the sha. 751 */ 752if(get_sha1_hex(buf, sha1) || 753(buf[40] !='\0'&& !isspace(buf[40]))) { 754*type |= REF_ISBROKEN; 755 errno = EINVAL; 756goto out; 757} 758 759 ret =0; 760 761out: 762 save_errno = errno; 763strbuf_release(&sb_path); 764strbuf_release(&sb_contents); 765 errno = save_errno; 766return ret; 767} 768 769static voidunlock_ref(struct ref_lock *lock) 770{ 771/* Do not free lock->lk -- atexit() still looks at them */ 772if(lock->lk) 773rollback_lock_file(lock->lk); 774free(lock->ref_name); 775free(lock); 776} 777 778/* 779 * Lock refname, without following symrefs, and set *lock_p to point 780 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 781 * and type similarly to read_raw_ref(). 782 * 783 * The caller must verify that refname is a "safe" reference name (in 784 * the sense of refname_is_safe()) before calling this function. 785 * 786 * If the reference doesn't already exist, verify that refname doesn't 787 * have a D/F conflict with any existing references. extras and skip 788 * are passed to refs_verify_refname_available() for this check. 789 * 790 * If mustexist is not set and the reference is not found or is 791 * broken, lock the reference anyway but clear sha1. 792 * 793 * Return 0 on success. On failure, write an error message to err and 794 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 795 * 796 * Implementation note: This function is basically 797 * 798 * lock reference 799 * read_raw_ref() 800 * 801 * but it includes a lot more code to 802 * - Deal with possible races with other processes 803 * - Avoid calling refs_verify_refname_available() when it can be 804 * avoided, namely if we were successfully able to read the ref 805 * - Generate informative error messages in the case of failure 806 */ 807static intlock_raw_ref(struct files_ref_store *refs, 808const char*refname,int mustexist, 809const struct string_list *extras, 810const struct string_list *skip, 811struct ref_lock **lock_p, 812struct strbuf *referent, 813unsigned int*type, 814struct strbuf *err) 815{ 816struct ref_lock *lock; 817struct strbuf ref_file = STRBUF_INIT; 818int attempts_remaining =3; 819int ret = TRANSACTION_GENERIC_ERROR; 820 821assert(err); 822files_assert_main_repository(refs,"lock_raw_ref"); 823 824*type =0; 825 826/* First lock the file so it can't change out from under us. */ 827 828*lock_p = lock =xcalloc(1,sizeof(*lock)); 829 830 lock->ref_name =xstrdup(refname); 831files_ref_path(refs, &ref_file, refname); 832 833retry: 834switch(safe_create_leading_directories(ref_file.buf)) { 835case SCLD_OK: 836break;/* success */ 837case SCLD_EXISTS: 838/* 839 * Suppose refname is "refs/foo/bar". We just failed 840 * to create the containing directory, "refs/foo", 841 * because there was a non-directory in the way. This 842 * indicates a D/F conflict, probably because of 843 * another reference such as "refs/foo". There is no 844 * reason to expect this error to be transitory. 845 */ 846if(refs_verify_refname_available(&refs->base, refname, 847 extras, skip, err)) { 848if(mustexist) { 849/* 850 * To the user the relevant error is 851 * that the "mustexist" reference is 852 * missing: 853 */ 854strbuf_reset(err); 855strbuf_addf(err,"unable to resolve reference '%s'", 856 refname); 857}else{ 858/* 859 * The error message set by 860 * refs_verify_refname_available() is 861 * OK. 862 */ 863 ret = TRANSACTION_NAME_CONFLICT; 864} 865}else{ 866/* 867 * The file that is in the way isn't a loose 868 * reference. Report it as a low-level 869 * failure. 870 */ 871strbuf_addf(err,"unable to create lock file%s.lock; " 872"non-directory in the way", 873 ref_file.buf); 874} 875goto error_return; 876case SCLD_VANISHED: 877/* Maybe another process was tidying up. Try again. */ 878if(--attempts_remaining >0) 879goto retry; 880/* fall through */ 881default: 882strbuf_addf(err,"unable to create directory for%s", 883 ref_file.buf); 884goto error_return; 885} 886 887if(!lock->lk) 888 lock->lk =xcalloc(1,sizeof(struct lock_file)); 889 890if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 891if(errno == ENOENT && --attempts_remaining >0) { 892/* 893 * Maybe somebody just deleted one of the 894 * directories leading to ref_file. Try 895 * again: 896 */ 897goto retry; 898}else{ 899unable_to_lock_message(ref_file.buf, errno, err); 900goto error_return; 901} 902} 903 904/* 905 * Now we hold the lock and can read the reference without 906 * fear that its value will change. 907 */ 908 909if(files_read_raw_ref(&refs->base, refname, 910 lock->old_oid.hash, referent, type)) { 911if(errno == ENOENT) { 912if(mustexist) { 913/* Garden variety missing reference. */ 914strbuf_addf(err,"unable to resolve reference '%s'", 915 refname); 916goto error_return; 917}else{ 918/* 919 * Reference is missing, but that's OK. We 920 * know that there is not a conflict with 921 * another loose reference because 922 * (supposing that we are trying to lock 923 * reference "refs/foo/bar"): 924 * 925 * - We were successfully able to create 926 * the lockfile refs/foo/bar.lock, so we 927 * know there cannot be a loose reference 928 * named "refs/foo". 929 * 930 * - We got ENOENT and not EISDIR, so we 931 * know that there cannot be a loose 932 * reference named "refs/foo/bar/baz". 933 */ 934} 935}else if(errno == EISDIR) { 936/* 937 * There is a directory in the way. It might have 938 * contained references that have been deleted. If 939 * we don't require that the reference already 940 * exists, try to remove the directory so that it 941 * doesn't cause trouble when we want to rename the 942 * lockfile into place later. 943 */ 944if(mustexist) { 945/* Garden variety missing reference. */ 946strbuf_addf(err,"unable to resolve reference '%s'", 947 refname); 948goto error_return; 949}else if(remove_dir_recursively(&ref_file, 950 REMOVE_DIR_EMPTY_ONLY)) { 951if(refs_verify_refname_available( 952&refs->base, refname, 953 extras, skip, err)) { 954/* 955 * The error message set by 956 * verify_refname_available() is OK. 957 */ 958 ret = TRANSACTION_NAME_CONFLICT; 959goto error_return; 960}else{ 961/* 962 * We can't delete the directory, 963 * but we also don't know of any 964 * references that it should 965 * contain. 966 */ 967strbuf_addf(err,"there is a non-empty directory '%s' " 968"blocking reference '%s'", 969 ref_file.buf, refname); 970goto error_return; 971} 972} 973}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 974strbuf_addf(err,"unable to resolve reference '%s': " 975"reference broken", refname); 976goto error_return; 977}else{ 978strbuf_addf(err,"unable to resolve reference '%s':%s", 979 refname,strerror(errno)); 980goto error_return; 981} 982 983/* 984 * If the ref did not exist and we are creating it, 985 * make sure there is no existing ref that conflicts 986 * with refname: 987 */ 988if(refs_verify_refname_available( 989&refs->base, refname, 990 extras, skip, err)) 991goto error_return; 992} 993 994 ret =0; 995goto out; 996 997error_return: 998unlock_ref(lock); 999*lock_p = NULL;10001001out:1002strbuf_release(&ref_file);1003return ret;1004}10051006static intfiles_peel_ref(struct ref_store *ref_store,1007const char*refname,unsigned char*sha1)1008{1009struct files_ref_store *refs =1010files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB,1011"peel_ref");1012int flag;1013unsigned char base[20];10141015if(current_ref_iter && current_ref_iter->refname == refname) {1016struct object_id peeled;10171018if(ref_iterator_peel(current_ref_iter, &peeled))1019return-1;1020hashcpy(sha1, peeled.hash);1021return0;1022}10231024if(refs_read_ref_full(ref_store, refname,1025 RESOLVE_REF_READING, base, &flag))1026return-1;10271028/*1029 * If the reference is packed, read its ref_entry from the1030 * cache in the hope that we already know its peeled value.1031 * We only try this optimization on packed references because1032 * (a) forcing the filling of the loose reference cache could1033 * be expensive and (b) loose references anyway usually do not1034 * have REF_KNOWS_PEELED.1035 */1036if(flag & REF_ISPACKED) {1037struct ref_entry *r =get_packed_ref(refs, refname);1038if(r) {1039if(peel_entry(r,0))1040return-1;1041hashcpy(sha1, r->u.value.peeled.hash);1042return0;1043}1044}10451046returnpeel_object(base, sha1);1047}10481049struct files_ref_iterator {1050struct ref_iterator base;10511052struct packed_ref_cache *packed_ref_cache;1053struct ref_iterator *iter0;1054unsigned int flags;1055};10561057static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator)1058{1059struct files_ref_iterator *iter =1060(struct files_ref_iterator *)ref_iterator;1061int ok;10621063while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) {1064if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY &&1065ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE)1066continue;10671068if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) &&1069!ref_resolves_to_object(iter->iter0->refname,1070 iter->iter0->oid,1071 iter->iter0->flags))1072continue;10731074 iter->base.refname = iter->iter0->refname;1075 iter->base.oid = iter->iter0->oid;1076 iter->base.flags = iter->iter0->flags;1077return ITER_OK;1078}10791080 iter->iter0 = NULL;1081if(ref_iterator_abort(ref_iterator) != ITER_DONE)1082 ok = ITER_ERROR;10831084return ok;1085}10861087static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator,1088struct object_id *peeled)1089{1090struct files_ref_iterator *iter =1091(struct files_ref_iterator *)ref_iterator;10921093returnref_iterator_peel(iter->iter0, peeled);1094}10951096static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator)1097{1098struct files_ref_iterator *iter =1099(struct files_ref_iterator *)ref_iterator;1100int ok = ITER_DONE;11011102if(iter->iter0)1103 ok =ref_iterator_abort(iter->iter0);11041105release_packed_ref_cache(iter->packed_ref_cache);1106base_ref_iterator_free(ref_iterator);1107return ok;1108}11091110static struct ref_iterator_vtable files_ref_iterator_vtable = {1111 files_ref_iterator_advance,1112 files_ref_iterator_peel,1113 files_ref_iterator_abort1114};11151116static struct ref_iterator *files_ref_iterator_begin(1117struct ref_store *ref_store,1118const char*prefix,unsigned int flags)1119{1120struct files_ref_store *refs;1121struct ref_iterator *loose_iter, *packed_iter;1122struct files_ref_iterator *iter;1123struct ref_iterator *ref_iterator;1124unsigned int required_flags = REF_STORE_READ;11251126if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN))1127 required_flags |= REF_STORE_ODB;11281129 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin");11301131 iter =xcalloc(1,sizeof(*iter));1132 ref_iterator = &iter->base;1133base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable);11341135/*1136 * We must make sure that all loose refs are read before1137 * accessing the packed-refs file; this avoids a race1138 * condition if loose refs are migrated to the packed-refs1139 * file by a simultaneous process, but our in-memory view is1140 * from before the migration. We ensure this as follows:1141 * First, we call start the loose refs iteration with its1142 * `prime_ref` argument set to true. This causes the loose1143 * references in the subtree to be pre-read into the cache.1144 * (If they've already been read, that's OK; we only need to1145 * guarantee that they're read before the packed refs, not1146 * *how much* before.) After that, we call1147 * get_packed_ref_cache(), which internally checks whether the1148 * packed-ref cache is up to date with what is on disk, and1149 * re-reads it if not.1150 */11511152 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs),1153 prefix,1);11541155 iter->packed_ref_cache =get_packed_ref_cache(refs);1156acquire_packed_ref_cache(iter->packed_ref_cache);1157 packed_iter =cache_ref_iterator_begin(iter->packed_ref_cache->cache,1158 prefix,0);11591160 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter);1161 iter->flags = flags;11621163return ref_iterator;1164}11651166/*1167 * Verify that the reference locked by lock has the value old_sha1.1168 * Fail if the reference doesn't exist and mustexist is set. Return 01169 * on success. On error, write an error message to err, set errno, and1170 * return a negative value.1171 */1172static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock,1173const unsigned char*old_sha1,int mustexist,1174struct strbuf *err)1175{1176assert(err);11771178if(refs_read_ref_full(ref_store, lock->ref_name,1179 mustexist ? RESOLVE_REF_READING :0,1180 lock->old_oid.hash, NULL)) {1181if(old_sha1) {1182int save_errno = errno;1183strbuf_addf(err,"can't verify ref '%s'", lock->ref_name);1184 errno = save_errno;1185return-1;1186}else{1187oidclr(&lock->old_oid);1188return0;1189}1190}1191if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) {1192strbuf_addf(err,"ref '%s' is at%sbut expected%s",1193 lock->ref_name,1194oid_to_hex(&lock->old_oid),1195sha1_to_hex(old_sha1));1196 errno = EBUSY;1197return-1;1198}1199return0;1200}12011202static intremove_empty_directories(struct strbuf *path)1203{1204/*1205 * we want to create a file but there is a directory there;1206 * if that is an empty directory (or a directory that contains1207 * only empty directories), remove them.1208 */1209returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY);1210}12111212static intcreate_reflock(const char*path,void*cb)1213{1214struct lock_file *lk = cb;12151216returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0;1217}12181219/*1220 * Locks a ref returning the lock on success and NULL on failure.1221 * On failure errno is set to something meaningful.1222 */1223static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs,1224const char*refname,1225const unsigned char*old_sha1,1226const struct string_list *extras,1227const struct string_list *skip,1228unsigned int flags,int*type,1229struct strbuf *err)1230{1231struct strbuf ref_file = STRBUF_INIT;1232struct ref_lock *lock;1233int last_errno =0;1234int mustexist = (old_sha1 && !is_null_sha1(old_sha1));1235int resolve_flags = RESOLVE_REF_NO_RECURSE;1236int resolved;12371238files_assert_main_repository(refs,"lock_ref_sha1_basic");1239assert(err);12401241 lock =xcalloc(1,sizeof(struct ref_lock));12421243if(mustexist)1244 resolve_flags |= RESOLVE_REF_READING;1245if(flags & REF_DELETING)1246 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME;12471248files_ref_path(refs, &ref_file, refname);1249 resolved = !!refs_resolve_ref_unsafe(&refs->base,1250 refname, resolve_flags,1251 lock->old_oid.hash, type);1252if(!resolved && errno == EISDIR) {1253/*1254 * we are trying to lock foo but we used to1255 * have foo/bar which now does not exist;1256 * it is normal for the empty directory 'foo'1257 * to remain.1258 */1259if(remove_empty_directories(&ref_file)) {1260 last_errno = errno;1261if(!refs_verify_refname_available(1262&refs->base,1263 refname, extras, skip, err))1264strbuf_addf(err,"there are still refs under '%s'",1265 refname);1266goto error_return;1267}1268 resolved = !!refs_resolve_ref_unsafe(&refs->base,1269 refname, resolve_flags,1270 lock->old_oid.hash, type);1271}1272if(!resolved) {1273 last_errno = errno;1274if(last_errno != ENOTDIR ||1275!refs_verify_refname_available(&refs->base, refname,1276 extras, skip, err))1277strbuf_addf(err,"unable to resolve reference '%s':%s",1278 refname,strerror(last_errno));12791280goto error_return;1281}12821283/*1284 * If the ref did not exist and we are creating it, make sure1285 * there is no existing packed ref whose name begins with our1286 * refname, nor a packed ref whose name is a proper prefix of1287 * our refname.1288 */1289if(is_null_oid(&lock->old_oid) &&1290refs_verify_refname_available(&refs->base, refname,1291 extras, skip, err)) {1292 last_errno = ENOTDIR;1293goto error_return;1294}12951296 lock->lk =xcalloc(1,sizeof(struct lock_file));12971298 lock->ref_name =xstrdup(refname);12991300if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) {1301 last_errno = errno;1302unable_to_lock_message(ref_file.buf, errno, err);1303goto error_return;1304}13051306if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) {1307 last_errno = errno;1308goto error_return;1309}1310goto out;13111312 error_return:1313unlock_ref(lock);1314 lock = NULL;13151316 out:1317strbuf_release(&ref_file);1318 errno = last_errno;1319return lock;1320}13211322/*1323 * Write an entry to the packed-refs file for the specified refname.1324 * If peeled is non-NULL, write it as the entry's peeled value.1325 */1326static voidwrite_packed_entry(FILE*fh,const char*refname,1327const unsigned char*sha1,1328const unsigned char*peeled)1329{1330fprintf_or_die(fh,"%s %s\n",sha1_to_hex(sha1), refname);1331if(peeled)1332fprintf_or_die(fh,"^%s\n",sha1_to_hex(peeled));1333}13341335/*1336 * Lock the packed-refs file for writing. Flags is passed to1337 * hold_lock_file_for_update(). Return 0 on success. On errors, set1338 * errno appropriately and return a nonzero value.1339 */1340static intlock_packed_refs(struct files_ref_store *refs,int flags)1341{1342static int timeout_configured =0;1343static int timeout_value =1000;1344struct packed_ref_cache *packed_ref_cache;13451346files_assert_main_repository(refs,"lock_packed_refs");13471348if(!timeout_configured) {1349git_config_get_int("core.packedrefstimeout", &timeout_value);1350 timeout_configured =1;1351}13521353if(hold_lock_file_for_update_timeout(1354&refs->packed_ref_store->lock,1355 refs->packed_ref_store->path,1356 flags, timeout_value) <0)1357return-1;13581359/*1360 * Now that we hold the `packed-refs` lock, make sure that our1361 * cache matches the current version of the file. Normally1362 * `get_packed_ref_cache()` does that for us, but that1363 * function assumes that when the file is locked, any existing1364 * cache is still valid. We've just locked the file, but it1365 * might have changed the moment *before* we locked it.1366 */1367validate_packed_ref_cache(refs);13681369 packed_ref_cache =get_packed_ref_cache(refs);1370/* Increment the reference count to prevent it from being freed: */1371acquire_packed_ref_cache(packed_ref_cache);1372return0;1373}13741375/*1376 * Write the current version of the packed refs cache from memory to1377 * disk. The packed-refs file must already be locked for writing (see1378 * lock_packed_refs()). Return zero on success. On errors, set errno1379 * and return a nonzero value1380 */1381static intcommit_packed_refs(struct files_ref_store *refs)1382{1383struct packed_ref_cache *packed_ref_cache =1384get_packed_ref_cache(refs);1385int ok, error =0;1386int save_errno =0;1387FILE*out;1388struct ref_iterator *iter;13891390files_assert_main_repository(refs,"commit_packed_refs");13911392if(!is_lock_file_locked(&refs->packed_ref_store->lock))1393die("BUG: packed-refs not locked");13941395 out =fdopen_lock_file(&refs->packed_ref_store->lock,"w");1396if(!out)1397die_errno("unable to fdopen packed-refs descriptor");13981399fprintf_or_die(out,"%s", PACKED_REFS_HEADER);14001401 iter =cache_ref_iterator_begin(packed_ref_cache->cache, NULL,0);1402while((ok =ref_iterator_advance(iter)) == ITER_OK) {1403struct object_id peeled;1404int peel_error =ref_iterator_peel(iter, &peeled);14051406write_packed_entry(out, iter->refname, iter->oid->hash,1407 peel_error ? NULL : peeled.hash);1408}14091410if(ok != ITER_DONE)1411die("error while iterating over references");14121413if(commit_lock_file(&refs->packed_ref_store->lock)) {1414 save_errno = errno;1415 error = -1;1416}1417release_packed_ref_cache(packed_ref_cache);1418 errno = save_errno;1419return error;1420}14211422/*1423 * Rollback the lockfile for the packed-refs file, and discard the1424 * in-memory packed reference cache. (The packed-refs file will be1425 * read anew if it is needed again after this function is called.)1426 */1427static voidrollback_packed_refs(struct files_ref_store *refs)1428{1429struct packed_ref_cache *packed_ref_cache =1430get_packed_ref_cache(refs);14311432files_assert_main_repository(refs,"rollback_packed_refs");14331434if(!is_lock_file_locked(&refs->packed_ref_store->lock))1435die("BUG: packed-refs not locked");1436rollback_lock_file(&refs->packed_ref_store->lock);1437release_packed_ref_cache(packed_ref_cache);1438clear_packed_ref_cache(refs);1439}14401441struct ref_to_prune {1442struct ref_to_prune *next;1443unsigned char sha1[20];1444char name[FLEX_ARRAY];1445};14461447enum{1448 REMOVE_EMPTY_PARENTS_REF =0x01,1449 REMOVE_EMPTY_PARENTS_REFLOG =0x021450};14511452/*1453 * Remove empty parent directories associated with the specified1454 * reference and/or its reflog, but spare [logs/]refs/ and immediate1455 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or1456 * REMOVE_EMPTY_PARENTS_REFLOG.1457 */1458static voidtry_remove_empty_parents(struct files_ref_store *refs,1459const char*refname,1460unsigned int flags)1461{1462struct strbuf buf = STRBUF_INIT;1463struct strbuf sb = STRBUF_INIT;1464char*p, *q;1465int i;14661467strbuf_addstr(&buf, refname);1468 p = buf.buf;1469for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1470while(*p && *p !='/')1471 p++;1472/* tolerate duplicate slashes; see check_refname_format() */1473while(*p =='/')1474 p++;1475}1476 q = buf.buf + buf.len;1477while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1478while(q > p && *q !='/')1479 q--;1480while(q > p && *(q-1) =='/')1481 q--;1482if(q == p)1483break;1484strbuf_setlen(&buf, q - buf.buf);14851486strbuf_reset(&sb);1487files_ref_path(refs, &sb, buf.buf);1488if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1489 flags &= ~REMOVE_EMPTY_PARENTS_REF;14901491strbuf_reset(&sb);1492files_reflog_path(refs, &sb, buf.buf);1493if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1494 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1495}1496strbuf_release(&buf);1497strbuf_release(&sb);1498}14991500/* make sure nobody touched the ref, and unlink */1501static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1502{1503struct ref_transaction *transaction;1504struct strbuf err = STRBUF_INIT;15051506if(check_refname_format(r->name,0))1507return;15081509 transaction =ref_store_transaction_begin(&refs->base, &err);1510if(!transaction ||1511ref_transaction_delete(transaction, r->name, r->sha1,1512 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1513ref_transaction_commit(transaction, &err)) {1514ref_transaction_free(transaction);1515error("%s", err.buf);1516strbuf_release(&err);1517return;1518}1519ref_transaction_free(transaction);1520strbuf_release(&err);1521}15221523static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1524{1525while(r) {1526prune_ref(refs, r);1527 r = r->next;1528}1529}15301531/*1532 * Return true if the specified reference should be packed.1533 */1534static intshould_pack_ref(const char*refname,1535const struct object_id *oid,unsigned int ref_flags,1536unsigned int pack_flags)1537{1538/* Do not pack per-worktree refs: */1539if(ref_type(refname) != REF_TYPE_NORMAL)1540return0;15411542/* Do not pack non-tags unless PACK_REFS_ALL is set: */1543if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1544return0;15451546/* Do not pack symbolic refs: */1547if(ref_flags & REF_ISSYMREF)1548return0;15491550/* Do not pack broken refs: */1551if(!ref_resolves_to_object(refname, oid, ref_flags))1552return0;15531554return1;1555}15561557static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1558{1559struct files_ref_store *refs =1560files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1561"pack_refs");1562struct ref_iterator *iter;1563int ok;1564struct ref_to_prune *refs_to_prune = NULL;15651566lock_packed_refs(refs, LOCK_DIE_ON_ERROR);15671568 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1569while((ok =ref_iterator_advance(iter)) == ITER_OK) {1570/*1571 * If the loose reference can be packed, add an entry1572 * in the packed ref cache. If the reference should be1573 * pruned, also add it to refs_to_prune.1574 */1575if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1576 flags))1577continue;15781579/*1580 * Create an entry in the packed-refs cache equivalent1581 * to the one from the loose ref cache, except that1582 * we don't copy the peeled status, because we want it1583 * to be re-peeled.1584 */1585add_packed_ref(refs, iter->refname, iter->oid);15861587/* Schedule the loose reference for pruning if requested. */1588if((flags & PACK_REFS_PRUNE)) {1589struct ref_to_prune *n;1590FLEX_ALLOC_STR(n, name, iter->refname);1591hashcpy(n->sha1, iter->oid->hash);1592 n->next = refs_to_prune;1593 refs_to_prune = n;1594}1595}1596if(ok != ITER_DONE)1597die("error while iterating over references");15981599if(commit_packed_refs(refs))1600die_errno("unable to overwrite old ref-pack file");16011602prune_refs(refs, refs_to_prune);1603return0;1604}16051606/*1607 * Rewrite the packed-refs file, omitting any refs listed in1608 * 'refnames'. On error, leave packed-refs unchanged, write an error1609 * message to 'err', and return a nonzero value.1610 *1611 * The refs in 'refnames' needn't be sorted. `err` must not be NULL.1612 */1613static intrepack_without_refs(struct files_ref_store *refs,1614struct string_list *refnames,struct strbuf *err)1615{1616struct ref_dir *packed;1617struct string_list_item *refname;1618int ret, needs_repacking =0, removed =0;16191620files_assert_main_repository(refs,"repack_without_refs");1621assert(err);16221623/* Look for a packed ref */1624for_each_string_list_item(refname, refnames) {1625if(get_packed_ref(refs, refname->string)) {1626 needs_repacking =1;1627break;1628}1629}16301631/* Avoid locking if we have nothing to do */1632if(!needs_repacking)1633return0;/* no refname exists in packed refs */16341635if(lock_packed_refs(refs,0)) {1636unable_to_lock_message(refs->packed_ref_store->path, errno, err);1637return-1;1638}1639 packed =get_packed_refs(refs);16401641/* Remove refnames from the cache */1642for_each_string_list_item(refname, refnames)1643if(remove_entry_from_dir(packed, refname->string) != -1)1644 removed =1;1645if(!removed) {1646/*1647 * All packed entries disappeared while we were1648 * acquiring the lock.1649 */1650rollback_packed_refs(refs);1651return0;1652}16531654/* Write what remains */1655 ret =commit_packed_refs(refs);1656if(ret)1657strbuf_addf(err,"unable to overwrite old ref-pack file:%s",1658strerror(errno));1659return ret;1660}16611662static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1663struct string_list *refnames,unsigned int flags)1664{1665struct files_ref_store *refs =1666files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1667struct strbuf err = STRBUF_INIT;1668int i, result =0;16691670if(!refnames->nr)1671return0;16721673 result =repack_without_refs(refs, refnames, &err);1674if(result) {1675/*1676 * If we failed to rewrite the packed-refs file, then1677 * it is unsafe to try to remove loose refs, because1678 * doing so might expose an obsolete packed value for1679 * a reference that might even point at an object that1680 * has been garbage collected.1681 */1682if(refnames->nr ==1)1683error(_("could not delete reference%s:%s"),1684 refnames->items[0].string, err.buf);1685else1686error(_("could not delete references:%s"), err.buf);16871688goto out;1689}16901691for(i =0; i < refnames->nr; i++) {1692const char*refname = refnames->items[i].string;16931694if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1695 result |=error(_("could not remove reference%s"), refname);1696}16971698out:1699strbuf_release(&err);1700return result;1701}17021703/*1704 * People using contrib's git-new-workdir have .git/logs/refs ->1705 * /some/other/path/.git/logs/refs, and that may live on another device.1706 *1707 * IOW, to avoid cross device rename errors, the temporary renamed log must1708 * live into logs/refs.1709 */1710#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"17111712struct rename_cb {1713const char*tmp_renamed_log;1714int true_errno;1715};17161717static intrename_tmp_log_callback(const char*path,void*cb_data)1718{1719struct rename_cb *cb = cb_data;17201721if(rename(cb->tmp_renamed_log, path)) {1722/*1723 * rename(a, b) when b is an existing directory ought1724 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1725 * Sheesh. Record the true errno for error reporting,1726 * but report EISDIR to raceproof_create_file() so1727 * that it knows to retry.1728 */1729 cb->true_errno = errno;1730if(errno == ENOTDIR)1731 errno = EISDIR;1732return-1;1733}else{1734return0;1735}1736}17371738static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1739{1740struct strbuf path = STRBUF_INIT;1741struct strbuf tmp = STRBUF_INIT;1742struct rename_cb cb;1743int ret;17441745files_reflog_path(refs, &path, newrefname);1746files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1747 cb.tmp_renamed_log = tmp.buf;1748 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1749if(ret) {1750if(errno == EISDIR)1751error("directory not empty:%s", path.buf);1752else1753error("unable to move logfile%sto%s:%s",1754 tmp.buf, path.buf,1755strerror(cb.true_errno));1756}17571758strbuf_release(&path);1759strbuf_release(&tmp);1760return ret;1761}17621763static intwrite_ref_to_lockfile(struct ref_lock *lock,1764const struct object_id *oid,struct strbuf *err);1765static intcommit_ref_update(struct files_ref_store *refs,1766struct ref_lock *lock,1767const struct object_id *oid,const char*logmsg,1768struct strbuf *err);17691770static intfiles_rename_ref(struct ref_store *ref_store,1771const char*oldrefname,const char*newrefname,1772const char*logmsg)1773{1774struct files_ref_store *refs =1775files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1776struct object_id oid, orig_oid;1777int flag =0, logmoved =0;1778struct ref_lock *lock;1779struct stat loginfo;1780struct strbuf sb_oldref = STRBUF_INIT;1781struct strbuf sb_newref = STRBUF_INIT;1782struct strbuf tmp_renamed_log = STRBUF_INIT;1783int log, ret;1784struct strbuf err = STRBUF_INIT;17851786files_reflog_path(refs, &sb_oldref, oldrefname);1787files_reflog_path(refs, &sb_newref, newrefname);1788files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);17891790 log = !lstat(sb_oldref.buf, &loginfo);1791if(log &&S_ISLNK(loginfo.st_mode)) {1792 ret =error("reflog for%sis a symlink", oldrefname);1793goto out;1794}17951796if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1797 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1798 orig_oid.hash, &flag)) {1799 ret =error("refname%snot found", oldrefname);1800goto out;1801}18021803if(flag & REF_ISSYMREF) {1804 ret =error("refname%sis a symbolic ref, renaming it is not supported",1805 oldrefname);1806goto out;1807}1808if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1809 ret =1;1810goto out;1811}18121813if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1814 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1815 oldrefname,strerror(errno));1816goto out;1817}18181819if(refs_delete_ref(&refs->base, logmsg, oldrefname,1820 orig_oid.hash, REF_NODEREF)) {1821error("unable to delete old%s", oldrefname);1822goto rollback;1823}18241825/*1826 * Since we are doing a shallow lookup, oid is not the1827 * correct value to pass to delete_ref as old_oid. But that1828 * doesn't matter, because an old_oid check wouldn't add to1829 * the safety anyway; we want to delete the reference whatever1830 * its current value.1831 */1832if(!refs_read_ref_full(&refs->base, newrefname,1833 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1834 oid.hash, NULL) &&1835refs_delete_ref(&refs->base, NULL, newrefname,1836 NULL, REF_NODEREF)) {1837if(errno == EISDIR) {1838struct strbuf path = STRBUF_INIT;1839int result;18401841files_ref_path(refs, &path, newrefname);1842 result =remove_empty_directories(&path);1843strbuf_release(&path);18441845if(result) {1846error("Directory not empty:%s", newrefname);1847goto rollback;1848}1849}else{1850error("unable to delete existing%s", newrefname);1851goto rollback;1852}1853}18541855if(log &&rename_tmp_log(refs, newrefname))1856goto rollback;18571858 logmoved = log;18591860 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1861 REF_NODEREF, NULL, &err);1862if(!lock) {1863error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1864strbuf_release(&err);1865goto rollback;1866}1867oidcpy(&lock->old_oid, &orig_oid);18681869if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1870commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1871error("unable to write current sha1 into%s:%s", newrefname, err.buf);1872strbuf_release(&err);1873goto rollback;1874}18751876 ret =0;1877goto out;18781879 rollback:1880 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1881 REF_NODEREF, NULL, &err);1882if(!lock) {1883error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1884strbuf_release(&err);1885goto rollbacklog;1886}18871888 flag = log_all_ref_updates;1889 log_all_ref_updates = LOG_REFS_NONE;1890if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1891commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1892error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1893strbuf_release(&err);1894}1895 log_all_ref_updates = flag;18961897 rollbacklog:1898if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1899error("unable to restore logfile%sfrom%s:%s",1900 oldrefname, newrefname,strerror(errno));1901if(!logmoved && log &&1902rename(tmp_renamed_log.buf, sb_oldref.buf))1903error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1904 oldrefname,strerror(errno));1905 ret =1;1906 out:1907strbuf_release(&sb_newref);1908strbuf_release(&sb_oldref);1909strbuf_release(&tmp_renamed_log);19101911return ret;1912}19131914static intclose_ref(struct ref_lock *lock)1915{1916if(close_lock_file(lock->lk))1917return-1;1918return0;1919}19201921static intcommit_ref(struct ref_lock *lock)1922{1923char*path =get_locked_file_path(lock->lk);1924struct stat st;19251926if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1927/*1928 * There is a directory at the path we want to rename1929 * the lockfile to. Hopefully it is empty; try to1930 * delete it.1931 */1932size_t len =strlen(path);1933struct strbuf sb_path = STRBUF_INIT;19341935strbuf_attach(&sb_path, path, len, len);19361937/*1938 * If this fails, commit_lock_file() will also fail1939 * and will report the problem.1940 */1941remove_empty_directories(&sb_path);1942strbuf_release(&sb_path);1943}else{1944free(path);1945}19461947if(commit_lock_file(lock->lk))1948return-1;1949return0;1950}19511952static intopen_or_create_logfile(const char*path,void*cb)1953{1954int*fd = cb;19551956*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1957return(*fd <0) ? -1:0;1958}19591960/*1961 * Create a reflog for a ref. If force_create = 0, only create the1962 * reflog for certain refs (those for which should_autocreate_reflog1963 * returns non-zero). Otherwise, create it regardless of the reference1964 * name. If the logfile already existed or was created, return 0 and1965 * set *logfd to the file descriptor opened for appending to the file.1966 * If no logfile exists and we decided not to create one, return 0 and1967 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1968 * return -1.1969 */1970static intlog_ref_setup(struct files_ref_store *refs,1971const char*refname,int force_create,1972int*logfd,struct strbuf *err)1973{1974struct strbuf logfile_sb = STRBUF_INIT;1975char*logfile;19761977files_reflog_path(refs, &logfile_sb, refname);1978 logfile =strbuf_detach(&logfile_sb, NULL);19791980if(force_create ||should_autocreate_reflog(refname)) {1981if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1982if(errno == ENOENT)1983strbuf_addf(err,"unable to create directory for '%s': "1984"%s", logfile,strerror(errno));1985else if(errno == EISDIR)1986strbuf_addf(err,"there are still logs under '%s'",1987 logfile);1988else1989strbuf_addf(err,"unable to append to '%s':%s",1990 logfile,strerror(errno));19911992goto error;1993}1994}else{1995*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1996if(*logfd <0) {1997if(errno == ENOENT || errno == EISDIR) {1998/*1999 * The logfile doesn't already exist,2000 * but that is not an error; it only2001 * means that we won't write log2002 * entries to it.2003 */2004;2005}else{2006strbuf_addf(err,"unable to append to '%s':%s",2007 logfile,strerror(errno));2008goto error;2009}2010}2011}20122013if(*logfd >=0)2014adjust_shared_perm(logfile);20152016free(logfile);2017return0;20182019error:2020free(logfile);2021return-1;2022}20232024static intfiles_create_reflog(struct ref_store *ref_store,2025const char*refname,int force_create,2026struct strbuf *err)2027{2028struct files_ref_store *refs =2029files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");2030int fd;20312032if(log_ref_setup(refs, refname, force_create, &fd, err))2033return-1;20342035if(fd >=0)2036close(fd);20372038return0;2039}20402041static intlog_ref_write_fd(int fd,const struct object_id *old_oid,2042const struct object_id *new_oid,2043const char*committer,const char*msg)2044{2045int msglen, written;2046unsigned maxlen, len;2047char*logrec;20482049 msglen = msg ?strlen(msg) :0;2050 maxlen =strlen(committer) + msglen +100;2051 logrec =xmalloc(maxlen);2052 len =xsnprintf(logrec, maxlen,"%s %s %s\n",2053oid_to_hex(old_oid),2054oid_to_hex(new_oid),2055 committer);2056if(msglen)2057 len +=copy_reflog_msg(logrec + len -1, msg) -1;20582059 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;2060free(logrec);2061if(written != len)2062return-1;20632064return0;2065}20662067static intfiles_log_ref_write(struct files_ref_store *refs,2068const char*refname,const struct object_id *old_oid,2069const struct object_id *new_oid,const char*msg,2070int flags,struct strbuf *err)2071{2072int logfd, result;20732074if(log_all_ref_updates == LOG_REFS_UNSET)2075 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;20762077 result =log_ref_setup(refs, refname,2078 flags & REF_FORCE_CREATE_REFLOG,2079&logfd, err);20802081if(result)2082return result;20832084if(logfd <0)2085return0;2086 result =log_ref_write_fd(logfd, old_oid, new_oid,2087git_committer_info(0), msg);2088if(result) {2089struct strbuf sb = STRBUF_INIT;2090int save_errno = errno;20912092files_reflog_path(refs, &sb, refname);2093strbuf_addf(err,"unable to append to '%s':%s",2094 sb.buf,strerror(save_errno));2095strbuf_release(&sb);2096close(logfd);2097return-1;2098}2099if(close(logfd)) {2100struct strbuf sb = STRBUF_INIT;2101int save_errno = errno;21022103files_reflog_path(refs, &sb, refname);2104strbuf_addf(err,"unable to append to '%s':%s",2105 sb.buf,strerror(save_errno));2106strbuf_release(&sb);2107return-1;2108}2109return0;2110}21112112/*2113 * Write sha1 into the open lockfile, then close the lockfile. On2114 * errors, rollback the lockfile, fill in *err and2115 * return -1.2116 */2117static intwrite_ref_to_lockfile(struct ref_lock *lock,2118const struct object_id *oid,struct strbuf *err)2119{2120static char term ='\n';2121struct object *o;2122int fd;21232124 o =parse_object(oid);2125if(!o) {2126strbuf_addf(err,2127"trying to write ref '%s' with nonexistent object%s",2128 lock->ref_name,oid_to_hex(oid));2129unlock_ref(lock);2130return-1;2131}2132if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {2133strbuf_addf(err,2134"trying to write non-commit object%sto branch '%s'",2135oid_to_hex(oid), lock->ref_name);2136unlock_ref(lock);2137return-1;2138}2139 fd =get_lock_file_fd(lock->lk);2140if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2141write_in_full(fd, &term,1) !=1||2142close_ref(lock) <0) {2143strbuf_addf(err,2144"couldn't write '%s'",get_lock_file_path(lock->lk));2145unlock_ref(lock);2146return-1;2147}2148return0;2149}21502151/*2152 * Commit a change to a loose reference that has already been written2153 * to the loose reference lockfile. Also update the reflogs if2154 * necessary, using the specified lockmsg (which can be NULL).2155 */2156static intcommit_ref_update(struct files_ref_store *refs,2157struct ref_lock *lock,2158const struct object_id *oid,const char*logmsg,2159struct strbuf *err)2160{2161files_assert_main_repository(refs,"commit_ref_update");21622163clear_loose_ref_cache(refs);2164if(files_log_ref_write(refs, lock->ref_name,2165&lock->old_oid, oid,2166 logmsg,0, err)) {2167char*old_msg =strbuf_detach(err, NULL);2168strbuf_addf(err,"cannot update the ref '%s':%s",2169 lock->ref_name, old_msg);2170free(old_msg);2171unlock_ref(lock);2172return-1;2173}21742175if(strcmp(lock->ref_name,"HEAD") !=0) {2176/*2177 * Special hack: If a branch is updated directly and HEAD2178 * points to it (may happen on the remote side of a push2179 * for example) then logically the HEAD reflog should be2180 * updated too.2181 * A generic solution implies reverse symref information,2182 * but finding all symrefs pointing to the given branch2183 * would be rather costly for this rare event (the direct2184 * update of a branch) to be worth it. So let's cheat and2185 * check with HEAD only which should cover 99% of all usage2186 * scenarios (even 100% of the default ones).2187 */2188struct object_id head_oid;2189int head_flag;2190const char*head_ref;21912192 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",2193 RESOLVE_REF_READING,2194 head_oid.hash, &head_flag);2195if(head_ref && (head_flag & REF_ISSYMREF) &&2196!strcmp(head_ref, lock->ref_name)) {2197struct strbuf log_err = STRBUF_INIT;2198if(files_log_ref_write(refs,"HEAD",2199&lock->old_oid, oid,2200 logmsg,0, &log_err)) {2201error("%s", log_err.buf);2202strbuf_release(&log_err);2203}2204}2205}22062207if(commit_ref(lock)) {2208strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2209unlock_ref(lock);2210return-1;2211}22122213unlock_ref(lock);2214return0;2215}22162217static intcreate_ref_symlink(struct ref_lock *lock,const char*target)2218{2219int ret = -1;2220#ifndef NO_SYMLINK_HEAD2221char*ref_path =get_locked_file_path(lock->lk);2222unlink(ref_path);2223 ret =symlink(target, ref_path);2224free(ref_path);22252226if(ret)2227fprintf(stderr,"no symlink - falling back to symbolic ref\n");2228#endif2229return ret;2230}22312232static voidupdate_symref_reflog(struct files_ref_store *refs,2233struct ref_lock *lock,const char*refname,2234const char*target,const char*logmsg)2235{2236struct strbuf err = STRBUF_INIT;2237struct object_id new_oid;2238if(logmsg &&2239!refs_read_ref_full(&refs->base, target,2240 RESOLVE_REF_READING, new_oid.hash, NULL) &&2241files_log_ref_write(refs, refname, &lock->old_oid,2242&new_oid, logmsg,0, &err)) {2243error("%s", err.buf);2244strbuf_release(&err);2245}2246}22472248static intcreate_symref_locked(struct files_ref_store *refs,2249struct ref_lock *lock,const char*refname,2250const char*target,const char*logmsg)2251{2252if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {2253update_symref_reflog(refs, lock, refname, target, logmsg);2254return0;2255}22562257if(!fdopen_lock_file(lock->lk,"w"))2258returnerror("unable to fdopen%s:%s",2259 lock->lk->tempfile.filename.buf,strerror(errno));22602261update_symref_reflog(refs, lock, refname, target, logmsg);22622263/* no error check; commit_ref will check ferror */2264fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);2265if(commit_ref(lock) <0)2266returnerror("unable to write symref for%s:%s", refname,2267strerror(errno));2268return0;2269}22702271static intfiles_create_symref(struct ref_store *ref_store,2272const char*refname,const char*target,2273const char*logmsg)2274{2275struct files_ref_store *refs =2276files_downcast(ref_store, REF_STORE_WRITE,"create_symref");2277struct strbuf err = STRBUF_INIT;2278struct ref_lock *lock;2279int ret;22802281 lock =lock_ref_sha1_basic(refs, refname, NULL,2282 NULL, NULL, REF_NODEREF, NULL,2283&err);2284if(!lock) {2285error("%s", err.buf);2286strbuf_release(&err);2287return-1;2288}22892290 ret =create_symref_locked(refs, lock, refname, target, logmsg);2291unlock_ref(lock);2292return ret;2293}22942295static intfiles_reflog_exists(struct ref_store *ref_store,2296const char*refname)2297{2298struct files_ref_store *refs =2299files_downcast(ref_store, REF_STORE_READ,"reflog_exists");2300struct strbuf sb = STRBUF_INIT;2301struct stat st;2302int ret;23032304files_reflog_path(refs, &sb, refname);2305 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);2306strbuf_release(&sb);2307return ret;2308}23092310static intfiles_delete_reflog(struct ref_store *ref_store,2311const char*refname)2312{2313struct files_ref_store *refs =2314files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");2315struct strbuf sb = STRBUF_INIT;2316int ret;23172318files_reflog_path(refs, &sb, refname);2319 ret =remove_path(sb.buf);2320strbuf_release(&sb);2321return ret;2322}23232324static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)2325{2326struct object_id ooid, noid;2327char*email_end, *message;2328 timestamp_t timestamp;2329int tz;2330const char*p = sb->buf;23312332/* old SP new SP name <email> SP time TAB msg LF */2333if(!sb->len || sb->buf[sb->len -1] !='\n'||2334parse_oid_hex(p, &ooid, &p) || *p++ !=' '||2335parse_oid_hex(p, &noid, &p) || *p++ !=' '||2336!(email_end =strchr(p,'>')) ||2337 email_end[1] !=' '||2338!(timestamp =parse_timestamp(email_end +2, &message,10)) ||2339!message || message[0] !=' '||2340(message[1] !='+'&& message[1] !='-') ||2341!isdigit(message[2]) || !isdigit(message[3]) ||2342!isdigit(message[4]) || !isdigit(message[5]))2343return0;/* corrupt? */2344 email_end[1] ='\0';2345 tz =strtol(message +1, NULL,10);2346if(message[6] !='\t')2347 message +=6;2348else2349 message +=7;2350returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);2351}23522353static char*find_beginning_of_line(char*bob,char*scan)2354{2355while(bob < scan && *(--scan) !='\n')2356;/* keep scanning backwards */2357/*2358 * Return either beginning of the buffer, or LF at the end of2359 * the previous line.2360 */2361return scan;2362}23632364static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,2365const char*refname,2366 each_reflog_ent_fn fn,2367void*cb_data)2368{2369struct files_ref_store *refs =2370files_downcast(ref_store, REF_STORE_READ,2371"for_each_reflog_ent_reverse");2372struct strbuf sb = STRBUF_INIT;2373FILE*logfp;2374long pos;2375int ret =0, at_tail =1;23762377files_reflog_path(refs, &sb, refname);2378 logfp =fopen(sb.buf,"r");2379strbuf_release(&sb);2380if(!logfp)2381return-1;23822383/* Jump to the end */2384if(fseek(logfp,0, SEEK_END) <0)2385 ret =error("cannot seek back reflog for%s:%s",2386 refname,strerror(errno));2387 pos =ftell(logfp);2388while(!ret &&0< pos) {2389int cnt;2390size_t nread;2391char buf[BUFSIZ];2392char*endp, *scanp;23932394/* Fill next block from the end */2395 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;2396if(fseek(logfp, pos - cnt, SEEK_SET)) {2397 ret =error("cannot seek back reflog for%s:%s",2398 refname,strerror(errno));2399break;2400}2401 nread =fread(buf, cnt,1, logfp);2402if(nread !=1) {2403 ret =error("cannot read%dbytes from reflog for%s:%s",2404 cnt, refname,strerror(errno));2405break;2406}2407 pos -= cnt;24082409 scanp = endp = buf + cnt;2410if(at_tail && scanp[-1] =='\n')2411/* Looking at the final LF at the end of the file */2412 scanp--;2413 at_tail =0;24142415while(buf < scanp) {2416/*2417 * terminating LF of the previous line, or the beginning2418 * of the buffer.2419 */2420char*bp;24212422 bp =find_beginning_of_line(buf, scanp);24232424if(*bp =='\n') {2425/*2426 * The newline is the end of the previous line,2427 * so we know we have complete line starting2428 * at (bp + 1). Prefix it onto any prior data2429 * we collected for the line and process it.2430 */2431strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));2432 scanp = bp;2433 endp = bp +1;2434 ret =show_one_reflog_ent(&sb, fn, cb_data);2435strbuf_reset(&sb);2436if(ret)2437break;2438}else if(!pos) {2439/*2440 * We are at the start of the buffer, and the2441 * start of the file; there is no previous2442 * line, and we have everything for this one.2443 * Process it, and we can end the loop.2444 */2445strbuf_splice(&sb,0,0, buf, endp - buf);2446 ret =show_one_reflog_ent(&sb, fn, cb_data);2447strbuf_reset(&sb);2448break;2449}24502451if(bp == buf) {2452/*2453 * We are at the start of the buffer, and there2454 * is more file to read backwards. Which means2455 * we are in the middle of a line. Note that we2456 * may get here even if *bp was a newline; that2457 * just means we are at the exact end of the2458 * previous line, rather than some spot in the2459 * middle.2460 *2461 * Save away what we have to be combined with2462 * the data from the next read.2463 */2464strbuf_splice(&sb,0,0, buf, endp - buf);2465break;2466}2467}24682469}2470if(!ret && sb.len)2471die("BUG: reverse reflog parser had leftover data");24722473fclose(logfp);2474strbuf_release(&sb);2475return ret;2476}24772478static intfiles_for_each_reflog_ent(struct ref_store *ref_store,2479const char*refname,2480 each_reflog_ent_fn fn,void*cb_data)2481{2482struct files_ref_store *refs =2483files_downcast(ref_store, REF_STORE_READ,2484"for_each_reflog_ent");2485FILE*logfp;2486struct strbuf sb = STRBUF_INIT;2487int ret =0;24882489files_reflog_path(refs, &sb, refname);2490 logfp =fopen(sb.buf,"r");2491strbuf_release(&sb);2492if(!logfp)2493return-1;24942495while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))2496 ret =show_one_reflog_ent(&sb, fn, cb_data);2497fclose(logfp);2498strbuf_release(&sb);2499return ret;2500}25012502struct files_reflog_iterator {2503struct ref_iterator base;25042505struct ref_store *ref_store;2506struct dir_iterator *dir_iterator;2507struct object_id oid;2508};25092510static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2511{2512struct files_reflog_iterator *iter =2513(struct files_reflog_iterator *)ref_iterator;2514struct dir_iterator *diter = iter->dir_iterator;2515int ok;25162517while((ok =dir_iterator_advance(diter)) == ITER_OK) {2518int flags;25192520if(!S_ISREG(diter->st.st_mode))2521continue;2522if(diter->basename[0] =='.')2523continue;2524if(ends_with(diter->basename,".lock"))2525continue;25262527if(refs_read_ref_full(iter->ref_store,2528 diter->relative_path,0,2529 iter->oid.hash, &flags)) {2530error("bad ref for%s", diter->path.buf);2531continue;2532}25332534 iter->base.refname = diter->relative_path;2535 iter->base.oid = &iter->oid;2536 iter->base.flags = flags;2537return ITER_OK;2538}25392540 iter->dir_iterator = NULL;2541if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2542 ok = ITER_ERROR;2543return ok;2544}25452546static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2547struct object_id *peeled)2548{2549die("BUG: ref_iterator_peel() called for reflog_iterator");2550}25512552static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2553{2554struct files_reflog_iterator *iter =2555(struct files_reflog_iterator *)ref_iterator;2556int ok = ITER_DONE;25572558if(iter->dir_iterator)2559 ok =dir_iterator_abort(iter->dir_iterator);25602561base_ref_iterator_free(ref_iterator);2562return ok;2563}25642565static struct ref_iterator_vtable files_reflog_iterator_vtable = {2566 files_reflog_iterator_advance,2567 files_reflog_iterator_peel,2568 files_reflog_iterator_abort2569};25702571static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2572{2573struct files_ref_store *refs =2574files_downcast(ref_store, REF_STORE_READ,2575"reflog_iterator_begin");2576struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2577struct ref_iterator *ref_iterator = &iter->base;2578struct strbuf sb = STRBUF_INIT;25792580base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2581files_reflog_path(refs, &sb, NULL);2582 iter->dir_iterator =dir_iterator_begin(sb.buf);2583 iter->ref_store = ref_store;2584strbuf_release(&sb);2585return ref_iterator;2586}25872588/*2589 * If update is a direct update of head_ref (the reference pointed to2590 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2591 */2592static intsplit_head_update(struct ref_update *update,2593struct ref_transaction *transaction,2594const char*head_ref,2595struct string_list *affected_refnames,2596struct strbuf *err)2597{2598struct string_list_item *item;2599struct ref_update *new_update;26002601if((update->flags & REF_LOG_ONLY) ||2602(update->flags & REF_ISPRUNING) ||2603(update->flags & REF_UPDATE_VIA_HEAD))2604return0;26052606if(strcmp(update->refname, head_ref))2607return0;26082609/*2610 * First make sure that HEAD is not already in the2611 * transaction. This insertion is O(N) in the transaction2612 * size, but it happens at most once per transaction.2613 */2614 item =string_list_insert(affected_refnames,"HEAD");2615if(item->util) {2616/* An entry already existed */2617strbuf_addf(err,2618"multiple updates for 'HEAD' (including one "2619"via its referent '%s') are not allowed",2620 update->refname);2621return TRANSACTION_NAME_CONFLICT;2622}26232624 new_update =ref_transaction_add_update(2625 transaction,"HEAD",2626 update->flags | REF_LOG_ONLY | REF_NODEREF,2627 update->new_oid.hash, update->old_oid.hash,2628 update->msg);26292630 item->util = new_update;26312632return0;2633}26342635/*2636 * update is for a symref that points at referent and doesn't have2637 * REF_NODEREF set. Split it into two updates:2638 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2639 * - A new, separate update for the referent reference2640 * Note that the new update will itself be subject to splitting when2641 * the iteration gets to it.2642 */2643static intsplit_symref_update(struct files_ref_store *refs,2644struct ref_update *update,2645const char*referent,2646struct ref_transaction *transaction,2647struct string_list *affected_refnames,2648struct strbuf *err)2649{2650struct string_list_item *item;2651struct ref_update *new_update;2652unsigned int new_flags;26532654/*2655 * First make sure that referent is not already in the2656 * transaction. This insertion is O(N) in the transaction2657 * size, but it happens at most once per symref in a2658 * transaction.2659 */2660 item =string_list_insert(affected_refnames, referent);2661if(item->util) {2662/* An entry already existed */2663strbuf_addf(err,2664"multiple updates for '%s' (including one "2665"via symref '%s') are not allowed",2666 referent, update->refname);2667return TRANSACTION_NAME_CONFLICT;2668}26692670 new_flags = update->flags;2671if(!strcmp(update->refname,"HEAD")) {2672/*2673 * Record that the new update came via HEAD, so that2674 * when we process it, split_head_update() doesn't try2675 * to add another reflog update for HEAD. Note that2676 * this bit will be propagated if the new_update2677 * itself needs to be split.2678 */2679 new_flags |= REF_UPDATE_VIA_HEAD;2680}26812682 new_update =ref_transaction_add_update(2683 transaction, referent, new_flags,2684 update->new_oid.hash, update->old_oid.hash,2685 update->msg);26862687 new_update->parent_update = update;26882689/*2690 * Change the symbolic ref update to log only. Also, it2691 * doesn't need to check its old SHA-1 value, as that will be2692 * done when new_update is processed.2693 */2694 update->flags |= REF_LOG_ONLY | REF_NODEREF;2695 update->flags &= ~REF_HAVE_OLD;26962697 item->util = new_update;26982699return0;2700}27012702/*2703 * Return the refname under which update was originally requested.2704 */2705static const char*original_update_refname(struct ref_update *update)2706{2707while(update->parent_update)2708 update = update->parent_update;27092710return update->refname;2711}27122713/*2714 * Check whether the REF_HAVE_OLD and old_oid values stored in update2715 * are consistent with oid, which is the reference's current value. If2716 * everything is OK, return 0; otherwise, write an error message to2717 * err and return -1.2718 */2719static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2720struct strbuf *err)2721{2722if(!(update->flags & REF_HAVE_OLD) ||2723!oidcmp(oid, &update->old_oid))2724return0;27252726if(is_null_oid(&update->old_oid))2727strbuf_addf(err,"cannot lock ref '%s': "2728"reference already exists",2729original_update_refname(update));2730else if(is_null_oid(oid))2731strbuf_addf(err,"cannot lock ref '%s': "2732"reference is missing but expected%s",2733original_update_refname(update),2734oid_to_hex(&update->old_oid));2735else2736strbuf_addf(err,"cannot lock ref '%s': "2737"is at%sbut expected%s",2738original_update_refname(update),2739oid_to_hex(oid),2740oid_to_hex(&update->old_oid));27412742return-1;2743}27442745/*2746 * Prepare for carrying out update:2747 * - Lock the reference referred to by update.2748 * - Read the reference under lock.2749 * - Check that its old SHA-1 value (if specified) is correct, and in2750 * any case record it in update->lock->old_oid for later use when2751 * writing the reflog.2752 * - If it is a symref update without REF_NODEREF, split it up into a2753 * REF_LOG_ONLY update of the symref and add a separate update for2754 * the referent to transaction.2755 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2756 * update of HEAD.2757 */2758static intlock_ref_for_update(struct files_ref_store *refs,2759struct ref_update *update,2760struct ref_transaction *transaction,2761const char*head_ref,2762struct string_list *affected_refnames,2763struct strbuf *err)2764{2765struct strbuf referent = STRBUF_INIT;2766int mustexist = (update->flags & REF_HAVE_OLD) &&2767!is_null_oid(&update->old_oid);2768int ret;2769struct ref_lock *lock;27702771files_assert_main_repository(refs,"lock_ref_for_update");27722773if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2774 update->flags |= REF_DELETING;27752776if(head_ref) {2777 ret =split_head_update(update, transaction, head_ref,2778 affected_refnames, err);2779if(ret)2780return ret;2781}27822783 ret =lock_raw_ref(refs, update->refname, mustexist,2784 affected_refnames, NULL,2785&lock, &referent,2786&update->type, err);2787if(ret) {2788char*reason;27892790 reason =strbuf_detach(err, NULL);2791strbuf_addf(err,"cannot lock ref '%s':%s",2792original_update_refname(update), reason);2793free(reason);2794return ret;2795}27962797 update->backend_data = lock;27982799if(update->type & REF_ISSYMREF) {2800if(update->flags & REF_NODEREF) {2801/*2802 * We won't be reading the referent as part of2803 * the transaction, so we have to read it here2804 * to record and possibly check old_sha1:2805 */2806if(refs_read_ref_full(&refs->base,2807 referent.buf,0,2808 lock->old_oid.hash, NULL)) {2809if(update->flags & REF_HAVE_OLD) {2810strbuf_addf(err,"cannot lock ref '%s': "2811"error reading reference",2812original_update_refname(update));2813return-1;2814}2815}else if(check_old_oid(update, &lock->old_oid, err)) {2816return TRANSACTION_GENERIC_ERROR;2817}2818}else{2819/*2820 * Create a new update for the reference this2821 * symref is pointing at. Also, we will record2822 * and verify old_sha1 for this update as part2823 * of processing the split-off update, so we2824 * don't have to do it here.2825 */2826 ret =split_symref_update(refs, update,2827 referent.buf, transaction,2828 affected_refnames, err);2829if(ret)2830return ret;2831}2832}else{2833struct ref_update *parent_update;28342835if(check_old_oid(update, &lock->old_oid, err))2836return TRANSACTION_GENERIC_ERROR;28372838/*2839 * If this update is happening indirectly because of a2840 * symref update, record the old SHA-1 in the parent2841 * update:2842 */2843for(parent_update = update->parent_update;2844 parent_update;2845 parent_update = parent_update->parent_update) {2846struct ref_lock *parent_lock = parent_update->backend_data;2847oidcpy(&parent_lock->old_oid, &lock->old_oid);2848}2849}28502851if((update->flags & REF_HAVE_NEW) &&2852!(update->flags & REF_DELETING) &&2853!(update->flags & REF_LOG_ONLY)) {2854if(!(update->type & REF_ISSYMREF) &&2855!oidcmp(&lock->old_oid, &update->new_oid)) {2856/*2857 * The reference already has the desired2858 * value, so we don't need to write it.2859 */2860}else if(write_ref_to_lockfile(lock, &update->new_oid,2861 err)) {2862char*write_err =strbuf_detach(err, NULL);28632864/*2865 * The lock was freed upon failure of2866 * write_ref_to_lockfile():2867 */2868 update->backend_data = NULL;2869strbuf_addf(err,2870"cannot update ref '%s':%s",2871 update->refname, write_err);2872free(write_err);2873return TRANSACTION_GENERIC_ERROR;2874}else{2875 update->flags |= REF_NEEDS_COMMIT;2876}2877}2878if(!(update->flags & REF_NEEDS_COMMIT)) {2879/*2880 * We didn't call write_ref_to_lockfile(), so2881 * the lockfile is still open. Close it to2882 * free up the file descriptor:2883 */2884if(close_ref(lock)) {2885strbuf_addf(err,"couldn't close '%s.lock'",2886 update->refname);2887return TRANSACTION_GENERIC_ERROR;2888}2889}2890return0;2891}28922893/*2894 * Unlock any references in `transaction` that are still locked, and2895 * mark the transaction closed.2896 */2897static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2898{2899size_t i;29002901for(i =0; i < transaction->nr; i++) {2902struct ref_update *update = transaction->updates[i];2903struct ref_lock *lock = update->backend_data;29042905if(lock) {2906unlock_ref(lock);2907 update->backend_data = NULL;2908}2909}29102911 transaction->state = REF_TRANSACTION_CLOSED;2912}29132914static intfiles_transaction_prepare(struct ref_store *ref_store,2915struct ref_transaction *transaction,2916struct strbuf *err)2917{2918struct files_ref_store *refs =2919files_downcast(ref_store, REF_STORE_WRITE,2920"ref_transaction_prepare");2921size_t i;2922int ret =0;2923struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2924char*head_ref = NULL;2925int head_type;2926struct object_id head_oid;29272928assert(err);29292930if(!transaction->nr)2931goto cleanup;29322933/*2934 * Fail if a refname appears more than once in the2935 * transaction. (If we end up splitting up any updates using2936 * split_symref_update() or split_head_update(), those2937 * functions will check that the new updates don't have the2938 * same refname as any existing ones.)2939 */2940for(i =0; i < transaction->nr; i++) {2941struct ref_update *update = transaction->updates[i];2942struct string_list_item *item =2943string_list_append(&affected_refnames, update->refname);29442945/*2946 * We store a pointer to update in item->util, but at2947 * the moment we never use the value of this field2948 * except to check whether it is non-NULL.2949 */2950 item->util = update;2951}2952string_list_sort(&affected_refnames);2953if(ref_update_reject_duplicates(&affected_refnames, err)) {2954 ret = TRANSACTION_GENERIC_ERROR;2955goto cleanup;2956}29572958/*2959 * Special hack: If a branch is updated directly and HEAD2960 * points to it (may happen on the remote side of a push2961 * for example) then logically the HEAD reflog should be2962 * updated too.2963 *2964 * A generic solution would require reverse symref lookups,2965 * but finding all symrefs pointing to a given branch would be2966 * rather costly for this rare event (the direct update of a2967 * branch) to be worth it. So let's cheat and check with HEAD2968 * only, which should cover 99% of all usage scenarios (even2969 * 100% of the default ones).2970 *2971 * So if HEAD is a symbolic reference, then record the name of2972 * the reference that it points to. If we see an update of2973 * head_ref within the transaction, then split_head_update()2974 * arranges for the reflog of HEAD to be updated, too.2975 */2976 head_ref =refs_resolve_refdup(ref_store,"HEAD",2977 RESOLVE_REF_NO_RECURSE,2978 head_oid.hash, &head_type);29792980if(head_ref && !(head_type & REF_ISSYMREF)) {2981free(head_ref);2982 head_ref = NULL;2983}29842985/*2986 * Acquire all locks, verify old values if provided, check2987 * that new values are valid, and write new values to the2988 * lockfiles, ready to be activated. Only keep one lockfile2989 * open at a time to avoid running out of file descriptors.2990 * Note that lock_ref_for_update() might append more updates2991 * to the transaction.2992 */2993for(i =0; i < transaction->nr; i++) {2994struct ref_update *update = transaction->updates[i];29952996 ret =lock_ref_for_update(refs, update, transaction,2997 head_ref, &affected_refnames, err);2998if(ret)2999break;3000}30013002cleanup:3003free(head_ref);3004string_list_clear(&affected_refnames,0);30053006if(ret)3007files_transaction_cleanup(transaction);3008else3009 transaction->state = REF_TRANSACTION_PREPARED;30103011return ret;3012}30133014static intfiles_transaction_finish(struct ref_store *ref_store,3015struct ref_transaction *transaction,3016struct strbuf *err)3017{3018struct files_ref_store *refs =3019files_downcast(ref_store,0,"ref_transaction_finish");3020size_t i;3021int ret =0;3022struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;3023struct string_list_item *ref_to_delete;3024struct strbuf sb = STRBUF_INIT;30253026assert(err);30273028if(!transaction->nr) {3029 transaction->state = REF_TRANSACTION_CLOSED;3030return0;3031}30323033/* Perform updates first so live commits remain referenced */3034for(i =0; i < transaction->nr; i++) {3035struct ref_update *update = transaction->updates[i];3036struct ref_lock *lock = update->backend_data;30373038if(update->flags & REF_NEEDS_COMMIT ||3039 update->flags & REF_LOG_ONLY) {3040if(files_log_ref_write(refs,3041 lock->ref_name,3042&lock->old_oid,3043&update->new_oid,3044 update->msg, update->flags,3045 err)) {3046char*old_msg =strbuf_detach(err, NULL);30473048strbuf_addf(err,"cannot update the ref '%s':%s",3049 lock->ref_name, old_msg);3050free(old_msg);3051unlock_ref(lock);3052 update->backend_data = NULL;3053 ret = TRANSACTION_GENERIC_ERROR;3054goto cleanup;3055}3056}3057if(update->flags & REF_NEEDS_COMMIT) {3058clear_loose_ref_cache(refs);3059if(commit_ref(lock)) {3060strbuf_addf(err,"couldn't set '%s'", lock->ref_name);3061unlock_ref(lock);3062 update->backend_data = NULL;3063 ret = TRANSACTION_GENERIC_ERROR;3064goto cleanup;3065}3066}3067}3068/* Perform deletes now that updates are safely completed */3069for(i =0; i < transaction->nr; i++) {3070struct ref_update *update = transaction->updates[i];3071struct ref_lock *lock = update->backend_data;30723073if(update->flags & REF_DELETING &&3074!(update->flags & REF_LOG_ONLY)) {3075if(!(update->type & REF_ISPACKED) ||3076 update->type & REF_ISSYMREF) {3077/* It is a loose reference. */3078strbuf_reset(&sb);3079files_ref_path(refs, &sb, lock->ref_name);3080if(unlink_or_msg(sb.buf, err)) {3081 ret = TRANSACTION_GENERIC_ERROR;3082goto cleanup;3083}3084 update->flags |= REF_DELETED_LOOSE;3085}30863087if(!(update->flags & REF_ISPRUNING))3088string_list_append(&refs_to_delete,3089 lock->ref_name);3090}3091}30923093if(repack_without_refs(refs, &refs_to_delete, err)) {3094 ret = TRANSACTION_GENERIC_ERROR;3095goto cleanup;3096}30973098/* Delete the reflogs of any references that were deleted: */3099for_each_string_list_item(ref_to_delete, &refs_to_delete) {3100strbuf_reset(&sb);3101files_reflog_path(refs, &sb, ref_to_delete->string);3102if(!unlink_or_warn(sb.buf))3103try_remove_empty_parents(refs, ref_to_delete->string,3104 REMOVE_EMPTY_PARENTS_REFLOG);3105}31063107clear_loose_ref_cache(refs);31083109cleanup:3110files_transaction_cleanup(transaction);31113112for(i =0; i < transaction->nr; i++) {3113struct ref_update *update = transaction->updates[i];31143115if(update->flags & REF_DELETED_LOOSE) {3116/*3117 * The loose reference was deleted. Delete any3118 * empty parent directories. (Note that this3119 * can only work because we have already3120 * removed the lockfile.)3121 */3122try_remove_empty_parents(refs, update->refname,3123 REMOVE_EMPTY_PARENTS_REF);3124}3125}31263127strbuf_release(&sb);3128string_list_clear(&refs_to_delete,0);3129return ret;3130}31313132static intfiles_transaction_abort(struct ref_store *ref_store,3133struct ref_transaction *transaction,3134struct strbuf *err)3135{3136files_transaction_cleanup(transaction);3137return0;3138}31393140static intref_present(const char*refname,3141const struct object_id *oid,int flags,void*cb_data)3142{3143struct string_list *affected_refnames = cb_data;31443145returnstring_list_has_string(affected_refnames, refname);3146}31473148static intfiles_initial_transaction_commit(struct ref_store *ref_store,3149struct ref_transaction *transaction,3150struct strbuf *err)3151{3152struct files_ref_store *refs =3153files_downcast(ref_store, REF_STORE_WRITE,3154"initial_ref_transaction_commit");3155size_t i;3156int ret =0;3157struct string_list affected_refnames = STRING_LIST_INIT_NODUP;31583159assert(err);31603161if(transaction->state != REF_TRANSACTION_OPEN)3162die("BUG: commit called for transaction that is not open");31633164/* Fail if a refname appears more than once in the transaction: */3165for(i =0; i < transaction->nr; i++)3166string_list_append(&affected_refnames,3167 transaction->updates[i]->refname);3168string_list_sort(&affected_refnames);3169if(ref_update_reject_duplicates(&affected_refnames, err)) {3170 ret = TRANSACTION_GENERIC_ERROR;3171goto cleanup;3172}31733174/*3175 * It's really undefined to call this function in an active3176 * repository or when there are existing references: we are3177 * only locking and changing packed-refs, so (1) any3178 * simultaneous processes might try to change a reference at3179 * the same time we do, and (2) any existing loose versions of3180 * the references that we are setting would have precedence3181 * over our values. But some remote helpers create the remote3182 * "HEAD" and "master" branches before calling this function,3183 * so here we really only check that none of the references3184 * that we are creating already exists.3185 */3186if(refs_for_each_rawref(&refs->base, ref_present,3187&affected_refnames))3188die("BUG: initial ref transaction called with existing refs");31893190for(i =0; i < transaction->nr; i++) {3191struct ref_update *update = transaction->updates[i];31923193if((update->flags & REF_HAVE_OLD) &&3194!is_null_oid(&update->old_oid))3195die("BUG: initial ref transaction with old_sha1 set");3196if(refs_verify_refname_available(&refs->base, update->refname,3197&affected_refnames, NULL,3198 err)) {3199 ret = TRANSACTION_NAME_CONFLICT;3200goto cleanup;3201}3202}32033204if(lock_packed_refs(refs,0)) {3205strbuf_addf(err,"unable to lock packed-refs file:%s",3206strerror(errno));3207 ret = TRANSACTION_GENERIC_ERROR;3208goto cleanup;3209}32103211for(i =0; i < transaction->nr; i++) {3212struct ref_update *update = transaction->updates[i];32133214if((update->flags & REF_HAVE_NEW) &&3215!is_null_oid(&update->new_oid))3216add_packed_ref(refs, update->refname,3217&update->new_oid);3218}32193220if(commit_packed_refs(refs)) {3221strbuf_addf(err,"unable to commit packed-refs file:%s",3222strerror(errno));3223 ret = TRANSACTION_GENERIC_ERROR;3224goto cleanup;3225}32263227cleanup:3228 transaction->state = REF_TRANSACTION_CLOSED;3229string_list_clear(&affected_refnames,0);3230return ret;3231}32323233struct expire_reflog_cb {3234unsigned int flags;3235 reflog_expiry_should_prune_fn *should_prune_fn;3236void*policy_cb;3237FILE*newlog;3238struct object_id last_kept_oid;3239};32403241static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,3242const char*email, timestamp_t timestamp,int tz,3243const char*message,void*cb_data)3244{3245struct expire_reflog_cb *cb = cb_data;3246struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;32473248if(cb->flags & EXPIRE_REFLOGS_REWRITE)3249 ooid = &cb->last_kept_oid;32503251if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,3252 message, policy_cb)) {3253if(!cb->newlog)3254printf("would prune%s", message);3255else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3256printf("prune%s", message);3257}else{3258if(cb->newlog) {3259fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",3260oid_to_hex(ooid),oid_to_hex(noid),3261 email, timestamp, tz, message);3262oidcpy(&cb->last_kept_oid, noid);3263}3264if(cb->flags & EXPIRE_REFLOGS_VERBOSE)3265printf("keep%s", message);3266}3267return0;3268}32693270static intfiles_reflog_expire(struct ref_store *ref_store,3271const char*refname,const unsigned char*sha1,3272unsigned int flags,3273 reflog_expiry_prepare_fn prepare_fn,3274 reflog_expiry_should_prune_fn should_prune_fn,3275 reflog_expiry_cleanup_fn cleanup_fn,3276void*policy_cb_data)3277{3278struct files_ref_store *refs =3279files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");3280static struct lock_file reflog_lock;3281struct expire_reflog_cb cb;3282struct ref_lock *lock;3283struct strbuf log_file_sb = STRBUF_INIT;3284char*log_file;3285int status =0;3286int type;3287struct strbuf err = STRBUF_INIT;3288struct object_id oid;32893290memset(&cb,0,sizeof(cb));3291 cb.flags = flags;3292 cb.policy_cb = policy_cb_data;3293 cb.should_prune_fn = should_prune_fn;32943295/*3296 * The reflog file is locked by holding the lock on the3297 * reference itself, plus we might need to update the3298 * reference if --updateref was specified:3299 */3300 lock =lock_ref_sha1_basic(refs, refname, sha1,3301 NULL, NULL, REF_NODEREF,3302&type, &err);3303if(!lock) {3304error("cannot lock ref '%s':%s", refname, err.buf);3305strbuf_release(&err);3306return-1;3307}3308if(!refs_reflog_exists(ref_store, refname)) {3309unlock_ref(lock);3310return0;3311}33123313files_reflog_path(refs, &log_file_sb, refname);3314 log_file =strbuf_detach(&log_file_sb, NULL);3315if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3316/*3317 * Even though holding $GIT_DIR/logs/$reflog.lock has3318 * no locking implications, we use the lock_file3319 * machinery here anyway because it does a lot of the3320 * work we need, including cleaning up if the program3321 * exits unexpectedly.3322 */3323if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {3324struct strbuf err = STRBUF_INIT;3325unable_to_lock_message(log_file, errno, &err);3326error("%s", err.buf);3327strbuf_release(&err);3328goto failure;3329}3330 cb.newlog =fdopen_lock_file(&reflog_lock,"w");3331if(!cb.newlog) {3332error("cannot fdopen%s(%s)",3333get_lock_file_path(&reflog_lock),strerror(errno));3334goto failure;3335}3336}33373338hashcpy(oid.hash, sha1);33393340(*prepare_fn)(refname, &oid, cb.policy_cb);3341refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);3342(*cleanup_fn)(cb.policy_cb);33433344if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {3345/*3346 * It doesn't make sense to adjust a reference pointed3347 * to by a symbolic ref based on expiring entries in3348 * the symbolic reference's reflog. Nor can we update3349 * a reference if there are no remaining reflog3350 * entries.3351 */3352int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3353!(type & REF_ISSYMREF) &&3354!is_null_oid(&cb.last_kept_oid);33553356if(close_lock_file(&reflog_lock)) {3357 status |=error("couldn't write%s:%s", log_file,3358strerror(errno));3359}else if(update &&3360(write_in_full(get_lock_file_fd(lock->lk),3361oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3362write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||3363close_ref(lock) <0)) {3364 status |=error("couldn't write%s",3365get_lock_file_path(lock->lk));3366rollback_lock_file(&reflog_lock);3367}else if(commit_lock_file(&reflog_lock)) {3368 status |=error("unable to write reflog '%s' (%s)",3369 log_file,strerror(errno));3370}else if(update &&commit_ref(lock)) {3371 status |=error("couldn't set%s", lock->ref_name);3372}3373}3374free(log_file);3375unlock_ref(lock);3376return status;33773378 failure:3379rollback_lock_file(&reflog_lock);3380free(log_file);3381unlock_ref(lock);3382return-1;3383}33843385static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3386{3387struct files_ref_store *refs =3388files_downcast(ref_store, REF_STORE_WRITE,"init_db");3389struct strbuf sb = STRBUF_INIT;33903391/*3392 * Create .git/refs/{heads,tags}3393 */3394files_ref_path(refs, &sb,"refs/heads");3395safe_create_dir(sb.buf,1);33963397strbuf_reset(&sb);3398files_ref_path(refs, &sb,"refs/tags");3399safe_create_dir(sb.buf,1);34003401strbuf_release(&sb);3402return0;3403}34043405struct ref_storage_be refs_be_files = {3406 NULL,3407"files",3408 files_ref_store_create,3409 files_init_db,3410 files_transaction_prepare,3411 files_transaction_finish,3412 files_transaction_abort,3413 files_initial_transaction_commit,34143415 files_pack_refs,3416 files_peel_ref,3417 files_create_symref,3418 files_delete_refs,3419 files_rename_ref,34203421 files_ref_iterator_begin,3422 files_read_raw_ref,34233424 files_reflog_iterator_begin,3425 files_for_each_reflog_ent,3426 files_for_each_reflog_ent_reverse,3427 files_reflog_exists,3428 files_create_reflog,3429 files_delete_reflog,3430 files_reflog_expire3431};