1#include"../cache.h" 2#include"../config.h" 3#include"../refs.h" 4#include"refs-internal.h" 5#include"ref-cache.h" 6#include"packed-backend.h" 7#include"../iterator.h" 8#include"../dir-iterator.h" 9#include"../lockfile.h" 10#include"../object.h" 11#include"../dir.h" 12 13struct ref_lock { 14char*ref_name; 15struct lock_file *lk; 16struct object_id old_oid; 17}; 18 19/* 20 * Future: need to be in "struct repository" 21 * when doing a full libification. 22 */ 23struct files_ref_store { 24struct ref_store base; 25unsigned int store_flags; 26 27char*gitdir; 28char*gitcommondir; 29 30struct ref_cache *loose; 31 32struct ref_store *packed_ref_store; 33}; 34 35static voidclear_loose_ref_cache(struct files_ref_store *refs) 36{ 37if(refs->loose) { 38free_ref_cache(refs->loose); 39 refs->loose = NULL; 40} 41} 42 43/* 44 * Create a new submodule ref cache and add it to the internal 45 * set of caches. 46 */ 47static struct ref_store *files_ref_store_create(const char*gitdir, 48unsigned int flags) 49{ 50struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 51struct ref_store *ref_store = (struct ref_store *)refs; 52struct strbuf sb = STRBUF_INIT; 53 54base_ref_store_init(ref_store, &refs_be_files); 55 refs->store_flags = flags; 56 57 refs->gitdir =xstrdup(gitdir); 58get_common_dir_noenv(&sb, gitdir); 59 refs->gitcommondir =strbuf_detach(&sb, NULL); 60strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 61 refs->packed_ref_store =packed_ref_store_create(sb.buf, flags); 62strbuf_release(&sb); 63 64return ref_store; 65} 66 67/* 68 * Die if refs is not the main ref store. caller is used in any 69 * necessary error messages. 70 */ 71static voidfiles_assert_main_repository(struct files_ref_store *refs, 72const char*caller) 73{ 74if(refs->store_flags & REF_STORE_MAIN) 75return; 76 77die("BUG: operation%sonly allowed for main ref store", caller); 78} 79 80/* 81 * Downcast ref_store to files_ref_store. Die if ref_store is not a 82 * files_ref_store. required_flags is compared with ref_store's 83 * store_flags to ensure the ref_store has all required capabilities. 84 * "caller" is used in any necessary error messages. 85 */ 86static struct files_ref_store *files_downcast(struct ref_store *ref_store, 87unsigned int required_flags, 88const char*caller) 89{ 90struct files_ref_store *refs; 91 92if(ref_store->be != &refs_be_files) 93die("BUG: ref_store is type\"%s\"not\"files\"in%s", 94 ref_store->be->name, caller); 95 96 refs = (struct files_ref_store *)ref_store; 97 98if((refs->store_flags & required_flags) != required_flags) 99die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 100 caller, required_flags, refs->store_flags); 101 102return refs; 103} 104 105static voidfiles_reflog_path(struct files_ref_store *refs, 106struct strbuf *sb, 107const char*refname) 108{ 109switch(ref_type(refname)) { 110case REF_TYPE_PER_WORKTREE: 111case REF_TYPE_PSEUDOREF: 112strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 113break; 114case REF_TYPE_NORMAL: 115strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 116break; 117default: 118die("BUG: unknown ref type%dof ref%s", 119ref_type(refname), refname); 120} 121} 122 123static voidfiles_ref_path(struct files_ref_store *refs, 124struct strbuf *sb, 125const char*refname) 126{ 127switch(ref_type(refname)) { 128case REF_TYPE_PER_WORKTREE: 129case REF_TYPE_PSEUDOREF: 130strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 131break; 132case REF_TYPE_NORMAL: 133strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 134break; 135default: 136die("BUG: unknown ref type%dof ref%s", 137ref_type(refname), refname); 138} 139} 140 141/* 142 * Read the loose references from the namespace dirname into dir 143 * (without recursing). dirname must end with '/'. dir must be the 144 * directory entry corresponding to dirname. 145 */ 146static voidloose_fill_ref_dir(struct ref_store *ref_store, 147struct ref_dir *dir,const char*dirname) 148{ 149struct files_ref_store *refs = 150files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 151DIR*d; 152struct dirent *de; 153int dirnamelen =strlen(dirname); 154struct strbuf refname; 155struct strbuf path = STRBUF_INIT; 156size_t path_baselen; 157 158files_ref_path(refs, &path, dirname); 159 path_baselen = path.len; 160 161 d =opendir(path.buf); 162if(!d) { 163strbuf_release(&path); 164return; 165} 166 167strbuf_init(&refname, dirnamelen +257); 168strbuf_add(&refname, dirname, dirnamelen); 169 170while((de =readdir(d)) != NULL) { 171struct object_id oid; 172struct stat st; 173int flag; 174 175if(de->d_name[0] =='.') 176continue; 177if(ends_with(de->d_name,".lock")) 178continue; 179strbuf_addstr(&refname, de->d_name); 180strbuf_addstr(&path, de->d_name); 181if(stat(path.buf, &st) <0) { 182;/* silently ignore */ 183}else if(S_ISDIR(st.st_mode)) { 184strbuf_addch(&refname,'/'); 185add_entry_to_dir(dir, 186create_dir_entry(dir->cache, refname.buf, 187 refname.len,1)); 188}else{ 189if(!refs_resolve_ref_unsafe(&refs->base, 190 refname.buf, 191 RESOLVE_REF_READING, 192 oid.hash, &flag)) { 193oidclr(&oid); 194 flag |= REF_ISBROKEN; 195}else if(is_null_oid(&oid)) { 196/* 197 * It is so astronomically unlikely 198 * that NULL_SHA1 is the SHA-1 of an 199 * actual object that we consider its 200 * appearance in a loose reference 201 * file to be repo corruption 202 * (probably due to a software bug). 203 */ 204 flag |= REF_ISBROKEN; 205} 206 207if(check_refname_format(refname.buf, 208 REFNAME_ALLOW_ONELEVEL)) { 209if(!refname_is_safe(refname.buf)) 210die("loose refname is dangerous:%s", refname.buf); 211oidclr(&oid); 212 flag |= REF_BAD_NAME | REF_ISBROKEN; 213} 214add_entry_to_dir(dir, 215create_ref_entry(refname.buf, &oid, flag)); 216} 217strbuf_setlen(&refname, dirnamelen); 218strbuf_setlen(&path, path_baselen); 219} 220strbuf_release(&refname); 221strbuf_release(&path); 222closedir(d); 223 224/* 225 * Manually add refs/bisect, which, being per-worktree, might 226 * not appear in the directory listing for refs/ in the main 227 * repo. 228 */ 229if(!strcmp(dirname,"refs/")) { 230int pos =search_ref_dir(dir,"refs/bisect/",12); 231 232if(pos <0) { 233struct ref_entry *child_entry =create_dir_entry( 234 dir->cache,"refs/bisect/",12,1); 235add_entry_to_dir(dir, child_entry); 236} 237} 238} 239 240static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 241{ 242if(!refs->loose) { 243/* 244 * Mark the top-level directory complete because we 245 * are about to read the only subdirectory that can 246 * hold references: 247 */ 248 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 249 250/* We're going to fill the top level ourselves: */ 251 refs->loose->root->flag &= ~REF_INCOMPLETE; 252 253/* 254 * Add an incomplete entry for "refs/" (to be filled 255 * lazily): 256 */ 257add_entry_to_dir(get_ref_dir(refs->loose->root), 258create_dir_entry(refs->loose,"refs/",5,1)); 259} 260return refs->loose; 261} 262 263static intfiles_read_raw_ref(struct ref_store *ref_store, 264const char*refname,unsigned char*sha1, 265struct strbuf *referent,unsigned int*type) 266{ 267struct files_ref_store *refs = 268files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 269struct strbuf sb_contents = STRBUF_INIT; 270struct strbuf sb_path = STRBUF_INIT; 271const char*path; 272const char*buf; 273struct stat st; 274int fd; 275int ret = -1; 276int save_errno; 277int remaining_retries =3; 278 279*type =0; 280strbuf_reset(&sb_path); 281 282files_ref_path(refs, &sb_path, refname); 283 284 path = sb_path.buf; 285 286stat_ref: 287/* 288 * We might have to loop back here to avoid a race 289 * condition: first we lstat() the file, then we try 290 * to read it as a link or as a file. But if somebody 291 * changes the type of the file (file <-> directory 292 * <-> symlink) between the lstat() and reading, then 293 * we don't want to report that as an error but rather 294 * try again starting with the lstat(). 295 * 296 * We'll keep a count of the retries, though, just to avoid 297 * any confusing situation sending us into an infinite loop. 298 */ 299 300if(remaining_retries-- <=0) 301goto out; 302 303if(lstat(path, &st) <0) { 304if(errno != ENOENT) 305goto out; 306if(refs_read_raw_ref(refs->packed_ref_store, refname, 307 sha1, referent, type)) { 308 errno = ENOENT; 309goto out; 310} 311 ret =0; 312goto out; 313} 314 315/* Follow "normalized" - ie "refs/.." symlinks by hand */ 316if(S_ISLNK(st.st_mode)) { 317strbuf_reset(&sb_contents); 318if(strbuf_readlink(&sb_contents, path,0) <0) { 319if(errno == ENOENT || errno == EINVAL) 320/* inconsistent with lstat; retry */ 321goto stat_ref; 322else 323goto out; 324} 325if(starts_with(sb_contents.buf,"refs/") && 326!check_refname_format(sb_contents.buf,0)) { 327strbuf_swap(&sb_contents, referent); 328*type |= REF_ISSYMREF; 329 ret =0; 330goto out; 331} 332/* 333 * It doesn't look like a refname; fall through to just 334 * treating it like a non-symlink, and reading whatever it 335 * points to. 336 */ 337} 338 339/* Is it a directory? */ 340if(S_ISDIR(st.st_mode)) { 341/* 342 * Even though there is a directory where the loose 343 * ref is supposed to be, there could still be a 344 * packed ref: 345 */ 346if(refs_read_raw_ref(refs->packed_ref_store, refname, 347 sha1, referent, type)) { 348 errno = EISDIR; 349goto out; 350} 351 ret =0; 352goto out; 353} 354 355/* 356 * Anything else, just open it and try to use it as 357 * a ref 358 */ 359 fd =open(path, O_RDONLY); 360if(fd <0) { 361if(errno == ENOENT && !S_ISLNK(st.st_mode)) 362/* inconsistent with lstat; retry */ 363goto stat_ref; 364else 365goto out; 366} 367strbuf_reset(&sb_contents); 368if(strbuf_read(&sb_contents, fd,256) <0) { 369int save_errno = errno; 370close(fd); 371 errno = save_errno; 372goto out; 373} 374close(fd); 375strbuf_rtrim(&sb_contents); 376 buf = sb_contents.buf; 377if(starts_with(buf,"ref:")) { 378 buf +=4; 379while(isspace(*buf)) 380 buf++; 381 382strbuf_reset(referent); 383strbuf_addstr(referent, buf); 384*type |= REF_ISSYMREF; 385 ret =0; 386goto out; 387} 388 389/* 390 * Please note that FETCH_HEAD has additional 391 * data after the sha. 392 */ 393if(get_sha1_hex(buf, sha1) || 394(buf[40] !='\0'&& !isspace(buf[40]))) { 395*type |= REF_ISBROKEN; 396 errno = EINVAL; 397goto out; 398} 399 400 ret =0; 401 402out: 403 save_errno = errno; 404strbuf_release(&sb_path); 405strbuf_release(&sb_contents); 406 errno = save_errno; 407return ret; 408} 409 410static voidunlock_ref(struct ref_lock *lock) 411{ 412/* Do not free lock->lk -- atexit() still looks at them */ 413if(lock->lk) 414rollback_lock_file(lock->lk); 415free(lock->ref_name); 416free(lock); 417} 418 419/* 420 * Lock refname, without following symrefs, and set *lock_p to point 421 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 422 * and type similarly to read_raw_ref(). 423 * 424 * The caller must verify that refname is a "safe" reference name (in 425 * the sense of refname_is_safe()) before calling this function. 426 * 427 * If the reference doesn't already exist, verify that refname doesn't 428 * have a D/F conflict with any existing references. extras and skip 429 * are passed to refs_verify_refname_available() for this check. 430 * 431 * If mustexist is not set and the reference is not found or is 432 * broken, lock the reference anyway but clear sha1. 433 * 434 * Return 0 on success. On failure, write an error message to err and 435 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 436 * 437 * Implementation note: This function is basically 438 * 439 * lock reference 440 * read_raw_ref() 441 * 442 * but it includes a lot more code to 443 * - Deal with possible races with other processes 444 * - Avoid calling refs_verify_refname_available() when it can be 445 * avoided, namely if we were successfully able to read the ref 446 * - Generate informative error messages in the case of failure 447 */ 448static intlock_raw_ref(struct files_ref_store *refs, 449const char*refname,int mustexist, 450const struct string_list *extras, 451const struct string_list *skip, 452struct ref_lock **lock_p, 453struct strbuf *referent, 454unsigned int*type, 455struct strbuf *err) 456{ 457struct ref_lock *lock; 458struct strbuf ref_file = STRBUF_INIT; 459int attempts_remaining =3; 460int ret = TRANSACTION_GENERIC_ERROR; 461 462assert(err); 463files_assert_main_repository(refs,"lock_raw_ref"); 464 465*type =0; 466 467/* First lock the file so it can't change out from under us. */ 468 469*lock_p = lock =xcalloc(1,sizeof(*lock)); 470 471 lock->ref_name =xstrdup(refname); 472files_ref_path(refs, &ref_file, refname); 473 474retry: 475switch(safe_create_leading_directories(ref_file.buf)) { 476case SCLD_OK: 477break;/* success */ 478case SCLD_EXISTS: 479/* 480 * Suppose refname is "refs/foo/bar". We just failed 481 * to create the containing directory, "refs/foo", 482 * because there was a non-directory in the way. This 483 * indicates a D/F conflict, probably because of 484 * another reference such as "refs/foo". There is no 485 * reason to expect this error to be transitory. 486 */ 487if(refs_verify_refname_available(&refs->base, refname, 488 extras, skip, err)) { 489if(mustexist) { 490/* 491 * To the user the relevant error is 492 * that the "mustexist" reference is 493 * missing: 494 */ 495strbuf_reset(err); 496strbuf_addf(err,"unable to resolve reference '%s'", 497 refname); 498}else{ 499/* 500 * The error message set by 501 * refs_verify_refname_available() is 502 * OK. 503 */ 504 ret = TRANSACTION_NAME_CONFLICT; 505} 506}else{ 507/* 508 * The file that is in the way isn't a loose 509 * reference. Report it as a low-level 510 * failure. 511 */ 512strbuf_addf(err,"unable to create lock file%s.lock; " 513"non-directory in the way", 514 ref_file.buf); 515} 516goto error_return; 517case SCLD_VANISHED: 518/* Maybe another process was tidying up. Try again. */ 519if(--attempts_remaining >0) 520goto retry; 521/* fall through */ 522default: 523strbuf_addf(err,"unable to create directory for%s", 524 ref_file.buf); 525goto error_return; 526} 527 528if(!lock->lk) 529 lock->lk =xcalloc(1,sizeof(struct lock_file)); 530 531if(hold_lock_file_for_update_timeout( 532 lock->lk, ref_file.buf, LOCK_NO_DEREF, 533get_files_ref_lock_timeout_ms()) <0) { 534if(errno == ENOENT && --attempts_remaining >0) { 535/* 536 * Maybe somebody just deleted one of the 537 * directories leading to ref_file. Try 538 * again: 539 */ 540goto retry; 541}else{ 542unable_to_lock_message(ref_file.buf, errno, err); 543goto error_return; 544} 545} 546 547/* 548 * Now we hold the lock and can read the reference without 549 * fear that its value will change. 550 */ 551 552if(files_read_raw_ref(&refs->base, refname, 553 lock->old_oid.hash, referent, type)) { 554if(errno == ENOENT) { 555if(mustexist) { 556/* Garden variety missing reference. */ 557strbuf_addf(err,"unable to resolve reference '%s'", 558 refname); 559goto error_return; 560}else{ 561/* 562 * Reference is missing, but that's OK. We 563 * know that there is not a conflict with 564 * another loose reference because 565 * (supposing that we are trying to lock 566 * reference "refs/foo/bar"): 567 * 568 * - We were successfully able to create 569 * the lockfile refs/foo/bar.lock, so we 570 * know there cannot be a loose reference 571 * named "refs/foo". 572 * 573 * - We got ENOENT and not EISDIR, so we 574 * know that there cannot be a loose 575 * reference named "refs/foo/bar/baz". 576 */ 577} 578}else if(errno == EISDIR) { 579/* 580 * There is a directory in the way. It might have 581 * contained references that have been deleted. If 582 * we don't require that the reference already 583 * exists, try to remove the directory so that it 584 * doesn't cause trouble when we want to rename the 585 * lockfile into place later. 586 */ 587if(mustexist) { 588/* Garden variety missing reference. */ 589strbuf_addf(err,"unable to resolve reference '%s'", 590 refname); 591goto error_return; 592}else if(remove_dir_recursively(&ref_file, 593 REMOVE_DIR_EMPTY_ONLY)) { 594if(refs_verify_refname_available( 595&refs->base, refname, 596 extras, skip, err)) { 597/* 598 * The error message set by 599 * verify_refname_available() is OK. 600 */ 601 ret = TRANSACTION_NAME_CONFLICT; 602goto error_return; 603}else{ 604/* 605 * We can't delete the directory, 606 * but we also don't know of any 607 * references that it should 608 * contain. 609 */ 610strbuf_addf(err,"there is a non-empty directory '%s' " 611"blocking reference '%s'", 612 ref_file.buf, refname); 613goto error_return; 614} 615} 616}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 617strbuf_addf(err,"unable to resolve reference '%s': " 618"reference broken", refname); 619goto error_return; 620}else{ 621strbuf_addf(err,"unable to resolve reference '%s':%s", 622 refname,strerror(errno)); 623goto error_return; 624} 625 626/* 627 * If the ref did not exist and we are creating it, 628 * make sure there is no existing packed ref that 629 * conflicts with refname: 630 */ 631if(refs_verify_refname_available( 632 refs->packed_ref_store, refname, 633 extras, skip, err)) 634goto error_return; 635} 636 637 ret =0; 638goto out; 639 640error_return: 641unlock_ref(lock); 642*lock_p = NULL; 643 644out: 645strbuf_release(&ref_file); 646return ret; 647} 648 649static intfiles_peel_ref(struct ref_store *ref_store, 650const char*refname,unsigned char*sha1) 651{ 652struct files_ref_store *refs = 653files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 654"peel_ref"); 655int flag; 656unsigned char base[20]; 657 658if(current_ref_iter && current_ref_iter->refname == refname) { 659struct object_id peeled; 660 661if(ref_iterator_peel(current_ref_iter, &peeled)) 662return-1; 663hashcpy(sha1, peeled.hash); 664return0; 665} 666 667if(refs_read_ref_full(ref_store, refname, 668 RESOLVE_REF_READING, base, &flag)) 669return-1; 670 671/* 672 * If the reference is packed, read its ref_entry from the 673 * cache in the hope that we already know its peeled value. 674 * We only try this optimization on packed references because 675 * (a) forcing the filling of the loose reference cache could 676 * be expensive and (b) loose references anyway usually do not 677 * have REF_KNOWS_PEELED. 678 */ 679if(flag & REF_ISPACKED && 680!refs_peel_ref(refs->packed_ref_store, refname, sha1)) 681return0; 682 683returnpeel_object(base, sha1); 684} 685 686struct files_ref_iterator { 687struct ref_iterator base; 688 689struct ref_iterator *iter0; 690unsigned int flags; 691}; 692 693static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 694{ 695struct files_ref_iterator *iter = 696(struct files_ref_iterator *)ref_iterator; 697int ok; 698 699while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 700if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 701ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE) 702continue; 703 704if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 705!ref_resolves_to_object(iter->iter0->refname, 706 iter->iter0->oid, 707 iter->iter0->flags)) 708continue; 709 710 iter->base.refname = iter->iter0->refname; 711 iter->base.oid = iter->iter0->oid; 712 iter->base.flags = iter->iter0->flags; 713return ITER_OK; 714} 715 716 iter->iter0 = NULL; 717if(ref_iterator_abort(ref_iterator) != ITER_DONE) 718 ok = ITER_ERROR; 719 720return ok; 721} 722 723static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator, 724struct object_id *peeled) 725{ 726struct files_ref_iterator *iter = 727(struct files_ref_iterator *)ref_iterator; 728 729returnref_iterator_peel(iter->iter0, peeled); 730} 731 732static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator) 733{ 734struct files_ref_iterator *iter = 735(struct files_ref_iterator *)ref_iterator; 736int ok = ITER_DONE; 737 738if(iter->iter0) 739 ok =ref_iterator_abort(iter->iter0); 740 741base_ref_iterator_free(ref_iterator); 742return ok; 743} 744 745static struct ref_iterator_vtable files_ref_iterator_vtable = { 746 files_ref_iterator_advance, 747 files_ref_iterator_peel, 748 files_ref_iterator_abort 749}; 750 751static struct ref_iterator *files_ref_iterator_begin( 752struct ref_store *ref_store, 753const char*prefix,unsigned int flags) 754{ 755struct files_ref_store *refs; 756struct ref_iterator *loose_iter, *packed_iter; 757struct files_ref_iterator *iter; 758struct ref_iterator *ref_iterator; 759unsigned int required_flags = REF_STORE_READ; 760 761if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) 762 required_flags |= REF_STORE_ODB; 763 764 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin"); 765 766 iter =xcalloc(1,sizeof(*iter)); 767 ref_iterator = &iter->base; 768base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable); 769 770/* 771 * We must make sure that all loose refs are read before 772 * accessing the packed-refs file; this avoids a race 773 * condition if loose refs are migrated to the packed-refs 774 * file by a simultaneous process, but our in-memory view is 775 * from before the migration. We ensure this as follows: 776 * First, we call start the loose refs iteration with its 777 * `prime_ref` argument set to true. This causes the loose 778 * references in the subtree to be pre-read into the cache. 779 * (If they've already been read, that's OK; we only need to 780 * guarantee that they're read before the packed refs, not 781 * *how much* before.) After that, we call 782 * packed_ref_iterator_begin(), which internally checks 783 * whether the packed-ref cache is up to date with what is on 784 * disk, and re-reads it if not. 785 */ 786 787 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), 788 prefix,1); 789 790/* 791 * The packed-refs file might contain broken references, for 792 * example an old version of a reference that points at an 793 * object that has since been garbage-collected. This is OK as 794 * long as there is a corresponding loose reference that 795 * overrides it, and we don't want to emit an error message in 796 * this case. So ask the packed_ref_store for all of its 797 * references, and (if needed) do our own check for broken 798 * ones in files_ref_iterator_advance(), after we have merged 799 * the packed and loose references. 800 */ 801 packed_iter =refs_ref_iterator_begin( 802 refs->packed_ref_store, prefix,0, 803 DO_FOR_EACH_INCLUDE_BROKEN); 804 805 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter); 806 iter->flags = flags; 807 808return ref_iterator; 809} 810 811/* 812 * Verify that the reference locked by lock has the value old_sha1. 813 * Fail if the reference doesn't exist and mustexist is set. Return 0 814 * on success. On error, write an error message to err, set errno, and 815 * return a negative value. 816 */ 817static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock, 818const unsigned char*old_sha1,int mustexist, 819struct strbuf *err) 820{ 821assert(err); 822 823if(refs_read_ref_full(ref_store, lock->ref_name, 824 mustexist ? RESOLVE_REF_READING :0, 825 lock->old_oid.hash, NULL)) { 826if(old_sha1) { 827int save_errno = errno; 828strbuf_addf(err,"can't verify ref '%s'", lock->ref_name); 829 errno = save_errno; 830return-1; 831}else{ 832oidclr(&lock->old_oid); 833return0; 834} 835} 836if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) { 837strbuf_addf(err,"ref '%s' is at%sbut expected%s", 838 lock->ref_name, 839oid_to_hex(&lock->old_oid), 840sha1_to_hex(old_sha1)); 841 errno = EBUSY; 842return-1; 843} 844return0; 845} 846 847static intremove_empty_directories(struct strbuf *path) 848{ 849/* 850 * we want to create a file but there is a directory there; 851 * if that is an empty directory (or a directory that contains 852 * only empty directories), remove them. 853 */ 854returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY); 855} 856 857static intcreate_reflock(const char*path,void*cb) 858{ 859struct lock_file *lk = cb; 860 861returnhold_lock_file_for_update_timeout( 862 lk, path, LOCK_NO_DEREF, 863get_files_ref_lock_timeout_ms()) <0? -1:0; 864} 865 866/* 867 * Locks a ref returning the lock on success and NULL on failure. 868 * On failure errno is set to something meaningful. 869 */ 870static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs, 871const char*refname, 872const unsigned char*old_sha1, 873const struct string_list *extras, 874const struct string_list *skip, 875unsigned int flags,int*type, 876struct strbuf *err) 877{ 878struct strbuf ref_file = STRBUF_INIT; 879struct ref_lock *lock; 880int last_errno =0; 881int mustexist = (old_sha1 && !is_null_sha1(old_sha1)); 882int resolve_flags = RESOLVE_REF_NO_RECURSE; 883int resolved; 884 885files_assert_main_repository(refs,"lock_ref_sha1_basic"); 886assert(err); 887 888 lock =xcalloc(1,sizeof(struct ref_lock)); 889 890if(mustexist) 891 resolve_flags |= RESOLVE_REF_READING; 892if(flags & REF_DELETING) 893 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME; 894 895files_ref_path(refs, &ref_file, refname); 896 resolved = !!refs_resolve_ref_unsafe(&refs->base, 897 refname, resolve_flags, 898 lock->old_oid.hash, type); 899if(!resolved && errno == EISDIR) { 900/* 901 * we are trying to lock foo but we used to 902 * have foo/bar which now does not exist; 903 * it is normal for the empty directory 'foo' 904 * to remain. 905 */ 906if(remove_empty_directories(&ref_file)) { 907 last_errno = errno; 908if(!refs_verify_refname_available( 909&refs->base, 910 refname, extras, skip, err)) 911strbuf_addf(err,"there are still refs under '%s'", 912 refname); 913goto error_return; 914} 915 resolved = !!refs_resolve_ref_unsafe(&refs->base, 916 refname, resolve_flags, 917 lock->old_oid.hash, type); 918} 919if(!resolved) { 920 last_errno = errno; 921if(last_errno != ENOTDIR || 922!refs_verify_refname_available(&refs->base, refname, 923 extras, skip, err)) 924strbuf_addf(err,"unable to resolve reference '%s':%s", 925 refname,strerror(last_errno)); 926 927goto error_return; 928} 929 930/* 931 * If the ref did not exist and we are creating it, make sure 932 * there is no existing packed ref whose name begins with our 933 * refname, nor a packed ref whose name is a proper prefix of 934 * our refname. 935 */ 936if(is_null_oid(&lock->old_oid) && 937refs_verify_refname_available(refs->packed_ref_store, refname, 938 extras, skip, err)) { 939 last_errno = ENOTDIR; 940goto error_return; 941} 942 943 lock->lk =xcalloc(1,sizeof(struct lock_file)); 944 945 lock->ref_name =xstrdup(refname); 946 947if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) { 948 last_errno = errno; 949unable_to_lock_message(ref_file.buf, errno, err); 950goto error_return; 951} 952 953if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) { 954 last_errno = errno; 955goto error_return; 956} 957goto out; 958 959 error_return: 960unlock_ref(lock); 961 lock = NULL; 962 963 out: 964strbuf_release(&ref_file); 965 errno = last_errno; 966return lock; 967} 968 969struct ref_to_prune { 970struct ref_to_prune *next; 971unsigned char sha1[20]; 972char name[FLEX_ARRAY]; 973}; 974 975enum{ 976 REMOVE_EMPTY_PARENTS_REF =0x01, 977 REMOVE_EMPTY_PARENTS_REFLOG =0x02 978}; 979 980/* 981 * Remove empty parent directories associated with the specified 982 * reference and/or its reflog, but spare [logs/]refs/ and immediate 983 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or 984 * REMOVE_EMPTY_PARENTS_REFLOG. 985 */ 986static voidtry_remove_empty_parents(struct files_ref_store *refs, 987const char*refname, 988unsigned int flags) 989{ 990struct strbuf buf = STRBUF_INIT; 991struct strbuf sb = STRBUF_INIT; 992char*p, *q; 993int i; 994 995strbuf_addstr(&buf, refname); 996 p = buf.buf; 997for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */ 998while(*p && *p !='/') 999 p++;1000/* tolerate duplicate slashes; see check_refname_format() */1001while(*p =='/')1002 p++;1003}1004 q = buf.buf + buf.len;1005while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1006while(q > p && *q !='/')1007 q--;1008while(q > p && *(q-1) =='/')1009 q--;1010if(q == p)1011break;1012strbuf_setlen(&buf, q - buf.buf);10131014strbuf_reset(&sb);1015files_ref_path(refs, &sb, buf.buf);1016if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1017 flags &= ~REMOVE_EMPTY_PARENTS_REF;10181019strbuf_reset(&sb);1020files_reflog_path(refs, &sb, buf.buf);1021if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1022 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1023}1024strbuf_release(&buf);1025strbuf_release(&sb);1026}10271028/* make sure nobody touched the ref, and unlink */1029static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1030{1031struct ref_transaction *transaction;1032struct strbuf err = STRBUF_INIT;10331034if(check_refname_format(r->name,0))1035return;10361037 transaction =ref_store_transaction_begin(&refs->base, &err);1038if(!transaction ||1039ref_transaction_delete(transaction, r->name, r->sha1,1040 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1041ref_transaction_commit(transaction, &err)) {1042ref_transaction_free(transaction);1043error("%s", err.buf);1044strbuf_release(&err);1045return;1046}1047ref_transaction_free(transaction);1048strbuf_release(&err);1049}10501051static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1052{1053while(r) {1054prune_ref(refs, r);1055 r = r->next;1056}1057}10581059/*1060 * Return true if the specified reference should be packed.1061 */1062static intshould_pack_ref(const char*refname,1063const struct object_id *oid,unsigned int ref_flags,1064unsigned int pack_flags)1065{1066/* Do not pack per-worktree refs: */1067if(ref_type(refname) != REF_TYPE_NORMAL)1068return0;10691070/* Do not pack non-tags unless PACK_REFS_ALL is set: */1071if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1072return0;10731074/* Do not pack symbolic refs: */1075if(ref_flags & REF_ISSYMREF)1076return0;10771078/* Do not pack broken refs: */1079if(!ref_resolves_to_object(refname, oid, ref_flags))1080return0;10811082return1;1083}10841085static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1086{1087struct files_ref_store *refs =1088files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1089"pack_refs");1090struct ref_iterator *iter;1091int ok;1092struct ref_to_prune *refs_to_prune = NULL;1093struct strbuf err = STRBUF_INIT;10941095packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);10961097 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1098while((ok =ref_iterator_advance(iter)) == ITER_OK) {1099/*1100 * If the loose reference can be packed, add an entry1101 * in the packed ref cache. If the reference should be1102 * pruned, also add it to refs_to_prune.1103 */1104if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1105 flags))1106continue;11071108/*1109 * Create an entry in the packed-refs cache equivalent1110 * to the one from the loose ref cache, except that1111 * we don't copy the peeled status, because we want it1112 * to be re-peeled.1113 */1114add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);11151116/* Schedule the loose reference for pruning if requested. */1117if((flags & PACK_REFS_PRUNE)) {1118struct ref_to_prune *n;1119FLEX_ALLOC_STR(n, name, iter->refname);1120hashcpy(n->sha1, iter->oid->hash);1121 n->next = refs_to_prune;1122 refs_to_prune = n;1123}1124}1125if(ok != ITER_DONE)1126die("error while iterating over references");11271128if(commit_packed_refs(refs->packed_ref_store, &err))1129die("unable to overwrite old ref-pack file:%s", err.buf);1130packed_refs_unlock(refs->packed_ref_store);11311132prune_refs(refs, refs_to_prune);1133strbuf_release(&err);1134return0;1135}11361137static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1138struct string_list *refnames,unsigned int flags)1139{1140struct files_ref_store *refs =1141files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1142struct strbuf err = STRBUF_INIT;1143int i, result =0;11441145if(!refnames->nr)1146return0;11471148if(packed_refs_lock(refs->packed_ref_store,0, &err))1149goto error;11501151if(repack_without_refs(refs->packed_ref_store, refnames, &err)) {1152packed_refs_unlock(refs->packed_ref_store);1153goto error;1154}11551156packed_refs_unlock(refs->packed_ref_store);11571158for(i =0; i < refnames->nr; i++) {1159const char*refname = refnames->items[i].string;11601161if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1162 result |=error(_("could not remove reference%s"), refname);1163}11641165strbuf_release(&err);1166return result;11671168error:1169/*1170 * If we failed to rewrite the packed-refs file, then it is1171 * unsafe to try to remove loose refs, because doing so might1172 * expose an obsolete packed value for a reference that might1173 * even point at an object that has been garbage collected.1174 */1175if(refnames->nr ==1)1176error(_("could not delete reference%s:%s"),1177 refnames->items[0].string, err.buf);1178else1179error(_("could not delete references:%s"), err.buf);11801181strbuf_release(&err);1182return-1;1183}11841185/*1186 * People using contrib's git-new-workdir have .git/logs/refs ->1187 * /some/other/path/.git/logs/refs, and that may live on another device.1188 *1189 * IOW, to avoid cross device rename errors, the temporary renamed log must1190 * live into logs/refs.1191 */1192#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"11931194struct rename_cb {1195const char*tmp_renamed_log;1196int true_errno;1197};11981199static intrename_tmp_log_callback(const char*path,void*cb_data)1200{1201struct rename_cb *cb = cb_data;12021203if(rename(cb->tmp_renamed_log, path)) {1204/*1205 * rename(a, b) when b is an existing directory ought1206 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1207 * Sheesh. Record the true errno for error reporting,1208 * but report EISDIR to raceproof_create_file() so1209 * that it knows to retry.1210 */1211 cb->true_errno = errno;1212if(errno == ENOTDIR)1213 errno = EISDIR;1214return-1;1215}else{1216return0;1217}1218}12191220static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1221{1222struct strbuf path = STRBUF_INIT;1223struct strbuf tmp = STRBUF_INIT;1224struct rename_cb cb;1225int ret;12261227files_reflog_path(refs, &path, newrefname);1228files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1229 cb.tmp_renamed_log = tmp.buf;1230 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1231if(ret) {1232if(errno == EISDIR)1233error("directory not empty:%s", path.buf);1234else1235error("unable to move logfile%sto%s:%s",1236 tmp.buf, path.buf,1237strerror(cb.true_errno));1238}12391240strbuf_release(&path);1241strbuf_release(&tmp);1242return ret;1243}12441245static intwrite_ref_to_lockfile(struct ref_lock *lock,1246const struct object_id *oid,struct strbuf *err);1247static intcommit_ref_update(struct files_ref_store *refs,1248struct ref_lock *lock,1249const struct object_id *oid,const char*logmsg,1250struct strbuf *err);12511252static intfiles_rename_ref(struct ref_store *ref_store,1253const char*oldrefname,const char*newrefname,1254const char*logmsg)1255{1256struct files_ref_store *refs =1257files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1258struct object_id oid, orig_oid;1259int flag =0, logmoved =0;1260struct ref_lock *lock;1261struct stat loginfo;1262struct strbuf sb_oldref = STRBUF_INIT;1263struct strbuf sb_newref = STRBUF_INIT;1264struct strbuf tmp_renamed_log = STRBUF_INIT;1265int log, ret;1266struct strbuf err = STRBUF_INIT;12671268files_reflog_path(refs, &sb_oldref, oldrefname);1269files_reflog_path(refs, &sb_newref, newrefname);1270files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12711272 log = !lstat(sb_oldref.buf, &loginfo);1273if(log &&S_ISLNK(loginfo.st_mode)) {1274 ret =error("reflog for%sis a symlink", oldrefname);1275goto out;1276}12771278if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1279 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1280 orig_oid.hash, &flag)) {1281 ret =error("refname%snot found", oldrefname);1282goto out;1283}12841285if(flag & REF_ISSYMREF) {1286 ret =error("refname%sis a symbolic ref, renaming it is not supported",1287 oldrefname);1288goto out;1289}1290if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1291 ret =1;1292goto out;1293}12941295if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1296 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1297 oldrefname,strerror(errno));1298goto out;1299}13001301if(refs_delete_ref(&refs->base, logmsg, oldrefname,1302 orig_oid.hash, REF_NODEREF)) {1303error("unable to delete old%s", oldrefname);1304goto rollback;1305}13061307/*1308 * Since we are doing a shallow lookup, oid is not the1309 * correct value to pass to delete_ref as old_oid. But that1310 * doesn't matter, because an old_oid check wouldn't add to1311 * the safety anyway; we want to delete the reference whatever1312 * its current value.1313 */1314if(!refs_read_ref_full(&refs->base, newrefname,1315 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1316 oid.hash, NULL) &&1317refs_delete_ref(&refs->base, NULL, newrefname,1318 NULL, REF_NODEREF)) {1319if(errno == EISDIR) {1320struct strbuf path = STRBUF_INIT;1321int result;13221323files_ref_path(refs, &path, newrefname);1324 result =remove_empty_directories(&path);1325strbuf_release(&path);13261327if(result) {1328error("Directory not empty:%s", newrefname);1329goto rollback;1330}1331}else{1332error("unable to delete existing%s", newrefname);1333goto rollback;1334}1335}13361337if(log &&rename_tmp_log(refs, newrefname))1338goto rollback;13391340 logmoved = log;13411342 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1343 REF_NODEREF, NULL, &err);1344if(!lock) {1345error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1346strbuf_release(&err);1347goto rollback;1348}1349oidcpy(&lock->old_oid, &orig_oid);13501351if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1352commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1353error("unable to write current sha1 into%s:%s", newrefname, err.buf);1354strbuf_release(&err);1355goto rollback;1356}13571358 ret =0;1359goto out;13601361 rollback:1362 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1363 REF_NODEREF, NULL, &err);1364if(!lock) {1365error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1366strbuf_release(&err);1367goto rollbacklog;1368}13691370 flag = log_all_ref_updates;1371 log_all_ref_updates = LOG_REFS_NONE;1372if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1373commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1374error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1375strbuf_release(&err);1376}1377 log_all_ref_updates = flag;13781379 rollbacklog:1380if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1381error("unable to restore logfile%sfrom%s:%s",1382 oldrefname, newrefname,strerror(errno));1383if(!logmoved && log &&1384rename(tmp_renamed_log.buf, sb_oldref.buf))1385error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1386 oldrefname,strerror(errno));1387 ret =1;1388 out:1389strbuf_release(&sb_newref);1390strbuf_release(&sb_oldref);1391strbuf_release(&tmp_renamed_log);13921393return ret;1394}13951396static intclose_ref(struct ref_lock *lock)1397{1398if(close_lock_file(lock->lk))1399return-1;1400return0;1401}14021403static intcommit_ref(struct ref_lock *lock)1404{1405char*path =get_locked_file_path(lock->lk);1406struct stat st;14071408if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1409/*1410 * There is a directory at the path we want to rename1411 * the lockfile to. Hopefully it is empty; try to1412 * delete it.1413 */1414size_t len =strlen(path);1415struct strbuf sb_path = STRBUF_INIT;14161417strbuf_attach(&sb_path, path, len, len);14181419/*1420 * If this fails, commit_lock_file() will also fail1421 * and will report the problem.1422 */1423remove_empty_directories(&sb_path);1424strbuf_release(&sb_path);1425}else{1426free(path);1427}14281429if(commit_lock_file(lock->lk))1430return-1;1431return0;1432}14331434static intopen_or_create_logfile(const char*path,void*cb)1435{1436int*fd = cb;14371438*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1439return(*fd <0) ? -1:0;1440}14411442/*1443 * Create a reflog for a ref. If force_create = 0, only create the1444 * reflog for certain refs (those for which should_autocreate_reflog1445 * returns non-zero). Otherwise, create it regardless of the reference1446 * name. If the logfile already existed or was created, return 0 and1447 * set *logfd to the file descriptor opened for appending to the file.1448 * If no logfile exists and we decided not to create one, return 0 and1449 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1450 * return -1.1451 */1452static intlog_ref_setup(struct files_ref_store *refs,1453const char*refname,int force_create,1454int*logfd,struct strbuf *err)1455{1456struct strbuf logfile_sb = STRBUF_INIT;1457char*logfile;14581459files_reflog_path(refs, &logfile_sb, refname);1460 logfile =strbuf_detach(&logfile_sb, NULL);14611462if(force_create ||should_autocreate_reflog(refname)) {1463if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1464if(errno == ENOENT)1465strbuf_addf(err,"unable to create directory for '%s': "1466"%s", logfile,strerror(errno));1467else if(errno == EISDIR)1468strbuf_addf(err,"there are still logs under '%s'",1469 logfile);1470else1471strbuf_addf(err,"unable to append to '%s':%s",1472 logfile,strerror(errno));14731474goto error;1475}1476}else{1477*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1478if(*logfd <0) {1479if(errno == ENOENT || errno == EISDIR) {1480/*1481 * The logfile doesn't already exist,1482 * but that is not an error; it only1483 * means that we won't write log1484 * entries to it.1485 */1486;1487}else{1488strbuf_addf(err,"unable to append to '%s':%s",1489 logfile,strerror(errno));1490goto error;1491}1492}1493}14941495if(*logfd >=0)1496adjust_shared_perm(logfile);14971498free(logfile);1499return0;15001501error:1502free(logfile);1503return-1;1504}15051506static intfiles_create_reflog(struct ref_store *ref_store,1507const char*refname,int force_create,1508struct strbuf *err)1509{1510struct files_ref_store *refs =1511files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1512int fd;15131514if(log_ref_setup(refs, refname, force_create, &fd, err))1515return-1;15161517if(fd >=0)1518close(fd);15191520return0;1521}15221523static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1524const struct object_id *new_oid,1525const char*committer,const char*msg)1526{1527int msglen, written;1528unsigned maxlen, len;1529char*logrec;15301531 msglen = msg ?strlen(msg) :0;1532 maxlen =strlen(committer) + msglen +100;1533 logrec =xmalloc(maxlen);1534 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1535oid_to_hex(old_oid),1536oid_to_hex(new_oid),1537 committer);1538if(msglen)1539 len +=copy_reflog_msg(logrec + len -1, msg) -1;15401541 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1542free(logrec);1543if(written != len)1544return-1;15451546return0;1547}15481549static intfiles_log_ref_write(struct files_ref_store *refs,1550const char*refname,const struct object_id *old_oid,1551const struct object_id *new_oid,const char*msg,1552int flags,struct strbuf *err)1553{1554int logfd, result;15551556if(log_all_ref_updates == LOG_REFS_UNSET)1557 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15581559 result =log_ref_setup(refs, refname,1560 flags & REF_FORCE_CREATE_REFLOG,1561&logfd, err);15621563if(result)1564return result;15651566if(logfd <0)1567return0;1568 result =log_ref_write_fd(logfd, old_oid, new_oid,1569git_committer_info(0), msg);1570if(result) {1571struct strbuf sb = STRBUF_INIT;1572int save_errno = errno;15731574files_reflog_path(refs, &sb, refname);1575strbuf_addf(err,"unable to append to '%s':%s",1576 sb.buf,strerror(save_errno));1577strbuf_release(&sb);1578close(logfd);1579return-1;1580}1581if(close(logfd)) {1582struct strbuf sb = STRBUF_INIT;1583int save_errno = errno;15841585files_reflog_path(refs, &sb, refname);1586strbuf_addf(err,"unable to append to '%s':%s",1587 sb.buf,strerror(save_errno));1588strbuf_release(&sb);1589return-1;1590}1591return0;1592}15931594/*1595 * Write sha1 into the open lockfile, then close the lockfile. On1596 * errors, rollback the lockfile, fill in *err and1597 * return -1.1598 */1599static intwrite_ref_to_lockfile(struct ref_lock *lock,1600const struct object_id *oid,struct strbuf *err)1601{1602static char term ='\n';1603struct object *o;1604int fd;16051606 o =parse_object(oid);1607if(!o) {1608strbuf_addf(err,1609"trying to write ref '%s' with nonexistent object%s",1610 lock->ref_name,oid_to_hex(oid));1611unlock_ref(lock);1612return-1;1613}1614if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1615strbuf_addf(err,1616"trying to write non-commit object%sto branch '%s'",1617oid_to_hex(oid), lock->ref_name);1618unlock_ref(lock);1619return-1;1620}1621 fd =get_lock_file_fd(lock->lk);1622if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1623write_in_full(fd, &term,1) !=1||1624close_ref(lock) <0) {1625strbuf_addf(err,1626"couldn't write '%s'",get_lock_file_path(lock->lk));1627unlock_ref(lock);1628return-1;1629}1630return0;1631}16321633/*1634 * Commit a change to a loose reference that has already been written1635 * to the loose reference lockfile. Also update the reflogs if1636 * necessary, using the specified lockmsg (which can be NULL).1637 */1638static intcommit_ref_update(struct files_ref_store *refs,1639struct ref_lock *lock,1640const struct object_id *oid,const char*logmsg,1641struct strbuf *err)1642{1643files_assert_main_repository(refs,"commit_ref_update");16441645clear_loose_ref_cache(refs);1646if(files_log_ref_write(refs, lock->ref_name,1647&lock->old_oid, oid,1648 logmsg,0, err)) {1649char*old_msg =strbuf_detach(err, NULL);1650strbuf_addf(err,"cannot update the ref '%s':%s",1651 lock->ref_name, old_msg);1652free(old_msg);1653unlock_ref(lock);1654return-1;1655}16561657if(strcmp(lock->ref_name,"HEAD") !=0) {1658/*1659 * Special hack: If a branch is updated directly and HEAD1660 * points to it (may happen on the remote side of a push1661 * for example) then logically the HEAD reflog should be1662 * updated too.1663 * A generic solution implies reverse symref information,1664 * but finding all symrefs pointing to the given branch1665 * would be rather costly for this rare event (the direct1666 * update of a branch) to be worth it. So let's cheat and1667 * check with HEAD only which should cover 99% of all usage1668 * scenarios (even 100% of the default ones).1669 */1670struct object_id head_oid;1671int head_flag;1672const char*head_ref;16731674 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1675 RESOLVE_REF_READING,1676 head_oid.hash, &head_flag);1677if(head_ref && (head_flag & REF_ISSYMREF) &&1678!strcmp(head_ref, lock->ref_name)) {1679struct strbuf log_err = STRBUF_INIT;1680if(files_log_ref_write(refs,"HEAD",1681&lock->old_oid, oid,1682 logmsg,0, &log_err)) {1683error("%s", log_err.buf);1684strbuf_release(&log_err);1685}1686}1687}16881689if(commit_ref(lock)) {1690strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1691unlock_ref(lock);1692return-1;1693}16941695unlock_ref(lock);1696return0;1697}16981699static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1700{1701int ret = -1;1702#ifndef NO_SYMLINK_HEAD1703char*ref_path =get_locked_file_path(lock->lk);1704unlink(ref_path);1705 ret =symlink(target, ref_path);1706free(ref_path);17071708if(ret)1709fprintf(stderr,"no symlink - falling back to symbolic ref\n");1710#endif1711return ret;1712}17131714static voidupdate_symref_reflog(struct files_ref_store *refs,1715struct ref_lock *lock,const char*refname,1716const char*target,const char*logmsg)1717{1718struct strbuf err = STRBUF_INIT;1719struct object_id new_oid;1720if(logmsg &&1721!refs_read_ref_full(&refs->base, target,1722 RESOLVE_REF_READING, new_oid.hash, NULL) &&1723files_log_ref_write(refs, refname, &lock->old_oid,1724&new_oid, logmsg,0, &err)) {1725error("%s", err.buf);1726strbuf_release(&err);1727}1728}17291730static intcreate_symref_locked(struct files_ref_store *refs,1731struct ref_lock *lock,const char*refname,1732const char*target,const char*logmsg)1733{1734if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1735update_symref_reflog(refs, lock, refname, target, logmsg);1736return0;1737}17381739if(!fdopen_lock_file(lock->lk,"w"))1740returnerror("unable to fdopen%s:%s",1741 lock->lk->tempfile.filename.buf,strerror(errno));17421743update_symref_reflog(refs, lock, refname, target, logmsg);17441745/* no error check; commit_ref will check ferror */1746fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);1747if(commit_ref(lock) <0)1748returnerror("unable to write symref for%s:%s", refname,1749strerror(errno));1750return0;1751}17521753static intfiles_create_symref(struct ref_store *ref_store,1754const char*refname,const char*target,1755const char*logmsg)1756{1757struct files_ref_store *refs =1758files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1759struct strbuf err = STRBUF_INIT;1760struct ref_lock *lock;1761int ret;17621763 lock =lock_ref_sha1_basic(refs, refname, NULL,1764 NULL, NULL, REF_NODEREF, NULL,1765&err);1766if(!lock) {1767error("%s", err.buf);1768strbuf_release(&err);1769return-1;1770}17711772 ret =create_symref_locked(refs, lock, refname, target, logmsg);1773unlock_ref(lock);1774return ret;1775}17761777static intfiles_reflog_exists(struct ref_store *ref_store,1778const char*refname)1779{1780struct files_ref_store *refs =1781files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1782struct strbuf sb = STRBUF_INIT;1783struct stat st;1784int ret;17851786files_reflog_path(refs, &sb, refname);1787 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1788strbuf_release(&sb);1789return ret;1790}17911792static intfiles_delete_reflog(struct ref_store *ref_store,1793const char*refname)1794{1795struct files_ref_store *refs =1796files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1797struct strbuf sb = STRBUF_INIT;1798int ret;17991800files_reflog_path(refs, &sb, refname);1801 ret =remove_path(sb.buf);1802strbuf_release(&sb);1803return ret;1804}18051806static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1807{1808struct object_id ooid, noid;1809char*email_end, *message;1810 timestamp_t timestamp;1811int tz;1812const char*p = sb->buf;18131814/* old SP new SP name <email> SP time TAB msg LF */1815if(!sb->len || sb->buf[sb->len -1] !='\n'||1816parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1817parse_oid_hex(p, &noid, &p) || *p++ !=' '||1818!(email_end =strchr(p,'>')) ||1819 email_end[1] !=' '||1820!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1821!message || message[0] !=' '||1822(message[1] !='+'&& message[1] !='-') ||1823!isdigit(message[2]) || !isdigit(message[3]) ||1824!isdigit(message[4]) || !isdigit(message[5]))1825return0;/* corrupt? */1826 email_end[1] ='\0';1827 tz =strtol(message +1, NULL,10);1828if(message[6] !='\t')1829 message +=6;1830else1831 message +=7;1832returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1833}18341835static char*find_beginning_of_line(char*bob,char*scan)1836{1837while(bob < scan && *(--scan) !='\n')1838;/* keep scanning backwards */1839/*1840 * Return either beginning of the buffer, or LF at the end of1841 * the previous line.1842 */1843return scan;1844}18451846static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1847const char*refname,1848 each_reflog_ent_fn fn,1849void*cb_data)1850{1851struct files_ref_store *refs =1852files_downcast(ref_store, REF_STORE_READ,1853"for_each_reflog_ent_reverse");1854struct strbuf sb = STRBUF_INIT;1855FILE*logfp;1856long pos;1857int ret =0, at_tail =1;18581859files_reflog_path(refs, &sb, refname);1860 logfp =fopen(sb.buf,"r");1861strbuf_release(&sb);1862if(!logfp)1863return-1;18641865/* Jump to the end */1866if(fseek(logfp,0, SEEK_END) <0)1867 ret =error("cannot seek back reflog for%s:%s",1868 refname,strerror(errno));1869 pos =ftell(logfp);1870while(!ret &&0< pos) {1871int cnt;1872size_t nread;1873char buf[BUFSIZ];1874char*endp, *scanp;18751876/* Fill next block from the end */1877 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1878if(fseek(logfp, pos - cnt, SEEK_SET)) {1879 ret =error("cannot seek back reflog for%s:%s",1880 refname,strerror(errno));1881break;1882}1883 nread =fread(buf, cnt,1, logfp);1884if(nread !=1) {1885 ret =error("cannot read%dbytes from reflog for%s:%s",1886 cnt, refname,strerror(errno));1887break;1888}1889 pos -= cnt;18901891 scanp = endp = buf + cnt;1892if(at_tail && scanp[-1] =='\n')1893/* Looking at the final LF at the end of the file */1894 scanp--;1895 at_tail =0;18961897while(buf < scanp) {1898/*1899 * terminating LF of the previous line, or the beginning1900 * of the buffer.1901 */1902char*bp;19031904 bp =find_beginning_of_line(buf, scanp);19051906if(*bp =='\n') {1907/*1908 * The newline is the end of the previous line,1909 * so we know we have complete line starting1910 * at (bp + 1). Prefix it onto any prior data1911 * we collected for the line and process it.1912 */1913strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1914 scanp = bp;1915 endp = bp +1;1916 ret =show_one_reflog_ent(&sb, fn, cb_data);1917strbuf_reset(&sb);1918if(ret)1919break;1920}else if(!pos) {1921/*1922 * We are at the start of the buffer, and the1923 * start of the file; there is no previous1924 * line, and we have everything for this one.1925 * Process it, and we can end the loop.1926 */1927strbuf_splice(&sb,0,0, buf, endp - buf);1928 ret =show_one_reflog_ent(&sb, fn, cb_data);1929strbuf_reset(&sb);1930break;1931}19321933if(bp == buf) {1934/*1935 * We are at the start of the buffer, and there1936 * is more file to read backwards. Which means1937 * we are in the middle of a line. Note that we1938 * may get here even if *bp was a newline; that1939 * just means we are at the exact end of the1940 * previous line, rather than some spot in the1941 * middle.1942 *1943 * Save away what we have to be combined with1944 * the data from the next read.1945 */1946strbuf_splice(&sb,0,0, buf, endp - buf);1947break;1948}1949}19501951}1952if(!ret && sb.len)1953die("BUG: reverse reflog parser had leftover data");19541955fclose(logfp);1956strbuf_release(&sb);1957return ret;1958}19591960static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1961const char*refname,1962 each_reflog_ent_fn fn,void*cb_data)1963{1964struct files_ref_store *refs =1965files_downcast(ref_store, REF_STORE_READ,1966"for_each_reflog_ent");1967FILE*logfp;1968struct strbuf sb = STRBUF_INIT;1969int ret =0;19701971files_reflog_path(refs, &sb, refname);1972 logfp =fopen(sb.buf,"r");1973strbuf_release(&sb);1974if(!logfp)1975return-1;19761977while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1978 ret =show_one_reflog_ent(&sb, fn, cb_data);1979fclose(logfp);1980strbuf_release(&sb);1981return ret;1982}19831984struct files_reflog_iterator {1985struct ref_iterator base;19861987struct ref_store *ref_store;1988struct dir_iterator *dir_iterator;1989struct object_id oid;1990};19911992static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)1993{1994struct files_reflog_iterator *iter =1995(struct files_reflog_iterator *)ref_iterator;1996struct dir_iterator *diter = iter->dir_iterator;1997int ok;19981999while((ok =dir_iterator_advance(diter)) == ITER_OK) {2000int flags;20012002if(!S_ISREG(diter->st.st_mode))2003continue;2004if(diter->basename[0] =='.')2005continue;2006if(ends_with(diter->basename,".lock"))2007continue;20082009if(refs_read_ref_full(iter->ref_store,2010 diter->relative_path,0,2011 iter->oid.hash, &flags)) {2012error("bad ref for%s", diter->path.buf);2013continue;2014}20152016 iter->base.refname = diter->relative_path;2017 iter->base.oid = &iter->oid;2018 iter->base.flags = flags;2019return ITER_OK;2020}20212022 iter->dir_iterator = NULL;2023if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2024 ok = ITER_ERROR;2025return ok;2026}20272028static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2029struct object_id *peeled)2030{2031die("BUG: ref_iterator_peel() called for reflog_iterator");2032}20332034static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2035{2036struct files_reflog_iterator *iter =2037(struct files_reflog_iterator *)ref_iterator;2038int ok = ITER_DONE;20392040if(iter->dir_iterator)2041 ok =dir_iterator_abort(iter->dir_iterator);20422043base_ref_iterator_free(ref_iterator);2044return ok;2045}20462047static struct ref_iterator_vtable files_reflog_iterator_vtable = {2048 files_reflog_iterator_advance,2049 files_reflog_iterator_peel,2050 files_reflog_iterator_abort2051};20522053static struct ref_iterator *reflog_iterator_begin(struct ref_store *ref_store,2054const char*gitdir)2055{2056struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2057struct ref_iterator *ref_iterator = &iter->base;2058struct strbuf sb = STRBUF_INIT;20592060base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2061strbuf_addf(&sb,"%s/logs", gitdir);2062 iter->dir_iterator =dir_iterator_begin(sb.buf);2063 iter->ref_store = ref_store;2064strbuf_release(&sb);20652066return ref_iterator;2067}20682069static enum iterator_selection reflog_iterator_select(2070struct ref_iterator *iter_worktree,2071struct ref_iterator *iter_common,2072void*cb_data)2073{2074if(iter_worktree) {2075/*2076 * We're a bit loose here. We probably should ignore2077 * common refs if they are accidentally added as2078 * per-worktree refs.2079 */2080return ITER_SELECT_0;2081}else if(iter_common) {2082if(ref_type(iter_common->refname) == REF_TYPE_NORMAL)2083return ITER_SELECT_1;20842085/*2086 * The main ref store may contain main worktree's2087 * per-worktree refs, which should be ignored2088 */2089return ITER_SKIP_1;2090}else2091return ITER_DONE;2092}20932094static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2095{2096struct files_ref_store *refs =2097files_downcast(ref_store, REF_STORE_READ,2098"reflog_iterator_begin");20992100if(!strcmp(refs->gitdir, refs->gitcommondir)) {2101returnreflog_iterator_begin(ref_store, refs->gitcommondir);2102}else{2103returnmerge_ref_iterator_begin(2104reflog_iterator_begin(ref_store, refs->gitdir),2105reflog_iterator_begin(ref_store, refs->gitcommondir),2106 reflog_iterator_select, refs);2107}2108}21092110/*2111 * If update is a direct update of head_ref (the reference pointed to2112 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2113 */2114static intsplit_head_update(struct ref_update *update,2115struct ref_transaction *transaction,2116const char*head_ref,2117struct string_list *affected_refnames,2118struct strbuf *err)2119{2120struct string_list_item *item;2121struct ref_update *new_update;21222123if((update->flags & REF_LOG_ONLY) ||2124(update->flags & REF_ISPRUNING) ||2125(update->flags & REF_UPDATE_VIA_HEAD))2126return0;21272128if(strcmp(update->refname, head_ref))2129return0;21302131/*2132 * First make sure that HEAD is not already in the2133 * transaction. This check is O(lg N) in the transaction2134 * size, but it happens at most once per transaction.2135 */2136if(string_list_has_string(affected_refnames,"HEAD")) {2137/* An entry already existed */2138strbuf_addf(err,2139"multiple updates for 'HEAD' (including one "2140"via its referent '%s') are not allowed",2141 update->refname);2142return TRANSACTION_NAME_CONFLICT;2143}21442145 new_update =ref_transaction_add_update(2146 transaction,"HEAD",2147 update->flags | REF_LOG_ONLY | REF_NODEREF,2148 update->new_oid.hash, update->old_oid.hash,2149 update->msg);21502151/*2152 * Add "HEAD". This insertion is O(N) in the transaction2153 * size, but it happens at most once per transaction.2154 * Add new_update->refname instead of a literal "HEAD".2155 */2156if(strcmp(new_update->refname,"HEAD"))2157BUG("%sunexpectedly not 'HEAD'", new_update->refname);2158 item =string_list_insert(affected_refnames, new_update->refname);2159 item->util = new_update;21602161return0;2162}21632164/*2165 * update is for a symref that points at referent and doesn't have2166 * REF_NODEREF set. Split it into two updates:2167 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2168 * - A new, separate update for the referent reference2169 * Note that the new update will itself be subject to splitting when2170 * the iteration gets to it.2171 */2172static intsplit_symref_update(struct files_ref_store *refs,2173struct ref_update *update,2174const char*referent,2175struct ref_transaction *transaction,2176struct string_list *affected_refnames,2177struct strbuf *err)2178{2179struct string_list_item *item;2180struct ref_update *new_update;2181unsigned int new_flags;21822183/*2184 * First make sure that referent is not already in the2185 * transaction. This check is O(lg N) in the transaction2186 * size, but it happens at most once per symref in a2187 * transaction.2188 */2189if(string_list_has_string(affected_refnames, referent)) {2190/* An entry already exists */2191strbuf_addf(err,2192"multiple updates for '%s' (including one "2193"via symref '%s') are not allowed",2194 referent, update->refname);2195return TRANSACTION_NAME_CONFLICT;2196}21972198 new_flags = update->flags;2199if(!strcmp(update->refname,"HEAD")) {2200/*2201 * Record that the new update came via HEAD, so that2202 * when we process it, split_head_update() doesn't try2203 * to add another reflog update for HEAD. Note that2204 * this bit will be propagated if the new_update2205 * itself needs to be split.2206 */2207 new_flags |= REF_UPDATE_VIA_HEAD;2208}22092210 new_update =ref_transaction_add_update(2211 transaction, referent, new_flags,2212 update->new_oid.hash, update->old_oid.hash,2213 update->msg);22142215 new_update->parent_update = update;22162217/*2218 * Change the symbolic ref update to log only. Also, it2219 * doesn't need to check its old SHA-1 value, as that will be2220 * done when new_update is processed.2221 */2222 update->flags |= REF_LOG_ONLY | REF_NODEREF;2223 update->flags &= ~REF_HAVE_OLD;22242225/*2226 * Add the referent. This insertion is O(N) in the transaction2227 * size, but it happens at most once per symref in a2228 * transaction. Make sure to add new_update->refname, which will2229 * be valid as long as affected_refnames is in use, and NOT2230 * referent, which might soon be freed by our caller.2231 */2232 item =string_list_insert(affected_refnames, new_update->refname);2233if(item->util)2234BUG("%sunexpectedly found in affected_refnames",2235 new_update->refname);2236 item->util = new_update;22372238return0;2239}22402241/*2242 * Return the refname under which update was originally requested.2243 */2244static const char*original_update_refname(struct ref_update *update)2245{2246while(update->parent_update)2247 update = update->parent_update;22482249return update->refname;2250}22512252/*2253 * Check whether the REF_HAVE_OLD and old_oid values stored in update2254 * are consistent with oid, which is the reference's current value. If2255 * everything is OK, return 0; otherwise, write an error message to2256 * err and return -1.2257 */2258static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2259struct strbuf *err)2260{2261if(!(update->flags & REF_HAVE_OLD) ||2262!oidcmp(oid, &update->old_oid))2263return0;22642265if(is_null_oid(&update->old_oid))2266strbuf_addf(err,"cannot lock ref '%s': "2267"reference already exists",2268original_update_refname(update));2269else if(is_null_oid(oid))2270strbuf_addf(err,"cannot lock ref '%s': "2271"reference is missing but expected%s",2272original_update_refname(update),2273oid_to_hex(&update->old_oid));2274else2275strbuf_addf(err,"cannot lock ref '%s': "2276"is at%sbut expected%s",2277original_update_refname(update),2278oid_to_hex(oid),2279oid_to_hex(&update->old_oid));22802281return-1;2282}22832284/*2285 * Prepare for carrying out update:2286 * - Lock the reference referred to by update.2287 * - Read the reference under lock.2288 * - Check that its old SHA-1 value (if specified) is correct, and in2289 * any case record it in update->lock->old_oid for later use when2290 * writing the reflog.2291 * - If it is a symref update without REF_NODEREF, split it up into a2292 * REF_LOG_ONLY update of the symref and add a separate update for2293 * the referent to transaction.2294 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2295 * update of HEAD.2296 */2297static intlock_ref_for_update(struct files_ref_store *refs,2298struct ref_update *update,2299struct ref_transaction *transaction,2300const char*head_ref,2301struct string_list *affected_refnames,2302struct strbuf *err)2303{2304struct strbuf referent = STRBUF_INIT;2305int mustexist = (update->flags & REF_HAVE_OLD) &&2306!is_null_oid(&update->old_oid);2307int ret =0;2308struct ref_lock *lock;23092310files_assert_main_repository(refs,"lock_ref_for_update");23112312if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2313 update->flags |= REF_DELETING;23142315if(head_ref) {2316 ret =split_head_update(update, transaction, head_ref,2317 affected_refnames, err);2318if(ret)2319goto out;2320}23212322 ret =lock_raw_ref(refs, update->refname, mustexist,2323 affected_refnames, NULL,2324&lock, &referent,2325&update->type, err);2326if(ret) {2327char*reason;23282329 reason =strbuf_detach(err, NULL);2330strbuf_addf(err,"cannot lock ref '%s':%s",2331original_update_refname(update), reason);2332free(reason);2333goto out;2334}23352336 update->backend_data = lock;23372338if(update->type & REF_ISSYMREF) {2339if(update->flags & REF_NODEREF) {2340/*2341 * We won't be reading the referent as part of2342 * the transaction, so we have to read it here2343 * to record and possibly check old_sha1:2344 */2345if(refs_read_ref_full(&refs->base,2346 referent.buf,0,2347 lock->old_oid.hash, NULL)) {2348if(update->flags & REF_HAVE_OLD) {2349strbuf_addf(err,"cannot lock ref '%s': "2350"error reading reference",2351original_update_refname(update));2352 ret = TRANSACTION_GENERIC_ERROR;2353goto out;2354}2355}else if(check_old_oid(update, &lock->old_oid, err)) {2356 ret = TRANSACTION_GENERIC_ERROR;2357goto out;2358}2359}else{2360/*2361 * Create a new update for the reference this2362 * symref is pointing at. Also, we will record2363 * and verify old_sha1 for this update as part2364 * of processing the split-off update, so we2365 * don't have to do it here.2366 */2367 ret =split_symref_update(refs, update,2368 referent.buf, transaction,2369 affected_refnames, err);2370if(ret)2371goto out;2372}2373}else{2374struct ref_update *parent_update;23752376if(check_old_oid(update, &lock->old_oid, err)) {2377 ret = TRANSACTION_GENERIC_ERROR;2378goto out;2379}23802381/*2382 * If this update is happening indirectly because of a2383 * symref update, record the old SHA-1 in the parent2384 * update:2385 */2386for(parent_update = update->parent_update;2387 parent_update;2388 parent_update = parent_update->parent_update) {2389struct ref_lock *parent_lock = parent_update->backend_data;2390oidcpy(&parent_lock->old_oid, &lock->old_oid);2391}2392}23932394if((update->flags & REF_HAVE_NEW) &&2395!(update->flags & REF_DELETING) &&2396!(update->flags & REF_LOG_ONLY)) {2397if(!(update->type & REF_ISSYMREF) &&2398!oidcmp(&lock->old_oid, &update->new_oid)) {2399/*2400 * The reference already has the desired2401 * value, so we don't need to write it.2402 */2403}else if(write_ref_to_lockfile(lock, &update->new_oid,2404 err)) {2405char*write_err =strbuf_detach(err, NULL);24062407/*2408 * The lock was freed upon failure of2409 * write_ref_to_lockfile():2410 */2411 update->backend_data = NULL;2412strbuf_addf(err,2413"cannot update ref '%s':%s",2414 update->refname, write_err);2415free(write_err);2416 ret = TRANSACTION_GENERIC_ERROR;2417goto out;2418}else{2419 update->flags |= REF_NEEDS_COMMIT;2420}2421}2422if(!(update->flags & REF_NEEDS_COMMIT)) {2423/*2424 * We didn't call write_ref_to_lockfile(), so2425 * the lockfile is still open. Close it to2426 * free up the file descriptor:2427 */2428if(close_ref(lock)) {2429strbuf_addf(err,"couldn't close '%s.lock'",2430 update->refname);2431 ret = TRANSACTION_GENERIC_ERROR;2432goto out;2433}2434}24352436out:2437strbuf_release(&referent);2438return ret;2439}24402441/*2442 * Unlock any references in `transaction` that are still locked, and2443 * mark the transaction closed.2444 */2445static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2446{2447size_t i;24482449for(i =0; i < transaction->nr; i++) {2450struct ref_update *update = transaction->updates[i];2451struct ref_lock *lock = update->backend_data;24522453if(lock) {2454unlock_ref(lock);2455 update->backend_data = NULL;2456}2457}24582459 transaction->state = REF_TRANSACTION_CLOSED;2460}24612462static intfiles_transaction_prepare(struct ref_store *ref_store,2463struct ref_transaction *transaction,2464struct strbuf *err)2465{2466struct files_ref_store *refs =2467files_downcast(ref_store, REF_STORE_WRITE,2468"ref_transaction_prepare");2469size_t i;2470int ret =0;2471struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2472char*head_ref = NULL;2473int head_type;2474struct object_id head_oid;24752476assert(err);24772478if(!transaction->nr)2479goto cleanup;24802481/*2482 * Fail if a refname appears more than once in the2483 * transaction. (If we end up splitting up any updates using2484 * split_symref_update() or split_head_update(), those2485 * functions will check that the new updates don't have the2486 * same refname as any existing ones.)2487 */2488for(i =0; i < transaction->nr; i++) {2489struct ref_update *update = transaction->updates[i];2490struct string_list_item *item =2491string_list_append(&affected_refnames, update->refname);24922493/*2494 * We store a pointer to update in item->util, but at2495 * the moment we never use the value of this field2496 * except to check whether it is non-NULL.2497 */2498 item->util = update;2499}2500string_list_sort(&affected_refnames);2501if(ref_update_reject_duplicates(&affected_refnames, err)) {2502 ret = TRANSACTION_GENERIC_ERROR;2503goto cleanup;2504}25052506/*2507 * Special hack: If a branch is updated directly and HEAD2508 * points to it (may happen on the remote side of a push2509 * for example) then logically the HEAD reflog should be2510 * updated too.2511 *2512 * A generic solution would require reverse symref lookups,2513 * but finding all symrefs pointing to a given branch would be2514 * rather costly for this rare event (the direct update of a2515 * branch) to be worth it. So let's cheat and check with HEAD2516 * only, which should cover 99% of all usage scenarios (even2517 * 100% of the default ones).2518 *2519 * So if HEAD is a symbolic reference, then record the name of2520 * the reference that it points to. If we see an update of2521 * head_ref within the transaction, then split_head_update()2522 * arranges for the reflog of HEAD to be updated, too.2523 */2524 head_ref =refs_resolve_refdup(ref_store,"HEAD",2525 RESOLVE_REF_NO_RECURSE,2526 head_oid.hash, &head_type);25272528if(head_ref && !(head_type & REF_ISSYMREF)) {2529FREE_AND_NULL(head_ref);2530}25312532/*2533 * Acquire all locks, verify old values if provided, check2534 * that new values are valid, and write new values to the2535 * lockfiles, ready to be activated. Only keep one lockfile2536 * open at a time to avoid running out of file descriptors.2537 * Note that lock_ref_for_update() might append more updates2538 * to the transaction.2539 */2540for(i =0; i < transaction->nr; i++) {2541struct ref_update *update = transaction->updates[i];25422543 ret =lock_ref_for_update(refs, update, transaction,2544 head_ref, &affected_refnames, err);2545if(ret)2546break;2547}25482549cleanup:2550free(head_ref);2551string_list_clear(&affected_refnames,0);25522553if(ret)2554files_transaction_cleanup(transaction);2555else2556 transaction->state = REF_TRANSACTION_PREPARED;25572558return ret;2559}25602561static intfiles_transaction_finish(struct ref_store *ref_store,2562struct ref_transaction *transaction,2563struct strbuf *err)2564{2565struct files_ref_store *refs =2566files_downcast(ref_store,0,"ref_transaction_finish");2567size_t i;2568int ret =0;2569struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2570struct string_list_item *ref_to_delete;2571struct strbuf sb = STRBUF_INIT;25722573assert(err);25742575if(!transaction->nr) {2576 transaction->state = REF_TRANSACTION_CLOSED;2577return0;2578}25792580/* Perform updates first so live commits remain referenced */2581for(i =0; i < transaction->nr; i++) {2582struct ref_update *update = transaction->updates[i];2583struct ref_lock *lock = update->backend_data;25842585if(update->flags & REF_NEEDS_COMMIT ||2586 update->flags & REF_LOG_ONLY) {2587if(files_log_ref_write(refs,2588 lock->ref_name,2589&lock->old_oid,2590&update->new_oid,2591 update->msg, update->flags,2592 err)) {2593char*old_msg =strbuf_detach(err, NULL);25942595strbuf_addf(err,"cannot update the ref '%s':%s",2596 lock->ref_name, old_msg);2597free(old_msg);2598unlock_ref(lock);2599 update->backend_data = NULL;2600 ret = TRANSACTION_GENERIC_ERROR;2601goto cleanup;2602}2603}2604if(update->flags & REF_NEEDS_COMMIT) {2605clear_loose_ref_cache(refs);2606if(commit_ref(lock)) {2607strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2608unlock_ref(lock);2609 update->backend_data = NULL;2610 ret = TRANSACTION_GENERIC_ERROR;2611goto cleanup;2612}2613}2614}2615/* Perform deletes now that updates are safely completed */2616for(i =0; i < transaction->nr; i++) {2617struct ref_update *update = transaction->updates[i];2618struct ref_lock *lock = update->backend_data;26192620if(update->flags & REF_DELETING &&2621!(update->flags & REF_LOG_ONLY)) {2622if(!(update->type & REF_ISPACKED) ||2623 update->type & REF_ISSYMREF) {2624/* It is a loose reference. */2625strbuf_reset(&sb);2626files_ref_path(refs, &sb, lock->ref_name);2627if(unlink_or_msg(sb.buf, err)) {2628 ret = TRANSACTION_GENERIC_ERROR;2629goto cleanup;2630}2631 update->flags |= REF_DELETED_LOOSE;2632}26332634if(!(update->flags & REF_ISPRUNING))2635string_list_append(&refs_to_delete,2636 lock->ref_name);2637}2638}26392640if(packed_refs_lock(refs->packed_ref_store,0, err)) {2641 ret = TRANSACTION_GENERIC_ERROR;2642goto cleanup;2643}26442645if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {2646 ret = TRANSACTION_GENERIC_ERROR;2647packed_refs_unlock(refs->packed_ref_store);2648goto cleanup;2649}26502651packed_refs_unlock(refs->packed_ref_store);26522653/* Delete the reflogs of any references that were deleted: */2654for_each_string_list_item(ref_to_delete, &refs_to_delete) {2655strbuf_reset(&sb);2656files_reflog_path(refs, &sb, ref_to_delete->string);2657if(!unlink_or_warn(sb.buf))2658try_remove_empty_parents(refs, ref_to_delete->string,2659 REMOVE_EMPTY_PARENTS_REFLOG);2660}26612662clear_loose_ref_cache(refs);26632664cleanup:2665files_transaction_cleanup(transaction);26662667for(i =0; i < transaction->nr; i++) {2668struct ref_update *update = transaction->updates[i];26692670if(update->flags & REF_DELETED_LOOSE) {2671/*2672 * The loose reference was deleted. Delete any2673 * empty parent directories. (Note that this2674 * can only work because we have already2675 * removed the lockfile.)2676 */2677try_remove_empty_parents(refs, update->refname,2678 REMOVE_EMPTY_PARENTS_REF);2679}2680}26812682strbuf_release(&sb);2683string_list_clear(&refs_to_delete,0);2684return ret;2685}26862687static intfiles_transaction_abort(struct ref_store *ref_store,2688struct ref_transaction *transaction,2689struct strbuf *err)2690{2691files_transaction_cleanup(transaction);2692return0;2693}26942695static intref_present(const char*refname,2696const struct object_id *oid,int flags,void*cb_data)2697{2698struct string_list *affected_refnames = cb_data;26992700returnstring_list_has_string(affected_refnames, refname);2701}27022703static intfiles_initial_transaction_commit(struct ref_store *ref_store,2704struct ref_transaction *transaction,2705struct strbuf *err)2706{2707struct files_ref_store *refs =2708files_downcast(ref_store, REF_STORE_WRITE,2709"initial_ref_transaction_commit");2710size_t i;2711int ret =0;2712struct string_list affected_refnames = STRING_LIST_INIT_NODUP;27132714assert(err);27152716if(transaction->state != REF_TRANSACTION_OPEN)2717die("BUG: commit called for transaction that is not open");27182719/* Fail if a refname appears more than once in the transaction: */2720for(i =0; i < transaction->nr; i++)2721string_list_append(&affected_refnames,2722 transaction->updates[i]->refname);2723string_list_sort(&affected_refnames);2724if(ref_update_reject_duplicates(&affected_refnames, err)) {2725 ret = TRANSACTION_GENERIC_ERROR;2726goto cleanup;2727}27282729/*2730 * It's really undefined to call this function in an active2731 * repository or when there are existing references: we are2732 * only locking and changing packed-refs, so (1) any2733 * simultaneous processes might try to change a reference at2734 * the same time we do, and (2) any existing loose versions of2735 * the references that we are setting would have precedence2736 * over our values. But some remote helpers create the remote2737 * "HEAD" and "master" branches before calling this function,2738 * so here we really only check that none of the references2739 * that we are creating already exists.2740 */2741if(refs_for_each_rawref(&refs->base, ref_present,2742&affected_refnames))2743die("BUG: initial ref transaction called with existing refs");27442745for(i =0; i < transaction->nr; i++) {2746struct ref_update *update = transaction->updates[i];27472748if((update->flags & REF_HAVE_OLD) &&2749!is_null_oid(&update->old_oid))2750die("BUG: initial ref transaction with old_sha1 set");2751if(refs_verify_refname_available(&refs->base, update->refname,2752&affected_refnames, NULL,2753 err)) {2754 ret = TRANSACTION_NAME_CONFLICT;2755goto cleanup;2756}2757}27582759if(packed_refs_lock(refs->packed_ref_store,0, err)) {2760 ret = TRANSACTION_GENERIC_ERROR;2761goto cleanup;2762}27632764for(i =0; i < transaction->nr; i++) {2765struct ref_update *update = transaction->updates[i];27662767if((update->flags & REF_HAVE_NEW) &&2768!is_null_oid(&update->new_oid))2769add_packed_ref(refs->packed_ref_store, update->refname,2770&update->new_oid);2771}27722773if(commit_packed_refs(refs->packed_ref_store, err)) {2774 ret = TRANSACTION_GENERIC_ERROR;2775goto cleanup;2776}27772778cleanup:2779packed_refs_unlock(refs->packed_ref_store);2780 transaction->state = REF_TRANSACTION_CLOSED;2781string_list_clear(&affected_refnames,0);2782return ret;2783}27842785struct expire_reflog_cb {2786unsigned int flags;2787 reflog_expiry_should_prune_fn *should_prune_fn;2788void*policy_cb;2789FILE*newlog;2790struct object_id last_kept_oid;2791};27922793static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2794const char*email, timestamp_t timestamp,int tz,2795const char*message,void*cb_data)2796{2797struct expire_reflog_cb *cb = cb_data;2798struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;27992800if(cb->flags & EXPIRE_REFLOGS_REWRITE)2801 ooid = &cb->last_kept_oid;28022803if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2804 message, policy_cb)) {2805if(!cb->newlog)2806printf("would prune%s", message);2807else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2808printf("prune%s", message);2809}else{2810if(cb->newlog) {2811fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2812oid_to_hex(ooid),oid_to_hex(noid),2813 email, timestamp, tz, message);2814oidcpy(&cb->last_kept_oid, noid);2815}2816if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2817printf("keep%s", message);2818}2819return0;2820}28212822static intfiles_reflog_expire(struct ref_store *ref_store,2823const char*refname,const unsigned char*sha1,2824unsigned int flags,2825 reflog_expiry_prepare_fn prepare_fn,2826 reflog_expiry_should_prune_fn should_prune_fn,2827 reflog_expiry_cleanup_fn cleanup_fn,2828void*policy_cb_data)2829{2830struct files_ref_store *refs =2831files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2832static struct lock_file reflog_lock;2833struct expire_reflog_cb cb;2834struct ref_lock *lock;2835struct strbuf log_file_sb = STRBUF_INIT;2836char*log_file;2837int status =0;2838int type;2839struct strbuf err = STRBUF_INIT;2840struct object_id oid;28412842memset(&cb,0,sizeof(cb));2843 cb.flags = flags;2844 cb.policy_cb = policy_cb_data;2845 cb.should_prune_fn = should_prune_fn;28462847/*2848 * The reflog file is locked by holding the lock on the2849 * reference itself, plus we might need to update the2850 * reference if --updateref was specified:2851 */2852 lock =lock_ref_sha1_basic(refs, refname, sha1,2853 NULL, NULL, REF_NODEREF,2854&type, &err);2855if(!lock) {2856error("cannot lock ref '%s':%s", refname, err.buf);2857strbuf_release(&err);2858return-1;2859}2860if(!refs_reflog_exists(ref_store, refname)) {2861unlock_ref(lock);2862return0;2863}28642865files_reflog_path(refs, &log_file_sb, refname);2866 log_file =strbuf_detach(&log_file_sb, NULL);2867if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2868/*2869 * Even though holding $GIT_DIR/logs/$reflog.lock has2870 * no locking implications, we use the lock_file2871 * machinery here anyway because it does a lot of the2872 * work we need, including cleaning up if the program2873 * exits unexpectedly.2874 */2875if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2876struct strbuf err = STRBUF_INIT;2877unable_to_lock_message(log_file, errno, &err);2878error("%s", err.buf);2879strbuf_release(&err);2880goto failure;2881}2882 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2883if(!cb.newlog) {2884error("cannot fdopen%s(%s)",2885get_lock_file_path(&reflog_lock),strerror(errno));2886goto failure;2887}2888}28892890hashcpy(oid.hash, sha1);28912892(*prepare_fn)(refname, &oid, cb.policy_cb);2893refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2894(*cleanup_fn)(cb.policy_cb);28952896if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2897/*2898 * It doesn't make sense to adjust a reference pointed2899 * to by a symbolic ref based on expiring entries in2900 * the symbolic reference's reflog. Nor can we update2901 * a reference if there are no remaining reflog2902 * entries.2903 */2904int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2905!(type & REF_ISSYMREF) &&2906!is_null_oid(&cb.last_kept_oid);29072908if(close_lock_file(&reflog_lock)) {2909 status |=error("couldn't write%s:%s", log_file,2910strerror(errno));2911}else if(update &&2912(write_in_full(get_lock_file_fd(lock->lk),2913oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2914write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||2915close_ref(lock) <0)) {2916 status |=error("couldn't write%s",2917get_lock_file_path(lock->lk));2918rollback_lock_file(&reflog_lock);2919}else if(commit_lock_file(&reflog_lock)) {2920 status |=error("unable to write reflog '%s' (%s)",2921 log_file,strerror(errno));2922}else if(update &&commit_ref(lock)) {2923 status |=error("couldn't set%s", lock->ref_name);2924}2925}2926free(log_file);2927unlock_ref(lock);2928return status;29292930 failure:2931rollback_lock_file(&reflog_lock);2932free(log_file);2933unlock_ref(lock);2934return-1;2935}29362937static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2938{2939struct files_ref_store *refs =2940files_downcast(ref_store, REF_STORE_WRITE,"init_db");2941struct strbuf sb = STRBUF_INIT;29422943/*2944 * Create .git/refs/{heads,tags}2945 */2946files_ref_path(refs, &sb,"refs/heads");2947safe_create_dir(sb.buf,1);29482949strbuf_reset(&sb);2950files_ref_path(refs, &sb,"refs/tags");2951safe_create_dir(sb.buf,1);29522953strbuf_release(&sb);2954return0;2955}29562957struct ref_storage_be refs_be_files = {2958 NULL,2959"files",2960 files_ref_store_create,2961 files_init_db,2962 files_transaction_prepare,2963 files_transaction_finish,2964 files_transaction_abort,2965 files_initial_transaction_commit,29662967 files_pack_refs,2968 files_peel_ref,2969 files_create_symref,2970 files_delete_refs,2971 files_rename_ref,29722973 files_ref_iterator_begin,2974 files_read_raw_ref,29752976 files_reflog_iterator_begin,2977 files_for_each_reflog_ent,2978 files_for_each_reflog_ent_reverse,2979 files_reflog_exists,2980 files_create_reflog,2981 files_delete_reflog,2982 files_reflog_expire2983};