1#include"../cache.h" 2#include"../config.h" 3#include"../refs.h" 4#include"refs-internal.h" 5#include"ref-cache.h" 6#include"packed-backend.h" 7#include"../iterator.h" 8#include"../dir-iterator.h" 9#include"../lockfile.h" 10#include"../object.h" 11#include"../dir.h" 12 13struct ref_lock { 14char*ref_name; 15struct lock_file *lk; 16struct object_id old_oid; 17}; 18 19/* 20 * Future: need to be in "struct repository" 21 * when doing a full libification. 22 */ 23struct files_ref_store { 24struct ref_store base; 25unsigned int store_flags; 26 27char*gitdir; 28char*gitcommondir; 29 30struct ref_cache *loose; 31 32struct ref_store *packed_ref_store; 33}; 34 35static voidclear_loose_ref_cache(struct files_ref_store *refs) 36{ 37if(refs->loose) { 38free_ref_cache(refs->loose); 39 refs->loose = NULL; 40} 41} 42 43/* 44 * Create a new submodule ref cache and add it to the internal 45 * set of caches. 46 */ 47static struct ref_store *files_ref_store_create(const char*gitdir, 48unsigned int flags) 49{ 50struct files_ref_store *refs =xcalloc(1,sizeof(*refs)); 51struct ref_store *ref_store = (struct ref_store *)refs; 52struct strbuf sb = STRBUF_INIT; 53 54base_ref_store_init(ref_store, &refs_be_files); 55 refs->store_flags = flags; 56 57 refs->gitdir =xstrdup(gitdir); 58get_common_dir_noenv(&sb, gitdir); 59 refs->gitcommondir =strbuf_detach(&sb, NULL); 60strbuf_addf(&sb,"%s/packed-refs", refs->gitcommondir); 61 refs->packed_ref_store =packed_ref_store_create(sb.buf, flags); 62strbuf_release(&sb); 63 64return ref_store; 65} 66 67/* 68 * Die if refs is not the main ref store. caller is used in any 69 * necessary error messages. 70 */ 71static voidfiles_assert_main_repository(struct files_ref_store *refs, 72const char*caller) 73{ 74if(refs->store_flags & REF_STORE_MAIN) 75return; 76 77die("BUG: operation%sonly allowed for main ref store", caller); 78} 79 80/* 81 * Downcast ref_store to files_ref_store. Die if ref_store is not a 82 * files_ref_store. required_flags is compared with ref_store's 83 * store_flags to ensure the ref_store has all required capabilities. 84 * "caller" is used in any necessary error messages. 85 */ 86static struct files_ref_store *files_downcast(struct ref_store *ref_store, 87unsigned int required_flags, 88const char*caller) 89{ 90struct files_ref_store *refs; 91 92if(ref_store->be != &refs_be_files) 93die("BUG: ref_store is type\"%s\"not\"files\"in%s", 94 ref_store->be->name, caller); 95 96 refs = (struct files_ref_store *)ref_store; 97 98if((refs->store_flags & required_flags) != required_flags) 99die("BUG: operation%srequires abilities 0x%x, but only have 0x%x", 100 caller, required_flags, refs->store_flags); 101 102return refs; 103} 104 105static voidfiles_reflog_path(struct files_ref_store *refs, 106struct strbuf *sb, 107const char*refname) 108{ 109switch(ref_type(refname)) { 110case REF_TYPE_PER_WORKTREE: 111case REF_TYPE_PSEUDOREF: 112strbuf_addf(sb,"%s/logs/%s", refs->gitdir, refname); 113break; 114case REF_TYPE_NORMAL: 115strbuf_addf(sb,"%s/logs/%s", refs->gitcommondir, refname); 116break; 117default: 118die("BUG: unknown ref type%dof ref%s", 119ref_type(refname), refname); 120} 121} 122 123static voidfiles_ref_path(struct files_ref_store *refs, 124struct strbuf *sb, 125const char*refname) 126{ 127switch(ref_type(refname)) { 128case REF_TYPE_PER_WORKTREE: 129case REF_TYPE_PSEUDOREF: 130strbuf_addf(sb,"%s/%s", refs->gitdir, refname); 131break; 132case REF_TYPE_NORMAL: 133strbuf_addf(sb,"%s/%s", refs->gitcommondir, refname); 134break; 135default: 136die("BUG: unknown ref type%dof ref%s", 137ref_type(refname), refname); 138} 139} 140 141/* 142 * Read the loose references from the namespace dirname into dir 143 * (without recursing). dirname must end with '/'. dir must be the 144 * directory entry corresponding to dirname. 145 */ 146static voidloose_fill_ref_dir(struct ref_store *ref_store, 147struct ref_dir *dir,const char*dirname) 148{ 149struct files_ref_store *refs = 150files_downcast(ref_store, REF_STORE_READ,"fill_ref_dir"); 151DIR*d; 152struct dirent *de; 153int dirnamelen =strlen(dirname); 154struct strbuf refname; 155struct strbuf path = STRBUF_INIT; 156size_t path_baselen; 157 158files_ref_path(refs, &path, dirname); 159 path_baselen = path.len; 160 161 d =opendir(path.buf); 162if(!d) { 163strbuf_release(&path); 164return; 165} 166 167strbuf_init(&refname, dirnamelen +257); 168strbuf_add(&refname, dirname, dirnamelen); 169 170while((de =readdir(d)) != NULL) { 171struct object_id oid; 172struct stat st; 173int flag; 174 175if(de->d_name[0] =='.') 176continue; 177if(ends_with(de->d_name,".lock")) 178continue; 179strbuf_addstr(&refname, de->d_name); 180strbuf_addstr(&path, de->d_name); 181if(stat(path.buf, &st) <0) { 182;/* silently ignore */ 183}else if(S_ISDIR(st.st_mode)) { 184strbuf_addch(&refname,'/'); 185add_entry_to_dir(dir, 186create_dir_entry(dir->cache, refname.buf, 187 refname.len,1)); 188}else{ 189if(!refs_resolve_ref_unsafe(&refs->base, 190 refname.buf, 191 RESOLVE_REF_READING, 192 oid.hash, &flag)) { 193oidclr(&oid); 194 flag |= REF_ISBROKEN; 195}else if(is_null_oid(&oid)) { 196/* 197 * It is so astronomically unlikely 198 * that NULL_SHA1 is the SHA-1 of an 199 * actual object that we consider its 200 * appearance in a loose reference 201 * file to be repo corruption 202 * (probably due to a software bug). 203 */ 204 flag |= REF_ISBROKEN; 205} 206 207if(check_refname_format(refname.buf, 208 REFNAME_ALLOW_ONELEVEL)) { 209if(!refname_is_safe(refname.buf)) 210die("loose refname is dangerous:%s", refname.buf); 211oidclr(&oid); 212 flag |= REF_BAD_NAME | REF_ISBROKEN; 213} 214add_entry_to_dir(dir, 215create_ref_entry(refname.buf, &oid, flag)); 216} 217strbuf_setlen(&refname, dirnamelen); 218strbuf_setlen(&path, path_baselen); 219} 220strbuf_release(&refname); 221strbuf_release(&path); 222closedir(d); 223 224/* 225 * Manually add refs/bisect, which, being per-worktree, might 226 * not appear in the directory listing for refs/ in the main 227 * repo. 228 */ 229if(!strcmp(dirname,"refs/")) { 230int pos =search_ref_dir(dir,"refs/bisect/",12); 231 232if(pos <0) { 233struct ref_entry *child_entry =create_dir_entry( 234 dir->cache,"refs/bisect/",12,1); 235add_entry_to_dir(dir, child_entry); 236} 237} 238} 239 240static struct ref_cache *get_loose_ref_cache(struct files_ref_store *refs) 241{ 242if(!refs->loose) { 243/* 244 * Mark the top-level directory complete because we 245 * are about to read the only subdirectory that can 246 * hold references: 247 */ 248 refs->loose =create_ref_cache(&refs->base, loose_fill_ref_dir); 249 250/* We're going to fill the top level ourselves: */ 251 refs->loose->root->flag &= ~REF_INCOMPLETE; 252 253/* 254 * Add an incomplete entry for "refs/" (to be filled 255 * lazily): 256 */ 257add_entry_to_dir(get_ref_dir(refs->loose->root), 258create_dir_entry(refs->loose,"refs/",5,1)); 259} 260return refs->loose; 261} 262 263static intfiles_read_raw_ref(struct ref_store *ref_store, 264const char*refname,unsigned char*sha1, 265struct strbuf *referent,unsigned int*type) 266{ 267struct files_ref_store *refs = 268files_downcast(ref_store, REF_STORE_READ,"read_raw_ref"); 269struct strbuf sb_contents = STRBUF_INIT; 270struct strbuf sb_path = STRBUF_INIT; 271const char*path; 272const char*buf; 273struct stat st; 274int fd; 275int ret = -1; 276int save_errno; 277int remaining_retries =3; 278 279*type =0; 280strbuf_reset(&sb_path); 281 282files_ref_path(refs, &sb_path, refname); 283 284 path = sb_path.buf; 285 286stat_ref: 287/* 288 * We might have to loop back here to avoid a race 289 * condition: first we lstat() the file, then we try 290 * to read it as a link or as a file. But if somebody 291 * changes the type of the file (file <-> directory 292 * <-> symlink) between the lstat() and reading, then 293 * we don't want to report that as an error but rather 294 * try again starting with the lstat(). 295 * 296 * We'll keep a count of the retries, though, just to avoid 297 * any confusing situation sending us into an infinite loop. 298 */ 299 300if(remaining_retries-- <=0) 301goto out; 302 303if(lstat(path, &st) <0) { 304if(errno != ENOENT) 305goto out; 306if(refs_read_raw_ref(refs->packed_ref_store, refname, 307 sha1, referent, type)) { 308 errno = ENOENT; 309goto out; 310} 311 ret =0; 312goto out; 313} 314 315/* Follow "normalized" - ie "refs/.." symlinks by hand */ 316if(S_ISLNK(st.st_mode)) { 317strbuf_reset(&sb_contents); 318if(strbuf_readlink(&sb_contents, path,0) <0) { 319if(errno == ENOENT || errno == EINVAL) 320/* inconsistent with lstat; retry */ 321goto stat_ref; 322else 323goto out; 324} 325if(starts_with(sb_contents.buf,"refs/") && 326!check_refname_format(sb_contents.buf,0)) { 327strbuf_swap(&sb_contents, referent); 328*type |= REF_ISSYMREF; 329 ret =0; 330goto out; 331} 332/* 333 * It doesn't look like a refname; fall through to just 334 * treating it like a non-symlink, and reading whatever it 335 * points to. 336 */ 337} 338 339/* Is it a directory? */ 340if(S_ISDIR(st.st_mode)) { 341/* 342 * Even though there is a directory where the loose 343 * ref is supposed to be, there could still be a 344 * packed ref: 345 */ 346if(refs_read_raw_ref(refs->packed_ref_store, refname, 347 sha1, referent, type)) { 348 errno = EISDIR; 349goto out; 350} 351 ret =0; 352goto out; 353} 354 355/* 356 * Anything else, just open it and try to use it as 357 * a ref 358 */ 359 fd =open(path, O_RDONLY); 360if(fd <0) { 361if(errno == ENOENT && !S_ISLNK(st.st_mode)) 362/* inconsistent with lstat; retry */ 363goto stat_ref; 364else 365goto out; 366} 367strbuf_reset(&sb_contents); 368if(strbuf_read(&sb_contents, fd,256) <0) { 369int save_errno = errno; 370close(fd); 371 errno = save_errno; 372goto out; 373} 374close(fd); 375strbuf_rtrim(&sb_contents); 376 buf = sb_contents.buf; 377if(starts_with(buf,"ref:")) { 378 buf +=4; 379while(isspace(*buf)) 380 buf++; 381 382strbuf_reset(referent); 383strbuf_addstr(referent, buf); 384*type |= REF_ISSYMREF; 385 ret =0; 386goto out; 387} 388 389/* 390 * Please note that FETCH_HEAD has additional 391 * data after the sha. 392 */ 393if(get_sha1_hex(buf, sha1) || 394(buf[40] !='\0'&& !isspace(buf[40]))) { 395*type |= REF_ISBROKEN; 396 errno = EINVAL; 397goto out; 398} 399 400 ret =0; 401 402out: 403 save_errno = errno; 404strbuf_release(&sb_path); 405strbuf_release(&sb_contents); 406 errno = save_errno; 407return ret; 408} 409 410static voidunlock_ref(struct ref_lock *lock) 411{ 412/* Do not free lock->lk -- atexit() still looks at them */ 413if(lock->lk) 414rollback_lock_file(lock->lk); 415free(lock->ref_name); 416free(lock); 417} 418 419/* 420 * Lock refname, without following symrefs, and set *lock_p to point 421 * at a newly-allocated lock object. Fill in lock->old_oid, referent, 422 * and type similarly to read_raw_ref(). 423 * 424 * The caller must verify that refname is a "safe" reference name (in 425 * the sense of refname_is_safe()) before calling this function. 426 * 427 * If the reference doesn't already exist, verify that refname doesn't 428 * have a D/F conflict with any existing references. extras and skip 429 * are passed to refs_verify_refname_available() for this check. 430 * 431 * If mustexist is not set and the reference is not found or is 432 * broken, lock the reference anyway but clear sha1. 433 * 434 * Return 0 on success. On failure, write an error message to err and 435 * return TRANSACTION_NAME_CONFLICT or TRANSACTION_GENERIC_ERROR. 436 * 437 * Implementation note: This function is basically 438 * 439 * lock reference 440 * read_raw_ref() 441 * 442 * but it includes a lot more code to 443 * - Deal with possible races with other processes 444 * - Avoid calling refs_verify_refname_available() when it can be 445 * avoided, namely if we were successfully able to read the ref 446 * - Generate informative error messages in the case of failure 447 */ 448static intlock_raw_ref(struct files_ref_store *refs, 449const char*refname,int mustexist, 450const struct string_list *extras, 451const struct string_list *skip, 452struct ref_lock **lock_p, 453struct strbuf *referent, 454unsigned int*type, 455struct strbuf *err) 456{ 457struct ref_lock *lock; 458struct strbuf ref_file = STRBUF_INIT; 459int attempts_remaining =3; 460int ret = TRANSACTION_GENERIC_ERROR; 461 462assert(err); 463files_assert_main_repository(refs,"lock_raw_ref"); 464 465*type =0; 466 467/* First lock the file so it can't change out from under us. */ 468 469*lock_p = lock =xcalloc(1,sizeof(*lock)); 470 471 lock->ref_name =xstrdup(refname); 472files_ref_path(refs, &ref_file, refname); 473 474retry: 475switch(safe_create_leading_directories(ref_file.buf)) { 476case SCLD_OK: 477break;/* success */ 478case SCLD_EXISTS: 479/* 480 * Suppose refname is "refs/foo/bar". We just failed 481 * to create the containing directory, "refs/foo", 482 * because there was a non-directory in the way. This 483 * indicates a D/F conflict, probably because of 484 * another reference such as "refs/foo". There is no 485 * reason to expect this error to be transitory. 486 */ 487if(refs_verify_refname_available(&refs->base, refname, 488 extras, skip, err)) { 489if(mustexist) { 490/* 491 * To the user the relevant error is 492 * that the "mustexist" reference is 493 * missing: 494 */ 495strbuf_reset(err); 496strbuf_addf(err,"unable to resolve reference '%s'", 497 refname); 498}else{ 499/* 500 * The error message set by 501 * refs_verify_refname_available() is 502 * OK. 503 */ 504 ret = TRANSACTION_NAME_CONFLICT; 505} 506}else{ 507/* 508 * The file that is in the way isn't a loose 509 * reference. Report it as a low-level 510 * failure. 511 */ 512strbuf_addf(err,"unable to create lock file%s.lock; " 513"non-directory in the way", 514 ref_file.buf); 515} 516goto error_return; 517case SCLD_VANISHED: 518/* Maybe another process was tidying up. Try again. */ 519if(--attempts_remaining >0) 520goto retry; 521/* fall through */ 522default: 523strbuf_addf(err,"unable to create directory for%s", 524 ref_file.buf); 525goto error_return; 526} 527 528if(!lock->lk) 529 lock->lk =xcalloc(1,sizeof(struct lock_file)); 530 531if(hold_lock_file_for_update(lock->lk, ref_file.buf, LOCK_NO_DEREF) <0) { 532if(errno == ENOENT && --attempts_remaining >0) { 533/* 534 * Maybe somebody just deleted one of the 535 * directories leading to ref_file. Try 536 * again: 537 */ 538goto retry; 539}else{ 540unable_to_lock_message(ref_file.buf, errno, err); 541goto error_return; 542} 543} 544 545/* 546 * Now we hold the lock and can read the reference without 547 * fear that its value will change. 548 */ 549 550if(files_read_raw_ref(&refs->base, refname, 551 lock->old_oid.hash, referent, type)) { 552if(errno == ENOENT) { 553if(mustexist) { 554/* Garden variety missing reference. */ 555strbuf_addf(err,"unable to resolve reference '%s'", 556 refname); 557goto error_return; 558}else{ 559/* 560 * Reference is missing, but that's OK. We 561 * know that there is not a conflict with 562 * another loose reference because 563 * (supposing that we are trying to lock 564 * reference "refs/foo/bar"): 565 * 566 * - We were successfully able to create 567 * the lockfile refs/foo/bar.lock, so we 568 * know there cannot be a loose reference 569 * named "refs/foo". 570 * 571 * - We got ENOENT and not EISDIR, so we 572 * know that there cannot be a loose 573 * reference named "refs/foo/bar/baz". 574 */ 575} 576}else if(errno == EISDIR) { 577/* 578 * There is a directory in the way. It might have 579 * contained references that have been deleted. If 580 * we don't require that the reference already 581 * exists, try to remove the directory so that it 582 * doesn't cause trouble when we want to rename the 583 * lockfile into place later. 584 */ 585if(mustexist) { 586/* Garden variety missing reference. */ 587strbuf_addf(err,"unable to resolve reference '%s'", 588 refname); 589goto error_return; 590}else if(remove_dir_recursively(&ref_file, 591 REMOVE_DIR_EMPTY_ONLY)) { 592if(refs_verify_refname_available( 593&refs->base, refname, 594 extras, skip, err)) { 595/* 596 * The error message set by 597 * verify_refname_available() is OK. 598 */ 599 ret = TRANSACTION_NAME_CONFLICT; 600goto error_return; 601}else{ 602/* 603 * We can't delete the directory, 604 * but we also don't know of any 605 * references that it should 606 * contain. 607 */ 608strbuf_addf(err,"there is a non-empty directory '%s' " 609"blocking reference '%s'", 610 ref_file.buf, refname); 611goto error_return; 612} 613} 614}else if(errno == EINVAL && (*type & REF_ISBROKEN)) { 615strbuf_addf(err,"unable to resolve reference '%s': " 616"reference broken", refname); 617goto error_return; 618}else{ 619strbuf_addf(err,"unable to resolve reference '%s':%s", 620 refname,strerror(errno)); 621goto error_return; 622} 623 624/* 625 * If the ref did not exist and we are creating it, 626 * make sure there is no existing packed ref that 627 * conflicts with refname: 628 */ 629if(refs_verify_refname_available( 630 refs->packed_ref_store, refname, 631 extras, skip, err)) 632goto error_return; 633} 634 635 ret =0; 636goto out; 637 638error_return: 639unlock_ref(lock); 640*lock_p = NULL; 641 642out: 643strbuf_release(&ref_file); 644return ret; 645} 646 647static intfiles_peel_ref(struct ref_store *ref_store, 648const char*refname,unsigned char*sha1) 649{ 650struct files_ref_store *refs = 651files_downcast(ref_store, REF_STORE_READ | REF_STORE_ODB, 652"peel_ref"); 653int flag; 654unsigned char base[20]; 655 656if(current_ref_iter && current_ref_iter->refname == refname) { 657struct object_id peeled; 658 659if(ref_iterator_peel(current_ref_iter, &peeled)) 660return-1; 661hashcpy(sha1, peeled.hash); 662return0; 663} 664 665if(refs_read_ref_full(ref_store, refname, 666 RESOLVE_REF_READING, base, &flag)) 667return-1; 668 669/* 670 * If the reference is packed, read its ref_entry from the 671 * cache in the hope that we already know its peeled value. 672 * We only try this optimization on packed references because 673 * (a) forcing the filling of the loose reference cache could 674 * be expensive and (b) loose references anyway usually do not 675 * have REF_KNOWS_PEELED. 676 */ 677if(flag & REF_ISPACKED && 678!refs_peel_ref(refs->packed_ref_store, refname, sha1)) 679return0; 680 681returnpeel_object(base, sha1); 682} 683 684struct files_ref_iterator { 685struct ref_iterator base; 686 687struct ref_iterator *iter0; 688unsigned int flags; 689}; 690 691static intfiles_ref_iterator_advance(struct ref_iterator *ref_iterator) 692{ 693struct files_ref_iterator *iter = 694(struct files_ref_iterator *)ref_iterator; 695int ok; 696 697while((ok =ref_iterator_advance(iter->iter0)) == ITER_OK) { 698if(iter->flags & DO_FOR_EACH_PER_WORKTREE_ONLY && 699ref_type(iter->iter0->refname) != REF_TYPE_PER_WORKTREE) 700continue; 701 702if(!(iter->flags & DO_FOR_EACH_INCLUDE_BROKEN) && 703!ref_resolves_to_object(iter->iter0->refname, 704 iter->iter0->oid, 705 iter->iter0->flags)) 706continue; 707 708 iter->base.refname = iter->iter0->refname; 709 iter->base.oid = iter->iter0->oid; 710 iter->base.flags = iter->iter0->flags; 711return ITER_OK; 712} 713 714 iter->iter0 = NULL; 715if(ref_iterator_abort(ref_iterator) != ITER_DONE) 716 ok = ITER_ERROR; 717 718return ok; 719} 720 721static intfiles_ref_iterator_peel(struct ref_iterator *ref_iterator, 722struct object_id *peeled) 723{ 724struct files_ref_iterator *iter = 725(struct files_ref_iterator *)ref_iterator; 726 727returnref_iterator_peel(iter->iter0, peeled); 728} 729 730static intfiles_ref_iterator_abort(struct ref_iterator *ref_iterator) 731{ 732struct files_ref_iterator *iter = 733(struct files_ref_iterator *)ref_iterator; 734int ok = ITER_DONE; 735 736if(iter->iter0) 737 ok =ref_iterator_abort(iter->iter0); 738 739base_ref_iterator_free(ref_iterator); 740return ok; 741} 742 743static struct ref_iterator_vtable files_ref_iterator_vtable = { 744 files_ref_iterator_advance, 745 files_ref_iterator_peel, 746 files_ref_iterator_abort 747}; 748 749static struct ref_iterator *files_ref_iterator_begin( 750struct ref_store *ref_store, 751const char*prefix,unsigned int flags) 752{ 753struct files_ref_store *refs; 754struct ref_iterator *loose_iter, *packed_iter; 755struct files_ref_iterator *iter; 756struct ref_iterator *ref_iterator; 757unsigned int required_flags = REF_STORE_READ; 758 759if(!(flags & DO_FOR_EACH_INCLUDE_BROKEN)) 760 required_flags |= REF_STORE_ODB; 761 762 refs =files_downcast(ref_store, required_flags,"ref_iterator_begin"); 763 764 iter =xcalloc(1,sizeof(*iter)); 765 ref_iterator = &iter->base; 766base_ref_iterator_init(ref_iterator, &files_ref_iterator_vtable); 767 768/* 769 * We must make sure that all loose refs are read before 770 * accessing the packed-refs file; this avoids a race 771 * condition if loose refs are migrated to the packed-refs 772 * file by a simultaneous process, but our in-memory view is 773 * from before the migration. We ensure this as follows: 774 * First, we call start the loose refs iteration with its 775 * `prime_ref` argument set to true. This causes the loose 776 * references in the subtree to be pre-read into the cache. 777 * (If they've already been read, that's OK; we only need to 778 * guarantee that they're read before the packed refs, not 779 * *how much* before.) After that, we call 780 * packed_ref_iterator_begin(), which internally checks 781 * whether the packed-ref cache is up to date with what is on 782 * disk, and re-reads it if not. 783 */ 784 785 loose_iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), 786 prefix,1); 787 788/* 789 * The packed-refs file might contain broken references, for 790 * example an old version of a reference that points at an 791 * object that has since been garbage-collected. This is OK as 792 * long as there is a corresponding loose reference that 793 * overrides it, and we don't want to emit an error message in 794 * this case. So ask the packed_ref_store for all of its 795 * references, and (if needed) do our own check for broken 796 * ones in files_ref_iterator_advance(), after we have merged 797 * the packed and loose references. 798 */ 799 packed_iter =refs_ref_iterator_begin( 800 refs->packed_ref_store, prefix,0, 801 DO_FOR_EACH_INCLUDE_BROKEN); 802 803 iter->iter0 =overlay_ref_iterator_begin(loose_iter, packed_iter); 804 iter->flags = flags; 805 806return ref_iterator; 807} 808 809/* 810 * Verify that the reference locked by lock has the value old_sha1. 811 * Fail if the reference doesn't exist and mustexist is set. Return 0 812 * on success. On error, write an error message to err, set errno, and 813 * return a negative value. 814 */ 815static intverify_lock(struct ref_store *ref_store,struct ref_lock *lock, 816const unsigned char*old_sha1,int mustexist, 817struct strbuf *err) 818{ 819assert(err); 820 821if(refs_read_ref_full(ref_store, lock->ref_name, 822 mustexist ? RESOLVE_REF_READING :0, 823 lock->old_oid.hash, NULL)) { 824if(old_sha1) { 825int save_errno = errno; 826strbuf_addf(err,"can't verify ref '%s'", lock->ref_name); 827 errno = save_errno; 828return-1; 829}else{ 830oidclr(&lock->old_oid); 831return0; 832} 833} 834if(old_sha1 &&hashcmp(lock->old_oid.hash, old_sha1)) { 835strbuf_addf(err,"ref '%s' is at%sbut expected%s", 836 lock->ref_name, 837oid_to_hex(&lock->old_oid), 838sha1_to_hex(old_sha1)); 839 errno = EBUSY; 840return-1; 841} 842return0; 843} 844 845static intremove_empty_directories(struct strbuf *path) 846{ 847/* 848 * we want to create a file but there is a directory there; 849 * if that is an empty directory (or a directory that contains 850 * only empty directories), remove them. 851 */ 852returnremove_dir_recursively(path, REMOVE_DIR_EMPTY_ONLY); 853} 854 855static intcreate_reflock(const char*path,void*cb) 856{ 857struct lock_file *lk = cb; 858 859returnhold_lock_file_for_update(lk, path, LOCK_NO_DEREF) <0? -1:0; 860} 861 862/* 863 * Locks a ref returning the lock on success and NULL on failure. 864 * On failure errno is set to something meaningful. 865 */ 866static struct ref_lock *lock_ref_sha1_basic(struct files_ref_store *refs, 867const char*refname, 868const unsigned char*old_sha1, 869const struct string_list *extras, 870const struct string_list *skip, 871unsigned int flags,int*type, 872struct strbuf *err) 873{ 874struct strbuf ref_file = STRBUF_INIT; 875struct ref_lock *lock; 876int last_errno =0; 877int mustexist = (old_sha1 && !is_null_sha1(old_sha1)); 878int resolve_flags = RESOLVE_REF_NO_RECURSE; 879int resolved; 880 881files_assert_main_repository(refs,"lock_ref_sha1_basic"); 882assert(err); 883 884 lock =xcalloc(1,sizeof(struct ref_lock)); 885 886if(mustexist) 887 resolve_flags |= RESOLVE_REF_READING; 888if(flags & REF_DELETING) 889 resolve_flags |= RESOLVE_REF_ALLOW_BAD_NAME; 890 891files_ref_path(refs, &ref_file, refname); 892 resolved = !!refs_resolve_ref_unsafe(&refs->base, 893 refname, resolve_flags, 894 lock->old_oid.hash, type); 895if(!resolved && errno == EISDIR) { 896/* 897 * we are trying to lock foo but we used to 898 * have foo/bar which now does not exist; 899 * it is normal for the empty directory 'foo' 900 * to remain. 901 */ 902if(remove_empty_directories(&ref_file)) { 903 last_errno = errno; 904if(!refs_verify_refname_available( 905&refs->base, 906 refname, extras, skip, err)) 907strbuf_addf(err,"there are still refs under '%s'", 908 refname); 909goto error_return; 910} 911 resolved = !!refs_resolve_ref_unsafe(&refs->base, 912 refname, resolve_flags, 913 lock->old_oid.hash, type); 914} 915if(!resolved) { 916 last_errno = errno; 917if(last_errno != ENOTDIR || 918!refs_verify_refname_available(&refs->base, refname, 919 extras, skip, err)) 920strbuf_addf(err,"unable to resolve reference '%s':%s", 921 refname,strerror(last_errno)); 922 923goto error_return; 924} 925 926/* 927 * If the ref did not exist and we are creating it, make sure 928 * there is no existing packed ref whose name begins with our 929 * refname, nor a packed ref whose name is a proper prefix of 930 * our refname. 931 */ 932if(is_null_oid(&lock->old_oid) && 933refs_verify_refname_available(refs->packed_ref_store, refname, 934 extras, skip, err)) { 935 last_errno = ENOTDIR; 936goto error_return; 937} 938 939 lock->lk =xcalloc(1,sizeof(struct lock_file)); 940 941 lock->ref_name =xstrdup(refname); 942 943if(raceproof_create_file(ref_file.buf, create_reflock, lock->lk)) { 944 last_errno = errno; 945unable_to_lock_message(ref_file.buf, errno, err); 946goto error_return; 947} 948 949if(verify_lock(&refs->base, lock, old_sha1, mustexist, err)) { 950 last_errno = errno; 951goto error_return; 952} 953goto out; 954 955 error_return: 956unlock_ref(lock); 957 lock = NULL; 958 959 out: 960strbuf_release(&ref_file); 961 errno = last_errno; 962return lock; 963} 964 965struct ref_to_prune { 966struct ref_to_prune *next; 967unsigned char sha1[20]; 968char name[FLEX_ARRAY]; 969}; 970 971enum{ 972 REMOVE_EMPTY_PARENTS_REF =0x01, 973 REMOVE_EMPTY_PARENTS_REFLOG =0x02 974}; 975 976/* 977 * Remove empty parent directories associated with the specified 978 * reference and/or its reflog, but spare [logs/]refs/ and immediate 979 * subdirs. flags is a combination of REMOVE_EMPTY_PARENTS_REF and/or 980 * REMOVE_EMPTY_PARENTS_REFLOG. 981 */ 982static voidtry_remove_empty_parents(struct files_ref_store *refs, 983const char*refname, 984unsigned int flags) 985{ 986struct strbuf buf = STRBUF_INIT; 987struct strbuf sb = STRBUF_INIT; 988char*p, *q; 989int i; 990 991strbuf_addstr(&buf, refname); 992 p = buf.buf; 993for(i =0; i <2; i++) {/* refs/{heads,tags,...}/ */ 994while(*p && *p !='/') 995 p++; 996/* tolerate duplicate slashes; see check_refname_format() */ 997while(*p =='/') 998 p++; 999}1000 q = buf.buf + buf.len;1001while(flags & (REMOVE_EMPTY_PARENTS_REF | REMOVE_EMPTY_PARENTS_REFLOG)) {1002while(q > p && *q !='/')1003 q--;1004while(q > p && *(q-1) =='/')1005 q--;1006if(q == p)1007break;1008strbuf_setlen(&buf, q - buf.buf);10091010strbuf_reset(&sb);1011files_ref_path(refs, &sb, buf.buf);1012if((flags & REMOVE_EMPTY_PARENTS_REF) &&rmdir(sb.buf))1013 flags &= ~REMOVE_EMPTY_PARENTS_REF;10141015strbuf_reset(&sb);1016files_reflog_path(refs, &sb, buf.buf);1017if((flags & REMOVE_EMPTY_PARENTS_REFLOG) &&rmdir(sb.buf))1018 flags &= ~REMOVE_EMPTY_PARENTS_REFLOG;1019}1020strbuf_release(&buf);1021strbuf_release(&sb);1022}10231024/* make sure nobody touched the ref, and unlink */1025static voidprune_ref(struct files_ref_store *refs,struct ref_to_prune *r)1026{1027struct ref_transaction *transaction;1028struct strbuf err = STRBUF_INIT;10291030if(check_refname_format(r->name,0))1031return;10321033 transaction =ref_store_transaction_begin(&refs->base, &err);1034if(!transaction ||1035ref_transaction_delete(transaction, r->name, r->sha1,1036 REF_ISPRUNING | REF_NODEREF, NULL, &err) ||1037ref_transaction_commit(transaction, &err)) {1038ref_transaction_free(transaction);1039error("%s", err.buf);1040strbuf_release(&err);1041return;1042}1043ref_transaction_free(transaction);1044strbuf_release(&err);1045}10461047static voidprune_refs(struct files_ref_store *refs,struct ref_to_prune *r)1048{1049while(r) {1050prune_ref(refs, r);1051 r = r->next;1052}1053}10541055/*1056 * Return true if the specified reference should be packed.1057 */1058static intshould_pack_ref(const char*refname,1059const struct object_id *oid,unsigned int ref_flags,1060unsigned int pack_flags)1061{1062/* Do not pack per-worktree refs: */1063if(ref_type(refname) != REF_TYPE_NORMAL)1064return0;10651066/* Do not pack non-tags unless PACK_REFS_ALL is set: */1067if(!(pack_flags & PACK_REFS_ALL) && !starts_with(refname,"refs/tags/"))1068return0;10691070/* Do not pack symbolic refs: */1071if(ref_flags & REF_ISSYMREF)1072return0;10731074/* Do not pack broken refs: */1075if(!ref_resolves_to_object(refname, oid, ref_flags))1076return0;10771078return1;1079}10801081static intfiles_pack_refs(struct ref_store *ref_store,unsigned int flags)1082{1083struct files_ref_store *refs =1084files_downcast(ref_store, REF_STORE_WRITE | REF_STORE_ODB,1085"pack_refs");1086struct ref_iterator *iter;1087int ok;1088struct ref_to_prune *refs_to_prune = NULL;1089struct strbuf err = STRBUF_INIT;10901091packed_refs_lock(refs->packed_ref_store, LOCK_DIE_ON_ERROR, &err);10921093 iter =cache_ref_iterator_begin(get_loose_ref_cache(refs), NULL,0);1094while((ok =ref_iterator_advance(iter)) == ITER_OK) {1095/*1096 * If the loose reference can be packed, add an entry1097 * in the packed ref cache. If the reference should be1098 * pruned, also add it to refs_to_prune.1099 */1100if(!should_pack_ref(iter->refname, iter->oid, iter->flags,1101 flags))1102continue;11031104/*1105 * Create an entry in the packed-refs cache equivalent1106 * to the one from the loose ref cache, except that1107 * we don't copy the peeled status, because we want it1108 * to be re-peeled.1109 */1110add_packed_ref(refs->packed_ref_store, iter->refname, iter->oid);11111112/* Schedule the loose reference for pruning if requested. */1113if((flags & PACK_REFS_PRUNE)) {1114struct ref_to_prune *n;1115FLEX_ALLOC_STR(n, name, iter->refname);1116hashcpy(n->sha1, iter->oid->hash);1117 n->next = refs_to_prune;1118 refs_to_prune = n;1119}1120}1121if(ok != ITER_DONE)1122die("error while iterating over references");11231124if(commit_packed_refs(refs->packed_ref_store, &err))1125die("unable to overwrite old ref-pack file:%s", err.buf);1126packed_refs_unlock(refs->packed_ref_store);11271128prune_refs(refs, refs_to_prune);1129strbuf_release(&err);1130return0;1131}11321133static intfiles_delete_refs(struct ref_store *ref_store,const char*msg,1134struct string_list *refnames,unsigned int flags)1135{1136struct files_ref_store *refs =1137files_downcast(ref_store, REF_STORE_WRITE,"delete_refs");1138struct strbuf err = STRBUF_INIT;1139int i, result =0;11401141if(!refnames->nr)1142return0;11431144if(packed_refs_lock(refs->packed_ref_store,0, &err))1145goto error;11461147if(repack_without_refs(refs->packed_ref_store, refnames, &err)) {1148packed_refs_unlock(refs->packed_ref_store);1149goto error;1150}11511152packed_refs_unlock(refs->packed_ref_store);11531154for(i =0; i < refnames->nr; i++) {1155const char*refname = refnames->items[i].string;11561157if(refs_delete_ref(&refs->base, msg, refname, NULL, flags))1158 result |=error(_("could not remove reference%s"), refname);1159}11601161strbuf_release(&err);1162return result;11631164error:1165/*1166 * If we failed to rewrite the packed-refs file, then it is1167 * unsafe to try to remove loose refs, because doing so might1168 * expose an obsolete packed value for a reference that might1169 * even point at an object that has been garbage collected.1170 */1171if(refnames->nr ==1)1172error(_("could not delete reference%s:%s"),1173 refnames->items[0].string, err.buf);1174else1175error(_("could not delete references:%s"), err.buf);11761177strbuf_release(&err);1178return-1;1179}11801181/*1182 * People using contrib's git-new-workdir have .git/logs/refs ->1183 * /some/other/path/.git/logs/refs, and that may live on another device.1184 *1185 * IOW, to avoid cross device rename errors, the temporary renamed log must1186 * live into logs/refs.1187 */1188#define TMP_RENAMED_LOG"refs/.tmp-renamed-log"11891190struct rename_cb {1191const char*tmp_renamed_log;1192int true_errno;1193};11941195static intrename_tmp_log_callback(const char*path,void*cb_data)1196{1197struct rename_cb *cb = cb_data;11981199if(rename(cb->tmp_renamed_log, path)) {1200/*1201 * rename(a, b) when b is an existing directory ought1202 * to result in ISDIR, but Solaris 5.8 gives ENOTDIR.1203 * Sheesh. Record the true errno for error reporting,1204 * but report EISDIR to raceproof_create_file() so1205 * that it knows to retry.1206 */1207 cb->true_errno = errno;1208if(errno == ENOTDIR)1209 errno = EISDIR;1210return-1;1211}else{1212return0;1213}1214}12151216static intrename_tmp_log(struct files_ref_store *refs,const char*newrefname)1217{1218struct strbuf path = STRBUF_INIT;1219struct strbuf tmp = STRBUF_INIT;1220struct rename_cb cb;1221int ret;12221223files_reflog_path(refs, &path, newrefname);1224files_reflog_path(refs, &tmp, TMP_RENAMED_LOG);1225 cb.tmp_renamed_log = tmp.buf;1226 ret =raceproof_create_file(path.buf, rename_tmp_log_callback, &cb);1227if(ret) {1228if(errno == EISDIR)1229error("directory not empty:%s", path.buf);1230else1231error("unable to move logfile%sto%s:%s",1232 tmp.buf, path.buf,1233strerror(cb.true_errno));1234}12351236strbuf_release(&path);1237strbuf_release(&tmp);1238return ret;1239}12401241static intwrite_ref_to_lockfile(struct ref_lock *lock,1242const struct object_id *oid,struct strbuf *err);1243static intcommit_ref_update(struct files_ref_store *refs,1244struct ref_lock *lock,1245const struct object_id *oid,const char*logmsg,1246struct strbuf *err);12471248static intfiles_rename_ref(struct ref_store *ref_store,1249const char*oldrefname,const char*newrefname,1250const char*logmsg)1251{1252struct files_ref_store *refs =1253files_downcast(ref_store, REF_STORE_WRITE,"rename_ref");1254struct object_id oid, orig_oid;1255int flag =0, logmoved =0;1256struct ref_lock *lock;1257struct stat loginfo;1258struct strbuf sb_oldref = STRBUF_INIT;1259struct strbuf sb_newref = STRBUF_INIT;1260struct strbuf tmp_renamed_log = STRBUF_INIT;1261int log, ret;1262struct strbuf err = STRBUF_INIT;12631264files_reflog_path(refs, &sb_oldref, oldrefname);1265files_reflog_path(refs, &sb_newref, newrefname);1266files_reflog_path(refs, &tmp_renamed_log, TMP_RENAMED_LOG);12671268 log = !lstat(sb_oldref.buf, &loginfo);1269if(log &&S_ISLNK(loginfo.st_mode)) {1270 ret =error("reflog for%sis a symlink", oldrefname);1271goto out;1272}12731274if(!refs_resolve_ref_unsafe(&refs->base, oldrefname,1275 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1276 orig_oid.hash, &flag)) {1277 ret =error("refname%snot found", oldrefname);1278goto out;1279}12801281if(flag & REF_ISSYMREF) {1282 ret =error("refname%sis a symbolic ref, renaming it is not supported",1283 oldrefname);1284goto out;1285}1286if(!refs_rename_ref_available(&refs->base, oldrefname, newrefname)) {1287 ret =1;1288goto out;1289}12901291if(log &&rename(sb_oldref.buf, tmp_renamed_log.buf)) {1292 ret =error("unable to move logfile logs/%sto logs/"TMP_RENAMED_LOG":%s",1293 oldrefname,strerror(errno));1294goto out;1295}12961297if(refs_delete_ref(&refs->base, logmsg, oldrefname,1298 orig_oid.hash, REF_NODEREF)) {1299error("unable to delete old%s", oldrefname);1300goto rollback;1301}13021303/*1304 * Since we are doing a shallow lookup, oid is not the1305 * correct value to pass to delete_ref as old_oid. But that1306 * doesn't matter, because an old_oid check wouldn't add to1307 * the safety anyway; we want to delete the reference whatever1308 * its current value.1309 */1310if(!refs_read_ref_full(&refs->base, newrefname,1311 RESOLVE_REF_READING | RESOLVE_REF_NO_RECURSE,1312 oid.hash, NULL) &&1313refs_delete_ref(&refs->base, NULL, newrefname,1314 NULL, REF_NODEREF)) {1315if(errno == EISDIR) {1316struct strbuf path = STRBUF_INIT;1317int result;13181319files_ref_path(refs, &path, newrefname);1320 result =remove_empty_directories(&path);1321strbuf_release(&path);13221323if(result) {1324error("Directory not empty:%s", newrefname);1325goto rollback;1326}1327}else{1328error("unable to delete existing%s", newrefname);1329goto rollback;1330}1331}13321333if(log &&rename_tmp_log(refs, newrefname))1334goto rollback;13351336 logmoved = log;13371338 lock =lock_ref_sha1_basic(refs, newrefname, NULL, NULL, NULL,1339 REF_NODEREF, NULL, &err);1340if(!lock) {1341error("unable to rename '%s' to '%s':%s", oldrefname, newrefname, err.buf);1342strbuf_release(&err);1343goto rollback;1344}1345oidcpy(&lock->old_oid, &orig_oid);13461347if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1348commit_ref_update(refs, lock, &orig_oid, logmsg, &err)) {1349error("unable to write current sha1 into%s:%s", newrefname, err.buf);1350strbuf_release(&err);1351goto rollback;1352}13531354 ret =0;1355goto out;13561357 rollback:1358 lock =lock_ref_sha1_basic(refs, oldrefname, NULL, NULL, NULL,1359 REF_NODEREF, NULL, &err);1360if(!lock) {1361error("unable to lock%sfor rollback:%s", oldrefname, err.buf);1362strbuf_release(&err);1363goto rollbacklog;1364}13651366 flag = log_all_ref_updates;1367 log_all_ref_updates = LOG_REFS_NONE;1368if(write_ref_to_lockfile(lock, &orig_oid, &err) ||1369commit_ref_update(refs, lock, &orig_oid, NULL, &err)) {1370error("unable to write current sha1 into%s:%s", oldrefname, err.buf);1371strbuf_release(&err);1372}1373 log_all_ref_updates = flag;13741375 rollbacklog:1376if(logmoved &&rename(sb_newref.buf, sb_oldref.buf))1377error("unable to restore logfile%sfrom%s:%s",1378 oldrefname, newrefname,strerror(errno));1379if(!logmoved && log &&1380rename(tmp_renamed_log.buf, sb_oldref.buf))1381error("unable to restore logfile%sfrom logs/"TMP_RENAMED_LOG":%s",1382 oldrefname,strerror(errno));1383 ret =1;1384 out:1385strbuf_release(&sb_newref);1386strbuf_release(&sb_oldref);1387strbuf_release(&tmp_renamed_log);13881389return ret;1390}13911392static intclose_ref(struct ref_lock *lock)1393{1394if(close_lock_file(lock->lk))1395return-1;1396return0;1397}13981399static intcommit_ref(struct ref_lock *lock)1400{1401char*path =get_locked_file_path(lock->lk);1402struct stat st;14031404if(!lstat(path, &st) &&S_ISDIR(st.st_mode)) {1405/*1406 * There is a directory at the path we want to rename1407 * the lockfile to. Hopefully it is empty; try to1408 * delete it.1409 */1410size_t len =strlen(path);1411struct strbuf sb_path = STRBUF_INIT;14121413strbuf_attach(&sb_path, path, len, len);14141415/*1416 * If this fails, commit_lock_file() will also fail1417 * and will report the problem.1418 */1419remove_empty_directories(&sb_path);1420strbuf_release(&sb_path);1421}else{1422free(path);1423}14241425if(commit_lock_file(lock->lk))1426return-1;1427return0;1428}14291430static intopen_or_create_logfile(const char*path,void*cb)1431{1432int*fd = cb;14331434*fd =open(path, O_APPEND | O_WRONLY | O_CREAT,0666);1435return(*fd <0) ? -1:0;1436}14371438/*1439 * Create a reflog for a ref. If force_create = 0, only create the1440 * reflog for certain refs (those for which should_autocreate_reflog1441 * returns non-zero). Otherwise, create it regardless of the reference1442 * name. If the logfile already existed or was created, return 0 and1443 * set *logfd to the file descriptor opened for appending to the file.1444 * If no logfile exists and we decided not to create one, return 0 and1445 * set *logfd to -1. On failure, fill in *err, set *logfd to -1, and1446 * return -1.1447 */1448static intlog_ref_setup(struct files_ref_store *refs,1449const char*refname,int force_create,1450int*logfd,struct strbuf *err)1451{1452struct strbuf logfile_sb = STRBUF_INIT;1453char*logfile;14541455files_reflog_path(refs, &logfile_sb, refname);1456 logfile =strbuf_detach(&logfile_sb, NULL);14571458if(force_create ||should_autocreate_reflog(refname)) {1459if(raceproof_create_file(logfile, open_or_create_logfile, logfd)) {1460if(errno == ENOENT)1461strbuf_addf(err,"unable to create directory for '%s': "1462"%s", logfile,strerror(errno));1463else if(errno == EISDIR)1464strbuf_addf(err,"there are still logs under '%s'",1465 logfile);1466else1467strbuf_addf(err,"unable to append to '%s':%s",1468 logfile,strerror(errno));14691470goto error;1471}1472}else{1473*logfd =open(logfile, O_APPEND | O_WRONLY,0666);1474if(*logfd <0) {1475if(errno == ENOENT || errno == EISDIR) {1476/*1477 * The logfile doesn't already exist,1478 * but that is not an error; it only1479 * means that we won't write log1480 * entries to it.1481 */1482;1483}else{1484strbuf_addf(err,"unable to append to '%s':%s",1485 logfile,strerror(errno));1486goto error;1487}1488}1489}14901491if(*logfd >=0)1492adjust_shared_perm(logfile);14931494free(logfile);1495return0;14961497error:1498free(logfile);1499return-1;1500}15011502static intfiles_create_reflog(struct ref_store *ref_store,1503const char*refname,int force_create,1504struct strbuf *err)1505{1506struct files_ref_store *refs =1507files_downcast(ref_store, REF_STORE_WRITE,"create_reflog");1508int fd;15091510if(log_ref_setup(refs, refname, force_create, &fd, err))1511return-1;15121513if(fd >=0)1514close(fd);15151516return0;1517}15181519static intlog_ref_write_fd(int fd,const struct object_id *old_oid,1520const struct object_id *new_oid,1521const char*committer,const char*msg)1522{1523int msglen, written;1524unsigned maxlen, len;1525char*logrec;15261527 msglen = msg ?strlen(msg) :0;1528 maxlen =strlen(committer) + msglen +100;1529 logrec =xmalloc(maxlen);1530 len =xsnprintf(logrec, maxlen,"%s %s %s\n",1531oid_to_hex(old_oid),1532oid_to_hex(new_oid),1533 committer);1534if(msglen)1535 len +=copy_reflog_msg(logrec + len -1, msg) -1;15361537 written = len <= maxlen ?write_in_full(fd, logrec, len) : -1;1538free(logrec);1539if(written != len)1540return-1;15411542return0;1543}15441545static intfiles_log_ref_write(struct files_ref_store *refs,1546const char*refname,const struct object_id *old_oid,1547const struct object_id *new_oid,const char*msg,1548int flags,struct strbuf *err)1549{1550int logfd, result;15511552if(log_all_ref_updates == LOG_REFS_UNSET)1553 log_all_ref_updates =is_bare_repository() ? LOG_REFS_NONE : LOG_REFS_NORMAL;15541555 result =log_ref_setup(refs, refname,1556 flags & REF_FORCE_CREATE_REFLOG,1557&logfd, err);15581559if(result)1560return result;15611562if(logfd <0)1563return0;1564 result =log_ref_write_fd(logfd, old_oid, new_oid,1565git_committer_info(0), msg);1566if(result) {1567struct strbuf sb = STRBUF_INIT;1568int save_errno = errno;15691570files_reflog_path(refs, &sb, refname);1571strbuf_addf(err,"unable to append to '%s':%s",1572 sb.buf,strerror(save_errno));1573strbuf_release(&sb);1574close(logfd);1575return-1;1576}1577if(close(logfd)) {1578struct strbuf sb = STRBUF_INIT;1579int save_errno = errno;15801581files_reflog_path(refs, &sb, refname);1582strbuf_addf(err,"unable to append to '%s':%s",1583 sb.buf,strerror(save_errno));1584strbuf_release(&sb);1585return-1;1586}1587return0;1588}15891590/*1591 * Write sha1 into the open lockfile, then close the lockfile. On1592 * errors, rollback the lockfile, fill in *err and1593 * return -1.1594 */1595static intwrite_ref_to_lockfile(struct ref_lock *lock,1596const struct object_id *oid,struct strbuf *err)1597{1598static char term ='\n';1599struct object *o;1600int fd;16011602 o =parse_object(oid);1603if(!o) {1604strbuf_addf(err,1605"trying to write ref '%s' with nonexistent object%s",1606 lock->ref_name,oid_to_hex(oid));1607unlock_ref(lock);1608return-1;1609}1610if(o->type != OBJ_COMMIT &&is_branch(lock->ref_name)) {1611strbuf_addf(err,1612"trying to write non-commit object%sto branch '%s'",1613oid_to_hex(oid), lock->ref_name);1614unlock_ref(lock);1615return-1;1616}1617 fd =get_lock_file_fd(lock->lk);1618if(write_in_full(fd,oid_to_hex(oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||1619write_in_full(fd, &term,1) !=1||1620close_ref(lock) <0) {1621strbuf_addf(err,1622"couldn't write '%s'",get_lock_file_path(lock->lk));1623unlock_ref(lock);1624return-1;1625}1626return0;1627}16281629/*1630 * Commit a change to a loose reference that has already been written1631 * to the loose reference lockfile. Also update the reflogs if1632 * necessary, using the specified lockmsg (which can be NULL).1633 */1634static intcommit_ref_update(struct files_ref_store *refs,1635struct ref_lock *lock,1636const struct object_id *oid,const char*logmsg,1637struct strbuf *err)1638{1639files_assert_main_repository(refs,"commit_ref_update");16401641clear_loose_ref_cache(refs);1642if(files_log_ref_write(refs, lock->ref_name,1643&lock->old_oid, oid,1644 logmsg,0, err)) {1645char*old_msg =strbuf_detach(err, NULL);1646strbuf_addf(err,"cannot update the ref '%s':%s",1647 lock->ref_name, old_msg);1648free(old_msg);1649unlock_ref(lock);1650return-1;1651}16521653if(strcmp(lock->ref_name,"HEAD") !=0) {1654/*1655 * Special hack: If a branch is updated directly and HEAD1656 * points to it (may happen on the remote side of a push1657 * for example) then logically the HEAD reflog should be1658 * updated too.1659 * A generic solution implies reverse symref information,1660 * but finding all symrefs pointing to the given branch1661 * would be rather costly for this rare event (the direct1662 * update of a branch) to be worth it. So let's cheat and1663 * check with HEAD only which should cover 99% of all usage1664 * scenarios (even 100% of the default ones).1665 */1666struct object_id head_oid;1667int head_flag;1668const char*head_ref;16691670 head_ref =refs_resolve_ref_unsafe(&refs->base,"HEAD",1671 RESOLVE_REF_READING,1672 head_oid.hash, &head_flag);1673if(head_ref && (head_flag & REF_ISSYMREF) &&1674!strcmp(head_ref, lock->ref_name)) {1675struct strbuf log_err = STRBUF_INIT;1676if(files_log_ref_write(refs,"HEAD",1677&lock->old_oid, oid,1678 logmsg,0, &log_err)) {1679error("%s", log_err.buf);1680strbuf_release(&log_err);1681}1682}1683}16841685if(commit_ref(lock)) {1686strbuf_addf(err,"couldn't set '%s'", lock->ref_name);1687unlock_ref(lock);1688return-1;1689}16901691unlock_ref(lock);1692return0;1693}16941695static intcreate_ref_symlink(struct ref_lock *lock,const char*target)1696{1697int ret = -1;1698#ifndef NO_SYMLINK_HEAD1699char*ref_path =get_locked_file_path(lock->lk);1700unlink(ref_path);1701 ret =symlink(target, ref_path);1702free(ref_path);17031704if(ret)1705fprintf(stderr,"no symlink - falling back to symbolic ref\n");1706#endif1707return ret;1708}17091710static voidupdate_symref_reflog(struct files_ref_store *refs,1711struct ref_lock *lock,const char*refname,1712const char*target,const char*logmsg)1713{1714struct strbuf err = STRBUF_INIT;1715struct object_id new_oid;1716if(logmsg &&1717!refs_read_ref_full(&refs->base, target,1718 RESOLVE_REF_READING, new_oid.hash, NULL) &&1719files_log_ref_write(refs, refname, &lock->old_oid,1720&new_oid, logmsg,0, &err)) {1721error("%s", err.buf);1722strbuf_release(&err);1723}1724}17251726static intcreate_symref_locked(struct files_ref_store *refs,1727struct ref_lock *lock,const char*refname,1728const char*target,const char*logmsg)1729{1730if(prefer_symlink_refs && !create_ref_symlink(lock, target)) {1731update_symref_reflog(refs, lock, refname, target, logmsg);1732return0;1733}17341735if(!fdopen_lock_file(lock->lk,"w"))1736returnerror("unable to fdopen%s:%s",1737 lock->lk->tempfile.filename.buf,strerror(errno));17381739update_symref_reflog(refs, lock, refname, target, logmsg);17401741/* no error check; commit_ref will check ferror */1742fprintf(lock->lk->tempfile.fp,"ref:%s\n", target);1743if(commit_ref(lock) <0)1744returnerror("unable to write symref for%s:%s", refname,1745strerror(errno));1746return0;1747}17481749static intfiles_create_symref(struct ref_store *ref_store,1750const char*refname,const char*target,1751const char*logmsg)1752{1753struct files_ref_store *refs =1754files_downcast(ref_store, REF_STORE_WRITE,"create_symref");1755struct strbuf err = STRBUF_INIT;1756struct ref_lock *lock;1757int ret;17581759 lock =lock_ref_sha1_basic(refs, refname, NULL,1760 NULL, NULL, REF_NODEREF, NULL,1761&err);1762if(!lock) {1763error("%s", err.buf);1764strbuf_release(&err);1765return-1;1766}17671768 ret =create_symref_locked(refs, lock, refname, target, logmsg);1769unlock_ref(lock);1770return ret;1771}17721773static intfiles_reflog_exists(struct ref_store *ref_store,1774const char*refname)1775{1776struct files_ref_store *refs =1777files_downcast(ref_store, REF_STORE_READ,"reflog_exists");1778struct strbuf sb = STRBUF_INIT;1779struct stat st;1780int ret;17811782files_reflog_path(refs, &sb, refname);1783 ret = !lstat(sb.buf, &st) &&S_ISREG(st.st_mode);1784strbuf_release(&sb);1785return ret;1786}17871788static intfiles_delete_reflog(struct ref_store *ref_store,1789const char*refname)1790{1791struct files_ref_store *refs =1792files_downcast(ref_store, REF_STORE_WRITE,"delete_reflog");1793struct strbuf sb = STRBUF_INIT;1794int ret;17951796files_reflog_path(refs, &sb, refname);1797 ret =remove_path(sb.buf);1798strbuf_release(&sb);1799return ret;1800}18011802static intshow_one_reflog_ent(struct strbuf *sb, each_reflog_ent_fn fn,void*cb_data)1803{1804struct object_id ooid, noid;1805char*email_end, *message;1806 timestamp_t timestamp;1807int tz;1808const char*p = sb->buf;18091810/* old SP new SP name <email> SP time TAB msg LF */1811if(!sb->len || sb->buf[sb->len -1] !='\n'||1812parse_oid_hex(p, &ooid, &p) || *p++ !=' '||1813parse_oid_hex(p, &noid, &p) || *p++ !=' '||1814!(email_end =strchr(p,'>')) ||1815 email_end[1] !=' '||1816!(timestamp =parse_timestamp(email_end +2, &message,10)) ||1817!message || message[0] !=' '||1818(message[1] !='+'&& message[1] !='-') ||1819!isdigit(message[2]) || !isdigit(message[3]) ||1820!isdigit(message[4]) || !isdigit(message[5]))1821return0;/* corrupt? */1822 email_end[1] ='\0';1823 tz =strtol(message +1, NULL,10);1824if(message[6] !='\t')1825 message +=6;1826else1827 message +=7;1828returnfn(&ooid, &noid, p, timestamp, tz, message, cb_data);1829}18301831static char*find_beginning_of_line(char*bob,char*scan)1832{1833while(bob < scan && *(--scan) !='\n')1834;/* keep scanning backwards */1835/*1836 * Return either beginning of the buffer, or LF at the end of1837 * the previous line.1838 */1839return scan;1840}18411842static intfiles_for_each_reflog_ent_reverse(struct ref_store *ref_store,1843const char*refname,1844 each_reflog_ent_fn fn,1845void*cb_data)1846{1847struct files_ref_store *refs =1848files_downcast(ref_store, REF_STORE_READ,1849"for_each_reflog_ent_reverse");1850struct strbuf sb = STRBUF_INIT;1851FILE*logfp;1852long pos;1853int ret =0, at_tail =1;18541855files_reflog_path(refs, &sb, refname);1856 logfp =fopen(sb.buf,"r");1857strbuf_release(&sb);1858if(!logfp)1859return-1;18601861/* Jump to the end */1862if(fseek(logfp,0, SEEK_END) <0)1863 ret =error("cannot seek back reflog for%s:%s",1864 refname,strerror(errno));1865 pos =ftell(logfp);1866while(!ret &&0< pos) {1867int cnt;1868size_t nread;1869char buf[BUFSIZ];1870char*endp, *scanp;18711872/* Fill next block from the end */1873 cnt = (sizeof(buf) < pos) ?sizeof(buf) : pos;1874if(fseek(logfp, pos - cnt, SEEK_SET)) {1875 ret =error("cannot seek back reflog for%s:%s",1876 refname,strerror(errno));1877break;1878}1879 nread =fread(buf, cnt,1, logfp);1880if(nread !=1) {1881 ret =error("cannot read%dbytes from reflog for%s:%s",1882 cnt, refname,strerror(errno));1883break;1884}1885 pos -= cnt;18861887 scanp = endp = buf + cnt;1888if(at_tail && scanp[-1] =='\n')1889/* Looking at the final LF at the end of the file */1890 scanp--;1891 at_tail =0;18921893while(buf < scanp) {1894/*1895 * terminating LF of the previous line, or the beginning1896 * of the buffer.1897 */1898char*bp;18991900 bp =find_beginning_of_line(buf, scanp);19011902if(*bp =='\n') {1903/*1904 * The newline is the end of the previous line,1905 * so we know we have complete line starting1906 * at (bp + 1). Prefix it onto any prior data1907 * we collected for the line and process it.1908 */1909strbuf_splice(&sb,0,0, bp +1, endp - (bp +1));1910 scanp = bp;1911 endp = bp +1;1912 ret =show_one_reflog_ent(&sb, fn, cb_data);1913strbuf_reset(&sb);1914if(ret)1915break;1916}else if(!pos) {1917/*1918 * We are at the start of the buffer, and the1919 * start of the file; there is no previous1920 * line, and we have everything for this one.1921 * Process it, and we can end the loop.1922 */1923strbuf_splice(&sb,0,0, buf, endp - buf);1924 ret =show_one_reflog_ent(&sb, fn, cb_data);1925strbuf_reset(&sb);1926break;1927}19281929if(bp == buf) {1930/*1931 * We are at the start of the buffer, and there1932 * is more file to read backwards. Which means1933 * we are in the middle of a line. Note that we1934 * may get here even if *bp was a newline; that1935 * just means we are at the exact end of the1936 * previous line, rather than some spot in the1937 * middle.1938 *1939 * Save away what we have to be combined with1940 * the data from the next read.1941 */1942strbuf_splice(&sb,0,0, buf, endp - buf);1943break;1944}1945}19461947}1948if(!ret && sb.len)1949die("BUG: reverse reflog parser had leftover data");19501951fclose(logfp);1952strbuf_release(&sb);1953return ret;1954}19551956static intfiles_for_each_reflog_ent(struct ref_store *ref_store,1957const char*refname,1958 each_reflog_ent_fn fn,void*cb_data)1959{1960struct files_ref_store *refs =1961files_downcast(ref_store, REF_STORE_READ,1962"for_each_reflog_ent");1963FILE*logfp;1964struct strbuf sb = STRBUF_INIT;1965int ret =0;19661967files_reflog_path(refs, &sb, refname);1968 logfp =fopen(sb.buf,"r");1969strbuf_release(&sb);1970if(!logfp)1971return-1;19721973while(!ret && !strbuf_getwholeline(&sb, logfp,'\n'))1974 ret =show_one_reflog_ent(&sb, fn, cb_data);1975fclose(logfp);1976strbuf_release(&sb);1977return ret;1978}19791980struct files_reflog_iterator {1981struct ref_iterator base;19821983struct ref_store *ref_store;1984struct dir_iterator *dir_iterator;1985struct object_id oid;1986};19871988static intfiles_reflog_iterator_advance(struct ref_iterator *ref_iterator)1989{1990struct files_reflog_iterator *iter =1991(struct files_reflog_iterator *)ref_iterator;1992struct dir_iterator *diter = iter->dir_iterator;1993int ok;19941995while((ok =dir_iterator_advance(diter)) == ITER_OK) {1996int flags;19971998if(!S_ISREG(diter->st.st_mode))1999continue;2000if(diter->basename[0] =='.')2001continue;2002if(ends_with(diter->basename,".lock"))2003continue;20042005if(refs_read_ref_full(iter->ref_store,2006 diter->relative_path,0,2007 iter->oid.hash, &flags)) {2008error("bad ref for%s", diter->path.buf);2009continue;2010}20112012 iter->base.refname = diter->relative_path;2013 iter->base.oid = &iter->oid;2014 iter->base.flags = flags;2015return ITER_OK;2016}20172018 iter->dir_iterator = NULL;2019if(ref_iterator_abort(ref_iterator) == ITER_ERROR)2020 ok = ITER_ERROR;2021return ok;2022}20232024static intfiles_reflog_iterator_peel(struct ref_iterator *ref_iterator,2025struct object_id *peeled)2026{2027die("BUG: ref_iterator_peel() called for reflog_iterator");2028}20292030static intfiles_reflog_iterator_abort(struct ref_iterator *ref_iterator)2031{2032struct files_reflog_iterator *iter =2033(struct files_reflog_iterator *)ref_iterator;2034int ok = ITER_DONE;20352036if(iter->dir_iterator)2037 ok =dir_iterator_abort(iter->dir_iterator);20382039base_ref_iterator_free(ref_iterator);2040return ok;2041}20422043static struct ref_iterator_vtable files_reflog_iterator_vtable = {2044 files_reflog_iterator_advance,2045 files_reflog_iterator_peel,2046 files_reflog_iterator_abort2047};20482049static struct ref_iterator *reflog_iterator_begin(struct ref_store *ref_store,2050const char*gitdir)2051{2052struct files_reflog_iterator *iter =xcalloc(1,sizeof(*iter));2053struct ref_iterator *ref_iterator = &iter->base;2054struct strbuf sb = STRBUF_INIT;20552056base_ref_iterator_init(ref_iterator, &files_reflog_iterator_vtable);2057strbuf_addf(&sb,"%s/logs", gitdir);2058 iter->dir_iterator =dir_iterator_begin(sb.buf);2059 iter->ref_store = ref_store;2060strbuf_release(&sb);20612062return ref_iterator;2063}20642065static enum iterator_selection reflog_iterator_select(2066struct ref_iterator *iter_worktree,2067struct ref_iterator *iter_common,2068void*cb_data)2069{2070if(iter_worktree) {2071/*2072 * We're a bit loose here. We probably should ignore2073 * common refs if they are accidentally added as2074 * per-worktree refs.2075 */2076return ITER_SELECT_0;2077}else if(iter_common) {2078if(ref_type(iter_common->refname) == REF_TYPE_NORMAL)2079return ITER_SELECT_1;20802081/*2082 * The main ref store may contain main worktree's2083 * per-worktree refs, which should be ignored2084 */2085return ITER_SKIP_1;2086}else2087return ITER_DONE;2088}20892090static struct ref_iterator *files_reflog_iterator_begin(struct ref_store *ref_store)2091{2092struct files_ref_store *refs =2093files_downcast(ref_store, REF_STORE_READ,2094"reflog_iterator_begin");20952096if(!strcmp(refs->gitdir, refs->gitcommondir)) {2097returnreflog_iterator_begin(ref_store, refs->gitcommondir);2098}else{2099returnmerge_ref_iterator_begin(2100reflog_iterator_begin(ref_store, refs->gitdir),2101reflog_iterator_begin(ref_store, refs->gitcommondir),2102 reflog_iterator_select, refs);2103}2104}21052106/*2107 * If update is a direct update of head_ref (the reference pointed to2108 * by HEAD), then add an extra REF_LOG_ONLY update for HEAD.2109 */2110static intsplit_head_update(struct ref_update *update,2111struct ref_transaction *transaction,2112const char*head_ref,2113struct string_list *affected_refnames,2114struct strbuf *err)2115{2116struct string_list_item *item;2117struct ref_update *new_update;21182119if((update->flags & REF_LOG_ONLY) ||2120(update->flags & REF_ISPRUNING) ||2121(update->flags & REF_UPDATE_VIA_HEAD))2122return0;21232124if(strcmp(update->refname, head_ref))2125return0;21262127/*2128 * First make sure that HEAD is not already in the2129 * transaction. This insertion is O(N) in the transaction2130 * size, but it happens at most once per transaction.2131 */2132 item =string_list_insert(affected_refnames,"HEAD");2133if(item->util) {2134/* An entry already existed */2135strbuf_addf(err,2136"multiple updates for 'HEAD' (including one "2137"via its referent '%s') are not allowed",2138 update->refname);2139return TRANSACTION_NAME_CONFLICT;2140}21412142 new_update =ref_transaction_add_update(2143 transaction,"HEAD",2144 update->flags | REF_LOG_ONLY | REF_NODEREF,2145 update->new_oid.hash, update->old_oid.hash,2146 update->msg);21472148 item->util = new_update;21492150return0;2151}21522153/*2154 * update is for a symref that points at referent and doesn't have2155 * REF_NODEREF set. Split it into two updates:2156 * - The original update, but with REF_LOG_ONLY and REF_NODEREF set2157 * - A new, separate update for the referent reference2158 * Note that the new update will itself be subject to splitting when2159 * the iteration gets to it.2160 */2161static intsplit_symref_update(struct files_ref_store *refs,2162struct ref_update *update,2163const char*referent,2164struct ref_transaction *transaction,2165struct string_list *affected_refnames,2166struct strbuf *err)2167{2168struct string_list_item *item;2169struct ref_update *new_update;2170unsigned int new_flags;21712172/*2173 * First make sure that referent is not already in the2174 * transaction. This insertion is O(N) in the transaction2175 * size, but it happens at most once per symref in a2176 * transaction.2177 */2178 item =string_list_insert(affected_refnames, referent);2179if(item->util) {2180/* An entry already existed */2181strbuf_addf(err,2182"multiple updates for '%s' (including one "2183"via symref '%s') are not allowed",2184 referent, update->refname);2185return TRANSACTION_NAME_CONFLICT;2186}21872188 new_flags = update->flags;2189if(!strcmp(update->refname,"HEAD")) {2190/*2191 * Record that the new update came via HEAD, so that2192 * when we process it, split_head_update() doesn't try2193 * to add another reflog update for HEAD. Note that2194 * this bit will be propagated if the new_update2195 * itself needs to be split.2196 */2197 new_flags |= REF_UPDATE_VIA_HEAD;2198}21992200 new_update =ref_transaction_add_update(2201 transaction, referent, new_flags,2202 update->new_oid.hash, update->old_oid.hash,2203 update->msg);22042205 new_update->parent_update = update;22062207/*2208 * Change the symbolic ref update to log only. Also, it2209 * doesn't need to check its old SHA-1 value, as that will be2210 * done when new_update is processed.2211 */2212 update->flags |= REF_LOG_ONLY | REF_NODEREF;2213 update->flags &= ~REF_HAVE_OLD;22142215 item->util = new_update;22162217return0;2218}22192220/*2221 * Return the refname under which update was originally requested.2222 */2223static const char*original_update_refname(struct ref_update *update)2224{2225while(update->parent_update)2226 update = update->parent_update;22272228return update->refname;2229}22302231/*2232 * Check whether the REF_HAVE_OLD and old_oid values stored in update2233 * are consistent with oid, which is the reference's current value. If2234 * everything is OK, return 0; otherwise, write an error message to2235 * err and return -1.2236 */2237static intcheck_old_oid(struct ref_update *update,struct object_id *oid,2238struct strbuf *err)2239{2240if(!(update->flags & REF_HAVE_OLD) ||2241!oidcmp(oid, &update->old_oid))2242return0;22432244if(is_null_oid(&update->old_oid))2245strbuf_addf(err,"cannot lock ref '%s': "2246"reference already exists",2247original_update_refname(update));2248else if(is_null_oid(oid))2249strbuf_addf(err,"cannot lock ref '%s': "2250"reference is missing but expected%s",2251original_update_refname(update),2252oid_to_hex(&update->old_oid));2253else2254strbuf_addf(err,"cannot lock ref '%s': "2255"is at%sbut expected%s",2256original_update_refname(update),2257oid_to_hex(oid),2258oid_to_hex(&update->old_oid));22592260return-1;2261}22622263/*2264 * Prepare for carrying out update:2265 * - Lock the reference referred to by update.2266 * - Read the reference under lock.2267 * - Check that its old SHA-1 value (if specified) is correct, and in2268 * any case record it in update->lock->old_oid for later use when2269 * writing the reflog.2270 * - If it is a symref update without REF_NODEREF, split it up into a2271 * REF_LOG_ONLY update of the symref and add a separate update for2272 * the referent to transaction.2273 * - If it is an update of head_ref, add a corresponding REF_LOG_ONLY2274 * update of HEAD.2275 */2276static intlock_ref_for_update(struct files_ref_store *refs,2277struct ref_update *update,2278struct ref_transaction *transaction,2279const char*head_ref,2280struct string_list *affected_refnames,2281struct strbuf *err)2282{2283struct strbuf referent = STRBUF_INIT;2284int mustexist = (update->flags & REF_HAVE_OLD) &&2285!is_null_oid(&update->old_oid);2286int ret;2287struct ref_lock *lock;22882289files_assert_main_repository(refs,"lock_ref_for_update");22902291if((update->flags & REF_HAVE_NEW) &&is_null_oid(&update->new_oid))2292 update->flags |= REF_DELETING;22932294if(head_ref) {2295 ret =split_head_update(update, transaction, head_ref,2296 affected_refnames, err);2297if(ret)2298return ret;2299}23002301 ret =lock_raw_ref(refs, update->refname, mustexist,2302 affected_refnames, NULL,2303&lock, &referent,2304&update->type, err);2305if(ret) {2306char*reason;23072308 reason =strbuf_detach(err, NULL);2309strbuf_addf(err,"cannot lock ref '%s':%s",2310original_update_refname(update), reason);2311free(reason);2312return ret;2313}23142315 update->backend_data = lock;23162317if(update->type & REF_ISSYMREF) {2318if(update->flags & REF_NODEREF) {2319/*2320 * We won't be reading the referent as part of2321 * the transaction, so we have to read it here2322 * to record and possibly check old_sha1:2323 */2324if(refs_read_ref_full(&refs->base,2325 referent.buf,0,2326 lock->old_oid.hash, NULL)) {2327if(update->flags & REF_HAVE_OLD) {2328strbuf_addf(err,"cannot lock ref '%s': "2329"error reading reference",2330original_update_refname(update));2331return-1;2332}2333}else if(check_old_oid(update, &lock->old_oid, err)) {2334return TRANSACTION_GENERIC_ERROR;2335}2336}else{2337/*2338 * Create a new update for the reference this2339 * symref is pointing at. Also, we will record2340 * and verify old_sha1 for this update as part2341 * of processing the split-off update, so we2342 * don't have to do it here.2343 */2344 ret =split_symref_update(refs, update,2345 referent.buf, transaction,2346 affected_refnames, err);2347if(ret)2348return ret;2349}2350}else{2351struct ref_update *parent_update;23522353if(check_old_oid(update, &lock->old_oid, err))2354return TRANSACTION_GENERIC_ERROR;23552356/*2357 * If this update is happening indirectly because of a2358 * symref update, record the old SHA-1 in the parent2359 * update:2360 */2361for(parent_update = update->parent_update;2362 parent_update;2363 parent_update = parent_update->parent_update) {2364struct ref_lock *parent_lock = parent_update->backend_data;2365oidcpy(&parent_lock->old_oid, &lock->old_oid);2366}2367}23682369if((update->flags & REF_HAVE_NEW) &&2370!(update->flags & REF_DELETING) &&2371!(update->flags & REF_LOG_ONLY)) {2372if(!(update->type & REF_ISSYMREF) &&2373!oidcmp(&lock->old_oid, &update->new_oid)) {2374/*2375 * The reference already has the desired2376 * value, so we don't need to write it.2377 */2378}else if(write_ref_to_lockfile(lock, &update->new_oid,2379 err)) {2380char*write_err =strbuf_detach(err, NULL);23812382/*2383 * The lock was freed upon failure of2384 * write_ref_to_lockfile():2385 */2386 update->backend_data = NULL;2387strbuf_addf(err,2388"cannot update ref '%s':%s",2389 update->refname, write_err);2390free(write_err);2391return TRANSACTION_GENERIC_ERROR;2392}else{2393 update->flags |= REF_NEEDS_COMMIT;2394}2395}2396if(!(update->flags & REF_NEEDS_COMMIT)) {2397/*2398 * We didn't call write_ref_to_lockfile(), so2399 * the lockfile is still open. Close it to2400 * free up the file descriptor:2401 */2402if(close_ref(lock)) {2403strbuf_addf(err,"couldn't close '%s.lock'",2404 update->refname);2405return TRANSACTION_GENERIC_ERROR;2406}2407}2408return0;2409}24102411/*2412 * Unlock any references in `transaction` that are still locked, and2413 * mark the transaction closed.2414 */2415static voidfiles_transaction_cleanup(struct ref_transaction *transaction)2416{2417size_t i;24182419for(i =0; i < transaction->nr; i++) {2420struct ref_update *update = transaction->updates[i];2421struct ref_lock *lock = update->backend_data;24222423if(lock) {2424unlock_ref(lock);2425 update->backend_data = NULL;2426}2427}24282429 transaction->state = REF_TRANSACTION_CLOSED;2430}24312432static intfiles_transaction_prepare(struct ref_store *ref_store,2433struct ref_transaction *transaction,2434struct strbuf *err)2435{2436struct files_ref_store *refs =2437files_downcast(ref_store, REF_STORE_WRITE,2438"ref_transaction_prepare");2439size_t i;2440int ret =0;2441struct string_list affected_refnames = STRING_LIST_INIT_NODUP;2442char*head_ref = NULL;2443int head_type;2444struct object_id head_oid;24452446assert(err);24472448if(!transaction->nr)2449goto cleanup;24502451/*2452 * Fail if a refname appears more than once in the2453 * transaction. (If we end up splitting up any updates using2454 * split_symref_update() or split_head_update(), those2455 * functions will check that the new updates don't have the2456 * same refname as any existing ones.)2457 */2458for(i =0; i < transaction->nr; i++) {2459struct ref_update *update = transaction->updates[i];2460struct string_list_item *item =2461string_list_append(&affected_refnames, update->refname);24622463/*2464 * We store a pointer to update in item->util, but at2465 * the moment we never use the value of this field2466 * except to check whether it is non-NULL.2467 */2468 item->util = update;2469}2470string_list_sort(&affected_refnames);2471if(ref_update_reject_duplicates(&affected_refnames, err)) {2472 ret = TRANSACTION_GENERIC_ERROR;2473goto cleanup;2474}24752476/*2477 * Special hack: If a branch is updated directly and HEAD2478 * points to it (may happen on the remote side of a push2479 * for example) then logically the HEAD reflog should be2480 * updated too.2481 *2482 * A generic solution would require reverse symref lookups,2483 * but finding all symrefs pointing to a given branch would be2484 * rather costly for this rare event (the direct update of a2485 * branch) to be worth it. So let's cheat and check with HEAD2486 * only, which should cover 99% of all usage scenarios (even2487 * 100% of the default ones).2488 *2489 * So if HEAD is a symbolic reference, then record the name of2490 * the reference that it points to. If we see an update of2491 * head_ref within the transaction, then split_head_update()2492 * arranges for the reflog of HEAD to be updated, too.2493 */2494 head_ref =refs_resolve_refdup(ref_store,"HEAD",2495 RESOLVE_REF_NO_RECURSE,2496 head_oid.hash, &head_type);24972498if(head_ref && !(head_type & REF_ISSYMREF)) {2499FREE_AND_NULL(head_ref);2500}25012502/*2503 * Acquire all locks, verify old values if provided, check2504 * that new values are valid, and write new values to the2505 * lockfiles, ready to be activated. Only keep one lockfile2506 * open at a time to avoid running out of file descriptors.2507 * Note that lock_ref_for_update() might append more updates2508 * to the transaction.2509 */2510for(i =0; i < transaction->nr; i++) {2511struct ref_update *update = transaction->updates[i];25122513 ret =lock_ref_for_update(refs, update, transaction,2514 head_ref, &affected_refnames, err);2515if(ret)2516break;2517}25182519cleanup:2520free(head_ref);2521string_list_clear(&affected_refnames,0);25222523if(ret)2524files_transaction_cleanup(transaction);2525else2526 transaction->state = REF_TRANSACTION_PREPARED;25272528return ret;2529}25302531static intfiles_transaction_finish(struct ref_store *ref_store,2532struct ref_transaction *transaction,2533struct strbuf *err)2534{2535struct files_ref_store *refs =2536files_downcast(ref_store,0,"ref_transaction_finish");2537size_t i;2538int ret =0;2539struct string_list refs_to_delete = STRING_LIST_INIT_NODUP;2540struct string_list_item *ref_to_delete;2541struct strbuf sb = STRBUF_INIT;25422543assert(err);25442545if(!transaction->nr) {2546 transaction->state = REF_TRANSACTION_CLOSED;2547return0;2548}25492550/* Perform updates first so live commits remain referenced */2551for(i =0; i < transaction->nr; i++) {2552struct ref_update *update = transaction->updates[i];2553struct ref_lock *lock = update->backend_data;25542555if(update->flags & REF_NEEDS_COMMIT ||2556 update->flags & REF_LOG_ONLY) {2557if(files_log_ref_write(refs,2558 lock->ref_name,2559&lock->old_oid,2560&update->new_oid,2561 update->msg, update->flags,2562 err)) {2563char*old_msg =strbuf_detach(err, NULL);25642565strbuf_addf(err,"cannot update the ref '%s':%s",2566 lock->ref_name, old_msg);2567free(old_msg);2568unlock_ref(lock);2569 update->backend_data = NULL;2570 ret = TRANSACTION_GENERIC_ERROR;2571goto cleanup;2572}2573}2574if(update->flags & REF_NEEDS_COMMIT) {2575clear_loose_ref_cache(refs);2576if(commit_ref(lock)) {2577strbuf_addf(err,"couldn't set '%s'", lock->ref_name);2578unlock_ref(lock);2579 update->backend_data = NULL;2580 ret = TRANSACTION_GENERIC_ERROR;2581goto cleanup;2582}2583}2584}2585/* Perform deletes now that updates are safely completed */2586for(i =0; i < transaction->nr; i++) {2587struct ref_update *update = transaction->updates[i];2588struct ref_lock *lock = update->backend_data;25892590if(update->flags & REF_DELETING &&2591!(update->flags & REF_LOG_ONLY)) {2592if(!(update->type & REF_ISPACKED) ||2593 update->type & REF_ISSYMREF) {2594/* It is a loose reference. */2595strbuf_reset(&sb);2596files_ref_path(refs, &sb, lock->ref_name);2597if(unlink_or_msg(sb.buf, err)) {2598 ret = TRANSACTION_GENERIC_ERROR;2599goto cleanup;2600}2601 update->flags |= REF_DELETED_LOOSE;2602}26032604if(!(update->flags & REF_ISPRUNING))2605string_list_append(&refs_to_delete,2606 lock->ref_name);2607}2608}26092610if(packed_refs_lock(refs->packed_ref_store,0, err)) {2611 ret = TRANSACTION_GENERIC_ERROR;2612goto cleanup;2613}26142615if(repack_without_refs(refs->packed_ref_store, &refs_to_delete, err)) {2616 ret = TRANSACTION_GENERIC_ERROR;2617packed_refs_unlock(refs->packed_ref_store);2618goto cleanup;2619}26202621packed_refs_unlock(refs->packed_ref_store);26222623/* Delete the reflogs of any references that were deleted: */2624for_each_string_list_item(ref_to_delete, &refs_to_delete) {2625strbuf_reset(&sb);2626files_reflog_path(refs, &sb, ref_to_delete->string);2627if(!unlink_or_warn(sb.buf))2628try_remove_empty_parents(refs, ref_to_delete->string,2629 REMOVE_EMPTY_PARENTS_REFLOG);2630}26312632clear_loose_ref_cache(refs);26332634cleanup:2635files_transaction_cleanup(transaction);26362637for(i =0; i < transaction->nr; i++) {2638struct ref_update *update = transaction->updates[i];26392640if(update->flags & REF_DELETED_LOOSE) {2641/*2642 * The loose reference was deleted. Delete any2643 * empty parent directories. (Note that this2644 * can only work because we have already2645 * removed the lockfile.)2646 */2647try_remove_empty_parents(refs, update->refname,2648 REMOVE_EMPTY_PARENTS_REF);2649}2650}26512652strbuf_release(&sb);2653string_list_clear(&refs_to_delete,0);2654return ret;2655}26562657static intfiles_transaction_abort(struct ref_store *ref_store,2658struct ref_transaction *transaction,2659struct strbuf *err)2660{2661files_transaction_cleanup(transaction);2662return0;2663}26642665static intref_present(const char*refname,2666const struct object_id *oid,int flags,void*cb_data)2667{2668struct string_list *affected_refnames = cb_data;26692670returnstring_list_has_string(affected_refnames, refname);2671}26722673static intfiles_initial_transaction_commit(struct ref_store *ref_store,2674struct ref_transaction *transaction,2675struct strbuf *err)2676{2677struct files_ref_store *refs =2678files_downcast(ref_store, REF_STORE_WRITE,2679"initial_ref_transaction_commit");2680size_t i;2681int ret =0;2682struct string_list affected_refnames = STRING_LIST_INIT_NODUP;26832684assert(err);26852686if(transaction->state != REF_TRANSACTION_OPEN)2687die("BUG: commit called for transaction that is not open");26882689/* Fail if a refname appears more than once in the transaction: */2690for(i =0; i < transaction->nr; i++)2691string_list_append(&affected_refnames,2692 transaction->updates[i]->refname);2693string_list_sort(&affected_refnames);2694if(ref_update_reject_duplicates(&affected_refnames, err)) {2695 ret = TRANSACTION_GENERIC_ERROR;2696goto cleanup;2697}26982699/*2700 * It's really undefined to call this function in an active2701 * repository or when there are existing references: we are2702 * only locking and changing packed-refs, so (1) any2703 * simultaneous processes might try to change a reference at2704 * the same time we do, and (2) any existing loose versions of2705 * the references that we are setting would have precedence2706 * over our values. But some remote helpers create the remote2707 * "HEAD" and "master" branches before calling this function,2708 * so here we really only check that none of the references2709 * that we are creating already exists.2710 */2711if(refs_for_each_rawref(&refs->base, ref_present,2712&affected_refnames))2713die("BUG: initial ref transaction called with existing refs");27142715for(i =0; i < transaction->nr; i++) {2716struct ref_update *update = transaction->updates[i];27172718if((update->flags & REF_HAVE_OLD) &&2719!is_null_oid(&update->old_oid))2720die("BUG: initial ref transaction with old_sha1 set");2721if(refs_verify_refname_available(&refs->base, update->refname,2722&affected_refnames, NULL,2723 err)) {2724 ret = TRANSACTION_NAME_CONFLICT;2725goto cleanup;2726}2727}27282729if(packed_refs_lock(refs->packed_ref_store,0, err)) {2730 ret = TRANSACTION_GENERIC_ERROR;2731goto cleanup;2732}27332734for(i =0; i < transaction->nr; i++) {2735struct ref_update *update = transaction->updates[i];27362737if((update->flags & REF_HAVE_NEW) &&2738!is_null_oid(&update->new_oid))2739add_packed_ref(refs->packed_ref_store, update->refname,2740&update->new_oid);2741}27422743if(commit_packed_refs(refs->packed_ref_store, err)) {2744 ret = TRANSACTION_GENERIC_ERROR;2745goto cleanup;2746}27472748cleanup:2749packed_refs_unlock(refs->packed_ref_store);2750 transaction->state = REF_TRANSACTION_CLOSED;2751string_list_clear(&affected_refnames,0);2752return ret;2753}27542755struct expire_reflog_cb {2756unsigned int flags;2757 reflog_expiry_should_prune_fn *should_prune_fn;2758void*policy_cb;2759FILE*newlog;2760struct object_id last_kept_oid;2761};27622763static intexpire_reflog_ent(struct object_id *ooid,struct object_id *noid,2764const char*email, timestamp_t timestamp,int tz,2765const char*message,void*cb_data)2766{2767struct expire_reflog_cb *cb = cb_data;2768struct expire_reflog_policy_cb *policy_cb = cb->policy_cb;27692770if(cb->flags & EXPIRE_REFLOGS_REWRITE)2771 ooid = &cb->last_kept_oid;27722773if((*cb->should_prune_fn)(ooid, noid, email, timestamp, tz,2774 message, policy_cb)) {2775if(!cb->newlog)2776printf("would prune%s", message);2777else if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2778printf("prune%s", message);2779}else{2780if(cb->newlog) {2781fprintf(cb->newlog,"%s %s %s%"PRItime" %+05d\t%s",2782oid_to_hex(ooid),oid_to_hex(noid),2783 email, timestamp, tz, message);2784oidcpy(&cb->last_kept_oid, noid);2785}2786if(cb->flags & EXPIRE_REFLOGS_VERBOSE)2787printf("keep%s", message);2788}2789return0;2790}27912792static intfiles_reflog_expire(struct ref_store *ref_store,2793const char*refname,const unsigned char*sha1,2794unsigned int flags,2795 reflog_expiry_prepare_fn prepare_fn,2796 reflog_expiry_should_prune_fn should_prune_fn,2797 reflog_expiry_cleanup_fn cleanup_fn,2798void*policy_cb_data)2799{2800struct files_ref_store *refs =2801files_downcast(ref_store, REF_STORE_WRITE,"reflog_expire");2802static struct lock_file reflog_lock;2803struct expire_reflog_cb cb;2804struct ref_lock *lock;2805struct strbuf log_file_sb = STRBUF_INIT;2806char*log_file;2807int status =0;2808int type;2809struct strbuf err = STRBUF_INIT;2810struct object_id oid;28112812memset(&cb,0,sizeof(cb));2813 cb.flags = flags;2814 cb.policy_cb = policy_cb_data;2815 cb.should_prune_fn = should_prune_fn;28162817/*2818 * The reflog file is locked by holding the lock on the2819 * reference itself, plus we might need to update the2820 * reference if --updateref was specified:2821 */2822 lock =lock_ref_sha1_basic(refs, refname, sha1,2823 NULL, NULL, REF_NODEREF,2824&type, &err);2825if(!lock) {2826error("cannot lock ref '%s':%s", refname, err.buf);2827strbuf_release(&err);2828return-1;2829}2830if(!refs_reflog_exists(ref_store, refname)) {2831unlock_ref(lock);2832return0;2833}28342835files_reflog_path(refs, &log_file_sb, refname);2836 log_file =strbuf_detach(&log_file_sb, NULL);2837if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2838/*2839 * Even though holding $GIT_DIR/logs/$reflog.lock has2840 * no locking implications, we use the lock_file2841 * machinery here anyway because it does a lot of the2842 * work we need, including cleaning up if the program2843 * exits unexpectedly.2844 */2845if(hold_lock_file_for_update(&reflog_lock, log_file,0) <0) {2846struct strbuf err = STRBUF_INIT;2847unable_to_lock_message(log_file, errno, &err);2848error("%s", err.buf);2849strbuf_release(&err);2850goto failure;2851}2852 cb.newlog =fdopen_lock_file(&reflog_lock,"w");2853if(!cb.newlog) {2854error("cannot fdopen%s(%s)",2855get_lock_file_path(&reflog_lock),strerror(errno));2856goto failure;2857}2858}28592860hashcpy(oid.hash, sha1);28612862(*prepare_fn)(refname, &oid, cb.policy_cb);2863refs_for_each_reflog_ent(ref_store, refname, expire_reflog_ent, &cb);2864(*cleanup_fn)(cb.policy_cb);28652866if(!(flags & EXPIRE_REFLOGS_DRY_RUN)) {2867/*2868 * It doesn't make sense to adjust a reference pointed2869 * to by a symbolic ref based on expiring entries in2870 * the symbolic reference's reflog. Nor can we update2871 * a reference if there are no remaining reflog2872 * entries.2873 */2874int update = (flags & EXPIRE_REFLOGS_UPDATE_REF) &&2875!(type & REF_ISSYMREF) &&2876!is_null_oid(&cb.last_kept_oid);28772878if(close_lock_file(&reflog_lock)) {2879 status |=error("couldn't write%s:%s", log_file,2880strerror(errno));2881}else if(update &&2882(write_in_full(get_lock_file_fd(lock->lk),2883oid_to_hex(&cb.last_kept_oid), GIT_SHA1_HEXSZ) != GIT_SHA1_HEXSZ ||2884write_str_in_full(get_lock_file_fd(lock->lk),"\n") !=1||2885close_ref(lock) <0)) {2886 status |=error("couldn't write%s",2887get_lock_file_path(lock->lk));2888rollback_lock_file(&reflog_lock);2889}else if(commit_lock_file(&reflog_lock)) {2890 status |=error("unable to write reflog '%s' (%s)",2891 log_file,strerror(errno));2892}else if(update &&commit_ref(lock)) {2893 status |=error("couldn't set%s", lock->ref_name);2894}2895}2896free(log_file);2897unlock_ref(lock);2898return status;28992900 failure:2901rollback_lock_file(&reflog_lock);2902free(log_file);2903unlock_ref(lock);2904return-1;2905}29062907static intfiles_init_db(struct ref_store *ref_store,struct strbuf *err)2908{2909struct files_ref_store *refs =2910files_downcast(ref_store, REF_STORE_WRITE,"init_db");2911struct strbuf sb = STRBUF_INIT;29122913/*2914 * Create .git/refs/{heads,tags}2915 */2916files_ref_path(refs, &sb,"refs/heads");2917safe_create_dir(sb.buf,1);29182919strbuf_reset(&sb);2920files_ref_path(refs, &sb,"refs/tags");2921safe_create_dir(sb.buf,1);29222923strbuf_release(&sb);2924return0;2925}29262927struct ref_storage_be refs_be_files = {2928 NULL,2929"files",2930 files_ref_store_create,2931 files_init_db,2932 files_transaction_prepare,2933 files_transaction_finish,2934 files_transaction_abort,2935 files_initial_transaction_commit,29362937 files_pack_refs,2938 files_peel_ref,2939 files_create_symref,2940 files_delete_refs,2941 files_rename_ref,29422943 files_ref_iterator_begin,2944 files_read_raw_ref,29452946 files_reflog_iterator_begin,2947 files_for_each_reflog_ent,2948 files_for_each_reflog_ent_reverse,2949 files_reflog_exists,2950 files_create_reflog,2951 files_delete_reflog,2952 files_reflog_expire2953};