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}10431044static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1045{1046while(r) {1047prune_ref(refs, r);1048 r = r->next;1049}1050}10511052/*1053 * Return true if the specified reference should be packed.1054 */1055static intshould_pack_ref(const char*refname,1056const struct object_id *oid,unsigned int ref_flags,1057unsigned int pack_flags)1058{1059/* Do not pack per-worktree refs: */1060if(ref_type(refname) != REF_TYPE_NORMAL)1061return0;10621063/* Do not pack non-tags unless PACK_REFS_ALL is set: */1064if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1065return0;10661067/* Do not pack symbolic refs: */1068if(ref_flags & REF_ISSYMREF)1069return0;10701071/* Do not pack broken refs: */1072if(!ref_resolves_to_object(refname, oid, ref_flags))1073return0;10741075return1;1076}10771078static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1079{1080struct files_ref_store *refs =1081files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1082"pack_refs");1083struct ref_iterator *iter;1084int ok;1085struct ref_to_prune *refs_to_prune = NULL;1086struct strbuf err = STRBUF_INIT;10871088packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);10891090 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1091while((ok =ref_iterator_advance(iter)) == ITER_OK) {1092/*1093 * If the loose reference can be packed, add an entry1094 * in the packed ref cache. If the reference should be1095 * pruned, also add it to refs_to_prune.1096 */1097if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1098 flags))1099continue;11001101/*1102 * Create an entry in the packed-refs cache equivalent1103 * to the one from the loose ref cache, except that1104 * we don't copy the peeled status, because we want it1105 * to be re-peeled.1106 */1107add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);11081109/* Schedule the loose reference for pruning if requested. */1110if((flags & PACK_REFS_PRUNE)) {1111struct ref_to_prune *n;1112FLEX_ALLOC_STR(n, name, iter->refname);1113hashcpy(n->sha1, iter->oid->hash);1114 n->next = refs_to_prune;1115 refs_to_prune = n;1116}1117}1118if(ok != ITER_DONE)1119die("error while iterating over references");11201121if(commit_packed_refs(refs->packed_ref_store, &err))1122die("unable to overwrite old ref-pack file:%s", err.buf);1123packed_refs_unlock(refs->packed_ref_store);11241125prune_refs(refs, refs_to_prune);1126strbuf_release(&err);1127return0;1128}11291130static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1131struct string_list *refnames,unsigned int flags)1132{1133struct files_ref_store *refs =1134files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1135struct strbuf err = STRBUF_INIT;1136int i, result =0;11371138if(!refnames->nr)1139return0;11401141if(packed_refs_lock(refs->packed_ref_store,0, &err))1142goto error;11431144if(repack_without_refs(refs->packed_ref_store, refnames, &err)) {1145packed_refs_unlock(refs->packed_ref_store);1146goto error;1147}11481149packed_refs_unlock(refs->packed_ref_store);11501151for(i =0; i < refnames->nr; i++) {1152const char*refname = refnames->items[i].string;11531154if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1155 result |=error(_("could not remove reference%s"), refname);1156}11571158strbuf_release(&err);1159return result;11601161error:1162/*1163 * If we failed to rewrite the packed-refs file, then it is1164 * unsafe to try to remove loose refs, because doing so might1165 * expose an obsolete packed value for a reference that might1166 * even point at an object that has been garbage collected.1167 */1168if(refnames->nr ==1)1169error(_("could not delete reference%s:%s"),1170 refnames->items[0].string, err.buf);1171else1172error(_("could not delete references:%s"), err.buf);11731174strbuf_release(&err);1175return-1;1176}11771178/*1179 * People using contrib's git-new-workdir have .git/logs/refs ->1180 * /some/other/path/.git/logs/refs, and that may live on another device.1181 *1182 * IOW, to avoid cross device rename errors, the temporary renamed log must1183 * live into logs/refs.1184 */1185#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"11861187struct rename_cb {1188const char*tmp_renamed_log;1189int true_errno;1190};11911192static intrename_tmp_log_callback(const char*path,void*cb_data)1193{1194struct rename_cb *cb = cb_data;11951196if(rename(cb->tmp_renamed_log, path)) {1197/*1198 * rename(a, b) when b is an existing directory ought1199 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1200 * Sheesh. Record the true errno for error reporting,1201 * but report EISDIR to raceproof_create_file() so1202 * that it knows to retry.1203 */1204 cb->true_errno = errno;1205if(errno == ENOTDIR)1206 errno = EISDIR;1207return-1;1208}else{1209return0;1210}1211}12121213static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1214{1215struct strbuf path = STRBUF_INIT;1216struct strbuf tmp = STRBUF_INIT;1217struct rename_cb cb;1218int ret;12191220files_reflog_path(refs, &path, newrefname);1221files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1222 cb.tmp_renamed_log = tmp.buf;1223 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1224if(ret) {1225if(errno == EISDIR)1226error("directory not empty:%s", path.buf);1227else1228error("unable to move logfile%sto%s:%s",1229 tmp.buf, path.buf,1230strerror(cb.true_errno));1231}12321233strbuf_release(&path);1234strbuf_release(&tmp);1235return ret;1236}12371238static intwrite_ref_to_lockfile(struct ref_lock *lock,1239const struct object_id *oid,struct strbuf *err);1240static intcommit_ref_update(struct files_ref_store *refs,1241struct ref_lock *lock,1242const struct object_id *oid,const char*logmsg,1243struct strbuf *err);12441245static intfiles_rename_ref(struct ref_store *ref_store,1246const char*oldrefname,const char*newrefname,1247const char*logmsg)1248{1249struct files_ref_store *refs =1250files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1251struct object_id oid, orig_oid;1252int flag =0, logmoved =0;1253struct ref_lock *lock;1254struct stat loginfo;1255struct strbuf sb_oldref = STRBUF_INIT;1256struct strbuf sb_newref = STRBUF_INIT;1257struct strbuf tmp_renamed_log = STRBUF_INIT;1258int log, ret;1259struct strbuf err = STRBUF_INIT;12601261files_reflog_path(refs, &sb_oldref, oldrefname);1262files_reflog_path(refs, &sb_newref, newrefname);1263files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12641265 log = !lstat(sb_oldref.buf, &loginfo);1266if(log &&S_ISLNK(loginfo.st_mode)) {1267 ret =error("reflog for%sis a symlink", oldrefname);1268goto out;1269}12701271if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1272 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1273 orig_oid.hash, &flag)) {1274 ret =error("refname%snot found", oldrefname);1275goto out;1276}12771278if(flag & REF_ISSYMREF) {1279 ret =error("refname%sis a symbolic ref, renaming it is not supported",1280 oldrefname);1281goto out;1282}1283if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1284 ret =1;1285goto out;1286}12871288if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1289 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1290 oldrefname,strerror(errno));1291goto out;1292}12931294if(refs_delete_ref(&refs->base, logmsg, oldrefname,1295 orig_oid.hash, REF_NODEREF)) {1296error("unable to delete old%s", oldrefname);1297goto rollback;1298}12991300/*1301 * Since we are doing a shallow lookup, oid is not the1302 * correct value to pass to delete_ref as old_oid. But that1303 * doesn't matter, because an old_oid check wouldn't add to1304 * the safety anyway; we want to delete the reference whatever1305 * its current value.1306 */1307if(!refs_read_ref_full(&refs->base, newrefname,1308 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1309 oid.hash, NULL) &&1310refs_delete_ref(&refs->base, NULL, newrefname,1311 NULL, REF_NODEREF)) {1312if(errno == EISDIR) {1313struct strbuf path = STRBUF_INIT;1314int result;13151316files_ref_path(refs, &path, newrefname);1317 result =remove_empty_directories(&path);1318strbuf_release(&path);13191320if(result) {1321error("Directory not empty:%s", newrefname);1322goto rollback;1323}1324}else{1325error("unable to delete existing%s", newrefname);1326goto rollback;1327}1328}13291330if(log &&rename_tmp_log(refs, newrefname))1331goto rollback;13321333 logmoved = log;13341335 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1336 REF_NODEREF, NULL, &err);1337if(!lock) {1338error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1339strbuf_release(&err);1340goto rollback;1341}1342oidcpy(&lock->old_oid, &orig_oid);13431344if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1345commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1346error("unable to write current sha1 into%s:%s", newrefname, err.buf);1347strbuf_release(&err);1348goto rollback;1349}13501351 ret =0;1352goto out;13531354 rollback:1355 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1356 REF_NODEREF, NULL, &err);1357if(!lock) {1358error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1359strbuf_release(&err);1360goto rollbacklog;1361}13621363 flag = log_all_ref_updates;1364 log_all_ref_updates = LOG_REFS_NONE;1365if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1366commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1367error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1368strbuf_release(&err);1369}1370 log_all_ref_updates = flag;13711372 rollbacklog:1373if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1374error("unable to restore logfile%sfrom%s:%s",1375 oldrefname, newrefname,strerror(errno));1376if(!logmoved && log &&1377rename(tmp_renamed_log.buf, sb_oldref.buf))1378error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1379 oldrefname,strerror(errno));1380 ret =1;1381 out:1382strbuf_release(&sb_newref);1383strbuf_release(&sb_oldref);1384strbuf_release(&tmp_renamed_log);13851386return ret;1387}13881389static intclose_ref_gently(struct ref_lock *lock)1390{1391if(close_lock_file_gently(&lock->lk))1392return-1;1393return0;1394}13951396static intcommit_ref(struct ref_lock *lock)1397{1398char*path =get_locked_file_path(&lock->lk);1399struct stat st;14001401if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1402/*1403 * There is a directory at the path we want to rename1404 * the lockfile to. Hopefully it is empty; try to1405 * delete it.1406 */1407size_t len =strlen(path);1408struct strbuf sb_path = STRBUF_INIT;14091410strbuf_attach(&sb_path, path, len, len);14111412/*1413 * If this fails, commit_lock_file() will also fail1414 * and will report the problem.1415 */1416remove_empty_directories(&sb_path);1417strbuf_release(&sb_path);1418}else{1419free(path);1420}14211422if(commit_lock_file(&lock->lk))1423return-1;1424return0;1425}14261427static intopen_or_create_logfile(const char*path,void*cb)1428{1429int*fd = cb;14301431*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1432return(*fd <0) ? -1:0;1433}14341435/*1436 * Create a reflog for a ref. If force_create = 0, only create the1437 * reflog for certain refs (those for which should_autocreate_reflog1438 * returns non-zero). Otherwise, create it regardless of the reference1439 * name. If the logfile already existed or was created, return 0 and1440 * set *logfd to the file descriptor opened for appending to the file.1441 * If no logfile exists and we decided not to create one, return 0 and1442 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1443 * return -1.1444 */1445static intlog_ref_setup(struct files_ref_store *refs,1446const char*refname,int force_create,1447int*logfd,struct strbuf *err)1448{1449struct strbuf logfile_sb = STRBUF_INIT;1450char*logfile;14511452files_reflog_path(refs, &logfile_sb, refname);1453 logfile =strbuf_detach(&logfile_sb, NULL);14541455if(force_create ||should_autocreate_reflog(refname)) {1456if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1457if(errno == ENOENT)1458strbuf_addf(err,"unable to create directory for '%s': "1459"%s", logfile,strerror(errno));1460else if(errno == EISDIR)1461strbuf_addf(err,"there are still logs under '%s'",1462 logfile);1463else1464strbuf_addf(err,"unable to append to '%s':%s",1465 logfile,strerror(errno));14661467goto error;1468}1469}else{1470*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1471if(*logfd <0) {1472if(errno == ENOENT || errno == EISDIR) {1473/*1474 * The logfile doesn't already exist,1475 * but that is not an error; it only1476 * means that we won't write log1477 * entries to it.1478 */1479;1480}else{1481strbuf_addf(err,"unable to append to '%s':%s",1482 logfile,strerror(errno));1483goto error;1484}1485}1486}14871488if(*logfd >=0)1489adjust_shared_perm(logfile);14901491free(logfile);1492return0;14931494error:1495free(logfile);1496return-1;1497}14981499static intfiles_create_reflog(struct ref_store *ref_store,1500const char*refname,int force_create,1501struct strbuf *err)1502{1503struct files_ref_store *refs =1504files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1505int fd;15061507if(log_ref_setup(refs, refname, force_create, &fd, err))1508return-1;15091510if(fd >=0)1511close(fd);15121513return0;1514}15151516static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1517const struct object_id *new_oid,1518const char*committer,const char*msg)1519{1520int msglen, written;1521unsigned maxlen, len;1522char*logrec;15231524 msglen = msg ?strlen(msg) :0;1525 maxlen =strlen(committer) + msglen +100;1526 logrec =xmalloc(maxlen);1527 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1528oid_to_hex(old_oid),1529oid_to_hex(new_oid),1530 committer);1531if(msglen)1532 len +=copy_reflog_msg(logrec + len -1, msg) -1;15331534 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1535free(logrec);1536if(written != len)1537return-1;15381539return0;1540}15411542static intfiles_log_ref_write(struct files_ref_store *refs,1543const char*refname,const struct object_id *old_oid,1544const struct object_id *new_oid,const char*msg,1545int flags,struct strbuf *err)1546{1547int logfd, result;15481549if(log_all_ref_updates == LOG_REFS_UNSET)1550 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15511552 result =log_ref_setup(refs, refname,1553 flags & REF_FORCE_CREATE_REFLOG,1554&logfd, err);15551556if(result)1557return result;15581559if(logfd <0)1560return0;1561 result =log_ref_write_fd(logfd, old_oid, new_oid,1562git_committer_info(0), msg);1563if(result) {1564struct strbuf sb = STRBUF_INIT;1565int save_errno = errno;15661567files_reflog_path(refs, &sb, refname);1568strbuf_addf(err,"unable to append to '%s':%s",1569 sb.buf,strerror(save_errno));1570strbuf_release(&sb);1571close(logfd);1572return-1;1573}1574if(close(logfd)) {1575struct strbuf sb = STRBUF_INIT;1576int save_errno = errno;15771578files_reflog_path(refs, &sb, refname);1579strbuf_addf(err,"unable to append to '%s':%s",1580 sb.buf,strerror(save_errno));1581strbuf_release(&sb);1582return-1;1583}1584return0;1585}15861587/*1588 * Write sha1 into the open lockfile, then close the lockfile. On1589 * errors, rollback the lockfile, fill in *err and1590 * return -1.1591 */1592static intwrite_ref_to_lockfile(struct ref_lock *lock,1593const struct object_id *oid,struct strbuf *err)1594{1595static char term ='\n';1596struct object *o;1597int fd;15981599 o =parse_object(oid);1600if(!o) {1601strbuf_addf(err,1602"trying to write ref '%s' with nonexistent object%s",1603 lock->ref_name,oid_to_hex(oid));1604unlock_ref(lock);1605return-1;1606}1607if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1608strbuf_addf(err,1609"trying to write non-commit object%sto branch '%s'",1610oid_to_hex(oid), lock->ref_name);1611unlock_ref(lock);1612return-1;1613}1614 fd =get_lock_file_fd(&lock->lk);1615if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1616write_in_full(fd, &term,1) !=1||1617close_ref_gently(lock) <0) {1618strbuf_addf(err,1619"couldn't write '%s'",get_lock_file_path(&lock->lk));1620unlock_ref(lock);1621return-1;1622}1623return0;1624}16251626/*1627 * Commit a change to a loose reference that has already been written1628 * to the loose reference lockfile. Also update the reflogs if1629 * necessary, using the specified lockmsg (which can be NULL).1630 */1631static intcommit_ref_update(struct files_ref_store *refs,1632struct ref_lock *lock,1633const struct object_id *oid,const char*logmsg,1634struct strbuf *err)1635{1636files_assert_main_repository(refs,"commit_ref_update");16371638clear_loose_ref_cache(refs);1639if(files_log_ref_write(refs, lock->ref_name,1640&lock->old_oid, oid,1641 logmsg,0, err)) {1642char*old_msg =strbuf_detach(err, NULL);1643strbuf_addf(err,"cannot update the ref '%s':%s",1644 lock->ref_name, old_msg);1645free(old_msg);1646unlock_ref(lock);1647return-1;1648}16491650if(strcmp(lock->ref_name,"HEAD") !=0) {1651/*1652 * Special hack: If a branch is updated directly and HEAD1653 * points to it (may happen on the remote side of a push1654 * for example) then logically the HEAD reflog should be1655 * updated too.1656 * A generic solution implies reverse symref information,1657 * but finding all symrefs pointing to the given branch1658 * would be rather costly for this rare event (the direct1659 * update of a branch) to be worth it. So let's cheat and1660 * check with HEAD only which should cover 99% of all usage1661 * scenarios (even 100% of the default ones).1662 */1663struct object_id head_oid;1664int head_flag;1665const char*head_ref;16661667 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1668 RESOLVE_REF_READING,1669 head_oid.hash, &head_flag);1670if(head_ref && (head_flag & REF_ISSYMREF) &&1671!strcmp(head_ref, lock->ref_name)) {1672struct strbuf log_err = STRBUF_INIT;1673if(files_log_ref_write(refs,"HEAD",1674&lock->old_oid, oid,1675 logmsg,0, &log_err)) {1676error("%s", log_err.buf);1677strbuf_release(&log_err);1678}1679}1680}16811682if(commit_ref(lock)) {1683strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1684unlock_ref(lock);1685return-1;1686}16871688unlock_ref(lock);1689return0;1690}16911692static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1693{1694int ret = -1;1695#ifndef NO_SYMLINK_HEAD1696char*ref_path =get_locked_file_path(&lock->lk);1697unlink(ref_path);1698 ret =symlink(target, ref_path);1699free(ref_path);17001701if(ret)1702fprintf(stderr,"no symlink - falling back to symbolic ref\n");1703#endif1704return ret;1705}17061707static voidupdate_symref_reflog(struct files_ref_store *refs,1708struct ref_lock *lock,const char*refname,1709const char*target,const char*logmsg)1710{1711struct strbuf err = STRBUF_INIT;1712struct object_id new_oid;1713if(logmsg &&1714!refs_read_ref_full(&refs->base, target,1715 RESOLVE_REF_READING, new_oid.hash, NULL) &&1716files_log_ref_write(refs, refname, &lock->old_oid,1717&new_oid, logmsg,0, &err)) {1718error("%s", err.buf);1719strbuf_release(&err);1720}1721}17221723static intcreate_symref_locked(struct files_ref_store *refs,1724struct ref_lock *lock,const char*refname,1725const char*target,const char*logmsg)1726{1727if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1728update_symref_reflog(refs, lock, refname, target, logmsg);1729return0;1730}17311732if(!fdopen_lock_file(&lock->lk,"w"))1733returnerror("unable to fdopen%s:%s",1734 lock->lk.tempfile->filename.buf,strerror(errno));17351736update_symref_reflog(refs, lock, refname, target, logmsg);17371738/* no error check; commit_ref will check ferror */1739fprintf(lock->lk.tempfile->fp,"ref:%s\n", target);1740if(commit_ref(lock) <0)1741returnerror("unable to write symref for%s:%s", refname,1742strerror(errno));1743return0;1744}17451746static intfiles_create_symref(struct ref_store *ref_store,1747const char*refname,const char*target,1748const char*logmsg)1749{1750struct files_ref_store *refs =1751files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1752struct strbuf err = STRBUF_INIT;1753struct ref_lock *lock;1754int ret;17551756 lock =lock_ref_sha1_basic(refs, refname, NULL,1757 NULL, NULL, REF_NODEREF, NULL,1758&err);1759if(!lock) {1760error("%s", err.buf);1761strbuf_release(&err);1762return-1;1763}17641765 ret =create_symref_locked(refs, lock, refname, target, logmsg);1766unlock_ref(lock);1767return ret;1768}17691770static intfiles_reflog_exists(struct ref_store *ref_store,1771const char*refname)1772{1773struct files_ref_store *refs =1774files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1775struct strbuf sb = STRBUF_INIT;1776struct stat st;1777int ret;17781779files_reflog_path(refs, &sb, refname);1780 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1781strbuf_release(&sb);1782return ret;1783}17841785static intfiles_delete_reflog(struct ref_store *ref_store,1786const char*refname)1787{1788struct files_ref_store *refs =1789files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1790struct strbuf sb = STRBUF_INIT;1791int ret;17921793files_reflog_path(refs, &sb, refname);1794 ret =remove_path(sb.buf);1795strbuf_release(&sb);1796return ret;1797}17981799static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1800{1801struct object_id ooid, noid;1802char*email_end, *message;1803 timestamp_t timestamp;1804int tz;1805const char*p = sb->buf;18061807/* old SP new SP name <email> SP time TAB msg LF */1808if(!sb->len || sb->buf[sb->len -1] !='\n'||1809parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1810parse_oid_hex(p, &noid, &p) || *p++ !=' '||1811!(email_end =strchr(p,'>')) ||1812 email_end[1] !=' '||1813!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1814!message || message[0] !=' '||1815(message[1] !='+'&& message[1] !='-') ||1816!isdigit(message[2]) || !isdigit(message[3]) ||1817!isdigit(message[4]) || !isdigit(message[5]))1818return0;/* corrupt? */1819 email_end[1] ='\0';1820 tz =strtol(message +1, NULL,10);1821if(message[6] !='\t')1822 message +=6;1823else1824 message +=7;1825returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1826}18271828static char*find_beginning_of_line(char*bob,char*scan)1829{1830while(bob < scan && *(--scan) !='\n')1831;/* keep scanning backwards */1832/*1833 * Return either beginning of the buffer, or LF at the end of1834 * the previous line.1835 */1836return scan;1837}18381839static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1840const char*refname,1841 each_reflog_ent_fn fn,1842void*cb_data)1843{1844struct files_ref_store *refs =1845files_downcast(ref_store, REF_STORE_READ,1846"for_each_reflog_ent_reverse");1847struct strbuf sb = STRBUF_INIT;1848FILE*logfp;1849long pos;1850int ret =0, at_tail =1;18511852files_reflog_path(refs, &sb, refname);1853 logfp =fopen(sb.buf,"r");1854strbuf_release(&sb);1855if(!logfp)1856return-1;18571858/* Jump to the end */1859if(fseek(logfp,0, SEEK_END) <0)1860 ret =error("cannot seek back reflog for%s:%s",1861 refname,strerror(errno));1862 pos =ftell(logfp);1863while(!ret &&0< pos) {1864int cnt;1865size_t nread;1866char buf[BUFSIZ];1867char*endp, *scanp;18681869/* Fill next block from the end */1870 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1871if(fseek(logfp, pos - cnt, SEEK_SET)) {1872 ret =error("cannot seek back reflog for%s:%s",1873 refname,strerror(errno));1874break;1875}1876 nread =fread(buf, cnt,1, logfp);1877if(nread !=1) {1878 ret =error("cannot read%dbytes from reflog for%s:%s",1879 cnt, refname,strerror(errno));1880break;1881}1882 pos -= cnt;18831884 scanp = endp = buf + cnt;1885if(at_tail && scanp[-1] =='\n')1886/* Looking at the final LF at the end of the file */1887 scanp--;1888 at_tail =0;18891890while(buf < scanp) {1891/*1892 * terminating LF of the previous line, or the beginning1893 * of the buffer.1894 */1895char*bp;18961897 bp =find_beginning_of_line(buf, scanp);18981899if(*bp =='\n') {1900/*1901 * The newline is the end of the previous line,1902 * so we know we have complete line starting1903 * at (bp + 1). Prefix it onto any prior data1904 * we collected for the line and process it.1905 */1906strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1907 scanp = bp;1908 endp = bp +1;1909 ret =show_one_reflog_ent(&sb, fn, cb_data);1910strbuf_reset(&sb);1911if(ret)1912break;1913}else if(!pos) {1914/*1915 * We are at the start of the buffer, and the1916 * start of the file; there is no previous1917 * line, and we have everything for this one.1918 * Process it, and we can end the loop.1919 */1920strbuf_splice(&sb,0,0, buf, endp - buf);1921 ret =show_one_reflog_ent(&sb, fn, cb_data);1922strbuf_reset(&sb);1923break;1924}19251926if(bp == buf) {1927/*1928 * We are at the start of the buffer, and there1929 * is more file to read backwards. Which means1930 * we are in the middle of a line. Note that we1931 * may get here even if *bp was a newline; that1932 * just means we are at the exact end of the1933 * previous line, rather than some spot in the1934 * middle.1935 *1936 * Save away what we have to be combined with1937 * the data from the next read.1938 */1939strbuf_splice(&sb,0,0, buf, endp - buf);1940break;1941}1942}19431944}1945if(!ret && sb.len)1946die("BUG: reverse reflog parser had leftover data");19471948fclose(logfp);1949strbuf_release(&sb);1950return ret;1951}19521953static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1954const char*refname,1955 each_reflog_ent_fn fn,void*cb_data)1956{1957struct files_ref_store *refs =1958files_downcast(ref_store, REF_STORE_READ,1959"for_each_reflog_ent");1960FILE*logfp;1961struct strbuf sb = STRBUF_INIT;1962int ret =0;19631964files_reflog_path(refs, &sb, refname);1965 logfp =fopen(sb.buf,"r");1966strbuf_release(&sb);1967if(!logfp)1968return-1;19691970while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1971 ret =show_one_reflog_ent(&sb, fn, cb_data);1972fclose(logfp);1973strbuf_release(&sb);1974return ret;1975}19761977struct files_reflog_iterator {1978struct ref_iterator base;19791980struct ref_store *ref_store;1981struct dir_iterator *dir_iterator;1982struct object_id oid;1983};19841985static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)1986{1987struct files_reflog_iterator *iter =1988(struct files_reflog_iterator *)ref_iterator;1989struct dir_iterator *diter = iter->dir_iterator;1990int ok;19911992while((ok =dir_iterator_advance(diter)) == ITER_OK) {1993int flags;19941995if(!S_ISREG(diter->st.st_mode))1996continue;1997if(diter->basename[0] =='.')1998continue;1999if(ends_with(diter->basename,".lock"))2000continue;20012002if(refs_read_ref_full(iter->ref_store,2003 diter->relative_path,0,2004 iter->oid.hash, &flags)) {2005error("bad ref for%s", diter->path.buf);2006continue;2007}20082009 iter->base.refname = diter->relative_path;2010 iter->base.oid = &iter->oid;2011 iter->base.flags = flags;2012return ITER_OK;2013}20142015 iter->dir_iterator = NULL;2016if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2017 ok = ITER_ERROR;2018return ok;2019}20202021static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2022struct object_id *peeled)2023{2024die("BUG: ref_iterator_peel() called for reflog_iterator");2025}20262027static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2028{2029struct files_reflog_iterator *iter =2030(struct files_reflog_iterator *)ref_iterator;2031int ok = ITER_DONE;20322033if(iter->dir_iterator)2034 ok =dir_iterator_abort(iter->dir_iterator);20352036base_ref_iterator_free(ref_iterator);2037return ok;2038}20392040static struct ref_iterator_vtable files_reflog_iterator_vtable = {2041 files_reflog_iterator_advance,2042 files_reflog_iterator_peel,2043 files_reflog_iterator_abort2044};20452046static struct ref_iterator *reflog_iterator_begin(struct ref_store *ref_store,2047const char*gitdir)2048{2049struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2050struct ref_iterator *ref_iterator = &iter->base;2051struct strbuf sb = STRBUF_INIT;20522053base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2054strbuf_addf(&sb,"%s/logs", gitdir);2055 iter->dir_iterator =dir_iterator_begin(sb.buf);2056 iter->ref_store = ref_store;2057strbuf_release(&sb);20582059return ref_iterator;2060}20612062static enum iterator_selection reflog_iterator_select(2063struct ref_iterator *iter_worktree,2064struct ref_iterator *iter_common,2065void*cb_data)2066{2067if(iter_worktree) {2068/*2069 * We're a bit loose here. We probably should ignore2070 * common refs if they are accidentally added as2071 * per-worktree refs.2072 */2073return ITER_SELECT_0;2074}else if(iter_common) {2075if(ref_type(iter_common->refname) == REF_TYPE_NORMAL)2076return ITER_SELECT_1;20772078/*2079 * The main ref store may contain main worktree's2080 * per-worktree refs, which should be ignored2081 */2082return ITER_SKIP_1;2083}else2084return ITER_DONE;2085}20862087static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2088{2089struct files_ref_store *refs =2090files_downcast(ref_store, REF_STORE_READ,2091"reflog_iterator_begin");20922093if(!strcmp(refs->gitdir, refs->gitcommondir)) {2094returnreflog_iterator_begin(ref_store, refs->gitcommondir);2095}else{2096returnmerge_ref_iterator_begin(2097reflog_iterator_begin(ref_store, refs->gitdir),2098reflog_iterator_begin(ref_store, refs->gitcommondir),2099 reflog_iterator_select, refs);2100}2101}21022103/*2104 * If update is a direct update of head_ref (the reference pointed to2105 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2106 */2107static intsplit_head_update(struct ref_update *update,2108struct ref_transaction *transaction,2109const char*head_ref,2110struct string_list *affected_refnames,2111struct strbuf *err)2112{2113struct string_list_item *item;2114struct ref_update *new_update;21152116if((update->flags & REF_LOG_ONLY) ||2117(update->flags & REF_ISPRUNING) ||2118(update->flags & REF_UPDATE_VIA_HEAD))2119return0;21202121if(strcmp(update->refname, head_ref))2122return0;21232124/*2125 * First make sure that HEAD is not already in the2126 * transaction. This check is O(lg N) in the transaction2127 * size, but it happens at most once per transaction.2128 */2129if(string_list_has_string(affected_refnames,"HEAD")) {2130/* An entry already existed */2131strbuf_addf(err,2132"multiple updates for 'HEAD' (including one "2133"via its referent '%s') are not allowed",2134 update->refname);2135return TRANSACTION_NAME_CONFLICT;2136}21372138 new_update =ref_transaction_add_update(2139 transaction,"HEAD",2140 update->flags | REF_LOG_ONLY | REF_NODEREF,2141 update->new_oid.hash, update->old_oid.hash,2142 update->msg);21432144/*2145 * Add "HEAD". This insertion is O(N) in the transaction2146 * size, but it happens at most once per transaction.2147 * Add new_update->refname instead of a literal "HEAD".2148 */2149if(strcmp(new_update->refname,"HEAD"))2150BUG("%sunexpectedly not 'HEAD'", new_update->refname);2151 item =string_list_insert(affected_refnames, new_update->refname);2152 item->util = new_update;21532154return0;2155}21562157/*2158 * update is for a symref that points at referent and doesn't have2159 * REF_NODEREF set. Split it into two updates:2160 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2161 * - A new, separate update for the referent reference2162 * Note that the new update will itself be subject to splitting when2163 * the iteration gets to it.2164 */2165static intsplit_symref_update(struct files_ref_store *refs,2166struct ref_update *update,2167const char*referent,2168struct ref_transaction *transaction,2169struct string_list *affected_refnames,2170struct strbuf *err)2171{2172struct string_list_item *item;2173struct ref_update *new_update;2174unsigned int new_flags;21752176/*2177 * First make sure that referent is not already in the2178 * transaction. This check is O(lg N) in the transaction2179 * size, but it happens at most once per symref in a2180 * transaction.2181 */2182if(string_list_has_string(affected_refnames, referent)) {2183/* An entry already exists */2184strbuf_addf(err,2185"multiple updates for '%s' (including one "2186"via symref '%s') are not allowed",2187 referent, update->refname);2188return TRANSACTION_NAME_CONFLICT;2189}21902191 new_flags = update->flags;2192if(!strcmp(update->refname,"HEAD")) {2193/*2194 * Record that the new update came via HEAD, so that2195 * when we process it, split_head_update() doesn't try2196 * to add another reflog update for HEAD. Note that2197 * this bit will be propagated if the new_update2198 * itself needs to be split.2199 */2200 new_flags |= REF_UPDATE_VIA_HEAD;2201}22022203 new_update =ref_transaction_add_update(2204 transaction, referent, new_flags,2205 update->new_oid.hash, update->old_oid.hash,2206 update->msg);22072208 new_update->parent_update = update;22092210/*2211 * Change the symbolic ref update to log only. Also, it2212 * doesn't need to check its old SHA-1 value, as that will be2213 * done when new_update is processed.2214 */2215 update->flags |= REF_LOG_ONLY | REF_NODEREF;2216 update->flags &= ~REF_HAVE_OLD;22172218/*2219 * Add the referent. This insertion is O(N) in the transaction2220 * size, but it happens at most once per symref in a2221 * transaction. Make sure to add new_update->refname, which will2222 * be valid as long as affected_refnames is in use, and NOT2223 * referent, which might soon be freed by our caller.2224 */2225 item =string_list_insert(affected_refnames, new_update->refname);2226if(item->util)2227BUG("%sunexpectedly found in affected_refnames",2228 new_update->refname);2229 item->util = new_update;22302231return0;2232}22332234/*2235 * Return the refname under which update was originally requested.2236 */2237static const char*original_update_refname(struct ref_update *update)2238{2239while(update->parent_update)2240 update = update->parent_update;22412242return update->refname;2243}22442245/*2246 * Check whether the REF_HAVE_OLD and old_oid values stored in update2247 * are consistent with oid, which is the reference's current value. If2248 * everything is OK, return 0; otherwise, write an error message to2249 * err and return -1.2250 */2251static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2252struct strbuf *err)2253{2254if(!(update->flags & REF_HAVE_OLD) ||2255!oidcmp(oid, &update->old_oid))2256return0;22572258if(is_null_oid(&update->old_oid))2259strbuf_addf(err,"cannot lock ref '%s': "2260"reference already exists",2261original_update_refname(update));2262else if(is_null_oid(oid))2263strbuf_addf(err,"cannot lock ref '%s': "2264"reference is missing but expected%s",2265original_update_refname(update),2266oid_to_hex(&update->old_oid));2267else2268strbuf_addf(err,"cannot lock ref '%s': "2269"is at%sbut expected%s",2270original_update_refname(update),2271oid_to_hex(oid),2272oid_to_hex(&update->old_oid));22732274return-1;2275}22762277/*2278 * Prepare for carrying out update:2279 * - Lock the reference referred to by update.2280 * - Read the reference under lock.2281 * - Check that its old SHA-1 value (if specified) is correct, and in2282 * any case record it in update->lock->old_oid for later use when2283 * writing the reflog.2284 * - If it is a symref update without REF_NODEREF, split it up into a2285 * REF_LOG_ONLY update of the symref and add a separate update for2286 * the referent to transaction.2287 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2288 * update of HEAD.2289 */2290static intlock_ref_for_update(struct files_ref_store *refs,2291struct ref_update *update,2292struct ref_transaction *transaction,2293const char*head_ref,2294struct string_list *affected_refnames,2295struct strbuf *err)2296{2297struct strbuf referent = STRBUF_INIT;2298int mustexist = (update->flags & REF_HAVE_OLD) &&2299!is_null_oid(&update->old_oid);2300int ret =0;2301struct ref_lock *lock;23022303files_assert_main_repository(refs,"lock_ref_for_update");23042305if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2306 update->flags |= REF_DELETING;23072308if(head_ref) {2309 ret =split_head_update(update, transaction, head_ref,2310 affected_refnames, err);2311if(ret)2312goto out;2313}23142315 ret =lock_raw_ref(refs, update->refname, mustexist,2316 affected_refnames, NULL,2317&lock, &referent,2318&update->type, err);2319if(ret) {2320char*reason;23212322 reason =strbuf_detach(err, NULL);2323strbuf_addf(err,"cannot lock ref '%s':%s",2324original_update_refname(update), reason);2325free(reason);2326goto out;2327}23282329 update->backend_data = lock;23302331if(update->type & REF_ISSYMREF) {2332if(update->flags & REF_NODEREF) {2333/*2334 * We won't be reading the referent as part of2335 * the transaction, so we have to read it here2336 * to record and possibly check old_sha1:2337 */2338if(refs_read_ref_full(&refs->base,2339 referent.buf,0,2340 lock->old_oid.hash, NULL)) {2341if(update->flags & REF_HAVE_OLD) {2342strbuf_addf(err,"cannot lock ref '%s': "2343"error reading reference",2344original_update_refname(update));2345 ret = TRANSACTION_GENERIC_ERROR;2346goto out;2347}2348}else if(check_old_oid(update, &lock->old_oid, err)) {2349 ret = TRANSACTION_GENERIC_ERROR;2350goto out;2351}2352}else{2353/*2354 * Create a new update for the reference this2355 * symref is pointing at. Also, we will record2356 * and verify old_sha1 for this update as part2357 * of processing the split-off update, so we2358 * don't have to do it here.2359 */2360 ret =split_symref_update(refs, update,2361 referent.buf, transaction,2362 affected_refnames, err);2363if(ret)2364goto out;2365}2366}else{2367struct ref_update *parent_update;23682369if(check_old_oid(update, &lock->old_oid, err)) {2370 ret = TRANSACTION_GENERIC_ERROR;2371goto out;2372}23732374/*2375 * If this update is happening indirectly because of a2376 * symref update, record the old SHA-1 in the parent2377 * update:2378 */2379for(parent_update = update->parent_update;2380 parent_update;2381 parent_update = parent_update->parent_update) {2382struct ref_lock *parent_lock = parent_update->backend_data;2383oidcpy(&parent_lock->old_oid, &lock->old_oid);2384}2385}23862387if((update->flags & REF_HAVE_NEW) &&2388!(update->flags & REF_DELETING) &&2389!(update->flags & REF_LOG_ONLY)) {2390if(!(update->type & REF_ISSYMREF) &&2391!oidcmp(&lock->old_oid, &update->new_oid)) {2392/*2393 * The reference already has the desired2394 * value, so we don't need to write it.2395 */2396}else if(write_ref_to_lockfile(lock, &update->new_oid,2397 err)) {2398char*write_err =strbuf_detach(err, NULL);23992400/*2401 * The lock was freed upon failure of2402 * write_ref_to_lockfile():2403 */2404 update->backend_data = NULL;2405strbuf_addf(err,2406"cannot update ref '%s':%s",2407 update->refname, write_err);2408free(write_err);2409 ret = TRANSACTION_GENERIC_ERROR;2410goto out;2411}else{2412 update->flags |= REF_NEEDS_COMMIT;2413}2414}2415if(!(update->flags & REF_NEEDS_COMMIT)) {2416/*2417 * We didn't call write_ref_to_lockfile(), so2418 * the lockfile is still open. Close it to2419 * free up the file descriptor:2420 */2421if(close_ref_gently(lock)) {2422strbuf_addf(err,"couldn't close '%s.lock'",2423 update->refname);2424 ret = TRANSACTION_GENERIC_ERROR;2425goto out;2426}2427}24282429out:2430strbuf_release(&referent);2431return ret;2432}24332434/*2435 * Unlock any references in `transaction` that are still locked, and2436 * mark the transaction closed.2437 */2438static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2439{2440size_t i;24412442for(i =0; i < transaction->nr; i++) {2443struct ref_update *update = transaction->updates[i];2444struct ref_lock *lock = update->backend_data;24452446if(lock) {2447unlock_ref(lock);2448 update->backend_data = NULL;2449}2450}24512452 transaction->state = REF_TRANSACTION_CLOSED;2453}24542455static intfiles_transaction_prepare(struct ref_store *ref_store,2456struct ref_transaction *transaction,2457struct strbuf *err)2458{2459struct files_ref_store *refs =2460files_downcast(ref_store, REF_STORE_WRITE,2461"ref_transaction_prepare");2462size_t i;2463int ret =0;2464struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2465char*head_ref = NULL;2466int head_type;2467struct object_id head_oid;24682469assert(err);24702471if(!transaction->nr)2472goto cleanup;24732474/*2475 * Fail if a refname appears more than once in the2476 * transaction. (If we end up splitting up any updates using2477 * split_symref_update() or split_head_update(), those2478 * functions will check that the new updates don't have the2479 * same refname as any existing ones.)2480 */2481for(i =0; i < transaction->nr; i++) {2482struct ref_update *update = transaction->updates[i];2483struct string_list_item *item =2484string_list_append(&affected_refnames, update->refname);24852486/*2487 * We store a pointer to update in item->util, but at2488 * the moment we never use the value of this field2489 * except to check whether it is non-NULL.2490 */2491 item->util = update;2492}2493string_list_sort(&affected_refnames);2494if(ref_update_reject_duplicates(&affected_refnames, err)) {2495 ret = TRANSACTION_GENERIC_ERROR;2496goto cleanup;2497}24982499/*2500 * Special hack: If a branch is updated directly and HEAD2501 * points to it (may happen on the remote side of a push2502 * for example) then logically the HEAD reflog should be2503 * updated too.2504 *2505 * A generic solution would require reverse symref lookups,2506 * but finding all symrefs pointing to a given branch would be2507 * rather costly for this rare event (the direct update of a2508 * branch) to be worth it. So let's cheat and check with HEAD2509 * only, which should cover 99% of all usage scenarios (even2510 * 100% of the default ones).2511 *2512 * So if HEAD is a symbolic reference, then record the name of2513 * the reference that it points to. If we see an update of2514 * head_ref within the transaction, then split_head_update()2515 * arranges for the reflog of HEAD to be updated, too.2516 */2517 head_ref =refs_resolve_refdup(ref_store,"HEAD",2518 RESOLVE_REF_NO_RECURSE,2519 head_oid.hash, &head_type);25202521if(head_ref && !(head_type & REF_ISSYMREF)) {2522FREE_AND_NULL(head_ref);2523}25242525/*2526 * Acquire all locks, verify old values if provided, check2527 * that new values are valid, and write new values to the2528 * lockfiles, ready to be activated. Only keep one lockfile2529 * open at a time to avoid running out of file descriptors.2530 * Note that lock_ref_for_update() might append more updates2531 * to the transaction.2532 */2533for(i =0; i < transaction->nr; i++) {2534struct ref_update *update = transaction->updates[i];25352536 ret =lock_ref_for_update(refs, update, transaction,2537 head_ref, &affected_refnames, err);2538if(ret)2539break;2540}25412542cleanup:2543free(head_ref);2544string_list_clear(&affected_refnames,0);25452546if(ret)2547files_transaction_cleanup(transaction);2548else2549 transaction->state = REF_TRANSACTION_PREPARED;25502551return ret;2552}25532554static intfiles_transaction_finish(struct ref_store *ref_store,2555struct ref_transaction *transaction,2556struct strbuf *err)2557{2558struct files_ref_store *refs =2559files_downcast(ref_store,0,"ref_transaction_finish");2560size_t i;2561int ret =0;2562struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2563struct string_list_item *ref_to_delete;2564struct strbuf sb = STRBUF_INIT;25652566assert(err);25672568if(!transaction->nr) {2569 transaction->state = REF_TRANSACTION_CLOSED;2570return0;2571}25722573/* Perform updates first so live commits remain referenced */2574for(i =0; i < transaction->nr; i++) {2575struct ref_update *update = transaction->updates[i];2576struct ref_lock *lock = update->backend_data;25772578if(update->flags & REF_NEEDS_COMMIT ||2579 update->flags & REF_LOG_ONLY) {2580if(files_log_ref_write(refs,2581 lock->ref_name,2582&lock->old_oid,2583&update->new_oid,2584 update->msg, update->flags,2585 err)) {2586char*old_msg =strbuf_detach(err, NULL);25872588strbuf_addf(err,"cannot update the ref '%s':%s",2589 lock->ref_name, old_msg);2590free(old_msg);2591unlock_ref(lock);2592 update->backend_data = NULL;2593 ret = TRANSACTION_GENERIC_ERROR;2594goto cleanup;2595}2596}2597if(update->flags & REF_NEEDS_COMMIT) {2598clear_loose_ref_cache(refs);2599if(commit_ref(lock)) {2600strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2601unlock_ref(lock);2602 update->backend_data = NULL;2603 ret = TRANSACTION_GENERIC_ERROR;2604goto cleanup;2605}2606}2607}2608/* Perform deletes now that updates are safely completed */2609for(i =0; i < transaction->nr; i++) {2610struct ref_update *update = transaction->updates[i];2611struct ref_lock *lock = update->backend_data;26122613if(update->flags & REF_DELETING &&2614!(update->flags & REF_LOG_ONLY)) {2615if(!(update->type & REF_ISPACKED) ||2616 update->type & REF_ISSYMREF) {2617/* It is a loose reference. */2618strbuf_reset(&sb);2619files_ref_path(refs, &sb, lock->ref_name);2620if(unlink_or_msg(sb.buf, err)) {2621 ret = TRANSACTION_GENERIC_ERROR;2622goto cleanup;2623}2624 update->flags |= REF_DELETED_LOOSE;2625}26262627if(!(update->flags & REF_ISPRUNING))2628string_list_append(&refs_to_delete,2629 lock->ref_name);2630}2631}26322633if(packed_refs_lock(refs->packed_ref_store,0, err)) {2634 ret = TRANSACTION_GENERIC_ERROR;2635goto cleanup;2636}26372638if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {2639 ret = TRANSACTION_GENERIC_ERROR;2640packed_refs_unlock(refs->packed_ref_store);2641goto cleanup;2642}26432644packed_refs_unlock(refs->packed_ref_store);26452646/* Delete the reflogs of any references that were deleted: */2647for_each_string_list_item(ref_to_delete, &refs_to_delete) {2648strbuf_reset(&sb);2649files_reflog_path(refs, &sb, ref_to_delete->string);2650if(!unlink_or_warn(sb.buf))2651try_remove_empty_parents(refs, ref_to_delete->string,2652 REMOVE_EMPTY_PARENTS_REFLOG);2653}26542655clear_loose_ref_cache(refs);26562657cleanup:2658files_transaction_cleanup(transaction);26592660for(i =0; i < transaction->nr; i++) {2661struct ref_update *update = transaction->updates[i];26622663if(update->flags & REF_DELETED_LOOSE) {2664/*2665 * The loose reference was deleted. Delete any2666 * empty parent directories. (Note that this2667 * can only work because we have already2668 * removed the lockfile.)2669 */2670try_remove_empty_parents(refs, update->refname,2671 REMOVE_EMPTY_PARENTS_REF);2672}2673}26742675strbuf_release(&sb);2676string_list_clear(&refs_to_delete,0);2677return ret;2678}26792680static intfiles_transaction_abort(struct ref_store *ref_store,2681struct ref_transaction *transaction,2682struct strbuf *err)2683{2684files_transaction_cleanup(transaction);2685return0;2686}26872688static intref_present(const char*refname,2689const struct object_id *oid,int flags,void*cb_data)2690{2691struct string_list *affected_refnames = cb_data;26922693returnstring_list_has_string(affected_refnames, refname);2694}26952696static intfiles_initial_transaction_commit(struct ref_store *ref_store,2697struct ref_transaction *transaction,2698struct strbuf *err)2699{2700struct files_ref_store *refs =2701files_downcast(ref_store, REF_STORE_WRITE,2702"initial_ref_transaction_commit");2703size_t i;2704int ret =0;2705struct string_list affected_refnames = STRING_LIST_INIT_NODUP;27062707assert(err);27082709if(transaction->state != REF_TRANSACTION_OPEN)2710die("BUG: commit called for transaction that is not open");27112712/* Fail if a refname appears more than once in the transaction: */2713for(i =0; i < transaction->nr; i++)2714string_list_append(&affected_refnames,2715 transaction->updates[i]->refname);2716string_list_sort(&affected_refnames);2717if(ref_update_reject_duplicates(&affected_refnames, err)) {2718 ret = TRANSACTION_GENERIC_ERROR;2719goto cleanup;2720}27212722/*2723 * It's really undefined to call this function in an active2724 * repository or when there are existing references: we are2725 * only locking and changing packed-refs, so (1) any2726 * simultaneous processes might try to change a reference at2727 * the same time we do, and (2) any existing loose versions of2728 * the references that we are setting would have precedence2729 * over our values. But some remote helpers create the remote2730 * "HEAD" and "master" branches before calling this function,2731 * so here we really only check that none of the references2732 * that we are creating already exists.2733 */2734if(refs_for_each_rawref(&refs->base, ref_present,2735&affected_refnames))2736die("BUG: initial ref transaction called with existing refs");27372738for(i =0; i < transaction->nr; i++) {2739struct ref_update *update = transaction->updates[i];27402741if((update->flags & REF_HAVE_OLD) &&2742!is_null_oid(&update->old_oid))2743die("BUG: initial ref transaction with old_sha1 set");2744if(refs_verify_refname_available(&refs->base, update->refname,2745&affected_refnames, NULL,2746 err)) {2747 ret = TRANSACTION_NAME_CONFLICT;2748goto cleanup;2749}2750}27512752if(packed_refs_lock(refs->packed_ref_store,0, err)) {2753 ret = TRANSACTION_GENERIC_ERROR;2754goto cleanup;2755}27562757for(i =0; i < transaction->nr; i++) {2758struct ref_update *update = transaction->updates[i];27592760if((update->flags & REF_HAVE_NEW) &&2761!is_null_oid(&update->new_oid))2762add_packed_ref(refs->packed_ref_store, update->refname,2763&update->new_oid);2764}27652766if(commit_packed_refs(refs->packed_ref_store, err)) {2767 ret = TRANSACTION_GENERIC_ERROR;2768goto cleanup;2769}27702771cleanup:2772packed_refs_unlock(refs->packed_ref_store);2773 transaction->state = REF_TRANSACTION_CLOSED;2774string_list_clear(&affected_refnames,0);2775return ret;2776}27772778struct expire_reflog_cb {2779unsigned int flags;2780 reflog_expiry_should_prune_fn *should_prune_fn;2781void*policy_cb;2782FILE*newlog;2783struct object_id last_kept_oid;2784};27852786static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2787const char*email, timestamp_t timestamp,int tz,2788const char*message,void*cb_data)2789{2790struct expire_reflog_cb *cb = cb_data;2791struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;27922793if(cb->flags & EXPIRE_REFLOGS_REWRITE)2794 ooid = &cb->last_kept_oid;27952796if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2797 message, policy_cb)) {2798if(!cb->newlog)2799printf("would prune%s", message);2800else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2801printf("prune%s", message);2802}else{2803if(cb->newlog) {2804fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2805oid_to_hex(ooid),oid_to_hex(noid),2806 email, timestamp, tz, message);2807oidcpy(&cb->last_kept_oid, noid);2808}2809if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2810printf("keep%s", message);2811}2812return0;2813}28142815static intfiles_reflog_expire(struct ref_store *ref_store,2816const char*refname,const unsigned char*sha1,2817unsigned int flags,2818 reflog_expiry_prepare_fn prepare_fn,2819 reflog_expiry_should_prune_fn should_prune_fn,2820 reflog_expiry_cleanup_fn cleanup_fn,2821void*policy_cb_data)2822{2823struct files_ref_store *refs =2824files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2825static struct lock_file reflog_lock;2826struct expire_reflog_cb cb;2827struct ref_lock *lock;2828struct strbuf log_file_sb = STRBUF_INIT;2829char*log_file;2830int status =0;2831int type;2832struct strbuf err = STRBUF_INIT;2833struct object_id oid;28342835memset(&cb,0,sizeof(cb));2836 cb.flags = flags;2837 cb.policy_cb = policy_cb_data;2838 cb.should_prune_fn = should_prune_fn;28392840/*2841 * The reflog file is locked by holding the lock on the2842 * reference itself, plus we might need to update the2843 * reference if --updateref was specified:2844 */2845 lock =lock_ref_sha1_basic(refs, refname, sha1,2846 NULL, NULL, REF_NODEREF,2847&type, &err);2848if(!lock) {2849error("cannot lock ref '%s':%s", refname, err.buf);2850strbuf_release(&err);2851return-1;2852}2853if(!refs_reflog_exists(ref_store, refname)) {2854unlock_ref(lock);2855return0;2856}28572858files_reflog_path(refs, &log_file_sb, refname);2859 log_file =strbuf_detach(&log_file_sb, NULL);2860if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2861/*2862 * Even though holding $GIT_DIR/logs/$reflog.lock has2863 * no locking implications, we use the lock_file2864 * machinery here anyway because it does a lot of the2865 * work we need, including cleaning up if the program2866 * exits unexpectedly.2867 */2868if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2869struct strbuf err = STRBUF_INIT;2870unable_to_lock_message(log_file, errno, &err);2871error("%s", err.buf);2872strbuf_release(&err);2873goto failure;2874}2875 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2876if(!cb.newlog) {2877error("cannot fdopen%s(%s)",2878get_lock_file_path(&reflog_lock),strerror(errno));2879goto failure;2880}2881}28822883hashcpy(oid.hash, sha1);28842885(*prepare_fn)(refname, &oid, cb.policy_cb);2886refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2887(*cleanup_fn)(cb.policy_cb);28882889if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2890/*2891 * It doesn't make sense to adjust a reference pointed2892 * to by a symbolic ref based on expiring entries in2893 * the symbolic reference's reflog. Nor can we update2894 * a reference if there are no remaining reflog2895 * entries.2896 */2897int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2898!(type & REF_ISSYMREF) &&2899!is_null_oid(&cb.last_kept_oid);29002901if(close_lock_file_gently(&reflog_lock)) {2902 status |=error("couldn't write%s:%s", log_file,2903strerror(errno));2904rollback_lock_file(&reflog_lock);2905}else if(update &&2906(write_in_full(get_lock_file_fd(&lock->lk),2907oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2908write_str_in_full(get_lock_file_fd(&lock->lk),"\n") !=1||2909close_ref_gently(lock) <0)) {2910 status |=error("couldn't write%s",2911get_lock_file_path(&lock->lk));2912rollback_lock_file(&reflog_lock);2913}else if(commit_lock_file(&reflog_lock)) {2914 status |=error("unable to write reflog '%s' (%s)",2915 log_file,strerror(errno));2916}else if(update &&commit_ref(lock)) {2917 status |=error("couldn't set%s", lock->ref_name);2918}2919}2920free(log_file);2921unlock_ref(lock);2922return status;29232924 failure:2925rollback_lock_file(&reflog_lock);2926free(log_file);2927unlock_ref(lock);2928return-1;2929}29302931static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2932{2933struct files_ref_store *refs =2934files_downcast(ref_store, REF_STORE_WRITE,"init_db");2935struct strbuf sb = STRBUF_INIT;29362937/*2938 * Create .git/refs/{heads,tags}2939 */2940files_ref_path(refs, &sb,"refs/heads");2941safe_create_dir(sb.buf,1);29422943strbuf_reset(&sb);2944files_ref_path(refs, &sb,"refs/tags");2945safe_create_dir(sb.buf,1);29462947strbuf_release(&sb);2948return0;2949}29502951struct ref_storage_be refs_be_files = {2952 NULL,2953"files",2954 files_ref_store_create,2955 files_init_db,2956 files_transaction_prepare,2957 files_transaction_finish,2958 files_transaction_abort,2959 files_initial_transaction_commit,29602961 files_pack_refs,2962 files_peel_ref,2963 files_create_symref,2964 files_delete_refs,2965 files_rename_ref,29662967 files_ref_iterator_begin,2968 files_read_raw_ref,29692970 files_reflog_iterator_begin,2971 files_for_each_reflog_ent,2972 files_for_each_reflog_ent_reverse,2973 files_reflog_exists,2974 files_create_reflog,2975 files_delete_reflog,2976 files_reflog_expire2977};