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 packed ref that 635 * conflicts with refname: 636 */ 637if(refs_verify_refname_available( 638 refs->packed_ref_store, 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->packed_ref_store, 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, &err);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);1134packed_refs_unlock(refs->packed_ref_store);11351136prune_refs(refs, refs_to_prune);1137strbuf_release(&err);1138return0;1139}11401141static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1142struct string_list *refnames,unsigned int flags)1143{1144struct files_ref_store *refs =1145files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1146struct strbuf err = STRBUF_INIT;1147int i, result =0;11481149if(!refnames->nr)1150return0;11511152if(packed_refs_lock(refs->packed_ref_store,0, &err))1153goto error;11541155if(repack_without_refs(refs->packed_ref_store, refnames, &err)) {1156packed_refs_unlock(refs->packed_ref_store);1157goto error;1158}11591160packed_refs_unlock(refs->packed_ref_store);11611162for(i =0; i < refnames->nr; i++) {1163const char*refname = refnames->items[i].string;11641165if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1166 result |=error(_("could not remove reference%s"), refname);1167}11681169strbuf_release(&err);1170return result;11711172error:1173/*1174 * If we failed to rewrite the packed-refs file, then it is1175 * unsafe to try to remove loose refs, because doing so might1176 * expose an obsolete packed value for a reference that might1177 * even point at an object that has been garbage collected.1178 */1179if(refnames->nr ==1)1180error(_("could not delete reference%s:%s"),1181 refnames->items[0].string, err.buf);1182else1183error(_("could not delete references:%s"), err.buf);11841185strbuf_release(&err);1186return-1;1187}11881189/*1190 * People using contrib's git-new-workdir have .git/logs/refs ->1191 * /some/other/path/.git/logs/refs, and that may live on another device.1192 *1193 * IOW, to avoid cross device rename errors, the temporary renamed log must1194 * live into logs/refs.1195 */1196#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"11971198struct rename_cb {1199const char*tmp_renamed_log;1200int true_errno;1201};12021203static intrename_tmp_log_callback(const char*path,void*cb_data)1204{1205struct rename_cb *cb = cb_data;12061207if(rename(cb->tmp_renamed_log, path)) {1208/*1209 * rename(a, b) when b is an existing directory ought1210 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1211 * Sheesh. Record the true errno for error reporting,1212 * but report EISDIR to raceproof_create_file() so1213 * that it knows to retry.1214 */1215 cb->true_errno = errno;1216if(errno == ENOTDIR)1217 errno = EISDIR;1218return-1;1219}else{1220return0;1221}1222}12231224static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1225{1226struct strbuf path = STRBUF_INIT;1227struct strbuf tmp = STRBUF_INIT;1228struct rename_cb cb;1229int ret;12301231files_reflog_path(refs, &path, newrefname);1232files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1233 cb.tmp_renamed_log = tmp.buf;1234 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1235if(ret) {1236if(errno == EISDIR)1237error("directory not empty:%s", path.buf);1238else1239error("unable to move logfile%sto%s:%s",1240 tmp.buf, path.buf,1241strerror(cb.true_errno));1242}12431244strbuf_release(&path);1245strbuf_release(&tmp);1246return ret;1247}12481249static intwrite_ref_to_lockfile(struct ref_lock *lock,1250const struct object_id *oid,struct strbuf *err);1251static intcommit_ref_update(struct files_ref_store *refs,1252struct ref_lock *lock,1253const struct object_id *oid,const char*logmsg,1254struct strbuf *err);12551256static intfiles_rename_ref(struct ref_store *ref_store,1257const char*oldrefname,const char*newrefname,1258const char*logmsg)1259{1260struct files_ref_store *refs =1261files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1262struct object_id oid, orig_oid;1263int flag =0, logmoved =0;1264struct ref_lock *lock;1265struct stat loginfo;1266struct strbuf sb_oldref = STRBUF_INIT;1267struct strbuf sb_newref = STRBUF_INIT;1268struct strbuf tmp_renamed_log = STRBUF_INIT;1269int log, ret;1270struct strbuf err = STRBUF_INIT;12711272files_reflog_path(refs, &sb_oldref, oldrefname);1273files_reflog_path(refs, &sb_newref, newrefname);1274files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12751276 log = !lstat(sb_oldref.buf, &loginfo);1277if(log &&S_ISLNK(loginfo.st_mode)) {1278 ret =error("reflog for%sis a symlink", oldrefname);1279goto out;1280}12811282if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1283 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1284 orig_oid.hash, &flag)) {1285 ret =error("refname%snot found", oldrefname);1286goto out;1287}12881289if(flag & REF_ISSYMREF) {1290 ret =error("refname%sis a symbolic ref, renaming it is not supported",1291 oldrefname);1292goto out;1293}1294if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1295 ret =1;1296goto out;1297}12981299if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1300 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1301 oldrefname,strerror(errno));1302goto out;1303}13041305if(refs_delete_ref(&refs->base, logmsg, oldrefname,1306 orig_oid.hash, REF_NODEREF)) {1307error("unable to delete old%s", oldrefname);1308goto rollback;1309}13101311/*1312 * Since we are doing a shallow lookup, oid is not the1313 * correct value to pass to delete_ref as old_oid. But that1314 * doesn't matter, because an old_oid check wouldn't add to1315 * the safety anyway; we want to delete the reference whatever1316 * its current value.1317 */1318if(!refs_read_ref_full(&refs->base, newrefname,1319 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1320 oid.hash, NULL) &&1321refs_delete_ref(&refs->base, NULL, newrefname,1322 NULL, REF_NODEREF)) {1323if(errno == EISDIR) {1324struct strbuf path = STRBUF_INIT;1325int result;13261327files_ref_path(refs, &path, newrefname);1328 result =remove_empty_directories(&path);1329strbuf_release(&path);13301331if(result) {1332error("Directory not empty:%s", newrefname);1333goto rollback;1334}1335}else{1336error("unable to delete existing%s", newrefname);1337goto rollback;1338}1339}13401341if(log &&rename_tmp_log(refs, newrefname))1342goto rollback;13431344 logmoved = log;13451346 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1347 REF_NODEREF, NULL, &err);1348if(!lock) {1349error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1350strbuf_release(&err);1351goto rollback;1352}1353oidcpy(&lock->old_oid, &orig_oid);13541355if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1356commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1357error("unable to write current sha1 into%s:%s", newrefname, err.buf);1358strbuf_release(&err);1359goto rollback;1360}13611362 ret =0;1363goto out;13641365 rollback:1366 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1367 REF_NODEREF, NULL, &err);1368if(!lock) {1369error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1370strbuf_release(&err);1371goto rollbacklog;1372}13731374 flag = log_all_ref_updates;1375 log_all_ref_updates = LOG_REFS_NONE;1376if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1377commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1378error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1379strbuf_release(&err);1380}1381 log_all_ref_updates = flag;13821383 rollbacklog:1384if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1385error("unable to restore logfile%sfrom%s:%s",1386 oldrefname, newrefname,strerror(errno));1387if(!logmoved && log &&1388rename(tmp_renamed_log.buf, sb_oldref.buf))1389error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1390 oldrefname,strerror(errno));1391 ret =1;1392 out:1393strbuf_release(&sb_newref);1394strbuf_release(&sb_oldref);1395strbuf_release(&tmp_renamed_log);13961397return ret;1398}13991400static intclose_ref(struct ref_lock *lock)1401{1402if(close_lock_file(lock->lk))1403return-1;1404return0;1405}14061407static intcommit_ref(struct ref_lock *lock)1408{1409char*path =get_locked_file_path(lock->lk);1410struct stat st;14111412if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1413/*1414 * There is a directory at the path we want to rename1415 * the lockfile to. Hopefully it is empty; try to1416 * delete it.1417 */1418size_t len =strlen(path);1419struct strbuf sb_path = STRBUF_INIT;14201421strbuf_attach(&sb_path, path, len, len);14221423/*1424 * If this fails, commit_lock_file() will also fail1425 * and will report the problem.1426 */1427remove_empty_directories(&sb_path);1428strbuf_release(&sb_path);1429}else{1430free(path);1431}14321433if(commit_lock_file(lock->lk))1434return-1;1435return0;1436}14371438static intopen_or_create_logfile(const char*path,void*cb)1439{1440int*fd = cb;14411442*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1443return(*fd <0) ? -1:0;1444}14451446/*1447 * Create a reflog for a ref. If force_create = 0, only create the1448 * reflog for certain refs (those for which should_autocreate_reflog1449 * returns non-zero). Otherwise, create it regardless of the reference1450 * name. If the logfile already existed or was created, return 0 and1451 * set *logfd to the file descriptor opened for appending to the file.1452 * If no logfile exists and we decided not to create one, return 0 and1453 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1454 * return -1.1455 */1456static intlog_ref_setup(struct files_ref_store *refs,1457const char*refname,int force_create,1458int*logfd,struct strbuf *err)1459{1460struct strbuf logfile_sb = STRBUF_INIT;1461char*logfile;14621463files_reflog_path(refs, &logfile_sb, refname);1464 logfile =strbuf_detach(&logfile_sb, NULL);14651466if(force_create ||should_autocreate_reflog(refname)) {1467if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1468if(errno == ENOENT)1469strbuf_addf(err,"unable to create directory for '%s': "1470"%s", logfile,strerror(errno));1471else if(errno == EISDIR)1472strbuf_addf(err,"there are still logs under '%s'",1473 logfile);1474else1475strbuf_addf(err,"unable to append to '%s':%s",1476 logfile,strerror(errno));14771478goto error;1479}1480}else{1481*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1482if(*logfd <0) {1483if(errno == ENOENT || errno == EISDIR) {1484/*1485 * The logfile doesn't already exist,1486 * but that is not an error; it only1487 * means that we won't write log1488 * entries to it.1489 */1490;1491}else{1492strbuf_addf(err,"unable to append to '%s':%s",1493 logfile,strerror(errno));1494goto error;1495}1496}1497}14981499if(*logfd >=0)1500adjust_shared_perm(logfile);15011502free(logfile);1503return0;15041505error:1506free(logfile);1507return-1;1508}15091510static intfiles_create_reflog(struct ref_store *ref_store,1511const char*refname,int force_create,1512struct strbuf *err)1513{1514struct files_ref_store *refs =1515files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1516int fd;15171518if(log_ref_setup(refs, refname, force_create, &fd, err))1519return-1;15201521if(fd >=0)1522close(fd);15231524return0;1525}15261527static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1528const struct object_id *new_oid,1529const char*committer,const char*msg)1530{1531int msglen, written;1532unsigned maxlen, len;1533char*logrec;15341535 msglen = msg ?strlen(msg) :0;1536 maxlen =strlen(committer) + msglen +100;1537 logrec =xmalloc(maxlen);1538 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1539oid_to_hex(old_oid),1540oid_to_hex(new_oid),1541 committer);1542if(msglen)1543 len +=copy_reflog_msg(logrec + len -1, msg) -1;15441545 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1546free(logrec);1547if(written != len)1548return-1;15491550return0;1551}15521553static intfiles_log_ref_write(struct files_ref_store *refs,1554const char*refname,const struct object_id *old_oid,1555const struct object_id *new_oid,const char*msg,1556int flags,struct strbuf *err)1557{1558int logfd, result;15591560if(log_all_ref_updates == LOG_REFS_UNSET)1561 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15621563 result =log_ref_setup(refs, refname,1564 flags & REF_FORCE_CREATE_REFLOG,1565&logfd, err);15661567if(result)1568return result;15691570if(logfd <0)1571return0;1572 result =log_ref_write_fd(logfd, old_oid, new_oid,1573git_committer_info(0), msg);1574if(result) {1575struct strbuf sb = STRBUF_INIT;1576int save_errno = errno;15771578files_reflog_path(refs, &sb, refname);1579strbuf_addf(err,"unable to append to '%s':%s",1580 sb.buf,strerror(save_errno));1581strbuf_release(&sb);1582close(logfd);1583return-1;1584}1585if(close(logfd)) {1586struct strbuf sb = STRBUF_INIT;1587int save_errno = errno;15881589files_reflog_path(refs, &sb, refname);1590strbuf_addf(err,"unable to append to '%s':%s",1591 sb.buf,strerror(save_errno));1592strbuf_release(&sb);1593return-1;1594}1595return0;1596}15971598/*1599 * Write sha1 into the open lockfile, then close the lockfile. On1600 * errors, rollback the lockfile, fill in *err and1601 * return -1.1602 */1603static intwrite_ref_to_lockfile(struct ref_lock *lock,1604const struct object_id *oid,struct strbuf *err)1605{1606static char term ='\n';1607struct object *o;1608int fd;16091610 o =parse_object(oid);1611if(!o) {1612strbuf_addf(err,1613"trying to write ref '%s' with nonexistent object%s",1614 lock->ref_name,oid_to_hex(oid));1615unlock_ref(lock);1616return-1;1617}1618if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1619strbuf_addf(err,1620"trying to write non-commit object%sto branch '%s'",1621oid_to_hex(oid), lock->ref_name);1622unlock_ref(lock);1623return-1;1624}1625 fd =get_lock_file_fd(lock->lk);1626if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1627write_in_full(fd, &term,1) !=1||1628close_ref(lock) <0) {1629strbuf_addf(err,1630"couldn't write '%s'",get_lock_file_path(lock->lk));1631unlock_ref(lock);1632return-1;1633}1634return0;1635}16361637/*1638 * Commit a change to a loose reference that has already been written1639 * to the loose reference lockfile. Also update the reflogs if1640 * necessary, using the specified lockmsg (which can be NULL).1641 */1642static intcommit_ref_update(struct files_ref_store *refs,1643struct ref_lock *lock,1644const struct object_id *oid,const char*logmsg,1645struct strbuf *err)1646{1647files_assert_main_repository(refs,"commit_ref_update");16481649clear_loose_ref_cache(refs);1650if(files_log_ref_write(refs, lock->ref_name,1651&lock->old_oid, oid,1652 logmsg,0, err)) {1653char*old_msg =strbuf_detach(err, NULL);1654strbuf_addf(err,"cannot update the ref '%s':%s",1655 lock->ref_name, old_msg);1656free(old_msg);1657unlock_ref(lock);1658return-1;1659}16601661if(strcmp(lock->ref_name,"HEAD") !=0) {1662/*1663 * Special hack: If a branch is updated directly and HEAD1664 * points to it (may happen on the remote side of a push1665 * for example) then logically the HEAD reflog should be1666 * updated too.1667 * A generic solution implies reverse symref information,1668 * but finding all symrefs pointing to the given branch1669 * would be rather costly for this rare event (the direct1670 * update of a branch) to be worth it. So let's cheat and1671 * check with HEAD only which should cover 99% of all usage1672 * scenarios (even 100% of the default ones).1673 */1674struct object_id head_oid;1675int head_flag;1676const char*head_ref;16771678 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1679 RESOLVE_REF_READING,1680 head_oid.hash, &head_flag);1681if(head_ref && (head_flag & REF_ISSYMREF) &&1682!strcmp(head_ref, lock->ref_name)) {1683struct strbuf log_err = STRBUF_INIT;1684if(files_log_ref_write(refs,"HEAD",1685&lock->old_oid, oid,1686 logmsg,0, &log_err)) {1687error("%s", log_err.buf);1688strbuf_release(&log_err);1689}1690}1691}16921693if(commit_ref(lock)) {1694strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1695unlock_ref(lock);1696return-1;1697}16981699unlock_ref(lock);1700return0;1701}17021703static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1704{1705int ret = -1;1706#ifndef NO_SYMLINK_HEAD1707char*ref_path =get_locked_file_path(lock->lk);1708unlink(ref_path);1709 ret =symlink(target, ref_path);1710free(ref_path);17111712if(ret)1713fprintf(stderr,"no symlink - falling back to symbolic ref\n");1714#endif1715return ret;1716}17171718static voidupdate_symref_reflog(struct files_ref_store *refs,1719struct ref_lock *lock,const char*refname,1720const char*target,const char*logmsg)1721{1722struct strbuf err = STRBUF_INIT;1723struct object_id new_oid;1724if(logmsg &&1725!refs_read_ref_full(&refs->base, target,1726 RESOLVE_REF_READING, new_oid.hash, NULL) &&1727files_log_ref_write(refs, refname, &lock->old_oid,1728&new_oid, logmsg,0, &err)) {1729error("%s", err.buf);1730strbuf_release(&err);1731}1732}17331734static intcreate_symref_locked(struct files_ref_store *refs,1735struct ref_lock *lock,const char*refname,1736const char*target,const char*logmsg)1737{1738if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1739update_symref_reflog(refs, lock, refname, target, logmsg);1740return0;1741}17421743if(!fdopen_lock_file(lock->lk,"w"))1744returnerror("unable to fdopen%s:%s",1745 lock->lk->tempfile.filename.buf,strerror(errno));17461747update_symref_reflog(refs, lock, refname, target, logmsg);17481749/* no error check; commit_ref will check ferror */1750fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);1751if(commit_ref(lock) <0)1752returnerror("unable to write symref for%s:%s", refname,1753strerror(errno));1754return0;1755}17561757static intfiles_create_symref(struct ref_store *ref_store,1758const char*refname,const char*target,1759const char*logmsg)1760{1761struct files_ref_store *refs =1762files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1763struct strbuf err = STRBUF_INIT;1764struct ref_lock *lock;1765int ret;17661767 lock =lock_ref_sha1_basic(refs, refname, NULL,1768 NULL, NULL, REF_NODEREF, NULL,1769&err);1770if(!lock) {1771error("%s", err.buf);1772strbuf_release(&err);1773return-1;1774}17751776 ret =create_symref_locked(refs, lock, refname, target, logmsg);1777unlock_ref(lock);1778return ret;1779}17801781static intfiles_reflog_exists(struct ref_store *ref_store,1782const char*refname)1783{1784struct files_ref_store *refs =1785files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1786struct strbuf sb = STRBUF_INIT;1787struct stat st;1788int ret;17891790files_reflog_path(refs, &sb, refname);1791 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1792strbuf_release(&sb);1793return ret;1794}17951796static intfiles_delete_reflog(struct ref_store *ref_store,1797const char*refname)1798{1799struct files_ref_store *refs =1800files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1801struct strbuf sb = STRBUF_INIT;1802int ret;18031804files_reflog_path(refs, &sb, refname);1805 ret =remove_path(sb.buf);1806strbuf_release(&sb);1807return ret;1808}18091810static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1811{1812struct object_id ooid, noid;1813char*email_end, *message;1814 timestamp_t timestamp;1815int tz;1816const char*p = sb->buf;18171818/* old SP new SP name <email> SP time TAB msg LF */1819if(!sb->len || sb->buf[sb->len -1] !='\n'||1820parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1821parse_oid_hex(p, &noid, &p) || *p++ !=' '||1822!(email_end =strchr(p,'>')) ||1823 email_end[1] !=' '||1824!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1825!message || message[0] !=' '||1826(message[1] !='+'&& message[1] !='-') ||1827!isdigit(message[2]) || !isdigit(message[3]) ||1828!isdigit(message[4]) || !isdigit(message[5]))1829return0;/* corrupt? */1830 email_end[1] ='\0';1831 tz =strtol(message +1, NULL,10);1832if(message[6] !='\t')1833 message +=6;1834else1835 message +=7;1836returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1837}18381839static char*find_beginning_of_line(char*bob,char*scan)1840{1841while(bob < scan && *(--scan) !='\n')1842;/* keep scanning backwards */1843/*1844 * Return either beginning of the buffer, or LF at the end of1845 * the previous line.1846 */1847return scan;1848}18491850static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1851const char*refname,1852 each_reflog_ent_fn fn,1853void*cb_data)1854{1855struct files_ref_store *refs =1856files_downcast(ref_store, REF_STORE_READ,1857"for_each_reflog_ent_reverse");1858struct strbuf sb = STRBUF_INIT;1859FILE*logfp;1860long pos;1861int ret =0, at_tail =1;18621863files_reflog_path(refs, &sb, refname);1864 logfp =fopen(sb.buf,"r");1865strbuf_release(&sb);1866if(!logfp)1867return-1;18681869/* Jump to the end */1870if(fseek(logfp,0, SEEK_END) <0)1871 ret =error("cannot seek back reflog for%s:%s",1872 refname,strerror(errno));1873 pos =ftell(logfp);1874while(!ret &&0< pos) {1875int cnt;1876size_t nread;1877char buf[BUFSIZ];1878char*endp, *scanp;18791880/* Fill next block from the end */1881 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1882if(fseek(logfp, pos - cnt, SEEK_SET)) {1883 ret =error("cannot seek back reflog for%s:%s",1884 refname,strerror(errno));1885break;1886}1887 nread =fread(buf, cnt,1, logfp);1888if(nread !=1) {1889 ret =error("cannot read%dbytes from reflog for%s:%s",1890 cnt, refname,strerror(errno));1891break;1892}1893 pos -= cnt;18941895 scanp = endp = buf + cnt;1896if(at_tail && scanp[-1] =='\n')1897/* Looking at the final LF at the end of the file */1898 scanp--;1899 at_tail =0;19001901while(buf < scanp) {1902/*1903 * terminating LF of the previous line, or the beginning1904 * of the buffer.1905 */1906char*bp;19071908 bp =find_beginning_of_line(buf, scanp);19091910if(*bp =='\n') {1911/*1912 * The newline is the end of the previous line,1913 * so we know we have complete line starting1914 * at (bp + 1). Prefix it onto any prior data1915 * we collected for the line and process it.1916 */1917strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1918 scanp = bp;1919 endp = bp +1;1920 ret =show_one_reflog_ent(&sb, fn, cb_data);1921strbuf_reset(&sb);1922if(ret)1923break;1924}else if(!pos) {1925/*1926 * We are at the start of the buffer, and the1927 * start of the file; there is no previous1928 * line, and we have everything for this one.1929 * Process it, and we can end the loop.1930 */1931strbuf_splice(&sb,0,0, buf, endp - buf);1932 ret =show_one_reflog_ent(&sb, fn, cb_data);1933strbuf_reset(&sb);1934break;1935}19361937if(bp == buf) {1938/*1939 * We are at the start of the buffer, and there1940 * is more file to read backwards. Which means1941 * we are in the middle of a line. Note that we1942 * may get here even if *bp was a newline; that1943 * just means we are at the exact end of the1944 * previous line, rather than some spot in the1945 * middle.1946 *1947 * Save away what we have to be combined with1948 * the data from the next read.1949 */1950strbuf_splice(&sb,0,0, buf, endp - buf);1951break;1952}1953}19541955}1956if(!ret && sb.len)1957die("BUG: reverse reflog parser had leftover data");19581959fclose(logfp);1960strbuf_release(&sb);1961return ret;1962}19631964static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1965const char*refname,1966 each_reflog_ent_fn fn,void*cb_data)1967{1968struct files_ref_store *refs =1969files_downcast(ref_store, REF_STORE_READ,1970"for_each_reflog_ent");1971FILE*logfp;1972struct strbuf sb = STRBUF_INIT;1973int ret =0;19741975files_reflog_path(refs, &sb, refname);1976 logfp =fopen(sb.buf,"r");1977strbuf_release(&sb);1978if(!logfp)1979return-1;19801981while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1982 ret =show_one_reflog_ent(&sb, fn, cb_data);1983fclose(logfp);1984strbuf_release(&sb);1985return ret;1986}19871988struct files_reflog_iterator {1989struct ref_iterator base;19901991struct ref_store *ref_store;1992struct dir_iterator *dir_iterator;1993struct object_id oid;1994};19951996static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)1997{1998struct files_reflog_iterator *iter =1999(struct files_reflog_iterator *)ref_iterator;2000struct dir_iterator *diter = iter->dir_iterator;2001int ok;20022003while((ok =dir_iterator_advance(diter)) == ITER_OK) {2004int flags;20052006if(!S_ISREG(diter->st.st_mode))2007continue;2008if(diter->basename[0] =='.')2009continue;2010if(ends_with(diter->basename,".lock"))2011continue;20122013if(refs_read_ref_full(iter->ref_store,2014 diter->relative_path,0,2015 iter->oid.hash, &flags)) {2016error("bad ref for%s", diter->path.buf);2017continue;2018}20192020 iter->base.refname = diter->relative_path;2021 iter->base.oid = &iter->oid;2022 iter->base.flags = flags;2023return ITER_OK;2024}20252026 iter->dir_iterator = NULL;2027if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2028 ok = ITER_ERROR;2029return ok;2030}20312032static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2033struct object_id *peeled)2034{2035die("BUG: ref_iterator_peel() called for reflog_iterator");2036}20372038static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2039{2040struct files_reflog_iterator *iter =2041(struct files_reflog_iterator *)ref_iterator;2042int ok = ITER_DONE;20432044if(iter->dir_iterator)2045 ok =dir_iterator_abort(iter->dir_iterator);20462047base_ref_iterator_free(ref_iterator);2048return ok;2049}20502051static struct ref_iterator_vtable files_reflog_iterator_vtable = {2052 files_reflog_iterator_advance,2053 files_reflog_iterator_peel,2054 files_reflog_iterator_abort2055};20562057static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2058{2059struct files_ref_store *refs =2060files_downcast(ref_store, REF_STORE_READ,2061"reflog_iterator_begin");2062struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2063struct ref_iterator *ref_iterator = &iter->base;2064struct strbuf sb = STRBUF_INIT;20652066base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2067files_reflog_path(refs, &sb, NULL);2068 iter->dir_iterator =dir_iterator_begin(sb.buf);2069 iter->ref_store = ref_store;2070strbuf_release(&sb);2071return ref_iterator;2072}20732074/*2075 * If update is a direct update of head_ref (the reference pointed to2076 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2077 */2078static intsplit_head_update(struct ref_update *update,2079struct ref_transaction *transaction,2080const char*head_ref,2081struct string_list *affected_refnames,2082struct strbuf *err)2083{2084struct string_list_item *item;2085struct ref_update *new_update;20862087if((update->flags & REF_LOG_ONLY) ||2088(update->flags & REF_ISPRUNING) ||2089(update->flags & REF_UPDATE_VIA_HEAD))2090return0;20912092if(strcmp(update->refname, head_ref))2093return0;20942095/*2096 * First make sure that HEAD is not already in the2097 * transaction. This insertion is O(N) in the transaction2098 * size, but it happens at most once per transaction.2099 */2100 item =string_list_insert(affected_refnames,"HEAD");2101if(item->util) {2102/* An entry already existed */2103strbuf_addf(err,2104"multiple updates for 'HEAD' (including one "2105"via its referent '%s') are not allowed",2106 update->refname);2107return TRANSACTION_NAME_CONFLICT;2108}21092110 new_update =ref_transaction_add_update(2111 transaction,"HEAD",2112 update->flags | REF_LOG_ONLY | REF_NODEREF,2113 update->new_oid.hash, update->old_oid.hash,2114 update->msg);21152116 item->util = new_update;21172118return0;2119}21202121/*2122 * update is for a symref that points at referent and doesn't have2123 * REF_NODEREF set. Split it into two updates:2124 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2125 * - A new, separate update for the referent reference2126 * Note that the new update will itself be subject to splitting when2127 * the iteration gets to it.2128 */2129static intsplit_symref_update(struct files_ref_store *refs,2130struct ref_update *update,2131const char*referent,2132struct ref_transaction *transaction,2133struct string_list *affected_refnames,2134struct strbuf *err)2135{2136struct string_list_item *item;2137struct ref_update *new_update;2138unsigned int new_flags;21392140/*2141 * First make sure that referent is not already in the2142 * transaction. This insertion is O(N) in the transaction2143 * size, but it happens at most once per symref in a2144 * transaction.2145 */2146 item =string_list_insert(affected_refnames, referent);2147if(item->util) {2148/* An entry already existed */2149strbuf_addf(err,2150"multiple updates for '%s' (including one "2151"via symref '%s') are not allowed",2152 referent, update->refname);2153return TRANSACTION_NAME_CONFLICT;2154}21552156 new_flags = update->flags;2157if(!strcmp(update->refname,"HEAD")) {2158/*2159 * Record that the new update came via HEAD, so that2160 * when we process it, split_head_update() doesn't try2161 * to add another reflog update for HEAD. Note that2162 * this bit will be propagated if the new_update2163 * itself needs to be split.2164 */2165 new_flags |= REF_UPDATE_VIA_HEAD;2166}21672168 new_update =ref_transaction_add_update(2169 transaction, referent, new_flags,2170 update->new_oid.hash, update->old_oid.hash,2171 update->msg);21722173 new_update->parent_update = update;21742175/*2176 * Change the symbolic ref update to log only. Also, it2177 * doesn't need to check its old SHA-1 value, as that will be2178 * done when new_update is processed.2179 */2180 update->flags |= REF_LOG_ONLY | REF_NODEREF;2181 update->flags &= ~REF_HAVE_OLD;21822183 item->util = new_update;21842185return0;2186}21872188/*2189 * Return the refname under which update was originally requested.2190 */2191static const char*original_update_refname(struct ref_update *update)2192{2193while(update->parent_update)2194 update = update->parent_update;21952196return update->refname;2197}21982199/*2200 * Check whether the REF_HAVE_OLD and old_oid values stored in update2201 * are consistent with oid, which is the reference's current value. If2202 * everything is OK, return 0; otherwise, write an error message to2203 * err and return -1.2204 */2205static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2206struct strbuf *err)2207{2208if(!(update->flags & REF_HAVE_OLD) ||2209!oidcmp(oid, &update->old_oid))2210return0;22112212if(is_null_oid(&update->old_oid))2213strbuf_addf(err,"cannot lock ref '%s': "2214"reference already exists",2215original_update_refname(update));2216else if(is_null_oid(oid))2217strbuf_addf(err,"cannot lock ref '%s': "2218"reference is missing but expected%s",2219original_update_refname(update),2220oid_to_hex(&update->old_oid));2221else2222strbuf_addf(err,"cannot lock ref '%s': "2223"is at%sbut expected%s",2224original_update_refname(update),2225oid_to_hex(oid),2226oid_to_hex(&update->old_oid));22272228return-1;2229}22302231/*2232 * Prepare for carrying out update:2233 * - Lock the reference referred to by update.2234 * - Read the reference under lock.2235 * - Check that its old SHA-1 value (if specified) is correct, and in2236 * any case record it in update->lock->old_oid for later use when2237 * writing the reflog.2238 * - If it is a symref update without REF_NODEREF, split it up into a2239 * REF_LOG_ONLY update of the symref and add a separate update for2240 * the referent to transaction.2241 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2242 * update of HEAD.2243 */2244static intlock_ref_for_update(struct files_ref_store *refs,2245struct ref_update *update,2246struct ref_transaction *transaction,2247const char*head_ref,2248struct string_list *affected_refnames,2249struct strbuf *err)2250{2251struct strbuf referent = STRBUF_INIT;2252int mustexist = (update->flags & REF_HAVE_OLD) &&2253!is_null_oid(&update->old_oid);2254int ret;2255struct ref_lock *lock;22562257files_assert_main_repository(refs,"lock_ref_for_update");22582259if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2260 update->flags |= REF_DELETING;22612262if(head_ref) {2263 ret =split_head_update(update, transaction, head_ref,2264 affected_refnames, err);2265if(ret)2266return ret;2267}22682269 ret =lock_raw_ref(refs, update->refname, mustexist,2270 affected_refnames, NULL,2271&lock, &referent,2272&update->type, err);2273if(ret) {2274char*reason;22752276 reason =strbuf_detach(err, NULL);2277strbuf_addf(err,"cannot lock ref '%s':%s",2278original_update_refname(update), reason);2279free(reason);2280return ret;2281}22822283 update->backend_data = lock;22842285if(update->type & REF_ISSYMREF) {2286if(update->flags & REF_NODEREF) {2287/*2288 * We won't be reading the referent as part of2289 * the transaction, so we have to read it here2290 * to record and possibly check old_sha1:2291 */2292if(refs_read_ref_full(&refs->base,2293 referent.buf,0,2294 lock->old_oid.hash, NULL)) {2295if(update->flags & REF_HAVE_OLD) {2296strbuf_addf(err,"cannot lock ref '%s': "2297"error reading reference",2298original_update_refname(update));2299return-1;2300}2301}else if(check_old_oid(update, &lock->old_oid, err)) {2302return TRANSACTION_GENERIC_ERROR;2303}2304}else{2305/*2306 * Create a new update for the reference this2307 * symref is pointing at. Also, we will record2308 * and verify old_sha1 for this update as part2309 * of processing the split-off update, so we2310 * don't have to do it here.2311 */2312 ret =split_symref_update(refs, update,2313 referent.buf, transaction,2314 affected_refnames, err);2315if(ret)2316return ret;2317}2318}else{2319struct ref_update *parent_update;23202321if(check_old_oid(update, &lock->old_oid, err))2322return TRANSACTION_GENERIC_ERROR;23232324/*2325 * If this update is happening indirectly because of a2326 * symref update, record the old SHA-1 in the parent2327 * update:2328 */2329for(parent_update = update->parent_update;2330 parent_update;2331 parent_update = parent_update->parent_update) {2332struct ref_lock *parent_lock = parent_update->backend_data;2333oidcpy(&parent_lock->old_oid, &lock->old_oid);2334}2335}23362337if((update->flags & REF_HAVE_NEW) &&2338!(update->flags & REF_DELETING) &&2339!(update->flags & REF_LOG_ONLY)) {2340if(!(update->type & REF_ISSYMREF) &&2341!oidcmp(&lock->old_oid, &update->new_oid)) {2342/*2343 * The reference already has the desired2344 * value, so we don't need to write it.2345 */2346}else if(write_ref_to_lockfile(lock, &update->new_oid,2347 err)) {2348char*write_err =strbuf_detach(err, NULL);23492350/*2351 * The lock was freed upon failure of2352 * write_ref_to_lockfile():2353 */2354 update->backend_data = NULL;2355strbuf_addf(err,2356"cannot update ref '%s':%s",2357 update->refname, write_err);2358free(write_err);2359return TRANSACTION_GENERIC_ERROR;2360}else{2361 update->flags |= REF_NEEDS_COMMIT;2362}2363}2364if(!(update->flags & REF_NEEDS_COMMIT)) {2365/*2366 * We didn't call write_ref_to_lockfile(), so2367 * the lockfile is still open. Close it to2368 * free up the file descriptor:2369 */2370if(close_ref(lock)) {2371strbuf_addf(err,"couldn't close '%s.lock'",2372 update->refname);2373return TRANSACTION_GENERIC_ERROR;2374}2375}2376return0;2377}23782379/*2380 * Unlock any references in `transaction` that are still locked, and2381 * mark the transaction closed.2382 */2383static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2384{2385size_t i;23862387for(i =0; i < transaction->nr; i++) {2388struct ref_update *update = transaction->updates[i];2389struct ref_lock *lock = update->backend_data;23902391if(lock) {2392unlock_ref(lock);2393 update->backend_data = NULL;2394}2395}23962397 transaction->state = REF_TRANSACTION_CLOSED;2398}23992400static intfiles_transaction_prepare(struct ref_store *ref_store,2401struct ref_transaction *transaction,2402struct strbuf *err)2403{2404struct files_ref_store *refs =2405files_downcast(ref_store, REF_STORE_WRITE,2406"ref_transaction_prepare");2407size_t i;2408int ret =0;2409struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2410char*head_ref = NULL;2411int head_type;2412struct object_id head_oid;24132414assert(err);24152416if(!transaction->nr)2417goto cleanup;24182419/*2420 * Fail if a refname appears more than once in the2421 * transaction. (If we end up splitting up any updates using2422 * split_symref_update() or split_head_update(), those2423 * functions will check that the new updates don't have the2424 * same refname as any existing ones.)2425 */2426for(i =0; i < transaction->nr; i++) {2427struct ref_update *update = transaction->updates[i];2428struct string_list_item *item =2429string_list_append(&affected_refnames, update->refname);24302431/*2432 * We store a pointer to update in item->util, but at2433 * the moment we never use the value of this field2434 * except to check whether it is non-NULL.2435 */2436 item->util = update;2437}2438string_list_sort(&affected_refnames);2439if(ref_update_reject_duplicates(&affected_refnames, err)) {2440 ret = TRANSACTION_GENERIC_ERROR;2441goto cleanup;2442}24432444/*2445 * Special hack: If a branch is updated directly and HEAD2446 * points to it (may happen on the remote side of a push2447 * for example) then logically the HEAD reflog should be2448 * updated too.2449 *2450 * A generic solution would require reverse symref lookups,2451 * but finding all symrefs pointing to a given branch would be2452 * rather costly for this rare event (the direct update of a2453 * branch) to be worth it. So let's cheat and check with HEAD2454 * only, which should cover 99% of all usage scenarios (even2455 * 100% of the default ones).2456 *2457 * So if HEAD is a symbolic reference, then record the name of2458 * the reference that it points to. If we see an update of2459 * head_ref within the transaction, then split_head_update()2460 * arranges for the reflog of HEAD to be updated, too.2461 */2462 head_ref =refs_resolve_refdup(ref_store,"HEAD",2463 RESOLVE_REF_NO_RECURSE,2464 head_oid.hash, &head_type);24652466if(head_ref && !(head_type & REF_ISSYMREF)) {2467free(head_ref);2468 head_ref = NULL;2469}24702471/*2472 * Acquire all locks, verify old values if provided, check2473 * that new values are valid, and write new values to the2474 * lockfiles, ready to be activated. Only keep one lockfile2475 * open at a time to avoid running out of file descriptors.2476 * Note that lock_ref_for_update() might append more updates2477 * to the transaction.2478 */2479for(i =0; i < transaction->nr; i++) {2480struct ref_update *update = transaction->updates[i];24812482 ret =lock_ref_for_update(refs, update, transaction,2483 head_ref, &affected_refnames, err);2484if(ret)2485break;2486}24872488cleanup:2489free(head_ref);2490string_list_clear(&affected_refnames,0);24912492if(ret)2493files_transaction_cleanup(transaction);2494else2495 transaction->state = REF_TRANSACTION_PREPARED;24962497return ret;2498}24992500static intfiles_transaction_finish(struct ref_store *ref_store,2501struct ref_transaction *transaction,2502struct strbuf *err)2503{2504struct files_ref_store *refs =2505files_downcast(ref_store,0,"ref_transaction_finish");2506size_t i;2507int ret =0;2508struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2509struct string_list_item *ref_to_delete;2510struct strbuf sb = STRBUF_INIT;25112512assert(err);25132514if(!transaction->nr) {2515 transaction->state = REF_TRANSACTION_CLOSED;2516return0;2517}25182519/* Perform updates first so live commits remain referenced */2520for(i =0; i < transaction->nr; i++) {2521struct ref_update *update = transaction->updates[i];2522struct ref_lock *lock = update->backend_data;25232524if(update->flags & REF_NEEDS_COMMIT ||2525 update->flags & REF_LOG_ONLY) {2526if(files_log_ref_write(refs,2527 lock->ref_name,2528&lock->old_oid,2529&update->new_oid,2530 update->msg, update->flags,2531 err)) {2532char*old_msg =strbuf_detach(err, NULL);25332534strbuf_addf(err,"cannot update the ref '%s':%s",2535 lock->ref_name, old_msg);2536free(old_msg);2537unlock_ref(lock);2538 update->backend_data = NULL;2539 ret = TRANSACTION_GENERIC_ERROR;2540goto cleanup;2541}2542}2543if(update->flags & REF_NEEDS_COMMIT) {2544clear_loose_ref_cache(refs);2545if(commit_ref(lock)) {2546strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2547unlock_ref(lock);2548 update->backend_data = NULL;2549 ret = TRANSACTION_GENERIC_ERROR;2550goto cleanup;2551}2552}2553}2554/* Perform deletes now that updates are safely completed */2555for(i =0; i < transaction->nr; i++) {2556struct ref_update *update = transaction->updates[i];2557struct ref_lock *lock = update->backend_data;25582559if(update->flags & REF_DELETING &&2560!(update->flags & REF_LOG_ONLY)) {2561if(!(update->type & REF_ISPACKED) ||2562 update->type & REF_ISSYMREF) {2563/* It is a loose reference. */2564strbuf_reset(&sb);2565files_ref_path(refs, &sb, lock->ref_name);2566if(unlink_or_msg(sb.buf, err)) {2567 ret = TRANSACTION_GENERIC_ERROR;2568goto cleanup;2569}2570 update->flags |= REF_DELETED_LOOSE;2571}25722573if(!(update->flags & REF_ISPRUNING))2574string_list_append(&refs_to_delete,2575 lock->ref_name);2576}2577}25782579if(packed_refs_lock(refs->packed_ref_store,0, err)) {2580 ret = TRANSACTION_GENERIC_ERROR;2581goto cleanup;2582}25832584if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {2585 ret = TRANSACTION_GENERIC_ERROR;2586packed_refs_unlock(refs->packed_ref_store);2587goto cleanup;2588}25892590packed_refs_unlock(refs->packed_ref_store);25912592/* Delete the reflogs of any references that were deleted: */2593for_each_string_list_item(ref_to_delete, &refs_to_delete) {2594strbuf_reset(&sb);2595files_reflog_path(refs, &sb, ref_to_delete->string);2596if(!unlink_or_warn(sb.buf))2597try_remove_empty_parents(refs, ref_to_delete->string,2598 REMOVE_EMPTY_PARENTS_REFLOG);2599}26002601clear_loose_ref_cache(refs);26022603cleanup:2604files_transaction_cleanup(transaction);26052606for(i =0; i < transaction->nr; i++) {2607struct ref_update *update = transaction->updates[i];26082609if(update->flags & REF_DELETED_LOOSE) {2610/*2611 * The loose reference was deleted. Delete any2612 * empty parent directories. (Note that this2613 * can only work because we have already2614 * removed the lockfile.)2615 */2616try_remove_empty_parents(refs, update->refname,2617 REMOVE_EMPTY_PARENTS_REF);2618}2619}26202621strbuf_release(&sb);2622string_list_clear(&refs_to_delete,0);2623return ret;2624}26252626static intfiles_transaction_abort(struct ref_store *ref_store,2627struct ref_transaction *transaction,2628struct strbuf *err)2629{2630files_transaction_cleanup(transaction);2631return0;2632}26332634static intref_present(const char*refname,2635const struct object_id *oid,int flags,void*cb_data)2636{2637struct string_list *affected_refnames = cb_data;26382639returnstring_list_has_string(affected_refnames, refname);2640}26412642static intfiles_initial_transaction_commit(struct ref_store *ref_store,2643struct ref_transaction *transaction,2644struct strbuf *err)2645{2646struct files_ref_store *refs =2647files_downcast(ref_store, REF_STORE_WRITE,2648"initial_ref_transaction_commit");2649size_t i;2650int ret =0;2651struct string_list affected_refnames = STRING_LIST_INIT_NODUP;26522653assert(err);26542655if(transaction->state != REF_TRANSACTION_OPEN)2656die("BUG: commit called for transaction that is not open");26572658/* Fail if a refname appears more than once in the transaction: */2659for(i =0; i < transaction->nr; i++)2660string_list_append(&affected_refnames,2661 transaction->updates[i]->refname);2662string_list_sort(&affected_refnames);2663if(ref_update_reject_duplicates(&affected_refnames, err)) {2664 ret = TRANSACTION_GENERIC_ERROR;2665goto cleanup;2666}26672668/*2669 * It's really undefined to call this function in an active2670 * repository or when there are existing references: we are2671 * only locking and changing packed-refs, so (1) any2672 * simultaneous processes might try to change a reference at2673 * the same time we do, and (2) any existing loose versions of2674 * the references that we are setting would have precedence2675 * over our values. But some remote helpers create the remote2676 * "HEAD" and "master" branches before calling this function,2677 * so here we really only check that none of the references2678 * that we are creating already exists.2679 */2680if(refs_for_each_rawref(&refs->base, ref_present,2681&affected_refnames))2682die("BUG: initial ref transaction called with existing refs");26832684for(i =0; i < transaction->nr; i++) {2685struct ref_update *update = transaction->updates[i];26862687if((update->flags & REF_HAVE_OLD) &&2688!is_null_oid(&update->old_oid))2689die("BUG: initial ref transaction with old_sha1 set");2690if(refs_verify_refname_available(&refs->base, update->refname,2691&affected_refnames, NULL,2692 err)) {2693 ret = TRANSACTION_NAME_CONFLICT;2694goto cleanup;2695}2696}26972698if(packed_refs_lock(refs->packed_ref_store,0, err)) {2699 ret = TRANSACTION_GENERIC_ERROR;2700goto cleanup;2701}27022703for(i =0; i < transaction->nr; i++) {2704struct ref_update *update = transaction->updates[i];27052706if((update->flags & REF_HAVE_NEW) &&2707!is_null_oid(&update->new_oid))2708add_packed_ref(refs->packed_ref_store, update->refname,2709&update->new_oid);2710}27112712if(commit_packed_refs(refs->packed_ref_store, err)) {2713 ret = TRANSACTION_GENERIC_ERROR;2714goto cleanup;2715}27162717cleanup:2718packed_refs_unlock(refs->packed_ref_store);2719 transaction->state = REF_TRANSACTION_CLOSED;2720string_list_clear(&affected_refnames,0);2721return ret;2722}27232724struct expire_reflog_cb {2725unsigned int flags;2726 reflog_expiry_should_prune_fn *should_prune_fn;2727void*policy_cb;2728FILE*newlog;2729struct object_id last_kept_oid;2730};27312732static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2733const char*email, timestamp_t timestamp,int tz,2734const char*message,void*cb_data)2735{2736struct expire_reflog_cb *cb = cb_data;2737struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;27382739if(cb->flags & EXPIRE_REFLOGS_REWRITE)2740 ooid = &cb->last_kept_oid;27412742if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2743 message, policy_cb)) {2744if(!cb->newlog)2745printf("would prune%s", message);2746else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2747printf("prune%s", message);2748}else{2749if(cb->newlog) {2750fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2751oid_to_hex(ooid),oid_to_hex(noid),2752 email, timestamp, tz, message);2753oidcpy(&cb->last_kept_oid, noid);2754}2755if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2756printf("keep%s", message);2757}2758return0;2759}27602761static intfiles_reflog_expire(struct ref_store *ref_store,2762const char*refname,const unsigned char*sha1,2763unsigned int flags,2764 reflog_expiry_prepare_fn prepare_fn,2765 reflog_expiry_should_prune_fn should_prune_fn,2766 reflog_expiry_cleanup_fn cleanup_fn,2767void*policy_cb_data)2768{2769struct files_ref_store *refs =2770files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2771static struct lock_file reflog_lock;2772struct expire_reflog_cb cb;2773struct ref_lock *lock;2774struct strbuf log_file_sb = STRBUF_INIT;2775char*log_file;2776int status =0;2777int type;2778struct strbuf err = STRBUF_INIT;2779struct object_id oid;27802781memset(&cb,0,sizeof(cb));2782 cb.flags = flags;2783 cb.policy_cb = policy_cb_data;2784 cb.should_prune_fn = should_prune_fn;27852786/*2787 * The reflog file is locked by holding the lock on the2788 * reference itself, plus we might need to update the2789 * reference if --updateref was specified:2790 */2791 lock =lock_ref_sha1_basic(refs, refname, sha1,2792 NULL, NULL, REF_NODEREF,2793&type, &err);2794if(!lock) {2795error("cannot lock ref '%s':%s", refname, err.buf);2796strbuf_release(&err);2797return-1;2798}2799if(!refs_reflog_exists(ref_store, refname)) {2800unlock_ref(lock);2801return0;2802}28032804files_reflog_path(refs, &log_file_sb, refname);2805 log_file =strbuf_detach(&log_file_sb, NULL);2806if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2807/*2808 * Even though holding $GIT_DIR/logs/$reflog.lock has2809 * no locking implications, we use the lock_file2810 * machinery here anyway because it does a lot of the2811 * work we need, including cleaning up if the program2812 * exits unexpectedly.2813 */2814if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2815struct strbuf err = STRBUF_INIT;2816unable_to_lock_message(log_file, errno, &err);2817error("%s", err.buf);2818strbuf_release(&err);2819goto failure;2820}2821 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2822if(!cb.newlog) {2823error("cannot fdopen%s(%s)",2824get_lock_file_path(&reflog_lock),strerror(errno));2825goto failure;2826}2827}28282829hashcpy(oid.hash, sha1);28302831(*prepare_fn)(refname, &oid, cb.policy_cb);2832refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2833(*cleanup_fn)(cb.policy_cb);28342835if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2836/*2837 * It doesn't make sense to adjust a reference pointed2838 * to by a symbolic ref based on expiring entries in2839 * the symbolic reference's reflog. Nor can we update2840 * a reference if there are no remaining reflog2841 * entries.2842 */2843int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2844!(type & REF_ISSYMREF) &&2845!is_null_oid(&cb.last_kept_oid);28462847if(close_lock_file(&reflog_lock)) {2848 status |=error("couldn't write%s:%s", log_file,2849strerror(errno));2850}else if(update &&2851(write_in_full(get_lock_file_fd(lock->lk),2852oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2853write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||2854close_ref(lock) <0)) {2855 status |=error("couldn't write%s",2856get_lock_file_path(lock->lk));2857rollback_lock_file(&reflog_lock);2858}else if(commit_lock_file(&reflog_lock)) {2859 status |=error("unable to write reflog '%s' (%s)",2860 log_file,strerror(errno));2861}else if(update &&commit_ref(lock)) {2862 status |=error("couldn't set%s", lock->ref_name);2863}2864}2865free(log_file);2866unlock_ref(lock);2867return status;28682869 failure:2870rollback_lock_file(&reflog_lock);2871free(log_file);2872unlock_ref(lock);2873return-1;2874}28752876static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2877{2878struct files_ref_store *refs =2879files_downcast(ref_store, REF_STORE_WRITE,"init_db");2880struct strbuf sb = STRBUF_INIT;28812882/*2883 * Create .git/refs/{heads,tags}2884 */2885files_ref_path(refs, &sb,"refs/heads");2886safe_create_dir(sb.buf,1);28872888strbuf_reset(&sb);2889files_ref_path(refs, &sb,"refs/tags");2890safe_create_dir(sb.buf,1);28912892strbuf_release(&sb);2893return0;2894}28952896struct ref_storage_be refs_be_files = {2897 NULL,2898"files",2899 files_ref_store_create,2900 files_init_db,2901 files_transaction_prepare,2902 files_transaction_finish,2903 files_transaction_abort,2904 files_initial_transaction_commit,29052906 files_pack_refs,2907 files_peel_ref,2908 files_create_symref,2909 files_delete_refs,2910 files_rename_ref,29112912 files_ref_iterator_begin,2913 files_read_raw_ref,29142915 files_reflog_iterator_begin,2916 files_for_each_reflog_ent,2917 files_for_each_reflog_ent_reverse,2918 files_reflog_exists,2919 files_create_reflog,2920 files_delete_reflog,2921 files_reflog_expire2922};