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{ 412rollback_lock_file(&lock->lk); 413free(lock->ref_name); 414free(lock); 415} 416 417/* 418 * Lock refname, without following symrefs, and set *lock_p to point 419 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 420 * and type similarly to read_raw_ref(). 421 * 422 * The caller must verify that refname is a "safe" reference name (in 423 * the sense of refname_is_safe()) before calling this function. 424 * 425 * If the reference doesn't already exist, verify that refname doesn't 426 * have a D/F conflict with any existing references. extras and skip 427 * are passed to refs_verify_refname_available() for this check. 428 * 429 * If mustexist is not set and the reference is not found or is 430 * broken, lock the reference anyway but clear sha1. 431 * 432 * Return 0 on success. On failure, write an error message to err and 433 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 434 * 435 * Implementation note: This function is basically 436 * 437 * lock reference 438 * read_raw_ref() 439 * 440 * but it includes a lot more code to 441 * - Deal with possible races with other processes 442 * - Avoid calling refs_verify_refname_available() when it can be 443 * avoided, namely if we were successfully able to read the ref 444 * - Generate informative error messages in the case of failure 445 */ 446static intlock_raw_ref(struct files_ref_store *refs, 447const char*refname,int mustexist, 448const struct string_list *extras, 449const struct string_list *skip, 450struct ref_lock **lock_p, 451struct strbuf *referent, 452unsigned int*type, 453struct strbuf *err) 454{ 455struct ref_lock *lock; 456struct strbuf ref_file = STRBUF_INIT; 457int attempts_remaining =3; 458int ret = TRANSACTION_GENERIC_ERROR; 459 460assert(err); 461files_assert_main_repository(refs,"lock_raw_ref"); 462 463*type =0; 464 465/* First lock the file so it can't change out from under us. */ 466 467*lock_p = lock =xcalloc(1,sizeof(*lock)); 468 469 lock->ref_name =xstrdup(refname); 470files_ref_path(refs, &ref_file, refname); 471 472retry: 473switch(safe_create_leading_directories(ref_file.buf)) { 474case SCLD_OK: 475break;/* success */ 476case SCLD_EXISTS: 477/* 478 * Suppose refname is "refs/foo/bar". We just failed 479 * to create the containing directory, "refs/foo", 480 * because there was a non-directory in the way. This 481 * indicates a D/F conflict, probably because of 482 * another reference such as "refs/foo". There is no 483 * reason to expect this error to be transitory. 484 */ 485if(refs_verify_refname_available(&refs->base, refname, 486 extras, skip, err)) { 487if(mustexist) { 488/* 489 * To the user the relevant error is 490 * that the "mustexist" reference is 491 * missing: 492 */ 493strbuf_reset(err); 494strbuf_addf(err,"unable to resolve reference '%s'", 495 refname); 496}else{ 497/* 498 * The error message set by 499 * refs_verify_refname_available() is 500 * OK. 501 */ 502 ret = TRANSACTION_NAME_CONFLICT; 503} 504}else{ 505/* 506 * The file that is in the way isn't a loose 507 * reference. Report it as a low-level 508 * failure. 509 */ 510strbuf_addf(err,"unable to create lock file%s.lock; " 511"non-directory in the way", 512 ref_file.buf); 513} 514goto error_return; 515case SCLD_VANISHED: 516/* Maybe another process was tidying up. Try again. */ 517if(--attempts_remaining >0) 518goto retry; 519/* fall through */ 520default: 521strbuf_addf(err,"unable to create directory for%s", 522 ref_file.buf); 523goto error_return; 524} 525 526if(hold_lock_file_for_update_timeout( 527&lock->lk, ref_file.buf, LOCK_NO_DEREF, 528get_files_ref_lock_timeout_ms()) <0) { 529if(errno == ENOENT && --attempts_remaining >0) { 530/* 531 * Maybe somebody just deleted one of the 532 * directories leading to ref_file. Try 533 * again: 534 */ 535goto retry; 536}else{ 537unable_to_lock_message(ref_file.buf, errno, err); 538goto error_return; 539} 540} 541 542/* 543 * Now we hold the lock and can read the reference without 544 * fear that its value will change. 545 */ 546 547if(files_read_raw_ref(&refs->base, refname, 548 lock->old_oid.hash, referent, type)) { 549if(errno == ENOENT) { 550if(mustexist) { 551/* Garden variety missing reference. */ 552strbuf_addf(err,"unable to resolve reference '%s'", 553 refname); 554goto error_return; 555}else{ 556/* 557 * Reference is missing, but that's OK. We 558 * know that there is not a conflict with 559 * another loose reference because 560 * (supposing that we are trying to lock 561 * reference "refs/foo/bar"): 562 * 563 * - We were successfully able to create 564 * the lockfile refs/foo/bar.lock, so we 565 * know there cannot be a loose reference 566 * named "refs/foo". 567 * 568 * - We got ENOENT and not EISDIR, so we 569 * know that there cannot be a loose 570 * reference named "refs/foo/bar/baz". 571 */ 572} 573}else if(errno == EISDIR) { 574/* 575 * There is a directory in the way. It might have 576 * contained references that have been deleted. If 577 * we don't require that the reference already 578 * exists, try to remove the directory so that it 579 * doesn't cause trouble when we want to rename the 580 * lockfile into place later. 581 */ 582if(mustexist) { 583/* Garden variety missing reference. */ 584strbuf_addf(err,"unable to resolve reference '%s'", 585 refname); 586goto error_return; 587}else if(remove_dir_recursively(&ref_file, 588 REMOVE_DIR_EMPTY_ONLY)) { 589if(refs_verify_refname_available( 590&refs->base, refname, 591 extras, skip, err)) { 592/* 593 * The error message set by 594 * verify_refname_available() is OK. 595 */ 596 ret = TRANSACTION_NAME_CONFLICT; 597goto error_return; 598}else{ 599/* 600 * We can't delete the directory, 601 * but we also don't know of any 602 * references that it should 603 * contain. 604 */ 605strbuf_addf(err,"there is a non-empty directory '%s' " 606"blocking reference '%s'", 607 ref_file.buf, refname); 608goto error_return; 609} 610} 611}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 612strbuf_addf(err,"unable to resolve reference '%s': " 613"reference broken", refname); 614goto error_return; 615}else{ 616strbuf_addf(err,"unable to resolve reference '%s':%s", 617 refname,strerror(errno)); 618goto error_return; 619} 620 621/* 622 * If the ref did not exist and we are creating it, 623 * make sure there is no existing packed ref that 624 * conflicts with refname: 625 */ 626if(refs_verify_refname_available( 627 refs->packed_ref_store, refname, 628 extras, skip, err)) 629goto error_return; 630} 631 632 ret =0; 633goto out; 634 635error_return: 636unlock_ref(lock); 637*lock_p = NULL; 638 639out: 640strbuf_release(&ref_file); 641return ret; 642} 643 644static intfiles_peel_ref(struct ref_store *ref_store, 645const char*refname,unsigned char*sha1) 646{ 647struct files_ref_store *refs = 648files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 649"peel_ref"); 650int flag; 651unsigned char base[20]; 652 653if(current_ref_iter && current_ref_iter->refname == refname) { 654struct object_id peeled; 655 656if(ref_iterator_peel(current_ref_iter, &peeled)) 657return-1; 658hashcpy(sha1, peeled.hash); 659return0; 660} 661 662if(refs_read_ref_full(ref_store, refname, 663 RESOLVE_REF_READING, base, &flag)) 664return-1; 665 666/* 667 * If the reference is packed, read its ref_entry from the 668 * cache in the hope that we already know its peeled value. 669 * We only try this optimization on packed references because 670 * (a) forcing the filling of the loose reference cache could 671 * be expensive and (b) loose references anyway usually do not 672 * have REF_KNOWS_PEELED. 673 */ 674if(flag & REF_ISPACKED && 675!refs_peel_ref(refs->packed_ref_store, refname, sha1)) 676return0; 677 678returnpeel_object(base, sha1); 679} 680 681struct files_ref_iterator { 682struct ref_iterator base; 683 684struct ref_iterator *iter0; 685unsigned int flags; 686}; 687 688static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 689{ 690struct files_ref_iterator *iter = 691(struct files_ref_iterator *)ref_iterator; 692int ok; 693 694while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 695if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 696ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE) 697continue; 698 699if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 700!ref_resolves_to_object(iter->iter0->refname, 701 iter->iter0->oid, 702 iter->iter0->flags)) 703continue; 704 705 iter->base.refname = iter->iter0->refname; 706 iter->base.oid = iter->iter0->oid; 707 iter->base.flags = iter->iter0->flags; 708return ITER_OK; 709} 710 711 iter->iter0 = NULL; 712if(ref_iterator_abort(ref_iterator) != ITER_DONE) 713 ok = ITER_ERROR; 714 715return ok; 716} 717 718static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator, 719struct object_id *peeled) 720{ 721struct files_ref_iterator *iter = 722(struct files_ref_iterator *)ref_iterator; 723 724returnref_iterator_peel(iter->iter0, peeled); 725} 726 727static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator) 728{ 729struct files_ref_iterator *iter = 730(struct files_ref_iterator *)ref_iterator; 731int ok = ITER_DONE; 732 733if(iter->iter0) 734 ok =ref_iterator_abort(iter->iter0); 735 736base_ref_iterator_free(ref_iterator); 737return ok; 738} 739 740static struct ref_iterator_vtable files_ref_iterator_vtable = { 741 files_ref_iterator_advance, 742 files_ref_iterator_peel, 743 files_ref_iterator_abort 744}; 745 746static struct ref_iterator *files_ref_iterator_begin( 747struct ref_store *ref_store, 748const char*prefix,unsigned int flags) 749{ 750struct files_ref_store *refs; 751struct ref_iterator *loose_iter, *packed_iter; 752struct files_ref_iterator *iter; 753struct ref_iterator *ref_iterator; 754unsigned int required_flags = REF_STORE_READ; 755 756if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) 757 required_flags |= REF_STORE_ODB; 758 759 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin"); 760 761 iter =xcalloc(1,sizeof(*iter)); 762 ref_iterator = &iter->base; 763base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable); 764 765/* 766 * We must make sure that all loose refs are read before 767 * accessing the packed-refs file; this avoids a race 768 * condition if loose refs are migrated to the packed-refs 769 * file by a simultaneous process, but our in-memory view is 770 * from before the migration. We ensure this as follows: 771 * First, we call start the loose refs iteration with its 772 * `prime_ref` argument set to true. This causes the loose 773 * references in the subtree to be pre-read into the cache. 774 * (If they've already been read, that's OK; we only need to 775 * guarantee that they're read before the packed refs, not 776 * *how much* before.) After that, we call 777 * packed_ref_iterator_begin(), which internally checks 778 * whether the packed-ref cache is up to date with what is on 779 * disk, and re-reads it if not. 780 */ 781 782 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), 783 prefix,1); 784 785/* 786 * The packed-refs file might contain broken references, for 787 * example an old version of a reference that points at an 788 * object that has since been garbage-collected. This is OK as 789 * long as there is a corresponding loose reference that 790 * overrides it, and we don't want to emit an error message in 791 * this case. So ask the packed_ref_store for all of its 792 * references, and (if needed) do our own check for broken 793 * ones in files_ref_iterator_advance(), after we have merged 794 * the packed and loose references. 795 */ 796 packed_iter =refs_ref_iterator_begin( 797 refs->packed_ref_store, prefix,0, 798 DO_FOR_EACH_INCLUDE_BROKEN); 799 800 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter); 801 iter->flags = flags; 802 803return ref_iterator; 804} 805 806/* 807 * Verify that the reference locked by lock has the value old_sha1. 808 * Fail if the reference doesn't exist and mustexist is set. Return 0 809 * on success. On error, write an error message to err, set errno, and 810 * return a negative value. 811 */ 812static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock, 813const unsigned char*old_sha1,int mustexist, 814struct strbuf *err) 815{ 816assert(err); 817 818if(refs_read_ref_full(ref_store, lock->ref_name, 819 mustexist ? RESOLVE_REF_READING :0, 820 lock->old_oid.hash, NULL)) { 821if(old_sha1) { 822int save_errno = errno; 823strbuf_addf(err,"can't verify ref '%s'", lock->ref_name); 824 errno = save_errno; 825return-1; 826}else{ 827oidclr(&lock->old_oid); 828return0; 829} 830} 831if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) { 832strbuf_addf(err,"ref '%s' is at%sbut expected%s", 833 lock->ref_name, 834oid_to_hex(&lock->old_oid), 835sha1_to_hex(old_sha1)); 836 errno = EBUSY; 837return-1; 838} 839return0; 840} 841 842static intremove_empty_directories(struct strbuf *path) 843{ 844/* 845 * we want to create a file but there is a directory there; 846 * if that is an empty directory (or a directory that contains 847 * only empty directories), remove them. 848 */ 849returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY); 850} 851 852static intcreate_reflock(const char*path,void*cb) 853{ 854struct lock_file *lk = cb; 855 856returnhold_lock_file_for_update_timeout( 857 lk, path, LOCK_NO_DEREF, 858get_files_ref_lock_timeout_ms()) <0? -1:0; 859} 860 861/* 862 * Locks a ref returning the lock on success and NULL on failure. 863 * On failure errno is set to something meaningful. 864 */ 865static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs, 866const char*refname, 867const unsigned char*old_sha1, 868const struct string_list *extras, 869const struct string_list *skip, 870unsigned int flags,int*type, 871struct strbuf *err) 872{ 873struct strbuf ref_file = STRBUF_INIT; 874struct ref_lock *lock; 875int last_errno =0; 876int mustexist = (old_sha1 && !is_null_sha1(old_sha1)); 877int resolve_flags = RESOLVE_REF_NO_RECURSE; 878int resolved; 879 880files_assert_main_repository(refs,"lock_ref_sha1_basic"); 881assert(err); 882 883 lock =xcalloc(1,sizeof(struct ref_lock)); 884 885if(mustexist) 886 resolve_flags |= RESOLVE_REF_READING; 887if(flags & REF_DELETING) 888 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME; 889 890files_ref_path(refs, &ref_file, refname); 891 resolved = !!refs_resolve_ref_unsafe(&refs->base, 892 refname, resolve_flags, 893 lock->old_oid.hash, type); 894if(!resolved && errno == EISDIR) { 895/* 896 * we are trying to lock foo but we used to 897 * have foo/bar which now does not exist; 898 * it is normal for the empty directory 'foo' 899 * to remain. 900 */ 901if(remove_empty_directories(&ref_file)) { 902 last_errno = errno; 903if(!refs_verify_refname_available( 904&refs->base, 905 refname, extras, skip, err)) 906strbuf_addf(err,"there are still refs under '%s'", 907 refname); 908goto error_return; 909} 910 resolved = !!refs_resolve_ref_unsafe(&refs->base, 911 refname, resolve_flags, 912 lock->old_oid.hash, type); 913} 914if(!resolved) { 915 last_errno = errno; 916if(last_errno != ENOTDIR || 917!refs_verify_refname_available(&refs->base, refname, 918 extras, skip, err)) 919strbuf_addf(err,"unable to resolve reference '%s':%s", 920 refname,strerror(last_errno)); 921 922goto error_return; 923} 924 925/* 926 * If the ref did not exist and we are creating it, make sure 927 * there is no existing packed ref whose name begins with our 928 * refname, nor a packed ref whose name is a proper prefix of 929 * our refname. 930 */ 931if(is_null_oid(&lock->old_oid) && 932refs_verify_refname_available(refs->packed_ref_store, refname, 933 extras, skip, err)) { 934 last_errno = ENOTDIR; 935goto error_return; 936} 937 938 lock->ref_name =xstrdup(refname); 939 940if(raceproof_create_file(ref_file.buf, create_reflock, &lock->lk)) { 941 last_errno = errno; 942unable_to_lock_message(ref_file.buf, errno, err); 943goto error_return; 944} 945 946if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) { 947 last_errno = errno; 948goto error_return; 949} 950goto out; 951 952 error_return: 953unlock_ref(lock); 954 lock = NULL; 955 956 out: 957strbuf_release(&ref_file); 958 errno = last_errno; 959return lock; 960} 961 962struct ref_to_prune { 963struct ref_to_prune *next; 964unsigned char sha1[20]; 965char name[FLEX_ARRAY]; 966}; 967 968enum{ 969 REMOVE_EMPTY_PARENTS_REF =0x01, 970 REMOVE_EMPTY_PARENTS_REFLOG =0x02 971}; 972 973/* 974 * Remove empty parent directories associated with the specified 975 * reference and/or its reflog, but spare [logs/]refs/ and immediate 976 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or 977 * REMOVE_EMPTY_PARENTS_REFLOG. 978 */ 979static voidtry_remove_empty_parents(struct files_ref_store *refs, 980const char*refname, 981unsigned int flags) 982{ 983struct strbuf buf = STRBUF_INIT; 984struct strbuf sb = STRBUF_INIT; 985char*p, *q; 986int i; 987 988strbuf_addstr(&buf, refname); 989 p = buf.buf; 990for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */ 991while(*p && *p !='/') 992 p++; 993/* tolerate duplicate slashes; see check_refname_format() */ 994while(*p =='/') 995 p++; 996} 997 q = buf.buf + buf.len; 998while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) { 999while(q > p && *q !='/')1000 q--;1001while(q > p && *(q-1) =='/')1002 q--;1003if(q == p)1004break;1005strbuf_setlen(&buf, q - buf.buf);10061007strbuf_reset(&sb);1008files_ref_path(refs, &sb, buf.buf);1009if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1010 flags &= ~REMOVE_EMPTY_PARENTS_REF;10111012strbuf_reset(&sb);1013files_reflog_path(refs, &sb, buf.buf);1014if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1015 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1016}1017strbuf_release(&buf);1018strbuf_release(&sb);1019}10201021/* make sure nobody touched the ref, and unlink */1022static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1023{1024struct ref_transaction *transaction;1025struct strbuf err = STRBUF_INIT;10261027if(check_refname_format(r->name,0))1028return;10291030 transaction =ref_store_transaction_begin(&refs->base, &err);1031if(!transaction ||1032ref_transaction_delete(transaction, r->name, r->sha1,1033 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1034ref_transaction_commit(transaction, &err)) {1035ref_transaction_free(transaction);1036error("%s", err.buf);1037strbuf_release(&err);1038return;1039}1040ref_transaction_free(transaction);1041strbuf_release(&err);1042}10431044/*1045 * Prune the loose versions of the references in the linked list1046 * `*refs_to_prune`, freeing the entries in the list as we go.1047 */1048static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune **refs_to_prune)1049{1050while(*refs_to_prune) {1051struct ref_to_prune *r = *refs_to_prune;1052*refs_to_prune = r->next;1053prune_ref(refs, r);1054free(r);1055}1056}10571058/*1059 * Return true if the specified reference should be packed.1060 */1061static intshould_pack_ref(const char*refname,1062const struct object_id *oid,unsigned int ref_flags,1063unsigned int pack_flags)1064{1065/* Do not pack per-worktree refs: */1066if(ref_type(refname) != REF_TYPE_NORMAL)1067return0;10681069/* Do not pack non-tags unless PACK_REFS_ALL is set: */1070if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1071return0;10721073/* Do not pack symbolic refs: */1074if(ref_flags & REF_ISSYMREF)1075return0;10761077/* Do not pack broken refs: */1078if(!ref_resolves_to_object(refname, oid, ref_flags))1079return0;10801081return1;1082}10831084static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1085{1086struct files_ref_store *refs =1087files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1088"pack_refs");1089struct ref_iterator *iter;1090int ok;1091struct ref_to_prune *refs_to_prune = NULL;1092struct strbuf err = STRBUF_INIT;1093struct ref_transaction *transaction;10941095 transaction =ref_store_transaction_begin(refs->packed_ref_store, &err);1096if(!transaction)1097return-1;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 * Add a reference creation for this reference to the1114 * packed-refs transaction:1115 */1116if(ref_transaction_update(transaction, iter->refname,1117 iter->oid->hash, NULL,1118 REF_NODEREF, NULL, &err))1119die("failure preparing to create packed reference%s:%s",1120 iter->refname, err.buf);11211122/* Schedule the loose reference for pruning if requested. */1123if((flags & PACK_REFS_PRUNE)) {1124struct ref_to_prune *n;1125FLEX_ALLOC_STR(n, name, iter->refname);1126hashcpy(n->sha1, iter->oid->hash);1127 n->next = refs_to_prune;1128 refs_to_prune = n;1129}1130}1131if(ok != ITER_DONE)1132die("error while iterating over references");11331134if(ref_transaction_commit(transaction, &err))1135die("unable to write new packed-refs:%s", err.buf);11361137ref_transaction_free(transaction);11381139packed_refs_unlock(refs->packed_ref_store);11401141prune_refs(refs, &refs_to_prune);1142strbuf_release(&err);1143return0;1144}11451146static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1147struct string_list *refnames,unsigned int flags)1148{1149struct files_ref_store *refs =1150files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1151struct strbuf err = STRBUF_INIT;1152int i, result =0;11531154if(!refnames->nr)1155return0;11561157if(packed_refs_lock(refs->packed_ref_store,0, &err))1158goto error;11591160if(refs_delete_refs(refs->packed_ref_store, msg, refnames, flags)) {1161packed_refs_unlock(refs->packed_ref_store);1162goto error;1163}11641165packed_refs_unlock(refs->packed_ref_store);11661167for(i =0; i < refnames->nr; i++) {1168const char*refname = refnames->items[i].string;11691170if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1171 result |=error(_("could not remove reference%s"), refname);1172}11731174strbuf_release(&err);1175return result;11761177error:1178/*1179 * If we failed to rewrite the packed-refs file, then it is1180 * unsafe to try to remove loose refs, because doing so might1181 * expose an obsolete packed value for a reference that might1182 * even point at an object that has been garbage collected.1183 */1184if(refnames->nr ==1)1185error(_("could not delete reference%s:%s"),1186 refnames->items[0].string, err.buf);1187else1188error(_("could not delete references:%s"), err.buf);11891190strbuf_release(&err);1191return-1;1192}11931194/*1195 * People using contrib's git-new-workdir have .git/logs/refs ->1196 * /some/other/path/.git/logs/refs, and that may live on another device.1197 *1198 * IOW, to avoid cross device rename errors, the temporary renamed log must1199 * live into logs/refs.1200 */1201#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"12021203struct rename_cb {1204const char*tmp_renamed_log;1205int true_errno;1206};12071208static intrename_tmp_log_callback(const char*path,void*cb_data)1209{1210struct rename_cb *cb = cb_data;12111212if(rename(cb->tmp_renamed_log, path)) {1213/*1214 * rename(a, b) when b is an existing directory ought1215 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1216 * Sheesh. Record the true errno for error reporting,1217 * but report EISDIR to raceproof_create_file() so1218 * that it knows to retry.1219 */1220 cb->true_errno = errno;1221if(errno == ENOTDIR)1222 errno = EISDIR;1223return-1;1224}else{1225return0;1226}1227}12281229static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1230{1231struct strbuf path = STRBUF_INIT;1232struct strbuf tmp = STRBUF_INIT;1233struct rename_cb cb;1234int ret;12351236files_reflog_path(refs, &path, newrefname);1237files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1238 cb.tmp_renamed_log = tmp.buf;1239 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1240if(ret) {1241if(errno == EISDIR)1242error("directory not empty:%s", path.buf);1243else1244error("unable to move logfile%sto%s:%s",1245 tmp.buf, path.buf,1246strerror(cb.true_errno));1247}12481249strbuf_release(&path);1250strbuf_release(&tmp);1251return ret;1252}12531254static intwrite_ref_to_lockfile(struct ref_lock *lock,1255const struct object_id *oid,struct strbuf *err);1256static intcommit_ref_update(struct files_ref_store *refs,1257struct ref_lock *lock,1258const struct object_id *oid,const char*logmsg,1259struct strbuf *err);12601261static intfiles_rename_ref(struct ref_store *ref_store,1262const char*oldrefname,const char*newrefname,1263const char*logmsg)1264{1265struct files_ref_store *refs =1266files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1267struct object_id oid, orig_oid;1268int flag =0, logmoved =0;1269struct ref_lock *lock;1270struct stat loginfo;1271struct strbuf sb_oldref = STRBUF_INIT;1272struct strbuf sb_newref = STRBUF_INIT;1273struct strbuf tmp_renamed_log = STRBUF_INIT;1274int log, ret;1275struct strbuf err = STRBUF_INIT;12761277files_reflog_path(refs, &sb_oldref, oldrefname);1278files_reflog_path(refs, &sb_newref, newrefname);1279files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12801281 log = !lstat(sb_oldref.buf, &loginfo);1282if(log &&S_ISLNK(loginfo.st_mode)) {1283 ret =error("reflog for%sis a symlink", oldrefname);1284goto out;1285}12861287if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1288 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1289 orig_oid.hash, &flag)) {1290 ret =error("refname%snot found", oldrefname);1291goto out;1292}12931294if(flag & REF_ISSYMREF) {1295 ret =error("refname%sis a symbolic ref, renaming it is not supported",1296 oldrefname);1297goto out;1298}1299if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1300 ret =1;1301goto out;1302}13031304if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1305 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1306 oldrefname,strerror(errno));1307goto out;1308}13091310if(refs_delete_ref(&refs->base, logmsg, oldrefname,1311 orig_oid.hash, REF_NODEREF)) {1312error("unable to delete old%s", oldrefname);1313goto rollback;1314}13151316/*1317 * Since we are doing a shallow lookup, oid is not the1318 * correct value to pass to delete_ref as old_oid. But that1319 * doesn't matter, because an old_oid check wouldn't add to1320 * the safety anyway; we want to delete the reference whatever1321 * its current value.1322 */1323if(!refs_read_ref_full(&refs->base, newrefname,1324 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1325 oid.hash, NULL) &&1326refs_delete_ref(&refs->base, NULL, newrefname,1327 NULL, REF_NODEREF)) {1328if(errno == EISDIR) {1329struct strbuf path = STRBUF_INIT;1330int result;13311332files_ref_path(refs, &path, newrefname);1333 result =remove_empty_directories(&path);1334strbuf_release(&path);13351336if(result) {1337error("Directory not empty:%s", newrefname);1338goto rollback;1339}1340}else{1341error("unable to delete existing%s", newrefname);1342goto rollback;1343}1344}13451346if(log &&rename_tmp_log(refs, newrefname))1347goto rollback;13481349 logmoved = log;13501351 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1352 REF_NODEREF, NULL, &err);1353if(!lock) {1354error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1355strbuf_release(&err);1356goto rollback;1357}1358oidcpy(&lock->old_oid, &orig_oid);13591360if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1361commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1362error("unable to write current sha1 into%s:%s", newrefname, err.buf);1363strbuf_release(&err);1364goto rollback;1365}13661367 ret =0;1368goto out;13691370 rollback:1371 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1372 REF_NODEREF, NULL, &err);1373if(!lock) {1374error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1375strbuf_release(&err);1376goto rollbacklog;1377}13781379 flag = log_all_ref_updates;1380 log_all_ref_updates = LOG_REFS_NONE;1381if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1382commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1383error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1384strbuf_release(&err);1385}1386 log_all_ref_updates = flag;13871388 rollbacklog:1389if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1390error("unable to restore logfile%sfrom%s:%s",1391 oldrefname, newrefname,strerror(errno));1392if(!logmoved && log &&1393rename(tmp_renamed_log.buf, sb_oldref.buf))1394error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1395 oldrefname,strerror(errno));1396 ret =1;1397 out:1398strbuf_release(&sb_newref);1399strbuf_release(&sb_oldref);1400strbuf_release(&tmp_renamed_log);14011402return ret;1403}14041405static intclose_ref_gently(struct ref_lock *lock)1406{1407if(close_lock_file_gently(&lock->lk))1408return-1;1409return0;1410}14111412static intcommit_ref(struct ref_lock *lock)1413{1414char*path =get_locked_file_path(&lock->lk);1415struct stat st;14161417if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1418/*1419 * There is a directory at the path we want to rename1420 * the lockfile to. Hopefully it is empty; try to1421 * delete it.1422 */1423size_t len =strlen(path);1424struct strbuf sb_path = STRBUF_INIT;14251426strbuf_attach(&sb_path, path, len, len);14271428/*1429 * If this fails, commit_lock_file() will also fail1430 * and will report the problem.1431 */1432remove_empty_directories(&sb_path);1433strbuf_release(&sb_path);1434}else{1435free(path);1436}14371438if(commit_lock_file(&lock->lk))1439return-1;1440return0;1441}14421443static intopen_or_create_logfile(const char*path,void*cb)1444{1445int*fd = cb;14461447*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1448return(*fd <0) ? -1:0;1449}14501451/*1452 * Create a reflog for a ref. If force_create = 0, only create the1453 * reflog for certain refs (those for which should_autocreate_reflog1454 * returns non-zero). Otherwise, create it regardless of the reference1455 * name. If the logfile already existed or was created, return 0 and1456 * set *logfd to the file descriptor opened for appending to the file.1457 * If no logfile exists and we decided not to create one, return 0 and1458 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1459 * return -1.1460 */1461static intlog_ref_setup(struct files_ref_store *refs,1462const char*refname,int force_create,1463int*logfd,struct strbuf *err)1464{1465struct strbuf logfile_sb = STRBUF_INIT;1466char*logfile;14671468files_reflog_path(refs, &logfile_sb, refname);1469 logfile =strbuf_detach(&logfile_sb, NULL);14701471if(force_create ||should_autocreate_reflog(refname)) {1472if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1473if(errno == ENOENT)1474strbuf_addf(err,"unable to create directory for '%s': "1475"%s", logfile,strerror(errno));1476else if(errno == EISDIR)1477strbuf_addf(err,"there are still logs under '%s'",1478 logfile);1479else1480strbuf_addf(err,"unable to append to '%s':%s",1481 logfile,strerror(errno));14821483goto error;1484}1485}else{1486*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1487if(*logfd <0) {1488if(errno == ENOENT || errno == EISDIR) {1489/*1490 * The logfile doesn't already exist,1491 * but that is not an error; it only1492 * means that we won't write log1493 * entries to it.1494 */1495;1496}else{1497strbuf_addf(err,"unable to append to '%s':%s",1498 logfile,strerror(errno));1499goto error;1500}1501}1502}15031504if(*logfd >=0)1505adjust_shared_perm(logfile);15061507free(logfile);1508return0;15091510error:1511free(logfile);1512return-1;1513}15141515static intfiles_create_reflog(struct ref_store *ref_store,1516const char*refname,int force_create,1517struct strbuf *err)1518{1519struct files_ref_store *refs =1520files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1521int fd;15221523if(log_ref_setup(refs, refname, force_create, &fd, err))1524return-1;15251526if(fd >=0)1527close(fd);15281529return0;1530}15311532static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1533const struct object_id *new_oid,1534const char*committer,const char*msg)1535{1536int msglen, written;1537unsigned maxlen, len;1538char*logrec;15391540 msglen = msg ?strlen(msg) :0;1541 maxlen =strlen(committer) + msglen +100;1542 logrec =xmalloc(maxlen);1543 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1544oid_to_hex(old_oid),1545oid_to_hex(new_oid),1546 committer);1547if(msglen)1548 len +=copy_reflog_msg(logrec + len -1, msg) -1;15491550 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1551free(logrec);1552if(written != len)1553return-1;15541555return0;1556}15571558static intfiles_log_ref_write(struct files_ref_store *refs,1559const char*refname,const struct object_id *old_oid,1560const struct object_id *new_oid,const char*msg,1561int flags,struct strbuf *err)1562{1563int logfd, result;15641565if(log_all_ref_updates == LOG_REFS_UNSET)1566 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15671568 result =log_ref_setup(refs, refname,1569 flags & REF_FORCE_CREATE_REFLOG,1570&logfd, err);15711572if(result)1573return result;15741575if(logfd <0)1576return0;1577 result =log_ref_write_fd(logfd, old_oid, new_oid,1578git_committer_info(0), msg);1579if(result) {1580struct strbuf sb = STRBUF_INIT;1581int save_errno = errno;15821583files_reflog_path(refs, &sb, refname);1584strbuf_addf(err,"unable to append to '%s':%s",1585 sb.buf,strerror(save_errno));1586strbuf_release(&sb);1587close(logfd);1588return-1;1589}1590if(close(logfd)) {1591struct strbuf sb = STRBUF_INIT;1592int save_errno = errno;15931594files_reflog_path(refs, &sb, refname);1595strbuf_addf(err,"unable to append to '%s':%s",1596 sb.buf,strerror(save_errno));1597strbuf_release(&sb);1598return-1;1599}1600return0;1601}16021603/*1604 * Write sha1 into the open lockfile, then close the lockfile. On1605 * errors, rollback the lockfile, fill in *err and1606 * return -1.1607 */1608static intwrite_ref_to_lockfile(struct ref_lock *lock,1609const struct object_id *oid,struct strbuf *err)1610{1611static char term ='\n';1612struct object *o;1613int fd;16141615 o =parse_object(oid);1616if(!o) {1617strbuf_addf(err,1618"trying to write ref '%s' with nonexistent object%s",1619 lock->ref_name,oid_to_hex(oid));1620unlock_ref(lock);1621return-1;1622}1623if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1624strbuf_addf(err,1625"trying to write non-commit object%sto branch '%s'",1626oid_to_hex(oid), lock->ref_name);1627unlock_ref(lock);1628return-1;1629}1630 fd =get_lock_file_fd(&lock->lk);1631if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1632write_in_full(fd, &term,1) !=1||1633close_ref_gently(lock) <0) {1634strbuf_addf(err,1635"couldn't write '%s'",get_lock_file_path(&lock->lk));1636unlock_ref(lock);1637return-1;1638}1639return0;1640}16411642/*1643 * Commit a change to a loose reference that has already been written1644 * to the loose reference lockfile. Also update the reflogs if1645 * necessary, using the specified lockmsg (which can be NULL).1646 */1647static intcommit_ref_update(struct files_ref_store *refs,1648struct ref_lock *lock,1649const struct object_id *oid,const char*logmsg,1650struct strbuf *err)1651{1652files_assert_main_repository(refs,"commit_ref_update");16531654clear_loose_ref_cache(refs);1655if(files_log_ref_write(refs, lock->ref_name,1656&lock->old_oid, oid,1657 logmsg,0, err)) {1658char*old_msg =strbuf_detach(err, NULL);1659strbuf_addf(err,"cannot update the ref '%s':%s",1660 lock->ref_name, old_msg);1661free(old_msg);1662unlock_ref(lock);1663return-1;1664}16651666if(strcmp(lock->ref_name,"HEAD") !=0) {1667/*1668 * Special hack: If a branch is updated directly and HEAD1669 * points to it (may happen on the remote side of a push1670 * for example) then logically the HEAD reflog should be1671 * updated too.1672 * A generic solution implies reverse symref information,1673 * but finding all symrefs pointing to the given branch1674 * would be rather costly for this rare event (the direct1675 * update of a branch) to be worth it. So let's cheat and1676 * check with HEAD only which should cover 99% of all usage1677 * scenarios (even 100% of the default ones).1678 */1679struct object_id head_oid;1680int head_flag;1681const char*head_ref;16821683 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1684 RESOLVE_REF_READING,1685 head_oid.hash, &head_flag);1686if(head_ref && (head_flag & REF_ISSYMREF) &&1687!strcmp(head_ref, lock->ref_name)) {1688struct strbuf log_err = STRBUF_INIT;1689if(files_log_ref_write(refs,"HEAD",1690&lock->old_oid, oid,1691 logmsg,0, &log_err)) {1692error("%s", log_err.buf);1693strbuf_release(&log_err);1694}1695}1696}16971698if(commit_ref(lock)) {1699strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1700unlock_ref(lock);1701return-1;1702}17031704unlock_ref(lock);1705return0;1706}17071708static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1709{1710int ret = -1;1711#ifndef NO_SYMLINK_HEAD1712char*ref_path =get_locked_file_path(&lock->lk);1713unlink(ref_path);1714 ret =symlink(target, ref_path);1715free(ref_path);17161717if(ret)1718fprintf(stderr,"no symlink - falling back to symbolic ref\n");1719#endif1720return ret;1721}17221723static voidupdate_symref_reflog(struct files_ref_store *refs,1724struct ref_lock *lock,const char*refname,1725const char*target,const char*logmsg)1726{1727struct strbuf err = STRBUF_INIT;1728struct object_id new_oid;1729if(logmsg &&1730!refs_read_ref_full(&refs->base, target,1731 RESOLVE_REF_READING, new_oid.hash, NULL) &&1732files_log_ref_write(refs, refname, &lock->old_oid,1733&new_oid, logmsg,0, &err)) {1734error("%s", err.buf);1735strbuf_release(&err);1736}1737}17381739static intcreate_symref_locked(struct files_ref_store *refs,1740struct ref_lock *lock,const char*refname,1741const char*target,const char*logmsg)1742{1743if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1744update_symref_reflog(refs, lock, refname, target, logmsg);1745return0;1746}17471748if(!fdopen_lock_file(&lock->lk,"w"))1749returnerror("unable to fdopen%s:%s",1750 lock->lk.tempfile->filename.buf,strerror(errno));17511752update_symref_reflog(refs, lock, refname, target, logmsg);17531754/* no error check; commit_ref will check ferror */1755fprintf(lock->lk.tempfile->fp,"ref:%s\n", target);1756if(commit_ref(lock) <0)1757returnerror("unable to write symref for%s:%s", refname,1758strerror(errno));1759return0;1760}17611762static intfiles_create_symref(struct ref_store *ref_store,1763const char*refname,const char*target,1764const char*logmsg)1765{1766struct files_ref_store *refs =1767files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1768struct strbuf err = STRBUF_INIT;1769struct ref_lock *lock;1770int ret;17711772 lock =lock_ref_sha1_basic(refs, refname, NULL,1773 NULL, NULL, REF_NODEREF, NULL,1774&err);1775if(!lock) {1776error("%s", err.buf);1777strbuf_release(&err);1778return-1;1779}17801781 ret =create_symref_locked(refs, lock, refname, target, logmsg);1782unlock_ref(lock);1783return ret;1784}17851786static intfiles_reflog_exists(struct ref_store *ref_store,1787const char*refname)1788{1789struct files_ref_store *refs =1790files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1791struct strbuf sb = STRBUF_INIT;1792struct stat st;1793int ret;17941795files_reflog_path(refs, &sb, refname);1796 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1797strbuf_release(&sb);1798return ret;1799}18001801static intfiles_delete_reflog(struct ref_store *ref_store,1802const char*refname)1803{1804struct files_ref_store *refs =1805files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1806struct strbuf sb = STRBUF_INIT;1807int ret;18081809files_reflog_path(refs, &sb, refname);1810 ret =remove_path(sb.buf);1811strbuf_release(&sb);1812return ret;1813}18141815static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1816{1817struct object_id ooid, noid;1818char*email_end, *message;1819 timestamp_t timestamp;1820int tz;1821const char*p = sb->buf;18221823/* old SP new SP name <email> SP time TAB msg LF */1824if(!sb->len || sb->buf[sb->len -1] !='\n'||1825parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1826parse_oid_hex(p, &noid, &p) || *p++ !=' '||1827!(email_end =strchr(p,'>')) ||1828 email_end[1] !=' '||1829!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1830!message || message[0] !=' '||1831(message[1] !='+'&& message[1] !='-') ||1832!isdigit(message[2]) || !isdigit(message[3]) ||1833!isdigit(message[4]) || !isdigit(message[5]))1834return0;/* corrupt? */1835 email_end[1] ='\0';1836 tz =strtol(message +1, NULL,10);1837if(message[6] !='\t')1838 message +=6;1839else1840 message +=7;1841returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1842}18431844static char*find_beginning_of_line(char*bob,char*scan)1845{1846while(bob < scan && *(--scan) !='\n')1847;/* keep scanning backwards */1848/*1849 * Return either beginning of the buffer, or LF at the end of1850 * the previous line.1851 */1852return scan;1853}18541855static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1856const char*refname,1857 each_reflog_ent_fn fn,1858void*cb_data)1859{1860struct files_ref_store *refs =1861files_downcast(ref_store, REF_STORE_READ,1862"for_each_reflog_ent_reverse");1863struct strbuf sb = STRBUF_INIT;1864FILE*logfp;1865long pos;1866int ret =0, at_tail =1;18671868files_reflog_path(refs, &sb, refname);1869 logfp =fopen(sb.buf,"r");1870strbuf_release(&sb);1871if(!logfp)1872return-1;18731874/* Jump to the end */1875if(fseek(logfp,0, SEEK_END) <0)1876 ret =error("cannot seek back reflog for%s:%s",1877 refname,strerror(errno));1878 pos =ftell(logfp);1879while(!ret &&0< pos) {1880int cnt;1881size_t nread;1882char buf[BUFSIZ];1883char*endp, *scanp;18841885/* Fill next block from the end */1886 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1887if(fseek(logfp, pos - cnt, SEEK_SET)) {1888 ret =error("cannot seek back reflog for%s:%s",1889 refname,strerror(errno));1890break;1891}1892 nread =fread(buf, cnt,1, logfp);1893if(nread !=1) {1894 ret =error("cannot read%dbytes from reflog for%s:%s",1895 cnt, refname,strerror(errno));1896break;1897}1898 pos -= cnt;18991900 scanp = endp = buf + cnt;1901if(at_tail && scanp[-1] =='\n')1902/* Looking at the final LF at the end of the file */1903 scanp--;1904 at_tail =0;19051906while(buf < scanp) {1907/*1908 * terminating LF of the previous line, or the beginning1909 * of the buffer.1910 */1911char*bp;19121913 bp =find_beginning_of_line(buf, scanp);19141915if(*bp =='\n') {1916/*1917 * The newline is the end of the previous line,1918 * so we know we have complete line starting1919 * at (bp + 1). Prefix it onto any prior data1920 * we collected for the line and process it.1921 */1922strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1923 scanp = bp;1924 endp = bp +1;1925 ret =show_one_reflog_ent(&sb, fn, cb_data);1926strbuf_reset(&sb);1927if(ret)1928break;1929}else if(!pos) {1930/*1931 * We are at the start of the buffer, and the1932 * start of the file; there is no previous1933 * line, and we have everything for this one.1934 * Process it, and we can end the loop.1935 */1936strbuf_splice(&sb,0,0, buf, endp - buf);1937 ret =show_one_reflog_ent(&sb, fn, cb_data);1938strbuf_reset(&sb);1939break;1940}19411942if(bp == buf) {1943/*1944 * We are at the start of the buffer, and there1945 * is more file to read backwards. Which means1946 * we are in the middle of a line. Note that we1947 * may get here even if *bp was a newline; that1948 * just means we are at the exact end of the1949 * previous line, rather than some spot in the1950 * middle.1951 *1952 * Save away what we have to be combined with1953 * the data from the next read.1954 */1955strbuf_splice(&sb,0,0, buf, endp - buf);1956break;1957}1958}19591960}1961if(!ret && sb.len)1962die("BUG: reverse reflog parser had leftover data");19631964fclose(logfp);1965strbuf_release(&sb);1966return ret;1967}19681969static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1970const char*refname,1971 each_reflog_ent_fn fn,void*cb_data)1972{1973struct files_ref_store *refs =1974files_downcast(ref_store, REF_STORE_READ,1975"for_each_reflog_ent");1976FILE*logfp;1977struct strbuf sb = STRBUF_INIT;1978int ret =0;19791980files_reflog_path(refs, &sb, refname);1981 logfp =fopen(sb.buf,"r");1982strbuf_release(&sb);1983if(!logfp)1984return-1;19851986while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1987 ret =show_one_reflog_ent(&sb, fn, cb_data);1988fclose(logfp);1989strbuf_release(&sb);1990return ret;1991}19921993struct files_reflog_iterator {1994struct ref_iterator base;19951996struct ref_store *ref_store;1997struct dir_iterator *dir_iterator;1998struct object_id oid;1999};20002001static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)2002{2003struct files_reflog_iterator *iter =2004(struct files_reflog_iterator *)ref_iterator;2005struct dir_iterator *diter = iter->dir_iterator;2006int ok;20072008while((ok =dir_iterator_advance(diter)) == ITER_OK) {2009int flags;20102011if(!S_ISREG(diter->st.st_mode))2012continue;2013if(diter->basename[0] =='.')2014continue;2015if(ends_with(diter->basename,".lock"))2016continue;20172018if(refs_read_ref_full(iter->ref_store,2019 diter->relative_path,0,2020 iter->oid.hash, &flags)) {2021error("bad ref for%s", diter->path.buf);2022continue;2023}20242025 iter->base.refname = diter->relative_path;2026 iter->base.oid = &iter->oid;2027 iter->base.flags = flags;2028return ITER_OK;2029}20302031 iter->dir_iterator = NULL;2032if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2033 ok = ITER_ERROR;2034return ok;2035}20362037static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2038struct object_id *peeled)2039{2040die("BUG: ref_iterator_peel() called for reflog_iterator");2041}20422043static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2044{2045struct files_reflog_iterator *iter =2046(struct files_reflog_iterator *)ref_iterator;2047int ok = ITER_DONE;20482049if(iter->dir_iterator)2050 ok =dir_iterator_abort(iter->dir_iterator);20512052base_ref_iterator_free(ref_iterator);2053return ok;2054}20552056static struct ref_iterator_vtable files_reflog_iterator_vtable = {2057 files_reflog_iterator_advance,2058 files_reflog_iterator_peel,2059 files_reflog_iterator_abort2060};20612062static struct ref_iterator *reflog_iterator_begin(struct ref_store *ref_store,2063const char*gitdir)2064{2065struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2066struct ref_iterator *ref_iterator = &iter->base;2067struct strbuf sb = STRBUF_INIT;20682069base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2070strbuf_addf(&sb,"%s/logs", gitdir);2071 iter->dir_iterator =dir_iterator_begin(sb.buf);2072 iter->ref_store = ref_store;2073strbuf_release(&sb);20742075return ref_iterator;2076}20772078static enum iterator_selection reflog_iterator_select(2079struct ref_iterator *iter_worktree,2080struct ref_iterator *iter_common,2081void*cb_data)2082{2083if(iter_worktree) {2084/*2085 * We're a bit loose here. We probably should ignore2086 * common refs if they are accidentally added as2087 * per-worktree refs.2088 */2089return ITER_SELECT_0;2090}else if(iter_common) {2091if(ref_type(iter_common->refname) == REF_TYPE_NORMAL)2092return ITER_SELECT_1;20932094/*2095 * The main ref store may contain main worktree's2096 * per-worktree refs, which should be ignored2097 */2098return ITER_SKIP_1;2099}else2100return ITER_DONE;2101}21022103static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2104{2105struct files_ref_store *refs =2106files_downcast(ref_store, REF_STORE_READ,2107"reflog_iterator_begin");21082109if(!strcmp(refs->gitdir, refs->gitcommondir)) {2110returnreflog_iterator_begin(ref_store, refs->gitcommondir);2111}else{2112returnmerge_ref_iterator_begin(2113reflog_iterator_begin(ref_store, refs->gitdir),2114reflog_iterator_begin(ref_store, refs->gitcommondir),2115 reflog_iterator_select, refs);2116}2117}21182119/*2120 * If update is a direct update of head_ref (the reference pointed to2121 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2122 */2123static intsplit_head_update(struct ref_update *update,2124struct ref_transaction *transaction,2125const char*head_ref,2126struct string_list *affected_refnames,2127struct strbuf *err)2128{2129struct string_list_item *item;2130struct ref_update *new_update;21312132if((update->flags & REF_LOG_ONLY) ||2133(update->flags & REF_ISPRUNING) ||2134(update->flags & REF_UPDATE_VIA_HEAD))2135return0;21362137if(strcmp(update->refname, head_ref))2138return0;21392140/*2141 * First make sure that HEAD is not already in the2142 * transaction. This check is O(lg N) in the transaction2143 * size, but it happens at most once per transaction.2144 */2145if(string_list_has_string(affected_refnames,"HEAD")) {2146/* An entry already existed */2147strbuf_addf(err,2148"multiple updates for 'HEAD' (including one "2149"via its referent '%s') are not allowed",2150 update->refname);2151return TRANSACTION_NAME_CONFLICT;2152}21532154 new_update =ref_transaction_add_update(2155 transaction,"HEAD",2156 update->flags | REF_LOG_ONLY | REF_NODEREF,2157 update->new_oid.hash, update->old_oid.hash,2158 update->msg);21592160/*2161 * Add "HEAD". This insertion is O(N) in the transaction2162 * size, but it happens at most once per transaction.2163 * Add new_update->refname instead of a literal "HEAD".2164 */2165if(strcmp(new_update->refname,"HEAD"))2166BUG("%sunexpectedly not 'HEAD'", new_update->refname);2167 item =string_list_insert(affected_refnames, new_update->refname);2168 item->util = new_update;21692170return0;2171}21722173/*2174 * update is for a symref that points at referent and doesn't have2175 * REF_NODEREF set. Split it into two updates:2176 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2177 * - A new, separate update for the referent reference2178 * Note that the new update will itself be subject to splitting when2179 * the iteration gets to it.2180 */2181static intsplit_symref_update(struct files_ref_store *refs,2182struct ref_update *update,2183const char*referent,2184struct ref_transaction *transaction,2185struct string_list *affected_refnames,2186struct strbuf *err)2187{2188struct string_list_item *item;2189struct ref_update *new_update;2190unsigned int new_flags;21912192/*2193 * First make sure that referent is not already in the2194 * transaction. This check is O(lg N) in the transaction2195 * size, but it happens at most once per symref in a2196 * transaction.2197 */2198if(string_list_has_string(affected_refnames, referent)) {2199/* An entry already exists */2200strbuf_addf(err,2201"multiple updates for '%s' (including one "2202"via symref '%s') are not allowed",2203 referent, update->refname);2204return TRANSACTION_NAME_CONFLICT;2205}22062207 new_flags = update->flags;2208if(!strcmp(update->refname,"HEAD")) {2209/*2210 * Record that the new update came via HEAD, so that2211 * when we process it, split_head_update() doesn't try2212 * to add another reflog update for HEAD. Note that2213 * this bit will be propagated if the new_update2214 * itself needs to be split.2215 */2216 new_flags |= REF_UPDATE_VIA_HEAD;2217}22182219 new_update =ref_transaction_add_update(2220 transaction, referent, new_flags,2221 update->new_oid.hash, update->old_oid.hash,2222 update->msg);22232224 new_update->parent_update = update;22252226/*2227 * Change the symbolic ref update to log only. Also, it2228 * doesn't need to check its old SHA-1 value, as that will be2229 * done when new_update is processed.2230 */2231 update->flags |= REF_LOG_ONLY | REF_NODEREF;2232 update->flags &= ~REF_HAVE_OLD;22332234/*2235 * Add the referent. This insertion is O(N) in the transaction2236 * size, but it happens at most once per symref in a2237 * transaction. Make sure to add new_update->refname, which will2238 * be valid as long as affected_refnames is in use, and NOT2239 * referent, which might soon be freed by our caller.2240 */2241 item =string_list_insert(affected_refnames, new_update->refname);2242if(item->util)2243BUG("%sunexpectedly found in affected_refnames",2244 new_update->refname);2245 item->util = new_update;22462247return0;2248}22492250/*2251 * Return the refname under which update was originally requested.2252 */2253static const char*original_update_refname(struct ref_update *update)2254{2255while(update->parent_update)2256 update = update->parent_update;22572258return update->refname;2259}22602261/*2262 * Check whether the REF_HAVE_OLD and old_oid values stored in update2263 * are consistent with oid, which is the reference's current value. If2264 * everything is OK, return 0; otherwise, write an error message to2265 * err and return -1.2266 */2267static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2268struct strbuf *err)2269{2270if(!(update->flags & REF_HAVE_OLD) ||2271!oidcmp(oid, &update->old_oid))2272return0;22732274if(is_null_oid(&update->old_oid))2275strbuf_addf(err,"cannot lock ref '%s': "2276"reference already exists",2277original_update_refname(update));2278else if(is_null_oid(oid))2279strbuf_addf(err,"cannot lock ref '%s': "2280"reference is missing but expected%s",2281original_update_refname(update),2282oid_to_hex(&update->old_oid));2283else2284strbuf_addf(err,"cannot lock ref '%s': "2285"is at%sbut expected%s",2286original_update_refname(update),2287oid_to_hex(oid),2288oid_to_hex(&update->old_oid));22892290return-1;2291}22922293/*2294 * Prepare for carrying out update:2295 * - Lock the reference referred to by update.2296 * - Read the reference under lock.2297 * - Check that its old SHA-1 value (if specified) is correct, and in2298 * any case record it in update->lock->old_oid for later use when2299 * writing the reflog.2300 * - If it is a symref update without REF_NODEREF, split it up into a2301 * REF_LOG_ONLY update of the symref and add a separate update for2302 * the referent to transaction.2303 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2304 * update of HEAD.2305 */2306static intlock_ref_for_update(struct files_ref_store *refs,2307struct ref_update *update,2308struct ref_transaction *transaction,2309const char*head_ref,2310struct string_list *affected_refnames,2311struct strbuf *err)2312{2313struct strbuf referent = STRBUF_INIT;2314int mustexist = (update->flags & REF_HAVE_OLD) &&2315!is_null_oid(&update->old_oid);2316int ret =0;2317struct ref_lock *lock;23182319files_assert_main_repository(refs,"lock_ref_for_update");23202321if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2322 update->flags |= REF_DELETING;23232324if(head_ref) {2325 ret =split_head_update(update, transaction, head_ref,2326 affected_refnames, err);2327if(ret)2328goto out;2329}23302331 ret =lock_raw_ref(refs, update->refname, mustexist,2332 affected_refnames, NULL,2333&lock, &referent,2334&update->type, err);2335if(ret) {2336char*reason;23372338 reason =strbuf_detach(err, NULL);2339strbuf_addf(err,"cannot lock ref '%s':%s",2340original_update_refname(update), reason);2341free(reason);2342goto out;2343}23442345 update->backend_data = lock;23462347if(update->type & REF_ISSYMREF) {2348if(update->flags & REF_NODEREF) {2349/*2350 * We won't be reading the referent as part of2351 * the transaction, so we have to read it here2352 * to record and possibly check old_sha1:2353 */2354if(refs_read_ref_full(&refs->base,2355 referent.buf,0,2356 lock->old_oid.hash, NULL)) {2357if(update->flags & REF_HAVE_OLD) {2358strbuf_addf(err,"cannot lock ref '%s': "2359"error reading reference",2360original_update_refname(update));2361 ret = TRANSACTION_GENERIC_ERROR;2362goto out;2363}2364}else if(check_old_oid(update, &lock->old_oid, err)) {2365 ret = TRANSACTION_GENERIC_ERROR;2366goto out;2367}2368}else{2369/*2370 * Create a new update for the reference this2371 * symref is pointing at. Also, we will record2372 * and verify old_sha1 for this update as part2373 * of processing the split-off update, so we2374 * don't have to do it here.2375 */2376 ret =split_symref_update(refs, update,2377 referent.buf, transaction,2378 affected_refnames, err);2379if(ret)2380goto out;2381}2382}else{2383struct ref_update *parent_update;23842385if(check_old_oid(update, &lock->old_oid, err)) {2386 ret = TRANSACTION_GENERIC_ERROR;2387goto out;2388}23892390/*2391 * If this update is happening indirectly because of a2392 * symref update, record the old SHA-1 in the parent2393 * update:2394 */2395for(parent_update = update->parent_update;2396 parent_update;2397 parent_update = parent_update->parent_update) {2398struct ref_lock *parent_lock = parent_update->backend_data;2399oidcpy(&parent_lock->old_oid, &lock->old_oid);2400}2401}24022403if((update->flags & REF_HAVE_NEW) &&2404!(update->flags & REF_DELETING) &&2405!(update->flags & REF_LOG_ONLY)) {2406if(!(update->type & REF_ISSYMREF) &&2407!oidcmp(&lock->old_oid, &update->new_oid)) {2408/*2409 * The reference already has the desired2410 * value, so we don't need to write it.2411 */2412}else if(write_ref_to_lockfile(lock, &update->new_oid,2413 err)) {2414char*write_err =strbuf_detach(err, NULL);24152416/*2417 * The lock was freed upon failure of2418 * write_ref_to_lockfile():2419 */2420 update->backend_data = NULL;2421strbuf_addf(err,2422"cannot update ref '%s':%s",2423 update->refname, write_err);2424free(write_err);2425 ret = TRANSACTION_GENERIC_ERROR;2426goto out;2427}else{2428 update->flags |= REF_NEEDS_COMMIT;2429}2430}2431if(!(update->flags & REF_NEEDS_COMMIT)) {2432/*2433 * We didn't call write_ref_to_lockfile(), so2434 * the lockfile is still open. Close it to2435 * free up the file descriptor:2436 */2437if(close_ref_gently(lock)) {2438strbuf_addf(err,"couldn't close '%s.lock'",2439 update->refname);2440 ret = TRANSACTION_GENERIC_ERROR;2441goto out;2442}2443}24442445out:2446strbuf_release(&referent);2447return ret;2448}24492450struct files_transaction_backend_data {2451struct ref_transaction *packed_transaction;2452int packed_refs_locked;2453};24542455/*2456 * Unlock any references in `transaction` that are still locked, and2457 * mark the transaction closed.2458 */2459static voidfiles_transaction_cleanup(struct files_ref_store *refs,2460struct ref_transaction *transaction)2461{2462size_t i;2463struct files_transaction_backend_data *backend_data =2464 transaction->backend_data;2465struct strbuf err = STRBUF_INIT;24662467for(i =0; i < transaction->nr; i++) {2468struct ref_update *update = transaction->updates[i];2469struct ref_lock *lock = update->backend_data;24702471if(lock) {2472unlock_ref(lock);2473 update->backend_data = NULL;2474}2475}24762477if(backend_data->packed_transaction &&2478ref_transaction_abort(backend_data->packed_transaction, &err)) {2479error("error aborting transaction:%s", err.buf);2480strbuf_release(&err);2481}24822483if(backend_data->packed_refs_locked)2484packed_refs_unlock(refs->packed_ref_store);24852486free(backend_data);24872488 transaction->state = REF_TRANSACTION_CLOSED;2489}24902491static intfiles_transaction_prepare(struct ref_store *ref_store,2492struct ref_transaction *transaction,2493struct strbuf *err)2494{2495struct files_ref_store *refs =2496files_downcast(ref_store, REF_STORE_WRITE,2497"ref_transaction_prepare");2498size_t i;2499int ret =0;2500struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2501char*head_ref = NULL;2502int head_type;2503struct object_id head_oid;2504struct files_transaction_backend_data *backend_data;2505struct ref_transaction *packed_transaction = NULL;25062507assert(err);25082509if(!transaction->nr)2510goto cleanup;25112512 backend_data =xcalloc(1,sizeof(*backend_data));2513 transaction->backend_data = backend_data;25142515/*2516 * Fail if a refname appears more than once in the2517 * transaction. (If we end up splitting up any updates using2518 * split_symref_update() or split_head_update(), those2519 * functions will check that the new updates don't have the2520 * same refname as any existing ones.)2521 */2522for(i =0; i < transaction->nr; i++) {2523struct ref_update *update = transaction->updates[i];2524struct string_list_item *item =2525string_list_append(&affected_refnames, update->refname);25262527/*2528 * We store a pointer to update in item->util, but at2529 * the moment we never use the value of this field2530 * except to check whether it is non-NULL.2531 */2532 item->util = update;2533}2534string_list_sort(&affected_refnames);2535if(ref_update_reject_duplicates(&affected_refnames, err)) {2536 ret = TRANSACTION_GENERIC_ERROR;2537goto cleanup;2538}25392540/*2541 * Special hack: If a branch is updated directly and HEAD2542 * points to it (may happen on the remote side of a push2543 * for example) then logically the HEAD reflog should be2544 * updated too.2545 *2546 * A generic solution would require reverse symref lookups,2547 * but finding all symrefs pointing to a given branch would be2548 * rather costly for this rare event (the direct update of a2549 * branch) to be worth it. So let's cheat and check with HEAD2550 * only, which should cover 99% of all usage scenarios (even2551 * 100% of the default ones).2552 *2553 * So if HEAD is a symbolic reference, then record the name of2554 * the reference that it points to. If we see an update of2555 * head_ref within the transaction, then split_head_update()2556 * arranges for the reflog of HEAD to be updated, too.2557 */2558 head_ref =refs_resolve_refdup(ref_store,"HEAD",2559 RESOLVE_REF_NO_RECURSE,2560 head_oid.hash, &head_type);25612562if(head_ref && !(head_type & REF_ISSYMREF)) {2563FREE_AND_NULL(head_ref);2564}25652566/*2567 * Acquire all locks, verify old values if provided, check2568 * that new values are valid, and write new values to the2569 * lockfiles, ready to be activated. Only keep one lockfile2570 * open at a time to avoid running out of file descriptors.2571 * Note that lock_ref_for_update() might append more updates2572 * to the transaction.2573 */2574for(i =0; i < transaction->nr; i++) {2575struct ref_update *update = transaction->updates[i];25762577 ret =lock_ref_for_update(refs, update, transaction,2578 head_ref, &affected_refnames, err);2579if(ret)2580break;25812582if(update->flags & REF_DELETING &&2583!(update->flags & REF_LOG_ONLY) &&2584!(update->flags & REF_ISPRUNING)) {2585/*2586 * This reference has to be deleted from2587 * packed-refs if it exists there.2588 */2589if(!packed_transaction) {2590 packed_transaction =ref_store_transaction_begin(2591 refs->packed_ref_store, err);2592if(!packed_transaction) {2593 ret = TRANSACTION_GENERIC_ERROR;2594goto cleanup;2595}25962597 backend_data->packed_transaction =2598 packed_transaction;2599}26002601ref_transaction_add_update(2602 packed_transaction, update->refname,2603 update->flags & ~REF_HAVE_OLD,2604 update->new_oid.hash, update->old_oid.hash,2605 NULL);2606}2607}26082609if(packed_transaction) {2610if(packed_refs_lock(refs->packed_ref_store,0, err)) {2611 ret = TRANSACTION_GENERIC_ERROR;2612goto cleanup;2613}2614 backend_data->packed_refs_locked =1;2615 ret =ref_transaction_prepare(packed_transaction, err);2616}26172618cleanup:2619free(head_ref);2620string_list_clear(&affected_refnames,0);26212622if(ret)2623files_transaction_cleanup(refs, transaction);2624else2625 transaction->state = REF_TRANSACTION_PREPARED;26262627return ret;2628}26292630static intfiles_transaction_finish(struct ref_store *ref_store,2631struct ref_transaction *transaction,2632struct strbuf *err)2633{2634struct files_ref_store *refs =2635files_downcast(ref_store,0,"ref_transaction_finish");2636size_t i;2637int ret =0;2638struct strbuf sb = STRBUF_INIT;2639struct files_transaction_backend_data *backend_data;2640struct ref_transaction *packed_transaction;264126422643assert(err);26442645if(!transaction->nr) {2646 transaction->state = REF_TRANSACTION_CLOSED;2647return0;2648}26492650 backend_data = transaction->backend_data;2651 packed_transaction = backend_data->packed_transaction;26522653/* Perform updates first so live commits remain referenced */2654for(i =0; i < transaction->nr; i++) {2655struct ref_update *update = transaction->updates[i];2656struct ref_lock *lock = update->backend_data;26572658if(update->flags & REF_NEEDS_COMMIT ||2659 update->flags & REF_LOG_ONLY) {2660if(files_log_ref_write(refs,2661 lock->ref_name,2662&lock->old_oid,2663&update->new_oid,2664 update->msg, update->flags,2665 err)) {2666char*old_msg =strbuf_detach(err, NULL);26672668strbuf_addf(err,"cannot update the ref '%s':%s",2669 lock->ref_name, old_msg);2670free(old_msg);2671unlock_ref(lock);2672 update->backend_data = NULL;2673 ret = TRANSACTION_GENERIC_ERROR;2674goto cleanup;2675}2676}2677if(update->flags & REF_NEEDS_COMMIT) {2678clear_loose_ref_cache(refs);2679if(commit_ref(lock)) {2680strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2681unlock_ref(lock);2682 update->backend_data = NULL;2683 ret = TRANSACTION_GENERIC_ERROR;2684goto cleanup;2685}2686}2687}26882689/*2690 * Now that updates are safely completed, we can perform2691 * deletes. First delete the reflogs of any references that2692 * will be deleted, since (in the unexpected event of an2693 * error) leaving a reference without a reflog is less bad2694 * than leaving a reflog without a reference (the latter is a2695 * mildly invalid repository state):2696 */2697for(i =0; i < transaction->nr; i++) {2698struct ref_update *update = transaction->updates[i];2699if(update->flags & REF_DELETING &&2700!(update->flags & REF_LOG_ONLY) &&2701!(update->flags & REF_ISPRUNING)) {2702strbuf_reset(&sb);2703files_reflog_path(refs, &sb, update->refname);2704if(!unlink_or_warn(sb.buf))2705try_remove_empty_parents(refs, update->refname,2706 REMOVE_EMPTY_PARENTS_REFLOG);2707}2708}27092710/*2711 * Perform deletes now that updates are safely completed.2712 *2713 * First delete any packed versions of the references, while2714 * retaining the packed-refs lock:2715 */2716if(packed_transaction) {2717 ret =ref_transaction_commit(packed_transaction, err);2718ref_transaction_free(packed_transaction);2719 packed_transaction = NULL;2720 backend_data->packed_transaction = NULL;2721if(ret)2722goto cleanup;2723}27242725/* Now delete the loose versions of the references: */2726for(i =0; i < transaction->nr; i++) {2727struct ref_update *update = transaction->updates[i];2728struct ref_lock *lock = update->backend_data;27292730if(update->flags & REF_DELETING &&2731!(update->flags & REF_LOG_ONLY)) {2732if(!(update->type & REF_ISPACKED) ||2733 update->type & REF_ISSYMREF) {2734/* It is a loose reference. */2735strbuf_reset(&sb);2736files_ref_path(refs, &sb, lock->ref_name);2737if(unlink_or_msg(sb.buf, err)) {2738 ret = TRANSACTION_GENERIC_ERROR;2739goto cleanup;2740}2741 update->flags |= REF_DELETED_LOOSE;2742}2743}2744}27452746clear_loose_ref_cache(refs);27472748cleanup:2749files_transaction_cleanup(refs, transaction);27502751for(i =0; i < transaction->nr; i++) {2752struct ref_update *update = transaction->updates[i];27532754if(update->flags & REF_DELETED_LOOSE) {2755/*2756 * The loose reference was deleted. Delete any2757 * empty parent directories. (Note that this2758 * can only work because we have already2759 * removed the lockfile.)2760 */2761try_remove_empty_parents(refs, update->refname,2762 REMOVE_EMPTY_PARENTS_REF);2763}2764}27652766strbuf_release(&sb);2767return ret;2768}27692770static intfiles_transaction_abort(struct ref_store *ref_store,2771struct ref_transaction *transaction,2772struct strbuf *err)2773{2774struct files_ref_store *refs =2775files_downcast(ref_store,0,"ref_transaction_abort");27762777files_transaction_cleanup(refs, transaction);2778return0;2779}27802781static intref_present(const char*refname,2782const struct object_id *oid,int flags,void*cb_data)2783{2784struct string_list *affected_refnames = cb_data;27852786returnstring_list_has_string(affected_refnames, refname);2787}27882789static intfiles_initial_transaction_commit(struct ref_store *ref_store,2790struct ref_transaction *transaction,2791struct strbuf *err)2792{2793struct files_ref_store *refs =2794files_downcast(ref_store, REF_STORE_WRITE,2795"initial_ref_transaction_commit");2796size_t i;2797int ret =0;2798struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2799struct ref_transaction *packed_transaction = NULL;28002801assert(err);28022803if(transaction->state != REF_TRANSACTION_OPEN)2804die("BUG: commit called for transaction that is not open");28052806/* Fail if a refname appears more than once in the transaction: */2807for(i =0; i < transaction->nr; i++)2808string_list_append(&affected_refnames,2809 transaction->updates[i]->refname);2810string_list_sort(&affected_refnames);2811if(ref_update_reject_duplicates(&affected_refnames, err)) {2812 ret = TRANSACTION_GENERIC_ERROR;2813goto cleanup;2814}28152816/*2817 * It's really undefined to call this function in an active2818 * repository or when there are existing references: we are2819 * only locking and changing packed-refs, so (1) any2820 * simultaneous processes might try to change a reference at2821 * the same time we do, and (2) any existing loose versions of2822 * the references that we are setting would have precedence2823 * over our values. But some remote helpers create the remote2824 * "HEAD" and "master" branches before calling this function,2825 * so here we really only check that none of the references2826 * that we are creating already exists.2827 */2828if(refs_for_each_rawref(&refs->base, ref_present,2829&affected_refnames))2830die("BUG: initial ref transaction called with existing refs");28312832 packed_transaction =ref_store_transaction_begin(refs->packed_ref_store, err);2833if(!packed_transaction) {2834 ret = TRANSACTION_GENERIC_ERROR;2835goto cleanup;2836}28372838for(i =0; i < transaction->nr; i++) {2839struct ref_update *update = transaction->updates[i];28402841if((update->flags & REF_HAVE_OLD) &&2842!is_null_oid(&update->old_oid))2843die("BUG: initial ref transaction with old_sha1 set");2844if(refs_verify_refname_available(&refs->base, update->refname,2845&affected_refnames, NULL,2846 err)) {2847 ret = TRANSACTION_NAME_CONFLICT;2848goto cleanup;2849}28502851/*2852 * Add a reference creation for this reference to the2853 * packed-refs transaction:2854 */2855ref_transaction_add_update(packed_transaction, update->refname,2856 update->flags & ~REF_HAVE_OLD,2857 update->new_oid.hash, update->old_oid.hash,2858 NULL);2859}28602861if(packed_refs_lock(refs->packed_ref_store,0, err)) {2862 ret = TRANSACTION_GENERIC_ERROR;2863goto cleanup;2864}28652866if(initial_ref_transaction_commit(packed_transaction, err)) {2867 ret = TRANSACTION_GENERIC_ERROR;2868goto cleanup;2869}28702871cleanup:2872if(packed_transaction)2873ref_transaction_free(packed_transaction);2874packed_refs_unlock(refs->packed_ref_store);2875 transaction->state = REF_TRANSACTION_CLOSED;2876string_list_clear(&affected_refnames,0);2877return ret;2878}28792880struct expire_reflog_cb {2881unsigned int flags;2882 reflog_expiry_should_prune_fn *should_prune_fn;2883void*policy_cb;2884FILE*newlog;2885struct object_id last_kept_oid;2886};28872888static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2889const char*email, timestamp_t timestamp,int tz,2890const char*message,void*cb_data)2891{2892struct expire_reflog_cb *cb = cb_data;2893struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;28942895if(cb->flags & EXPIRE_REFLOGS_REWRITE)2896 ooid = &cb->last_kept_oid;28972898if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2899 message, policy_cb)) {2900if(!cb->newlog)2901printf("would prune%s", message);2902else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2903printf("prune%s", message);2904}else{2905if(cb->newlog) {2906fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2907oid_to_hex(ooid),oid_to_hex(noid),2908 email, timestamp, tz, message);2909oidcpy(&cb->last_kept_oid, noid);2910}2911if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2912printf("keep%s", message);2913}2914return0;2915}29162917static intfiles_reflog_expire(struct ref_store *ref_store,2918const char*refname,const unsigned char*sha1,2919unsigned int flags,2920 reflog_expiry_prepare_fn prepare_fn,2921 reflog_expiry_should_prune_fn should_prune_fn,2922 reflog_expiry_cleanup_fn cleanup_fn,2923void*policy_cb_data)2924{2925struct files_ref_store *refs =2926files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2927static struct lock_file reflog_lock;2928struct expire_reflog_cb cb;2929struct ref_lock *lock;2930struct strbuf log_file_sb = STRBUF_INIT;2931char*log_file;2932int status =0;2933int type;2934struct strbuf err = STRBUF_INIT;2935struct object_id oid;29362937memset(&cb,0,sizeof(cb));2938 cb.flags = flags;2939 cb.policy_cb = policy_cb_data;2940 cb.should_prune_fn = should_prune_fn;29412942/*2943 * The reflog file is locked by holding the lock on the2944 * reference itself, plus we might need to update the2945 * reference if --updateref was specified:2946 */2947 lock =lock_ref_sha1_basic(refs, refname, sha1,2948 NULL, NULL, REF_NODEREF,2949&type, &err);2950if(!lock) {2951error("cannot lock ref '%s':%s", refname, err.buf);2952strbuf_release(&err);2953return-1;2954}2955if(!refs_reflog_exists(ref_store, refname)) {2956unlock_ref(lock);2957return0;2958}29592960files_reflog_path(refs, &log_file_sb, refname);2961 log_file =strbuf_detach(&log_file_sb, NULL);2962if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2963/*2964 * Even though holding $GIT_DIR/logs/$reflog.lock has2965 * no locking implications, we use the lock_file2966 * machinery here anyway because it does a lot of the2967 * work we need, including cleaning up if the program2968 * exits unexpectedly.2969 */2970if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2971struct strbuf err = STRBUF_INIT;2972unable_to_lock_message(log_file, errno, &err);2973error("%s", err.buf);2974strbuf_release(&err);2975goto failure;2976}2977 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2978if(!cb.newlog) {2979error("cannot fdopen%s(%s)",2980get_lock_file_path(&reflog_lock),strerror(errno));2981goto failure;2982}2983}29842985hashcpy(oid.hash, sha1);29862987(*prepare_fn)(refname, &oid, cb.policy_cb);2988refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2989(*cleanup_fn)(cb.policy_cb);29902991if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2992/*2993 * It doesn't make sense to adjust a reference pointed2994 * to by a symbolic ref based on expiring entries in2995 * the symbolic reference's reflog. Nor can we update2996 * a reference if there are no remaining reflog2997 * entries.2998 */2999int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&3000!(type & REF_ISSYMREF) &&3001!is_null_oid(&cb.last_kept_oid);30023003if(close_lock_file_gently(&reflog_lock)) {3004 status |=error("couldn't write%s:%s", log_file,3005strerror(errno));3006rollback_lock_file(&reflog_lock);3007}else if(update &&3008(write_in_full(get_lock_file_fd(&lock->lk),3009oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||3010write_str_in_full(get_lock_file_fd(&lock->lk),"\n") !=1||3011close_ref_gently(lock) <0)) {3012 status |=error("couldn't write%s",3013get_lock_file_path(&lock->lk));3014rollback_lock_file(&reflog_lock);3015}else if(commit_lock_file(&reflog_lock)) {3016 status |=error("unable to write reflog '%s' (%s)",3017 log_file,strerror(errno));3018}else if(update &&commit_ref(lock)) {3019 status |=error("couldn't set%s", lock->ref_name);3020}3021}3022free(log_file);3023unlock_ref(lock);3024return status;30253026 failure:3027rollback_lock_file(&reflog_lock);3028free(log_file);3029unlock_ref(lock);3030return-1;3031}30323033static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)3034{3035struct files_ref_store *refs =3036files_downcast(ref_store, REF_STORE_WRITE,"init_db");3037struct strbuf sb = STRBUF_INIT;30383039/*3040 * Create .git/refs/{heads,tags}3041 */3042files_ref_path(refs, &sb,"refs/heads");3043safe_create_dir(sb.buf,1);30443045strbuf_reset(&sb);3046files_ref_path(refs, &sb,"refs/tags");3047safe_create_dir(sb.buf,1);30483049strbuf_release(&sb);3050return0;3051}30523053struct ref_storage_be refs_be_files = {3054 NULL,3055"files",3056 files_ref_store_create,3057 files_init_db,3058 files_transaction_prepare,3059 files_transaction_finish,3060 files_transaction_abort,3061 files_initial_transaction_commit,30623063 files_pack_refs,3064 files_peel_ref,3065 files_create_symref,3066 files_delete_refs,3067 files_rename_ref,30683069 files_ref_iterator_begin,3070 files_read_raw_ref,30713072 files_reflog_iterator_begin,3073 files_for_each_reflog_ent,3074 files_for_each_reflog_ent_reverse,3075 files_reflog_exists,3076 files_create_reflog,3077 files_delete_reflog,3078 files_reflog_expire3079};