1#include"../cache.h" 2#include"../refs.h" 3#include"refs-internal.h" 4#include"ref-cache.h" 5#include"packed-backend.h" 6#include"../iterator.h" 7#include"../dir-iterator.h" 8#include"../lockfile.h" 9#include"../object.h" 10#include"../dir.h" 11 12struct ref_lock { 13char*ref_name; 14struct lock_file *lk; 15struct object_id old_oid; 16}; 17 18/* 19 * Future: need to be in "struct repository" 20 * when doing a full libification. 21 */ 22struct files_ref_store { 23struct ref_store base; 24unsigned int store_flags; 25 26char*gitdir; 27char*gitcommondir; 28 29struct ref_cache *loose; 30 31struct ref_store *packed_ref_store; 32}; 33 34static voidclear_loose_ref_cache(struct files_ref_store *refs) 35{ 36if(refs->loose) { 37free_ref_cache(refs->loose); 38 refs->loose = NULL; 39} 40} 41 42/* 43 * Create a new submodule ref cache and add it to the internal 44 * set of caches. 45 */ 46static struct ref_store *files_ref_store_create(const char*gitdir, 47unsigned int flags) 48{ 49struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 50struct ref_store *ref_store = (struct ref_store *)refs; 51struct strbuf sb = STRBUF_INIT; 52 53base_ref_store_init(ref_store, &refs_be_files); 54 refs->store_flags = flags; 55 56 refs->gitdir =xstrdup(gitdir); 57get_common_dir_noenv(&sb, gitdir); 58 refs->gitcommondir =strbuf_detach(&sb, NULL); 59strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 60 refs->packed_ref_store =packed_ref_store_create(sb.buf, flags); 61strbuf_release(&sb); 62 63return ref_store; 64} 65 66/* 67 * Die if refs is not the main ref store. caller is used in any 68 * necessary error messages. 69 */ 70static voidfiles_assert_main_repository(struct files_ref_store *refs, 71const char*caller) 72{ 73if(refs->store_flags & REF_STORE_MAIN) 74return; 75 76die("BUG: operation%sonly allowed for main ref store", caller); 77} 78 79/* 80 * Downcast ref_store to files_ref_store. Die if ref_store is not a 81 * files_ref_store. required_flags is compared with ref_store's 82 * store_flags to ensure the ref_store has all required capabilities. 83 * "caller" is used in any necessary error messages. 84 */ 85static struct files_ref_store *files_downcast(struct ref_store *ref_store, 86unsigned int required_flags, 87const char*caller) 88{ 89struct files_ref_store *refs; 90 91if(ref_store->be != &refs_be_files) 92die("BUG: ref_store is type\"%s\"not\"files\"in%s", 93 ref_store->be->name, caller); 94 95 refs = (struct files_ref_store *)ref_store; 96 97if((refs->store_flags & required_flags) != required_flags) 98die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 99 caller, required_flags, refs->store_flags); 100 101return refs; 102} 103 104static voidfiles_reflog_path(struct files_ref_store *refs, 105struct strbuf *sb, 106const char*refname) 107{ 108if(!refname) { 109/* 110 * FIXME: of course this is wrong in multi worktree 111 * setting. To be fixed real soon. 112 */ 113strbuf_addf(sb,"%s/logs", refs->gitcommondir); 114return; 115} 116 117switch(ref_type(refname)) { 118case REF_TYPE_PER_WORKTREE: 119case REF_TYPE_PSEUDOREF: 120strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 121break; 122case REF_TYPE_NORMAL: 123strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 124break; 125default: 126die("BUG: unknown ref type%dof ref%s", 127ref_type(refname), refname); 128} 129} 130 131static voidfiles_ref_path(struct files_ref_store *refs, 132struct strbuf *sb, 133const char*refname) 134{ 135switch(ref_type(refname)) { 136case REF_TYPE_PER_WORKTREE: 137case REF_TYPE_PSEUDOREF: 138strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 139break; 140case REF_TYPE_NORMAL: 141strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 142break; 143default: 144die("BUG: unknown ref type%dof ref%s", 145ref_type(refname), refname); 146} 147} 148 149/* 150 * Read the loose references from the namespace dirname into dir 151 * (without recursing). dirname must end with '/'. dir must be the 152 * directory entry corresponding to dirname. 153 */ 154static voidloose_fill_ref_dir(struct ref_store *ref_store, 155struct ref_dir *dir,const char*dirname) 156{ 157struct files_ref_store *refs = 158files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 159DIR*d; 160struct dirent *de; 161int dirnamelen =strlen(dirname); 162struct strbuf refname; 163struct strbuf path = STRBUF_INIT; 164size_t path_baselen; 165 166files_ref_path(refs, &path, dirname); 167 path_baselen = path.len; 168 169 d =opendir(path.buf); 170if(!d) { 171strbuf_release(&path); 172return; 173} 174 175strbuf_init(&refname, dirnamelen +257); 176strbuf_add(&refname, dirname, dirnamelen); 177 178while((de =readdir(d)) != NULL) { 179struct object_id oid; 180struct stat st; 181int flag; 182 183if(de->d_name[0] =='.') 184continue; 185if(ends_with(de->d_name,".lock")) 186continue; 187strbuf_addstr(&refname, de->d_name); 188strbuf_addstr(&path, de->d_name); 189if(stat(path.buf, &st) <0) { 190;/* silently ignore */ 191}else if(S_ISDIR(st.st_mode)) { 192strbuf_addch(&refname,'/'); 193add_entry_to_dir(dir, 194create_dir_entry(dir->cache, refname.buf, 195 refname.len,1)); 196}else{ 197if(!refs_resolve_ref_unsafe(&refs->base, 198 refname.buf, 199 RESOLVE_REF_READING, 200 oid.hash, &flag)) { 201oidclr(&oid); 202 flag |= REF_ISBROKEN; 203}else if(is_null_oid(&oid)) { 204/* 205 * It is so astronomically unlikely 206 * that NULL_SHA1 is the SHA-1 of an 207 * actual object that we consider its 208 * appearance in a loose reference 209 * file to be repo corruption 210 * (probably due to a software bug). 211 */ 212 flag |= REF_ISBROKEN; 213} 214 215if(check_refname_format(refname.buf, 216 REFNAME_ALLOW_ONELEVEL)) { 217if(!refname_is_safe(refname.buf)) 218die("loose refname is dangerous:%s", refname.buf); 219oidclr(&oid); 220 flag |= REF_BAD_NAME | REF_ISBROKEN; 221} 222add_entry_to_dir(dir, 223create_ref_entry(refname.buf, &oid, flag)); 224} 225strbuf_setlen(&refname, dirnamelen); 226strbuf_setlen(&path, path_baselen); 227} 228strbuf_release(&refname); 229strbuf_release(&path); 230closedir(d); 231 232/* 233 * Manually add refs/bisect, which, being per-worktree, might 234 * not appear in the directory listing for refs/ in the main 235 * repo. 236 */ 237if(!strcmp(dirname,"refs/")) { 238int pos =search_ref_dir(dir,"refs/bisect/",12); 239 240if(pos <0) { 241struct ref_entry *child_entry =create_dir_entry( 242 dir->cache,"refs/bisect/",12,1); 243add_entry_to_dir(dir, child_entry); 244} 245} 246} 247 248static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 249{ 250if(!refs->loose) { 251/* 252 * Mark the top-level directory complete because we 253 * are about to read the only subdirectory that can 254 * hold references: 255 */ 256 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 257 258/* We're going to fill the top level ourselves: */ 259 refs->loose->root->flag &= ~REF_INCOMPLETE; 260 261/* 262 * Add an incomplete entry for "refs/" (to be filled 263 * lazily): 264 */ 265add_entry_to_dir(get_ref_dir(refs->loose->root), 266create_dir_entry(refs->loose,"refs/",5,1)); 267} 268return refs->loose; 269} 270 271static intfiles_read_raw_ref(struct ref_store *ref_store, 272const char*refname,unsigned char*sha1, 273struct strbuf *referent,unsigned int*type) 274{ 275struct files_ref_store *refs = 276files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 277struct strbuf sb_contents = STRBUF_INIT; 278struct strbuf sb_path = STRBUF_INIT; 279const char*path; 280const char*buf; 281struct stat st; 282int fd; 283int ret = -1; 284int save_errno; 285int remaining_retries =3; 286 287*type =0; 288strbuf_reset(&sb_path); 289 290files_ref_path(refs, &sb_path, refname); 291 292 path = sb_path.buf; 293 294stat_ref: 295/* 296 * We might have to loop back here to avoid a race 297 * condition: first we lstat() the file, then we try 298 * to read it as a link or as a file. But if somebody 299 * changes the type of the file (file <-> directory 300 * <-> symlink) between the lstat() and reading, then 301 * we don't want to report that as an error but rather 302 * try again starting with the lstat(). 303 * 304 * We'll keep a count of the retries, though, just to avoid 305 * any confusing situation sending us into an infinite loop. 306 */ 307 308if(remaining_retries-- <=0) 309goto out; 310 311if(lstat(path, &st) <0) { 312if(errno != ENOENT) 313goto out; 314if(refs_read_raw_ref(refs->packed_ref_store, refname, 315 sha1, referent, type)) { 316 errno = ENOENT; 317goto out; 318} 319 ret =0; 320goto out; 321} 322 323/* Follow "normalized" - ie "refs/.." symlinks by hand */ 324if(S_ISLNK(st.st_mode)) { 325strbuf_reset(&sb_contents); 326if(strbuf_readlink(&sb_contents, path,0) <0) { 327if(errno == ENOENT || errno == EINVAL) 328/* inconsistent with lstat; retry */ 329goto stat_ref; 330else 331goto out; 332} 333if(starts_with(sb_contents.buf,"refs/") && 334!check_refname_format(sb_contents.buf,0)) { 335strbuf_swap(&sb_contents, referent); 336*type |= REF_ISSYMREF; 337 ret =0; 338goto out; 339} 340/* 341 * It doesn't look like a refname; fall through to just 342 * treating it like a non-symlink, and reading whatever it 343 * points to. 344 */ 345} 346 347/* Is it a directory? */ 348if(S_ISDIR(st.st_mode)) { 349/* 350 * Even though there is a directory where the loose 351 * ref is supposed to be, there could still be a 352 * packed ref: 353 */ 354if(refs_read_raw_ref(refs->packed_ref_store, refname, 355 sha1, referent, type)) { 356 errno = EISDIR; 357goto out; 358} 359 ret =0; 360goto out; 361} 362 363/* 364 * Anything else, just open it and try to use it as 365 * a ref 366 */ 367 fd =open(path, O_RDONLY); 368if(fd <0) { 369if(errno == ENOENT && !S_ISLNK(st.st_mode)) 370/* inconsistent with lstat; retry */ 371goto stat_ref; 372else 373goto out; 374} 375strbuf_reset(&sb_contents); 376if(strbuf_read(&sb_contents, fd,256) <0) { 377int save_errno = errno; 378close(fd); 379 errno = save_errno; 380goto out; 381} 382close(fd); 383strbuf_rtrim(&sb_contents); 384 buf = sb_contents.buf; 385if(starts_with(buf,"ref:")) { 386 buf +=4; 387while(isspace(*buf)) 388 buf++; 389 390strbuf_reset(referent); 391strbuf_addstr(referent, buf); 392*type |= REF_ISSYMREF; 393 ret =0; 394goto out; 395} 396 397/* 398 * Please note that FETCH_HEAD has additional 399 * data after the sha. 400 */ 401if(get_sha1_hex(buf, sha1) || 402(buf[40] !='\0'&& !isspace(buf[40]))) { 403*type |= REF_ISBROKEN; 404 errno = EINVAL; 405goto out; 406} 407 408 ret =0; 409 410out: 411 save_errno = errno; 412strbuf_release(&sb_path); 413strbuf_release(&sb_contents); 414 errno = save_errno; 415return ret; 416} 417 418static voidunlock_ref(struct ref_lock *lock) 419{ 420/* Do not free lock->lk -- atexit() still looks at them */ 421if(lock->lk) 422rollback_lock_file(lock->lk); 423free(lock->ref_name); 424free(lock); 425} 426 427/* 428 * Lock refname, without following symrefs, and set *lock_p to point 429 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 430 * and type similarly to read_raw_ref(). 431 * 432 * The caller must verify that refname is a "safe" reference name (in 433 * the sense of refname_is_safe()) before calling this function. 434 * 435 * If the reference doesn't already exist, verify that refname doesn't 436 * have a D/F conflict with any existing references. extras and skip 437 * are passed to refs_verify_refname_available() for this check. 438 * 439 * If mustexist is not set and the reference is not found or is 440 * broken, lock the reference anyway but clear sha1. 441 * 442 * Return 0 on success. On failure, write an error message to err and 443 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 444 * 445 * Implementation note: This function is basically 446 * 447 * lock reference 448 * read_raw_ref() 449 * 450 * but it includes a lot more code to 451 * - Deal with possible races with other processes 452 * - Avoid calling refs_verify_refname_available() when it can be 453 * avoided, namely if we were successfully able to read the ref 454 * - Generate informative error messages in the case of failure 455 */ 456static intlock_raw_ref(struct files_ref_store *refs, 457const char*refname,int mustexist, 458const struct string_list *extras, 459const struct string_list *skip, 460struct ref_lock **lock_p, 461struct strbuf *referent, 462unsigned int*type, 463struct strbuf *err) 464{ 465struct ref_lock *lock; 466struct strbuf ref_file = STRBUF_INIT; 467int attempts_remaining =3; 468int ret = TRANSACTION_GENERIC_ERROR; 469 470assert(err); 471files_assert_main_repository(refs,"lock_raw_ref"); 472 473*type =0; 474 475/* First lock the file so it can't change out from under us. */ 476 477*lock_p = lock =xcalloc(1,sizeof(*lock)); 478 479 lock->ref_name =xstrdup(refname); 480files_ref_path(refs, &ref_file, refname); 481 482retry: 483switch(safe_create_leading_directories(ref_file.buf)) { 484case SCLD_OK: 485break;/* success */ 486case SCLD_EXISTS: 487/* 488 * Suppose refname is "refs/foo/bar". We just failed 489 * to create the containing directory, "refs/foo", 490 * because there was a non-directory in the way. This 491 * indicates a D/F conflict, probably because of 492 * another reference such as "refs/foo". There is no 493 * reason to expect this error to be transitory. 494 */ 495if(refs_verify_refname_available(&refs->base, refname, 496 extras, skip, err)) { 497if(mustexist) { 498/* 499 * To the user the relevant error is 500 * that the "mustexist" reference is 501 * missing: 502 */ 503strbuf_reset(err); 504strbuf_addf(err,"unable to resolve reference '%s'", 505 refname); 506}else{ 507/* 508 * The error message set by 509 * refs_verify_refname_available() is 510 * OK. 511 */ 512 ret = TRANSACTION_NAME_CONFLICT; 513} 514}else{ 515/* 516 * The file that is in the way isn't a loose 517 * reference. Report it as a low-level 518 * failure. 519 */ 520strbuf_addf(err,"unable to create lock file%s.lock; " 521"non-directory in the way", 522 ref_file.buf); 523} 524goto error_return; 525case SCLD_VANISHED: 526/* Maybe another process was tidying up. Try again. */ 527if(--attempts_remaining >0) 528goto retry; 529/* fall through */ 530default: 531strbuf_addf(err,"unable to create directory for%s", 532 ref_file.buf); 533goto error_return; 534} 535 536if(!lock->lk) 537 lock->lk =xcalloc(1,sizeof(struct lock_file)); 538 539if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 540if(errno == ENOENT && --attempts_remaining >0) { 541/* 542 * Maybe somebody just deleted one of the 543 * directories leading to ref_file. Try 544 * again: 545 */ 546goto retry; 547}else{ 548unable_to_lock_message(ref_file.buf, errno, err); 549goto error_return; 550} 551} 552 553/* 554 * Now we hold the lock and can read the reference without 555 * fear that its value will change. 556 */ 557 558if(files_read_raw_ref(&refs->base, refname, 559 lock->old_oid.hash, referent, type)) { 560if(errno == ENOENT) { 561if(mustexist) { 562/* Garden variety missing reference. */ 563strbuf_addf(err,"unable to resolve reference '%s'", 564 refname); 565goto error_return; 566}else{ 567/* 568 * Reference is missing, but that's OK. We 569 * know that there is not a conflict with 570 * another loose reference because 571 * (supposing that we are trying to lock 572 * reference "refs/foo/bar"): 573 * 574 * - We were successfully able to create 575 * the lockfile refs/foo/bar.lock, so we 576 * know there cannot be a loose reference 577 * named "refs/foo". 578 * 579 * - We got ENOENT and not EISDIR, so we 580 * know that there cannot be a loose 581 * reference named "refs/foo/bar/baz". 582 */ 583} 584}else if(errno == EISDIR) { 585/* 586 * There is a directory in the way. It might have 587 * contained references that have been deleted. If 588 * we don't require that the reference already 589 * exists, try to remove the directory so that it 590 * doesn't cause trouble when we want to rename the 591 * lockfile into place later. 592 */ 593if(mustexist) { 594/* Garden variety missing reference. */ 595strbuf_addf(err,"unable to resolve reference '%s'", 596 refname); 597goto error_return; 598}else if(remove_dir_recursively(&ref_file, 599 REMOVE_DIR_EMPTY_ONLY)) { 600if(refs_verify_refname_available( 601&refs->base, refname, 602 extras, skip, err)) { 603/* 604 * The error message set by 605 * verify_refname_available() is OK. 606 */ 607 ret = TRANSACTION_NAME_CONFLICT; 608goto error_return; 609}else{ 610/* 611 * We can't delete the directory, 612 * but we also don't know of any 613 * references that it should 614 * contain. 615 */ 616strbuf_addf(err,"there is a non-empty directory '%s' " 617"blocking reference '%s'", 618 ref_file.buf, refname); 619goto error_return; 620} 621} 622}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 623strbuf_addf(err,"unable to resolve reference '%s': " 624"reference broken", refname); 625goto error_return; 626}else{ 627strbuf_addf(err,"unable to resolve reference '%s':%s", 628 refname,strerror(errno)); 629goto error_return; 630} 631 632/* 633 * If the ref did not exist and we are creating it, 634 * make sure there is no existing ref that conflicts 635 * with refname: 636 */ 637if(refs_verify_refname_available( 638&refs->base, refname, 639 extras, skip, err)) 640goto error_return; 641} 642 643 ret =0; 644goto out; 645 646error_return: 647unlock_ref(lock); 648*lock_p = NULL; 649 650out: 651strbuf_release(&ref_file); 652return ret; 653} 654 655static intfiles_peel_ref(struct ref_store *ref_store, 656const char*refname,unsigned char*sha1) 657{ 658struct files_ref_store *refs = 659files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 660"peel_ref"); 661int flag; 662unsigned char base[20]; 663 664if(current_ref_iter && current_ref_iter->refname == refname) { 665struct object_id peeled; 666 667if(ref_iterator_peel(current_ref_iter, &peeled)) 668return-1; 669hashcpy(sha1, peeled.hash); 670return0; 671} 672 673if(refs_read_ref_full(ref_store, refname, 674 RESOLVE_REF_READING, base, &flag)) 675return-1; 676 677/* 678 * If the reference is packed, read its ref_entry from the 679 * cache in the hope that we already know its peeled value. 680 * We only try this optimization on packed references because 681 * (a) forcing the filling of the loose reference cache could 682 * be expensive and (b) loose references anyway usually do not 683 * have REF_KNOWS_PEELED. 684 */ 685if(flag & REF_ISPACKED && 686!refs_peel_ref(refs->packed_ref_store, refname, sha1)) 687return0; 688 689returnpeel_object(base, sha1); 690} 691 692struct files_ref_iterator { 693struct ref_iterator base; 694 695struct ref_iterator *iter0; 696unsigned int flags; 697}; 698 699static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 700{ 701struct files_ref_iterator *iter = 702(struct files_ref_iterator *)ref_iterator; 703int ok; 704 705while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 706if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 707ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE) 708continue; 709 710if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 711!ref_resolves_to_object(iter->iter0->refname, 712 iter->iter0->oid, 713 iter->iter0->flags)) 714continue; 715 716 iter->base.refname = iter->iter0->refname; 717 iter->base.oid = iter->iter0->oid; 718 iter->base.flags = iter->iter0->flags; 719return ITER_OK; 720} 721 722 iter->iter0 = NULL; 723if(ref_iterator_abort(ref_iterator) != ITER_DONE) 724 ok = ITER_ERROR; 725 726return ok; 727} 728 729static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator, 730struct object_id *peeled) 731{ 732struct files_ref_iterator *iter = 733(struct files_ref_iterator *)ref_iterator; 734 735returnref_iterator_peel(iter->iter0, peeled); 736} 737 738static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator) 739{ 740struct files_ref_iterator *iter = 741(struct files_ref_iterator *)ref_iterator; 742int ok = ITER_DONE; 743 744if(iter->iter0) 745 ok =ref_iterator_abort(iter->iter0); 746 747base_ref_iterator_free(ref_iterator); 748return ok; 749} 750 751static struct ref_iterator_vtable files_ref_iterator_vtable = { 752 files_ref_iterator_advance, 753 files_ref_iterator_peel, 754 files_ref_iterator_abort 755}; 756 757static struct ref_iterator *files_ref_iterator_begin( 758struct ref_store *ref_store, 759const char*prefix,unsigned int flags) 760{ 761struct files_ref_store *refs; 762struct ref_iterator *loose_iter, *packed_iter; 763struct files_ref_iterator *iter; 764struct ref_iterator *ref_iterator; 765unsigned int required_flags = REF_STORE_READ; 766 767if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) 768 required_flags |= REF_STORE_ODB; 769 770 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin"); 771 772 iter =xcalloc(1,sizeof(*iter)); 773 ref_iterator = &iter->base; 774base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable); 775 776/* 777 * We must make sure that all loose refs are read before 778 * accessing the packed-refs file; this avoids a race 779 * condition if loose refs are migrated to the packed-refs 780 * file by a simultaneous process, but our in-memory view is 781 * from before the migration. We ensure this as follows: 782 * First, we call start the loose refs iteration with its 783 * `prime_ref` argument set to true. This causes the loose 784 * references in the subtree to be pre-read into the cache. 785 * (If they've already been read, that's OK; we only need to 786 * guarantee that they're read before the packed refs, not 787 * *how much* before.) After that, we call 788 * packed_ref_iterator_begin(), which internally checks 789 * whether the packed-ref cache is up to date with what is on 790 * disk, and re-reads it if not. 791 */ 792 793 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), 794 prefix,1); 795 796/* 797 * The packed-refs file might contain broken references, for 798 * example an old version of a reference that points at an 799 * object that has since been garbage-collected. This is OK as 800 * long as there is a corresponding loose reference that 801 * overrides it, and we don't want to emit an error message in 802 * this case. So ask the packed_ref_store for all of its 803 * references, and (if needed) do our own check for broken 804 * ones in files_ref_iterator_advance(), after we have merged 805 * the packed and loose references. 806 */ 807 packed_iter =refs_ref_iterator_begin( 808 refs->packed_ref_store, prefix,0, 809 DO_FOR_EACH_INCLUDE_BROKEN); 810 811 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter); 812 iter->flags = flags; 813 814return ref_iterator; 815} 816 817/* 818 * Verify that the reference locked by lock has the value old_sha1. 819 * Fail if the reference doesn't exist and mustexist is set. Return 0 820 * on success. On error, write an error message to err, set errno, and 821 * return a negative value. 822 */ 823static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock, 824const unsigned char*old_sha1,int mustexist, 825struct strbuf *err) 826{ 827assert(err); 828 829if(refs_read_ref_full(ref_store, lock->ref_name, 830 mustexist ? RESOLVE_REF_READING :0, 831 lock->old_oid.hash, NULL)) { 832if(old_sha1) { 833int save_errno = errno; 834strbuf_addf(err,"can't verify ref '%s'", lock->ref_name); 835 errno = save_errno; 836return-1; 837}else{ 838oidclr(&lock->old_oid); 839return0; 840} 841} 842if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) { 843strbuf_addf(err,"ref '%s' is at%sbut expected%s", 844 lock->ref_name, 845oid_to_hex(&lock->old_oid), 846sha1_to_hex(old_sha1)); 847 errno = EBUSY; 848return-1; 849} 850return0; 851} 852 853static intremove_empty_directories(struct strbuf *path) 854{ 855/* 856 * we want to create a file but there is a directory there; 857 * if that is an empty directory (or a directory that contains 858 * only empty directories), remove them. 859 */ 860returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY); 861} 862 863static intcreate_reflock(const char*path,void*cb) 864{ 865struct lock_file *lk = cb; 866 867returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0; 868} 869 870/* 871 * Locks a ref returning the lock on success and NULL on failure. 872 * On failure errno is set to something meaningful. 873 */ 874static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs, 875const char*refname, 876const unsigned char*old_sha1, 877const struct string_list *extras, 878const struct string_list *skip, 879unsigned int flags,int*type, 880struct strbuf *err) 881{ 882struct strbuf ref_file = STRBUF_INIT; 883struct ref_lock *lock; 884int last_errno =0; 885int mustexist = (old_sha1 && !is_null_sha1(old_sha1)); 886int resolve_flags = RESOLVE_REF_NO_RECURSE; 887int resolved; 888 889files_assert_main_repository(refs,"lock_ref_sha1_basic"); 890assert(err); 891 892 lock =xcalloc(1,sizeof(struct ref_lock)); 893 894if(mustexist) 895 resolve_flags |= RESOLVE_REF_READING; 896if(flags & REF_DELETING) 897 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME; 898 899files_ref_path(refs, &ref_file, refname); 900 resolved = !!refs_resolve_ref_unsafe(&refs->base, 901 refname, resolve_flags, 902 lock->old_oid.hash, type); 903if(!resolved && errno == EISDIR) { 904/* 905 * we are trying to lock foo but we used to 906 * have foo/bar which now does not exist; 907 * it is normal for the empty directory 'foo' 908 * to remain. 909 */ 910if(remove_empty_directories(&ref_file)) { 911 last_errno = errno; 912if(!refs_verify_refname_available( 913&refs->base, 914 refname, extras, skip, err)) 915strbuf_addf(err,"there are still refs under '%s'", 916 refname); 917goto error_return; 918} 919 resolved = !!refs_resolve_ref_unsafe(&refs->base, 920 refname, resolve_flags, 921 lock->old_oid.hash, type); 922} 923if(!resolved) { 924 last_errno = errno; 925if(last_errno != ENOTDIR || 926!refs_verify_refname_available(&refs->base, refname, 927 extras, skip, err)) 928strbuf_addf(err,"unable to resolve reference '%s':%s", 929 refname,strerror(last_errno)); 930 931goto error_return; 932} 933 934/* 935 * If the ref did not exist and we are creating it, make sure 936 * there is no existing packed ref whose name begins with our 937 * refname, nor a packed ref whose name is a proper prefix of 938 * our refname. 939 */ 940if(is_null_oid(&lock->old_oid) && 941refs_verify_refname_available(&refs->base, refname, 942 extras, skip, err)) { 943 last_errno = ENOTDIR; 944goto error_return; 945} 946 947 lock->lk =xcalloc(1,sizeof(struct lock_file)); 948 949 lock->ref_name =xstrdup(refname); 950 951if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) { 952 last_errno = errno; 953unable_to_lock_message(ref_file.buf, errno, err); 954goto error_return; 955} 956 957if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) { 958 last_errno = errno; 959goto error_return; 960} 961goto out; 962 963 error_return: 964unlock_ref(lock); 965 lock = NULL; 966 967 out: 968strbuf_release(&ref_file); 969 errno = last_errno; 970return lock; 971} 972 973struct ref_to_prune { 974struct ref_to_prune *next; 975unsigned char sha1[20]; 976char name[FLEX_ARRAY]; 977}; 978 979enum{ 980 REMOVE_EMPTY_PARENTS_REF =0x01, 981 REMOVE_EMPTY_PARENTS_REFLOG =0x02 982}; 983 984/* 985 * Remove empty parent directories associated with the specified 986 * reference and/or its reflog, but spare [logs/]refs/ and immediate 987 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or 988 * REMOVE_EMPTY_PARENTS_REFLOG. 989 */ 990static voidtry_remove_empty_parents(struct files_ref_store *refs, 991const char*refname, 992unsigned int flags) 993{ 994struct strbuf buf = STRBUF_INIT; 995struct strbuf sb = STRBUF_INIT; 996char*p, *q; 997int i; 998 999strbuf_addstr(&buf, refname);1000 p = buf.buf;1001for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */1002while(*p && *p !='/')1003 p++;1004/* tolerate duplicate slashes; see check_refname_format() */1005while(*p =='/')1006 p++;1007}1008 q = buf.buf + buf.len;1009while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1010while(q > p && *q !='/')1011 q--;1012while(q > p && *(q-1) =='/')1013 q--;1014if(q == p)1015break;1016strbuf_setlen(&buf, q - buf.buf);10171018strbuf_reset(&sb);1019files_ref_path(refs, &sb, buf.buf);1020if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1021 flags &= ~REMOVE_EMPTY_PARENTS_REF;10221023strbuf_reset(&sb);1024files_reflog_path(refs, &sb, buf.buf);1025if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1026 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1027}1028strbuf_release(&buf);1029strbuf_release(&sb);1030}10311032/* make sure nobody touched the ref, and unlink */1033static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1034{1035struct ref_transaction *transaction;1036struct strbuf err = STRBUF_INIT;10371038if(check_refname_format(r->name,0))1039return;10401041 transaction =ref_store_transaction_begin(&refs->base, &err);1042if(!transaction ||1043ref_transaction_delete(transaction, r->name, r->sha1,1044 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1045ref_transaction_commit(transaction, &err)) {1046ref_transaction_free(transaction);1047error("%s", err.buf);1048strbuf_release(&err);1049return;1050}1051ref_transaction_free(transaction);1052strbuf_release(&err);1053}10541055static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1056{1057while(r) {1058prune_ref(refs, r);1059 r = r->next;1060}1061}10621063/*1064 * Return true if the specified reference should be packed.1065 */1066static intshould_pack_ref(const char*refname,1067const struct object_id *oid,unsigned int ref_flags,1068unsigned int pack_flags)1069{1070/* Do not pack per-worktree refs: */1071if(ref_type(refname) != REF_TYPE_NORMAL)1072return0;10731074/* Do not pack non-tags unless PACK_REFS_ALL is set: */1075if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1076return0;10771078/* Do not pack symbolic refs: */1079if(ref_flags & REF_ISSYMREF)1080return0;10811082/* Do not pack broken refs: */1083if(!ref_resolves_to_object(refname, oid, ref_flags))1084return0;10851086return1;1087}10881089static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1090{1091struct files_ref_store *refs =1092files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1093"pack_refs");1094struct ref_iterator *iter;1095int ok;1096struct ref_to_prune *refs_to_prune = NULL;1097struct strbuf err = STRBUF_INIT;10981099packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR);11001101 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1102while((ok =ref_iterator_advance(iter)) == ITER_OK) {1103/*1104 * If the loose reference can be packed, add an entry1105 * in the packed ref cache. If the reference should be1106 * pruned, also add it to refs_to_prune.1107 */1108if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1109 flags))1110continue;11111112/*1113 * Create an entry in the packed-refs cache equivalent1114 * to the one from the loose ref cache, except that1115 * we don't copy the peeled status, because we want it1116 * to be re-peeled.1117 */1118add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);11191120/* Schedule the loose reference for pruning if requested. */1121if((flags & PACK_REFS_PRUNE)) {1122struct ref_to_prune *n;1123FLEX_ALLOC_STR(n, name, iter->refname);1124hashcpy(n->sha1, iter->oid->hash);1125 n->next = refs_to_prune;1126 refs_to_prune = n;1127}1128}1129if(ok != ITER_DONE)1130die("error while iterating over references");11311132if(commit_packed_refs(refs->packed_ref_store, &err))1133die("unable to overwrite old ref-pack file:%s", err.buf);11341135prune_refs(refs, refs_to_prune);1136strbuf_release(&err);1137return0;1138}11391140static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1141struct string_list *refnames,unsigned int flags)1142{1143struct files_ref_store *refs =1144files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1145struct strbuf err = STRBUF_INIT;1146int i, result =0;11471148if(!refnames->nr)1149return0;11501151 result =repack_without_refs(refs->packed_ref_store, refnames, &err);1152if(result) {1153/*1154 * If we failed to rewrite the packed-refs file, then1155 * it is unsafe to try to remove loose refs, because1156 * doing so might expose an obsolete packed value for1157 * a reference that might even point at an object that1158 * has been garbage collected.1159 */1160if(refnames->nr ==1)1161error(_("could not delete reference%s:%s"),1162 refnames->items[0].string, err.buf);1163else1164error(_("could not delete references:%s"), err.buf);11651166goto out;1167}11681169for(i =0; i < refnames->nr; i++) {1170const char*refname = refnames->items[i].string;11711172if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1173 result |=error(_("could not remove reference%s"), refname);1174}11751176out:1177strbuf_release(&err);1178return result;1179}11801181/*1182 * People using contrib's git-new-workdir have .git/logs/refs ->1183 * /some/other/path/.git/logs/refs, and that may live on another device.1184 *1185 * IOW, to avoid cross device rename errors, the temporary renamed log must1186 * live into logs/refs.1187 */1188#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"11891190struct rename_cb {1191const char*tmp_renamed_log;1192int true_errno;1193};11941195static intrename_tmp_log_callback(const char*path,void*cb_data)1196{1197struct rename_cb *cb = cb_data;11981199if(rename(cb->tmp_renamed_log, path)) {1200/*1201 * rename(a, b) when b is an existing directory ought1202 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1203 * Sheesh. Record the true errno for error reporting,1204 * but report EISDIR to raceproof_create_file() so1205 * that it knows to retry.1206 */1207 cb->true_errno = errno;1208if(errno == ENOTDIR)1209 errno = EISDIR;1210return-1;1211}else{1212return0;1213}1214}12151216static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1217{1218struct strbuf path = STRBUF_INIT;1219struct strbuf tmp = STRBUF_INIT;1220struct rename_cb cb;1221int ret;12221223files_reflog_path(refs, &path, newrefname);1224files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1225 cb.tmp_renamed_log = tmp.buf;1226 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1227if(ret) {1228if(errno == EISDIR)1229error("directory not empty:%s", path.buf);1230else1231error("unable to move logfile%sto%s:%s",1232 tmp.buf, path.buf,1233strerror(cb.true_errno));1234}12351236strbuf_release(&path);1237strbuf_release(&tmp);1238return ret;1239}12401241static intwrite_ref_to_lockfile(struct ref_lock *lock,1242const struct object_id *oid,struct strbuf *err);1243static intcommit_ref_update(struct files_ref_store *refs,1244struct ref_lock *lock,1245const struct object_id *oid,const char*logmsg,1246struct strbuf *err);12471248static intfiles_rename_ref(struct ref_store *ref_store,1249const char*oldrefname,const char*newrefname,1250const char*logmsg)1251{1252struct files_ref_store *refs =1253files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1254struct object_id oid, orig_oid;1255int flag =0, logmoved =0;1256struct ref_lock *lock;1257struct stat loginfo;1258struct strbuf sb_oldref = STRBUF_INIT;1259struct strbuf sb_newref = STRBUF_INIT;1260struct strbuf tmp_renamed_log = STRBUF_INIT;1261int log, ret;1262struct strbuf err = STRBUF_INIT;12631264files_reflog_path(refs, &sb_oldref, oldrefname);1265files_reflog_path(refs, &sb_newref, newrefname);1266files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12671268 log = !lstat(sb_oldref.buf, &loginfo);1269if(log &&S_ISLNK(loginfo.st_mode)) {1270 ret =error("reflog for%sis a symlink", oldrefname);1271goto out;1272}12731274if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1275 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1276 orig_oid.hash, &flag)) {1277 ret =error("refname%snot found", oldrefname);1278goto out;1279}12801281if(flag & REF_ISSYMREF) {1282 ret =error("refname%sis a symbolic ref, renaming it is not supported",1283 oldrefname);1284goto out;1285}1286if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1287 ret =1;1288goto out;1289}12901291if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1292 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1293 oldrefname,strerror(errno));1294goto out;1295}12961297if(refs_delete_ref(&refs->base, logmsg, oldrefname,1298 orig_oid.hash, REF_NODEREF)) {1299error("unable to delete old%s", oldrefname);1300goto rollback;1301}13021303/*1304 * Since we are doing a shallow lookup, oid is not the1305 * correct value to pass to delete_ref as old_oid. But that1306 * doesn't matter, because an old_oid check wouldn't add to1307 * the safety anyway; we want to delete the reference whatever1308 * its current value.1309 */1310if(!refs_read_ref_full(&refs->base, newrefname,1311 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1312 oid.hash, NULL) &&1313refs_delete_ref(&refs->base, NULL, newrefname,1314 NULL, REF_NODEREF)) {1315if(errno == EISDIR) {1316struct strbuf path = STRBUF_INIT;1317int result;13181319files_ref_path(refs, &path, newrefname);1320 result =remove_empty_directories(&path);1321strbuf_release(&path);13221323if(result) {1324error("Directory not empty:%s", newrefname);1325goto rollback;1326}1327}else{1328error("unable to delete existing%s", newrefname);1329goto rollback;1330}1331}13321333if(log &&rename_tmp_log(refs, newrefname))1334goto rollback;13351336 logmoved = log;13371338 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1339 REF_NODEREF, NULL, &err);1340if(!lock) {1341error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1342strbuf_release(&err);1343goto rollback;1344}1345oidcpy(&lock->old_oid, &orig_oid);13461347if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1348commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1349error("unable to write current sha1 into%s:%s", newrefname, err.buf);1350strbuf_release(&err);1351goto rollback;1352}13531354 ret =0;1355goto out;13561357 rollback:1358 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1359 REF_NODEREF, NULL, &err);1360if(!lock) {1361error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1362strbuf_release(&err);1363goto rollbacklog;1364}13651366 flag = log_all_ref_updates;1367 log_all_ref_updates = LOG_REFS_NONE;1368if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1369commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1370error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1371strbuf_release(&err);1372}1373 log_all_ref_updates = flag;13741375 rollbacklog:1376if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1377error("unable to restore logfile%sfrom%s:%s",1378 oldrefname, newrefname,strerror(errno));1379if(!logmoved && log &&1380rename(tmp_renamed_log.buf, sb_oldref.buf))1381error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1382 oldrefname,strerror(errno));1383 ret =1;1384 out:1385strbuf_release(&sb_newref);1386strbuf_release(&sb_oldref);1387strbuf_release(&tmp_renamed_log);13881389return ret;1390}13911392static intclose_ref(struct ref_lock *lock)1393{1394if(close_lock_file(lock->lk))1395return-1;1396return0;1397}13981399static intcommit_ref(struct ref_lock *lock)1400{1401char*path =get_locked_file_path(lock->lk);1402struct stat st;14031404if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1405/*1406 * There is a directory at the path we want to rename1407 * the lockfile to. Hopefully it is empty; try to1408 * delete it.1409 */1410size_t len =strlen(path);1411struct strbuf sb_path = STRBUF_INIT;14121413strbuf_attach(&sb_path, path, len, len);14141415/*1416 * If this fails, commit_lock_file() will also fail1417 * and will report the problem.1418 */1419remove_empty_directories(&sb_path);1420strbuf_release(&sb_path);1421}else{1422free(path);1423}14241425if(commit_lock_file(lock->lk))1426return-1;1427return0;1428}14291430static intopen_or_create_logfile(const char*path,void*cb)1431{1432int*fd = cb;14331434*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1435return(*fd <0) ? -1:0;1436}14371438/*1439 * Create a reflog for a ref. If force_create = 0, only create the1440 * reflog for certain refs (those for which should_autocreate_reflog1441 * returns non-zero). Otherwise, create it regardless of the reference1442 * name. If the logfile already existed or was created, return 0 and1443 * set *logfd to the file descriptor opened for appending to the file.1444 * If no logfile exists and we decided not to create one, return 0 and1445 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1446 * return -1.1447 */1448static intlog_ref_setup(struct files_ref_store *refs,1449const char*refname,int force_create,1450int*logfd,struct strbuf *err)1451{1452struct strbuf logfile_sb = STRBUF_INIT;1453char*logfile;14541455files_reflog_path(refs, &logfile_sb, refname);1456 logfile =strbuf_detach(&logfile_sb, NULL);14571458if(force_create ||should_autocreate_reflog(refname)) {1459if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1460if(errno == ENOENT)1461strbuf_addf(err,"unable to create directory for '%s': "1462"%s", logfile,strerror(errno));1463else if(errno == EISDIR)1464strbuf_addf(err,"there are still logs under '%s'",1465 logfile);1466else1467strbuf_addf(err,"unable to append to '%s':%s",1468 logfile,strerror(errno));14691470goto error;1471}1472}else{1473*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1474if(*logfd <0) {1475if(errno == ENOENT || errno == EISDIR) {1476/*1477 * The logfile doesn't already exist,1478 * but that is not an error; it only1479 * means that we won't write log1480 * entries to it.1481 */1482;1483}else{1484strbuf_addf(err,"unable to append to '%s':%s",1485 logfile,strerror(errno));1486goto error;1487}1488}1489}14901491if(*logfd >=0)1492adjust_shared_perm(logfile);14931494free(logfile);1495return0;14961497error:1498free(logfile);1499return-1;1500}15011502static intfiles_create_reflog(struct ref_store *ref_store,1503const char*refname,int force_create,1504struct strbuf *err)1505{1506struct files_ref_store *refs =1507files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1508int fd;15091510if(log_ref_setup(refs, refname, force_create, &fd, err))1511return-1;15121513if(fd >=0)1514close(fd);15151516return0;1517}15181519static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1520const struct object_id *new_oid,1521const char*committer,const char*msg)1522{1523int msglen, written;1524unsigned maxlen, len;1525char*logrec;15261527 msglen = msg ?strlen(msg) :0;1528 maxlen =strlen(committer) + msglen +100;1529 logrec =xmalloc(maxlen);1530 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1531oid_to_hex(old_oid),1532oid_to_hex(new_oid),1533 committer);1534if(msglen)1535 len +=copy_reflog_msg(logrec + len -1, msg) -1;15361537 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1538free(logrec);1539if(written != len)1540return-1;15411542return0;1543}15441545static intfiles_log_ref_write(struct files_ref_store *refs,1546const char*refname,const struct object_id *old_oid,1547const struct object_id *new_oid,const char*msg,1548int flags,struct strbuf *err)1549{1550int logfd, result;15511552if(log_all_ref_updates == LOG_REFS_UNSET)1553 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15541555 result =log_ref_setup(refs, refname,1556 flags & REF_FORCE_CREATE_REFLOG,1557&logfd, err);15581559if(result)1560return result;15611562if(logfd <0)1563return0;1564 result =log_ref_write_fd(logfd, old_oid, new_oid,1565git_committer_info(0), msg);1566if(result) {1567struct strbuf sb = STRBUF_INIT;1568int save_errno = errno;15691570files_reflog_path(refs, &sb, refname);1571strbuf_addf(err,"unable to append to '%s':%s",1572 sb.buf,strerror(save_errno));1573strbuf_release(&sb);1574close(logfd);1575return-1;1576}1577if(close(logfd)) {1578struct strbuf sb = STRBUF_INIT;1579int save_errno = errno;15801581files_reflog_path(refs, &sb, refname);1582strbuf_addf(err,"unable to append to '%s':%s",1583 sb.buf,strerror(save_errno));1584strbuf_release(&sb);1585return-1;1586}1587return0;1588}15891590/*1591 * Write sha1 into the open lockfile, then close the lockfile. On1592 * errors, rollback the lockfile, fill in *err and1593 * return -1.1594 */1595static intwrite_ref_to_lockfile(struct ref_lock *lock,1596const struct object_id *oid,struct strbuf *err)1597{1598static char term ='\n';1599struct object *o;1600int fd;16011602 o =parse_object(oid);1603if(!o) {1604strbuf_addf(err,1605"trying to write ref '%s' with nonexistent object%s",1606 lock->ref_name,oid_to_hex(oid));1607unlock_ref(lock);1608return-1;1609}1610if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1611strbuf_addf(err,1612"trying to write non-commit object%sto branch '%s'",1613oid_to_hex(oid), lock->ref_name);1614unlock_ref(lock);1615return-1;1616}1617 fd =get_lock_file_fd(lock->lk);1618if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1619write_in_full(fd, &term,1) !=1||1620close_ref(lock) <0) {1621strbuf_addf(err,1622"couldn't write '%s'",get_lock_file_path(lock->lk));1623unlock_ref(lock);1624return-1;1625}1626return0;1627}16281629/*1630 * Commit a change to a loose reference that has already been written1631 * to the loose reference lockfile. Also update the reflogs if1632 * necessary, using the specified lockmsg (which can be NULL).1633 */1634static intcommit_ref_update(struct files_ref_store *refs,1635struct ref_lock *lock,1636const struct object_id *oid,const char*logmsg,1637struct strbuf *err)1638{1639files_assert_main_repository(refs,"commit_ref_update");16401641clear_loose_ref_cache(refs);1642if(files_log_ref_write(refs, lock->ref_name,1643&lock->old_oid, oid,1644 logmsg,0, err)) {1645char*old_msg =strbuf_detach(err, NULL);1646strbuf_addf(err,"cannot update the ref '%s':%s",1647 lock->ref_name, old_msg);1648free(old_msg);1649unlock_ref(lock);1650return-1;1651}16521653if(strcmp(lock->ref_name,"HEAD") !=0) {1654/*1655 * Special hack: If a branch is updated directly and HEAD1656 * points to it (may happen on the remote side of a push1657 * for example) then logically the HEAD reflog should be1658 * updated too.1659 * A generic solution implies reverse symref information,1660 * but finding all symrefs pointing to the given branch1661 * would be rather costly for this rare event (the direct1662 * update of a branch) to be worth it. So let's cheat and1663 * check with HEAD only which should cover 99% of all usage1664 * scenarios (even 100% of the default ones).1665 */1666struct object_id head_oid;1667int head_flag;1668const char*head_ref;16691670 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1671 RESOLVE_REF_READING,1672 head_oid.hash, &head_flag);1673if(head_ref && (head_flag & REF_ISSYMREF) &&1674!strcmp(head_ref, lock->ref_name)) {1675struct strbuf log_err = STRBUF_INIT;1676if(files_log_ref_write(refs,"HEAD",1677&lock->old_oid, oid,1678 logmsg,0, &log_err)) {1679error("%s", log_err.buf);1680strbuf_release(&log_err);1681}1682}1683}16841685if(commit_ref(lock)) {1686strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1687unlock_ref(lock);1688return-1;1689}16901691unlock_ref(lock);1692return0;1693}16941695static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1696{1697int ret = -1;1698#ifndef NO_SYMLINK_HEAD1699char*ref_path =get_locked_file_path(lock->lk);1700unlink(ref_path);1701 ret =symlink(target, ref_path);1702free(ref_path);17031704if(ret)1705fprintf(stderr,"no symlink - falling back to symbolic ref\n");1706#endif1707return ret;1708}17091710static voidupdate_symref_reflog(struct files_ref_store *refs,1711struct ref_lock *lock,const char*refname,1712const char*target,const char*logmsg)1713{1714struct strbuf err = STRBUF_INIT;1715struct object_id new_oid;1716if(logmsg &&1717!refs_read_ref_full(&refs->base, target,1718 RESOLVE_REF_READING, new_oid.hash, NULL) &&1719files_log_ref_write(refs, refname, &lock->old_oid,1720&new_oid, logmsg,0, &err)) {1721error("%s", err.buf);1722strbuf_release(&err);1723}1724}17251726static intcreate_symref_locked(struct files_ref_store *refs,1727struct ref_lock *lock,const char*refname,1728const char*target,const char*logmsg)1729{1730if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1731update_symref_reflog(refs, lock, refname, target, logmsg);1732return0;1733}17341735if(!fdopen_lock_file(lock->lk,"w"))1736returnerror("unable to fdopen%s:%s",1737 lock->lk->tempfile.filename.buf,strerror(errno));17381739update_symref_reflog(refs, lock, refname, target, logmsg);17401741/* no error check; commit_ref will check ferror */1742fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);1743if(commit_ref(lock) <0)1744returnerror("unable to write symref for%s:%s", refname,1745strerror(errno));1746return0;1747}17481749static intfiles_create_symref(struct ref_store *ref_store,1750const char*refname,const char*target,1751const char*logmsg)1752{1753struct files_ref_store *refs =1754files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1755struct strbuf err = STRBUF_INIT;1756struct ref_lock *lock;1757int ret;17581759 lock =lock_ref_sha1_basic(refs, refname, NULL,1760 NULL, NULL, REF_NODEREF, NULL,1761&err);1762if(!lock) {1763error("%s", err.buf);1764strbuf_release(&err);1765return-1;1766}17671768 ret =create_symref_locked(refs, lock, refname, target, logmsg);1769unlock_ref(lock);1770return ret;1771}17721773static intfiles_reflog_exists(struct ref_store *ref_store,1774const char*refname)1775{1776struct files_ref_store *refs =1777files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1778struct strbuf sb = STRBUF_INIT;1779struct stat st;1780int ret;17811782files_reflog_path(refs, &sb, refname);1783 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1784strbuf_release(&sb);1785return ret;1786}17871788static intfiles_delete_reflog(struct ref_store *ref_store,1789const char*refname)1790{1791struct files_ref_store *refs =1792files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1793struct strbuf sb = STRBUF_INIT;1794int ret;17951796files_reflog_path(refs, &sb, refname);1797 ret =remove_path(sb.buf);1798strbuf_release(&sb);1799return ret;1800}18011802static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1803{1804struct object_id ooid, noid;1805char*email_end, *message;1806 timestamp_t timestamp;1807int tz;1808const char*p = sb->buf;18091810/* old SP new SP name <email> SP time TAB msg LF */1811if(!sb->len || sb->buf[sb->len -1] !='\n'||1812parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1813parse_oid_hex(p, &noid, &p) || *p++ !=' '||1814!(email_end =strchr(p,'>')) ||1815 email_end[1] !=' '||1816!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1817!message || message[0] !=' '||1818(message[1] !='+'&& message[1] !='-') ||1819!isdigit(message[2]) || !isdigit(message[3]) ||1820!isdigit(message[4]) || !isdigit(message[5]))1821return0;/* corrupt? */1822 email_end[1] ='\0';1823 tz =strtol(message +1, NULL,10);1824if(message[6] !='\t')1825 message +=6;1826else1827 message +=7;1828returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1829}18301831static char*find_beginning_of_line(char*bob,char*scan)1832{1833while(bob < scan && *(--scan) !='\n')1834;/* keep scanning backwards */1835/*1836 * Return either beginning of the buffer, or LF at the end of1837 * the previous line.1838 */1839return scan;1840}18411842static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1843const char*refname,1844 each_reflog_ent_fn fn,1845void*cb_data)1846{1847struct files_ref_store *refs =1848files_downcast(ref_store, REF_STORE_READ,1849"for_each_reflog_ent_reverse");1850struct strbuf sb = STRBUF_INIT;1851FILE*logfp;1852long pos;1853int ret =0, at_tail =1;18541855files_reflog_path(refs, &sb, refname);1856 logfp =fopen(sb.buf,"r");1857strbuf_release(&sb);1858if(!logfp)1859return-1;18601861/* Jump to the end */1862if(fseek(logfp,0, SEEK_END) <0)1863 ret =error("cannot seek back reflog for%s:%s",1864 refname,strerror(errno));1865 pos =ftell(logfp);1866while(!ret &&0< pos) {1867int cnt;1868size_t nread;1869char buf[BUFSIZ];1870char*endp, *scanp;18711872/* Fill next block from the end */1873 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1874if(fseek(logfp, pos - cnt, SEEK_SET)) {1875 ret =error("cannot seek back reflog for%s:%s",1876 refname,strerror(errno));1877break;1878}1879 nread =fread(buf, cnt,1, logfp);1880if(nread !=1) {1881 ret =error("cannot read%dbytes from reflog for%s:%s",1882 cnt, refname,strerror(errno));1883break;1884}1885 pos -= cnt;18861887 scanp = endp = buf + cnt;1888if(at_tail && scanp[-1] =='\n')1889/* Looking at the final LF at the end of the file */1890 scanp--;1891 at_tail =0;18921893while(buf < scanp) {1894/*1895 * terminating LF of the previous line, or the beginning1896 * of the buffer.1897 */1898char*bp;18991900 bp =find_beginning_of_line(buf, scanp);19011902if(*bp =='\n') {1903/*1904 * The newline is the end of the previous line,1905 * so we know we have complete line starting1906 * at (bp + 1). Prefix it onto any prior data1907 * we collected for the line and process it.1908 */1909strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1910 scanp = bp;1911 endp = bp +1;1912 ret =show_one_reflog_ent(&sb, fn, cb_data);1913strbuf_reset(&sb);1914if(ret)1915break;1916}else if(!pos) {1917/*1918 * We are at the start of the buffer, and the1919 * start of the file; there is no previous1920 * line, and we have everything for this one.1921 * Process it, and we can end the loop.1922 */1923strbuf_splice(&sb,0,0, buf, endp - buf);1924 ret =show_one_reflog_ent(&sb, fn, cb_data);1925strbuf_reset(&sb);1926break;1927}19281929if(bp == buf) {1930/*1931 * We are at the start of the buffer, and there1932 * is more file to read backwards. Which means1933 * we are in the middle of a line. Note that we1934 * may get here even if *bp was a newline; that1935 * just means we are at the exact end of the1936 * previous line, rather than some spot in the1937 * middle.1938 *1939 * Save away what we have to be combined with1940 * the data from the next read.1941 */1942strbuf_splice(&sb,0,0, buf, endp - buf);1943break;1944}1945}19461947}1948if(!ret && sb.len)1949die("BUG: reverse reflog parser had leftover data");19501951fclose(logfp);1952strbuf_release(&sb);1953return ret;1954}19551956static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1957const char*refname,1958 each_reflog_ent_fn fn,void*cb_data)1959{1960struct files_ref_store *refs =1961files_downcast(ref_store, REF_STORE_READ,1962"for_each_reflog_ent");1963FILE*logfp;1964struct strbuf sb = STRBUF_INIT;1965int ret =0;19661967files_reflog_path(refs, &sb, refname);1968 logfp =fopen(sb.buf,"r");1969strbuf_release(&sb);1970if(!logfp)1971return-1;19721973while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1974 ret =show_one_reflog_ent(&sb, fn, cb_data);1975fclose(logfp);1976strbuf_release(&sb);1977return ret;1978}19791980struct files_reflog_iterator {1981struct ref_iterator base;19821983struct ref_store *ref_store;1984struct dir_iterator *dir_iterator;1985struct object_id oid;1986};19871988static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)1989{1990struct files_reflog_iterator *iter =1991(struct files_reflog_iterator *)ref_iterator;1992struct dir_iterator *diter = iter->dir_iterator;1993int ok;19941995while((ok =dir_iterator_advance(diter)) == ITER_OK) {1996int flags;19971998if(!S_ISREG(diter->st.st_mode))1999continue;2000if(diter->basename[0] =='.')2001continue;2002if(ends_with(diter->basename,".lock"))2003continue;20042005if(refs_read_ref_full(iter->ref_store,2006 diter->relative_path,0,2007 iter->oid.hash, &flags)) {2008error("bad ref for%s", diter->path.buf);2009continue;2010}20112012 iter->base.refname = diter->relative_path;2013 iter->base.oid = &iter->oid;2014 iter->base.flags = flags;2015return ITER_OK;2016}20172018 iter->dir_iterator = NULL;2019if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2020 ok = ITER_ERROR;2021return ok;2022}20232024static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2025struct object_id *peeled)2026{2027die("BUG: ref_iterator_peel() called for reflog_iterator");2028}20292030static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2031{2032struct files_reflog_iterator *iter =2033(struct files_reflog_iterator *)ref_iterator;2034int ok = ITER_DONE;20352036if(iter->dir_iterator)2037 ok =dir_iterator_abort(iter->dir_iterator);20382039base_ref_iterator_free(ref_iterator);2040return ok;2041}20422043static struct ref_iterator_vtable files_reflog_iterator_vtable = {2044 files_reflog_iterator_advance,2045 files_reflog_iterator_peel,2046 files_reflog_iterator_abort2047};20482049static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2050{2051struct files_ref_store *refs =2052files_downcast(ref_store, REF_STORE_READ,2053"reflog_iterator_begin");2054struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2055struct ref_iterator *ref_iterator = &iter->base;2056struct strbuf sb = STRBUF_INIT;20572058base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2059files_reflog_path(refs, &sb, NULL);2060 iter->dir_iterator =dir_iterator_begin(sb.buf);2061 iter->ref_store = ref_store;2062strbuf_release(&sb);2063return ref_iterator;2064}20652066/*2067 * If update is a direct update of head_ref (the reference pointed to2068 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2069 */2070static intsplit_head_update(struct ref_update *update,2071struct ref_transaction *transaction,2072const char*head_ref,2073struct string_list *affected_refnames,2074struct strbuf *err)2075{2076struct string_list_item *item;2077struct ref_update *new_update;20782079if((update->flags & REF_LOG_ONLY) ||2080(update->flags & REF_ISPRUNING) ||2081(update->flags & REF_UPDATE_VIA_HEAD))2082return0;20832084if(strcmp(update->refname, head_ref))2085return0;20862087/*2088 * First make sure that HEAD is not already in the2089 * transaction. This insertion is O(N) in the transaction2090 * size, but it happens at most once per transaction.2091 */2092 item =string_list_insert(affected_refnames,"HEAD");2093if(item->util) {2094/* An entry already existed */2095strbuf_addf(err,2096"multiple updates for 'HEAD' (including one "2097"via its referent '%s') are not allowed",2098 update->refname);2099return TRANSACTION_NAME_CONFLICT;2100}21012102 new_update =ref_transaction_add_update(2103 transaction,"HEAD",2104 update->flags | REF_LOG_ONLY | REF_NODEREF,2105 update->new_oid.hash, update->old_oid.hash,2106 update->msg);21072108 item->util = new_update;21092110return0;2111}21122113/*2114 * update is for a symref that points at referent and doesn't have2115 * REF_NODEREF set. Split it into two updates:2116 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2117 * - A new, separate update for the referent reference2118 * Note that the new update will itself be subject to splitting when2119 * the iteration gets to it.2120 */2121static intsplit_symref_update(struct files_ref_store *refs,2122struct ref_update *update,2123const char*referent,2124struct ref_transaction *transaction,2125struct string_list *affected_refnames,2126struct strbuf *err)2127{2128struct string_list_item *item;2129struct ref_update *new_update;2130unsigned int new_flags;21312132/*2133 * First make sure that referent is not already in the2134 * transaction. This insertion is O(N) in the transaction2135 * size, but it happens at most once per symref in a2136 * transaction.2137 */2138 item =string_list_insert(affected_refnames, referent);2139if(item->util) {2140/* An entry already existed */2141strbuf_addf(err,2142"multiple updates for '%s' (including one "2143"via symref '%s') are not allowed",2144 referent, update->refname);2145return TRANSACTION_NAME_CONFLICT;2146}21472148 new_flags = update->flags;2149if(!strcmp(update->refname,"HEAD")) {2150/*2151 * Record that the new update came via HEAD, so that2152 * when we process it, split_head_update() doesn't try2153 * to add another reflog update for HEAD. Note that2154 * this bit will be propagated if the new_update2155 * itself needs to be split.2156 */2157 new_flags |= REF_UPDATE_VIA_HEAD;2158}21592160 new_update =ref_transaction_add_update(2161 transaction, referent, new_flags,2162 update->new_oid.hash, update->old_oid.hash,2163 update->msg);21642165 new_update->parent_update = update;21662167/*2168 * Change the symbolic ref update to log only. Also, it2169 * doesn't need to check its old SHA-1 value, as that will be2170 * done when new_update is processed.2171 */2172 update->flags |= REF_LOG_ONLY | REF_NODEREF;2173 update->flags &= ~REF_HAVE_OLD;21742175 item->util = new_update;21762177return0;2178}21792180/*2181 * Return the refname under which update was originally requested.2182 */2183static const char*original_update_refname(struct ref_update *update)2184{2185while(update->parent_update)2186 update = update->parent_update;21872188return update->refname;2189}21902191/*2192 * Check whether the REF_HAVE_OLD and old_oid values stored in update2193 * are consistent with oid, which is the reference's current value. If2194 * everything is OK, return 0; otherwise, write an error message to2195 * err and return -1.2196 */2197static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2198struct strbuf *err)2199{2200if(!(update->flags & REF_HAVE_OLD) ||2201!oidcmp(oid, &update->old_oid))2202return0;22032204if(is_null_oid(&update->old_oid))2205strbuf_addf(err,"cannot lock ref '%s': "2206"reference already exists",2207original_update_refname(update));2208else if(is_null_oid(oid))2209strbuf_addf(err,"cannot lock ref '%s': "2210"reference is missing but expected%s",2211original_update_refname(update),2212oid_to_hex(&update->old_oid));2213else2214strbuf_addf(err,"cannot lock ref '%s': "2215"is at%sbut expected%s",2216original_update_refname(update),2217oid_to_hex(oid),2218oid_to_hex(&update->old_oid));22192220return-1;2221}22222223/*2224 * Prepare for carrying out update:2225 * - Lock the reference referred to by update.2226 * - Read the reference under lock.2227 * - Check that its old SHA-1 value (if specified) is correct, and in2228 * any case record it in update->lock->old_oid for later use when2229 * writing the reflog.2230 * - If it is a symref update without REF_NODEREF, split it up into a2231 * REF_LOG_ONLY update of the symref and add a separate update for2232 * the referent to transaction.2233 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2234 * update of HEAD.2235 */2236static intlock_ref_for_update(struct files_ref_store *refs,2237struct ref_update *update,2238struct ref_transaction *transaction,2239const char*head_ref,2240struct string_list *affected_refnames,2241struct strbuf *err)2242{2243struct strbuf referent = STRBUF_INIT;2244int mustexist = (update->flags & REF_HAVE_OLD) &&2245!is_null_oid(&update->old_oid);2246int ret;2247struct ref_lock *lock;22482249files_assert_main_repository(refs,"lock_ref_for_update");22502251if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2252 update->flags |= REF_DELETING;22532254if(head_ref) {2255 ret =split_head_update(update, transaction, head_ref,2256 affected_refnames, err);2257if(ret)2258return ret;2259}22602261 ret =lock_raw_ref(refs, update->refname, mustexist,2262 affected_refnames, NULL,2263&lock, &referent,2264&update->type, err);2265if(ret) {2266char*reason;22672268 reason =strbuf_detach(err, NULL);2269strbuf_addf(err,"cannot lock ref '%s':%s",2270original_update_refname(update), reason);2271free(reason);2272return ret;2273}22742275 update->backend_data = lock;22762277if(update->type & REF_ISSYMREF) {2278if(update->flags & REF_NODEREF) {2279/*2280 * We won't be reading the referent as part of2281 * the transaction, so we have to read it here2282 * to record and possibly check old_sha1:2283 */2284if(refs_read_ref_full(&refs->base,2285 referent.buf,0,2286 lock->old_oid.hash, NULL)) {2287if(update->flags & REF_HAVE_OLD) {2288strbuf_addf(err,"cannot lock ref '%s': "2289"error reading reference",2290original_update_refname(update));2291return-1;2292}2293}else if(check_old_oid(update, &lock->old_oid, err)) {2294return TRANSACTION_GENERIC_ERROR;2295}2296}else{2297/*2298 * Create a new update for the reference this2299 * symref is pointing at. Also, we will record2300 * and verify old_sha1 for this update as part2301 * of processing the split-off update, so we2302 * don't have to do it here.2303 */2304 ret =split_symref_update(refs, update,2305 referent.buf, transaction,2306 affected_refnames, err);2307if(ret)2308return ret;2309}2310}else{2311struct ref_update *parent_update;23122313if(check_old_oid(update, &lock->old_oid, err))2314return TRANSACTION_GENERIC_ERROR;23152316/*2317 * If this update is happening indirectly because of a2318 * symref update, record the old SHA-1 in the parent2319 * update:2320 */2321for(parent_update = update->parent_update;2322 parent_update;2323 parent_update = parent_update->parent_update) {2324struct ref_lock *parent_lock = parent_update->backend_data;2325oidcpy(&parent_lock->old_oid, &lock->old_oid);2326}2327}23282329if((update->flags & REF_HAVE_NEW) &&2330!(update->flags & REF_DELETING) &&2331!(update->flags & REF_LOG_ONLY)) {2332if(!(update->type & REF_ISSYMREF) &&2333!oidcmp(&lock->old_oid, &update->new_oid)) {2334/*2335 * The reference already has the desired2336 * value, so we don't need to write it.2337 */2338}else if(write_ref_to_lockfile(lock, &update->new_oid,2339 err)) {2340char*write_err =strbuf_detach(err, NULL);23412342/*2343 * The lock was freed upon failure of2344 * write_ref_to_lockfile():2345 */2346 update->backend_data = NULL;2347strbuf_addf(err,2348"cannot update ref '%s':%s",2349 update->refname, write_err);2350free(write_err);2351return TRANSACTION_GENERIC_ERROR;2352}else{2353 update->flags |= REF_NEEDS_COMMIT;2354}2355}2356if(!(update->flags & REF_NEEDS_COMMIT)) {2357/*2358 * We didn't call write_ref_to_lockfile(), so2359 * the lockfile is still open. Close it to2360 * free up the file descriptor:2361 */2362if(close_ref(lock)) {2363strbuf_addf(err,"couldn't close '%s.lock'",2364 update->refname);2365return TRANSACTION_GENERIC_ERROR;2366}2367}2368return0;2369}23702371/*2372 * Unlock any references in `transaction` that are still locked, and2373 * mark the transaction closed.2374 */2375static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2376{2377size_t i;23782379for(i =0; i < transaction->nr; i++) {2380struct ref_update *update = transaction->updates[i];2381struct ref_lock *lock = update->backend_data;23822383if(lock) {2384unlock_ref(lock);2385 update->backend_data = NULL;2386}2387}23882389 transaction->state = REF_TRANSACTION_CLOSED;2390}23912392static intfiles_transaction_prepare(struct ref_store *ref_store,2393struct ref_transaction *transaction,2394struct strbuf *err)2395{2396struct files_ref_store *refs =2397files_downcast(ref_store, REF_STORE_WRITE,2398"ref_transaction_prepare");2399size_t i;2400int ret =0;2401struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2402char*head_ref = NULL;2403int head_type;2404struct object_id head_oid;24052406assert(err);24072408if(!transaction->nr)2409goto cleanup;24102411/*2412 * Fail if a refname appears more than once in the2413 * transaction. (If we end up splitting up any updates using2414 * split_symref_update() or split_head_update(), those2415 * functions will check that the new updates don't have the2416 * same refname as any existing ones.)2417 */2418for(i =0; i < transaction->nr; i++) {2419struct ref_update *update = transaction->updates[i];2420struct string_list_item *item =2421string_list_append(&affected_refnames, update->refname);24222423/*2424 * We store a pointer to update in item->util, but at2425 * the moment we never use the value of this field2426 * except to check whether it is non-NULL.2427 */2428 item->util = update;2429}2430string_list_sort(&affected_refnames);2431if(ref_update_reject_duplicates(&affected_refnames, err)) {2432 ret = TRANSACTION_GENERIC_ERROR;2433goto cleanup;2434}24352436/*2437 * Special hack: If a branch is updated directly and HEAD2438 * points to it (may happen on the remote side of a push2439 * for example) then logically the HEAD reflog should be2440 * updated too.2441 *2442 * A generic solution would require reverse symref lookups,2443 * but finding all symrefs pointing to a given branch would be2444 * rather costly for this rare event (the direct update of a2445 * branch) to be worth it. So let's cheat and check with HEAD2446 * only, which should cover 99% of all usage scenarios (even2447 * 100% of the default ones).2448 *2449 * So if HEAD is a symbolic reference, then record the name of2450 * the reference that it points to. If we see an update of2451 * head_ref within the transaction, then split_head_update()2452 * arranges for the reflog of HEAD to be updated, too.2453 */2454 head_ref =refs_resolve_refdup(ref_store,"HEAD",2455 RESOLVE_REF_NO_RECURSE,2456 head_oid.hash, &head_type);24572458if(head_ref && !(head_type & REF_ISSYMREF)) {2459free(head_ref);2460 head_ref = NULL;2461}24622463/*2464 * Acquire all locks, verify old values if provided, check2465 * that new values are valid, and write new values to the2466 * lockfiles, ready to be activated. Only keep one lockfile2467 * open at a time to avoid running out of file descriptors.2468 * Note that lock_ref_for_update() might append more updates2469 * to the transaction.2470 */2471for(i =0; i < transaction->nr; i++) {2472struct ref_update *update = transaction->updates[i];24732474 ret =lock_ref_for_update(refs, update, transaction,2475 head_ref, &affected_refnames, err);2476if(ret)2477break;2478}24792480cleanup:2481free(head_ref);2482string_list_clear(&affected_refnames,0);24832484if(ret)2485files_transaction_cleanup(transaction);2486else2487 transaction->state = REF_TRANSACTION_PREPARED;24882489return ret;2490}24912492static intfiles_transaction_finish(struct ref_store *ref_store,2493struct ref_transaction *transaction,2494struct strbuf *err)2495{2496struct files_ref_store *refs =2497files_downcast(ref_store,0,"ref_transaction_finish");2498size_t i;2499int ret =0;2500struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2501struct string_list_item *ref_to_delete;2502struct strbuf sb = STRBUF_INIT;25032504assert(err);25052506if(!transaction->nr) {2507 transaction->state = REF_TRANSACTION_CLOSED;2508return0;2509}25102511/* Perform updates first so live commits remain referenced */2512for(i =0; i < transaction->nr; i++) {2513struct ref_update *update = transaction->updates[i];2514struct ref_lock *lock = update->backend_data;25152516if(update->flags & REF_NEEDS_COMMIT ||2517 update->flags & REF_LOG_ONLY) {2518if(files_log_ref_write(refs,2519 lock->ref_name,2520&lock->old_oid,2521&update->new_oid,2522 update->msg, update->flags,2523 err)) {2524char*old_msg =strbuf_detach(err, NULL);25252526strbuf_addf(err,"cannot update the ref '%s':%s",2527 lock->ref_name, old_msg);2528free(old_msg);2529unlock_ref(lock);2530 update->backend_data = NULL;2531 ret = TRANSACTION_GENERIC_ERROR;2532goto cleanup;2533}2534}2535if(update->flags & REF_NEEDS_COMMIT) {2536clear_loose_ref_cache(refs);2537if(commit_ref(lock)) {2538strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2539unlock_ref(lock);2540 update->backend_data = NULL;2541 ret = TRANSACTION_GENERIC_ERROR;2542goto cleanup;2543}2544}2545}2546/* Perform deletes now that updates are safely completed */2547for(i =0; i < transaction->nr; i++) {2548struct ref_update *update = transaction->updates[i];2549struct ref_lock *lock = update->backend_data;25502551if(update->flags & REF_DELETING &&2552!(update->flags & REF_LOG_ONLY)) {2553if(!(update->type & REF_ISPACKED) ||2554 update->type & REF_ISSYMREF) {2555/* It is a loose reference. */2556strbuf_reset(&sb);2557files_ref_path(refs, &sb, lock->ref_name);2558if(unlink_or_msg(sb.buf, err)) {2559 ret = TRANSACTION_GENERIC_ERROR;2560goto cleanup;2561}2562 update->flags |= REF_DELETED_LOOSE;2563}25642565if(!(update->flags & REF_ISPRUNING))2566string_list_append(&refs_to_delete,2567 lock->ref_name);2568}2569}25702571if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {2572 ret = TRANSACTION_GENERIC_ERROR;2573goto cleanup;2574}25752576/* Delete the reflogs of any references that were deleted: */2577for_each_string_list_item(ref_to_delete, &refs_to_delete) {2578strbuf_reset(&sb);2579files_reflog_path(refs, &sb, ref_to_delete->string);2580if(!unlink_or_warn(sb.buf))2581try_remove_empty_parents(refs, ref_to_delete->string,2582 REMOVE_EMPTY_PARENTS_REFLOG);2583}25842585clear_loose_ref_cache(refs);25862587cleanup:2588files_transaction_cleanup(transaction);25892590for(i =0; i < transaction->nr; i++) {2591struct ref_update *update = transaction->updates[i];25922593if(update->flags & REF_DELETED_LOOSE) {2594/*2595 * The loose reference was deleted. Delete any2596 * empty parent directories. (Note that this2597 * can only work because we have already2598 * removed the lockfile.)2599 */2600try_remove_empty_parents(refs, update->refname,2601 REMOVE_EMPTY_PARENTS_REF);2602}2603}26042605strbuf_release(&sb);2606string_list_clear(&refs_to_delete,0);2607return ret;2608}26092610static intfiles_transaction_abort(struct ref_store *ref_store,2611struct ref_transaction *transaction,2612struct strbuf *err)2613{2614files_transaction_cleanup(transaction);2615return0;2616}26172618static intref_present(const char*refname,2619const struct object_id *oid,int flags,void*cb_data)2620{2621struct string_list *affected_refnames = cb_data;26222623returnstring_list_has_string(affected_refnames, refname);2624}26252626static intfiles_initial_transaction_commit(struct ref_store *ref_store,2627struct ref_transaction *transaction,2628struct strbuf *err)2629{2630struct files_ref_store *refs =2631files_downcast(ref_store, REF_STORE_WRITE,2632"initial_ref_transaction_commit");2633size_t i;2634int ret =0;2635struct string_list affected_refnames = STRING_LIST_INIT_NODUP;26362637assert(err);26382639if(transaction->state != REF_TRANSACTION_OPEN)2640die("BUG: commit called for transaction that is not open");26412642/* Fail if a refname appears more than once in the transaction: */2643for(i =0; i < transaction->nr; i++)2644string_list_append(&affected_refnames,2645 transaction->updates[i]->refname);2646string_list_sort(&affected_refnames);2647if(ref_update_reject_duplicates(&affected_refnames, err)) {2648 ret = TRANSACTION_GENERIC_ERROR;2649goto cleanup;2650}26512652/*2653 * It's really undefined to call this function in an active2654 * repository or when there are existing references: we are2655 * only locking and changing packed-refs, so (1) any2656 * simultaneous processes might try to change a reference at2657 * the same time we do, and (2) any existing loose versions of2658 * the references that we are setting would have precedence2659 * over our values. But some remote helpers create the remote2660 * "HEAD" and "master" branches before calling this function,2661 * so here we really only check that none of the references2662 * that we are creating already exists.2663 */2664if(refs_for_each_rawref(&refs->base, ref_present,2665&affected_refnames))2666die("BUG: initial ref transaction called with existing refs");26672668for(i =0; i < transaction->nr; i++) {2669struct ref_update *update = transaction->updates[i];26702671if((update->flags & REF_HAVE_OLD) &&2672!is_null_oid(&update->old_oid))2673die("BUG: initial ref transaction with old_sha1 set");2674if(refs_verify_refname_available(&refs->base, update->refname,2675&affected_refnames, NULL,2676 err)) {2677 ret = TRANSACTION_NAME_CONFLICT;2678goto cleanup;2679}2680}26812682if(packed_refs_lock(refs->packed_ref_store,0)) {2683strbuf_addf(err,"unable to lock packed-refs file:%s",2684strerror(errno));2685 ret = TRANSACTION_GENERIC_ERROR;2686goto cleanup;2687}26882689for(i =0; i < transaction->nr; i++) {2690struct ref_update *update = transaction->updates[i];26912692if((update->flags & REF_HAVE_NEW) &&2693!is_null_oid(&update->new_oid))2694add_packed_ref(refs->packed_ref_store, update->refname,2695&update->new_oid);2696}26972698if(commit_packed_refs(refs->packed_ref_store, err)) {2699 ret = TRANSACTION_GENERIC_ERROR;2700goto cleanup;2701}27022703cleanup:2704 transaction->state = REF_TRANSACTION_CLOSED;2705string_list_clear(&affected_refnames,0);2706return ret;2707}27082709struct expire_reflog_cb {2710unsigned int flags;2711 reflog_expiry_should_prune_fn *should_prune_fn;2712void*policy_cb;2713FILE*newlog;2714struct object_id last_kept_oid;2715};27162717static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2718const char*email, timestamp_t timestamp,int tz,2719const char*message,void*cb_data)2720{2721struct expire_reflog_cb *cb = cb_data;2722struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;27232724if(cb->flags & EXPIRE_REFLOGS_REWRITE)2725 ooid = &cb->last_kept_oid;27262727if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2728 message, policy_cb)) {2729if(!cb->newlog)2730printf("would prune%s", message);2731else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2732printf("prune%s", message);2733}else{2734if(cb->newlog) {2735fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2736oid_to_hex(ooid),oid_to_hex(noid),2737 email, timestamp, tz, message);2738oidcpy(&cb->last_kept_oid, noid);2739}2740if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2741printf("keep%s", message);2742}2743return0;2744}27452746static intfiles_reflog_expire(struct ref_store *ref_store,2747const char*refname,const unsigned char*sha1,2748unsigned int flags,2749 reflog_expiry_prepare_fn prepare_fn,2750 reflog_expiry_should_prune_fn should_prune_fn,2751 reflog_expiry_cleanup_fn cleanup_fn,2752void*policy_cb_data)2753{2754struct files_ref_store *refs =2755files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2756static struct lock_file reflog_lock;2757struct expire_reflog_cb cb;2758struct ref_lock *lock;2759struct strbuf log_file_sb = STRBUF_INIT;2760char*log_file;2761int status =0;2762int type;2763struct strbuf err = STRBUF_INIT;2764struct object_id oid;27652766memset(&cb,0,sizeof(cb));2767 cb.flags = flags;2768 cb.policy_cb = policy_cb_data;2769 cb.should_prune_fn = should_prune_fn;27702771/*2772 * The reflog file is locked by holding the lock on the2773 * reference itself, plus we might need to update the2774 * reference if --updateref was specified:2775 */2776 lock =lock_ref_sha1_basic(refs, refname, sha1,2777 NULL, NULL, REF_NODEREF,2778&type, &err);2779if(!lock) {2780error("cannot lock ref '%s':%s", refname, err.buf);2781strbuf_release(&err);2782return-1;2783}2784if(!refs_reflog_exists(ref_store, refname)) {2785unlock_ref(lock);2786return0;2787}27882789files_reflog_path(refs, &log_file_sb, refname);2790 log_file =strbuf_detach(&log_file_sb, NULL);2791if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2792/*2793 * Even though holding $GIT_DIR/logs/$reflog.lock has2794 * no locking implications, we use the lock_file2795 * machinery here anyway because it does a lot of the2796 * work we need, including cleaning up if the program2797 * exits unexpectedly.2798 */2799if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2800struct strbuf err = STRBUF_INIT;2801unable_to_lock_message(log_file, errno, &err);2802error("%s", err.buf);2803strbuf_release(&err);2804goto failure;2805}2806 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2807if(!cb.newlog) {2808error("cannot fdopen%s(%s)",2809get_lock_file_path(&reflog_lock),strerror(errno));2810goto failure;2811}2812}28132814hashcpy(oid.hash, sha1);28152816(*prepare_fn)(refname, &oid, cb.policy_cb);2817refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2818(*cleanup_fn)(cb.policy_cb);28192820if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2821/*2822 * It doesn't make sense to adjust a reference pointed2823 * to by a symbolic ref based on expiring entries in2824 * the symbolic reference's reflog. Nor can we update2825 * a reference if there are no remaining reflog2826 * entries.2827 */2828int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2829!(type & REF_ISSYMREF) &&2830!is_null_oid(&cb.last_kept_oid);28312832if(close_lock_file(&reflog_lock)) {2833 status |=error("couldn't write%s:%s", log_file,2834strerror(errno));2835}else if(update &&2836(write_in_full(get_lock_file_fd(lock->lk),2837oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2838write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||2839close_ref(lock) <0)) {2840 status |=error("couldn't write%s",2841get_lock_file_path(lock->lk));2842rollback_lock_file(&reflog_lock);2843}else if(commit_lock_file(&reflog_lock)) {2844 status |=error("unable to write reflog '%s' (%s)",2845 log_file,strerror(errno));2846}else if(update &&commit_ref(lock)) {2847 status |=error("couldn't set%s", lock->ref_name);2848}2849}2850free(log_file);2851unlock_ref(lock);2852return status;28532854 failure:2855rollback_lock_file(&reflog_lock);2856free(log_file);2857unlock_ref(lock);2858return-1;2859}28602861static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2862{2863struct files_ref_store *refs =2864files_downcast(ref_store, REF_STORE_WRITE,"init_db");2865struct strbuf sb = STRBUF_INIT;28662867/*2868 * Create .git/refs/{heads,tags}2869 */2870files_ref_path(refs, &sb,"refs/heads");2871safe_create_dir(sb.buf,1);28722873strbuf_reset(&sb);2874files_ref_path(refs, &sb,"refs/tags");2875safe_create_dir(sb.buf,1);28762877strbuf_release(&sb);2878return0;2879}28802881struct ref_storage_be refs_be_files = {2882 NULL,2883"files",2884 files_ref_store_create,2885 files_init_db,2886 files_transaction_prepare,2887 files_transaction_finish,2888 files_transaction_abort,2889 files_initial_transaction_commit,28902891 files_pack_refs,2892 files_peel_ref,2893 files_create_symref,2894 files_delete_refs,2895 files_rename_ref,28962897 files_ref_iterator_begin,2898 files_read_raw_ref,28992900 files_reflog_iterator_begin,2901 files_for_each_reflog_ent,2902 files_for_each_reflog_ent_reverse,2903 files_reflog_exists,2904 files_create_reflog,2905 files_delete_reflog,2906 files_reflog_expire2907};